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

@ -1,319 +1,209 @@
/**
* MetaLab Editor — Tiptap 所见即所得编辑器
* MetaLab Editor — Vditor Markdown 所见即所得编辑器
*
* Tiptap 基于 ProseMirror输出 HTML无需 Markdown 知识即可使用
* 后端存储 HTML通过 bluemonday 消毒确保安全
* Vditor 原生支持 MD + WYSIWYG后端存储 Markdown。
* 图片上传复用现有 /api/posts/upload-image后端已返回 Vditor 原生响应格式
* 安全模型:前端输出 MD纯文本→ 后端直接存储 → 详情页客户端 Vditor 渲染为 HTML。
*
* 安全模型Tiptap → HTML富文本→ 后端 bluemonday 消毒 → 存储
* Shortcode 扩展语法([zone:type:params]
* 输入 [zone: 触发自动补全,选择类型后自动生成对应语法。
* 支持的 shortcode 详情见 /docs/vditor-migration-plan.md
*
* Vditor 全局对象由 /static/vditor/dist/index.min.js 提供。
*/
import { Editor } from '@tiptap/core'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import Image from '@tiptap/extension-image'
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import { common, createLowlight } from 'lowlight'
// ---- 状态 ----
let editor = null
let currentHTML = ''
let vditor = null
let draftTimer = null
let submitting = false
// ---- CSRF Token ----
function getCsrfToken() {
const meta = document.querySelector('meta[name="csrf-token"]')
return meta ? meta.getAttribute('content') : ''
}
// ---- 初始化 ----
document.addEventListener('DOMContentLoaded', () => {
const container = document.getElementById('editor-container')
const container = document.getElementById('vditor')
if (!container) return
const postId = document.getElementById('postId')?.value
const isEdit = !!postId
// 从容器 data-content 属性获取初始 HTML 内容(由后端 SSR 渲染)
const initialContent = container.dataset.content || ''
currentHTML = initialContent
editor = new Editor({
element: container,
extensions: [
StarterKit.configure({
heading: { levels: [1, 2, 3] },
link: {
openOnClick: false,
HTMLAttributes: { rel: 'noopener noreferrer', target: '_blank' },
},
codeBlock: false,
}),
CodeBlockLowlight.configure({
lowlight: createLowlight(common),
defaultLanguage: null,
}),
Placeholder.configure({
placeholder: '在此输入正文...',
}),
Image.configure({
inline: true,
}),
],
content: initialContent,
onUpdate: ({ editor }) => {
const html = editor.getHTML()
// 忽略空内容(<p></p>
currentHTML = html === '<p></p>' ? '' : html
updateWordCount(editor.getText())
scheduleDraft(currentHTML)
},
})
// 初始字数统计
updateWordCount(editor.getText())
// 恢复草稿(延迟确保编辑器完全初始化)
if (!isEdit) {
setTimeout(() => restoreDraft(), 100)
// 获取初始内容:编辑模式下从后端传入,新帖模式尝试恢复草稿
let initialMD = ''
if (isEdit) {
// 编辑模式:从后端 JSON 嵌入的 Post.BodyMD中获取
// 由 Go 模板 {{.Post.Body}} 嵌入到 hidden 字段或 script 标签
initialMD = ''
}
// 工具栏按钮绑定
setupToolbar()
// 从隐藏字段获取编辑内容Go 模板传入)
const editBodyEl = document.getElementById('editBody')
if (editBodyEl) {
initialMD = editBodyEl.value
}
// 全屏切换
document.getElementById('btnFullscreen')?.addEventListener('click', toggleFullscreen)
vditor = new Vditor('vditor', {
// 核心配置
mode: 'wysiwyg',
cdn: '/static/vditor',
height: '100%',
lang: 'zh_CN',
placeholder: '在此输入正文...',
// 工具栏(精简,适合技术社区)
toolbar: [
'headings', 'bold', 'italic', 'strike', '|',
'line', 'code', 'inline-code', 'link', 'quote', '|',
'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
'upload', 'table', '|',
'undo', 'redo', '|',
'fullscreen', 'code-theme', '|',
'outline', 'preview', 'devtools',
],
// 计数器
counter: {
enable: true,
type: 'text',
},
// Shortcode 自动补全提示
// 输入 [zone: 后触发,列出所有已注册的 shortcode 类型
hint: {
extend: [
{
key: '[zone:event:',
value: '[zone:event:活动ID]',
},
{
key: '[zone:game:',
value: '[zone:game:游戏Slug]',
},
{
key: '[zone:poll:',
value: '[zone:poll:投票ID]',
},
{
key: '[zone:resource:',
value: '[zone:resource:资源ID]',
},
],
},
// 大纲
outline: {
enable: true,
position: 'right',
},
// 预览配置
preview: {
theme: { current: 'light', path: '/static/vditor/dist/css/content-theme' },
hljs: { style: 'github-dark', enable: true },
markdown: { codeBlockPreview: true },
},
// 图片上传
upload: {
url: '/api/posts/upload-image',
fieldName: 'file',
max: 5 * 1024 * 1024,
accept: 'image/jpg,image/jpeg,image/png,image/gif,image/webp',
// setHeaders 为函数,每次上传前重新读取 CSRF token
setHeaders() {
return { 'X-CSRF-Token': getCsrfToken() }
},
},
// 初始内容
value: initialMD,
// 初始化完成
after() {
// 新帖模式下恢复草稿
if (!isEdit) {
setTimeout(() => restoreDraft(), 100)
}
// 更新字数
updateWordCount()
},
// 内容变化
input(value) {
scheduleDraft(value)
updateWordCount()
},
})
// 表单提交
document.getElementById('postForm')?.addEventListener('submit', handleSubmit)
// Ctrl+S / F11 快捷键
document.addEventListener('keydown', handleKeyboard)
})
// ---- 工具栏 ----
function setupToolbar() {
const toolbar = document.getElementById('toolbar')
if (!toolbar) return
const actionMap = {
bold: () => editor.chain().focus().toggleBold().run(),
italic: () => editor.chain().focus().toggleItalic().run(),
strike: () => editor.chain().focus().toggleStrike().run(),
code: () => editor.chain().focus().toggleCode().run(),
h1: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
h2: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
h3: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
bulletList: () => editor.chain().focus().toggleBulletList().run(),
orderedList: () => editor.chain().focus().toggleOrderedList().run(),
blockquote: () => editor.chain().focus().toggleBlockquote().run(),
codeBlock: () => editor.chain().focus().toggleCodeBlock().run(),
horizontalRule: () => editor.chain().focus().setHorizontalRule().run(),
undo: () => editor.chain().focus().undo().run(),
redo: () => editor.chain().focus().redo().run(),
}
const activeCheck = {
bold: () => editor.isActive('bold'),
italic: () => editor.isActive('italic'),
strike: () => editor.isActive('strike'),
code: () => editor.isActive('code'),
h1: () => editor.isActive('heading', { level: 1 }),
h2: () => editor.isActive('heading', { level: 2 }),
h3: () => editor.isActive('heading', { level: 3 }),
bulletList: () => editor.isActive('bulletList'),
orderedList: () => editor.isActive('orderedList'),
blockquote: () => editor.isActive('blockquote'),
codeBlock: () => editor.isActive('codeBlock'),
}
function updateActive() {
toolbar.querySelectorAll('[data-action]').forEach(btn => {
const action = btn.dataset.action
const check = activeCheck[action]
btn.classList.toggle('is-active', check ? check() : false)
})
}
toolbar.addEventListener('click', (e) => {
const btn = e.target.closest('[data-action]')
if (!btn) return
const action = btn.dataset.action
if (actionMap[action]) {
actionMap[action]()
updateActive()
// 快捷键 Ctrl+S
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault()
document.getElementById('postForm')?.dispatchEvent(new Event('submit'))
}
})
// ---- 代码块语言选择器 ----
const langSelect = document.getElementById('codeLangSelect')
if (langSelect) {
// 阻止 select 获取焦点导致编辑器失焦
langSelect.addEventListener('mousedown', (e) => {
// 全屏快捷键 F11
document.addEventListener('keydown', (e) => {
if (e.key === 'F11') {
e.preventDefault()
// 手动切换选项
const opts = langSelect.options
let nextIdx = langSelect.selectedIndex + 1
if (nextIdx >= opts.length) nextIdx = 0
langSelect.selectedIndex = nextIdx
const lang = opts[nextIdx].value
// 在编辑器内更新代码块语言属性
editor.chain().focus().updateAttributes('codeBlock', { language: lang === 'text' ? null : lang }).run()
})
// 当光标在代码块内时显示语言选择器并同步当前语言,移出时隐藏
editor.on('selectionUpdate', () => {
if (editor.isActive('codeBlock')) {
langSelect.style.display = ''
const attrs = editor.getAttributes('codeBlock')
langSelect.value = attrs.language || 'text'
} else {
langSelect.style.display = 'none'
}
})
}
// ---- 代码块语言标签注入 ----
// 为每个 <pre> 注入语言标签 DOM 元素(因为 CSS ::before 在 overflow:auto 容器中不可靠)
// Tiptap CodeBlockLowlight 在 pre 上输出 data-language 属性,同时 code 上有 language-xxx class
function injectCodeLangLabels() {
const editorEl = document.querySelector('#editor-container .tiptap')
if (!editorEl) return
editorEl.querySelectorAll('pre').forEach(pre => {
// 移除旧标签
const old = pre.querySelector('.code-lang-label')
if (old) old.remove()
// 从 pre 的 data-language 或 code 的 class 中获取语言
let lang = pre.getAttribute('data-language')
if (!lang) {
const code = pre.querySelector('code')
if (code) {
const match = code.className.match(/language-(\w+)/)
if (match) lang = match[1]
}
}
lang = lang || 'text'
const label = document.createElement('div')
label.className = 'code-lang-label'
label.textContent = lang
pre.insertBefore(label, pre.firstChild)
pre.style.paddingTop = '32px'
})
}
editor.on('update', injectCodeLangLabels)
// 初始注入
setTimeout(injectCodeLangLabels, 50)
editor.on('selectionUpdate', updateActive)
editor.on('update', updateActive)
}
// ---- 图片上传(拖拽/粘贴) ----
// Tiptap 默认支持图片拖入,但我们需要上传到服务器并替换 src
// 通过监听 editor 的 drop/paste 事件处理图片
document.addEventListener('DOMContentLoaded', () => {
// 延迟绑定,等 editor 初始化
setTimeout(() => {
const editorEl = document.querySelector('#editor-container .tiptap')
if (!editorEl) return
// 粘贴图片
editorEl.addEventListener('paste', async (e) => {
const items = e.clipboardData?.items
if (!items) return
for (const item of items) {
if (item.type.startsWith('image/')) {
e.preventDefault()
const file = item.getAsFile()
const url = await uploadSingleImage(file)
if (url) {
editor.chain().focus().setImage({ src: url }).run()
}
break
}
}
})
// 拖入图片
editorEl.addEventListener('drop', async (e) => {
const files = e.dataTransfer?.files
if (!files || files.length === 0) return
const imageFiles = Array.from(files).filter(f => f.type.startsWith('image/'))
if (imageFiles.length === 0) return
e.preventDefault()
for (const file of imageFiles) {
const url = await uploadSingleImage(file)
if (url) {
editor.chain().focus().setImage({ src: url }).run()
}
}
})
}, 200)
const layout = document.querySelector('.editor-layout')
if (layout) layout.classList.toggle('fullscreen')
}
})
})
async function uploadSingleImage(file) {
const csrfMeta = document.querySelector('meta[name="csrf-token"]')
const csrf = csrfMeta ? csrfMeta.getAttribute('content') : ''
const formData = new FormData()
formData.append('file', file)
try {
const resp = await fetch('/api/posts/upload-image', {
method: 'POST',
headers: { 'X-CSRF-Token': csrf },
body: formData,
})
const data = await resp.json()
if (data.success || data.code === 200) {
return data.data?.url || data.url || ''
}
} catch (e) {
// 上传失败,静默忽略
}
return ''
}
// ---- 字数统计 ----
function updateWordCount(text) {
function updateWordCount() {
const el = document.getElementById('wordCount')
if (!el) return
const len = (text || '').replace(/\s/g, '').length
el.textContent = len + ' 字'
if (!el || !vditor) return
// Vditor 自带计数器已渲染到 .vditor-counter我们同步到自定义的状态栏
const counterEl = document.querySelector('.vditor-counter')
if (counterEl) {
el.textContent = counterEl.textContent
}
}
// ---- 草稿保存/恢复 ----
function scheduleDraft(html) {
function scheduleDraft(md) {
clearTimeout(draftTimer)
draftTimer = setTimeout(() => saveDraft(html), 2000)
draftTimer = setTimeout(() => saveDraft(md), 2000)
}
function saveDraft(html) {
function saveDraft(md) {
const title = document.getElementById('postTitle')?.value || ''
if (!html.trim() && !title.trim()) return
if (!md.trim() && !title.trim()) return
try {
localStorage.setItem('draft_post_title', title)
localStorage.setItem('draft_post_body_html', html)
localStorage.setItem('draft_post_body_md', md)
const statusEl = document.getElementById('draftStatus')
if (statusEl) {
statusEl.style.display = ''
setTimeout(() => { statusEl.style.display = 'none' }, 2000)
}
} catch (e) {
// localStorage 不可用,静默忽略
// localStorage 不可用
}
}
function restoreDraft() {
try {
const title = localStorage.getItem('draft_post_title')
const html = localStorage.getItem('draft_post_body_html')
const md = localStorage.getItem('draft_post_body_md')
if (title) {
document.getElementById('postTitle').value = title
}
if (html && editor) {
editor.commands.setContent(html)
currentHTML = html
updateWordCount(editor.getText())
if (md && vditor) {
vditor.setValue(md)
updateWordCount()
}
} catch (e) {
// 静默忽略
@ -323,30 +213,10 @@ function restoreDraft() {
function clearDraft() {
try {
localStorage.removeItem('draft_post_title')
localStorage.removeItem('draft_post_body_html')
localStorage.removeItem('draft_post_body_md')
} catch (e) { /* ignore */ }
}
// ---- 全屏 ----
function toggleFullscreen() {
const layout = document.querySelector('.editor-layout')
if (!layout) return
layout.classList.toggle('fullscreen')
}
// ---- 键盘快捷键 ----
function handleKeyboard(e) {
if (e.key === 'F11') {
e.preventDefault()
toggleFullscreen()
}
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault()
document.getElementById('postForm')?.dispatchEvent(new Event('submit'))
}
}
// ---- 表单提交 ----
async function handleSubmit(e) {
e.preventDefault()
@ -366,26 +236,21 @@ async function handleSubmit(e) {
if (!title) { alert('请输入标题'); return }
// 获取编辑器 HTML 内容
const body = editor ? editor.getHTML() : ''
// 忽略空段落
const cleanBody = body === '<p></p>' ? '' : body
if (!cleanBody.trim()) { alert('请输入正文'); return }
// 获取 Vditor Markdown 内容
const body = vditor ? vditor.getValue() : ''
if (!body.trim()) { alert('请输入正文'); return }
const isEdit = !!postId
const url = isEdit ? '/api/posts/' + postId : '/api/posts'
const method = isEdit ? 'PUT' : 'POST'
const csrfMeta = document.querySelector('meta[name="csrf-token"]')
const csrf = csrfMeta ? csrfMeta.getAttribute('content') : ''
const resp = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrf,
'X-CSRF-Token': getCsrfToken(),
},
body: JSON.stringify({ title, body: cleanBody }),
body: JSON.stringify({ title, body }),
})
const data = await resp.json()
@ -407,8 +272,8 @@ async function handleSubmit(e) {
submitting = false
if (submitBtn) {
submitBtn.disabled = false
submitBtn.textContent = submitBtn.textContent === '提交中...' ?
(document.getElementById('postId')?.value ? '保存修改' : '发布帖子') : submitBtn.textContent
const isEdit = !!document.getElementById('postId')?.value
submitBtn.textContent = isEdit ? '保存修改' : '发布帖子'
}
}
}

View File

@ -0,0 +1,135 @@
/**
* Shortcode 卡片渲染器 — 配合 [zone:type:params] Markdown 扩展语法
*
* 工作流程:
* 1. 后端 ShortcodeService 将 MD 中的 [zone:type:params] 替换为占位 <div class="zone-card">
* 2. Vditor.preview() 渲染 MD占位 div 原样保留
* 3. 本脚本扫描所有 .zone-card根据 data-zone-* 属性渲染对应卡片 UI
*
* 添加新卡片类型:
* 1. 在 cardRenderers 中注册类型标识和渲染函数
* 2. 渲染函数接收 id 参数,返回 HTML 字符串
* 3. 如果后端 API 已可用,在渲染函数中 fetch 数据;否则展示静态占位卡片
*
* 后端 shortcode 语法参考: /docs/vditor-migration-plan.md
*/
(function () {
'use strict';
// =========================================================================
// 卡片渲染函数注册表
//
// 每个渲染函数签名为: function(id: string) → html: string
// id 来自 [zone:type:id] 中的 id 部分
// =========================================================================
var cardRenderers = {
/**
* 活动卡片 — [zone:event:活动ID]
* TODO: 接入活动 API 后改为 fetch 动态数据
*/
event: function (id) {
return '' +
'<div class="zone-card-event">' +
' <div class="zone-card-event-icon">🎪</div>' +
' <div class="zone-card-event-body">' +
' <div class="zone-card-event-title">官方活动</div>' +
' <div class="zone-card-event-id">活动 ID: ' + escapeHtml(id) + '</div>' +
' </div>' +
' <a class="zone-card-event-link" href="/events/' + escapeHtml(id) + '" target="_blank">查看详情 →</a>' +
'</div>';
},
/**
* 游戏卡片 — [zone:game:游戏slug]
* TODO: 接入游戏数据库 API 后改为 fetch 动态数据
*/
game: function (id) {
return '' +
'<div class="zone-card-game">' +
' <div class="zone-card-game-icon">🎮</div>' +
' <div class="zone-card-game-body">' +
' <div class="zone-card-game-title">相关游戏</div>' +
' <div class="zone-card-game-slug">' + escapeHtml(id) + '</div>' +
' </div>' +
' <a class="zone-card-game-link" href="/games/' + escapeHtml(id) + '" target="_blank">查看 →</a>' +
'</div>';
},
/**
* 投票组件 — [zone:poll:投票ID]
* ※预留:后端投票 API 未实现,当前展示占位卡片
*/
poll: function (id) {
return '' +
'<div class="zone-card-poll">' +
' <div class="zone-card-poll-icon">📊</div>' +
' <div class="zone-card-poll-body">' +
' <div class="zone-card-poll-title">社区投票</div>' +
' <div class="zone-card-poll-id">投票 ID: ' + escapeHtml(id) + '</div>' +
' </div>' +
' <span class="zone-card-poll-pending">即将开放</span>' +
'</div>';
},
/**
* 资源卡片 — [zone:resource:资源ID]
* ※预留:后端资源 API 未实现,当前展示占位卡片
*/
resource: function (id) {
return '' +
'<div class="zone-card-resource">' +
' <div class="zone-card-resource-icon">📦</div>' +
' <div class="zone-card-resource-body">' +
' <div class="zone-card-resource-title">推荐资源</div>' +
' <div class="zone-card-resource-id">资源 ID: ' + escapeHtml(id) + '</div>' +
' </div>' +
' <a class="zone-card-resource-link" href="/resources/' + escapeHtml(id) + '" target="_blank">查看 →</a>' +
'</div>';
}
};
// =========================================================================
// 工具函数
// =========================================================================
function escapeHtml(str) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// =========================================================================
// 主渲染逻辑
// =========================================================================
/**
* renderShortcodes — 扫描容器内所有 .zone-card 占位并渲染
* @param {HTMLElement} container — 包含 shortcode 占位的 DOM 容器
*/
window.renderShortcodes = function (container) {
if (!container) return;
var placeholders = container.querySelectorAll('.zone-card');
for (var i = 0; i < placeholders.length; i++) {
var el = placeholders[i];
var type = el.getAttribute('data-zone-type');
var id = el.getAttribute('data-zone-id');
if (!type || !id) continue;
var renderer = cardRenderers[type];
if (!renderer) continue;
// 渲染卡片 HTML 并替换占位 div
try {
el.outerHTML = renderer(id);
} catch (e) {
// 渲染失败时保留占位文本
console.warn('[Shortcode] render failed for type=' + type + ' id=' + id, e);
}
}
};
})();