编辑器模块(笔记)初版
This commit is contained in:
1 parent
7e65825d3e
commit
ad987111a3
66 files changed
+17470
-283
No files matched your search
@@ -11,7 +11,8 @@ import {
|
||||
Music,
|
||||
Languages,
|
||||
SquareTerminal,
|
||||
Bot
|
||||
Bot,
|
||||
NotebookPen
|
||||
} from '@lucide/vue'
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,8 @@ export const moduleIconMap: Record<string, Component> = {
|
||||
music: Music,
|
||||
translate: Languages,
|
||||
terminal: SquareTerminal,
|
||||
dsh: Bot
|
||||
dsh: Bot,
|
||||
notes: NotebookPen
|
||||
}
|
||||
|
||||
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
||||
|
||||
@@ -14,6 +14,7 @@ import { moduleConfig as music } from './music'
|
||||
import { moduleConfig as translate } from './translate'
|
||||
import { moduleConfig as terminal } from './terminal'
|
||||
import { moduleConfig as dsh } from './dsh'
|
||||
import { moduleConfig as notes } from './notes'
|
||||
|
||||
const allModules: ModuleConfig[] = [
|
||||
proxy,
|
||||
@@ -27,7 +28,8 @@ const allModules: ModuleConfig[] = [
|
||||
music,
|
||||
translate,
|
||||
terminal,
|
||||
dsh
|
||||
dsh,
|
||||
notes
|
||||
]
|
||||
|
||||
// 启动时注册所有模块
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import {
|
||||
CircleAlert,
|
||||
Cloud,
|
||||
FolderOpen,
|
||||
HardDrive,
|
||||
@@ -327,6 +328,9 @@ const GRID = { gridTemplateColumns: '28px 36px minmax(0,1fr) 74px 28px' }
|
||||
|
||||
const listEmptyHint = computed(() => {
|
||||
if (view.value === 'feiniu') {
|
||||
// 拉取失败优先于「曲库为空」:一首都没有且请求失败时,只写「曲库为空」
|
||||
// 会被读成「NAS 上确实没歌」,而真正的原因(如服务端 unknown error)看不到
|
||||
if (store.libraryError) return store.libraryError
|
||||
return store.config.loggedIn ? '曲库为空,试试刷新或检查 NAS 曲库目录' : '请先在「设置 → 飞牛音乐连接」登录'
|
||||
}
|
||||
return '暂无本地音乐,点击「扫描本地曲库」,或到「设置 → 存储与上传」添加本地曲库目录'
|
||||
@@ -554,8 +558,11 @@ const listEmptyHint = computed(() => {
|
||||
<Loader2 class="size-4 animate-spin" /> 加载曲库…
|
||||
</div>
|
||||
<Empty v-else-if="!store.tracks.length">
|
||||
<EmptyMedia><Music2 class="size-8 text-muted-foreground" /></EmptyMedia>
|
||||
<EmptyTitle>曲库为空</EmptyTitle>
|
||||
<EmptyMedia>
|
||||
<CircleAlert v-if="store.libraryError" class="size-8 text-destructive" />
|
||||
<Music2 v-else class="size-8 text-muted-foreground" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>{{ store.libraryError ? '曲库加载失败' : '曲库为空' }}</EmptyTitle>
|
||||
<EmptyDescription>{{ listEmptyHint }}</EmptyDescription>
|
||||
</Empty>
|
||||
<Empty v-else-if="!filteredTracks.length">
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记模块主页面 —— **只做设置与管理,不做编辑**。
|
||||
*
|
||||
* 编辑发生在独立窗口(`openNotesWindow()`),本页负责:库状态与入口、库根管理、
|
||||
* 编辑器偏好。所有设置**即时生效、无保存按钮**。
|
||||
*
|
||||
* 版式遵循 `UI_DESIGN_SYSTEM.md`:
|
||||
* - 模块根 `min-h-full p-5`(滚动归属主滚动区,模块自身不建滚动容器)
|
||||
* - **不渲染 Tab 行**,Tab 注册给标题栏常驻切换器(`useModuleTabs` + `alwaysVisible`)
|
||||
* - 概览用「状态横幅 + 卡片」(§3.4);设置页用「多张 Card + 卡内标题 + `SettingRow`」
|
||||
* (与 dsh / 音乐设置页一致,`SettingGroup` 留给全局设置页那种多分组场景)
|
||||
* - 空态一律 `StateBlock`,不手写占位文案
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
BookOpen,
|
||||
CalendarDays,
|
||||
Copy,
|
||||
Database,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
FolderOpen,
|
||||
Keyboard,
|
||||
Library,
|
||||
NotebookPen,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
Tags
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { openNotesWindow } from './openWindow'
|
||||
import { notesClient } from './notesClient'
|
||||
import { EDITOR_THEME_OPTIONS } from './editor/themes'
|
||||
import WebdavPanel from './components/WebdavPanel.vue'
|
||||
import ImportExportPanel from './components/ImportExportPanel.vue'
|
||||
import NewNoteDialog from './components/NewNoteDialog.vue'
|
||||
import type { NoteSettings } from '@/types/notes'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const activeTab = ref('overview')
|
||||
// Tab 结构(规划 §8-Q5):概览 / 库 / 编辑器 / 同步。
|
||||
// 「关于」并入概览(模块信息量不足以独占一页),设置项按主题归入对应页。
|
||||
useModuleTabs(
|
||||
'notes',
|
||||
activeTab,
|
||||
[
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'library', label: '库' },
|
||||
{ value: 'editor', label: '编辑器' },
|
||||
{ value: 'sync', label: '同步' }
|
||||
],
|
||||
{ alwaysVisible: true }
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void store.init()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
store.disposeListeners()
|
||||
})
|
||||
|
||||
// ===== 全局快捷键请求(Rust 只发事件,这里负责开对话框 / 开窗口)=====
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
watch(
|
||||
() => store.newNoteRequest,
|
||||
() => {
|
||||
activeTab.value = 'overview'
|
||||
newNoteOpen.value = true
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => store.openEditorRequest,
|
||||
() => void openEditor()
|
||||
)
|
||||
|
||||
/**
|
||||
* 冷启动的「用 Thing 打开」:命令行留下的文件路径取到后,直接开一个笔记窗口。
|
||||
*
|
||||
* **只在主窗口做**:笔记窗口内部也会渲染本模块(`#notes-window` 是独立入口,
|
||||
* 不走这里),但它的 hash 里已经带了 `?path=`,由 `NotesWindow` 自己打开 ——
|
||||
* 这里再响应一次就会开第二个窗口。
|
||||
*/
|
||||
watch(
|
||||
() => store.pendingOpenPath,
|
||||
path => {
|
||||
if (!path || isNotesWindow()) return
|
||||
void openNotesWindow({ path }).catch(e => toast.error(`打开文件失败:${String(e)}`))
|
||||
}
|
||||
)
|
||||
|
||||
/** 当前是否运行在笔记独立窗口里(hash 形如 `#notes-window?...`)。 */
|
||||
function isNotesWindow(): boolean {
|
||||
return window.location.hash.startsWith(`#${WINDOWS.notesWindow}`)
|
||||
}
|
||||
|
||||
// ===== 设置写入(即时生效) =====
|
||||
function commit(patch: Partial<NoteSettings>): void {
|
||||
void store.patchSettings(patch)
|
||||
}
|
||||
|
||||
function onNumber(
|
||||
patchKey: 'fontSize' | 'lineHeight' | 'tabSize' | 'autosaveMs' | 'maxFileSizeMb',
|
||||
event: Event
|
||||
) {
|
||||
const value = Number((event.target as HTMLInputElement).value)
|
||||
if (!Number.isFinite(value)) return
|
||||
commit({ [patchKey]: value } as Partial<NoteSettings>)
|
||||
}
|
||||
|
||||
// ===== 库根 =====
|
||||
const resetRootOpen = ref(false)
|
||||
|
||||
async function pickLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({ directory: true, multiple: false, title: '选择笔记库目录' })
|
||||
if (typeof selected !== 'string') return
|
||||
await store.setLibraryRoot(selected)
|
||||
toast.success('已切换笔记库')
|
||||
} catch (e) {
|
||||
toast.error(`切换失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resetLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
await store.setLibraryRoot(null)
|
||||
toast.success('已恢复默认库目录')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
resetRootOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revealRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await openPath(store.libraryRoot)
|
||||
} catch (e) {
|
||||
toast.error(`打开目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(store.libraryRoot)
|
||||
toast.success('库路径已复制')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function openEditor(): Promise<void> {
|
||||
try {
|
||||
await openNotesWindow()
|
||||
} catch (e) {
|
||||
toast.error(`打开编辑器失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 在编辑器窗口里直接打开磁盘文件(路径来自系统对话框,选择即授权)。 */
|
||||
async function openExternalFile(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: '打开文件'
|
||||
})
|
||||
if (typeof selected !== 'string') return
|
||||
await notesClient.authorizeFile(selected)
|
||||
await openNotesWindow({ path: selected })
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const rebuilding = ref(false)
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
rebuilding.value = true
|
||||
try {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
} catch (e) {
|
||||
toast.error(`重建索引失败:${String(e)}`)
|
||||
} finally {
|
||||
rebuilding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开今天的日记(不存在则按日记模板创建)。 */
|
||||
async function openDailyNote(): Promise<void> {
|
||||
try {
|
||||
await store.openDailyNote()
|
||||
await openNotesWindow({ relPath: store.currentRelPath })
|
||||
} catch (e) {
|
||||
toast.error(`打开日记失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const noteCount = computed(() => store.info?.noteCount ?? 0)
|
||||
const rootKind = computed(() => (store.info?.isCustom ? '自定义' : '默认'))
|
||||
/** 索引状态摘要(横幅右侧;索引未就绪时显示占位) */
|
||||
const indexSummary = computed(() => {
|
||||
const stats = store.indexStats
|
||||
if (!stats) return '索引准备中'
|
||||
return `索引 ${stats.noteCount} / 文件 ${stats.fileCount}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-full p-5">
|
||||
<Tabs v-model="activeTab" class="flex min-h-full w-full flex-col">
|
||||
<!-- ===== 概览 ===== -->
|
||||
<TabsContent value="overview" class="tab-animate">
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- 状态横幅:状态区 → 指标区 → 操作区(§3.4) -->
|
||||
<Card class="!py-0 !gap-0">
|
||||
<CardContent class="flex flex-wrap items-center gap-x-6 gap-y-3 px-4 py-4">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span
|
||||
v-if="!store.info"
|
||||
class="flex items-center gap-1.5 text-[13px] text-muted-foreground"
|
||||
>
|
||||
<span class="size-2 rounded-full bg-muted-foreground" />加载中
|
||||
</span>
|
||||
<template v-else>
|
||||
<span class="flex items-center gap-1.5 text-[13px] text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已就绪
|
||||
</span>
|
||||
</template>
|
||||
<span class="text-[13px] text-fg-secondary">本地 Markdown 笔记库</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">笔记数</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ noteCount }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库类型</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ rootKind }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库目录</span>
|
||||
<span class="truncate font-mono text-[13px] text-fg-secondary">
|
||||
{{ store.libraryRoot || '—' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-28 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">索引</span>
|
||||
<span class="truncate text-[13px] text-fg-secondary">
|
||||
{{ store.indexing ? '同步中…' : indexSummary }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="ml-auto flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="outline" @click="openDailyNote">
|
||||
<CalendarDays class="size-3.5" />今日日记
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />打开目录
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" @click="openExternalFile">
|
||||
<FolderOpen class="size-3.5" />打开文件
|
||||
</Button>
|
||||
<Button size="sm" @click="openEditor">
|
||||
<NotebookPen class="size-3.5" />打开编辑器
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 最近打开 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<BookOpen class="size-4 text-primary" />
|
||||
最近打开
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<StateBlock
|
||||
v-if="!store.recent.length"
|
||||
variant="empty"
|
||||
title="还没有打开过笔记"
|
||||
description="点上方「打开编辑器」新建或打开一篇笔记"
|
||||
:min-height="140"
|
||||
/>
|
||||
<div v-else class="flex flex-col divide-y divide-divider">
|
||||
<button
|
||||
v-for="item in store.recent"
|
||||
:key="item.relPath"
|
||||
type="button"
|
||||
class="flex min-h-13 items-center gap-4 py-2 text-left transition-colors duration-150 outline-none hover:text-primary focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
@click="openNotesWindow({ relPath: item.relPath })"
|
||||
>
|
||||
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="truncate text-[13px] text-foreground">
|
||||
{{ item.name.replace(/\.md$/i, '') }}
|
||||
</span>
|
||||
<span class="truncate text-xs text-muted-foreground">{{ item.relPath }}</span>
|
||||
</span>
|
||||
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 库(库根 / 索引 / 导入导出) ===== -->
|
||||
<TabsContent value="library" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 笔记库 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Library class="size-4 text-primary" />
|
||||
笔记库
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
笔记以 Markdown 文件形式保存在该目录;切换库只改变指向,原目录内容不会被移动
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="库目录" :description="store.libraryRoot || '—'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="copyRoot">
|
||||
<Copy class="size-3.5" />复制
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />浏览
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="pickLibraryRoot">
|
||||
<NotebookPen class="size-3.5" />切换…
|
||||
</Button>
|
||||
<Button
|
||||
v-if="store.info?.isCustom"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="resetRootOpen = true"
|
||||
>
|
||||
恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重新扫描" description="在应用外新增或修改文件后,手动刷新库内容">
|
||||
<Button variant="outline" size="sm" @click="store.refreshLibrary()">
|
||||
<RefreshCw class="size-3.5" />刷新
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 索引与检索(P1) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Database class="size-4 text-primary" />
|
||||
索引与检索
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
全文检索与标签依赖一份 SQLite 索引(存放在库内 <code class="font-mono">.notes/</code>)。
|
||||
它只是加速层:删掉也能从 Markdown 文件完整重建,不影响笔记本身。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="索引状态"
|
||||
:description="store.indexStats?.dbPath || '尚未建立索引'"
|
||||
>
|
||||
<div class="flex items-center gap-3 text-[13px] text-fg-secondary">
|
||||
<span class="tabular-nums">笔记 {{ store.indexStats?.noteCount ?? 0 }}</span>
|
||||
<span class="tabular-nums">文件 {{ store.indexStats?.fileCount ?? 0 }}</span>
|
||||
<span class="flex items-center gap-1 tabular-nums">
|
||||
<Tags class="size-3.5" />{{ store.indexStats?.tagCount ?? 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重建索引" description="按文件重新解析标题、标签与双链(库很大时需要一点时间)">
|
||||
<Button variant="outline" size="sm" :disabled="rebuilding || store.indexing" @click="rebuildIndex">
|
||||
<RefreshCw class="size-3.5" :class="rebuilding && 'animate-spin'" />重建
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="外部改动监听" description="库内文件在应用外被修改时提醒(监听始终开启)">
|
||||
<span class="flex items-center gap-1.5 text-xs text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已启用
|
||||
</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="单文件大小上限"
|
||||
description="超过该大小的文件会关闭所见即所得 / 折叠 / 补全,单位 MB"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="store.settings.maxFileSizeMb"
|
||||
@change="onNumber('maxFileSizeMb', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 导入 / 导出(P2) -->
|
||||
<ImportExportPanel />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 编辑器 ===== -->
|
||||
<TabsContent value="editor" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 编辑器外观 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Palette class="size-4 text-primary" />
|
||||
编辑器外观
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="配色方案" description="跟随应用时按应用深浅自动选深/浅变体" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => commit({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="跟随应用深浅" description="开关打开时,配色方案仅作为取色基准">
|
||||
<Switch
|
||||
:model-value="store.settings.followAppTheme"
|
||||
@update:model-value="v => commit({ followAppTheme: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体族" description="留空使用内置等宽字体栈" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.fontFamily"
|
||||
placeholder="Cascadia Code, Consolas, …"
|
||||
@change="(e: Event) => commit({ fontFamily: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字号" description="单位 px" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="10"
|
||||
max="32"
|
||||
:model-value="store.settings.fontSize"
|
||||
@change="onNumber('fontSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="行高" description="倍数,建议 1.5 ~ 2.0" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="1"
|
||||
max="3"
|
||||
:model-value="store.settings.lineHeight"
|
||||
@change="onNumber('lineHeight', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体连字" description="启用 ligatures(如 => 显示为箭头)">
|
||||
<Switch
|
||||
:model-value="store.settings.ligatures"
|
||||
@update:model-value="v => commit({ ligatures: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="显示行号">
|
||||
<Switch
|
||||
:model-value="store.settings.showLineNumbers"
|
||||
@update:model-value="v => commit({ showLineNumbers: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="显示大纲"
|
||||
description="在编辑器侧栏显示标题树(Ctrl+Shift+L 可临时切换)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showOutline"
|
||||
@update:model-value="v => commit({ showOutline: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 编辑器行为 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Eye class="size-4 text-primary" />
|
||||
编辑器行为
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="所见即所得"
|
||||
description="Live Preview:语法符号在非光标行隐藏、光标行显形;关闭后为纯源码 + 高亮"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.livePreview"
|
||||
@update:model-value="v => commit({ livePreview: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="默认视图" description="新开编辑器窗口时的初始视图" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.defaultView)"
|
||||
@update:model-value="v => commit({ defaultView: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="wysiwyg">所见即所得</SelectItem>
|
||||
<SelectItem value="source">源码</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="自动保存" description="停止输入后延迟保存,单位毫秒;0 = 关闭(仅 Ctrl+S)" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="10000"
|
||||
step="100"
|
||||
:model-value="store.settings.autosaveMs"
|
||||
@change="onNumber('autosaveMs', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="Tab 宽度" description="按空格数计" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="8"
|
||||
:model-value="store.settings.tabSize"
|
||||
@change="onNumber('tabSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="自动补全"
|
||||
description="括号自动闭合与代码补全(大文件会临时关闭)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.autocomplete"
|
||||
@update:model-value="v => commit({ autocomplete: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="识别 [[双链]]"
|
||||
description="按 Obsidian 语义解析双链并写入索引(反链面板留待后续)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.wikilink"
|
||||
@update:model-value="v => commit({ wikilink: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="复用文档窗口"
|
||||
description="同一篇笔记重复打开时聚焦已有窗口,而不是开出第二个(两个窗口会自动保存,后写的覆盖先写的)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.reuseWindow"
|
||||
@update:model-value="v => commit({ reuseWindow: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="导出时高亮代码"
|
||||
description="关闭后导出的 HTML 里代码块是纯黑白,适合黑白打印机"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.exportHighlight"
|
||||
@update:model-value="v => commit({ exportHighlight: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="新建时选模板"
|
||||
description="关闭后用上次选中的模板直接新建"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showTemplatePicker"
|
||||
@update:model-value="v => commit({ showTemplatePicker: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 全局快捷键(P2) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Keyboard class="size-4 text-primary" />
|
||||
全局快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
留空即不注册。格式如 <code class="font-mono">Ctrl+Shift+N</code>;与本应用其它模块
|
||||
的快捷键冲突时会注册失败(日志里会写明是谁占了)。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="新建笔记" description="任意界面按下都打开新建对话框" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.newNoteShortcut"
|
||||
placeholder="Ctrl+Shift+N"
|
||||
@change="(e: Event) => commit({ newNoteShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="打开编辑器窗口" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.openEditorShortcut"
|
||||
placeholder="未设置"
|
||||
@change="(e: Event) => commit({ openEditorShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 同步(WebDAV) ===== -->
|
||||
<TabsContent value="sync" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<WebdavPanel />
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="resetRootOpen"
|
||||
title="恢复默认库目录"
|
||||
description="笔记不会丢失:仅把库根指回应用数据目录下的默认位置,原目录内容保持不动。"
|
||||
confirm-text="恢复默认"
|
||||
@confirm="resetLibraryRoot"
|
||||
/>
|
||||
|
||||
<!-- 全局快捷键(Ctrl+Shift+N)触发的新建对话框:落在库根 -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" dir-rel="" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,525 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记独立窗口根组件(`#notes-window`)。
|
||||
*
|
||||
* # 为什么是独立窗口
|
||||
*
|
||||
* 主模块页只做设置与管理;真正的编辑发生在这里 —— 可多开、可拖到副屏,
|
||||
* 编辑体验接近一个独立应用(与终端 / 下载 / 翻译窗口同一范式)。
|
||||
*
|
||||
* # 生命周期要点
|
||||
*
|
||||
* - 窗口由 `openWindow.ts` **隐藏创建**,本组件 `applyTheme` 之后才 `show`
|
||||
* (否则深色模式下会先闪一下纯白窗口);
|
||||
* - 自带一份 Pinia(`main.ts` 里为独立窗口注入),store 通过 IPC 与 Rust 对齐;
|
||||
* - 监听 `notes-settings` / `notes-library-changed` / `notes-file-changed`
|
||||
* 实现与主窗口及外部编辑器的实时同步。
|
||||
*
|
||||
* # P1 新增的三种「异步危险」
|
||||
*
|
||||
* 1. **外部改动**:库文件在别的编辑器里被改了,而我们这边有未保存内容 —— 不能
|
||||
* 静默重载(会丢掉用户刚敲的字),弹出横幅让用户选;
|
||||
* 2. **打开库外文件**:路径来自系统对话框,必须先 `authorize` 才能写回;
|
||||
* 3. **大文件**:超过阈值时关掉 Live Preview / 折叠 / 补全(降级在 `core.ts`,
|
||||
* 这里只负责把 `large` 标记和提示露出来)。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { Effect, EffectState, getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { AlertTriangle, Minus, NotebookPen, PanelLeft, Square, X } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { ConfirmDialog, StateBlock } from '@/components/common'
|
||||
import { STORAGE_KEYS } from '@/lib/constants'
|
||||
import { applyStoredAccent } from '@/lib/theme'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import LibrarySidebar from './components/LibrarySidebar.vue'
|
||||
import EditorHost from './components/EditorHost.vue'
|
||||
import EditorToolbar from './components/EditorToolbar.vue'
|
||||
import QuickOpen from './components/QuickOpen.vue'
|
||||
import type { NoteViewMode } from '@/types/notes'
|
||||
import type { Command, EditorView } from '@codemirror/view'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
const win = getCurrentWindow()
|
||||
const store = useNotesStore()
|
||||
|
||||
const isDark = ref(false)
|
||||
const sidebarVisible = ref(true)
|
||||
const viewMode = ref<NoteViewMode>('wysiwyg')
|
||||
const hostRef = ref<InstanceType<typeof EditorHost> | null>(null)
|
||||
const sidebarRef = ref<InstanceType<typeof LibrarySidebar> | null>(null)
|
||||
const quickOpen = ref(false)
|
||||
const cursorLine = ref(0)
|
||||
const cursorColumn = ref(1)
|
||||
|
||||
// ===== 主题与窗口效果(与主应用同步) =====
|
||||
function readMainTheme(): { theme: string; effect: string } {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||
if (raw) {
|
||||
const s = JSON.parse(raw) as { theme?: string; effect?: string }
|
||||
return { theme: s.theme ?? 'system', effect: s.effect ?? 'mica' }
|
||||
}
|
||||
} catch {
|
||||
/* 设置不可读时按默认处理 */
|
||||
}
|
||||
return { theme: 'system', effect: 'mica' }
|
||||
}
|
||||
|
||||
function resolveIsDark(theme: string): boolean {
|
||||
if (theme === 'dark') return true
|
||||
if (theme === 'light') return false
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
async function applyTheme(): Promise<void> {
|
||||
const root = document.documentElement
|
||||
const { theme, effect } = readMainTheme()
|
||||
|
||||
try {
|
||||
await win.setTheme(theme === 'system' ? null : (theme as 'dark' | 'light'))
|
||||
} catch {
|
||||
/* 平台不支持时忽略 */
|
||||
}
|
||||
|
||||
const dark = resolveIsDark(theme)
|
||||
isDark.value = dark
|
||||
root.classList.remove('dark', 'effect-mica', 'effect-acrylic', 'effect-normal')
|
||||
root.classList.add(`effect-${effect}`)
|
||||
if (dark) root.classList.add('dark')
|
||||
applyStoredAccent(root, dark ? 'dark' : 'light', STORAGE_KEYS.appSettings)
|
||||
|
||||
try {
|
||||
// setEffects 会直接覆盖当前效果,无需 clearEffects(那个命令未在 capability 中授权)
|
||||
if (effect === 'mica') {
|
||||
await win.setEffects({
|
||||
effects: [Effect.Mica],
|
||||
state: EffectState.FollowsWindowActiveState,
|
||||
color: dark ? [30, 41, 59, 0] : [248, 250, 252, 0]
|
||||
})
|
||||
await win.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else if (effect === 'acrylic') {
|
||||
await win.setEffects({
|
||||
effects: [Effect.Acrylic],
|
||||
state: EffectState.FollowsWindowActiveState,
|
||||
color: dark ? [30, 41, 59, 0] : [248, 250, 252, 0]
|
||||
})
|
||||
await win.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else {
|
||||
const bg = dark ? '#16161a' : '#ffffff'
|
||||
await win.setBackgroundColor(bg)
|
||||
root.style.setProperty('--popup-bg', bg)
|
||||
}
|
||||
} catch {
|
||||
/* 忽略效果设置失败 */
|
||||
}
|
||||
}
|
||||
|
||||
const darkMedia = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const onThemeChange = () => void applyTheme()
|
||||
const onStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEYS.appSettings) void applyTheme()
|
||||
}
|
||||
|
||||
// ===== 窗口控制 =====
|
||||
const doMinimize = () => win.minimize().catch(() => undefined)
|
||||
const doToggleMaximize = () => win.toggleMaximize().catch(() => undefined)
|
||||
|
||||
/** 关闭确认(有未保存改动时) */
|
||||
const closeConfirmOpen = ref(false)
|
||||
|
||||
async function doClose(): Promise<void> {
|
||||
if (store.dirty) {
|
||||
closeConfirmOpen.value = true
|
||||
return
|
||||
}
|
||||
await forceClose()
|
||||
}
|
||||
|
||||
async function forceClose(): Promise<void> {
|
||||
try {
|
||||
await store.saveCurrent()
|
||||
} catch {
|
||||
/* 保存失败不阻塞关闭;脏数据仍在编辑器里 */
|
||||
}
|
||||
win.close().catch(() => undefined)
|
||||
}
|
||||
|
||||
const startDrag = () => {
|
||||
win.startDragging().catch(() => undefined)
|
||||
}
|
||||
|
||||
// ===== 编辑器命令转发 =====
|
||||
function applyCommand(command: Command): void {
|
||||
const view = hostRef.value?.getView() as EditorView | null | undefined
|
||||
if (view) command(view)
|
||||
}
|
||||
|
||||
async function doSave(): Promise<void> {
|
||||
try {
|
||||
await store.saveCurrent()
|
||||
toast.success('已保存')
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function onCursorMoved(line: number, column: number): void {
|
||||
cursorLine.value = line
|
||||
cursorColumn.value = column
|
||||
sidebarRef.value?.setCursorLine(line)
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击 `[[wikilink]]`。
|
||||
*
|
||||
* 目标是**库内相对路径**(`名字.md`)—— 与 Rust 侧 `resolve_link` 的「按名字 + 相对
|
||||
* 当前目录」判据保持一致。找不到就按这个名字在当前笔记所在目录新建一篇:
|
||||
* 「先写链接、后补内容」是双链笔记的标准用法,静默失败会让这个习惯立刻失效。
|
||||
*/
|
||||
async function onWikilink(target: string): Promise<void> {
|
||||
const name = target.trim()
|
||||
if (!name) return
|
||||
const dir = store.currentRelPath.split('/').slice(0, -1).join('/')
|
||||
const relPath = dir ? `${dir}/${name}.md` : `${name}.md`
|
||||
if (store.entries.some(entry => entry.relPath === relPath)) {
|
||||
await store.openNote(relPath)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.createNote(dir, name)
|
||||
toast.success(`已新建「${name}」`)
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 打开库外文件 =====
|
||||
async function doOpenFile(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: '打开文件',
|
||||
filters: [
|
||||
{ name: '文本 / 代码', extensions: ['md', 'txt', 'json', 'yaml', 'yml', 'toml', 'ini', 'log', 'csv'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
})
|
||||
if (typeof selected !== 'string') return
|
||||
await store.openFile(selected)
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 外部改动 =====
|
||||
const externalConfirmOpen = ref(false)
|
||||
|
||||
async function reloadFromExternal(): Promise<void> {
|
||||
try {
|
||||
await store.reloadCurrent()
|
||||
store.externalChange = null
|
||||
toast.success('已重新载入')
|
||||
} catch (e) {
|
||||
toast.error(`重新载入失败:${String(e)}`)
|
||||
} finally {
|
||||
externalConfirmOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 「保留我的改动」:只清掉提示,磁盘上的版本仍是外部那份(用户下次保存会覆盖它) */
|
||||
function keepLocal(): void {
|
||||
store.externalChange = null
|
||||
externalConfirmOpen.value = false
|
||||
}
|
||||
|
||||
// ===== 全局按键(窗口级) =====
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const mod = event.ctrlKey || event.metaKey
|
||||
if (!mod) return
|
||||
const key = event.key.toLowerCase()
|
||||
|
||||
if (key === 's') {
|
||||
event.preventDefault()
|
||||
void doSave()
|
||||
} else if (key === 'p' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
quickOpen.value = true
|
||||
} else if (key === 'o') {
|
||||
event.preventDefault()
|
||||
void doOpenFile()
|
||||
} else if (key === 'f' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showSearch()
|
||||
} else if (key === 'm' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
viewMode.value = viewMode.value === 'wysiwyg' ? 'source' : 'wysiwyg'
|
||||
} else if (key === 'l' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showOutline()
|
||||
} else if (key === 'n' && event.shiftKey) {
|
||||
// 与全局快捷键同义:窗口内有焦点时在本窗口直接开对话框,不必绕 Rust 一圈
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showNewNote()
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 hash 查询串解析初始要打开的文档(`file` = 库内笔记,`path` = 库外文件)。 */
|
||||
function initialTarget(): { relPath: string; path: string } {
|
||||
const hash = window.location.hash
|
||||
const queryIndex = hash.indexOf('?')
|
||||
if (queryIndex < 0) return { relPath: '', path: '' }
|
||||
const params = new URLSearchParams(hash.slice(queryIndex + 1))
|
||||
return { relPath: params.get('file') ?? '', path: params.get('path') ?? '' }
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
darkMedia.addEventListener('change', onThemeChange)
|
||||
window.addEventListener('storage', onStorageChange)
|
||||
window.addEventListener('keydown', onKeydown, true)
|
||||
|
||||
// 主题 → 显示(窗口是隐藏创建的,这一步之后用户才第一次看到它)
|
||||
await applyTheme()
|
||||
try {
|
||||
await win.show()
|
||||
await win.setFocus()
|
||||
} catch (e) {
|
||||
logger.warn(`显示笔记窗口失败:${String(e)}`)
|
||||
}
|
||||
|
||||
await store.init()
|
||||
viewMode.value = store.settings.defaultView === 'source' ? 'source' : 'wysiwyg'
|
||||
|
||||
const { relPath: targetRel, path: targetPath } = initialTarget()
|
||||
if (targetRel) {
|
||||
await store.openNote(targetRel)
|
||||
} else if (targetPath) {
|
||||
try {
|
||||
await store.openFile(targetPath)
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
} else if (store.recent.length) {
|
||||
await store.openNote(store.recent[0].relPath)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
darkMedia.removeEventListener('change', onThemeChange)
|
||||
window.removeEventListener('storage', onStorageChange)
|
||||
window.removeEventListener('keydown', onKeydown, true)
|
||||
store.disposeListeners()
|
||||
})
|
||||
|
||||
// ===== 状态栏 =====
|
||||
const title = computed(() => store.currentName || '笔记')
|
||||
const statusText = computed(() => {
|
||||
if (store.saving) return '保存中…'
|
||||
if (store.dirty) return '未保存'
|
||||
if (!store.hasDocument) return '未打开文档'
|
||||
return '已保存'
|
||||
})
|
||||
/** 编码 / 换行只在库外文件里有意义(笔记永远是 UTF-8 + 换行跟随原文) */
|
||||
const encodingLabel = computed(() => (store.kind === 'file' ? store.fileDoc?.encoding ?? '' : ''))
|
||||
const eolLabel = computed(() => {
|
||||
if (store.kind !== 'file') return ''
|
||||
return store.fileDoc?.eol === 'crlf' ? 'CRLF' : 'LF'
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="notes-window flex h-screen flex-col overflow-hidden text-foreground">
|
||||
<!-- 自绘标题栏:仅标题区是拖动区,右侧按钮区不是(否则鼠标事件被拖动拦截) -->
|
||||
<header class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<div
|
||||
class="flex h-full min-w-0 flex-1 items-center gap-2 pl-1"
|
||||
data-tauri-drag-region
|
||||
@mousedown="startDrag"
|
||||
>
|
||||
<NotebookPen class="size-3.5 shrink-0 text-primary" />
|
||||
<span class="pointer-events-none truncate text-xs font-medium">{{ title }}</span>
|
||||
<span
|
||||
v-if="store.kind === 'file'"
|
||||
class="pointer-events-none shrink-0 rounded-sm bg-muted px-1 text-[10px] text-fg-secondary"
|
||||
>
|
||||
文件
|
||||
</span>
|
||||
<span v-if="store.dirty" class="size-1.5 shrink-0 rounded-full bg-primary" />
|
||||
</div>
|
||||
|
||||
<div class="w-px h-4 bg-border shrink-0" />
|
||||
|
||||
<TooltipProvider :delay-duration="400">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="sidebarVisible = !sidebarVisible">
|
||||
<PanelLeft class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">切换侧栏</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="doMinimize">
|
||||
<Minus class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">最小化</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="doToggleMaximize">
|
||||
<Square class="size-3" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">最大化 / 还原</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="hover:!bg-destructive hover:!text-destructive-foreground"
|
||||
@click="doClose"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">关闭窗口</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</header>
|
||||
|
||||
<!-- 工具栏 -->
|
||||
<EditorToolbar
|
||||
:apply="applyCommand"
|
||||
:view-mode="viewMode"
|
||||
:dirty="store.dirty"
|
||||
:saving="store.saving"
|
||||
:name="store.currentName"
|
||||
@update:view-mode="viewMode = $event"
|
||||
@save="doSave"
|
||||
@open-file="doOpenFile"
|
||||
@quick-open="quickOpen = true"
|
||||
/>
|
||||
|
||||
<!-- 外部改动提示(有未保存改动时才会出现) -->
|
||||
<div
|
||||
v-if="store.externalChange"
|
||||
class="flex shrink-0 items-center gap-2 border-b border-border bg-warning-soft px-3 py-1.5 text-xs"
|
||||
>
|
||||
<AlertTriangle class="size-3.5 shrink-0 text-warning" />
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
该文件已在应用外被
|
||||
{{ store.externalChange.kind === 'removed' ? '删除' : '修改' }}
|
||||
—— 你的未保存改动仍在编辑器里
|
||||
</span>
|
||||
<Button variant="outline" size="sm" @click="keepLocal">保留我的改动</Button>
|
||||
<Button variant="outline" size="sm" @click="externalConfirmOpen = true">查看并重载</Button>
|
||||
</div>
|
||||
|
||||
<!-- 大文件降级提示 -->
|
||||
<div
|
||||
v-if="store.fileDoc?.large"
|
||||
class="flex shrink-0 items-center gap-2 border-b border-border bg-muted px-3 py-1 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<AlertTriangle class="size-3 shrink-0" />
|
||||
文件较大,已关闭「所见即所得 / 折叠 / 自动补全」以保证输入流畅
|
||||
</div>
|
||||
|
||||
<!-- 主体:侧栏 + 编辑器 -->
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<LibrarySidebar
|
||||
v-if="sidebarVisible"
|
||||
ref="sidebarRef"
|
||||
@open="store.openNote($event)"
|
||||
@jump="hostRef?.jumpTo($event)"
|
||||
/>
|
||||
<main class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div v-if="!store.hasDocument" class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<StateBlock
|
||||
variant="empty"
|
||||
title="未打开文档"
|
||||
description="从左侧选择一篇笔记、新建一篇,或用 Ctrl+O 打开磁盘上的文件"
|
||||
:min-height="200"
|
||||
>
|
||||
<template #action>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" size="sm" @click="sidebarVisible = true">
|
||||
<PanelLeft class="size-3.5" />打开侧栏
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="doOpenFile">打开文件…</Button>
|
||||
</div>
|
||||
</template>
|
||||
</StateBlock>
|
||||
</div>
|
||||
<EditorHost
|
||||
v-show="store.hasDocument"
|
||||
ref="hostRef"
|
||||
:is-dark="isDark"
|
||||
:live-preview="viewMode === 'wysiwyg'"
|
||||
@cursor-moved="onCursorMoved"
|
||||
@wikilink="onWikilink"
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- 状态栏 -->
|
||||
<footer
|
||||
class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<span>{{ statusText }}</span>
|
||||
<span v-if="store.hasDocument" class="tabular-nums">
|
||||
{{ store.wordCount }} 字 · {{ store.lineCount }} 行
|
||||
</span>
|
||||
<span v-if="store.hasDocument" class="tabular-nums">行 {{ cursorLine }} : {{ cursorColumn }}</span>
|
||||
<span v-if="store.kind === 'note'" class="rounded-sm bg-muted px-1.5 py-0.5 text-[10px]">
|
||||
{{ store.languageLabel }}
|
||||
</span>
|
||||
<span v-if="encodingLabel" class="uppercase">{{ encodingLabel }}</span>
|
||||
<span v-if="eolLabel">{{ eolLabel }}</span>
|
||||
<span class="ml-auto truncate">{{ store.fileDoc?.path || store.libraryRoot }}</span>
|
||||
</footer>
|
||||
|
||||
<!-- 快速打开(Ctrl+P) -->
|
||||
<QuickOpen v-model:open="quickOpen" @select="store.openNote($event)" />
|
||||
|
||||
<!-- 关闭确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="closeConfirmOpen"
|
||||
title="有未保存的改动"
|
||||
description="关闭窗口会丢失这些改动(自动保存会对未保存内容做最后一次尝试)。"
|
||||
confirm-text="保存并关闭"
|
||||
@confirm="forceClose"
|
||||
/>
|
||||
|
||||
<!-- 重载确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="externalConfirmOpen"
|
||||
title="重新载入将丢弃未保存的改动"
|
||||
description="磁盘上的版本会覆盖编辑器里的内容,你当前的改动无法恢复。"
|
||||
variant="danger"
|
||||
confirm-text="丢弃并重载"
|
||||
@confirm="reloadFromExternal"
|
||||
/>
|
||||
|
||||
<Toaster />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 窗口根容器:mica/acrylic 下透明,普通模式用不透明底色(--popup-bg 由 applyTheme 写入) */
|
||||
.notes-window {
|
||||
background: var(--popup-bg, var(--background));
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 反链面板:当前笔记的**出链**与**入链**。
|
||||
*
|
||||
* # 数据从哪来
|
||||
*
|
||||
* 全部来自 SQLite 索引的 `links` 表(写入索引时已把 `[[名字]]` 按 Obsidian 语义
|
||||
* 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `notes_backlinks`
|
||||
* 调用就把两侧都取回。
|
||||
*
|
||||
* # 未解析链接为什么值得显示
|
||||
*
|
||||
* `[[还不存在的笔记]]` 在 Obsidian 里是一个**新建入口**,不是错误。面板把它单独列在
|
||||
* 「未解析」分组下并允许一键创建 —— 这正是双链笔记「先写链接、后补内容」的用法。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ArrowUpRight, Link2, Link2Off, Loader2, RefreshCw } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import type { NoteBacklinks, NoteLink } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前笔记的库内相对路径(空串 = 没有笔记,面板显示空态) */
|
||||
relPath: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 打开某篇笔记 */
|
||||
open: [relPath: string]
|
||||
/** 已用某个名字新建了一篇(未解析链接的一键创建);上层据此展开树 */
|
||||
create: [name: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const data = ref<NoteBacklinks | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
/** 已解析的出链 */
|
||||
const resolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.resolved)
|
||||
)
|
||||
/** 未解析的出链(可一键新建) */
|
||||
const unresolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => !item.resolved && item.kind !== 'url')
|
||||
)
|
||||
/** 外部链接(`[](https://…)`):只展示不可跳转到库内 */
|
||||
const externalOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.kind === 'url')
|
||||
)
|
||||
|
||||
async function load(): Promise<void> {
|
||||
if (!props.relPath) {
|
||||
data.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
data.value = await notesClient.backlinks(props.relPath)
|
||||
} catch (e) {
|
||||
// 索引还没建立时这里会失败:不是错误,只是「暂时没有数据」
|
||||
data.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.relPath, store.indexStats?.noteCount],
|
||||
() => void load(),
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
/** 点击未解析链接:按名字新建一篇(`createNote` 会顺带把它打开)。 */
|
||||
async function createMissing(link: NoteLink): Promise<void> {
|
||||
try {
|
||||
await store.createNote(currentDirOf(props.relPath), link.target)
|
||||
emit('create', link.target)
|
||||
await load()
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新笔记落在当前笔记所在目录(与 Obsidian「同目录优先」的习惯一致)。 */
|
||||
function currentDirOf(relPath: string): string {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
function targetOf(link: NoteLink): string {
|
||||
// URL 类型直接交给系统浏览器由上层处理;这里统一用 relPath(可能为空)
|
||||
return link.relPath || link.target
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<Link2 class="size-3" />
|
||||
<span>双链</span>
|
||||
<span class="ml-auto tabular-nums">
|
||||
被 {{ data?.incomingSources ?? 0 }} 篇引用 · 出链 {{ resolvedOutgoing.length + unresolvedOutgoing.length }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="刷新"
|
||||
@click="load"
|
||||
>
|
||||
<RefreshCw class="size-3" :class="loading && 'animate-spin'" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<div v-if="loading && !data" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在查询链接…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!relPath"
|
||||
variant="empty"
|
||||
title="未打开笔记"
|
||||
description="打开一篇笔记后这里会显示它的双链"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!data?.incoming.length && !data?.outgoing.length"
|
||||
variant="empty"
|
||||
title="还没有链接"
|
||||
description="在正文里写 [[另一篇笔记]],或在别处引用这篇"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<!-- 入链 -->
|
||||
<p v-if="data?.incoming.length" class="px-1 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase">
|
||||
被引用({{ data.incomingSources }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in data?.incoming ?? []"
|
||||
:key="`in-${link.relPath}-${link.target}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', link.relPath)"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
<span class="ml-auto shrink-0 truncate text-[10px] text-fg-disabled">{{ link.relPath }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 已解析出链 -->
|
||||
<p
|
||||
v-if="resolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
指向({{ resolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in resolvedOutgoing"
|
||||
:key="`out-${link.relPath}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', targetOf(link))"
|
||||
>
|
||||
<Link2 class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 未解析出链(可一键新建) -->
|
||||
<p
|
||||
v-if="unresolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
未解析({{ unresolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in unresolvedOutgoing"
|
||||
:key="`miss-${link.target}`"
|
||||
type="button"
|
||||
class="group flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-muted-foreground transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
title="点击新建这篇笔记"
|
||||
@click="createMissing(link)"
|
||||
>
|
||||
<Link2Off class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
<span class="ml-auto shrink-0 text-[10px] opacity-0 group-hover:opacity-100">新建</span>
|
||||
</button>
|
||||
|
||||
<!-- 外部链接 -->
|
||||
<p
|
||||
v-if="externalOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
外部链接({{ externalOutgoing.length }})
|
||||
</p>
|
||||
<a
|
||||
v-for="link in externalOutgoing"
|
||||
:key="`url-${link.target}`"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
:href="link.target"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
</a>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,245 @@
|
||||
<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 { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import {
|
||||
createEditorState,
|
||||
jumpToPosition,
|
||||
reconfigureEditor,
|
||||
replaceDoc,
|
||||
setLanguageExtension,
|
||||
type EditorConfig
|
||||
} from '../editor/core'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Extension } from '@codemirror/state'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
|
||||
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 = useNotesStore()
|
||||
const hostRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
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
|
||||
applyingDoc = true
|
||||
replaceDoc(view, store.content)
|
||||
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)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="hostRef" class="notes-editor-host h-full min-h-0 overflow-hidden" />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notes-editor-host :deep(.cm-editor) {
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
}
|
||||
.notes-editor-host :deep(.cm-scroller) {
|
||||
padding: 12px 8px 32px;
|
||||
overflow: auto;
|
||||
}
|
||||
.notes-editor-host :deep(.cm-editor.cm-focused) {
|
||||
outline: none;
|
||||
}
|
||||
/* 笔记正文里正文与标题之间留些气口,Live Preview 下更接近阅读视图 */
|
||||
.notes-editor-host :deep(.cm-content) {
|
||||
padding-bottom: 24vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,243 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 编辑器工具栏:格式化按钮 + 视图切换 + 保存 + 配色快切 + 打开文件。
|
||||
*
|
||||
* 格式化命令通过 `apply` 由父级(NotesWindow)转发到当前 EditorView ——
|
||||
* 工具栏本身不持有编辑器实例(实例在 EditorHost 内部,非响应式)。
|
||||
*
|
||||
* 控件尺寸与图标写法对齐项目约定:按钮图标显式 `size-3.5`、下拉用 `Select`。
|
||||
*
|
||||
* # 文件模式下藏掉 Markdown 格式按钮
|
||||
*
|
||||
* `.py` 文件里的「加粗 / 引用 / 任务列表」没有任何意义,留着只会让人以为按了
|
||||
* 会有用。因此按 `store.kind` 切换:笔记显示格式化组,文件显示「打开 / 快速打开 /
|
||||
* 编码与换行信息」,两者共用保存与配色。
|
||||
*/
|
||||
import {
|
||||
Bold,
|
||||
Code,
|
||||
Eye,
|
||||
FileDown,
|
||||
FileSearch,
|
||||
FolderOpen,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
Italic,
|
||||
Link,
|
||||
List,
|
||||
ListChecks,
|
||||
Loader2,
|
||||
Quote,
|
||||
Save,
|
||||
SquareCode,
|
||||
Strikethrough
|
||||
} from '@lucide/vue'
|
||||
import { ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { toast } from 'vue-sonner'
|
||||
import type { Command } from '@codemirror/view'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import { notesCommands } from '../editor/keymap'
|
||||
import { EDITOR_THEME_OPTIONS } from '../editor/themes'
|
||||
import type { NoteViewMode } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{
|
||||
apply: (command: Command) => void
|
||||
viewMode: NoteViewMode
|
||||
dirty: boolean
|
||||
saving: boolean
|
||||
name: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:viewMode': [value: NoteViewMode]
|
||||
save: []
|
||||
'open-file': []
|
||||
'quick-open': []
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const run = (command: Command) => props.apply(command)
|
||||
|
||||
const exporting = ref(false)
|
||||
|
||||
/**
|
||||
* 导出当前笔记为 HTML。
|
||||
*
|
||||
* 渲染链路(markdown-it + DOMPurify + highlight.js)**按需 import**:
|
||||
* 它约 1MB,而导出是低频动作 —— 静态引入会让「打开编辑器窗口」这个最常见的动作
|
||||
* 也背上这份体积。
|
||||
*/
|
||||
async function exportHtml(): Promise<void> {
|
||||
if (!store.currentRelPath) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const doc = await notesClient.readNote(store.currentRelPath)
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
title: store.currentName || doc.name.replace(/\.md$/i, ''),
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: `${doc.name.replace(/\.md$/i, '')}.html`,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
const saved = await notesClient.exportNote(store.currentRelPath, html, dest)
|
||||
toast.success(`已导出:${saved}`)
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-3">
|
||||
<!-- 文档名 + 未保存标记 -->
|
||||
<div class="mr-2 flex min-w-0 items-center gap-1.5">
|
||||
<span class="truncate text-[13px] font-medium text-foreground">
|
||||
{{ name || '未打开文档' }}
|
||||
</span>
|
||||
<span
|
||||
v-if="dirty"
|
||||
class="size-1.5 shrink-0 rounded-full bg-primary"
|
||||
title="有未保存的改动"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<!-- ===== 笔记模式:Markdown 格式化 ===== -->
|
||||
<template v-if="store.kind === 'note'">
|
||||
<Button variant="ghost" size="icon-sm" title="加粗 (Ctrl+B)" @click="run(notesCommands.bold)">
|
||||
<Bold class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="斜体 (Ctrl+I)" @click="run(notesCommands.italic)">
|
||||
<Italic class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="删除线 (Ctrl+Shift+X)"
|
||||
@click="run(notesCommands.strikethrough)"
|
||||
>
|
||||
<Strikethrough class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="行内代码 (Ctrl+E)"
|
||||
@click="run(notesCommands.inlineCode)"
|
||||
>
|
||||
<Code class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="链接 (Ctrl+K)" @click="run(notesCommands.link)">
|
||||
<Link class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<Button variant="ghost" size="icon-sm" title="一级标题 (Ctrl+1)" @click="run(notesCommands.heading(1))">
|
||||
<Heading1 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="二级标题 (Ctrl+2)" @click="run(notesCommands.heading(2))">
|
||||
<Heading2 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="三级标题 (Ctrl+3)" @click="run(notesCommands.heading(3))">
|
||||
<Heading3 class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<Button variant="ghost" size="icon-sm" title="无序列表" @click="run(notesCommands.bulletList)">
|
||||
<List class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="任务列表" @click="run(notesCommands.taskList)">
|
||||
<ListChecks class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="引用" @click="run(notesCommands.quote)">
|
||||
<Quote class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="代码块 (Ctrl+Shift+C)" @click="run(notesCommands.codeBlock)">
|
||||
<SquareCode class="size-3.5" />
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<!-- ===== 文件模式 ===== -->
|
||||
<template v-else>
|
||||
<Button variant="ghost" size="sm" title="打开磁盘文件 (Ctrl+O)" @click="emit('open-file')">
|
||||
<FolderOpen class="size-3.5" />打开
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" title="快速打开 (Ctrl+P)" @click="emit('quick-open')">
|
||||
<FileSearch class="size-3.5" />快速打开
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-2">
|
||||
<!-- 导出当前笔记为 HTML(低频动作:渲染链路按需加载) -->
|
||||
<Button
|
||||
v-if="store.kind === 'note' && store.currentRelPath"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
:disabled="exporting"
|
||||
title="导出为独立 HTML(可离线打开或系统打印成 PDF)"
|
||||
@click="exportHtml"
|
||||
>
|
||||
<Loader2 v-if="exporting" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
导出
|
||||
</Button>
|
||||
<!-- 配色快切(与设置页同一份取值) -->
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => store.patchSettings({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="h-7 w-40 text-xs"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<!-- 视图切换(只对 Markdown 有意义) -->
|
||||
<TooltipProvider v-if="store.kind === 'note'" :delay-duration="400">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="emit('update:viewMode', viewMode === 'wysiwyg' ? 'source' : 'wysiwyg')"
|
||||
>
|
||||
<Eye class="size-3.5" />
|
||||
{{ viewMode === 'wysiwyg' ? '所见即所得' : '源码' }}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">切换视图 (Ctrl+Shift+M)</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<Button variant="outline" size="sm" :disabled="!dirty || saving" @click="emit('save')">
|
||||
<Save class="size-3.5" />
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,314 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 导入 / 导出面板(主模块页「库」区)。
|
||||
*
|
||||
* # 三条链路,各自的风险点
|
||||
*
|
||||
* - **导入**:批量写库,唯一硬规则是「绝不覆盖」(重名加序号),选择即授权;
|
||||
* - **导出 HTML**:渲染在前端(`markdownExport`),落盘在后端 —— 后端不碰渲染、
|
||||
* 前端不碰文件系统,各自只做自己擅长且可审计的那一半;
|
||||
* - **导出 zip**:整库或某个目录打包,方便分享/迁移。
|
||||
*
|
||||
* # 为什么导出 HTML 的路径要用户选两次(先选笔记、再选保存位置)
|
||||
*
|
||||
* 批量导出(一次选目录、每篇一个 HTML)看起来更省事,但「一篇笔记配一个 assets 目录」
|
||||
* 的结构很难在浏览器里可靠实现(`<base>` 与相对路径在不同浏览器行为不一致)。
|
||||
* 这里只做**单篇 → 单文件**,路径语义清晰:导出文件和笔记在库内同级时相对路径依然有效。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
FileDown,
|
||||
FileUp,
|
||||
FolderInput,
|
||||
FolderOutput,
|
||||
Loader2,
|
||||
NotebookPen
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { SettingRow } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const busy = ref<'import' | 'export' | 'zip' | null>(null)
|
||||
|
||||
/**
|
||||
* 「当前打开的笔记」这个选项的哨兵值。
|
||||
*
|
||||
* **不能用空串**:reka-ui 的 `Select` 把空串保留给「清空选择、显示 placeholder」,
|
||||
* 放一个 `value=""` 的 `SelectItem` 会直接抛
|
||||
* 「A <SelectItem /> must have a value prop that is not an empty string」。
|
||||
* 用哨兵值 + 调用点翻译,比「把空串当合法值」更清楚:哨兵名本身就说明了语义。
|
||||
*/
|
||||
const CURRENT_NOTE = '__current__'
|
||||
/** 「整个库」这个选项的哨兵值(同上,空串留给 placeholder) */
|
||||
const WHOLE_LIBRARY = '__all__'
|
||||
|
||||
/** 导出 HTML 的目标笔记(`CURRENT_NOTE` = 当前打开的笔记) */
|
||||
const exportTarget = ref(CURRENT_NOTE)
|
||||
|
||||
/** 库内目录选项(导出 zip 时限定范围) */
|
||||
const dirOptions = computed(() => {
|
||||
const dirs = store.entries.filter(e => e.isDir).map(e => e.relPath)
|
||||
return [{ value: WHOLE_LIBRARY, label: '整个库' }, ...dirs.map(d => ({ value: d, label: d }))]
|
||||
})
|
||||
/** 导出 zip 的范围(`WHOLE_LIBRARY` = 整库) */
|
||||
const zipScope = ref(WHOLE_LIBRARY)
|
||||
|
||||
/**
|
||||
* 可导出的笔记。
|
||||
*
|
||||
* 当前笔记只作为**第一个选项**出现(而不是「空串代表当前」)—— 这样列表里每一项
|
||||
* 都有明确的值,用户也能在「当前笔记」与具体路径之间切换。
|
||||
*/
|
||||
const noteOptions = computed(() => {
|
||||
const files = store.entries.filter(e => !e.isDir)
|
||||
const options: Array<{ value: string; label: string }> = []
|
||||
if (store.currentRelPath) {
|
||||
options.push({ value: CURRENT_NOTE, label: `当前笔记(${store.currentName})` })
|
||||
}
|
||||
options.push(...files.map(f => ({ value: f.relPath, label: f.relPath })))
|
||||
return options
|
||||
})
|
||||
|
||||
/** 导入:文件 / 目录 / zip 都走同一个入口(后端按扩展名判别)。 */
|
||||
async function doImport(kind: 'file' | 'dir'): Promise<void> {
|
||||
try {
|
||||
const selected = await open(
|
||||
kind === 'dir'
|
||||
? { directory: true, multiple: false, title: '选择要导入的文件夹' }
|
||||
: {
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title: '选择要导入的文件或 zip',
|
||||
filters: [
|
||||
{ name: 'Markdown / Zip', extensions: ['md', 'markdown', 'zip'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
}
|
||||
)
|
||||
if (typeof selected !== 'string') return
|
||||
busy.value = 'import'
|
||||
const report = await notesClient.import(selected, '')
|
||||
await store.refreshLibrary()
|
||||
await store.syncIndex()
|
||||
const renamed = report.renamed ? `,${report.renamed} 篇重名已加序号` : ''
|
||||
const skipped = report.skipped ? `,跳过 ${report.skipped} 个非笔记文件` : ''
|
||||
toast.success(`导入 ${report.imported} 个文件${renamed}${skipped}`)
|
||||
if (report.failures.length) {
|
||||
toast.warning(`${report.failures.length} 条失败:${report.failures[0]}`)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出单篇 HTML:渲染在本地做,落盘交给后端。 */
|
||||
async function doExportHtml(): Promise<void> {
|
||||
// 哨兵值翻译成真实路径(见 `CURRENT_NOTE` 的说明)
|
||||
const relPath = exportTarget.value === CURRENT_NOTE ? store.currentRelPath : exportTarget.value
|
||||
if (!relPath) {
|
||||
toast.error(store.currentRelPath ? '请先选择要导出的笔记' : '请先在编辑器里打开一篇笔记')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const doc = await notesClient.readNote(relPath)
|
||||
// **动态引入**:`markdownExport` 会拉进 markdown-it + DOMPurify + highlight.js
|
||||
// (实测约 1MB),而导出是低频动作。静态引入会让「笔记」模块页一打开就下载
|
||||
// 这三个包(chunk 从 ~130kB 涨到 1.1MB),把首屏拖垮。
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
// 标题用笔记自己的显示名,而不是「当前笔记」那个下拉标签
|
||||
title: doc.name.replace(/\.md$/i, ''),
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const suggested = doc.name.replace(/\.md$/i, '') + '.html'
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: suggested,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'export'
|
||||
const saved = await notesClient.exportNote(relPath, html, dest)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开', onClick: () => void openPath(saved) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出 zip(整库或某个目录)。 */
|
||||
async function doExportZip(): Promise<void> {
|
||||
try {
|
||||
// 哨兵值翻译:`WHOLE_LIBRARY` → 不传范围(后端按「整库」处理)
|
||||
const scope = zipScope.value === WHOLE_LIBRARY ? '' : zipScope.value
|
||||
const scopeLabel = scope ? scope.replace(/\//g, '-') : 'thing-notes'
|
||||
const dest = await open({
|
||||
title: '导出 zip',
|
||||
defaultPath: `${scopeLabel}.zip`,
|
||||
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'zip'
|
||||
const saved = await notesClient.exportZip(dest, scope || undefined)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开目录', onClick: () => void openPath(saved.replace(/[\\/][^\\/]+$/, '')) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 把内置模板写到库内 `templates/`,方便用户直接改。 */
|
||||
async function exportTemplates(): Promise<void> {
|
||||
try {
|
||||
const written = await store.exportBuiltinTemplates()
|
||||
if (written.length) {
|
||||
toast.success(`已写入 ${written.length} 个内置模板到 templates/`)
|
||||
} else {
|
||||
toast.info('templates/ 里已有这些模板,未覆盖')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`写入模板失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- ===== 导入 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileUp class="size-4 text-primary" />
|
||||
导入
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
导入 Markdown 目录 / 单文件 / zip 包。**同名笔记不会被覆盖**,会自动加序号;
|
||||
图片等附件进 <code class="font-mono">assets/</code>,其它类型文件忽略。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导入文件夹" description="保留子目录结构,跳过隐藏目录与 __MACOSX">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!!busy"
|
||||
@click="doImport('dir')"
|
||||
>
|
||||
<Loader2 v-if="busy === 'import'" class="size-3.5 animate-spin" />
|
||||
<FolderInput v-else class="size-3.5" />
|
||||
选择文件夹
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="导入文件 / zip" description="单个 .md 或一个压缩包">
|
||||
<Button variant="outline" size="sm" :disabled="!!busy" @click="doImport('file')">
|
||||
<FileUp class="size-3.5" />选择文件
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 导出 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileDown class="size-4 text-primary" />
|
||||
导出
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
HTML 为**单文件、零外链**(样式内联),可离线双击打开或直接用系统打印成 PDF;
|
||||
正文经过消毒,笔记里嵌的脚本不会被执行。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导出笔记" description="Markdown → 独立 HTML" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="exportTarget">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in noteOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportHtml"
|
||||
>
|
||||
<Loader2 v-if="busy === 'export'" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
导出 HTML
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="导出 zip" description="整库或某个目录(含 assets/,不含 .notes/)" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="zipScope">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in dirOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportZip"
|
||||
>
|
||||
<Loader2 v-if="busy === 'zip'" class="size-3.5 animate-spin" />
|
||||
<FolderOutput v-else class="size-3.5" />
|
||||
导出 zip
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="内置模板"
|
||||
description="把日记 / 会议纪要等内置模板写到库内 templates/,改完即刻生效"
|
||||
>
|
||||
<Button variant="outline" size="sm" @click="exportTemplates">
|
||||
<NotebookPen class="size-3.5" />写入 templates/
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 说明:导入目标目录固定为库根(保持与 zip 内结构一致),因此这里只给提示 -->
|
||||
<p class="px-1 text-[11px] text-muted-foreground">
|
||||
提示:导入的笔记都落在库根下(保留源目录结构)。想放到别处,导入后拖到目标目录即可。
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,466 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记库侧栏:目录树 / 全文检索 / 大纲 三视图 + 新建/重命名/删除 + 最近打开。
|
||||
*
|
||||
* 版式对齐终端「文件管理器」的 `FilePane`(同类场景:独立窗口里的分栏列表):
|
||||
* - 局部滚动一律用 `ScrollArea`(不写原生 `overflow-y-auto`,见 UI_DESIGN_SYSTEM §3.2)
|
||||
* - 选中态 `bg-row-selected` / hover 态 `hover:bg-row-hover`(两态不混用同一色)
|
||||
* - 紧凑输入 `h-7 text-xs`(与 FilePane 的筛选框一致)
|
||||
* - 空态用 `StateBlock`,不手写占位文案
|
||||
*
|
||||
* 树用「展开集合 + 扁平化」渲染,而不是递归子组件 —— 扁平列表能把过滤
|
||||
* (只保留命中项及其祖先)一并做掉。
|
||||
*
|
||||
* # 三视图为什么在同一个侧栏里切换
|
||||
*
|
||||
* 目录树 / 检索 / 大纲三者是**同一时刻只需一个**的导航手段,各自单开一个面板会
|
||||
* 把编辑器挤窄。用分段导航切换既省宽度,也让「我在找什么」始终只有一个答案。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FilePlus,
|
||||
FileText,
|
||||
Folder,
|
||||
FolderPlus,
|
||||
Link2,
|
||||
ListTree,
|
||||
Loader2,
|
||||
Pencil,
|
||||
RotateCw,
|
||||
Search,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { ConfirmDialog, SegmentedNav, StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import type { LibraryEntry, LibraryTreeNode } from '@/types/notes'
|
||||
import SearchPanel from './SearchPanel.vue'
|
||||
import MarkdownOutline from './MarkdownOutline.vue'
|
||||
import BacklinksPanel from './BacklinksPanel.vue'
|
||||
import NewNoteDialog from './NewNoteDialog.vue'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string]; jump: [from: number] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 侧栏视图 */
|
||||
const view = ref<'files' | 'search' | 'outline' | 'links'>('files')
|
||||
/** 已展开的目录 */
|
||||
const expanded = ref<Set<string>>(new Set())
|
||||
/** 名称过滤 */
|
||||
const filter = ref('')
|
||||
/** 当前选中的目录(新建目标;空串 = 库根) */
|
||||
const selectedDir = ref('')
|
||||
/** 编辑器光标行(大纲高亮用;由 NotesWindow 传入) */
|
||||
const cursorLine = ref(0)
|
||||
|
||||
defineExpose({
|
||||
/** 由 NotesWindow 在光标移动时调用 */
|
||||
setCursorLine: (line: number) => {
|
||||
cursorLine.value = line
|
||||
},
|
||||
/** 由 NotesWindow 在快捷键触发时调用 */
|
||||
showSearch: () => {
|
||||
view.value = 'search'
|
||||
},
|
||||
showOutline: () => {
|
||||
view.value = 'outline'
|
||||
},
|
||||
showFiles: () => {
|
||||
view.value = 'files'
|
||||
},
|
||||
/** 由 NotesWindow 在 Ctrl+Shift+N 时调用 */
|
||||
showNewNote: () => {
|
||||
view.value = 'files'
|
||||
void startNewNote()
|
||||
}
|
||||
})
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ value: 'files', label: '文件', icon: FileText },
|
||||
{ value: 'search', label: '检索', icon: Search },
|
||||
{ value: 'outline', label: '大纲', icon: ListTree },
|
||||
{ value: 'links', label: '双链', icon: Link2 }
|
||||
]
|
||||
|
||||
// ===== 扁平化 + 过滤 =====
|
||||
const flatNodes = computed(() => {
|
||||
const keyword = filter.value.trim().toLowerCase()
|
||||
const out: Array<{ entry: LibraryEntry; depth: number }> = []
|
||||
|
||||
const matches = (node: LibraryTreeNode): boolean => {
|
||||
if (!keyword) return true
|
||||
if (node.entry.name.toLowerCase().includes(keyword)) return true
|
||||
return node.children.some(matches)
|
||||
}
|
||||
|
||||
const walk = (nodes: LibraryTreeNode[], depth: number) => {
|
||||
for (const node of nodes) {
|
||||
if (!matches(node)) continue
|
||||
out.push({ entry: node.entry, depth })
|
||||
const open = expanded.value.has(node.entry.relPath) || !!keyword
|
||||
if (node.entry.isDir && open) walk(node.children, depth + 1)
|
||||
}
|
||||
}
|
||||
walk(store.tree, 0)
|
||||
return out
|
||||
})
|
||||
|
||||
watch(
|
||||
() => store.currentRelPath,
|
||||
relPath => {
|
||||
if (!relPath) return
|
||||
// 展开当前笔记的所有祖先目录,保证选中项可见
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
let prefix = ''
|
||||
const next = new Set(expanded.value)
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const isExpanded = (relPath: string) => expanded.value.has(relPath)
|
||||
|
||||
const toggleDir = (entry: LibraryEntry) => {
|
||||
const next = new Set(expanded.value)
|
||||
if (next.has(entry.relPath)) next.delete(entry.relPath)
|
||||
else next.add(entry.relPath)
|
||||
expanded.value = next
|
||||
selectedDir.value = entry.relPath
|
||||
}
|
||||
|
||||
const onRowClick = (entry: LibraryEntry) => {
|
||||
if (entry.isDir) {
|
||||
toggleDir(entry)
|
||||
return
|
||||
}
|
||||
emit('open', entry.relPath)
|
||||
}
|
||||
|
||||
const targetLabel = computed(() => (selectedDir.value ? selectedDir.value : '库根'))
|
||||
|
||||
// ===== 新建笔记(走带模板选择的对话框) =====
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
/**
|
||||
* 新建笔记入口。
|
||||
*
|
||||
* `showTemplatePicker` 关闭时**跳过对话框**,用「未命名」+ 上次的模板直接建 ——
|
||||
* 这是「快速记一笔」的路径,多一个对话框就多一次打断。名字建好后可以就地重命名。
|
||||
*/
|
||||
async function startNewNote(): Promise<void> {
|
||||
if (store.settings.showTemplatePicker) {
|
||||
newNoteOpen.value = true
|
||||
return
|
||||
}
|
||||
try {
|
||||
const stamp = new Date()
|
||||
const name = `未命名 ${stamp.getHours()}${String(stamp.getMinutes()).padStart(2, '0')}`
|
||||
await store.createNote(selectedDir.value, name, store.lastTemplateId || undefined)
|
||||
if (store.currentRelPath) revealNote(store.currentRelPath)
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建完成后展开新笔记的祖先目录,让它在树里可见 */
|
||||
function revealNote(relPath: string): void {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
const next = new Set(expanded.value)
|
||||
let prefix = ''
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
view.value = 'files'
|
||||
}
|
||||
|
||||
function onCreated(relPath: string): void {
|
||||
revealNote(relPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 反链面板里点了「未解析链接」→ 已按名字新建了一篇。
|
||||
*
|
||||
* 新建动作由面板内部完成(它知道 link 的原始名字),这里只负责把树展开到新笔记、
|
||||
* 并把它打开 —— 面板不持有「打开哪一篇」的知识,`store.currentRelPath` 由
|
||||
* `createNote` 自己更新。
|
||||
*/
|
||||
function onLinkCreated(): void {
|
||||
if (store.currentRelPath) revealNote(store.currentRelPath)
|
||||
}
|
||||
|
||||
// ===== 名称输入对话框(新建文件夹 / 重命名) =====
|
||||
type PromptMode = 'folder' | 'rename'
|
||||
const promptOpen = ref(false)
|
||||
const promptMode = ref<PromptMode>('folder')
|
||||
const promptValue = ref('')
|
||||
const promptTarget = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const promptTitle = computed(() => (promptMode.value === 'folder' ? '新建文件夹' : '重命名'))
|
||||
|
||||
function openPrompt(mode: PromptMode, target: string, initial = '') {
|
||||
promptMode.value = mode
|
||||
promptTarget.value = target
|
||||
promptValue.value = initial
|
||||
promptOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmPrompt() {
|
||||
const name = promptValue.value.trim()
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (promptMode.value === 'folder') {
|
||||
await store.createFolder(selectedDir.value, name)
|
||||
} else {
|
||||
await store.renameEntry(promptTarget.value, name)
|
||||
}
|
||||
promptOpen.value = false
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 删除确认 =====
|
||||
const confirmOpen = ref(false)
|
||||
const deleteTarget = ref<LibraryEntry | null>(null)
|
||||
|
||||
function askDelete(entry: LibraryEntry) {
|
||||
deleteTarget.value = entry
|
||||
confirmOpen.value = true
|
||||
}
|
||||
|
||||
async function doDelete() {
|
||||
const entry = deleteTarget.value
|
||||
if (!entry) return
|
||||
try {
|
||||
await store.deleteEntry(entry.relPath)
|
||||
toast.success(`已删除「${entry.name}」`)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
confirmOpen.value = false
|
||||
deleteTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="flex h-full min-h-0 w-64 shrink-0 flex-col border-r border-border">
|
||||
<!-- 头部操作 -->
|
||||
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<span class="ml-1 text-[13px] font-medium text-foreground">笔记库</span>
|
||||
<div class="ml-auto flex items-center gap-0.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.settings.showTemplatePicker ? '新建笔记(可选模板)' : '新建笔记'"
|
||||
@click="startNewNote"
|
||||
>
|
||||
<FilePlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="新建文件夹" @click="openPrompt('folder', selectedDir)">
|
||||
<FolderPlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.indexing ? '正在重建索引…' : '重建索引'"
|
||||
:disabled="store.indexing"
|
||||
@click="rebuildIndex"
|
||||
>
|
||||
<RotateCw class="size-3.5" :class="store.indexing && 'animate-spin'" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视图切换 -->
|
||||
<div class="shrink-0 px-2 pt-2">
|
||||
<SegmentedNav v-model="view" :items="NAV_ITEMS" block />
|
||||
</div>
|
||||
|
||||
<!-- ===== 文件视图 ===== -->
|
||||
<template v-if="view === 'files'">
|
||||
<div class="shrink-0 px-2 py-2">
|
||||
<div class="relative">
|
||||
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-xs" />
|
||||
<button
|
||||
v-if="filter"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="filter = ''"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1.5 px-0.5 text-[11px] text-muted-foreground">
|
||||
新建目标:<span class="text-fg-secondary">{{ targetLabel }}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 pb-2">
|
||||
<div v-if="store.loading" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在扫描库…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!flatNodes.length"
|
||||
variant="empty"
|
||||
:title="filter ? '没有匹配的笔记' : '笔记库为空'"
|
||||
:description="filter ? undefined : '点上方按钮新建第一篇笔记'"
|
||||
:min-height="140"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="item in flatNodes"
|
||||
:key="item.entry.relPath"
|
||||
class="group flex h-7 cursor-pointer items-center gap-1 rounded-sm pr-1 transition-colors duration-150"
|
||||
:class="
|
||||
store.currentRelPath === item.entry.relPath
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${item.depth * 12 + 4}px` }"
|
||||
@click="onRowClick(item.entry)"
|
||||
>
|
||||
<component
|
||||
:is="
|
||||
item.entry.isDir
|
||||
? isExpanded(item.entry.relPath)
|
||||
? ChevronDown
|
||||
: ChevronRight
|
||||
: FileText
|
||||
"
|
||||
class="size-3.5 shrink-0 opacity-70"
|
||||
/>
|
||||
<Folder v-if="item.entry.isDir" class="size-3.5 shrink-0 opacity-80" />
|
||||
<span class="truncate">{{ item.entry.name }}</span>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-0.5 opacity-0 group-hover:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="重命名"
|
||||
@click.stop="openPrompt('rename', item.entry.relPath, item.entry.name)"
|
||||
>
|
||||
<Pencil class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="删除"
|
||||
@click.stop="askDelete(item.entry)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<!-- 最近打开 -->
|
||||
<div v-if="store.recent.length" class="shrink-0 border-t border-border px-2 py-2">
|
||||
<p class="px-0.5 pb-1 text-[11px] font-medium text-muted-foreground">最近打开</p>
|
||||
<ScrollArea class="max-h-32">
|
||||
<div class="px-0.5">
|
||||
<button
|
||||
v-for="item in store.recent"
|
||||
:key="item.relPath"
|
||||
type="button"
|
||||
class="flex h-6 w-full items-center truncate rounded-sm px-1 text-left text-xs text-fg-secondary hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', item.relPath)"
|
||||
>
|
||||
{{ item.name.replace(/\.md$/i, '') }}
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ===== 检索视图 ===== -->
|
||||
<SearchPanel v-else-if="view === 'search'" class="min-h-0 flex-1" @open="emit('open', $event)" />
|
||||
|
||||
<!-- ===== 大纲视图 ===== -->
|
||||
<MarkdownOutline
|
||||
v-else-if="view === 'outline'"
|
||||
class="min-h-0 flex-1"
|
||||
:cursor-line="cursorLine"
|
||||
@jump="emit('jump', $event)"
|
||||
/>
|
||||
|
||||
<!-- ===== 双链视图 ===== -->
|
||||
<BacklinksPanel
|
||||
v-else
|
||||
class="min-h-0 flex-1"
|
||||
:rel-path="store.currentRelPath"
|
||||
@open="emit('open', $event)"
|
||||
@create="onLinkCreated"
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<!-- 名称输入对话框 -->
|
||||
<Dialog :open="promptOpen" @update:open="promptOpen = $event">
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ promptTitle }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
v-model="promptValue"
|
||||
:placeholder="promptMode === 'folder' ? '文件夹名称' : '名称'"
|
||||
@keydown.enter="confirmPrompt"
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="promptOpen = false">取消</Button>
|
||||
<Button :disabled="busy" @click="confirmPrompt">确定</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 删除确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="删除确认"
|
||||
variant="danger"
|
||||
confirm-text="删除"
|
||||
:description="
|
||||
deleteTarget?.isDir
|
||||
? `将删除文件夹「${deleteTarget?.name}」及其全部内容,此操作不可撤销。`
|
||||
: `将删除「${deleteTarget?.name}」,此操作不可撤销。`
|
||||
"
|
||||
@confirm="doDelete"
|
||||
/>
|
||||
|
||||
<!-- 新建笔记(名称 + 模板) -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" :dir-rel="selectedDir" @created="onCreated" />
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记大纲(标题树)。
|
||||
*
|
||||
* 结构与渲染分离:标题提取是纯函数 `extractOutline`(可单测,见 `editor/outline.ts`),
|
||||
* 本组件只负责「层级缩进 + 当前标题高亮 + 点击跳转」。
|
||||
*
|
||||
* # 当前标题怎么算
|
||||
*
|
||||
* 用编辑器的光标行号(由 `NotesWindow` 通过 props 传入)与标题行号比较,取
|
||||
* 「最后一个行号 ≤ 光标行」的标题。**不用滚动位置**:Live Preview 下装饰会让
|
||||
* 每行高度不一致,按像素反推当前标题很容易差一行,而光标位置是精确的。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { Hash, ListTree } from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 编辑器当前光标所在行(1 起;0 = 未知) */
|
||||
cursorLine: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ jump: [from: number] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 最浅一级标题的层级(让缩进从 0 开始,而不是每篇都从 h2 缩进一档) */
|
||||
const minLevel = computed(() =>
|
||||
store.outline.reduce((min, item) => Math.min(min, item.level), 6)
|
||||
)
|
||||
|
||||
const currentIndex = computed(() => {
|
||||
if (!props.cursorLine) return -1
|
||||
let found = -1
|
||||
for (let index = 0; index < store.outline.length; index++) {
|
||||
const heading = store.outline[index]
|
||||
if (heading && heading.line <= props.cursorLine) found = index
|
||||
else break
|
||||
}
|
||||
return found
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<ListTree class="size-3" />
|
||||
<span>大纲</span>
|
||||
<span class="ml-auto tabular-nums">{{ store.outline.length }} 个标题</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<StateBlock
|
||||
v-if="!store.outline.length"
|
||||
variant="empty"
|
||||
title="还没有标题"
|
||||
description="用 # 开头写一行标题,这里会自动生成大纲"
|
||||
:min-height="120"
|
||||
/>
|
||||
<button
|
||||
v-for="(heading, index) in store.outline"
|
||||
:key="`${heading.line}-${heading.from}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1 rounded-sm py-1 pr-1 text-left text-xs transition-colors duration-150"
|
||||
:class="
|
||||
index === currentIndex
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${(heading.level - minLevel) * 12 + 6}px` }"
|
||||
@click="emit('jump', heading.from)"
|
||||
>
|
||||
<Hash class="size-3 shrink-0 opacity-60" />
|
||||
<span class="truncate" :class="heading.level <= 2 ? 'font-medium' : ''">
|
||||
{{ heading.text || '(空标题)' }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 新建笔记对话框(名称 + 模板)。
|
||||
*
|
||||
* # 为什么把模板选择放进「新建」而不是设置页
|
||||
*
|
||||
* 模板是**每次新建时的决策**(今天写日记、明天写会议纪要),把它藏在设置里意味着
|
||||
* 用户得先改设置再新建、改两次。这里做成对话框里的一个下拉:默认选中上次用过的那个,
|
||||
* 一路回车就能建。
|
||||
*
|
||||
* # 名称即标题
|
||||
*
|
||||
* 输入的名称同时作为文件名与 front-matter 里的 `title`。不额外要一个「标题」字段:
|
||||
* 「文件名和标题不一样」在文件即真相的模型里只会带来困惑(重命名文件后标题不同步)。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { NotebookPen } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** 新建目标目录(库内相对路径,空串 = 库根) */
|
||||
dirRel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
created: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const name = ref('')
|
||||
const templateId = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const dirLabel = computed(() => props.dirRel || '库根')
|
||||
|
||||
/** 默认选中:上次用过的模板 → 空白笔记 → 第一个可用模板 */
|
||||
function pickDefaultTemplate(): void {
|
||||
if (templateId.value) return
|
||||
if (store.lastTemplateId && store.templates.some(t => t.id === store.lastTemplateId)) {
|
||||
templateId.value = store.lastTemplateId
|
||||
return
|
||||
}
|
||||
const blank = store.templates.find(t => t.name === '空白笔记')
|
||||
templateId.value = blank?.id ?? store.templates[0]?.id ?? ''
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
name.value = ''
|
||||
busy.value = false
|
||||
if (!store.templates.length) await store.loadTemplates()
|
||||
pickDefaultTemplate()
|
||||
}
|
||||
)
|
||||
|
||||
async function confirm(): Promise<void> {
|
||||
const title = name.value.trim()
|
||||
if (!title) return
|
||||
busy.value = true
|
||||
try {
|
||||
await store.createNote(props.dirRel, title, templateId.value || undefined)
|
||||
emit('created', store.currentRelPath)
|
||||
emit('update:open', false)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建笔记</DialogTitle>
|
||||
<DialogDescription>
|
||||
目标目录:{{ dirLabel }} · 名称同时作为文件名与 front-matter 的 title
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<Input
|
||||
v-model="name"
|
||||
placeholder="笔记名称"
|
||||
autofocus
|
||||
@keydown.enter="confirm"
|
||||
/>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-xs text-muted-foreground">模板</span>
|
||||
<Select v-model="templateId">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="item in store.templates" :key="item.id" :value="item.id">
|
||||
{{ item.name }}{{ item.builtin ? '(内置)' : '' }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span
|
||||
v-if="store.templates.find(t => t.id === templateId)?.description"
|
||||
class="line-clamp-2 text-[11px] text-muted-foreground"
|
||||
>
|
||||
{{ store.templates.find(t => t.id === templateId)?.description }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="emit('update:open', false)">取消</Button>
|
||||
<Button :disabled="busy || !name.trim()" @click="confirm">
|
||||
<NotebookPen class="size-3.5" />新建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 快速打开(`Ctrl+P`):库内文件跳转,类 VS Code。
|
||||
*
|
||||
* # 为什么在本地过滤而不是每次都查后端
|
||||
*
|
||||
* 库内笔记清单在打开面板时一次性取回(上限 1000 条,`notes_list_notes`),
|
||||
* 之后的每一次按键都只是对这份内存清单做子串匹配。这样输入零延迟 —— 而「按关键词
|
||||
* 找文件」本来就是模糊匹配,走 FTS5 反而会因为分词器把文件名切碎而给出意外结果
|
||||
* (FTS 是给正文用的)。
|
||||
*
|
||||
* # 排序:连续匹配 > 前缀 > 词首 > 位置靠前
|
||||
*
|
||||
* 单纯按「是否包含」排序会让 `笔记.md` 与 `我的笔记归档.md` 并列,用户真正想找的
|
||||
* 通常是名字更短、匹配更靠前的那个。这里用一个小的评分函数把「匹配质量」显式化,
|
||||
* 而不是依赖清单的顺序。
|
||||
*/
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { CornerDownLeft, FileText, Search } from '@lucide/vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import type { NoteSearchHit } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{ open: boolean }>()
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
select: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const keyword = ref('')
|
||||
const active = ref(0)
|
||||
const panelRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
/** 输入框聚焦:`Input` 是对 reka-ui 的包装,不保证暴露内部 `<input>`,直接查 DOM。 */
|
||||
async function focusInput(): Promise<void> {
|
||||
await nextTick()
|
||||
panelRef.value?.querySelector('input')?.focus()
|
||||
}
|
||||
|
||||
/** 匹配质量评分(越小越靠前)。 */
|
||||
function score(hit: NoteSearchHit, needle: string): number {
|
||||
const title = hit.title.toLowerCase()
|
||||
const path = hit.relPath.toLowerCase()
|
||||
const at = title.indexOf(needle)
|
||||
if (at === 0) return 0
|
||||
if (at > 0) return 1
|
||||
if (path.includes(`/${needle}`)) return 2
|
||||
if (path.includes(needle)) return 3
|
||||
return 99
|
||||
}
|
||||
|
||||
const results = computed<NoteSearchHit[]>(() => {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return store.quickOpenList.slice(0, 200)
|
||||
return store.quickOpenList
|
||||
.map(hit => ({ hit, rank: score(hit, needle) }))
|
||||
.filter(item => item.rank < 99)
|
||||
.sort((a, b) => a.rank - b.rank || b.hit.modified - a.hit.modified)
|
||||
.slice(0, 200)
|
||||
.map(item => item.hit)
|
||||
})
|
||||
|
||||
/** 标题里命中关键词的位置(渲染高亮用)。 */
|
||||
function titleParts(hit: NoteSearchHit): Array<{ text: string; hit: boolean }> {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return [{ text: hit.title, hit: false }]
|
||||
const at = hit.title.toLowerCase().indexOf(needle)
|
||||
if (at < 0) return [{ text: hit.title, hit: false }]
|
||||
return [
|
||||
{ text: hit.title.slice(0, at), hit: false },
|
||||
{ text: hit.title.slice(at, at + needle.length), hit: true },
|
||||
{ text: hit.title.slice(at + needle.length), hit: false }
|
||||
].filter(part => part.text.length > 0)
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function choose(hit: NoteSearchHit | undefined): void {
|
||||
if (!hit) return
|
||||
emit('select', hit.relPath)
|
||||
close()
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault()
|
||||
active.value = Math.min(active.value + 1, results.value.length - 1)
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
event.preventDefault()
|
||||
active.value = Math.max(active.value - 1, 0)
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
choose(results.value[active.value])
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
keyword.value = ''
|
||||
active.value = 0
|
||||
await store.loadQuickOpen()
|
||||
await focusInput()
|
||||
}
|
||||
)
|
||||
|
||||
watch(keyword, () => {
|
||||
active.value = 0
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition
|
||||
enter-active-class="transition-opacity duration-150"
|
||||
leave-active-class="transition-opacity duration-150"
|
||||
enter-from-class="opacity-0"
|
||||
leave-to-class="opacity-0"
|
||||
>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-[12vh]"
|
||||
@click.self="close"
|
||||
>
|
||||
<div
|
||||
ref="panelRef"
|
||||
class="flex max-h-[60vh] w-[min(560px,92vw)] flex-col overflow-hidden rounded-lg border border-border bg-popup shadow-lg"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<div class="relative shrink-0 border-b border-border p-2">
|
||||
<Search class="absolute top-1/2 left-4 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="keyword"
|
||||
placeholder="按名称跳转到笔记…"
|
||||
class="h-8 border-0 bg-transparent pl-7 text-[13px] shadow-none focus-visible:ring-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="p-1">
|
||||
<StateBlock
|
||||
v-if="!results.length"
|
||||
variant="empty"
|
||||
title="没有匹配的笔记"
|
||||
:min-height="100"
|
||||
/>
|
||||
<button
|
||||
v-for="(hit, index) in results"
|
||||
:key="hit.relPath"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left"
|
||||
:class="index === active ? 'bg-row-selected text-primary-soft-text' : 'hover:bg-row-hover'"
|
||||
@mouseenter="active = index"
|
||||
@click="choose(hit)"
|
||||
>
|
||||
<FileText class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="min-w-0 flex-1 truncate text-xs">
|
||||
<template v-for="(part, partIndex) in titleParts(hit)" :key="partIndex">
|
||||
<mark v-if="part.hit" class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text">{{ part.text }}</mark>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
<span class="max-w-[45%] shrink-0 truncate text-[10px] text-fg-disabled">{{ hit.relPath }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[10px] text-muted-foreground">
|
||||
<span class="flex items-center gap-1"><CornerDownLeft class="size-3" />打开</span>
|
||||
<span>↑↓ 选择</span>
|
||||
<span>Esc 关闭</span>
|
||||
<span class="ml-auto tabular-nums">{{ results.length }} / {{ store.quickOpenList.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -0,0 +1,173 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 库内全文检索面板(FTS5)。
|
||||
*
|
||||
* # 检索由 Rust 做,前端只做「输入 → 查询 → 渲染」
|
||||
*
|
||||
* 匹配、排序(标题权重高于正文)、片段提取、分页全部在 SQL 里完成:把候选集拉回
|
||||
* 前端再过滤会在大库上卡住主线程,而且「命中总数」会变成假的(前端只拿到了当页)。
|
||||
* 这里的防抖只是**省请求**,不是正确性的一部分。
|
||||
*
|
||||
* # 高亮片段为什么不用 v-html
|
||||
*
|
||||
* 片段来自用户笔记正文,直接 `v-html` 就是一个自找的 XSS 面。Rust 侧回传的是
|
||||
* 用 `\u0002` / `\u0003` 定界的纯文本,这里切成数组后用 `<mark>` 渲染
|
||||
* (见 `splitHighlight`)—— 文本永远走插值,不经过 HTML 解析。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { FileText, Loader2, Search, Tag, X } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { splitHighlight } from '@/types/notes'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 输入框的值与「已提交的关键词」分开:前者每次按键都变,后者只在防抖后提交 */
|
||||
const input = ref(store.searchKeyword)
|
||||
const activeTag = ref(store.searchTag)
|
||||
|
||||
let debounce: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function submit(immediate = false): void {
|
||||
if (debounce) clearTimeout(debounce)
|
||||
const run = () => {
|
||||
debounce = null
|
||||
void store.search({ keyword: input.value, tag: activeTag.value })
|
||||
}
|
||||
// 回车/点按钮时立即查,打字时防抖 250ms
|
||||
if (immediate) run()
|
||||
else debounce = setTimeout(run, 250)
|
||||
}
|
||||
|
||||
function pickTag(tag: string): void {
|
||||
activeTag.value = activeTag.value === tag ? '' : tag
|
||||
submit(true)
|
||||
}
|
||||
|
||||
function clearAll(): void {
|
||||
input.value = ''
|
||||
activeTag.value = ''
|
||||
store.clearSearch()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => store.searchTag,
|
||||
tag => {
|
||||
if (tag !== activeTag.value) activeTag.value = tag
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void store.loadTags()
|
||||
// 首次进入若已有结果就保留,否则给一个空关键词查询(把最近改动的笔记列出来)
|
||||
if (!store.searchHits.length) submit(true)
|
||||
})
|
||||
|
||||
const hasQuery = computed(() => !!input.value.trim() || !!activeTag.value)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<!-- 关键词 -->
|
||||
<div class="shrink-0 px-2 pb-2">
|
||||
<div class="relative">
|
||||
<Search class="absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="input"
|
||||
placeholder="搜索标题与正文…"
|
||||
class="h-7 pl-7 pr-6 text-xs"
|
||||
@input="submit()"
|
||||
@keydown.enter="submit(true)"
|
||||
/>
|
||||
<button
|
||||
v-if="input"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="input = ''; submit(true)"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 标签筛选 -->
|
||||
<div v-if="store.tags.length" class="mt-2 flex flex-wrap gap-1">
|
||||
<button
|
||||
v-for="item in store.tags.slice(0, 12)"
|
||||
:key="item.tag"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
|
||||
:class="
|
||||
activeTag === item.tag
|
||||
? 'bg-primary-soft text-primary-soft-text'
|
||||
: 'bg-muted text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||
"
|
||||
@click="pickTag(item.tag)"
|
||||
>
|
||||
<Tag class="size-2.5" />
|
||||
{{ item.tag }}
|
||||
<span class="tabular-nums opacity-70">{{ item.count }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果统计 -->
|
||||
<div class="flex h-6 shrink-0 items-center gap-2 border-y border-border px-2 text-[11px] text-muted-foreground">
|
||||
<span v-if="store.searching" class="flex items-center gap-1.5">
|
||||
<Loader2 class="size-3 animate-spin" />检索中…
|
||||
</span>
|
||||
<span v-else>共 {{ store.searchTotal }} 条</span>
|
||||
<button
|
||||
v-if="hasQuery"
|
||||
type="button"
|
||||
class="ml-auto text-muted-foreground hover:text-foreground"
|
||||
@click="clearAll"
|
||||
>
|
||||
重置
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 结果列表 -->
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<StateBlock
|
||||
v-if="!store.searchHits.length && !store.searching"
|
||||
variant="empty"
|
||||
:title="hasQuery ? '没有匹配的笔记' : '还没有可搜索的内容'"
|
||||
:description="hasQuery ? '换个关键词,或点「重置」看全部' : '索引同步完成后这里会列出库内笔记'"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<button
|
||||
v-for="hit in store.searchHits"
|
||||
:key="hit.relPath"
|
||||
type="button"
|
||||
class="flex w-full flex-col gap-0.5 rounded-sm px-2 py-1.5 text-left transition-colors duration-150 hover:bg-row-hover"
|
||||
@click="emit('open', hit.relPath)"
|
||||
>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<FileText class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span class="truncate text-xs font-medium text-foreground">{{ hit.title }}</span>
|
||||
</span>
|
||||
<span v-if="hit.snippet" class="line-clamp-2 pl-5 text-[11px] leading-relaxed text-muted-foreground">
|
||||
<template v-for="(part, index) in splitHighlight(hit.snippet)" :key="index">
|
||||
<mark v-if="part.hit" class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text">{{ part.text }}</mark>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
<span class="truncate pl-5 text-[10px] text-fg-disabled">{{ hit.relPath }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="store.searchHasMore" class="mt-1 flex justify-center">
|
||||
<Button variant="ghost" size="sm" :disabled="store.searching" @click="store.searchMore()">
|
||||
加载更多
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,490 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* WebDAV 设置与同步面板(主模块页「同步」区)。
|
||||
*
|
||||
* # 三块内容,对应三种使用姿态
|
||||
*
|
||||
* 1. **连接**:地址 / 账号 / 应用密码 / 远端根 —— 密码进系统凭据管理器,不回显;
|
||||
* 2. **同步**:方向、冲突策略、立即同步 —— 双向默认,冲突默认「两侧都留」;
|
||||
* 3. **备份**:zip 快照(立即备份 / 快照列表 / 恢复)—— 「只是要个备份」的路径,
|
||||
* 比同步简单也更不容易出事(规划 §3.6)。
|
||||
*
|
||||
* # 为什么设置改动要显式 `commitSettings`
|
||||
*
|
||||
* 别的设置(主题/字体)改动即落盘没问题,因为它们只影响本机显示;同步设置改错会让
|
||||
* **下一次同步按错误的方向跑**(比如把「只上传」误当成双向)。因此这里同样即时保存,
|
||||
* 但在切换方向 / 冲突策略时给出明确文案,而不是静默生效。
|
||||
*/
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import {
|
||||
AlertTriangle,
|
||||
ArrowDownToLine,
|
||||
ArrowUpFromLine,
|
||||
CloudUpload,
|
||||
Database,
|
||||
HardDriveDownload,
|
||||
Loader2,
|
||||
PlugZap,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Trash2
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import type { ConflictPolicy, SyncDirection } from '@/types/notes'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 密码输入框(提交后立刻清空,不留内存态) */
|
||||
const password = ref('')
|
||||
const testing = ref(false)
|
||||
const restoring = ref<string | null>(null)
|
||||
/** 待恢复的快照名(非空即弹出确认框) */
|
||||
const restoreTarget = ref<string | null>(null)
|
||||
/** 确认框的 open 必须是 boolean:`restoreTarget` 同时承载「点了哪一个」,
|
||||
* 因此这里显式做一次类型转换,而不是把 `string | null` 直接塞给 `open` */
|
||||
const restoreOpen = computed({
|
||||
get: () => restoreTarget.value !== null,
|
||||
set: (value: boolean) => {
|
||||
if (!value) restoreTarget.value = null
|
||||
}
|
||||
})
|
||||
|
||||
const webdav = computed(() => store.settings.webdav)
|
||||
const configured = computed(() => store.webdavStatus?.configured ?? false)
|
||||
const hasPassword = computed(() => store.webdavStatus?.hasPassword ?? false)
|
||||
|
||||
const DIRECTION_OPTIONS: Array<{ value: SyncDirection; label: string; hint: string }> = [
|
||||
{ value: 'bidirectional', label: '双向同步', hint: '两侧都改时按冲突策略处理' },
|
||||
{ value: 'upload', label: '仅上传(本地 → 远端)', hint: '把本地当作唯一真相,远端只作备份' },
|
||||
{ value: 'download', label: '仅下载(远端 → 本地)', hint: '换机器恢复时用,本地改动不会被上传' }
|
||||
]
|
||||
|
||||
const CONFLICT_OPTIONS: Array<{ value: ConflictPolicy; label: string }> = [
|
||||
{ value: 'keepBoth', label: '两侧都留(最保守)' },
|
||||
{ value: 'newer', label: '保留较新的' },
|
||||
{ value: 'localWins', label: '本地覆盖远端' },
|
||||
{ value: 'remoteWins', label: '远端覆盖本地' }
|
||||
]
|
||||
|
||||
/** 局部更新 webdav 设置(`webdav` 是嵌套对象,整体替换) */
|
||||
function patchWebdav(patch: Partial<typeof webdav.value>): void {
|
||||
void store.patchSettings({ webdav: { ...webdav.value, ...patch } })
|
||||
}
|
||||
|
||||
async function savePassword(): Promise<void> {
|
||||
const value = password.value
|
||||
if (!value.trim()) {
|
||||
toast.error('密码不能为空')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.refreshWebdav(value)
|
||||
password.value = ''
|
||||
toast.success('密码已保存到系统凭据管理器')
|
||||
} catch (e) {
|
||||
toast.error(`保存密码失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function clearPassword(): Promise<void> {
|
||||
try {
|
||||
await store.refreshWebdav('')
|
||||
toast.success('已清除保存的密码')
|
||||
} catch (e) {
|
||||
toast.error(`清除密码失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function testConnection(): Promise<void> {
|
||||
testing.value = true
|
||||
try {
|
||||
const result = await notesClient.testWebdav()
|
||||
if (result.created.length) {
|
||||
toast.success(`${result.message}(新建了 ${result.created.length} 层目录)`)
|
||||
} else {
|
||||
toast.success(result.message)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`连接失败:${String(e)}`)
|
||||
} finally {
|
||||
testing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function syncNow(): Promise<void> {
|
||||
try {
|
||||
const report = await store.syncNow()
|
||||
if (!report) return
|
||||
if (report.failed > 0) {
|
||||
toast.warning(
|
||||
`同步完成但 ${report.failed} 条失败(上传 ${report.uploaded} / 下载 ${report.downloaded})`
|
||||
)
|
||||
} else {
|
||||
toast.success(
|
||||
`同步完成:上传 ${report.uploaded} · 下载 ${report.downloaded} · 改名 ${report.moved} · 删除 ${report.deletedRemote + report.deletedLocal} · 冲突 ${report.conflicts}(${report.elapsedMs}ms)`
|
||||
)
|
||||
}
|
||||
void store.loadBackups()
|
||||
} catch (e) {
|
||||
toast.error(`同步失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function backupNow(): Promise<void> {
|
||||
try {
|
||||
const report = await store.backupNow()
|
||||
toast.success(`快照已上传:${report.name}(${report.files} 个文件,${formatBytes(report.bytes)})`)
|
||||
void store.loadBackups()
|
||||
} catch (e) {
|
||||
toast.error(`备份失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出本地快照(不连远端)。 */
|
||||
async function exportLocalSnapshot(): Promise<void> {
|
||||
try {
|
||||
const dest = await open({
|
||||
title: '保存快照',
|
||||
defaultPath: `thing-notes-${new Date().toISOString().slice(0, 10)}.zip`,
|
||||
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
const saved = await notesClient.exportSnapshotLocal(dest)
|
||||
toast.success(`快照已导出:${saved}`)
|
||||
} catch (e) {
|
||||
toast.error(`导出快照失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function doRestore(): Promise<void> {
|
||||
const name = restoreTarget.value
|
||||
if (!name) return
|
||||
restoring.value = name
|
||||
try {
|
||||
await store.restoreBackup(name)
|
||||
toast.success('恢复完成(已存在的本地文件未被覆盖)')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
restoring.value = null
|
||||
restoreTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function formatTime(ms: number): string {
|
||||
if (!ms) return '—'
|
||||
return new Date(ms).toLocaleString()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void store.loadWebdavStatus()
|
||||
void store.loadBackups()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- ===== 连接 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<PlugZap class="size-4 text-primary" />
|
||||
WebDAV 连接
|
||||
<span
|
||||
class="ml-auto rounded-sm px-1.5 py-0.5 text-[11px]"
|
||||
:class="configured ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'"
|
||||
>
|
||||
{{ configured ? '已配置' : '未配置' }}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
兼容 Nextcloud / 群晖 / 坚果云 / Alist 等标准 WebDAV 服务。密码保存在 Windows
|
||||
凭据管理器(服务名 <code class="font-mono">Thing</code>),不写入设置文件。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="服务地址" description="含协议与路径,例如 https://dav.jianguoyun.com/dav" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.url"
|
||||
placeholder="https://dav.example.com/dav"
|
||||
@change="(e: Event) => patchWebdav({ url: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="账号" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.username"
|
||||
placeholder="邮箱或用户名"
|
||||
@change="(e: Event) => patchWebdav({ username: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="密码 / 应用密码"
|
||||
:description="hasPassword ? '已保存(留空即不修改)' : '尚未保存'"
|
||||
control-width="wide"
|
||||
>
|
||||
<div class="flex w-full items-center gap-2">
|
||||
<Input
|
||||
v-model="password"
|
||||
type="password"
|
||||
:placeholder="hasPassword ? '••••••••(已保存)' : '应用密码'"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<Button size="sm" :disabled="!password.trim()" @click="savePassword">保存</Button>
|
||||
<Button
|
||||
v-if="hasPassword"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="clearPassword"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="远端根目录" description="该目录不存在时会自动逐级创建" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.remoteRoot"
|
||||
placeholder="thing-notes"
|
||||
@change="(e: Event) => patchWebdav({ remoteRoot: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="连接自检" description="验证地址与凭据,并列出远端已有文件数">
|
||||
<Button variant="outline" size="sm" :disabled="testing" @click="testConnection">
|
||||
<Loader2 v-if="testing" class="size-3.5 animate-spin" />
|
||||
<ShieldCheck v-else class="size-3.5" />
|
||||
测试连接
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 同步 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<CloudUpload class="size-4 text-primary" />
|
||||
同步
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
同步以本地库为准:远端只接收推送与拉取,不作为工作目录。库内
|
||||
<code class="font-mono">.notes/</code>(索引与同步基线)永不参与同步。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="同步方向" :description="DIRECTION_OPTIONS.find(o => o.value === webdav.direction)?.hint" control-width="wide">
|
||||
<Select
|
||||
:model-value="webdav.direction"
|
||||
@update:model-value="v => patchWebdav({ direction: v as SyncDirection })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in DIRECTION_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="冲突策略"
|
||||
description="仅双向同步时生效:两侧都改过的文件怎么处理"
|
||||
control-width="wide"
|
||||
>
|
||||
<Select
|
||||
:model-value="webdav.conflict"
|
||||
@update:model-value="v => patchWebdav({ conflict: v as ConflictPolicy })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in CONFLICT_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="启动时自动同步" description="应用启动后后台跑一次(失败只记日志,不打扰)">
|
||||
<Switch
|
||||
:model-value="webdav.autoSyncOnLaunch"
|
||||
@update:model-value="v => patchWebdav({ autoSyncOnLaunch: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="快照保留份数"
|
||||
description="远端 backups/ 目录里保留的 zip 数量,超出后删最旧的"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="webdav.backupKeep"
|
||||
@change="(e: Event) => patchWebdav({ backupKeep: Number((e.target as HTMLInputElement).value) || 7 })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<!-- 进度 -->
|
||||
<div v-if="store.syncing" class="flex flex-col gap-2 py-3">
|
||||
<div class="flex items-center gap-2 text-[13px] text-fg-secondary">
|
||||
<Loader2 class="size-3.5 shrink-0 animate-spin" />
|
||||
<span class="truncate">
|
||||
{{ store.syncProgress?.message || '同步中…' }}
|
||||
<span v-if="store.syncProgress?.current" class="text-muted-foreground">
|
||||
· {{ store.syncProgress.current }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="store.syncProgress?.total" class="ml-auto shrink-0 tabular-nums">
|
||||
{{ store.syncProgress.done }} / {{ store.syncProgress.total }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
class="h-full bg-primary transition-all duration-200"
|
||||
:style="{
|
||||
width: store.syncProgress?.total
|
||||
? `${Math.round(((store.syncProgress?.done ?? 0) / store.syncProgress.total) * 100)}%`
|
||||
: '8%'
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingRow label="立即操作" description="同步后会顺带上传一份 zip 快照(先同步再备份)">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button size="sm" :disabled="!configured || store.syncing" @click="syncNow">
|
||||
<ArrowUpFromLine class="size-3.5" />立即同步
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!configured || store.syncing" @click="backupNow">
|
||||
<Database class="size-3.5" />仅快照
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!configured || store.syncing" @click="exportLocalSnapshot">
|
||||
<ArrowDownToLine class="size-3.5" />导出到本地
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<!-- 最近一次结果 -->
|
||||
<div v-if="store.lastSyncReport" class="flex flex-wrap gap-x-4 gap-y-1 py-2 text-[11px] text-muted-foreground">
|
||||
<span>上次同步:上传 {{ store.lastSyncReport.uploaded }}</span>
|
||||
<span>下载 {{ store.lastSyncReport.downloaded }}</span>
|
||||
<span>改名 {{ store.lastSyncReport.moved }}</span>
|
||||
<span>删除 {{ store.lastSyncReport.deletedRemote + store.lastSyncReport.deletedLocal }}</span>
|
||||
<span :class="store.lastSyncReport.conflicts ? 'text-warning' : ''">
|
||||
冲突 {{ store.lastSyncReport.conflicts }}
|
||||
</span>
|
||||
<span :class="store.lastSyncReport.failed ? 'text-danger' : ''">
|
||||
失败 {{ store.lastSyncReport.failed }}
|
||||
</span>
|
||||
<span class="tabular-nums">{{ store.lastSyncReport.elapsedMs }}ms</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="store.lastSyncReport?.failures.length"
|
||||
class="flex flex-col gap-1 rounded-sm bg-danger/10 p-2 text-[11px] text-danger"
|
||||
>
|
||||
<span class="flex items-center gap-1 font-medium">
|
||||
<AlertTriangle class="size-3" />失败明细
|
||||
</span>
|
||||
<span v-for="(item, index) in store.lastSyncReport.failures" :key="index" class="truncate">
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 快照列表 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<HardDriveDownload class="size-4 text-primary" />
|
||||
远端快照
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="ml-auto"
|
||||
:disabled="!configured || store.loadingBackups"
|
||||
title="刷新快照列表"
|
||||
@click="store.loadBackups()"
|
||||
>
|
||||
<RefreshCw class="size-3.5" :class="store.loadingBackups && 'animate-spin'" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
恢复只会**补上本地缺失的文件**,不会覆盖你已有的笔记 —— 需要整库回退时,请先在
|
||||
资源管理器里移走旧库再恢复。
|
||||
</p>
|
||||
<StateBlock
|
||||
v-if="!store.backups.length"
|
||||
variant="empty"
|
||||
:title="configured ? '远端还没有快照' : '尚未配置 WebDAV'"
|
||||
:description="configured ? '点「仅快照」上传第一份' : undefined"
|
||||
:min-height="100"
|
||||
/>
|
||||
<div v-else class="flex flex-col divide-y divide-divider">
|
||||
<div
|
||||
v-for="item in store.backups"
|
||||
:key="item.name"
|
||||
class="flex items-center gap-3 py-2 text-[13px]"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate font-mono text-xs text-fg-secondary">
|
||||
{{ item.name }}
|
||||
</span>
|
||||
<span class="shrink-0 tabular-nums text-xs text-muted-foreground">
|
||||
{{ formatBytes(item.size) }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-muted-foreground">{{ formatTime(item.modified) }}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!!restoring"
|
||||
@click="restoreTarget = item.name"
|
||||
>
|
||||
<Loader2 v-if="restoring === item.name" class="size-3.5 animate-spin" />
|
||||
恢复
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="restoreOpen"
|
||||
title="从快照恢复"
|
||||
:description="`将把快照「${restoreTarget ?? ''}」里本地缺失的文件补进库根。已存在的文件不会被覆盖。`"
|
||||
confirm-text="开始恢复"
|
||||
@confirm="doRestore"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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) 和 。',
|
||||
'',
|
||||
'> 引用行',
|
||||
'',
|
||||
'- [ ] 待办',
|
||||
'- 普通项',
|
||||
'',
|
||||
'```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, /<b>&"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('')
|
||||
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\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 & B <C></title>'))
|
||||
assert.ok(html.includes('<h1 class="note-title">A & B <C></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}/)
|
||||
})
|
||||
@@ -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> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}
|
||||
|
||||
/** HTML 文本/属性转义:导出的每个动态值(标题、语言名、时间)都必须过这里 */
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replace(/[&<>"']/g, ch => HTML_ESCAPES[ch] ?? ch)
|
||||
}
|
||||
|
||||
/** 纯文本摘要里要还原的常见实体(` ` 还原成空格,交给后续空白折叠处理) */
|
||||
const ENTITY_TEXTS: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'",
|
||||
' ': ' '
|
||||
}
|
||||
|
||||
/** 行是不是 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)必须先于链接(保留文字)处理,否则 `` 会被链接规则切碎
|
||||
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 图片独占一行、且不在光标行上」时替换整段 `` ——
|
||||
* 与行内混排的图片(`见  所示`)保持源码形态:把行内图片换成块级
|
||||
* `<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` 节点的原始目标(`` 里 `target` 的原文)。 */
|
||||
function imageTarget(raw: string): { alt: string; target: string } | null {
|
||||
// 结构固定为 ``:找第一个 `](`,再从末尾去掉 `)`
|
||||
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 }
|
||||
)
|
||||
]
|
||||
}
|
||||
@@ -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), ' ## 缩进二级')
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||
|
||||
/**
|
||||
* 全局搜索索引(本模块无内部 Tab,`tab` 一律省略 —— 搜索后直接落在模块页)。
|
||||
*/
|
||||
const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '笔记',
|
||||
description: 'Markdown 笔记库:所见即所得编辑、本地存储、WebDAV 备份',
|
||||
keywords: ['笔记', 'notes', 'note', 'markdown', 'md', '文档', 'wiki', '知识库']
|
||||
},
|
||||
{
|
||||
title: '打开笔记编辑器',
|
||||
description: '在新窗口中打开笔记 / 编辑器(可多开)',
|
||||
keywords: ['打开', '编辑器', '窗口', '独立窗口', 'editor', '工作区']
|
||||
},
|
||||
{
|
||||
title: '新建笔记',
|
||||
description: '在笔记库中新建一篇 Markdown 笔记',
|
||||
keywords: ['新建', '新建笔记', 'new', '创建', 'create']
|
||||
},
|
||||
{
|
||||
title: '笔记库设置',
|
||||
description: '库根目录、编辑器主题、字体字号、自动保存',
|
||||
keywords: ['设置', '主题', '字体', '字号', '库目录', '库根', '自动保存', 'vscode', 'darcula']
|
||||
}
|
||||
]
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'notes',
|
||||
name: '笔记',
|
||||
icon: 'notes',
|
||||
description: 'Markdown 笔记库与代码编辑器(所见即所得 + 多语言高亮 + 独立窗口)',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./NotesModule.vue'),
|
||||
searchItems,
|
||||
// 默认排在终端(40)之后
|
||||
order: 45
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 笔记模块的 IPC 客户端:命令名的**唯一落点**。
|
||||
*
|
||||
* # 为什么不直接在组件/ store 里写 `invoke('notes_xxx')`
|
||||
*
|
||||
* P0 阶段本项目还没有为新增命令重新生成 `src/lib/bindings.ts`(那需要一次
|
||||
* debug 构建跑 `export_bindings`),于是新增命令的类型只能手写。手写类型散落在
|
||||
* 十几处调用点时会同步腐坏:后端改个字段,前端在另一个文件里仍然编译通过。
|
||||
* 因此这里做一层薄封装 —— **命令名与返回类型只在本文件出现一次**,
|
||||
* 待 `bindings.ts` 重新生成后,改这一个文件即可完成切换。
|
||||
*
|
||||
* 参数名一律用 snake_case 形态的 camelCase(`relPath` / `dirRel` …),与
|
||||
* tauri-specta 生成的调用约定一致;改错参数名会被 Tauri 在运行时报
|
||||
* `invalid args`,所以这里刻意不做「参数对象透传」的花活,只做显式形参。
|
||||
*/
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import type {
|
||||
BackupReport,
|
||||
BackupSnapshot,
|
||||
ImportReport,
|
||||
LibraryEntry,
|
||||
LibraryInfo,
|
||||
LinkEdge,
|
||||
NoteBacklinks,
|
||||
NoteDoc,
|
||||
NoteFileDoc,
|
||||
NoteIndexReport,
|
||||
NoteIndexStats,
|
||||
NoteSearchPage,
|
||||
NoteSearchQuery,
|
||||
NoteSettings,
|
||||
NoteTagCount,
|
||||
SyncOutcome,
|
||||
TemplateSource,
|
||||
WebdavStatus,
|
||||
WebdavTestResult
|
||||
} from '@/types/notes'
|
||||
import type { NoteSearchHit, NoteTemplate } from '@/types/notes'
|
||||
|
||||
export const notesClient = {
|
||||
// ===== 设置 =====
|
||||
getSettings: () => invoke<NoteSettings>('notes_get_settings'),
|
||||
saveSettings: (settings: NoteSettings) =>
|
||||
invoke<NoteSettings>('notes_save_settings', { settings }),
|
||||
|
||||
// ===== 库 =====
|
||||
libraryInfo: () => invoke<LibraryInfo>('notes_library_info'),
|
||||
setLibraryRoot: (root: string | null) => invoke<LibraryInfo>('notes_set_library_root', { root }),
|
||||
scanLibrary: () => invoke<LibraryEntry[]>('notes_scan_library'),
|
||||
readNote: (relPath: string) => invoke<NoteDoc>('notes_read_note', { relPath }),
|
||||
saveNote: (relPath: string, content: string) =>
|
||||
invoke<NoteDoc>('notes_save_note', { relPath, content }),
|
||||
createNote: (dirRel: string, name: string, templateId?: string) =>
|
||||
invoke<NoteDoc>('notes_create_note', { dirRel, name, templateId: templateId ?? null }),
|
||||
createFolder: (dirRel: string, name: string) =>
|
||||
invoke<null>('notes_create_folder', { dirRel, name }),
|
||||
renameEntry: (relPath: string, newName: string) =>
|
||||
invoke<string>('notes_rename_entry', { relPath, newName }),
|
||||
deleteEntry: (relPath: string) => invoke<null>('notes_delete_entry', { relPath }),
|
||||
/** 打开(或创建)今天的日记 */
|
||||
dailyNote: () => invoke<NoteDoc>('notes_daily_note'),
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
rebuildIndex: () => invoke<NoteIndexReport>('notes_rebuild_index'),
|
||||
syncIndex: () => invoke<NoteIndexReport>('notes_sync_index'),
|
||||
/** 全文检索 / 标签 / 目录筛选(`query` 与 Rust 侧 `NoteSearchQuery` 一一对应) */
|
||||
search: (query: NoteSearchQuery) => invoke<NoteSearchPage>('notes_search_notes', { query }),
|
||||
listNotes: (limit?: number) => invoke<NoteSearchHit[]>('notes_list_notes', { limit: limit ?? null }),
|
||||
tags: () => invoke<NoteTagCount[]>('notes_tags'),
|
||||
indexStats: () => invoke<NoteIndexStats>('notes_index_stats'),
|
||||
/** 一篇笔记的出链 / 入链 */
|
||||
backlinks: (relPath: string) => invoke<NoteBacklinks>('notes_backlinks', { relPath }),
|
||||
/** 全库链接图(已解析的内部链接边) */
|
||||
linkGraph: () => invoke<LinkEdge[]>('notes_link_graph'),
|
||||
/**
|
||||
* 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
*
|
||||
* 冷启动时 Rust 无法 `emit`(前端还没注册监听),因此改为前端主动取一次。
|
||||
*/
|
||||
takePendingFile: () => invoke<string | null>('notes_take_pending_file'),
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
openFile: (path: string) => invoke<NoteFileDoc>('notes_open_file', { path }),
|
||||
writeFile: (path: string, content: string, encoding: string, eol: string) =>
|
||||
invoke<NoteFileDoc>('notes_write_file', { path, content, encoding, eol }),
|
||||
/** 登记系统对话框选中的路径为「可写」(它不是经 `openFile` 打开的) */
|
||||
authorizeFile: (path: string) => invoke<null>('notes_authorize_file', { path }),
|
||||
/** 把 base64 图片写进库根 `assets/`,返回可插入 Markdown 的相对路径 */
|
||||
writeAsset: (fileName: string, ext: string, dataBase64: string) =>
|
||||
invoke<string>('notes_write_asset', { fileName, ext, dataBase64 }),
|
||||
/**
|
||||
* 把库内图片读成 `data:` URL(内联预览用)。
|
||||
*
|
||||
* 返回 `null` 表示「不适合预览」(非图片扩展名 / 超过大小上限)——
|
||||
* 不是错误,调用方按普通文本渲染即可。
|
||||
*/
|
||||
readAsset: (relPath: string) => invoke<string | null>('notes_read_asset', { relPath }),
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
listTemplates: () => invoke<NoteTemplate[]>('notes_list_templates'),
|
||||
/** 不带参数 = 把全部内置模板导出到库内 `templates/` */
|
||||
addTemplate: (name?: string, body?: string) =>
|
||||
invoke<string[]>('notes_add_template', { name: name ?? null, body: body ?? null }),
|
||||
readTemplate: (templateId: string) =>
|
||||
invoke<TemplateSource>('notes_read_template', { templateId }),
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
import: (source: string, destDir: string) =>
|
||||
invoke<ImportReport>('notes_import', { source, destDir }),
|
||||
/** 把渲染好的 HTML 写到用户选定的位置(渲染在前端,落盘在后端) */
|
||||
exportNote: (relPath: string, html: string, dest: string) =>
|
||||
invoke<string>('notes_export_note', { relPath, html, dest }),
|
||||
exportZip: (dest: string, dirRel?: string) =>
|
||||
invoke<string>('notes_export_zip', { dest, dirRel: dirRel ?? null }),
|
||||
exportSnapshotLocal: (dest?: string) =>
|
||||
invoke<string>('notes_export_snapshot_local', { dest: dest ?? null }),
|
||||
|
||||
// ===== WebDAV(P2) =====
|
||||
webdavStatus: () => invoke<WebdavStatus>('notes_webdav_status'),
|
||||
setWebdavPassword: (password: string) =>
|
||||
invoke<null>('notes_set_webdav_password', { password }),
|
||||
testWebdav: () => invoke<WebdavTestResult>('notes_test_webdav'),
|
||||
syncNow: () => invoke<SyncOutcome>('notes_sync_now'),
|
||||
backupNow: () => invoke<BackupReport>('notes_backup_now'),
|
||||
listBackups: () => invoke<BackupSnapshot[]>('notes_list_backups'),
|
||||
restoreBackup: (name: string) => invoke<ImportReport>('notes_restore_backup', { name })
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 笔记「独立窗口」的创建入口(由前端创建,范式同 terminal/openWindow.ts)。
|
||||
*
|
||||
* - label 前缀 `notes-window-` 命中 `capabilities/notes-window.json` 的 `notes-window-*` 授权;
|
||||
* - **隐藏创建**:窗口初始底色是白的,而主题要等前端读 localStorage 后才应用 ——
|
||||
* 直接显示会先闪一下纯白。由 NotesWindow.vue 应用完主题(含窗口效果)再自己 show;
|
||||
* - **同目标判重聚焦**(规划 §8-Q1 选 (a)):窗口默认多开,但「同一个文件开两个窗口」
|
||||
* 几乎总是误操作 —— 两个窗口各自自动保存,后写的会覆盖先写的。
|
||||
*
|
||||
* # label 里为什么是哈希而不是明文路径
|
||||
*
|
||||
* 判重需要「由目标反推出窗口 label」。用 `notes-window-<目标>` 最直观,但窗口 label
|
||||
* 会出现在系统任务栏与调试面板里,把绝对路径(含用户名、项目名)塞进去既不雅也
|
||||
* 不必要。改用 FNV-1a 哈希:**同样稳定、可反推 label、但不泄露路径**。
|
||||
* 哈希碰撞的后果只是「两个不同文件被当成同一个窗口」——32 位空间下这在单次会话里
|
||||
* 可以忽略,而代价(不判重)远小于把路径写进 label。
|
||||
*/
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
|
||||
/** label 前缀必须落在 `notes-window-*`(capability 的 glob)里 */
|
||||
const LABEL_PREFIX = `${WINDOWS.notesWindow}-`
|
||||
|
||||
/** FNV-1a 32 位哈希 → base36(稳定、短、无特殊字符)。 */
|
||||
function hashTarget(target: string): string {
|
||||
let hash = 0x811c9dc5
|
||||
for (let index = 0; index < target.length; index++) {
|
||||
hash ^= target.charCodeAt(index)
|
||||
hash = Math.imul(hash, 0x01000193) >>> 0
|
||||
}
|
||||
return hash.toString(36)
|
||||
}
|
||||
|
||||
/** 目标(相对路径或绝对路径)对应的窗口 label。 */
|
||||
export function labelForTarget(target: string): string {
|
||||
return `${LABEL_PREFIX}t${hashTarget(target)}`
|
||||
}
|
||||
|
||||
/** 聚焦已经打开该目标的窗口(找到返回 true)。 */
|
||||
async function focusTarget(target: string): Promise<boolean> {
|
||||
const existing = await WebviewWindow.getByLabel(labelForTarget(target))
|
||||
if (!existing) return false
|
||||
try {
|
||||
await existing.show()
|
||||
await existing.setFocus()
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个笔记窗口。
|
||||
*
|
||||
* @param options.relPath 可选:打开时直达的笔记(相对库根路径)
|
||||
* @param options.path 可选:打开时直达的**库外文件**(绝对路径,供 P1 的「打开文件」用)
|
||||
* @param options.dedupe 同一目标已开窗口时聚焦它(默认 true)
|
||||
*/
|
||||
export async function openNotesWindow(options?: {
|
||||
relPath?: string
|
||||
path?: string
|
||||
dedupe?: boolean
|
||||
}): Promise<void> {
|
||||
const isFile = !options?.relPath && !!options?.path
|
||||
const target = options?.relPath ?? options?.path ?? ''
|
||||
const query = target
|
||||
? `?${isFile ? 'path' : 'file'}=${encodeURIComponent(target)}`
|
||||
: ''
|
||||
|
||||
if (target && options?.dedupe !== false) {
|
||||
// 「复用文档窗口」是可关闭的设置(默认开)。关掉时每次新建窗口 ——
|
||||
// 有些用户确实想并排对照同一篇的不同位置。
|
||||
const reuse = useNotesStore().settings.reuseWindow
|
||||
if (reuse) {
|
||||
const focused = await focusTarget(target)
|
||||
if (focused) return
|
||||
}
|
||||
}
|
||||
|
||||
// 有目标时 label 由目标决定(于是「再点一次同一个文件」会命中上面那段判重)
|
||||
const label = target ? labelForTarget(target) : `${LABEL_PREFIX}${Date.now().toString(36)}`
|
||||
// label 已存在但判重被显式关掉:加时间戳后缀,避免 create 直接抛错
|
||||
const taken = await WebviewWindow.getByLabel(label)
|
||||
const finalLabel = taken ? `${label}-${Date.now().toString(36)}` : label
|
||||
|
||||
const win = new WebviewWindow(finalLabel, {
|
||||
url: `index.html#${WINDOWS.notesWindow}${query}`,
|
||||
title: '笔记',
|
||||
width: 1200,
|
||||
height: 800,
|
||||
minWidth: 760,
|
||||
minHeight: 480,
|
||||
resizable: true,
|
||||
decorations: false,
|
||||
// 透明通道用于承载 mica / acrylic(与主窗口一致的观感)
|
||||
transparent: true,
|
||||
shadow: true,
|
||||
center: true,
|
||||
visible: false,
|
||||
focus: false
|
||||
})
|
||||
|
||||
win.once('tauri://error', e => {
|
||||
logger.error(`打开笔记窗口失败:${String(e)}`)
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
win.once('tauri://created', () => resolve())
|
||||
win.once('tauri://error', e => reject(new Error(String(e))))
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user