编辑器三件套(参考 xLog):CodeMirror 源码模式 + 外链图片一键转存 + 上传进度/前置校验
- md 页签从裸 textarea 升级 CodeMirror 6:markdown 语法高亮、行内历史,粘贴/拖图直传; markdown 仍是唯一真相源,转存/切换用 syncCM 全量灌回,工具栏选区辅助改为面向 CM - POST /api/admin/files/import:外链抓取复用 linkmeta SSRF 防护拨号与跳转限制, 二进制传输放宽 30s;类型按内容嗅探反查白名单,与手动上传共用去重/落盘(persistFile 抽取共享) - 上传走 XHR 进度回调 + 编辑器 toast 栈:类型/大小前置校验(与后端白名单一致)、逐文件进度 - persistFile 去重路径补 URL 解析——此前命中去重返回的行没有 URL,转存替换会把正文图链清空(已修复受损数据) - hub nil 安全(测试环境未装配时不 panic)
This commit is contained in:
@@ -2,9 +2,14 @@
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
|
||||
import { adminApi } from '../api'
|
||||
import { site } from '../site'
|
||||
import { Crepe, CrepeFeature } from '@milkdown/crepe'
|
||||
import '@milkdown/crepe/theme/common/style.css'
|
||||
import '@milkdown/crepe/theme/frame.css'
|
||||
import { EditorView as CMView, keymap } from '@codemirror/view'
|
||||
import { EditorState } from '@codemirror/state'
|
||||
import { markdown as markdownLang } from '@codemirror/lang-markdown'
|
||||
import { history, defaultKeymap, historyKeymap, indentWithTab } from '@codemirror/commands'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -184,6 +189,10 @@ onBeforeUnmount(() => {
|
||||
crepe.destroy()
|
||||
crepe = null
|
||||
}
|
||||
if (cmView) {
|
||||
cmView.destroy()
|
||||
cmView = null
|
||||
}
|
||||
})
|
||||
|
||||
// ---------- mode switching ----------
|
||||
@@ -195,6 +204,10 @@ async function switchMode(next) {
|
||||
crepe.destroy()
|
||||
crepe = null
|
||||
}
|
||||
// CM 懒挂载;已挂载就把 wysiwyg 期间产生的 markdown 灌回来
|
||||
await nextTick()
|
||||
mountCM()
|
||||
syncCM()
|
||||
} else {
|
||||
// MD → WYSIWYG: spin up crepe with the current markdown
|
||||
await nextTick()
|
||||
@@ -399,6 +412,76 @@ function clearCover() {
|
||||
// ---------- 工具栏:Markdown 模式插入 + 通用动作 ----------
|
||||
|
||||
const mdPane = ref(null)
|
||||
|
||||
// ---------- CodeMirror 源码模式 ----------
|
||||
// md 页签不是裸 textarea:语法高亮 + 行内历史(⌘Z),粘贴/拖图片直接上传。
|
||||
// markdown 仍是唯一真相源——CM 的改动写回 form.content_md,
|
||||
// 外部改动(转存替换、wysiwyg 切回)用 syncCM 全量灌回。
|
||||
let cmView = null
|
||||
const cmTheme = CMView.theme({
|
||||
'&': { color: 'var(--admin-ink)', backgroundColor: 'transparent', fontSize: '13.5px' },
|
||||
'.cm-content': { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', lineHeight: '1.75', padding: '12px 0 40vh' },
|
||||
'.cm-scroller': { overflow: 'auto', maxHeight: '70vh' },
|
||||
'.cm-line': { padding: '0 2px' },
|
||||
'&.cm-focused': { outline: 'none' },
|
||||
'.cm-cursor': { borderLeftColor: 'var(--admin-accent)' },
|
||||
'.cm-selectionBackground, ::selection': { backgroundColor: 'color-mix(in srgb, var(--admin-accent) 18%, transparent) !important' },
|
||||
'.cm-activeLine': { backgroundColor: 'color-mix(in srgb, var(--admin-accent) 6%, transparent)' },
|
||||
'.cm-heading, .cm-header': { color: 'var(--admin-accent)', fontWeight: '600' },
|
||||
'.cm-link, .cm-url': { color: 'var(--admin-accent)', textDecoration: 'underline' },
|
||||
'.cm-emphasis': { fontStyle: 'italic' },
|
||||
'.cm-strong': { fontWeight: '700' },
|
||||
'.cm-code, .cm-monospace': { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', color: 'var(--admin-muted)' }
|
||||
})
|
||||
|
||||
function handleEditorFiles(files, view) {
|
||||
const list = [...files].filter((f) => f.type.startsWith('image/'))
|
||||
if (!list.length) return false
|
||||
view.dispatch({
|
||||
changes: { from: view.state.selection.main.from, insert: ' ' }
|
||||
})
|
||||
;[...list].forEach((f) => uploadOne(f, { insertImage: true }))
|
||||
return true
|
||||
}
|
||||
|
||||
function mountCM() {
|
||||
if (cmView || !mdPane.value) return
|
||||
cmView = new CMView({
|
||||
parent: mdPane.value,
|
||||
state: EditorState.create({
|
||||
doc: form.content_md,
|
||||
extensions: [
|
||||
history(),
|
||||
keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
|
||||
markdownLang(),
|
||||
cmTheme,
|
||||
CMView.updateListener.of((u) => {
|
||||
if (u.docChanged) form.content_md = u.state.doc.toString()
|
||||
}),
|
||||
CMView.domEventHandlers({
|
||||
paste: (e, view) => handleEditorFiles(e.clipboardData?.files, view),
|
||||
drop: (e, view) => {
|
||||
if (e.dataTransfer?.files?.length) {
|
||||
e.preventDefault()
|
||||
return handleEditorFiles(e.dataTransfer.files, view)
|
||||
}
|
||||
return false
|
||||
}
|
||||
})
|
||||
]
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 用 form.content_md 的当前值整段灌回(进入 md 页签、转存替换后调用)
|
||||
function syncCM() {
|
||||
if (!cmView) return
|
||||
const cur = cmView.state.doc.toString()
|
||||
if (cur === form.content_md) return
|
||||
cmView.dispatch({
|
||||
changes: { from: 0, to: cur.length, insert: form.content_md }
|
||||
})
|
||||
}
|
||||
const showLinkInput = ref(false)
|
||||
const showImageInput = ref(false)
|
||||
const linkText = ref('')
|
||||
@@ -407,22 +490,31 @@ const imageUrl = ref('')
|
||||
const imageAlt = ref('')
|
||||
|
||||
function insertAtCursor(text, selStart, selEnd) {
|
||||
if (cmView) {
|
||||
if (selStart == null) {
|
||||
const s = cmView.state.selection.main
|
||||
selStart = s.from
|
||||
selEnd = s.to
|
||||
}
|
||||
cmView.dispatch({
|
||||
changes: { from: selStart, to: selEnd, insert: text },
|
||||
selection: { anchor: selStart + text.length }
|
||||
})
|
||||
cmView.focus()
|
||||
return
|
||||
}
|
||||
const before = form.content_md.slice(0, selStart)
|
||||
const after = form.content_md.slice(selEnd)
|
||||
form.content_md = before + text + after
|
||||
nextTick(() => {
|
||||
if (!mdPane.value) return
|
||||
const newPos = selStart + text.length
|
||||
mdPane.value.focus()
|
||||
mdPane.value.setSelectionRange(newPos, newPos)
|
||||
})
|
||||
}
|
||||
|
||||
function withSelection(fn) {
|
||||
const el = mdPane.value
|
||||
const start = el ? el.selectionStart : form.content_md.length
|
||||
const end = el ? el.selectionEnd : form.content_md.length
|
||||
fn(start, end)
|
||||
if (cmView) {
|
||||
const sel = cmView.state.selection.main
|
||||
fn(sel.from, sel.to)
|
||||
return
|
||||
}
|
||||
fn(form.content_md.length, form.content_md.length)
|
||||
}
|
||||
|
||||
function tbBold() {
|
||||
@@ -533,24 +625,142 @@ function commitImage() {
|
||||
showImageInput.value = false
|
||||
}
|
||||
|
||||
// ---------- toast ----------
|
||||
// 编辑器内的轻提示:上传进度、转存结果、校验失败。自动消失,错误多留一会儿。
|
||||
const toasts = reactive([])
|
||||
let toastSeq = 0
|
||||
function toast(text, type = 'info', ttl = 2600) {
|
||||
const id = ++toastSeq
|
||||
toasts.push({ id, text, type })
|
||||
setTimeout(() => {
|
||||
const i = toasts.findIndex((t) => t.id === id)
|
||||
if (i >= 0) toasts.splice(i, 1)
|
||||
}, ttl)
|
||||
return id
|
||||
}
|
||||
function toastUpdate(id, text, type = 'info') {
|
||||
const t = toasts.find((x) => x.id === id)
|
||||
if (t) {
|
||||
t.text = text
|
||||
t.type = type
|
||||
}
|
||||
}
|
||||
function toastDone(id, text) {
|
||||
toastUpdate(id, text, 'ok')
|
||||
const idx = toasts.findIndex((t) => t.id === id)
|
||||
if (idx >= 0) {
|
||||
const t = toasts[idx]
|
||||
setTimeout(() => {
|
||||
const i = toasts.indexOf(t)
|
||||
if (i >= 0) toasts.splice(i, 1)
|
||||
}, 1800)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 上传(封面 / 编辑器插图共用) ----------
|
||||
// 后台「高级 → 自定义 JS」无关;走 /api/admin/files(FormData)。
|
||||
const uploadingImage = ref(false)
|
||||
|
||||
async function uploadOne(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
// 与后端 allowFileExt / 50MB 上限一致:上传前本地校验,省一趟白跑
|
||||
const ALLOW_UPLOAD_EXT = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif', 'pdf', 'zip', 'txt']
|
||||
const MAX_UPLOAD_MB = 50
|
||||
|
||||
function validateFile(file) {
|
||||
const ext = (file.name.split('.').pop() || '').toLowerCase()
|
||||
if (!ALLOW_UPLOAD_EXT.includes(ext)) {
|
||||
return `不支持的类型 .${ext}(允许:${ALLOW_UPLOAD_EXT.join('/')})`
|
||||
}
|
||||
if (file.size > MAX_UPLOAD_MB * 1024 * 1024) {
|
||||
return `${file.name} 超过 ${MAX_UPLOAD_MB}MB 上限`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
// opts.cmView 传了就把结果以 markdown 图片插到该编辑器光标处(md 页签粘贴/拖拽)
|
||||
async function uploadOne(file, opts = {}) {
|
||||
const bad = validateFile(file)
|
||||
if (bad) {
|
||||
toast(bad, 'err')
|
||||
throw new Error(bad)
|
||||
}
|
||||
const tid = toast(`上传 ${file.name} 0%`, 'info', 60000)
|
||||
try {
|
||||
const data = await adminApi.uploadFiles(fd)
|
||||
const data = await adminApi.uploadFile(file, (p) =>
|
||||
toastUpdate(tid, `上传 ${file.name} ${Math.round(p * 100)}%`)
|
||||
)
|
||||
const f = Array.isArray(data) ? data[0] : null
|
||||
if (!f || !f.url) throw new Error('上传失败')
|
||||
toastDone(tid, `${file.name} 上传完成`)
|
||||
if (opts.cmView) {
|
||||
const v = opts.cmView
|
||||
const pos = v.state.selection.main.from
|
||||
v.dispatch({ changes: { from: pos, insert: `\n` } })
|
||||
}
|
||||
return f.url
|
||||
} catch (e) {
|
||||
toastUpdate(tid, `${file.name} 上传失败:${e.message || '未知错误'}`, 'err')
|
||||
error.value = e.message || '上传失败'
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 外链图片转存 ----------
|
||||
// xLog 的 Cloud:正文里的外链 <img> 一键抓回自己的存储(后端走 SSRF
|
||||
// 防护拨号 + 同一套白名单/去重),成功后原地替换 markdown 里的 URL。
|
||||
const importing = ref(false)
|
||||
|
||||
function externalImages(md) {
|
||||
const own = [site.uploads_public_base, location.origin].filter(Boolean)
|
||||
const out = []
|
||||
const re = /!\[[^\]]*\]\((https?:\/\/[^)\s]+)\)/g
|
||||
let m
|
||||
while ((m = re.exec(md))) {
|
||||
const u = m[1]
|
||||
if (!own.some((b) => u.startsWith(b)) && !u.startsWith('/uploads/')) out.push(u)
|
||||
}
|
||||
return [...new Set(out)]
|
||||
}
|
||||
|
||||
async function importExternal() {
|
||||
if (importing.value) return
|
||||
const urls = externalImages(form.content_md)
|
||||
if (!urls.length) {
|
||||
toast('正文里没有外链图片', 'info')
|
||||
return
|
||||
}
|
||||
importing.value = true
|
||||
const tid = toast(`转存外链图片 0/${urls.length}…`, 'info', 120000)
|
||||
try {
|
||||
const data = await adminApi.importFiles(urls)
|
||||
// 后端按原址回:source -> 转存后的文件(同内容去重时可能是已有行)
|
||||
const ok = new Map((data.files || []).map((e) => [e.source, e.file]))
|
||||
const errs = data.errors || {}
|
||||
let done = 0
|
||||
let changed = false
|
||||
form.content_md = form.content_md.replace(
|
||||
/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/g,
|
||||
(whole, alt, u) => {
|
||||
if (!ok.has(u)) return whole
|
||||
done++
|
||||
toastUpdate(tid, `转存外链图片 ${done}/${urls.length}…`)
|
||||
changed = true
|
||||
return `.url})`
|
||||
}
|
||||
)
|
||||
if (changed) syncCM()
|
||||
const fail = Object.keys(errs).length
|
||||
if (fail) {
|
||||
toastUpdate(tid, `转存完成:${done} 成功,${fail} 失败(${Object.values(errs)[0]})`, fail ? 'err' : 'ok')
|
||||
} else {
|
||||
toastDone(tid, `转存完成:${done} 张已入自己的存储`)
|
||||
}
|
||||
} catch (e) {
|
||||
toastUpdate(tid, '转存失败:' + (e.message || ''), 'err')
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const coverInput = ref(null)
|
||||
async function onCoverPick(e) {
|
||||
const file = e.target.files && e.target.files[0]
|
||||
@@ -693,6 +903,14 @@ const tbGroups = computed(() => [
|
||||
<div class="editor-mode">
|
||||
<button :class="{ on: mode === 'wysiwyg' }" @click="switchMode('wysiwyg')">富文本</button>
|
||||
<button :class="{ on: mode === 'md' }" @click="switchMode('md')">Markdown</button>
|
||||
<button
|
||||
class="btn"
|
||||
:disabled="importing"
|
||||
title="把正文里的外链图片抓回自己的存储"
|
||||
@click="importExternal"
|
||||
>
|
||||
{{ importing ? '转存中…' : '⇲ 转存外链图' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -775,16 +993,13 @@ const tbGroups = computed(() => [
|
||||
|
||||
<!-- editor area -->
|
||||
<div v-show="mode === 'wysiwyg'" ref="editorEl"></div>
|
||||
<textarea
|
||||
v-show="mode === 'md'"
|
||||
ref="mdPane"
|
||||
class="md-pane"
|
||||
v-model="form.content_md"
|
||||
placeholder="直接写 Markdown…"
|
||||
aria-label="Markdown 正文"
|
||||
@paste="onMdPaste"
|
||||
@drop="onMdDrop"
|
||||
></textarea>
|
||||
<!-- md 页签:CodeMirror 6(语法高亮/历史/粘贴拖拽上传),markdown 唯一真相源 -->
|
||||
<div v-show="mode === 'md'" ref="mdPane" class="md-pane" aria-label="Markdown 正文"></div>
|
||||
|
||||
<!-- 轻提示栈 -->
|
||||
<div class="toast-stack" aria-live="polite">
|
||||
<div v-for="t in toasts" :key="t.id" class="toast" :class="t.type">{{ t.text }}</div>
|
||||
</div>
|
||||
|
||||
<div class="editor-stats">
|
||||
<span><strong>{{ cjkChars }}</strong> 汉字</span>
|
||||
|
||||
Reference in New Issue
Block a user