This commit is contained in:
zhongluofeng committed 2026-10-10 14:29:48 +08:00
1 parent ad987111a3
commit c9e61f38c5
89 files changed
+11775 -3155

No files matched your search

@@ -0,0 +1,317 @@
<script setup lang="ts">
/**
* CM6 编辑器宿主。
*
* 职责:装配 EditorView、把文档变更回写 store(含自动保存防抖)、
* 按设置热重配置(主题/排版/行号/Live Preview 开关/语言)。
*
* # 编辑器实例为什么不是响应式的
*
* EditorView 存普通变量、不进 `ref`:把它放进 Vue 响应式系统会让整个 CM state 树
* 被 Proxy 包一层,既慢又容易被误触发(CM6 的 state 是不可变对象,语义上就不该
* 被 Vue 追踪)。
*
* # 「整篇替换」的判据是 docRevision,不是内容字符串
*
* 只比对内容会把用户自己的每一次输入也当成外部替换(光标被弹回行首);
* 只比对路径又漏掉「同一篇被外部改动后重载」。因此用 store 里的自增
* `docRevision`:只有在**整篇装载**(打开/重载)时才替换文档。
*
* # 语言是异步来的
*
* 语言包按需 `import()`(见 `editor/languages.ts`)。这里 watch 的是
* `store.language`(一个 thunk),拿到后就地 `setLanguageExtension`;
* 旧语言的过期结果由 store 里的令牌机制丢弃,这里不需要再判一次。
*/
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { EditorView } from '@codemirror/view'
import { useEditorStore } from '@/stores/editorStore'
import {
createEditorState,
jumpToPosition,
reconfigureEditor,
replaceDoc,
setLanguageExtension,
type EditorConfig
} from '../editor/core'
import { editorBackground } from '../editor/themes'
import { createLogger } from '@/lib/logger'
import type { Extension } from '@codemirror/state'
const logger = createLogger('editor')
const props = defineProps<{
/** 应用当前是否深色(跟随应用主题时用于取深/浅变体) */
isDark: boolean
/** 是否启用 Live Preview */
livePreview: boolean
}>()
const emit = defineEmits<{
/** 光标移动(行号 1 起,列号 1 起) */
'cursor-moved': [line: number, column: number]
/** 点击了 `[[wikilink]]`(`target` 是去掉 `#` 与别名后的笔记名) */
'wikilink': [target: string]
}>()
const store = useEditorStore()
const hostRef = ref<HTMLDivElement | null>(null)
/**
* 编辑器外壳底色:跟随当前**实际生效**的主题。
*
* CM6 只会绘制 `.cm-editor` 覆盖到的区域,正文下方留白等仍由外壳容器显示;
* 若外壳透明就会透出窗口的 mica 背景(表现为「编辑器背景是透明的」)。
*/
const hostBackground = computed(() =>
editorBackground(String(store.settings.editorTheme), store.settings.followAppTheme, props.isDark)
)
let view: EditorView | null = null
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
/** 程序化替换文档期间抑制「变更 → 置脏」 */
let applyingDoc = false
/** 已应用的文档版本,避免重复整篇替换 */
let appliedRevision = -1
/** 语言令牌:丢弃过期的异步加载结果(与 store 里的令牌是两层保险) */
let languageSeq = 0
function currentConfig(): EditorConfig {
const s = store.settings
const large = store.fileDoc?.large ?? false
return {
livePreview: props.livePreview,
showLineNumbers: s.showLineNumbers,
tabSize: s.tabSize,
fontFamily: s.fontFamily,
fontSize: s.fontSize,
lineHeight: s.lineHeight,
ligatures: s.ligatures,
theme: String(s.editorTheme),
followAppTheme: s.followAppTheme,
isDark: props.isDark,
// 初始语言留空:语言由 applyLanguage 单独设置(见下方 watch),
// 放在这里会让每次 reconfigure 都把语言重置一遍(异步加载的结果被抹掉)
language: () => null,
largeFile: large,
autocomplete: s.autocomplete,
wikilink: s.wikilink && store.kind === 'note',
onWikilink: target => emit('wikilink', target),
// 图片预览只在库内笔记里有意义(库外文件没有库根上下文)
currentRelPath: store.kind === 'note' ? store.currentRelPath : '',
images: store.kind === 'note'
}
}
function scheduleAutosave(): void {
const ms = store.settings.autosaveMs
if (!ms) return
if (autosaveTimer) clearTimeout(autosaveTimer)
autosaveTimer = setTimeout(() => {
autosaveTimer = null
void store.saveCurrent().catch(() => undefined)
}, ms)
}
function flushAutosave(): void {
if (autosaveTimer) {
clearTimeout(autosaveTimer)
autosaveTimer = null
}
void store.saveCurrent().catch(() => undefined)
}
/** 加载并应用当前文档的语言扩展。 */
async function applyLanguage(seq: number): Promise<void> {
if (!view) return
let extension: Extension | null = null
try {
extension = await store.language()
} catch (e) {
logger.warn(`语言扩展加载失败:${String(e)}`)
}
// 期间用户又切了文档 → 这次结果作废
if (seq !== languageSeq || !view) return
setLanguageExtension(view, extension)
}
onMounted(() => {
if (!hostRef.value) return
view = new EditorView({
parent: hostRef.value,
state: createEditorState({
doc: store.content,
config: currentConfig(),
onDocChanged: doc => {
if (applyingDoc) return
store.setContent(doc)
scheduleAutosave()
},
onSelectionChanged: (line, column) => emit('cursor-moved', line, column)
})
})
appliedRevision = store.docRevision
void applyLanguage(++languageSeq)
})
/**
* 整篇装载(打开笔记 / 打开文件 / 重载):替换文档。
*
* 用 `docRevision` 而不是路径:重载同一篇时路径没变,但内容必须被换掉。
*/
watch(
() => store.docRevision,
() => {
if (!view) return
if (autosaveTimer) {
clearTimeout(autosaveTimer)
autosaveTimer = null
}
if (appliedRevision === store.docRevision) return
appliedRevision = store.docRevision
// 目标光标行要在 replaceDoc **之前**取:替换会派发 selection 变化,
// updateListener 随即把 store.cursorLine 覆盖成 1,之后再读就只剩第 1 行了。
const restoreLine = store.cursorLine
applyingDoc = true
replaceDoc(view, store.content)
// 标签切换 / 会话恢复:按 store.cursorLine 复位光标(默认第 1 行不动)
if (restoreLine > 1) {
const line = Math.min(restoreLine, view.state.doc.lines)
const pos = view.state.doc.line(line).from
view.dispatch({ selection: { anchor: pos }, scrollIntoView: false })
}
applyingDoc = false
void applyLanguage(++languageSeq)
}
)
/** 语言变化(异步加载完成 / 切换到另一种语言)。 */
watch(
() => store.language,
() => {
void applyLanguage(++languageSeq)
}
)
/**
* 切换笔记:Live Preview 的图片预览按「相对当前笔记所在目录」解析目标,
* 因此换一篇就要重建一次装饰(把新的 `currentRelPath` 交给它)。
*
* 只动 mode 与 wikilink 两个 compartment:语言由 `applyLanguage` 单独负责,
* 在这里一并 reconfigure 会把刚异步加载好的语言重置掉。
*/
watch(
() => store.currentRelPath,
() => {
if (!view) return
try {
reconfigureEditor(view, currentConfig())
} catch (e) {
logger.error(`切换笔记后重配置失败:${String(e)}`)
}
}
)
/** 设置 / 深浅 / 视图模式 / 文档类型变化:热重配置,不重建编辑器。 */
watch(
() => [store.settings, props.isDark, props.livePreview, store.fileDoc?.large],
() => {
if (!view) return
try {
reconfigureEditor(view, currentConfig())
} catch (e) {
logger.error(`重配置编辑器失败:${String(e)}`)
}
},
{ deep: true }
)
onBeforeUnmount(() => {
flushAutosave()
view?.destroy()
view = null
})
defineExpose({
focus: () => view?.focus(),
getView: () => view,
/** 大纲点击跳转 */
jumpTo: (position: number) => {
if (view) jumpToPosition(view, position)
},
/**
* 跳转到某行某列(统一搜索器的「在目录 / 库中查找」结果点击用)。
*
* 行号可能来自**稍早的**检索结果,用户在此期间可能已编辑 —— 越界一律夹到文档
* 范围内(同 `jumpToPosition` 的取舍:跳到近似位置好过整块报错)。
*/
jumpToLine: (line: number, column = 1) => {
if (!view) return
const total = view.state.doc.lines
const number = Math.max(1, Math.min(Math.floor(line), total))
const info = view.state.doc.line(number)
const anchor = Math.min(info.to, info.from + Math.max(0, column - 1))
view.dispatch({ selection: { anchor }, scrollIntoView: true })
view.focus()
}
})
</script>
<template>
<div
ref="hostRef"
class="editor-host h-full min-h-0 overflow-hidden"
:style="{ background: hostBackground }"
/>
</template>
<style scoped>
.editor-host :deep(.cm-editor) {
height: 100%;
/* 不写 background: transparent —— 让 CM6 主题自己的底色生效(见 themes.ts) */
}
.editor-host :deep(.cm-scroller) {
padding: 12px 8px 32px;
overflow: auto;
/* 滚动条与项目 ScrollArea 一致:细轨 + 圆角 thumb(同终端 xterm 的做法) */
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-track {
background: transparent;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb {
background: var(--border);
border: 3px solid transparent;
border-radius: 9999px;
background-clip: padding-box;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb:hover {
background: var(--muted-foreground);
background-clip: padding-box;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-corner {
background: transparent;
}
.editor-host :deep(.cm-editor.cm-focused) {
outline: none;
}
/* 统一搜索器的命中高亮:改用应用语义色,而不是 @codemirror/search 自带的黄/橙
—— 自带色在浅色主题下几乎看不见,也与应用观感割裂 */
.editor-host :deep(.cm-searchMatch) {
background: color-mix(in srgb, var(--primary) 26%, transparent);
outline: none;
border-radius: 2px;
}
.editor-host :deep(.cm-searchMatch.cm-searchMatch-selected) {
background: color-mix(in srgb, var(--primary) 55%, transparent);
}
/* 笔记正文里正文与标题之间留些气口,Live Preview 下更接近阅读视图 */
.editor-host :deep(.cm-content) {
padding-bottom: 24vh;
}
</style>