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:
2026-05-30 15:56:22 +08:00
parent c9808ab9b2
commit 6ec12010f3
121 changed files with 8267 additions and 613 deletions

View File

@ -22,3 +22,16 @@ func OkWithMessage(c *gin.Context, data interface{}, message string) {
func Error(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{"success": false, "message": message})
}
// VditorUploadOk Vditor 图片上传成功响应
// succMap: key=原始文件名, value=文件 URL
func VditorUploadOk(c *gin.Context, succMap map[string]string) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "",
"data": gin.H{
"errFiles": []string{},
"succMap": succMap,
},
})
}

View File

@ -3,7 +3,6 @@ package controller
import (
"errors"
"fmt"
"html/template"
"mime/multipart"
"net/http"
"os"
@ -14,18 +13,20 @@ import (
"metazone.cc/metalab/internal/common"
"metazone.cc/metalab/internal/model"
"metazone.cc/metalab/internal/service"
"github.com/gin-gonic/gin"
)
// PostController 帖子控制器SSR 页面 + API
type PostController struct {
postService postUseCase
postService postUseCase
shortcodeSvc *service.ShortcodeService
}
// NewPostController 构造函数
func NewPostController(ps postUseCase) *PostController {
return &PostController{postService: ps}
func NewPostController(ps postUseCase, scs *service.ShortcodeService) *PostController {
return &PostController{postService: ps, shortcodeSvc: scs}
}
// ListPage 帖子列表页
@ -105,13 +106,19 @@ func (ctrl *PostController) ShowPage(c *gin.Context) {
}
}
// 处理 shortcode[zone:type:params] → HTML 占位符
// 占位 div 会被 Vditor.preview() 保留,由前端 shortcode.js 渲染为卡片
if ctrl.shortcodeSvc != nil {
result := ctrl.shortcodeSvc.Process(post.Body)
post.Body = result.ProcessedBody
}
c.HTML(http.StatusOK, "posts/show.html", common.BuildPageData(c, gin.H{
"Title": post.Title,
"Post": post,
"PostBodyHTML": template.HTML(post.BodyHTML),
"UID": uid,
"StatusNames": model.PostStatusDisplayNames,
"ExtraCSS": "/static/css/posts.css",
"Title": post.Title,
"Post": post,
"UID": uid,
"StatusNames": model.PostStatusDisplayNames,
"ExtraCSS": "/static/css/posts.css",
}))
}
@ -367,6 +374,12 @@ func (ctrl *PostController) ShowAPI(c *gin.Context) {
}
}
// 处理 shortcode[zone:type:params] → HTML 占位符
if ctrl.shortcodeSvc != nil {
result := ctrl.shortcodeSvc.Process(post.Body)
post.Body = result.ProcessedBody
}
common.Ok(c, post)
}
@ -423,7 +436,7 @@ func (ctrl *PostController) UploadImage(c *gin.Context) {
}
url := "/uploads/posts/" + filename
common.Ok(c, gin.H{"url": url})
common.VditorUploadOk(c, map[string]string{header.Filename: url})
}
// saveUploadedFile 将 multipart.File 写入目标路径

View File

