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

No files matched your search

+21 -1
View File
@@ -8,12 +8,18 @@
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-go": "^6.0.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/lang-rust": "^6.0.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-sql": "^6.10.0",
"@codemirror/lang-vue": "^0.1.3",
"@codemirror/lang-xml": "^6.1.0",
@@ -26,9 +32,11 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.13",
"@lucide/vue": "^1.48.0",
"@replit/codemirror-lang-csharp": "^6.2.0",
"@replit/codemirror-lang-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.3.2",
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-autostart": "^2.6.0",
"@tauri-apps/plugin-autostart": "~2.6.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
"@tauri-apps/plugin-opener": "^2.7.0",
@@ -43,6 +51,8 @@
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"codemirror-lang-elixir": "^4.0.1",
"codemirror-lang-makefile": "^0.1.1",
"dompurify": "^3.4.16",
"highlight.js": "^11.12.0",
"markdown-it": "^15.0.2",
@@ -293,6 +303,10 @@
"@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "https://registry.npmmirror.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
"@replit/codemirror-lang-csharp": ["@replit/codemirror-lang-csharp@6.2.0", "https://registry.npmmirror.com/@replit/codemirror-lang-csharp/-/codemirror-lang-csharp-6.2.0.tgz", { "peerDependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-6utbaWkoymhoAXj051mkRp+VIJlpwUgCX9Toevz3YatiZsz512fw3OVCedXQx+WcR0wb6zVHjChnuxqfCLtFVQ=="],
"@replit/codemirror-lang-svelte": ["@replit/codemirror-lang-svelte@6.0.0", "https://registry.npmmirror.com/@replit/codemirror-lang-svelte/-/codemirror-lang-svelte-6.0.0.tgz", { "peerDependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.1", "@codemirror/lang-html": "^6.2.0", "@codemirror/lang-javascript": "^6.1.1", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/highlight": "^1.0.0", "@lezer/javascript": "^1.2.0", "@lezer/lr": "^1.0.0" } }, "sha512-U2OqqgMM6jKelL0GNWbAmqlu1S078zZNoBqlJBW+retTc5M4Mha6/Y2cf4SVg6ddgloJvmcSpt4hHrVoM4ePRA=="],
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.2", "https://registry.npmmirror.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", { "os": "android", "cpu": "arm" }, "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg=="],
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.2", "https://registry.npmmirror.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz", { "os": "android", "cpu": "arm64" }, "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw=="],
@@ -551,6 +565,10 @@
"clsx": ["clsx@2.1.1", "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
"codemirror-lang-elixir": ["codemirror-lang-elixir@4.0.1", "https://registry.npmmirror.com/codemirror-lang-elixir/-/codemirror-lang-elixir-4.0.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "lezer-elixir": "^1.0.0" } }, "sha512-z6W/XB4b7TZrp9EZYBGVq93vQfvKbff+1iM8YZaVErL0dguBAeLmVRlEv1NuDZHOP1qjJ3NwyibkUkNWn7q9VQ=="],
"codemirror-lang-makefile": ["codemirror-lang-makefile@0.1.1", "https://registry.npmmirror.com/codemirror-lang-makefile/-/codemirror-lang-makefile-0.1.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-aCmX0TIj88pQDFeBLmfhiE1ZYmLcWf2c9hk0pscbshCk1x1JO1314q67fbpSaPWm86fl8+wZ2gFuNPlVJ2iFzw=="],
"color-convert": ["color-convert@2.0.1", "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
@@ -677,6 +695,8 @@
"levn": ["levn@0.4.1", "https://registry.npmmirror.com/levn/-/levn-0.4.1.tgz", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
"lezer-elixir": ["lezer-elixir@1.1.3", "https://registry.npmmirror.com/lezer-elixir/-/lezer-elixir-1.1.3.tgz", { "dependencies": { "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.3.0" } }, "sha512-Ymc58/WhxdZS9yEOlnKbF3rdeBdFcPm4OEm26KMqA1Za9vztXi7I5qwGw1KxYmm3Nv0iDHq//EQyBwSEzKG9Mg=="],
"lightningcss": ["lightningcss@1.32.0", "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.32.0.tgz", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
+1 -1
View File
@@ -74,7 +74,7 @@
### 3.1 编辑器核心
- **打开方式**:最近文件 / 目录树 / 笔记库树 / 系统对话框 / 命令行 / 文件关联 / 资源管理器右键 / 拖入窗口。
- **打开方式**:最近文件 / 目录树 / 笔记库树 / 系统对话框 / 命令行 / 文件关联 / 资源管理器右键。
- **视图按类型自动选**:`.md`/`.markdown`/`.mdx` 默认 Markdown(Live Preview,可在状态栏切到源码);其余按扩展名加载语言高亮(`@codemirror/lang-*` 按需 `import()`)。
- **基础编辑**:行号、折叠、括号匹配、多光标、矩形选择、搜索替换(CM6 原生 `searchKeymap`)、转到行(`Alt+G`)、撤销栈、Tab 缩进。
- **快捷键**(窗口内,CM6 `keymap` 优先于全局):`Ctrl+S` 保存、`Ctrl+Shift+S` 另存为、`Ctrl+O` 打开、`Ctrl+P` 快速打开、`Ctrl+W` 关闭当前文档、`Ctrl+Tab` 文档间切换、`Ctrl+E` 切换编码、`Ctrl+Shift+M` 切换 Live Preview/源码。
+974 -66
View File
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -17,12 +17,18 @@
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-go": "^6.0.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/lang-rust": "^6.0.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-sql": "^6.10.0",
"@codemirror/lang-vue": "^0.1.3",
"@codemirror/lang-xml": "^6.1.0",
@@ -35,9 +41,11 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.13",
"@lucide/vue": "^1.48.0",
"@replit/codemirror-lang-csharp": "^6.2.0",
"@replit/codemirror-lang-svelte": "^6.0.0",
"@tailwindcss/vite": "^4.3.2",
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-autostart": "^2.6.0",
"@tauri-apps/plugin-autostart": "~2.6.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
"@tauri-apps/plugin-global-shortcut": "^2.4.0",
"@tauri-apps/plugin-opener": "^2.7.0",
@@ -52,6 +60,8 @@
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"codemirror-lang-elixir": "^4.0.1",
"codemirror-lang-makefile": "^0.1.1",
"dompurify": "^3.4.16",
"highlight.js": "^11.12.0",
"markdown-it": "^15.0.2",
+14 -13
View File
@@ -1694,7 +1694,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.2",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1967,7 +1967,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -2961,7 +2961,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.57.0",
"windows-core 0.61.2",
]
[[package]]
@@ -4127,7 +4127,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5378,7 +5378,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5983,7 +5983,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6040,7 +6040,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6621,7 +6621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7644,7 +7644,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7666,6 +7666,7 @@ dependencies = [
"base64 0.22.1",
"bytes",
"cbc 0.1.2",
"chardetng",
"chrono",
"cpal",
"dashmap",
@@ -8114,7 +8115,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8167,7 +8168,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8565,7 +8566,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.48.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -8586,7 +8587,7 @@ dependencies = [
"objc2-foundation",
"objc2-quartz-core",
"raw-window-handle",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
"windows-version",
]
+4
View File
@@ -30,6 +30,10 @@ async-trait = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
regex = "1"
# 编码统计探测(Firefox 的探测器):判断「非 UTF-8 文件到底是 Shift_JIS 还是
# GB18030」这类问题。GB18030 几乎能解码任意字节序列,「试解是否成功」不可靠,
# 会把日文 Shift_JIS 误判成中文 GB18030。
chardetng = "1.0"
serde_yaml = "0.9"
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
specta-typescript = "0.0.12"
+19
View File
@@ -0,0 +1,19 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "dsh-window",
"description": "Capability for the dsh startup progress window (#dsh-window). Self-drawn title bar + theme; only local app commands are invoked.",
"windows": ["dsh-window"],
"permissions": [
"core:default",
"core:window:allow-show",
"core:window:allow-hide",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-set-focus",
"core:window:allow-start-dragging",
"core:window:allow-set-theme",
"core:window:allow-set-background-color",
"core:event:allow-listen",
"core:event:allow-emit"
]
}
@@ -1,8 +1,8 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "notes-window",
"description": "Capability for the notes/editor windows (multi-open, label = notes-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
"windows": ["notes-window-*"],
"identifier": "editor-window",
"description": "Capability for the editor windows (multi-open, label = editor-window-<n>). Needs the CM6 editor's window controls, events (settings/library sync) and opener.",
"windows": ["editor-window-*"],
"permissions": [
"core:default",
"core:window:allow-show",
+1 -1
View File
@@ -61,7 +61,7 @@ impl SuppressState {
// saturating:异常路径下的多余 end 不应让计数下溢,否则会永久屏蔽
let _ = self
.burst
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
.try_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
Some(v.saturating_sub(1))
});
}
+25 -14
View File
@@ -26,9 +26,13 @@ pub mod windows {
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
#[allow(dead_code)]
pub const DSH_WEB: &str = "dsh-web";
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-<n>`(可多开)
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${EDITOR_WINDOW}-<n>`(可多开)
#[allow(dead_code)]
pub const NOTES_WINDOW: &str = "notes-window";
pub const EDITOR_WINDOW: &str = "editor-window";
/// dsh「启动进度」独立窗口(单例,由前端创建)。
/// 服务就绪后由前端打开真正的 [`DSH_WEB`] 窗口并关闭它。
#[allow(dead_code)]
pub const DSH_WINDOW: &str = "dsh-window";
}
/// Tauri 事件名(与前端 constants::EVENTS 对应)
@@ -37,8 +41,12 @@ pub mod events {
pub const TRAY_MENU_SHOW: &str = "tray-menu-show";
pub const TRAY_MENU_STATE_UPDATED: &str = "tray-menu-state-updated";
pub const TRAY_TOGGLE_OSD: &str = "tray:toggle-osd";
pub const TRAY_NEW_DOWNLOAD: &str = "tray:new-download";
pub const TRAY_OPEN_SETTINGS: &str = "tray:open-settings";
/// 托盘菜单「终端」:打开新建终端选择窗口(窗口由前端创建)
pub const TRAY_OPEN_TERMINAL: &str = "tray:open-terminal";
/// 托盘菜单「dsh」:打开 dsh 独立窗口(未启动时先显示启动进度)
pub const TRAY_OPEN_DSH: &str = "tray:open-dsh";
/// 托盘菜单「编辑器」:打开编辑器独立窗口(窗口由前端创建)
pub const TRAY_OPEN_EDITOR: &str = "tray:open-editor";
// 剪贴板
pub const CLIPBOARD_CHANGED: &str = "clipboard-changed";
pub const CLIPBOARD_POPUP_SHOW: &str = "clipboard-popup-show";
@@ -138,23 +146,26 @@ pub mod events {
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
pub const NOTES_SETTINGS: &str = "notes-settings";
pub const EDITOR_SETTINGS: &str = "editor-settings";
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
pub const NOTES_LIBRARY_CHANGED: &str = "notes-library-changed";
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 notes::index_service::NoteFileEvent)。
// 与 NOTES_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
pub const EDITOR_LIBRARY_CHANGED: &str = "editor-library-changed";
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 editor::index_service::NoteFileEvent)。
// 与 EDITOR_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
pub const NOTES_FILE_CHANGED: &str = "notes-file-changed";
// 笔记模块:WebDAV 同步进度(负载见 notes::types::SyncProgress)。
pub const EDITOR_FILE_CHANGED: &str = "editor-file-changed";
// 笔记模块:WebDAV 同步进度(负载见 editor::types::SyncProgress)。
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
pub const NOTES_SYNC_PROGRESS: &str = "notes-sync-progress";
pub const EDITOR_SYNC_PROGRESS: &str = "editor-sync-progress";
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
pub const NOTES_NEW_NOTE: &str = "notes-new-note";
pub const EDITOR_NEW_NOTE: &str = "editor-new-note";
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
pub const NOTES_OPEN_EDITOR: &str = "notes-open-editor";
pub const EDITOR_OPEN_EDITOR: &str = "editor-open-editor";
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
pub const NOTES_OPEN_FILE: &str = "notes-open-file";
pub const EDITOR_OPEN_FILE: &str = "editor-open-file";
// 笔记模块:需要打开一个**文件夹**(负载 `{ path }`)。
// 来源:资源管理器右键「用 Thing 编辑器打开」(目录 / 目录背景)。
pub const EDITOR_OPEN_FOLDER: &str = "editor-open-folder";
}
+8 -1
View File
@@ -210,12 +210,19 @@ impl DshManager {
.clone()
.ok_or_else(|| "未找到 npm(Node 分发中缺少 npm-cli.js)".to_string())?;
// 未指定版本时必须显式写成 `@latest`,**不能**只给裸包名:
// npm 对「裸包名且该包已存在于 prefix 下的 package.json」的语义是
// 「安装满足现有 range 的最新版」,而首次安装时 npm 自己写下的
// `@deepseek-ai/dsh: ^0.1.7-rc.2` 一旦遇到 0.2.x 就永远不满足,
// 于是 `npm install @deepseek-ai/dsh` 只会回一句 "up to date",
// 版本原地不动(这正是「更新到最新」点了没反应的根因)。
// 显式 tag/版本会覆盖 package.json 里的旧 range,npm 才会真正升级。
let spec = version
.as_deref()
.map(|v| v.trim())
.filter(|v| !v.is_empty())
.map(|v| format!("{DSH_PACKAGE}@{v}"))
.unwrap_or_else(|| DSH_PACKAGE.to_string());
.unwrap_or_else(|| format!("{DSH_PACKAGE}@latest"));
let install_dir = self.install_root();
// npm 的 prefix 目录不存在时由 npm 自己创建;这里先建一次,避免
+231
View File
@@ -0,0 +1,231 @@
//! 「用 Thing 打开」的参数解析与事件投递。
//!
//! # 两条入口,同一份逻辑
//!
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
//! 资源管理器右键菜单(`HKCU\...\shell\ThingEditor`)同样以参数形式传入文件/文件夹;
//! 2. **热启动**:应用已在运行时再次打开,会起第二个进程,由
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
//!
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`open_target_from_args`]。
//! 解析成功后统一发事件(文件走 `editor-open-file`、文件夹走 `editor-open-folder`),
//! **窗口由前端创建** —— Rust 侧不持有窗口 label 策略。
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::Serialize;
use specta::Type;
/// 一个待打开目标(文件或文件夹)。
#[derive(Debug, Clone)]
pub enum OpenTarget {
File(PathBuf),
/// 文件夹:由编辑器「本地目录」面板承载
Folder(PathBuf),
}
impl OpenTarget {
pub fn path(&self) -> &Path {
match self {
Self::File(p) | Self::Folder(p) => p,
}
}
pub fn kind(&self) -> &'static str {
match self {
Self::File(_) => "file",
Self::Folder(_) => "folder",
}
}
}
/// 回传给前端的待打开目标。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct OpenTargetPayload {
/// 绝对路径
pub path: String,
/// `"file"` | `"folder"`
pub kind: String,
}
impl From<&OpenTarget> for OpenTargetPayload {
fn from(target: &OpenTarget) -> Self {
Self {
path: target.path().to_string_lossy().to_string(),
kind: target.kind().to_string(),
}
}
}
/// 「启动时命令行指定的目标」缓存。
///
/// # 为什么需要缓存而不是启动时直接 `emit`
///
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
/// 「双击 .md 打开了应用,但笔记没打开」。
///
/// 因此这里把目标存下来,由前端在注册完监听后**主动取一次**
/// (`editor_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
static PENDING: std::sync::OnceLock<Mutex<Option<OpenTarget>>> = std::sync::OnceLock::new();
fn pending_slot() -> &'static Mutex<Option<OpenTarget>> {
PENDING.get_or_init(|| Mutex::new(None))
}
/// 记下「启动时想打开的目标」(由 `setup` 调用)。
pub fn remember_pending_target(target: OpenTarget) {
if let Ok(mut slot) = pending_slot().lock() {
*slot = Some(target);
}
}
/// 取出并清空待打开目标(由 `editor_take_pending_file` 命令调用)。
pub fn take_pending_target() -> Option<OpenTargetPayload> {
pending_slot()
.lock()
.ok()
.and_then(|mut slot| slot.take())
.map(|target| OpenTargetPayload::from(&target))
}
/// 从一组命令行参数里挑出「看起来是要打开的路径」。
///
/// 只认「**存在**的路径」,其余一律忽略 —— 宁可漏开一个窗口,也不要因为一个开关
/// 参数把主窗口的启动逻辑搞乱。目录优先(右键文件夹的场景)。
pub fn open_target_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<OpenTarget> {
for arg in args {
let trimmed = arg.trim().trim_matches('"');
if trimmed.is_empty() || trimmed.starts_with('-') {
continue;
}
let path = PathBuf::from(trimmed);
if path.is_dir() {
return Some(OpenTarget::Folder(path));
}
if path.is_file() {
return Some(OpenTarget::File(path));
}
}
None
}
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径(仅 `.md`/`.markdown`/`.mdx`)。
///
/// 实际启动路径用的是 [`open_target_from_args`](接受任意文件与文件夹,以支持资源
/// 管理器右键菜单);这个更严格的入口现在**只服务于单测**,故仅测试构建时编译。
#[cfg(test)]
pub fn note_path_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<PathBuf> {
for arg in args {
let trimmed = arg.trim().trim_matches('"');
if trimmed.is_empty() || trimmed.starts_with('-') {
continue;
}
let lower = trimmed.to_ascii_lowercase();
let is_note_ext =
lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".mdx");
if !is_note_ext {
continue;
}
let path = PathBuf::from(trimmed);
if path.is_file() {
return Some(path);
}
}
None
}
/// 通知前端「要打开这个目标」(窗口由前端创建)。
pub fn emit_open_target(app: &tauri::AppHandle, target: &OpenTarget) {
use tauri::Emitter;
let payload = serde_json::json!({ "path": target.path().to_string_lossy() });
let event = match target {
OpenTarget::File(_) => crate::constants::events::EDITOR_OPEN_FILE,
OpenTarget::Folder(_) => crate::constants::events::EDITOR_OPEN_FOLDER,
};
if let Err(e) = app.emit(event, payload) {
crate::logger::log_warn("editor", &format!("发出打开目标事件失败: {e}"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_note(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, "# x").unwrap();
path
}
#[test]
fn picks_markdown_path_and_ignores_flags() {
let note = temp_note("会议.md");
let args = vec![
"--some-flag".to_string(),
"not-a-file".to_string(),
note.to_string_lossy().to_string(),
];
assert_eq!(note_path_from_args(args), Some(note.clone()));
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
#[test]
fn accepts_markdown_and_mdx_too() {
let note = temp_note("a.markdown");
assert_eq!(
note_path_from_args(vec![note.to_string_lossy().to_string()]),
Some(note.clone())
);
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
#[test]
fn ignores_non_markdown_and_missing_files() {
// 非笔记扩展名
assert_eq!(note_path_from_args(vec!["C:\\a\\b.txt".to_string()]), None);
// 不存在的 .md:静默忽略(否则会开一个空窗口)
assert_eq!(
note_path_from_args(vec!["C:\\definitely\\missing\\x.md".to_string()]),
None
);
// 空参数与开关
assert_eq!(
note_path_from_args(vec!["".to_string(), "-v".to_string()]),
None
);
}
#[test]
fn strips_surrounding_quotes() {
let note = temp_note("带 空格.md");
let quoted = format!("\"{}\"", note.to_string_lossy());
assert_eq!(note_path_from_args(vec![quoted]), Some(note.clone()));
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
/// 右键菜单:任意扩展名的文件都要被接受(不只 .md)。
#[test]
fn open_target_accepts_any_file_and_folder() {
let file = temp_note("plain.txt");
match open_target_from_args(vec![file.to_string_lossy().to_string()]) {
Some(OpenTarget::File(p)) => assert_eq!(p, file),
other => panic!("应识别为文件: {other:?}"),
}
let dir = file.parent().unwrap().to_path_buf();
match open_target_from_args(vec![dir.to_string_lossy().to_string()]) {
Some(OpenTarget::Folder(p)) => assert_eq!(p, dir),
other => panic!("应识别为文件夹: {other:?}"),
}
let _ = std::fs::remove_file(&file);
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -11,7 +11,7 @@
//! # 打包内容
//!
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
//! (记录快照时间、文件数、格式版本)。**不打包 `.notes/`**:里面是索引与同步基线,
//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线,
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
//!
//! # 轮转
@@ -23,8 +23,8 @@
use std::io::Write;
use std::path::{Path, PathBuf};
use super::webdav::client::WebdavClient;
use crate::notes::library;
use crate::notes::types::{BackupReport, BackupSnapshot, WebdavSettings};
use crate::editor::library;
use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings};
/// 远端存放快照的目录(相对远端根)。
pub const BACKUP_DIR: &str = "backups";
@@ -63,14 +63,14 @@ pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
if rel.is_empty() {
continue;
}
// `.notes/` 是本机私有数据(索引 + 同步基线),不进快照
// `.editor/` 是本机私有数据(索引 + 同步基线),不进快照
if rel.split('/').any(|part| part.starts_with('.')) {
continue;
}
let bytes = match std::fs::read(entry.path()) {
Ok(bytes) => bytes,
Err(e) => {
crate::logger::log_warn("notes", &format!("快照跳过 {rel}(读取失败: {e})"));
crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})"));
continue;
}
};
@@ -138,7 +138,7 @@ pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>,
let mut pruned = Vec::new();
for snapshot in snapshots.into_iter().take(outdated) {
if let Err(e) = client.delete(&format!("{BACKUP_DIR}/{}", snapshot.name)) {
crate::logger::log_warn("notes", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
continue;
}
pruned.push(snapshot.name);
@@ -201,7 +201,7 @@ pub fn restore_snapshot(
.map_err(|e| format!("读取快照条目失败: {e}"))?;
let Some(entry_path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
// `enclosed_name` 会拒绝 `..` 与绝对路径 —— 恶意快照不能写到库外
crate::logger::log_warn("notes", "快照里有越界路径,已跳过");
crate::logger::log_warn("editor", "快照里有越界路径,已跳过");
continue;
};
let rel = entry_path.to_string_lossy().replace('\\', "/");
@@ -246,17 +246,17 @@ pub fn sync_then_backup(
if report.failed == 0 {
state.last_sync = chrono::Local::now().timestamp_millis().max(0) as u64;
if let Err(e) = state.save(root) {
crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}"));
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
}
} else {
crate::logger::log_warn(
"notes",
"editor",
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
);
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
// 于是下一轮会把它们重新算作差异并重试
if let Err(e) = state.save(root) {
crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}"));
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
}
}
@@ -301,14 +301,14 @@ mod tests {
}
#[test]
fn snapshot_contains_notes_and_assets_but_not_private_dir() {
fn snapshot_excludes_private_dir() {
let root = temp_root("build");
std::fs::write(root.join("a.md"), "# A").unwrap();
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("sub/b.md"), "# B").unwrap();
std::fs::write(root.join("assets/pic.png"), [1u8, 2, 3]).unwrap();
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::write(root.join(".notes/notes.db"), "索引不该进快照").unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::write(root.join(".editor/editor.db"), "索引不该进快照").unwrap();
let (bytes, files) = build_snapshot(&root).unwrap();
assert_eq!(files, 3, "两篇笔记 + 一个附件");
@@ -323,7 +323,7 @@ mod tests {
assert!(names.contains(&"assets/pic.png".to_string()), "{names:?}");
assert!(names.contains(&MANIFEST_NAME.to_string()), "{names:?}");
assert!(
!names.iter().any(|n| n.starts_with(".notes")),
!names.iter().any(|n| n.starts_with(".editor")),
"私有目录不该进快照: {names:?}"
);
@@ -33,35 +33,35 @@ use super::index_service::{self, IndexService, NoteIndexReport};
use super::library;
use super::templates::{self, NoteTemplate};
use super::types::{
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, NoteSettings,
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings,
SyncProgress,
};
use super::webdav::{self, WebdavTestResult};
use super::NotesManager;
use super::EditorManager;
use crate::constants::events;
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
fn emit_library_changed(app: &AppHandle) {
if let Err(e) = app.emit(events::NOTES_LIBRARY_CHANGED, ()) {
crate::logger::log_warn("notes", &format!("发出库变更事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_LIBRARY_CHANGED, ()) {
crate::logger::log_warn("editor", &format!("发出库变更事件失败: {e}"));
}
}
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
fn emit_settings_changed(app: &AppHandle) {
if let Err(e) = app.emit(events::NOTES_SETTINGS, ()) {
crate::logger::log_warn("notes", &format!("发出设置变更事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) {
crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}"));
}
}
/// 当前库根(按设置解析),并确保目录存在。
fn current_root(state: &NotesManager) -> PathBuf {
fn current_root(state: &EditorManager) -> PathBuf {
let settings = state.load_settings();
library::resolve_library_root(state.module_dir(), &settings)
}
/// 取索引服务并把它的库根对齐到当前设置。
fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService, String> {
fn indexed<'a>(app: &AppHandle, state: &EditorManager) -> Result<&'a IndexService, String> {
let root = current_root(state);
let service = index_service::service(app);
service.retarget(root)?;
@@ -69,7 +69,7 @@ fn indexed<'a>(app: &AppHandle, state: &NotesManager) -> Result<&'a IndexService
}
/// 组装库状态概览。
fn library_info(state: &NotesManager) -> Result<LibraryInfo, String> {
fn library_info(state: &EditorManager) -> Result<LibraryInfo, String> {
let settings = state.load_settings();
let root = library::resolve_library_root(state.module_dir(), &settings);
library::ensure_library(&root)?;
@@ -85,21 +85,48 @@ fn library_info(state: &NotesManager) -> Result<LibraryInfo, String> {
})
}
/// 标记「本应用刚写过」,随后把库同步进索引。
/// 标记「本应用刚**批量**写过」,随后把库同步进索引。
///
/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后
/// 在抑制窗口内的一切文件事件都当作自己写的。
///
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
fn mark_written_then_index(app: &AppHandle, state: &EditorManager) {
match indexed(app, state) {
Ok(service) => {
service.mark_write();
service.mark_write_all();
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("保存后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
}
}
Err(e) => crate::logger::log_warn("notes", &format!("索引服务不可用: {e}")),
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
/// 写入前登记「本应用即将写这一篇笔记」(按库内相对路径)。
///
/// **必须在 `library::write_note` 之前调用**:notify 的 Modify 事件可能与写入几乎
/// 同时到达索引 worker,晚于写盘再登记就会漏过 —— 前端便会把自家的保存当成
/// 「外部修改」,进而重载文档、把光标弹回第一行。
fn mark_pending_note_write(app: &AppHandle, state: &EditorManager, rel_path: &str) {
match indexed(app, state) {
Ok(service) => service.mark_write_path(rel_path),
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
/// 把库同步进索引(不登记自我写入 —— 调用方已在写入前按路径登记过)。
fn sync_index_after_write(app: &AppHandle, state: &EditorManager) {
match indexed(app, state) {
Ok(service) => {
if let Err(e) = service.sync() {
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
}
}
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
}
}
@@ -108,18 +135,36 @@ fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
/// 读取笔记模块设置。
#[tauri::command]
#[specta::specta]
pub fn notes_get_settings(state: State<'_, NotesManager>) -> Result<NoteSettings, String> {
pub fn editor_get_settings(state: State<'_, EditorManager>) -> Result<EditorSettings, String> {
Ok(state.load_settings())
}
/// 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。
///
/// 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿,
/// 收尾交给「关闭该文件时选择保存 / 删除」。
///
/// # 为什么不放在**安装目录**
///
/// 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败;
/// 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的
/// 标准位置,且卸载时随程序数据一起清理。
#[tauri::command]
#[specta::specta]
pub fn editor_scratch_dir(state: State<'_, EditorManager>) -> Result<String, String> {
let dir = state.module_dir().join("scratch");
std::fs::create_dir_all(&dir).map_err(|e| format!("创建临时目录失败:{e}"))?;
Ok(dir.to_string_lossy().to_string())
}
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
#[tauri::command]
#[specta::specta]
pub fn notes_save_settings(
pub fn editor_save_settings(
app: AppHandle,
state: State<'_, NotesManager>,
settings: NoteSettings,
) -> Result<NoteSettings, String> {
state: State<'_, EditorManager>,
settings: EditorSettings,
) -> Result<EditorSettings, String> {
let mut next = settings;
next.heal();
state.save_settings(&next)?;
@@ -133,16 +178,16 @@ pub fn notes_save_settings(
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
#[tauri::command]
#[specta::specta]
pub fn notes_library_info(state: State<'_, NotesManager>) -> Result<LibraryInfo, String> {
pub fn editor_library_info(state: State<'_, EditorManager>) -> Result<LibraryInfo, String> {
library_info(&state)
}
/// 设置库根(`None` 或空串 = 恢复默认库根)。
#[tauri::command]
#[specta::specta]
pub fn notes_set_library_root(
pub fn editor_set_library_root(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
root: Option<String>,
) -> Result<LibraryInfo, String> {
let cleaned = root.and_then(|r| {
@@ -177,7 +222,7 @@ pub fn notes_set_library_root(
/// 扫描库,返回扁平条目列表(前端组树)。
#[tauri::command]
#[specta::specta]
pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryEntry>, String> {
pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result<Vec<LibraryEntry>, String> {
let root = current_root(&state);
library::ensure_library(&root)?;
library::scan(&root)
@@ -186,7 +231,7 @@ pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryE
/// 读取一篇笔记。
#[tauri::command]
#[specta::specta]
pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Result<NoteDoc, String> {
pub fn editor_read_note(state: State<'_, EditorManager>, rel_path: String) -> Result<NoteDoc, String> {
let root = current_root(&state);
library::read_note(&root, &rel_path)
}
@@ -194,15 +239,17 @@ pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Resu
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
#[tauri::command]
#[specta::specta]
pub fn notes_save_note(
pub fn editor_save_note(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
content: String,
) -> Result<NoteDoc, String> {
let root = current_root(&state);
// 先登记「即将写这一篇」,再落盘:notify 的事件可能与写入同时抵达 worker
mark_pending_note_write(&app, &state, &rel_path);
let doc = library::write_note(&root, &rel_path, &content)?;
mark_written_then_index(&app, &state);
sync_index_after_write(&app, &state);
emit_library_changed(&app);
Ok(doc)
}
@@ -213,9 +260,9 @@ pub fn notes_save_note(
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
#[tauri::command]
#[specta::specta]
pub fn notes_create_note(
pub fn editor_create_note(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
dir_rel: String,
name: String,
template_id: Option<String>,
@@ -236,7 +283,7 @@ pub fn notes_create_note(
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
#[tauri::command]
#[specta::specta]
pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Result<NoteDoc, String> {
pub fn editor_daily_note(app: AppHandle, state: State<'_, EditorManager>) -> Result<NoteDoc, String> {
let root = current_root(&state);
let name = templates::daily_note_name();
let dir = "日记";
@@ -261,9 +308,9 @@ pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Resul
/// 新建文件夹。
#[tauri::command]
#[specta::specta]
pub fn notes_create_folder(
pub fn editor_create_folder(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
dir_rel: String,
name: String,
) -> Result<(), String> {
@@ -276,9 +323,9 @@ pub fn notes_create_folder(
/// 重命名条目,返回新相对路径。
#[tauri::command]
#[specta::specta]
pub fn notes_rename_entry(
pub fn editor_rename_entry(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
new_name: String,
) -> Result<String, String> {
@@ -287,7 +334,7 @@ pub fn notes_rename_entry(
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
if let Ok(service) = indexed(&app, &state) {
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("改名后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}"));
}
}
emit_library_changed(&app);
@@ -297,16 +344,16 @@ pub fn notes_rename_entry(
/// 删除条目(目录递归删除)。
#[tauri::command]
#[specta::specta]
pub fn notes_delete_entry(
pub fn editor_delete_entry(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<(), String> {
let root = current_root(&state);
library::delete_entry(&root, &rel_path)?;
if let Ok(service) = indexed(&app, &state) {
if let Err(e) = service.sync() {
crate::logger::log_warn("notes", &format!("删除后同步索引失败: {e}"));
crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}"));
}
}
emit_library_changed(&app);
@@ -318,9 +365,9 @@ pub fn notes_delete_entry(
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
#[tauri::command]
#[specta::specta]
pub fn notes_rebuild_index(
pub fn editor_rebuild_index(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexReport, String> {
let service = indexed(&app, &state)?;
let report = service.rebuild()?;
@@ -330,9 +377,9 @@ pub fn notes_rebuild_index(
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
#[tauri::command]
#[specta::specta]
pub fn notes_sync_index(
pub fn editor_sync_index(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexReport, String> {
let service = indexed(&app, &state)?;
let report = service.sync()?;
@@ -350,9 +397,9 @@ fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -
/// 全文检索 / 按标签 / 按目录筛选。
#[tauri::command]
#[specta::specta]
pub fn notes_search_notes(
pub fn editor_search_notes(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
query: NoteSearchQuery,
) -> Result<NoteSearchPage, String> {
let service = indexed(&app, &state)?;
@@ -362,9 +409,9 @@ pub fn notes_search_notes(
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
#[tauri::command]
#[specta::specta]
pub fn notes_list_notes(
pub fn editor_list_notes(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
limit: Option<i64>,
) -> Result<Vec<NoteSearchHit>, String> {
let service = indexed(&app, &state)?;
@@ -374,9 +421,9 @@ pub fn notes_list_notes(
/// 标签及计数。
#[tauri::command]
#[specta::specta]
pub fn notes_tags(
pub fn editor_tags(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<Vec<super::index::NoteTagCount>, String> {
let service = indexed(&app, &state)?;
service.tags()
@@ -385,9 +432,9 @@ pub fn notes_tags(
/// 一篇笔记的链接关系(出链 + 入链)。
#[tauri::command]
#[specta::specta]
pub fn notes_backlinks(
pub fn editor_backlinks(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<NoteBacklinks, String> {
let service = indexed(&app, &state)?;
@@ -397,9 +444,9 @@ pub fn notes_backlinks(
/// 全库链接图(已解析的内部链接边)。
#[tauri::command]
#[specta::specta]
pub fn notes_link_graph(
pub fn editor_link_graph(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<Vec<LinkEdge>, String> {
let service = indexed(&app, &state)?;
let edges = service.link_graph()?;
@@ -421,9 +468,9 @@ pub struct LinkEdge {
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
#[tauri::command]
#[specta::specta]
pub fn notes_index_stats(
pub fn editor_index_stats(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<NoteIndexStats, String> {
let service = indexed(&app, &state)?;
service.stats()
@@ -451,8 +498,8 @@ const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
#[tauri::command]
#[specta::specta]
pub fn notes_read_asset(
state: State<'_, NotesManager>,
pub fn editor_read_asset(
state: State<'_, EditorManager>,
rel_path: String,
) -> Result<Option<String>, String> {
let root = current_root(&state);
@@ -479,7 +526,7 @@ pub fn notes_read_asset(
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
if meta.len() > MAX_ASSET_BYTES {
crate::logger::log_info(
"notes",
"editor",
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
);
return Ok(None);
@@ -493,11 +540,11 @@ pub fn notes_read_asset(
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
///
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
/// 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。
/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
#[tauri::command]
#[specta::specta]
pub fn notes_take_pending_file() -> Result<Option<String>, String> {
Ok(super::args::take_pending_file().map(|path| super::files::display_path(&path)))
pub fn editor_take_pending_file() -> Result<Option<super::args::OpenTargetPayload>, String> {
Ok(super::args::take_pending_target())
}
/// 打开(读取)库外任意文件。
@@ -506,8 +553,8 @@ pub fn notes_take_pending_file() -> Result<Option<String>, String> {
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
#[tauri::command]
#[specta::specta]
pub fn notes_open_file(
state: State<'_, NotesManager>,
pub fn editor_open_file(
state: State<'_, EditorManager>,
path: String,
) -> Result<files::FileDoc, String> {
let settings = state.load_settings();
@@ -517,9 +564,9 @@ pub fn notes_open_file(
/// 保存库外任意文件(按前端回传的编码与换行写回)。
#[tauri::command]
#[specta::specta]
pub fn notes_write_file(
pub fn editor_write_file(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
path: String,
content: String,
encoding: String,
@@ -528,18 +575,32 @@ pub fn notes_write_file(
let settings = state.load_settings();
let doc = files::write_file(&path, &content, &encoding, &eol, settings.max_file_size_mb)?;
if let Ok(service) = indexed(&app, &state) {
service.mark_write();
// 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制;
// 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。
service.mark_write_all();
}
Ok(doc)
}
/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。
#[tauri::command]
#[specta::specta]
pub fn editor_redecode_file(
state: State<'_, EditorManager>,
path: String,
encoding: String,
) -> Result<files::FileDoc, String> {
let settings = state.load_settings();
files::redecode_file(&path, &encoding, settings.max_file_size_mb)
}
/// 显式登记一个路径为「可写」。
///
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
#[tauri::command]
#[specta::specta]
pub fn notes_authorize_file(path: String) -> Result<(), String> {
pub fn editor_authorize_file(path: String) -> Result<(), String> {
if path.trim().is_empty() {
return Err("路径为空".to_string());
}
@@ -554,8 +615,8 @@ pub fn notes_authorize_file(path: String) -> Result<(), String> {
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
#[tauri::command]
#[specta::specta]
pub fn notes_write_asset(
state: State<'_, NotesManager>,
pub fn editor_write_asset(
state: State<'_, EditorManager>,
file_name: String,
ext: String,
data_base64: String,
@@ -577,7 +638,7 @@ pub fn notes_write_asset(
/// 就能直接写文件,不需要用户先去资源管理器建目录。
#[tauri::command]
#[specta::specta]
pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result<Vec<NoteTemplate>, String> {
pub fn editor_list_templates(state: State<'_, EditorManager>) -> Result<Vec<NoteTemplate>, String> {
let root = current_root(&state);
library::ensure_library(&root)?;
let _ = templates::ensure_dir(&root);
@@ -591,9 +652,9 @@ pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result<Vec<NoteTe
/// - 传 `name` + `body`:新建一个自定义模板。
#[tauri::command]
#[specta::specta]
pub fn notes_add_template(
pub fn editor_add_template(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
name: Option<String>,
body: Option<String>,
) -> Result<Vec<String>, String> {
@@ -623,8 +684,8 @@ pub fn notes_add_template(
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
#[tauri::command]
#[specta::specta]
pub fn notes_read_template(
state: State<'_, NotesManager>,
pub fn editor_read_template(
state: State<'_, EditorManager>,
template_id: String,
) -> Result<TemplateSource, String> {
let root = current_root(&state);
@@ -649,9 +710,9 @@ pub struct TemplateSource {
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
#[tauri::command]
#[specta::specta]
pub fn notes_import(
pub fn editor_import(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
source: String,
dest_dir: String,
) -> Result<ImportReport, String> {
@@ -668,8 +729,8 @@ pub fn notes_import(
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
#[tauri::command]
#[specta::specta]
pub fn notes_export_note(
state: State<'_, NotesManager>,
pub fn editor_export_note(
state: State<'_, EditorManager>,
rel_path: String,
html: String,
dest: String,
@@ -687,7 +748,7 @@ pub fn notes_export_note(
let bytes = html.into_bytes();
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
crate::logger::log_info(
"notes",
"editor",
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
);
Ok(target.to_string_lossy().to_string())
@@ -696,8 +757,8 @@ pub fn notes_export_note(
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
#[tauri::command]
#[specta::specta]
pub fn notes_export_zip(
state: State<'_, NotesManager>,
pub fn editor_export_zip(
state: State<'_, EditorManager>,
dest: String,
dir_rel: Option<String>,
) -> Result<String, String> {
@@ -713,7 +774,7 @@ pub fn notes_export_zip(
}
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
crate::logger::log_info(
"notes",
"editor",
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
);
Ok(dest_path.to_string_lossy().to_string())
@@ -721,13 +782,13 @@ pub fn notes_export_zip(
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
///
/// 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
#[tauri::command]
#[specta::specta]
pub fn notes_export_snapshot_local(
state: State<'_, NotesManager>,
pub fn editor_export_snapshot_local(
state: State<'_, EditorManager>,
dest: Option<String>,
) -> Result<String, String> {
let root = current_root(&state);
@@ -745,7 +806,7 @@ pub fn notes_export_snapshot_local(
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
#[tauri::command]
#[specta::specta]
pub fn notes_webdav_status(state: State<'_, NotesManager>) -> Result<WebdavStatus, String> {
pub fn editor_webdav_status(state: State<'_, EditorManager>) -> Result<WebdavStatus, String> {
let settings = state.load_settings();
let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD)
.ok()
@@ -773,7 +834,7 @@ pub struct WebdavStatus {
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
#[tauri::command]
#[specta::specta]
pub fn notes_set_webdav_password(password: String) -> Result<(), String> {
pub fn editor_set_webdav_password(password: String) -> Result<(), String> {
if password.trim().is_empty() {
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
}
@@ -783,8 +844,8 @@ pub fn notes_set_webdav_password(password: String) -> Result<(), String> {
/// 连接自检(建目录 + 列远端)。
#[tauri::command]
#[specta::specta]
pub async fn notes_test_webdav(
state: State<'_, NotesManager>,
pub async fn editor_test_webdav(
state: State<'_, EditorManager>,
) -> Result<WebdavTestResult, String> {
let settings = state.load_settings().webdav;
run_blocking(move || webdav::test_connection(&settings)).await
@@ -793,9 +854,9 @@ pub async fn notes_test_webdav(
/// 立即同步(并按设置决定是否追加一次快照备份)。
#[tauri::command]
#[specta::specta]
pub async fn notes_sync_now(
pub async fn editor_sync_now(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
) -> Result<SyncOutcome, String> {
let settings = state.load_settings();
let webdav = settings.webdav.clone();
@@ -804,7 +865,7 @@ pub async fn notes_sync_now(
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
let _ = app.emit(
events::NOTES_SYNC_PROGRESS,
events::EDITOR_SYNC_PROGRESS,
SyncProgress {
done: 0,
total: 0,
@@ -843,8 +904,8 @@ pub struct SyncOutcome {
/// 只做一次 zip 快照备份(不上传增量)。
#[tauri::command]
#[specta::specta]
pub async fn notes_backup_now(
state: State<'_, NotesManager>,
pub async fn editor_backup_now(
state: State<'_, EditorManager>,
) -> Result<BackupReport, String> {
let settings = state.load_settings();
let webdav = settings.webdav.clone();
@@ -861,8 +922,8 @@ pub async fn notes_backup_now(
/// 列出远端已有快照。
#[tauri::command]
#[specta::specta]
pub async fn notes_list_backups(
state: State<'_, NotesManager>,
pub async fn editor_list_backups(
state: State<'_, EditorManager>,
) -> Result<Vec<BackupSnapshot>, String> {
let settings = state.load_settings().webdav;
run_blocking(move || {
@@ -875,9 +936,9 @@ pub async fn notes_list_backups(
/// 从远端快照恢复(不覆盖本地已有文件)。
#[tauri::command]
#[specta::specta]
pub async fn notes_restore_backup(
pub async fn editor_restore_backup(
app: AppHandle,
state: State<'_, NotesManager>,
state: State<'_, EditorManager>,
name: String,
) -> Result<ImportReport, String> {
let settings = state.load_settings();
+147
View File
@@ -0,0 +1,147 @@
//! 编辑器「本地目录」命令层:直接操作用户真实文件系统(不进索引、无沙箱)。
//!
//! # 为什么复用 `terminal::local_fs`
//!
//! 列举 / 新建目录 / 重命名 / **回收站删除** 在终端模块的「本地栏」已经实现过,
//! 且把「目录/文件分流」「不弹系统错误对话框」「拒绝删除盘符根」这些细节处理好了。
//! 这里只补它没有的两件事:
//! 1. **新建文件**(空文本,终端本地栏只建目录);
//! 2. **重名一律报错**——目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件。
//!
//! # 安全边界(与终端同一姿态)
//!
//! 路径来自用户自己的浏览/输入,不做「限制在本目录根下」的约束(那是本地文件管理器,
//! 限制根只会挡住用户自己)。唯一硬守卫是 **拒绝删除盘符根**(已在
//! [`terminal::local_fs::delete`] 内实现),且删除一律走回收站。
use std::path::Path;
use serde::Serialize;
use specta::Type;
use super::library::validate_name;
use crate::terminal::local_fs;
/// 批量删除结果(回传前端展示「成功 N 项、失败明细」)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DeleteReport {
/// 成功移入回收站的项数
pub removed: u32,
/// 失败明细(路径 + 原因)
pub failed: Vec<String>,
}
/// 列举本地目录(`path` 为空 = 用户主目录)。
#[tauri::command]
#[specta::specta]
pub fn editor_read_dir(path: String) -> Result<local_fs::LocalDir, String> {
local_fs::list_dir(&path)
}
/// 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。
#[tauri::command]
#[specta::specta]
pub fn editor_create_file(dir: String, name: String) -> Result<String, String> {
let target = resolve_child(&dir, &name)?;
if target.exists() {
return Err(format!("「{name}」已存在"));
}
std::fs::write(&target, b"").map_err(|e| format!("新建文件失败: {e}"))?;
Ok(local_fs::display_path(&target))
}
/// 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。
///
/// 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹
/// 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同
/// (真实文件系统 vs 库内),必须能同时在命令表里存在。
#[tauri::command]
#[specta::specta]
pub fn editor_create_dir(dir: String, name: String) -> Result<String, String> {
let target = resolve_child(&dir, &name)?;
if target.exists() {
return Err(format!("「{name}」已存在"));
}
local_fs::create_dir(&target.to_string_lossy())?;
Ok(local_fs::display_path(&target))
}
/// 同目录内重命名。目标存在则报错。
#[tauri::command]
#[specta::specta]
pub fn editor_rename_path(path: String, new_name: String) -> Result<String, String> {
let src = Path::new(path.trim());
if !src.exists() {
return Err("路径不存在".to_string());
}
let parent = src.parent().ok_or_else(|| "无法解析父目录".to_string())?;
let name = validate_name(&new_name)?;
let target = parent.join(&name);
if target == src {
return Ok(local_fs::display_path(src));
}
if target.exists() {
return Err(format!("「{name}」已存在"));
}
local_fs::rename(&path, &target.to_string_lossy())?;
Ok(local_fs::display_path(&target))
}
/// 删除若干本地项(**走系统回收站**,不是永久删除)。
///
/// 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。
#[tauri::command]
#[specta::specta]
pub async fn editor_delete_path(paths: Vec<String>) -> Result<DeleteReport, String> {
tauri::async_runtime::spawn_blocking(move || {
let (removed, failed) = local_fs::delete(&paths);
DeleteReport {
removed: removed as u32,
failed,
}
})
.await
.map_err(|e| format!("删除任务失败: {e}"))
}
/// 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。
///
/// 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。
#[tauri::command]
#[specta::specta]
pub fn editor_move_path(path: String, dest_dir: String) -> Result<String, String> {
let src = Path::new(path.trim());
if !src.exists() {
return Err("源路径不存在".to_string());
}
let dest = Path::new(dest_dir.trim());
if !dest.is_dir() {
return Err("目标目录不存在".to_string());
}
let name = src
.file_name()
.ok_or_else(|| "无法解析文件名".to_string())?;
let target = dest.join(name);
if target == src {
return Ok(local_fs::display_path(src));
}
if target.exists() {
return Err(format!("目标目录中已存在「{}」", name.to_string_lossy()));
}
if src.is_dir() && dest.starts_with(src) {
return Err("不能把文件夹移动到自身或子目录中".to_string());
}
local_fs::rename(&path, &target.to_string_lossy())?;
Ok(local_fs::display_path(&target))
}
/// 校验名字并把「目录 + 名字」拼成绝对路径。
fn resolve_child(dir: &str, name: &str) -> Result<std::path::PathBuf, String> {
let name = validate_name(name)?;
let dir = Path::new(dir.trim());
if !dir.is_dir() {
return Err("目标目录不存在".to_string());
}
Ok(dir.join(name))
}
@@ -5,7 +5,7 @@
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
//! 普通目录(除了 `.notes/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
use std::io::Write;
@@ -59,7 +59,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
continue;
}
// 私有目录(索引 + 同步基线)任何情况下都不导出
if rel == ".notes" || rel.starts_with(".notes/") {
if rel == ".editor" || rel.starts_with(".editor/") {
continue;
}
if let Some(prefix) = &filter_prefix {
@@ -74,7 +74,7 @@ pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
let bytes = match std::fs::read(entry.path()) {
Ok(bytes) => bytes,
Err(e) => {
crate::logger::log_warn("notes", &format!("导出跳过 {rel}(读取失败: {e})"));
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
continue;
}
};
@@ -113,10 +113,10 @@ mod tests {
#[test]
fn full_export_skips_private_dir_only() {
let root = temp_lib("all");
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::create_dir_all(root.join(".custom")).unwrap();
std::fs::write(root.join("a.md"), "A").unwrap();
std::fs::write(root.join(".notes/notes.db"), "x").unwrap();
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
@@ -129,7 +129,7 @@ mod tests {
"普通点号目录应被导出: {list:?}"
);
assert!(
!list.iter().any(|n| n.starts_with(".notes")),
!list.iter().any(|n| n.starts_with(".editor")),
"私有目录不该导出: {list:?}"
);
@@ -10,7 +10,7 @@
//! # 为什么要有授权白名单
//!
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
//! `notes_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
//! 命令行参数、库本身。
@@ -69,6 +69,15 @@ pub struct FileDoc {
pub large: bool,
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
pub lines: u64,
/// 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因)
pub readonly: bool,
}
/// 探测写权限:以写模式打开但**不写入**(失败 → 只读)。
///
/// 比「打开成功但保存时才报错」体验好得多:只读文件一打开就能看到状态栏标记。
fn is_writable(path: &Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_ok()
}
/// 登记一个路径为「已授权可写」。
@@ -105,16 +114,18 @@ pub fn display_path(path: &Path) -> String {
}
}
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / …)。
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / `shift_jis` / …)。
///
/// # 判定顺序(每一步都有理由)
///
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。这一步的优先级高于任何
/// 统计猜测 —— 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
/// 3. **GB18030 试解**:GB18030 是 GBK 的超集,用它解 GBK 内容总能成功,
/// 因此作为「非 UTF-8 中文」的兜底(比 GBK 更宽,能覆盖 4 字节生僻字);
/// 4. 都失败则按 UTF-8 有损解码(宁可显示替换字符,也不要打不开文件)。
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。优先级高于任何统计猜测 ——
/// 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
/// 3. **chardetng 统计探测**:区分 Shift_JIS / Big5 / EUC-KR / GB18030 等 CJK 编码。
/// 这一步不能省:GB18030 几乎能解码任意字节序列,若只靠「试解是否成功」,
/// 日文 Shift_JIS 文件会被静默当成中文 GB18030;
/// 4. 探测器给不出我们支持的编码 → 退回 GB18030 兜底;仍不行则按 UTF-8 有损解码
/// (宁可显示替换字符,也不要打不开文件)。
pub fn detect_encoding(bytes: &[u8]) -> String {
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
return "utf-8-bom".to_string();
@@ -128,15 +139,50 @@ pub fn detect_encoding(bytes: &[u8]) -> String {
if std::str::from_utf8(bytes).is_ok() {
return "utf-8".to_string();
}
// 非 UTF-8:交给 GB18030 兜底(GBK 的每个序列在 GB18030 下都合法)
// 非 UTF-8:先用统计探测区分 CJK 编码(Shift_JIS / Big5 / EUC-KR / GB18030 …)。
// 不能直接拿 GB18030 兜底 —— GB18030 几乎能解码任意字节序列,试解永远「成功」,
// 会把日文 Shift_JIS 文件静默当成中文 GB18030(用户实测到的问题)。
if let Some(name) = detect_with_chardetng(bytes) {
return name;
}
// 探测器给不出我们支持的编码:退回 GB18030(GBK 的每个序列在它之下都合法)
if crate::terminal::encoding::is_supported("gb18030") {
return "gb18030".to_string();
}
"utf-8".to_string()
}
/// 用 `chardetng` 统计探测非 UTF-8 文本的编码,并映射回本模块的规范编码名。
///
/// 只接受我们**支持**的编码(见 `terminal::encoding::SUPPORTED`):探测器给出的
/// 单字节西文编码(`windows-125x` / `ISO-8859-x` / `KOI8-*`)统一归到 `latin1`
/// (它们都是单字节、逐字节一一映射,不会产生替换字符);其余未知的一律返回
/// `None`,由调用方走兜底 —— 宁可退回 GB18030,也不要返回一个解出来全是 `` 的名字。
fn detect_with_chardetng(bytes: &[u8]) -> Option<String> {
use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
detector.feed(bytes, true);
// 调用前已排除「合法 UTF-8」,因此不允许探测器再返回 UTF-8
let guessed = detector.guess(None, Utf8Detection::Deny);
let name = guessed.name().to_ascii_lowercase();
if name.starts_with("windows-125")
|| name.starts_with("iso-8859")
|| name.starts_with("koi8")
|| name == "ibm866"
{
return Some("latin1".to_string());
}
let normalized = crate::terminal::encoding::normalize(&name);
if crate::terminal::encoding::is_supported(&normalized) {
return Some(normalized);
}
None
}
/// 按编码把字节解成字符串(BOM 已剥离)。
fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
pub(crate) fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
match encoding {
"utf-8-bom" => {
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
@@ -151,7 +197,11 @@ fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
}
/// 按编码把字符串编成字节(必要时写回 BOM)。
fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
///
/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次,
/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 UTF-8
/// 或删除这些字符。
pub(crate) fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
match encoding {
"utf-8-bom" => {
let mut out = vec![0xEF, 0xBB, 0xBF];
@@ -163,11 +213,46 @@ fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
if !crate::terminal::encoding::is_supported(&normalized) {
return Err(format!("不支持的编码:{other}"));
}
Ok(crate::terminal::encoding::encode(text, &normalized))
let encoded = crate::terminal::encoding::encode(text, &normalized);
// UTF-8 能表示任何字符串,无需比对
if normalized != "utf-8"
&& crate::terminal::encoding::decode(&encoded, &normalized) != text
{
let bad = find_unencodable(text, &normalized);
let preview = bad
.iter()
.take(8)
.map(|(index, ch)| format!("第 {index} 个「{ch}」"))
.collect::<Vec<_>>()
.join("、");
let tail = if bad.len() > 8 {
format!(",等共 {} 个字符", bad.len())
} else {
String::new()
};
return Err(format!(
"编码「{other}」无法表示:{preview}{tail}。请改用 UTF-8,或删除这些字符后再保存"
));
}
Ok(encoded)
}
}
}
/// 找出目标编码无法表示的字符(位置按字符计,从 1 开始)。仅在错误路径上跑。
fn find_unencodable(text: &str, encoding: &str) -> Vec<(usize, char)> {
let mut out = Vec::new();
for (index, ch) in text.chars().enumerate() {
let mut buf = [0u8; 4];
let s = ch.encode_utf8(&mut buf);
let encoded = crate::terminal::encoding::encode(s, encoding);
if crate::terminal::encoding::decode(&encoded, encoding) != &*s {
out.push((index + 1, ch));
}
}
out
}
/// 探测换行风格(`\r\n` 只要出现一次就判定为 CRLF —— 混合换行的文件按主流风格写回)。
fn detect_eol(text: &str) -> String {
if text.contains("\r\n") {
@@ -177,8 +262,25 @@ fn detect_eol(text: &str) -> String {
}
}
/// 读取任意文件。
/// 读取任意文件(自动探测编码)。
pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
read_file_inner(path, max_mb, None)
}
/// 以指定编码**重新解码磁盘字节**(不写回,只换一种解释方式)。
///
/// 语义(规划 §5.3):切换编码是「换一种方式解释**磁盘字节**」,而不是「重新解释
/// 缓冲区文本」—— 因此必须回到磁盘字节重新解码,而不是把编辑器里已有的字符串再转一次。
pub fn redecode_file(path: &str, encoding: &str, max_mb: u32) -> Result<FileDoc, String> {
read_file_inner(path, max_mb, Some(encoding))
}
/// 读取实现。`forced_encoding` 为 `None` 时走探测链(BOM → 严格 UTF-8 → GB18030)。
fn read_file_inner(
path: &str,
max_mb: u32,
forced_encoding: Option<&str>,
) -> Result<FileDoc, String> {
let trimmed = path.trim();
if trimmed.is_empty() {
return Err("路径为空".to_string());
@@ -193,7 +295,21 @@ pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
}
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
let encoding = detect_encoding(&bytes);
let encoding = match forced_encoding {
Some(enc) if !enc.trim().is_empty() => {
let requested = enc.trim();
let normalized = if requested.eq_ignore_ascii_case("utf-8-bom") {
"utf-8-bom".to_string()
} else {
crate::terminal::encoding::normalize(requested)
};
if normalized != "utf-8-bom" && !crate::terminal::encoding::is_supported(&normalized) {
return Err(format!("不支持的编码:{requested}"));
}
normalized
}
_ => detect_encoding(&bytes),
};
let raw = decode_bytes(&bytes, &encoding);
let eol = detect_eol(&raw);
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
@@ -219,6 +335,7 @@ pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
large: meta.len() > limit,
readonly: !is_writable(p),
})
}
@@ -241,6 +358,9 @@ pub fn write_file(
if !is_authorized(p) {
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
}
if !is_writable(p) {
return Err("文件为只读,无法保存".to_string());
}
let enc = if encoding.trim().is_empty() {
"utf-8".to_string()
@@ -307,11 +427,30 @@ mod tests {
}
#[test]
fn detects_non_utf8_as_gb18030() {
// 「测试」的 GBK 字节:合法 UTF-8 校验必然失败
let gbk = crate::terminal::encoding::encode("测试", "gbk");
assert_eq!(detect_encoding(&gbk), "gb18030");
assert_eq!(decode_bytes(&gbk, "gb18030"), "测试");
fn detects_non_utf8_chinese_as_gbk_family() {
// 中文:合法 UTF-8 校验必然失败,探测应落在 GBK 家族(gbk 或 gb18030)
let text = "这是一段中文测试文本,用于验证编码探测。";
let gbk = crate::terminal::encoding::encode(text, "gbk");
let detected = detect_encoding(&gbk);
assert!(
detected == "gbk" || detected == "gb18030",
"中文应探测为 GBK 家族,实际为 {detected}"
);
// GB18030 是 GBK 的超集,用它解码同样能还原
assert_eq!(decode_bytes(&gbk, "gb18030"), text);
}
#[test]
fn detects_shift_jis_not_gb18030() {
// 日文 Shift_JIS:GB18030 也能「解码成功」,这正是旧实现误判成中文的原因
let text = "これは日本語のテキストです。テスト用のサンプル文です。";
let sjis = crate::terminal::encoding::encode(text, "shift_jis");
let detected = detect_encoding(&sjis);
assert_eq!(
detected, "shift_jis",
"日文 Shift_JIS 不应被误判(实际 {detected})"
);
assert_eq!(decode_bytes(&sjis, "shift_jis"), text);
}
#[test]
+890
View File
@@ -0,0 +1,890 @@
//! 「在路径中查找」(Find in Path):对真实文件系统做逐行文本 / 正则检索。
//!
//! # 为什么不用 `index.rs` 的 FTS5 索引
//!
//! 索引是**笔记库专用**的加速层:它只覆盖 `.md`、只回传片段(没有行号),且不支持
//! 正则。而「在目录 / 库中查找」需要的是**逐行命中 + 行号 + 正则**——这正是 IDEA
//! 的 Find in Path 语义(真 grep,不是索引查询)。因此这里直接扫盘,与索引解耦:
//! 索引挂掉 / 还没同步完,搜索依然可用。
//!
//! # 边界(防卡死是第一位的)
//!
//! - 跳过目录名清单里的目录(默认见 [`DEFAULT_SKIP_DIRS`])与超过大小上限的文件;
//! - 跳过二进制文件(前 8KB 含 NUL 字节);
//! - **完整统计**所有命中行(`total` / `total_files`),预览结构只构建前 `limit` 条
//! (`returned`),`truncated` = 统计到的总数超过回传的预览数。
//!
//! 「计数便宜、预览贵」:就算超过上限,也只继续 `regex.find` 计数,不再做字符开窗 ——
//! 于是「全库一共多少处命中」永远是准的,而 UI 可以分页展示回传的那部分。
//!
//! # 按文件自己的编码读
//!
//! 每个文件先用 `detect_encoding` 探测(BOM / UTF-8 合法性 / `chardetng` 统计),再按
//! 该编码解码 —— 于是 GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是**可读的原文字**,
//! 而不是一堆 U+FFFD。替换同样按原编码写回(复用 `files.rs` 里那套已带往返校验的
//! `encode_text`),因此不会把 GBK 文件改成 UTF-8。
//!
//! # 每行只出一条命中
//!
//! 一行里出现多次匹配时,只回传**第一处**(`match_start` / `match_end` 指向它)。
//! 这是 grep 类工具的常规做法:结果列表以「行」为单位才能扫读,一行列十条几乎相同
//! 的预览反而是噪声。
use std::path::Path;
use regex::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};
use specta::Type;
use walkdir::WalkDir;
use crate::editor::files::{decode_bytes, detect_encoding, encode_text};
/// 单文件大小上限(超过则跳过:这类文件多是日志 / 数据,检索无意义且极慢)
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
/// 单行预览最大字符数(超出时围绕命中位置开窗)
const PREVIEW_MAX_CHARS: usize = 220;
/// 命中前保留的上下文字符数(开窗时)
const PREVIEW_LEAD_CHARS: usize = 60;
/// 每个文件最多回传的命中行数(防止单个大文件刷满结果)
const MAX_MATCHES_PER_FILE: usize = 200;
/// 二进制探测读取的头部字节数
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
/// 默认跳过的目录名(`|` 分隔,大小写不敏感)。
///
/// 这是**唯一**的跳过依据:早期实现还会无条件跳过所有点目录,那样用户在搜索卡片里
/// 把 `.git` 从清单里删掉也搜不进去 —— 控件就成了摆设。默认清单已覆盖常见组合。
///
/// 与前端 `EditorSearch.vue` 的默认值必须一致(前端是展示源,这里是字段缺省时的兜底)。
const DEFAULT_SKIP_DIRS: &str = "debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build";
/// 把 `|` / `,` 分隔的清单拆开(去空白、去空项)。跳过目录名与文件名通配共用这个约定。
fn split_list(raw: &str) -> Vec<String> {
raw.split(['|', ','])
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect()
}
/// 跳过目录名集合(已转小写)。
///
/// `None` = 用内置默认清单;`Some("")` = **不跳过任何目录**(用户清空输入框就是明确
/// 要求全盘搜,包括 `node_modules`)。
fn skip_dir_set(raw: &Option<String>) -> Vec<String> {
let list = match raw {
Some(s) => split_list(s),
None => split_list(DEFAULT_SKIP_DIRS),
};
list.iter().map(|s| s.to_lowercase()).collect()
}
/// 文件名通配过滤器(`None` = 不过滤)。
///
/// `*` / `*.*` 按 Windows 习惯当「全部文件」,不按字面 glob 处理 —— 否则 `Makefile`
/// 这类无扩展名的文件会被默认值意外排除。多项用 `|` 或 `,` 分隔,大小写不敏感。
fn build_file_filter(raw: &Option<String>) -> Option<Regex> {
let parts = match raw {
Some(s) => split_list(s),
None => return None,
};
if parts.is_empty() || parts.iter().any(|p| p == "*" || p == "*.*") {
return None;
}
let body = parts
.iter()
.map(|p| glob_to_regex(p))
.collect::<Vec<_>>()
.join("|");
RegexBuilder::new(&format!("^(?:{body})$"))
.case_insensitive(true)
.build()
.ok()
}
/// 单个通配片段 → 正则(只匹配文件名,所以 `*` 不必排除路径分隔符)。
fn glob_to_regex(pattern: &str) -> String {
let mut out = String::new();
for ch in pattern.chars() {
match ch {
'*' => out.push_str(".*"),
'?' => out.push('.'),
other => out.push_str(&regex::escape(&other.to_string())),
}
}
out
}
/// 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。
#[derive(Debug, Clone, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathSearchQuery {
/// 检索根目录(绝对路径)
pub dir: String,
/// 关键词(`regex` 为真时按正则解释)
pub pattern: String,
/// 区分大小写(默认关:与 CM6 搜索一致)
pub case_sensitive: bool,
/// 全词匹配
pub whole_word: bool,
/// 按正则解释关键词
pub regex: bool,
/// 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 ——
/// 超过上限的命中只计数不构建预览,由前端分页展示回传的部分
pub limit: Option<i64>,
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
pub file_types: Option<String>,
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
pub skip_dirs: Option<String>,
}
/// 一处命中(以「行」为单位)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathSearchMatch {
/// 行号(1 起)
pub line: i64,
/// 行内字符列(1 起,指向首个匹配)
pub column: i64,
/// 该行预览(超长时围绕命中开窗,两端以 `…` 标记)
pub preview: String,
/// 命中在 `preview` 中的起始字符下标(前端高亮用)
pub match_start: i64,
/// 命中在 `preview` 中的结束字符下标(不含)
pub match_end: i64,
}
/// 一个文件内的全部命中。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathSearchFileHits {
/// 文件绝对路径
pub path: String,
/// 文件名(结果列表展示)
pub name: String,
/// 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分)
pub total_in_file: i64,
pub matches: Vec<PathSearchMatch>,
}
/// 一次「在路径中查找」的结果。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathSearchResult {
/// 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列)
pub files: Vec<PathSearchFileHits>,
/// 全树命中行总数(统计完整,不受 `limit` 影响)
pub total: i64,
/// 全树至少命中一行的文件总数(≥ `files.len()`)
pub total_files: i64,
/// 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`)
pub returned: i64,
/// `total > returned`:还有命中未回传预览
pub truncated: bool,
}
/// 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。
#[derive(Debug, Clone, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathReplaceQuery {
/// 检索根目录(绝对路径)
pub dir: String,
/// 关键词(`regex` 为真时按正则解释)
pub pattern: String,
/// 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开)
pub replacement: String,
/// 区分大小写(默认关)
pub case_sensitive: bool,
/// 全词匹配
pub whole_word: bool,
/// 按正则解释关键词
pub regex: bool,
/// 替换总数上限(缺省 1000,夹在 1..=5000)
pub limit: Option<i64>,
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
pub file_types: Option<String>,
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
pub skip_dirs: Option<String>,
}
/// 一个被修改的文件。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathReplaceFileResult {
pub path: String,
pub name: String,
pub replacements: i64,
}
/// 被跳过的文件(非 UTF-8 / 写不进去)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathReplaceSkipped {
pub path: String,
pub reason: String,
}
/// 一次「在路径中替换」的结果。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PathReplaceResult {
/// 实际被改写的文件(含各自的替换处数)
pub files: Vec<PathReplaceFileResult>,
pub files_changed: i64,
pub replacements: i64,
/// 达到上限提前停止:此时**只改了前面一部分文件**
pub truncated: bool,
pub skipped: Vec<PathReplaceSkipped>,
}
/// 在目录内逐行检索,按文件分组返回。
pub fn search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
let pattern = query.pattern.trim();
let dir = Path::new(query.dir.trim());
if !dir.is_dir() {
return Err("目标目录不存在".to_string());
}
if pattern.is_empty() {
return Ok(PathSearchResult {
files: Vec::new(),
total: 0,
total_files: 0,
returned: 0,
truncated: false,
});
}
let regex = build_regex(pattern, &query)?;
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
let skip_dirs = skip_dir_set(&query.skip_dirs);
let file_filter = build_file_filter(&query.file_types);
let mut files: Vec<PathSearchFileHits> = Vec::new();
let mut total = 0usize;
let mut total_files = 0usize;
let mut returned = 0usize;
// 不再「达限即停」:命中行数与文件数要统计完整树(用户要的是准确的总量),
// 超过 `limit` 之后只继续计数,不再构建预览结构(开窗/换算才是贵的)。
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
// 按文件**自己的编码**解码:GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是
// 可读的原文字,而不是一堆 U+FFFD
let text = decode_bytes(bytes, &detect_encoding(bytes));
let mut hits: Vec<PathSearchMatch> = Vec::new();
let mut in_file = 0usize;
for (index, raw) in text.split('\n').enumerate() {
let line = raw.strip_suffix('\r').unwrap_or(raw);
let Some(m) = regex.find(line) else { continue };
in_file += 1;
if returned < limit && hits.len() < MAX_MATCHES_PER_FILE {
hits.push(make_match(line, m.start(), m.end(), (index + 1) as i64));
returned += 1;
}
}
if in_file > 0 {
total += in_file;
total_files += 1;
// 预览为空的文件(上限已满)不进 `files`:UI 上一个没有行的文件头是噪声
if !hits.is_empty() {
files.push(PathSearchFileHits {
path: path.to_string_lossy().to_string(),
name: file_name_of(path),
total_in_file: in_file as i64,
matches: hits,
});
}
}
true
});
Ok(PathSearchResult {
files,
total: total as i64,
total_files: total_files as i64,
returned: returned as i64,
truncated: total > returned,
})
}
/// 在目录内逐文件替换。
///
/// # 安全模型(这是会**改用户磁盘文件**的操作,每条都是刻意的)
///
/// - **按文件自己的编码读与写**:`detect_encoding` 探测 → `decode_bytes` 解码 →
/// `encode_text` 编码写回,所以 GBK 文件写回去还是 GBK,不会被改成 UTF-8。
/// - **编码不可字节级还原就跳过**:编码探测对某些文件是有歧义的(同一段内容在
/// GBK / GB18030 下能编出不同字节,UTF-16 的 BOM 也不一定补得回来)。写回前先验
/// 「原文按该编码重新编码 == 原字节」,不等就整文件跳过 —— 否则重编码会顺手改掉
/// 未命中的字节,那是用户无从察觉的数据损坏。
/// - **替换内容编不进去就跳过**:交给 `encode_text` 判定(它绝不把不可表示字符静默
/// 变成 `?`),失败原因逐个回报到 `skipped`。
/// - **只写真正变了的文件**:没匹配到就 `return`,不徒增 mtime、不触发文件监听事件。
/// - **上限停在文件边界**:替换总数达到 `limit` 就停止并回传 `truncated`。绝不写
/// 「一个文件只改了一半」,所以允许总数略微超过上限。
/// - **失败即记录**:只读 / 被占用等写入失败不影响其它文件,逐个回报 `skipped`。
pub fn replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
let pattern = query.pattern.trim();
let dir = Path::new(query.dir.trim());
if !dir.is_dir() {
return Err("目标目录不存在".to_string());
}
let mut result = PathReplaceResult {
files: Vec::new(),
files_changed: 0,
replacements: 0,
truncated: false,
skipped: Vec::new(),
};
if pattern.is_empty() {
return Ok(result);
}
let regex = build_regex(pattern, &query)?;
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
let skip_dirs = skip_dir_set(&query.skip_dirs);
let file_filter = build_file_filter(&query.file_types);
// 正则关闭时按字面量写入(不让 `$1` / `$foo` 被意外展开 —— 用户在做纯文本替换);
// 开启时才做捕获组展开,并把 CM6 风格的 `$&`(整个匹配)统一成 Rust regex 的 `$0`
let expand = query.regex;
let replacement = if expand {
query.replacement.replace("$&", "$0")
} else {
query.replacement.clone()
};
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
if result.replacements as usize >= limit {
result.truncated = true;
return false;
}
let encoding = detect_encoding(bytes);
let text = decode_bytes(bytes, &encoding);
// 编码必须能字节级还原原文,否则重编码会改动未命中的字节(见函数文档)
match encode_text(&text, &encoding) {
Ok(same) if same == bytes => {}
Ok(_) => {
result.skipped.push(PathReplaceSkipped {
path: path.to_string_lossy().to_string(),
reason: format!("编码「{encoding}」无法字节级还原原文,已跳过(避免改动未命中的字节)"),
});
return true;
}
Err(e) => {
result.skipped.push(PathReplaceSkipped {
path: path.to_string_lossy().to_string(),
reason: e,
});
return true;
}
}
let count = regex.find_iter(&text).count();
if count == 0 {
return true;
}
let next = if expand {
regex.replace_all(&text, replacement.as_str())
} else {
regex.replace_all(&text, regex::NoExpand(replacement.as_str()))
};
let out = match encode_text(&next, &encoding) {
Ok(b) => b,
Err(e) => {
result.skipped.push(PathReplaceSkipped {
path: path.to_string_lossy().to_string(),
reason: e,
});
return true;
}
};
if let Err(e) = std::fs::write(path, &out) {
result.skipped.push(PathReplaceSkipped {
path: path.to_string_lossy().to_string(),
reason: format!("写入失败:{e}"),
});
return true;
}
result.replacements += count as i64;
result.files_changed += 1;
result.files.push(PathReplaceFileResult {
path: path.to_string_lossy().to_string(),
name: file_name_of(path),
replacements: count as i64,
});
true
});
Ok(result)
}
/// 遍历 `dir` 下的候选文件(剪枝 + 尺寸 + 二进制 + 文件名通配),逐个把字节交给 `visit`。
///
/// `visit` 返回 `false` 表示调用方要求提前结束(例如命中总数已达上限)。
///
/// 抽出来给「查找」与「替换」共用:两者的**取舍必须完全一致**(跳哪些目录、多大算大、
/// 什么算二进制、按什么文件名过滤),否则会出现「搜得到、替换却跳过」这种自相矛盾的行为。
fn for_each_candidate_file(
dir: &Path,
skip_dirs: &[String],
file_filter: Option<&Regex>,
mut visit: impl FnMut(&Path, &[u8]) -> bool,
) {
for entry in WalkDir::new(dir)
.follow_links(false)
.into_iter()
.filter_entry(|e| !should_skip(e, skip_dirs))
{
let Ok(entry) = entry else { continue };
if !entry.file_type().is_file() {
continue;
}
if let Some(filter) = file_filter {
let name = entry.file_name().to_string_lossy();
if !filter.is_match(&name) {
continue;
}
}
let Ok(meta) = entry.metadata() else { continue };
if meta.len() > MAX_FILE_BYTES {
continue;
}
let Ok(bytes) = std::fs::read(entry.path()) else { continue };
// 二进制文件(头部含 NUL)直接跳过:只会读到一堆乱码预览
if bytes[..bytes.len().min(BINARY_SNIFF_BYTES)].contains(&0u8) {
continue;
}
if !visit(entry.path(), &bytes) {
return;
}
}
}
/// 文件名(结果列表展示用)。
fn file_name_of(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default()
}
/// 查找 / 替换请求共有的匹配选项。
///
/// 抽成 trait 是为了让两处 `build_regex` 调用**不可能**把选项传串位 —— 查找与替换必须
/// 用完全一样的规则构造正则,否则会出现「搜到的和替换的不是同一批」这种最坏情况。
trait MatchOptions {
fn regex_mode(&self) -> bool;
fn whole_word(&self) -> bool;
fn case_sensitive(&self) -> bool;
}
impl MatchOptions for PathSearchQuery {
fn regex_mode(&self) -> bool {
self.regex
}
fn whole_word(&self) -> bool {
self.whole_word
}
fn case_sensitive(&self) -> bool {
self.case_sensitive
}
}
impl MatchOptions for PathReplaceQuery {
fn regex_mode(&self) -> bool {
self.regex
}
fn whole_word(&self) -> bool {
self.whole_word
}
fn case_sensitive(&self) -> bool {
self.case_sensitive
}
}
/// 组装正则:`regex` 关闭时转义为字面量,`whole_word` 时包一层词边界。
fn build_regex(pattern: &str, options: &impl MatchOptions) -> Result<Regex, String> {
let core = if options.regex_mode() {
pattern.to_string()
} else {
regex::escape(pattern)
};
let body = if options.whole_word() {
format!(r"\b(?:{core})\b")
} else {
core
};
RegexBuilder::new(&body)
.case_insensitive(!options.case_sensitive())
.build()
.map_err(|e| format!("正则表达式无效:{e}"))
}
/// 目录遍历剪枝:按**清单里的名字**跳过(大小写不敏感)。根目录(depth 0)永不跳过。
fn should_skip(entry: &walkdir::DirEntry, skip_dirs: &[String]) -> bool {
if entry.depth() == 0 || !entry.file_type().is_dir() {
return false;
}
let name = entry.file_name().to_string_lossy().to_lowercase();
skip_dirs.iter().any(|s| *s == name)
}
/// 构造一行命中:超长行围绕命中开窗,并把命中位置换算成预览内的字符下标。
fn make_match(line: &str, match_start: usize, match_end: usize, line_no: i64) -> PathSearchMatch {
let chars: Vec<char> = line.chars().collect();
let start_ch = char_index(line, match_start);
let end_ch = char_index(line, match_end);
let window_start = start_ch.saturating_sub(PREVIEW_LEAD_CHARS);
let window_end = (window_start + PREVIEW_MAX_CHARS)
.max(end_ch)
.min(chars.len());
let body: String = chars[window_start..window_end].iter().collect();
let prefix = if window_start > 0 { "…" } else { "" };
let suffix = if window_end < chars.len() { "…" } else { "" };
let preview = format!("{prefix}{body}{suffix}");
let lead = prefix.chars().count() as i64;
let preview_len = preview.chars().count() as i64;
let match_from = ((start_ch - window_start) as i64 + lead).clamp(0, preview_len);
let match_to = ((end_ch - window_start) as i64 + lead).clamp(match_from, preview_len);
PathSearchMatch {
line: line_no,
column: (start_ch + 1) as i64,
preview,
match_start: match_from,
match_end: match_to,
}
}
/// 字节下标 → 字符下标(`regex` 给的是字节偏移,前端高亮要字符下标)。
fn char_index(s: &str, byte: usize) -> usize {
let byte = byte.min(s.len());
s[..byte].chars().count()
}
/// 「在路径中查找」命令。
///
/// 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它
/// (范式同 `editor_delete_path` / `editor_sync_now`)。
#[tauri::command]
#[specta::specta]
pub async fn editor_search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
tauri::async_runtime::spawn_blocking(move || search_in_path(query))
.await
.map_err(|e| format!("检索任务失败: {e}"))?
}
/// 「在路径中替换」命令。
///
/// 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。
#[tauri::command]
#[specta::specta]
pub async fn editor_replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
tauri::async_runtime::spawn_blocking(move || replace_in_path(query))
.await
.map_err(|e| format!("替换任务失败: {e}"))?
}
#[cfg(test)]
mod tests {
use super::*;
/// 每个用例独占一个临时目录(测试并行跑,不能共用)。
///
/// 用 crate 的 `target/test-tmp/` 而不是 `std::env::temp_dir()`:系统临时目录在受限
/// 环境下未必可写(本机就是这样 —— 连既有的 `files.rs` 用例也会 `PermissionDenied`),
/// 而 `target/` 一定可写,且已被 gitignore。
fn temp_dir(name: &str) -> std::path::PathBuf {
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("test-tmp")
.join(format!("grep-{name}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// 字面量(非正则)替换请求。
fn literal(dir: &Path, pattern: &str, replacement: &str) -> PathReplaceQuery {
PathReplaceQuery {
dir: dir.to_string_lossy().to_string(),
pattern: pattern.to_string(),
replacement: replacement.to_string(),
case_sensitive: true,
whole_word: false,
regex: false,
limit: None,
file_types: None,
skip_dirs: None,
}
}
/// 同上的查找请求。
fn search_query(dir: &Path, pattern: &str) -> PathSearchQuery {
PathSearchQuery {
dir: dir.to_string_lossy().to_string(),
pattern: pattern.to_string(),
case_sensitive: true,
whole_word: false,
regex: false,
limit: None,
file_types: None,
skip_dirs: None,
}
}
#[test]
fn literal_replace_keeps_bom_and_crlf() {
let dir = temp_dir("bom-crlf");
let file = dir.join("a.txt");
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"foo\r\nfoo\r\n");
std::fs::write(&file, &bytes).unwrap();
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
assert_eq!(result.replacements, 2);
assert_eq!(result.files_changed, 1);
assert!(!result.truncated);
assert!(result.skipped.is_empty());
let mut expected = vec![0xEF, 0xBB, 0xBF];
expected.extend_from_slice(b"bar\r\nbar\r\n");
assert_eq!(
std::fs::read(&file).unwrap(),
expected,
"BOM 与 CRLF 必须原样保留"
);
}
#[test]
fn literal_replacement_does_not_expand_captures() {
let dir = temp_dir("literal-dollar");
let file = dir.join("a.txt");
std::fs::write(&file, "foo\n").unwrap();
replace_in_path(literal(&dir, "foo", "$1x")).unwrap();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"$1x\n",
"正则关闭时替换串必须按字面量写入"
);
}
#[test]
fn regex_mode_expands_groups_and_normalizes_ampersand() {
let dir = temp_dir("regex-groups");
let a = dir.join("a.txt");
let b = dir.join("b.txt");
std::fs::write(&a, "user@host\n").unwrap();
std::fs::write(&b, "word\n").unwrap();
let mut groups = literal(&dir, r"(\w+)@(\w+)", "$2.$1");
groups.regex = true;
replace_in_path(groups).unwrap();
assert_eq!(std::fs::read_to_string(&a).unwrap(), "host.user\n");
// `$&`(CM6 风格的「整个匹配」)要等价于 Rust 的 `$0`
let mut whole = literal(&dir, "word", "[$&]");
whole.regex = true;
replace_in_path(whole).unwrap();
assert_eq!(std::fs::read_to_string(&b).unwrap(), "[word]\n");
}
#[test]
fn searches_and_replaces_gbk_file_keeping_its_encoding() {
let dir = temp_dir("gbk");
let file = dir.join("a.txt");
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
std::fs::write(&file, &original).unwrap();
assert!(
std::str::from_utf8(&original).is_err(),
"前提:原文不是合法 UTF-8"
);
// 查找:预览要按原编码解出中文,而不是一堆 U+FFFD
let found = search_in_path(search_query(&dir, "foo")).unwrap();
assert_eq!(found.total, 1);
let preview = &found.files[0].matches[0].preview;
assert!(preview.contains("中文"), "预览应按原编码解出中文,实际:{preview}");
assert!(!preview.contains('\u{FFFD}'), "预览不应出现替换字符");
// 替换:写回去仍然是 GBK
let replaced = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
assert_eq!(replaced.replacements, 1);
assert!(
replaced.skipped.is_empty(),
"GBK 文件应能正常替换,实际跳过:{:?}",
replaced.skipped
);
let after = std::fs::read(&file).unwrap();
assert_eq!(
decode_bytes(&after, &detect_encoding(&after)),
"中文 bar\n",
"应能按原编码读回替换后的内容"
);
assert!(
std::str::from_utf8(&after).is_err(),
"不能把 GBK 文件写成 UTF-8"
);
}
#[test]
fn skips_replace_when_replacement_is_not_encodable() {
let dir = temp_dir("unencodable");
let file = dir.join("a.txt");
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
std::fs::write(&file, &original).unwrap();
// emoji 编不进 GBK:必须跳过并回报,绝不能写成 `?`
let result = replace_in_path(literal(&dir, "foo", "🙂")).unwrap();
assert_eq!(result.replacements, 0);
assert_eq!(result.skipped.len(), 1, "应回报为跳过");
assert_eq!(
std::fs::read(&file).unwrap(),
original,
"编码装不下替换内容时,文件必须一个字节都不动"
);
}
#[test]
fn respects_custom_skip_dirs_and_file_types() {
let dir = temp_dir("filters");
// 目录名刻意不落在默认清单里(`vendor` / `build` 之类都在清单里)
let sub = dir.join("innersrc");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(dir.join("a.md"), "foo\n").unwrap();
std::fs::write(dir.join("b.txt"), "foo\n").unwrap();
std::fs::write(sub.join("c.md"), "foo\n").unwrap();
// `innersrc` 不在默认清单里 → 三处都命中
assert_eq!(search_in_path(search_query(&dir, "foo")).unwrap().total, 3);
// 只搜 *.md
let mut by_type = search_query(&dir, "foo");
by_type.file_types = Some("*.md".to_string());
assert_eq!(search_in_path(by_type).unwrap().total, 2, "应只命中 .md");
// 跳过 innersrc
let mut skip = search_query(&dir, "foo");
skip.skip_dirs = Some("innersrc".to_string());
assert_eq!(
search_in_path(skip).unwrap().total,
2,
"innersrc 下的应被跳过"
);
// 默认清单跳过 .git
let git = dir.join(".git");
std::fs::create_dir_all(&git).unwrap();
std::fs::write(git.join("cfg"), "foo\n").unwrap();
assert_eq!(
search_in_path(search_query(&dir, "foo")).unwrap().total,
3,
"默认清单应跳过 .git"
);
// 清空清单 = 不跳过任何目录(清单是唯一依据)
let mut no_skip = search_query(&dir, "foo");
no_skip.skip_dirs = Some(String::new());
assert_eq!(
search_in_path(no_skip).unwrap().total,
4,
"清空清单后连 .git 也要搜"
);
// `*.*` 按「全部文件」处理:无扩展名的 Makefile 不能被排除
std::fs::write(dir.join("Makefile"), "foo\n").unwrap();
let mut star = search_query(&dir, "foo");
star.file_types = Some("*.*".to_string());
assert_eq!(
search_in_path(star).unwrap().total,
4,
"*.* 应包含无扩展名文件"
);
}
#[test]
fn limit_stops_at_file_boundary_without_half_writes() {
let dir = temp_dir("limit");
for name in ["1.txt", "2.txt", "3.txt"] {
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
}
let mut query = literal(&dir, "foo", "bar");
query.limit = Some(2);
let result = replace_in_path(query).unwrap();
assert!(result.truncated, "达到上限应回报 truncated");
assert_eq!(result.files_changed, 1, "上限停在文件边界,只应改完一个文件");
assert_eq!(result.replacements, 2);
// 其余两个文件必须完全没动(绝不能出现「只改了一半」的文件)
let untouched = ["1.txt", "2.txt", "3.txt"]
.iter()
.filter(|n| std::fs::read_to_string(dir.join(n)).unwrap() == "foo\nfoo\n")
.count();
assert_eq!(untouched, 2);
}
#[test]
fn skips_binary_files_and_pruned_dirs() {
let dir = temp_dir("binary-prune");
let bin = dir.join("bin.dat");
std::fs::write(&bin, b"foo\0foo").unwrap();
let git = dir.join(".git");
std::fs::create_dir_all(&git).unwrap();
std::fs::write(git.join("cfg"), "foo\n").unwrap();
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
assert_eq!(result.replacements, 0, "二进制文件与 .git 都不该被改写");
assert_eq!(std::fs::read(&bin).unwrap(), b"foo\0foo");
assert_eq!(std::fs::read_to_string(git.join("cfg")).unwrap(), "foo\n");
}
#[test]
fn search_and_replace_agree_on_matches() {
let dir = temp_dir("agree");
std::fs::write(dir.join("a.txt"), "Alpha alpha ALPHA\n").unwrap();
let found = search_in_path(search_query(&dir, "Alpha")).unwrap();
assert_eq!(found.total, 1);
let replaced = replace_in_path(literal(&dir, "Alpha", "Beta")).unwrap();
assert_eq!(replaced.replacements, 1, "替换处数必须与检索结果一致");
assert_eq!(
std::fs::read_to_string(dir.join("a.txt")).unwrap(),
"Beta alpha ALPHA\n"
);
}
#[test]
fn search_counts_all_hits_beyond_limit() {
let dir = temp_dir("count-all");
for name in ["1.txt", "2.txt", "3.txt"] {
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
}
let mut query = search_query(&dir, "foo");
query.limit = Some(2);
let result = search_in_path(query).unwrap();
assert_eq!(result.total, 6, "总数统计完整树,不受 limit 影响");
assert_eq!(result.total_files, 3, "文件数同样统计完整树");
assert_eq!(result.returned, 2, "预览只回传 limit 条");
assert!(result.truncated, "total > returned 应标记截断");
assert_eq!(result.files.len(), 1, "超出上限的文件不再回传预览");
assert_eq!(result.files[0].name, "1.txt");
assert_eq!(result.files[0].total_in_file, 2);
assert_eq!(result.files[0].matches.len(), 2);
// limit 足够时 truncated 为假,且 returned == total
let full = search_in_path(search_query(&dir, "foo")).unwrap();
assert_eq!(full.returned, full.total);
assert!(!full.truncated);
}
}
File renamed without changes.
@@ -3,7 +3,7 @@
//! # 索引不是真相
//!
//! 真相永远是库根下的 `.md` 文件(见 `library.rs`)。本模块只是**可随时丢弃重建**
//! 的加速层:删掉 `{库根}/.notes/notes.db` 的唯一后果是下次搜索前要做一次全量扫描。
//! 的加速层:删掉 `{库根}/.editor/editor.db` 的唯一后果是下次搜索前要做一次全量扫描。
//! 因此这里不写「强一致」逻辑,只保证「一次同步之后索引与文件一致」——
//! 增量同步靠 `(mtime, size)` 快速筛掉未变文件,变了才读内容算 hash。
//!
@@ -13,7 +13,7 @@
//! 不需要维护「库 → 索引文件」的映射;把整个库目录拷走时索引一起走,新机器上
//! 第一次搜索只做增量校验而不是全量重建。
//!
//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.notes/`:
//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.editor/`:
//! 库扫描(`library::scan`)本来就跳过点号开头的目录,它不会出现在侧栏树里;
//! P2 的 WebDAV 同步也会按约定排除它。
//!
@@ -398,7 +398,7 @@ pub struct NoteSyncReport {
}
/// 笔记索引(持有 SQLite 连接 + 当前库根)。
pub struct NotesIndex {
pub struct EditorIndex {
conn: Connection,
/// 索引所属的库根(库切换时整个索引实例被替换)
root: PathBuf,
@@ -406,15 +406,17 @@ pub struct NotesIndex {
db_path: PathBuf,
}
impl NotesIndex {
impl EditorIndex {
/// 打开(或创建)某个库根对应的索引。
///
/// 库根切换后由命令层用新库根调用本函数重建实例 —— 索引与库一一对应,
/// 不做「一份索引服务多个库」的多态(那需要为每张表加 root 列,得不偿失)。
pub fn open(root: &Path) -> Result<Self, String> {
let dir = root.join(".notes");
// 惰性迁移旧私有目录(幂等):索引可重建,但同步基线要跟着搬过去
library::migrate_private_dir(root);
let dir = root.join(library::PRIVATE_DIR);
std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?;
let db_path = dir.join("notes.db");
let db_path = dir.join("editor.db");
let conn = Connection::open(&db_path).map_err(|e| format!("打开笔记索引失败: {e}"))?;
conn.busy_timeout(std::time::Duration::from_secs(3))
.map_err(|e| format!("设置索引超时失败: {e}"))?;
@@ -450,7 +452,7 @@ impl NotesIndex {
if version != 0 && version != SCHEMA_VERSION {
crate::logger::log_warn(
"notes",
"editor",
&format!("索引结构版本 {version} → {SCHEMA_VERSION},按文件重建索引"),
);
self.drop_all()?;
@@ -563,7 +565,7 @@ impl NotesIndex {
continue;
}
let path = entry.path();
// 跳过点号目录(含 `.notes/` 自身)与根级 assets/
// 跳过点号目录(含 `.editor/` 自身)与根级 assets/
if skip_path(&root, path) {
continue;
}
@@ -626,7 +628,7 @@ impl NotesIndex {
let bytes = match std::fs::read(&path) {
Ok(b) => b,
Err(e) => {
crate::logger::log_warn("notes", &format!("索引读取失败 {rel}: {e}"));
crate::logger::log_warn("editor", &format!("索引读取失败 {rel}: {e}"));
continue;
}
};
@@ -1069,7 +1071,7 @@ fn skip_path(root: &Path, path: &Path) -> bool {
return false;
}
let parts: Vec<&str> = rel.split('/').collect();
// 任何一层是点号开头 → 排除(`.notes/` 索引自身、`.git/` 等)
// 任何一层是点号开头 → 排除(`.editor/` 索引自身、`.git/` 等)
if parts.iter().any(|p| p.starts_with('.')) {
return true;
}
@@ -1294,7 +1296,7 @@ mod tests {
#[test]
fn index_roundtrip_search_tags_and_rebuild() {
let root = std::env::temp_dir().join(format!(
"thing-notes-index-test-{}",
"thing-editor-index-test-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
@@ -1314,9 +1316,9 @@ mod tests {
// 非 .md 与点号目录都不该被索引
std::fs::write(root.join("notes/notes.txt"), "不该被索引").unwrap();
// 先打开索引(顺带创建 `.notes/` 目录),再往里塞一个「不该被索引」的 .md
let mut index = NotesIndex::open(&root).unwrap();
std::fs::write(root.join(".notes/ignored.md"), "也不该被索引").unwrap();
// 先打开索引(顺带创建 `.editor/` 目录),再往里塞一个「不该被索引」的 .md
let mut index = EditorIndex::open(&root).unwrap();
std::fs::write(root.join(".editor/ignored.md"), "也不该被索引").unwrap();
let report = index.sync().unwrap();
assert_eq!(report.indexed, 2, "只应索引两篇 .md");
@@ -1427,7 +1429,7 @@ mod tests {
#[test]
fn front_matter_id_and_dates_are_indexed() {
let root = std::env::temp_dir().join(format!(
"thing-notes-index-fm-{}",
"thing-editor-index-fm-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
@@ -1438,7 +1440,7 @@ mod tests {
)
.unwrap();
let mut index = NotesIndex::open(&root).unwrap();
let mut index = EditorIndex::open(&root).unwrap();
index.sync().unwrap();
let page = index
.search(NoteSearchQuery {
@@ -19,8 +19,11 @@
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
//! 关着而漏掉索引更新。
//!
//! 自我保存抑制([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
//! `Modify(Data)`,若不抑制,前端就会在用户自己打字时反复弹出「文件已被外部修改」。
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
@@ -33,21 +36,28 @@ use specta::Type;
use tauri::{AppHandle, Emitter};
use super::files;
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, NotesIndex};
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
use super::library;
use crate::constants::events;
/// 自我保存抑制窗口:`notes_write_*` 之后这段时间内的文件事件不当作「外部修改」。
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
///
/// 取 1200ms:前端自动保存默认 800ms 防抖,加上写盘与 notify 自身的派发延迟,
/// 这个窗口足够覆盖「自己写的」这一类事件,又短到不会吞掉用户紧接着在外部编辑器
/// 里的另一次保存(那种情况用户本来就刚切过窗口,多等一秒无妨)。
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
const SUPPRESS_MS: u64 = 1200;
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
///
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
const SELF_WRITE_TTL_MS: u64 = 30_000;
/// 单个文件事件的去抖说明。
///
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
/// 前端 `notes-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
const _DEBOUNCE_NOTE_MS: u64 = 250;
@@ -109,7 +119,7 @@ enum Request {
/// 全量重建
Rebuild(Sender<Result<NoteSyncReport, String>>),
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
SyncPath(PathBuf, bool),
SyncPath(PathBuf),
/// 全文检索
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
/// 快速打开清单
@@ -126,11 +136,38 @@ enum Request {
Retarget(PathBuf, Sender<Result<(), String>>),
}
/// 一条「本应用自己写入」的登记。
struct SelfWrite {
/// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致)
rel: String,
/// 登记时刻(写入之前,见 [`IndexService::mark_write_path`])
marked: Instant,
/// 首次被文件事件命中的时刻(`None` = 还没等到它的事件)
matched: Option<Instant>,
}
/// 丢弃过期的自我写入登记。
///
/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。
/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。
fn prune_self_writes(paths: &mut Vec<SelfWrite>) {
let dedupe = Duration::from_millis(SUPPRESS_MS);
let wait = Duration::from_millis(SELF_WRITE_TTL_MS);
paths.retain(|entry| match entry.matched {
Some(at) => at.elapsed() < dedupe,
None => entry.marked.elapsed() < wait,
});
}
/// 索引服务的句柄(命令层只拿到这个)。
pub struct IndexService {
tx: Sender<Request>,
/// 自我保存抑制的时间点(`notes_write_*` 写入)
last_write: Mutex<Option<Instant>>,
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
bulk_write: Mutex<Option<Instant>>,
/// 单个文件的自我写入登记。
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
write_paths: Mutex<Vec<SelfWrite>>,
}
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
@@ -145,29 +182,72 @@ impl IndexService {
let (tx, rx) = mpsc::channel::<Request>();
let handle_tx = tx.clone();
std::thread::Builder::new()
.name("notes-index".to_string())
.name("editor-index".to_string())
.spawn(move || worker_loop(app, rx, handle_tx))
.expect("启动笔记索引线程失败");
Self {
tx,
last_write: Mutex::new(None),
bulk_write: Mutex::new(None),
write_paths: Mutex::new(Vec::new()),
}
}
/// 标记「刚刚由本应用写入了文件」,用于抑制自我触发的「外部修改」提示。
pub fn mark_write(&self) {
if let Ok(mut slot) = self.last_write.lock() {
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
pub fn mark_write_all(&self) {
if let Ok(mut slot) = self.bulk_write.lock() {
*slot = Some(Instant::now());
}
}
fn recently_written(&self) -> bool {
self.last_write
/// 登记「本应用即将写入这个库内相对路径」。
///
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
pub fn mark_write_path(&self, rel: &str) {
if rel.is_empty() {
return;
}
if let Ok(mut paths) = self.write_paths.lock() {
prune_self_writes(&mut paths);
paths.push(SelfWrite {
rel: rel.to_string(),
marked: Instant::now(),
matched: None,
});
}
}
/// 这个库内相对路径是不是「本应用自己刚写的」。
///
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
fn recently_written(&self, rel: &str) -> bool {
let bulk = self
.bulk_write
.lock()
.ok()
.and_then(|slot| *slot)
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
.unwrap_or(false)
.unwrap_or(false);
if bulk {
return true;
}
let Ok(mut paths) = self.write_paths.lock() else {
return false;
};
prune_self_writes(&mut paths);
let index = paths
.iter()
.position(|entry| entry.rel == rel && entry.matched.is_none())
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
let Some(index) = index else {
return false;
};
let entry = &mut paths[index];
entry.matched.get_or_insert_with(Instant::now);
true
}
/// 增量同步整个库。
@@ -252,9 +332,9 @@ impl IndexService {
}
}
/// worker 主循环:独占 [`NotesIndex`],串行处理所有请求。
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
let mut index: Option<NotesIndex> = None;
let mut index: Option<EditorIndex> = None;
let mut watcher: Option<RecommendedWatcher> = None;
let mut watched_root: Option<PathBuf> = None;
let mut root: Option<PathBuf> = None;
@@ -288,6 +368,14 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
}
Request::Retarget(next, reply) => {
// 库根未变:直接返回,不重开索引、不重建监听器。
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
// 制造出「自己保存却被当成外部修改」的竞态。
if root.as_deref() == Some(next.as_path()) {
let _ = reply.send(Ok(()));
continue;
}
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
index = None;
root = Some(next.clone());
@@ -302,17 +390,17 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
}
Request::SyncPath(path, from_app) => {
Request::SyncPath(path) => {
if let Some(current) = root.clone() {
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
if index.is_none() {
if let Err(e) = ensure_index(&app, &mut index, &current) {
crate::logger::log_warn("notes", &format!("索引不可用: {e}"));
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
continue;
}
}
ensure_watcher(&mut watcher, &mut watched_root, &current, &handle_tx);
sync_one(&app, index.as_mut(), &current, &path, from_app);
sync_one(&app, index.as_mut(), &current, &path);
}
}
}
@@ -322,9 +410,9 @@ fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
fn with_index<T>(
app: &AppHandle,
index: &mut Option<NotesIndex>,
index: &mut Option<EditorIndex>,
root: &mut Option<PathBuf>,
run: impl FnOnce(&mut NotesIndex) -> Result<T, String>,
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
) -> Result<T, String> {
let Some(current) = root.clone() else {
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
@@ -339,18 +427,18 @@ fn with_index<T>(
}
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
fn ensure_index(app: &AppHandle, index: &mut Option<NotesIndex>, root: &Path) -> Result<(), String> {
fn ensure_index(app: &AppHandle, index: &mut Option<EditorIndex>, root: &Path) -> Result<(), String> {
if let Some(existing) = index.as_ref() {
if existing.root() == root {
return Ok(());
}
}
if let Err(e) = library::ensure_library(root) {
crate::logger::log_warn("notes", &e);
crate::logger::log_warn("editor", &e);
}
let opened = NotesIndex::open(root)?;
let opened = EditorIndex::open(root)?;
crate::logger::log_info(
"notes",
"editor",
&format!("索引已就绪: {}", opened.db_path().display()),
);
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
@@ -367,7 +455,7 @@ fn ensure_watcher(
tx: &Sender<Request>,
) {
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
crate::logger::log_warn("notes", &e);
crate::logger::log_warn("editor", &e);
}
}
@@ -385,7 +473,7 @@ fn ensure_watcher_inner(
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
for path in event_paths(&event) {
let _ = sender.send(Request::SyncPath(path, true));
let _ = sender.send(Request::SyncPath(path));
}
})
.map_err(|e| format!("创建库监听器失败: {e}"))?;
@@ -396,11 +484,11 @@ fn ensure_watcher_inner(
// 替换旧监听器(drop 即 unwatch)
*watcher = Some(next);
*watched_root = Some(root.to_path_buf());
crate::logger::log_info("notes", &format!("库监听已启动: {}", root.display()));
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
Ok(())
}
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.notes/` 自身)。
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
///
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
@@ -428,13 +516,10 @@ fn event_paths(event: &notify::Event) -> Vec<PathBuf> {
}
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
fn sync_one(
app: &AppHandle,
index: Option<&mut NotesIndex>,
root: &Path,
path: &Path,
from_app: bool,
) {
///
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
let Some(index) = index else { return };
let rel = library::rel_string(root, path);
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
@@ -442,8 +527,10 @@ fn sync_one(
}
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
let service = SERVICE.get();
let self_write = from_app && service.map(|s| s.recently_written()).unwrap_or(false);
let self_write = SERVICE
.get()
.map(|service| service.recently_written(&rel))
.unwrap_or(false);
let kind = if path.is_file() {
if let Ok(bytes) = std::fs::read(path) {
@@ -464,7 +551,7 @@ fn sync_one(
&content_hash(&bytes),
&stems,
) {
crate::logger::log_warn("notes", &format!("增量索引 {rel} 失败: {e}"));
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
}
} else {
return;
@@ -474,27 +561,26 @@ fn sync_one(
CHANGE_MODIFIED
} else {
if let Err(e) = index.remove_note(&rel) {
crate::logger::log_warn("notes", &format!("移除索引 {rel} 失败: {e}"));
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
}
CHANGE_REMOVED
};
if self_write {
// 自己写的:索引已更新,前端无需提示(它的编辑器里本来就是最新内容)
return;
}
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
let payload = NoteFileEvent {
rel_path: rel,
abs_path: files::display_path(path),
kind: kind.to_string(), at: std::time::SystemTime::now()
kind: kind.to_string(),
at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0),
from_app: self_write,
};
if let Err(e) = app.emit(events::NOTES_FILE_CHANGED, payload) {
crate::logger::log_warn("notes", &format!("发出文件变化事件失败: {e}"));
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
}
}
@@ -9,12 +9,16 @@
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use super::types::{LibraryEntry, NoteDoc, NoteSettings};
use super::types::{LibraryEntry, NoteDoc, EditorSettings};
/// 默认库根相对模块目录的名字:`{app_data_dir}/notes/library`
/// 默认库根相对模块目录的名字:`{app_data_dir}/editor/library`
pub const DEFAULT_LIBRARY_DIR: &str = "library";
/// 附件(粘贴图片等)目录名,位于库根下
pub const ASSETS_DIR: &str = "assets";
/// 库内私有目录名(索引 + 同步基线),**永不参与同步 / 导出 / 快照**。
pub const PRIVATE_DIR: &str = ".editor";
/// v1「笔记模块」的私有目录名;首次打开时惰性迁移到 [`PRIVATE_DIR`]。
const LEGACY_PRIVATE_DIR: &str = ".notes";
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
@@ -34,15 +38,43 @@ pub fn default_library_root(module_dir: &Path) -> PathBuf {
}
/// 由设置解析出当前生效的库根。
pub fn resolve_library_root(module_dir: &Path, settings: &NoteSettings) -> PathBuf {
pub fn resolve_library_root(module_dir: &Path, settings: &EditorSettings) -> PathBuf {
match &settings.library_root {
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
_ => default_library_root(module_dir),
}
}
/// 确保库根与其 `assets/` 子目录存在。
/// 惰性迁移旧私有目录 `.notes/` → `.editor/`(幂等)。
///
/// 索引可重建,但迁移能保住同步基线(`sync.json`),因此优先整目录重命名。
/// 迁移后残留的旧索引文件(`notes.db*`)直接删除 —— 下次打开会按新库根重建。
pub fn migrate_private_dir(root: &Path) {
let old = root.join(LEGACY_PRIVATE_DIR);
let new = root.join(PRIVATE_DIR);
if !old.is_dir() || new.exists() {
return;
}
match std::fs::rename(&old, &new) {
Ok(()) => {
for stale in ["notes.db", "notes.db-wal", "notes.db-shm"] {
let _ = std::fs::remove_file(new.join(stale));
}
crate::logger::log_info(
"editor",
&format!("已迁移库内私有目录 {LEGACY_PRIVATE_DIR}/ → {PRIVATE_DIR}/"),
);
}
Err(e) => crate::logger::log_warn(
"editor",
&format!("迁移库内私有目录失败(将按新目录重建): {e}"),
),
}
}
/// 确保库根与其 `assets/` 子目录存在(顺带惰性迁移旧私有目录)。
pub fn ensure_library(root: &Path) -> Result<(), String> {
migrate_private_dir(root);
std::fs::create_dir_all(root).map_err(|e| format!("创建笔记库目录失败: {e}"))?;
std::fs::create_dir_all(root.join(ASSETS_DIR))
.map_err(|e| format!("创建附件目录失败: {e}"))?;
@@ -136,7 +168,7 @@ fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
let mut files: Vec<(String, PathBuf)> = Vec::new();
for entry in read.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
// 隐藏项(含 `.notes` 之类的私有目录)一律不进库树
// 隐藏项(含 `.editor` 之类的私有目录)一律不进库树
if name.starts_with('.') {
continue;
}
@@ -7,7 +7,7 @@
//! ↓ Tauri IPC ↓
//! commands.rs 命令层
//! ↓
//! NotesManager(本文件):设置读写 / 库根解析
//! EditorManager(本文件):设置读写 / 库根解析
//! ↓
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
//! ```
@@ -25,36 +25,48 @@
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
//! ```
//!
//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。
//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
mod args;
mod backup;
mod commands;
mod dirs;
mod export;
mod files;
mod grep;
mod import;
mod index;
mod index_service;
mod library;
mod shell_menu;
mod templates;
mod types;
mod webdav;
pub use commands::{
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
notes_write_asset, notes_write_file,
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
editor_restore_backup,
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
editor_write_asset, editor_write_file,
};
pub use args::{emit_open_file, note_path_from_args, remember_pending_file};
use types::NoteSettings;
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
pub use dirs::{
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
editor_rename_path,
};
pub use grep::{editor_replace_in_path, editor_search_in_path};
pub use shell_menu::{
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
};
use types::EditorSettings;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
@@ -65,19 +77,34 @@ const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
struct SettingsCache {
read_at: Instant,
settings: NoteSettings,
settings: EditorSettings,
}
/// 笔记模块管理器(Tauri State)。
pub struct NotesManager {
/// 模块自身目录:`{app_data_dir}/notes`
/// 笔记 / 编辑器模块管理器(Tauri State)。
pub struct EditorManager {
/// 模块自身目录:`{app_data_dir}/editor`
module_dir: PathBuf,
cache: Mutex<Option<SettingsCache>>,
}
impl NotesManager {
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
///
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
let legacy = app_data_dir.join("notes");
if legacy.is_dir() && !module_dir.exists() {
match std::fs::rename(&legacy, module_dir) {
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
}
}
}
impl EditorManager {
pub fn new(app_data_dir: PathBuf) -> Self {
let module_dir = app_data_dir.join("notes");
let module_dir = app_data_dir.join("editor");
migrate_legacy_module_dir(&app_data_dir, &module_dir);
let _ = std::fs::create_dir_all(&module_dir);
Self {
module_dir,
@@ -100,23 +127,23 @@ impl NotesManager {
let settings = self.load_settings();
let new_note = settings.new_note_shortcut.clone();
if let Err(e) = crate::shortcut::register_shortcut(app, "notes-new-note", &new_note, |app| {
if let Err(e) = app.emit(crate::constants::events::NOTES_NEW_NOTE, ()) {
crate::logger::log_warn("notes", &format!("发出新建笔记事件失败: {e}"));
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
}
}) {
crate::logger::log_warn("notes", &format!("注册「新建笔记」快捷键失败: {e}"));
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
}
let open_editor = settings.open_editor_shortcut.clone();
if let Err(e) =
crate::shortcut::register_shortcut(app, "notes-open-editor", &open_editor, |app| {
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_EDITOR, ()) {
crate::logger::log_warn("notes", &format!("发出打开编辑器事件失败: {e}"));
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
}
})
{
crate::logger::log_warn("notes", &format!("注册「打开编辑器」快捷键失败: {e}"));
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
}
}
@@ -125,7 +152,7 @@ impl NotesManager {
}
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
pub fn load_settings(&self) -> NoteSettings {
pub fn load_settings(&self) -> EditorSettings {
if let Ok(cache) = self.cache.lock() {
if let Some(entry) = cache.as_ref() {
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
@@ -136,9 +163,11 @@ impl NotesManager {
let mut settings = std::fs::read_to_string(self.settings_path())
.ok()
.and_then(|s| serde_json::from_str::<NoteSettings>(&s).ok())
.and_then(|s| serde_json::from_str::<EditorSettings>(&s).ok())
.unwrap_or_default();
let healed = settings.heal();
// 刷新「最近记录」的存在性(只读,不触发落盘)
settings.refresh_recent_exists();
if let Ok(mut cache) = self.cache.lock() {
*cache = Some(SettingsCache {
read_at: Instant::now(),
@@ -147,14 +176,14 @@ impl NotesManager {
}
if healed {
if let Err(e) = self.save_settings(&settings) {
crate::logger::log_error("notes", &format!("设置自愈落盘失败: {e}"));
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
}
}
settings
}
/// 保存设置并刷新缓存。
pub fn save_settings(&self, settings: &NoteSettings) -> Result<(), String> {
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
let json = serde_json::to_string_pretty(settings)
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
std::fs::write(self.settings_path(), json)
+165
View File
@@ -0,0 +1,165 @@
//! Windows 资源管理器右键菜单(HKCU,**免管理员**)。
//!
//! # 为什么走用户级注册表
//!
//! 文件关联由安装器写 `HKLM`/`OpenWithProgids`;而「右键 → 用 Thing 编辑器打开」
//! 只需 `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,
//! 用户级即可生效、无需提权(范式同 `mihomo_manager/system_proxy.rs`)。
//!
//! # 为什么默认不自动注册
//!
//! 注册表项里写的是**绝对 exe 路径**:打包安装后指向安装目录(稳定),但
//! `tauri dev` 下指向 `target\debug\thing.exe` —— 一旦清理 target 就成了死链。
//! 因此注册/卸载都只在设置页按钮下发生,且注册前校验 exe 存在。
//!
//! # 三处菜单
//!
//! | 键 | 场景 | 参数 |
//! |---|---|---|
//! | `*` | 任意文件 | `%1` |
//! | `Directory` | 文件夹 | `%1` |
//! | `Directory\Background` | 目录背景空白处 | `%V`(当前目录) |
use serde::Serialize;
use specta::Type;
/// 右键菜单键名与显示名。
const MENU_KEY: &str = "ThingEditor";
const MENU_LABEL: &str = "用 Thing 编辑器打开";
/// 右键菜单状态(回传设置页展示)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ContextMenuStatus {
/// 是否已注册(以 `*` 键为准)
pub registered: bool,
/// 当前可执行文件绝对路径(注册表里写入的就是它)
pub exe_path: String,
/// 是否开发模式(exe 路径不稳定,UI 需给出提示)
pub is_dev: bool,
}
fn exe_path() -> String {
std::env::current_exe()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default()
}
/// 读取当前状态。
#[tauri::command]
#[specta::specta]
pub fn editor_context_menu_status() -> ContextMenuStatus {
ContextMenuStatus {
registered: imp::registered(),
exe_path: exe_path(),
is_dev: cfg!(debug_assertions),
}
}
/// 注册右键菜单(写 HKCU)。
#[tauri::command]
#[specta::specta]
pub fn editor_register_context_menu() -> Result<ContextMenuStatus, String> {
imp::register()?;
Ok(editor_context_menu_status())
}
/// 卸载右键菜单(删 HKCU 对应项)。
#[tauri::command]
#[specta::specta]
pub fn editor_unregister_context_menu() -> Result<ContextMenuStatus, String> {
imp::unregister()?;
Ok(editor_context_menu_status())
}
// ===== Windows 实现 =====
#[cfg(windows)]
mod imp {
use super::{exe_path, MENU_KEY, MENU_LABEL};
use std::path::Path;
const ROOTS: [&str; 3] = ["*", "Directory", "Directory\\Background"];
fn key_path(root: &str) -> String {
format!("Software\\Classes\\{root}\\shell\\{MENU_KEY}")
}
pub fn registered() -> bool {
use winreg::enums::HKEY_CURRENT_USER;
use winreg::RegKey;
RegKey::predef(HKEY_CURRENT_USER)
.open_subkey(key_path("*"))
.is_ok()
}
pub fn register() -> Result<(), String> {
use winreg::enums::HKEY_CURRENT_USER;
use winreg::RegKey;
let exe = exe_path();
if exe.is_empty() {
return Err("无法确定可执行文件路径".to_string());
}
if !Path::new(&exe).is_file() {
return Err(format!("可执行文件不存在:{exe}(开发模式下请先构建)"));
}
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
for root in ROOTS {
let path = key_path(root);
let (key, _) = hkcu
.create_subkey(&path)
.map_err(|e| format!("写入注册表失败({root}): {e}"))?;
key.set_value("", &MENU_LABEL)
.map_err(|e| format!("写入菜单名称失败({root}): {e}"))?;
key.set_value("Icon", &exe)
.map_err(|e| format!("写入菜单图标失败({root}): {e}"))?;
// Directory\Background 传入的是「当前目录」,用 %V;其余用 %1
let arg = if root.ends_with("Background") { "%V" } else { "%1" };
let (cmd_key, _) = hkcu
.create_subkey(format!("{path}\\command"))
.map_err(|e| format!("写入菜单命令失败({root}): {e}"))?;
cmd_key
.set_value("", &format!("\"{exe}\" \"{arg}\""))
.map_err(|e| format!("写入菜单命令行失败({root}): {e}"))?;
}
crate::logger::log_info("editor", &format!("已注册右键菜单,指向 {exe}"));
Ok(())
}
pub fn unregister() -> Result<(), String> {
use winreg::enums::HKEY_CURRENT_USER;
use winreg::RegKey;
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
for root in ROOTS {
let path = key_path(root);
match hkcu.delete_subkey_all(&path) {
Ok(()) => {}
// 本就不存在视为成功(幂等)
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(format!("删除注册表项失败({root}): {e}")),
}
}
crate::logger::log_info("editor", "已卸载右键菜单");
Ok(())
}
}
// ===== 非 Windows:明确告知不支持 =====
#[cfg(not(windows))]
mod imp {
pub fn registered() -> bool {
false
}
pub fn register() -> Result<(), String> {
Err("资源管理器右键菜单仅支持 Windows".to_string())
}
pub fn unregister() -> Result<(), String> {
Err("资源管理器右键菜单仅支持 Windows".to_string())
}
}
File renamed without changes.
@@ -1,6 +1,6 @@
//! 笔记模块的数据模型。
//!
//! 持久化位置:`{app_data_dir}/notes/settings.json`(与 ai / translate / terminal 同一范式)。
//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
//!
@@ -10,8 +10,11 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// 结构版本号。字段增减时递增,由 [`NoteSettings::heal`] 推进。
pub const NOTES_SETTINGS_VERSION: u32 = 2;
/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。
pub const EDITOR_SETTINGS_VERSION: u32 = 4;
/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。
pub const RECENT_LIMIT: usize = 20;
/// 同步方向。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -101,7 +104,7 @@ impl WebdavSettings {
}
}
/// 同步进度(事件 `notes-sync-progress` 的负载)。
/// 同步进度(事件 `editor-sync-progress` 的负载)。
#[derive(Debug, Clone, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SyncProgress {
@@ -155,16 +158,33 @@ pub struct ImportReport {
pub failures: Vec<String>,
}
/// 最近打开的一个文件 / 文件夹。
///
/// `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。
/// 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct RecentEntry {
/// 绝对路径(文件或文件夹)
pub path: String,
/// 显示名(文件名 / 文件夹名)
pub name: String,
/// 最近打开时间(Unix 毫秒)
pub opened_at: u64,
/// 该路径当前是否仍存在(读取设置时刷新)
pub exists: bool,
}
/// 笔记 / 编辑器设置根结构。
///
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct NoteSettings {
pub struct EditorSettings {
/// 结构版本号
pub version: u32,
/// 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`)
/// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`)
pub library_root: Option<String>,
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
pub editor_theme: String,
@@ -208,16 +228,20 @@ pub struct NoteSettings {
/// 全局快捷键:新建笔记(空串 = 不注册)。
///
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
/// 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
/// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
pub new_note_shortcut: String,
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
pub open_editor_shortcut: String,
/// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`])
pub recent_files: Vec<RecentEntry>,
/// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`])
pub recent_folders: Vec<RecentEntry>,
}
impl Default for NoteSettings {
impl Default for EditorSettings {
fn default() -> Self {
Self {
version: NOTES_SETTINGS_VERSION,
version: EDITOR_SETTINGS_VERSION,
library_root: None,
editor_theme: "system".to_string(),
follow_app_theme: true,
@@ -227,7 +251,9 @@ impl Default for NoteSettings {
ligatures: false,
tab_size: 2,
live_preview: true,
autosave_ms: 800,
// 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着
// 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。
autosave_ms: 0,
default_view: "wysiwyg".to_string(),
show_line_numbers: true,
show_outline: true,
@@ -239,12 +265,14 @@ impl Default for NoteSettings {
show_template_picker: true,
export_highlight: true,
new_note_shortcut: String::new(),
open_editor_shortcut: String::new(),
open_editor_shortcut: "Alt+E".to_string(),
recent_files: Vec::new(),
recent_folders: Vec::new(),
}
}
}
impl NoteSettings {
impl EditorSettings {
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
/// 返回是否发生了变更(由调用方决定是否落盘)。
pub fn heal(&mut self) -> bool {
@@ -287,13 +315,47 @@ impl NoteSettings {
}
}
if self.version < NOTES_SETTINGS_VERSION {
self.version = NOTES_SETTINGS_VERSION;
// v3:引入「打开编辑器」默认快捷键 Alt+E(用户已显式设过则不覆盖)
if self.version < 3 && self.open_editor_shortcut.trim().is_empty() {
self.open_editor_shortcut = "Alt+E".to_string();
changed = true;
}
// v4:自动保存默认从 800ms 改为关闭 —— 仍是 800 说明用户从未改过这个值
//(旧默认),此时关闭它;用户显式设过的其他值一律保留。
if self.version < 4 && self.autosave_ms == 800 {
self.autosave_ms = 0;
changed = true;
}
if self.version < EDITOR_SETTINGS_VERSION {
self.version = EDITOR_SETTINGS_VERSION;
changed = true;
}
// 最近记录上限:超出淘汰最旧(列表约定为新在前)
if self.recent_files.len() > RECENT_LIMIT {
self.recent_files.truncate(RECENT_LIMIT);
changed = true;
}
if self.recent_folders.len() > RECENT_LIMIT {
self.recent_folders.truncate(RECENT_LIMIT);
changed = true;
}
changed
}
/// 刷新最近记录的「是否存在」标记(读取设置时调用,供 UI 灰显失效项)。
pub fn refresh_recent_exists(&mut self) {
for entry in self
.recent_files
.iter_mut()
.chain(self.recent_folders.iter_mut())
{
entry.exists = !entry.path.trim().is_empty() && std::path::Path::new(&entry.path).exists();
}
}
}
/// 库内一个条目(文件或目录)的扁平描述。
@@ -323,7 +385,7 @@ pub struct LibraryEntry {
pub struct LibraryInfo {
/// 当前生效的库根绝对路径
pub root: String,
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`)
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`)
pub is_custom: bool,
/// `.md` 笔记数量(不含目录)
pub note_count: u32,
@@ -252,7 +252,7 @@ impl WebdavClient {
if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() {
let wait = BACKOFF_MS[attempt];
crate::logger::log_warn(
"notes",
"editor",
&format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1),
);
std::thread::sleep(Duration::from_millis(wait));
@@ -265,7 +265,7 @@ impl WebdavClient {
if attempt < BACKOFF_MS.len() {
let wait = BACKOFF_MS[attempt];
crate::logger::log_warn(
"notes",
"editor",
&format!("WebDAV 请求失败({e}),{wait}ms 后重试"),
);
std::thread::sleep(Duration::from_millis(wait));
@@ -373,7 +373,7 @@ impl WebdavClient {
while let Some(dir) = queue.pop() {
depth += 1;
if depth > 4096 {
crate::logger::log_warn("notes", "远端目录过多,提前结束遍历");
crate::logger::log_warn("editor", "远端目录过多,提前结束遍历");
break;
}
let Some(entries) = self.list(&dir)? else {
@@ -664,7 +664,7 @@ fn parse_http_date(value: &str) -> Option<u64> {
/// 该远端路径是否应当排除在同步之外。
///
/// `.notes/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
/// `.editor/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
pub fn should_skip(rel: &str) -> bool {
let normalized = rel.replace('\\', "/");
@@ -772,7 +772,7 @@ mod tests {
#[test]
fn skip_rules_exclude_private_dir() {
assert!(should_skip(".notes/notes.db"));
assert!(should_skip(".editor/editor.db"));
assert!(should_skip("a/.hidden/b.md"));
assert!(should_skip("node_modules/x.md"));
assert!(!should_skip("notes/a.md"));
@@ -15,11 +15,11 @@ pub mod sync;
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::notes::types::WebdavSettings;
use crate::editor::types::WebdavSettings;
use client::WebdavClient;
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
pub const KEYRING_PASSWORD: &str = "notes.webdav.password";
pub const KEYRING_PASSWORD: &str = "editor.webdav.password";
/// 连接自检结果(设置页展示)。
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
@@ -2,7 +2,7 @@
//!
//! # 状态存在哪、为什么不是「靠时间戳猜」
//!
//! `{库根}/.notes/sync.json` 记录**上次成功同步时**每个文件的两侧指纹:
//! `{库根}/.editor/sync.json` 记录**上次成功同步时**每个文件的两侧指纹:
//! 本地内容的 hash + 本地 mtime,以及远端的 mtime。有了基线才能回答「谁改的」:
//!
//! - 本地 hash ≠ 基线 hash → 本地改了;
@@ -36,11 +36,11 @@ use tauri::{AppHandle, Emitter};
use super::client::{should_skip, WebdavClient};
use crate::constants::events;
use crate::notes::index::content_hash;
use crate::notes::library;
use crate::notes::types::{ConflictPolicy, SyncDirection, WebdavSettings};
use crate::editor::index::content_hash;
use crate::editor::library;
use crate::editor::types::{ConflictPolicy, SyncDirection, WebdavSettings};
/// 同步状态文件名(位于库根 `.notes/` 下,永不参与同步)。
/// 同步状态文件名(位于库根 `.editor/` 下,永不参与同步)。
const SYNC_STATE_FILE: &str = "sync.json";
/// 状态文件结构版本。
const SYNC_STATE_VERSION: u32 = 1;
@@ -73,7 +73,7 @@ pub struct SyncState {
impl SyncState {
/// 从库根读取状态(缺失/损坏都回退空状态 —— 最坏结果是「下次同步当作首次」)。
pub fn load(root: &Path, remote_root: &str) -> Self {
let path = root.join(".notes").join(SYNC_STATE_FILE);
let path = root.join(".editor").join(SYNC_STATE_FILE);
let mut state: SyncState = std::fs::read_to_string(&path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
@@ -91,7 +91,7 @@ impl SyncState {
/// 落盘。
pub fn save(&self, root: &Path) -> Result<(), String> {
let dir = root.join(".notes");
let dir = root.join(".editor");
std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?;
let text = serde_json::to_string_pretty(self).map_err(|e| format!("序列化同步状态失败: {e}"))?;
std::fs::write(dir.join(SYNC_STATE_FILE), text).map_err(|e| format!("写入同步状态失败: {e}"))
@@ -546,14 +546,14 @@ impl<'a> SyncRunner<'a> {
/// 发进度事件(前端据此画进度条)。
fn progress(&self, done: usize, current: &str, kind: &str) {
let payload = crate::notes::types::SyncProgress {
let payload = crate::editor::types::SyncProgress {
done: done as u32,
total: self.total as u32,
current: current.to_string(),
kind: kind.to_string(),
message: String::new(),
};
let _ = self.app.emit(events::NOTES_SYNC_PROGRESS, payload);
let _ = self.app.emit(events::EDITOR_SYNC_PROGRESS, payload);
}
/// 执行整个计划。
@@ -579,7 +579,7 @@ impl<'a> SyncRunner<'a> {
if report.failures.len() < MAX_FAILURES {
report.failures.push(format!("{}:{e}", item.rel_path));
}
crate::logger::log_warn("notes", &format!("同步 {} 失败: {e}", item.rel_path));
crate::logger::log_warn("editor", &format!("同步 {} 失败: {e}", item.rel_path));
continue;
}
match item.kind {
@@ -1078,10 +1078,10 @@ mod tests {
let root = std::env::temp_dir().join(format!("thing-notes-scan-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("notes")).unwrap();
std::fs::create_dir_all(root.join(".notes")).unwrap();
std::fs::create_dir_all(root.join(".editor")).unwrap();
std::fs::write(root.join("notes/a.md"), "x").unwrap();
std::fs::write(root.join("notes/b.txt"), "x").unwrap();
std::fs::write(root.join(".notes/notes.db"), "x").unwrap();
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
let map = scan_local(&root).unwrap();
let keys: Vec<&String> = map.keys().collect();
+100 -69
View File
@@ -10,7 +10,7 @@ mod mihomo_manager;
mod monitor_kernel;
pub mod music;
mod network_monitor;
mod notes;
mod editor;
mod osd_window;
mod process_manager;
mod quickpanel;
@@ -38,17 +38,20 @@ use download_engine::{
use logger::{
log_clear, log_info_state, log_list, log_message,
};
use notes::{
notes_add_template, notes_authorize_file, notes_backlinks, notes_backup_now,
notes_create_folder, notes_create_note, notes_daily_note, notes_delete_entry,
notes_export_note, notes_export_snapshot_local, notes_export_zip, notes_get_settings,
notes_import, notes_index_stats, notes_library_info, notes_link_graph, notes_list_backups,
notes_list_notes, notes_list_templates, notes_open_file, notes_read_asset, notes_read_note,
notes_read_template, notes_rebuild_index, notes_rename_entry, notes_restore_backup,
notes_save_note, notes_save_settings, notes_scan_library, notes_search_notes,
notes_set_library_root, notes_set_webdav_password, notes_sync_index, notes_sync_now,
notes_tags, notes_take_pending_file, notes_test_webdav, notes_webdav_status,
notes_write_asset, notes_write_file,
use editor::{
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry, editor_restore_backup,
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
editor_write_asset, editor_write_file,
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path, editor_delete_path,
editor_move_path, editor_search_in_path, editor_replace_in_path,
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
};
use mihomo_manager::{
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
@@ -138,7 +141,7 @@ use quickpanel::{
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
};
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready, tray_music_control, tray_music_state};
use terminal::commands::{
terminal_attach_session, terminal_clear_known_hosts, terminal_clear_session,
terminal_close_session, terminal_confirm_host_key, terminal_default_cwd, terminal_delete_host,
@@ -337,18 +340,27 @@ fn export_bindings() {
dsh_unregister_shortcut, dsh_start, dsh_stop, dsh_restart,
dsh_ai_preview, dsh_ai_sync, dsh_log_tail, dsh_install_log, dsh_log_clear,
dsh_open_dir,
// notes(39)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
notes_get_settings, notes_save_settings, notes_library_info, notes_set_library_root,
notes_scan_library, notes_read_note, notes_save_note, notes_create_note,
notes_create_folder, notes_rename_entry, notes_delete_entry,
notes_rebuild_index, notes_sync_index, notes_search_notes, notes_list_notes,
notes_tags, notes_index_stats, notes_open_file, notes_write_file,
notes_write_asset, notes_authorize_file,
notes_list_templates, notes_add_template, notes_read_template, notes_daily_note,
notes_import, notes_export_note, notes_export_zip, notes_export_snapshot_local,
notes_webdav_status, notes_set_webdav_password, notes_test_webdav,
notes_sync_now, notes_backup_now, notes_list_backups, notes_restore_backup,
notes_backlinks, notes_link_graph, notes_take_pending_file, notes_read_asset,
// editor(40)——与 `run()` 里那份保持一致,否则 bindings.ts 缺类型
editor_get_settings, editor_save_settings, editor_library_info, editor_set_library_root,
editor_scan_library, editor_read_note, editor_save_note, editor_create_note,
editor_create_folder, editor_rename_entry, editor_delete_entry,
editor_rebuild_index, editor_sync_index, editor_search_notes, editor_list_notes,
editor_tags, editor_index_stats, editor_open_file, editor_write_file,
editor_scratch_dir,
editor_redecode_file,
editor_write_asset, editor_authorize_file,
editor_list_templates, editor_add_template, editor_read_template, editor_daily_note,
editor_import, editor_export_note, editor_export_zip, editor_export_snapshot_local,
editor_webdav_status, editor_set_webdav_password, editor_test_webdav,
editor_sync_now, editor_backup_now, editor_list_backups, editor_restore_backup,
editor_backlinks, editor_link_graph, editor_take_pending_file, editor_read_asset,
// 本地目录树(P3-5)
editor_read_dir, editor_create_file, editor_create_dir, editor_rename_path,
editor_delete_path, editor_move_path,
// 在路径中查找 / 替换(统一搜索器的「当前目录 / 笔记库」范围)
editor_search_in_path, editor_replace_in_path,
// 系统集成(P4-4)
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
])
.export(Typescript::default(), "../src/lib/bindings.ts")
.expect("failed to export bindings");
@@ -384,11 +396,13 @@ pub fn run() {
let _ = window.unminimize();
let _ = window.set_focus();
}
match crate::notes::note_path_from_args(argv.clone()) {
Some(path) => crate::notes::emit_open_file(app, &path),
// argv[0] 是第二个实例自身的 exe 路径(插件传的是完整命令行),必须跳过 ——
// 否则 `open_target_from_args` 会把 exe 当成「要打开的文件」返回。
match crate::editor::open_target_from_args(argv.into_iter().skip(1)) {
Some(target) => crate::editor::emit_open_target(app, &target),
None => {
// 没有文件参数(用户又点了一次快捷方式):只把主窗口叫到前面,别开新窗口
crate::logger::log_info("notes", "第二个实例无文件参数,仅聚焦主窗口");
crate::logger::log_info("editor", "第二个实例无文件参数,仅聚焦主窗口");
}
}
}))
@@ -618,6 +632,8 @@ pub fn run() {
tray_menu_action,
tray_menu_hide,
tray_menu_ready,
tray_music_state,
tray_music_control,
snap_fix::fix_snap_background,
screenshot_capture_fullscreen,
screenshot_get_fullscreen_bmp,
@@ -812,47 +828,62 @@ pub fn run() {
dsh_install_log,
dsh_log_clear,
dsh_open_dir,
// notes(39)
notes_get_settings,
notes_save_settings,
notes_library_info,
notes_set_library_root,
notes_scan_library,
notes_read_note,
notes_save_note,
notes_create_note,
notes_create_folder,
notes_rename_entry,
notes_delete_entry,
notes_rebuild_index,
notes_sync_index,
notes_search_notes,
notes_list_notes,
notes_tags,
notes_index_stats,
notes_open_file,
notes_write_file,
notes_write_asset,
notes_authorize_file,
notes_list_templates,
notes_add_template,
notes_read_template,
notes_daily_note,
notes_import,
notes_export_note,
notes_export_zip,
notes_export_snapshot_local,
notes_webdav_status,
notes_set_webdav_password,
notes_test_webdav,
notes_sync_now,
notes_backup_now,
notes_list_backups,
notes_restore_backup,
notes_backlinks,
notes_link_graph,
notes_take_pending_file,
notes_read_asset
// editor(39)
editor_get_settings,
editor_save_settings,
editor_library_info,
editor_set_library_root,
editor_scan_library,
editor_read_note,
editor_save_note,
editor_create_note,
editor_create_folder,
editor_rename_entry,
editor_delete_entry,
editor_rebuild_index,
editor_sync_index,
editor_search_notes,
editor_list_notes,
editor_tags,
editor_index_stats,
editor_open_file,
editor_scratch_dir,
editor_write_file,
editor_redecode_file,
editor_write_asset,
editor_authorize_file,
editor_list_templates,
editor_add_template,
editor_read_template,
editor_daily_note,
editor_import,
editor_export_note,
editor_export_zip,
editor_export_snapshot_local,
editor_webdav_status,
editor_set_webdav_password,
editor_test_webdav,
editor_sync_now,
editor_backup_now,
editor_list_backups,
editor_restore_backup,
editor_backlinks,
editor_link_graph,
editor_take_pending_file,
editor_read_asset,
// 本地目录树(P3-5)
editor_read_dir,
editor_create_file,
editor_create_dir,
editor_rename_path,
editor_delete_path,
editor_move_path,
editor_search_in_path,
editor_replace_in_path,
// 系统集成(P4-4)
editor_context_menu_status,
editor_register_context_menu,
editor_unregister_context_menu
])
.setup(setup::init)
.on_window_event(|window, event| {
+1 -1
View File
@@ -43,7 +43,7 @@ pub use remote::{
pub use smtc::{
music_smtc_clear, music_smtc_update_metadata, music_smtc_update_playback_state,
music_smtc_update_position, SmtcController,
music_smtc_update_position, SmtcController, SMTC_BUTTON_EVENT,
};
pub use commands::{
-153
View File
@@ -1,153 +0,0 @@
//! 「用 Thing 打开」的参数解析与事件投递。
//!
//! # 两条入口,同一份逻辑
//!
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
//! 2. **热启动**:应用已在运行时双击 `.md`,会起第二个进程,由
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
//!
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`note_path_from_args`]。
//! 解析成功后统一发 [`crate::constants::events::NOTES_OPEN_FILE`],**窗口由前端创建** ——
//! Rust 侧不持有窗口 label 策略,也不该知道「用户是不是想让它在已有窗口里打开」。
use std::path::{Path, PathBuf};
use std::sync::Mutex;
/// 「启动时命令行指定的文件」缓存。
///
/// # 为什么需要缓存而不是启动时直接 `emit`
///
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
/// 「双击 .md 打开了应用,但笔记没打开」。
///
/// 因此这里把路径存下来,由前端在注册完监听后**主动取一次**
/// (`notes_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
static PENDING: std::sync::OnceLock<Mutex<Option<PathBuf>>> = std::sync::OnceLock::new();
fn pending_slot() -> &'static Mutex<Option<PathBuf>> {
PENDING.get_or_init(|| Mutex::new(None))
}
/// 记下「启动时想打开的文件」(由 `setup` 调用)。
pub fn remember_pending_file(path: PathBuf) {
if let Ok(mut slot) = pending_slot().lock() {
*slot = Some(path);
}
}
/// 取出并清空待打开文件(由 `notes_take_pending_file` 命令调用)。
pub fn take_pending_file() -> Option<PathBuf> {
pending_slot()
.lock()
.ok()
.and_then(|mut slot| slot.take())
}
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径。
///
/// # 为什么需要挑而不是直接用 `args[1]`
///
/// 关联启动时命令行长这样:`thing.exe D:\笔记\会议.md`;
/// 但从「开始菜单 → 打开」启动时可能有别的开关参数;开发模式下还有 `cargo run --`。
/// 这里只认「**存在**的文件 + 笔记类扩展名」,其余一律忽略 ——
/// 宁可漏开一个窗口,也不要因为一个参数把主窗口的启动逻辑搞乱。
///
/// 认的扩展名比「只有 .md」宽一点:`.markdown` / `.mdx` 也常见,且编辑器都能处理
/// (打开后走「库外文件」路径,不影响库内笔记的 `.md` 约定)。
///
/// # 为什么要 `.is_file()`
///
/// 参数里出现 `foo.md` 但那个文件其实不存在(用户删了、路径编码错了)时,
/// 让前端去报「文件不存在」不如在这里就静默忽略 —— 前端那条路径会开一个空窗口。
pub fn note_path_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<PathBuf> {
for arg in args {
let trimmed = arg.trim().trim_matches('"');
if trimmed.is_empty() || trimmed.starts_with('-') {
continue;
}
let lower = trimmed.to_ascii_lowercase();
let is_note_ext =
lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".mdx");
if !is_note_ext {
continue;
}
let path = PathBuf::from(trimmed);
if path.is_file() {
return Some(path);
}
}
None
}
/// 通知前端「要打开这个文件」(窗口由前端创建)。
pub fn emit_open_file(app: &tauri::AppHandle, path: &Path) {
use tauri::Emitter;
let payload = serde_json::json!({ "path": path.to_string_lossy() });
if let Err(e) = app.emit(crate::constants::events::NOTES_OPEN_FILE, payload) {
crate::logger::log_warn("notes", &format!("发出打开文件事件失败: {e}"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_note(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
std::fs::write(&path, "# x").unwrap();
path
}
#[test]
fn picks_markdown_path_and_ignores_flags() {
let note = temp_note("会议.md");
let args = vec![
"--some-flag".to_string(),
"not-a-file".to_string(),
note.to_string_lossy().to_string(),
];
assert_eq!(note_path_from_args(args), Some(note.clone()));
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
#[test]
fn accepts_markdown_and_mdx_too() {
let note = temp_note("a.markdown");
assert_eq!(
note_path_from_args(vec![note.to_string_lossy().to_string()]),
Some(note.clone())
);
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
#[test]
fn ignores_non_markdown_and_missing_files() {
// 非笔记扩展名
assert_eq!(note_path_from_args(vec!["C:\\a\\b.txt".to_string()]), None);
// 不存在的 .md:静默忽略(否则会开一个空窗口)
assert_eq!(
note_path_from_args(vec!["C:\\definitely\\missing\\x.md".to_string()]),
None
);
// 空参数与开关
assert_eq!(
note_path_from_args(vec!["".to_string(), "-v".to_string()]),
None
);
}
#[test]
fn strips_surrounding_quotes() {
let note = temp_note("带 空格.md");
let quoted = format!("\"{}\"", note.to_string_lossy());
assert_eq!(note_path_from_args(vec![quoted]), Some(note.clone()));
let _ = std::fs::remove_file(&note);
let _ = std::fs::remove_dir_all(note.parent().unwrap());
}
}
+7 -7
View File
@@ -21,7 +21,7 @@ use crate::mihomo_manager::MihomoManager;
use crate::monitor_kernel::{MonitorKernel, check_and_relaunch_if_needed};
use crate::music::MusicManager;
use crate::network_monitor::NetworkMonitor;
use crate::notes::NotesManager;
use crate::editor::EditorManager;
use crate::process_manager::{ProcessManager, start_monitoring_thread};
use crate::terminal::TerminalManager;
use crate::translate::TranslateManager;
@@ -84,19 +84,19 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
let dsh = crate::dsh::DshManager::new(app_data_dir.clone());
app.manage(dsh);
// ===== 笔记模块:NotesManager =====
// ===== 笔记模块:EditorManager =====
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
let notes = NotesManager::new(app_data_dir.clone());
let notes = EditorManager::new(app_data_dir.clone());
let _ = notes.load_settings();
// 按设置注册「新建笔记 / 打开编辑器」两个全局快捷键(失败只记日志,不阻断启动)
notes.init_on_launch(app.handle());
app.manage(notes);
// 「用 Thing 打开」的**冷启动**路径:命令行里带了 .md 就记下来。
// 不在这里 `emit` —— 此时 WebView 还没加载、前端还没注册监听,事件会丢掉。
// 前端注册完监听后会主动调 `notes_take_pending_file` 取走(见 notes/args.rs)。
if let Some(path) = crate::notes::note_path_from_args(std::env::args().skip(1)) {
crate::logger::log_info("notes", &format!("命令行指定打开: {}", path.display()));
crate::notes::remember_pending_file(path);
// 前端注册完监听后会主动调 `editor_take_pending_file` 取走(见 editor/args.rs)。
if let Some(target) = crate::editor::open_target_from_args(std::env::args().skip(1)) {
crate::logger::log_info("editor", &format!("命令行指定打开: {}", target.path().display()));
crate::editor::remember_pending_target(target);
}
// ===== 翻译模块:TranslateManager =====
+86 -6
View File
@@ -27,6 +27,7 @@ static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(N
use crate::win32_util::{get_work_area, get_monitor_bounds_at_point, get_dpi_for_point};
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
use crate::monitor_kernel::MonitorKernel;
use crate::music::{AudioEngine, SmtcMetaCache, SMTC_BUTTON_EVENT};
use crate::process_manager::{ProcessManager, ProcessStatus};
/// 托盘菜单窗口标签
@@ -53,6 +54,34 @@ pub struct TrayMenuState {
pub proxy_current: Option<String>,
}
/// 托盘音乐控制条状态。
///
/// 曲目信息取自 [`SmtcMetaCache`](前端推给 SMTC 的元数据回填),
/// 播放态取自 [`AudioEngine`]:两者都在 Rust 侧,托盘菜单只需一次拉取。
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MusicState {
pub playing: bool,
pub title: String,
pub artist: String,
}
fn get_music_state(app: &AppHandle) -> MusicState {
let playing = app
.try_state::<AudioEngine>()
.map(|e| e.state().playing)
.unwrap_or(false);
let (title, artist) = app
.try_state::<SmtcMetaCache>()
.and_then(|c| c.0.lock().ok().map(|g| (g.title.clone(), g.artist.clone())))
.unwrap_or_default();
MusicState {
playing,
title,
artist,
}
}
// ===== 状态查询 =====
fn is_proxy_running(app: &AppHandle) -> bool {
@@ -420,14 +449,18 @@ pub async fn tray_menu_action(
send_notification(&app, "Kernel 重启失败", &e);
}
}
"download_new" => {
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
"terminal" => {
// 新建终端选择窗口由前端创建(label 需命中 terminal-window-* 授权)
let _ = app.emit(crate::constants::events::TRAY_OPEN_TERMINAL, ());
hide_tray_menu(&app);
}
"settings" => {
focus_main_window(&app);
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
"dsh" => {
// 未启动时前端会先开进度窗口并同步拉起服务
let _ = app.emit(crate::constants::events::TRAY_OPEN_DSH, ());
hide_tray_menu(&app);
}
"editor" => {
let _ = app.emit(crate::constants::events::TRAY_OPEN_EDITOR, ());
hide_tray_menu(&app);
}
"quit" => {
@@ -463,6 +496,37 @@ pub async fn tray_menu_hide(app: AppHandle) -> Result<(), String> {
Ok(())
}
/// 读取音乐控制条状态(托盘菜单显示时 / 可见期间轮询)。
#[tauri::command]
pub fn tray_music_state(app: AppHandle) -> MusicState {
get_music_state(&app)
}
/// 托盘音乐控制条动作。
///
/// 动作统一经 [`SMTC_BUTTON_EVENT`] 转给主窗口前端(`feiniuStore`)执行——
/// 队列、洗牌、单曲循环等播放语义都在前端,托盘只负责转发,不重复实现。
/// `action`:`toggle` | `play` | `pause` | `next` | `prev`。
#[tauri::command]
pub fn tray_music_control(app: AppHandle, action: String) -> Result<(), String> {
let name = match action.as_str() {
"play" => "play",
"pause" => "pause",
// 无当前会话时按下「播放/暂停」应重新起播,故按引擎真实态决定
"toggle" => {
if get_music_state(&app).playing {
"pause"
} else {
"play"
}
}
"next" => "next",
"prev" => "prev",
other => return Err(format!("未知的音乐控制动作: {other}")),
};
app.emit(SMTC_BUTTON_EVENT, name).map_err(|e| e.to_string())
}
/// 前端测量内容高度后调用:调整窗口大小、精确定位、然后显示。
/// 这样窗口从一开始就是正确尺寸和位置,不会出现间隙。
#[tauri::command]
@@ -502,6 +566,22 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
let mut t = LAST_SHOW_TIME.lock().unwrap_or_else(|e| e.into_inner());
*t = Some(Instant::now());
}
// 位置与尺寸先交给一次原生 SetWindowPos 落位:窗口隐藏时,上面的 set_size/set_position
// 不保证在紧随其后的 show 之前生效,首次弹出会沿用预创建时的旧高度——表现为
// 「第一次高度不对、收起后再开正常」。原生调用同步返回,窗口已处于目标位置与尺寸。
// 显示仍走 Tauri 的 show():它才会做 tao 的可见性/激活/Z 序处理(直接 SWP_SHOWWINDOW
// 会让菜单掉到任务栏后面,且窗口拿不到焦点,失焦自动关闭随之失效)。
#[cfg(windows)]
if let Ok(hwnd) = win.hwnd() {
crate::win32_util::set_bounds(
hwnd.0 as isize,
x as i32,
y as i32,
win_w_px as i32,
win_h_px as i32,
);
}
let _ = win.show();
let _ = win.set_focus();
+42
View File
@@ -233,6 +233,45 @@ pub fn hide_window(hwnd: isize) {
}
}
/// 一次调用原子地设置窗口位置与**客户区**尺寸(物理像素),不改变可见性与 Z 序。
///
/// `w`/`h` 是客户区(内容区)尺寸,不是外框尺寸——调用方量的是内容高度,这里负责换算:
/// `SetWindowPos` 的宽高按**外框**算,而无边框 + 阴影的窗口外侧还有一段 DWM 阴影边距,
/// 直接把它当外框传会把客户区压小、内容底下被裁掉。换算方式与 tao 的 `set_inner_size`
/// 一致:用 `GetWindowRect - GetClientRect` 得到这段隐藏偏移后补上去。
///
/// 存在的理由:窗口处于隐藏态时,Tauri 的 `set_size`/`set_position` 不保证在紧随其后的
/// `show` 之前落到窗口上——托盘菜单首次弹出因此沿用预创建时的旧高度,收起后再开才正常。
/// `SetWindowPos` 是同步调用,返回时窗口已在目标位置与尺寸上;先由它落位、再走 Tauri 的
/// `show()`,首次显示即为最终尺寸且无中间帧。
///
/// 注意**不要**在这里加 `SWP_SHOWWINDOW`:那会绕开 tao 的可见性/激活处理,
/// 窗口既不置顶(掉到任务栏后面)也拿不到焦点(继而不能靠失焦自动关闭)。
#[cfg(windows)]
pub fn set_bounds(hwnd: isize, x: i32, y: i32, w: i32, h: i32) {
use windows_sys::Win32::Foundation::RECT;
use windows_sys::Win32::UI::WindowsAndMessaging::{
GetClientRect, GetWindowRect, SetWindowPos, SWP_NOACTIVATE, SWP_NOZORDER,
};
unsafe {
let (mut wr, mut cr): (RECT, RECT) = (std::mem::zeroed(), std::mem::zeroed());
if GetWindowRect(hwnd, &mut wr) == 0 || GetClientRect(hwnd, &mut cr) == 0 {
return;
}
let frame_w = (wr.right - wr.left) - (cr.right - cr.left);
let frame_h = (wr.bottom - wr.top) - (cr.bottom - cr.top);
SetWindowPos(
hwnd,
0,
x,
y,
w + frame_w,
h + frame_h,
SWP_NOACTIVATE | SWP_NOZORDER,
);
}
}
/// 系统自上次用户输入(鼠标/键盘)以来的空闲时长(毫秒)。
/// 用于闲时执行耗时后台任务(如文件索引构建),避免与应用运行/用户操作抢 IO。
/// GetLastInputInfo 的 dwTime 与 GetTickCount 同为系统启动后毫秒数,用 wrapping 减法防回绕。
@@ -288,5 +327,8 @@ pub fn show_no_activate(_hwnd: isize) {}
#[cfg(not(windows))]
pub fn hide_window(_hwnd: isize) {}
#[cfg(not(windows))]
pub fn set_bounds(_hwnd: isize, _x: i32, _y: i32, _w: i32, _h: i32) {}
#[cfg(not(windows))]
pub fn get_idle_time_ms() -> u64 { 0 }
+2 -2
View File
@@ -41,8 +41,8 @@
"fileAssociations": [
{
"ext": ["md", "markdown", "mdx"],
"name": "Markdown 笔记",
"description": "用 Thing 打开 Markdown 笔记",
"name": "Markdown 文档",
"description": "用 Thing 编辑器打开 Markdown 文档",
"role": "Editor"
}
],
+21 -14
View File
@@ -14,10 +14,12 @@ import { useScreenshotStore } from '@/stores/screenshotStore'
import { useQuickPanelStore } from '@/stores/quickpanelStore'
import { useMonitorStore } from '@/stores/monitorStore'
import { useProcessStore } from '@/stores/processStore'
import { useDshStore } from '@/stores/dshStore'
import { TooltipProvider } from '@/components/ui/tooltip'
import { moduleRegistry } from '@/modules/registry'
import type { ModuleMeta } from '@/types/module'
import { pendingNewDownload } from '@/lib/trayEvents'
import { openTerminalPickerWindow } from '@/modules/terminal/openWindow'
import { openEditorWindow } from '@/modules/editor/openWindow'
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
import { commands } from '@/lib/bindings'
@@ -27,6 +29,7 @@ const screenshotStore = useScreenshotStore()
const quickpanelStore = useQuickPanelStore()
const monitorStore = useMonitorStore()
const processStore = useProcessStore()
const dshStore = useDshStore()
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
interface NavModule {
@@ -244,15 +247,24 @@ onMounted(async () => {
// 监听托盘菜单事件
// tray:toggle-osd 由 monitorStore.initOsd() 注册的监听处理(与监控模块生命周期解耦)
// 托盘「终端」:开「新建终端选择窗口」(与快捷键同一条路径,全程不打扰主窗口)
trayUnlisteners.push(
await listen(EVENTS.trayNewDownload, () => {
// 设置标志位,DownloaderModule 挂载后消费
pendingNewDownload.value = true
// 切换到下载模块(如果未启用则切换到设置)
const enabledIds = appStore.enabledModules.map(m => m.id)
if (enabledIds.includes('downloader') || moduleRegistry.getConfig('downloader')?.builtin) {
handleModuleChange('downloader')
}
await listen(EVENTS.trayOpenTerminal, () => {
void openTerminalPickerWindow().catch(e =>
console.error('[tray] 打开终端窗口失败:', e)
)
})
)
// 托盘「编辑器」:开编辑器独立窗口
trayUnlisteners.push(
await listen(EVENTS.trayOpenEditor, () => {
void openEditorWindow().catch(e => console.error('[tray] 打开编辑器窗口失败:', e))
})
)
// 托盘「dsh」:就绪则直接开界面,否则先开启动进度窗口并同步拉起服务
trayUnlisteners.push(
await listen(EVENTS.trayOpenDsh, () => {
void dshStore.openFromTray().catch(e => console.error('[tray] 打开 dsh 失败:', e))
})
)
// 浏览器扩展新增下载:为该任务创建一个专属的一次性下载窗口(不打断主界面)。
@@ -263,11 +275,6 @@ onMounted(async () => {
void openDownloadWindow(e.payload.id)
})
)
trayUnlisteners.push(
await listen(EVENTS.trayOpenSettings, () => {
handleModuleChange('settings')
})
)
// 截图导出监听(应用级常驻,确保任何来源的截图都记录到历史)
screenshotStore.initExportListener().catch(e => console.error('[screenshot] 导出监听初始化失败:', e))
// 滚动截图完成 → 进编辑器(应用级常驻)
+353 -107
View File
@@ -921,53 +921,68 @@ export const commands = {
/** 在资源管理器中打开 dsh 模块目录。 */
dshOpenDir: () => __TAURI_INVOKE<null>("dsh_open_dir"),
/** 读取笔记模块设置。 */
notesGetSettings: () => __TAURI_INVOKE<NoteSettings>("notes_get_settings"),
editorGetSettings: () => __TAURI_INVOKE<EditorSettings>("editor_get_settings"),
/** 保存笔记模块设置(自愈后落盘,并广播给各窗口)。 */
notesSaveSettings: (settings: NoteSettings) => __TAURI_INVOKE<NoteSettings>("notes_save_settings", { settings }),
editorSaveSettings: (settings: EditorSettings) => __TAURI_INVOKE<EditorSettings>("editor_save_settings", { settings }),
/** 当前库状态概览(库根 / 是否自定义 / 笔记数)。 */
notesLibraryInfo: () => __TAURI_INVOKE<LibraryInfo>("notes_library_info"),
editorLibraryInfo: () => __TAURI_INVOKE<LibraryInfo>("editor_library_info"),
/** 设置库根(`None` 或空串 = 恢复默认库根)。 */
notesSetLibraryRoot: (root: string | null) => __TAURI_INVOKE<LibraryInfo>("notes_set_library_root", { root }),
editorSetLibraryRoot: (root: string | null) => __TAURI_INVOKE<LibraryInfo>("editor_set_library_root", { root }),
/** 扫描库,返回扁平条目列表(前端组树)。 */
notesScanLibrary: () => __TAURI_INVOKE<LibraryEntry[]>("notes_scan_library"),
editorScanLibrary: () => __TAURI_INVOKE<LibraryEntry[]>("editor_scan_library"),
/** 读取一篇笔记。 */
notesReadNote: (relPath: string) => __TAURI_INVOKE<NoteDoc>("notes_read_note", { relPath }),
editorReadNote: (relPath: string) => __TAURI_INVOKE<NoteDoc>("editor_read_note", { relPath }),
/** 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。 */
notesSaveNote: (relPath: string, content: string) => __TAURI_INVOKE<NoteDoc>("notes_save_note", { relPath, content }),
editorSaveNote: (relPath: string, content: string) => __TAURI_INVOKE<NoteDoc>("editor_save_note", { relPath, content }),
/**
* 新建笔记(自动补 `.md`、重名加序号),返回新文档。
*
* `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
* 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
*/
notesCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE<NoteDoc>("notes_create_note", { dirRel, name, templateId }),
editorCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE<NoteDoc>("editor_create_note", { dirRel, name, templateId }),
/** 新建文件夹。 */
notesCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE<null>("notes_create_folder", { dirRel, name }),
editorCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE<null>("editor_create_folder", { dirRel, name }),
/** 重命名条目,返回新相对路径。 */
notesRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE<string>("notes_rename_entry", { relPath, newName }),
editorRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE<string>("editor_rename_entry", { relPath, newName }),
/** 删除条目(目录递归删除)。 */
notesDeleteEntry: (relPath: string) => __TAURI_INVOKE<null>("notes_delete_entry", { relPath }),
editorDeleteEntry: (relPath: string) => __TAURI_INVOKE<null>("editor_delete_entry", { relPath }),
/** 全量重建索引(设置页「重建索引」)。文件不受影响。 */
notesRebuildIndex: () => __TAURI_INVOKE<NoteIndexReport>("notes_rebuild_index"),
editorRebuildIndex: () => __TAURI_INVOKE<NoteIndexReport>("editor_rebuild_index"),
/** 增量同步索引(打开编辑器 / 手动刷新时调用)。 */
notesSyncIndex: () => __TAURI_INVOKE<NoteIndexReport>("notes_sync_index"),
editorSyncIndex: () => __TAURI_INVOKE<NoteIndexReport>("editor_sync_index"),
/** 全文检索 / 按标签 / 按目录筛选。 */
notesSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE<NoteSearchPage>("notes_search_notes", { query }),
editorSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE<NoteSearchPage>("editor_search_notes", { query }),
/** 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。 */
notesListNotes: (limit: number | null) => __TAURI_INVOKE<NoteSearchHit[]>("notes_list_notes", { limit }),
editorListNotes: (limit: number | null) => __TAURI_INVOKE<NoteSearchHit[]>("editor_list_notes", { limit }),
/** 标签及计数。 */
notesTags: () => __TAURI_INVOKE<NoteTagCount[]>("notes_tags"),
editorTags: () => __TAURI_INVOKE<NoteTagCount[]>("editor_tags"),
/** 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。 */
notesIndexStats: () => __TAURI_INVOKE<NoteIndexStats>("notes_index_stats"),
editorIndexStats: () => __TAURI_INVOKE<NoteIndexStats>("editor_index_stats"),
/**
* 打开(读取)库外任意文件。
*
* 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
* 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
*/
notesOpenFile: (path: string) => __TAURI_INVOKE<FileDoc>("notes_open_file", { path }),
editorOpenFile: (path: string) => __TAURI_INVOKE<FileDoc>("editor_open_file", { path }),
/** 保存库外任意文件(按前端回传的编码与换行写回)。 */
notesWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE<FileDoc>("notes_write_file", { path, content, encoding, eol }),
editorWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE<FileDoc>("editor_write_file", { path, content, encoding, eol }),
/**
* 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。
*
* 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿,
* 收尾交给「关闭该文件时选择保存 / 删除」。
*
* # 为什么不放在**安装目录**
*
* 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败;
* 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的
* 标准位置,且卸载时随程序数据一起清理。
*/
editorScratchDir: () => __TAURI_INVOKE<string>("editor_scratch_dir"),
/** 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。 */
editorRedecodeFile: (path: string, encoding: string) => __TAURI_INVOKE<FileDoc>("editor_redecode_file", { path, encoding }),
/**
* 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
*
@@ -975,21 +990,21 @@ export const commands = {
* 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
* 安全得多(写的位置由后端决定,且只落在 `assets/`)。
*/
notesWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE<string>("notes_write_asset", { fileName, ext, dataBase64 }),
editorWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE<string>("editor_write_asset", { fileName, ext, dataBase64 }),
/**
* 显式登记一个路径为「可写」。
*
* 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
* 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
* 但用户确实是用系统对话框选的,属于「用户显式选择」)。
*/
notesAuthorizeFile: (path: string) => __TAURI_INVOKE<null>("notes_authorize_file", { path }),
editorAuthorizeFile: (path: string) => __TAURI_INVOKE<null>("editor_authorize_file", { path }),
/**
* 列出可用模板(用户模板优先,同名覆盖内置)。
*
* 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
* 就能直接写文件,不需要用户先去资源管理器建目录。
*/
notesListTemplates: () => __TAURI_INVOKE<NoteTemplate[]>("notes_list_templates"),
editorListTemplates: () => __TAURI_INVOKE<NoteTemplate[]>("editor_list_templates"),
/**
* 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
*
@@ -997,61 +1012,111 @@ export const commands = {
* - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
* - 传 `name` + `body`:新建一个自定义模板。
*/
notesAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE<string[]>("notes_add_template", { name, body }),
editorAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE<string[]>("editor_add_template", { name, body }),
/**
* 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
*
* 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
* 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
*/
notesReadTemplate: (templateId: string) => __TAURI_INVOKE<TemplateSource>("notes_read_template", { templateId }),
editorReadTemplate: (templateId: string) => __TAURI_INVOKE<TemplateSource>("editor_read_template", { templateId }),
/** 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。 */
notesDailyNote: () => __TAURI_INVOKE<NoteDoc>("notes_daily_note"),
editorDailyNote: () => __TAURI_INVOKE<NoteDoc>("editor_daily_note"),
/** 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 */
notesImport: (source: string, destDir: string) => __TAURI_INVOKE<ImportReport>("notes_import", { source, destDir }),
editorImport: (source: string, destDir: string) => __TAURI_INVOKE<ImportReport>("editor_import", { source, destDir }),
/**
* 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
*
* HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
* 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
*/
notesExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE<string>("notes_export_note", { relPath, html, dest }),
editorExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE<string>("editor_export_note", { relPath, html, dest }),
/** 把整库(或某个目录)打包成 zip,返回落盘路径。 */
notesExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE<string>("notes_export_zip", { dest, dirRel }),
editorExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE<string>("editor_export_zip", { dest, dirRel }),
/**
* 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
*
* 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
* 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
* 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
* 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
*/
notesExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE<string>("notes_export_snapshot_local", { dest }),
editorExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE<string>("editor_export_snapshot_local", { dest }),
/** 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。 */
notesWebdavStatus: () => __TAURI_INVOKE<WebdavStatus>("notes_webdav_status"),
editorWebdavStatus: () => __TAURI_INVOKE<WebdavStatus>("editor_webdav_status"),
/** 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。 */
notesSetWebdavPassword: (password: string) => __TAURI_INVOKE<null>("notes_set_webdav_password", { password }),
editorSetWebdavPassword: (password: string) => __TAURI_INVOKE<null>("editor_set_webdav_password", { password }),
/** 连接自检(建目录 + 列远端)。 */
notesTestWebdav: () => __TAURI_INVOKE<WebdavTestResult>("notes_test_webdav"),
editorTestWebdav: () => __TAURI_INVOKE<WebdavTestResult>("editor_test_webdav"),
/** 立即同步(并按设置决定是否追加一次快照备份)。 */
notesSyncNow: () => __TAURI_INVOKE<SyncOutcome>("notes_sync_now"),
editorSyncNow: () => __TAURI_INVOKE<SyncOutcome>("editor_sync_now"),
/** 只做一次 zip 快照备份(不上传增量)。 */
notesBackupNow: () => __TAURI_INVOKE<BackupReport>("notes_backup_now"),
editorBackupNow: () => __TAURI_INVOKE<BackupReport>("editor_backup_now"),
/** 列出远端已有快照。 */
notesListBackups: () => __TAURI_INVOKE<BackupSnapshot[]>("notes_list_backups"),
editorListBackups: () => __TAURI_INVOKE<BackupSnapshot[]>("editor_list_backups"),
/** 从远端快照恢复(不覆盖本地已有文件)。 */
notesRestoreBackup: (name: string) => __TAURI_INVOKE<ImportReport>("notes_restore_backup", { name }),
editorRestoreBackup: (name: string) => __TAURI_INVOKE<ImportReport>("editor_restore_backup", { name }),
/** 一篇笔记的链接关系(出链 + 入链)。 */
notesBacklinks: (relPath: string) => __TAURI_INVOKE<NoteBacklinks>("notes_backlinks", { relPath }),
editorBacklinks: (relPath: string) => __TAURI_INVOKE<NoteBacklinks>("editor_backlinks", { relPath }),
/** 全库链接图(已解析的内部链接边)。 */
notesLinkGraph: () => __TAURI_INVOKE<LinkEdge[]>("notes_link_graph"),
editorLinkGraph: () => __TAURI_INVOKE<LinkEdge[]>("editor_link_graph"),
/**
* 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
*
* 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
* 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。
* 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
*/
notesTakePendingFile: () => __TAURI_INVOKE<string | null>("notes_take_pending_file"),
notesReadAsset: (relPath: string) => __TAURI_INVOKE<string | null>("notes_read_asset", { relPath }),
editorTakePendingFile: () => __TAURI_INVOKE<{
/** 绝对路径 */
path: string,
/** `"file"` | `"folder"` */
kind: string,
} | null>("editor_take_pending_file"),
editorReadAsset: (relPath: string) => __TAURI_INVOKE<string | null>("editor_read_asset", { relPath }),
/** 列举本地目录(`path` 为空 = 用户主目录)。 */
editorReadDir: (path: string) => __TAURI_INVOKE<LocalDir>("editor_read_dir", { path }),
/** 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。 */
editorCreateFile: (dir: string, name: string) => __TAURI_INVOKE<string>("editor_create_file", { dir, name }),
/**
* 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。
*
* 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹
* 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同
* (真实文件系统 vs 库内),必须能同时在命令表里存在。
*/
editorCreateDir: (dir: string, name: string) => __TAURI_INVOKE<string>("editor_create_dir", { dir, name }),
/** 同目录内重命名。目标存在则报错。 */
editorRenamePath: (path: string, newName: string) => __TAURI_INVOKE<string>("editor_rename_path", { path, newName }),
/**
* 删除若干本地项(**走系统回收站**,不是永久删除)。
*
* 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。
*/
editorDeletePath: (paths: string[]) => __TAURI_INVOKE<DeleteReport>("editor_delete_path", { paths }),
/**
* 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。
*
* 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。
*/
editorMovePath: (path: string, destDir: string) => __TAURI_INVOKE<string>("editor_move_path", { path, destDir }),
/**
* 「在路径中查找」命令。
*
* 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它
* (范式同 `editor_delete_path` / `editor_sync_now`)。
*/
editorSearchInPath: (query: PathSearchQuery) => __TAURI_INVOKE<PathSearchResult>("editor_search_in_path", { query }),
/**
* 「在路径中替换」命令。
*
* 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。
*/
editorReplaceInPath: (query: PathReplaceQuery) => __TAURI_INVOKE<PathReplaceResult>("editor_replace_in_path", { query }),
/** 读取当前状态。 */
editorContextMenuStatus: () => __TAURI_INVOKE<ContextMenuStatus>("editor_context_menu_status"),
/** 注册右键菜单(写 HKCU)。 */
editorRegisterContextMenu: () => __TAURI_INVOKE<ContextMenuStatus>("editor_register_context_menu"),
/** 卸载右键菜单(删 HKCU 对应项)。 */
editorUnregisterContextMenu: () => __TAURI_INVOKE<ContextMenuStatus>("editor_unregister_context_menu"),
};
/* Types */
@@ -1509,6 +1574,16 @@ export type ConflictPolicy =
/** 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径) */
"keepBoth";
/** 右键菜单状态(回传设置页展示)。 */
export type ContextMenuStatus = {
/** 是否已注册(以 `*` 键为准) */
registered: boolean,
/** 当前可执行文件绝对路径(注册表里写入的就是它) */
exePath: string,
/** 是否开发模式(exe 路径不稳定,UI 需给出提示) */
isDev: boolean,
};
/** 自定义命令 */
export type CustomCommand = {
id: string,
@@ -1517,6 +1592,14 @@ export type CustomCommand = {
args?: string[],
};
/** 批量删除结果(回传前端展示「成功 N 项、失败明细」)。 */
export type DeleteReport = {
/** 成功移入回收站的项数 */
removed: number,
/** 失败明细(路径 + 原因) */
failed: string[],
};
/** 批量删除单个条目的结果。 */
export type DeleteResult = {
name: string,
@@ -1736,6 +1819,73 @@ export type DuplicateKind =
/** 磁盘文件已存在 */
"fileExists";
/**
* 笔记 / 编辑器设置根结构。
*
* 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
* 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
*/
export type EditorSettings = {
/** 结构版本号 */
version?: number,
/** 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`) */
libraryRoot?: string | null,
/** 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …) */
editorTheme?: string,
/** 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准) */
followAppTheme?: boolean,
/** 编辑器字体族(空串 = 用内置等宽字体栈) */
fontFamily?: string,
/** 字号(px) */
fontSize?: number,
/** 行高倍数 */
lineHeight?: number | null,
/** 是否启用字体连字(ligatures) */
ligatures?: boolean,
/** Tab 宽度(空格数) */
tabSize?: number,
/** 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮) */
livePreview?: boolean,
/** 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S) */
autosaveMs?: number,
/** 默认视图:"wysiwyg" | "source" */
defaultView?: string,
/** 是否显示行号 */
showLineNumbers?: boolean,
/** 是否显示大纲侧栏(P1) */
showOutline?: boolean,
/** 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭) */
autocomplete?: boolean,
/**
* 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
* 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
*/
maxFileSizeMb?: number,
/** 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链) */
wikilink?: boolean,
/** 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口) */
reuseWindow?: boolean,
/** WebDAV 备份 / 同步设置(P2) */
webdav?: WebdavSettings,
/** 新建笔记时是否弹出模板选择(P2) */
showTemplatePicker?: boolean,
/** 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白) */
exportHighlight?: boolean,
/**
* 全局快捷键:新建笔记(空串 = 不注册)。
*
* 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
* 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
*/
newNoteShortcut?: string,
/** 全局快捷键:打开编辑器窗口(空串 = 不注册) */
openEditorShortcut?: string,
/** 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`]) */
recentFiles?: RecentEntry[],
/** 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`]) */
recentFolders?: RecentEntry[],
};
/**
* 引擎连通性自检结果。
*
@@ -1856,6 +2006,8 @@ export type FileDoc = {
large: boolean,
/** 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略) */
lines: number,
/** 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因) */
readonly: boolean,
};
export type FileEntry = {
@@ -2118,7 +2270,7 @@ export type LibraryEntry = {
export type LibraryInfo = {
/** 当前生效的库根绝对路径 */
root: string,
/** 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`) */
/** 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`) */
isCustom: boolean,
/** `.md` 笔记数量(不含目录) */
noteCount: number,
@@ -2133,6 +2285,30 @@ export type LinkEdge = {
to: string,
};
/** 目录列举结果。 */
export type LocalDir = {
/** 规范化之后的目录(`canonicalize` 结果,已去掉 Windows 的 `\\?\` 前缀) */
cwd: string,
/** 父目录;已是盘符根时为 None(前端据此禁用「上一级」) */
parent: string | null,
entries: LocalEntry[],
};
/** 一个本地目录项(回传前端渲染)。 */
export type LocalEntry = {
name: string,
/** 完整路径(本地形态,Windows 下用 `\` 分隔) */
path: string,
/** "dir" | "file" | "other"(符号链接返回**目标**的类型,见模块注释) */
kind: string,
/** 字节数;目录为 0(前端显示为「—」) */
size: number,
/** 修改时间(Unix 毫秒;系统未提供时为 None) */
modifiedAt: number | null,
/** 符号链接的目标(非链接为 None) */
linkTarget: string | null,
};
/** 环境状态(返回前端,设置页「环境检查」面板展示) */
export type MusicEnvStatus = {
/** 系统 Python 版本(如 "3.14.5"),无则 None */
@@ -2348,69 +2524,6 @@ export type NoteSearchQuery = {
limit?: number,
};
/**
* 笔记 / 编辑器设置根结构。
*
* 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
* 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
*/
export type NoteSettings = {
/** 结构版本号 */
version?: number,
/** 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`) */
libraryRoot?: string | null,
/** 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …) */
editorTheme?: string,
/** 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准) */
followAppTheme?: boolean,
/** 编辑器字体族(空串 = 用内置等宽字体栈) */
fontFamily?: string,
/** 字号(px) */
fontSize?: number,
/** 行高倍数 */
lineHeight?: number | null,
/** 是否启用字体连字(ligatures) */
ligatures?: boolean,
/** Tab 宽度(空格数) */
tabSize?: number,
/** 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮) */
livePreview?: boolean,
/** 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S) */
autosaveMs?: number,
/** 默认视图:"wysiwyg" | "source" */
defaultView?: string,
/** 是否显示行号 */
showLineNumbers?: boolean,
/** 是否显示大纲侧栏(P1) */
showOutline?: boolean,
/** 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭) */
autocomplete?: boolean,
/**
* 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
* 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
*/
maxFileSizeMb?: number,
/** 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链) */
wikilink?: boolean,
/** 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口) */
reuseWindow?: boolean,
/** WebDAV 备份 / 同步设置(P2) */
webdav?: WebdavSettings,
/** 新建笔记时是否弹出模板选择(P2) */
showTemplatePicker?: boolean,
/** 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白) */
exportHighlight?: boolean,
/**
* 全局快捷键:新建笔记(空串 = 不注册)。
*
* 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
* 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
*/
newNoteShortcut?: string,
/** 全局快捷键:打开编辑器窗口(空串 = 不注册) */
openEditorShortcut?: string,
};
/** 标签及其笔记数。 */
export type NoteTagCount = {
tag: string,
@@ -2431,6 +2544,122 @@ export type NoteTemplate = {
body: string,
};
/** 回传给前端的待打开目标。 */
export type OpenTargetPayload = {
/** 绝对路径 */
path: string,
/** `"file"` | `"folder"` */
kind: string,
};
/** 一个被修改的文件。 */
export type PathReplaceFileResult = {
path: string,
name: string,
replacements: number,
};
/** 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。 */
export type PathReplaceQuery = {
/** 检索根目录(绝对路径) */
dir: string,
/** 关键词(`regex` 为真时按正则解释) */
pattern: string,
/** 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开) */
replacement: string,
/** 区分大小写(默认关) */
caseSensitive: boolean,
/** 全词匹配 */
wholeWord: boolean,
/** 按正则解释关键词 */
regex: boolean,
/** 替换总数上限(缺省 1000,夹在 1..=5000) */
limit: number | null,
/** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */
fileTypes: string | null,
/** 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) */
skipDirs: string | null,
};
/** 一次「在路径中替换」的结果。 */
export type PathReplaceResult = {
/** 实际被改写的文件(含各自的替换处数) */
files: PathReplaceFileResult[],
filesChanged: number,
replacements: number,
/** 达到上限提前停止:此时**只改了前面一部分文件** */
truncated: boolean,
skipped: PathReplaceSkipped[],
};
/** 被跳过的文件(非 UTF-8 / 写不进去)。 */
export type PathReplaceSkipped = {
path: string,
reason: string,
};
/** 一个文件内的全部命中。 */
export type PathSearchFileHits = {
/** 文件绝对路径 */
path: string,
/** 文件名(结果列表展示) */
name: string,
/** 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分) */
totalInFile: number,
matches: PathSearchMatch[],
};
/** 一处命中(以「行」为单位)。 */
export type PathSearchMatch = {
/** 行号(1 起) */
line: number,
/** 行内字符列(1 起,指向首个匹配) */
column: number,
/** 该行预览(超长时围绕命中开窗,两端以 `…` 标记) */
preview: string,
/** 命中在 `preview` 中的起始字符下标(前端高亮用) */
matchStart: number,
/** 命中在 `preview` 中的结束字符下标(不含) */
matchEnd: number,
};
/** 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。 */
export type PathSearchQuery = {
/** 检索根目录(绝对路径) */
dir: string,
/** 关键词(`regex` 为真时按正则解释) */
pattern: string,
/** 区分大小写(默认关:与 CM6 搜索一致) */
caseSensitive: boolean,
/** 全词匹配 */
wholeWord: boolean,
/** 按正则解释关键词 */
regex: boolean,
/**
* 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 ——
* 超过上限的命中只计数不构建预览,由前端分页展示回传的部分
*/
limit: number | null,
/** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */
fileTypes: string | null,
/** 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单) */
skipDirs: string | null,
};
/** 一次「在路径中查找」的结果。 */
export type PathSearchResult = {
/** 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列) */
files: PathSearchFileHits[],
/** 全树命中行总数(统计完整,不受 `limit` 影响) */
total: number,
/** 全树至少命中一行的文件总数(≥ `files.len()`) */
totalFiles: number,
/** 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`) */
returned: number,
/** `total > returned`:还有命中未回传预览 */
truncated: boolean,
};
/** 划词结果悬浮窗外观(P1 生效)。 */
export type PopupSettings = {
/** 正文字号(逻辑像素) */
@@ -2560,6 +2789,23 @@ export type QuickPanelSettings = {
customCommands?: CustomCommand[],
};
/**
* 最近打开的一个文件 / 文件夹。
*
* `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。
* 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。
*/
export type RecentEntry = {
/** 绝对路径(文件或文件夹) */
path?: string,
/** 显示名(文件名 / 文件夹名) */
name?: string,
/** 最近打开时间(Unix 毫秒) */
openedAt?: number,
/** 该路径当前是否仍存在(读取设置时刷新) */
exists?: boolean,
};
/** 远程配置(§5.1 命令 `remote_get_config` / `remote_set_enabled`)。 */
export type RemoteConfig = {
/** 开关(持久化) */
+24 -15
View File
@@ -27,8 +27,13 @@ export const WINDOWS = {
* 时,webview 仍可正常加载与交互,只是拿不到 IPC)。
*/
dshWeb: 'dsh-web',
/** 笔记独立窗口前缀,实际 label = `${notesWindow}-<n>`(可多开) */
notesWindow: 'notes-window',
/** 编辑器独立窗口前缀,实际 label = `${editorWindow}-<n>`(可多开) */
editorWindow: 'editor-window',
/**
* dsh「启动进度」独立窗口(单例)。
* 服务就绪后由主窗口打开真正的 {@link dshWeb} 窗口并关闭它。
*/
dshWindow: 'dsh-window',
} as const
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
@@ -37,8 +42,12 @@ export const EVENTS = {
trayMenuShow: 'tray-menu-show',
trayMenuStateUpdated: 'tray-menu-state-updated',
trayToggleOsd: 'tray:toggle-osd',
trayNewDownload: 'tray:new-download',
trayOpenSettings: 'tray:open-settings',
/** 托盘「终端」:打开新建终端选择窗口 */
trayOpenTerminal: 'tray:open-terminal',
/** 托盘「dsh」:打开 dsh 独立窗口(未启动时先显示启动进度) */
trayOpenDsh: 'tray:open-dsh',
/** 托盘「编辑器」:打开编辑器独立窗口 */
trayOpenEditor: 'tray:open-editor',
// 剪贴板
clipboardChanged: 'clipboard-changed',
clipboardPopupShow: 'clipboard-popup-show',
@@ -150,19 +159,21 @@ export const EVENTS = {
/** 全局快捷键按下:打开 dsh 独立窗口(无负载) */
dshOpenWindow: 'dsh-open-window',
/** 笔记:设置已保存(无负载)。各窗口据此重读设置,实现跨窗口同步 */
notesSettings: 'notes-settings',
editorSettings: 'editor-settings',
/** 笔记:库内容已变更(新建/保存/重命名/删除/切换库根,无负载) */
notesLibraryChanged: 'notes-library-changed',
/** 笔记:库内文件在应用外被改动(负载见 src/types/notes.ts 的 NoteFileEvent) */
notesFileChanged: 'notes-file-changed',
/** 笔记:WebDAV 同步进度(负载见 src/types/notes.ts 的 SyncProgress) */
notesSyncProgress: 'notes-sync-progress',
editorLibraryChanged: 'editor-library-changed',
/** 笔记:库内文件在应用外被改动(负载见 src/types/editor.ts 的 NoteFileEvent) */
editorFileChanged: 'editor-file-changed',
/** 笔记:WebDAV 同步进度(负载见 src/types/editor.ts 的 SyncProgress) */
editorSyncProgress: 'editor-sync-progress',
/** 笔记:全局快捷键「新建笔记」被按下(无负载;主窗口据此打开新建对话框) */
notesNewNote: 'notes-new-note',
editorNewNote: 'editor-new-note',
/** 笔记:全局快捷键「打开编辑器」被按下(无负载) */
notesOpenEditor: 'notes-open-editor',
editorOpenEditor: 'editor-open-editor',
/** 笔记:需要打开一个磁盘文件(负载 `{ path }`;来自文件关联 / 命令行) */
notesOpenFile: 'notes-open-file',
editorOpenFile: 'editor-open-file',
/** 编辑器:需要打开一个文件夹(负载 `{ path }`;来自资源管理器右键) */
editorOpenFolder: 'editor-open-folder',
} as const
/** localStorage 存储键 */
@@ -188,6 +199,4 @@ export const STORAGE_KEYS = {
monitorOverviewCards: 'thing_monitor_overview_cards',
screenshotHistory: 'thing_screenshot_history',
screenshotPinIndex: 'thing_screenshot_pin_index',
/** 笔记模块:最近打开(`{ relPath, name, at }[]`) */
notesRecent: 'thing_notes_recent',
} as const
+4 -3
View File
@@ -43,13 +43,14 @@ const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Pr
['#terminal-window', '终端独立窗口', () => import('./modules/terminal/TerminalWindow.vue')],
['#new-terminal-window', '新建终端窗口', () => import('./modules/terminal/NewTerminalWindow.vue')],
['#file-window', '文件管理器窗口', () => import('./modules/terminal/FileWindow.vue')],
['#notes-window', '笔记窗口', () => import('./modules/notes/NotesWindow.vue')],
['#editor-window', '编辑器窗口', () => import('./modules/editor/EditorWindow.vue')],
['#dsh-window', 'dsh 启动窗口', () => import('./modules/dsh/DshWindow.vue')],
]
const winHash = window.location.hash
// #screenshot-overlay 带窗口号参数(多屏)、#download-window 带 ?task= 参数,
// #terminal-window 带 /{session_id} 路径参数、#notes-window 带 ?file=(库内笔记)
// #terminal-window 带 /{session_id} 路径参数、#editor-window 带 ?file=(库内笔记)
// 或 ?path=(库外文件)参数,均按前缀匹配;其余精确匹配
const matched = standaloneWindowApps.find(([hash]) => {
if (
@@ -57,7 +58,7 @@ const matched = standaloneWindowApps.find(([hash]) => {
hash === '#screenshot-scroll' ||
hash === '#download-window' ||
hash === '#terminal-window' ||
hash === '#notes-window'
hash === '#editor-window'
)
return winHash.startsWith(hash)
return winHash === hash
+212
View File
@@ -0,0 +1,212 @@
<script setup lang="ts">
/**
* dsh「启动进度」独立窗口(`#dsh-window`)。
*
* # 用途
*
* 托盘菜单点「dsh」时,若服务未启动/未就绪,主窗口会先开这个窗口,再同步拉起
* 服务(`dsh_start`)—— 用户立刻能看到进度,而不是干等一个没有任何反馈的托盘点击。
*
* # 职责边界:本窗口只渲染,不编排
*
* 窗口自己轮询 `dsh_env_status`(本地状态查询,轻量)+ `dsh_log_tail` 渲染进度;
* **何时切换到 Web 界面由主窗口负责**(它持有带令牌地址与 `openWebWindow`):
* 就绪后主窗口打开 `dsh-web` 窗口并关闭本窗口。这样远端页面永远不会挂在本窗口
* 的 label 上(本窗口登记了 capability,不能让远端页面拿到 IPC)。
*
* # 隐藏创建
*
* 窗口由前端**隐藏创建**(见 dshStore.openProgressWindow),本组件应用完主题
* (含 `setBackgroundColor`)再 show —— 否则深色模式下会先闪一个纯白窗口。
*/
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { AlertCircle, Bot, CheckCircle2, Loader2, Minus, X } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import { createLogger } from '@/lib/logger'
import { applyStoredAccent } from '@/lib/theme'
import { STORAGE_KEYS } from '@/lib/constants'
import type { DshEnvStatus, DshServerStatus } from '@/types/dsh'
const logger = createLogger('dsh')
const win = getCurrentWindow()
/** 与 style.css 的 --background 对齐:浅色 #ffffff / 深色 #16161a */
const WINDOW_BG = { light: '#ffffff', dark: '#16161a' }
function readMainTheme(): string {
try {
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
if (raw) return (JSON.parse(raw) as { theme?: string }).theme ?? 'system'
} catch {
/* 设置不可读时按跟随系统处理 */
}
return 'system'
}
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() {
const root = document.documentElement
const theme = readMainTheme()
const isDark = resolveIsDark(theme)
try {
await win.setTheme(theme === 'system' ? null : (theme as 'dark' | 'light'))
} catch {
/* 平台不支持时忽略 */
}
try {
// 底色单独 try:setTheme 失败不该连带跳过底色,否则仍会白底闪一下
await win.setBackgroundColor(isDark ? WINDOW_BG.dark : WINDOW_BG.light)
} catch {
/* 忽略 */
}
root.classList.toggle('dark', isDark)
applyStoredAccent(root, isDark ? 'dark' : 'light', STORAGE_KEYS.appSettings)
}
// ===== 状态 =====
const server = ref<DshServerStatus | null>(null)
const logTail = ref('')
/** 距本次打开已过去的秒数(服务启动通常几秒~几十秒,给个可见的时间参照) */
const elapsed = ref(0)
/** 就绪:已监听 + 已拿到带令牌地址(主窗口据此打开界面) */
const canOpen = computed(() => !!server.value?.ready && !!server.value?.launchUrl)
const failed = computed(() => !!server.value?.error)
/** 阶段文案:按状态逐级推进(就绪由主窗口接手切界面) */
const stageText = computed(() => {
const s = server.value
if (!s) return '读取状态…'
if (s.error) return '启动失败'
if (s.ready && s.launchUrl) return '已就绪,正在打开界面…'
if (s.ready) return '等待访问地址(令牌)…'
if (s.running) return '服务启动中…'
return '准备启动…'
})
const timer = ref<ReturnType<typeof setInterval> | null>(null)
const logTimer = ref<ReturnType<typeof setInterval> | null>(null)
/**
* 状态查询的时间上限(秒)。
*
* 就绪探测最多 60s(Rust `READY_TIMEOUT`),主窗口的等待也以此为准;留点余量后
* 停止查询——否则用户把窗口留在那儿时,会一直以 1Hz 探测 Node 版本。
*/
const MAX_POLL_SECONDS = 75
async function refreshState() {
try {
const env = await invoke<DshEnvStatus>('dsh_env_status')
server.value = env.server
} catch (e) {
logger.error('读取 dsh 状态失败: ' + e)
}
}
async function refreshLog() {
try {
logTail.value = await invoke<string>('dsh_log_tail', { lines: 6 })
} catch {
/* 日志读取失败不影响进度显示 */
}
}
function minimize() {
void win.minimize()
}
function closeWindow() {
void win.close()
}
onMounted(async () => {
await applyTheme()
try {
await win.show()
await win.setFocus()
} catch (e) {
logger.warn(`显示 dsh 启动窗口失败:${String(e)}`)
}
await refreshState()
await refreshLog()
timer.value = setInterval(() => {
elapsed.value += 1
// 到达终态(就绪 / 失败)后停止状态查询:`dsh_env_status` 会探测 Node 版本
// (跑一次 `node --version` 子进程),没必要在窗口留守期间持续消耗。
// 就绪后主窗口会立刻关掉本窗口;失败时停在错误上即可。
if (!canOpen.value && !failed.value && elapsed.value <= MAX_POLL_SECONDS) void refreshState()
}, 1000)
logTimer.value = setInterval(() => {
if (!failed.value) void refreshLog()
}, 1500)
})
onBeforeUnmount(() => {
if (timer.value) clearInterval(timer.value)
if (logTimer.value) clearInterval(logTimer.value)
})
</script>
<template>
<div class="flex h-screen w-screen flex-col overflow-hidden bg-background text-foreground">
<!-- 控制栏:标题(兼拖拽区)+ 关闭 -->
<div class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-1.5">
<div class="flex h-full min-w-0 flex-1 items-center gap-1.5 px-2" data-tauri-drag-region>
<Bot class="pointer-events-none size-3.5 shrink-0 text-muted-foreground" />
<span class="pointer-events-none truncate text-xs font-medium">DeepSeek Harness</span>
</div>
<Button variant="ghost" size="icon-sm" @click="minimize">
<Minus class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
class="hover:!bg-destructive hover:!text-destructive-foreground"
@click="closeWindow"
>
<X class="size-3.5" />
</Button>
</div>
<div class="flex min-h-0 flex-1 flex-col gap-3 px-4 py-4">
<!-- 阶段:图标 + 文案 + 计时 -->
<div class="flex items-center gap-2.5">
<CheckCircle2 v-if="canOpen" class="size-4 shrink-0 text-success" />
<AlertCircle v-else-if="failed" class="size-4 shrink-0 text-danger" />
<Loader2 v-else class="size-4 shrink-0 animate-spin text-primary" />
<span class="text-[13px] font-medium" :class="{ 'text-danger': failed }">{{ stageText }}</span>
<span class="ml-auto text-[11px] tabular-nums text-muted-foreground">{{ elapsed }}s</span>
</div>
<!-- 失败原因:留在眼前,避免用户只看到托盘「没反应」 -->
<div
v-if="server?.error"
class="rounded-md border border-border bg-danger-soft px-3 py-2 text-[12px] text-danger-text"
>
{{ server.error }}
</div>
<!-- 启动输出尾部:给「进度」一个可读的落点 -->
<div class="flex min-h-0 flex-1 flex-col gap-1.5">
<span class="text-[11px] text-muted-foreground">启动输出</span>
<pre
class="min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-all rounded-md border border-border bg-secondary/40 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-fg-secondary"
>{{ logTail || '(暂无输出)' }}</pre>
</div>
<p v-if="canOpen" class="text-[11px] text-muted-foreground">
界面即将在独立窗口中打开,本窗口会自动关闭。
</p>
</div>
</div>
</template>
@@ -2,7 +2,7 @@
/**
* 笔记模块主页面 —— **只做设置与管理,不做编辑**。
*
* 编辑发生在独立窗口(`openNotesWindow()`),本页负责:库状态与入口、库根管理、
* 编辑发生在独立窗口(`openEditorWindow()`),本页负责:库状态与入口、库根管理、
* 编辑器偏好。所有设置**即时生效、无保存按钮**。
*
* 版式遵循 `UI_DESIGN_SYSTEM.md`:
@@ -23,12 +23,14 @@ import {
ExternalLink,
Eye,
FolderOpen,
FolderPlus,
Keyboard,
Library,
NotebookPen,
Palette,
RefreshCw,
Tags
Tags,
Wrench
} from '@lucide/vue'
import { toast } from 'vue-sonner'
import { Tabs, TabsContent } from '@/components/ui/tabs'
@@ -46,34 +48,35 @@ import {
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 { useEditorStore } from '@/stores/editorStore'
import { openEditorWindow } from './openWindow'
import { editorClient } from './editorClient'
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'
import type { ContextMenuStatus, EditorSettings } from '@/types/editor'
const store = useNotesStore()
const store = useEditorStore()
const activeTab = ref('overview')
// Tab 结构(规划 §8-Q5):概览 / 库 / 编辑器 / 同步。
// 「关于」并入概览(模块信息量不足以独占一页),设置项按主题归入对应页。
// Tab 结构(规划 §6.1):概览 / 库 / 编辑器 / 集成。
// 「同步」并入「库」(同步是库的属性);「集成」放文件关联 / 右键菜单 / 单实例。
useModuleTabs(
'notes',
'editor',
activeTab,
[
{ value: 'overview', label: '概览' },
{ value: 'library', label: '库' },
{ value: 'editor', label: '编辑器' },
{ value: 'sync', label: '同步' }
{ value: 'integration', label: '集成' }
],
{ alwaysVisible: true }
)
onMounted(() => {
void store.init()
void loadContextMenu()
})
onBeforeUnmount(() => {
store.disposeListeners()
@@ -98,25 +101,26 @@ watch(
/**
* 冷启动的「用 Thing 打开」:命令行留下的文件路径取到后,直接开一个笔记窗口。
*
* **只在主窗口做**:笔记窗口内部也会渲染本模块(`#notes-window` 是独立入口,
* 不走这里),但它的 hash 里已经带了 `?path=`,由 `NotesWindow` 自己打开 ——
* **只在主窗口做**:笔记窗口内部也会渲染本模块(`#editor-window` 是独立入口,
* 不走这里),但它的 hash 里已经带了 `?path=`,由 `EditorWindow` 自己打开 ——
* 这里再响应一次就会开第二个窗口。
*/
watch(
() => store.pendingOpenPath,
path => {
if (!path || isNotesWindow()) return
void openNotesWindow({ path }).catch(e => toast.error(`打开文件失败:${String(e)}`))
() => store.pendingOpenTarget,
target => {
if (!target || isEditorWindow()) return
const options = target.kind === 'folder' ? { folder: target.path } : { path: target.path }
void openEditorWindow(options).catch(e => toast.error(`打开失败:${String(e)}`))
}
)
/** 当前是否运行在笔记独立窗口里(hash 形如 `#notes-window?...`)。 */
function isNotesWindow(): boolean {
return window.location.hash.startsWith(`#${WINDOWS.notesWindow}`)
/** 当前是否运行在编辑器独立窗口里(hash 形如 `#editor-window?...`)。 */
function isEditorWindow(): boolean {
return window.location.hash.startsWith(`#${WINDOWS.editorWindow}`)
}
// ===== 设置写入(即时生效) =====
function commit(patch: Partial<NoteSettings>): void {
function commit(patch: Partial<EditorSettings>): void {
void store.patchSettings(patch)
}
@@ -126,7 +130,7 @@ function onNumber(
) {
const value = Number((event.target as HTMLInputElement).value)
if (!Number.isFinite(value)) return
commit({ [patchKey]: value } as Partial<NoteSettings>)
commit({ [patchKey]: value } as Partial<EditorSettings>)
}
// ===== 库根 =====
@@ -175,7 +179,7 @@ async function copyRoot(): Promise<void> {
async function openEditor(): Promise<void> {
try {
await openNotesWindow()
await openEditorWindow()
} catch (e) {
toast.error(`打开编辑器失败:${String(e)}`)
}
@@ -190,13 +194,80 @@ async function openExternalFile(): Promise<void> {
title: '打开文件'
})
if (typeof selected !== 'string') return
await notesClient.authorizeFile(selected)
await openNotesWindow({ path: selected })
await editorClient.authorizeFile(selected)
await openEditorWindow({ path: selected })
} catch (e) {
toast.error(`打开文件失败:${String(e)}`)
}
}
/** 在编辑器窗口里打开一个本地文件夹(目录面板)。 */
async function openFolder(): Promise<void> {
try {
const selected = await open({ directory: true, multiple: false, title: '打开文件夹' })
if (typeof selected !== 'string') return
await openEditorWindow({ folder: selected })
} catch (e) {
toast.error(`打开文件夹失败:${String(e)}`)
}
}
/** 打开一个「最近文件」:库内 `.md` 走笔记语义,其余走库外文件语义。 */
async function openRecentFile(entry: { path: string }): Promise<void> {
const root = (store.libraryRoot || '').replace(/[\\/]+$/, '')
const norm = entry.path.replace(/\//g, '\\').toLowerCase()
if (root && norm.startsWith(root.replace(/\//g, '\\').toLowerCase()) && /\.(md|markdown|mdx)$/i.test(entry.path)) {
const rel = entry.path.slice(root.length).replace(/^[\\/]+/, '').replace(/\\/g, '/')
await openEditorWindow({ relPath: rel })
return
}
await openEditorWindow({ path: entry.path })
}
async function openRecentFolder(entry: { path: string }): Promise<void> {
await openEditorWindow({ folder: entry.path })
}
// ===== 系统集成(P4-4) =====
const contextMenu = ref<ContextMenuStatus | null>(null)
const contextBusy = ref(false)
async function loadContextMenu(): Promise<void> {
try {
contextMenu.value = await editorClient.contextMenuStatus()
} catch (e) {
toast.error(`读取集成状态失败:${String(e)}`)
}
}
async function registerContextMenu(): Promise<void> {
contextBusy.value = true
try {
contextMenu.value = await editorClient.registerContextMenu()
toast.success('已注册右键菜单')
} catch (e) {
toast.error(`注册失败:${String(e)}`)
} finally {
contextBusy.value = false
}
}
async function unregisterContextMenu(): Promise<void> {
contextBusy.value = true
try {
contextMenu.value = await editorClient.unregisterContextMenu()
toast.success('已卸载右键菜单')
} catch (e) {
toast.error(`卸载失败:${String(e)}`)
} finally {
contextBusy.value = false
}
}
watch(activeTab, tab => {
if (tab === 'integration') void loadContextMenu()
})
const rebuilding = ref(false)
async function rebuildIndex(): Promise<void> {
@@ -216,7 +287,7 @@ async function rebuildIndex(): Promise<void> {
async function openDailyNote(): Promise<void> {
try {
await store.openDailyNote()
await openNotesWindow({ relPath: store.currentRelPath })
await openEditorWindow({ relPath: store.currentRelPath })
} catch (e) {
toast.error(`打开日记失败:${String(e)}`)
}
@@ -290,6 +361,9 @@ const indexSummary = computed(() => {
<Button size="sm" variant="outline" @click="openExternalFile">
<FolderOpen class="size-3.5" />打开文件
</Button>
<Button size="sm" variant="outline" @click="openFolder">
<FolderPlus class="size-3.5" />打开文件夹
</Button>
<Button size="sm" @click="openEditor">
<NotebookPen class="size-3.5" />打开编辑器
</Button>
@@ -297,7 +371,7 @@ const indexSummary = computed(() => {
</CardContent>
</Card>
<!-- 最近打开 -->
<!-- 最近打开:文件与文件夹两份列表(与笔记库解耦) -->
<Card class="!gap-2 !py-4">
<CardHeader class="!px-4">
<CardTitle class="flex items-center gap-2 text-base">
@@ -307,28 +381,58 @@ const indexSummary = computed(() => {
</CardHeader>
<CardContent class="!px-4">
<StateBlock
v-if="!store.recent.length"
v-if="!store.recentFiles.length && !store.recentFolders.length"
variant="empty"
title="还没有打开过笔记"
description="点上方「打开编辑器」新建或打开一篇笔记"
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 v-else class="flex flex-col gap-4">
<div v-if="store.recentFiles.length" class="flex flex-col">
<p class="pb-1 text-[11px] font-medium text-muted-foreground">最近文件</p>
<div class="flex flex-col divide-y divide-divider">
<button
v-for="item in store.recentFiles"
:key="item.path"
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"
:class="item.exists ? '' : 'opacity-50'"
@click="openRecentFile(item)"
>
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
<span class="truncate text-[13px] text-foreground">
{{ item.name }}
<span v-if="!item.exists" class="text-[11px] text-muted-foreground">(已失效)</span>
</span>
<span class="truncate text-xs text-muted-foreground">{{ item.path }}</span>
</span>
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
</button>
</div>
</div>
<div v-if="store.recentFolders.length" class="flex flex-col">
<p class="pb-1 text-[11px] font-medium text-muted-foreground">最近文件夹</p>
<div class="flex flex-col divide-y divide-divider">
<button
v-for="item in store.recentFolders"
:key="item.path"
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"
:class="item.exists ? '' : 'opacity-50'"
@click="openRecentFolder(item)"
>
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
<span class="truncate text-[13px] text-foreground">
{{ item.name }}
<span v-if="!item.exists" class="text-[11px] text-muted-foreground">(已失效)</span>
</span>
<span class="truncate text-xs text-muted-foreground">{{ item.path }}</span>
</span>
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
</button>
</div>
</div>
</div>
</CardContent>
</Card>
@@ -393,7 +497,7 @@ const indexSummary = computed(() => {
</CardHeader>
<CardContent class="!px-4">
<p class="pb-2 text-xs text-muted-foreground">
全文检索与标签依赖一份 SQLite 索引(存放在库内 <code class="font-mono">.notes/</code>)。
全文检索与标签依赖一份 SQLite 索引(存放在库内 <code class="font-mono">.editor/</code>)。
它只是加速层:删掉也能从 Markdown 文件完整重建,不影响笔记本身。
</p>
<div class="flex flex-col divide-y divide-divider">
@@ -441,6 +545,9 @@ const indexSummary = computed(() => {
<!-- 导入 / 导出(P2) -->
<ImportExportPanel />
<!-- WebDAV 备份 / 同步(原「同步」页,并入库页) -->
<WebdavPanel />
</div>
</TabsContent>
@@ -523,7 +630,7 @@ const indexSummary = computed(() => {
<SettingRow
label="显示大纲"
description="在编辑器侧栏显示标题树(Ctrl+Shift+L 可临时切换)"
description="在编辑区右侧抽屉显示标题树(Ctrl+Shift+O 可临时切换)"
>
<Switch
:model-value="store.settings.showOutline"
@@ -675,10 +782,98 @@ const indexSummary = computed(() => {
</div>
</TabsContent>
<!-- ===== 同步(WebDAV) ===== -->
<TabsContent value="sync" class="tab-animate">
<!-- ===== 集成(系统集成) ===== -->
<TabsContent value="integration" class="tab-animate">
<div class="flex flex-col gap-4 pb-4">
<WebdavPanel />
<Card class="!gap-2 !py-4">
<CardHeader class="!px-4">
<CardTitle class="flex items-center gap-2 text-base">
<Wrench class="size-4 text-primary" />
系统集成
</CardTitle>
</CardHeader>
<CardContent class="!px-4">
<p class="pb-2 text-xs text-muted-foreground">
让编辑器融入系统:双击文档打开、资源管理器右键、全局快捷键。所有注册都走用户级
(免管理员);开发模式下 exe 路径不稳定,因此<b>右键菜单默认不自动注册</b>。
</p>
<div class="flex flex-col divide-y divide-divider">
<SettingRow
label="文件关联"
description="双击 .md / .markdown / .mdx 用本应用打开(由安装器写入)"
>
<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="应用已运行时再次打开文件会转交给既有实例,不新起进程"
>
<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="
contextMenu?.registered
? '已注册「用 Thing 编辑器打开」(文件 / 文件夹 / 目录背景)'
: '未注册;注册后可在资源管理器右键直接打开'
"
>
<div class="flex items-center gap-2">
<span
v-if="contextMenu?.registered"
class="flex items-center gap-1.5 text-xs text-success"
>
<span class="size-2 rounded-full bg-success" />已注册
</span>
<Button
v-if="!contextMenu?.registered"
size="sm"
variant="outline"
:disabled="contextBusy"
@click="registerContextMenu"
>
注册
</Button>
<Button
v-else
size="sm"
variant="outline"
:disabled="contextBusy"
@click="unregisterContextMenu"
>
卸载
</Button>
</div>
</SettingRow>
<SettingRow
label="可执行文件路径"
:description="contextMenu?.exePath || '—'"
>
<span
v-if="contextMenu?.isDev"
class="rounded-sm bg-warning-soft px-1.5 py-0.5 text-[10px] text-warning"
>
开发模式
</span>
<span v-else class="text-xs text-muted-foreground">安装目录</span>
</SettingRow>
<SettingRow
label="全局快捷键"
description="打开编辑器 / 新建笔记的键位在「编辑器」页配置"
>
<span class="text-xs text-muted-foreground">见「编辑器」页</span>
</SettingRow>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
+1000
View File
@@ -0,0 +1,1000 @@
<script setup lang="ts">
/**
* 编辑器独立窗口根组件(`#editor-window`)。
*
* # 为什么是独立窗口
*
* 主模块页只做设置与管理;真正的编辑发生在这里 —— 可多开、可拖到副屏,
* 编辑体验接近一个独立应用(与终端 / 下载 / 翻译窗口同一范式)。
*
* # 生命周期要点
*
* - 窗口由 `openWindow.ts` **隐藏创建**,本组件 `applyTheme` 之后才 `show`
* (否则深色模式下会先闪一下纯白窗口);
* - 自带一份 Pinia(`main.ts` 里为独立窗口注入),store 通过 IPC 与 Rust 对齐;
* - 监听 `editor-settings` / `editor-library-changed` / `editor-file-changed`
* 实现与主窗口及外部编辑器的实时同步。
*
* # P1 新增的三种「异步危险」
*
* 1. **外部改动**:库文件在别的编辑器里被改了,而我们这边有未保存内容 —— 不能
* 静默重载(会丢掉用户刚敲的字),弹出横幅让用户选;
* 2. **打开库外文件**:路径来自系统对话框,必须先 `authorize` 才能写回;
* 3. **大文件**:超过阈值时关掉 Live Preview / 折叠 / 补全(降级在 `core.ts`,
* 这里只负责把 `large` 标记和提示露出来)。
*/
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Effect, EffectState, getCurrentWindow } from '@tauri-apps/api/window'
import { open, save } from '@tauri-apps/plugin-dialog'
import { AlertTriangle, History, 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 {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { ConfirmDialog, StateBlock } from '@/components/common'
import { STORAGE_KEYS } from '@/lib/constants'
import { applyStoredAccent } from '@/lib/theme'
import { createLogger } from '@/lib/logger'
import { useEditorStore } from '@/stores/editorStore'
import type { PathReplaceResult } from '@/types/editor'
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 DrawerPanel from './components/DrawerPanel.vue'
import EditorTabs from './components/EditorTabs.vue'
import EditorSearch, { type SearchScope } from './components/EditorSearch.vue'
import SearchResultsPanel from './components/SearchResultsPanel.vue'
import { useEditorSearchStore } from '@/stores/editorSearchStore'
import type { Command, EditorView } from '@codemirror/view'
const logger = createLogger('editor')
const win = getCurrentWindow()
const store = useEditorStore()
const searchStore = useEditorSearchStore()
const isDark = ref(false)
const sidebarVisible = ref(true)
const hostRef = ref<InstanceType<typeof EditorHost> | null>(null)
const sidebarRef = ref<InstanceType<typeof LibrarySidebar> | null>(null)
const quickOpen = ref(false)
const cursorColumn = ref(1)
// ===== 统一搜索器(P4-6):一个输入区覆盖「当前文件 / 当前目录 / 笔记库」 =====
const searchOpen = ref(false)
const searchScope = ref<SearchScope>('file')
/** 右侧抽屉模式(`null` = 关闭):大纲 / 双链 / 图谱 */
const drawerMode = ref<'outline' | 'links' | 'graph' | null>(null)
// ===== 主题与窗口效果(与主应用同步) =====
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)
/** 关闭标签确认 */
const tabCloseConfirmOpen = ref(false)
const pendingCloseTabId = ref('')
/** 关闭临时草稿的三选一(保存到别处 / 删除 / 取消) */
const scratchCloseOpen = ref(false)
/** 请求关闭某个标签(脏数据时弹确认;临时草稿则问「保存到别处 / 删除」)。 */
function requestCloseTab(id: string): void {
const tab = store.tabs.find(t => t.id === id)
if (!tab) return
// 草稿优先:它的收尾是「存到别处 or 删掉」,与普通的「未保存改动」不是一回事
if (store.isScratchTab(id)) {
pendingCloseTabId.value = id
scratchCloseOpen.value = true
return
}
const dirty = id === store.activeTabId ? store.dirty : tab.dirty
if (dirty) {
pendingCloseTabId.value = id
tabCloseConfirmOpen.value = true
return
}
store.closeTab(id)
}
/**
* 草稿关闭三选一:保存到别处 / 删除 / 取消。
*
* 「保存」走系统「另存为」对话框(`save()`),落盘后原草稿一并删除 —— 内容已经在新
* 位置了;因为是**复制到用户指定路径**,这也顺带给了草稿一个「正经身份」,此后它不再
* 被认作草稿(判据是路径)。
*/
async function saveScratchAndClose(): Promise<void> {
const id = pendingCloseTabId.value
const tab = store.tabs.find(t => t.id === id)
scratchCloseOpen.value = false
if (!tab) return
store.activateTab(id)
const suggested = store.fileDoc?.name ?? '草稿.txt'
try {
const target = await save({
title: '保存草稿到…',
defaultPath: suggested,
filters: [
{ name: '文本文件', extensions: ['txt'] },
{ name: '所有文件', extensions: ['*'] }
]
})
if (typeof target !== 'string') {
// 用户在系统对话框里取消了:当作没点过,草稿与标签都留着
return
}
await store.saveScratchAs(target)
store.closeTab(id)
toast.success('草稿已保存')
} catch (e) {
toast.error(`保存失败:${String(e)}`)
}
}
/** 草稿关闭:删除临时文件并关掉标签。 */
async function discardScratchAndClose(): Promise<void> {
const id = pendingCloseTabId.value
scratchCloseOpen.value = false
if (!id) return
store.activateTab(id)
try {
await store.discardScratch()
} finally {
store.closeTab(id)
}
}
/** 确认关闭脏标签:先切过去保存,再关闭。 */
async function confirmCloseTab(): Promise<void> {
const id = pendingCloseTabId.value
tabCloseConfirmOpen.value = false
store.activateTab(id)
try {
await store.saveCurrent()
} catch {
/* 保存失败仍关闭(用户已确认) */
}
store.closeTab(id)
}
async function doClose(): Promise<void> {
if (store.anyDirty) {
closeConfirmOpen.value = true
return
}
await forceClose()
}
async function forceClose(): Promise<void> {
const original = store.activeTabId
// 逐个标签切换并保存(保存只作用于活动文档)
for (const tab of [...store.tabs]) {
store.activateTab(tab.id)
try {
await store.saveCurrent()
} catch {
/* 保存失败不阻塞关闭;脏数据仍在编辑器里 */
}
}
// 上面的循环把活动标签挪到了最后一个 —— 复原成用户关闭时正在看的那一篇,
// 会话里的「活动项」才与用户所见一致
if (original) store.activateTab(original)
// 关窗前记录会话(下次无目标打开时恢复)
store.saveSession()
win.close().catch(() => undefined)
}
/**
* 标签集合一变就落一次会话(防抖 300ms)。
*
* 只在关窗时写是不够的:标题栏的关闭按钮走 `forceClose` 会写,但 Alt+F4 / 任务栏
* 关闭不走前端流程,`onBeforeUnmount` 在 WebView 被销毁时也不保证执行 —— 会话就是这么
* 丢的。持续写把这个缺口堵上。
*
* 依赖的是「标签形态」而不是整个 store:光标移动不会触发写盘,光标行只在写入的那一刻
* 取当前值(恢复时是最佳努力,不追求逐次精确)。
*/
const sessionShape = computed(() =>
[store.activeTabId, ...store.tabs.map(t => `${t.kind}|${t.relPath}|${t.path}`)].join('\u0000')
)
let sessionTimer: ReturnType<typeof setTimeout> | null = null
watch(sessionShape, () => {
if (sessionTimer) clearTimeout(sessionTimer)
sessionTimer = setTimeout(() => {
sessionTimer = null
store.saveSession()
}, 300)
})
// ===== 编辑器命令转发 =====
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()
// 成功不弹提示(项目约定:无错误即无声)—— Ctrl+S 是高频动作,toast 反而打扰
} catch (e) {
toast.error(`保存失败:${String(e)}`)
}
}
function onCursorMoved(line: number, column: number): void {
store.setCursorLine(line)
cursorColumn.value = column
}
/** 顶部导航:切侧栏视图(并确保侧栏可见)。 */
function onNav(view: 'library' | 'directory' | 'recent'): void {
sidebarVisible.value = true
store.setSideView(view)
}
// ===== 统一搜索器 =====
/** 取当前 CM6 视图(未打开文档时为 null)。 */
function getEditorView(): EditorView | null {
return hostRef.value?.getView() ?? null
}
/** 从路径取所在目录(同时兼容 `\` 与 `/`)。 */
function dirNameOf(path: string): string {
const index = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
return index > 0 ? path.slice(0, index) : ''
}
/**
* 「当前目录」的检索根。
*
* 优先用侧栏已打开的目录;没有就用**当前文件所在目录** —— 用户在编辑某个文件时
* 想「在这个文件附近找一下」,这是最符合直觉的默认。
*/
const searchDir = computed(() => {
if (store.dirListing?.cwd) return store.dirListing.cwd
if (store.kind === 'file' && store.fileDoc?.path) return dirNameOf(store.fileDoc.path)
if (store.kind === 'note' && store.currentRelPath) {
return dirNameOf(store.noteAbsPath(store.currentRelPath))
}
return ''
})
const libraryPath = computed(() => store.info?.root ?? '')
function openSearch(scope: SearchScope = 'file'): void {
searchScope.value = scope
searchOpen.value = true
}
/** 结果点击:打开文件并跳到那一行(检索期间文件可能已被改动,由 jumpToLine 夹取)。 */
async function onSearchOpenFile(payload: {
path: string
line: number
column: number
}): Promise<void> {
try {
await store.openDoc(payload.path)
} catch (e) {
toast.error(`打开失败:${String(e)}`)
return
}
await nextTick()
hostRef.value?.jumpToLine(payload.line, payload.column)
}
/**
* 新建临时草稿文件(工具条的「新建临时文件」)。
*
* 文件落在 `{app_data_dir}/editor/scratch/`,**不随应用退出删除** —— 只有用户关闭这个
* 文件时才会被问「保存到别处 / 删除」(见 `requestCloseTab`)。
*/
async function doNewScratch(): Promise<void> {
try {
await store.newScratchFile()
} catch (e) {
toast.error(`新建临时文件失败:${String(e)}`)
}
}
/**
* 目录 / 库的批量替换完成:磁盘上一批文件已被改写,当前文档可能就是其中之一。
*
* 走 `reloadAfterExternal`:没有未保存改动就直接重载;有改动只挂 `externalChange`
* 提示,绝不静默丢掉用户正在写的内容(取舍见 store 里的注释)。库内文件另外还有
* 文件监听事件负责刷新侧栏,这里只管当前文档。
*/
async function onPathReplaced(result: PathReplaceResult): Promise<void> {
await store.reloadAfterExternal()
const scope = `${result.replacements} 处 / ${result.filesChanged} 个文件`
if (result.skipped.length) {
// 跳过的原因(编码装不下替换内容 / 写入失败 / 编码无法字节级还原)逐个记日志:
// toast 只报数量,具体到哪个文件为什么跳过看日志更合适
logger.warn(
`目录替换跳过 ${result.skipped.length} 个文件:` +
result.skipped.map(s => `${s.path}(${s.reason})`).join(';')
)
toast.warning(`已替换 ${scope},${result.skipped.length} 个文件被跳过(原因见日志)`)
} else if (result.truncated) {
toast.warning(`已替换 ${scope}(达到上限,未处理完)`)
} else {
toast.success(`已替换 ${scope}`)
}
}
/**
* 点击 `[[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 === 'w') {
// 关闭当前标签(Ctrl+W)
event.preventDefault()
if (store.activeTabId) requestCloseTab(store.activeTabId)
} else if (key === 'tab') {
// 文档间切换(Ctrl+Tab / Ctrl+Shift+Tab)
event.preventDefault()
store.cycleTab(event.shiftKey ? -1 : 1)
} else if (key === 'p' && !event.shiftKey) {
event.preventDefault()
quickOpen.value = true
} else if (key === 'o' && !event.shiftKey) {
event.preventDefault()
void doOpenFile()
} else if (key === 'f') {
// Ctrl+F = 当前文件;Ctrl+Shift+F = 在路径中查找(有目录用目录,否则用笔记库)
event.preventDefault()
openSearch(event.shiftKey ? (searchDir.value ? 'dir' : 'library') : 'file')
} else if (key === 'm' && event.shiftKey) {
event.preventDefault()
store.setViewMode(store.viewMode === 'wysiwyg' ? 'source' : 'wysiwyg')
} else if (key === 'o' && event.shiftKey) {
// 切换右侧抽屉:大纲
event.preventDefault()
drawerMode.value = drawerMode.value === 'outline' ? null : 'outline'
} else if (key === 'b' && event.shiftKey) {
// 切换右侧抽屉:双链
event.preventDefault()
drawerMode.value = drawerMode.value === 'links' ? null : 'links'
} else if (key === 'g' && event.shiftKey) {
// 切换右侧抽屉:双链图谱
event.preventDefault()
drawerMode.value = drawerMode.value === 'graph' ? null : 'graph'
} else if (key === 'n' && event.shiftKey) {
// 与全局快捷键同义:窗口内有焦点时在本窗口直接开对话框,不必绕 Rust 一圈
event.preventDefault()
sidebarVisible.value = true
sidebarRef.value?.showNewNote()
}
}
/** 从 hash 查询串解析初始要打开的文档(`file` = 库内笔记,`path` = 库外文件,`folder` = 本地目录)。 */
function initialTarget(): { relPath: string; path: string; folder: string } {
const hash = window.location.hash
const queryIndex = hash.indexOf('?')
if (queryIndex < 0) return { relPath: '', path: '', folder: '' }
const params = new URLSearchParams(hash.slice(queryIndex + 1))
return {
relPath: params.get('file') ?? '',
path: params.get('path') ?? '',
folder: params.get('folder') ?? ''
}
}
onMounted(async () => {
darkMedia.addEventListener('change', onThemeChange)
window.addEventListener('storage', onStorageChange)
window.addEventListener('keydown', onKeydown, true)
// 检索历史与面板高度来自 localStorage:尽早读取,状态栏按钮与结果面板都要用
searchStore.init()
// 主题 → 显示(窗口是隐藏创建的,这一步之后用户才第一次看到它)
await applyTheme()
try {
await win.show()
await win.setFocus()
} catch (e) {
logger.warn(`显示笔记窗口失败:${String(e)}`)
}
await store.init()
store.setViewMode(store.settings.defaultView === 'source' ? 'source' : 'wysiwyg')
const { relPath: targetRel, path: targetPath, folder: targetFolder } = initialTarget()
if (targetRel) {
await store.openNote(targetRel)
} else if (targetPath) {
try {
await store.openFile(targetPath)
} catch (e) {
toast.error(`打开文件失败:${String(e)}`)
}
} else if (targetFolder) {
sidebarVisible.value = true
sidebarRef.value?.showDirectory()
await store.openFolder(targetFolder).catch(e => toast.error(`打开文件夹失败:${String(e)}`))
} else if (store.hasSession()) {
// 无目标:恢复上次会话(打开的文档 + 光标位置)
await store.restoreSession()
} else if (store.recentFiles.length) {
await store.openDoc(store.recentFiles[0]!.path).catch(() => undefined)
}
})
onBeforeUnmount(() => {
darkMedia.removeEventListener('change', onThemeChange)
window.removeEventListener('storage', onStorageChange)
window.removeEventListener('keydown', onKeydown, true)
if (sessionTimer) {
clearTimeout(sessionTimer)
sessionTimer = null
}
store.saveSession()
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'
})
/** 状态栏可切换的编码(值与 `terminal::encoding::normalize` 的规范形态一致)。 */
const ENCODING_OPTIONS = [
{ value: 'utf-8', label: 'UTF-8' },
{ value: 'utf-8-bom', label: 'UTF-8 BOM' },
{ value: 'gb18030', label: 'GB18030' },
{ value: 'gbk', label: 'GBK' },
{ value: 'big5', label: 'Big5' },
{ value: 'shift_jis', label: 'Shift_JIS' },
{ value: 'euc-kr', label: 'EUC-KR' },
{ value: 'latin1', label: 'Latin-1' }
]
// ===== 切换编码(§5.3:有未保存改动时三选一) =====
const encodingDialogOpen = ref(false)
const pendingEncoding = ref('')
/**
* 请求把当前文件按新编码重新解释。
*
* 语义是「换一种方式解释磁盘字节」,因此会从磁盘重新解码并整篇替换内容 ——
* 有未保存改动时必须先让用户选:丢弃 / 先保存 / 取消。
*/
function requestEncoding(encoding: string): void {
if (store.kind !== 'file' || !store.fileDoc) return
if (encoding === store.fileDoc.encoding) return
if (store.dirty) {
pendingEncoding.value = encoding
encodingDialogOpen.value = true
return
}
void store.redecode(encoding).catch(e => toast.error(`切换编码失败:${String(e)}`))
}
async function discardAndRedecode(): Promise<void> {
const encoding = pendingEncoding.value
encodingDialogOpen.value = false
try {
await store.redecode(encoding)
} catch (e) {
toast.error(`切换编码失败:${String(e)}`)
}
}
async function saveThenRedecode(): Promise<void> {
const encoding = pendingEncoding.value
encodingDialogOpen.value = false
try {
// 先按旧编码落盘(用户能立刻看出旧编码是否选错),再按新编码读回
await store.saveCurrent()
await store.redecode(encoding)
} catch (e) {
toast.error(`切换编码失败:${String(e)}`)
}
}
</script>
<template>
<div class="editor-window relative 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">
<!--
这里**不要**再挂 `@mousedown="startDrag"`:`data-tauri-drag-region` 本身已处理
「按住拖动 + 双击最大化/还原」,再手动调一次 `startDragging()` 会让第一次按下
就进入拖动模式,双击的第二下落进拖动里 —— 表现就是「抽搐一下」而不是最大化。
(终端 / 文件窗口同样只靠这个属性。)
-->
<div
class="flex h-full min-w-0 flex-1 items-center gap-2 pl-1"
data-tauri-drag-region
>
<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.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="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>
<!-- 主体:侧栏自导航行起贯通到底;导航行 / 标签栏 / 编辑器同处右侧「编辑列」 -->
<div class="flex min-h-0 flex-1">
<LibrarySidebar v-if="sidebarVisible" ref="sidebarRef" @open="store.openNote($event)" />
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
<!-- 导航行:快捷图标操作行 -->
<EditorToolbar
:apply="applyCommand"
:view-mode="store.viewMode"
:dirty="store.dirty"
:saving="store.saving"
:sidebar-visible="sidebarVisible"
@update:view-mode="store.setViewMode($event)"
@save="doSave"
@open-file="doOpenFile"
@new-file="doNewScratch"
@quick-open="quickOpen = true"
@toggle-sidebar="sidebarVisible = !sidebarVisible"
@nav="onNav"
@open-search="openSearch(searchDir ? 'dir' : 'library')"
/>
<!-- 文档标签栏(多文档) -->
<EditorTabs v-if="store.tabs.length" @close="requestCloseTab" />
<!-- 外部改动提示(有未保存改动时才会出现) -->
<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>
<!-- 统一搜索栏:横跨编辑列宽度,压在内容上方(IDEA 的 Find 栏位置) -->
<EditorSearch
v-model:open="searchOpen"
v-model:scope="searchScope"
:dir-path="searchDir"
:library-path="libraryPath"
:get-view="getEditorView"
@open-file="onSearchOpenFile"
@replaced="onPathReplaced"
/>
<main class="relative 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="store.viewMode === 'wysiwyg'"
@cursor-moved="onCursorMoved"
@wikilink="onWikilink"
/>
</main>
<!-- 目录 / 库检索结果面板:编辑列底部(IDE 的「Find in Path」工具窗位置) -->
<SearchResultsPanel @open-file="onSearchOpenFile" />
</div>
<!-- 右侧抽屉:大纲 / 双链(描述当前文档,而非「去哪找文件」) -->
<DrawerPanel
v-if="drawerMode"
:mode="drawerMode"
:cursor-line="store.cursorLine"
@update:mode="drawerMode = $event"
@close="drawerMode = null"
@jump="hostRef?.jumpTo($event)"
@open="store.openNote($event)"
/>
</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">行 {{ store.cursorLine }} : {{ cursorColumn }}</span>
<span v-if="store.hasDocument">语法:{{ store.languageLabel }}</span>
<span
v-if="store.fileDoc?.readonly"
class="rounded-sm bg-warning-soft px-1.5 py-0.5 text-[10px] text-warning"
>
只读
</span>
<template v-if="store.kind === 'file'">
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button
type="button"
class="rounded-sm px-1.5 py-0.5 text-[10px] uppercase transition-colors hover:bg-hover"
title="切换编码(重新解释磁盘字节)"
>
{{ encodingLabel }}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" class="w-44">
<DropdownMenuLabel>编码</DropdownMenuLabel>
<DropdownMenuItem
v-for="opt in ENCODING_OPTIONS"
:key="opt.value"
@click="requestEncoding(opt.value)"
>
{{ opt.label }}
<span
v-if="store.fileDoc?.encoding === opt.value"
class="ml-auto text-[10px] text-muted-foreground"
>
当前
</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button
type="button"
class="rounded-sm px-1.5 py-0.5 text-[10px] transition-colors hover:bg-hover"
title="切换换行(只影响下次保存)"
>
{{ eolLabel }}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" class="w-32">
<DropdownMenuLabel>换行</DropdownMenuLabel>
<DropdownMenuItem @click="store.setEol('lf')">
LF
<span v-if="store.fileDoc?.eol !== 'crlf'" class="ml-auto text-[10px] text-muted-foreground">当前</span>
</DropdownMenuItem>
<DropdownMenuItem @click="store.setEol('crlf')">
CRLF
<span v-if="store.fileDoc?.eol === 'crlf'" class="ml-auto text-[10px] text-muted-foreground">当前</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</template>
<!--
目录检索历史:点开底部结果面板(与编码 / 换行同属「状态栏可操作项」分组)。
始终可见而非「有历史才出现」—— 它是结果面板的唯一入口,藏起来用户就找不到
「上次搜了什么」了;没有历史时点开会看到空态说明。
-->
<button
type="button"
class="flex shrink-0 items-center gap-1 rounded-sm px-1.5 py-0.5 transition-colors duration-150 hover:bg-hover hover:text-foreground"
:class="searchStore.panelOpen && 'bg-active text-foreground'"
:title="
searchStore.records.length
? `目录检索历史(${searchStore.records.length} 条)—— 点击开关结果面板`
: '目录检索历史 —— 还没有记录,去搜索栏选「目录」范围搜一次'
"
@click="searchStore.togglePanel()"
>
<History class="size-3" />
<span>检索历史</span>
<span v-if="searchStore.records.length" class="tabular-nums">{{ searchStore.records.length }}</span>
</button>
<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"
/>
<!-- 关闭标签确认 -->
<ConfirmDialog
v-model:open="tabCloseConfirmOpen"
title="该标签有未保存的改动"
description="关闭标签会丢失这些改动(选择「保存并关闭」会先保存再关闭)。"
confirm-text="保存并关闭"
@confirm="confirmCloseTab"
/>
<!--
关闭临时草稿:三选一(保存到别处 / 删除 / 取消)。
不用 ConfirmDialog —— 它是「确认 / 取消」两键,而这里必须给出第三条明确出路,
否则用户只能在「丢掉草稿」与「不关标签」之间二选一。
-->
<Dialog :open="scratchCloseOpen" @update:open="scratchCloseOpen = $event">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>关闭临时文件</DialogTitle>
<DialogDescription>
这是一个临时草稿文件,存放在应用数据目录。「保存到别处」会把它另存到你指定的
路径(原临时文件随即删除);「删除」则直接丢弃。
</DialogDescription>
</DialogHeader>
<DialogFooter class="gap-2">
<Button variant="outline" @click="scratchCloseOpen = false">取消</Button>
<Button variant="destructive" @click="discardScratchAndClose">删除</Button>
<Button @click="saveScratchAndClose">保存到别处…</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<!-- 切换编码:有未保存改动时三选一(§5.3) -->
<Dialog :open="encodingDialogOpen" @update:open="encodingDialogOpen = $event">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>有未保存的改动</DialogTitle>
</DialogHeader>
<p class="text-xs leading-relaxed text-muted-foreground">
切换编码会以「{{ pendingEncoding }}」重新解释磁盘字节并整篇替换编辑器内容。
当前有未保存的改动,请选择如何处理:
</p>
<DialogFooter class="flex-col gap-2 sm:flex-col sm:space-x-0">
<Button class="w-full" @click="discardAndRedecode">
丢弃我的改动并按新编码重读
</Button>
<Button variant="outline" class="w-full" @click="saveThenRedecode">
先按旧编码保存,再按新编码重读
</Button>
<Button variant="ghost" class="w-full" @click="encodingDialogOpen = false">
取消
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Toaster />
</div>
</template>
<style scoped>
/* 窗口根容器:mica/acrylic 下透明,普通模式用不透明底色(--popup-bg 由 applyTheme 写入) */
.editor-window {
background: var(--popup-bg, var(--background));
}
</style>
@@ -5,7 +5,7 @@
* # 数据从哪来
*
* 全部来自 SQLite 索引的 `links` 表(写入索引时已把 `[[名字]]` 按 Obsidian 语义
* 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `notes_backlinks`
* 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `editor_backlinks`
* 调用就把两侧都取回。
*
* # 未解析链接为什么值得显示
@@ -18,9 +18,9 @@ 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'
import { useEditorStore } from '@/stores/editorStore'
import { editorClient } from '../editorClient'
import type { NoteBacklinks, NoteLink } from '@/types/editor'
const props = defineProps<{
/** 当前笔记的库内相对路径(空串 = 没有笔记,面板显示空态) */
@@ -34,7 +34,7 @@ const emit = defineEmits<{
create: [name: string]
}>()
const store = useNotesStore()
const store = useEditorStore()
const data = ref<NoteBacklinks | null>(null)
const loading = ref(false)
@@ -58,7 +58,7 @@ async function load(): Promise<void> {
}
loading.value = true
try {
data.value = await notesClient.backlinks(props.relPath)
data.value = await editorClient.backlinks(props.relPath)
} catch (e) {
// 索引还没建立时这里会失败:不是错误,只是「暂时没有数据」
data.value = null
@@ -0,0 +1,823 @@
<script setup lang="ts">
/**
* 本地目录面板(P3-5 / P5-2):以**懒加载文件树**浏览并操作用户真实文件系统。
*
* 与「笔记库」面板的本质区别:
* - 库是**沙箱**(根目录内、相对路径、走索引);目录是**看盘**(任意路径、
* 绝对路径、不进索引、不做全文检索);
* - 树是**懒加载**的:根 = 打开的文件夹(`store.dirListing`),子目录在展开时才经
* `editor_read_dir` 拉一层并缓存 —— 大目录不再一次全量列举,展开哪层读哪层。
*
* 所有写操作都是**显式动作**,且删除一律走系统回收站(Rust 侧 `editor_delete_path`)。
*
* # 多选与拖拽(P5-2)
*
* 单击保持「进目录(展开/收起)/ 打开文件」;`Ctrl/Cmd+单击` 切换选中、`Shift+单击`
* 范围选中。选中非空时底部出现批量操作条(批量重命名 / 删除所选)。行可拖拽到
* 文件夹行完成移动。
*
* # 结构性操作后的刷新策略
*
* 新建 / 重命名 / 删除 / 移动都会让**已缓存的路径**失真 —— 统一走 `invalidate()`:
* 清空子层缓存 → 重读根 → 并行重读所有已展开目录。展开的目录通常只有几个,代价可忽略;
* 换来的是「缓存里的路径永远有效」这条不变量(拖放目标、选中集都按路径工作)。
*/
import { computed, ref, watch } from 'vue'
import {
AppWindow,
ArrowUp,
ChevronDown,
ChevronRight,
ExternalLink,
FilePlus,
FileText,
Folder,
FolderInput,
FolderOpen,
FolderPlus,
Loader2,
Pencil,
RotateCw,
SquarePen,
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, StateBlock } from '@/components/common'
import { useEditorStore } from '@/stores/editorStore'
import { editorClient } from '../editorClient'
import { openEditorWindow } from '../openWindow'
import type { DirEntry } from '@/types/editor'
const store = useEditorStore()
const filter = ref('')
// ===== 懒加载树 =====
/** 树行:条目 + 层级(缩进用) */
interface TreeRow {
entry: DirEntry
depth: number
}
/** 已展开的目录(值 = 该目录的子层已请求/已缓存) */
const expanded = ref<Set<string>>(new Set())
/** 子层缓存:目录绝对路径 → 其子项(Rust 保证目录在前、各自按名排序) */
const childrenMap = ref<Map<string, DirEntry[]>>(new Map())
/** 正在加载子层的目录(行内转圈用) */
const loadingDirs = ref<Set<string>>(new Set())
/** 新建文件 / 文件夹的目标目录(空串 = 根) */
const selectedDir = ref('')
const rootEntries = computed<DirEntry[]>(() => store.dirListing?.entries ?? [])
const rootCwd = computed(() => store.dirListing?.cwd ?? '')
const cwdName = computed(() => {
const cwd = rootCwd.value
if (!cwd) return '本地目录'
return cwd.split(/[\\/]/).filter(Boolean).pop() ?? cwd
})
/** 目录名过滤:命中自身或任一**已加载**后代才可见;过滤时全部按展开渲染。 */
const rows = computed<TreeRow[]>(() => {
const kw = filter.value.trim().toLowerCase()
const out: TreeRow[] = []
const matches = (entry: DirEntry, kids: DirEntry[] | undefined): boolean => {
if (!kw) return true
if (entry.name.toLowerCase().includes(kw)) return true
return (kids ?? []).some(k => matches(k, childrenMap.value.get(k.path)))
}
const walk = (list: DirEntry[], depth: number) => {
for (const entry of list) {
const kids = childrenMap.value.get(entry.path)
if (!matches(entry, kids)) continue
out.push({ entry, depth })
if (entry.kind !== 'dir') continue
const open = expanded.value.has(entry.path) || !!kw
if (open) walk(kids ?? [], depth + 1)
}
}
walk(rootEntries.value, 0)
return out
})
/** 拉取一个目录的子层并写入缓存(已缓存则跳过)。 */
async function loadChildren(path: string): Promise<void> {
if (childrenMap.value.has(path)) return
const loading = new Set(loadingDirs.value)
loading.add(path)
loadingDirs.value = loading
try {
const listing = await editorClient.readDir(path)
const map = new Map(childrenMap.value)
map.set(path, listing.entries)
childrenMap.value = map
} catch (e) {
// 读失败就收起来,别留一个「展开但永远是空的」目录
const next = new Set(expanded.value)
next.delete(path)
expanded.value = next
toast.error(String(e))
} finally {
const done = new Set(loadingDirs.value)
done.delete(path)
loadingDirs.value = done
}
}
function toggleDir(entry: DirEntry): void {
const next = new Set(expanded.value)
if (next.has(entry.path)) {
next.delete(entry.path)
} else {
next.add(entry.path)
selectedDir.value = entry.path
void loadChildren(entry.path)
}
expanded.value = next
}
/**
* 结构性操作后的统一失效:清空缓存 → 重读根 → 并行重读已展开目录。
*
* 「清空缓存」而不是逐个修补:重命名 / 移动会让后代路径整体变化,逐个推导既啰嗦
* 又容易漏;重新拉取已展开的几层是最不容易出错的兜底。
*/
async function invalidate(): Promise<void> {
childrenMap.value = new Map()
await store.readDir(rootCwd.value)
await Promise.all([...expanded.value].map(p => loadChildren(p)))
}
// 换根(打开 / 上一级 / 重新打开):树状态与选择全部重置
watch(
() => store.dirListing?.cwd,
() => {
childrenMap.value = new Map()
expanded.value = new Set()
loadingDirs.value = new Set()
selectedDir.value = ''
filter.value = ''
selected.value = new Set()
lastIndex.value = -1
}
)
// ===== 多选 =====
const selected = ref<Set<string>>(new Set())
const lastIndex = ref(-1)
const allKnown = computed<DirEntry[]>(() => {
const out = [...rootEntries.value]
for (const kids of childrenMap.value.values()) out.push(...kids)
return out
})
const selectedEntries = computed(() => allKnown.value.filter(e => selected.value.has(e.path)))
function toggleSelect(entry: DirEntry): void {
const next = new Set(selected.value)
if (next.has(entry.path)) next.delete(entry.path)
else next.add(entry.path)
selected.value = next
}
function rangeSelect(entry: TreeRow): void {
const list = rows.value
const to = list.findIndex(e => e.entry.path === entry.entry.path)
const from = lastIndex.value >= 0 ? lastIndex.value : to
const [lo, hi] = from <= to ? [from, to] : [to, from]
const next = new Set(selected.value)
for (let i = lo; i <= hi; i++) {
const item = list[i]
if (item) next.add(item.entry.path)
}
selected.value = next
}
// ===== 导航与打开 =====
async function openFolder(): Promise<void> {
try {
await store.openFolderDialog()
} catch (e) {
toast.error(`打开文件夹失败:${String(e)}`)
}
}
/**
* 在已打开文件夹里一键建一个临时文本文件(免命名,建完直接打开)。
*
* 建在**根**下;命名走「`新建文本.txt` → `新建文本 2.txt` → …」:不弹框才叫一键,
* 所以得自己避开重名(用根列表判断占用;真撞上了后端会报错,toast 会带出原因)。
*/
async function createTempFile(): Promise<void> {
const used = new Set(rootEntries.value.map(e => e.name.toLowerCase()))
let name = '新建文本.txt'
for (let i = 2; used.has(name.toLowerCase()) && i < 1000; i++) {
name = `新建文本 ${i}.txt`
}
try {
await createIn(selectedDir.value || rootCwd.value, 'file', name)
toast.success(`已创建 ${name}`)
} catch (e) {
toast.error(`新建文件失败:${String(e)}`)
}
}
async function goUp(): Promise<void> {
const parent = store.dirListing?.parent
if (!parent) return
try {
await store.readDir(parent)
} catch (e) {
toast.error(String(e))
}
}
async function refresh(): Promise<void> {
if (!rootCwd.value) return
try {
await invalidate()
} catch (e) {
toast.error(String(e))
}
}
function openEntry(entry: DirEntry): void {
if (entry.kind === 'dir') {
toggleDir(entry)
} else {
void store.openDoc(entry.path).catch(e => toast.error(`打开失败:${String(e)}`))
}
}
async function openInNewWindow(entry: DirEntry): Promise<void> {
try {
if (entry.kind === 'dir') await openEditorWindow({ folder: entry.path, dedupe: false })
else await openEditorWindow({ path: entry.path, dedupe: false })
} catch (e) {
toast.error(`在新窗口打开失败:${String(e)}`)
}
}
function onRowClick(entry: TreeRow, event: MouseEvent): void {
const index = rows.value.findIndex(e => e.entry.path === entry.entry.path)
if (event.ctrlKey || event.metaKey) {
toggleSelect(entry.entry)
lastIndex.value = index
return
}
if (event.shiftKey) {
rangeSelect(entry)
return
}
if (selected.value.size > 0) selected.value = new Set()
lastIndex.value = index
openEntry(entry.entry)
}
// ===== 拖拽移动 =====
const dragging = ref('')
/** 当前作为放置目标的文件夹路径(高亮用) */
const dropTarget = ref('')
function onDragStart(entry: DirEntry, event: DragEvent): void {
dragging.value = entry.path
event.dataTransfer?.setData('text/plain', entry.path)
if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move'
}
function onDragOver(entry: DirEntry, event: DragEvent): void {
if (entry.kind !== 'dir' || !dragging.value || dragging.value === entry.path) return
event.preventDefault()
if (event.dataTransfer) event.dataTransfer.dropEffect = 'move'
dropTarget.value = entry.path
}
async function onDrop(entry: DirEntry, event: DragEvent): Promise<void> {
event.preventDefault()
const src = dragging.value
dragging.value = ''
dropTarget.value = ''
if (!src || entry.kind !== 'dir' || src === entry.path) return
try {
await editorClient.movePath(src, entry.path)
await invalidate()
} catch (e) {
toast.error(`移动失败:${String(e)}`)
}
}
function onDragEnd(): void {
dragging.value = ''
dropTarget.value = ''
}
// ===== 新建 / 重命名(目标 = 选中的目录,缺省根) =====
type PromptMode = 'file' | 'folder' | 'rename'
const promptOpen = ref(false)
const promptMode = ref<PromptMode>('file')
const promptValue = ref('')
const promptTarget = ref('')
const busy = ref(false)
const promptTitle = computed(() => {
if (promptMode.value === 'file') return '新建文件'
if (promptMode.value === 'folder') return '新建文件夹'
return '重命名'
})
const promptTargetLabel = computed(() => {
if (promptMode.value === 'rename') return ''
const dir = selectedDir.value || rootCwd.value
if (!dir) return ''
const name = dir.split(/[\\/]/).filter(Boolean).pop() ?? dir
return `位置:${name}`
})
function openPrompt(mode: PromptMode, target = '', initial = ''): void {
promptMode.value = mode
promptTarget.value = target
promptValue.value = initial
promptOpen.value = true
}
/** 在指定目录下新建文件 / 文件夹;成功后失效缓存并(文件)打开。 */
async function createIn(dir: string, kind: 'file' | 'folder', name: string): Promise<void> {
if (!dir) return
if (kind === 'file') {
const path = await editorClient.createFile(dir, name)
await invalidate()
await store.recordRecentFile(path, name)
await store.openFile(path)
} else {
await editorClient.createDir(dir, name)
await invalidate()
// 新建的文件夹就地展开,让用户立刻看到它
const next = new Set(expanded.value)
next.add(dir)
expanded.value = next
void loadChildren(dir)
}
}
async function confirmPrompt(): Promise<void> {
const name = promptValue.value.trim()
if (!name) {
toast.error('名称不能为空')
return
}
busy.value = true
try {
if (promptMode.value === 'file') {
await createIn(selectedDir.value || rootCwd.value, 'file', name)
} else if (promptMode.value === 'folder') {
await createIn(selectedDir.value || rootCwd.value, 'folder', name)
} else {
await editorClient.renamePath(promptTarget.value, name)
await invalidate()
}
promptOpen.value = false
} catch (e) {
toast.error(String(e))
} finally {
busy.value = false
}
}
// ===== 批量重命名(模板化) =====
const batchOpen = ref(false)
const batchTemplate = ref('{name}')
const batchBusy = ref(false)
/** 模板占位符:{name} 原名(去扩展名)、{ext} 扩展名(含点)、{n} 序号(1 起) */
function renderTemplate(entry: DirEntry, index: number): string {
const dot = entry.name.lastIndexOf('.')
const stem = dot > 0 ? entry.name.slice(0, dot) : entry.name
const ext = dot > 0 ? entry.name.slice(dot) : ''
return batchTemplate.value
.replace(/\{name\}/g, stem)
.replace(/\{ext\}/g, ext)
.replace(/\{n\}/g, String(index + 1))
}
const batchPreview = computed(() =>
selectedEntries.value.map((entry, index) => ({
entry,
next: renderTemplate(entry, index).trim()
}))
)
function openBatch(): void {
if (!selectedEntries.value.length) return
batchTemplate.value = '{name}'
batchOpen.value = true
}
async function confirmBatch(): Promise<void> {
const items = batchPreview.value
if (items.some(i => !i.next)) {
toast.error('新名称不能为空')
return
}
if (new Set(items.map(i => i.next)).size !== items.length) {
toast.error('新名称存在重复')
return
}
batchBusy.value = true
try {
const failed: string[] = []
for (const item of items) {
try {
await editorClient.renamePath(item.entry.path, item.next)
} catch (e) {
failed.push(`${item.next}:${String(e)}`)
}
}
await invalidate()
if (failed.length) toast.error(`部分失败:${failed.join(';')}`)
else toast.success(`已重命名 ${items.length} 项`)
batchOpen.value = false
selected.value = new Set()
} catch (e) {
toast.error(String(e))
} finally {
batchBusy.value = false
}
}
// ===== 删除 =====
const confirmOpen = ref(false)
const deleteTargets = ref<DirEntry[]>([])
function askDelete(list: DirEntry[]): void {
if (!list.length) return
deleteTargets.value = list
confirmOpen.value = true
}
async function doDelete(): Promise<void> {
const list = deleteTargets.value
if (!list.length) return
try {
const report = await editorClient.deletePath(list.map(e => e.path))
await invalidate()
if (report.removed > 0) toast.success(`已移入回收站 ${report.removed} 项`)
if (report.failed.length) toast.error(report.failed.join(';'))
selected.value = new Set()
} catch (e) {
toast.error(String(e))
} finally {
confirmOpen.value = false
deleteTargets.value = []
}
}
// ===== 右键菜单(行内 4 个按钮改到这里) =====
const menuOpen = ref(false)
const menuX = ref(0)
const menuY = ref(0)
const menuEntry = ref<DirEntry | null>(null)
/** 菜单项数(用于贴边翻转时的预估高度) */
const MENU_ITEMS = 6
const MENU_WIDTH = 184
/** 右键打开菜单;若该行不在选中集内,则把选中集改为「仅它」。 */
function openMenu(event: MouseEvent, entry: DirEntry): void {
if (!selected.value.has(entry.path)) selected.value = new Set([entry.path])
menuEntry.value = entry
const height = MENU_ITEMS * 28 + 16
menuX.value = Math.max(8, Math.min(event.clientX, window.innerWidth - MENU_WIDTH - 8))
menuY.value = Math.max(8, Math.min(event.clientY, window.innerHeight - height - 8))
menuOpen.value = true
}
function closeMenu(): void {
menuOpen.value = false
menuEntry.value = null
}
/** 删除目标:右键行在选中集内时删整批,否则只删它。 */
const menuDeleteTargets = computed<DirEntry[]>(() => {
const entry = menuEntry.value
if (!entry) return []
return selected.value.has(entry.path) ? selectedEntries.value : [entry]
})
function menuOpenEntry(): void {
const entry = menuEntry.value
closeMenu()
if (entry) openEntry(entry)
}
function menuNewWindow(): void {
const entry = menuEntry.value
closeMenu()
if (entry) void openInNewWindow(entry)
}
function menuReveal(): void {
const entry = menuEntry.value
closeMenu()
if (entry) store.revealPath(entry.path)
}
function menuRename(): void {
const entry = menuEntry.value
closeMenu()
if (entry) openPrompt('rename', entry.path, entry.name)
}
function menuDelete(): void {
const targets = menuDeleteTargets.value
closeMenu()
askDelete(targets)
}
// 不默认加载主目录:默认态就是「打开文件夹」入口,由用户显式选择
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<!-- 默认态:尚未打开任何文件夹时,面板本身就是一个「打开文件夹」入口 -->
<div v-if="!store.dirListing" class="flex min-h-0 flex-1 items-center justify-center">
<StateBlock
variant="empty"
title="未打开文件夹"
description="选择一个本地文件夹后,可在其中浏览、打开与编辑文件"
:min-height="180"
>
<template #action>
<Button size="sm" @click="openFolder">
<FolderOpen class="size-3.5" />打开文件夹
</Button>
</template>
</StateBlock>
</div>
<!-- 工具条:上一级 / 刷新 / 打开文件夹 -->
<div v-if="store.dirListing" class="flex h-8 shrink-0 items-center gap-0.5 px-2">
<Button
variant="ghost"
size="icon-sm"
title="上一级"
:disabled="!store.dirListing?.parent"
@click="goUp"
>
<ArrowUp class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
:title="store.dirLoading ? '正在读取…' : '刷新'"
:disabled="store.dirLoading"
@click="refresh"
>
<RotateCw class="size-3.5" :class="store.dirLoading && 'animate-spin'" />
</Button>
<span class="ml-1 truncate text-[11px] font-medium text-fg-secondary" :title="store.dirListing?.cwd">
{{ cwdName }}
</span>
<div class="ml-auto flex items-center gap-0.5">
<Button variant="ghost" size="icon-sm" title="新建文件(在选中的目录 / 根)" @click="openPrompt('file')">
<FilePlus class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="新建文件夹(在选中的目录 / 根)" @click="openPrompt('folder')">
<FolderPlus class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="新建临时文本文件(一键创建,不弹命名框)"
:disabled="store.dirLoading"
@click="createTempFile"
>
<SquarePen class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="打开文件夹…" @click="openFolder">
<FolderOpen class="size-3.5" />
</Button>
</div>
</div>
<!-- 过滤 -->
<div v-if="store.dirListing" class="shrink-0 px-2 pb-2">
<div class="relative">
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-[11px]" />
<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>
</div>
<!-- 树 -->
<ScrollArea v-if="store.dirListing" class="min-h-0 flex-1">
<div class="px-1.5 pb-2">
<div v-if="store.dirLoading && !rootEntries.length" class="flex items-center justify-center gap-2 p-4">
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
<span class="text-[11px] text-muted-foreground">正在读取目录…</span>
</div>
<StateBlock
v-else-if="!rows.length"
variant="empty"
:title="filter ? '没有匹配项' : '空目录'"
:description="filter ? undefined : '换个目录,或点右上角打开一个文件夹'"
:min-height="140"
/>
<template v-else>
<div
v-for="row in rows"
:key="row.entry.path"
class="group flex h-7 cursor-pointer items-center gap-1 rounded-sm pr-1.5 transition-colors duration-150"
:class="[
selected.has(row.entry.path)
? 'bg-primary-soft text-primary-soft-text'
: store.fileDoc?.path === row.entry.path
? 'bg-row-selected text-primary-soft-text'
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground',
dropTarget === row.entry.path && 'ring-1 ring-primary ring-inset'
]"
:style="{ paddingLeft: `${row.depth * 12 + 4}px` }"
:title="row.entry.path"
draggable="true"
@dragstart="onDragStart(row.entry, $event)"
@dragover="onDragOver(row.entry, $event)"
@drop="onDrop(row.entry, $event)"
@dragend="onDragEnd"
@click="onRowClick(row, $event)"
@contextmenu.prevent="openMenu($event, row.entry)"
>
<!-- 目录行:展开箭头(懒加载不转圈 —— 目录树展开是高频动作,闪烁比等待更烦)
文件行:占位对齐 + 文件图标 -->
<template v-if="row.entry.kind === 'dir'">
<component
:is="expanded.has(row.entry.path) ? ChevronDown : ChevronRight"
class="size-3.5 shrink-0 opacity-70"
/>
<Folder class="size-3.5 shrink-0 opacity-80" />
</template>
<template v-else>
<span class="w-3.5 shrink-0" />
<FileText class="size-3.5 shrink-0 opacity-70" />
</template>
<span class="truncate text-xs">{{ row.entry.name }}</span>
</div>
</template>
</div>
</ScrollArea>
<!-- 批量操作条(有选中时) -->
<div
v-if="store.dirListing && selected.size"
class="flex h-8 shrink-0 items-center gap-1 border-t border-border px-2 text-[11px] text-muted-foreground"
>
<span class="tabular-nums">已选 {{ selected.size }} 项</span>
<div class="ml-auto flex items-center gap-1">
<Button variant="outline" size="sm" @click="openBatch">
<FolderInput class="size-3.5" />批量重命名
</Button>
<Button variant="outline" size="sm" @click="askDelete(selectedEntries)">
<Trash2 class="size-3.5" />删除
</Button>
<Button variant="ghost" size="icon-sm" title="取消选择" @click="selected = new Set()">
<X class="size-3.5" />
</Button>
</div>
</div>
<!-- 右键菜单:文件行的操作(原行内 4 个按钮移到这里) -->
<template v-if="menuOpen && menuEntry">
<div class="fixed inset-0 z-40" @click="closeMenu" @contextmenu.prevent="closeMenu" />
<div
class="fixed z-50 min-w-[184px] overflow-hidden rounded-md border border-border bg-card py-1 text-xs text-foreground shadow-md"
:style="{ left: `${menuX}px`, top: `${menuY}px` }"
>
<button
type="button"
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
@click="menuOpenEntry"
>
<FolderOpen class="size-3.5 opacity-70" />打开
</button>
<button
type="button"
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
@click="menuNewWindow"
>
<AppWindow class="size-3.5 opacity-70" />在新窗口打开
</button>
<button
type="button"
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
@click="menuReveal"
>
<ExternalLink class="size-3.5 opacity-70" />在资源管理器中显示
</button>
<div class="my-1 h-px bg-divider" />
<button
type="button"
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
@click="menuRename"
>
<Pencil class="size-3.5 opacity-70" />重命名
</button>
<button
type="button"
class="flex w-full items-center gap-2 px-2.5 py-1.5 text-left transition-colors hover:bg-row-hover"
@click="menuDelete"
>
<Trash2 class="size-3.5 opacity-70" />
删除{{ menuDeleteTargets.length > 1 ? ` (${menuDeleteTargets.length})` : '' }}
</button>
</div>
</template>
<!-- 名称输入 -->
<Dialog :open="promptOpen" @update:open="promptOpen = $event">
<DialogContent class="sm:max-w-sm">
<DialogHeader>
<DialogTitle>{{ promptTitle }}</DialogTitle>
</DialogHeader>
<Input
v-model="promptValue"
:placeholder="promptMode === 'rename' ? '新名称' : '名称'"
@keydown.enter="confirmPrompt"
/>
<p v-if="promptTargetLabel" class="text-[11px] text-muted-foreground">{{ promptTargetLabel }}</p>
<DialogFooter>
<Button variant="outline" :disabled="busy" @click="promptOpen = false">取消</Button>
<Button :disabled="busy" @click="confirmPrompt">确定</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<!-- 批量重命名 -->
<Dialog :open="batchOpen" @update:open="batchOpen = $event">
<DialogContent class="sm:max-w-lg">
<DialogHeader>
<DialogTitle>批量重命名({{ selectedEntries.length }} 项)</DialogTitle>
</DialogHeader>
<div class="flex flex-col gap-2">
<Input v-model="batchTemplate" placeholder="名称模板" />
<p class="text-[11px] text-muted-foreground">
占位符:<code class="font-mono">{name}</code> 原名 ·
<code class="font-mono">{ext}</code> 扩展名 ·
<code class="font-mono">{n}</code> 序号
</p>
<ScrollArea class="max-h-60 rounded-sm border border-border">
<div class="divide-y divide-divider">
<div
v-for="item in batchPreview"
:key="item.entry.path"
class="flex items-center gap-2 px-2 py-1 text-xs"
>
<span class="min-w-0 flex-1 truncate text-fg-secondary">{{ item.entry.name }}</span>
<span class="shrink-0 text-muted-foreground">→</span>
<span class="min-w-0 flex-1 truncate text-foreground">{{ item.next || '(空)' }}</span>
</div>
</div>
</ScrollArea>
</div>
<DialogFooter>
<Button variant="outline" :disabled="batchBusy" @click="batchOpen = false">取消</Button>
<Button :disabled="batchBusy" @click="confirmBatch">重命名</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<!-- 删除确认(走回收站) -->
<ConfirmDialog
v-model:open="confirmOpen"
title="删除确认"
variant="danger"
confirm-text="移入回收站"
:description="
deleteTargets.length > 1
? `将把选中的 ${deleteTargets.length} 项移入系统回收站(不是永久删除)。`
: `将把「${deleteTargets[0]?.name}」移入系统回收站(不是永久删除)。`
"
@confirm="doDelete"
/>
</div>
</template>
@@ -0,0 +1,73 @@
<script setup lang="ts">
/**
* 编辑区右侧抽屉(P3-4):承载「大纲 / 双链」。
*
* 为什么把它们从侧栏挪出来:侧栏描述的是「去哪找文件」,而大纲与双链描述的是
* **当前文档**。混在一起会让侧栏在「导航」与「文档信息」两种语义之间摇摆。
*/
import { Link2, ListTree, Share2, X } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import { SegmentedNav } from '@/components/common'
import MarkdownOutline from './MarkdownOutline.vue'
import BacklinksPanel from './BacklinksPanel.vue'
import LinkGraph from './LinkGraph.vue'
import { useEditorStore } from '@/stores/editorStore'
const props = defineProps<{
mode: 'outline' | 'links' | 'graph'
/** 编辑器当前光标行(大纲高亮用) */
cursorLine: number
}>()
const emit = defineEmits<{
'update:mode': [mode: 'outline' | 'links' | 'graph']
close: []
jump: [from: number]
open: [relPath: string]
create: []
}>()
const store = useEditorStore()
const NAV_ITEMS = [
{ value: 'outline', label: '大纲', icon: ListTree },
{ value: 'links', label: '双链', icon: Link2 },
{ value: 'graph', label: '图谱', icon: Share2 }
]
function setMode(mode: string): void {
if (mode === 'links' || mode === 'graph') emit('update:mode', mode)
else emit('update:mode', 'outline')
}
</script>
<template>
<aside class="flex h-full min-h-0 w-64 shrink-0 flex-col border-l border-border">
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-2">
<SegmentedNav
:model-value="props.mode"
:items="NAV_ITEMS"
block
@update:model-value="setMode"
/>
<Button variant="ghost" size="icon-sm" title="关闭抽屉" @click="emit('close')">
<X class="size-3.5" />
</Button>
</div>
<MarkdownOutline
v-if="props.mode === 'outline'"
class="min-h-0 flex-1"
:cursor-line="props.cursorLine"
@jump="emit('jump', $event)"
/>
<BacklinksPanel
v-else-if="props.mode === 'links'"
class="min-h-0 flex-1"
:rel-path="store.currentRelPath"
@open="emit('open', $event)"
@create="emit('create')"
/>
<LinkGraph v-else class="min-h-0 flex-1" @open="emit('open', $event)" />
</aside>
</template>
@@ -23,9 +23,9 @@
* `store.language`(一个 thunk),拿到后就地 `setLanguageExtension`;
* 旧语言的过期结果由 store 里的令牌机制丢弃,这里不需要再判一次。
*/
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { EditorView } from '@codemirror/view'
import { useNotesStore } from '@/stores/notesStore'
import { useEditorStore } from '@/stores/editorStore'
import {
createEditorState,
jumpToPosition,
@@ -34,10 +34,11 @@ import {
setLanguageExtension,
type EditorConfig
} from '../editor/core'
import { editorBackground } from '../editor/themes'
import { createLogger } from '@/lib/logger'
import type { Extension } from '@codemirror/state'
const logger = createLogger('notes')
const logger = createLogger('editor')
const props = defineProps<{
/** 应用当前是否深色(跟随应用主题时用于取深/浅变体) */
@@ -53,9 +54,19 @@ const emit = defineEmits<{
'wikilink': [target: string]
}>()
const store = useNotesStore()
const store = useEditorStore()
const hostRef = ref<HTMLDivElement | null>(null)
/**
* 编辑器外壳底色:跟随当前**实际生效**的主题。
*
* CM6 只会绘制 `.cm-editor` 覆盖到的区域,正文下方留白等仍由外壳容器显示;
* 若外壳透明就会透出窗口的 mica 背景(表现为「编辑器背景是透明的」)。
*/
const hostBackground = computed(() =>
editorBackground(String(store.settings.editorTheme), store.settings.followAppTheme, props.isDark)
)
let view: EditorView | null = null
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
/** 程序化替换文档期间抑制「变更 → 置脏」 */
@@ -158,8 +169,17 @@ watch(
}
if (appliedRevision === store.docRevision) return
appliedRevision = store.docRevision
// 目标光标行要在 replaceDoc **之前**取:替换会派发 selection 变化,
// updateListener 随即把 store.cursorLine 覆盖成 1,之后再读就只剩第 1 行了。
const restoreLine = store.cursorLine
applyingDoc = true
replaceDoc(view, store.content)
// 标签切换 / 会话恢复:按 store.cursorLine 复位光标(默认第 1 行不动)
if (restoreLine > 1) {
const line = Math.min(restoreLine, view.state.doc.lines)
const pos = view.state.doc.line(line).from
view.dispatch({ selection: { anchor: pos }, scrollIntoView: false })
}
applyingDoc = false
void applyLanguage(++languageSeq)
}
@@ -218,28 +238,80 @@ defineExpose({
/** 大纲点击跳转 */
jumpTo: (position: number) => {
if (view) jumpToPosition(view, position)
},
/**
* 跳转到某行某列(统一搜索器的「在目录 / 库中查找」结果点击用)。
*
* 行号可能来自**稍早的**检索结果,用户在此期间可能已编辑 —— 越界一律夹到文档
* 范围内(同 `jumpToPosition` 的取舍:跳到近似位置好过整块报错)。
*/
jumpToLine: (line: number, column = 1) => {
if (!view) return
const total = view.state.doc.lines
const number = Math.max(1, Math.min(Math.floor(line), total))
const info = view.state.doc.line(number)
const anchor = Math.min(info.to, info.from + Math.max(0, column - 1))
view.dispatch({ selection: { anchor }, scrollIntoView: true })
view.focus()
}
})
</script>
<template>
<div ref="hostRef" class="notes-editor-host h-full min-h-0 overflow-hidden" />
<div
ref="hostRef"
class="editor-host h-full min-h-0 overflow-hidden"
:style="{ background: hostBackground }"
/>
</template>
<style scoped>
.notes-editor-host :deep(.cm-editor) {
.editor-host :deep(.cm-editor) {
height: 100%;
background: transparent;
/* 不写 background: transparent —— 让 CM6 主题自己的底色生效(见 themes.ts) */
}
.notes-editor-host :deep(.cm-scroller) {
.editor-host :deep(.cm-scroller) {
padding: 12px 8px 32px;
overflow: auto;
/* 滚动条与项目 ScrollArea 一致:细轨 + 圆角 thumb(同终端 xterm 的做法) */
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.notes-editor-host :deep(.cm-editor.cm-focused) {
.editor-host :deep(.cm-scroller)::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-track {
background: transparent;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb {
background: var(--border);
border: 3px solid transparent;
border-radius: 9999px;
background-clip: padding-box;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-thumb:hover {
background: var(--muted-foreground);
background-clip: padding-box;
}
.editor-host :deep(.cm-scroller)::-webkit-scrollbar-corner {
background: transparent;
}
.editor-host :deep(.cm-editor.cm-focused) {
outline: none;
}
/* 统一搜索器的命中高亮:改用应用语义色,而不是 @codemirror/search 自带的黄/橙
—— 自带色在浅色主题下几乎看不见,也与应用观感割裂 */
.editor-host :deep(.cm-searchMatch) {
background: color-mix(in srgb, var(--primary) 26%, transparent);
outline: none;
border-radius: 2px;
}
.editor-host :deep(.cm-searchMatch.cm-searchMatch-selected) {
background: color-mix(in srgb, var(--primary) 55%, transparent);
}
/* 笔记正文里正文与标题之间留些气口,Live Preview 下更接近阅读视图 */
.notes-editor-host :deep(.cm-content) {
.editor-host :deep(.cm-content) {
padding-bottom: 24vh;
}
</style>
@@ -0,0 +1,879 @@
<script setup lang="ts">
/**
* 统一搜索器(Find / Replace,IDEA 风格浮动卡片)。
*
* # 为什么要把「编辑器自带查找」与「笔记库检索」合到这里
*
* 原来有两套搜索:CM6 自带面板(只能查当前文件)与侧栏 FTS5 索引检索(只能查笔记库,
* 只有片段没有行号、不支持正则)。用户要在两者之间来回切换,且都不能「在当前目录里
* 搜一段正则」。这里把三者收进**一个**输入区,用「范围」切换:
*
* ```text
* 当前文件 → CM6 search API(实时高亮 + N/M + 替换)
* 目录 → Rust 逐行 grep + 批量替换,结果落到**底部结果面板**
* 笔记库 → 同一个 grep,检索根换成库根
* ```
*
* # 为什么是横跨编辑列的条(而不是悬浮小卡片)
*
* 照 IDEA 的 Find 栏:横跨编辑区宽度、压在内容上方、不遮挡正文。窄卡片会把长目录路径
* 与过滤条件挤成一行放不下,横条则能从容分行排布。
*
* # 结果为什么不在这里显示
*
* 结果列表搬到了编辑列底部的 `SearchResultsPanel`:卡片宽度有限(预览截断得厉害),
* 而且卡片一关结果就没了 —— 但「先搜完、再逐条点开看」才是这个功能的真实用法。
* 因此卡片只负责**发起检索**,结果 / 历史 / 面板开关都归 `editorSearchStore`。
*
* # 为什么两种范围的行为不同
*
* - 当前文件是**内存里的字符串**,边打字边搜没有成本 → 防抖 120ms 实时搜;
* - 当前目录 / 笔记库是**磁盘扫描** → 只在回车 / 点搜索时执行一次,绝不边打字边扫盘。
*
* # 关键词从选中文本来
*
* `Ctrl+F` 打开时把**当前选中的文本**填进关键词(IDEA / VS Code 行为);跨行选区不算,
* 见 `prefillFromSelection`。
*
* # 目录范围的替换是破坏性的
*
* 目录 / 笔记库的「全部替换」会**直接改写磁盘文件**:它走 Rust 的批量替换,而不是编辑器
* 缓冲区。因此必须先过确认框,后端按每个文件的原编码写回,并把跳过的文件逐个回报
* (见 `grep.rs::replace_in_path`)。
*
* # 检索条件(目录 / 库范围)
*
* - **检索只在回车 / 点搜索按钮时发起**:切范围、改目录、改过滤、点历史条目都**只改
* 条件不搜**。磁盘扫描既慢又不知道什么时候来的结果,必须由一个明确动作触发;
* - **目录**:可自由输入的输入框(默认侧栏打开的目录 / 当前文件所在目录),右侧图标
* 打开系统选择器;
* - **文件类型 / 跳过目录**(**仅目录范围**):各带一个开关与输入框(`|` 或 `,` 分隔)。
* 跳过目录清单是后端**唯一**的跳过依据,所以清空它就会连 `node_modules` 一起搜 ——
* 这是用户明确要求时才会做的事。笔记库范围不暴露这两个条件(见 `pathFilters`);
* - 关键词 / 替换串 / 目录 / 类型 / 跳过目录都带**图标历史**(见 `SearchHistoryInput`):
* 点输入框右侧的历史图标才展开,聚焦不打断输入。点历史只填值。这组历史是
* 「刚输入过什么」,与结果面板里那份「检索记录」(按条件重跑)是两回事。
*
* # 编码
*
* 目录 / 库范围**不假设 UTF-8**:后端按每个文件自己的编码解码(预览即原文),替换也按
* 原编码写回。编码装不下替换内容的文件会被跳过并列出,绝不做有损写入。
*
* # Esc 关闭
*
* `Esc` 由根节点统一接管(`@keydown.esc`):搜索栏里有七八个输入框与按钮,逐个挂
* 处理器既啰嗦又容易漏 —— 而「Esc 关掉搜索栏」在哪个控件上按都该成立。事件从子控件
* 冒泡到根节点即可覆盖全部。
*
* # 为什么高亮不用 v-html
*
* 结果预览来自用户文件正文,`v-html` 是自找的 XSS 面。Rust 回传的是命中下标,
* 底部结果面板用 `pieces()` 切成「普通 / 命中」两段文本,永远走插值渲染。
*/
import { computed, nextTick, reactive, ref, watch } from 'vue'
import {
CaseSensitive,
ChevronDown,
ChevronRight,
ChevronUp,
FileType,
FolderOpen,
FolderX,
Loader2,
Regex,
ReplaceAll,
RotateCcw,
Search,
WholeWord,
X
} from '@lucide/vue'
// 别名:`open` 与本组件的 `open` prop 同名,会和模板里的绑定撞名
import { open as openDialog } from '@tauri-apps/plugin-dialog'
import type { EditorView } from '@codemirror/view'
import {
SearchQuery,
replaceAll as cmReplaceAll,
replaceNext as cmReplaceNext,
setSearchQuery
} from '@codemirror/search'
import { Button } from '@/components/ui/button'
import { ConfirmDialog } from '@/components/common'
import { editorClient } from '../editorClient'
import SearchHistoryInput from './SearchHistoryInput.vue'
import { useEditorSearchStore } from '@/stores/editorSearchStore'
import type { PathReplaceResult } from '@/types/editor'
/** 搜索范围:当前文件 / 当前目录 / 笔记库 */
export type SearchScope = 'file' | 'dir' | 'library'
const props = defineProps<{
/** 卡片是否可见 */
open: boolean
scope: SearchScope
/** 「当前目录」的检索根(绝对路径;空串 = 无可用目录) */
dirPath: string
/** 笔记库根(绝对路径;空串 = 尚未设置库) */
libraryPath: string
/** 取当前 CM6 视图(未打开文档时为 null) */
getView: () => EditorView | null
}>()
const emit = defineEmits<{
'update:open': [value: boolean]
'update:scope': [value: SearchScope]
/** 结果点击:打开文件并跳到某行某列 */
'open-file': [payload: { path: string; line: number; column: number }]
/** 目录 / 库的批量替换已完成(磁盘文件已被改写,调用方需要重载当前文档) */
replaced: [result: PathReplaceResult]
}>()
const isFile = computed(() => props.scope === 'file')
/**
* 用户显式指定的检索目录(`null` = 用默认:侧栏打开的目录 / 当前文件所在目录)。
*
* 只存在组件内存里,不落设置:它是「这一次想在哪找」的临时意图,不该在下次开窗口时
* 悄悄把范围指回某个旧目录。卡片关掉再打开会保留(组件不卸载),符合「刚选过」的预期。
*/
const customDir = ref<string | null>(null)
/**
* 「目录」范围实际用的检索根:用户手填 / 选过的优先,否则用默认(侧栏打开的目录 /
* 当前文件所在目录)。
*
* 用 `??` 而不是 `||` —— 用户把输入框清空是**有效状态**(会提示「请指定检索目录」),
* 不该被当成「没填」而悄悄回落到默认值。
*/
const dirRoot = computed(() => customDir.value ?? props.dirPath)
/** 目录输入框的绑定:读时回落默认值,写时记成「用户指定的目录」。 */
const dirValue = computed({
get: () => dirRoot.value,
set: value => {
customDir.value = value
}
})
/** 检索根(目录 / 笔记库) */
const activeDir = computed(() => (props.scope === 'dir' ? dirRoot.value : props.libraryPath))
// ===== 输入与选项 =====
const pattern = ref('')
const replaceText = ref('')
const showReplace = ref(false)
const caseSensitive = ref(false)
const wholeWord = ref(false)
const regex = ref(false)
/**
* 文件类型默认值:`*.*` = 全部文件(Windows 习惯)。后端也把 `*` / `*.*` 当「全部」
* 处理,否则无扩展名的 `Makefile` 会被默认值意外排除。
*/
const DEFAULT_FILE_TYPES = '*.*'
/**
* 跳过目录名默认值。
*
* **必须与 Rust `grep.rs::DEFAULT_SKIP_DIRS` 一致** —— 这里是展示源(用户看到的初值),
* 那边是字段缺省时的兜底。后端已不再无条件跳过点目录,清单是唯一依据。
*/
const DEFAULT_SKIP_DIRS =
'debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build'
/** 文件类型过滤开关(关掉 = 不按类型过滤,等于全部文件) */
const useFileTypes = ref(true)
const fileTypes = ref(DEFAULT_FILE_TYPES)
/** 跳过目录开关(关掉 = 不跳过任何目录,连 node_modules 一起搜) */
const useSkipDirs = ref(true)
const skipDirs = ref(DEFAULT_SKIP_DIRS)
// ===== 历史记录 =====
//
// 落 localStorage 而不是模块设置:这是搜索卡片自己的「用过什么」,跨窗口共享、重启后
// 还在(与编辑器会话同一姿态),但不需要进 settings.json 受设置版本迁移管。
const HISTORY_KEY = 'thing_editor_search_history'
/** 每组历史最多留多少条 */
const HISTORY_MAX = 20
interface SearchHistory {
pattern: string[]
replace: string[]
dir: string[]
fileTypes: string[]
skipDirs: string[]
}
function emptyHistory(): SearchHistory {
return { pattern: [], replace: [], dir: [], fileTypes: [], skipDirs: [] }
}
function loadHistory(): SearchHistory {
const base = emptyHistory()
try {
const raw = localStorage.getItem(HISTORY_KEY)
if (!raw) return base
const parsed = JSON.parse(raw) as Partial<SearchHistory>
for (const key of Object.keys(base) as Array<keyof SearchHistory>) {
const value = parsed[key]
if (Array.isArray(value)) {
base[key] = value.filter(v => typeof v === 'string' && v.trim()).slice(0, HISTORY_MAX)
}
}
} catch {
/* 坏数据一律当空历史,不影响搜索 */
}
return base
}
const history = reactive<SearchHistory>(loadHistory())
function saveHistory(): void {
try {
localStorage.setItem(HISTORY_KEY, JSON.stringify(history))
} catch {
/* 忽略存储失败 */
}
}
/** 记一条历史(去重 + 置顶 + 限量)。空串不记。 */
function remember(key: keyof SearchHistory, value: string): void {
const text = value.trim()
if (!text) return
history[key] = [text, ...history[key].filter(item => item !== text)].slice(0, HISTORY_MAX)
saveHistory()
}
function forget(key: keyof SearchHistory, value: string): void {
history[key] = history[key].filter(item => item !== value)
saveHistory()
}
function clearHistory(key: keyof SearchHistory): void {
history[key] = []
saveHistory()
}
// ===== 当前文件范围 =====
const matchCount = ref(0)
const currentMatch = ref(0)
/** 命中的字符区间(用于上一个 / 下一个导航) */
let fileMatches: Array<{ from: number; to: number }> = []
// ===== 目录 / 笔记库范围 =====
//
// 状态(结果 / 历史 / 底部面板)都在 `editorSearchStore` 里:结果面板与状态栏按钮也要
// 读它,而这个卡片一关(`v-if`)本地 state 就没了 —— 面板却还得继续显示上次的结果。
const searchStore = useEditorSearchStore()
const results = computed(() => searchStore.results)
const searching = computed(() => searchStore.searching)
const patternRef = ref<InstanceType<typeof SearchHistoryInput> | null>(null)
const scopeHint = computed(() => {
if (props.scope === 'file') return ''
if (props.scope === 'library') return props.libraryPath || '尚未设置笔记库'
return dirRoot.value || '请指定检索目录'
})
/**
* Ctrl+F 打开时用**当前选中的文本**填关键词(IDEA / VS Code 的行为)。
*
* 只取「非空且不跨行」的选区:跨行片段当关键词没有意义 —— 当前文件里换行只是字面量,
* 磁盘 grep 又是逐行匹配的,拿一整段代码当搜索词只会得到 0 命中。此时沿用上一次的
* 关键词,由调用方在输入框里全选,方便直接覆盖输入。
*/
function prefillFromSelection(): void {
const view = props.getView()
if (!view) return
const range = view.state.selection.main
if (range.empty) return
const text = view.state.sliceDoc(range.from, range.to)
if (!text || text.includes('\n') || text.includes('\r')) return
pattern.value = text
}
// ===== 当前文件:CM6 search API =====
function buildQuery(): SearchQuery {
return new SearchQuery({
search: pattern.value,
caseSensitive: caseSensitive.value,
regexp: regex.value,
wholeWord: wholeWord.value,
replace: replaceText.value
})
}
/** 清掉编辑器里的命中高亮(关闭卡片 / 清空关键词时)。 */
function clearFileHighlights(): void {
const view = props.getView()
if (!view) return
view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: '' })) })
matchCount.value = 0
currentMatch.value = 0
fileMatches = []
}
/** 选中第 index 处命中(0 起)并滚动到可见。 */
function selectMatch(index: number): void {
const view = props.getView()
const range = fileMatches[index]
if (!view || !range) return
view.dispatch({
selection: { anchor: range.from, head: range.to },
scrollIntoView: true
})
}
function runFileSearch(): void {
const view = props.getView()
if (!view) {
clearFileHighlights()
return
}
const query = buildQuery()
if (!query.valid) {
// 空关键词或非法正则:清掉高亮,但不弹错(用户还在输入过程中)
view.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: '' })) })
matchCount.value = 0
currentMatch.value = 0
fileMatches = []
return
}
// 先把查询写进编辑器状态(高亮随之渲染),再自行枚举命中做 N/M 与导航
view.dispatch({ effects: setSearchQuery.of(query) })
const collected: Array<{ from: number; to: number }> = []
const cursor = query.getCursor(view.state)
for (let step = cursor.next(); !step.done; step = cursor.next()) {
collected.push(step.value)
// 上限只是防止病态文档把枚举拖死;正常文档远达不到
if (collected.length >= 20000) break
}
fileMatches = collected
matchCount.value = collected.length
if (!collected.length) {
currentMatch.value = 0
return
}
// 落到「当前选区起点之后的第一处」,没有则回到第一处(同 IDEA 的落点规则)
const from = view.state.selection.main.from
let index = collected.findIndex(range => range.from >= from)
if (index < 0) index = 0
currentMatch.value = index + 1
selectMatch(index)
}
/** 上一个 / 下一个(循环)。 */
function stepFile(delta: number): void {
const total = matchCount.value
if (!total) return
let index = currentMatch.value - 1
if (index < 0) index = delta > 0 ? -1 : 0
index = (index + delta + total) % total
currentMatch.value = index + 1
selectMatch(index)
}
/** 替换当前命中。 */
function replaceCurrent(): void {
const view = props.getView()
if (!view || !pattern.value) return
remember('replace', replaceText.value)
view.dispatch({ effects: setSearchQuery.of(buildQuery()) })
cmReplaceNext(view)
runFileSearch()
}
/** 全部替换。 */
function replaceAll(): void {
const view = props.getView()
if (!view || !pattern.value) return
remember('replace', replaceText.value)
view.dispatch({ effects: setSearchQuery.of(buildQuery()) })
cmReplaceAll(view)
runFileSearch()
}
// ===== 当前目录 / 笔记库:Rust 逐行 grep =====
/** 选一个目录作为「目录」范围的检索根。 */
async function pickDir(): Promise<void> {
const selected = await openDialog({ directory: true, multiple: false, title: '选择检索目录' })
if (typeof selected !== 'string') return
customDir.value = selected
// 只改条件,不顺手搜一次:检索一律由「回车 / 点搜索按钮」发起(见 submit)
}
/** 恢复默认检索根(侧栏打开的目录 / 当前文件所在目录)。 */
function resetDir(): void {
customDir.value = null
}
/**
* 目录范围共用的过滤选项。
*
* - 笔记库范围**不暴露**这两个条件:库是「找笔记」的场景,按类型 / 目录过滤只会添乱。
* 类型送 `null`(不过滤),跳过目录送 `null` 让后端用它内置的默认清单兜底(避免
* 走 `.git` / `node_modules`,那是安全网而不是用户配置项);
* - 开关关掉时:类型送 `null`(不过滤),跳过目录送**空串**(明确「不跳过任何目录」)——
* 送 `null` 会退回后端默认清单,正好是关掉开关的反效果。
*/
function pathFilters(): { fileTypes: string | null; skipDirs: string | null } {
if (props.scope === 'library') return { fileTypes: null, skipDirs: null }
return {
fileTypes: useFileTypes.value ? fileTypes.value : null,
skipDirs: useSkipDirs.value ? skipDirs.value : ''
}
}
/** 记下这次检索用到的条件(只在真正发起检索时记,边打字不写历史)。 */
function rememberPathInputs(): void {
remember('pattern', pattern.value)
remember('dir', activeDir.value)
// 只有目录范围才用到这两个条件
if (props.scope !== 'dir') return
if (useFileTypes.value) remember('fileTypes', fileTypes.value)
if (useSkipDirs.value) remember('skipDirs', skipDirs.value)
}
async function runPathSearch(): Promise<void> {
const keyword = pattern.value.trim()
if (!keyword || props.scope === 'file') return
const dir = activeDir.value
if (!dir) {
searchStore.error = scopeHint.value
searchStore.results = null
return
}
await searchStore.runQuery({
dir,
pattern: pattern.value,
caseSensitive: caseSensitive.value,
wholeWord: wholeWord.value,
regex: regex.value,
// 后端已把命中总数统计完整;这里只要尽量多的预览(后端夹在 1..=5000),
// 界面由结果面板分段渲染,不会一次挂出几千行
limit: 5000,
...pathFilters()
})
// 结果现在在底部面板里展示(`SearchResultsPanel`),此处只负责把条件记进输入框历史
rememberPathInputs()
}
/** 回车 / 点搜索:按当前范围分派。 */
function submit(backwards = false): void {
// 显式提交才算「搜过一次」:当前文件范围是边打字边搜的,不能每个字符都进历史
remember('pattern', pattern.value)
if (isFile.value) stepFile(backwards ? -1 : 1)
else void runPathSearch()
}
// ===== 当前目录 / 笔记库:批量替换(会改写磁盘) =====
const replacing = ref(false)
const replaceConfirmOpen = ref(false)
/**
* 确认框文案:把「会影响什么」说清楚 —— `ConfirmDialog` 的用途就在于此
* (规范明确不用 `window.confirm`,正是因为它承载不了这句话)。
*/
const replaceConfirmText = computed(() => {
const r = results.value
const files = r?.files.length ?? 0
const total = r?.total ?? 0
const to = replaceText.value || '(空)'
let text =
`将在 ${files} 个文件中,把 ${total} 处「${pattern.value}」替换为「${to}」。` +
'此操作直接改写磁盘文件,无法在编辑器里撤销。' +
'每个文件按它自己的原编码写回;编码装不下替换内容的文件会跳过并在结果里列出。'
if (r?.truncated) {
text += `命中总数超出单次替换上限(5000 处),本次只替换前面一部分,完成后可再次执行。`
}
return text
})
function askPathReplace(): void {
if (!results.value?.total || !pattern.value.trim() || replacing.value) return
replaceConfirmOpen.value = true
}
/** 「全部替换」按钮的提示(写在这里而不是模板里,避免模板表达式的空值收窄问题)。 */
const pathReplaceTitle = computed(() => {
const r = results.value
if (!r?.total) return '先检索出结果,再替换'
return `在 ${r.totalFiles} 个文件中替换 ${r.total} 处(改写磁盘,会先确认)`
})
async function runPathReplace(): Promise<void> {
replaceConfirmOpen.value = false
const dir = activeDir.value
if (!dir) return
replacing.value = true
try {
const result = await editorClient.replaceInPath({
dir,
pattern: pattern.value,
replacement: replaceText.value,
caseSensitive: caseSensitive.value,
wholeWord: wholeWord.value,
regex: regex.value,
// 替换仍是「改写磁盘」的有界操作(后端停在文件边界),上限用满 5000
limit: 5000,
...pathFilters()
})
remember('replace', replaceText.value)
rememberPathInputs()
// 结果面板里的行号 / 预览已经全部过期 —— 按原条件重扫一次(顺带刷新记录里的命中数)
await runPathSearch()
emit('replaced', result)
} catch (e) {
searchStore.error = String(e)
} finally {
replacing.value = false
}
}
function close(): void {
emit('update:open', false)
}
function setScope(scope: SearchScope): void {
if (props.scope === scope) return
emit('update:scope', scope)
}
// ===== 联动 =====
let debounce: ReturnType<typeof setTimeout> | null = null
// 边打字边搜只对「当前文件」成立:目录 / 库是磁盘扫描,交给回车触发
watch([pattern, caseSensitive, wholeWord, regex], () => {
if (!props.open || !isFile.value) return
if (debounce) clearTimeout(debounce)
debounce = setTimeout(() => {
debounce = null
runFileSearch()
}, 120)
})
// 换范围:切到「当前文件」时立即重算高亮(内存里搜,没有成本)。
// 切到目录 / 库**不**自动搜 —— 检索一律由回车 / 点搜索按钮发起(见 submit)
watch(
() => props.scope,
scope => {
if (debounce) clearTimeout(debounce)
if (scope === 'file') runFileSearch()
}
)
// 说明:**不**在目录根变化时清空结果面板。
//
// 面板展示的是「某条检索记录的结果」,它自带完整条件(目录 / 关键词 / 过滤),是自洽的;
// 用户在卡片里改目录或改关键词,都不该把已经搜出来的结果擦掉 —— 那会让「先搜完再慢慢看」
// 这个主要用法失效。要换内容就再搜一次,结果会整体替换。
watch(
() => props.open,
open => {
if (!open) {
clearFileHighlights()
return
}
// 先看有没有选中文本要带进来,再决定关键词从哪儿来
prefillFromSelection()
void nextTick(() => patternRef.value?.focusAndSelect())
// 打开卡片:当前文件范围立即重算高亮;目录 / 库不开搜(要搜得自己按回车)
if (isFile.value) runFileSearch()
}
)
</script>
<template>
<div
v-if="open"
class="flex w-full shrink-0 flex-col border-b-2 border-primary/60 bg-popover text-popover-foreground"
@keydown.esc.prevent="close"
>
<!-- 第 1 行:关键词 + 计数 + 匹配选项 + 上一个 / 下一个 + 关闭 -->
<div class="flex h-8 items-center gap-0.5 px-2">
<Button
variant="ghost"
size="icon-sm"
:title="showReplace ? '收起替换' : '展开替换'"
@click="showReplace = !showReplace"
>
<component :is="showReplace ? ChevronDown : ChevronRight" class="size-3.5" />
</Button>
<SearchHistoryInput
ref="patternRef"
v-model="pattern"
:history="history.pattern"
:placeholder="
scope === 'file' ? '在当前文件中查找…' : scope === 'dir' ? '在目录中查找…' : '在笔记库中查找…'
"
class="w-[420px] min-w-[140px]"
input-class="h-6 text-xs"
@submit="submit(false)"
@submit-backwards="submit(true)"
@remove-history="forget('pattern', $event)"
@clear-history="clearHistory('pattern')"
/>
<!-- 计数只在当前文件范围有意义(目录 / 库的结果数在底部结果面板) -->
<span
v-if="isFile"
class="min-w-[52px] shrink-0 text-right text-[11px] tabular-nums text-muted-foreground"
>
{{ matchCount ? `${currentMatch}/${matchCount}` : '无结果' }}
</span>
<Button
variant="ghost"
size="icon-sm"
:title="caseSensitive ? '区分大小写:开' : '区分大小写:关'"
:class="caseSensitive && 'bg-active text-foreground'"
@click="caseSensitive = !caseSensitive"
>
<CaseSensitive class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
:title="wholeWord ? '全词匹配:开' : '全词匹配:关'"
:class="wholeWord && 'bg-active text-foreground'"
@click="wholeWord = !wholeWord"
>
<WholeWord class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
:title="regex ? '正则表达式:开' : '正则表达式:关'"
:class="regex && 'bg-active text-foreground'"
@click="regex = !regex"
>
<Regex class="size-3.5" />
</Button>
<template v-if="isFile">
<Button
variant="ghost"
size="icon-sm"
title="上一个 (Shift+Enter)"
:disabled="!matchCount"
@click="stepFile(-1)"
>
<ChevronUp class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="下一个 (Enter)"
:disabled="!matchCount"
@click="stepFile(1)"
>
<ChevronDown class="size-3.5" />
</Button>
</template>
<Button v-else variant="ghost" size="icon-sm" title="搜索 (Enter)" @click="submit(false)">
<Loader2 v-if="searching" class="size-3.5 animate-spin" />
<Search v-else class="size-3.5" />
</Button>
<!-- 选项 / 导航按钮紧跟输入框左移,只有关闭按钮留在最右 -->
<div class="flex-1" />
<Button variant="ghost" size="icon-sm" title="关闭 (Esc)" @click="close">
<X class="size-3.5" />
</Button>
</div>
<!-- 第 2 行:替换。当前文件走 CM6(改内存),目录 / 库走 Rust 批量替换(改写磁盘) -->
<div v-if="showReplace" class="flex h-8 items-center gap-0.5 px-2">
<!-- 空位 = 上一行那个 size-7(28px)的展开按钮,**行内间距也必须一样**(gap-0.5)
才能让两个输入框的左边缘严格重合(`gap-1` 会多推出去 2px) -->
<div class="w-7 shrink-0" />
<SearchHistoryInput
v-model="replaceText"
:history="history.replace"
placeholder="替换为…"
class="w-[420px] min-w-[140px]"
input-class="h-6 text-xs"
@submit="isFile ? replaceCurrent() : askPathReplace()"
@remove-history="forget('replace', $event)"
@clear-history="clearHistory('replace')"
/>
<template v-if="isFile">
<Button variant="outline" size="sm" :disabled="!matchCount" @click="replaceCurrent">
替换
</Button>
<Button variant="outline" size="sm" :disabled="!matchCount" @click="replaceAll">
全部替换
</Button>
</template>
<Button
v-else
variant="outline"
size="sm"
:disabled="!results?.total || replacing"
:title="pathReplaceTitle"
@click="askPathReplace"
>
<Loader2 v-if="replacing" class="size-3 animate-spin" />
<ReplaceAll v-else class="size-3" />
全部替换
</Button>
</div>
<!-- 第 3 行:范围 + 检索根 -->
<div class="flex items-center gap-1 border-t border-border px-2 py-1">
<button
type="button"
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
:class="
scope === 'file'
? 'bg-active text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
@click="setScope('file')"
>
当前文件
</button>
<button
type="button"
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
:class="
scope === 'dir'
? 'bg-active text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
title="在目录中查找(默认为侧栏打开的目录 / 当前文件所在目录,可手动输入或选择)"
@click="setScope('dir')"
>
目录
</button>
<button
type="button"
class="rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150 disabled:pointer-events-none disabled:opacity-50"
:class="
scope === 'library'
? 'bg-active text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
:disabled="!libraryPath"
title="在笔记库根目录中查找"
@click="setScope('library')"
>
笔记库
</button>
<!-- 检索根:目录范围可自由输入,右侧图标打开系统选择器;库范围只读展示 -->
<template v-if="scope === 'dir'">
<SearchHistoryInput
v-model="dirValue"
:history="history.dir"
placeholder="输入或选择检索目录…"
input-class="h-6 font-mono text-[11px]"
class="ml-1 min-w-0 flex-1"
@submit="runPathSearch()"
@remove-history="forget('dir', $event)"
@clear-history="clearHistory('dir')"
/>
<Button
variant="ghost"
size="icon-sm"
class="shrink-0"
title="打开系统目录选择器"
@click="pickDir"
>
<FolderOpen class="size-3.5" />
</Button>
<Button
v-if="customDir !== null"
variant="ghost"
size="icon-sm"
class="shrink-0"
title="恢复默认目录(侧栏打开的目录 / 当前文件所在目录)"
@click="resetDir"
>
<RotateCcw class="size-3.5" />
</Button>
</template>
<span v-else-if="scopeHint" class="ml-2 min-w-0 flex-1 truncate text-[10px] text-fg-disabled" :title="scopeHint">
{{ scopeHint }}
</span>
<span v-else-if="!isFile && !pattern.trim()" class="ml-2 text-[10px] text-fg-disabled">
输入关键词后按回车检索
</span>
</div>
<!-- 第 4 行:过滤条件。**只有目录范围**需要 —— 笔记库是「找笔记」,过滤只会添乱 -->
<div v-if="scope === 'dir'" class="flex items-center gap-4 border-t border-border px-2 py-1">
<div class="flex w-72 shrink-0 items-center gap-1.5">
<Button
variant="ghost"
size="icon-sm"
class="shrink-0"
:title="useFileTypes ? '按文件类型过滤:开' : '按文件类型过滤:关(搜全部文件)'"
:class="useFileTypes && 'bg-active text-foreground'"
@click="useFileTypes = !useFileTypes"
>
<FileType class="size-3.5" />
</Button>
<span class="shrink-0 text-xs text-foreground">文件类型</span>
<SearchHistoryInput
v-model="fileTypes"
:history="history.fileTypes"
:disabled="!useFileTypes"
placeholder="*.*|*.ts|*.vue"
input-class="h-6 font-mono text-[11px]"
class="min-w-0 flex-1"
@submit="runPathSearch()"
@remove-history="forget('fileTypes', $event)"
@clear-history="clearHistory('fileTypes')"
/>
</div>
<div class="flex min-w-0 flex-1 items-center gap-1.5">
<Button
variant="ghost"
size="icon-sm"
class="shrink-0"
:title="useSkipDirs ? '按清单跳过目录:开' : '不跳过任何目录(含 node_modules 等)'"
:class="useSkipDirs && 'bg-active text-foreground'"
@click="useSkipDirs = !useSkipDirs"
>
<FolderX class="size-3.5" />
</Button>
<span class="shrink-0 text-xs text-foreground">跳过目录</span>
<SearchHistoryInput
v-model="skipDirs"
:history="history.skipDirs"
:disabled="!useSkipDirs"
placeholder="node_modules|.git|dist"
input-class="h-6 font-mono text-[11px]"
class="min-w-0 flex-1"
@submit="runPathSearch()"
@remove-history="forget('skipDirs', $event)"
@clear-history="clearHistory('skipDirs')"
/>
</div>
</div>
<!-- 目录 / 库替换的确认:这是会改写磁盘的不可逆操作,必须让用户看清影响面 -->
<ConfirmDialog
v-model:open="replaceConfirmOpen"
variant="danger"
title="在目录中替换"
:description="replaceConfirmText"
confirm-text="全部替换"
:loading="replacing"
@confirm="runPathReplace"
/>
</div>
</template>
@@ -0,0 +1,45 @@
<script setup lang="ts">
/**
* 文档标签栏(P4-5)。
*
* 一个编辑器窗口内可同时打开多篇文档,每个标签**独立**保存内容、编码 / 换行、
* 视图模式与未保存状态。标签的「脏」指示点用 store 的 `tabViews`:活动标签取
* 实时值(正在敲字),后台标签取切换时收回的快照。
*/
import { FileCode2, FileText, X } from '@lucide/vue'
import { useEditorStore } from '@/stores/editorStore'
const emit = defineEmits<{ close: [id: string] }>()
const store = useEditorStore()
</script>
<template>
<div class="flex h-8 shrink-0 items-stretch gap-0.5 overflow-x-auto border-b border-border px-1">
<div
v-for="tab in store.tabViews"
:key="tab.id"
class="group flex max-w-52 min-w-0 cursor-pointer items-center gap-1.5 rounded-t-sm border-b-2 px-2 text-xs transition-colors duration-150"
:class="
tab.id === store.activeTabId
? 'border-primary bg-row-selected text-foreground'
: 'border-transparent text-fg-secondary hover:bg-row-hover hover:text-foreground'
"
:title="tab.name"
@click="store.activateTab(tab.id)"
>
<FileText v-if="tab.kind === 'note'" class="size-3.5 shrink-0 opacity-70" />
<FileCode2 v-else class="size-3.5 shrink-0 opacity-70" />
<span class="truncate">{{ tab.name }}</span>
<span v-if="tab.dirty" class="shrink-0 font-medium text-primary" title="有未保存的改动">*</span>
<button
type="button"
class="shrink-0 rounded-sm p-0.5 opacity-0 transition-opacity hover:bg-active group-hover:opacity-100"
title="关闭标签(Ctrl+W)"
@click.stop="emit('close', tab.id)"
>
<X class="size-3" />
</button>
</div>
</div>
</template>
@@ -0,0 +1,282 @@
<script setup lang="ts">
/**
* 顶部快捷操作行(原「工具栏」)。
*
* # 为什么只有图标
*
* 文件名在**窗口标题**与**标签栏**里都有了,工具栏再显示一遍是重复信息;按钮文字
* 也会把这一行撑得很宽。因此整行统一为图标按钮,标题(含快捷键)走 tooltip。
*
* # 一行里放两类东西
*
* 1. **侧栏导航**(库 / 目录 / 最近)—— 从侧栏内部搬上来,侧栏只留内容;
* 2. **文档操作**(在路径中查找 / 打开 / 快速打开 / 保存 / 视图 / 导出)+ 笔记的
* Markdown 格式化。检索不再是「侧栏的一个视图」,而是统一搜索器(EditorSearch),
* 因此这个按钮只负责把搜索器叫出来,不参与侧栏高亮。
*
* 配色快切已移除:主题是配置项,只在模块设置页出现,避免两个入口改同一份设置。
*/
import {
Bold,
Code,
Eye,
FileDown,
FilePlus,
FileSearch,
FolderOpen,
FolderTree,
Heading1,
Heading2,
Heading3,
History,
Italic,
Library,
Link,
List,
ListChecks,
Loader2,
PanelLeft,
Quote,
Save,
Search,
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 { useEditorStore } from '@/stores/editorStore'
import { editorClient } from '../editorClient'
import { editorCommands } from '../editor/keymap'
import type { NoteViewMode } from '@/types/editor'
type SideView = 'library' | 'directory' | 'recent'
const props = defineProps<{
apply: (command: Command) => void
viewMode: NoteViewMode
dirty: boolean
saving: boolean
/** 侧栏是否可见(决定开关按钮的状态与 tooltip) */
sidebarVisible: boolean
}>()
const emit = defineEmits<{
'update:viewMode': [value: NoteViewMode]
save: []
'open-file': []
/** 新建临时文件(草稿) */
'new-file': []
'quick-open': []
'toggle-sidebar': []
nav: [view: SideView]
/** 打开统一搜索器(在路径中查找) */
'open-search': []
}>()
const store = useEditorStore()
const run = (command: Command) => props.apply(command)
const exporting = ref(false)
/** 侧栏导航按钮当前是否处于「选中」状态(侧栏可见且视图匹配)。 */
function isActive(view: SideView): boolean {
return props.sidebarVisible && store.sideView === view
}
/**
* 导出当前笔记为 HTML。
*
* 渲染链路(markdown-it + DOMPurify + highlight.js)**按需 import**:
* 它约 1MB,而导出是低频动作 —— 静态引入会让「打开编辑器窗口」这个最常见的动作
* 也背上这份体积。
*/
async function exportHtml(): Promise<void> {
if (!store.currentRelPath) return
exporting.value = true
try {
const doc = await editorClient.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 editorClient.exportNote(store.currentRelPath, html, dest)
toast.success(`已导出:${saved}`)
} catch (e) {
toast.error(`导出失败:${String(e)}`)
} finally {
exporting.value = false
}
}
</script>
<template>
<div
class="flex h-9 shrink-0 items-center gap-0.5 overflow-x-auto border-b border-border px-2"
>
<!-- 侧栏开关 -->
<Button
variant="ghost"
size="icon-sm"
:title="sidebarVisible ? '隐藏侧栏' : '显示侧栏'"
@click="emit('toggle-sidebar')"
>
<PanelLeft class="size-3.5" />
</Button>
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
<!-- 侧栏导航:库 / 目录 / 最近 -->
<Button
variant="ghost"
size="icon-sm"
title="笔记库"
:class="isActive('library') && 'bg-active text-foreground'"
@click="emit('nav', 'library')"
>
<Library class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="本地目录"
:class="isActive('directory') && 'bg-active text-foreground'"
@click="emit('nav', 'directory')"
>
<FolderTree class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="在路径中查找 (Ctrl+Shift+F)"
@click="emit('open-search')"
>
<Search class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="最近打开"
:class="isActive('recent') && 'bg-active text-foreground'"
@click="emit('nav', 'recent')"
>
<History class="size-3.5" />
</Button>
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
<!-- 文档操作 -->
<Button
variant="ghost"
size="icon-sm"
title="新建临时文件(草稿,存放在应用数据目录;关闭时可选择保存到别处或删除)"
@click="emit('new-file')"
>
<FilePlus class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="打开磁盘文件 (Ctrl+O)" @click="emit('open-file')">
<FolderOpen class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="快速打开 (Ctrl+P)" @click="emit('quick-open')">
<FileSearch class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
:title="dirty ? '保存 (Ctrl+S)' : '没有需要保存的改动'"
:disabled="!dirty || saving"
@click="emit('save')"
>
<Loader2 v-if="saving" class="size-3.5 animate-spin" />
<Save v-else class="size-3.5" />
</Button>
<Button
v-if="store.kind === 'note'"
variant="ghost"
size="icon-sm"
:title="viewMode === 'wysiwyg' ? '切到源码视图 (Ctrl+Shift+M)' : '切到所见即所得 (Ctrl+Shift+M)'"
@click="emit('update:viewMode', viewMode === 'wysiwyg' ? 'source' : 'wysiwyg')"
>
<Eye class="size-3.5" />
</Button>
<Button
v-if="store.kind === 'note' && store.currentRelPath"
variant="ghost"
size="icon-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>
<!-- Markdown 格式化(仅笔记) -->
<template v-if="store.kind === 'note'">
<div class="mx-1 h-4 w-px shrink-0 bg-divider" />
<Button variant="ghost" size="icon-sm" title="加粗 (Ctrl+B)" @click="run(editorCommands.bold)">
<Bold class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="斜体 (Ctrl+I)" @click="run(editorCommands.italic)">
<Italic class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="删除线 (Ctrl+Shift+X)"
@click="run(editorCommands.strikethrough)"
>
<Strikethrough class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="行内代码 (Ctrl+E)"
@click="run(editorCommands.inlineCode)"
>
<Code class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="链接 (Ctrl+K)" @click="run(editorCommands.link)">
<Link class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="一级标题 (Ctrl+1)" @click="run(editorCommands.heading(1))">
<Heading1 class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="二级标题 (Ctrl+2)" @click="run(editorCommands.heading(2))">
<Heading2 class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="三级标题 (Ctrl+3)" @click="run(editorCommands.heading(3))">
<Heading3 class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="无序列表" @click="run(editorCommands.bulletList)">
<List class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="任务列表" @click="run(editorCommands.taskList)">
<ListChecks class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="引用" @click="run(editorCommands.quote)">
<Quote class="size-3.5" />
</Button>
<Button
variant="ghost"
size="icon-sm"
title="代码块 (Ctrl+Shift+C)"
@click="run(editorCommands.codeBlock)"
>
<SquareCode class="size-3.5" />
</Button>
</template>
</div>
</template>
@@ -37,10 +37,10 @@ import {
SelectValue
} from '@/components/ui/select'
import { SettingRow } from '@/components/common'
import { useNotesStore } from '@/stores/notesStore'
import { notesClient } from '../notesClient'
import { useEditorStore } from '@/stores/editorStore'
import { editorClient } from '../editorClient'
const store = useNotesStore()
const store = useEditorStore()
const busy = ref<'import' | 'export' | 'zip' | null>(null)
@@ -101,7 +101,7 @@ async function doImport(kind: 'file' | 'dir'): Promise<void> {
)
if (typeof selected !== 'string') return
busy.value = 'import'
const report = await notesClient.import(selected, '')
const report = await editorClient.import(selected, '')
await store.refreshLibrary()
await store.syncIndex()
const renamed = report.renamed ? `,${report.renamed} 篇重名已加序号` : ''
@@ -126,7 +126,7 @@ async function doExportHtml(): Promise<void> {
return
}
try {
const doc = await notesClient.readNote(relPath)
const doc = await editorClient.readNote(relPath)
// **动态引入**:`markdownExport` 会拉进 markdown-it + DOMPurify + highlight.js
// (实测约 1MB),而导出是低频动作。静态引入会让「笔记」模块页一打开就下载
// 这三个包(chunk 从 ~130kB 涨到 1.1MB),把首屏拖垮。
@@ -146,7 +146,7 @@ async function doExportHtml(): Promise<void> {
})
if (typeof dest !== 'string') return
busy.value = 'export'
const saved = await notesClient.exportNote(relPath, html, dest)
const saved = await editorClient.exportNote(relPath, html, dest)
toast.success(`已导出:${saved}`, {
action: { label: '打开', onClick: () => void openPath(saved) }
})
@@ -170,7 +170,7 @@ async function doExportZip(): Promise<void> {
})
if (typeof dest !== 'string') return
busy.value = 'zip'
const saved = await notesClient.exportZip(dest, scope || undefined)
const saved = await editorClient.exportZip(dest, scope || undefined)
toast.success(`已导出:${saved}`, {
action: { label: '打开目录', onClick: () => void openPath(saved.replace(/[\\/][^\\/]+$/, '')) }
})
@@ -270,7 +270,7 @@ async function exportTemplates(): Promise<void> {
</div>
</SettingRow>
<SettingRow label="导出 zip" description="整库或某个目录(含 assets/,不含 .notes/)" control-width="wide">
<SettingRow label="导出 zip" description="整库或某个目录(含 assets/,不含 .editor/)" control-width="wide">
<div class="flex w-full flex-col gap-2">
<Select v-model="zipScope">
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
@@ -1,20 +1,30 @@
<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`,不手写占位文案
* 「检索」已不再是侧栏的一个视图 —— 它并入了统一搜索器(`EditorSearch.vue`),
* 那一处同时覆盖「当前文件 / 当前目录 / 笔记库」,侧栏只保留「去哪找文件」的导航。
*
* 树用「展开集合 + 扁平化」渲染,而不是递归子组件 —— 扁平列表能把过滤
* (只保留命中项及其祖先)一并做掉。
* # 两个并列的「根」
*
* # 三视图为什么在同一个侧栏里切换
* - **笔记库**:沙箱 + 索引 + front-matter + 双链(相对库根路径)
* - **本地目录**:任意路径 + 不进索引 + 无 front-matter 语义(真实文件系统)
*
* 目录树 / 检索 / 大纲三者是**同一时刻只需一个**的导航手段,各自单开一个面板会
* 把编辑器挤窄。用分段导航切换既省宽度,也让「我在找什么」始终只有一个答案。
* 两者是并列的导航能力,编辑对象(文件本身)才是模块中心。
*
* # 大纲 / 双链去哪了
*
* 它们描述的是**当前文档**而不是「去哪找文件」,因此移到编辑区右侧抽屉
* (见 `DrawerPanel.vue`)。侧栏只回答「去哪找」。
*
* 版式沿用终端「文件管理器」(`ScrollArea` 滚动、`bg-row-selected` 选中、
* 紧凑输入 `h-7 text-xs`、空态用 `StateBlock`)。
*
* # 字号比主界面「小一号」
*
* 侧栏是窄栏(256px)且常年挂在那里,行名与标题若用正文尺寸会显得拥挤、抢视线。
* 因此列表行统一 `text-xs`(12px)、标题与提示再用 `text-[11px]` / `text-[10px]` 递减 ——
* 层级拉开,密度也更接近 JetBrains 的工具窗口。
*/
import { computed, ref, watch } from 'vue'
import {
@@ -24,12 +34,9 @@ import {
FileText,
Folder,
FolderPlus,
Link2,
ListTree,
Loader2,
Pencil,
RotateCw,
Search,
Trash2,
X
} from '@lucide/vue'
@@ -38,58 +45,39 @@ 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 { ConfirmDialog, StateBlock } from '@/components/common'
import { useEditorStore } from '@/stores/editorStore'
import type { LibraryEntry, LibraryTreeNode } from '@/types/editor'
import DirectoryPanel from './DirectoryPanel.vue'
import RecentPanel from './RecentPanel.vue'
import NewNoteDialog from './NewNoteDialog.vue'
const emit = defineEmits<{ open: [relPath: string]; jump: [from: number] }>()
const emit = defineEmits<{ open: [relPath: string] }>()
const store = useNotesStore()
const store = useEditorStore()
/** 侧栏视图 */
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)
/** 侧栏视图由顶部操作行控制(`store.sideView`),这里只管内容 */
const view = computed(() => store.sideView)
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 时调用 */
/** 由 EditorWindow 在顶部导航触发时调用 */
showLibrary: () => store.setSideView('library'),
/** 由 EditorWindow 在 `?folder=` 打开时调用 */
showDirectory: () => store.setSideView('directory'),
/** 由 EditorWindow 在 Ctrl+Shift+N 时调用 */
showNewNote: () => {
view.value = 'files'
store.setSideView('library')
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()
@@ -186,24 +174,13 @@ function revealNote(relPath: string): void {
next.add(prefix)
}
expanded.value = next
view.value = 'files'
store.setSideView('library')
}
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)
@@ -270,13 +247,66 @@ async function rebuildIndex(): Promise<void> {
await store.refreshLibrary()
toast.success('索引已重建')
}
// ===== 宽度拖拽 =====
//
// 与底部结果面板(SearchResultsPanel)同一套 Pointer Events + setPointerCapture 范式:
// 指针被捕获后拖出窗口边界也不丢事件。宽度落 localStorage,下次打开保持。
const WIDTH_KEY = 'thing_editor_sidebar_width'
const MIN_WIDTH = 200
const MAX_WIDTH = 520
function loadWidth(): number {
try {
const raw = localStorage.getItem(WIDTH_KEY)
const n = raw ? Number(raw) : NaN
return Number.isFinite(n) ? Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, n)) : 256
} catch {
return 256
}
}
const width = ref(loadWidth())
const resizing = ref(false)
let dragStartX = 0
let dragStartWidth = 0
function onResizeStart(event: PointerEvent): void {
dragStartX = event.clientX
dragStartWidth = width.value
resizing.value = true
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
}
function onResizeMove(event: PointerEvent): void {
if (!resizing.value) return
// 往右拖 = 侧栏变宽
width.value = Math.round(Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, dragStartWidth + (event.clientX - dragStartX))))
}
function onResizeEnd(event: PointerEvent): void {
if (!resizing.value) return
resizing.value = false
;(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
try {
localStorage.setItem(WIDTH_KEY, String(width.value))
} catch {
/* 忽略存储失败 */
}
}
</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>
<aside
class="relative flex h-full min-h-0 shrink-0 flex-col border-r border-border"
:style="{ width: `${width}px` }"
>
<!-- 头部:仅库视图需要库操作(导航已在顶部操作行) -->
<div
v-if="view === 'library'"
class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-2"
>
<span class="ml-1 text-xs font-medium text-foreground">笔记库</span>
<div class="ml-auto flex items-center gap-0.5">
<Button
variant="ghost"
@@ -301,16 +331,11 @@ async function rebuildIndex(): Promise<void> {
</div>
</div>
<!-- 视图切换 -->
<div class="shrink-0 px-2 pt-2">
<SegmentedNav v-model="view" :items="NAV_ITEMS" block />
</div>
<!-- ===== 文件视图 ===== -->
<template v-if="view === 'files'">
<!-- ===== 库视图 ===== -->
<template v-if="view === 'library'">
<div class="shrink-0 px-2 py-2">
<div class="relative">
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-xs" />
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-[11px]" />
<button
v-if="filter"
type="button"
@@ -320,7 +345,7 @@ async function rebuildIndex(): Promise<void> {
<X class="size-3" />
</button>
</div>
<p class="mt-1.5 px-0.5 text-[11px] text-muted-foreground">
<p class="mt-1.5 px-0.5 text-[10px] text-muted-foreground">
新建目标:<span class="text-fg-secondary">{{ targetLabel }}</span>
</p>
</div>
@@ -329,7 +354,7 @@ async function rebuildIndex(): Promise<void> {
<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>
<span class="text-[11px] text-muted-foreground">正在扫描库…</span>
</div>
<StateBlock
@@ -364,7 +389,7 @@ async function rebuildIndex(): Promise<void> {
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>
<span class="truncate text-xs">{{ item.entry.name }}</span>
<div class="ml-auto flex shrink-0 items-center gap-0.5 opacity-0 group-hover:opacity-100">
<button
@@ -388,44 +413,26 @@ async function rebuildIndex(): Promise<void> {
</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)" />
<!-- ===== 目录视图(本地文件系统) ===== -->
<DirectoryPanel v-else-if="view === 'directory'" class="min-h-0 flex-1" />
<!-- ===== 大纲视图 ===== -->
<MarkdownOutline
v-else-if="view === 'outline'"
class="min-h-0 flex-1"
:cursor-line="cursorLine"
@jump="emit('jump', $event)"
/>
<!-- ===== 最近视图 ===== -->
<RecentPanel v-else class="min-h-0 flex-1" />
<!-- ===== 双链视图 ===== -->
<BacklinksPanel
v-else
class="min-h-0 flex-1"
:rel-path="store.currentRelPath"
@open="emit('open', $event)"
@create="onLinkCreated"
<!--
右边缘拖拽手柄:4px 宽、贴住整条右边框(比边框线好点中),hover / 拖动时高亮。
拖动实时改宽,松手落盘 —— 与底部结果面板的高度拖拽同一套交互。
-->
<div
class="absolute inset-y-0 right-0 z-10 w-1 cursor-col-resize touch-none select-none transition-colors duration-150 hover:bg-primary/30"
:class="resizing && 'bg-primary/40'"
title="拖动调整侧栏宽度"
@pointerdown="onResizeStart"
@pointermove="onResizeMove"
@pointerup="onResizeEnd"
@pointercancel="onResizeEnd"
/>
</aside>
@@ -463,4 +470,4 @@ async function rebuildIndex(): Promise<void> {
<!-- 新建笔记(名称 + 模板) -->
<NewNoteDialog v-model:open="newNoteOpen" :dir-rel="selectedDir" @created="onCreated" />
</template>
</template>
+215
View File
@@ -0,0 +1,215 @@
<script setup lang="ts">
/**
* 双链图谱(P5-4):把 `editor_link_graph` 的内部链接边画成力导向图。
*
* 布局是**一次性计算**(不跑动画):简化 Fruchterman-Reingold 迭代若干轮后
* 归一化到 viewBox,再用静态 SVG 渲染。理由是图谱打开频率低、节点规模小,
* 省掉 requestAnimationFrame 循环能让组件保持「无副作用」、易于推理。
*
* 点击节点 → 打开对应笔记。当前笔记节点高亮。
*/
import { computed, onMounted } from 'vue'
import { Loader2, Share2 } from '@lucide/vue'
import { ScrollArea } from '@/components/ui/scroll-area'
import { StateBlock } from '@/components/common'
import { useEditorStore } from '@/stores/editorStore'
const emit = defineEmits<{ open: [relPath: string] }>()
const store = useEditorStore()
/** 节点上限:超过则只画前 N 个(避免 O(n²) 迭代在大库上卡住主线程) */
const NODE_LIMIT = 400
const WIDTH = 520
const HEIGHT = 520
const PADDING = 24
const ITERATIONS = 180
interface GNode {
id: string
label: string
x: number
y: number
deg: number
}
interface GEdge {
a: number
b: number
}
const layout = computed(() => {
const index = new Map<string, number>()
const nodes: GNode[] = []
const addNode = (id: string): number => {
const found = index.get(id)
if (found !== undefined) return found
if (nodes.length >= NODE_LIMIT) return -1
const label = (id.split('/').pop() ?? id).replace(/\.md$/i, '')
index.set(id, nodes.length)
nodes.push({ id, label, x: 0, y: 0, deg: 0 })
return nodes.length - 1
}
const edges: GEdge[] = []
for (const e of store.linkGraph) {
const a = addNode(e.from)
const b = addNode(e.to)
if (a < 0 || b < 0) continue
edges.push({ a, b })
nodes[a]!.deg += 1
nodes[b]!.deg += 1
}
if (!nodes.length) return { nodes: [], edges: [], truncated: false }
const n = nodes.length
// 初始环形布局
for (let i = 0; i < n; i++) {
const angle = (i / n) * Math.PI * 2
nodes[i]!.x = Math.cos(angle) * 200
nodes[i]!.y = Math.sin(angle) * 200
}
// 简化 FR:斥力 O(n²) + 沿边引力
const k = Math.sqrt((400 * 400) / Math.max(n, 1))
const temp0 = 80
for (let it = 0; it < ITERATIONS; it++) {
const temp = temp0 * (1 - it / ITERATIONS)
const dx = new Float64Array(n)
const dy = new Float64Array(n)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let vx = nodes[i]!.x - nodes[j]!.x
let vy = nodes[i]!.y - nodes[j]!.y
let d2 = vx * vx + vy * vy
if (d2 < 0.01) {
vx = 0.1 * (i - j) || 0.1
vy = 0.1
d2 = vx * vx + vy * vy
}
const d = Math.sqrt(d2)
const f = (k * k) / d
dx[i] += (vx / d) * f
dy[i] += (vy / d) * f
dx[j] -= (vx / d) * f
dy[j] -= (vy / d) * f
}
}
for (const e of edges) {
const vx = nodes[e.a]!.x - nodes[e.b]!.x
const vy = nodes[e.a]!.y - nodes[e.b]!.y
const d = Math.max(Math.sqrt(vx * vx + vy * vy), 0.01)
const f = (d * d) / k
dx[e.a] -= (vx / d) * f
dy[e.a] -= (vy / d) * f
dx[e.b] += (vx / d) * f
dy[e.b] += (vy / d) * f
}
for (let i = 0; i < n; i++) {
const len = Math.max(Math.sqrt(dx[i]! * dx[i]! + dy[i]! * dy[i]!), 0.001)
const step = Math.min(len, temp) / len
nodes[i]!.x += dx[i]! * step
nodes[i]!.y += dy[i]! * step
}
}
// 归一化到 viewBox(等比缩放 + 居中)
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
for (const nd of nodes) {
minX = Math.min(minX, nd.x)
minY = Math.min(minY, nd.y)
maxX = Math.max(maxX, nd.x)
maxY = Math.max(maxY, nd.y)
}
const scale = Math.min(
(WIDTH - PADDING * 2) / Math.max(maxX - minX, 1),
(HEIGHT - PADDING * 2) / Math.max(maxY - minY, 1)
)
const ox = (WIDTH - (maxX - minX) * scale) / 2 - minX * scale
const oy = (HEIGHT - (maxY - minY) * scale) / 2 - minY * scale
return {
nodes: nodes.map(nd => ({ ...nd, x: nd.x * scale + ox, y: nd.y * scale + oy })),
edges,
truncated: store.linkGraph.length > 0 && nodes.length >= NODE_LIMIT
}
})
const radius = (deg: number): number => Math.min(3 + deg * 1.2, 9)
const showLabels = computed(() => layout.value.nodes.length <= 60)
const isCurrent = (id: string): boolean => store.currentRelPath === id
onMounted(() => {
void store.loadLinkGraph()
})
</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">
<Share2 class="size-3" />
<span>双链图谱</span>
<span class="ml-auto tabular-nums">{{ layout.nodes.length }} 节点 · {{ layout.edges.length }} 边</span>
</div>
<div v-if="store.loadingGraph && !layout.nodes.length" 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="!layout.nodes.length"
variant="empty"
title="还没有双链"
description="在笔记里写 [[另一篇]] 建立链接,图谱会显示它们的关系"
:min-height="140"
/>
<ScrollArea v-else class="min-h-0 flex-1">
<div class="px-1.5 py-2">
<svg :viewBox="`0 0 ${WIDTH} ${HEIGHT}`" class="w-full select-none">
<line
v-for="(edge, i) in layout.edges"
:key="`e${i}`"
:x1="layout.nodes[edge.a]?.x"
:y1="layout.nodes[edge.a]?.y"
:x2="layout.nodes[edge.b]?.x"
:y2="layout.nodes[edge.b]?.y"
class="stroke-border"
stroke-width="1"
/>
<g
v-for="node in layout.nodes"
:key="node.id"
class="cursor-pointer"
@click="emit('open', node.id)"
>
<title>{{ node.id }}</title>
<circle
:cx="node.x"
:cy="node.y"
:r="radius(node.deg)"
:class="isCurrent(node.id) ? 'fill-primary' : 'fill-muted-foreground'"
/>
<text
v-if="showLabels"
:x="node.x"
:y="node.y - radius(node.deg) - 2"
text-anchor="middle"
class="fill-foreground"
font-size="9"
>
{{ node.label }}
</text>
</g>
</svg>
<p v-if="layout.truncated" class="px-1 pt-1 text-[11px] text-muted-foreground">
节点较多,仅显示前 {{ NODE_LIMIT }} 个。
</p>
</div>
</ScrollArea>
</div>
</template>
@@ -7,7 +7,7 @@
*
* # 当前标题怎么算
*
* 用编辑器的光标行号(由 `NotesWindow` 通过 props 传入)与标题行号比较,取
* 用编辑器的光标行号(由 `EditorWindow` 通过 props 传入)与标题行号比较,取
* 「最后一个行号 ≤ 光标行」的标题。**不用滚动位置**:Live Preview 下装饰会让
* 每行高度不一致,按像素反推当前标题很容易差一行,而光标位置是精确的。
*/
@@ -15,7 +15,7 @@ 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'
import { useEditorStore } from '@/stores/editorStore'
const props = defineProps<{
/** 编辑器当前光标所在行(1 起;0 = 未知) */
@@ -24,7 +24,7 @@ const props = defineProps<{
const emit = defineEmits<{ jump: [from: number] }>()
const store = useNotesStore()
const store = useEditorStore()
/** 最浅一级标题的层级(让缩进从 0 开始,而不是每篇都从 h2 缩进一档) */
const minLevel = computed(() =>
@@ -32,7 +32,7 @@ import {
SelectTrigger,
SelectValue
} from '@/components/ui/select'
import { useNotesStore } from '@/stores/notesStore'
import { useEditorStore } from '@/stores/editorStore'
const props = defineProps<{
open: boolean
@@ -45,7 +45,7 @@ const emit = defineEmits<{
created: [relPath: string]
}>()
const store = useNotesStore()
const store = useEditorStore()
const name = ref('')
const templateId = ref('')
const busy = ref(false)
@@ -4,7 +4,7 @@
*
* # 为什么在本地过滤而不是每次都查后端
*
* 库内笔记清单在打开面板时一次性取回(上限 1000 条,`notes_list_notes`),
* 库内笔记清单在打开面板时一次性取回(上限 1000 条,`editor_list_notes`),
* 之后的每一次按键都只是对这份内存清单做子串匹配。这样输入零延迟 —— 而「按关键词
* 找文件」本来就是模糊匹配,走 FTS5 反而会因为分词器把文件名切碎而给出意外结果
* (FTS 是给正文用的)。
@@ -20,8 +20,8 @@ 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'
import { useEditorStore } from '@/stores/editorStore'
import type { NoteSearchHit } from '@/types/editor'
const props = defineProps<{ open: boolean }>()
const emit = defineEmits<{
@@ -29,7 +29,7 @@ const emit = defineEmits<{
select: [relPath: string]
}>()
const store = useNotesStore()
const store = useEditorStore()
const keyword = ref('')
const active = ref(0)
const panelRef = ref<HTMLDivElement | null>(null)
@@ -0,0 +1,136 @@
<script setup lang="ts">
/**
* 最近记录面板(P3-6):最近文件 + 最近文件夹两份列表。
*
* 「文件」与「文件夹」**分开存**(`settings.json` 的 `recentFiles` / `recentFolders`):
* 两者用途不同(打开文档 vs 打开目录),混在一起会让「最近文件夹」被文件挤掉。
* 记录与笔记库解耦 —— 库可以换 / 删,历史不该跟着丢。
*
* 失效项(路径已不存在)灰显但仍可点击清理由此产生的困惑:点击会给出明确失败提示,
* 而不是静默什么都不做。
*/
import { computed } from 'vue'
import { ExternalLink, FileText, Folder, History } from '@lucide/vue'
import { toast } from 'vue-sonner'
import { ScrollArea } from '@/components/ui/scroll-area'
import { StateBlock } from '@/components/common'
import { useEditorStore } from '@/stores/editorStore'
import type { RecentEntry } from '@/types/editor'
const store = useEditorStore()
const files = computed(() => store.recentFiles)
const folders = computed(() => store.recentFolders)
async function openFile(entry: RecentEntry): Promise<void> {
try {
await store.openDoc(entry.path)
} catch (e) {
toast.error(`打开失败:${String(e)}`)
}
}
/**
* 打开一个「最近文件夹」:读目录 + **切到侧栏的「目录」视图**。
*
* 只 `openFolder` 是不够的 —— 它只把 `dirListing` 读进 store,而侧栏还停在「最近」页,
* 于是用户点了一下什么都「没发生」(同一个列表还在那儿)。切视图才是点击应有的反馈:
* 跳到本地文件夹侧栏,直接看到这棵目录树。
*
* 先 await 再切:目录列举是异步的,提前切会先渲染一帧空态。
*/
async function openFolder(entry: RecentEntry): Promise<void> {
try {
await store.openFolder(entry.path)
store.setSideView('directory')
} catch (e) {
toast.error(`打开文件夹失败:${String(e)}`)
}
}
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<StateBlock
v-if="!files.length && !folders.length"
variant="empty"
title="还没有最近记录"
description="打开过的文件与文件夹会出现在这里"
:min-height="160"
/>
<ScrollArea v-else class="min-h-0 flex-1">
<div class="px-1.5 py-2">
<!-- 最近文件 -->
<div v-if="files.length" class="mb-2">
<div class="flex h-6 items-center gap-1.5 px-1.5 text-[11px] font-medium text-muted-foreground">
<FileText class="size-3" />
<span>最近文件</span>
<button
type="button"
class="ml-auto text-muted-foreground hover:text-foreground"
@click="store.clearRecentFiles()"
>
清空
</button>
</div>
<div
v-for="entry in files"
:key="entry.path"
class="group flex h-7 w-full cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-left text-xs transition-colors duration-150 hover:bg-row-hover"
:class="entry.exists ? 'text-fg-secondary hover:text-foreground' : 'text-fg-disabled'"
:title="entry.path"
@click="openFile(entry)"
>
<FileText class="size-3.5 shrink-0 opacity-70" />
<span class="truncate">{{ entry.name }}</span>
<span v-if="!entry.exists" class="shrink-0 text-[10px]">(已失效)</span>
<button
type="button"
class="ml-auto rounded-sm p-0.5 opacity-0 group-hover:opacity-100 hover:bg-active"
title="在资源管理器中显示"
@click.stop="store.revealPath(entry.path)"
>
<ExternalLink class="size-3.5" />
</button>
</div>
</div>
<!-- 最近文件夹 -->
<div v-if="folders.length">
<div class="flex h-6 items-center gap-1.5 px-1.5 text-[11px] font-medium text-muted-foreground">
<Folder class="size-3" />
<span>最近文件夹</span>
<button
type="button"
class="ml-auto text-muted-foreground hover:text-foreground"
@click="store.clearRecentFolders()"
>
清空
</button>
</div>
<div
v-for="entry in folders"
:key="entry.path"
class="group flex h-7 w-full cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-left text-xs transition-colors duration-150 hover:bg-row-hover"
:class="entry.exists ? 'text-fg-secondary hover:text-foreground' : 'text-fg-disabled'"
:title="entry.path"
@click="openFolder(entry)"
>
<History class="size-3.5 shrink-0 opacity-70" />
<span class="truncate">{{ entry.name }}</span>
<span v-if="!entry.exists" class="shrink-0 text-[10px]">(已失效)</span>
<button
type="button"
class="ml-auto rounded-sm p-0.5 opacity-0 group-hover:opacity-100 hover:bg-active"
title="在资源管理器中显示"
@click.stop="store.revealPath(entry.path)"
>
<ExternalLink class="size-3.5" />
</button>
</div>
</div>
</div>
</ScrollArea>
</div>
</template>
@@ -0,0 +1,160 @@
<script setup lang="ts">
/**
* 带「历史下拉」的输入框(查找词 / 替换串 / 目录 / 过滤条件共用)。
*
* # 为什么不用 `ui/combobox`
*
* reka-ui 的 Combobox 是「可筛选下拉」,要接 `open` / `searchTerm` / `selected` 一整套
* 受控状态;而这里要的只是「点一下图标列出用过的值,点一条填回去」。手写这一层更直白,
* 也不会和输入框自身的 Enter(提交)语义打架。
*
* # 为什么改为「图标点击展开」而不是「聚焦即展开」
*
* 聚焦即展开的问题:Tab / 点击进入输入框(哪怕只想改一两个字符)都会弹一层历史,
* 视觉噪声大。改为输入框**右侧的历史图标**点击展开 / 再点收起 —— 历史是低频动作,
* 交给显式动作更安静。失焦即收起。
*
* # 三个交互细节
*
* - 图标用 `@mousedown.prevent`:阻止默认行为后输入框不会先失焦,点击才不会被
* 先触发的 blur 吞掉;
* - 列表项同样 `@mousedown.prevent`:点选时输入框不失焦,值直接填入;
* - **Enter 只负责提交**,不做「选中第一条」—— 搜索框里回车即搜索是既有习惯,
* 让下拉抢走这个键会很难受。
*/
import { computed, ref } from 'vue'
import { History, X } from '@lucide/vue'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'
const props = defineProps<{
modelValue: string
placeholder?: string
/** 历史条目(新的在前) */
history: string[]
disabled?: boolean
/** 透传给 `Input` 的 class(行高 / 内边距等由调用方决定) */
inputClass?: string
}>()
const emit = defineEmits<{
'update:modelValue': [value: string]
/** 回车:提交(父组件决定是「搜索」还是「替换」) */
submit: []
/** Shift+回车:反向提交(只有「查找」用得上,即「上一个」) */
submitBackwards: []
removeHistory: [value: string]
clearHistory: []
}>()
const inputRef = ref<InstanceType<typeof Input> | null>(null)
/** 历史下拉是否被**显式**打开(点右侧历史图标切换;聚焦不再自动展开) */
const manualOpen = ref(false)
/**
* 只在「输入框有内容」时按包含关系过滤,空框则列全部。
*
* 当前值本身要从列表里排除(否则刚提交过的词会自己冒出来挡着)。
*/
const items = computed(() => {
const query = props.modelValue.trim().toLowerCase()
const list = props.history.filter(h => h !== props.modelValue)
if (!query) return list
return list.filter(h => h.toLowerCase().includes(query))
})
const open = computed(() => manualOpen.value && !props.disabled && items.value.length > 0)
function toggleHistory(): void {
manualOpen.value = !open.value
}
function closeHistory(): void {
manualOpen.value = false
}
/** 聚焦并全选已有内容(打开卡片时用:直接输入即可覆盖)。 */
function focusAndSelect(): void {
inputRef.value?.focus()
inputRef.value?.element()?.select()
}
defineExpose({ focusAndSelect })
</script>
<template>
<!-- 宽度由调用方给:搜索 / 替换固定窄宽,目录与过滤条件撑满剩余空间 -->
<div class="relative min-w-0">
<Input
ref="inputRef"
:model-value="modelValue"
:placeholder="placeholder"
:disabled="disabled"
:class="[inputClass, 'pr-7']"
@update:model-value="emit('update:modelValue', String($event))"
@focus="manualOpen = false"
@blur="closeHistory"
@keydown.enter.exact.prevent="emit('submit')"
@keydown.shift.enter.exact.prevent="emit('submitBackwards')"
/>
<!-- 历史开关图标:显式动作展开 / 收起(聚焦不再自动弹层) -->
<button
type="button"
class="absolute top-1/2 right-1 -translate-y-1/2 rounded-sm p-0.5 transition-colors duration-150"
:class="open ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'"
:title="open ? '收起历史' : '展开历史'"
:disabled="disabled"
tabindex="-1"
@mousedown.prevent
@click="toggleHistory"
>
<History class="size-3" />
</button>
<!-- 历史下拉:绝对定位贴在输入框下方,宽度跟随输入框;列表用 ScrollArea 滚动 -->
<div
v-if="open"
class="absolute top-full left-0 z-40 mt-1 w-full rounded-md border border-border bg-popover p-0.5 shadow-md"
>
<div class="flex items-center gap-1 px-1.5 py-1 text-[10px] text-fg-disabled">
<History class="size-3" />历史
<button
type="button"
class="ml-auto rounded-sm px-1 transition-colors duration-150 hover:bg-hover hover:text-foreground"
title="清空这组历史"
@mousedown.prevent="emit('clearHistory')"
>
清空
</button>
</div>
<ScrollArea class="max-h-56">
<div class="pb-0.5">
<div
v-for="item in items"
:key="item"
class="group flex items-center gap-1 rounded-sm hover:bg-row-hover"
>
<button
type="button"
class="min-w-0 flex-1 truncate px-1.5 py-1 text-left font-mono text-[11px] text-fg-secondary transition-colors duration-150 group-hover:text-foreground"
:title="item"
@mousedown.prevent="emit('update:modelValue', item)"
>
{{ item }}
</button>
<button
type="button"
class="mr-1 shrink-0 rounded-sm p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-active"
title="从历史中删除"
@mousedown.prevent="emit('removeHistory', item)"
>
<X class="size-3" />
</button>
</div>
</div>
</ScrollArea>
</div>
</div>
</template>
@@ -0,0 +1,406 @@
<script setup lang="ts">
/**
* 目录 / 笔记库检索的底部结果面板(IDEA「Find in Path」工具窗的位置)。
*
* # 为什么从搜索卡片里搬出来
*
* 结果列表塞在悬浮卡片里有两个硬伤:卡片宽度有限(预览被截断得厉害),且卡片一关
* 结果就没了 —— 而「先搜完、再逐条点开看」才是这个功能的真实用法。搬到编辑区底部的
* 独立面板后,结果可以一直摆着,边看代码边点下一条。
*
* # 结果点开后会怎样
*
* 面板只管「导航」,不负责判重:命中来自磁盘扫描,文件此刻可能已被外部改动。行号越界
* 由 `EditorHost.jumpToLine` 夹取(跳到近似位置好过整块报错)。
*
* # 历史是「条件」不是「结果」
*
* 点历史条目 = 按原条件**重跑**(见 `editorSearchStore` 的注释)。因此在历史页把鼠标
* 悬在条目上会提示「点击重新检索」,避免用户误以为是快照。
*/
import { computed, ref, watch } from 'vue'
import { ChevronDown, ChevronRight, History, Loader2, RotateCw, SearchX, Trash2, X } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { StateBlock } from '@/components/common'
import { useEditorSearchStore, specToQuery, type SearchRecord } from '@/stores/editorSearchStore'
import type { PathSearchFileHits, PathSearchMatch } from '@/types/editor'
const emit = defineEmits<{
/** 打开文件并跳到某行某列 */
'open-file': [payload: { path: string; line: number; column: number }]
}>()
const store = useEditorSearchStore()
const tab = ref<'results' | 'history'>('results')
// ===== 上边缘拖拽调高 =====
//
// 用 Pointer Events + `setPointerCapture`:指针一旦被捕获,即使拖出面板/窗口边界也继续
// 收到 move 事件,不会出现「拖快了就丢手柄」的经典问题(用 mousemove 就得在 window 上
// 挂一堆全局监听与清理)。
const resizing = ref(false)
let dragStartY = 0
let dragStartHeight = 0
function onResizeStart(event: PointerEvent): void {
dragStartY = event.clientY
dragStartHeight = store.panelHeight
resizing.value = true
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
}
function onResizeMove(event: PointerEvent): void {
if (!resizing.value) return
// 往上拖 = 面板变高(clientY 越小越高)
store.setPanelHeight(dragStartHeight + (dragStartY - event.clientY))
}
function onResizeEnd(event: PointerEvent): void {
if (!resizing.value) return
resizing.value = false
;(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
store.persistPanelHeight()
}
/** 预览切片:切成「命中前 / 命中 / 命中后」三段(永远走插值,不用 v-html)。 */
function pieces(match: PathSearchMatch): Array<{ text: string; hit: boolean }> {
const chars = Array.from(match.preview)
const start = Math.max(0, Math.min(match.matchStart, chars.length))
const end = Math.max(start, Math.min(match.matchEnd, chars.length))
return [
{ text: chars.slice(0, start).join(''), hit: false },
{ text: chars.slice(start, end).join(''), hit: true },
{ text: chars.slice(end).join(''), hit: false }
]
}
const isCollapsed = (path: string): boolean => store.collapsed.includes(path)
// ===== 前端分段显示 =====
//
// 后端把全树命中总数统计完整(`total` 可能上万),但预览条数有上限(`returned`)。
// 就算只渲染 `returned` 条,几千行 DOM 也会让面板滚动卡顿 —— 这里每段只挂
// `PAGE_SIZE` 条,底部「显示更多」续一段;换一次检索结果就回到第一段。
/** 每段渲染的命中条数 */
const PAGE_SIZE = 200
const visibleCount = ref(PAGE_SIZE)
watch(
() => store.results,
() => {
visibleCount.value = PAGE_SIZE
}
)
/** 窗口内的文件切片:窗口耗尽即停,文件内剩余命中不渲染(数据都在,点开就有)。 */
const visibleFiles = computed<Array<{ file: PathSearchFileHits; shown: PathSearchMatch[] }>>(() => {
const r = store.results
if (!r) return []
let budget = visibleCount.value
const out: Array<{ file: PathSearchFileHits; shown: PathSearchMatch[] }> = []
for (const file of r.files) {
if (budget <= 0) break
const shown = file.matches.slice(0, budget)
out.push({ file, shown })
budget -= shown.length
}
return out
})
/** 还有多少条已回传但未渲染的命中(「显示更多」按钮的文案来源)。 */
const remainingCount = computed(() => {
const r = store.results
if (!r) return 0
return Math.max(0, r.returned - visibleCount.value)
})
function showMore(): void {
visibleCount.value += PAGE_SIZE
}
/** 命中数 / 文件数的汇总文案(`total` 是全树统计,不是回传数)。 */
const summary = computed(() => {
const r = store.results
if (!r) return ''
return `${r.total} 处命中 · ${r.totalFiles} 个文件`
})
/** 条件的可读摘要(历史列表与结果页眉都用它,避免两处格式漂移)。 */
function describe(record: {
dir: string
pattern: string
fileTypes: string | null
skipDirs: string
caseSensitive: boolean
wholeWord: boolean
regex: boolean
}): string {
const flags: string[] = []
if (record.caseSensitive) flags.push('Aa')
if (record.wholeWord) flags.push('W')
if (record.regex) flags.push('.*')
const parts = [`「${record.pattern}」`]
if (flags.length) parts.push(flags.join(' '))
if (record.fileTypes) parts.push(record.fileTypes)
return parts.join(' · ')
}
function relativeTime(at: number): string {
const diff = Date.now() - at
const minute = 60_000
if (diff < minute) return '刚刚'
if (diff < 60 * minute) return `${Math.floor(diff / minute)} 分钟前`
if (diff < 24 * 60 * minute) return `${Math.floor(diff / (60 * minute))} 小时前`
return new Date(at).toLocaleDateString()
}
function rerun(record: SearchRecord): void {
tab.value = 'results'
void store.rerunRecord(record.id)
}
/** 重跑当前结果(文件可能已被改动)。 */
function refresh(): void {
const record = store.records.find(r => r.id === store.activeId)
if (!record) return
void store.rerunRecord(record.id)
}
/** 直接以这条记录的条件拼查询串(用于 tooltip 展示搜索目标目录)。 */
function queryOf(record: SearchRecord): string {
return specToQuery(record).dir
}
</script>
<template>
<section
v-if="store.panelOpen"
class="flex shrink-0 flex-col bg-background"
:style="{ height: `${store.panelHeight}px` }"
>
<!--
上边缘:既是「编辑区 / 结果区」的分界线(主题色,够明显),也是拖拽调高的手柄。
手柄本身做厚一点(h-1.5)并带 hover/拖动高亮,否则 2px 的线很难点中。
-->
<div
class="group flex h-1.5 shrink-0 cursor-row-resize touch-none items-center justify-center border-t-2 border-primary/60 bg-primary/5 select-none transition-colors duration-150 hover:bg-primary/20"
:class="resizing && 'bg-primary/25'"
title="拖动调整结果面板高度"
@pointerdown="onResizeStart"
@pointermove="onResizeMove"
@pointerup="onResizeEnd"
@pointercancel="onResizeEnd"
>
<span class="h-0.5 w-10 rounded-full bg-primary/50 group-hover:bg-primary/80" />
</div>
<!-- 页眉:Tab + 当前条件 + 操作 -->
<div class="flex h-8 shrink-0 items-center gap-1 border-b border-border px-2">
<button
type="button"
class="rounded-sm px-2 py-0.5 text-xs transition-colors duration-150"
:class="
tab === 'results'
? 'bg-active font-medium text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
@click="tab = 'results'"
>
结果
</button>
<button
type="button"
class="flex items-center gap-1 rounded-sm px-2 py-0.5 text-xs transition-colors duration-150"
:class="
tab === 'history'
? 'bg-active font-medium text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
@click="tab = 'history'"
>
<History class="size-3" />历史
<span v-if="store.records.length" class="tabular-nums text-fg-disabled">
{{ store.records.length }}
</span>
</button>
<!-- 结果页眉:条件 + 汇总 + 重跑 -->
<template v-if="tab === 'results'">
<span v-if="store.searching" class="ml-2 flex items-center gap-1.5 text-[11px] text-muted-foreground">
<Loader2 class="size-3 animate-spin" />检索中…
</span>
<template v-else-if="store.error">
<span class="ml-2 min-w-0 truncate text-[11px] text-destructive">{{ store.error }}</span>
</template>
<template v-else-if="store.results">
<span class="ml-2 text-[11px] tabular-nums text-muted-foreground">{{ summary }}</span>
<span
v-if="store.results.truncated"
class="text-[11px] tabular-nums text-warning"
title="为避免拖慢界面,预览只回传了一部分;总数仍是全树统计"
>
(已回传前 {{ store.results.returned }} 条)
</span>
<span
class="ml-2 min-w-0 flex-1 truncate font-mono text-[10px] text-fg-disabled"
:title="store.records.find(r => r.id === store.activeId)?.dir ?? ''"
>
{{ store.records.find(r => r.id === store.activeId)?.dir ?? '' }}
</span>
</template>
</template>
<div class="ml-auto flex shrink-0 items-center gap-0.5">
<Button
v-if="tab === 'results' && store.activeId"
variant="ghost"
size="icon-sm"
title="按原条件重新检索(磁盘内容可能已变)"
@click="refresh"
>
<RotateCw class="size-3.5" />
</Button>
<Button
v-if="tab === 'history' && store.records.length"
variant="ghost"
size="icon-sm"
title="清空全部检索历史"
@click="store.clearRecords()"
>
<Trash2 class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="关闭结果面板" @click="store.panelOpen = false">
<X class="size-3.5" />
</Button>
</div>
</div>
<!-- ===== 结果页 ===== -->
<ScrollArea v-if="tab === 'results'" class="min-h-0 flex-1">
<div v-if="store.results?.files.length" class="px-1.5 py-1">
<div v-for="entry in visibleFiles" :key="entry.file.path">
<button
type="button"
class="flex w-full items-center gap-1.5 rounded-sm px-1.5 py-1 text-left transition-colors duration-150 hover:bg-row-hover"
:title="entry.file.path"
@click="store.toggleFile(entry.file.path)"
>
<component
:is="isCollapsed(entry.file.path) ? ChevronRight : ChevronDown"
class="size-3 shrink-0 opacity-60"
/>
<span class="truncate text-xs font-medium text-foreground">{{ entry.file.name }}</span>
<span
class="shrink-0 text-[10px] tabular-nums"
:class="entry.shown.length < entry.file.totalInFile ? 'text-warning' : 'text-muted-foreground'"
:title="entry.shown.length < entry.file.totalInFile ? `该文件共 ${entry.file.totalInFile} 处命中` : undefined"
>
{{ entry.shown.length < entry.file.totalInFile ? `${entry.shown.length} / ${entry.file.totalInFile}` : entry.file.totalInFile }}
</span>
<span class="ml-auto min-w-0 truncate pl-2 text-[10px] text-fg-disabled">
{{ entry.file.path }}
</span>
</button>
<template v-if="!isCollapsed(entry.file.path)">
<button
v-for="match in entry.shown"
:key="`${entry.file.path}:${match.line}:${match.column}`"
type="button"
class="flex w-full items-center gap-2 rounded-sm py-0.5 pr-1.5 pl-6 text-left transition-colors duration-150 hover:bg-row-hover"
@click="emit('open-file', { path: entry.file.path, line: match.line, column: match.column })"
>
<span class="w-10 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground">
{{ match.line }}
</span>
<span
class="min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-pre font-mono text-[11px] text-fg-secondary"
>
<template v-for="(piece, index) in pieces(match)" :key="index">
<mark
v-if="piece.hit"
class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text"
>{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</button>
</template>
</div>
<!-- 分段续读:已回传的命中分页渲染,点一次多挂 PAGE_SIZE 条 -->
<button
v-if="remainingCount > 0"
type="button"
class="mx-1.5 my-1 flex w-[calc(100%-12px)] items-center justify-center gap-1 rounded-sm border border-dashed border-border py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:border-primary/40 hover:bg-row-hover hover:text-foreground"
@click="showMore"
>
显示更多(剩余 {{ remainingCount }} 处)
</button>
</div>
<StateBlock
v-else-if="!store.searching && !store.error && store.results"
variant="empty"
title="没有匹配"
description="换个关键词或调整过滤条件再试"
:min-height="120"
/>
<StateBlock
v-else-if="!store.searching && !store.error"
variant="empty"
title="还没有检索结果"
description="在搜索栏选「目录」或「笔记库」范围,输入关键词后按回车"
:min-height="120"
/>
</ScrollArea>
<!-- ===== 历史页 ===== -->
<ScrollArea v-else class="min-h-0 flex-1">
<div v-if="store.records.length" class="flex flex-col px-1.5 py-1">
<div
v-for="record in store.records"
:key="record.id"
class="group flex items-center gap-2 rounded-sm px-1.5 py-1 transition-colors duration-150 hover:bg-row-hover"
>
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-2 text-left"
:title="`点击按原条件重新检索\n目录:${queryOf(record)}`"
@click="rerun(record)"
>
<SearchX class="size-3.5 shrink-0 opacity-60" />
<span class="min-w-0 flex-1 truncate text-xs text-fg-secondary group-hover:text-foreground">
{{ describe(record) }}
</span>
<span class="shrink-0 text-[10px] tabular-nums text-fg-disabled">
{{ record.hits }} 处 / {{ record.files }} 文件
</span>
<span class="w-16 shrink-0 text-right text-[10px] text-fg-disabled">
{{ relativeTime(record.at) }}
</span>
</button>
<button
type="button"
class="shrink-0 rounded-sm p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-active"
title="删除这条历史"
@click="store.removeRecord(record.id)"
>
<X class="size-3" />
</button>
</div>
</div>
<StateBlock
v-else
variant="empty"
title="还没有检索历史"
description="每次在目录 / 笔记库范围检索都会记下条件(只存条件,点击时重新检索)"
:min-height="120"
/>
</ScrollArea>
</section>
</template>
@@ -42,12 +42,12 @@ import {
SelectValue
} from '@/components/ui/select'
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
import { useNotesStore } from '@/stores/notesStore'
import { notesClient } from '../notesClient'
import { useEditorStore } from '@/stores/editorStore'
import { editorClient } from '../editorClient'
import { open } from '@tauri-apps/plugin-dialog'
import type { ConflictPolicy, SyncDirection } from '@/types/notes'
import type { ConflictPolicy, SyncDirection } from '@/types/editor'
const store = useNotesStore()
const store = useEditorStore()
/** 密码输入框(提交后立刻清空,不留内存态) */
const password = ref('')
@@ -113,7 +113,7 @@ async function clearPassword(): Promise<void> {
async function testConnection(): Promise<void> {
testing.value = true
try {
const result = await notesClient.testWebdav()
const result = await editorClient.testWebdav()
if (result.created.length) {
toast.success(`${result.message}(新建了 ${result.created.length} 层目录)`)
} else {
@@ -164,7 +164,7 @@ async function exportLocalSnapshot(): Promise<void> {
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
})
if (typeof dest !== 'string') return
const saved = await notesClient.exportSnapshotLocal(dest)
const saved = await editorClient.exportSnapshotLocal(dest)
toast.success(`快照已导出:${saved}`)
} catch (e) {
toast.error(`导出快照失败:${String(e)}`)
@@ -296,7 +296,7 @@ onMounted(() => {
<CardContent class="!px-4">
<p class="pb-2 text-xs text-muted-foreground">
同步以本地库为准:远端只接收推送与拉取,不作为工作目录。库内
<code class="font-mono">.notes/</code>(索引与同步基线)永不参与同步。
<code class="font-mono">.editor/</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">
+184
View File
@@ -0,0 +1,184 @@
/**
* Classic ASP(`<% ... %>` 内嵌 VBScript)与 ASP.NET(内嵌 C#)的流式语法。
*
* # 为什么要自己拼一层
*
* CM6 没有 ASP 语言包;`@codemirror/legacy-modes` 里只有 `xml`/`html`(标记段)与
* `vbscript`(含 ASP 变体 `vbScriptASP`)、`clike`(含 C#)这些**各自独立**的流式
* 模式。CodeMirror 5 时代靠 `htmlembedded` + `multiplexingMode` 把两者按定界符缝
* 在一起,而 CM6 的 legacy-modes **没有**搬运 multiplexingMode —— 于是这里补上这层
* 「按 `<%` / `%>` 切换子模式」的多路复用。两种 ASP 只有内层语言不同,共用同一套。
*
* # 为什么用流式(StreamLanguage)而不是 lezer
*
* `@codemirror/lang-html` 的 lezer 语法不接受 `<%`:`<` 之后 `%` 不是合法标签名,
* 会被解析成错误节点 —— 无法在其上叠加代码块。流式模式是唯一能复用现成实现的路径,
* 代价是放弃 lezer 的增量语法树。
*
* # 已知取舍(诚实记录,未做未提)
*
* - `<script>` / `<style>` 内部**不**内嵌 JS/CSS:那是 CM5 的 htmlmixed 才有的能力,
* legacy-modes 未提供。
* - 字符串字面量里的 `%>`(如 `x = "%>"`)会提前结束代码块 —— 与 CM5 的
* multiplexingMode 同样的行为,不做特殊处理。
* - 缩进只在标记段沿用 HTML 的规则;代码段每块重建状态,避免沿用上一块的缩进层级。
*/
import {
StreamLanguage,
type IndentContext,
type StreamParser,
type StringStream
} from '@codemirror/language'
import { csharp as csharpStreamMode } from '@codemirror/legacy-modes/mode/clike'
import { html as htmlStream } from '@codemirror/legacy-modes/mode/xml'
import { vbScriptASP } from '@codemirror/legacy-modes/mode/vbscript'
import type { Extension } from '@codemirror/state'
/** 子模式状态:legacy-modes 的状态是不透明对象,这里只保证能浅拷贝。 */
type SubState = Record<string, unknown>
/** 多路复用状态:当前由谁出 token,以及两个子模式各自的内部状态。 */
interface AspState {
/** html = 标记段;asp = `<% ... %>` 代码段;comment = `<%-- ... --%>` 注释段 */
mode: 'html' | 'asp' | 'comment'
/** html/xml 流式模式的状态 */
outer: SubState
/** 代码段流式模式的状态(每个 `<% ... %>` 块重新开一个) */
inner: SubState
}
// legacy-modes 的导出类型是 `StreamParser<unknown>`,这里收窄成可操作的形状
const htmlMode = htmlStream as unknown as StreamParser<SubState>
/** `<% ... %>` 内层:Classic ASP 用 VBScript(含下面的 `:` 误报修正) */
const vbMode = vbsStream()
/** `<% ... %>` 内层:ASP.NET 用 C#(legacy 词法器,理由见 `aspx()`) */
const csharpMode = csharpStreamMode as unknown as StreamParser<SubState>
/**
* VBScript 流式解析器(legacy-modes 的 `vbScript` 加一层**误报修正**)。
*
* 老式 vbscript 词法器把语句分隔符 `:`(VB 里既用于 `a = 1 : b = 2` 也用于 `Label:`)
* 判成 `error`,而 `@codemirror/language` 把 `error` 解析成 `invalid` 标签、兜底高亮
* 又给 invalid 配了红色 —— 结果每个 .vbs / .asp 里都会飘红。编辑器不是 linter,
* 这种误报比「不上色」更糟,因此在 token 层面统一降级为「无高亮」。
*
* 挂在 token 输出上而不是自己重写词法器:`:` 在词法器内部还会驱动状态机(缩进、
* `doInCurrentLine` 等),重写容易错;只改输出的样式名是零风险的。
*/
function vbsStream(): StreamParser<SubState> {
const inner = vbScriptASP as unknown as StreamParser<SubState>
return {
name: inner.name,
startState: unit => inner.startState?.(unit) ?? {},
copyState: state => inner.copyState?.(state) ?? { ...state },
token(stream: StringStream, state: SubState) {
const style = inner.token(stream, state)
return style === 'error' || style === 'invalid' ? null : style
},
indent: (state, textAfter, context) => inner.indent?.(state, textAfter, context) ?? null,
blankLine: (state, unit) => inner.blankLine?.(state, unit),
languageData: inner.languageData
}
}
const OPEN = '<%'
const CLOSE = '%>'
const COMMENT_OPEN = '--'
const COMMENT_CLOSE = '--%>'
function startSub(parser: StreamParser<SubState>): SubState {
return parser.startState?.(2) ?? {}
}
function createAsp(name: string, innerMode: StreamParser<SubState>): StreamParser<AspState> {
return {
name,
startState: () => ({
mode: 'html',
outer: startSub(htmlMode),
inner: startSub(innerMode)
}),
copyState: state => ({
mode: state.mode,
outer: htmlMode.copyState?.(state.outer) ?? { ...state.outer },
inner: innerMode.copyState?.(state.inner) ?? { ...state.inner }
}),
token(stream: StringStream, state: AspState) {
// `<%-- ... --%>`:ASP 注释,整段按注释着色
if (state.mode === 'comment') {
if (stream.match(COMMENT_CLOSE)) {
state.mode = 'html'
return 'meta'
}
// 未到行尾时至少吞掉一个字符(`skipTo` 命中则停在定界符之前)
if (!stream.skipTo(COMMENT_CLOSE)) stream.skipToEnd()
return 'comment'
}
// `<% ... %>`:交给内层语言。`%>` 必须在**委托之前**先判 —— VBScript 的运算符
// 集合不含 `%`,一旦让它先吃,`%` 会被当成 error 吞掉,块就再也关不上
if (state.mode === 'asp') {
if (stream.match(CLOSE)) {
state.mode = 'html'
return 'meta'
}
const before = stream.pos
const style = innerMode.token(stream, state.inner)
if (stream.pos === before) stream.next() // 兜底:保证流一定前进
return style
}
// 标记段:先看是不是 `<%` 开头的代码块,否则原样交给 html 流式模式
if (stream.match(OPEN)) {
if (stream.match(COMMENT_OPEN)) {
state.mode = 'comment'
return 'comment'
}
// `<%@ ... %>` 是页面指令(Language / CodePage 等)。把 `@` 一并按 meta 吃掉,
// 否则内层语言会把它判成 error,在每页首行留一个红点
stream.match('@')
state.mode = 'asp'
state.inner = startSub(innerMode) // 每块独立状态:块间缩进不互相污染
return 'meta'
}
return htmlMode.token(stream, state.outer)
},
indent(state: AspState, textAfter: string, context: IndentContext): number | null {
if (state.mode === 'html') return htmlMode.indent?.(state.outer, textAfter, context) ?? null
return null
},
languageData: htmlMode.languageData
}
}
/** Classic ASP(`.asp` / `.asa`):`<% %>` 内是 VBScript。 */
export function asp(): Extension {
return StreamLanguage.define(createAsp('asp', vbMode))
}
/**
* 独立 VBScript(`.vbs`):不套 HTML 多路复用,直接用修正过误报的流式解析。
*
* 放在这里而不是在 `languages.ts` 里直接 `StreamLanguage.define(vbScriptASP)`,
* 是为了和 ASP 共用同一份修正(`vbsStream()`),避免两处行为漂移。
*/
export function vbs(): Extension {
return StreamLanguage.define(vbMode)
}
/**
* ASP.NET(`.aspx` / `.ascx` / `.ashx` …):`<% %>` 内通常是 C#。
*
* 内层用的是 legacy-modes 的 C# **词法器**,而不是 `.cs` 文件用的
* `@replit/codemirror-lang-csharp` —— 后者是 lezer 语法,没法塞进流式多路复用里。
* 取舍:`.aspx` 内联代码块的精度弱于 `.cs` 文件,但 HTML 结构与代码块都能着色,
* 好过整篇按纯文本 / 把 `<% %>` 当 HTML 错误节点处理。
*/
export function aspx(): Extension {
return StreamLanguage.define(createAsp('aspx', csharpMode))
}
@@ -36,9 +36,9 @@ import {
defaultHighlightStyle
} from '@codemirror/language'
import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search'
import { highlightSelectionMatches, search } from '@codemirror/search'
import { notesKeymap } from './keymap'
import { editorKeymap } from './keymap'
import { markdownLivePreview } from './markdownLivePreview'
import { editorTypography, resolveEditorTheme } from './themes'
import { wikilinkExtension, type WikilinkHandlers } from './wikilink'
@@ -103,7 +103,12 @@ const baseExtensions: Extension = [
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
highlightActiveLine(),
highlightSelectionMatches(),
// `highlightSelectionMatches` 在 heavyExtensions 里:它随选区变化全量扫描,
// 大文件中是可感知的输入延迟来源,跟折叠 / 补全一起降载
// 搜索状态 + 命中高亮。这里**只**引入状态字段,不绑 `searchKeymap`:
// 自带搜索面板已由统一搜索器(EditorSearch.vue)取代,Ctrl+F 由窗口级按键接管,
// 面板只在显式 `openSearchPanel` 时才出现 —— 于是它永远不会出现。
search(),
rectangularSelection(),
crosshairCursor(),
// 兜底高亮:自建主题自带 HighlightStyle,但 Stream/未知语言可能没有对应标签,
@@ -115,7 +120,13 @@ const baseExtensions: Extension = [
/** 重扩展(大文件时全部关闭)。 */
function heavyExtensions(config: EditorConfig): Extension {
if (config.largeFile) return []
const parts: Extension[] = [bracketMatching(), foldGutter()]
const parts: Extension[] = [
bracketMatching(),
foldGutter(),
// 选区匹配高亮(所有选区出现处/全文档同词)每次选区变化都要全量扫描,
// 大文件里选中一段文字就能把输入拖出可感知的延迟 —— 归入重扩展
highlightSelectionMatches()
]
if (config.autocomplete) parts.push(closeBrackets())
return parts
}
@@ -172,10 +183,9 @@ export function createEditorState(options: {
heavyCompartment.of(c.heavy),
wikilinkCompartment.of(c.wikilink),
keymap.of([
...notesKeymap,
...editorKeymap,
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...foldKeymap,
indentWithTab
@@ -18,7 +18,7 @@
* 缓存不主动失效:用户替换了同名图片的场景很罕见,而「每 3 秒清一次缓存」会让
* 滚动长文档时反复读盘。切库时由 `resetImageCache()` 清空。
*/
import { notesClient } from '../notesClient'
import { editorClient } from '../editorClient'
/** 缓存:库内相对路径 → data URL(`null` = 已确认不可预览) */
const cache = new Map<string, string | null>()
@@ -39,7 +39,7 @@ export function cachedImage(relPath: string): string | null | undefined {
/**
* 解析 Markdown 图片目标为「库内相对路径」。
*
* 规则与 `notes_read_asset` 的安全模型一致:
* 规则与 `editor_read_asset` 的安全模型一致:
* - 绝对 URL(`http://` / `https://` / `data:`)→ `null`(外链不内联,交给浏览器);
* - 以 `/` 开头 → 视为**库根相对**路径;
* - 其余 → 相对当前笔记所在目录解析,支持 `./` 与 `../`。
@@ -86,7 +86,7 @@ export async function fetchImage(relPath: string): Promise<string | null> {
const pending = inflight.get(relPath)
if (pending) return pending
const task = notesClient
const task = editorClient
.readAsset(relPath)
.then(value => {
cache.set(relPath, value)
@@ -106,7 +106,7 @@ const insertCodeBlock: Command = view => {
}
/** 编辑器快捷键(优先级高于全局快捷键)。 */
export const notesKeymap: KeyBinding[] = [
export const editorKeymap: KeyBinding[] = [
{ key: 'Mod-b', run: wrapSelection('**'), preventDefault: true },
{ key: 'Mod-i', run: wrapSelection('*'), preventDefault: true },
{ key: 'Mod-Shift-x', run: wrapSelection('~~'), preventDefault: true },
@@ -122,7 +122,7 @@ export const notesKeymap: KeyBinding[] = [
]
/** 供工具栏按钮调用的命令集合。 */
export const notesCommands = {
export const editorCommands = {
bold: wrapSelection('**'),
italic: wrapSelection('*'),
strikethrough: wrapSelection('~~'),
+461
View File
@@ -0,0 +1,461 @@
/**
* 语言支持:扩展名 → 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` 这类扩展名(以及一大批我们想要的别名)。手写表虽然
* 啰嗦,但**行为完全可预期**:前端没有「这个扩展名到底映射到哪个语言」的推理,
* 只有一张查表。
*
* # 围栏代码块的内嵌高亮(P5-3)
*
* `markdown({ codeLanguages })` 接受 language-data 的语言清单,让 ```rust 这类
* 围栏代码块按 info 串内嵌高亮。清单本身要异步 `import()`,而 `markdown()` 是同步
* 构建设置的 —— 解法是把整个 markdown 加载器变成异步(`LanguageLoader` 本就允许
* 返回 Promise,`EditorHost.applyLanguage` 会 await),因此没有额外抖动。
*
* # 第三方语言包
*
* 官方 lezer 包(`@codemirror/lang-*`)之外的缺口,按需引入:
* - `@replit/codemirror-lang-csharp`:C#(npm 上没有官方 `@codemirror/lang-csharp`);
* - `@replit/codemirror-lang-svelte`、`codemirror-lang-elixir`、`codemirror-lang-makefile`:
* 这三个语言在 legacy-modes 里没有可用模式,只能靠社区包;
* - 其余全部走 `@codemirror/legacy-modes` 的流式解析(`StreamLanguage`)。
*
* # 未内置的语言
*
* 表格之外的一律退回纯文本(不加载任何扩展)。
* - `Dockerfile` / `Containerfile` / `Makefile` / `Gemfile` 等:按完整文件名匹配;
* - `.asp` / `.aspx`:没有现成语言包,用自建的多路复用(HTML + 代码块),见 `aspMode.ts`;
* - 其余未知扩展名:纯文本。
*
* 统一原则:宁可「没高亮但能正常编辑」,也不要「高亮错乱」。
*/
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
import { StreamLanguage } from '@codemirror/language'
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
}
/**
* 多扩展名 / 多文件名共用的条目。
*
* 同一个语言常被多个扩展名(或「扩展名 + 完整文件名」)映射,例如 Clojure 的
* `clj/cljs/cljc/edn`、F# 的 `fs/fsi/fsx`、ASP.NET 的 `aspx/ascx/ashx/asmx/asax`,
* 以及 Ruby / Groovy / CMake / Makefile 那种「扩展名 + 无扩展名的约定文件名」。
* 写成共享常量只保留一份 thunk,避免同一行 `import()` 复制四五遍。
*
* `const` 不像函数声明那样提升,因此这一块必须放在 `LOADERS` / `FILENAME_LOADERS` 之前。
*/
const SVELTE: LanguageEntry = {
label: 'Svelte',
load: () => import('@replit/codemirror-lang-svelte').then(m => m.svelte())
}
/** ASP.NET 页面 / 用户控件 / 处理器 / Web 服务 / 全局应用类(`<% %>` 内按 C# 处理) */
const ASPNET: LanguageEntry = {
label: 'ASP.NET',
load: () => import('./aspMode').then(m => m.aspx())
}
const RUBY: LanguageEntry = {
label: 'Ruby',
load: () => stream(() => import('@codemirror/legacy-modes/mode/ruby'), m => m.ruby)
}
const GROOVY: LanguageEntry = {
label: 'Groovy',
load: () => stream(() => import('@codemirror/legacy-modes/mode/groovy'), m => m.groovy)
}
const FSHARP: LanguageEntry = {
label: 'F#',
load: () => stream(() => import('@codemirror/legacy-modes/mode/mllike'), m => m.fSharp)
}
const CLOJURE: LanguageEntry = {
label: 'Clojure',
load: () => stream(() => import('@codemirror/legacy-modes/mode/clojure'), m => m.clojure)
}
const VERILOG: LanguageEntry = {
label: 'Verilog',
load: () => stream(() => import('@codemirror/legacy-modes/mode/verilog'), m => m.verilog)
}
const FORTRAN: LanguageEntry = {
label: 'Fortran',
load: () => stream(() => import('@codemirror/legacy-modes/mode/fortran'), m => m.fortran)
}
const COMMON_LISP: LanguageEntry = {
label: 'Lisp',
load: () => stream(() => import('@codemirror/legacy-modes/mode/commonlisp'), m => m.commonLisp)
}
const CMAKE: LanguageEntry = {
label: 'CMake',
load: () => stream(() => import('@codemirror/legacy-modes/mode/cmake'), m => m.cmake)
}
const MAKEFILE: LanguageEntry = {
label: 'Makefile',
load: () => import('codemirror-lang-makefile').then(m => m.makefile())
}
/**
* 扩展名(小写,不含点)→ 语言。
*
* 值写成 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()) },
svelte: SVELTE,
html: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
htm: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
// Handlebars 本质是 HTML + `{{ }}` 插值,没有专门语言包,按 HTML 着色
hbs: { label: 'Handlebars', load: () => import('@codemirror/lang-html').then(m => m.html()) },
handlebars: { label: 'Handlebars', load: () => import('@codemirror/lang-html').then(m => m.html()) },
// Classic ASP:`<% %>` 内是 VBScript。没有现成语言包,用自建的多路复用,见 `aspMode.ts`
asp: { label: 'ASP', load: () => import('./aspMode').then(m => m.asp()) },
asa: { label: 'ASP', load: () => import('./aspMode').then(m => m.asp()) },
aspx: ASPNET,
ascx: ASPNET,
ashx: ASPNET,
asmx: ASPNET,
asax: ASPNET,
css: { label: 'CSS', load: () => import('@codemirror/lang-css').then(m => m.css()) },
scss: { label: 'SCSS', load: () => import('@codemirror/lang-sass').then(m => m.sass()) },
sass: {
label: 'Sass',
load: () => import('@codemirror/lang-sass').then(m => m.sass({ indented: true }))
},
less: { label: 'Less', load: () => import('@codemirror/lang-less').then(m => m.less()) },
// ===== 数据与配置 =====
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: xmlLike('XML'),
svg: xmlLike('SVG'),
xhtml: xmlLike('XHTML'),
xsd: xmlLike('XML Schema'),
xsl: xmlLike('XSL'),
xslt: xmlLike('XSLT'),
xaml: xmlLike('XAML'),
plist: xmlLike('Property List'),
rss: xmlLike('RSS'),
atom: xmlLike('Atom'),
wsdl: xmlLike('WSDL'),
// .NET / MSBuild 生态:工程文件与资源配置本质都是 XML
csproj: xmlLike('MSBuild'),
vbproj: xmlLike('MSBuild'),
fsproj: xmlLike('MSBuild'),
props: xmlLike('MSBuild'),
targets: xmlLike('MSBuild'),
nuspec: xmlLike('NuGet'),
resx: xmlLike('ResX'),
config: xmlLike('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()) },
php: { label: 'PHP', load: () => import('@codemirror/lang-php').then(m => m.php()) },
phtml: { label: 'PHP', load: () => import('@codemirror/lang-php').then(m => m.php()) },
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# 用社区 lezer 包:npm 上没有官方 `@codemirror/lang-csharp`,官方
// `@codemirror/language-data` 自己也是退回 legacy-modes 的 clike 词法器 —— 那个精度
// 明显不如真正的语法分析(拿不到类型/方法定义等语义标签),所以这里换第三方包
cs: { label: 'C#', load: () => import('@replit/codemirror-lang-csharp').then(m => m.csharp()) },
kt: { label: 'Kotlin', load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.kotlin) },
kts: { label: 'Kotlin', load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.kotlin) },
scala: { label: 'Scala', load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.scala) },
sc: { label: 'Scala', load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.scala) },
dart: { label: 'Dart', load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.dart) },
// `.mm` = Objective-C++(`.m` 语义歧义太大 —— MATLAB / Mathematica / Objective-C 都用它,不猜)
mm: {
label: 'Objective-C++',
load: () => stream(() => import('@codemirror/legacy-modes/mode/clike'), m => m.objectiveCpp)
},
groovy: GROOVY,
gradle: GROOVY,
fs: FSHARP,
fsi: FSHARP,
fsx: FSHARP,
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()) },
// ===== 脚本与配置(经 legacy-modes 的流式解析,P5-1) =====
sh: { label: 'Shell', load: () => stream(() => import('@codemirror/legacy-modes/mode/shell'), m => m.shell) },
bash: { label: 'Shell', load: () => stream(() => import('@codemirror/legacy-modes/mode/shell'), m => m.shell) },
zsh: { label: 'Shell', load: () => stream(() => import('@codemirror/legacy-modes/mode/shell'), m => m.shell) },
ps1: {
label: 'PowerShell',
load: () => stream(() => import('@codemirror/legacy-modes/mode/powershell'), m => m.powerShell)
},
psm1: {
label: 'PowerShell',
load: () => stream(() => import('@codemirror/legacy-modes/mode/powershell'), m => m.powerShell)
},
// VBScript / VB.NET(与 ASP 同族,但独立文件按纯脚本高亮,不套 HTML 多路复用)。
// VBScript 用裹了一层词法修正的 vbScript(原版把语句分隔符 `:` 当 error 涂红)——
// 见 `vbsStream()` 注释;ASP 的多路复用内部复用了同一个修正版
vbs: { label: 'VBScript', load: () => import('./aspMode').then(m => m.vbs()) },
vb: { label: 'VB.NET', load: () => stream(() => import('@codemirror/legacy-modes/mode/vb'), m => m.vb) },
toml: { label: 'TOML', load: () => stream(() => import('@codemirror/legacy-modes/mode/toml'), m => m.toml) },
ini: {
label: 'INI',
load: () => stream(() => import('@codemirror/legacy-modes/mode/properties'), m => m.properties)
},
cfg: {
label: 'INI',
load: () => stream(() => import('@codemirror/legacy-modes/mode/properties'), m => m.properties)
},
conf: {
label: 'INI',
load: () => stream(() => import('@codemirror/legacy-modes/mode/properties'), m => m.properties)
},
properties: {
label: 'INI',
load: () => stream(() => import('@codemirror/legacy-modes/mode/properties'), m => m.properties)
},
dockerfile: {
label: 'Dockerfile',
load: () => stream(() => import('@codemirror/legacy-modes/mode/dockerfile'), m => m.dockerFile)
},
// ===== 更多常见语言(全部经 legacy-modes 的流式解析) =====
//
// 这些语言在 npm 上都没有可用的 CM6 lezer 包(官方 `language-data` 对它们同样是
// 退回 legacy-modes)。统一原则不变:宁可「基础但可用」,也不要「精确但会错乱」。
rb: RUBY,
lua: { label: 'Lua', load: () => stream(() => import('@codemirror/legacy-modes/mode/lua'), m => m.lua) },
pl: { label: 'Perl', load: () => stream(() => import('@codemirror/legacy-modes/mode/perl'), m => m.perl) },
pm: { label: 'Perl', load: () => stream(() => import('@codemirror/legacy-modes/mode/perl'), m => m.perl) },
r: { label: 'R', load: () => stream(() => import('@codemirror/legacy-modes/mode/r'), m => m.r) },
swift: { label: 'Swift', load: () => stream(() => import('@codemirror/legacy-modes/mode/swift'), m => m.swift) },
jl: { label: 'Julia', load: () => stream(() => import('@codemirror/legacy-modes/mode/julia'), m => m.julia) },
ex: { label: 'Elixir', load: () => import('codemirror-lang-elixir').then(m => m.elixir()) },
exs: { label: 'Elixir', load: () => import('codemirror-lang-elixir').then(m => m.elixir()) },
erl: { label: 'Erlang', load: () => stream(() => import('@codemirror/legacy-modes/mode/erlang'), m => m.erlang) },
hrl: { label: 'Erlang', load: () => stream(() => import('@codemirror/legacy-modes/mode/erlang'), m => m.erlang) },
hs: { label: 'Haskell', load: () => stream(() => import('@codemirror/legacy-modes/mode/haskell'), m => m.haskell) },
clj: CLOJURE,
cljs: CLOJURE,
cljc: CLOJURE,
edn: CLOJURE,
elm: { label: 'Elm', load: () => stream(() => import('@codemirror/legacy-modes/mode/elm'), m => m.elm) },
d: { label: 'D', load: () => stream(() => import('@codemirror/legacy-modes/mode/d'), m => m.d) },
cr: { label: 'Crystal', load: () => stream(() => import('@codemirror/legacy-modes/mode/crystal'), m => m.crystal) },
coffee: {
label: 'CoffeeScript',
load: () => stream(() => import('@codemirror/legacy-modes/mode/coffeescript'), m => m.coffeeScript)
},
hx: { label: 'Haxe', load: () => stream(() => import('@codemirror/legacy-modes/mode/haxe'), m => m.haxe) },
pas: { label: 'Pascal', load: () => stream(() => import('@codemirror/legacy-modes/mode/pascal'), m => m.pascal) },
dpr: { label: 'Pascal', load: () => stream(() => import('@codemirror/legacy-modes/mode/pascal'), m => m.pascal) },
scm: { label: 'Scheme', load: () => stream(() => import('@codemirror/legacy-modes/mode/scheme'), m => m.scheme) },
ss: { label: 'Scheme', load: () => stream(() => import('@codemirror/legacy-modes/mode/scheme'), m => m.scheme) },
lisp: COMMON_LISP,
cl: COMMON_LISP,
el: COMMON_LISP,
tcl: { label: 'Tcl', load: () => stream(() => import('@codemirror/legacy-modes/mode/tcl'), m => m.tcl) },
cmake: CMAKE,
mk: MAKEFILE,
proto: {
label: 'Protocol Buffers',
load: () => stream(() => import('@codemirror/legacy-modes/mode/protobuf'), m => m.protobuf)
},
diff: { label: 'Diff', load: () => stream(() => import('@codemirror/legacy-modes/mode/diff'), m => m.diff) },
patch: { label: 'Diff', load: () => stream(() => import('@codemirror/legacy-modes/mode/diff'), m => m.diff) },
dtd: { label: 'DTD', load: () => stream(() => import('@codemirror/legacy-modes/mode/dtd'), m => m.dtd) },
v: VERILOG,
sv: VERILOG,
svh: VERILOG,
vhd: { label: 'VHDL', load: () => stream(() => import('@codemirror/legacy-modes/mode/vhdl'), m => m.vhdl) },
vhdl: { label: 'VHDL', load: () => stream(() => import('@codemirror/legacy-modes/mode/vhdl'), m => m.vhdl) },
f: FORTRAN,
for: FORTRAN,
f77: FORTRAN,
f90: FORTRAN,
f95: FORTRAN,
s: { label: 'Assembly', load: () => stream(() => import('@codemirror/legacy-modes/mode/gas'), m => m.gas) },
nsi: { label: 'NSIS', load: () => stream(() => import('@codemirror/legacy-modes/mode/nsis'), m => m.nsis) },
nsh: { label: 'NSIS', load: () => stream(() => import('@codemirror/legacy-modes/mode/nsis'), m => m.nsis) }
}
/**
* 按**完整文件名**(小写,不含路径)匹配的语言(无扩展名或需要整名匹配的场景)。
*/
const FILENAME_LOADERS: Record<string, LanguageEntry> = {
dockerfile: {
label: 'Dockerfile',
load: () => stream(() => import('@codemirror/legacy-modes/mode/dockerfile'), m => m.dockerFile)
},
containerfile: {
label: 'Dockerfile',
load: () => stream(() => import('@codemirror/legacy-modes/mode/dockerfile'), m => m.dockerFile)
},
// 约定文件名(无扩展名,按扩展名永远匹配不到)
makefile: MAKEFILE,
gnumakefile: MAKEFILE,
gemfile: RUBY,
rakefile: RUBY,
vagrantfile: RUBY,
jenkinsfile: GROOVY,
'cmakelists.txt': CMAKE,
// nginx 的配置文件名固定,但扩展名 `.conf` 已被 INI 占用 —— 只有整名匹配才不误判
'nginx.conf': {
label: 'Nginx',
load: () => stream(() => import('@codemirror/legacy-modes/mode/nginx'), m => m.nginx)
}
}
/**
* XML 家族共用一个语言条目(lang-xml 对 XML 各变体的解析是一致的,只有展示名不同)。
*
* 写成函数是为了不在表里重复十几遍同样的 `import()`;函数声明提升,因此放在
* `LOADERS` 之后也安全(`stream` 同此)。
*/
function xmlLike(label: string): LanguageEntry {
return { label, load: () => import('@codemirror/lang-xml').then(m => m.xml()) }
}
/**
* 用 legacy-modes 的流式解析构造扩展。
*
* StreamLanguage 的 token 名与 Lezer 高亮标签并非一一对应,但 `@codemirror/language`
* 的内置映射已覆盖常见 token;配合 `core.ts` 的 `defaultHighlightStyle` 兜底,
* 得到的是「可用的基础高亮」而非精确语义高亮。
*/
async function stream(
load: () => Promise<{ [key: string]: unknown }>,
pick: (mod: { [key: string]: unknown }) => unknown
): Promise<Extension> {
const mod = await load()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return StreamLanguage.define(pick(mod) as any)
}
/** 语言缓存:同一个语言只解析一次,之后复用已加载的扩展。 */
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()
}
/** 解析文件名对应的语言条目(先按完整文件名,再按扩展名)。 */
function resolveEntry(fileName: string): { key: string; entry: LanguageEntry } | null {
const base = (fileName.split(/[\\/]/).pop() ?? '').toLowerCase()
const byName = FILENAME_LOADERS[base]
if (byName) return { key: `fn:${base}`, entry: byName }
const ext = extensionOf(fileName)
const byExt = LOADERS[ext]
if (byExt) return { key: `ext:${ext}`, entry: byExt }
return null
}
/** 该文件名是否有内置语言支持。 */
export function hasLanguage(fileName: string): boolean {
return resolveEntry(fileName) !== null
}
/** 文件名对应的语言展示信息(无支持时返回「纯文本」)。 */
export function languageLabel(fileName: string): string {
return resolveEntry(fileName)?.entry.label ?? '纯文本'
}
/**
* 解析文件名对应的语言扩展。
*
* 返回 `null` 表示「没有内置语言」——调用方据此保持纯文本,而不是传空数组:
* 空数组与 `null` 在 Compartment 里语义相同,但 `null` 表达的是「本来就没有」,
* 而 `[]` 表达的是「有语言但选了无」,两者的日志与调试含义不同。
*/
export async function loadLanguage(fileName: string): Promise<Extension | null> {
const resolved = resolveEntry(fileName)
if (!resolved) return null
const cached = cache.get(resolved.key)
if (cached) return cached
const pending = Promise.resolve(resolved.entry.load()).catch(error => {
// 加载失败(离线 / chunk 404)时**不要**把失败的 promise 留在缓存里:
// 用户重连后再打开同一类型文件应当能成功
cache.delete(resolved.key)
throw error
})
cache.set(resolved.key, 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 {
// 返回 Promise(LanguageLoader 允许异步):内嵌代码块高亮需要 language-data 的
// 语言清单,而 `markdown()` 是同步构建设置的 —— 把清单的 `import()` 放到异步阶段,
// `EditorHost` 的 `applyLanguage` 本就会 await 语言加载器,因此没有额外抖动。
return async () => {
const { languages } = await import('@codemirror/language-data')
return markdown({
base: markdownLanguage,
extensions: GFM,
// ```rust 之类围栏代码块按 info 串匹配语言并内嵌高亮(P5-3)
codeLanguages: languages
})
}
}
@@ -51,7 +51,7 @@
* 3. 任何一步抛错都退化成「转义后的纯文本」,高亮失败绝不影响正文。
*
* 这里用 `highlight.js` 全量包(190+ 语言,同步可用,任何 info string 都有机会命中)。
* 代价是 NotesWindow chunk 变大:在 Tauri 里它从本地磁盘加载,换「```toml /
* 代价是 EditorWindow chunk 变大:在 Tauri 里它从本地磁盘加载,换「```toml /
* ```powershell / ```diff 也有高亮」是划算的。若哪天 chunk 预算吃紧,换成
* `highlight.js/lib/core` + 精选语言注册即可,其余逻辑一行都不用动。
*
@@ -85,7 +85,7 @@ export interface NoteHtmlInput {
* 是否对围栏代码块做语法高亮(默认 `true`)。
*
* 关掉它的场景是「打印」:黑白打印机上浅色 token 常常淡到看不见,而不上色至少是
* 稳定的黑字。对应设置项 `NoteSettings.exportHighlight`。
* 稳定的黑字。对应设置项 `EditorSettings.exportHighlight`。
*/
highlight?: boolean
}
File renamed without changes.
@@ -13,7 +13,7 @@
* - **配色**(本文件的 `createTheme` / `oneDark`):只负责颜色,是 CM6 的 `Extension`。
* - **排版**([`editorTypography`]):字体 / 字号 / 行高 / 连字,与配色独立可配。
*
* 主题 key 必须与 Rust 侧 `NoteSettings.editorTheme` 的取值保持一致,
* 主题 key 必须与 Rust 侧 `EditorSettings.editorTheme` 的取值保持一致,
* 否则用户选了主题却静默回落默认(终端模块踩过这个坑)。
*/
import { EditorView } from '@codemirror/view'
@@ -29,6 +29,21 @@ interface ThemeDefinition {
extension: Extension
}
/**
* 给一套主题的 TagStyle 补上**元信息**配色(`<?xml ?>`、`<!DOCTYPE>`、注解等)。
*
* `t.meta` 及其子标签(`processingInstruction` / `documentMeta` / `annotation`)原先在
* 自建主题里没有任何规则,于是落到 `defaultHighlightStyle` 的兜底色 `#404740` —— 深色
* 主题下几乎与背景同色,表现为「文件开头的 `<?xml ... ?>` 没有高亮」。这里统一补上,
* 取各主题的**关键字色**(VS Code 也把 XML 声明 / DOCTYPE 归入 `#569cd6` 这一族)。
*
* 追加在数组末尾不会影响既有规则:CM6 的 HighlightStyle 中靠前的规则优先,
* 而 `meta` 现有规则本就没有匹配项。
*/
function withMeta(styles: TagStyle[], color: string): TagStyle[] {
return [...styles, { tag: t.meta, color }]
}
const VSCODE_DARK: TagStyle[] = [
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#6a9955' },
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#569cd6' },
@@ -200,7 +215,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#cccccc',
gutterBorder: '#00000000'
},
styles: VSCODE_DARK
styles: withMeta(VSCODE_DARK, '#569cd6')
})
},
'vscode-light': {
@@ -219,7 +234,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#0b216f',
gutterBorder: '#00000000'
},
styles: VSCODE_LIGHT
styles: withMeta(VSCODE_LIGHT, '#0000ff')
})
},
'one-dark': {
@@ -242,7 +257,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#f8f8f2',
gutterBorder: '#00000000'
},
styles: DRACULA
styles: withMeta(DRACULA, '#ff79c6')
})
},
'solarized-dark': {
@@ -261,7 +276,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#93a1a1',
gutterBorder: '#00000000'
},
styles: SOLARIZED_DARK
styles: withMeta(SOLARIZED_DARK, '#859900')
})
},
'solarized-light': {
@@ -280,7 +295,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#586e75',
gutterBorder: '#00000000'
},
styles: SOLARIZED_LIGHT
styles: withMeta(SOLARIZED_LIGHT, '#859900')
})
},
'jetbrains-darcula': {
@@ -299,7 +314,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#a1a3a5',
gutterBorder: '#00000000'
},
styles: JETBRAINS_DARCULA
styles: withMeta(JETBRAINS_DARCULA, '#cc7832')
})
},
'intellij-light': {
@@ -318,7 +333,7 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#666666',
gutterBorder: '#00000000'
},
styles: INTELLIJ_LIGHT
styles: withMeta(INTELLIJ_LIGHT, '#0033b3')
})
},
'monokai-pro': {
@@ -337,11 +352,39 @@ export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
gutterActiveForeground: '#fcfcfa',
gutterBorder: '#00000000'
},
styles: MONOKAI_PRO
styles: withMeta(MONOKAI_PRO, '#ff6188')
})
}
}
/**
* 各主题(**实际生效名**)的编辑器底色。
*
* 用途:编辑器「外壳」容器(`.editor-host`)也要用同一底色 —— 否则 CM6 未绘制到的
* 区域(正文下方留白等)会透出窗口的 mica 背景,看起来「编辑器是透明的」。
*/
const THEME_BACKGROUNDS: Record<string, string> = {
'vscode-dark': '#1e1e1e',
'vscode-light': '#ffffff',
'one-dark': '#282c34',
dracula: '#282a36',
'solarized-dark': '#002b36',
'solarized-light': '#fdf6e3',
'jetbrains-darcula': '#2b2b2b',
'intellij-light': '#ffffff',
'monokai-pro': '#2d2a2e'
}
/** 求实际生效主题的编辑器底色(供编辑器外壳同步,避免窗口背景透出)。 */
export function editorBackground(
theme: string,
followAppTheme: boolean,
isDark: boolean
): string {
const name = effectiveThemeName(theme, followAppTheme, isDark)
return THEME_BACKGROUNDS[name] ?? THEME_BACKGROUNDS['vscode-dark']!
}
/** 设置页下拉选项(`system` 置于首位) */
export const EDITOR_THEME_OPTIONS: Array<{ value: string; label: string }> = [
{ value: 'system', label: '跟随应用' },
File renamed without changes.
+171
View File
@@ -0,0 +1,171 @@
/**
* 笔记模块的 IPC 客户端:命令名的**唯一落点**。
*
* # 为什么不直接在组件/ store 里写 `invoke('editor_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,
ContextMenuStatus,
DeleteReport,
DirListing,
ImportReport,
LibraryEntry,
LibraryInfo,
LinkEdge,
NoteBacklinks,
NoteDoc,
NoteFileDoc,
NoteIndexReport,
NoteIndexStats,
EditorSettings,
OpenTargetPayload,
PathSearchQuery,
PathSearchResult,
PathReplaceQuery,
PathReplaceResult,
SyncOutcome,
TemplateSource,
WebdavStatus,
WebdavTestResult
} from '@/types/editor'
import type { NoteSearchHit, NoteTemplate } from '@/types/editor'
export const editorClient = {
// ===== 设置 =====
getSettings: () => invoke<EditorSettings>('editor_get_settings'),
saveSettings: (settings: EditorSettings) =>
invoke<EditorSettings>('editor_save_settings', { settings }),
// ===== 库 =====
libraryInfo: () => invoke<LibraryInfo>('editor_library_info'),
setLibraryRoot: (root: string | null) => invoke<LibraryInfo>('editor_set_library_root', { root }),
scanLibrary: () => invoke<LibraryEntry[]>('editor_scan_library'),
readNote: (relPath: string) => invoke<NoteDoc>('editor_read_note', { relPath }),
saveNote: (relPath: string, content: string) =>
invoke<NoteDoc>('editor_save_note', { relPath, content }),
/**
* 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`,不存在则创建)。
*
* 「新建临时文件」用它:目录里的文件**不随应用退出删除**,由「关闭该文件时选择
* 保存 / 删除」收尾(见 `EditorWindow` 的草稿关闭流程)。
*/
scratchDir: () => invoke<string>('editor_scratch_dir'),
createNote: (dirRel: string, name: string, templateId?: string) =>
invoke<NoteDoc>('editor_create_note', { dirRel, name, templateId: templateId ?? null }),
createFolder: (dirRel: string, name: string) =>
invoke<null>('editor_create_folder', { dirRel, name }),
renameEntry: (relPath: string, newName: string) =>
invoke<string>('editor_rename_entry', { relPath, newName }),
deleteEntry: (relPath: string) => invoke<null>('editor_delete_entry', { relPath }),
/** 打开(或创建)今天的日记 */
dailyNote: () => invoke<NoteDoc>('editor_daily_note'),
// ===== 索引与检索 =====
rebuildIndex: () => invoke<NoteIndexReport>('editor_rebuild_index'),
syncIndex: () => invoke<NoteIndexReport>('editor_sync_index'),
listNotes: (limit?: number) => invoke<NoteSearchHit[]>('editor_list_notes', { limit: limit ?? null }),
indexStats: () => invoke<NoteIndexStats>('editor_index_stats'),
/**
* 「在路径中查找」(Find in Path):对目录逐行做文本 / 正则检索。
*
* 与索引检索(`editor_search_notes`)解耦:这里直接扫盘,返回**行号 + 预览**,
* 支持正则 —— 统一搜索器的「当前目录 / 笔记库」两个范围走它。
*/
searchInPath: (query: PathSearchQuery) =>
invoke<PathSearchResult>('editor_search_in_path', { query }),
/**
* 「在路径中替换」(Replace in Path):把匹配结果**写回磁盘**。
*
* 破坏性操作,调用方必须先让用户确认。后端只处理合法 UTF-8 文件并保留 BOM / 换行,
* 非 UTF-8 与写入失败的文件会在 `skipped` 里逐个回报(不静默丢弃)。
*/
replaceInPath: (query: PathReplaceQuery) =>
invoke<PathReplaceResult>('editor_replace_in_path', { query }),
/** 一篇笔记的出链 / 入链 */
backlinks: (relPath: string) => invoke<NoteBacklinks>('editor_backlinks', { relPath }),
/** 全库链接图(已解析的内部链接边) */
linkGraph: () => invoke<LinkEdge[]>('editor_link_graph'),
/**
* 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
*
* 冷启动时 Rust 无法 `emit`(前端还没注册监听),因此改为前端主动取一次。
*/
takePendingFile: () => invoke<OpenTargetPayload | null>('editor_take_pending_file'),
// ===== 库外任意文件 =====
openFile: (path: string) => invoke<NoteFileDoc>('editor_open_file', { path }),
/** 以指定编码重新解码磁盘字节(切换编码用;不写回) */
redecodeFile: (path: string, encoding: string) =>
invoke<NoteFileDoc>('editor_redecode_file', { path, encoding }),
writeFile: (path: string, content: string, encoding: string, eol: string) =>
invoke<NoteFileDoc>('editor_write_file', { path, content, encoding, eol }),
/** 登记系统对话框选中的路径为「可写」(它不是经 `openFile` 打开的) */
authorizeFile: (path: string) => invoke<null>('editor_authorize_file', { path }),
/** 把 base64 图片写进库根 `assets/`,返回可插入 Markdown 的相对路径 */
writeAsset: (fileName: string, ext: string, dataBase64: string) =>
invoke<string>('editor_write_asset', { fileName, ext, dataBase64 }),
/**
* 把库内图片读成 `data:` URL(内联预览用)。
*
* 返回 `null` 表示「不适合预览」(非图片扩展名 / 超过大小上限)——
* 不是错误,调用方按普通文本渲染即可。
*/
readAsset: (relPath: string) => invoke<string | null>('editor_read_asset', { relPath }),
// ===== 模板(P2) =====
listTemplates: () => invoke<NoteTemplate[]>('editor_list_templates'),
/** 不带参数 = 把全部内置模板导出到库内 `templates/` */
addTemplate: (name?: string, body?: string) =>
invoke<string[]>('editor_add_template', { name: name ?? null, body: body ?? null }),
readTemplate: (templateId: string) =>
invoke<TemplateSource>('editor_read_template', { templateId }),
// ===== 导入 / 导出(P2) =====
import: (source: string, destDir: string) =>
invoke<ImportReport>('editor_import', { source, destDir }),
/** 把渲染好的 HTML 写到用户选定的位置(渲染在前端,落盘在后端) */
exportNote: (relPath: string, html: string, dest: string) =>
invoke<string>('editor_export_note', { relPath, html, dest }),
exportZip: (dest: string, dirRel?: string) =>
invoke<string>('editor_export_zip', { dest, dirRel: dirRel ?? null }),
exportSnapshotLocal: (dest?: string) =>
invoke<string>('editor_export_snapshot_local', { dest: dest ?? null }),
// ===== WebDAV(P2) =====
webdavStatus: () => invoke<WebdavStatus>('editor_webdav_status'),
setWebdavPassword: (password: string) =>
invoke<null>('editor_set_webdav_password', { password }),
testWebdav: () => invoke<WebdavTestResult>('editor_test_webdav'),
syncNow: () => invoke<SyncOutcome>('editor_sync_now'),
backupNow: () => invoke<BackupReport>('editor_backup_now'),
listBackups: () => invoke<BackupSnapshot[]>('editor_list_backups'),
restoreBackup: (name: string) => invoke<ImportReport>('editor_restore_backup', { name }),
// ===== 本地目录(P3-5,操作用户真实文件系统) =====
readDir: (path: string) => invoke<DirListing>('editor_read_dir', { path }),
createFile: (dir: string, name: string) => invoke<string>('editor_create_file', { dir, name }),
createDir: (dir: string, name: string) => invoke<string>('editor_create_dir', { dir, name }),
renamePath: (path: string, newName: string) =>
invoke<string>('editor_rename_path', { path, newName }),
/** 移动到目标目录下 */
movePath: (path: string, destDir: string) =>
invoke<string>('editor_move_path', { path, destDir }),
deletePath: (paths: string[]) => invoke<DeleteReport>('editor_delete_path', { paths }),
// ===== 系统集成(P4-4,HKCU 右键菜单) =====
contextMenuStatus: () => invoke<ContextMenuStatus>('editor_context_menu_status'),
registerContextMenu: () => invoke<ContextMenuStatus>('editor_register_context_menu'),
unregisterContextMenu: () => invoke<ContextMenuStatus>('editor_unregister_context_menu')
}
+46
View File
@@ -0,0 +1,46 @@
import type { ModuleConfig } from '@/types/module'
import type { SearchIndexItem } from '@/stores/searchIndex'
/**
* 全局搜索索引(本模块无内部 Tab,`tab` 一律省略 —— 搜索后直接落在模块页)。
*/
const searchItems: SearchIndexItem[] = [
{
title: '编辑器',
description: '通用文本 / 代码编辑器:Markdown 实时预览、多编码、本地目录与笔记库',
keywords: ['编辑器', 'editor', 'notepad', '文本', '代码', 'markdown', 'md', '笔记', 'notes']
},
{
title: '打开编辑器',
description: '在新窗口中打开文件 / 笔记(可多开)',
keywords: ['打开', '编辑器', '窗口', '独立窗口', 'editor', '文件', '打开文件']
},
{
title: '打开文件夹',
description: '在编辑器的本地目录面板中打开一个文件夹',
keywords: ['打开', '文件夹', '目录', '目录树', 'folder', 'directory']
},
{
title: '新建笔记',
description: '在笔记库中新建一篇 Markdown 笔记',
keywords: ['新建', '新建笔记', 'new', '创建', 'create']
},
{
title: '编辑器设置',
description: '库根目录、编辑器主题、字体字号、编码、自动保存',
keywords: ['设置', '主题', '字体', '字号', '库目录', '库根', '编码', '自动保存', 'vscode', 'darcula']
}
]
export const moduleConfig: ModuleConfig = {
id: 'editor',
name: '编辑器',
icon: 'editor',
description: '通用文本 / 代码编辑器(Markdown 实时预览 + 多语言高亮 + 本地目录 + 笔记库)',
category: 'tool',
defaultEnabled: true,
loader: () => import('./EditorModule.vue'),
searchItems,
// 默认排在终端(40)之后
order: 45
}
@@ -1,15 +1,15 @@
/**
* 笔记「独立窗口」的创建入口(由前端创建,范式同 terminal/openWindow.ts)。
*
* - label 前缀 `notes-window-` 命中 `capabilities/notes-window.json` 的 `notes-window-*` 授权;
* - label 前缀 `editor-window-` 命中 `capabilities/editor-window.json` 的 `editor-window-*` 授权;
* - **隐藏创建**:窗口初始底色是白的,而主题要等前端读 localStorage 后才应用 ——
* 直接显示会先闪一下纯白。由 NotesWindow.vue 应用完主题(含窗口效果)再自己 show;
* 直接显示会先闪一下纯白。由 EditorWindow.vue 应用完主题(含窗口效果)再自己 show;
* - **同目标判重聚焦**(规划 §8-Q1 选 (a)):窗口默认多开,但「同一个文件开两个窗口」
* 几乎总是误操作 —— 两个窗口各自自动保存,后写的会覆盖先写的。
*
* # label 里为什么是哈希而不是明文路径
*
* 判重需要「由目标反推出窗口 label」。用 `notes-window-<目标>` 最直观,但窗口 label
* 判重需要「由目标反推出窗口 label」。用 `editor-window-<目标>` 最直观,但窗口 label
* 会出现在系统任务栏与调试面板里,把绝对路径(含用户名、项目名)塞进去既不雅也
* 不必要。改用 FNV-1a 哈希:**同样稳定、可反推 label、但不泄露路径**。
* 哈希碰撞的后果只是「两个不同文件被当成同一个窗口」——32 位空间下这在单次会话里
@@ -18,12 +18,12 @@
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { createLogger } from '@/lib/logger'
import { WINDOWS } from '@/lib/constants'
import { useNotesStore } from '@/stores/notesStore'
import { useEditorStore } from '@/stores/editorStore'
const logger = createLogger('notes')
const logger = createLogger('editor')
/** label 前缀必须落在 `notes-window-*`(capability 的 glob)里 */
const LABEL_PREFIX = `${WINDOWS.notesWindow}-`
/** label 前缀必须落在 `editor-window-*`(capability 的 glob)里 */
const LABEL_PREFIX = `${WINDOWS.editorWindow}-`
/** FNV-1a 32 位哈希 → base36(稳定、短、无特殊字符)。 */
function hashTarget(target: string): string {
@@ -54,27 +54,32 @@ async function focusTarget(target: string): Promise<boolean> {
}
/**
* 打开一个笔记窗口。
* 打开一个编辑器窗口。
*
* @param options.relPath 可选:打开时直达的笔记(相对库根路径)
* @param options.path 可选:打开时直达的**库外文件**(绝对路径,供 P1 的「打开文件」用)
* @param options.path 可选:打开时直达的**库外文件**(绝对路径)
* @param options.folder 可选:打开时直达的**本地目录**(绝对路径,目录面板)
* @param options.dedupe 同一目标已开窗口时聚焦它(默认 true)
*/
export async function openNotesWindow(options?: {
export async function openEditorWindow(options?: {
relPath?: string
path?: string
folder?: 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)}`
: ''
const target = options?.relPath ?? options?.path ?? options?.folder ?? ''
const query = options?.relPath
? `?file=${encodeURIComponent(options.relPath)}`
: options?.path
? `?path=${encodeURIComponent(options.path)}`
: options?.folder
? `?folder=${encodeURIComponent(options.folder)}`
: ''
if (target && options?.dedupe !== false) {
// 「复用文档窗口」是可关闭的设置(默认开)。关掉时每次新建窗口 ——
// 有些用户确实想并排对照同一篇的不同位置。
const reuse = useNotesStore().settings.reuseWindow
const reuse = useEditorStore().settings.reuseWindow
if (reuse) {
const focused = await focusTarget(target)
if (focused) return
@@ -88,8 +93,8 @@ export async function openNotesWindow(options?: {
const finalLabel = taken ? `${label}-${Date.now().toString(36)}` : label
const win = new WebviewWindow(finalLabel, {
url: `index.html#${WINDOWS.notesWindow}${query}`,
title: '笔记',
url: `index.html#${WINDOWS.editorWindow}${query}`,
title: '编辑器',
width: 1200,
height: 800,
minWidth: 760,
@@ -105,7 +110,7 @@ export async function openNotesWindow(options?: {
})
win.once('tauri://error', e => {
logger.error(`打开笔记窗口失败:${String(e)}`)
logger.error(`打开编辑器窗口失败:${String(e)}`)
})
await new Promise<void>((resolve, reject) => {
+2 -2
View File
@@ -12,7 +12,7 @@ import {
Languages,
SquareTerminal,
Bot,
NotebookPen
FileCode2
} from '@lucide/vue'
/**
@@ -35,7 +35,7 @@ export const moduleIconMap: Record<string, Component> = {
translate: Languages,
terminal: SquareTerminal,
dsh: Bot,
notes: NotebookPen
editor: FileCode2
}
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
+2 -2
View File
@@ -14,7 +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'
import { moduleConfig as editor } from './editor'
const allModules: ModuleConfig[] = [
proxy,
@@ -29,7 +29,7 @@ const allModules: ModuleConfig[] = [
translate,
terminal,
dsh,
notes
editor
]
// 启动时注册所有模块
-525
View File
@@ -1,525 +0,0 @@
<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>
@@ -1,243 +0,0 @@
<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>
@@ -1,173 +0,0 @@
<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>
-175
View File
@@ -1,175 +0,0 @@
/**
* 语言支持:扩展名 → 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
})
}
-41
View File
@@ -1,41 +0,0 @@
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
}
-127
View File
@@ -1,127 +0,0 @@
/**
* 笔记模块的 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 })
}
+179 -12
View File
@@ -7,8 +7,8 @@ import { STORAGE_KEYS } from '@/lib/constants'
import { applyAccent, readStoredAccent } from '@/lib/theme'
import { Effect, EffectState } from '@tauri-apps/api/window'
import {
Globe, Power, PowerOff, RefreshCw, Check, Monitor, Download,
Settings, LogOut,
Globe, Power, PowerOff, RefreshCw, Check, Monitor, LogOut,
Play, Pause, SkipBack, SkipForward, Music, SquareTerminal, Bot, FileCode2,
} from '@lucide/vue'
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
@@ -28,6 +28,13 @@ interface TrayMenuState {
proxyCurrent: string | null
}
/** 音乐控制条状态(与 Rust `tray_menu::MusicState` 对应) */
interface MusicState {
playing: boolean
title: string
artist: string
}
const state = reactive<TrayMenuState>({
proxyRunning: false,
systemProxy: false,
@@ -36,6 +43,7 @@ const state = reactive<TrayMenuState>({
proxyNodes: [],
proxyCurrent: null,
})
const music = reactive<MusicState>({ playing: false, title: '', artist: '' })
const loadingAction = ref<string | null>(null)
const refreshing = ref(false)
const osdVisible = ref(false)
@@ -301,6 +309,43 @@ function handleSelectNode(name: unknown) {
}
}
// ===== 音乐控制条 =====
//
// 与普通菜单项不同:点音乐按钮**不关闭菜单**(用户常要连点下一首),
// 因此不走 handleAction(它会 hide 菜单 + 取消焦点),而是单独一条路径。
/** 拉取一次音乐状态(本地查询,开销极小) */
async function refreshMusic() {
try {
Object.assign(music, await invoke<MusicState>('tray_music_state'))
} catch { /* 忽略 */ }
}
async function handleMusicControl(action: 'toggle' | 'next' | 'prev') {
// 乐观翻转播放态:动作要经主窗口前端执行(异步),先改本地避免按钮有明显延迟;
// 真实值由 1s 轮询纠正
if (action === 'toggle') music.playing = !music.playing
try {
await invoke('tray_music_control', { action })
} catch { /* 忽略 */ }
}
/** 音乐状态轮询定时器(仅菜单可见时运行) */
let musicTimer: number | null = null
function startMusicPolling() {
void refreshMusic()
if (musicTimer !== null) return
musicTimer = window.setInterval(() => void refreshMusic(), 1000)
}
function stopMusicPolling() {
if (musicTimer !== null) {
window.clearInterval(musicTimer)
musicTimer = null
}
}
function delayText(delay: number | null): string {
if (delay === null) return '未测试'
if (delay === 0) return '超时'
@@ -451,6 +496,8 @@ onMounted(async () => {
osdVisible.value = readOsdVisible()
// 显示前重置上次残留的下拉/焦点状态(双保险)
resetMenuState()
// 音乐控制条:显示时拉一次并开始轮询(隐藏后停止,不做无谓后台查询)
startMusicPolling()
// 开始合并窗口:等待完整状态,结束时才显示
menuJustShown = Date.now()
window.clearTimeout(finalizeTimer)
@@ -462,7 +509,10 @@ onMounted(async () => {
// 菜单失焦(点击其他位置自动隐藏)时重置下拉框与焦点,避免下次打开时残留
unlistenFns.push(await getCurrentWindow().onFocusChanged(({ payload: focused }) => {
if (!focused) resetMenuState()
if (!focused) {
resetMenuState()
stopMusicPolling()
}
}))
// - 显示流程的合并窗口内:完整状态补充到达,仅合并数据,让 finalizeTimer 统一显示
@@ -481,6 +531,7 @@ onMounted(async () => {
})
onUnmounted(() => {
stopMusicPolling()
unlistenFns.forEach((fn) => fn())
})
</script>
@@ -488,6 +539,39 @@ onUnmounted(() => {
<template>
<div class="tray-menu-root flex flex-col" @keydown="onKeydown" tabindex="0">
<div class="tray-menu-scroll flex-1 min-h-0 overflow-y-auto">
<!-- 音乐控制条(代理之上):当前曲目 + 上一首/播放暂停/下一首 -->
<div class="tray-music">
<Music class="size-4 shrink-0 tray-music-icon" />
<div class="tray-music-text">
<span class="tray-music-title">{{ music.title || '未在播放' }}</span>
<span class="tray-music-artist">{{ music.artist || (music.title ? '未知歌手' : '') }}</span>
</div>
<div class="tray-music-actions">
<button
class="tray-music-btn"
:disabled="!music.title"
title="上一首"
@click="handleMusicControl('prev')"
>
<SkipBack class="size-4" />
</button>
<button class="tray-music-btn primary" title="播放 / 暂停" @click="handleMusicControl('toggle')">
<Pause v-if="music.playing" class="size-4" />
<Play v-else class="size-4" />
</button>
<button
class="tray-music-btn"
:disabled="!music.title"
title="下一首"
@click="handleMusicControl('next')"
>
<SkipForward class="size-4" />
</button>
</div>
</div>
<div class="tray-separator"></div>
<div class="tray-section">
<div class="tray-section-header">
<Globe class="size-4 text-primary" />
@@ -581,16 +665,17 @@ onUnmounted(() => {
<div class="tray-separator"></div>
<button class="tray-item" @click="handleAction('download_new')">
<Download class="size-4" />
<span>新建下载</span>
<button class="tray-item" @click="handleAction('terminal')">
<SquareTerminal class="size-4" />
<span>终端</span>
</button>
<div class="tray-separator"></div>
<button class="tray-item" @click="handleAction('settings')">
<Settings class="size-4" />
<span>常规设置</span>
<button class="tray-item" @click="handleAction('dsh')">
<Bot class="size-4" />
<span>dsh</span>
</button>
<button class="tray-item" @click="handleAction('editor')">
<FileCode2 class="size-4" />
<span>编辑器</span>
</button>
<button class="tray-item tray-quit" @click="handleAction('quit')">
<LogOut class="size-4" />
@@ -672,6 +757,88 @@ onUnmounted(() => {
opacity: 0.5;
}
/* ===== 音乐控制条(代理之上) ===== */
.tray-music {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border-radius: 6px;
}
.tray-music-icon {
color: var(--primary);
}
.tray-music-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1px;
}
.tray-music-title {
font-size: 12.5px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tray-music-artist {
font-size: 10.5px;
color: var(--muted-foreground);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
/* 没有歌手时也占位,避免切换曲目时控制条高度跳动 */
min-height: 13px;
}
.tray-music-actions {
display: flex;
align-items: center;
gap: 2px;
flex-shrink: 0;
}
.tray-music-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border: none;
border-radius: 5px;
background: transparent;
color: var(--foreground);
cursor: pointer;
transition: background 0.08s;
}
.tray-music-btn:hover:not(:disabled) {
background: var(--row-hover-veil);
}
.tray-music-btn:active:not(:disabled) {
background: var(--row-selected-veil);
}
.tray-music-btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.tray-music-btn svg {
color: currentColor;
}
.tray-music-btn.primary {
background: color-mix(in oklch, var(--primary) 14%, transparent);
color: var(--primary);
}
.tray-music-btn.primary:hover:not(:disabled) {
background: color-mix(in oklch, var(--primary) 22%, transparent);
}
.tray-item {
display: flex;
align-items: center;
+115
View File
@@ -396,6 +396,120 @@ export const useDshStore = defineStore('dsh', () => {
}
}
// ===== 托盘「dsh」:先开启动进度窗口,同步启动,就绪后切到界面 =====
/** 启动进度窗口尺寸(逻辑像素) */
const PROGRESS_W = 460
const PROGRESS_H = 300
/** 打开(或聚焦)dsh 启动进度窗口(单例) */
async function openProgressWindow() {
const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')
const label = WINDOWS.dshWindow
const existing = await WebviewWindow.getByLabel(label)
if (existing) {
await existing.show().catch(() => {})
await existing.setFocus().catch(() => {})
return
}
const win = new WebviewWindow(label, {
url: 'index.html#dsh-window',
title: 'dsh · 启动中',
width: PROGRESS_W,
height: PROGRESS_H,
minWidth: 380,
minHeight: 220,
resizable: false,
decorations: false,
shadow: true,
center: true,
// **隐藏创建**:由 DshWindow.vue 应用完主题(含底色)再自己 show,
// 否则深色模式下会先闪一个纯白窗口(同 NewTerminalWindow / EditorWindow)。
visible: false,
focus: false
})
win.once('tauri://error', e => {
toast.error(`打开 dsh 启动窗口失败:${String(e.payload ?? '')}`)
})
await new Promise<void>((resolve, reject) => {
win.once('tauri://created', () => resolve())
win.once('tauri://error', e => reject(new Error(String(e.payload ?? e))))
})
}
/** 关闭启动进度窗口(若存在) */
async function closeProgressWindow() {
const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')
const existing = await WebviewWindow.getByLabel(WINDOWS.dshWindow)
if (existing) await existing.close().catch(() => {})
}
/**
* 等待服务进入「可打开」状态(已监听 + 已抓到带令牌地址)。
*
* 用事件驱动(`dsh-server-state`:启动/就绪/抓到令牌/失败都会推)而不是轮询
* `dsh_env_status`——后者每次都会跑 `node --version` 探版本,2Hz 轮询代价过高。
* 返回拿到的状态;失败或超时返回 null(此时进度窗口会停在错误/等待上)。
*/
function waitForServerReady(timeoutMs: number): Promise<DshServerStatus | null> {
return new Promise(resolve => {
let done = false
let unlisten: UnlistenFn | null = null
const finish = (status: DshServerStatus | null) => {
if (done) return
done = true
unlisten?.()
window.clearTimeout(timer)
resolve(status)
}
const timer = window.setTimeout(() => finish(null), timeoutMs)
void listen<DshServerStatus>(EVENTS.dshServerState, e => {
server.value = e.payload
if (e.payload?.error) finish(null)
else if (e.payload?.ready && e.payload?.launchUrl) finish(e.payload)
}).then(un => {
unlisten = un
// 注册监听期间状态可能已经变化:补判一次,避免错过
if (done) return
if (canOpen.value) finish(server.value)
else if (server.value?.error) finish(null)
})
})
}
/**
* 托盘菜单「dsh」入口。
*
* - 已就绪(拿到带令牌地址):直接开界面;
* - 未启动 / 未就绪:**先开启动进度窗口**(独立画面里显示进度),
* 同步拉起服务,就绪后自动打开 Web 界面并关闭进度窗口。
*
* 进度画面的内容由窗口自己按状态渲染(见 DshWindow.vue),这里只负责编排。
*/
async function openFromTray() {
await refresh()
if (canOpen.value) {
await openWebWindow()
return
}
if (!envReady.value) {
toast.warning('dsh 尚未安装或 Node 环境不满足要求,请先在 dsh 模块完成安装')
return
}
await openProgressWindow()
if (!running.value) {
await start()
// 启动即失败(端口占用 / 进程立即退出等):原因已 toast,进度窗口也会显示,
// 无需再空等超时
if (server.value?.error) return
}
const ready = await waitForServerReady(60_000)
if (ready) {
await openWebWindow()
await closeProgressWindow()
}
}
/**
* 全局快捷键触发:服务已就绪直接开窗,否则给一次短暂等待。
*
@@ -536,6 +650,7 @@ export const useDshStore = defineStore('dsh', () => {
openDir,
openWebWindow,
openInBrowser,
openFromTray,
registerShortcut,
unregisterShortcut,
initGlobalShortcut,
+287
View File
@@ -0,0 +1,287 @@
/**
* 目录 / 笔记库检索的状态:结果、检索历史、底部结果面板。
*
* # 为什么单独一个 store(而不是留在 `EditorSearch.vue` 里)
*
* 检索这件事现在有**三个消费方**:搜索卡片(发起)、底部结果面板(展示)、状态栏按钮
* (开关面板 + 看历史)。状态放在卡片组件里的话,面板与状态栏都得靠 props/emit 层层
* 转手,而且卡片一关(`v-if`)状态就没了 —— 面板却还得继续显示上次的结果。
*
* # 历史只存**条件**,不存结果
*
* 记录里只有目录 / 关键词 / 选项 / 类型 / 跳过目录,外加一个「命中数快照」用于列表展示。
* 点一条历史就是**按原条件重跑一次**:磁盘一直在变,存下来的行号与预览几分钟就会失真,
* 而 1000 条命中(含预览)塞进 localStorage 也不合适。重跑换来的是「看到的永远是真的」。
*
* # 落 localStorage 而不是 settings.json
*
* 与编辑器会话同一姿态:这是窗口级的临时状态,跨窗口共享、重启后还在,但不需要进
* 模块设置、也不该被设置版本迁移牵连。
*/
import { defineStore } from 'pinia'
import { editorClient } from '@/modules/editor/editorClient'
import { createLogger } from '@/lib/logger'
import type { PathSearchQuery, PathSearchResult } from '@/types/editor'
const logger = createLogger('editor')
const STORAGE_KEY = 'thing_editor_search_records'
/** 历史条数上限(够回溯,又不至于把 localStorage 写满) */
const MAX_RECORDS = 30
/** 结果面板高度(px)落盘用的键 */
const HEIGHT_KEY = 'thing_editor_search_panel_height'
/** 面板高度夹取范围;上限还要按窗口高度动态收(见 `clampPanelHeight`) */
const MIN_PANEL_HEIGHT = 140
const MAX_PANEL_HEIGHT = 760
/** 编辑器至少留出的高度:拖到再高也不该把编辑区压没 */
const MIN_EDITOR_HEIGHT = 260
const DEFAULT_PANEL_HEIGHT = 280
/** 一条检索记录:**只有条件** + 用于列表展示的命中数快照。 */
export interface SearchRecord {
id: string
/** 检索根(绝对路径) */
dir: string
pattern: string
fileTypes: string | null
/** 空串 = 不跳过任何目录(与后端语义一致) */
skipDirs: string
caseSensitive: boolean
wholeWord: boolean
regex: boolean
/** 当时命中的行数 / 文件数(仅供历史列表显示,不代表现在仍然如此) */
hits: number
files: number
/** 检索时间(Unix 毫秒) */
at: number
}
function loadRecords(): SearchRecord[] {
try {
const raw = localStorage.getItem(STORAGE_KEY)
if (!raw) return []
const parsed = JSON.parse(raw) as unknown
if (!Array.isArray(parsed)) return []
return (parsed as SearchRecord[])
.filter(r => r && typeof r === 'object' && typeof r.pattern === 'string' && r.pattern.trim())
.slice(0, MAX_RECORDS)
} catch {
// 坏数据一律当空历史:搜索本身不该因为历史读不出来而不可用
return []
}
}
/** 一次检索的完整条件(历史记录去掉展示用字段后的那一部分)。 */
export type SearchSpec = Omit<SearchRecord, 'id' | 'hits' | 'files' | 'at'>
/** 把记录还原成后端请求。 */
export function specToQuery(spec: SearchSpec, limit = 1000): PathSearchQuery {
return {
dir: spec.dir,
pattern: spec.pattern,
caseSensitive: spec.caseSensitive,
wholeWord: spec.wholeWord,
regex: spec.regex,
limit,
fileTypes: spec.fileTypes,
skipDirs: spec.skipDirs
}
}
/** 面板高度按窗口与上下限夹取。 */
function clampPanelHeight(px: number): number {
const max = Math.min(MAX_PANEL_HEIGHT, Math.max(MIN_PANEL_HEIGHT, window.innerHeight - MIN_EDITOR_HEIGHT))
return Math.round(Math.min(Math.max(px, MIN_PANEL_HEIGHT), max))
}
function loadPanelHeight(): number {
try {
const raw = localStorage.getItem(HEIGHT_KEY)
const parsed = raw ? Number(raw) : NaN
return Number.isFinite(parsed) ? clampPanelHeight(parsed) : DEFAULT_PANEL_HEIGHT
} catch {
return DEFAULT_PANEL_HEIGHT
}
}
let recordSeq = 0
function newRecordId(): string {
recordSeq += 1
return `s${recordSeq}-${Date.now().toString(36)}`
}
export const useEditorSearchStore = defineStore('editorSearch', {
state: () => ({
/** 检索历史(新的在前) */
records: [] as SearchRecord[],
/** 最近一次检索结果(`null` = 还没搜过) */
results: null as PathSearchResult | null,
/** 当前展示的结果对应哪条记录(`''` = 不是从历史里打开的) */
activeId: '' as string,
searching: false,
error: '' as string,
/** 底部结果面板是否展开 */
panelOpen: false,
/** 结果面板高度(px,可拖拽;落 localStorage) */
panelHeight: DEFAULT_PANEL_HEIGHT,
/** 结果面板里折叠起来的文件路径 */
collapsed: [] as string[]
}),
getters: {
/** 结果面板「结果」页是否有内容可看 */
hasResults(state): boolean {
return !!state.results || !!state.error || state.searching
}
},
actions: {
// ===== 历史与偏好 =====
/** 窗口挂载时调一次:把历史与面板高度读进来。 */
init(): void {
this.records = loadRecords()
this.panelHeight = loadPanelHeight()
},
/** 拖拽结果面板上边缘时实时改高度(夹取交给这里,调用方不必自己算边界)。 */
setPanelHeight(px: number): void {
this.panelHeight = clampPanelHeight(px)
},
/** 拖拽结束后落盘(拖动过程中不写,避免每帧一次 localStorage)。 */
persistPanelHeight(): void {
try {
localStorage.setItem(HEIGHT_KEY, String(this.panelHeight))
} catch {
/* 忽略存储失败 */
}
},
/** 记一条检索(同条件去重并置顶 —— 反复搜同一个词不该堆出一串重复项)。 */
rememberRecord(spec: SearchSpec, result: PathSearchResult | null): void {
const same = (r: SearchRecord) =>
r.dir === spec.dir &&
r.pattern === spec.pattern &&
r.fileTypes === spec.fileTypes &&
r.skipDirs === spec.skipDirs &&
r.caseSensitive === spec.caseSensitive &&
r.wholeWord === spec.wholeWord &&
r.regex === spec.regex
const previous = this.records.find(same)
const record: SearchRecord = {
id: previous?.id ?? newRecordId(),
...spec,
// total / totalFiles 是全树统计(不受回传上限影响),历史里要的就是这个数
hits: result?.total ?? 0,
files: result?.totalFiles ?? 0,
at: Date.now()
}
this.records = [record, ...this.records.filter(r => !same(r))].slice(0, MAX_RECORDS)
this.activeId = record.id
this.persist()
},
persist(): void {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(this.records))
} catch {
/* 忽略存储失败(配额满等),不影响检索 */
}
},
removeRecord(id: string): void {
this.records = this.records.filter(r => r.id !== id)
if (this.activeId === id) this.activeId = ''
this.persist()
},
clearRecords(): void {
this.records = []
this.activeId = ''
this.persist()
},
// ===== 检索 =====
/**
* 发起一次目录 / 库检索,并把条件记进历史。
*
* `record=false` 用于「重跑历史」:条件本来就已经在历史里了,再记一次只会把它
* 顶到最前面(其实也无害);但用于「刷新」时不该重复计数。
*/
async runQuery(query: PathSearchQuery, record = true): Promise<void> {
this.searching = true
this.error = ''
try {
const result = await editorClient.searchInPath(query)
this.results = result
this.collapsed = []
if (record) {
this.rememberRecord(
{
dir: query.dir,
pattern: query.pattern,
fileTypes: query.fileTypes ?? null,
skipDirs: query.skipDirs ?? '',
caseSensitive: query.caseSensitive,
wholeWord: query.wholeWord,
regex: query.regex
},
result
)
}
this.panelOpen = true
} catch (e) {
this.results = null
this.error = String(e)
this.panelOpen = true
logger.warn(`目录检索失败:${String(e)}`)
} finally {
this.searching = false
}
},
/** 按历史记录重跑(条件来自记录本身,因此完全自洽)。 */
async rerunRecord(id: string): Promise<void> {
const record = this.records.find(r => r.id === id)
if (!record) return
this.activeId = id
await this.runQuery(
specToQuery({
dir: record.dir,
pattern: record.pattern,
fileTypes: record.fileTypes,
skipDirs: record.skipDirs,
caseSensitive: record.caseSensitive,
wholeWord: record.wholeWord,
regex: record.regex
}),
// 重跑会刷新这条记录的命中数快照,但仍算「同一条」——去重逻辑会保留原 id
true
)
},
// ===== 面板 =====
togglePanel(): void {
this.panelOpen = !this.panelOpen
},
toggleFile(path: string): void {
const next = new Set(this.collapsed)
if (next.has(path)) next.delete(path)
else next.add(path)
this.collapsed = [...next]
},
/** 清空当前结果(关闭面板时保留历史,只丢结果)。 */
clearResults(): void {
this.results = null
this.error = ''
this.activeId = ''
this.collapsed = []
}
}
})
File diff suppressed because it is too large. Load diff
-846
View File
@@ -1,846 +0,0 @@
/**
* 笔记模块前端状态(主模块页与独立窗口共用同一份逻辑)。
*
* # Pinia 是窗口级的
*
* 主窗口与每个笔记独立窗口各有一份本 store 实例(WebView 各有 JS 运行时)。
* **真相在 Rust 侧**(设置文件 + 库文件 + SQLite 索引),因此这里的「缓存分叉」
* 无碍:各窗口经 `notes-settings` / `notes-library-changed` / `notes-file-changed`
* 事件重读即可对齐。
*
* # 编辑器同时服务两种文档(P1)
*
* P0 只有「库内笔记」,P1 加入「库外任意文件」。两者在 UI 上是同一个编辑器面板,
* 但**状态机完全不同**:笔记的真相在库根(相对路径 + front-matter + 自动保存),
* 文件的真相在磁盘那个绝对路径(编码 / 换行 / 大小上限)。因此这里不合并成一个
* 「文档」对象,而是显式用 [`kind`] 区分,`save()` 按 kind 分派 —— 合并状态会让
* 「保存时到底写哪个路径」变成隐式判断,正是数据事故的温床。
*/
import { defineStore } from 'pinia'
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { createLogger } from '@/lib/logger'
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
import { notesClient } from '@/modules/notes/notesClient'
import { loadLanguage, markdownLoader, type LanguageLoader } from '@/modules/notes/editor/languages'
import { extractOutline, type OutlineHeading } from '@/modules/notes/editor/outline'
import type { Extension } from '@codemirror/state'
import {
defaultNoteSettings,
type BackupReport,
type BackupSnapshot,
type LibraryEntry,
type LibraryInfo,
type LibraryTreeNode,
type NoteFileDoc,
type NoteFileEvent,
type NoteIndexStats,
type NoteSearchHit,
type NoteSearchQuery,
type NoteSettings,
type NoteTagCount,
type NoteTemplate,
type OpenFilePayload,
type SyncOutcome,
type SyncProgress,
type SyncReport,
type WebdavStatus
} from '@/types/notes'
const logger = createLogger('notes')
/** 最近打开记录 */
export interface RecentNote {
relPath: string
name: string
at: number
}
/** 编辑器正在编辑的文档类型 */
export type EditorKind = 'none' | 'note' | 'file'
/** 搜索结果一页的条数 */
const SEARCH_PAGE_SIZE = 30
/** 把扁平条目组装成树(Rust 已保证「目录在前、各自按名排序」)。 */
function buildTree(entries: LibraryEntry[]): LibraryTreeNode[] {
const nodes = new Map<string, LibraryTreeNode>()
for (const entry of entries) nodes.set(entry.relPath, { entry, children: [] })
const roots: LibraryTreeNode[] = []
for (const entry of entries) {
const node = nodes.get(entry.relPath)
if (!node) continue
const parent = entry.parentRel ? nodes.get(entry.parentRel) : undefined
if (parent) parent.children.push(node)
else roots.push(node)
}
return roots
}
function readRecent(): RecentNote[] {
try {
const raw = localStorage.getItem(STORAGE_KEYS.notesRecent)
if (!raw) return []
const parsed = JSON.parse(raw) as RecentNote[]
return Array.isArray(parsed) ? parsed.slice(0, 12) : []
} catch {
return []
}
}
/** 事件监听在模块级持有(不进 Pinia state,避免不可序列化对象入 state)。 */
let unlisteners: UnlistenFn[] = []
let listening = false
let refreshTimer: ReturnType<typeof setTimeout> | null = null
/**
* 语言加载令牌:语言包是异步 `import()` 的,快速切换文件时旧请求可能后到。
* 每次切换自增,回调只在令牌仍然最新时才写 state(避免「打开 b.py 后显示成 a.rb 高亮」)。
*/
let languageToken = 0
export const useNotesStore = defineStore('notes', {
state: () => ({
/** 模块设置(Rust 侧为准) */
settings: defaultNoteSettings() as NoteSettings,
/** 库状态概览 */
info: null as LibraryInfo | null,
/** 扁平条目 */
entries: [] as LibraryEntry[],
/** 侧栏树 */
tree: [] as LibraryTreeNode[],
/** 当前打开的笔记相对路径 */
currentRelPath: '' as string,
/** 当前文档完整内容(含 front-matter) */
content: '' as string,
/** 是否有未保存改动 */
dirty: false,
/** 正在保存 */
saving: false,
/** 正在加载库 */
loading: false,
/** 最近打开 */
recent: readRecent() as RecentNote[],
/** 设置是否已加载 */
ready: false,
// ===== P1:编辑器文档状态 =====
/** 当前编辑的是笔记还是库外文件 */
kind: 'none' as EditorKind,
/** 库外文件的完整信息(kind === 'file' 时有效) */
fileDoc: null as NoteFileDoc | null,
/** 当前文档的语言加载器(进 EditorConfig,供 core.ts 装配) */
language: markdownLoader() as LanguageLoader,
/** 语言展示名(状态栏) */
languageLabel: '纯文本' as string,
/** 大纲(Markdown 文档才有;由内容派生) */
outline: [] as OutlineHeading[],
// ===== P1:索引与检索 =====
/** 索引状态 */
indexStats: null as NoteIndexStats | null,
/** 索引是否正在同步/重建 */
indexing: false,
/** 标签清单 */
tags: [] as NoteTagCount[],
/** 搜索关键词 */
searchKeyword: '' as string,
/** 搜索时选中的标签(空 = 不限) */
searchTag: '' as string,
/** 搜索结果 */
searchHits: [] as NoteSearchHit[],
/** 命中总数(不受分页影响) */
searchTotal: 0,
/** 搜索中 */
searching: false,
/** 是否还有下一页 */
searchHasMore: false,
/** 快速打开清单(Ctrl+P) */
quickOpenList: [] as NoteSearchHit[],
/**
* 文档「装载版本号」。每当成篇装载内容(打开/重载)时自增。
*
* 编辑器据此判断「要不要整篇替换文档」——只比对内容字符串会把用户自己的
* 每一次输入也算成「外部替换」,只比对路径又漏掉「重载同一篇」。
* 一个自增计数是最不会出错的做法。
*/
docRevision: 0,
/**
* 「当前文档被外部改动」的待确认通知(`null` = 无)。
*
* 只在**当前文档有未保存改动**时才会被置上:那时不能静默重载(会丢掉用户
* 刚敲的内容),必须让用户选。没有未保存改动时直接重载,不留提示。
*/
externalChange: null as NoteFileEvent | null,
/** 新建笔记的请求标记(全局快捷键触发时自增,主模块页据此打开对话框)。 */
newNoteRequest: 0,
/** 「打开编辑器」的请求标记(全局快捷键触发时自增)。 */
openEditorRequest: 0,
/**
* 启动时命令行指定的待打开文件(冷启动的「用 Thing 打开」)。
*
* 主窗口取到后由模块页据此开笔记窗口;`init` 里 `consumePendingFile` 写入。
*/
pendingOpenPath: '' as string,
// ===== P2:模板 =====
/** 可用模板(首次打开「新建」对话框时拉取) */
templates: [] as NoteTemplate[],
/** 上次选择的模板 ID(同一窗口内记住,避免每次新建都要再选) */
lastTemplateId: '' as string,
// ===== P2:WebDAV =====
/** WebDAV 配置状态(不含密码) */
webdavStatus: null as WebdavStatus | null,
/** 同步进度(`null` = 空闲) */
syncing: false,
/** 同步进度百分比信息 */
syncProgress: null as SyncProgress | null,
/** 最近一次同步报告(设置页展示) */
lastSyncReport: null as SyncReport | null,
/** 远端快照列表 */
backups: [] as BackupSnapshot[],
/** 正在拉取快照列表 */
loadingBackups: false
}),
getters: {
/** 当前文档显示名(不含扩展名) */
currentName(state): string {
if (state.kind === 'file') return state.fileDoc?.name ?? ''
const entry = state.entries.find(e => e.relPath === state.currentRelPath)
if (entry) return entry.name.replace(/\.md$/i, '')
return state.currentRelPath.split('/').pop()?.replace(/\.md$/i, '') ?? ''
},
/** 是否有打开的文档(笔记或文件) */
hasDocument(state): boolean {
return state.kind === 'note' ? !!state.currentRelPath : state.kind === 'file'
},
/** 当前文档字数(按非空白字符计) */
wordCount(state): number {
const body = state.content.replace(/^---[\s\S]*?---\n?/, '')
return (body.match(/\S/g) ?? []).length
},
/** 当前文档行数 */
lineCount(state): number {
if (!state.content) return state.kind === 'none' ? 0 : 1
return state.content.split('\n').length
},
/** 库根显示名 */
libraryRoot(state): string {
return state.info?.root ?? ''
}
},
actions: {
// ===== 设置 =====
async loadSettings(): Promise<void> {
try {
this.settings = await notesClient.getSettings()
} catch (e) {
logger.error(`读取笔记设置失败: ${String(e)}`)
} finally {
this.ready = true
}
},
/** 局部更新设置(即时生效并落盘;返回值已由 Rust 自愈规范化)。 */
async patchSettings(patch: Partial<NoteSettings>): Promise<void> {
const next: NoteSettings = { ...this.settings, ...patch }
try {
this.settings = await notesClient.saveSettings(next)
} catch (e) {
logger.error(`保存笔记设置失败: ${String(e)}`)
}
},
// ===== 库 =====
async refreshLibrary(): Promise<void> {
this.loading = true
try {
const [info, entries] = await Promise.all([
notesClient.libraryInfo(),
notesClient.scanLibrary()
])
this.info = info
this.entries = entries
this.tree = buildTree(entries)
} catch (e) {
logger.error(`扫描笔记库失败: ${String(e)}`)
} finally {
this.loading = false
}
},
async setLibraryRoot(root: string | null): Promise<void> {
this.info = await notesClient.setLibraryRoot(root)
await this.refreshLibrary()
// 库换了,索引也要跟着换:重建比「猜差量」稳,且此时用户本来就在等
await this.rebuildIndex()
},
// ===== 索引与检索 =====
/** 增量同步索引(打开编辑器时调用一次,外部改动后由文件事件触发)。 */
async syncIndex(): Promise<void> {
this.indexing = true
try {
await notesClient.syncIndex()
await Promise.all([this.loadIndexStats(), this.loadTags()])
} catch (e) {
logger.error(`同步索引失败: ${String(e)}`)
} finally {
this.indexing = false
}
},
/** 全量重建索引(设置页按钮 / 切换库根后)。 */
async rebuildIndex(): Promise<void> {
this.indexing = true
try {
await notesClient.rebuildIndex()
await Promise.all([this.loadIndexStats(), this.loadTags()])
} catch (e) {
logger.error(`重建索引失败: ${String(e)}`)
} finally {
this.indexing = false
}
},
async loadIndexStats(): Promise<void> {
try {
this.indexStats = await notesClient.indexStats()
} catch (e) {
logger.error(`读取索引状态失败: ${String(e)}`)
}
},
async loadTags(): Promise<void> {
try {
this.tags = await notesClient.tags()
} catch (e) {
logger.error(`读取标签失败: ${String(e)}`)
}
},
/**
* 全文检索(第一页)。
*
* `tag` / `dir` 也走同一个命令:Rust 侧把它们与关键词组合在同一条 SQL 里,
* 前端不需要「先搜再过滤」——那种做法在分页时会漏结果。
*/
async search(options?: { keyword?: string; tag?: string; dir?: string }): Promise<void> {
if (options?.keyword !== undefined) this.searchKeyword = options.keyword
if (options?.tag !== undefined) this.searchTag = options.tag
this.searching = true
try {
const query: NoteSearchQuery = {
keyword: this.searchKeyword,
tag: this.searchTag,
dir: options?.dir ?? '',
offset: 0,
limit: SEARCH_PAGE_SIZE
}
const page = await notesClient.search(query)
this.searchHits = page.items
this.searchTotal = page.total
this.searchHasMore = page.items.length < page.total
} catch (e) {
logger.error(`检索失败: ${String(e)}`)
} finally {
this.searching = false
}
},
/** 搜索翻页(追加到现有结果后)。 */
async searchMore(): Promise<void> {
if (!this.searchHasMore || this.searching) return
this.searching = true
try {
const page = await notesClient.search({
keyword: this.searchKeyword,
tag: this.searchTag,
offset: this.searchHits.length,
limit: SEARCH_PAGE_SIZE
})
this.searchHits = [...this.searchHits, ...page.items]
this.searchTotal = page.total
this.searchHasMore = this.searchHits.length < page.total
} catch (e) {
logger.error(`检索翻页失败: ${String(e)}`)
} finally {
this.searching = false
}
},
clearSearch(): void {
this.searchKeyword = ''
this.searchTag = ''
this.searchHits = []
this.searchTotal = 0
this.searchHasMore = false
},
/** 拉取快速打开清单(Ctrl+P)。 */
async loadQuickOpen(): Promise<void> {
try {
this.quickOpenList = await notesClient.listNotes(1000)
} catch (e) {
logger.error(`读取文件清单失败: ${String(e)}`)
}
},
// ===== 笔记文档 =====
async openNote(relPath: string, options?: { keepDirty?: boolean }): Promise<void> {
if (this.kind === 'note' && this.currentRelPath === relPath) return
if (this.dirty && this.hasDocument && !options?.keepDirty) {
await this.saveCurrent()
}
try {
const doc = await notesClient.readNote(relPath)
this.kind = 'note'
this.fileDoc = null
this.currentRelPath = doc.relPath
this.content = doc.content
this.dirty = false
this.docRevision += 1
this.applyLanguage('note', doc.name, doc.relPath)
this.touchRecent(doc.relPath, doc.name)
} catch (e) {
logger.error(`打开笔记失败: ${String(e)}`)
}
},
/** 编辑器内容变化(来自 CM6 updateListener)。 */
setContent(content: string): void {
this.content = content
this.dirty = true
if (this.kind === 'note') this.refreshOutline()
},
async saveCurrent(): Promise<void> {
if (!this.dirty || this.saving || !this.hasDocument) return
this.saving = true
try {
if (this.kind === 'file') {
const doc = this.fileDoc
if (!doc) return
this.fileDoc = await notesClient.writeFile(
doc.path,
this.content,
doc.encoding,
doc.eol
)
} else {
await notesClient.saveNote(this.currentRelPath, this.content)
}
this.dirty = false
} catch (e) {
logger.error(`保存失败: ${String(e)}`)
throw e
} finally {
this.saving = false
}
},
async createNote(dirRel: string, name: string, templateId?: string): Promise<void> {
const template = templateId ?? this.lastTemplateId
const doc = await notesClient.createNote(dirRel, name, template)
if (template) this.lastTemplateId = template
await this.refreshLibrary()
this.kind = 'none'
this.currentRelPath = ''
await this.openNote(doc.relPath)
},
// ===== 模板(P2) =====
/** 拉取可用模板(幂等;库根变化后应重新拉取)。 */
async loadTemplates(): Promise<void> {
try {
this.templates = await notesClient.listTemplates()
} catch (e) {
logger.error(`读取模板失败: ${String(e)}`)
}
},
/** 新建模板(同名会失败,由调用方提示)。 */
async addTemplate(name: string, body: string): Promise<void> {
await notesClient.addTemplate(name, body)
await this.loadTemplates()
},
/** 把内置模板导出到库内 `templates/`,返回新写入的名字。 */
async exportBuiltinTemplates(): Promise<string[]> {
const written = await notesClient.addTemplate()
await this.loadTemplates()
return written
},
/** 打开(或创建)今天的日记。 */
async openDailyNote(): Promise<void> {
if (this.dirty && this.hasDocument) await this.saveCurrent()
const doc = await notesClient.dailyNote()
this.kind = 'none'
this.currentRelPath = ''
await this.refreshLibrary()
await this.openNote(doc.relPath)
},
// ===== WebDAV(P2) =====
async loadWebdavStatus(): Promise<void> {
try {
this.webdavStatus = await notesClient.webdavStatus()
} catch (e) {
logger.error(`读取 WebDAV 状态失败: ${String(e)}`)
}
},
/**
* 立即同步(进度由 `notes-sync-progress` 事件驱动)。
*
* 同步可能改变本地文件(下载覆盖、删除传播),因此结束后必须重载当前文档 ——
* 否则编辑器里显示的还是同步之前的旧内容,用户一保存就把同步结果覆盖回去了。
*/
async syncNow(): Promise<SyncReport | null> {
this.syncing = true
this.syncProgress = { done: 0, total: 0, current: '', kind: 'prepare', message: '正在比对清单…' }
try {
const outcome: SyncOutcome = await notesClient.syncNow()
this.lastSyncReport = outcome.report
await this.refreshLibrary()
await this.reloadAfterExternal()
return outcome.report
} catch (e) {
logger.error(`同步失败: ${String(e)}`)
throw e
} finally {
this.syncing = false
this.syncProgress = null
}
},
/** 只做一次 zip 快照备份。 */
async backupNow(): Promise<BackupReport> {
this.syncing = true
this.syncProgress = { done: 0, total: 0, current: '', kind: 'backup', message: '正在打包快照…' }
try {
const report = await notesClient.backupNow()
return report
} finally {
this.syncing = false
this.syncProgress = null
}
},
async loadBackups(): Promise<void> {
this.loadingBackups = true
try {
this.backups = await notesClient.listBackups()
} catch (e) {
logger.error(`读取快照列表失败: ${String(e)}`)
} finally {
this.loadingBackups = false
}
},
/**
* 从远端快照恢复(不覆盖本地已有文件)。
*
* `notes_restore_backup` 只会**补上本地缺失的文件** —— 因此这里可以放心重载
* 当前文档(它不会因为恢复而被改坏)。
*/
async restoreBackup(name: string): Promise<void> {
this.syncing = true
this.syncProgress = { done: 0, total: 0, current: name, kind: 'restore', message: '正在恢复快照…' }
try {
await notesClient.restoreBackup(name)
await this.refreshLibrary()
await this.syncIndex()
} finally {
this.syncing = false
this.syncProgress = null
}
},
/** 远端配置变化后重新读状态(保存设置时调用)。 */
async refreshWebdav(password?: string): Promise<void> {
if (password !== undefined) {
await notesClient.setWebdavPassword(password)
}
await this.loadWebdavStatus()
},
async createFolder(dirRel: string, name: string): Promise<void> {
await notesClient.createFolder(dirRel, name)
await this.refreshLibrary()
},
async renameEntry(relPath: string, newName: string): Promise<void> {
const nextRel = await notesClient.renameEntry(relPath, newName)
if (this.currentRelPath === relPath) this.currentRelPath = nextRel
await this.refreshLibrary()
},
async deleteEntry(relPath: string): Promise<void> {
await notesClient.deleteEntry(relPath)
if (this.currentRelPath === relPath) {
this.resetDocument()
}
await this.refreshLibrary()
},
// ===== 库外文件 =====
/**
* 打开一个库外文件。
*
* 若该文件同时也在库内(例如用「打开文件」选了笔记库里的 `.md`),
* 仍然按**文件**处理:文件语义(编码/换行/大文件降级)是用户从系统对话框
* 选择时更可预期的行为,而库语义(front-matter、库内相对路径)需要库上下文。
*/
async openFile(path: string): Promise<void> {
if (this.dirty && this.hasDocument) {
await this.saveCurrent()
}
const doc = await notesClient.openFile(path)
this.kind = 'file'
this.currentRelPath = ''
this.fileDoc = doc
this.content = doc.content
this.dirty = false
this.docRevision += 1
this.applyLanguage('file', doc.name, doc.path)
this.refreshOutline()
},
/**
* 重新载入当前文档(外部改动提示里点「重新载入」)。
*
* 会丢掉未保存的改动 —— 因此调用方必须先确认(UI 侧用 ConfirmDialog)。
*/
async reloadCurrent(): Promise<void> {
if (this.kind === 'file' && this.fileDoc) {
await this.openFile(this.fileDoc.path)
} else if (this.kind === 'note' && this.currentRelPath) {
const relPath = this.currentRelPath
this.kind = 'none'
this.currentRelPath = ''
await this.openNote(relPath)
}
},
resetDocument(): void {
this.kind = 'none'
this.currentRelPath = ''
this.fileDoc = null
this.content = ''
this.dirty = false
this.outline = []
this.externalChange = null
},
/**
* 同步(或任何批量改动)之后重新读一次当前文档。
*
* 有未保存改动时不重载 —— 同步刚把磁盘上的版本换掉,此时重载会丢用户正在写的东西;
* 改为留下 `externalChange` 提示,让用户自己决定。
*/
async reloadAfterExternal(): Promise<void> {
if (!this.hasDocument) return
if (this.dirty) {
this.externalChange = {
relPath: this.currentRelPath,
absPath: this.fileDoc?.path ?? '',
kind: 'modified',
at: Date.now(),
fromApp: false
}
return
}
try {
await this.reloadCurrent()
} catch (e) {
logger.error(`同步后重载文档失败: ${String(e)}`)
}
},
// ===== 语言与大纲 =====
/**
* 装配当前文档的语言(异步加载语言包 + 重建大纲)。
*
* 令牌机制防止「快速连续打开两个不同类型的文件」时旧语言后到覆盖新语言。
*/
applyLanguage(kind: 'note' | 'file', fileName: string, pathOrRel: string): void {
void pathOrRel
const token = ++languageToken
this.refreshOutline()
if (kind === 'note') {
this.language = markdownLoader()
this.languageLabel = 'Markdown'
return
}
// 先给一个「什么都不加载」的加载器:语言包到位前保持纯文本,
// 而不是停留在上一篇文档的语言(那会高亮错乱)
this.language = () => null
void loadLanguage(fileName)
.then((extension: Extension | null) => {
if (token !== languageToken) return
this.language = () => extension
})
.catch(e => {
logger.warn(`加载语言包失败(${fileName}):${String(e)}`)
if (token === languageToken) this.language = () => null
})
},
/** 重建大纲(仅 Markdown 文档;代码文件没有标题语义)。 */
refreshOutline(): void {
if (this.kind === 'file') {
this.outline = []
return
}
this.outline = extractOutline(this.content)
},
// ===== 最近打开 =====
touchRecent(relPath: string, name: string): void {
const next = [
{ relPath, name, at: Date.now() },
...this.recent.filter(item => item.relPath !== relPath)
].slice(0, 12)
this.recent = next
try {
localStorage.setItem(STORAGE_KEYS.notesRecent, JSON.stringify(next))
} catch {
/* 忽略存储失败 */
}
},
// ===== 事件与初始化 =====
/** 注册跨窗口同步监听(幂等;每个窗口注册一次)。 */
async initListeners(): Promise<void> {
if (listening) return
listening = true
try {
const unSettings = await listen(EVENTS.notesSettings, () => {
void this.loadSettings()
})
const unLibrary = await listen(EVENTS.notesLibraryChanged, () => {
// 打字时的自动保存会高频触发,这里做一次防抖,避免每 800ms 全量重扫
if (refreshTimer) clearTimeout(refreshTimer)
refreshTimer = setTimeout(() => void this.refreshLibrary(), 400)
})
const unFile = await listen<NoteFileEvent>(EVENTS.notesFileChanged, event => {
void this.onExternalChange(event.payload)
})
const unSync = await listen<SyncProgress>(EVENTS.notesSyncProgress, event => {
this.syncProgress = event.payload
})
// 全局快捷键:Rust 只发事件,窗口与对话框都由前端决定
const unNewNote = await listen(EVENTS.notesNewNote, () => {
this.newNoteRequest += 1
})
const unOpenEditor = await listen(EVENTS.notesOpenEditor, () => {
this.openEditorRequest += 1
})
// 「用 Thing 打开」(文件关联 / 命令行):Rust 只发路径,窗口由前端决定
const unOpenFile = await listen<OpenFilePayload>(EVENTS.notesOpenFile, event => {
const path = event.payload?.path ?? ''
if (path) void this.openFile(path).catch(e => logger.error(`打开文件失败: ${String(e)}`))
})
unlisteners = [
unSettings,
unLibrary,
unFile,
unSync,
unNewNote,
unOpenEditor,
unOpenFile
]
} catch (e) {
logger.error(`注册笔记事件监听失败: ${String(e)}`)
}
},
/**
* 库内文件在应用外被改动。
*
* 三种处理:
* - **不是当前文档**:只刷新树(用户可能正看着那一篇被删掉)
* - **是当前文档且没有未保存改动**:静默重载(用户看到的就是磁盘上的内容)
* - **是当前文档但有未保存改动**:**不动内容**,只标记 `externalChange`,
* 由 UI 提示用户选择「保留我的改动 / 重新载入」——静默覆盖是最不可接受的
* 做法:用户刚敲的一段话就这么没了
*/
async onExternalChange(event: NoteFileEvent): Promise<void> {
await this.refreshLibrary()
if (event.kind === 'removed') {
if (
(this.kind === 'note' && this.currentRelPath === event.relPath) ||
(this.kind === 'file' && this.fileDoc?.path.endsWith(event.relPath))
) {
this.externalChange = event
}
return
}
if (this.kind === 'note' && this.currentRelPath === event.relPath) {
if (this.dirty) this.externalChange = event
else await this.openNote(event.relPath, { keepDirty: true })
} else if (this.kind === 'file' && this.fileDoc?.path === event.relPath) {
this.externalChange = event
}
void this.syncIndex()
},
async init(): Promise<void> {
await this.loadSettings()
await this.refreshLibrary()
await this.initListeners()
// 索引同步放在最后:它是纯加速层,让窗口先显示出来(首屏不被扫描拖住)
void this.syncIndex()
// 「用 Thing 打开」的冷启动路径:启动时命令行留下的文件在这里取走
//(必须在 `initListeners` 之后 —— 监听没注册时 Rust 那边 emit 会丢事件)
void this.consumePendingFile()
// P2:WebDAV 状态与「启动时自动同步」
void this.loadWebdavStatus().then(() => {
if (this.settings.webdav.autoSyncOnLaunch && this.webdavStatus?.configured) {
// 只记日志不弹错:自动同步失败不该在每次启动时糊用户一脸提示
void this.syncNow().catch(e => logger.warn(`启动自动同步失败:${String(e)}`))
}
})
},
/**
* 取走启动时命令行留下的文件(取走即清空)。
*
* 只有主窗口需要做这件事:文件关联启动时打开的是主窗口,而它会把文件转交给
* 笔记窗口(`NotesWindow` 自己会按 `?path=` 打开)。
*/
async consumePendingFile(): Promise<void> {
try {
const path = await notesClient.takePendingFile()
if (path) this.pendingOpenPath = path
} catch (e) {
logger.warn(`读取待打开文件失败:${String(e)}`)
}
},
disposeListeners(): void { unlisteners.forEach(unlisten => unlisten())
unlisteners = []
listening = false
if (refreshTimer) {
clearTimeout(refreshTimer)
refreshTimer = null
}
}
}
})
+163 -11
View File
@@ -1,8 +1,8 @@
/**
* 笔记 / 编辑器模块的前端类型。
*
* 这些结构在 Rust 侧有同名定义(`src-tauri/src/notes/types.rs`)。
* 待 `bindings.ts` 生成后可由 `commands.notes_*` 的返回类型替代;
* 这些结构在 Rust 侧有同名定义(`src-tauri/src/editor/types.rs`)。
* 待 `bindings.ts` 生成后可由 `commands.editor_*` 的返回类型替代;
* P0 阶段先在此声明,避免为了类型而强依赖一次 debug 构建。
*/
@@ -37,7 +37,7 @@ export interface NoteDoc {
modified: number
}
/** 库外任意文件的读写结果(对应 Rust `notes::files::FileDoc`) */
/** 库外任意文件的读写结果(对应 Rust `editor::files::FileDoc`) */
export interface NoteFileDoc {
/** 绝对路径(Windows 下已剥掉 `\\?\` 前缀) */
path: string
@@ -53,6 +53,8 @@ export interface NoteFileDoc {
/** 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全) */
large: boolean
lines: number
/** 是否只读(打开时探测写权限失败;保存会被拦截) */
readonly: boolean
}
/** 搜索命中的一篇笔记 */
@@ -120,6 +122,21 @@ export interface OpenFilePayload {
path: string
}
/** 待打开目标(对应 Rust `OpenTargetPayload`:冷启动缓存) */
export interface OpenTargetPayload {
path: string
kind: 'file' | 'folder'
}
/** 右键菜单注册状态(对应 Rust `ContextMenuStatus`) */
export interface ContextMenuStatus {
registered: boolean
/** 注册表里写入的可执行文件绝对路径 */
exePath: string
/** 开发模式(exe 路径不稳定,UI 需提示) */
isDev: boolean
}
/** 索引状态 */
export interface NoteIndexStats {
noteCount: number
@@ -208,7 +225,7 @@ export interface WebdavTestResult {
message: string
}
/** 同步进度(事件 `notes-sync-progress` 的负载) */
/** 同步进度(事件 `editor-sync-progress` 的负载) */
export interface SyncProgress {
done: number
total: number
@@ -294,10 +311,19 @@ export type EditorThemeId =
/** 默认视图 */
export type NoteViewMode = 'wysiwyg' | 'source'
/** 模块设置(与 Rust `NoteSettings` 字段一一对应) */
export interface NoteSettings {
/** 最近打开的一个文件 / 文件夹(对应 Rust `RecentEntry`) */
export interface RecentEntry {
path: string
name: string
openedAt: number
/** 该路径当前是否仍存在(由 Rust 读取设置时刷新,供 UI 灰显失效项) */
exists: boolean
}
/** 模块设置(与 Rust `EditorSettings` 字段一一对应) */
export interface EditorSettings {
version: number
/** 自定义库根;`null` = 默认 `{appData}/notes/library` */
/** 自定义库根;`null` = 默认 `{appData}/editor/library` */
libraryRoot: string | null
editorTheme: EditorThemeId | string
followAppTheme: boolean
@@ -333,6 +359,130 @@ export interface NoteSettings {
newNoteShortcut: string
/** 全局快捷键:打开编辑器窗口(空串 = 不注册) */
openEditorShortcut: string
/** 最近打开的文件(与笔记库解耦) */
recentFiles: RecentEntry[]
/** 最近打开的文件夹(与笔记库解耦) */
recentFolders: RecentEntry[]
}
// ===== 本地目录(P3-5) =====
/** 一个本地目录项(对应 Rust `terminal::local_fs::LocalEntry`) */
export interface DirEntry {
name: string
/** 完整路径 */
path: string
/** "dir" | "file" | "other"(符号链接返回目标的类型) */
kind: 'dir' | 'file' | 'other'
size: number
modifiedAt: number | null
linkTarget: string | null
}
/** 目录列举结果(对应 Rust `LocalDir`) */
export interface DirListing {
cwd: string
parent: string | null
entries: DirEntry[]
}
/** 批量删除结果(对应 Rust `DeleteReport`) */
export interface DeleteReport {
removed: number
failed: string[]
}
// ===== 在路径中查找(Find in Path) =====
/** 查找请求(与 Rust `PathSearchQuery` 一一对应) */
export interface PathSearchQuery {
/** 检索根目录(绝对路径:当前目录或笔记库根) */
dir: string
/** 关键词(`regex` 为真时按正则解释) */
pattern: string
caseSensitive: boolean
wholeWord: boolean
regex: boolean
/** 命中总数上限(缺省由后端取 1000) */
limit?: number | null
/** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */
fileTypes?: string | null
/** 跳过的目录名(`|` / `,` 分隔;空串 = 不跳过任何目录) */
skipDirs?: string | null
}
/** 一处命中(以「行」为单位) */
export interface PathSearchMatch {
/** 行号(1 起) */
line: number
/** 行内字符列(1 起) */
column: number
/** 该行预览(超长时围绕命中开窗) */
preview: string
/** 命中在 `preview` 中的起始字符下标 */
matchStart: number
/** 命中在 `preview` 中的结束字符下标(不含) */
matchEnd: number
}
/** 一个文件内的全部命中 */
export interface PathSearchFileHits {
path: string
name: string
/** 该文件内全部命中行数(`matches` 可能因回传上限只含前一部分) */
totalInFile: number
matches: PathSearchMatch[]
}
/** 一次「在路径中查找」的结果 */
export interface PathSearchResult {
files: PathSearchFileHits[]
/** 全树命中行总数(统计完整,不受 limit 影响) */
total: number
/** 全树至少命中一行的文件总数(≥ files.length) */
totalFiles: number
/** 实际回传的预览条数(≤ total) */
returned: number
/** total > returned:还有命中未回传预览 */
truncated: boolean
}
/** 在路径中替换的请求(匹配选项与 `PathSearchQuery` 一致) */
export interface PathReplaceQuery {
dir: string
pattern: string
replacement: string
caseSensitive: boolean
wholeWord: boolean
regex: boolean
limit?: number | null
/** 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件) */
fileTypes?: string | null
/** 跳过的目录名(`|` / `,` 分隔;空串 = 不跳过任何目录) */
skipDirs?: string | null
}
/** 一个被改写的文件 */
export interface PathReplaceFileResult {
path: string
name: string
replacements: number
}
/** 被跳过的文件(非 UTF-8 / 写入失败) */
export interface PathReplaceSkipped {
path: string
reason: string
}
/** 一次「在路径中替换」的结果 */
export interface PathReplaceResult {
files: PathReplaceFileResult[]
filesChanged: number
replacements: number
/** 达到上限提前停止:此时只改了前面一部分文件 */
truncated: boolean
skipped: PathReplaceSkipped[]
}
/** 侧栏树节点 */
@@ -341,8 +491,8 @@ export interface LibraryTreeNode {
children: LibraryTreeNode[]
}
/** 默认值(与 Rust `NoteSettings::default` 保持一致) */
export function defaultNoteSettings(): NoteSettings {
/** 默认值(与 Rust `EditorSettings::default` 保持一致) */
export function defaultEditorSettings(): EditorSettings {
return {
version: 2,
libraryRoot: null,
@@ -354,7 +504,7 @@ export function defaultNoteSettings(): NoteSettings {
ligatures: false,
tabSize: 2,
livePreview: true,
autosaveMs: 800,
autosaveMs: 0,
defaultView: 'wysiwyg',
showLineNumbers: true,
showOutline: true,
@@ -366,7 +516,9 @@ export function defaultNoteSettings(): NoteSettings {
showTemplatePicker: true,
exportHighlight: true,
newNoteShortcut: '',
openEditorShortcut: ''
openEditorShortcut: '',
recentFiles: [],
recentFolders: []
}
}