feat: Tiptap替换为Vditor + MD存储重构 + Shortcode卡片扩展
- 编辑器:Tiptap 替换为 Vditor 3.11.2(wysiwyg 模式,本地托管 5.8MB,去 CDN) - 存储:Body 字段从 HTML 改为 Markdown,去除 BodyHTML,新增 Excerpt 列表摘要 - 安全:去除 bluemonday 依赖(MD 纯文本无 XSS 风险),go.mod 已清理 - Shortcode:新增 [zone:type:params] 扩展语法,支持活动/游戏/投票/资源卡片 - 图片上传:POST /api/posts/upload-image 直接返回 Vditor 原生响应格式 - 草稿:localStorage 键名改为 draft_post_body_md,与旧 HTML 草稿隔离 - 详情页:Vditor.method.min.js 客户端 MD → HTML 渲染,去 highlight.js CDN - 样式:去 Tiptap 样式 ~190 行,精简工具栏 CSS,新增卡片样式 - 文档:vditor-migration-plan.md 完整记录迁移决策、架构、用法
This commit is contained in:
@ -4,28 +4,74 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/config"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/microcosm-cc/bluemonday"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// sanitizePolicy Tiptap 输出 HTML 的消毒策略
|
||||
// 前端 WYSIWYG 编辑器输出 HTML,由 bluemonday UGC 策略消毒
|
||||
// 放行 code/pre 的 class/data-language 属性以保留代码高亮和语言标签
|
||||
// 放行 span 元素及其 hljs-* class 以保留 highlight.js 语法高亮
|
||||
// 放行 img 的 src/alt/title 属性以保留图片
|
||||
var sanitizePolicy = func() *bluemonday.Policy {
|
||||
p := bluemonday.UGCPolicy()
|
||||
p.AllowElements("span")
|
||||
p.AllowAttrs("class", "data-language").OnElements("code", "pre")
|
||||
p.AllowAttrs("class").Matching(regexp.MustCompile("^hljs-")).OnElements("span")
|
||||
p.AllowAttrs("src", "alt", "title").OnElements("img")
|
||||
return p
|
||||
}()
|
||||
// mdPatterns Markdown 语法正则(用于生成纯文本摘要)
|
||||
var mdPatterns = []*regexp.Regexp{
|
||||
// 代码块 ```...```
|
||||
regexp.MustCompile("(?s)```[^`]*```"),
|
||||
// 行内代码 `...`
|
||||
regexp.MustCompile("`[^`]+`"),
|
||||
// 图片 
|
||||
regexp.MustCompile(`!\[.*?\]\(.*?\)`),
|
||||
// 链接 [text](url)
|
||||
regexp.MustCompile(`\[([^\]]*)\]\(.*?\)`),
|
||||
// 标题标记 #
|
||||
regexp.MustCompile(`^#{1,6}\s+`),
|
||||
// 粗体/斜体/删除线标记
|
||||
regexp.MustCompile(`\*{1,3}|_{1,3}|~~`),
|
||||
// 引用 >
|
||||
regexp.MustCompile(`^>\s?`),
|
||||
// 列表标记
|
||||
regexp.MustCompile(`^[\s]*[-*+]\s+`),
|
||||
regexp.MustCompile(`^[\s]*\d+\.\s+`),
|
||||
// 分割线
|
||||
regexp.MustCompile(`^[-*_]{3,}\s*$`),
|
||||
}
|
||||
|
||||
// generateExcerpt 从 Markdown 生成纯文本摘要(最多 300 字符)
|
||||
// MD 作为纯文本存储无 XSS 风险,前端由 Vditor 渲染
|
||||
func generateExcerpt(md string) string {
|
||||
text := md
|
||||
|
||||
// 按行处理,保留行结构
|
||||
lines := strings.Split(text, "\n")
|
||||
var cleaned []string
|
||||
for _, line := range lines {
|
||||
cleanedLine := line
|
||||
for _, re := range mdPatterns {
|
||||
if re == mdPatterns[2] {
|
||||
// 链接保留文字: [text](url) → text
|
||||
cleanedLine = re.ReplaceAllString(cleanedLine, "$1")
|
||||
} else {
|
||||
cleanedLine = re.ReplaceAllString(cleanedLine, "")
|
||||
}
|
||||
}
|
||||
cleanedLine = strings.TrimSpace(cleanedLine)
|
||||
if cleanedLine != "" {
|
||||
cleaned = append(cleaned, cleanedLine)
|
||||
}
|
||||
}
|
||||
|
||||
result := strings.Join(cleaned, " ")
|
||||
|
||||
// 按 rune 截断,不切中文字符
|
||||
const maxChars = 300
|
||||
if utf8.RuneCountInString(result) > maxChars {
|
||||
runes := []rune(result)
|
||||
result = string(runes[:maxChars]) + "..."
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// PostService 帖子业务逻辑
|
||||
type PostService struct {
|
||||
@ -70,16 +116,10 @@ func (s *PostService) findPostWithAuthor(id uint) (*model.Post, error) {
|
||||
return post, nil
|
||||
}
|
||||
|
||||
// sanitizeHTML 对 Tiptap 输出的 HTML 进行消毒
|
||||
// 前端 WYSIWYG 编辑器直接输出 HTML,后端仅做安全消毒
|
||||
func (s *PostService) sanitizeHTML(body string) string {
|
||||
return sanitizePolicy.Sanitize(body)
|
||||
}
|
||||
|
||||
// Create 创建帖子
|
||||
// body 为 Vditor 输出的 Markdown,后端直接存储不做 HTML 消毒
|
||||
// MD 是纯文本,无 XSS 注入风险;前端渲染时由 Vditor 转 HTML
|
||||
func (s *PostService) Create(userID uint, title, body string) (*model.Post, error) {
|
||||
bodyHTML := s.sanitizeHTML(body)
|
||||
|
||||
status := model.PostStatusApproved
|
||||
if s.auditEnabled() {
|
||||
status = model.PostStatusDraft
|
||||
@ -88,7 +128,7 @@ func (s *PostService) Create(userID uint, title, body string) (*model.Post, erro
|
||||
post := &model.Post{
|
||||
Title: title,
|
||||
Body: body,
|
||||
BodyHTML: bodyHTML,
|
||||
Excerpt: generateExcerpt(body),
|
||||
UserID: userID,
|
||||
Status: status,
|
||||
AllowComment: true,
|
||||
@ -131,7 +171,7 @@ func (s *PostService) Update(postID uint, title, body string) error {
|
||||
|
||||
post.Title = title
|
||||
post.Body = body
|
||||
post.BodyHTML = s.sanitizeHTML(body)
|
||||
post.Excerpt = generateExcerpt(body)
|
||||
|
||||
// rejected 状态编辑后自动重置为 draft
|
||||
if post.Status == model.PostStatusRejected {
|
||||
|
||||
143
internal/service/shortcode_service.go
Normal file
143
internal/service/shortcode_service.go
Normal file
@ -0,0 +1,143 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"strings"
|
||||
|
||||
"metazone.cc/metalab/internal/model"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// ShortcodeService — Markdown shortcode 解析与渲染
|
||||
//
|
||||
// 职责:
|
||||
// 1. 从 Markdown body 中提取所有 [zone:type:params] 语法
|
||||
// 2. 将合法的 shortcode 替换为前端可识别的占位 HTML(<div class="zone-card">)
|
||||
// 3. 未注册的 shortcode 保持不变(不报错,避免破坏用户输入)
|
||||
//
|
||||
// 扩展新类型:
|
||||
// 1. 在 model/shortcode.go 中注册新 ShortcodeType 常量
|
||||
// 2. 在本文件的 renderPlaceholder() 中添加 case 分支
|
||||
// 3. 在 templates/.../shortcode.js 中添加前端卡片渲染逻辑
|
||||
// =============================================================================
|
||||
|
||||
// ShortcodeService 无状态,纯函数集合
|
||||
type ShortcodeService struct{}
|
||||
|
||||
// NewShortcodeService 构造函数
|
||||
func NewShortcodeService() *ShortcodeService {
|
||||
return &ShortcodeService{}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 主入口:解析 + 替换
|
||||
// =============================================================================
|
||||
|
||||
// Process 从 MD body 中提取 shortcode 并替换为占位 HTML
|
||||
// 返回的 ProcessedBody 可直接传给模板渲染(Go template 会自动对 HTML 实体转义,
|
||||
// 因此占位 div 需要用 template.HTML 类型标记为安全)
|
||||
func (s *ShortcodeService) Process(body string) model.ShortcodeResult {
|
||||
result := model.ShortcodeResult{
|
||||
ProcessedBody: body,
|
||||
}
|
||||
|
||||
// 一次遍历替换所有合法的 shortcode
|
||||
result.ProcessedBody = model.ShortcodePattern.ReplaceAllStringFunc(body, func(match string) string {
|
||||
sc, ok := parseShortcode(match)
|
||||
if !ok {
|
||||
return match // 格式不合法,保留原文
|
||||
}
|
||||
|
||||
if !model.IsValidType(string(sc.Type)) {
|
||||
return match // 类型未注册,保留原文
|
||||
}
|
||||
|
||||
// 生成占位 HTML
|
||||
placeholder := renderPlaceholder(sc)
|
||||
if placeholder == "" {
|
||||
return match
|
||||
}
|
||||
|
||||
result.Shortcodes = append(result.Shortcodes, sc)
|
||||
return placeholder
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 解析
|
||||
// =============================================================================
|
||||
|
||||
// parseShortcode 从 "[zone:type:params]" 字符串中解析出 Shortcode
|
||||
// 返回 false 表示格式不合法
|
||||
func parseShortcode(raw string) (model.Shortcode, bool) {
|
||||
matches := model.ShortcodePattern.FindStringSubmatch(raw)
|
||||
if len(matches) != 3 {
|
||||
return model.Shortcode{}, false
|
||||
}
|
||||
|
||||
sc := model.Shortcode{
|
||||
Raw: raw,
|
||||
Type: model.ShortcodeType(matches[1]),
|
||||
Params: strings.TrimSpace(matches[2]),
|
||||
}
|
||||
|
||||
if sc.Params == "" {
|
||||
return model.Shortcode{}, false
|
||||
}
|
||||
|
||||
return sc, true
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// 占位 HTML 渲染器(每个类型一个 case)
|
||||
// =============================================================================
|
||||
|
||||
// renderPlaceholder 根据 shortcode 类型生成前端占位 HTML
|
||||
//
|
||||
// 占位 div 结构约定:
|
||||
// <div class="zone-card" data-zone-type="类型" data-zone-id="参数"
|
||||
// data-zone-extra="附加信息">
|
||||
// <span class="zone-card-loading">卡片加载中...</span>
|
||||
// </div>
|
||||
//
|
||||
// 前端 shortcode.js 根据 data-zone-* 属性决定如何渲染。
|
||||
// "加载中..." 文本会被 shortcode.js 在渲染时替换,仅作降级显示。
|
||||
func renderPlaceholder(sc model.Shortcode) string {
|
||||
switch sc.Type {
|
||||
case model.ShortcodeEvent:
|
||||
// [zone:event:活动ID]
|
||||
// 前端根据活动ID获取标题、时间、封面等信息
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="event" data-zone-id="%s"><span class="zone-card-loading">活动卡片加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
)
|
||||
|
||||
case model.ShortcodeGame:
|
||||
// [zone:game:游戏slug]
|
||||
// 前端根据游戏slug获取名称、封面、标签等信息
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="game" data-zone-id="%s"><span class="zone-card-loading">游戏卡片加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
)
|
||||
|
||||
case model.ShortcodePoll:
|
||||
// [zone:poll:投票ID] ※预留
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="poll" data-zone-id="%s"><span class="zone-card-loading">投票组件加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
)
|
||||
|
||||
case model.ShortcodeResource:
|
||||
// [zone:resource:资源ID] ※预留
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="resource" data-zone-id="%s"><span class="zone-card-loading">资源卡片加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
)
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user