编辑器模块(笔记)初版

This commit is contained in:
zhongluofeng committed 2026-09-30 18:12:53 +08:00
1 parent 7e65825d3e
commit ad987111a3
66 files changed
+17470 -283

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
/**
* CM6 编辑器核心:扩展集组装 + 按设置热重配置 + 语言热切换。
*
* # 为什么用 Compartment
*
* 主题、排版、行号、Tab 宽度、Live Preview 开关、语言都必须在**不重建编辑器**的
* 前提下即时生效(项目约定:设置改动立即应用,无保存按钮)。`Compartment` 正是为此
* 而生:用 `reconfigure` 替换其中一组扩展,文档与光标位置完整保留。
*
* # 大文件降级(P1)
*
* 超过「大文件阈值」的文件会关掉 Live Preview、折叠、括号匹配、自动补全 —— 这些都
* 需要遍历语法树或做全量分析,几十万行的日志文件开着它们只会让输入延迟肉眼可见。
* 降级后仍保留高亮与行号:那是用户打开的**理由**(看代码),不该被省掉。
*/
import { Compartment, EditorState, type Extension } from '@codemirror/state'
import {
EditorView,
crosshairCursor,
drawSelection,
dropCursor,
highlightActiveLine,
highlightActiveLineGutter,
highlightSpecialChars,
keymap,
lineNumbers,
rectangularSelection
} from '@codemirror/view'
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands'
import {
bracketMatching,
foldGutter,
foldKeymap,
indentOnInput,
syntaxHighlighting,
defaultHighlightStyle
} from '@codemirror/language'
import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search'
import { notesKeymap } from './keymap'
import { markdownLivePreview } from './markdownLivePreview'
import { editorTypography, resolveEditorTheme } from './themes'
import { wikilinkExtension, type WikilinkHandlers } from './wikilink'
import { type LanguageLoader } from './languages'
/** 语言加载器的形态由 `languages.ts` 定义(这里只做转出,避免两处定义漂移) */
export type { LanguageLoader }
/** 编辑器配置(由模块设置映射而来)。 */
export interface EditorConfig {
/** 是否启用 Live Preview(false = 纯源码 / 代码高亮) */
livePreview: boolean
showLineNumbers: boolean
tabSize: number
fontFamily: string
fontSize: number
lineHeight: number
ligatures: boolean
theme: string
followAppTheme: boolean
/** 应用当前是否为深色(跟随应用时用于取深/浅变体) */
isDark: boolean
/** 语言扩展加载器 */
language: LanguageLoader
/** 大文件降级(关闭重扩展) */
largeFile: boolean
/** 是否启用自动补全 / 括号闭合 */
autocomplete: boolean
/** 是否识别 `[[wikilink]]`(点击跳转;关闭则只当普通文本) */
wikilink: boolean
/** wikilink 点击回调(`wikilink` 为真时必需) */
onWikilink?: WikilinkHandlers['onOpen']
/**
* 当前文档的库内相对路径(空串 = 库外文件)。
*
* Live Preview 的图片预览需要它来解析「相对当前笔记目录」的图片目标;
* 库外文件不做图片预览(没有库根上下文,路径语义不同)。
*/
currentRelPath: string
/** 是否启用图片内联预览 */
images: boolean
}
const themeCompartment = new Compartment()
const typographyCompartment = new Compartment()
const modeCompartment = new Compartment()
const lineNumbersCompartment = new Compartment()
const tabSizeCompartment = new Compartment()
const languageCompartment = new Compartment()
const heavyCompartment = new Compartment()
const wikilinkCompartment = new Compartment()
/** 行号 + 活动行行号(开启/关闭由 compartment 控制)。 */
const gutterExtensions: Extension = [lineNumbers(), highlightActiveLineGutter()]
/** 文档/光标之外的静态扩展(一次装配,之后不再变)。 */
const baseExtensions: Extension = [
highlightSpecialChars(),
history(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
highlightActiveLine(),
highlightSelectionMatches(),
rectangularSelection(),
crosshairCursor(),
// 兜底高亮:自建主题自带 HighlightStyle,但 Stream/未知语言可能没有对应标签,
// 这一层保证「总有点颜色」,且在所有主题下都安全
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
EditorView.lineWrapping
]
/** 重扩展(大文件时全部关闭)。 */
function heavyExtensions(config: EditorConfig): Extension {
if (config.largeFile) return []
const parts: Extension[] = [bracketMatching(), foldGutter()]
if (config.autocomplete) parts.push(closeBrackets())
return parts
}
/** 由配置解析出各 compartment 的内容。 */
function compartmentExtensions(config: EditorConfig) {
return {
theme: resolveEditorTheme(config.theme, config.followAppTheme, config.isDark),
typography: editorTypography({
fontFamily: config.fontFamily,
fontSize: config.fontSize,
lineHeight: config.lineHeight,
ligatures: config.ligatures
}),
// Live Preview 只对 Markdown 有意义;大文件一律关闭。
// 传 currentRelPath 是为了图片预览能按「相对当前笔记」解析目标。
mode:
config.livePreview && !config.largeFile
? markdownLivePreview({
currentRelPath: config.currentRelPath,
images: config.images
})
: [],
lineNumbers: config.showLineNumbers ? gutterExtensions : [],
tabSize: EditorState.tabSize.of(config.tabSize),
heavy: heavyExtensions(config),
// wikilink 只对笔记(Markdown)有意义;代码文件里的 `[[x]]` 是数组/属性访问,
// 给它加上点下划线会平白制造噪声
wikilink: config.wikilink
? wikilinkExtension({ onOpen: config.onWikilink ?? (() => undefined) })
: []
}
}
/** 创建编辑器状态。 */
export function createEditorState(options: {
doc: string
config: EditorConfig
onDocChanged: (doc: string) => void
/** 选区/光标变化(状态栏行号、大纲当前项用;可省略) */
onSelectionChanged?: (line: number, column: number) => void
}): EditorState {
const c = compartmentExtensions(options.config)
return EditorState.create({
doc: options.doc,
extensions: [
lineNumbersCompartment.of(c.lineNumbers),
baseExtensions,
tabSizeCompartment.of(c.tabSize),
themeCompartment.of(c.theme),
typographyCompartment.of(c.typography),
modeCompartment.of(c.mode),
languageCompartment.of([]),
heavyCompartment.of(c.heavy),
wikilinkCompartment.of(c.wikilink),
keymap.of([
...notesKeymap,
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...foldKeymap,
indentWithTab
]),
EditorView.updateListener.of(update => {
if (update.docChanged) options.onDocChanged(update.state.doc.toString())
if (update.selectionSet || update.docChanged) {
const head = update.state.selection.main.head
const line = update.state.doc.lineAt(head)
options.onSelectionChanged?.(line.number, head - line.from + 1)
}
})
]
})
}
/** 按新配置热重配置(不重建编辑器,不丢文档与光标)。 */
export function reconfigureEditor(view: EditorView, config: EditorConfig): void {
const c = compartmentExtensions(config)
view.dispatch({
effects: [
themeCompartment.reconfigure(c.theme),
typographyCompartment.reconfigure(c.typography),
modeCompartment.reconfigure(c.mode),
lineNumbersCompartment.reconfigure(c.lineNumbers),
tabSizeCompartment.reconfigure(c.tabSize),
heavyCompartment.reconfigure(c.heavy),
wikilinkCompartment.reconfigure(c.wikilink)
]
})
}
/**
* 热切换语言(异步加载完成后调用)。
*
* 语言包是按需 `import()` 的,因此这里是「先设空、加载完再设」的两步;调用方
* (`EditorHost`)用一个自增令牌丢弃过期结果,避免快速切换文件时旧语言覆盖新语言。
*/
export function setLanguageExtension(view: EditorView, extension: Extension | null): void {
view.dispatch({
effects: languageCompartment.reconfigure(extension ?? [])
})
}
/** 用新文档整体替换(切换笔记 / 打开文件时)。 */
export function replaceDoc(view: EditorView, doc: string): void {
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: doc },
selection: { anchor: 0 },
scrollIntoView: true
})
}
/**
* 把光标移到某个字符偏移并滚动到可见位置(大纲点击跳转用)。
*
* 越界偏移一律夹到文档范围内:大纲是基于**刚提取时**的内容算出来的,而用户可能
* 在此之后又编辑过(行变短、标题被删)。夹取比抛异常更合适 —— 跳到一个近似位置,
* 好过整个面板报错。
*/
export function jumpToPosition(view: EditorView, position: number): void {
const max = view.state.doc.length
const anchor = Math.max(0, Math.min(position, max))
view.dispatch({
selection: { anchor },
scrollIntoView: true
})
view.focus()
}
+106
View File
@@ -0,0 +1,106 @@
/**
* 图片内联预览(Live Preview 的一部分)。
*
* # 为什么单独一个文件
*
* 图片预览需要**异步 IO**(把库内图片读成 data URL),而 `markdownLivePreview.ts`
* 是一个纯同步的装饰构建器。把异步塞进去会让那个文件的每次选区变化都背上
* 「可能触发磁盘读取」的心智负担;独立出来后:
* - 本文件负责「解析图片目标 → 取字节(带缓存)→ 通知编辑器重建装饰」;
* - Live Preview 只问一句「这个目标当前有没有可用的 data URL」。
*
* # 缓存与失效
*
* 同一个图片在视口里可能被引用多次、重建装饰也会反复问同一个目标,因此必须缓存。
* 缓存键是**库内相对路径**,值为 `data URL | null`(`null` 表示「读过但不可预览」,
* 例如非图片或超过大小上限 —— 缓存它同样重要,否则每次重建都会白读一次磁盘)。
*
* 缓存不主动失效:用户替换了同名图片的场景很罕见,而「每 3 秒清一次缓存」会让
* 滚动长文档时反复读盘。切库时由 `resetImageCache()` 清空。
*/
import { notesClient } from '../notesClient'
/** 缓存:库内相对路径 → data URL(`null` = 已确认不可预览) */
const cache = new Map<string, string | null>()
/** 正在读取中的目标(避免同一张图并发读多次) */
const inflight = new Map<string, Promise<string | null>>()
/** 清空缓存(切库 / 重建索引后调用)。 */
export function resetImageCache(): void {
cache.clear()
inflight.clear()
}
/** 已经拿到结果的缓存(同步查询,供装饰构建器使用)。 */
export function cachedImage(relPath: string): string | null | undefined {
return cache.get(relPath)
}
/**
* 解析 Markdown 图片目标为「库内相对路径」。
*
* 规则与 `notes_read_asset` 的安全模型一致:
* - 绝对 URL(`http://` / `https://` / `data:`)→ `null`(外链不内联,交给浏览器);
* - 以 `/` 开头 → 视为**库根相对**路径;
* - 其余 → 相对当前笔记所在目录解析,支持 `./` 与 `../`。
*
* 返回 `null` 表示「这个目标不该内联预览」。
*/
export function resolveImagePath(target: string, currentRelPath: string): string | null {
let raw = target.trim()
if (!raw) return null
// 去掉可选的 title(`path "标题"` 或 `path '标题'`)
raw = raw.split(/\s+["']/)[0] ?? raw
// 去掉锚点与查询串(本地图片用不上)
raw = (raw.split('#')[0] ?? '').split('?')[0] ?? ''
if (!raw) return null
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return null // 绝对 URL / data:
const normalized = raw.replace(/\\/g, '/')
if (normalized.startsWith('/')) {
return normalized.replace(/^\/+/, '')
}
const base = currentRelPath.split('/').slice(0, -1)
const parts = [...base]
for (const segment of normalized.split('/')) {
if (!segment || segment === '.') continue
if (segment === '..') {
parts.pop()
continue
}
parts.push(segment)
}
return parts.join('/')
}
/**
* 预取一个图片(幂等)。
*
* 返回 data URL 或 `null`。调用方拿到新结果后应触发一次编辑器重建
* (Live Preview 会在重建时读到新缓存)。
*/
export async function fetchImage(relPath: string): Promise<string | null> {
const cached = cache.get(relPath)
if (cached !== undefined) return cached
const pending = inflight.get(relPath)
if (pending) return pending
const task = notesClient
.readAsset(relPath)
.then(value => {
cache.set(relPath, value)
return value
})
.catch(() => {
// 读取失败(权限、目录穿越被拒)也缓存成 null:不预览,但不反复重试
cache.set(relPath, null)
return null
})
.finally(() => {
inflight.delete(relPath)
})
inflight.set(relPath, task)
return task
}
+142
View File
@@ -0,0 +1,142 @@
/**
* 编辑器格式化命令与快捷键(Live Preview / 源码两种模式通用)。
*
* 命令都通过 `state.changeByRange` 表达,保证多光标下每个选区都被正确处理。
*/
import { EditorSelection, type EditorState } from '@codemirror/state'
import { type Command, type KeyBinding } from '@codemirror/view'
/** 用标记包裹选区;若选区两侧已是该标记,则取消包裹(可反复切换)。 */
function wrapSelection(before: string, after: string = before): Command {
return view => {
view.dispatch(
view.state.changeByRange(range => {
const text = view.state.sliceDoc(range.from, range.to)
const outerFrom = range.from - before.length
const outerTo = range.to + after.length
// 已包裹 → 取消
if (
outerFrom >= 0 &&
outerTo <= view.state.doc.length &&
view.state.sliceDoc(outerFrom, range.from) === before &&
view.state.sliceDoc(range.to, outerTo) === after
) {
return {
changes: [
{ from: outerFrom, to: range.from, insert: '' },
{ from: range.to, to: outerTo, insert: '' }
],
range: EditorSelection.range(outerFrom, outerFrom + text.length)
}
}
const insert = before + text + after
return {
changes: { from: range.from, to: range.to, insert },
range: EditorSelection.range(
range.from + before.length,
range.from + before.length + text.length
)
}
})
)
return true
}
}
/** 设置/取消标题层级(作用于主选区所在行)。 */
function setHeading(level: number): Command {
return view => {
const { state } = view
const pos = state.selection.main.head
const line = state.doc.lineAt(pos)
const match = /^(#{1,6})\s+/.exec(line.text)
const existing = match ? match[1].length : 0
const removeLen = match ? match[0].length : 0
const prefix = existing === level ? '' : `${'#'.repeat(level)} `
view.dispatch({
changes: { from: line.from, to: line.from + removeLen, insert: prefix },
selection: { anchor: line.from + prefix.length + Math.max(0, pos - line.from - removeLen) }
})
return true
}
}
/** 行首前缀开关(引用 / 列表)。 */
function toggleLinePrefix(prefix: string): Command {
return view => {
const { state } = view
const pos = state.selection.main.head
const line = state.doc.lineAt(pos)
if (line.text.startsWith(prefix)) {
view.dispatch({ changes: { from: line.from, to: line.from + prefix.length, insert: '' } })
} else {
view.dispatch({ changes: { from: line.from, insert: prefix } })
}
return true
}
}
/** 插入链接:`[文字](url)`,并选中 `url` 占位便于直接替换。 */
const insertLink: Command = view => {
const { state } = view
const range = state.selection.main
const text = state.sliceDoc(range.from, range.to) || '链接文字'
const insert = `[${text}](url)`
const urlFrom = range.from + text.length + 3
view.dispatch({
changes: { from: range.from, to: range.to, insert },
selection: EditorSelection.range(urlFrom, urlFrom + 3)
})
return true
}
/** 代码块:包围选区,或新起一个空代码块。 */
const insertCodeBlock: Command = view => {
const { state } = view
const range = state.selection.main
const text = state.sliceDoc(range.from, range.to)
const insert = `\`\`\`\n${text}\n\`\`\``
view.dispatch({
changes: { from: range.from, to: range.to, insert },
selection: EditorSelection.cursor(range.from + 4 + text.length)
})
return true
}
/** 编辑器快捷键(优先级高于全局快捷键)。 */
export const notesKeymap: KeyBinding[] = [
{ key: 'Mod-b', run: wrapSelection('**'), preventDefault: true },
{ key: 'Mod-i', run: wrapSelection('*'), preventDefault: true },
{ key: 'Mod-Shift-x', run: wrapSelection('~~'), preventDefault: true },
{ key: 'Mod-e', run: wrapSelection('`'), preventDefault: true },
{ key: 'Mod-k', run: insertLink, preventDefault: true },
{ key: 'Mod-Shift-c', run: insertCodeBlock, preventDefault: true },
{ key: 'Mod-1', run: setHeading(1), preventDefault: true },
{ key: 'Mod-2', run: setHeading(2), preventDefault: true },
{ key: 'Mod-3', run: setHeading(3), preventDefault: true },
{ key: 'Mod-Shift-8', run: toggleLinePrefix('- '), preventDefault: true },
{ key: 'Mod-Shift-9', run: toggleLinePrefix('- [ ] '), preventDefault: true },
{ key: 'Mod-Shift-.', run: toggleLinePrefix('> '), preventDefault: true }
]
/** 供工具栏按钮调用的命令集合。 */
export const notesCommands = {
bold: wrapSelection('**'),
italic: wrapSelection('*'),
strikethrough: wrapSelection('~~'),
inlineCode: wrapSelection('`'),
link: insertLink,
codeBlock: insertCodeBlock,
heading: setHeading,
bulletList: toggleLinePrefix('- '),
taskList: toggleLinePrefix('- [ ] '),
quote: toggleLinePrefix('> ')
}
/** 判断某一行是否以给定前缀开头(工具栏高亮态用)。 */
export function lineHasPrefix(state: EditorState, prefix: string): boolean {
const line = state.doc.lineAt(state.selection.main.head)
return line.text.startsWith(prefix)
}
+175
View File
@@ -0,0 +1,175 @@
/**
* 语言支持:扩展名 → CM6 语言扩展,**按需动态加载**。
*
* # 为什么必须懒加载
*
* `@codemirror/language-data` 的便利之处是「一个入口拿到所有语言」,代价是把
* 30 多个语言包全挂在依赖图上。若静态 `import`,Vite 会把它们塞进主 chunk ——
* 本项目首屏还要承载模块系统、终端、音乐等一堆东西,没有余量给「可能永远用不到
* 的 .cpp 语法」。这里手写一张显式映射表,每个语言一个 `import()`,Vite 自动切成
* 独立 chunk:用户打开 `.rs` 才下载 rust 的解析器(约 10~30 kB)。
*
* # 为什么不用 languageData 的 `LanguageDescription.matchFilename`
*
* 那个 API 是给「Markdown 内嵌代码块」用的,它按 name/alias 匹配,覆盖不到
* `.vue`、`.toml`、`.ps1` 这类扩展名(以及一大批我们想要的别名)。手写表虽然
* 啰嗦,但**行为完全可预期**:前端没有「这个扩展名到底映射到哪个语言」的推理,
* 只有一张查表。
*
* # 围栏代码块的内嵌高亮(P2)
*
* Markdown 里 ```rust 这类代码块本可由 `codeLanguages: languages` 内嵌高亮,
* 但 language-data 的清单需要异步加载,而 `markdown()` 是同步构建设置的。
* P1 先不做:没有内嵌高亮只是「代码块内是单色」,而异步清单会引入一次
* 「打开笔记 → 重配置编辑器」的抖动,得不偿失。
*
* # 未内置的语言
*
* 表格之外的一律退回纯文本(不加载任何扩展)。三类常见的缺口及理由:
* - `.scss` / `.less`:`@codemirror/lang-css` 只导出 `css()`,SCSS/Less 需要
* `@codemirror/lang-sass`(更重且语法覆盖不全)。CSS 变量为主的样式表用
* `css()` 就够,因此不引入;
* - `.sh` / `.ps1` / `.toml` / `.ini`:本来可以经 `@codemirror/legacy-modes` 的
* 流式解析补上,但那需要另一套高亮标签(Stream Language 的 token 名与 Lezer
* 高亮标签并非一一对应),P1 先不做;
* - 其余未知扩展名:纯文本。
*
* 统一原则:宁可「没高亮但能正常编辑」,也不要「高亮错乱」。
*/
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
import { GFM } from '@lezer/markdown'
import { type Extension } from '@codemirror/state'
/**
* 语言加载器:返回扩展(可同步、可异步)。
*
* **允许返回 `null`**:表示「这个文件没有内置语言」。用 `null` 而不是空数组表达
* 「本来就没有」,是为了让调用方(`EditorHost`)能在日志里区分「没有语言」与
* 「有语言但被卸下」;两者在 CM6 的 Compartment 里行为相同,但语义不同。
*/
export type LanguageLoader = () => Extension | null | Promise<Extension | null>
interface LanguageEntry {
/** 状态栏展示名 */
label: string
load: LanguageLoader
}
/**
* 扩展名(小写,不含点)→ 语言。
*
* 值写成 thunk 而不是已加载的扩展:`import()` 只在真正调用时执行,
* 表本身的构建不产生任何网络/打包开销。
*/
const LOADERS: Record<string, LanguageEntry> = {
// ===== 前端 =====
js: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
mjs: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
cjs: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
jsx: { label: 'JSX', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ jsx: true })) },
ts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
mts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
cts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
tsx: {
label: 'TSX',
load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true, jsx: true }))
},
vue: { label: 'Vue', load: () => import('@codemirror/lang-vue').then(m => m.vue()) },
html: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
htm: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
css: { label: 'CSS', load: () => import('@codemirror/lang-css').then(m => m.css()) },
// ===== 数据与配置 =====
json: { label: 'JSON', load: () => import('@codemirror/lang-json').then(m => m.json()) },
jsonc: { label: 'JSON', load: () => import('@codemirror/lang-json').then(m => m.json()) },
yaml: { label: 'YAML', load: () => import('@codemirror/lang-yaml').then(m => m.yaml()) },
yml: { label: 'YAML', load: () => import('@codemirror/lang-yaml').then(m => m.yaml()) },
xml: { label: 'XML', load: () => import('@codemirror/lang-xml').then(m => m.xml()) },
svg: { label: 'SVG', load: () => import('@codemirror/lang-xml').then(m => m.xml()) },
sql: { label: 'SQL', load: () => import('@codemirror/lang-sql').then(m => m.sql()) },
// ===== 后端与系统 =====
py: { label: 'Python', load: () => import('@codemirror/lang-python').then(m => m.python()) },
pyw: { label: 'Python', load: () => import('@codemirror/lang-python').then(m => m.python()) },
rs: { label: 'Rust', load: () => import('@codemirror/lang-rust').then(m => m.rust()) },
go: { label: 'Go', load: () => import('@codemirror/lang-go').then(m => m.go()) },
java: { label: 'Java', load: () => import('@codemirror/lang-java').then(m => m.java()) },
c: { label: 'C', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
h: { label: 'C/C++ Header', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
cc: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
cpp: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
cxx: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
hpp: { label: 'C++ Header', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) }
}
/** 语言缓存:同一个语言只解析一次,之后复用已加载的扩展。 */
const cache = new Map<string, Promise<Extension | null>>()
/** 从文件名取扩展名(小写、不含点;无扩展名返回空串)。 */
export function extensionOf(fileName: string): string {
const base = fileName.split(/[\\/]/).pop() ?? ''
const dot = base.lastIndexOf('.')
if (dot <= 0 || dot === base.length - 1) return ''
return base.slice(dot + 1).toLowerCase()
}
/** 该文件名是否有内置语言支持。 */
export function hasLanguage(fileName: string): boolean {
return !!LOADERS[extensionOf(fileName)]
}
/** 文件名对应的语言展示信息(无支持时返回「纯文本」)。 */
export function languageLabel(fileName: string): string {
return LOADERS[extensionOf(fileName)]?.label ?? '纯文本'
}
/**
* 解析文件名对应的语言扩展。
*
* 返回 `null` 表示「没有内置语言」——调用方据此保持纯文本,而不是传空数组:
* 空数组与 `null` 在 Compartment 里语义相同,但 `null` 表达的是「本来就没有」,
* 而 `[]` 表达的是「有语言但选了无」,两者的日志与调试含义不同。
*/
export async function loadLanguage(fileName: string): Promise<Extension | null> {
const ext = extensionOf(fileName)
const entry = LOADERS[ext]
if (!entry) return null
const cached = cache.get(ext)
if (cached) return cached
const pending = Promise.resolve(entry.load()).catch(error => {
// 加载失败(离线 / chunk 404)时**不要**把失败的 promise 留在缓存里:
// 用户重连后再打开同一类型文件应当能成功
cache.delete(ext)
throw error
})
cache.set(ext, pending)
return pending
}
/**
* 笔记(Markdown)模式的语言扩展。
*
* # 为什么显式加 GFM 扩展
*
* `markdown()` 默认只用**基础 CommonMark** 语法:表格(`| a | b |`)、任务列表
* (`- [ ]`)、删除线(`~~x~~`)都不会被解析成对应节点,于是
* - Live Preview 拿不到 `Table` / `TaskMarker` 节点,表格与复选框渲染不出来;
* - 大纲提取虽然是自己扫文本(不依赖语法树),但**编辑器内的**高亮与折叠也会缺一块。
*
* `@lezer/markdown` 导出 `GFM`(= Table + TaskList + Strikethrough + Autolink 的扩展包),
* 交给 `extensions` 即可。注意它只影响**解析**,不改变渲染 —— 渲染仍由
* `markdownLivePreview.ts` 的装饰负责。
*
* 与代码文件走同一条 `loadLanguage` 通道(`md` → Markdown),因此笔记与代码
* 在「语言如何装配」上没有第二条路径。
*/
export function markdownLoader(): LanguageLoader {
return () =>
markdown({
base: markdownLanguage,
extensions: GFM
})
}
@@ -0,0 +1,296 @@
/**
* markdownExport 单测(Node 内置 test runner)。
*
* # 为什么用 `renderMarkdownFragmentRaw`
*
* DOMPurify 需要 `window`/`document`:Node 里 `isSupported === false` 且对象上**根本
* 没有** `sanitize`,所以「消毒后的片段」在纯 Node 下无法断言(本文件里如实
* `t.skip()`,不装 jsdom、更不为跑通测试降低消毒强度)。
* 但「fence 语言识别、任务列表、表格、链接、图片」这些**渲染**行为是纯字符串逻辑,
* 必须能脱离浏览器回归,所以走模块里明确标注为「仅供单测」的未消毒入口。
*
* # 为什么两个方向都断言
*
* 一边断言「未消毒的片段里确实带着 `onerror=` / `<script>`」(证明消毒不是可选项),
* 一边断言「无 DOM 时消毒入口失败关闭,返回空串而不是原文」(证明降级方向是安全的那
* 一侧)。有 DOM 的环境(浏览器/未来的 DOM shim)会自动改跑真正的消毒断言。
*/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import DOMPurify from 'dompurify'
import {
markdownToPlainText,
renderMarkdownFragment,
renderMarkdownFragmentRaw,
renderNoteHtml,
stripFrontMatter
} from './markdownExport.ts'
/** 当前环境能不能真消毒(浏览器/happy-dom 之类为 true,纯 Node 为 false) */
const domAvailable = DOMPurify.isSupported && typeof DOMPurify.sanitize === 'function'
// ===== front-matter =====
test('stripFrontMatter:剥掉闭合的 front-matter', () => {
const src = ['---', 'title: 周报', 'tags:', ' - 工作', '---', '# 正文', '', '内容'].join('\n')
assert.equal(stripFrontMatter(src), '# 正文\n\n内容')
})
test('stripFrontMatter:闭合行是末行(末尾没有换行)也能处理', () => {
assert.equal(stripFrontMatter('---\ntitle: x\n---'), '')
assert.equal(stripFrontMatter('---\ntitle: x\n---\n正文'), '正文')
})
test('stripFrontMatter:未闭合时整篇当正文,一个字符都不吃', () => {
const unclosed = '---\ntitle: x\n# 正文\n--- 少了点什么'
assert.equal(stripFrontMatter(unclosed), unclosed)
// 只有一行 `---` 时同样不认
assert.equal(stripFrontMatter('---'), '---')
})
test('stripFrontMatter:CRLF 与 UTF-8 BOM', () => {
assert.equal(stripFrontMatter('---\r\ntitle: x\r\n---\r\n正文\r\n'), '正文\r\n')
assert.equal(stripFrontMatter('\uFEFF---\r\ntitle: x\r\n---\r\n正文'), '正文')
// 没有 front-matter 时也要剥 BOM:留着它 markdown-it 会渲染成不可见怪字符
assert.equal(stripFrontMatter('\uFEFF# 正文'), '# 正文')
})
test('stripFrontMatter:第一行不是整行 --- 时不认', () => {
assert.equal(stripFrontMatter('--- x\na: 1\n---\n正文'), '--- x\na: 1\n---\n正文')
assert.equal(stripFrontMatter(' ---\na: 1\n---\n正文'), ' ---\na: 1\n---\n正文')
})
test('stripFrontMatter:只剥第一段,正文里的 --- 原样保留', () => {
assert.equal(stripFrontMatter('---\na: 1\n---\n正文\n---\n更多'), '正文\n---\n更多')
})
// ===== 纯文本摘要 =====
test('markdownToPlainText:去掉标记、保留文字、折叠空白', () => {
const src = [
'---',
'title: 元数据不该出现',
'---',
'# 标题一',
'',
'这是 **粗体**、*斜体*、`行内代码`,还有 [链接文字](https://example.com/a) 和 ![图片说明](images/x.png)。',
'',
'> 引用行',
'',
'- [ ] 待办',
'- 普通项',
'',
'```js',
'const a = 1',
'```',
'',
'<p>html 段落</p>'
].join('\n')
const text = markdownToPlainText(src)
assert.ok(!text.includes('元数据不该出现'), 'front-matter 必须被剥掉')
for (const kept of ['标题一', '粗体', '斜体', '行内代码', '链接文字', '图片说明', '引用行', '待办', '普通项', 'const a = 1', 'html 段落']) {
assert.ok(text.includes(kept), `摘要应保留「${kept}」:${text}`)
}
for (const dropped of ['**', '`', '](', 'https://example.com', 'images/x.png', '<p>', '#', '>']) {
assert.ok(!text.includes(dropped), `摘要不该残留「${dropped}」:${text}`)
}
assert.ok(!/ {2}/.test(text), `空白应折叠成单空格:${text}`)
})
test('markdownToPlainText:默认 120 字符截断并加省略号', () => {
const text = markdownToPlainText(`# ${'x'.repeat(200)}`)
assert.equal(text.length, 121)
assert.ok(text.endsWith('…'))
assert.equal(text, `${'x'.repeat(120)}…`)
})
test('markdownToPlainText:按码点截断,emoji 不会被劈成半个', () => {
const text = markdownToPlainText('😀'.repeat(10), 3)
assert.equal(text, '😀😀😀…')
assert.equal(Array.from(text).length, 4)
})
test('markdownToPlainText:maxChars 为 0 时返回空串', () => {
assert.equal(markdownToPlainText('随便什么内容', 0), '')
})
test('markdownToPlainText:#tag 不算标题,分隔线要清干净', () => {
// 与 outline.ts 同一套判断:`#` 后必须有空白才算 ATX 标题
assert.equal(markdownToPlainText('#hashtag 不是标题'), '#hashtag 不是标题')
assert.equal(markdownToPlainText('* * *\n\n正文'), '正文')
assert.equal(markdownToPlainText('***'), '')
assert.equal(markdownToPlainText('标题\n==='), '标题')
// 表格:对齐分隔行是纯标记,要丢;单元格文字留着
const table = markdownToPlainText('| 模块 | 状态 |\n| --- | --- |\n| 导出 | 完成 |')
assert.ok(!table.includes('---'), table)
assert.ok(table.includes('模块'), table)
assert.ok(table.includes('导出'), table)
})
// ===== 渲染(未消毒片段)=====
test('围栏代码块:info string 命中注册表时按该语言高亮', () => {
const html = renderMarkdownFragmentRaw('```ts\nconst n: number = 1\n```')
assert.match(html, /<pre class="hljs">/)
assert.match(html, /<code class="hljs language-ts">/)
assert.match(html, /hljs-keyword/)
})
test('围栏代码块:`.js` 这类写法也能归一成语言名', () => {
const html = renderMarkdownFragmentRaw('```.js\nlet a = 1\n```')
assert.match(html, /<code class="hljs language-js">/)
})
test('围栏代码块:未注册的语言不抛错,猜不准的散文保持纯文本', () => {
const html = renderMarkdownFragmentRaw('```notalang\nplain text here\n```')
assert.match(html, /<pre class="hljs">/)
assert.match(html, /plain text here/)
// 相关度低于下限时不许上色:给散文瞎上色比没颜色更糟
assert.match(html, /<code class="hljs">/)
assert.doesNotMatch(html, /language-notalang/)
})
test('围栏代码块:语言名拼错时在候选集里自动识别', () => {
const html = renderMarkdownFragmentRaw('```typescrpt\ndef f(x):\n return x + 1\n```')
assert.match(html, /<code class="hljs language-python">/)
assert.match(html, /hljs-keyword/)
})
test('围栏代码块:内容被转义,原始 HTML 不会漏出去', () => {
const html = renderMarkdownFragmentRaw('```\n<b>&"x\n```')
assert.match(html, /&lt;b&gt;&amp;&quot;x/)
assert.doesNotMatch(html, /<b>/)
})
test('表格渲染', () => {
const html = renderMarkdownFragmentRaw('| 列 A | 列 B |\n| --- | --- |\n| 1 | 2 |')
assert.match(html, /<table>/)
assert.match(html, /<th>列 A<\/th>/)
assert.match(html, /<td>2<\/td>/)
})
test('任务列表渲染成 disabled 复选框', () => {
const html = renderMarkdownFragmentRaw('- [ ] 未完成\n- [x] 已完成\n- 普通项')
assert.match(html, /<input class="task-list-item-checkbox" type="checkbox" disabled>/)
assert.match(html, /type="checkbox" disabled checked>/)
assert.match(html, /class="task-list-item"/)
assert.match(html, /普通项/)
})
test('链接渲染与裸 URL 自动识别', () => {
const html = renderMarkdownFragmentRaw('[Thing](https://example.com/a) 与 https://example.org/b')
assert.match(html, /<a href="https:\/\/example\.com\/a">Thing<\/a>/)
assert.match(html, /href="https:\/\/example\.org\/b"/)
})
test('图片渲染(保留相对路径与 alt)', () => {
const html = renderMarkdownFragmentRaw('![示意图](images/demo.png)')
assert.match(html, /<img src="images\/demo\.png" alt="示意图">/)
})
test('未消毒片段确实会带出 XSS 载荷(说明消毒不是可选项)', () => {
const raw = renderMarkdownFragmentRaw('<img src=x onerror=alert(1)>\n\n<script>alert(1)</script>')
assert.match(raw, /onerror=/)
assert.match(raw, /<script>/)
})
// ===== 消毒 =====
test('无 DOM 环境:消毒入口失败关闭,返回空串而不是原文', t => {
if (domAvailable) {
t.skip('本环境有 DOM,消毒可用,该降级分支不适用')
return
}
assert.equal(renderMarkdownFragment('<script>alert(1)</script>'), '')
assert.equal(renderMarkdownFragment('# 正常标题'), '')
})
test('XSS:<script>、onerror、javascript: 被剥掉,该留的留着', t => {
if (!domAvailable) {
t.skip('Node 无 window/document:DOMPurify.isSupported=false,无 sanitize 可调')
return
}
const dirty = [
'<script>alert(1)</script>',
'',
'<img src=x onerror=alert(1)>',
'',
'[点我](javascript:alert(1))',
'',
'<span style="position:fixed;top:0">覆盖界面</span>',
'',
'<img src="a.png" srcset="https://evil.example/x.png 1x">',
'',
'<style>body{display:none}</style>'
].join('\n')
const html = renderMarkdownFragment(dirty)
assert.ok(!html.includes('onerror='), html)
assert.ok(!html.includes('<script'), html)
assert.ok(!html.includes('javascript:'), html)
assert.ok(!html.includes('style='), html)
assert.ok(!html.includes('srcset='), html)
assert.ok(!html.includes('<style'), html)
const kept = renderMarkdownFragment(
'```ts\nconst a = 1\n```\n\n| a |\n| --- |\n| 1 |\n\n- [x] 完成\n\n![图](a.png)\n\n<a href="https://example.com" target="_blank">外链</a>'
)
assert.match(kept, /class="hljs"/)
assert.match(kept, /<table>/)
assert.match(kept, /type="checkbox" disabled checked/)
assert.match(kept, /<img src="a\.png"/)
assert.match(kept, /target="_blank"/)
})
// ===== 导出文档 =====
test('renderNoteHtml:结构完整、<title> 与页首标题都转义', () => {
const html = renderNoteHtml({
title: 'A & B <C>',
fileName: 'a.md',
markdown: '# 正文',
exportedAt: new Date(2026, 0, 2, 3, 4)
})
assert.ok(html.startsWith('<!doctype html>'))
assert.ok(html.includes('<html lang="zh-CN">'))
assert.ok(html.includes('<meta charset="utf-8">'))
assert.ok(html.includes('name="viewport"'))
assert.ok(html.includes('<title>A &amp; B &lt;C&gt;</title>'))
assert.ok(html.includes('<h1 class="note-title">A &amp; B &lt;C&gt;</h1>'))
assert.ok(html.includes('导出自 Thing · 2026-01-02 03:04'))
assert.ok(html.includes('@media print'))
})
test('renderNoteHtml:内联样式自带排版与高亮配色,不依赖外部资源', () => {
const html = renderNoteHtml({ title: '排版', fileName: 'style.md', markdown: '正文' })
assert.ok(html.includes('780px'))
assert.ok(html.includes('line-height: 1.7'))
assert.ok(html.includes('overflow-x: auto'))
assert.ok(html.includes('background: #f6f8fa'))
assert.ok(html.includes('border-collapse: collapse'))
assert.ok(html.includes('border-left: 4px solid'))
assert.ok(html.includes('img { max-width: 100%'))
assert.ok(html.includes('.note-body mark'))
for (const token of ['hljs-keyword', 'hljs-string', 'hljs-comment', 'hljs-number', 'hljs-title', 'hljs-attr']) {
assert.ok(html.includes(`.${token}`), `缺少高亮配色 ${token}`)
}
})
test('renderNoteHtml:样式与外壳里没有任何外部地址', () => {
const html = renderNoteHtml({
title: '离线笔记',
fileName: 'offline.md',
markdown: '# 标题\n\n纯文本,没有任何链接。'
})
const style = /<style>([\s\S]*?)<\/style>/.exec(html)?.[1] ?? ''
assert.ok(style.length > 0)
assert.ok(!/https?:\/\//.test(style), '内联样式里不能出现外链')
assert.ok(!/https?:\/\//.test(html), '正文没有链接时整份文档都不该有外链')
assert.ok(!/<link|<script|@import/i.test(html))
})
test('renderNoteHtml:标题为空串时用 fileName 兜底,时间缺省用当前时间', () => {
const html = renderNoteHtml({ title: ' ', fileName: '周报.md', markdown: '正文' })
assert.ok(html.includes('<title>周报.md</title>'))
assert.ok(html.includes('<h1 class="note-title">周报.md</h1>'))
assert.match(html, /导出自 Thing · \d{4}-\d{2}-\d{2} \d{2}:\d{2}/)
})
+550
View File
@@ -0,0 +1,550 @@
/**
* 笔记导出 —— 把 Markdown 渲染成「能双击打开、能直接打印」的独立 HTML 文档。
*
* # 为什么产出一整份单文件 HTML
*
* 导出物必须能脱离本应用存在:发给别人、丢进归档、直接 Ctrl+P。所以这里吐出的是
* 完整的 `<!doctype html>`,样式内联、**零外部请求**(无 CDN、无外链字体/CSS/JS)
* —— 离线、换机器、几年后再打开都得是同一个样子。反过来这也意味着不能引用
* `highlight.js/styles/*.css` 这类现成主题:它们会变成一个 `<link>`,文件一挪窝就
* 掉样式。高亮配色改成在 [`EXPORT_STYLE`] 里内联一份最小 token 表。
*
* # 安全:这条链路的头号风险是 XSS
*
* 正文是用户内容,还可能来自别人的笔记库(导入/同步)。`markdown-it` 开了
* `html: true`(笔记里嵌原生 HTML 很常见,刻意放行),所以渲染出的片段**必然**能
* 包含 `<script>` / `onerror=` / `javascript:`。唯一出口是 `DOMPurify.sanitize()`:
* 对外函数只返回消毒后的字符串;模块里唯一的「原始片段」函数
* [`renderMarkdownFragmentRaw`] 明确标注为仅供单测,生产代码不要用。
*
* 消毒配置([`SANITIZE_CONFIG`])的取舍:
* - **走 DOMPurify 默认 HTML 白名单,只做减法加两个属性**。默认白名单已经精确覆盖
* 要保留的东西:`pre`/`code`(`class` 在默认属性表里,`hljs` token 靠它活下来)、
* `table` 全家族、`img`(相对路径天然合法,`javascript:` 会被 URI 校验拦下)、
* `input`(`type` / `disabled` / `checked` 都在默认属性表里,任务列表靠它)。
* `on*` 事件属性不在白名单里,天然被剥 —— 这比自己手写一份 `ALLOWED_TAGS` 再漏一个
* 标签安全得多,白名单越小越好维护。
* - `FORBID_TAGS: ['style']`:DOMPurify **不解析 CSS**(官方文档明确说明)。`<style>`
* 能重排/遮挡宿主界面(预览场景就在应用里渲染),必须拿掉。`script` 本来就在默认
* `FORBID_CONTENTS` 里,元素**连内容**一起丢,不会留下 `alert(1)` 这种残渣文本。
* - `FORBID_ATTR: ['style', 'srcset']`:内联 `style` 里的 `url()` 会拉外部资源,与本模块
* 「导出文件零外链」的承诺直接冲突,`position:fixed` 之类还能盖住界面。`srcset` 同理是
* 一条静默的外链通道(默认白名单里有它,而 markdown-it 永远生成不出来)。笔记里的格式
* 用 Markdown 表达足够,这点保真度不值得换两个风险。
* - `ADD_ATTR: ['target', 'rel']`:实测默认属性表里**没有** `target`(`rel` 有),而导出
* 文档里点开外链应当新标签页打开;这是唯一的「加法」,加的是无脚本能力的属性。
*
* 消毒器不可用时**失败关闭**(fail-closed):DOMPurify 依赖 DOM,Node 里
* `isSupported === false` 且根本没有 `sanitize`(实测 3.4.x:返回的对象上连该方法都
* 不存在)。此时宁可返回空串,也绝不回退成「输出原文」。
*
* # 高亮
*
* `highlight.js` 是**同步** API:`getLanguage()` 查注册表、`highlight()` 出 token、
* 未注册的语言用 `highlightAuto()` 兜底。三点必须注意:
* 1. **不能拿未注册的语言直接撞 `highlight()`** —— 它会抛 `Unknown language`(还顺手
* 打一条 console.error),一抛就把整篇渲染带崩,所以先 `getLanguage()` 过滤。
* 2. 自动识别不能贪心:不限定候选集时 `highlightAuto` 会遍历全量 190+ 语言(实测首轮
* 530ms、之后 ~30ms),答案还离谱(`const a = 1` → abnf)。所以只在「声明了语言却
* 不在注册表」时用,候选集限定在 [`AUTO_DETECT_SUBSET`],相关度低于
* [`AUTO_DETECT_MIN_RELEVANCE`] 就退回纯文本 —— 宁可没颜色,不要瞎上色。
* 3. 任何一步抛错都退化成「转义后的纯文本」,高亮失败绝不影响正文。
*
* 这里用 `highlight.js` 全量包(190+ 语言,同步可用,任何 info string 都有机会命中)。
* 代价是 NotesWindow chunk 变大:在 Tauri 里它从本地磁盘加载,换「```toml /
* ```powershell / ```diff 也有高亮」是划算的。若哪天 chunk 预算吃紧,换成
* `highlight.js/lib/core` + 精选语言注册即可,其余逻辑一行都不用动。
*
* # 边界与坑
*
* - front-matter 只认「第一行就是整行 `---`」,且必须再找到下一个整行 `---`;未闭合时
* 整篇当正文(绝不能把笔记正文当元数据吃掉)。BOM 一律先剥:它留在正文里会被
* markdown-it 当普通字符渲染出来,变成一个看不见的怪字符。
* - 逐行扫描 + 偏移推进,而不是 `split` 再拼回去:CRLF 的正文必须原样保留。
* - 导出时间手写格式化,不用 `toLocaleString`:输出稳定、可测、不随系统 locale 变样。
* - 不碰 Vue 与 CodeMirror,只依赖 markdown-it / DOMPurify / highlight.js,可以脱离
* 编辑器单测(`markdownExport.test.ts`)。
*/
import MarkdownIt from 'markdown-it'
import type { StateCore } from 'markdown-it'
import DOMPurify from 'dompurify'
import type { Config as DomPurifyConfig } from 'dompurify'
import hljs from 'highlight.js'
/** 单篇笔记导出为 HTML 所需的输入 */
export interface NoteHtmlInput {
/** 笔记标题(用于 <title> 与页首大标题;空串则用 fileName 兜底) */
title: string
/** 文件名(含 .md,作为标题兜底) */
fileName: string
/** Markdown 原文(**含 front-matter**,函数内部负责剥离) */
markdown: string
/** 导出时间(用于页脚;不传则用当前时间) */
exportedAt?: Date
/**
* 是否对围栏代码块做语法高亮(默认 `true`)。
*
* 关掉它的场景是「打印」:黑白打印机上浅色 token 常常淡到看不见,而不上色至少是
* 稳定的黑字。对应设置项 `NoteSettings.exportHighlight`。
*/
highlight?: boolean
}
/** 正文最大宽度(px):A4 打印约 180mm,屏幕上也是舒服的阅读行宽 */
const BODY_MAX_WIDTH = 780
/** 自动识别的相关度下限:低于它说明 highlight.js 只是在瞎猜,不如不上色 */
const AUTO_DETECT_MIN_RELEVANCE = 3
/** 超过这个长度的代码块不做自动识别:长文本上自动识别是性能地雷(哪怕有候选集限制) */
const AUTO_DETECT_MAX_CHARS = 20000
/**
* 未注册语言的自动识别候选集。**必须给候选集**:不给的话 `highlightAuto` 会遍历全量
* 190+ 语言 —— 实测首轮 530ms、之后每次 ~30ms,而且答案离谱(`plain text here` →
* applescript、`const a = 1` → abnf)。限定在常用语言上只要 0.5~15ms,答案也合理得多。
* 名字都是 highlight.js 注册表里的正式名/别名,未注册的名字会被它自己过滤掉。
*/
const AUTO_DETECT_SUBSET = [
'javascript',
'typescript',
'json',
'bash',
'python',
'java',
'c',
'cpp',
'csharp',
'go',
'rust',
'sql',
'yaml',
'xml',
'css',
'markdown',
'diff',
'ini',
'powershell'
]
/** 文本/属性转义表:文本节点用 `&<>`,双引号属性再加 `"` 与 `'` */
const HTML_ESCAPES: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}
/** HTML 文本/属性转义:导出的每个动态值(标题、语言名、时间)都必须过这里 */
function escapeHtml(text: string): string {
return text.replace(/[&<>"']/g, ch => HTML_ESCAPES[ch] ?? ch)
}
/** 纯文本摘要里要还原的常见实体(`&nbsp;` 还原成空格,交给后续空白折叠处理) */
const ENTITY_TEXTS: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
'&nbsp;': ' '
}
/** 行是不是 front-matter 分隔线:整行 `---`(允许行尾空格/制表符,CRLF 的 `\r` 先摘掉) */
function isFrontMatterDelimiter(line: string): boolean {
const withoutCr = line.endsWith('\r') ? line.slice(0, -1) : line
return /^---[ \t]*$/.test(withoutCr)
}
/** 本地时间 `YYYY-MM-DD HH:mm`:手写格式化,避免 `toLocaleString` 随系统 locale 变样 */
function formatLocalTimestamp(date: Date): string {
const pad = (value: number): string => String(value).padStart(2, '0')
const ymd = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
return `${ymd} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}
/**
* 剥掉 YAML front-matter,返回正文(无 front-matter 时原样返回)。
*
* 「原样」的唯一例外是 BOM:UTF-8 BOM 不是正文,留着它 markdown-it 会渲染出一个
* 不可见字符,所以无论有没有 front-matter 都先剥掉。未闭合时**整篇**当正文返回
* (只剥 BOM),绝不为了「看起来像元数据」把正文吃掉。
*/
export function stripFrontMatter(markdown: string): string {
const text = markdown.charCodeAt(0) === 0xfeff ? markdown.slice(1) : markdown
const firstBreak = text.indexOf('\n')
// 连第一行都不是整行 `---`(或整个文件只有一行)→ 不可能有闭合
if (firstBreak === -1 || !isFrontMatterDelimiter(text.slice(0, firstBreak))) return text
// 逐行找闭合的整行 `---`;按偏移推进,正文的 CRLF 才能原样带回
let lineStart = firstBreak + 1
while (lineStart <= text.length) {
const breakAt = text.indexOf('\n', lineStart)
const lineEnd = breakAt === -1 ? text.length : breakAt
if (isFrontMatterDelimiter(text.slice(lineStart, lineEnd))) {
// 闭合行正好是末行(末尾没有换行)时,正文为空
return breakAt === -1 ? '' : text.slice(breakAt + 1)
}
if (breakAt === -1) break
lineStart = breakAt + 1
}
return text
}
/**
* 从 Markdown 原文里提取纯文本摘要(用于列表/搜索展示;折叠空白,最多 maxChars 字符)。
*
* 截断按**码点**算(`Array.from`),不是 UTF-16 长度:不然 emoji 会被劈成半个代理对,
* 摘要末尾显示成一个方块。`maxChars` 之后追加的 `…` 不计入上限,所以结果最长是
* `maxChars + 1` 个字符。
*/
export function markdownToPlainText(markdown: string, maxChars = 120): string {
const limit = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 0
if (limit === 0) return ''
let text = stripFrontMatter(markdown)
// 围栏只去掉标记行,代码内容保留(摘要里代码往往正是要搜的东西)
text = text.replace(/^[ \t]*(?:```|~~~).*$/gm, '')
// 行级标记:引用、标题、分隔线(分隔线必须在列表标记之前处理,否则 `* * *` 会被啃成残渣)、列表
text = text.replace(/^[ \t]*>[ \t]?/gm, '')
text = text.replace(/^[ \t]{0,3}#{1,6}(?:[ \t]+|$)/gm, '')
text = text.replace(/^[ \t]*(?:[-*_=][ \t]*){3,}$/gm, '')
// 表格对齐分隔行(`| --- | --- |`)是纯标记,整行丢掉;单元格的 `|` 保留(shell 管道也是它)
text = text.replace(/^[ \t]*\|[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|[ \t]*$/gm, '')
text = text.replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, '')
// 图片(保留 alt)必须先于链接(保留文字)处理,否则 `![alt](url)` 会被链接规则切碎
text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
text = text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
text = text.replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1')
text = text.replace(/^[ \t]*\[[^\]]+\]:[^\n]*$/gm, '')
// 任务列表标记 `[ ]` / `[x]`
text = text.replace(/\[[ xX]\][ \t]+/g, '')
// 强调:只在成对出现时剥标记,避免把 `snake_case` 里的下划线也吃掉
text = text.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '$2')
text = text.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '$2')
text = text.replace(/(\*|_)(?=\S)([^*_]*?\S)\1/g, '$2')
text = text.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '$1')
text = text.replace(/`+([^`]*)`+/g, '$1')
// 行内 HTML 标签(含注释):整体换成空格,保证 `<p>a</p><p>b</p>` 不会粘成 "ab"
text = text.replace(/<[^>]*>/g, ' ')
text = text.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, entity => ENTITY_TEXTS[entity] ?? entity)
text = text.replace(/\s+/g, ' ').trim()
const chars = Array.from(text)
return chars.length > limit ? `${chars.slice(0, limit).join('')}…` : text
}
/** markdown-it 实例类型:默认导出是可调用的构造器,这里把实例类型取回来给插件签名用 */
type MarkdownItInstance = ReturnType<typeof MarkdownIt>
/**
* 最小 GFM 任务列表支持。
*
* markdown-it 本体不认 `- [ ]`(它只是普通文本),而任务列表是笔记里最常用的语法之一。
* 这里不改源码,而是在 core 规则里把列表项首个子节点从 `[ ] foo` 改写成
* 「disabled 复选框 + foo」的 `html_inline` token —— 生成的 `<input type="checkbox"
* disabled>` 同样要过 DOMPurify 配置(已确认保留),所以就算以后换别的列表解析器,
* 安全边界也不变。复选框一律 `disabled`:导出文档里它只是**状态展示**,可点的复选框
* 会产生「改了但没保存」的错觉。
*/
function taskListPlugin(md: MarkdownItInstance): void {
md.core.ruler.after('inline', 'thing-task-list', (state: StateCore): void => {
const tokens = state.tokens
for (let i = 2; i < tokens.length; i++) {
if (tokens[i].type !== 'inline') continue
// 标准嵌套是 list_item_open → paragraph_open → inline
if (tokens[i - 1].type !== 'paragraph_open' || tokens[i - 2].type !== 'list_item_open') continue
const children = tokens[i].children
if (!children || children.length === 0) continue
const first = children[0]
if (first.type !== 'text') continue
const matched = /^\[([ xX])\][ \t]+/.exec(first.content)
if (!matched) continue
first.content = first.content.slice(matched[0].length)
const checkbox = new state.Token('html_inline', '', 0)
const checked = matched[1] === ' ' ? '' : ' checked'
checkbox.content = `<input class="task-list-item-checkbox" type="checkbox" disabled${checked}> `
children.unshift(checkbox)
tokens[i - 2].attrJoin('class', 'task-list-item')
}
})
}
/**
* 把围栏的 info string 归一成 highlight.js 认的语言名。
*
* markdown-it 传进来的 `lang` 通常已经是第一个词,但仍要容忍 `.js`、`{.py}`、
* `python title="x"` 这些写法:只取第一段、去掉首尾的花括号与点、再截到第一个非语言字符。
*/
function normalizeFenceLanguage(rawLanguage: string): string {
const firstWord = rawLanguage
.trim()
.split(/\s+/)[0]
.replace(/^[.{}]+/, '')
.replace(/[},]+$/, '')
const matched = /^[a-z0-9+#_-]+/i.exec(firstWord)
return matched ? matched[0].toLowerCase() : ''
}
/**
* 把一段代码渲染成 `<pre class="hljs"><code>…</code></pre>`。
*
* 返回值以 `<pre` 开头是 markdown-it 的约定:命中这个前缀它就原样采用,不再自己包一层
* `<pre><code>`。整个过程不允许抛错 —— 任何异常都退化成转义后的纯文本,因为
* markdown-it 不会替我们兜住 `highlight` 回调里的异常,一抛就是整篇渲染失败。
*/
function renderCodeBlock(code: string, rawLanguage: string): string {
const language = normalizeFenceLanguage(rawLanguage)
let inner = ''
let highlighted = ''
try {
if (language && hljs.getLanguage(language)) {
inner = hljs.highlight(code, { language, ignoreIllegals: true }).value
highlighted = language
} else if (language && code.length <= AUTO_DETECT_MAX_CHARS) {
// 声明了语言却不在注册表(拼错、或全量包里也没有):在候选集里试一把
const auto = hljs.highlightAuto(code, AUTO_DETECT_SUBSET)
if (auto.language !== undefined && auto.relevance >= AUTO_DETECT_MIN_RELEVANCE) {
inner = auto.value
highlighted = auto.language
}
}
} catch {
inner = ''
highlighted = ''
}
if (inner === '') inner = escapeHtml(code)
const codeClass = highlighted === '' ? ' class="hljs"' : ` class="hljs language-${escapeHtml(highlighted)}"`
return `<pre class="hljs"><code${codeClass}>${inner}</code></pre>`
}
/**
* 渲染选项(模块级可变开关)。
*
* markdown-it 的 `highlight` 回调是**构造时**绑定的,而 `md` 是单例。这里用一个
* 模块级开关让回调按当前调用决定行为 —— 比「为了关高亮再造一个 MarkdownIt 实例」
* 简单,也比「把开关写进单例」(那会让一次导出永久影响后续所有渲染)安全:
* [`renderWithOptions`] 进入时设、`finally` 里复位,不存在跨调用残留。
*/
let highlightEnabled = true
/**
* markdown-it 实例。配置三件套的取舍:
* - `html: true`:笔记里嵌原生 HTML 很常见,放行;安全由 DOMPurify 负责,不由解析器负责。
* - `linkify: true`:裸 URL 变可点链接(导出文档里很实用)。
* - `breaks: false`:与编辑器预览一致 —— 单换行仍是软换行,不变成 `<br>`。
* - `typographer: false`:中文场景下智能标点收益小、翻车多(中文引号被替换),关掉。
*/
const md = new MarkdownIt({
html: true,
linkify: true,
breaks: false,
typographer: false,
highlight: (code, lang) => (highlightEnabled ? renderCodeBlock(code, lang) : '')
})
md.use(taskListPlugin)
/**
* 按选项渲染 Markdown。
*
* `highlight: false` 时回调返回空串,markdown-it 会自己把代码转义并包进
* `<pre><code>` —— 因此「关掉高亮」不需要再实现一遍代码块渲染。
*/
function renderWithOptions(markdown: string, highlight: boolean): string {
const previous = highlightEnabled
highlightEnabled = highlight
try {
return md.render(stripFrontMatter(markdown))
} finally {
highlightEnabled = previous
}
}
/**
* DOMPurify 配置:默认 HTML 白名单 + 减法(见文件头「安全」一节的完整理由)。
* 两个 `FORBID` 都是「默认白名单里有、但我们明确不要」的项,而不是自定义白名单。
*/
const SANITIZE_CONFIG: DomPurifyConfig = {
FORBID_TAGS: ['style'],
FORBID_ATTR: ['style', 'srcset'],
ADD_ATTR: ['target', 'rel']
}
/**
* 消毒的唯一入口。
*
* 失败关闭:DOMPurify 需要 `window`/`document`,无 DOM 环境(Node 单测、SSR)里
* `isSupported === false` 且 `sanitize` 根本不存在。此时返回空串 —— 宁可导出空白,
* 也绝不把未消毒的 HTML 交给调用方。`try/catch` 同理:消毒环节出任何意外,出口都是
* 「空」,不是「原文」。
*/
function sanitizeHtml(dirty: string): string {
if (!DOMPurify.isSupported || typeof DOMPurify.sanitize !== 'function') return ''
try {
return DOMPurify.sanitize(dirty, SANITIZE_CONFIG)
} catch {
return ''
}
}
/**
* Markdown → **未消毒**的 HTML 片段(含 front-matter 时先剥)。
*
* ⚠️ 仅供单测与本模块内部使用:返回的字符串里可以带着 `<script>` 和 `onerror=`。
* 之所以导出,是因为 DOMPurify 需要 DOM、Node 单测里跑不了,而「围栏语言识别、任务
* 列表、表格、链接」这些**渲染**行为必须能脱离浏览器回归。浏览器/生产代码请一律走
* [`renderMarkdownFragment`]。
*/
export function renderMarkdownFragmentRaw(markdown: string): string {
return renderWithOptions(markdown, true)
}
/** Markdown → 已消毒的 HTML 片段(不含 <html>/<style>;供预览/嵌入用) */
export function renderMarkdownFragment(markdown: string): string {
return sanitizeHtml(renderMarkdownFragmentRaw(markdown))
}
/**
* 导出文档的全部样式(内联进 `<style>`)。
*
* 三条硬约束:① 不出现任何外部 URL —— 无 `@import`、无外链字体,双击离线可看;
* ② 打印优先 —— 高亮配色只有一套(浅底深字),`@media print` 里再去掉底色与阴影,
* 保证黑白打印仍然可读;③ 只管导出文档自己的外观,不假设宿主环境。
*/
const EXPORT_STYLE = `
:root { color-scheme: light; }
* { box-sizing: border-box; }
body {
margin: 0;
padding: 32px 16px 64px;
background: #f5f6f8;
color: #1f2328;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
font-size: 16px;
line-height: 1.7;
}
.note {
max-width: ${BODY_MAX_WIDTH}px;
margin: 0 auto;
padding: 40px 44px 28px;
background: #ffffff;
border-radius: 10px;
box-shadow: 0 1px 3px rgba(31, 35, 40, 0.12);
}
.note-title { margin: 0 0 4px; font-size: 1.9em; line-height: 1.3; font-weight: 600; }
.note-body > :first-child { margin-top: 0; }
.note-body h1, .note-body h2, .note-body h3, .note-body h4, .note-body h5, .note-body h6 {
margin: 1.6em 0 0.6em;
line-height: 1.35;
font-weight: 600;
}
.note-body h1 { font-size: 1.6em; padding-bottom: 0.3em; border-bottom: 1px solid #d8dee4; }
.note-body h2 { font-size: 1.35em; padding-bottom: 0.3em; border-bottom: 1px solid #d8dee4; }
.note-body h3 { font-size: 1.15em; }
.note-body p { margin: 0 0 1em; }
.note-body a { color: #0969da; text-decoration: none; border-bottom: 1px solid rgba(9, 105, 218, 0.35); }
.note-body a:hover { border-bottom-color: currentColor; }
.note-body strong { font-weight: 600; }
.note-body mark { padding: 0 0.15em; background: #fff8c5; color: inherit; border-radius: 2px; }
.note-body img { max-width: 100%; height: auto; border-radius: 6px; }
.note-body blockquote {
margin: 0 0 1em;
padding: 0.2em 0 0.2em 1em;
border-left: 4px solid #d0d7de;
color: #59636e;
}
.note-body blockquote > :last-child { margin-bottom: 0; }
.note-body ul, .note-body ol { margin: 0 0 1em; padding-left: 1.6em; }
.note-body li { margin: 0.25em 0; }
.note-body li.task-list-item { margin-left: -1.35em; list-style: none; }
.note-body input[type="checkbox"] { margin-right: 0.45em; vertical-align: middle; }
.note-body code {
padding: 0.15em 0.35em;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
font-size: 0.9em;
background: rgba(129, 139, 152, 0.16);
border-radius: 4px;
}
.note-body pre {
margin: 0 0 1em;
padding: 12px 14px;
overflow-x: auto;
background: #f6f8fa;
border: 1px solid #d8dee4;
border-radius: 6px;
line-height: 1.55;
}
.note-body pre code { padding: 0; font-size: 0.875em; background: transparent; white-space: pre; }
.note-body table { display: block; max-width: 100%; margin: 0 0 1em; overflow-x: auto; border-collapse: collapse; }
.note-body th, .note-body td { padding: 6px 12px; border: 1px solid #d0d7de; }
.note-body th { font-weight: 600; background: #f6f8fa; }
.note-body hr { height: 1px; margin: 1.8em 0; border: 0; background: #d8dee4; }
/* 最小高亮配色:只有一套(白底可读),打印时不掉色 */
.note-body pre.hljs { color: #1f2328; }
.hljs-comment, .hljs-quote { color: #6e7781; font-style: italic; }
.hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-section { color: #cf222e; }
.hljs-string, .hljs-regexp, .hljs-addition { color: #0a3069; }
.hljs-number, .hljs-symbol, .hljs-bullet { color: #0550ae; }
.hljs-title, .hljs-name, .hljs-selector-id, .hljs-selector-class { color: #8250df; }
.hljs-attr, .hljs-attribute, .hljs-variable, .hljs-template-variable { color: #953800; }
.hljs-built_in, .hljs-type { color: #0550ae; }
.hljs-meta, .hljs-doctag, .hljs-deletion { color: #82071e; }
.hljs-tag { color: #116329; }
.hljs-emphasis { font-style: italic; }
.hljs-strong { font-weight: 600; }
.note-footer {
margin-top: 40px;
padding-top: 12px;
border-top: 1px solid #d8dee4;
color: #6e7781;
font-size: 0.8125em;
text-align: center;
}
@media print {
body { margin: 0; padding: 0; background: #ffffff; color: #000000; font-size: 12pt; }
.note { max-width: none; padding: 0; border-radius: 0; box-shadow: none; }
.note-body a { color: inherit; border-bottom: 0; }
.note-body pre, .note-body code, .note-body th, .note-body mark { background: transparent; }
.note-body pre { border-color: #999999; }
.note-body pre, .note-body table, .note-body blockquote { page-break-inside: avoid; }
}
`
/**
* 渲染单篇笔记为完整 HTML 文档字符串(含 <style>,不依赖外部资源)。
*
* 页面结构:页首 `<h1>`(标题)、正文(已消毒的 Markdown 片段)、页脚一行
* 「导出自 Thing · 时间」。标题只做转义、不做 `fileName` 去扩展名之类的加工 ——
* 调用方给什么就是什么,`fileName`(含 `.md`)仅作为空标题的兜底。
*/
export function renderNoteHtml(input: NoteHtmlInput): string {
const title = input.title.trim() || input.fileName.trim() || '未命名笔记'
const exportedAt =
input.exportedAt !== undefined && !Number.isNaN(input.exportedAt.getTime()) ? input.exportedAt : new Date()
const footer = `导出自 Thing · ${formatLocalTimestamp(exportedAt)}`
// 消毒后插入;`highlight: false` 时围栏代码块不带 hljs token 样式(打印友好)
const body = sanitizeHtml(renderWithOptions(input.markdown, input.highlight !== false))
return (
[
'<!doctype html>',
'<html lang="zh-CN">',
'<head>',
'<meta charset="utf-8">',
'<meta name="viewport" content="width=device-width, initial-scale=1">',
`<title>${escapeHtml(title)}</title>`,
`<style>${EXPORT_STYLE}</style>`,
'</head>',
'<body>',
'<article class="note">',
`<h1 class="note-title">${escapeHtml(title)}</h1>`,
'<div class="note-body">',
body,
'</div>',
`<footer class="note-footer">${escapeHtml(footer)}</footer>`,
'</article>',
'</body>',
'</html>',
''
].join('\n')
)
}
@@ -0,0 +1,461 @@
/**
* Live Preview 扩展 —— CM6 上的「所见即所得」。
*
* # 范式说明(重要)
*
* CodeMirror 是源码编辑器,没有块模型。这里的「所见即所得」= **Live Preview**
* (Typora / Obsidian 式):遍历 Lezer Markdown 语法树,
*
* - **非光标行**:隐藏 Markdown 语法符号(`#` `**` `[]()` `>` `-` …),
* 让渲染结果直接可见;
* - **光标行**(当前选区所覆盖的行):语法符号「显形」,恢复为可编辑源码;
* - **结构性元素**用装饰表达标签无法表达的部分:标题字号、行内代码底色、
* 引用条、代码块底色、分隔线 widget、任务复选框 widget(可点击改写文档)。
*
* 颜色(标题色 / 加粗 / 斜体 / 链接色)由主题的 HighlightStyle 负责,
* 这里只管结构与「隐藏」。
*
* # 性能
*
* 装饰只对 `view.visibleRanges` 计算(长文档不做全文遍历),
* 且文档/选区/视口变化时整批重建(见文件末的 ViewPlugin)。
*/
import {
Decoration,
EditorView,
ViewPlugin,
WidgetType,
type DecorationSet,
type ViewUpdate
} from '@codemirror/view'
import { type Extension, type Range } from '@codemirror/state'
import { syntaxTree } from '@codemirror/language'
import { type SyntaxNode } from '@lezer/common'
import { cachedImage, fetchImage, resolveImagePath } from './images'
/** Live Preview 的可选配置(图片预览需要知道「当前是哪篇笔记」)。 */
export interface LivePreviewOptions {
/**
* 当前笔记的库内相对路径(空串 = 库外文件,不做图片预览)。
*
* 图片目标按「相对当前笔记所在目录」解析,因此必须有这个上下文。
*/
currentRelPath?: string
/** 是否启用图片预览(默认 true) */
images?: boolean
}
/** 隐藏语法符号(替换为空) */
const HIDE = Decoration.replace({})
/** 取节点的「内部内容」区间(跳过首尾的语法标记子节点)。 */
function innerRange(node: SyntaxNode): { from: number; to: number } {
const first = node.firstChild
const last = node.lastChild
if (!first || !last) return { from: node.from, to: node.to }
const from = first.to
const to = last.from
return from < to ? { from, to } : { from: node.from, to: node.to }
}
/** 任务复选框:点击在 `[ ]` / `[x]` 间切换。 */
class CheckboxWidget extends WidgetType {
constructor(
readonly checked: boolean,
readonly from: number,
readonly to: number
) {
super()
}
eq(other: CheckboxWidget): boolean {
return other.checked === this.checked && other.from === this.from
}
toDOM(view: EditorView): HTMLElement {
const input = document.createElement('input')
input.type = 'checkbox'
input.checked = this.checked
input.className = 'cm-md-checkbox'
input.addEventListener('mousedown', event => {
event.preventDefault()
view.dispatch({
changes: { from: this.from, to: this.to, insert: this.checked ? '[ ]' : '[x]' }
})
})
return input
}
ignoreEvent(): boolean {
return false
}
}
/** 分隔线:把 `---` / `***` 渲染成一条水平线。 */
class HorizontalRuleWidget extends WidgetType {
eq(): boolean {
return true
}
toDOM(): HTMLElement {
const el = document.createElement('span')
el.className = 'cm-md-hr'
return el
}
ignoreEvent(): boolean {
return false
}
}
/**
* 内联图片预览。
*
* 只在「该 Markdown 图片独占一行、且不在光标行上」时替换整段 `![alt](src)` ——
* 与行内混排的图片(`见 ![图](a.png) 所示`)保持源码形态:把行内图片换成块级
* `<img>` 会撑高这一行,光标位置与视觉行对不上。
*
* 高度上限用 CSS 控制(`max-height: 320px`),而不是在 widget 里算 —— 算高度就
* 得等 `load` 事件,那会让装饰重建与图片加载互相触发。
*/
class InlineImageWidget extends WidgetType {
constructor(
readonly src: string,
readonly alt: string,
/** 文档里的完整原始片段(预览不可用时原样显示) */
readonly raw: string
) {
super()
}
eq(other: InlineImageWidget): boolean {
return other.src === this.src && other.alt === this.alt
}
toDOM(): HTMLElement {
const wrapper = document.createElement('span')
wrapper.className = 'cm-md-image'
const img = document.createElement('img')
img.src = this.src
img.alt = this.alt
img.loading = 'lazy'
// 拖拽图片应当拖「图片文件」而不是让编辑器选中文本
img.draggable = false
wrapper.appendChild(img)
if (this.alt) {
const caption = document.createElement('span')
caption.className = 'cm-md-image-alt'
caption.textContent = this.alt
wrapper.appendChild(caption)
}
return wrapper
}
ignoreEvent(): boolean {
return false
}
}
/** 是否为「链接类」节点的子 URL(决定是否随链接一起隐藏)。 */
function isLinkUrl(node: SyntaxNode): boolean {
const parent = node.parent
return parent?.name === 'Link' || parent?.name === 'Image'
}
/** 取出一个 `Image` 节点的原始目标(`![alt](target)` 里 `target` 的原文)。 */
function imageTarget(raw: string): { alt: string; target: string } | null {
// 结构固定为 `![alt](target)`:找第一个 `](`,再从末尾去掉 `)`
const open = raw.indexOf('](')
if (open < 0 || !raw.endsWith(')')) return null
const alt = raw.slice(2, open)
const target = raw.slice(open + 2, -1)
return { alt, target }
}
/**
* 「装饰构建器」旁表:`EditorView` → 重建函数。
*
* 图片是异步取字节的,拿到之后需要重算一次装饰。插件本身不把实例暴露给外部,
* 而是把重建函数登记在这里 —— 宿主(或本文件内部的图片回调)拿着同一个 view
* 就能触发重建,`ViewPlugin` 的 `update` 生命周期不会被外部伸手破坏。
*
* 用 `WeakMap`:编辑器销毁后条目自动消失,不会因为「关掉的窗口」泄漏。
*/
const builders = new WeakMap<EditorView, (view: EditorView) => void>()
/** 让某个编辑器重建 Live Preview 装饰(图片取到字节后调用)。 */
export function refreshDecorations(view: EditorView): void {
builders.get(view)?.(view)
}
/**
* 构建装饰集。
*
* 做成工厂(而不是模块级函数)是因为图片预览需要闭包持有「当前笔记路径」——
* 那是**每个 EditorView 实例**的上下文,放进模块级单例会在多窗口/多编辑器之间串味。
*/
function createBuilder(options: LivePreviewOptions) {
const currentRelPath = options.currentRelPath ?? ''
const imagesEnabled = options.images !== false && currentRelPath !== ''
return function buildDecorations(view: EditorView): DecorationSet {
const state = view.state
const doc = state.doc
const decos: Range<Decoration>[] = []
// 光标/选区覆盖的行:这些行内的语法符号显形(保持可编辑)
const activeLines = new Set<number>()
for (const range of state.selection.ranges) {
const startLine = doc.lineAt(range.from).number
const endLine = doc.lineAt(range.to).number
for (let n = startLine; n <= endLine; n++) activeLines.add(n)
}
const isActive = (pos: number) => activeLines.has(doc.lineAt(pos).number)
const mark = (from: number, to: number, cls: string) => {
if (from < to) decos.push({ from, to, value: Decoration.mark({ class: cls }) })
}
const line = (pos: number, cls: string) => {
const l = doc.lineAt(pos)
decos.push({ from: l.from, to: l.from, value: Decoration.line({ class: cls }) })
}
const replace = (from: number, to: number, value: Decoration) => {
if (from < to) decos.push({ from, to, value })
}
const hide = (from: number, to: number, swallowSpace = false) => {
let end = to
while (swallowSpace && end < doc.length && doc.sliceString(end, end + 1) === ' ') end++
replace(from, end, HIDE)
}
for (const { from, to } of view.visibleRanges) {
syntaxTree(state).iterate({
from,
to,
enter: node => {
const name = node.name
const active = isActive(node.from)
const n = node.node
switch (name) {
// ===== 标题:行级样式(字号/字重),符号在非光标行隐藏 =====
case 'ATXHeading1':
case 'ATXHeading2':
case 'ATXHeading3':
case 'ATXHeading4':
case 'ATXHeading5':
case 'ATXHeading6':
line(node.from, `cm-md-h${name.slice(-1)}`)
break
case 'SetextHeading1':
case 'SetextHeading2':
line(node.from, `cm-md-h${name.slice(-1)}`)
break
// ===== 语法标记:非光标行隐藏 =====
case 'HeaderMark':
if (!active) hide(node.from, node.to, true)
break
case 'EmphasisMark':
case 'StrikethroughMark':
if (!active) hide(node.from, node.to)
break
case 'LinkMark':
if (!active) hide(node.from, node.to)
break
case 'URL':
if (!active && isLinkUrl(n)) hide(node.from, node.to)
break
case 'QuoteMark':
if (!active) hide(node.from, node.to, true)
break
case 'ListMark':
if (!active) hide(node.from, node.to, true)
break
case 'CodeMark':
// 仅行内代码的反引号隐藏;围栏代码块的 ``` 保留(保留语言标注)
if (!active && n.parent?.name === 'InlineCode') hide(node.from, node.to)
break
// ===== 行内代码:底色 + 内边距(标签只给颜色) =====
case 'InlineCode': {
const inner = innerRange(n)
mark(inner.from, inner.to, 'cm-md-inlinecode')
break
}
// ===== 引用:整块左侧竖线 =====
case 'Blockquote': {
let pos = node.from
while (pos <= node.to) {
const l = doc.lineAt(pos)
line(l.from, 'cm-md-quote')
if (l.to >= node.to) break
pos = l.to + 1
}
break
}
// ===== 围栏代码块:整块底色 =====
case 'FencedCode': {
let pos = node.from
while (pos <= node.to) {
const l = doc.lineAt(pos)
line(l.from, 'cm-md-codeblock')
if (l.to >= node.to) break
pos = l.to + 1
}
break
}
// ===== 分隔线:非光标行渲染为水平线 =====
case 'HorizontalRule':
if (!active) {
replace(node.from, node.to, Decoration.replace({ widget: new HorizontalRuleWidget() }))
}
break
// ===== 任务列表:复选框 widget(任何状态下都可点击切换) =====
case 'TaskMarker': {
const text = doc.sliceString(node.from, node.to)
const checked = /\[[xX]\]/.test(text)
replace(
node.from,
node.to,
Decoration.replace({ widget: new CheckboxWidget(checked, node.from, node.to) })
)
break
}
// ===== 图片:独占一行 + 非光标行时内联预览 =====
case 'Image': {
if (!imagesEnabled || active) break
const startLine = doc.lineAt(node.from)
const endLine = doc.lineAt(node.to)
if (startLine.number !== endLine.number) break
// 只预览「这一行除了图片没有别的可见内容」的情况
const lineText = doc.sliceString(startLine.from, startLine.to).trim()
const raw = doc.sliceString(node.from, node.to)
if (lineText !== raw.trim()) break
const parsed = imageTarget(raw)
if (!parsed) break
const relPath = resolveImagePath(parsed.target, currentRelPath)
if (!relPath) break
const cached = cachedImage(relPath)
if (cached === undefined) {
// 首次见到:异步取字节,取到后重建这一篇的装饰
void fetchImage(relPath).then(() => {
const refresh = builders.get(view)
if (refresh) refresh(view)
})
break
}
if (cached === null) break // 已确认不可预览 → 保持源码形态
replace(
node.from,
node.to,
Decoration.replace({
widget: new InlineImageWidget(cached, parsed.alt, raw)
})
)
break
}
default:
break
}
}
})
}
return Decoration.set(decos, true)
}
}
/** Live Preview 的结构样式(颜色交给主题;这里只做标签表达不了的部分)。 */
const livePreviewTheme = EditorView.baseTheme({
'.cm-md-h1': { fontSize: '1.6em', fontWeight: '700', lineHeight: '1.4' },
'.cm-md-h2': { fontSize: '1.4em', fontWeight: '700', lineHeight: '1.4' },
'.cm-md-h3': { fontSize: '1.22em', fontWeight: '600' },
'.cm-md-h4': { fontSize: '1.1em', fontWeight: '600' },
'.cm-md-h5': { fontSize: '1em', fontWeight: '600' },
'.cm-md-h6': { fontSize: '0.94em', fontWeight: '600', opacity: '0.85' },
'.cm-md-quote': {
borderLeft: '3px solid currentColor',
opacity: '0.9',
paddingLeft: '12px'
},
'.cm-md-codeblock': {
backgroundColor: 'rgba(127, 127, 127, 0.12)'
},
'.cm-md-inlinecode': {
backgroundColor: 'rgba(127, 127, 127, 0.16)',
borderRadius: '4px',
padding: '0.1em 0.35em',
fontFamily: "'Cascadia Code', 'JetBrains Mono', Consolas, monospace"
},
'.cm-md-hr': {
display: 'inline-block',
width: '100%',
borderTop: '1px solid currentColor',
opacity: '0.35',
verticalAlign: 'middle'
},
'.cm-md-checkbox': {
marginRight: '6px',
verticalAlign: 'middle',
cursor: 'pointer'
},
'.cm-md-image': {
display: 'inline-flex',
flexDirection: 'column',
gap: '4px',
maxWidth: '100%',
verticalAlign: 'top'
},
// 高度上限交给 CSS:算高度要等 `load` 事件,会让装饰重建与图片加载互相触发
'.cm-md-image img': {
maxWidth: '100%',
maxHeight: '320px',
borderRadius: '6px',
objectFit: 'contain'
},
'.cm-md-image-alt': {
fontSize: '0.8em',
opacity: '0.6',
fontStyle: 'italic'
}
})
/**
* Live Preview 扩展工厂。
*
* 必须按编辑器实例构造(内部的 ViewPlugin 闭包持有该实例的笔记路径):
* 若做成模块级单例,多窗口/多编辑器会共用同一份闭包上下文 —— 在 A 笔记里预览的图片
* 会按 B 笔记的目录去解析。
*/
export function markdownLivePreview(options: LivePreviewOptions = {}): Extension {
const buildDecorations = createBuilder(options)
return [
livePreviewTheme,
ViewPlugin.fromClass(
class {
decorations: DecorationSet
constructor(view: EditorView) {
this.decorations = buildDecorations(view)
builders.set(view, next => {
this.decorations = buildDecorations(next)
// `Decoration.set` 换新对象后必须让 CM 知道视口需要重绘
next.requestMeasure()
})
}
update(update: ViewUpdate) {
if (update.docChanged || update.selectionSet || update.viewportChanged) {
this.decorations = buildDecorations(update.view)
}
}
},
{ decorations: value => value.decorations }
)
]
}
+170
View File
@@ -0,0 +1,170 @@
/**
* 大纲提取单测(Node 内置 test runner)。
*
* # 断言为什么全是「显式数字」
*
* `from` 的语义只有一条:**标题所在行的行首偏移**(ATX 含行首缩进)。这里一律写
* 死数字而不是 `doc.indexOf(...)` —— 用 indexOf 会把实现里的偏移错误「自我印证」
* 掉(实现取错锚点时,测试跟着错,永远绿)。
*
* # 已修正的期望(原稿手算有误)
*
* - 裸 `#` / `# `(空标题):`from` 是行首(0 / 2),不是「`#` 后一位」
* - Setext 标题:`from` 是**标题那一行**的行首,不是下划线的位置
* - CRLF:行首偏移按原始长度推进(`\r` 计入),标题行内容不含 `\r`
*
* 数字由脚本按「行首偏移累加」算出后写死(见提交说明),不是实现输出。
*/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { extractOutline } from './outline.ts'
test('ATX 各级标题:层级、文本、行号、偏移', () => {
const doc = ['# H1', '## H2', '### H3', '#### H4', '##### H5', '###### H6'].join('\n')
assert.deepEqual(extractOutline(doc), [
{ level: 1, text: 'H1', line: 1, from: 0 },
{ level: 2, text: 'H2', line: 2, from: 5 },
{ level: 3, text: 'H3', line: 3, from: 11 },
{ level: 4, text: 'H4', line: 4, from: 18 },
{ level: 5, text: 'H5', line: 5, from: 26 },
{ level: 6, text: 'H6', line: 6, from: 35 }
])
})
test('ATX 必须 # 后有空白:#tag / #hashtag / #中文 不算标题', () => {
const doc = ['#tag 不是标题', '#hashtag', '#中文标题', '正文 # 号在中间'].join('\n')
assert.deepEqual(extractOutline(doc), [])
})
test('裸 # 也算标题(# 后必须有空白,但内容可为空)', () => {
const doc = ['#', '# '].join('\n')
// `from` 一律是行首偏移:空标题没有「正文起点」可指,行首是唯一无歧义的锚点
assert.deepEqual(extractOutline(doc), [
{ level: 1, text: '', line: 1, from: 0 },
{ level: 1, text: '', line: 2, from: 2 }
])
})
test('ATX 内容保留原文(不解析行内语法)且 trim', () => {
const doc = '# **bold** `code` [x](y) '
assert.deepEqual(extractOutline(doc), [
{ level: 1, text: '**bold** `code` [x](y)', line: 1, from: 0 }
])
})
test('ATX 闭合 # 序列剥离,但内容中间的 # 与无空白的 # 保留', () => {
const doc = ['## 标题 ##', '# 中间 # 号 ##', '### 内容末尾 #x ###', '# 只剥结尾 ###'].join('\n')
assert.deepEqual(extractOutline(doc), [
{ level: 2, text: '标题', line: 1, from: 0 },
{ level: 1, text: '中间 # 号', line: 2, from: 9 },
{ level: 3, text: '内容末尾 #x', line: 3, from: 21 },
{ level: 1, text: '只剥结尾', line: 4, from: 37 }
])
})
test('ATX 允许最多 3 空格缩进,4 空格(缩进代码)不认', () => {
const doc = [' # 缩进三级', ' # 缩进四级'].join('\n')
// `from` 是行首(含缩进):跳到「这一行」,不是跳到 `#`
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '缩进三级', line: 1, from: 0 }])
})
test('7 个以上 # 不是标题', () => {
assert.deepEqual(extractOutline('####### 七个井号'), [])
})
test('Setext 标题:=== 为 1 级,--- 为 2 级', () => {
const doc = ['一级标题', '===', '', '二级标题', '---', '', '带下划线', '====='].join('\n')
assert.deepEqual(extractOutline(doc), [
{ level: 1, text: '一级标题', line: 1, from: 0 },
{ level: 2, text: '二级标题', line: 4, from: 10 },
{ level: 1, text: '带下划线', line: 7, from: 20 }
])
})
test('Setext:前面是空行 / 分隔线 / 列表项时不当标题', () => {
const doc = ['', '---', '~~~text', '- 列表项', '---', '> 引用', '==='].join('\n')
assert.deepEqual(extractOutline(doc), [])
})
test('front-matter 整块跳过,闭合 --- 不当 Setext 下划线', () => {
const doc = ['---', 'title: "# 假标题"', 'tags:', ' - a', '---', '# 真标题'].join('\n')
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 6, from: 35 }])
})
test('front-matter 结束后,后面的 Setext 正常识别', () => {
const doc = ['---', 'desc: 描述行', '---', '正文', 'Title', '---'].join('\n')
// 第 5 行的 `---` 把上一行 Title 提升为二级标题;第 2 行的 `---` 是 front-matter
// 闭合行,绝不能把 `desc: 描述行` 提升成标题(这是实现里真实踩过的坑)
assert.deepEqual(extractOutline(doc), [{ level: 2, text: 'Title', line: 5, from: 21 }])
})
test('围栏代码块(``` 与 ~~~)内的 # 与其后内容被跳过', () => {
const doc = [
'# 标题一',
'```md',
'# 假标题',
'## 也假',
'```',
'~~~',
'# 波浪号里也假',
'~~~',
'# 标题二'
].join('\n')
assert.deepEqual(extractOutline(doc), [
{ level: 1, text: '标题一', line: 1, from: 0 },
{ level: 1, text: '标题二', line: 9, from: 45 }
])
})
test('代码块内 Setext 下划线与围栏内未闭合围栏都不产生标题', () => {
const doc = ['```', '假标题', '---', '```', '真标题', '==='].join('\n')
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 5, from: 16 }])
})
test('未闭合围栏吞到文档末尾', () => {
const doc = ['# 保留', '```ts', '# 被吞', '## 也被吞'].join('\n')
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '保留', line: 1, from: 0 }])
})
test('围栏闭合行不能带语言标注', () => {
const doc = ['```', '```js', '# 仍在围栏内', '```', '# 出来啦'].join('\n')
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '出来啦', line: 5, from: 22 }])
})
test('缩进代码块(4 空格 / Tab)内的 # 被跳过', () => {
const doc = ['', ' # 缩进代码', '\t# Tab 代码', '', '# 真标题'].join('\n')
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 5, from: 23 }])
})
test('CRLF:行内容不含 \\r,行号与 from 偏移正确', () => {
const crlf = '# 一\r\n\r\n## 二\r\nSetext\r\n==='
// 行首偏移按原始长度推进:`# 一`(4+1) → 5……`\r\n` 的两行各占 1+1
assert.deepEqual(extractOutline(crlf), [
{ level: 1, text: '一', line: 1, from: 0 },
{ level: 2, text: '二', line: 3, from: 7 },
{ level: 1, text: 'Setext', line: 4, from: 13 }
])
})
test('CRLF 下标题文本不残留 \\r', () => {
const headings = extractOutline('# 标题\r\n## 二级 ##\r\n')
// `# 标题` 占 4+1 字节,加 `\r\n` 的 `\r`(在 split 后归上一行)→ 第二行行首为 6
assert.deepEqual(headings, [
{ level: 1, text: '标题', line: 1, from: 0 },
{ level: 2, text: '二级', line: 2, from: 6 }
])
})
test('空文档 / 无标题 / 只有空白行', () => {
assert.deepEqual(extractOutline(''), [])
assert.deepEqual(extractOutline('\n\n \n\t\n'), [])
assert.deepEqual(extractOutline('普通段落\n再来一行'), [])
})
test('from 指向标题行行首:ATX 含行首缩进', () => {
const doc = '前言\n\n ## 缩进二级\n\n正文 # 井号'
const headings = extractOutline(doc)
assert.deepEqual(headings, [{ level: 2, text: '缩进二级', line: 3, from: 4 }])
// 行首偏移 → 能直接取回该行(含缩进):' ## 缩进二级' 共 2+2+1+4 = 9 个字符
assert.equal(doc.slice(4, 4 + 9), ' ## 缩进二级')
})
+249
View File
@@ -0,0 +1,249 @@
/**
* 大纲提取 —— 从 Markdown 原文里捞出标题,供大纲面板渲染与点击跳转。
*
* # 为什么不用 CodeMirror 的语法树
*
* 编辑器里已经有 Lezer Markdown 语法树,但语法树只在视口(`visibleRanges`)内
* 才保证完整,而大纲需要**全文**的标题;另外大纲面板要能脱离编辑器单测。
* 所以这里做成「纯字符串进、纯数据出」的函数:无 DOM、无 CM 依赖、无第三方依赖。
* 代价是得自己实现一遍分块规则,边界以 CommonMark 为准做**务实子集**:
* 围栏代码块和 4 空格缩进代码块要跳过,行内语法一律不解析(标题文本保留原文)。
*
* # 关键取舍
*
* - **逐行扫描**:行号与偏移天然是行级的,比正则全文匹配更省心,也不会被
* 「跨行匹配」坑到。CRLF 下行内容先剥掉 `\r`,偏移仍按**原始长度**推进。
* - **`from` 一律是标题所在行的行首偏移**(ATX 含行首缩进)。语义只有一条:
* 「跳到这一行」。指向正文起点会让空标题(`#`、`# `)没有合法取值;指向 `#`
* 又因 `# ` 与 `# `(多个空格)长度不同而难以预期 —— 行首是唯一无歧义的锚点。
* - **ATX 必须 `#` 后跟空白**:否则 `#tag` / `#标题`(中文前无空格)会被误判成标题,
* 这类写法在笔记里太常见。收紧后误判为「不是标题」远比误判成标题安全。
* - **Setext 只在「上一行是自然段落文本」时才认**:空行 / ATX 标题 / 引用 /
* 列表项 / 缩进代码 后面跟的 `===` `---` 都不是 Setext 下划线(CommonMark
* 不允许这些块的惰性延续被 Setext 打断),`---` 更可能是分隔线,宁可漏也不要错。
* - **front-matter 是状态机而不是布尔量**:首行的 `---` 是**开头**,闭合要靠
* 「再遇到一个整行 `---`」。用布尔量会在第 0 行就把状态关掉,于是闭合行反而
* 把它上面那行元数据(`desc: xx`)提升成 Setext 标题 —— 真实踩过的坑,
* 详见 [`FrontMatterState`]。
* - **缩进代码块是启发式的**:只在「前面有空行」时才开始跳过 4 空格 / 1 Tab 行,
* 到第一个非空非缩进行结束。列表项内的相对缩进(如 2 空格续行)识别不了,
* 那种情况下带 4 空格的 `#` 会被当成标题 —— 这是有意接受的漏判。
*/
/** 大纲中的一个标题节点 */
export interface OutlineHeading {
/** 标题层级 1..6 */
level: number
/** 标题文本(已去掉 # 与首尾空白、去掉结尾的 # 闭合标记) */
text: string
/** 标题所在行号(1 起) */
line: number
/** 标题所在行的行首偏移(ATX 含行首缩进),点击跳转直接用它 */
from: number
}
/** 围栏代码块:行首最多 3 空格缩进 + 3 个以上连续 ` 或 ~。 */
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/
/** ATX 标题:行首最多 3 空格缩进 + 1~6 个 `#`(`#` 后可有空白与内容)。 */
const ATX_RE = /^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/
/** front-matter 分隔线:整行就是 `---`。 */
const FRONT_MATTER_FENCE_RE = /^-{3,}[ \t]*$/
/** Setext 下划线:最多 3 空格缩进 + 只有 `=` 或只有 `-`(+ 尾随空白)。 */
const SETEXT_UNDERLINE_RE = /^ {0,3}(=+|-+)[ \t]*$/
/** 引用块行首。 */
const BLOCKQUOTE_RE = /^ {0,3}>/
/** 无序列表项行首。 */
const BULLET_RE = /^ {0,3}[-+*](?:[ \t]|$)/
/** 有序列表项行首。 */
const ORDERED_RE = /^ {0,3}\d{1,9}[.)](?:[ \t]|$)/
/**
* front-matter 的三态。
*
* 首行就是 `---` 时,**这一行是开头而不是结尾**。用单个布尔量表示「是否在
* front-matter 内」会立刻在第 0 行把它关掉,随后第 2 行的闭合 `---` 就被当成
* 普通分隔线,把它上面那行 `desc: xx` 提升成 Setext 标题 —— 症状是
* 「元数据凭空变成大纲第一条」。
*
* 用常量对象而不是 `enum`:Node 的 TypeScript 支持是**只剥类型**(strip-only),
* `enum` 会生成运行时代码因而被拒绝(`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`),
* 单测就再也跑不起来。
*/
const FrontMatter = {
/** 首行不是 `---`:文档没有 front-matter */
None: 'none',
/** 首行是开头标记,正在元数据内 */
Inside: 'inside',
/** 已闭合;`frontMatterEndLine` 记录闭合行号,它不得再被当作 Setext 下划线 */
Closed: 'closed'
} as const
type FrontMatterState = (typeof FrontMatter)[keyof typeof FrontMatter]
/** 取数组中第 index 项;越界(`noUncheckedIndexedAccess` 的 `undefined`)退化为空串。 */
function at(list: string[], index: number): string {
return list[index] ?? ''
}
/** 行首缩进宽度(Tab 记 4)。 */
function indentWidth(line: string): number {
let width = 0
for (const ch of line) {
if (ch === ' ') width += 1
else if (ch === '\t') width += 4
else break
}
return width
}
/** 剥掉 ATX 结尾的 ` #` 闭合序列(CommonMark:闭合序列前必须有空白)。 */
function stripClosingHashes(value: string): string {
return value.replace(/[ \t]+#+[ \t]*$/, '')
}
/** 解析围栏行;不是围栏返回 null。反引号围栏的 info 里禁止再出现反引号。 */
function parseFence(line: string): { char: '`' | '~'; count: number } | null {
const match = FENCE_RE.exec(line)
if (!match) return null
const run = match[1] ?? ''
const rest = match[2] ?? ''
const char = run.charAt(0) as '`' | '~'
if (char === '`' && rest.includes('`')) return null
return { char, count: run.length }
}
/** 是否是某个围栏的合法闭合行(同字符、不短于开栏、除尾随空白外无其它字符)。 */
function isFenceClose(line: string, char: '`' | '~', count: number): boolean {
const match = FENCE_RE.exec(line)
if (!match) return false
const run = match[1] ?? ''
if ((match[2] ?? '').trim() !== '') return false
return run.charAt(0) === char && run.length >= count
}
/** 上一行是否算「自然段落文本」——只有它才允许被下一行的 `===` / `---` 提升为标题。 */
function isParagraphText(previous: string): boolean {
if (previous.trim() === '') return false
if (previous.startsWith(' ') || previous.startsWith('\t')) return false
if (previous.trimStart().startsWith('#')) return false
if (BLOCKQUOTE_RE.test(previous)) return false
if (BULLET_RE.test(previous)) return false
if (ORDERED_RE.test(previous)) return false
return true
}
/** 提取 Markdown 大纲。 */
export function extractOutline(doc: string): OutlineHeading[] {
const headings: OutlineHeading[] = []
if (doc === '') return headings
const lines = doc.split('\n')
/**
* 每行的行首偏移。
*
* **必须先算出来,不能在循环里「减回去」**:CRLF 下行内容的长度比原始行长少 1,
* 用 `当前偏移 - 上一行长度 - 1` 反推行首时,LF 恰好对、CRLF 一律偏 1 ——
* 这种「只在一种换行下错」的 bug 在 Windows 上几乎必然踩到。
*/
const lineStarts: number[] = []
{
let cursor = 0
for (const line of lines) {
lineStarts.push(cursor)
cursor += line.length + 1
}
}
const firstRaw = at(lines, 0)
const firstLine = firstRaw.endsWith('\r') ? firstRaw.slice(0, -1) : firstRaw
let frontMatter: FrontMatterState = FRONT_MATTER_FENCE_RE.test(firstLine)
? FrontMatter.Inside
: FrontMatter.None
/** front-matter 闭合行的行号(-1 = 无) */
let frontMatterEndLine = -1
let fenceChar: '`' | '~' | null = null
let fenceCount = 0
let inIndentedCode = false
for (let index = 0; index < lines.length; index++) {
const raw = at(lines, index)
const lineFrom = lineStarts[index] ?? 0
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
if (frontMatter === FrontMatter.Inside) {
// 元数据内:只有「整行 ---」才算闭合,且首行(index 0)就是那个开头本身
if (index > 0 && FRONT_MATTER_FENCE_RE.test(line.trim())) {
frontMatter = FrontMatter.Closed
frontMatterEndLine = index
}
continue
}
const fence = parseFence(line)
if (fenceChar !== null) {
// 围栏内:只看闭合行,其余(含 `#`)全部无视
if (isFenceClose(line, fenceChar, fenceCount)) fenceChar = null
continue
}
if (line.trim() === '') {
inIndentedCode = false
continue
}
const indent = indentWidth(line)
if (indent >= 4) {
// 缩进代码块启发式:前有空行才起块;块内(含其中的 `#`)全跳过
if (inIndentedCode) continue
if (index > 0 && at(lines, index - 1).trim() === '') {
inIndentedCode = true
continue
}
} else {
inIndentedCode = false
}
if (fence !== null) {
fenceChar = fence.char
fenceCount = fence.count
continue
}
const atx = ATX_RE.exec(line)
if (atx) {
const markerLen = (atx[1] ?? '').length
const body = line.slice(indent + markerLen)
const text = stripClosingHashes(body.trim()).trim()
headings.push({ level: markerLen, text, line: index + 1, from: lineFrom })
continue
}
// Setext:当前行是下划线,上一行才是标题文本
const underline = SETEXT_UNDERLINE_RE.exec(line)
if (!underline) continue
if (index === 0) continue
// front-matter 的闭合 `---` 不是下划线:否则它上面那行元数据会被提升成标题
if (index - 1 === frontMatterEndLine) continue
const previous = at(lines, index - 1)
if (!isParagraphText(previous)) continue
const title = previous.trim()
if (title === '') continue
headings.push({
level: (underline[1] ?? '').charAt(0) === '=' ? 1 : 2,
text: title,
// 行号/偏移都指回标题文本那一行(1 起行号 = index)
line: index,
from: lineStarts[index - 1] ?? 0
})
}
return headings
}
+418
View File
@@ -0,0 +1,418 @@
/**
* 编辑器配色方案与排版。
*
* # 为什么自建而不是堆第三方主题包
*
* 与终端模块 `terminalThemes.ts` 同一套取舍:常见的主题包把几十套颜色硬编码在一个
* 文件里(大部分用不上),且数值与 VS Code / JetBrains 的官方定义常有小幅偏差。
* 这里只保留实际提供的几套,色值取自各主题官方定义,保证「选了 vscode-dark
* 就和 VS Code 一致」。
*
* # 两层解耦
*
* - **配色**(本文件的 `createTheme` / `oneDark`):只负责颜色,是 CM6 的 `Extension`。
* - **排版**([`editorTypography`]):字体 / 字号 / 行高 / 连字,与配色独立可配。
*
* 主题 key 必须与 Rust 侧 `NoteSettings.editorTheme` 的取值保持一致,
* 否则用户选了主题却静默回落默认(终端模块踩过这个坑)。
*/
import { EditorView } from '@codemirror/view'
import { type Extension } from '@codemirror/state'
import { type TagStyle } from '@codemirror/language'
import { oneDark } from '@codemirror/theme-one-dark'
import { createTheme } from '@uiw/codemirror-themes'
import { tags as t } from '@lezer/highlight'
/** 主题的亮暗归属(供「跟随应用」取对应侧) */
interface ThemeDefinition {
dark: boolean
extension: Extension
}
const VSCODE_DARK: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#6a9955' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#569cd6' },
{ tag: [t.string, t.special(t.string)], color: '#ce9178' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#b5cea8' },
{ tag: [t.variableName, t.propertyName], color: '#9cdcfe' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#dcdcaa' },
{ tag: [t.typeName, t.className, t.tagName], color: '#4ec9b0' },
{ tag: [t.operator], color: '#d4d4d4' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#569cd6' },
{ tag: t.strong, color: '#d4d4d4', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#d4d4d4', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#d4d4d4', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#4fc1ff', textDecoration: 'underline' },
{ tag: t.monospace, color: '#ce9178' },
{ tag: t.quote, color: '#6a9955' }
]
const VSCODE_LIGHT: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#008000' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#0000ff' },
{ tag: [t.string, t.special(t.string)], color: '#a31515' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#098658' },
{ tag: [t.variableName, t.propertyName], color: '#001080' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#795e26' },
{ tag: [t.typeName, t.className, t.tagName], color: '#267f99' },
{ tag: [t.operator], color: '#333333' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#0000ff' },
{ tag: t.strong, color: '#333333', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#333333', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#333333', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#0451a5', textDecoration: 'underline' },
{ tag: t.monospace, color: '#a31515' },
{ tag: t.quote, color: '#008000' }
]
const DRACULA: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#6272a4' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#ff79c6' },
{ tag: [t.string, t.special(t.string)], color: '#f1fa8c' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#bd93f9' },
{ tag: [t.variableName, t.propertyName], color: '#f8f8f2' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#50fa7b' },
{ tag: [t.typeName, t.className, t.tagName], color: '#8be9fd' },
{ tag: [t.operator], color: '#ff79c6' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#bd93f9' },
{ tag: t.strong, color: '#f8f8f2', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#f8f8f2', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#f8f8f2', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#8be9fd', textDecoration: 'underline' },
{ tag: t.monospace, color: '#f1fa8c' },
{ tag: t.quote, color: '#6272a4' }
]
const SOLARIZED_DARK: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#586e75' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#859900' },
{ tag: [t.string, t.special(t.string)], color: '#2aa198' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#d33682' },
{ tag: [t.variableName, t.propertyName], color: '#b58900' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#268bd2' },
{ tag: [t.typeName, t.className, t.tagName], color: '#b58900' },
{ tag: [t.operator], color: '#859900' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#cb4b16' },
{ tag: t.strong, color: '#93a1a1', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#93a1a1', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#93a1a1', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#268bd2', textDecoration: 'underline' },
{ tag: t.monospace, color: '#2aa198' },
{ tag: t.quote, color: '#586e75' }
]
const SOLARIZED_LIGHT: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#93a1a1' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#859900' },
{ tag: [t.string, t.special(t.string)], color: '#2aa198' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#d33682' },
{ tag: [t.variableName, t.propertyName], color: '#b58900' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#268bd2' },
{ tag: [t.typeName, t.className, t.tagName], color: '#b58900' },
{ tag: [t.operator], color: '#859900' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#cb4b16' },
{ tag: t.strong, color: '#586e75', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#586e75', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#586e75', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#268bd2', textDecoration: 'underline' },
{ tag: t.monospace, color: '#2aa198' },
{ tag: t.quote, color: '#93a1a1' }
]
// ===== JetBrains 系列(P1,用户点名)=====
//
// CM6 没有官方的 JetBrains 配色包,因此按 JetBrains 各 IDE 的**默认配色方案**手校。
// 色值取自 IntelliJ 平台内置 scheme(Darcula / IntelliJ Light / Monokai Pro)的
// 常用取值;与终端模块「只保留实际提供的、数值取自官方」的策略一致。
//
// 一处刻意的取舍:JetBrains 的**关键字**在 Darcula 里是橙色(`#cc7832`)而不是
// 紫色 —— 直接套用「VS Code 式」的紫色关键字会让这个主题看起来一点都不像 IDEA。
const JETBRAINS_DARCULA: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#808080', fontStyle: 'italic' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#cc7832' },
{ tag: [t.string, t.special(t.string)], color: '#6a8759' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#6897bb' },
{ tag: [t.variableName, t.propertyName], color: '#a9b7c6' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#ffc66d' },
{ tag: [t.typeName, t.className, t.tagName], color: '#a9b7c6' },
{ tag: [t.operator], color: '#a9b7c6' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#ffc66d' },
{ tag: t.strong, color: '#a9b7c6', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#a9b7c6', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#a9b7c6', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#287bde', textDecoration: 'underline' },
{ tag: t.monospace, color: '#6a8759' },
{ tag: t.quote, color: '#808080' }
]
const INTELLIJ_LIGHT: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#8c8c8c', fontStyle: 'italic' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#0033b3' },
{ tag: [t.string, t.special(t.string)], color: '#067d17' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#1750eb' },
{ tag: [t.variableName, t.propertyName], color: '#000000' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#00627a' },
{ tag: [t.typeName, t.className, t.tagName], color: '#000000' },
{ tag: [t.operator], color: '#000000' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#00627a' },
{ tag: t.strong, color: '#000000', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#000000', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#000000', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#0000ff', textDecoration: 'underline' },
{ tag: t.monospace, color: '#067d17' },
{ tag: t.quote, color: '#8c8c8c' }
]
const MONOKAI_PRO: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#727072', fontStyle: 'italic' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#ff6188' },
{ tag: [t.string, t.special(t.string)], color: '#ffd866' },
{ tag: [t.number, t.bool, t.null, t.atom], color: '#ab9df2' },
{ tag: [t.variableName, t.propertyName], color: '#fcfcfa' },
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#a9dc76' },
{ tag: [t.typeName, t.className, t.tagName], color: '#78dce8' },
{ tag: [t.operator], color: '#ff6188' },
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#a9dc76' },
{ tag: t.strong, color: '#fcfcfa', fontWeight: 'bold' },
{ tag: t.emphasis, color: '#fcfcfa', fontStyle: 'italic' },
{ tag: t.strikethrough, color: '#fcfcfa', textDecoration: 'line-through' },
{ tag: [t.link, t.url], color: '#78dce8', textDecoration: 'underline' },
{ tag: t.monospace, color: '#ffd866' },
{ tag: t.quote, color: '#727072' }
]
/** 主题注册表(key 与 Rust 侧取值一致) */
export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
'vscode-dark': {
dark: true,
extension: createTheme({
theme: 'dark',
settings: {
background: '#1e1e1e',
foreground: '#d4d4d4',
caret: '#aeafad',
selection: '#264f78',
selectionMatch: '#264f7866',
lineHighlight: '#ffffff0a',
gutterBackground: '#1e1e1e',
gutterForeground: '#858585',
gutterActiveForeground: '#cccccc',
gutterBorder: '#00000000'
},
styles: VSCODE_DARK
})
},
'vscode-light': {
dark: false,
extension: createTheme({
theme: 'light',
settings: {
background: '#ffffff',
foreground: '#333333',
caret: '#000000',
selection: '#add6ff',
selectionMatch: '#add6ff80',
lineHighlight: '#00000008',
gutterBackground: '#ffffff',
gutterForeground: '#237893',
gutterActiveForeground: '#0b216f',
gutterBorder: '#00000000'
},
styles: VSCODE_LIGHT
})
},
'one-dark': {
dark: true,
extension: oneDark
},
dracula: {
dark: true,
extension: createTheme({
theme: 'dark',
settings: {
background: '#282a36',
foreground: '#f8f8f2',
caret: '#f8f8f2',
selection: '#44475a',
selectionMatch: '#44475a80',
lineHighlight: '#ffffff08',
gutterBackground: '#282a36',
gutterForeground: '#6272a4',
gutterActiveForeground: '#f8f8f2',
gutterBorder: '#00000000'
},
styles: DRACULA
})
},
'solarized-dark': {
dark: true,
extension: createTheme({
theme: 'dark',
settings: {
background: '#002b36',
foreground: '#839496',
caret: '#93a1a1',
selection: '#073642',
selectionMatch: '#07364280',
lineHighlight: '#ffffff08',
gutterBackground: '#002b36',
gutterForeground: '#586e75',
gutterActiveForeground: '#93a1a1',
gutterBorder: '#00000000'
},
styles: SOLARIZED_DARK
})
},
'solarized-light': {
dark: false,
extension: createTheme({
theme: 'light',
settings: {
background: '#fdf6e3',
foreground: '#657b83',
caret: '#586e75',
selection: '#eee8d5',
selectionMatch: '#eee8d580',
lineHighlight: '#00000008',
gutterBackground: '#fdf6e3',
gutterForeground: '#93a1a1',
gutterActiveForeground: '#586e75',
gutterBorder: '#00000000'
},
styles: SOLARIZED_LIGHT
})
},
'jetbrains-darcula': {
dark: true,
extension: createTheme({
theme: 'dark',
settings: {
background: '#2b2b2b',
foreground: '#a9b7c6',
caret: '#bbbbbb',
selection: '#214283',
selectionMatch: '#21428380',
lineHighlight: '#ffffff08',
gutterBackground: '#313335',
gutterForeground: '#606366',
gutterActiveForeground: '#a1a3a5',
gutterBorder: '#00000000'
},
styles: JETBRAINS_DARCULA
})
},
'intellij-light': {
dark: false,
extension: createTheme({
theme: 'light',
settings: {
background: '#ffffff',
foreground: '#000000',
caret: '#000000',
selection: '#a6d2ff',
selectionMatch: '#a6d2ff80',
lineHighlight: '#00000008',
gutterBackground: '#ffffff',
gutterForeground: '#999999',
gutterActiveForeground: '#666666',
gutterBorder: '#00000000'
},
styles: INTELLIJ_LIGHT
})
},
'monokai-pro': {
dark: true,
extension: createTheme({
theme: 'dark',
settings: {
background: '#2d2a2e',
foreground: '#fcfcfa',
caret: '#ffd866',
selection: '#5b595c',
selectionMatch: '#5b595c80',
lineHighlight: '#ffffff08',
gutterBackground: '#2d2a2e',
gutterForeground: '#727072',
gutterActiveForeground: '#fcfcfa',
gutterBorder: '#00000000'
},
styles: MONOKAI_PRO
})
}
}
/** 设置页下拉选项(`system` 置于首位) */
export const EDITOR_THEME_OPTIONS: Array<{ value: string; label: string }> = [
{ value: 'system', label: '跟随应用' },
{ value: 'vscode-dark', label: 'VS Code 深色' },
{ value: 'vscode-light', label: 'VS Code 浅色' },
{ value: 'one-dark', label: 'One Dark' },
{ value: 'dracula', label: 'Dracula' },
{ value: 'solarized-dark', label: 'Solarized 深色' },
{ value: 'solarized-light', label: 'Solarized 浅色' },
{ value: 'jetbrains-darcula', label: 'JetBrains Darcula' },
{ value: 'intellij-light', label: 'IntelliJ Light' },
{ value: 'monokai-pro', label: 'Monokai Pro' }
]
/** 亮暗成对:选深色主题但当前是浅色应用时,回落到对应浅色(避免浅底套深色) */
const THEME_PAIRS: Record<string, { light: string; dark: string }> = {
'vscode-dark': { light: 'vscode-light', dark: 'vscode-dark' },
'vscode-light': { light: 'vscode-light', dark: 'vscode-dark' },
'one-dark': { light: 'vscode-light', dark: 'one-dark' },
dracula: { light: 'vscode-light', dark: 'dracula' },
'solarized-dark': { light: 'solarized-light', dark: 'solarized-dark' },
'solarized-light': { light: 'solarized-light', dark: 'solarized-dark' },
// JetBrains 三套各自成对:Darcula ↔ IntelliJ Light(Monokai Pro 只有深色,
// 浅色侧回落到 IntelliJ Light —— 它的色系与 Monokai 的浅色变体最接近)
'jetbrains-darcula': { light: 'intellij-light', dark: 'jetbrains-darcula' },
'intellij-light': { light: 'intellij-light', dark: 'jetbrains-darcula' },
'monokai-pro': { light: 'intellij-light', dark: 'monokai-pro' },
system: { light: 'vscode-light', dark: 'vscode-dark' }
}
/** 求实际生效的主题名。 */
export function effectiveThemeName(
theme: string,
followAppTheme: boolean,
isDark: boolean
): string {
if (followAppTheme) {
const pair = THEME_PAIRS[theme] ?? THEME_PAIRS.system
return isDark ? pair.dark : pair.light
}
if (theme === 'system') return isDark ? 'vscode-dark' : 'vscode-light'
return EDITOR_THEMES[theme] ? theme : 'vscode-dark'
}
/** 解析为主题扩展。 */
export function resolveEditorTheme(
theme: string,
followAppTheme: boolean,
isDark: boolean
): Extension {
const name = effectiveThemeName(theme, followAppTheme, isDark)
return (EDITOR_THEMES[name] ?? EDITOR_THEMES['vscode-dark']).extension
}
/** 编辑器排版(字体 / 字号 / 行高 / 连字),与配色独立。 */
export function editorTypography(opts: {
fontFamily: string
fontSize: number
lineHeight: number
ligatures: boolean
}): Extension {
const family =
opts.fontFamily.trim() ||
"'Cascadia Code', 'JetBrains Mono', Consolas, 'Courier New', monospace"
return EditorView.theme({
'&': {
fontFamily: family,
fontSize: `${opts.fontSize}px`,
fontVariantLigatures: opts.ligatures ? 'contextual' : 'none'
},
'.cm-content, .cm-gutter': { lineHeight: String(opts.lineHeight) },
'.cm-scroller': { fontFamily: family }
})
}
+148
View File
@@ -0,0 +1,148 @@
/**
* `[[wikilink]]` 的显示与点击。
*
* # 为什么单独一个扩展
*
* Live Preview(`markdownLivePreview.ts`)负责**隐藏 Markdown 语法符号**,但它刻意
* 不处理 wikilink:那是 Obsidian 的扩展语法,Lezer 的 Markdown 语法树里根本没有对应
* 节点(`[[x]]` 会被解析成 `[` + `[x]` + `]` 这种普通链接片段),只能靠文本扫描识别。
* 把它塞进 Live Preview 会让那个文件同时承担两件事(语法树装饰 + 文本扫描),
* 因此独立成一层:**只做文本匹配与「可点击」**,不做任何隐藏。
*
* # 用 `Decoration.mark` 而不是 `replace`
*
* `replace` 会把 `[[` `]]` 从文档里「视觉删除」,但用户一旦把光标移进去就会看到
* 位置错乱(替换装饰与光标位置相互影响)。这里给整段加 class(`cm-wikilink`),
* 由 CSS 把方括号弱化显示 —— 既看得见语法(诚实),又一眼能认出是链接。
*
* # 点击行为
*
* 三种目标分别处理(与 Rust 侧 `resolve_link` 的判据一致):
* - `[[名字]]` / `[[名字|别名]]` → 按库内相对路径解析(`名字.md`),命中则打开;
* - `[[名字#小节]]` → 去掉 `#` 之后的部分,只按笔记名打开;
* - `[[缺失的笔记]]` → 回调交给上层(弹「新建这篇笔记」而不是静默失败)。
*/
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from '@codemirror/view'
import { type Extension, type Range } from '@codemirror/state'
/** `[[目标]]` 或 `[[目标|别名]]`;目标里不允许出现 `]`。 */
const WIKILINK_RE = /\[\[([^\]\n|]+)(?:\|([^\]\n]*))?\]\]/g
export interface WikilinkHandlers {
/** 点击一个链接(`target` 是去掉 `#` 与别名后的原始目标) */
onOpen: (target: string) => void
}
/** 解析 `[[...]]` 的内容为「笔记名 + 可选小节」。 */
export function parseWikilink(raw: string): { name: string; anchor: string } {
const [name, anchor = ''] = raw.split('#')
return { name: (name ?? '').trim(), anchor: anchor.trim() }
}
function buildDecorations(view: EditorView): DecorationSet {
const decos: Range<Decoration>[] = []
const doc = view.state.doc
for (const { from, to } of view.visibleRanges) {
// 按**行**扫:跨行不可能是 wikilink(正则里已禁 `\n`,这里再按行限制可以避免
// 在超长行上做无谓的大范围扫描)
let pos = from
while (pos <= to) {
const line = doc.lineAt(pos)
const text = doc.sliceString(line.from, line.to)
WIKILINK_RE.lastIndex = 0
let match = WIKILINK_RE.exec(text)
while (match) {
const start = line.from + match.index
const end = start + match[0].length
const raw = match[1] ?? ''
const { name } = parseWikilink(raw)
if (name) {
decos.push({
from: start,
to: end,
value: Decoration.mark({
class: 'cm-wikilink',
attributes: {
'data-wikilink': name,
title: `打开「${name}」`
}
})
})
}
match = WIKILINK_RE.exec(text)
}
if (line.to >= to) break
pos = line.to + 1
}
}
return Decoration.set(decos, true)
}
/** wikilink 外观 + 点击处理。 */
export function wikilinkExtension(handlers: WikilinkHandlers): Extension {
const theme = EditorView.baseTheme({
'.cm-wikilink': {
color: 'currentColor',
textDecoration: 'underline',
textDecorationStyle: 'dotted',
textUnderlineOffset: '3px',
cursor: 'pointer'
},
'.cm-wikilink:hover': {
backgroundColor: 'rgba(127, 127, 127, 0.18)',
borderRadius: '3px'
}
})
const plugin = ViewPlugin.fromClass(
class {
decorations: DecorationSet
constructor(view: EditorView) {
this.decorations = buildDecorations(view)
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged) {
this.decorations = buildDecorations(update.view)
}
}
},
{ decorations: value => value.decorations }
)
return [
theme,
plugin,
EditorView.domEventHandlers({
/**
* 用 `pointerdown` 而不是 `mousedown`。
*
* `mousedown` 触发时 CodeMirror 已经先把光标移到了点击位置 —— 于是
* 「点一下链接」会先改选区再跳转,看起来像「点了两次」。`pointerdown` 早于
* 选区更新,能干净地 `preventDefault()` 并直接跳转。
*
* 命中判定用 Decoration.mark 写上的 `data-wikilink` 属性(而不是按坐标反查
* 文档位置):属性是装饰渲染出来的,最可靠,也不依赖 `posAtCoords` 的取整行为。
*/
pointerdown(event, view) {
if (event.button !== 0) return false
const element = event.target as HTMLElement | null
const name = element?.getAttribute?.('data-wikilink')
if (!name) return false
// 不带修饰键时:这是「点链接」,不是「选文字」—— 抢掉事件直接跳转。
// 带 Shift/Alt 时放行,让用户可以正常拖选链接文字。
if (event.shiftKey || event.altKey) return false
event.preventDefault()
// `preventDefault` 也吃掉了浏览器默认的「点击聚焦」,因此要手动 focus
view.focus()
// 顺带把光标放到链接起点,用户跳转后再回来时位置合理
const pos = view.posAtDOM(element as HTMLElement, 0)
view.dispatch({ selection: { anchor: pos } })
handlers.onOpen(name)
return true
}
})
]
}