@ -8,17 +8,17 @@ import (
// Post 帖子/文章模型
type Post struct {
ID uint `gorm:"primarykey" json:"id"`
Title string `gorm:"type:varchar(200);not null" json:"title"`
Body string `gorm:"type:text" json:"body"`
BodyHTML string `gorm:"type:text" json:"body_html"`
UserID uint `gorm:"index;not null" json:"user_id"`
Status string `gorm:"type:varchar(20);index;default:draft;not null" json:"status"`
RejectReason string `gorm:"type:varchar(500);default:''" json:"reject_reason,omitempty"`
AllowComment bool `gorm:"default:true" json:"allow_comment"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID uint `gorm:"primarykey" json:"id"`
Title string `gorm:"type:varchar(200);not null" json:"title"`
Body string `gorm:"type:text" json:"body"` // Markdown content
Excerpt string `gorm:"type:varchar(500)" json:"excerpt"` // plain text summary for list
UserID uint `gorm:"index;not null" json:"user_id"`
Status string `gorm:"type:varchar(20);index;default:draft;not null" json:"status"`
RejectReason string `gorm:"type:varchar(500);default:''" json:"reject_reason,omitempty"`
AllowComment bool `gorm:"default:true" json:"allow_comment"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// 非数据库字段(联表查询填充)
// gorm:"-:migration" 指定不创建/迁移该列,"<-:false" 禁止写入,"column:author_name" 允许

View File

@ -0,0 +1,92 @@
package model
// =============================================================================
// Shortcode — Markdown 扩展语法
//
// 用法:在 MD 正文中插入 [zone:类型:参数],渲染时替换为对应 UI 卡片。
//
// 支持的 shortcode
// [zone:event:活动ID] → 官方活动卡片(标题、时间、封面、链接)
// [zone:game:游戏slug] → 游戏信息卡片(名称、封面、类型)
// [zone:poll:投票ID] → 投票组件(预留)
// [zone:resource:资源ID] → 资源卡片(工具/素材推荐,预留)
//
// 扩展现有类型:在 ShortcodeRegistry 中注册新类型 + 实现 Renderer 即可。
// =============================================================================
import "regexp"
// =============================================================================
// 语法常量
// =============================================================================
// ShortcodePattern 匹配所有 [zone:type:params] 模式的 shortcode
// 捕获组:$1=类型, $2=参数
var ShortcodePattern = regexp.MustCompile(`\[zone:(\w+):([^\]]+)\]`)
// =============================================================================
// 已注册的 Shortcode 类型
// =============================================================================
// ShortcodeType 定义一种 shortcode 的类型标识
type ShortcodeType string
const (
ShortcodeEvent ShortcodeType = "event" // [zone:event:活动ID]
ShortcodeGame ShortcodeType = "game" // [zone:game:游戏slug]
ShortcodePoll ShortcodeType = "poll" // [zone:poll:投票ID] ※预留后端API未实现
ShortcodeResource ShortcodeType = "resource" // [zone:resource:资源ID] ※预留后端API未实现
)
// allTypes 所有已定义的 shortcode 类型,添加新类型时在这里追加
var allTypes = []ShortcodeType{
ShortcodeEvent,
ShortcodeGame,
ShortcodePoll,
ShortcodeResource,
}
// IsValidType 检查给定类型是否已注册
func IsValidType(t string) bool {
for _, st := range allTypes {
if string(st) == t {
return true
}
}
return false
}
// =============================================================================
// 解析结果
// =============================================================================
// Shortcode 一次解析的结果
type Shortcode struct {
Raw string // 原始文本,如 "[zone:event:abc123]"
Type ShortcodeType // 类型
Params string // 参数ID/slug 等)
}
// ShortcodeResult 整个 body 的解析结果
type ShortcodeResult struct {
// ProcessedBody 替换后的 bodyshortcode → HTML 占位符),可直接传给模板渲染
ProcessedBody string
// Shortcodes 本次解析到的所有 shortcode 列表
Shortcodes []Shortcode
}
// =============================================================================
// 卡片渲染数据 DTO
// =============================================================================
// ShortcodeCard 渲染一张卡片的通用数据
// 前端根据 Type 决定具体 UI 组件,字段按需填充
type ShortcodeCard struct {
Type ShortcodeType `json:"type"`
ID string `json:"id"` // 业务 ID活动ID / 游戏slug
Title string `json:"title,omitempty"`
Cover string `json:"cover,omitempty"`
Desc string `json:"desc,omitempty"`
URL string `json:"url,omitempty"`
Extra string `json:"extra,omitempty"` // 扩展字段时间、标签等JSON string
}

View File

@ -32,7 +32,8 @@ func buildDeps(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSetting
postRepo := repository.NewPostRepo(db)
postService := service.NewPostService(postRepo, siteSettings)
postCtrl := controller.NewPostController(postService)
shortcodeSvc := service.NewShortcodeService()
postCtrl := controller.NewPostController(postService, shortcodeSvc)
adminPostCtrl := adminCtrl.NewAdminPostController(postService)
return &dependencies{

View File

@ -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("`[^`]+`"),
// 图片 ![alt](url)
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 {

View 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 ""
}
}