编辑器模块(笔记)初版
This commit is contained in:
1 parent
7e65825d3e
commit
ad987111a3
66 files changed
+17470
-283
No files matched your search
@@ -5,13 +5,34 @@
|
||||
"": {
|
||||
"name": "thing",
|
||||
"dependencies": {
|
||||
"@lucide/vue": "^1.28.0",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.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",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
@@ -22,10 +43,13 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"dompurify": "^3.4.16",
|
||||
"highlight.js": "^11.12.0",
|
||||
"markdown-it": "^15.0.2",
|
||||
"pinia": "^3.0.4",
|
||||
"pinyin-pro": "^3.28.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"reka-ui": "^2.10.1",
|
||||
"reka-ui": "^2.10.5",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"vue": "^3.5.13",
|
||||
@@ -33,7 +57,8 @@
|
||||
"vue-sonner": "^2.0.9",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@tauri-apps/cli": "^2.12.0",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
@@ -60,6 +85,68 @@
|
||||
|
||||
"@cacheable/utils": ["@cacheable/utils@2.5.0", "https://registry.npmmirror.com/@cacheable/utils/-/utils-2.5.0.tgz", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="],
|
||||
|
||||
"@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.3", "https://registry.npmmirror.com/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g=="],
|
||||
|
||||
"@codemirror/commands": ["@codemirror/commands@6.11.1", "https://registry.npmmirror.com/@codemirror/commands/-/commands-6.11.1.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg=="],
|
||||
|
||||
"@codemirror/lang-angular": ["@codemirror/lang-angular@0.1.4", "https://registry.npmmirror.com/@codemirror/lang-angular/-/lang-angular-0.1.4.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.3" } }, "sha512-oap+gsltb/fzdlTQWD6BFF4bSLKcDnlxDsLdePiJpCVNKWXSTAbiiQeYI3UmES+BLAdkmIC1WjyztC1pi/bX4g=="],
|
||||
|
||||
"@codemirror/lang-cpp": ["@codemirror/lang-cpp@6.0.3", "https://registry.npmmirror.com/@codemirror/lang-cpp/-/lang-cpp-6.0.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/cpp": "^1.0.0" } }, "sha512-URM26M3vunFFn9/sm6rzqrBzDgfWuDixp85uTY49wKudToc2jTHUrKIGGKs+QWND+YLofNNZpxcNGRynFJfvgA=="],
|
||||
|
||||
"@codemirror/lang-css": ["@codemirror/lang-css@6.3.1", "https://registry.npmmirror.com/@codemirror/lang-css/-/lang-css-6.3.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/css": "^1.1.7" } }, "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg=="],
|
||||
|
||||
"@codemirror/lang-go": ["@codemirror/lang-go@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-go/-/lang-go-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/go": "^1.0.0" } }, "sha512-7fNvbyNylvqCphW9HD6WFnRpcDjr+KXX/FgqXy5H5ZS0eC5edDljukm/yNgYkwTsgp2busdod50AOTIy6Jikfg=="],
|
||||
|
||||
"@codemirror/lang-html": ["@codemirror/lang-html@6.4.12", "https://registry.npmmirror.com/@codemirror/lang-html/-/lang-html-6.4.12.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w=="],
|
||||
|
||||
"@codemirror/lang-java": ["@codemirror/lang-java@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-java/-/lang-java-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/java": "^1.0.0" } }, "sha512-m5Nt1mQ/cznJY7tMfQTJchmrjdjQ71IDs+55d1GAa8DGaB8JXWsVCkVT284C3RTASaY43YknrK2X3hPO/J3MOQ=="],
|
||||
|
||||
"@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.5", "https://registry.npmmirror.com/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A=="],
|
||||
|
||||
"@codemirror/lang-jinja": ["@codemirror/lang-jinja@6.0.1", "https://registry.npmmirror.com/@codemirror/lang-jinja/-/lang-jinja-6.0.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.4.0" } }, "sha512-P5kyHLObzjtbGj16h+hyvZTxJhSjBEeSx4wMjbnAf3b0uwTy2+F0zGjMZL4PQOm/mh2eGZ5xUDVZXgwP783Nsw=="],
|
||||
|
||||
"@codemirror/lang-json": ["@codemirror/lang-json@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-json/-/lang-json-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/json": "^1.0.0" } }, "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ=="],
|
||||
|
||||
"@codemirror/lang-less": ["@codemirror/lang-less@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-less/-/lang-less-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-EYdQTG22V+KUUk8Qq582g7FMnCZeEHsyuOJisHRft/mQ+ZSZ2w51NupvDUHiqtsOy7It5cHLPGfHQLpMh9bqpQ=="],
|
||||
|
||||
"@codemirror/lang-liquid": ["@codemirror/lang-liquid@6.3.2", "https://registry.npmmirror.com/@codemirror/lang-liquid/-/lang-liquid-6.3.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-html": "^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.3.1" } }, "sha512-6PDVU3ZnfeYyz1at1E/ttorErZvZFXXt1OPhtfe1EZJ2V2iDFa0CwPqPgG5F7NXN0yONGoBogKmFAafKTqlwIw=="],
|
||||
|
||||
"@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "https://registry.npmmirror.com/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="],
|
||||
|
||||
"@codemirror/lang-php": ["@codemirror/lang-php@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-php/-/lang-php-6.0.2.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/php": "^1.0.0" } }, "sha512-ZKy2v1n8Fc8oEXj0Th0PUMXzQJ0AIR6TaZU+PbDHExFwdu+guzOA4jmCHS1Nz4vbFezwD7LyBdDnddSJeScMCA=="],
|
||||
|
||||
"@codemirror/lang-python": ["@codemirror/lang-python@6.2.1", "https://registry.npmmirror.com/@codemirror/lang-python/-/lang-python-6.2.1.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.3.2", "@codemirror/language": "^6.8.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/python": "^1.1.4" } }, "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw=="],
|
||||
|
||||
"@codemirror/lang-rust": ["@codemirror/lang-rust@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-rust/-/lang-rust-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/rust": "^1.0.0" } }, "sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA=="],
|
||||
|
||||
"@codemirror/lang-sass": ["@codemirror/lang-sass@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-sass/-/lang-sass-6.0.2.tgz", { "dependencies": { "@codemirror/lang-css": "^6.2.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/sass": "^1.0.0" } }, "sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q=="],
|
||||
|
||||
"@codemirror/lang-sql": ["@codemirror/lang-sql@6.10.0", "https://registry.npmmirror.com/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-6ayPkEd/yRw0XKBx5uAiToSgGECo/GY2NoJIHXIIQh1EVwLuKoU8BP/qK0qH5NLXAbtJRLuT73hx7P9X34iO4w=="],
|
||||
|
||||
"@codemirror/lang-vue": ["@codemirror/lang-vue@0.1.3", "https://registry.npmmirror.com/@codemirror/lang-vue/-/lang-vue-0.1.3.tgz", { "dependencies": { "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-javascript": "^6.1.2", "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.1" } }, "sha512-QSKdtYTDRhEHCfo5zOShzxCmqKJvgGrZwDQSdbvCRJ5pRLWBS7pD/8e/tH44aVQT6FKm0t6RVNoSUWHOI5vNug=="],
|
||||
|
||||
"@codemirror/lang-wast": ["@codemirror/lang-wast@6.0.2", "https://registry.npmmirror.com/@codemirror/lang-wast/-/lang-wast-6.0.2.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-Imi2KTpVGm7TKuUkqyJ5NRmeFWF7aMpNiwHnLQe0x9kmrxElndyH0K6H/gXtWwY6UshMRAhpENsgfpSwsgmC6Q=="],
|
||||
|
||||
"@codemirror/lang-xml": ["@codemirror/lang-xml@6.1.0", "https://registry.npmmirror.com/@codemirror/lang-xml/-/lang-xml-6.1.0.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.0.0", "@lezer/xml": "^1.0.0" } }, "sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg=="],
|
||||
|
||||
"@codemirror/lang-yaml": ["@codemirror/lang-yaml@6.1.3", "https://registry.npmmirror.com/@codemirror/lang-yaml/-/lang-yaml-6.1.3.tgz", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.2.0", "@lezer/lr": "^1.0.0", "@lezer/yaml": "^1.0.0" } }, "sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ=="],
|
||||
|
||||
"@codemirror/language": ["@codemirror/language@6.12.4", "https://registry.npmmirror.com/@codemirror/language/-/language-6.12.4.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A=="],
|
||||
|
||||
"@codemirror/language-data": ["@codemirror/language-data@6.5.2", "https://registry.npmmirror.com/@codemirror/language-data/-/language-data-6.5.2.tgz", { "dependencies": { "@codemirror/lang-angular": "^0.1.0", "@codemirror/lang-cpp": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-go": "^6.0.0", "@codemirror/lang-html": "^6.0.0", "@codemirror/lang-java": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/lang-jinja": "^6.0.0", "@codemirror/lang-json": "^6.0.0", "@codemirror/lang-less": "^6.0.0", "@codemirror/lang-liquid": "^6.0.0", "@codemirror/lang-markdown": "^6.0.0", "@codemirror/lang-php": "^6.0.0", "@codemirror/lang-python": "^6.0.0", "@codemirror/lang-rust": "^6.0.0", "@codemirror/lang-sass": "^6.0.0", "@codemirror/lang-sql": "^6.0.0", "@codemirror/lang-vue": "^0.1.1", "@codemirror/lang-wast": "^6.0.0", "@codemirror/lang-xml": "^6.0.0", "@codemirror/lang-yaml": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/legacy-modes": "^6.4.0" } }, "sha512-CPkWBKrNS8stYbEU5kwBwTf3JB1kghlbh4FSAwzGW2TEscdeHHH4FGysREW86Mqnj3Qn09s0/6Ea/TutmoTobg=="],
|
||||
|
||||
"@codemirror/legacy-modes": ["@codemirror/legacy-modes@6.5.4", "https://registry.npmmirror.com/@codemirror/legacy-modes/-/legacy-modes-6.5.4.tgz", { "dependencies": { "@codemirror/language": "^6.0.0" } }, "sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew=="],
|
||||
|
||||
"@codemirror/lint": ["@codemirror/lint@6.9.7", "https://registry.npmmirror.com/@codemirror/lint/-/lint-6.9.7.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="],
|
||||
|
||||
"@codemirror/search": ["@codemirror/search@6.7.2", "https://registry.npmmirror.com/@codemirror/search/-/search-6.7.2.tgz", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA=="],
|
||||
|
||||
"@codemirror/state": ["@codemirror/state@6.7.6", "https://registry.npmmirror.com/@codemirror/state/-/state-6.7.6.tgz", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w=="],
|
||||
|
||||
"@codemirror/theme-one-dark": ["@codemirror/theme-one-dark@6.1.3", "https://registry.npmmirror.com/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/highlight": "^1.0.0" } }, "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA=="],
|
||||
|
||||
"@codemirror/view": ["@codemirror/view@6.43.13", "https://registry.npmmirror.com/@codemirror/view/-/view-6.43.13.tgz", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "https://registry.npmmirror.com/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "https://registry.npmmirror.com/@esbuild/android-arm/-/android-arm-0.25.12.tgz", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
|
||||
@@ -162,7 +249,43 @@
|
||||
|
||||
"@keyv/serialize": ["@keyv/serialize@1.1.1", "https://registry.npmmirror.com/@keyv/serialize/-/serialize-1.1.1.tgz", {}, "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.28.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.28.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-cO89UyNM/0i2Srdi04nFWeEOQkqzDZlM2ehtWyBhcMpRTJDKpMZPCGAVlmVBgBgr5HaeL5L6FsU8RHsOdwXtKw=="],
|
||||
"@lezer/common": ["@lezer/common@1.5.3", "https://registry.npmmirror.com/@lezer/common/-/common-1.5.3.tgz", {}, "sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q=="],
|
||||
|
||||
"@lezer/cpp": ["@lezer/cpp@1.1.6", "https://registry.npmmirror.com/@lezer/cpp/-/cpp-1.1.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-vh9gWWJOXFVY8HBHK3Twzq8MgwG2iN4GSyzBP9sCGTe37P15x2R14VaBQk0VA0ezTRN1KHYBBsHhvpGZ2Xy/pA=="],
|
||||
|
||||
"@lezer/css": ["@lezer/css@1.3.8", "https://registry.npmmirror.com/@lezer/css/-/css-1.3.8.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og=="],
|
||||
|
||||
"@lezer/go": ["@lezer/go@1.0.1", "https://registry.npmmirror.com/@lezer/go/-/go-1.0.1.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-xToRsYxwsgJNHTgNdStpcvmbVuKxTapV0dM0wey1geMMRc9aggoVyKgzYp41D2/vVOx+Ii4hmE206kvxIXBVXQ=="],
|
||||
|
||||
"@lezer/highlight": ["@lezer/highlight@1.2.5", "https://registry.npmmirror.com/@lezer/highlight/-/highlight-1.2.5.tgz", { "dependencies": { "@lezer/common": "^1.3.0" } }, "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w=="],
|
||||
|
||||
"@lezer/html": ["@lezer/html@1.3.13", "https://registry.npmmirror.com/@lezer/html/-/html-1.3.13.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg=="],
|
||||
|
||||
"@lezer/java": ["@lezer/java@1.1.4", "https://registry.npmmirror.com/@lezer/java/-/java-1.1.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-gQylJ2xHV2xXsVqtnAcJrcROvLZJaQiC0tR//+q0k961BxqvyYttusPkJ8d9T1fPDJKHJW2etUH8XbIn9jhVUg=="],
|
||||
|
||||
"@lezer/javascript": ["@lezer/javascript@1.5.5", "https://registry.npmmirror.com/@lezer/javascript/-/javascript-1.5.5.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-sWg4yX1J6XW67AaAynVt0iwF0M5c+np36TEu+P2ifAJ8haRYvHnWDV28r1jdwnJehWCwXECutAUy56K4RBZIyg=="],
|
||||
|
||||
"@lezer/json": ["@lezer/json@1.0.3", "https://registry.npmmirror.com/@lezer/json/-/json-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ=="],
|
||||
|
||||
"@lezer/lr": ["@lezer/lr@1.4.10", "https://registry.npmmirror.com/@lezer/lr/-/lr-1.4.10.tgz", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A=="],
|
||||
|
||||
"@lezer/markdown": ["@lezer/markdown@1.7.2", "https://registry.npmmirror.com/@lezer/markdown/-/markdown-1.7.2.tgz", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ=="],
|
||||
|
||||
"@lezer/php": ["@lezer/php@1.0.6", "https://registry.npmmirror.com/@lezer/php/-/php-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.1.0" } }, "sha512-QJ2xNXPmsm/Z3IpThq8fnJrEIVpxhsIoj6GZBW0JYEd/l9zxpJZW216X4fzqQY4vgpdGIumypvI4uQjd4tnYtw=="],
|
||||
|
||||
"@lezer/python": ["@lezer/python@1.1.19", "https://registry.npmmirror.com/@lezer/python/-/python-1.1.19.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ=="],
|
||||
|
||||
"@lezer/rust": ["@lezer/rust@1.0.3", "https://registry.npmmirror.com/@lezer/rust/-/rust-1.0.3.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ=="],
|
||||
|
||||
"@lezer/sass": ["@lezer/sass@1.1.0", "https://registry.npmmirror.com/@lezer/sass/-/sass-1.1.0.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ=="],
|
||||
|
||||
"@lezer/xml": ["@lezer/xml@1.0.6", "https://registry.npmmirror.com/@lezer/xml/-/xml-1.0.6.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww=="],
|
||||
|
||||
"@lezer/yaml": ["@lezer/yaml@1.0.4", "https://registry.npmmirror.com/@lezer/yaml/-/yaml-1.0.4.tgz", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.4.0" } }, "sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw=="],
|
||||
|
||||
"@lucide/vue": ["@lucide/vue@1.49.0", "https://registry.npmmirror.com/@lucide/vue/-/vue-1.49.0.tgz", { "peerDependencies": { "vue": ">=3.0.1" } }, "sha512-7xS5gYnLoIx0jlmlRE3Rb71fIHaNqhVBiKMpOlqrYt6nMPy3C/62HJHo5XNsV3HTK+9l3M0hXICrIA7S5v6y5Q=="],
|
||||
|
||||
"@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "https://registry.npmmirror.com/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="],
|
||||
|
||||
"@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
|
||||
|
||||
@@ -256,39 +379,39 @@
|
||||
|
||||
"@tanstack/vue-virtual": ["@tanstack/vue-virtual@3.13.32", "https://registry.npmmirror.com/@tanstack/vue-virtual/-/vue-virtual-3.13.32.tgz", { "dependencies": { "@tanstack/virtual-core": "3.17.4" }, "peerDependencies": { "vue": "^2.7.0 || ^3.0.0" } }, "sha512-E8OCutx7QnwZdvpJijz0Q2PHsYDWBWjnGr3TvgWiqxTU35jB1kVhtkd93scRV7tTFuId2tg3x2iFiw+IE4evjQ=="],
|
||||
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.11.1", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.11.1.tgz", {}, "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA=="],
|
||||
"@tauri-apps/api": ["@tauri-apps/api@2.12.0", "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.12.0.tgz", {}, "sha512-fUSxFX8VABYe9W9K5ROdEaKVkNUFRcMSRofjruvaxztXA+I0XnQHcYHF8m/a6iExRUxsUf0HsFWhPBuH9IgzJw=="],
|
||||
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.11.4.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.11.4", "@tauri-apps/cli-darwin-x64": "2.11.4", "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4", "@tauri-apps/cli-linux-arm64-gnu": "2.11.4", "@tauri-apps/cli-linux-arm64-musl": "2.11.4", "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-gnu": "2.11.4", "@tauri-apps/cli-linux-x64-musl": "2.11.4", "@tauri-apps/cli-win32-arm64-msvc": "2.11.4", "@tauri-apps/cli-win32-ia32-msvc": "2.11.4", "@tauri-apps/cli-win32-x64-msvc": "2.11.4" }, "bin": { "tauri": "tauri.js" } }, "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ=="],
|
||||
"@tauri-apps/cli": ["@tauri-apps/cli@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli/-/cli-2.12.0.tgz", { "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "2.12.0", "@tauri-apps/cli-darwin-x64": "2.12.0", "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.0", "@tauri-apps/cli-linux-arm64-gnu": "2.12.0", "@tauri-apps/cli-linux-arm64-musl": "2.12.0", "@tauri-apps/cli-linux-riscv64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-gnu": "2.12.0", "@tauri-apps/cli-linux-x64-musl": "2.12.0", "@tauri-apps/cli-win32-arm64-msvc": "2.12.0", "@tauri-apps/cli-win32-ia32-msvc": "2.12.0", "@tauri-apps/cli-win32-x64-msvc": "2.12.0" }, "bin": { "tauri": "tauri.js" } }, "sha512-GIShnAR4C16kSTA8NO02fo8fOw/I5z5sAUEB5S2HlPHFnBkbihL4c9a/MpkxOm1+q5S+tFd3X4QUjHWxfyGzpQ=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ=="],
|
||||
"@tauri-apps/cli-darwin-arm64": ["@tauri-apps/cli-darwin-arm64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.0.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-v5J+jISihLGtih1+3yWagbsL+5dbLZORu4vaSI0vhY0Heb+MAW+T/1s1RyKxrQrwEPGBG5kqwfDDTnSbmVkuqA=="],
|
||||
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A=="],
|
||||
"@tauri-apps/cli-darwin-x64": ["@tauri-apps/cli-darwin-x64@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.0.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-g27I07pfW/dMS8vcNqB9lamgKF0TqLlcy8e7t9qDGsB1iaeyjJWb2TgBF4tM9ZwLqPAZUXbsz28oXljO12WC4g=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", { "os": "linux", "cpu": "arm" }, "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ=="],
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": ["@tauri-apps/cli-linux-arm-gnueabihf@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.0.tgz", { "os": "linux", "cpu": "arm" }, "sha512-gXyQ710fNc99YuxFxNyeX9PLSrIpbtgBBj7GQo9tSeRT6fIK40q3/gm7X5jqZo7mWLR2m0R/2ALd3vAWo0Z32Q=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA=="],
|
||||
"@tauri-apps/cli-linux-arm64-gnu": ["@tauri-apps/cli-linux-arm64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-H9cyXuq9WgxoHh2NZ+R+oN+W78x5UwaBDEp0/fmqUUkaBoioCuOZErM9xKiIV6bpNAhmw1RoWZ49u37q/vaiAg=="],
|
||||
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw=="],
|
||||
"@tauri-apps/cli-linux-arm64-musl": ["@tauri-apps/cli-linux-arm64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.0.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-5tFuk3JKMBa1M/iN4gN32OYlSfhY3aqb5PO3zCugxaT+sfecyMKpc3EM9VDbhmwWBE9QD4Tfj7wGhlqx2yy2pQ=="],
|
||||
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "none" }, "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ=="],
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": ["@tauri-apps/cli-linux-riscv64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "none" }, "sha512-LOrMyV+nb7pKq8P0BZtTBQuyzm1ORjn16R9MlupmxuT5LqxtuYJlw3VMwbaeXCToJ8jbP5u9JnkfmbqDlvETXw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ=="],
|
||||
"@tauri-apps/cli-linux-x64-gnu": ["@tauri-apps/cli-linux-x64-gnu@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-aMIkI+X9qvD2+k80QZB3tuOYT41/cEheikC510CwAIZ31KLXORsRASYYzM4mi1/58ICmtzSLFhCC08keir7COw=="],
|
||||
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", { "os": "linux", "cpu": "x64" }, "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A=="],
|
||||
"@tauri-apps/cli-linux-x64-musl": ["@tauri-apps/cli-linux-x64-musl@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.0.tgz", { "os": "linux", "cpu": "x64" }, "sha512-9gl3NhUbfuGhSKjeGCypKSdtoezOQRcDUrkhTWtLQEjnajets6peO6NadgI2DF0OzbiiFOzrnnIGMwBS+Ap6Iw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ=="],
|
||||
"@tauri-apps/cli-win32-arm64-msvc": ["@tauri-apps/cli-win32-arm64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-1W+v86wsYLuyBDN0iDessD4CD9o+yNyO0m8Dp3+/vfjiZrJ/v7R7/aTRBeikaq2tLGgxeag0gxnFggBNBGw91A=="],
|
||||
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA=="],
|
||||
"@tauri-apps/cli-win32-ia32-msvc": ["@tauri-apps/cli-win32-ia32-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.0.tgz", { "os": "win32", "cpu": "ia32" }, "sha512-SsBjvq4f7YaBGqcWoE3cycoItPf0SrQeqFqWWgfxoeZWAIz01E31LDSeZ2p/etJiIY0R9oi045chkFfb0O7WGw=="],
|
||||
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.11.4", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz", { "os": "win32", "cpu": "x64" }, "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw=="],
|
||||
"@tauri-apps/cli-win32-x64-msvc": ["@tauri-apps/cli-win32-x64-msvc@2.12.0", "https://registry.npmmirror.com/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-9zzDKYUH4TKKBgRdDdVQX8fiRO5gJ8hD1nGsHU9DOHG5Jpm3arjbu9Xg1frR20EusG3Sl8X0dppoO/4EoUXUGg=="],
|
||||
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.5.1", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.5.1.tgz", { "dependencies": { "@tauri-apps/api": "^2.8.0" } }, "sha512-zS/xx7yzveCcotkA+8TqkI2lysmG2wvQXv2HGAVExITmnFfHAdj1arGsbbfs3o6EktRHf6l34pJxc3YGG2mg7w=="],
|
||||
"@tauri-apps/plugin-autostart": ["@tauri-apps/plugin-autostart@2.6.0", "https://registry.npmmirror.com/@tauri-apps/plugin-autostart/-/plugin-autostart-2.6.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-myppl3C/dygGbn7Inmm3LqsAQ7SSsT3KtNpSt/e+fA5J7xeCIf8H+LMiE1tkS7mKzTfChCutfZCt0FQkrL/YdA=="],
|
||||
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.7.2", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.7.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-pX0IGm1I3I6wc+zeKYcq1GSqogK6okCNX5fOdaNU5ab1AjGS6l1E5wFNjEb7meg7ZFSp0JUs+0jQGQNyOvLrsg=="],
|
||||
"@tauri-apps/plugin-dialog": ["@tauri-apps/plugin-dialog@2.8.0", "https://registry.npmmirror.com/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-HSSD5C8UFE9ijD1wue84F7jjaIReFmj8AAPtS+xyjYRltJafIc4BiWHY7SJ6vbbew6u+YljEJHfyNfy5VwywXg=="],
|
||||
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.3.2", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.3.2.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-UReHNXrLvpEjylE4jb4oCYiy96uRykPUthoCQCmRXYrd5hs5X9DrW+qOn7GLW57EJN4tdK8bgK5twBTz2NOxzA=="],
|
||||
"@tauri-apps/plugin-global-shortcut": ["@tauri-apps/plugin-global-shortcut@2.4.0", "https://registry.npmmirror.com/@tauri-apps/plugin-global-shortcut/-/plugin-global-shortcut-2.4.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-XBA4PcRjRdJBp/jwFxc5YZ/yKhZuslpOG/pGaNfhnRDVGMQfoXEKMv/6A6vjzfKLUxr8ml3ay8o2W8Rk6mHICA=="],
|
||||
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.5.4", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.5.4.tgz", { "dependencies": { "@tauri-apps/api": "^2.11.0" } }, "sha512-1HnPkb+AmgO29HBazm4uPLKB+r7zzcTBW1d0fyYp1uP+jwtpoiNDGKMMzz58SFp49nOIrxdE3aUJtT57lfO9CQ=="],
|
||||
"@tauri-apps/plugin-opener": ["@tauri-apps/plugin-opener@2.7.0", "https://registry.npmmirror.com/@tauri-apps/plugin-opener/-/plugin-opener-2.7.0.tgz", { "dependencies": { "@tauri-apps/api": "^2.12.0" } }, "sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw=="],
|
||||
|
||||
"@types/esrecurse": ["@types/esrecurse@4.3.1", "https://registry.npmmirror.com/@types/esrecurse/-/esrecurse-4.3.1.tgz", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],
|
||||
|
||||
@@ -296,12 +419,20 @@
|
||||
|
||||
"@types/json-schema": ["@types/json-schema@7.0.15", "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.15.tgz", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
|
||||
|
||||
"@types/linkify-it": ["@types/linkify-it@5.0.0", "https://registry.npmmirror.com/@types/linkify-it/-/linkify-it-5.0.0.tgz", {}, "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q=="],
|
||||
|
||||
"@types/markdown-it": ["@types/markdown-it@14.2.0", "https://registry.npmmirror.com/@types/markdown-it/-/markdown-it-14.2.0.tgz", { "dependencies": { "@types/linkify-it": "^5", "@types/mdurl": "^2" } }, "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ=="],
|
||||
|
||||
"@types/mdurl": ["@types/mdurl@2.0.0", "https://registry.npmmirror.com/@types/mdurl/-/mdurl-2.0.0.tgz", {}, "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg=="],
|
||||
|
||||
"@types/node": ["@types/node@26.1.1", "https://registry.npmmirror.com/@types/node/-/node-26.1.1.tgz", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw=="],
|
||||
|
||||
"@types/qrcode": ["@types/qrcode@1.5.6", "https://registry.npmmirror.com/@types/qrcode/-/qrcode-1.5.6.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
|
||||
|
||||
"@types/sortablejs": ["@types/sortablejs@1.15.9", "https://registry.npmmirror.com/@types/sortablejs/-/sortablejs-1.15.9.tgz", {}, "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ=="],
|
||||
|
||||
"@types/trusted-types": ["@types/trusted-types@2.0.7", "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
|
||||
|
||||
"@types/web-bluetooth": ["@types/web-bluetooth@0.0.21", "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", {}, "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/type-utils": "8.70.0", "@typescript-eslint/utils": "8.70.0", "@typescript-eslint/visitor-keys": "8.70.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.70.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-/v8HZt6RlyIZxB3ntehELOcUcfxKPVGWXnQdJuHRmzrqgF8nQypcC/oxGW+Ot4VGKDq81XugPKxx0n5PBtf9PA=="],
|
||||
@@ -324,6 +455,8 @@
|
||||
|
||||
"@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.70.0", "https://registry.npmmirror.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.70.0.tgz", { "dependencies": { "@typescript-eslint/types": "8.70.0", "eslint-visitor-keys": "^5.0.0" } }, "sha512-BoC8PiO4Hkdo0TVJh9Ntxr5MxPDI7/oFsrygN5ADelFSeXG/qgNuucIGA+L5Z6JpPTE/uRfcTWtscjbUaufepQ=="],
|
||||
|
||||
"@uiw/codemirror-themes": ["@uiw/codemirror-themes@4.25.12", "https://registry.npmmirror.com/@uiw/codemirror-themes/-/codemirror-themes-4.25.12.tgz", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0" } }, "sha512-3bLX6C+gstr82SmY2FAj2TfHXnl2SnC+whRZJmRsv82wMhG8RZlZVy+o0rLuGRIPD9acuY0gpouHVRNUnzBj3g=="],
|
||||
|
||||
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@5.2.4", "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", { "peerDependencies": { "vite": "^5.0.0 || ^6.0.0", "vue": "^3.2.25" } }, "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA=="],
|
||||
|
||||
"@volar/language-core": ["@volar/language-core@2.4.15", "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.15.tgz", { "dependencies": { "@volar/source-map": "2.4.15" } }, "sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA=="],
|
||||
@@ -394,6 +527,8 @@
|
||||
|
||||
"ansi-styles": ["ansi-styles@4.3.0", "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"argparse": ["argparse@3.0.2", "https://registry.npmmirror.com/argparse/-/argparse-3.0.2.tgz", {}, "sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ=="],
|
||||
|
||||
"aria-hidden": ["aria-hidden@1.2.6", "https://registry.npmmirror.com/aria-hidden/-/aria-hidden-1.2.6.tgz", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
|
||||
|
||||
"balanced-match": ["balanced-match@4.0.4", "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
|
||||
@@ -422,6 +557,8 @@
|
||||
|
||||
"copy-anything": ["copy-anything@4.0.5", "https://registry.npmmirror.com/copy-anything/-/copy-anything-4.0.5.tgz", { "dependencies": { "is-what": "^5.2.0" } }, "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA=="],
|
||||
|
||||
"crelt": ["crelt@1.0.7", "https://registry.npmmirror.com/crelt/-/crelt-1.0.7.tgz", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "https://registry.npmmirror.com/cross-spawn/-/cross-spawn-7.0.6.tgz", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"cssesc": ["cssesc@3.0.0", "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
|
||||
@@ -442,11 +579,13 @@
|
||||
|
||||
"dijkstrajs": ["dijkstrajs@1.0.3", "https://registry.npmmirror.com/dijkstrajs/-/dijkstrajs-1.0.3.tgz", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="],
|
||||
|
||||
"dompurify": ["dompurify@3.4.16", "https://registry.npmmirror.com/dompurify/-/dompurify-3.4.16.tgz", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@8.0.0", "https://registry.npmmirror.com/emoji-regex/-/emoji-regex-8.0.0.tgz", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
|
||||
|
||||
"enhanced-resolve": ["enhanced-resolve@5.21.6", "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
"entities": ["entities@8.1.0", "https://registry.npmmirror.com/entities/-/entities-8.1.0.tgz", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
|
||||
|
||||
"esbuild": ["esbuild@0.25.12", "https://registry.npmmirror.com/esbuild/-/esbuild-0.25.12.tgz", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
|
||||
|
||||
@@ -506,6 +645,8 @@
|
||||
|
||||
"he": ["he@1.2.0", "https://registry.npmmirror.com/he/-/he-1.2.0.tgz", { "bin": { "he": "bin/he" } }, "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw=="],
|
||||
|
||||
"highlight.js": ["highlight.js@11.12.0", "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.12.0.tgz", {}, "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg=="],
|
||||
|
||||
"hookable": ["hookable@5.5.3", "https://registry.npmmirror.com/hookable/-/hookable-5.5.3.tgz", {}, "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ=="],
|
||||
|
||||
"hookified": ["hookified@1.15.1", "https://registry.npmmirror.com/hookified/-/hookified-1.15.1.tgz", {}, "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg=="],
|
||||
@@ -560,10 +701,16 @@
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
|
||||
|
||||
"linkify-it": ["linkify-it@6.1.0", "https://registry.npmmirror.com/linkify-it/-/linkify-it-6.1.0.tgz", { "dependencies": { "uc.micro": "^3.0.0" } }, "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw=="],
|
||||
|
||||
"locate-path": ["locate-path@6.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-6.0.0.tgz", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"markdown-it": ["markdown-it@15.0.2", "https://registry.npmmirror.com/markdown-it/-/markdown-it-15.0.2.tgz", { "dependencies": { "argparse": "^3.0.0", "entities": "^8.0.0", "linkify-it": "^6.0.0", "mdurl": "^2.1.0", "punycode.js": "^2.3.1", "uc.micro": "^3.0.0" }, "bin": { "markdown-it": "bin/markdown-it.mjs" } }, "sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw=="],
|
||||
|
||||
"mdurl": ["mdurl@2.1.0", "https://registry.npmmirror.com/mdurl/-/mdurl-2.1.0.tgz", {}, "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg=="],
|
||||
|
||||
"merge2": ["merge2@1.4.1", "https://registry.npmmirror.com/merge2/-/merge2-1.4.1.tgz", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
|
||||
|
||||
"micromatch": ["micromatch@4.0.8", "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
|
||||
@@ -618,13 +765,15 @@
|
||||
|
||||
"punycode": ["punycode@2.3.1", "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
|
||||
|
||||
"punycode.js": ["punycode.js@2.3.1", "https://registry.npmmirror.com/punycode.js/-/punycode.js-2.3.1.tgz", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
|
||||
|
||||
"qified": ["qified@0.10.1", "https://registry.npmmirror.com/qified/-/qified-0.10.1.tgz", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="],
|
||||
|
||||
"qrcode": ["qrcode@1.5.4", "https://registry.npmmirror.com/qrcode/-/qrcode-1.5.4.tgz", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"reka-ui": ["reka-ui@2.10.1", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.1.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-drcOQ4rQtDYAcGCsyQBqQg8QQ+H3B+zDaMJU0h8KPEPMa7g9BHu3zcOi4OB39XJSWizceFoNO0Z9tctSGLOXqg=="],
|
||||
"reka-ui": ["reka-ui@2.10.5", "https://registry.npmmirror.com/reka-ui/-/reka-ui-2.10.5.tgz", { "dependencies": { "@floating-ui/dom": "^1.6.13", "@floating-ui/vue": "^1.1.6", "@internationalized/date": "^3.5.0", "@internationalized/number": "^3.5.0", "@tanstack/vue-virtual": "^3.12.0", "@vueuse/core": "^14.1.0", "@vueuse/shared": "^14.1.0", "aria-hidden": "^1.2.4", "defu": "^6.1.5", "ohash": "^2.0.11" }, "peerDependencies": { "vue": ">= 3.4.0" } }, "sha512-/8o0y9BThE0hcHKFg+3770tWcJh3qKdOEFxLOPb9HIajXeFoH/J530cZH62jUJunbqwBgpSBL9v7nB8LJ5pDXA=="],
|
||||
|
||||
"require-directory": ["require-directory@2.1.1", "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
|
||||
|
||||
@@ -654,6 +803,8 @@
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "https://registry.npmmirror.com/strip-ansi/-/strip-ansi-6.0.1.tgz", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"style-mod": ["style-mod@4.1.4", "https://registry.npmmirror.com/style-mod/-/style-mod-4.1.4.tgz", {}, "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw=="],
|
||||
|
||||
"superjson": ["superjson@2.2.6", "https://registry.npmmirror.com/superjson/-/superjson-2.2.6.tgz", { "dependencies": { "copy-anything": "^4" } }, "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA=="],
|
||||
|
||||
"tailwind-merge": ["tailwind-merge@3.6.0", "https://registry.npmmirror.com/tailwind-merge/-/tailwind-merge-3.6.0.tgz", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="],
|
||||
@@ -678,6 +829,8 @@
|
||||
|
||||
"typescript-eslint": ["typescript-eslint@8.70.0", "https://registry.npmmirror.com/typescript-eslint/-/typescript-eslint-8.70.0.tgz", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.70.0", "@typescript-eslint/parser": "8.70.0", "@typescript-eslint/typescript-estree": "8.70.0", "@typescript-eslint/utils": "8.70.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-P/W5cz70/cQAuKfY3xwQMWWTV7BvJ0mAQmi+9mBcsVPaBUpd6Ohpa+fECv9rBFrQcig86jAiNBFNWUqnTjr4pw=="],
|
||||
|
||||
"uc.micro": ["uc.micro@3.0.0", "https://registry.npmmirror.com/uc.micro/-/uc.micro-3.0.0.tgz", {}, "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw=="],
|
||||
|
||||
"undici-types": ["undici-types@8.3.0", "https://registry.npmmirror.com/undici-types/-/undici-types-8.3.0.tgz", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],
|
||||
|
||||
"uri-js": ["uri-js@4.4.1", "https://registry.npmmirror.com/uri-js/-/uri-js-4.4.1.tgz", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
|
||||
@@ -700,6 +853,8 @@
|
||||
|
||||
"vue-tsc": ["vue-tsc@2.2.12", "https://registry.npmmirror.com/vue-tsc/-/vue-tsc-2.2.12.tgz", { "dependencies": { "@volar/typescript": "2.4.15", "@vue/language-core": "2.2.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "./bin/vue-tsc.js" } }, "sha512-P7OP77b2h/Pmk+lZdJ0YWs+5tJ6J2+uOQPo7tlBnY44QqQSPYvS0qVT4wqDJgwrZaLe47etJLLQRFia71GYITw=="],
|
||||
|
||||
"w3c-keyname": ["w3c-keyname@2.2.8", "https://registry.npmmirror.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
|
||||
|
||||
"which": ["which@2.0.2", "https://registry.npmmirror.com/which/-/which-2.0.2.tgz", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"which-module": ["which-module@2.0.1", "https://registry.npmmirror.com/which-module/-/which-module-2.0.1.tgz", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
|
||||
@@ -734,6 +889,8 @@
|
||||
|
||||
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.9", "https://registry.npmmirror.com/ignore/-/ignore-7.0.9.tgz", {}, "sha512-brTTsvFRt5C1gGHtPst/281UjPD5t9fBqbgoMPlVWy11ZLTPfu7HxK4ZYqO9H7o/yC9rSTCI85EaQ4OoY12qYw=="],
|
||||
|
||||
"@vue/compiler-core/entities": ["entities@7.0.1", "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"@vue/language-core/minimatch": ["minimatch@9.0.9", "https://registry.npmmirror.com/minimatch/-/minimatch-9.0.9.tgz", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
|
||||
|
||||
"fast-glob/glob-parent": ["glob-parent@5.1.2", "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
@@ -742,16 +899,10 @@
|
||||
|
||||
"qified/hookified": ["hookified@2.2.0", "https://registry.npmmirror.com/hookified/-/hookified-2.2.0.tgz", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="],
|
||||
|
||||
"reka-ui/@vueuse/core": ["@vueuse/core@14.3.0", "https://registry.npmmirror.com/@vueuse/core/-/core-14.3.0.tgz", { "dependencies": { "@types/web-bluetooth": "^0.0.21", "@vueuse/metadata": "14.3.0", "@vueuse/shared": "14.3.0" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-aHfz47g0ZhMtTVHmIzMVpJy8ePhhOy68GY5bv110+5DVtZ+W7BsOx+m61UNQqfrWyPztIHIanWa3E2tib3NFIw=="],
|
||||
|
||||
"reka-ui/@vueuse/shared": ["@vueuse/shared@14.3.0", "https://registry.npmmirror.com/@vueuse/shared/-/shared-14.3.0.tgz", { "peerDependencies": { "vue": "^3.5.0" } }, "sha512-bZpge9eSXwa4ToSiqJ7j6KRwhAsneMFoSz3LMWKQDkqimm3D/tbFlrklrs/IOqC8tEcYmXQZJ6N0UrjhBirVCg=="],
|
||||
|
||||
"yargs/find-up": ["find-up@4.1.0", "https://registry.npmmirror.com/find-up/-/find-up-4.1.0.tgz", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion": ["brace-expansion@2.1.2", "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.1.2.tgz", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA=="],
|
||||
|
||||
"reka-ui/@vueuse/core/@vueuse/metadata": ["@vueuse/metadata@14.3.0", "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-14.3.0.tgz", {}, "sha512-BwxmbAzwAVF50+MW57GXOUEV61nFBGnlBvrTqj49PqWJu3uw7hdu72ztXeZ33RdZtDY6kO+bfCAE1PCn88Tktw=="],
|
||||
|
||||
"yargs/find-up/locate-path": ["locate-path@5.0.0", "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],
|
||||
|
||||
"@vue/language-core/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,519 @@
|
||||
# 编辑器模块规划(Editor Module Plan)
|
||||
|
||||
> 状态:**方案已确认,待开工**(v1 已落地;v2 定位修订与本轮 10 项决策已定稿)
|
||||
> 本轮决策(2026-09-30,用户已拍板):**不引入工作区**(Q2=a)· **目录树不纳入索引**(Q3=a)· **标签页放 P4**(Q4=a)· **模块显示名 = 编辑器**(Q1=a)
|
||||
> v1 现状(原「笔记模块」,已全部落地):CM6 内核 + Live Preview + 本地笔记库 + 独立窗口 + 检索/索引 + WebDAV + 导入导出 + 模板 + 双链 + 图片预览 + 全局快捷键 + 文件关联
|
||||
> v2 修订方向:模块核心从「笔记」改为「**编辑器**」——一个 notepad++ 式的通用文本/代码编辑器;**笔记库与本地目录探查退化为它的两个并列导航能力**,不再是模块的中心
|
||||
> 已确认决策:所见即所得 = **Live Preview**(非块编辑);WebDAV = **备份 / 同步目标**(不做远端直连读写);编码 = **可探测、可切换、原样写回**
|
||||
> 定位:Thing 工具集的第 13 个模块,`id = editor`(原 `notes`),`category = 'tool'`
|
||||
> 作者:砚 | 日期:2026-09-30
|
||||
> 关联文档:`AI_DEV_GUIDE.md`(模块注册 / IPC / 进程管理范式)、`UI_DESIGN_SYSTEM.md`(页面框架 / 组件规范)、`TERMINAL_MODULE_PLAN.md`(独立窗口 / 跨窗口设置同步范式)
|
||||
>
|
||||
> 阅读顺序:**§11 开工清单(先读,它是执行入口)** → §0 结论 → §1 定位修订 → §3 功能规格 → §5 编码 → §7 缺口 → §8 路线图。
|
||||
> **§9 是 v1 的压缩实施记录**,只保留「为什么这么做」的结论与踩过的坑;**§10 是已拍板的决策表**(不再是待定项)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论先行
|
||||
|
||||
八个关键判断。
|
||||
|
||||
1. **模块改名 `notes` → `editor`,但一次到位、不留双命名。** `id` / 窗口 label / 事件名 / Rust 命令前缀 / 目录名 / 存储键全部统一。半改不改(模块叫 editor、命令还叫 `notes_*`)比不改更糟:读代码的人要同时维护两套心智。改名是机械工作(约 400 处标识符),风险集中在「漏改一处」,用脚本核对(§9.6)。
|
||||
|
||||
2. **「笔记」不是被删掉,而是被降级为一种能力。** 编辑器的最小模型是「路径 + 字节 + 编码」,笔记库是加在它之上的一层(库根沙箱 + front-matter + 索引 + 双链)。因此**文件是真相层,笔记库是视图层**——这条和 v1 的「文件即真相」并不冲突,只是把「库」从中心挪到了并列位置。
|
||||
|
||||
3. **左侧导航 = 两个并列的树 + 三块辅助能力。** 两个树:**笔记库**(沙箱、有索引、有双链)与**本地目录**(任意路径、无索引、无 front-matter 语义)。三块辅助:**文件名/内容搜索**、**最近打开(文件夹与文件分开记)**、**定位到资源管理器**。
|
||||
|
||||
4. **多编码是这一版的新增硬需求,且必须「可切换」。** 探测链:BOM → 严格 UTF-8 → GB18030(中文存量主力)→ 用户手动指定。写回**默认按读取时的编码**。切换编码的语义是「**换一种方式解释磁盘字节**」而不是「重新解释缓冲区文本」——因此切换动作会**从磁盘按新编码重新解码**(有未保存改动时先让用户三选一,见 §5.3)。
|
||||
|
||||
5. **系统集成走用户级注册表,不需要管理员权限。** 文件关联(双击打开)走 Tauri `fileAssociations`;**资源管理器右键菜单**(文件/文件夹)走 `HKCU\Software\Classes\*\shell\*` 与 `Directory\shell\*`,用**已在依赖树里的 `winreg`** 写(项目已有 `system_proxy.rs` / `glsmtc.rs` 两处先例)。**注册动作放在设置页按钮里、默认不自动写注册表**——开发模式下的 exe 路径是 `target\debug\thing.exe`,自动注册会留下指向临时产物的僵尸菜单项。
|
||||
|
||||
6. **默认全局快捷键 `Alt+E` 打开编辑器。** 走既有 `shortcut.rs`(原子注册 + 冲突检测),设置页可改。
|
||||
|
||||
7. **不引入「工作区」概念(已拍板)。** 用户要的是「右键文件夹 → 在这里打开」,用**当前目录根**这一个状态就够了(可切换 + 有历史)。引入 workspace 会连带出「多根 / 会话恢复 / 每根独立状态」三个复杂度,而收益(同时开两个目录树)在 notepad++ 式用法里很低。因此侧栏只有一个「目录」面板,根是单值。
|
||||
|
||||
8. **不做的事**(明确划界,避免无限扩张):不做 IDE 能力(调试器、终端内嵌、LSP 补全、Git 集成);不做块编辑器;不做远端工作区(WebDAV 只做备份/同步目标)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 定位修订(v1 → v2)
|
||||
|
||||
| 维度 | v1(笔记模块) | v2(编辑器模块) |
|
||||
|---|---|---|
|
||||
| 一句话 | 一个 Markdown 笔记库,带所见即所得编辑 | 一个通用文本/代码编辑器,**顺带**能管一个笔记库 |
|
||||
| 中心对象 | 笔记(库内 `.md`) | 文件(任意路径的任意文本) |
|
||||
| 首要入口 | 库树 → 选一篇笔记 | 打开文件 / 最近文件 / 目录树 → 选一个文件 |
|
||||
| 笔记库的角色 | 模块的**全部** | 两个导航根之一 + 一层语义(front-matter / 双链 / 索引) |
|
||||
| 编码 | 「尽量别写坏」(读时记、写回原样) | **一级功能**:探测 + 状态栏显示 + 可切换 |
|
||||
| 系统集成 | 无(P2 曾因依赖代价搁置) | 文件关联 + 资源管理器右键 + `Alt+E` |
|
||||
| 索引 | FTS5 全文检索(笔记的核心) | 保留,但只服务笔记库;目录树只做文件名匹配 |
|
||||
| markdown Live Preview | 默认视图 | **按文件类型自动选择**:`.md` 用 Live Preview,其余用纯高亮 |
|
||||
|
||||
> 一句话总结这次修订:**把「库」从产品中心降为两个导航能力之一,把「文件 + 编码 + 系统集成」提到中心。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 需求解构
|
||||
|
||||
| 用户原话 | 解构为 | 落点 |
|
||||
|---|---|---|
|
||||
| 「核心改为 Editer,标题和其他都改」 | 模块改名 + 重定位 + 主页面/窗口标题/文案全面改口径 | §1 / §7 / §9.6 |
|
||||
| 「笔记作为编辑器模块的一个核心功能」 | 笔记库降为并列能力,但保留全部既有实现 | §1 / §3.3 |
|
||||
| 「左边导航栏有两个功能:笔记库 / 本地目录结构」 | 侧栏两个并列根:库根(沙箱 + 索引)与当前目录(任意) | §3.3 / §6 |
|
||||
| 「导航栏需要定位打开文件位置、搜索文件名(参考 idea)」 | 「在资源管理器中显示」+ 两级过滤(文件名 LIKE / 库内 FTS) | §3.4 |
|
||||
| 「核心只是普通编辑器,类似 notepad++」 | 不引入 IDE 能力;以「打开快、编码稳、快捷键全」为质量目标 | §0.8 / §3.1 |
|
||||
| 「快捷键直接打开编辑器,默认 alt+e」 | 全局快捷键,默认 `Alt+E`,设置页可改 | §3.7 |
|
||||
| 「文件管理器右键菜单,用 Thing Editer 打开」 | HKCU 注册 `*\shell\ThingEditor` 与 `Directory\shell\ThingEditor` | §3.6 |
|
||||
| 「历史打开的文件夹/文件记录」 | 最近文件 + 最近文件夹两份列表(分组显示、可清空) | §3.5 |
|
||||
| 「多编码,识别 + 支持切换编码」 | 探测链 + 状态栏编码菜单 + 重解码 + 按新编码重写 | §5 |
|
||||
| 「优化结构和功能完整性」 | 补齐:编码切换、目录树、最近记录、右键菜单、大文件策略、只读打开 | §3 / §4 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 功能规格
|
||||
|
||||
### 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/源码。
|
||||
- **多文档**:同一窗口内多标签(**新增**,见 §8-P1)。`Ctrl+W` 关闭标签,关闭前若有未保存改动则二次确认。
|
||||
- **大文件策略**:超过阈值(默认 5MB,可配)时关闭 Live Preview / 折叠 / 补全 / 装饰,只保留高亮 + 行号;并在状态栏给出可点击的降级说明。
|
||||
- **只读打开**:检测到文件不可写时以只读模式打开(替代「打开成功但保存失败」)。
|
||||
|
||||
### 3.2 笔记模式(`.md` 在库内)
|
||||
|
||||
保持 v1 全部能力:Live Preview(标题/强调/行内代码/列表/任务/引用/代码块/分隔线/表格/图片内联)、`[[wikilink]]` 点击跳转与一键新建、front-matter 属性面板、大纲、双链面板、字数/行数统计。
|
||||
|
||||
### 3.3 左侧导航(两个并列根)
|
||||
|
||||
| 面板 | 根 | 能力 | 数据来源 |
|
||||
|---|---|---|---|
|
||||
| **笔记库** | 库根(可切换,默认 `{appData}/editor/library`) | 树 / 新建 / 重命名 / 删除 / 标签 / 双链 / FTS 全文检索 | SQLite 索引(`notes.db` → `editor.db`) |
|
||||
| **本地目录** | 当前目录根(可切换,有历史) | 树 / 文件名过滤 / 打开文件 / 新建文件/文件夹 / 重命名 / 删除 / 在资源管理器中显示 / 复制路径 | 直接 `fs` 读目录(**不进索引**) |
|
||||
|
||||
两个面板都在**同一个侧栏**里用分段导航切换(v1 已有 4 段:文件/检索/大纲/双链;v2 扩为:**库 / 目录 / 检索 / 最近**,大纲与双链改为编辑区右侧的**抽屉**,因为它们跟「当前文档」绑定而不是跟「导航」绑定)。
|
||||
|
||||
> 为什么把大纲/双链挪到右侧抽屉:它们描述的是**当前文档**,而侧栏描述的是**去哪找文件**。混在一起会让侧栏在「导航」与「文档信息」两种语义之间摇摆(v1 已经能感到这个别扭)。
|
||||
|
||||
### 3.4 搜索与定位
|
||||
|
||||
- **文件名过滤**:侧栏顶部输入框,对当前树做不区分大小写的子串匹配,命中项的**祖先自动展开**(v1 已有)。
|
||||
- **快速打开 `Ctrl+P`**:跨「库 + 最近 + 当前目录」的文件名跳转,本地模糊排序(连续匹配 > 前缀 > 词首 > 位置),零网络、零后端。
|
||||
- **库内全文检索 `Ctrl+Shift+F`**:FTS5(trigram),标题权重高于正文,命中片段高亮(定界符方案,不注入 HTML)。目录树**不做**全文检索(不在索引里,也不该为此扫盘)。
|
||||
- **定位打开文件位置**:`revealItemInDir`(`opener` 插件,能力已授权)。三处入口:标签右键、侧栏行右键、状态栏路径点击。
|
||||
- **搜索文件名作用域切换**:输入框旁边一个「当前树 / 全库 / 当前目录」的小切换(idea 的 `Ctrl+Shift+N` 体验,但不引入独立对话框)。
|
||||
|
||||
### 3.5 历史记录
|
||||
|
||||
- **最近文件**:路径 + 显示名 + 时间 + 是否仍存在(失效项灰显、可一键清理)。
|
||||
- **最近文件夹**:同理,用于「右键文件夹 → 在这里打开」与侧栏目录面板的快速切换。
|
||||
- 存储:`editor/settings.json` 的 `recentFiles` / `recentFolders`(**与笔记库解耦** —— 库可以换/删,历史不该跟着丢)。各自上限 20 条,超出淘汰最旧。
|
||||
- 两份列表**分开存**:文件与文件夹的用途不同,混在一起会让「最近文件夹」被文件挤掉。
|
||||
|
||||
### 3.6 系统集成
|
||||
|
||||
| 集成 | 机制 | 权限 |
|
||||
|---|---|---|
|
||||
| 双击 `.md`/`.markdown`/`.mdx` 打开 | `bundle.fileAssociations`(安装器写 `OpenWithProgids`) | 安装器 |
|
||||
| 「用 Thing 编辑器打开」(文件) | `HKCU\Software\Classes\*\shell\ThingEditor` | 用户级,免管理员 |
|
||||
| 「用 Thing 编辑器打开」(文件夹) | `HKCU\Software\Classes\Directory\shell\ThingEditor` | 同上 |
|
||||
| 「用 Thing 编辑器打开」(目录背景) | `HKCU\Software\Classes\Directory\Background\shell\ThingEditor` | 同上 |
|
||||
| 菜单图标 | 菜单项 `Icon` 值指向 exe(用 exe 自带图标) | — |
|
||||
| 已运行时的二次启动 | `tauri-plugin-single-instance` 转交 argv 给已有实例 | 已落地 |
|
||||
| 免注册表运行 | 设置页提供「注册 / 卸载右键菜单」按钮,并显示当前 exe 路径 | — |
|
||||
|
||||
**关键约束**:注册表条目里写的是**绝对 exe 路径**。
|
||||
- 打包安装后:指向安装目录的 exe,稳定;
|
||||
- `tauri dev` 下:指向 `target\debug\thing.exe`,一旦清理 target 就变成死链。
|
||||
→ 因此**默认不注册**,且注册时校验 exe 存在;设置页在 dev 环境下给出明确提示。
|
||||
|
||||
### 3.7 全局快捷键
|
||||
|
||||
| 快捷键 | 动作 | 默认 |
|
||||
|---|---|---|
|
||||
| `Alt+E` | 打开编辑器窗口(无参数 = 上次的文档/最近文件) | **本版新增默认值** |
|
||||
| `Ctrl+Shift+N` | 新建笔记(直接落库根) | 空(v1 已有实现,改为可配) |
|
||||
|
||||
两者都走 `shortcut.rs`,触发时只发事件、窗口由前端创建(v1 已确立的姿态)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 存储、索引与目录树
|
||||
|
||||
```
|
||||
{appData}/editor/ # 模块自身(与库解耦)
|
||||
├── settings.json # 设置 + 最近文件/文件夹
|
||||
├── editor.db # 笔记库索引(可重建)
|
||||
└── library/ # 默认库根
|
||||
├── notes/ assets/ templates/
|
||||
└── .editor/ # 库内私有:同步基线 sync.json
|
||||
```
|
||||
|
||||
- **配置文件全量走 `settings.json`**(v1 已如此),新增 `recentFiles` / `recentFolders` / `defaultEncoding` / `largeFileMb` / `contextMenuEnabled`。
|
||||
- **索引服务架构不变**(单线程 worker 独占 `rusqlite` 连接 + 通道排队 + notify 监听),只改名。
|
||||
- **目录树不进索引**:它是「看盘」而不是「管库」。目录树节点按需 `read_dir`(带缓存与手动刷新),深度上限与库树一致(24)。
|
||||
- **配置改动只在用户显式操作下发生**:目录树上的新建/重命名/删除都是显式动作,且删除走系统回收站(复用 `quickpanel` 的回收站实现,`terminal/local_fs.rs` 已有先例)。**目录树自身不做任何隐式写入**(不生成索引、不生成元数据文件、不自动整理)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 编码:探测、显示、切换
|
||||
|
||||
### 5.1 探测链(按优先级)
|
||||
|
||||
| 顺序 | 判据 | 结论 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 1 | `EF BB BF` / `FF FE` / `FE FF` | `utf-8-bom` / `utf-16le` / `utf-16be` | BOM 是无歧义事实,直接采信 |
|
||||
| 2 | `std::str::from_utf8` 通过 | `utf-8` | 结构性校验,不是统计猜测 |
|
||||
| 3 | 以上失败 | `gb18030` | 中文存量主力(GBK 超集),比「猜 Big5/Shift_JIS」安全 |
|
||||
| 4 | 用户手动指定 | 用户值 | 前三级都可能错,必须留人工兜底 |
|
||||
|
||||
**刻意不做**:字符频率统计 + 多编码自信度比较(chardet 式)。理由是它在短文本上比规则更不可靠,而本项目的主要场景(代码/配置/中文笔记)恰好都是「UTF-8 或 GB18030」二选一。真错了有第 4 级兜底,代价可控。
|
||||
|
||||
### 5.2 读取与状态
|
||||
|
||||
读文件时一次性回传:`content`(已解码 UTF-8 字符串 + 换行归一为 `\n`)、`encoding`(探测结果)、`eol`(`lf`/`crlf`)、`size`、`large`、`readonly`。
|
||||
|
||||
- 状态栏显示:`UTF-8` / `GB18030` / `UTF-8 BOM` + `CRLF` / `LF` + 只读标记。
|
||||
- `readonly`:打开时用 `OpenOptions::new().write(true).open()` 探一次写权限(**不实际写入**),失败则置只读。这比「打开成功但保存时才报错」体验好得多。
|
||||
- 编码名一律用 `terminal/encoding.rs` 的 `normalize()` 规范形态(`utf-8` / `gbk` / `gb18030` / `big5` / `shift_jis` / `euc-kr` / `latin1`),双端取值同源,避免「状态栏写 GBK、设置里叫 cp936」这种不一致。
|
||||
|
||||
### 5.3 切换编码(关键设计)
|
||||
|
||||
**核心约束:切换编码不是「重新解释缓冲区文本」,而是「换一种方式去解释磁盘字节」。**
|
||||
|
||||
- **切换时**:以磁盘当前字节(而非缓冲区文本)按新编码重新解码 → 替换缓冲区内容。
|
||||
- 若此时有未保存改动:弹确认框给出三个选项——①**丢弃我的改动并按新编码重读**(默认,语义最清晰);②**先保存再重读**(用旧编码落盘,再按新编码读回——用户能立刻看出旧编码是否选错);③取消。
|
||||
- **保存时**:按当前 `encoding` 编码写回。若目标编码无法表示缓冲区里的某些字符(例如把含 emoji 的文本存成 GBK),**保存前报错并列出无法表示的字符位置**,而不是静默替换成 `?`(静默替换 = 不可逆数据损坏)。
|
||||
- **状态栏编码下拉**:`UTF-8` / `UTF-8 BOM` / `GB18030` / `GBK` / `Big5` / `Shift_JIS` / `EUC-KR` / `Latin-1` + 「重新载入为…」(不改变写回编码,仅重新解释)。
|
||||
- **换行切换**:`LF` / `CRLF` 独立于编码(v1 已按读取值写回),状态栏可切换。
|
||||
|
||||
### 5.4 与终端模块的编码复用
|
||||
|
||||
`terminal/encoding.rs` 提供 `decode` / `encode` / `normalize` / `SUPPORTED` / `is_supported`(v1 已直接复用,未提取为公共模块 —— 它们是纯函数,无业务耦合;若将来第三个模块要用再提取)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 界面结构
|
||||
|
||||
### 6.1 主模块页(设置与管理,不编辑)
|
||||
|
||||
Tab 收敛为 **概览 / 库 / 编辑器 / 集成**(把 v1 的「同步」并入「库」,因为同步是库的属性):
|
||||
|
||||
| Tab | 内容 |
|
||||
|---|---|
|
||||
| 概览 | 库状态横幅(路径/笔记数/索引)、最近文件与文件夹、快捷入口(打开编辑器 / 打开文件 / 打开文件夹 / 今日日记) |
|
||||
| 库 | 库根切换、重建索引、导入导出、WebDAV(连接/方向/冲突/快照) |
|
||||
| 编辑器 | 主题(含 JetBrains 三套)、字体字号行高连字、Live Preview 开关、默认编码、大文件阈值、自动保存、快捷键 |
|
||||
| 集成 | 文件关联状态、**右键菜单注册/卸载**、exe 路径、单实例说明 |
|
||||
|
||||
### 6.2 编辑器窗口
|
||||
|
||||
```
|
||||
┌─ 标题栏(自绘:文档名 + 未保存点 + 窗口按钮)────────────────────────┐
|
||||
├─ 工具栏:保存 另存 打开 快速打开 | 格式化(.md 时) | 编码 换行 主题 ─┤
|
||||
├────────────┬──────────────────────────────────────────┬─────────────┤
|
||||
│ 侧栏 │ 标签页条:doc1 × | doc2 × | … │ 抽屉(可选) │
|
||||
│ [库|目录| │ │ 大纲 / 双链 │
|
||||
│ 检索|最近] │ 编辑器(CM6) │ │
|
||||
│ │ │ │
|
||||
│ 树 / 结果 │ │ │
|
||||
├────────────┴──────────────────────────────────────────┴─────────────┤
|
||||
│ 状态栏:保存态 · 字数/行数 · 行列 · 语言 · 编码 · 换行 · 路径 │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- 侧栏可整体折叠(腾出宽度给长行代码)。
|
||||
- 抽屉默认关闭,`Ctrl+Shift+O` 切大纲、`Ctrl+Shift+B` 切双链。**这两个键位在实现时由 `keymap.ts` 统一声明并做冲突检测**:若与 CM6 默认键位冲突,以 CM6 默认键位优先,本功能改用 `Alt+O` / `Alt+B`(冲突检测方式沿用 v1 的 `shortcut.rs` 思路,编辑器内用 CM6 的 keymap 优先级)。
|
||||
|
||||
### 6.3 目录面板的命令面(P3-5 实现依据)
|
||||
|
||||
| 命令 | 入参 | 说明 |
|
||||
|---|---|---|
|
||||
| `editor_read_dir` | `path: String`(空 = 用户主目录) | 返回 `cwd` / `parent` / `entries`(名字/路径/是否目录/大小/mtime) |
|
||||
| `editor_create_file` | `dir: String`, `name: String` | 重名报错(**不自动加序号**:目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件) |
|
||||
| `editor_create_folder` | `dir: String`, `name: String` | 同上 |
|
||||
| `editor_rename_path` | `path: String`, `newName: String` | 同目录改名;目标存在则报错 |
|
||||
| `editor_delete_path` | `paths: Vec<String>` | **走系统回收站**(复用 `quickpanel::commands::delete_file_impl`),返回 `(成功数, 失败明细)`;拒绝盘符根 |
|
||||
| `editor_reveal_path` | `path: String` | 在资源管理器中选中(`opener` 的 `reveal_item_in_dir`) |
|
||||
|
||||
**安全边界**:目录树操作的是**用户真实文件系统**(不是沙箱),因此
|
||||
- 不设「必须在本目录根下」的限制(那是本地文件管理器,限制根目录只会挡住用户自己);
|
||||
- 但**拒绝删除盘符根**(`Path::new(p).parent().is_none()`)—— 这是唯一不可恢复的事故;
|
||||
- 删除一律走回收站,不用 `remove_file`;
|
||||
- 路径来自用户自己的浏览/输入,与 `terminal/local_fs.rs` 同一姿态(该模块已有 `list_dir` / `delete` 的成熟实现,**优先复用而不是重写**)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 缺口清单(v1 已有 → v2 要做)
|
||||
|
||||
| # | 缺口 | 严重度 | 落点 |
|
||||
|---|---|---|---|
|
||||
| G1 | 模块仍叫 notes(id / 命令 / 事件 / 目录 / 存储键) | 高(结构性) | §9.6 |
|
||||
| G2 | 没有「本地目录」导航根(只有笔记库) | 高 | §3.3 |
|
||||
| G3 | 编码只能探测不能切换;无状态栏显示 | 高 | §5 |
|
||||
| G4 | 没有最近文件夹记录(只有最近笔记,且存在 localStorage) | 中 | §3.5 |
|
||||
| G5 | 没有资源管理器右键菜单 | 中 | §3.6 |
|
||||
| G6 | 默认全局快捷键为空(`Alt+E` 未设) | 低 | §3.7 |
|
||||
| G7 | 单窗口单文档(无标签页) | 中 | §3.1 |
|
||||
| G8 | 大纲/双链挤在导航侧栏里,语义混杂 | 中 | §3.3 |
|
||||
| G9 | 大文件降级没有「只读打开」与显式提示 | 低 | §3.1 / §5.2 |
|
||||
| G10 | 主模块页 Tab 结构未随定位调整(同步应并入库) | 低 | §6.1 |
|
||||
| G11 | 语言包缺 `.sh`/`.ps1`/`.toml`/`.ini`/`.scss`(legacy-modes 未接) | 低 | §8-P5.1 |
|
||||
| G12 | Markdown 内嵌代码块高亮未做(`codeLanguages` 异步问题) | 低 | §8-P5.3 |
|
||||
| G13 | `FileDoc` 无 `readonly` 字段(只读文件要等保存时才报错) | 中 | §5.2 / P4-1 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 分期路线图
|
||||
|
||||
> v1 的 P0/P1/P2 已全部落地(见 §9)。以下是从 **P3 起**的新路线图。
|
||||
|
||||
### P3 — 编辑器化改造(结构)
|
||||
|
||||
1. **改名**:`notes` → `editor`(id / 窗口 label / 事件 / 命令前缀 / 目录 / 存储键 / Rust 模块名),脚本核对无残留(§9.6)。
|
||||
2. **库内目录改名**:`<库根>/.notes/` → `<库根>/.editor/`(含 `sync.json`),首次打开时惰性迁移;索引可重建,丢了无损。
|
||||
3. **侧栏重构**:`库 / 目录 / 检索 / 最近` 四段;大纲与双链移到编辑区右侧抽屉。
|
||||
4. **本地目录树**:打开文件夹(对话框 / 右键菜单 / 最近文件夹)、树浏览、文件名过滤、打开文件、在资源管理器中显示、复制路径、手动刷新。
|
||||
5. **最近记录**:最近文件 + 最近文件夹(落 `settings.json`,分组显示、可清空、失效项灰显)。
|
||||
6. **主模块页 Tab 调整**:概览 / 库 / 编辑器 / 集成。
|
||||
|
||||
### P4 — 编码与系统集成(这一版的核心价值)
|
||||
|
||||
1. **编码探测链**(§5.1)+ 状态栏显示编码/换行/只读。
|
||||
2. **切换编码**(§5.3):重解码对话框三选项、保存时不可表示字符报错、换行独立切换。
|
||||
3. **系统集成**:`Alt+E` 默认值;HKCU 右键菜单注册/卸载(文件 + 文件夹 + 目录背景),设置页按钮 + exe 路径显示 + dev 环境提示。
|
||||
4. **只读打开**与大文件降级提示。
|
||||
5. **标签页**(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立编码与视图模式、关闭确认。
|
||||
|
||||
### P5 — 完善(本轮不做,按体感排后续优先级)
|
||||
|
||||
1. 语言包补齐:`.sh` / `.ps1` / `.toml` / `.ini` / `.dockerfile` 走 `legacy-modes`;`.scss` / `.less` 引入 `@codemirror/lang-sass`。
|
||||
2. 目录树上的文件操作完善:拖拽移动、在新窗口打开、批量重命名。
|
||||
3. Markdown 内嵌代码块高亮(`codeLanguages`,需解决 language-data 异步 vs `markdown()` 同步)。
|
||||
4. 双链图谱(数据已就绪:`editor_link_graph` 命令可用,仅缺可视化)。
|
||||
5. 会话恢复:关窗后重开恢复文档与光标位置。
|
||||
|
||||
---
|
||||
|
||||
## 9. v1 实施记录(压缩归档)
|
||||
|
||||
> 完整细节已在 v1 文档中,此处只留**结论**与**坑**——它们对 v2 仍然成立。
|
||||
|
||||
> **本节的文件名一律是 v2 目标名**。v1 代码里对应的真实路径是:
|
||||
> `src-tauri/src/notes/*.rs`、`src/modules/notes/**`、`src/stores/notesStore.ts`、
|
||||
> `src/types/notes.ts`,命令为 `notes_*`。
|
||||
|
||||
### 9.1 交付总览(v1,均已落地)
|
||||
|
||||
| 层 | 关键文件 |
|
||||
|---|---|
|
||||
| Rust 文件 IO | `editor/files.rs`(编码/换行探测、授权白名单、附件落盘) |
|
||||
| Rust 库 | `editor/library.rs`(`safe_join` 路径沙箱、扫描、增删改移) |
|
||||
| Rust 模板 | `editor/templates.rs`(4 个内置模板 + 库内覆盖 + `{{title}}`/`{{date}}`) |
|
||||
| Rust 导入导出 | `editor/import.rs`(文件/目录/zip,重名加序号、绝不覆盖)、`editor/export.rs`(整库/单目录 zip) |
|
||||
| Rust 索引 | `editor/index.rs`(SQLite + FTS5 trigram:front-matter、标签、双链、检索、片段)、`editor/index_service.rs`(单线程 worker + notify) |
|
||||
| Rust WebDAV | `editor/webdav/{client,sync}.rs`(PROPFIND/MKCOL/PUT/GET/DELETE/MOVE + 三方比对 + 冲突策略 + 改名识别)、`editor/backup.rs`(zip 快照 + 轮转 + 恢复) |
|
||||
| Rust 参数 | `editor/args.rs`(文件关联/命令行参数解析 + 待打开文件缓存) |
|
||||
| 前端内核 | `editor/core.ts`(Compartment 热重配置)、`markdownLivePreview.ts`、`languages.ts`、`themes.ts`、`keymap.ts`、`outline.ts`、`wikilink.ts`、`images.ts`、`markdownExport.ts` |
|
||||
| 前端组件 | `LibrarySidebar.vue`、`SearchPanel.vue`、`QuickOpen.vue`、`MarkdownOutline.vue`、`BacklinksPanel.vue`、`WebdavPanel.vue`、`ImportExportPanel.vue`、`NewNoteDialog.vue`、`EditorHost.vue`、`EditorToolbar.vue` |
|
||||
| 前端状态 | `stores/editorStore.ts`、`modules/editor/editorClient.ts`、`types/editor.ts` |
|
||||
| 命令 | 40 条(`notes_*` → 将统一改名为 `editor_*`) |
|
||||
|
||||
### 9.2 关键决策(v2 继续沿用)
|
||||
|
||||
- **真相是文件,索引可丢**:删掉 `editor.db` 的唯一后果是下次搜索前做一次全量扫描。
|
||||
- **索引由单线程 worker 独占**:`rusqlite::Connection` 非共享对象,而搜索命令(Tauri 线程池)、保存后的增量更新、notify 回调会并发进来;通道排队 + 专职线程换来「慢操作只排队不堵搜索」。
|
||||
- **FTS5 用 trigram**:默认 `unicode61` 把连续汉字切成一个词元,「会议」搜不到「周会议纪要」。代价是查询词 <3 字符静默返回空 → 回退 `LIKE` + Rust 侧自建片段。
|
||||
- **WebDAV 同步基线存两侧指纹**,不比 mtime(跨机时钟偏差会让「本地比远端新」两边都成立)。删除传播保守优先;同步有失败不推进基线。
|
||||
- **冲突「两侧都留」用远端 `MOVE`** 保留历史,而不是覆盖。
|
||||
- **同步/网络类命令一律 `async` + `spawn_blocking`**:`reqwest::blocking` 在 tokio 运行时线程上会 panic。
|
||||
- **HTML 导出零外链、失败关闭**:样式内联;DOMPurify 不可用时返回**空串**而不是原文。
|
||||
- **渲染链路按需 `import()`**:`markdownExport`(markdown-it + DOMPurify + highlight.js)约 1.1MB,静态引入会让模块 chunk 从 40kB 涨到 1.2MB。
|
||||
- **库外文件的路径授权白名单**:库内走 `safe_join`(根目录沙箱),库外走「用户显式打开过的绝对路径集合」。读宽松(读时登记),写严格。
|
||||
- **`from`(大纲)一律是行首偏移**:指向正文起点会让空标题没有合法取值。
|
||||
- **Live Preview 是装饰不是渲染**:只对 `view.visibleRanges` 计算(性能红线);光标行「显形」为可编辑源码。
|
||||
|
||||
### 9.3 验证状态(v1 收尾时)
|
||||
|
||||
```
|
||||
cargo check 0 warning
|
||||
cargo build 整包通过
|
||||
cargo test --lib 58 passed / 0 failed
|
||||
node --test 74 passed / 0 failed / 1 skipped(Node 无 DOM 的 XSS 断言)
|
||||
vue-tsc / eslint 通过
|
||||
vite build NotesModule 41kB(gzip 12.5) / NotesWindow 98kB(gzip 32.6)
|
||||
/ markdownExport 1.12MB(gzip 371) 按需加载
|
||||
接线核对 命令 定义=导出=注册 40/40/40,无差集
|
||||
事件 Rust 8 = TS 8,无差集
|
||||
类型 18 个结构字段名双端一一对应
|
||||
```
|
||||
|
||||
### 9.4 坑记录(跨版本有效)
|
||||
|
||||
1. **`<SelectItem>` 不能用空串 `value`**:reka-ui 把空串保留给 placeholder,会直接抛异常。用显式哨兵值(`'__all__'` / `'__current__'`)在调用点翻译。报错栈指向 `SelectItem.vue` 而不是调用方 —— 先搜 `value: ''`。
|
||||
2. **`cargo add <tauri 插件>` 会连带升级整个 tauri 依赖树**(wry / tray-icon / window-vibrancy),而 dev 启动会校验 JS 包与 crate 的 minor 是否一致。**改一边必须同时看另一边**。
|
||||
3. **不要把 `package.json` 交给 PowerShell 的 `Set-Content -Encoding UTF8`**(PS 5.1 写入 BOM),带 BOM 会让 Vite 读 PostCSS 配置直接失败。用 `node -e` 或 `UTF8Encoding($false)`。
|
||||
4. **CRLF 下反推行首偏移一律偏 1**:必须预先算 `lineStarts` 表,不要在循环里「减回去」。
|
||||
5. **front-matter 用状态机而不是布尔量**:首行 `---` 是*开头*,布尔量会在第 0 行就关掉状态,导致第 2 行的闭合 `---` 把上一行元数据提升成 Setext 标题。
|
||||
6. **`let plan = plan(...)` 会遮蔽函数名**,第二个测试起报 `E0618` 且位置离成因很远。函数名避开返回值名。
|
||||
7. **`enum` 不能出现在 `node --test` 直接跑的文件里**(Node 的 TS 支持是 strip-only)。用 `const X = {...} as const` + 类型别名。
|
||||
8. **quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`**(旧版 `&[u8]`),`BytesText` 无 `decode()`;升级时只 `cargo update -p quick-xml`,避免动到 wry 链。
|
||||
9. **冷启动的文件关联事件会丢**:`setup` 里 `emit` 时 WebView 还没加载。改为存 `OnceLock<Mutex<Option<PathBuf>>>`,前端注册完监听后主动取走。
|
||||
10. **FTS5 的 `snippet()` 对「走 LIKE 回退的短词」什么都不产出**;列索引用 `-1`(让 FTS 挑最佳列)。
|
||||
|
||||
### 9.5 与 v1 规划不一致之处(保留结论)
|
||||
|
||||
| 规划 | 实际 | 原因 |
|
||||
|---|---|---|
|
||||
| 语言支持走 `language-data` 一处入口 | 手写扩展名映射表 + 逐语言 `import()` | `matchFilename` 覆盖不到 `.vue`/`.toml`/`.ps1`;手写表行为可预期 |
|
||||
| Markdown 内嵌代码块高亮 | 未做 | language-data 清单异步 vs `markdown()` 同步(见 G12) |
|
||||
| `.scss` / `.less` | 未做 | `@codemirror/lang-css` 只导出 `css()` |
|
||||
| 表格渲染 / 图片内联 | **已做**(图片走 data URL,非 asset 协议) | asset 协议要求把用户自选库根加进白名单,等于给 WebView 开任意读文件的口子 |
|
||||
| 提取 `terminal/encoding.rs` 为公共模块 | 未提取,直接复用 | 纯函数无耦合;第三个模块要用时再提取 |
|
||||
| 系统关联 | 已做文件关联;**右键菜单本轮补** | §3.6 |
|
||||
| 双链图谱 / 托盘入口 / Mermaid | 未做 | §8-P5 / §0.8 |
|
||||
|
||||
### 9.6 改名清单(P3 的执行依据)
|
||||
|
||||
| 面 | v1 | v2 | 规模 |
|
||||
|---|---|---|---|
|
||||
| 模块 id / 目录 | `notes` / `src/modules/notes/` | `editor` / `src/modules/editor/` | 10 处 |
|
||||
| 窗口 hash / label 前缀 | `#notes-window` / `notes-window-*` | `#editor-window` / `editor-window-*` | 16 处 + capability 文件名 |
|
||||
| 事件名 | `notes-settings` 等 8 个 | `editor-*` | 4 处(双端一致) |
|
||||
| Rust 命令前缀 | `notes_*`(40 条) | `editor_*` | 246 行 |
|
||||
| Rust 模块目录 | `src-tauri/src/notes/` | `src-tauri/src/editor/` | 18 处 |
|
||||
| store / client / types | `notesStore` / `notesClient` / `types/notes.ts` | `editorStore` / `editorClient` / `types/editor.ts` | 77 处 |
|
||||
| localStorage 键 | `thing_notes_recent` | 改为落 `settings.json`(不再用 localStorage) | 1 处 |
|
||||
| capability 文件 | `notes-window.json` | `editor-window.json` | 1 文件 |
|
||||
| 默认库目录 | `{appData}/notes/library` | `{appData}/editor/library` | 需迁移逻辑(见下) |
|
||||
|
||||
**迁移策略**:`{appData}/notes/` 若存在且 `{appData}/editor/` 不存在 → 启动时整目录重命名并记日志;否则各自独立。库内 `.notes/`(索引 + 同步基线)同理改 `.editor/`,并在首次打开时惰性迁移(索引可重建,丢了也无损)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 决策表(已拍板,开工时按此执行)
|
||||
|
||||
> Q1–Q4 由用户于 2026-09-30 明确拍板;Q5–Q10 由本规划给出建议并**一并视为生效**(若要改,改这一行即可,不影响其它章节)。
|
||||
|
||||
| # | 决策点 | 结论 | 影响面 |
|
||||
|---|---|---|---|
|
||||
| Q1 | 模块显示名与英文 id | **`id = editor`,显示名「编辑器」**(一词式,与「终端」「下载」一致) | 模块注册、窗口标题、搜索项、改名清单 §9.6 |
|
||||
| Q2 | 是否引入「工作区」 | **不引入**。只有「笔记库根」与「当前目录根」两个单值 + 各自历史 | §3.3 侧栏只有一个目录面板;ST-4 无需 workspace 状态 |
|
||||
| Q3 | 目录树是否纳入索引 | **不纳入**。目录树只做文件名过滤;全文检索仅对笔记库可用(FTS5) | §3.4 / §4;`editor_index_*` 只处理库内 `.md` |
|
||||
| Q4 | 标签页放哪一期 | **P4**(与编码、系统集成同期) | §8-P4.5;`EditorHost` 需支持多 view 实例 |
|
||||
| Q5 | 右键菜单注册时机 | **设置页手动按钮**,默认不写注册表 | §3.6;dev 环境 exe 路径不稳定 |
|
||||
| Q6 | 目录树删除语义 | **走系统回收站**(复用 `quickpanel` 实现) | §4;与 `terminal/local_fs.rs` 同口径 |
|
||||
| Q7 | 默认编码兜底 | **`GB18030`**(探测链第 3 级) | §5.1;第 4 级人工指定兜底 |
|
||||
| Q8 | 「笔记库」这一叫法 | **保留**(库内文件仍是笔记,用户已理解该词) | §3.3 面板名「笔记库」 |
|
||||
| Q9 | 主模块页是否给「打开文件夹」入口 | **给** | §6.1 概览页行动区 |
|
||||
| Q10 | 大文件阈值 | **5MB 默认,可配**,且状态栏显式提示降级 | §3.1;`largeFileMb` 进设置 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 开工清单(执行入口)
|
||||
|
||||
> 本节是「照做即可」的清单。**P3 与 P4 之间没有依赖倒置**:P3 是结构改造(改名 + 侧栏 + 目录树 + 最近记录),P4 是能力新增(编码 + 系统集成 + 标签页)。建议**严格 P3 → P4**:改名会碰到 P4 要改的每一个文件,同时做会让 diff 无法 review。
|
||||
|
||||
### 11.1 定稿参数(实现时直接用这些值,不要再另起炉灶)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 模块 id / 显示名 / 图标 key | `editor` / `编辑器` / `editor`(`icons.ts` 映射到 `FileCode2` 或 `NotebookPen`,见下) |
|
||||
| 模块排序 `order` | **45**(沿用,排在终端 40 之后) |
|
||||
| 窗口 hash / label 前缀 | `#editor-window` / `editor-window-` |
|
||||
| 窗口查询参数 | `?file=<绝对路径>` / `?note=<库内相对路径>` / `?folder=<绝对路径>` |
|
||||
| Tauri 命令前缀 | `editor_`(40 条现有命令全部平移,P4 新增约 12 条) |
|
||||
| 事件名(8 个) | `editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`(最后一个是 P4 新增) |
|
||||
| Rust 模块目录 | `src-tauri/src/editor/` |
|
||||
| 前端目录 | `src/modules/editor/` |
|
||||
| store / client / types | `useEditorStore` / `src/modules/editor/editorClient.ts` / `src/types/editor.ts` |
|
||||
| 模块自身目录 | `{appData}/editor/`(settings.json / editor.db / library/) |
|
||||
| 库内私有目录 | `<库根>/.editor/`(`sync.json`) |
|
||||
| keyring 键 | `editor.webdav.password` |
|
||||
| 默认全局快捷键 | 打开编辑器 = **`Alt+E`**;新建笔记 = 空(可配) |
|
||||
| 默认库根 | `{appData}/editor/library` |
|
||||
| 默认编码 / 大文件阈值 | `UTF-8` 优先探测,兜底 `GB18030`;5MB |
|
||||
| 右键菜单键名 | `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,显示名 **「用 Thing 编辑器打开」** |
|
||||
| 图标 key / 组件 | key = `editor`;组件 **`FileCode2`**(已确认 `@lucide/vue` 有该图标;备选 `SquarePen` / `FileCode`)。侧栏新面板建议:目录 = `FolderTree`、最近 = `History`、抽屉 = `PanelRight` |
|
||||
|
||||
### 11.2 P3 执行顺序(每步都可独立验证 + 可提交)
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P3-1** | 改名:Rust 侧(模块目录 `notes/` → `editor/`、40 条命令 `notes_*` → `editor_*`、`NoteSettings` → `EditorSettings` 等类型名、事件常量) | `cargo check` 0 warning;`cargo test --lib editor::` 58 passed |
|
||||
| **P3-2** | 改名:前端侧(`src/modules/notes/` → `editor/`、`notesStore` → `editorStore`、`notesClient` → `editorClient`、`types/notes.ts` → `editor.ts`、`STORAGE_KEYS`、`main.ts` 路由、capability 文件名与 `windows` glob、模块注册与图标) | `vue-tsc` / `eslint` / `vite build` 通过;模块列表里显示「编辑器」 |
|
||||
| **P3-3** | 迁移:`{appData}/notes/` → `{appData}/editor/`(启动时整目录 rename,幂等);`<库根>/.notes/` → `.editor/`(惰性,`ensure_schema` 时探测并 rename) | 手工验证:改名前留下的库仍能被打开、索引被重建 |
|
||||
| **P3-4** | 侧栏重构为 `库 / 目录 / 检索 / 最近` 四段;大纲与双链移到右侧抽屉 | 四段可切换;抽屉快捷键生效 |
|
||||
| **P3-5** | 本地目录树:Rust `editor_read_dir` / `editor_create_file` / `editor_create_folder` / `editor_rename_path` / `editor_delete_path`(回收站)+ 前端 `DirectoryPanel.vue` | 能浏览、新建、重命名、删除(进回收站)、在资源管理器中显示 |
|
||||
| **P3-6** | 最近记录:`recentFiles` / `recentFolders` 落 `settings.json`,`RecentPanel.vue`,失效项灰显 + 清空 | 打开文件/文件夹后出现在「最近」,重启后仍在 |
|
||||
| **P3-7** | 主模块页 Tab → 概览 / 库 / 编辑器 / 集成(同步并入库页) | 四页可切换,入口按钮就位 |
|
||||
|
||||
**P3 完成判据**:模块叫「编辑器」、侧栏有库与目录两个根、最近记录可用、`cargo test` 与 `node --test` 全绿、`vite build` 通过且模块 chunk 无异常膨胀。
|
||||
|
||||
### 11.3 P4 执行顺序
|
||||
|
||||
| 步 | 内容 | 验证 |
|
||||
|---|---|---|
|
||||
| **P4-1** | `FileDoc` 增 `readonly`;`files.rs` 增写权限探测(`OpenOptions::new().write(true).open()` 不写入) | 只读文件打开后状态栏显示「只读」,保存被拦并给出原因 |
|
||||
| **P4-2** | 编码探测链按 §5.1 收紧(BOM → 严格 UTF-8 → GB18030);新增 `editor_redecode_file(path, encoding)` | Rust 单测覆盖 BOM/UTF-8/GBK/UTF-16 |
|
||||
| **P4-3** | 状态栏编码与本行下拉 + 切换编码三选项对话框(§5.3)+ 保存时不可表示字符报错 | 手工:GBK 文件切 UTF-8 看到乱码→切回正常;含 emoji 存 GBK 被拦 |
|
||||
| **P4-4** | 系统集成:`Alt+E` 默认值;右键菜单注册/卸载(`winreg`,HKCU)+ 设置页「集成」Tab | 注册后资源管理器右键出现菜单项,点击能打开文件/文件夹 |
|
||||
| **P4-5** | 标签页(多文档):`Ctrl+W` / `Ctrl+Tab`、每标签独立 `encoding`/`eol`/视图模式、关闭确认 | 同时开 3 个不同编码的文件,互不串味 |
|
||||
|
||||
**P4 完成判据**:编码可探测可切换、右键菜单可用、`Alt+E` 生效、多标签可用;§9.3 的全部检查项重新跑一遍通过。
|
||||
|
||||
### 11.4 每个阶段都要跑的验证命令
|
||||
|
||||
```powershell
|
||||
# Rust
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" check --message-format short # 必须 0 warning
|
||||
& "C:\Users\<user>\.cargo\bin\cargo.exe" test --lib editor:: # 单测(P3-1 后模块名变了)
|
||||
# 前端
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vue-tsc/bin/vue-tsc.js --noEmit
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/eslint/bin/eslint.js src
|
||||
& "C:\Program Files\nodejs\node.exe" node_modules/vite/bin/vite.js build
|
||||
& "C:\Program Files\nodejs\node.exe" --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/editor/editor/outline.test.ts
|
||||
```
|
||||
|
||||
> 注意:本机沙箱禁止直接 spawn 工作区外的可执行文件,必须用**绝对路径**调用
|
||||
> `cargo.exe` / `node.exe`(`node` 在 `C:\Program Files\nodejs\`)。
|
||||
> 新增依赖用 `bun add`,且 `$env:TEMP` 必须指向可写目录(详见 §9.4 的坑记录)。
|
||||
|
||||
### 11.5 改名核对脚本(P3-1/P3-2 完成后跑)
|
||||
|
||||
```powershell
|
||||
# 应无输出(除文档与 §9 的历史记录外)
|
||||
Select-String -Path (Get-ChildItem src,src-tauri/src,src-tauri/capabilities -Recurse -Include *.ts,*.vue,*.rs,*.json |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notes_" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
Select-String -Path (Get-ChildItem src -Recurse -Include *.ts,*.vue |
|
||||
ForEach-Object { $_.FullName }) -Pattern "notesStore|notesClient" | ForEach-Object { "$($_.Path):$($_.LineNumber)" }
|
||||
# 命令三方一致性(应 定义 = 导出 = 注册)
|
||||
# 见 §9.3 的接线核对做法:比对 commands.rs / mod.rs / lib.rs 两处
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:命名规范(v2)
|
||||
|
||||
- 模块 id:`editor`;显示名:`编辑器`;图标 key:`editor`。
|
||||
- 窗口 hash:`#editor-window`(可带 `?file=<abs path>` 或 `?note=<rel path>`);label 前缀:`editor-window`。
|
||||
- 事件名(**8 个**,与 v1 一一对应,最后一个为 P4 新增):`editor-settings` / `editor-library-changed` / `editor-file-changed` / `editor-sync-progress` / `editor-new-note` / `editor-open-editor` / `editor-open-file` / `editor-open-folder`。
|
||||
- 窗口 label 前缀:`editor-window-`(不是事件,列在此处避免与上表混淆)。
|
||||
- 前端组件:`DirectoryPanel.vue` / `RecentPanel.vue` / `EditorTabs.vue`(P4)/ `DrawerPanel.vue`(大纲与双链的容器)为 P3/P4 新增。
|
||||
- Rust 命令前缀:`editor_`;Rust 模块目录:`src-tauri/src/editor/`。
|
||||
- 前端 store:`useEditorStore`;类型文件:`src/types/editor.ts`;IPC 客户端:`src/modules/editor/editorClient.ts`。
|
||||
- 存储:`{appData}/editor/settings.json`;库内私有目录:`<库根>/.editor/`。
|
||||
- keyring 键:`editor.webdav.password`。
|
||||
|
||||
## 附录 B:能力边界(明确不做)
|
||||
|
||||
| 不做 | 理由 |
|
||||
|---|---|
|
||||
| 调试器 / 内嵌终端 / LSP 补全 / Git 集成 | 那是 IDE,与「notepad++ 式编辑器」的定位冲突;本项目终端模块已覆盖终端场景 |
|
||||
| 块编辑器(拖拽块、`/` 菜单) | 与「`.md` 文本是唯一真相」的模型不匹配(v1 已确认) |
|
||||
| 远端直连读写(把 WebDAV 当工作区) | 离线不可用、限流敏感、冲突面大(v1 已确认) |
|
||||
| 目录树全文索引 | 与「打开快」冲突(Q3) |
|
||||
| 字符频率统计式编码探测 | 短文本上比规则更不可靠(§5.1) |
|
||||
| 二进制文件编辑 | 编码/换行模型只对文本成立;识别为二进制时明确拒绝并提示用外部工具 |
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+33
-8
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "thing",
|
||||
"private": true,
|
||||
"version": "26.9.4",
|
||||
"version": "26.9.5",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -10,17 +10,38 @@
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint src",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts",
|
||||
"test": "node --test src/modules/quickpanel/engine.test.ts src/lib/calc.test.ts src/lib/theme.test.ts src/modules/notes/editor/outline.test.ts src/modules/notes/editor/markdownExport.test.ts",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@codemirror/lang-java": "^6.0.2",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/lang-rust": "^6.0.2",
|
||||
"@codemirror/lang-sql": "^6.10.0",
|
||||
"@codemirror/lang-vue": "^0.1.3",
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/language-data": "^6.5.2",
|
||||
"@codemirror/legacy-modes": "^6.5.4",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-autostart": "~2",
|
||||
"@tauri-apps/plugin-dialog": "^2",
|
||||
"@tauri-apps/plugin-global-shortcut": "^2",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"@tauri-apps/api": "^2.12.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",
|
||||
"@uiw/codemirror-themes": "^4.25.12",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-search": "^0.16.0",
|
||||
@@ -31,6 +52,9 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"dompurify": "^3.4.16",
|
||||
"highlight.js": "^11.12.0",
|
||||
"markdown-it": "^15.0.2",
|
||||
"pinia": "^3.0.4",
|
||||
"pinyin-pro": "^3.28.2",
|
||||
"qrcode": "^1.5.4",
|
||||
@@ -42,7 +66,8 @@
|
||||
"vue-sonner": "^2.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@tauri-apps/cli": "^2.12.0",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
|
||||
Generated
+153
-211
@@ -85,15 +85,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
@@ -735,9 +735,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "8.0.4"
|
||||
version = "9.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
|
||||
checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -746,9 +746,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
version = "6.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
@@ -885,12 +885,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cargo_toml"
|
||||
version = "0.22.3"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77"
|
||||
checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
|
||||
dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml 1.1.2+spec-1.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -931,13 +932,13 @@ checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
|
||||
|
||||
[[package]]
|
||||
name = "cfb"
|
||||
version = "0.7.3"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f"
|
||||
checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"fnv",
|
||||
"uuid",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1366,9 +1367,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.36.0"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
|
||||
checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
|
||||
dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
@@ -1379,29 +1380,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cssparser-macros"
|
||||
version = "0.6.1"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
|
||||
checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.8.0"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "352d39c2f7bef1d6ad73db6f5160efcaed66d94ef8c6c573a8410c00bf909a98"
|
||||
dependencies = [
|
||||
"ctor-proc-macro",
|
||||
"dtor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor-proc-macro"
|
||||
version = "0.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
|
||||
checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
|
||||
|
||||
[[package]]
|
||||
name = "ctr"
|
||||
@@ -1664,9 +1655,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "6.0.0"
|
||||
version = "7.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"
|
||||
checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
|
||||
dependencies = [
|
||||
"dirs-sys 0.5.0",
|
||||
]
|
||||
@@ -1754,9 +1745,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "dom_query"
|
||||
version = "0.27.0"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89"
|
||||
checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"cssparser",
|
||||
@@ -1803,21 +1794,6 @@ dependencies = [
|
||||
"dtoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1057d6c64987086ff8ed0fd3fbf377a6b7d205cc7715868cd401705f715cbe4"
|
||||
dependencies = [
|
||||
"dtor-proc-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtor-proc-macro"
|
||||
version = "0.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -2573,7 +2549,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c386b0a4a70cb2d39fffd74480f985b6f0bfbcb934b6a6b6b7e630e448f242e"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.7.0",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"once_cell",
|
||||
@@ -2830,9 +2806,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2"
|
||||
checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
|
||||
dependencies = [
|
||||
"log",
|
||||
"markup5ever",
|
||||
@@ -2985,7 +2961,7 @@ dependencies = [
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core 0.62.2",
|
||||
"windows-core 0.57.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3167,9 +3143,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "infer"
|
||||
version = "0.19.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7"
|
||||
checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
]
|
||||
@@ -3383,21 +3359,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "json-patch"
|
||||
version = "3.0.1"
|
||||
version = "4.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"
|
||||
checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"
|
||||
dependencies = [
|
||||
"jsonptr",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"thiserror 2.0.20",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonptr"
|
||||
version = "0.6.3"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"
|
||||
checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -3434,6 +3410,16 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyboard-types"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring"
|
||||
version = "3.6.3"
|
||||
@@ -3822,7 +3808,7 @@ dependencies = [
|
||||
"httparse",
|
||||
"librqbit-dualstack-sockets",
|
||||
"network-interface",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"reqwest 0.13.4",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -3968,9 +3954,9 @@ checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862"
|
||||
checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
|
||||
dependencies = [
|
||||
"log",
|
||||
"tendril",
|
||||
@@ -4125,14 +4111,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.19.3"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"
|
||||
checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"gtk",
|
||||
"keyboard-types",
|
||||
"keyboard-types 0.8.3",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
@@ -4441,6 +4427,7 @@ dependencies = [
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5080,7 +5067,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"indexmap 2.14.0",
|
||||
"quick-xml",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
"time",
|
||||
]
|
||||
@@ -5328,6 +5315,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.42.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.11"
|
||||
@@ -6213,9 +6209,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "selectors"
|
||||
version = "0.36.1"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
|
||||
checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"cssparser",
|
||||
@@ -6878,9 +6874,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "swift-rs"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7"
|
||||
checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
|
||||
dependencies = [
|
||||
"base64 0.21.7",
|
||||
"serde",
|
||||
@@ -7175,9 +7171,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tao"
|
||||
version = "0.35.3"
|
||||
version = "0.37.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
|
||||
checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2",
|
||||
@@ -7195,29 +7191,29 @@ dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
"ndk-sys",
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"objc2-ui-kit",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"tao-macros",
|
||||
"unicode-segmentation",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tao-macros"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"
|
||||
checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -7238,14 +7234,14 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
|
||||
|
||||
[[package]]
|
||||
name = "tauri"
|
||||
version = "2.11.5"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"
|
||||
checksum = "cb20ef8e6f97d6fe03039666cd82861f09a38b56291fa2f0f9fe140023f61c1a"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dunce",
|
||||
"embed_plist",
|
||||
"getrandom 0.3.4",
|
||||
@@ -7285,18 +7281,18 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"window-vibrancy",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-build"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"
|
||||
checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cargo_toml",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"glob",
|
||||
"heck 0.5.0",
|
||||
"json-patch",
|
||||
@@ -7311,16 +7307,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-codegen"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"
|
||||
checksum = "3926b73ac01df7c14f19ff872cd56e67213a87acc0000ea37ddb300f3d11a3e3"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"brotli",
|
||||
"ico",
|
||||
"json-patch",
|
||||
"plist",
|
||||
"png 0.17.16",
|
||||
"png 0.18.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"semver",
|
||||
@@ -7338,9 +7334,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-macros"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"
|
||||
checksum = "d21d0fa2c0529972ea6ecaf7404fcf40efac098eda0beb06ca682f41e33a6aa5"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -7352,9 +7348,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin"
|
||||
version = "2.6.3"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"
|
||||
checksum = "c9ff3ebb9fda56ceb93d46f6cbb126bae82951bf43498543a5163dde5def49a1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"glob",
|
||||
@@ -7368,9 +7364,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-autostart"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "459383cebc193cdd03d1ba4acc40f2c408a7abce419d64bdcd2d745bc2886f70"
|
||||
checksum = "d464b4c2a5742cdeaf89d739f0681a8770c380053919dcd3ab9bc65fdb9f7c5f"
|
||||
dependencies = [
|
||||
"auto-launch",
|
||||
"serde",
|
||||
@@ -7382,9 +7378,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-dialog"
|
||||
version = "2.7.2"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"
|
||||
checksum = "7527c5fd1678032d116c1a82e5d609c67370e56f858ae6cfd376bbca37fe0490"
|
||||
dependencies = [
|
||||
"log",
|
||||
"raw-window-handle",
|
||||
@@ -7400,9 +7396,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-fs"
|
||||
version = "2.5.1"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7ecc274121aca0c036a2b42d1cbe83d368d348f54e0bb8a735c2b1548e8f371"
|
||||
checksum = "466eb32466fe5021b6728b06862f9ff14a9f7e1af890047654e03a96d7c0e1bb"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"dunce",
|
||||
@@ -7424,9 +7420,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-global-shortcut"
|
||||
version = "2.3.2"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4dd9f4c5136c09cd962da0c86dc4accd4666db2ea591cf16e6597435843bd2b"
|
||||
checksum = "0bd2e1f725891a1613af8f25bf918ba3357654b0fd3f2d794c0ce76cbdd92ed2"
|
||||
dependencies = [
|
||||
"global-hotkey",
|
||||
"log",
|
||||
@@ -7439,9 +7435,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-notification"
|
||||
version = "2.3.3"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"
|
||||
checksum = "9237e5cc1458bf1b31ad3c8c2c8480e86b6ecf133d00648fe6c36f25821f2f79"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
@@ -7458,9 +7454,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-opener"
|
||||
version = "2.5.4"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17e1bea14edce6b793a04e2417e3fd924b9bc4faae83cdee7d714156cceeed29"
|
||||
checksum = "d39404b2572927e0d3ed30a7ca226037f7508d22e79c96ee6ef0d42b6a4b3345"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"glob",
|
||||
@@ -7474,7 +7470,23 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.20",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-single-instance"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91baf4f5db4b008fc2bcada0f7d3a49b45d911f94575ac236f225ed67554f5c0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -7496,9 +7508,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime"
|
||||
version = "2.11.3"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"
|
||||
checksum = "c9e6d5ef76985b32ff012a43b58df205d25a285e400ca878afcacddc5d5f3238"
|
||||
dependencies = [
|
||||
"cookie",
|
||||
"dpi",
|
||||
@@ -7516,14 +7528,14 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-wry"
|
||||
version = "2.11.4"
|
||||
version = "2.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
|
||||
checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"http",
|
||||
@@ -7541,7 +7553,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows 0.62.2",
|
||||
"wry",
|
||||
]
|
||||
|
||||
@@ -7564,9 +7576,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-utils"
|
||||
version = "2.9.3"
|
||||
version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"
|
||||
checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"brotli",
|
||||
@@ -7646,7 +7658,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.9.5"
|
||||
dependencies = [
|
||||
"aes 0.8.4",
|
||||
"async-trait",
|
||||
@@ -7668,6 +7680,7 @@ dependencies = [
|
||||
"lofty",
|
||||
"md-5",
|
||||
"notify",
|
||||
"quick-xml 0.42.0",
|
||||
"rand 0.8.8",
|
||||
"raw-window-handle",
|
||||
"regex",
|
||||
@@ -7692,6 +7705,7 @@ dependencies = [
|
||||
"tauri-plugin-global-shortcut",
|
||||
"tauri-plugin-notification",
|
||||
"tauri-plugin-opener",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-snap-layout",
|
||||
"tauri-specta",
|
||||
"tokio",
|
||||
@@ -7909,21 +7923,6 @@ dependencies = [
|
||||
"toml_edit 0.20.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.9.12+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"serde_core",
|
||||
"serde_spanned 1.1.1",
|
||||
"toml_datetime 0.7.5+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
@@ -7948,15 +7947,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.1+spec-1.1.0"
|
||||
@@ -8107,12 +8097,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tray-icon"
|
||||
version = "0.24.1"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"
|
||||
checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"libappindicator",
|
||||
"muda",
|
||||
"objc2",
|
||||
@@ -8180,47 +8170,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-property"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221"
|
||||
dependencies = [
|
||||
"unic-char-range",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-char-range"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-common"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc"
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-ident"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987"
|
||||
dependencies = [
|
||||
"unic-char-property",
|
||||
"unic-char-range",
|
||||
"unic-ucd-version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unic-ucd-version"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4"
|
||||
dependencies = [
|
||||
"unic-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
@@ -8288,13 +8237,13 @@ checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
|
||||
|
||||
[[package]]
|
||||
name = "urlpattern"
|
||||
version = "0.3.0"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d"
|
||||
checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"
|
||||
dependencies = [
|
||||
"icu_properties",
|
||||
"regex",
|
||||
"serde",
|
||||
"unic-ucd-ident",
|
||||
"url",
|
||||
]
|
||||
|
||||
@@ -8562,16 +8511,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
|
||||
checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8587,13 +8534,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webview2-com-sys"
|
||||
version = "0.38.2"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
|
||||
checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
|
||||
dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8618,7 +8565,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8629,16 +8576,17 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "window-vibrancy"
|
||||
version = "0.6.0"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c"
|
||||
checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
"objc2-quartz-core",
|
||||
"raw-window-handle",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
@@ -9252,12 +9200,6 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
@@ -9322,15 +9264,15 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
|
||||
|
||||
[[package]]
|
||||
name = "wry"
|
||||
version = "0.55.1"
|
||||
version = "0.57.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "186f9871daa55fd9c016578b810d149de58367113db7fb72b462d2323ce19514"
|
||||
checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"block2",
|
||||
"cookie",
|
||||
"crossbeam-channel",
|
||||
"dirs 6.0.0",
|
||||
"dirs 7.0.0",
|
||||
"dom_query",
|
||||
"dpi",
|
||||
"dunce",
|
||||
@@ -9358,8 +9300,8 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webkit2gtk-sys",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "thing"
|
||||
version = "26.9.4"
|
||||
version = "26.9.5"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -117,6 +117,11 @@ symphonia = { version = "0.6", features = ["mp3", "aac", "alac", "isomp4"] }
|
||||
# AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | SRC_DEFAULT_QUALITY,因此**可以用源采样率
|
||||
# 直接建流**,由 Windows 自己转换到设备混音格式 —— 不需要额外引入重采样库。
|
||||
cpal = "0.18"
|
||||
# WebDAV 的 PROPFIND 响应是 XML,且命名空间前缀由服务端随意指定(D: / d: / lp1: /
|
||||
# 无前缀),因此只能按 local name 做宽容的事件流解析。quick-xml 是纯 Rust、无 C 依赖,
|
||||
# 且比 serde 反序列化更能吃下各家 NAS 不一致的字段集合(见 notes/webdav/client.rs)。
|
||||
quick-xml = "0.42.0"
|
||||
tauri-plugin-single-instance = "2.5.1"
|
||||
# HDR 截图说明:windows-capture 的 Windows Graphics Capture 后端在 HDR 显示器上
|
||||
# 可能输出 scRGB / rgba16F 或 HDR10(PQ) 格式的帧,与项目其余截图路径
|
||||
# (GDI BitBlt,sRGB 8bit)色彩空间不一致。capture 层统一转成 sRGB 8bit
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$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-*"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-hide",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-theme",
|
||||
"core:window:allow-set-effects",
|
||||
"core:window:allow-set-background-color",
|
||||
"core:event:allow-listen",
|
||||
"core:event:allow-emit",
|
||||
"dialog:default",
|
||||
"opener:default",
|
||||
"opener:allow-open-path",
|
||||
"opener:allow-reveal-item-in-dir",
|
||||
"snap-layout:default"
|
||||
]
|
||||
}
|
||||
@@ -26,6 +26,9 @@ pub mod windows {
|
||||
/// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。
|
||||
#[allow(dead_code)]
|
||||
pub const DSH_WEB: &str = "dsh-web";
|
||||
/// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-<n>`(可多开)
|
||||
#[allow(dead_code)]
|
||||
pub const NOTES_WINDOW: &str = "notes-window";
|
||||
}
|
||||
|
||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||
@@ -134,4 +137,24 @@ pub mod events {
|
||||
/// dsh 模块:全局快捷键触发「打开独立窗口」(无负载)。
|
||||
/// 窗口由前端创建(它持有带令牌的地址与 label 判重),Rust 侧只负责注册快捷键。
|
||||
pub const DSH_OPEN_WINDOW: &str = "dsh-open-window";
|
||||
// 笔记模块:设置已保存(无负载)。各窗口据以重读设置,实现跨窗口同步(同 terminal-settings)
|
||||
pub const NOTES_SETTINGS: &str = "notes-settings";
|
||||
// 笔记模块:库内容已变更(新建/保存/重命名/删除/切换库根,无负载)
|
||||
pub const NOTES_LIBRARY_CHANGED: &str = "notes-library-changed";
|
||||
// 笔记模块:库内某个文件在**应用外**被改动了(负载见 notes::index_service::NoteFileEvent)。
|
||||
// 与 NOTES_LIBRARY_CHANGED 的区别:那个是「本应用改了,重读即可」,这个是
|
||||
// 「别人改了,当前打开的文档可能已经过时」——前端据此提示而不是静默覆盖。
|
||||
pub const NOTES_FILE_CHANGED: &str = "notes-file-changed";
|
||||
// 笔记模块:WebDAV 同步进度(负载见 notes::types::SyncProgress)。
|
||||
// 进度事件是高频的,前端按「每 X% 或每 N 条」节流显示即可;Rust 侧逐条发,
|
||||
// 因为节流放在发送端会让「最后一条」容易被丢掉(进度条停在 98%)。
|
||||
pub const NOTES_SYNC_PROGRESS: &str = "notes-sync-progress";
|
||||
// 笔记模块:全局快捷键按下「新建笔记」(无负载,窗口由前端创建)
|
||||
pub const NOTES_NEW_NOTE: &str = "notes-new-note";
|
||||
// 笔记模块:全局快捷键按下「打开编辑器窗口」(无负载)
|
||||
pub const NOTES_OPEN_EDITOR: &str = "notes-open-editor";
|
||||
// 笔记模块:需要打开一个磁盘文件(负载 `{ path }`)。
|
||||
// 来源有三:① 双击关联的 .md(单实例回调把参数转交过来);② 启动命令行参数;
|
||||
// ③ 系统「打开方式」。三种都只发事件,窗口由前端创建。
|
||||
pub const NOTES_OPEN_FILE: &str = "notes-open-file";
|
||||
}
|
||||
+91
-1
@@ -10,6 +10,7 @@ mod mihomo_manager;
|
||||
mod monitor_kernel;
|
||||
pub mod music;
|
||||
mod network_monitor;
|
||||
mod notes;
|
||||
mod osd_window;
|
||||
mod process_manager;
|
||||
mod quickpanel;
|
||||
@@ -37,6 +38,18 @@ 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 mihomo_manager::{
|
||||
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
||||
@@ -324,6 +337,18 @@ 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,
|
||||
])
|
||||
.export(Typescript::default(), "../src/lib/bindings.ts")
|
||||
.expect("failed to export bindings");
|
||||
@@ -343,6 +368,30 @@ pub fn run() {
|
||||
win32_util::set_app_user_model_id("thing.lfeng.me");
|
||||
|
||||
tauri::Builder::default()
|
||||
// 单实例必须是**第一个**注册的插件:它决定「第二个进程是退出还是把参数转交过来」,
|
||||
// 排在别的插件后面会让后面的插件在第二个进程里先跑一遍初始化(起两个托盘图标之类)。
|
||||
//
|
||||
// # 为什么需要它
|
||||
//
|
||||
// 「用 Thing 打开」的文件关联会让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
// 应用已在运行时就会冒出第二个进程 —— 没有这个插件,用户双击一个 .md 只会得到
|
||||
// 一个(或两个)空窗口,而且第二个实例会和第一个抢同一个 sqlite 索引文件。
|
||||
// 有了它,第二个进程立即退出,命令行参数被转交给第一个实例的下面这个回调。
|
||||
.plugin(tauri_plugin_single_instance::init(|app, argv, _cwd| {
|
||||
// 主窗口可能藏在托盘里:先把已有窗口叫出来,再决定开哪个
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
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),
|
||||
None => {
|
||||
// 没有文件参数(用户又点了一次快捷方式):只把主窗口叫到前面,别开新窗口
|
||||
crate::logger::log_info("notes", "第二个实例无文件参数,仅聚焦主窗口");
|
||||
}
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_autostart::Builder::new().build())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
@@ -762,7 +811,48 @@ pub fn run() {
|
||||
dsh_log_tail,
|
||||
dsh_install_log,
|
||||
dsh_log_clear,
|
||||
dsh_open_dir
|
||||
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
|
||||
])
|
||||
.setup(setup::init)
|
||||
.on_window_event(|window, event| {
|
||||
|
||||
@@ -32,6 +32,9 @@ pub use fnconnect::{extract_fn_id, resolve_base_url};
|
||||
use conn::{generate_device_id, sha256_hex};
|
||||
use proxy::{ProxyCfg, ProxyShared};
|
||||
|
||||
/// 登录接口路径(同时用于失败留痕)。
|
||||
const LOGIN_PATH: &str = "/music/api/v1/user/password-login";
|
||||
|
||||
/// 一条飞牛音乐连接(持久化在 `MusicSettings`)。
|
||||
#[derive(Serialize, Deserialize, Clone, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -151,6 +154,33 @@ fn slot_client(slot: &Mutex<Option<ClientSlot>>, insecure: bool, streaming: bool
|
||||
g.as_ref().unwrap().client.clone()
|
||||
}
|
||||
|
||||
/// 服务端错误 → 画面上要展示的提示。
|
||||
///
|
||||
/// 飞牛音乐失败时常常只回一句笼统的 `msg`(如 `unknown error`),单看它判断不出
|
||||
/// 该重试、该重新登录,还是该去 NAS 上修服务;这里按官方错误码表补上结论与处理动作,
|
||||
/// 让提示本身就能指导操作。HTTP 状态码与错误码附在括号里,便于对日志。
|
||||
///
|
||||
/// 只有取不到 `data` 的失败才会走到这里,因此不需要区分调用方。
|
||||
fn error_text(status: StatusCode, code: i64, msg: &str) -> String {
|
||||
let head = match code {
|
||||
100001 => "飞牛 NAS 的音乐服务内部异常,可在 NAS 上重启「飞牛音乐」应用后重试",
|
||||
100002 => "请求与 NAS 端音乐服务版本不匹配",
|
||||
100003 | 100004 => "当前账号没有权限",
|
||||
100005 => "目标不存在(可能已被删除)",
|
||||
110002 => "NAS 端音乐应用尚未初始化",
|
||||
140001 => "NAS 正在重建搜索索引,请稍后再试",
|
||||
_ => {
|
||||
let m = msg.trim();
|
||||
if m.is_empty() {
|
||||
"飞牛音乐请求失败"
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
};
|
||||
format!("{head}(HTTP {} / code {code})", status.as_u16())
|
||||
}
|
||||
|
||||
impl Feiniu {
|
||||
/// 设置缓存根目录({app_data}/music/cache),应用启动时调用一次。
|
||||
pub fn set_cache_root(&mut self, app_data_dir: &Path) {
|
||||
@@ -310,7 +340,7 @@ impl Feiniu {
|
||||
.relay;
|
||||
let mut rb = self
|
||||
.client(insecure)
|
||||
.post(format!("{base}/music/api/v1/user/password-login"))
|
||||
.post(format!("{base}{LOGIN_PATH}"))
|
||||
.json(&body);
|
||||
// 中继链路:登录请求也需带 mode=relay,否则网关 302 回登录页
|
||||
if let Some(cookie) = Self::auth_cookie("", relay) {
|
||||
@@ -328,20 +358,24 @@ impl Feiniu {
|
||||
format!("{kind}: {e}")
|
||||
})?;
|
||||
let status = resp.status();
|
||||
let b: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let b: Value = serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = b["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
let msg = b["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"POST {LOGIN_PATH} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
if code == 120001 {
|
||||
return Err("用户名或密码错误".into());
|
||||
}
|
||||
let msg = b["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("HTTP {status}"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
let token = b["data"]["userToken"]
|
||||
.as_str()
|
||||
@@ -515,20 +549,30 @@ impl Feiniu {
|
||||
}
|
||||
let resp = rb.send().await.map_err(|e| format!("请求失败: {e}"))?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let raw = resp.text().await.unwrap_or_default();
|
||||
let body: Value =
|
||||
serde_json::from_str(&raw).unwrap_or_else(|_| json!({ "code": status.as_u16() }));
|
||||
let code = body["code"].as_i64().unwrap_or(i64::from(status.as_u16()));
|
||||
if code != 0 {
|
||||
if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
|
||||
let msg = body["msg"].as_str().unwrap_or("");
|
||||
// 服务端对部分失败只给一句笼统的 msg(如 `unknown error`),
|
||||
// 不带状态码/错误码/原始响应就无从定位,这里一次性留全。
|
||||
crate::logger::log_error(
|
||||
"feiniu",
|
||||
&format!(
|
||||
"GET {path} 失败: HTTP {status} code={code} body={}",
|
||||
raw.chars().take(400).collect::<String>()
|
||||
),
|
||||
);
|
||||
// HTTP 401/403 与 120001(Unauthorized)都表示「这把会话不能用了」,
|
||||
// 需重新登录——不该混进「NAS 服务异常」的提示里。
|
||||
if status == StatusCode::UNAUTHORIZED
|
||||
|| status == StatusCode::FORBIDDEN
|
||||
|| code == 120001
|
||||
{
|
||||
return Err("登录已过期,请重新登录".into());
|
||||
}
|
||||
let msg = body["msg"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("请求失败(HTTP {status})"));
|
||||
return Err(msg);
|
||||
return Err(error_text(status, code, msg));
|
||||
}
|
||||
Ok(body["data"].clone())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! 「用 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(¬e);
|
||||
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(¬e);
|
||||
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(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! zip 快照备份:整库打包上传 + 远端轮转 + 恢复。
|
||||
//!
|
||||
//! # 为什么「快照」比「双向同步」更该先做
|
||||
//!
|
||||
//! 规划 §3.6 的判断:对「只是要个备份」的用户,一次上传一个完整 zip 比双向同步
|
||||
//! **可靠得多** —— 同步要考虑冲突、删除传播、时钟偏差;快照只有一个动作(上传),
|
||||
//! 失败就是失败,不会在半途产生「一半新一半旧」的库。
|
||||
//!
|
||||
//! 因此本模块与 `webdav/sync.rs` 是两条独立路径,用的是同一个客户端。
|
||||
//!
|
||||
//! # 打包内容
|
||||
//!
|
||||
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
|
||||
//! (记录快照时间、文件数、格式版本)。**不打包 `.notes/`**:里面是索引与同步基线,
|
||||
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
|
||||
//!
|
||||
//! # 轮转
|
||||
//!
|
||||
//! 上传后列出远端 `backups/` 下的快照,按**文件名里的时间戳**倒序保留
|
||||
//! [`WebdavSettings::backup_keep`] 份,其余删除。用文件名排序而不是远端 mtime:
|
||||
//! 各家服务端的 mtime 精度与时钟都不一致,而文件名是我们自己写的、单调递增。
|
||||
|
||||
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};
|
||||
|
||||
/// 远端存放快照的目录(相对远端根)。
|
||||
pub const BACKUP_DIR: &str = "backups";
|
||||
/// 快照文件名前缀。
|
||||
const SNAPSHOT_PREFIX: &str = "thing-notes-";
|
||||
/// 清单文件名(打包进 zip,供恢复时校验)。
|
||||
const MANIFEST_NAME: &str = "thing-notes-manifest.json";
|
||||
|
||||
/// 快照清单。
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotManifest {
|
||||
version: u32,
|
||||
created_at: String,
|
||||
files: u32,
|
||||
}
|
||||
|
||||
/// 打包库根为 zip 字节流(不触网,便于单测)。
|
||||
pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
|
||||
library::ensure_library(root)?;
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// `.notes/` 是本机私有数据(索引 + 同步基线),不进快照
|
||||
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})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel.clone(), options)
|
||||
.map_err(|e| format!("写入快照条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入快照内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
// 清单最后写:它要记录真实打包到的文件数
|
||||
let manifest = SnapshotManifest {
|
||||
version: 1,
|
||||
created_at: chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
files,
|
||||
};
|
||||
let manifest_bytes = serde_json::to_vec_pretty(&manifest)
|
||||
.map_err(|e| format!("序列化快照清单失败: {e}"))?;
|
||||
writer
|
||||
.start_file(MANIFEST_NAME, options)
|
||||
.map_err(|e| format!("写入快照清单失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&manifest_bytes)
|
||||
.map_err(|e| format!("写入快照清单内容失败: {e}"))?;
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成快照打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
/// 上传一份快照并做轮转。返回备份报告。
|
||||
pub fn upload_snapshot(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
) -> Result<BackupReport, String> {
|
||||
let (bytes, files) = build_snapshot(root)?;
|
||||
let name = format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
);
|
||||
let remote_path = format!("{BACKUP_DIR}/{name}");
|
||||
client.put(&remote_path, bytes.clone())?;
|
||||
|
||||
let pruned = prune_snapshots(client, settings.backup_keep)?;
|
||||
Ok(BackupReport {
|
||||
name,
|
||||
bytes: bytes.len() as u64,
|
||||
files,
|
||||
pruned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 轮转:只保留最新的 `keep` 份。
|
||||
pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>, String> {
|
||||
let keep = keep.max(1) as usize;
|
||||
let mut snapshots = list_snapshots(client)?;
|
||||
if snapshots.len() <= keep {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// 文件名里的时间戳是 `%Y%m%d-%H%M%S`,字典序即时间序
|
||||
snapshots.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let outdated = snapshots.len() - keep;
|
||||
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));
|
||||
continue;
|
||||
}
|
||||
pruned.push(snapshot.name);
|
||||
}
|
||||
Ok(pruned)
|
||||
}
|
||||
|
||||
/// 列出远端已有的快照。
|
||||
pub fn list_snapshots(client: &WebdavClient) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let entries = client.list(BACKUP_DIR)?;
|
||||
let Some(entries) = entries else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter(|entry| !entry.is_dir)
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.map(|name| name.starts_with(SNAPSHOT_PREFIX) && name.ends_with(".zip"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|entry| BackupSnapshot {
|
||||
name: entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
size: entry.size,
|
||||
modified: entry.modified,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 从快照恢复(**不覆盖已存在的本地文件**)。
|
||||
///
|
||||
/// 保守策略的理由:恢复的典型场景是「换机器」或「误删了几篇」。前者的本地基本是空的,
|
||||
/// 后者的本地有用户最近的工作 —— 覆盖会把「误删之前写的东西」一起冲掉。
|
||||
/// 需要时用户可以先在资源管理器里移走旧库,再恢复。
|
||||
pub fn restore_snapshot(
|
||||
root: &Path,
|
||||
client: &WebdavClient,
|
||||
name: &str,
|
||||
) -> Result<(u32, u32), String> {
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return Err("快照名不合法".to_string());
|
||||
}
|
||||
let bytes = client.get(&format!("{BACKUP_DIR}/{name}"))?;
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
|
||||
.map_err(|e| format!("读取快照失败: {e}"))?;
|
||||
|
||||
let mut written = 0u32;
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive
|
||||
.by_index(index)
|
||||
.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", "快照里有越界路径,已跳过");
|
||||
continue;
|
||||
};
|
||||
let rel = entry_path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(root, &rel)?;
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out)
|
||||
.map_err(|e| format!("读取快照内容失败: {e}"))?;
|
||||
std::fs::write(&target, out).map_err(|e| format!("写入 {rel} 失败: {e}"))?;
|
||||
written += 1;
|
||||
}
|
||||
Ok((written, kept))
|
||||
}
|
||||
|
||||
/// 一次完整的「同步 + 备份」会话入口(命令层用)。
|
||||
///
|
||||
/// 返回(同步报告, 可选备份报告)。`with_backup` 为真时在同步之后追加一次快照 ——
|
||||
/// 「先同步再备份」的顺序是刻意的:备份应当是**同步之后的一致状态**,
|
||||
/// 而不是把一次半途失败的同步结果定格下来。
|
||||
pub fn sync_then_backup(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
app: &tauri::AppHandle,
|
||||
with_backup: bool,
|
||||
) -> Result<(super::webdav::sync::SyncReport, Option<BackupReport>), String> {
|
||||
let (plan, mut state, remote) = super::webdav::sync::build_plan(root, settings, client)?;
|
||||
let runner = super::webdav::sync::SyncRunner::new(client, root, app, plan.actions.len());
|
||||
let report = runner.run(&plan, &mut state, &remote);
|
||||
|
||||
// 只有「没有失败」时才推进基线:失败的一轮如果把基线写下去,
|
||||
// 那些没传成功的文件会被当成「已同步」,下次同步就静默漏掉了
|
||||
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}"));
|
||||
}
|
||||
} else {
|
||||
crate::logger::log_warn(
|
||||
"notes",
|
||||
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
|
||||
);
|
||||
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
|
||||
// 于是下一轮会把它们重新算作差异并重试
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("notes", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
let backup = if with_backup {
|
||||
Some(upload_snapshot(root, settings, client)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((report, backup))
|
||||
}
|
||||
|
||||
/// 本地临时快照目录(供「导出快照到本地」与调试用)。
|
||||
///
|
||||
/// 与 [`upload_snapshot`] 共用 [`build_snapshot`],区别只是落盘而不是上传 ——
|
||||
/// 「我要一份备份,但不想连远端」是个很常见的诉求(比如先手动拷到网盘)。
|
||||
pub fn snapshot_to_file(root: &Path, dest: &Path) -> Result<u64, String> {
|
||||
let (bytes, _) = build_snapshot(root)?;
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(dest, &bytes).map_err(|e| format!("写入快照失败: {e}"))?;
|
||||
Ok(bytes.len() as u64)
|
||||
}
|
||||
|
||||
/// 库根的默认快照落点(用户点「导出快照到本地」时用)。
|
||||
pub fn default_snapshot_path(root: &Path) -> PathBuf {
|
||||
root.join(format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-backup-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_contains_notes_and_assets_but_not_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();
|
||||
|
||||
let (bytes, files) = build_snapshot(&root).unwrap();
|
||||
assert_eq!(files, 3, "两篇笔记 + 一个附件");
|
||||
assert!(!bytes.is_empty());
|
||||
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = (0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"a.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"sub/b.md".to_string()), "{names:?}");
|
||||
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:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_does_not_overwrite_existing_files() {
|
||||
let root = temp_root("restore");
|
||||
std::fs::write(root.join("a.md"), "新版").unwrap();
|
||||
std::fs::write(root.join("b.md"), "旧版").unwrap();
|
||||
let (bytes, _) = build_snapshot(&root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("a.md"), "本机已有内容").unwrap();
|
||||
|
||||
// 直接走「解包到库根」的那段逻辑(用本地 zip 代替远端下载)
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive.by_index(index).unwrap();
|
||||
let Some(path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(&root, &rel).unwrap();
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out).unwrap();
|
||||
std::fs::write(&target, out).unwrap();
|
||||
}
|
||||
assert_eq!(kept, 1, "已存在的 a.md 应被跳过");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "本机已有内容");
|
||||
assert_eq!(std::fs::read_to_string(root.join("b.md")).unwrap(), "旧版");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_file_writing() {
|
||||
let root = temp_root("to-file");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
let dest = root.join("out.zip");
|
||||
let size = snapshot_to_file(&root, &dest).unwrap();
|
||||
assert!(size > 0);
|
||||
assert!(dest.is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,916 @@
|
||||
//! 笔记模块 Tauri 命令层。
|
||||
//!
|
||||
//! 所有库操作都经 [`super::library`] 的路径安全校验、所有库外文件操作都经
|
||||
//! [`super::files`] 的授权白名单、所有 WebDAV 操作都经 [`super::webdav`] 的会话层;
|
||||
//! 命令本身只做几件事:解析当前库根 → 调下层 → 标记「本应用刚写过」→ 发事件。
|
||||
//!
|
||||
//! # 为什么每条命令都要先 `retarget`
|
||||
//!
|
||||
//! 索引服务是常驻 worker,它记着「自己挂在哪个库根上」。库根可以在设置里改,
|
||||
//! 而 worker 不知道这件事 —— 若命令层不主动告知,就会出现「侧栏显示新库、
|
||||
//! 搜索却在新库的旧索引里查」这种最难查的错。`retarget` 在库根未变时是两次
|
||||
//! 比较,成本可忽略。
|
||||
//!
|
||||
//! # 网络类命令为什么是异步的
|
||||
//!
|
||||
//! `tests_webdav` / `sync_now` / `backup_now` 会真的发 HTTP 请求(同步一个几百篇的
|
||||
//! 库可能跑几分钟)。Tauri 的同步命令会占住调用线程,因此这几个一律 `async` 并用
|
||||
//! `spawn_blocking` 把阻塞的 reqwest 调用挪到专用线程池 —— 既不卡 UI,也不卡
|
||||
//! Tauri 的命令线程池。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use super::backup;
|
||||
use super::export;
|
||||
use super::files;
|
||||
use super::import;
|
||||
use super::index::{
|
||||
NoteBacklinks, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery,
|
||||
};
|
||||
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,
|
||||
SyncProgress,
|
||||
};
|
||||
use super::webdav::{self, WebdavTestResult};
|
||||
use super::NotesManager;
|
||||
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}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
|
||||
fn emit_settings_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::NOTES_SETTINGS, ()) {
|
||||
crate::logger::log_warn("notes", &format!("发出设置变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前库根(按设置解析),并确保目录存在。
|
||||
fn current_root(state: &NotesManager) -> 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> {
|
||||
let root = current_root(state);
|
||||
let service = index_service::service(app);
|
||||
service.retarget(root)?;
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// 组装库状态概览。
|
||||
fn library_info(state: &NotesManager) -> Result<LibraryInfo, String> {
|
||||
let settings = state.load_settings();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let entries = library::scan(&root)?;
|
||||
Ok(LibraryInfo {
|
||||
root: root.to_string_lossy().to_string(),
|
||||
is_custom: settings
|
||||
.library_root
|
||||
.as_deref()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
note_count: library::count_notes(&entries),
|
||||
})
|
||||
}
|
||||
|
||||
/// 标记「本应用刚写过」,随后把库同步进索引。
|
||||
///
|
||||
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
|
||||
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
|
||||
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
|
||||
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
|
||||
fn mark_written_then_index(app: &AppHandle, state: &NotesManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
service.mark_write();
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("notes", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("notes", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 设置与库 =====
|
||||
|
||||
/// 读取笔记模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_get_settings(state: State<'_, NotesManager>) -> Result<NoteSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
settings: NoteSettings,
|
||||
) -> Result<NoteSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
// 全局快捷键可能刚被改了:就地重注册(`register_shortcut` 会先注销本模块的旧键,
|
||||
// 因此「清空快捷键」也能通过传空串生效)
|
||||
state.init_on_launch(&app);
|
||||
emit_settings_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_library_info(state: State<'_, NotesManager>) -> Result<LibraryInfo, String> {
|
||||
library_info(&state)
|
||||
}
|
||||
|
||||
/// 设置库根(`None` 或空串 = 恢复默认库根)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_set_library_root(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
root: Option<String>,
|
||||
) -> Result<LibraryInfo, String> {
|
||||
let cleaned = root.and_then(|r| {
|
||||
let trimmed = r.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed)
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = &cleaned {
|
||||
let p = std::path::Path::new(path);
|
||||
if !p.exists() {
|
||||
return Err(format!("目录不存在:{path}"));
|
||||
}
|
||||
if !p.is_dir() {
|
||||
return Err("请选择一个文件夹作为笔记库".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
settings.library_root = cleaned;
|
||||
state.save_settings(&settings)?;
|
||||
|
||||
emit_settings_changed(&app);
|
||||
let info = library_info(&state)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 扫描库,返回扁平条目列表(前端组树)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_scan_library(state: State<'_, NotesManager>) -> Result<Vec<LibraryEntry>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
library::scan(&root)
|
||||
}
|
||||
|
||||
/// 读取一篇笔记。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_read_note(state: State<'_, NotesManager>, rel_path: String) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
library::read_note(&root, &rel_path)
|
||||
}
|
||||
|
||||
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_save_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
content: String,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let doc = library::write_note(&root, &rel_path, &content)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
///
|
||||
/// `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_create_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
template_id: Option<String>,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let template = template_id.unwrap_or_default();
|
||||
// 模板为空时走「不读模板目录」的那条路径:模板目录被删/损坏也要能新建笔记
|
||||
let doc = if template.trim().is_empty() {
|
||||
library::create_note(&root, &dir_rel, &name)?
|
||||
} else {
|
||||
library::create_note_with_template(&root, &dir_rel, &name, &template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_daily_note(app: AppHandle, state: State<'_, NotesManager>) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let name = templates::daily_note_name();
|
||||
let dir = "日记";
|
||||
let rel = format!("{dir}/{name}.md");
|
||||
let path = library::safe_join(&root, &rel)?;
|
||||
let doc = if path.is_file() {
|
||||
library::read_note(&root, &rel)?
|
||||
} else {
|
||||
// 日记用同名内置模板;没有则回退默认(模板可被用户改名,这里不能假定存在)
|
||||
let template = if templates::body_of(&root, "builtin:日记").is_some() {
|
||||
"builtin:日记"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
library::create_note_with_template(&root, dir, &name, template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建文件夹。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_create_folder(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::create_folder(&root, &dir_rel, &name)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重命名条目,返回新相对路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_rename_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
new_name: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let next = library::rename_entry(&root, &rel_path, &new_name)?;
|
||||
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("notes", &format!("改名后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 删除条目(目录递归删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_delete_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
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}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
|
||||
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_rebuild_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.rebuild()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_sync_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.sync()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 把同步结果补上「索引里的笔记数」再回传(前端省一次 stats 往返)。
|
||||
fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -> NoteIndexReport {
|
||||
let note_count = service.stats().map(|s| s.note_count).unwrap_or(0);
|
||||
let mut out: NoteIndexReport = report.into();
|
||||
out.note_count = note_count;
|
||||
out
|
||||
}
|
||||
|
||||
/// 全文检索 / 按标签 / 按目录筛选。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_search_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
query: NoteSearchQuery,
|
||||
) -> Result<NoteSearchPage, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.search(query)
|
||||
}
|
||||
|
||||
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_list_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
limit: Option<i64>,
|
||||
) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.list(limit.unwrap_or(500))
|
||||
}
|
||||
|
||||
/// 标签及计数。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_tags(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.tags()
|
||||
}
|
||||
|
||||
/// 一篇笔记的链接关系(出链 + 入链)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_backlinks(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
) -> Result<NoteBacklinks, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.backlinks(&rel_path)
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_link_graph(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<Vec<LinkEdge>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let edges = service.link_graph()?;
|
||||
Ok(edges
|
||||
.into_iter()
|
||||
.map(|(from, to)| LinkEdge { from, to })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 链接图的一条边(用 `from`/`to` 而不是元组:元组序列化成数组后前端得按下标取值,
|
||||
/// 改一次顺序就静默错位 —— 与 `terminal/history.rs` 的 `HistorySource` 同一理由)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinkEdge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_index_stats(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<NoteIndexStats, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.stats()
|
||||
}
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
|
||||
/// 把库内图片读成 `data:` URL(供编辑器内联预览)。
|
||||
///
|
||||
/// # 为什么走 data URL 而不是 asset 协议
|
||||
///
|
||||
/// 库根是用户自选目录,可以用 `convertFileSrc` + `assetProtocol.scope` 直接把磁盘路径
|
||||
/// 交给 `<img>`。但那条路要求把「用户选的任意目录」加进 asset 协议的作用域白名单 ——
|
||||
/// 那等于给 WebView 开一个「可以按路径读任意文件」的口子,而笔记模块的整个安全模型
|
||||
/// 是「库根沙箱 + 授权白名单」。走 data URL 则完全在既有沙箱内:路径必须经
|
||||
/// [`library::safe_join`](拒绝 `..` 与绝对路径),且只认图片扩展名。
|
||||
///
|
||||
/// # 为什么必须有大小上限
|
||||
///
|
||||
/// data URL 是 base64,体积约为原文件的 1.34 倍,且会进 JS 堆。一张 20MB 的图片
|
||||
/// 变成 27MB 字符串,多预览几张就能把 WebView 拖垮。超限时**不报错**,返回
|
||||
/// `None` —— 调用方(编辑器)会把该图片节点当作普通文本渲染,用户看到的就是
|
||||
/// 原始 Markdown,不会打断编辑。
|
||||
const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_read_asset(
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let path = library::safe_join(&root, &rel_path)?;
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let mime = match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"svg" => "image/svg+xml",
|
||||
"bmp" => "image/bmp",
|
||||
"avif" => "image/avif",
|
||||
// 非图片(或未识别):不预览。返回 `None` 而不是报错 —— 正文里写个
|
||||
// `` 不该让编辑器弹错误。
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
|
||||
if meta.len() > MAX_ASSET_BYTES {
|
||||
crate::logger::log_info(
|
||||
"notes",
|
||||
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
use base64::Engine;
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取附件失败: {e}"))?;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
Ok(Some(format!("data:{mime};base64,{encoded}")))
|
||||
}
|
||||
|
||||
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
///
|
||||
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
|
||||
/// 事件会直接丢掉(见 `notes/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)))
|
||||
}
|
||||
|
||||
/// 打开(读取)库外任意文件。
|
||||
///
|
||||
/// 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_open_file(
|
||||
state: State<'_, NotesManager>,
|
||||
path: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
index_service::read_and_authorize(&path, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 保存库外任意文件(按前端回传的编码与换行写回)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_write_file(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
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();
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 显式登记一个路径为「可写」。
|
||||
///
|
||||
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
|
||||
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_authorize_file(path: String) -> Result<(), String> {
|
||||
if path.trim().is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
files::authorize(std::path::Path::new(path.trim()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
|
||||
///
|
||||
/// 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板,
|
||||
/// 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
|
||||
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_write_asset(
|
||||
state: State<'_, NotesManager>,
|
||||
file_name: String,
|
||||
ext: String,
|
||||
data_base64: String,
|
||||
) -> Result<String, String> {
|
||||
use base64::Engine;
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(data_base64.trim())
|
||||
.map_err(|e| format!("图片数据解析失败: {e}"))?;
|
||||
files::write_asset(&root, &file_name, &data, &ext)
|
||||
}
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
|
||||
/// 列出可用模板(用户模板优先,同名覆盖内置)。
|
||||
///
|
||||
/// 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
|
||||
/// 就能直接写文件,不需要用户先去资源管理器建目录。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_list_templates(state: State<'_, NotesManager>) -> Result<Vec<NoteTemplate>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let _ = templates::ensure_dir(&root);
|
||||
Ok(templates::list(&root))
|
||||
}
|
||||
|
||||
/// 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
|
||||
///
|
||||
/// 三种用法:
|
||||
/// - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
|
||||
/// - 传 `name` + `body`:新建一个自定义模板。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_add_template(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
name: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let written = match (name, body) {
|
||||
(Some(name), Some(body)) => {
|
||||
let safe = templates::validate_name(&name)?;
|
||||
templates::ensure_dir(&root)?;
|
||||
let path = root.join("templates").join(format!("{safe}.md"));
|
||||
if path.exists() {
|
||||
return Err(format!("模板「{safe}」已存在"));
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板失败: {e}"))?;
|
||||
vec![safe]
|
||||
}
|
||||
// 不带参数 = 导出全部内置模板
|
||||
_ => templates::export_builtin(&root)?,
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
|
||||
///
|
||||
/// 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
|
||||
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_read_template(
|
||||
state: State<'_, NotesManager>,
|
||||
template_id: String,
|
||||
) -> Result<TemplateSource, String> {
|
||||
let root = current_root(&state);
|
||||
let body = templates::body_of(&root, &template_id)
|
||||
.ok_or_else(|| format!("模板不存在:{template_id}"))?;
|
||||
Ok(TemplateSource {
|
||||
body,
|
||||
path: templates::relative_path(&template_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// 模板正文与它在库内的位置(`path` 为 `None` = 内置模板)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TemplateSource {
|
||||
pub body: String,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_import(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
source: String,
|
||||
dest_dir: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let root = current_root(&state);
|
||||
let report = import::import_path(&root, &source, &dest_dir)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
|
||||
///
|
||||
/// HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
|
||||
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_export_note(
|
||||
state: State<'_, NotesManager>,
|
||||
rel_path: String,
|
||||
html: String,
|
||||
dest: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
// 无论导出哪一篇,都要先确认它确实在库内(不接受库外相对路径)
|
||||
library::read_note(&root, &rel_path)?;
|
||||
let target = PathBuf::from(dest.trim());
|
||||
if target.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
let bytes = html.into_bytes();
|
||||
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"notes",
|
||||
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
|
||||
);
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_export_zip(
|
||||
state: State<'_, NotesManager>,
|
||||
dest: String,
|
||||
dir_rel: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let dest_path = PathBuf::from(dest.trim());
|
||||
if dest_path.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
let scope = dir_rel.unwrap_or_default();
|
||||
let (bytes, files) = export::zip_scope(&root, &scope)?;
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"notes",
|
||||
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
///
|
||||
/// 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_export_snapshot_local(
|
||||
state: State<'_, NotesManager>,
|
||||
dest: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let target = match dest.map(|d| d.trim().to_string()) {
|
||||
Some(d) if !d.is_empty() => PathBuf::from(d),
|
||||
_ => backup::default_snapshot_path(&root),
|
||||
};
|
||||
backup::snapshot_to_file(&root, &target)?;
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
// ===== WebDAV 同步 / 备份(P2) =====
|
||||
|
||||
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_webdav_status(state: State<'_, NotesManager>) -> Result<WebdavStatus, String> {
|
||||
let settings = state.load_settings();
|
||||
let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|value| !value.is_empty())
|
||||
.unwrap_or(false);
|
||||
Ok(WebdavStatus {
|
||||
configured: settings.webdav.is_configured(),
|
||||
has_password,
|
||||
remote_root: settings.webdav.remote_root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// WebDAV 配置状态(不包含密码本身)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavStatus {
|
||||
/// 地址与用户名是否已填
|
||||
pub configured: bool,
|
||||
/// keyring 里是否已存密码
|
||||
pub has_password: bool,
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn notes_set_webdav_password(password: String) -> Result<(), String> {
|
||||
if password.trim().is_empty() {
|
||||
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
|
||||
}
|
||||
crate::secrets::secret_write(webdav::KEYRING_PASSWORD, password.trim())
|
||||
}
|
||||
|
||||
/// 连接自检(建目录 + 列远端)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_test_webdav(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<WebdavTestResult, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || webdav::test_connection(&settings)).await
|
||||
}
|
||||
|
||||
/// 立即同步(并按设置决定是否追加一次快照备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_sync_now(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<SyncOutcome, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
|
||||
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
|
||||
let _ = app.emit(
|
||||
events::NOTES_SYNC_PROGRESS,
|
||||
SyncProgress {
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
kind: "prepare".to_string(),
|
||||
message: "正在比对清单…".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
let app_for_task = app.clone();
|
||||
let outcome = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
let (report, backup) = backup::sync_then_backup(&root, &webdav, &client, &app_for_task, true)?;
|
||||
Ok(SyncOutcome {
|
||||
report,
|
||||
backup,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
// 同步会改本地文件 → 索引必须跟着更新
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
outcome
|
||||
}
|
||||
|
||||
/// 一次同步的结果(报告 + 可选快照)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncOutcome {
|
||||
pub report: super::webdav::sync::SyncReport,
|
||||
pub backup: Option<BackupReport>,
|
||||
}
|
||||
|
||||
/// 只做一次 zip 快照备份(不上传增量)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_backup_now(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<BackupReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
backup::upload_snapshot(&root, &webdav, &client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 列出远端已有快照。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_list_backups(
|
||||
state: State<'_, NotesManager>,
|
||||
) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&settings)?;
|
||||
backup::list_snapshots(&client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 从远端快照恢复(不覆盖本地已有文件)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn notes_restore_backup(
|
||||
app: AppHandle,
|
||||
state: State<'_, NotesManager>,
|
||||
name: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let result = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
let (written, kept) = backup::restore_snapshot(&root, &client, &name)?;
|
||||
Ok(ImportReport {
|
||||
imported: written,
|
||||
renamed: 0,
|
||||
skipped: kept,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
})
|
||||
.await;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
result
|
||||
}
|
||||
|
||||
/// 把阻塞的 WebDAV 调用挪到专用线程池,避免占住 Tauri 的命令线程。
|
||||
///
|
||||
/// `reqwest::blocking` 在 tokio 运行时线程上会 panic(它内部会尝试建一个运行时),
|
||||
/// 因此**必须**走 `spawn_blocking` 而不是直接 `.await` 一个同步函数。
|
||||
async fn run_blocking<T, F>(task: F) -> Result<T, String>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, String> + Send + 'static,
|
||||
{
|
||||
match tokio::task::spawn_blocking(task).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => Err(format!("后台任务执行失败: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.notes/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
|
||||
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 打包范围。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// 整个库
|
||||
All,
|
||||
/// 只打包库内某个目录(连同库根的 `assets/`)
|
||||
Dir,
|
||||
}
|
||||
|
||||
/// 按范围打包,返回 `(zip 字节, 文件数)`。
|
||||
pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
|
||||
let scope = if dir_rel.trim().is_empty() {
|
||||
Scope::All
|
||||
} else {
|
||||
Scope::Dir
|
||||
};
|
||||
// 目录模式下先确认目标目录存在且仍在库内(`safe_join` 拒绝越界)
|
||||
let filter_prefix = if scope == Scope::Dir {
|
||||
let dir = library::safe_join(root, dir_rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("目录不存在:{dir_rel}"));
|
||||
}
|
||||
Some(library::rel_string(root, &dir))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// 私有目录(索引 + 同步基线)任何情况下都不导出
|
||||
if rel == ".notes" || rel.starts_with(".notes/") {
|
||||
continue;
|
||||
}
|
||||
if let Some(prefix) = &filter_prefix {
|
||||
// 目录模式:只收该目录下的文件,外加库根 assets/
|
||||
let in_scope = rel == *prefix
|
||||
|| rel.starts_with(&format!("{prefix}/"))
|
||||
|| rel.starts_with(&format!("{}/", library::ASSETS_DIR));
|
||||
if !in_scope {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("notes", &format!("导出跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(|e| format!("写入 zip 条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入 zip 内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成 zip 打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-export-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn names(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
(0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[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(".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(".custom/keep.md"), "保留").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "").unwrap();
|
||||
assert_eq!(count, 3, "a.md + .custom/keep.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"a.md".to_string()), "{list:?}");
|
||||
assert!(
|
||||
list.contains(&".custom/keep.md".to_string()),
|
||||
"普通点号目录应被导出: {list:?}"
|
||||
);
|
||||
assert!(
|
||||
!list.iter().any(|n| n.starts_with(".notes")),
|
||||
"私有目录不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_limits_scope_but_keeps_assets() {
|
||||
let root = temp_lib("dir");
|
||||
std::fs::create_dir_all(root.join("work")).unwrap();
|
||||
std::fs::create_dir_all(root.join("personal")).unwrap();
|
||||
std::fs::write(root.join("work/a.md"), "A").unwrap();
|
||||
std::fs::write(root.join("personal/b.md"), "B").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "work").unwrap();
|
||||
assert_eq!(count, 2, "work/a.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"work/a.md".to_string()), "{list:?}");
|
||||
assert!(list.contains(&"assets/p.png".to_string()), "{list:?}");
|
||||
assert!(
|
||||
!list.contains(&"personal/b.md".to_string()),
|
||||
"范围外文件不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_rejects_escape_and_missing() {
|
||||
let root = temp_lib("escape");
|
||||
assert!(zip_scope(&root, "../..").is_err(), "越界路径必须被拒");
|
||||
assert!(zip_scope(&root, "不存在").is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! 任意文本 / 代码文件的读写:编码探测、换行探测、授权路径白名单。
|
||||
//!
|
||||
//! # 与笔记库的分工
|
||||
//!
|
||||
//! 库内笔记走 `library.rs`(相对路径 + 树形结构 + front-matter);本模块服务的是
|
||||
//! **库外的任意文件**:用户用 `Ctrl+O` 或拖拽打开的一个 `.py`、`.json`、`.log`。
|
||||
//! 两者的安全模型完全不同 —— 库是「一个根目录内的沙箱」,而任意文件是「用户显式
|
||||
//! 点过的那个路径」。因此这里的守卫不是路径前缀,而是**授权集合**(见下)。
|
||||
//!
|
||||
//! # 为什么要有授权白名单
|
||||
//!
|
||||
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
|
||||
//! `notes_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
|
||||
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
|
||||
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
|
||||
//! 命令行参数、库本身。
|
||||
//!
|
||||
//! **读**比写宽松一档:读只要求「存在且是文件」,写入才强制授权。原因是打开一篇
|
||||
//! 从设置页点进来的文件不该因为「窗口重启过、授权表空了」而失败。
|
||||
//!
|
||||
//! # 编码与换行:读写成对
|
||||
//!
|
||||
//! GBK 文件被当成 UTF-8 读出来是乱码,再按 UTF-8 存回去就是**永久损坏**(原字节
|
||||
//! 已经不可逆地丢了)。因此读的时候把「编码 + 有无 BOM + 换行风格」一并记下来,
|
||||
//! 写回时原样还原;用户显式改编码时才按新编码写。换行同理:CRLF 文件存回去必须
|
||||
//! 还是 CRLF,否则一次「随手保存」就会在整个 diff 里掀起风暴。
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 会话内已授权(用户显式打开过)的路径集合。
|
||||
///
|
||||
/// 进程级静态而非 Tauri State:授权是「这一次运行期间用户点过什么」的事实,
|
||||
/// 与库根、设置无关,也不需要跨窗口同步(每个源窗口都会自己调 `authorize`)。
|
||||
static AUTHORIZED: std::sync::OnceLock<Mutex<HashSet<PathBuf>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn authorized() -> &'static Mutex<HashSet<PathBuf>> {
|
||||
AUTHORIZED.get_or_init(|| Mutex::new(HashSet::new()))
|
||||
}
|
||||
|
||||
/// 换行风格。
|
||||
pub const EOL_LF: &str = "lf";
|
||||
pub const EOL_CRLF: &str = "crlf";
|
||||
|
||||
/// 一个已打开文件的完整状态(前端据此显示编码/换行,并原样写回)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全)
|
||||
pub large: bool,
|
||||
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
|
||||
pub lines: u64,
|
||||
}
|
||||
|
||||
/// 登记一个路径为「已授权可写」。
|
||||
pub fn authorize(path: &Path) {
|
||||
let key = normalize_key(path);
|
||||
if let Ok(mut set) = authorized().lock() {
|
||||
set.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// 该路径是否已授权(写操作的前置条件)。
|
||||
pub fn is_authorized(path: &Path) -> bool {
|
||||
let key = normalize_key(path);
|
||||
authorized()
|
||||
.lock()
|
||||
.map(|set| set.contains(&key))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 授权集合的比对键:**尽力规范化**(解析符号链接与 `..`)。
|
||||
///
|
||||
/// 规范化失败(文件不存在)时退回原路径 —— 那说明写操作本来就会失败,
|
||||
/// 这里没必要为了「统一键」而提前报错。
|
||||
fn normalize_key(path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// 把路径转成可显示、可回传的字符串(剥掉 Windows 的 `\\?\` 扩展长度前缀)。
|
||||
pub fn display_path(path: &Path) -> String {
|
||||
let s = path.to_string_lossy().to_string();
|
||||
match s.strip_prefix(r"\\?\") {
|
||||
Some(rest) => rest.to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / …)。
|
||||
///
|
||||
/// # 判定顺序(每一步都有理由)
|
||||
///
|
||||
/// 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 有损解码(宁可显示替换字符,也不要打不开文件)。
|
||||
pub fn detect_encoding(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
|
||||
return "utf-8-bom".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
return "utf-16le".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFE, 0xFF]) {
|
||||
return "utf-16be".to_string();
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_ok() {
|
||||
return "utf-8".to_string();
|
||||
}
|
||||
// 非 UTF-8:交给 GB18030 兜底(GBK 的每个序列在 GB18030 下都合法)
|
||||
if crate::terminal::encoding::is_supported("gb18030") {
|
||||
return "gb18030".to_string();
|
||||
}
|
||||
"utf-8".to_string()
|
||||
}
|
||||
|
||||
/// 按编码把字节解成字符串(BOM 已剥离)。
|
||||
fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
|
||||
String::from_utf8_lossy(body).into_owned()
|
||||
}
|
||||
"utf-16le" | "utf-16be" => {
|
||||
// UTF-16 走 encoding_rs;BOM 由它自己处理
|
||||
crate::terminal::encoding::decode(bytes, "utf-16le")
|
||||
}
|
||||
other => crate::terminal::encoding::decode(bytes, other),
|
||||
}
|
||||
}
|
||||
|
||||
/// 按编码把字符串编成字节(必要时写回 BOM)。
|
||||
fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let mut out = vec![0xEF, 0xBB, 0xBF];
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
other => {
|
||||
let normalized = crate::terminal::encoding::normalize(other);
|
||||
if !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{other}"));
|
||||
}
|
||||
Ok(crate::terminal::encoding::encode(text, &normalized))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测换行风格(`\r\n` 只要出现一次就判定为 CRLF —— 混合换行的文件按主流风格写回)。
|
||||
fn detect_eol(text: &str) -> String {
|
||||
if text.contains("\r\n") {
|
||||
EOL_CRLF.to_string()
|
||||
} else {
|
||||
EOL_LF.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取任意文件。
|
||||
pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if p.is_dir() {
|
||||
return Err("这是一个目录,请选择文件".to_string());
|
||||
}
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
|
||||
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
let encoding = detect_encoding(&bytes);
|
||||
let raw = decode_bytes(&bytes, &encoding);
|
||||
let eol = detect_eol(&raw);
|
||||
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
|
||||
// 「行号 / 选区 / 大纲」三处计算各按各的口径,写法回时再还原
|
||||
let content = raw.replace("\r\n", "\n");
|
||||
let limit = (max_mb.max(1) as u64) * 1024 * 1024;
|
||||
|
||||
Ok(FileDoc {
|
||||
path: display_path(p),
|
||||
name: p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
lines: content.lines().count() as u64,
|
||||
content,
|
||||
encoding,
|
||||
eol,
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
large: meta.len() > limit,
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入任意文件。
|
||||
///
|
||||
/// `encoding` 为空串时沿用「读时探测到的编码」由前端回传的那个值 —— 调用方
|
||||
/// (编辑器)始终带着它,这里不接受「猜一个」。
|
||||
pub fn write_file(
|
||||
path: &str,
|
||||
content: &str,
|
||||
encoding: &str,
|
||||
eol: &str,
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if !is_authorized(p) {
|
||||
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
|
||||
}
|
||||
|
||||
let enc = if encoding.trim().is_empty() {
|
||||
"utf-8".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(encoding)
|
||||
};
|
||||
let text = if eol == EOL_CRLF {
|
||||
content.replace("\r\n", "\n").replace('\n', "\r\n")
|
||||
} else {
|
||||
content.replace("\r\n", "\n")
|
||||
};
|
||||
let bytes = encode_text(&text, &enc)?;
|
||||
|
||||
std::fs::write(p, &bytes).map_err(|e| format!("保存文件失败: {e}"))?;
|
||||
read_file(trimmed, max_mb)
|
||||
}
|
||||
|
||||
/// 把图片等二进制内容写入库根的 `assets/`(粘贴图片用)。
|
||||
///
|
||||
/// 返回**相对库根的路径**(统一 `/` 分隔),前端据此插入 Markdown 图片引用;
|
||||
/// 不使用绝对路径,保证笔记换个机器 / 换个库根也能打开。
|
||||
pub fn write_asset(
|
||||
root: &Path,
|
||||
file_name: &str,
|
||||
data: &[u8],
|
||||
ext: &str,
|
||||
) -> Result<String, String> {
|
||||
let assets = root.join(super::library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
|
||||
let stem = super::library::validate_name(file_name)?;
|
||||
let stem = Path::new(&stem)
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "image".to_string());
|
||||
let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();
|
||||
let ext = if ext.is_empty() { "png".to_string() } else { ext };
|
||||
|
||||
let mut candidate = format!("{stem}.{ext}");
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = format!("{stem}-{index}.{ext}");
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多,请清理 assets 目录".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::write(assets.join(&candidate), data).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(format!("{}/{candidate}", super::library::ASSETS_DIR))
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_bom_and_plain_utf8() {
|
||||
assert_eq!(detect_encoding(b"hello"), "utf-8");
|
||||
assert_eq!(detect_encoding("\u{feff}hello".as_bytes()), "utf-8-bom");
|
||||
assert_eq!(detect_encoding(&[0xFF, 0xFE, 0x41, 0x00]), "utf-16le");
|
||||
}
|
||||
|
||||
#[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"), "测试");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eol_roundtrip_preserves_crlf() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("crlf.txt");
|
||||
std::fs::write(&path, b"a\r\nb\r\n").unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.eol, EOL_CRLF);
|
||||
assert_eq!(doc.content, "a\nb\n");
|
||||
assert_eq!(doc.lines, 2);
|
||||
|
||||
authorize(&path);
|
||||
let saved = write_file(&display_path(&path), "a\nb\nc\n", "utf-8", EOL_CRLF, 5).unwrap();
|
||||
assert_eq!(saved.content, "a\nb\nc\n");
|
||||
// 落盘字节必须还是 CRLF(否则一次保存就污染整个 diff)
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"a\r\nb\r\nc\r\n");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_requires_authorization() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("unauthorized.txt");
|
||||
std::fs::write(&path, b"x").unwrap();
|
||||
let err = write_file(&display_path(&path), "y", "utf-8", EOL_LF, 5).unwrap_err();
|
||||
assert!(err.contains("未经授权"), "{err}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gbk_write_uses_original_encoding() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("gbk.txt");
|
||||
std::fs::write(&path, crate::terminal::encoding::encode("中文", "gbk")).unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.content, "中文");
|
||||
authorize(&path);
|
||||
write_file(&display_path(&path), "中文内容", &doc.encoding, &doc.eol, 5).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(crate::terminal::encoding::decode(&bytes, "gbk"), "中文内容");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_flag_uses_megabyte_limit() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("big.txt");
|
||||
std::fs::write(&path, vec![b'a'; 2048]).unwrap();
|
||||
assert!(read_file(&display_path(&path), 1).unwrap().large == false);
|
||||
// 阈值按 MB 计,2048 字节在 0 上限下被夹到 1MB,仍不算大文件
|
||||
assert!(!read_file(&display_path(&path), 0).unwrap().large);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
//! 导入:本地 Markdown 目录 / 单文件 / zip 包 → 笔记库。
|
||||
//!
|
||||
//! # 永不覆盖
|
||||
//!
|
||||
//! 导入的唯一硬规则是**不覆盖库内已有文件**:重名时加序号(`笔记 2.md`)。
|
||||
//! 理由很直接 —— 导入是个批量动作,用户不会记得库里已经有哪些名字;一旦某个
|
||||
//! 同名笔记被静默替换,就是一次不可撤销的数据丢失。「多一个文件」远比「少一篇笔记」
|
||||
//! 可接受。
|
||||
//!
|
||||
//! # zip 的路径安全
|
||||
//!
|
||||
//! zip 条目名可以包含 `..` 或绝对路径(经典的 Zip Slip)。这里用
|
||||
//! `enclosed_name()` 让 zip crate 做规范化与拒绝,再过一道 [`library::safe_join`]。
|
||||
//! 两层都做不是冗余:前者防的是「解包到库外」,后者防的是「库内路径被拼成绝对路径」。
|
||||
//!
|
||||
//! # 保留目录结构
|
||||
//!
|
||||
//! 导入目录时保留其相对结构(`笔记/2026/a.md` → `<目标目录>/笔记/2026/a.md`):
|
||||
//! 用户选一个目录导入,期待的是「把这棵子树搬进来」,而不是把几十篇笔记拍平到一层。
|
||||
//! 但**跳过隐藏目录与 `node_modules`**(与同步的排除规则同一口径)。
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::library;
|
||||
use super::types::ImportReport;
|
||||
|
||||
/// 测试里要用 `ZipWriter::write_all`(`Write` 是 trait 方法,必须进作用域)。
|
||||
#[cfg(test)]
|
||||
use std::io::Write as _;
|
||||
|
||||
/// 单次导入的文件数上限(防御性:避免误选 `C:\` 之类的目录把应用拖死)。
|
||||
const MAX_IMPORT_FILES: usize = 20_000;
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip,自动判别)。
|
||||
///
|
||||
/// `dest_dir` 为库内相对目录(空串 = 库根)。
|
||||
pub fn import_path(root: &Path, source: &str, dest_dir: &str) -> Result<ImportReport, String> {
|
||||
let path = PathBuf::from(source.trim());
|
||||
if !path.exists() {
|
||||
return Err(format!("路径不存在:{source}"));
|
||||
}
|
||||
library::ensure_library(root)?;
|
||||
// 目标目录先建出来(导入到新建的目录时它可能还不存在)
|
||||
let dest = library::safe_join(root, dest_dir)?;
|
||||
std::fs::create_dir_all(&dest).map_err(|e| format!("创建目标目录失败: {e}"))?;
|
||||
|
||||
let mut report = ImportReport::default();
|
||||
|
||||
if path.is_file() {
|
||||
let is_zip = path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("zip"))
|
||||
.unwrap_or(false);
|
||||
if is_zip {
|
||||
import_zip(root, &path, &dest, &mut report)?;
|
||||
} else {
|
||||
import_single(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
} else {
|
||||
import_dir(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
|
||||
// 导入后刷新索引交给命令层(它有 AppHandle 与索引服务)
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 导入单个文件(非 Markdown 的图片类文件放进 `assets/`)。
|
||||
fn import_single(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err("无法解析文件名".to_string());
|
||||
}
|
||||
if !is_markdown(&name) {
|
||||
// 单选的图片/附件:放进 assets,不当笔记
|
||||
return import_asset(root, file, &name, report);
|
||||
}
|
||||
copy_note(file, dest, &name, report)
|
||||
}
|
||||
|
||||
/// 递归导入目录(保留相对结构)。
|
||||
fn import_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let mut count = 0usize;
|
||||
for entry in walkdir::WalkDir::new(dir)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let rel_from_source = match path.strip_prefix(dir) {
|
||||
Ok(rel) => rel,
|
||||
Err(_) => continue,
|
||||
};
|
||||
// 跳过隐藏项与 node_modules(与同步排除口径一致)
|
||||
let rel_text = rel_from_source.to_string_lossy().replace('\\', "/");
|
||||
if rel_text
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("node_modules"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
if count > MAX_IMPORT_FILES {
|
||||
return Err(format!("导入文件过多(超过 {MAX_IMPORT_FILES}),请分批导入"));
|
||||
}
|
||||
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if is_markdown(&name) {
|
||||
// 保持子目录结构
|
||||
let sub = rel_from_source
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_dir = if sub.is_empty() {
|
||||
dest.to_path_buf()
|
||||
} else {
|
||||
let joined = library::safe_join(root, &relative_to(root, dest, &sub))?;
|
||||
std::fs::create_dir_all(&joined).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
joined
|
||||
};
|
||||
copy_note(path, &target_dir, &name, report)?;
|
||||
} else if is_asset(&name) {
|
||||
if let Err(e) = import_asset(root, path, &name, report) {
|
||||
push_failure(report, &rel_text, &e);
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 由「库内目标目录 + 源侧子目录」拼出库内相对路径。
|
||||
fn relative_to(root: &Path, dest: &Path, sub: &str) -> String {
|
||||
let prefix = library::rel_string(root, dest);
|
||||
if prefix.is_empty() {
|
||||
sub.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{sub}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 导入 zip 包(保留包内结构)。
|
||||
fn import_zip(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let handle = std::fs::File::open(file).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(handle).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
let dest_prefix = library::rel_string(root, dest);
|
||||
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取 zip 条目失败: {e}"))?;
|
||||
// Zip Slip 的第一道防线:`enclosed_name` 拒绝 `..`/绝对路径
|
||||
let Some(inner) = entry.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
push_failure(report, &format!("条目 #{index}"), "路径越界,已跳过");
|
||||
continue;
|
||||
};
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let rel = inner.to_string_lossy().replace('\\', "/");
|
||||
// macOS 压缩包常见的 `__MACOSX/` 与隐藏文件
|
||||
if rel
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("__MACOSX"))
|
||||
{
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let name = inner
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取 zip 内容失败: {e}"))?;
|
||||
|
||||
if is_markdown(&name) {
|
||||
let sub = inner
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_rel = if sub.is_empty() {
|
||||
join_rel(&dest_prefix, &name)
|
||||
} else {
|
||||
join_rel(&dest_prefix, &format!("{sub}/{name}"))
|
||||
};
|
||||
match write_unique(root, &target_rel, &bytes) {
|
||||
Ok(renamed) => {
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
}
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else if is_asset(&name) {
|
||||
match write_asset_unique(root, &name, &bytes) {
|
||||
Ok(_) => report.imported += 1,
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拷贝一篇 Markdown(重名加序号,**不覆盖**)。
|
||||
fn copy_note(
|
||||
file: &Path,
|
||||
dest_dir: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
// 目标目录已在库内,这里直接构造候选名并落盘(仍走 safe_join 的等价校验)
|
||||
let mut candidate = name.to_string();
|
||||
let mut index = 1;
|
||||
while dest_dir.join(&candidate).exists() {
|
||||
candidate = numbered(name, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let renamed = candidate != name;
|
||||
std::fs::write(dest_dir.join(&candidate), &bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把附件写进库根 `assets/`(重名加序号)。
|
||||
fn import_asset(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
write_asset_unique(root, name, &bytes)?;
|
||||
report.imported += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 写入 `assets/`(重名加序号)。
|
||||
fn write_asset_unique(root: &Path, name: &str, bytes: &[u8]) -> Result<String, String> {
|
||||
let assets = root.join(library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
let safe = library::validate_name(name)?;
|
||||
let mut candidate = safe.clone();
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = numbered(&safe, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多".to_string());
|
||||
}
|
||||
}
|
||||
std::fs::write(assets.join(&candidate), bytes).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
/// 按库内相对路径写入(重名加序号),返回是否被改名。
|
||||
fn write_unique(root: &Path, rel: &str, bytes: &[u8]) -> Result<bool, String> {
|
||||
let target = library::safe_join(root, rel)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let mut candidate = name.clone();
|
||||
let mut index = 1;
|
||||
let mut renamed = false;
|
||||
while target.parent().map(|p| p.join(&candidate).exists()).unwrap_or(false) {
|
||||
candidate = numbered(&name, index);
|
||||
index += 1;
|
||||
renamed = true;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let final_path = match target.parent() {
|
||||
Some(parent) => parent.join(&candidate),
|
||||
None => target.clone(),
|
||||
};
|
||||
std::fs::write(&final_path, bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// 拼相对路径(空前缀时不带斜杠)。
|
||||
fn join_rel(prefix: &str, name: &str) -> String {
|
||||
if prefix.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{name}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `笔记.md` → `笔记 2.md`
|
||||
fn numbered(name: &str, index: u32) -> String {
|
||||
match name.rfind('.') {
|
||||
Some(dot) => format!("{} {}{}", &name[..dot], index + 1, &name[dot..]),
|
||||
None => format!("{name} {}", index + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_markdown(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
|| name.to_ascii_lowercase().ends_with(".markdown")
|
||||
}
|
||||
|
||||
/// 附件类型的白名单(图片、PDF、压缩包以外的常见附件)。
|
||||
///
|
||||
/// 用白名单而不是「非 md 即附件」:导入一个目录时往往会混进 `.DS_Store`、
|
||||
/// `Thumbs.db`、`.gitignore` 之类;把它们全塞进 `assets/` 只会制造垃圾。
|
||||
fn is_asset(name: &str) -> bool {
|
||||
const EXT: &[&str] = &[
|
||||
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "avif", "pdf", "mp3", "wav", "mp4",
|
||||
"webm", "zip",
|
||||
];
|
||||
match name.rsplit('.').next() {
|
||||
Some(ext) => EXT.contains(&ext.to_ascii_lowercase().as_str()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_failure(report: &mut ImportReport, name: &str, error: &str) {
|
||||
if report.failures.len() < 20 {
|
||||
report.failures.push(format!("{name}:{error}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-import-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_single_file_renames_instead_of_overwriting() {
|
||||
let root = temp_lib("single");
|
||||
let src_dir = std::env::temp_dir().join(format!("thing-notes-src-single-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
std::fs::create_dir_all(&src_dir).unwrap();
|
||||
std::fs::write(src_dir.join("a.md"), "导入的内容").unwrap();
|
||||
// 库内已有一篇同名
|
||||
std::fs::write(root.join("a.md"), "库里原有的").unwrap();
|
||||
|
||||
let report = import_path(&root, &src_dir.join("a.md").to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1);
|
||||
assert_eq!(report.renamed, 1);
|
||||
// 原有内容必须没被覆盖
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "库里原有的");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a 2.md")).unwrap(), "导入的内容");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_keeps_structure_and_skips_junk() {
|
||||
let root = temp_lib("dir");
|
||||
let src = std::env::temp_dir().join(format!("thing-notes-src-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
std::fs::create_dir_all(src.join(".git")).unwrap();
|
||||
std::fs::write(src.join("top.md"), "top").unwrap();
|
||||
std::fs::write(src.join("sub/deep.md"), "deep").unwrap();
|
||||
std::fs::write(src.join("sub/note.txt"), "不是 md").unwrap();
|
||||
std::fs::write(src.join(".git/config"), "不该导入").unwrap();
|
||||
std::fs::write(src.join("pic.png"), [1u8, 2, 3]).unwrap();
|
||||
|
||||
let report = import_path(&root, &src.to_string_lossy(), "导入").unwrap();
|
||||
assert_eq!(report.imported, 3, "两篇 md + 一张图片: {report:?}");
|
||||
assert_eq!(report.skipped, 1, "note.txt 应被跳过: {report:?}");
|
||||
assert!(root.join("导入/top.md").is_file());
|
||||
assert!(root.join("导入/sub/deep.md").is_file(), "应保留子目录结构");
|
||||
assert!(root.join("assets/pic.png").is_file());
|
||||
assert!(!root.join("导入/.git").exists());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_zip_keeps_structure_and_rejects_traversal() {
|
||||
let root = temp_lib("zip");
|
||||
let zip_path = std::env::temp_dir().join(format!("thing-notes-src-{}.zip", std::process::id()));
|
||||
{
|
||||
let file = std::fs::File::create(&zip_path).unwrap();
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default();
|
||||
writer.start_file("notes/a.md", options).unwrap();
|
||||
writer.write_all(b"# A").unwrap();
|
||||
// 恶意条目:逃出库根
|
||||
writer.start_file("../escape.md", options).unwrap();
|
||||
writer.write_all("坏".as_bytes()).unwrap();
|
||||
writer.start_file("__MACOSX/x.md", options).unwrap();
|
||||
writer.write_all(b"mac").unwrap();
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
|
||||
let report = import_path(&root, &zip_path.to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1, "{report:?}");
|
||||
assert!(root.join("notes/a.md").is_file());
|
||||
// `enclosed_name()` 会把 `../escape.md` 归一化成 `escape.md`(去掉了越界前缀),
|
||||
// 关键是**没有写到库根之外**
|
||||
let parent = root.parent().unwrap();
|
||||
assert!(!parent.join("escape.md").exists(), "不能写到库根之外");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_file(&zip_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_names_keep_extension() {
|
||||
assert_eq!(numbered("a.md", 1), "a 2.md");
|
||||
assert_eq!(numbered("无扩展名", 0), "无扩展名 1");
|
||||
assert_eq!(numbered("a.b.md", 2), "a.b 3.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_whitelist_rejects_junk() {
|
||||
assert!(is_asset("pic.png"));
|
||||
assert!(is_asset("PIC.PNG"));
|
||||
assert!(is_asset("doc.pdf"));
|
||||
assert!(!is_asset("Thumbs.db"));
|
||||
assert!(!is_asset(".DS_Store"));
|
||||
assert!(!is_asset("noext"));
|
||||
}}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,506 @@
|
||||
//! 索引服务:单线程 worker + notify 文件监听。
|
||||
//!
|
||||
//! # 为什么索引必须由一个线程独占
|
||||
//!
|
||||
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
|
||||
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
|
||||
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
|
||||
//!
|
||||
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
|
||||
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
|
||||
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
|
||||
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
|
||||
//! 连接始终只有一个,顺序天然可预期。
|
||||
//!
|
||||
//! # 监听器为什么也挂在这个线程上
|
||||
//!
|
||||
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
|
||||
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
|
||||
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
|
||||
//! 关着而漏掉索引更新。
|
||||
//!
|
||||
//! 自我保存抑制([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
|
||||
//! `Modify(Data)`,若不抑制,前端就会在用户自己打字时反复弹出「文件已被外部修改」。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::files;
|
||||
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, NotesIndex};
|
||||
use super::library;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 自我保存抑制窗口:`notes_write_*` 之后这段时间内的文件事件不当作「外部修改」。
|
||||
///
|
||||
/// 取 1200ms:前端自动保存默认 800ms 防抖,加上写盘与 notify 自身的派发延迟,
|
||||
/// 这个窗口足够覆盖「自己写的」这一类事件,又短到不会吞掉用户紧接着在外部编辑器
|
||||
/// 里的另一次保存(那种情况用户本来就刚切过窗口,多等一秒无妨)。
|
||||
const SUPPRESS_MS: u64 = 1200;
|
||||
|
||||
/// 单个文件事件的去抖说明。
|
||||
///
|
||||
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
|
||||
/// 前端 `notes-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
|
||||
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
|
||||
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
|
||||
const _DEBOUNCE_NOTE_MS: u64 = 250;
|
||||
|
||||
/// 库文件变化的分类(前端据此决定「重载当前笔记」还是「只刷新树」)。
|
||||
///
|
||||
/// 只有 `removed` 是确定事实(文件不在了);「新建」与「修改」在单文件事件层面
|
||||
/// **无法区分**(notify 给的 `Create` 与 `Modify` 在一次保存里会同时出现),
|
||||
/// 因此统一报 [`CHANGE_MODIFIED`],由前端按「路径在不在当前树里」自行判断。
|
||||
pub const CHANGE_MODIFIED: &str = "modified";
|
||||
pub const CHANGE_REMOVED: &str = "removed";
|
||||
|
||||
/// 广播给各窗口的库文件变化事件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteFileEvent {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 磁盘上的绝对路径。
|
||||
///
|
||||
/// 前端需要它来判断「这个事件说的是不是我正在编辑的那个库外文件」——
|
||||
/// 相对库根路径对库外文件没有意义(它根本不在库里),只留 `rel_path`
|
||||
/// 会让「打开 D:\x\a.md 时有人在别处改了它」永远匹配不上。
|
||||
pub abs_path: String,
|
||||
/// "modified" | "removed"
|
||||
pub kind: String,
|
||||
/// 事件发生时间(Unix 毫秒)
|
||||
pub at: u64,
|
||||
/// 是否是本应用自己写入造成的(前端据此跳过「外部修改」提示)
|
||||
pub from_app: bool,
|
||||
}
|
||||
|
||||
/// 一次索引同步的结果(命令返回值)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteIndexReport {
|
||||
pub indexed: i64,
|
||||
pub removed: i64,
|
||||
pub skipped: i64,
|
||||
/// 同步后索引里的笔记数(前端直接显示,省一次统计往返)
|
||||
pub note_count: i64,
|
||||
}
|
||||
|
||||
impl From<NoteSyncReport> for NoteIndexReport {
|
||||
fn from(report: NoteSyncReport) -> Self {
|
||||
Self {
|
||||
indexed: report.indexed,
|
||||
removed: report.removed,
|
||||
skipped: report.skipped,
|
||||
note_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 请求。
|
||||
enum Request {
|
||||
/// 增量同步整个库
|
||||
Sync(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 全量重建
|
||||
Rebuild(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
|
||||
SyncPath(PathBuf, bool),
|
||||
/// 全文检索
|
||||
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
|
||||
/// 快速打开清单
|
||||
List(i64, Sender<Result<Vec<NoteSearchHit>, String>>),
|
||||
/// 标签清单
|
||||
Tags(Sender<Result<Vec<super::index::NoteTagCount>, String>>),
|
||||
/// 一篇笔记的出链 / 入链
|
||||
Backlinks(String, Sender<Result<super::index::NoteBacklinks, String>>),
|
||||
/// 全库链接图
|
||||
LinkGraph(Sender<Result<Vec<(String, String)>, String>>),
|
||||
/// 索引状态
|
||||
Stats(Sender<Result<NoteIndexStats, String>>),
|
||||
/// 重建监听器(库根变化后)
|
||||
Retarget(PathBuf, Sender<Result<(), String>>),
|
||||
}
|
||||
|
||||
/// 索引服务的句柄(命令层只拿到这个)。
|
||||
pub struct IndexService {
|
||||
tx: Sender<Request>,
|
||||
/// 自我保存抑制的时间点(`notes_write_*` 写入)
|
||||
last_write: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
|
||||
|
||||
/// 取索引服务(首次调用时启动 worker 线程与监听器)。
|
||||
pub fn service(app: &AppHandle) -> &'static IndexService {
|
||||
SERVICE.get_or_init(|| IndexService::start(app.clone()))
|
||||
}
|
||||
|
||||
impl IndexService {
|
||||
fn start(app: AppHandle) -> Self {
|
||||
let (tx, rx) = mpsc::channel::<Request>();
|
||||
let handle_tx = tx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("notes-index".to_string())
|
||||
.spawn(move || worker_loop(app, rx, handle_tx))
|
||||
.expect("启动笔记索引线程失败");
|
||||
Self {
|
||||
tx,
|
||||
last_write: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 标记「刚刚由本应用写入了文件」,用于抑制自我触发的「外部修改」提示。
|
||||
pub fn mark_write(&self) {
|
||||
if let Ok(mut slot) = self.last_write.lock() {
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
fn recently_written(&self) -> bool {
|
||||
self.last_write
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| *slot)
|
||||
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 增量同步整个库。
|
||||
pub fn sync(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Sync(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全量重建索引。
|
||||
pub fn rebuild(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Rebuild(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全文检索。
|
||||
pub fn search(&self, query: NoteSearchQuery) -> Result<NoteSearchPage, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Search(query, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 快速打开清单。
|
||||
pub fn list(&self, limit: i64) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::List(limit, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 标签清单。
|
||||
pub fn tags(&self) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Tags(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 索引状态。
|
||||
pub fn stats(&self) -> Result<NoteIndexStats, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Stats(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 一篇笔记的出链 / 入链。
|
||||
pub fn backlinks(&self, rel_path: &str) -> Result<super::index::NoteBacklinks, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Backlinks(rel_path.to_string(), tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
pub fn link_graph(&self) -> Result<Vec<(String, String)>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::LinkGraph(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 切换库根(重新打开索引 + 重建监听器)。
|
||||
pub fn retarget(&self, root: PathBuf) -> Result<(), String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Retarget(root, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 主循环:独占 [`NotesIndex`],串行处理所有请求。
|
||||
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
|
||||
let mut index: Option<NotesIndex> = None;
|
||||
let mut watcher: Option<RecommendedWatcher> = None;
|
||||
let mut watched_root: Option<PathBuf> = None;
|
||||
let mut root: Option<PathBuf> = None;
|
||||
|
||||
while let Ok(request) = rx.recv() {
|
||||
match request {
|
||||
Request::Sync(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.sync()));
|
||||
}
|
||||
Request::Rebuild(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.rebuild()));
|
||||
}
|
||||
Request::Search(query, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.search(query)));
|
||||
}
|
||||
Request::List(limit, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.list_notes(limit)));
|
||||
}
|
||||
Request::Tags(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.tags()));
|
||||
}
|
||||
Request::Backlinks(rel_path, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| {
|
||||
idx.backlinks(&rel_path)
|
||||
}));
|
||||
}
|
||||
Request::LinkGraph(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.link_graph()));
|
||||
}
|
||||
Request::Stats(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
|
||||
}
|
||||
Request::Retarget(next, reply) => {
|
||||
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
|
||||
index = None;
|
||||
root = Some(next.clone());
|
||||
let result = match ensure_index(&app, &mut index, &next) {
|
||||
Ok(_) => {
|
||||
watched_root = None; // 触发重建监听器
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
|
||||
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
|
||||
}
|
||||
Request::SyncPath(path, from_app) => {
|
||||
if let Some(current) = root.clone() {
|
||||
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
|
||||
if index.is_none() {
|
||||
if let Err(e) = ensure_index(&app, &mut index, ¤t) {
|
||||
crate::logger::log_warn("notes", &format!("索引不可用: {e}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensure_watcher(&mut watcher, &mut watched_root, ¤t, &handle_tx);
|
||||
sync_one(&app, index.as_mut(), ¤t, &path, from_app);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
|
||||
fn with_index<T>(
|
||||
app: &AppHandle,
|
||||
index: &mut Option<NotesIndex>,
|
||||
root: &mut Option<PathBuf>,
|
||||
run: impl FnOnce(&mut NotesIndex) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let Some(current) = root.clone() else {
|
||||
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
|
||||
// 猜错的后果是索引挂到别的目录上(用户切过库时尤其明显)。
|
||||
return Err("索引尚未指向任何笔记库(请先打开笔记窗口)".to_string());
|
||||
};
|
||||
ensure_index(app, index, ¤t)?;
|
||||
match index.as_mut() {
|
||||
Some(idx) => run(idx),
|
||||
None => Err("索引未就绪".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
|
||||
fn ensure_index(app: &AppHandle, index: &mut Option<NotesIndex>, 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);
|
||||
}
|
||||
let opened = NotesIndex::open(root)?;
|
||||
crate::logger::log_info(
|
||||
"notes",
|
||||
&format!("索引已就绪: {}", opened.db_path().display()),
|
||||
);
|
||||
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
|
||||
let _ = app;
|
||||
*index = Some(opened);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 确保监听器挂在 `root` 上。
|
||||
fn ensure_watcher(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) {
|
||||
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
|
||||
crate::logger::log_warn("notes", &e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 建/换监听器(`root` 未变则不动)。
|
||||
fn ensure_watcher_inner(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) -> Result<(), String> {
|
||||
if watched_root.as_deref() == Some(root) && watcher.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let sender = tx.clone();
|
||||
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));
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("创建库监听器失败: {e}"))?;
|
||||
|
||||
next.watch(root, RecursiveMode::Recursive)
|
||||
.map_err(|e| format!("监听笔记库失败: {e}"))?;
|
||||
|
||||
// 替换旧监听器(drop 即 unwatch)
|
||||
*watcher = Some(next);
|
||||
*watched_root = Some(root.to_path_buf());
|
||||
crate::logger::log_info("notes", &format!("库监听已启动: {}", root.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.notes/` 自身)。
|
||||
///
|
||||
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
|
||||
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
|
||||
fn event_paths(event: ¬ify::Event) -> Vec<PathBuf> {
|
||||
if matches!(event.kind, EventKind::Access(_) | EventKind::Other) {
|
||||
return Vec::new();
|
||||
}
|
||||
event
|
||||
.paths
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy().to_string());
|
||||
// 只跟踪 .md 与目录事件(目录事件用于捕捉「整目录移入」)
|
||||
let is_md = name
|
||||
.as_deref()
|
||||
.map(|n| n.to_ascii_lowercase().ends_with(".md"))
|
||||
.unwrap_or(false);
|
||||
let is_meta = p
|
||||
.components()
|
||||
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
|
||||
is_md && !is_meta
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
|
||||
fn sync_one(
|
||||
app: &AppHandle,
|
||||
index: Option<&mut NotesIndex>,
|
||||
root: &Path,
|
||||
path: &Path,
|
||||
from_app: bool,
|
||||
) {
|
||||
let Some(index) = index else { return };
|
||||
let rel = library::rel_string(root, path);
|
||||
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
|
||||
return;
|
||||
}
|
||||
|
||||
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
|
||||
let service = SERVICE.get();
|
||||
let self_write = from_app && service.map(|s| s.recently_written()).unwrap_or(false);
|
||||
|
||||
let kind = if path.is_file() {
|
||||
if let Ok(bytes) = std::fs::read(path) {
|
||||
let content = String::from_utf8_lossy(&bytes);
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let mtime = meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
let stems = std::collections::HashMap::new();
|
||||
if let Err(e) = index.upsert_note(
|
||||
&rel,
|
||||
&content,
|
||||
mtime,
|
||||
meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
&content_hash(&bytes),
|
||||
&stems,
|
||||
) {
|
||||
crate::logger::log_warn("notes", &format!("增量索引 {rel} 失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
|
||||
// (重载树)。真正需要区分时以库扫描结果为准。
|
||||
CHANGE_MODIFIED
|
||||
} else {
|
||||
if let Err(e) = index.remove_note(&rel) {
|
||||
crate::logger::log_warn("notes", &format!("移除索引 {rel} 失败: {e}"));
|
||||
}
|
||||
CHANGE_REMOVED
|
||||
};
|
||||
|
||||
if self_write {
|
||||
// 自己写的:索引已更新,前端无需提示(它的编辑器里本来就是最新内容)
|
||||
return;
|
||||
}
|
||||
|
||||
let payload = NoteFileEvent {
|
||||
rel_path: rel,
|
||||
abs_path: files::display_path(path),
|
||||
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}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 授权 + 读取(供命令层调用,收敛「读文件必须先登记授权」这条规则)。
|
||||
pub fn read_and_authorize(path: &str, max_mb: u32) -> Result<files::FileDoc, String> {
|
||||
let doc = files::read_file(path, max_mb)?;
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(doc)
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! 笔记库的文件系统层:路径安全解析、扫描、读写、增删改移。
|
||||
//!
|
||||
//! # 真相在文件,不在数据库
|
||||
//!
|
||||
//! 笔记就是库根下的 `.md` 文件树。本文件的每个函数都以「相对库根的路径」为
|
||||
//! 输入/输出,**所有路径都先过 [`safe_join`]**:拒绝绝对路径、盘符与 `..`,
|
||||
//! 保证任何操作都无法越出库根(前端传来的路径一律不可信)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::types::{LibraryEntry, NoteDoc, NoteSettings};
|
||||
|
||||
/// 默认库根相对模块目录的名字:`{app_data_dir}/notes/library`
|
||||
pub const DEFAULT_LIBRARY_DIR: &str = "library";
|
||||
/// 附件(粘贴图片等)目录名,位于库根下
|
||||
pub const ASSETS_DIR: &str = "assets";
|
||||
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
|
||||
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
|
||||
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
|
||||
pub const MAX_DEPTH: usize = 24;
|
||||
|
||||
/// 新建笔记的正文模板(front-matter + 一级标题)。
|
||||
fn note_template(title: &str) -> String {
|
||||
let now = chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||
format!(
|
||||
"---\ntitle: {title}\ncreated: {now}\nupdated: {now}\ntags: []\n---\n\n# {title}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// 默认库根路径(未配置自定义库根时使用)。
|
||||
pub fn default_library_root(module_dir: &Path) -> PathBuf {
|
||||
module_dir.join(DEFAULT_LIBRARY_DIR)
|
||||
}
|
||||
|
||||
/// 由设置解析出当前生效的库根。
|
||||
pub fn resolve_library_root(module_dir: &Path, settings: &NoteSettings) -> PathBuf {
|
||||
match &settings.library_root {
|
||||
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
|
||||
_ => default_library_root(module_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库根与其 `assets/` 子目录存在。
|
||||
pub fn ensure_library(root: &Path) -> Result<(), String> {
|
||||
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}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把「相对库根的路径」解析为绝对路径,并拒绝任何逃逸。
|
||||
///
|
||||
/// 空串表示库根本身。统一接受 `/` 与 `\` 两种分隔符输入,输出用系统分隔符。
|
||||
pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf, String> {
|
||||
let normalized = rel.trim().replace('\\', "/");
|
||||
if normalized.starts_with('/') || normalized.contains(':') {
|
||||
return Err("仅支持库内相对路径".to_string());
|
||||
}
|
||||
let mut out = root.to_path_buf();
|
||||
for part in normalized.split('/') {
|
||||
if part.is_empty() || part == "." {
|
||||
continue;
|
||||
}
|
||||
if part == ".." {
|
||||
return Err("路径不能包含上级目录(..)".to_string());
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 绝对路径 → 相对库根的路径(统一 `/` 分隔)。
|
||||
pub fn rel_string(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 校验用户输入的条目名(新建/重命名)。
|
||||
///
|
||||
/// 拒绝路径分隔符、Windows 保留字符与控制字符 —— 名称只应是「一个名字」,
|
||||
/// 不含任何路径语义。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("名称不能为空".to_string());
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return Err("名称不合法".to_string());
|
||||
}
|
||||
if name.chars().count() > 120 {
|
||||
return Err("名称过长".to_string());
|
||||
}
|
||||
if name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
|
||||
{
|
||||
return Err("名称不能包含 < > : \" / \\ | ? * 等字符".to_string());
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
fn is_note_file(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
}
|
||||
|
||||
fn modified_ms(meta: &std::fs::Metadata) -> u64 {
|
||||
meta.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 扫描整个库,返回扁平条目列表(目录在前、各自按名称排序;前端自行组树)。
|
||||
pub fn scan(root: &Path) -> Result<Vec<LibraryEntry>, String> {
|
||||
let mut out = Vec::new();
|
||||
if !root.is_dir() {
|
||||
return Ok(out);
|
||||
}
|
||||
walk(root, root, &mut out, 0);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let mut dirs: Vec<(String, PathBuf)> = Vec::new();
|
||||
let mut files: Vec<(String, PathBuf)> = Vec::new();
|
||||
for entry in read.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
// 隐藏项(含 `.notes` 之类的私有目录)一律不进库树
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let file_type = match entry.file_type() {
|
||||
Ok(t) => t,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let path = entry.path();
|
||||
if file_type.is_dir() {
|
||||
// 根级 assets 是图片仓库,不作为笔记目录展示,避免噪声
|
||||
if depth == 0 && name == ASSETS_DIR {
|
||||
continue;
|
||||
}
|
||||
dirs.push((name, path));
|
||||
} else if file_type.is_file() && is_note_file(&name) {
|
||||
files.push((name, path));
|
||||
}
|
||||
}
|
||||
|
||||
dirs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
for (name, path) in dirs {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: true,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: 0,
|
||||
});
|
||||
walk(root, &path, out, depth + 1);
|
||||
}
|
||||
for (name, path) in files {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: false,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 统计库内 `.md` 文件数量。
|
||||
pub fn count_notes(entries: &[LibraryEntry]) -> u32 {
|
||||
entries.iter().filter(|e| !e.is_dir).count() as u32
|
||||
}
|
||||
|
||||
/// 构造一篇文档的返回结构。
|
||||
fn to_doc(root: &Path, path: &Path, content: String) -> NoteDoc {
|
||||
let modified = std::fs::metadata(path).map(|m| modified_ms(&m)).unwrap_or(0);
|
||||
NoteDoc {
|
||||
rel_path: rel_string(root, path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content,
|
||||
modified,
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取一篇笔记(相对库根路径)。非 UTF-8 字节按 lossy 处理,不报错。
|
||||
pub fn read_note(root: &Path, rel: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
/// 写入一篇笔记(已存在的文件才允许写;不自动创建目录,由 create_note 负责)。
|
||||
pub fn write_note(root: &Path, rel: &str, content: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
std::fs::write(&path, content).map_err(|e| format!("保存笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, content.to_string()))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记:自动补 `.md`、重名自动加序号。
|
||||
///
|
||||
/// 用**内置**的 front-matter 模板(不读 `templates/`)。保留这个无模板参数的入口是
|
||||
/// 为了「模板目录被删/损坏时仍然能新建笔记」这条底线,单测也走它。
|
||||
pub fn create_note(root: &Path, dir_rel: &str, name: &str) -> Result<NoteDoc, String> {
|
||||
create_note_with_template(root, dir_rel, name, "")
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记,正文由模板渲染(`template_id` 为空 = 用内置默认模板)。
|
||||
///
|
||||
/// 模板渲染失败(模板文件被删、权限不足)时回退到内置模板而不是报错:
|
||||
/// 「新建笔记」这个动作不该因为一个辅助文件的问题而不可用。
|
||||
pub fn create_note_with_template(
|
||||
root: &Path,
|
||||
dir_rel: &str,
|
||||
name: &str,
|
||||
template_id: &str,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
|
||||
let mut file_name = validate_name(name)?;
|
||||
if !is_note_file(&file_name) {
|
||||
file_name.push_str(".md");
|
||||
}
|
||||
let title = file_name.trim_end_matches(".md").to_string();
|
||||
|
||||
// 重名自动加序号,避免「新建即报错」
|
||||
let mut candidate = file_name.clone();
|
||||
let mut index = 1;
|
||||
while dir.join(&candidate).exists() {
|
||||
candidate = format!("{title} {index}.md");
|
||||
index += 1;
|
||||
if index > 999 {
|
||||
return Err("同名文件过多,请换一个名称".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// 模板渲染:模板 ID 无效时 `render_for_new_note` 自己会回退到内置空白模板
|
||||
let content = if template_id.trim().is_empty() {
|
||||
note_template(&title)
|
||||
} else {
|
||||
super::templates::render_for_new_note(root, template_id, &title, dir_rel)
|
||||
};
|
||||
|
||||
let path = dir.join(&candidate);
|
||||
std::fs::write(&path, content).map_err(|e| format!("新建笔记失败: {e}"))?;
|
||||
read_note(root, &rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建文件夹。
|
||||
pub fn create_folder(root: &Path, dir_rel: &str, name: &str) -> Result<String, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
let folder_name = validate_name(name)?;
|
||||
let path = dir.join(&folder_name);
|
||||
if path.exists() {
|
||||
return Err(format!("「{folder_name}」已存在"));
|
||||
}
|
||||
std::fs::create_dir_all(&path).map_err(|e| format!("新建文件夹失败: {e}"))?;
|
||||
Ok(rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 重命名库内条目;返回新的相对路径。
|
||||
///
|
||||
/// 文件若未带扩展名,沿用原扩展名(避免 `a.md` 改成 `a` 变成无扩展名文件)。
|
||||
pub fn rename_entry(root: &Path, rel: &str, new_name: &str) -> Result<String, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
let mut name = validate_name(new_name)?;
|
||||
if path.is_file() {
|
||||
let old_ext = path.extension().map(|e| e.to_string_lossy().to_string());
|
||||
if let Some(ext) = old_ext {
|
||||
if !name.to_ascii_lowercase().ends_with(&format!(".{}", ext.to_ascii_lowercase())) {
|
||||
name.push('.');
|
||||
name.push_str(&ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let target = parent.join(&name);
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::rename(&path, &target).map_err(|e| format!("重命名失败: {e}"))?;
|
||||
Ok(rel_string(root, &target))
|
||||
}
|
||||
|
||||
/// 删除库内条目(目录递归删除)。
|
||||
pub fn delete_entry(root: &Path, rel: &str) -> Result<(), String> {
|
||||
if rel.trim().is_empty() {
|
||||
return Err("不能删除库根".to_string());
|
||||
}
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
if path.is_dir() {
|
||||
std::fs::remove_dir_all(&path).map_err(|e| format!("删除目录失败: {e}"))?;
|
||||
} else {
|
||||
std::fs::remove_file(&path).map_err(|e| format!("删除文件失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! 笔记 / 编辑器模块。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! NotesManager(本文件):设置读写 / 库根解析
|
||||
//! ↓
|
||||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||||
//! ```
|
||||
//!
|
||||
//! # 真相在文件
|
||||
//!
|
||||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||||
//!
|
||||
//! # 三个入口的职责边界
|
||||
//!
|
||||
//! ```text
|
||||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||||
//! ```
|
||||
//!
|
||||
//! 设置持久化:`{app_data_dir}/notes/settings.json`(范式同 ai / translate)。
|
||||
//! 默认库根:`{app_data_dir}/notes/library`;用户可在设置里改。
|
||||
|
||||
mod args;
|
||||
mod backup;
|
||||
mod commands;
|
||||
mod export;
|
||||
mod files;
|
||||
mod import;
|
||||
mod index;
|
||||
mod index_service;
|
||||
mod library;
|
||||
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,
|
||||
};
|
||||
pub use args::{emit_open_file, note_path_from_args, remember_pending_file};
|
||||
use types::NoteSettings;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: NoteSettings,
|
||||
}
|
||||
|
||||
/// 笔记模块管理器(Tauri State)。
|
||||
pub struct NotesManager {
|
||||
/// 模块自身目录:`{app_data_dir}/notes`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
impl NotesManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("notes");
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块自身目录(库根默认值基于它解析)。
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
|
||||
/// 启动时按设置注册全局快捷键。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(与 translate / terminal 同一姿态)。
|
||||
/// 触发时**只发事件**,窗口与「新建哪一篇」由前端决定 —— Rust 侧不持有窗口 label
|
||||
/// 策略,也不该知道当前打开的库是哪一篇(那是前端 store 的事)。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
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}"));
|
||||
}
|
||||
}) {
|
||||
crate::logger::log_warn("notes", &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::logger::log_warn("notes", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> NoteSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<NoteSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("notes", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &NoteSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json)
|
||||
.map_err(|e| format!("写入笔记设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 新建笔记的模板:内置默认模板 + 用户模板目录。
|
||||
//!
|
||||
//! # 模板为什么要落成 `.md` 文件
|
||||
//!
|
||||
//! 与「笔记的真相是文件」同一条原则:模板也是用户会想改的东西,做成 JSON 里的一段
|
||||
//! 字符串,用户既看不到也改不了。落成 `.md` 文件后,用任意编辑器改,改完立刻生效。
|
||||
//!
|
||||
//! # 两个来源
|
||||
//!
|
||||
//! - **内置**:编译进二进制(`include_str!`),保证全新机器上「新建笔记」永远有东西可用;
|
||||
//! - **用户**:`{库根}/templates/*.md`。库是可切换的,模板跟着库走 —— 一个技术笔记库
|
||||
//! 和一个日记库本来就该有不同的模板集。
|
||||
//!
|
||||
//! 同名时用户模板覆盖内置模板。内置模板不写进库根(否则用户第一次新建笔记就会
|
||||
//! 发现库里多出一堆他没建过的文件)。
|
||||
//!
|
||||
//! # 变量替换
|
||||
//!
|
||||
//! 只支持少量、无歧义的占位符(`{{date}}` / `{{time}}` / `{{title}}` / `{{datetime}}`)。
|
||||
//! **不做条件、循环、包含** —— 那是一条通往「半个模板引擎」的路,收益远小于维护成本。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 一个模板。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteTemplate {
|
||||
/// 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`)
|
||||
pub id: String,
|
||||
/// 显示名(文件名去掉扩展名)
|
||||
pub name: String,
|
||||
/// 说明(内置模板手写;用户模板取正文首行非空文本)
|
||||
pub description: String,
|
||||
/// 是否为内置模板(前端据此提示「不可删除」)
|
||||
pub builtin: bool,
|
||||
/// 模板正文(含 front-matter)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// 内置模板(编译进二进制)。
|
||||
const BUILTIN: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"空白笔记",
|
||||
"只有 front-matter 与一级标题,适合随手记",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: []\n---\n\n# {{title}}\n\n",
|
||||
),
|
||||
(
|
||||
"会议纪要",
|
||||
"议题 / 结论 / 待办三段式",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [会议]\n---\n\n# {{title}}\n\n- 时间:{{datetime}}\n- 参会:\n\n## 议题\n\n## 结论\n\n## 待办\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"日记",
|
||||
"按日期归档的日记骨架",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [日记]\n---\n\n# {{date}}\n\n## 今天做了什么\n\n## 明天要做什么\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"读书笔记",
|
||||
"书籍信息 + 摘录 + 思考",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [读书]\n---\n\n# {{title}}\n\n- 书名:\n- 作者:\n- 进度:\n\n## 摘录\n\n> \n\n## 我的思考\n\n",
|
||||
),
|
||||
];
|
||||
|
||||
/// 列出全部模板(用户模板优先,同名覆盖内置)。
|
||||
pub fn list(root: &Path) -> Vec<NoteTemplate> {
|
||||
let mut out: Vec<NoteTemplate> = Vec::new();
|
||||
|
||||
// 用户模板:`{库根}/templates/*.md`
|
||||
let dir = root.join("templates");
|
||||
if dir.is_dir() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path.is_file()
|
||||
&& path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("md"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
let name = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(body) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
out.push(NoteTemplate {
|
||||
id: format!("user:{name}"),
|
||||
description: first_meaningful_line(&body),
|
||||
name,
|
||||
builtin: false,
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 内置模板:跳过已被用户模板同名的
|
||||
for (name, description, body) in BUILTIN {
|
||||
if out.iter().any(|item| item.name == *name) {
|
||||
continue;
|
||||
}
|
||||
out.push(NoteTemplate {
|
||||
id: format!("builtin:{name}"),
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
builtin: true,
|
||||
body: body.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// 取模板 ID 对应的正文;找不到返回 `None`(调用方回退到默认模板)。
|
||||
pub fn body_of(root: &Path, id: &str) -> Option<String> {
|
||||
list(root).into_iter().find(|t| t.id == id).map(|t| t.body)
|
||||
}
|
||||
|
||||
/// 把模板正文渲染成一篇新笔记的内容。
|
||||
///
|
||||
/// `parent_dir` 是笔记所在的库内目录(用于 `{{date}}` 之类不受影响,但保留参数
|
||||
/// 以便将来加入「所在目录」变量)。
|
||||
pub fn render(body: &str, title: &str, _parent_dir: &str) -> String {
|
||||
let now = chrono::Local::now();
|
||||
body.replace("{{title}}", title)
|
||||
.replace("{{date}}", &now.format("%Y-%m-%d").to_string())
|
||||
.replace("{{time}}", &now.format("%H:%M").to_string())
|
||||
.replace("{{datetime}}", &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
|
||||
}
|
||||
|
||||
/// 日记的默认文件名(`2026-09-30`),供「今日日记」入口用。
|
||||
pub fn daily_note_name() -> String {
|
||||
chrono::Local::now().format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// 默认模板的 ID(新建笔记时未选模板就用它)。
|
||||
pub fn default_template_id() -> String {
|
||||
"builtin:空白笔记".to_string()
|
||||
}
|
||||
|
||||
/// 正文里第一行有意义的文本(用户模板的说明用)。
|
||||
fn first_meaningful_line(body: &str) -> String {
|
||||
for line in body.lines() {
|
||||
let text = line.trim();
|
||||
if text.is_empty() || text == "---" || text.starts_with('#') || text.starts_with("title:") {
|
||||
continue;
|
||||
}
|
||||
return text.chars().take(40).collect();
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 为「新建笔记」渲染正文:`template_id` 为空或找不到时用默认模板。
|
||||
pub fn render_for_new_note(root: &Path, template_id: &str, title: &str, dir_rel: &str) -> String {
|
||||
let id = if template_id.trim().is_empty() {
|
||||
default_template_id()
|
||||
} else {
|
||||
template_id.to_string()
|
||||
};
|
||||
match body_of(root, &id) {
|
||||
Some(body) => render(&body, title, dir_rel),
|
||||
None => {
|
||||
// 兜底:内置空白模板(即使模板目录被清空也能新建)
|
||||
let fallback = BUILTIN
|
||||
.first()
|
||||
.map(|(_, _, body)| *body)
|
||||
.unwrap_or("---\ntitle: {{title}}\n---\n\n# {{title}}\n\n");
|
||||
render(fallback, title, dir_rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库里的 `templates/` 目录存在(用户想自定义模板时不用自己新建目录)。
|
||||
pub fn ensure_dir(root: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(root.join("templates")).map_err(|e| format!("创建模板目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把内置模板写进库内 `templates/`(供「导出内置模板」按钮用;已存在的不覆盖)。
|
||||
pub fn export_builtin(root: &Path) -> Result<Vec<String>, String> {
|
||||
ensure_dir(root)?;
|
||||
let dir = root.join("templates");
|
||||
let mut written = Vec::new();
|
||||
for (name, _, body) in BUILTIN {
|
||||
let path = dir.join(format!("{name}.md"));
|
||||
if path.exists() {
|
||||
continue;
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板 {name} 失败: {e}"))?;
|
||||
written.push(name.to_string());
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 模板文件在库内的相对路径(前端「编辑模板」用;内置模板返回 `None`)。
|
||||
pub fn relative_path(id: &str) -> Option<String> {
|
||||
id.strip_prefix("user:")
|
||||
.map(|name| format!("templates/{name}.md"))
|
||||
}
|
||||
|
||||
/// 校验模板名(新建模板时用)。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
library::validate_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> std::path::PathBuf {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("thing-notes-tpl-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_templates_are_available_without_files() {
|
||||
let root = temp_root("builtin");
|
||||
let templates = list(&root);
|
||||
assert!(templates.len() >= 4, "{templates:?}");
|
||||
assert!(templates.iter().all(|t| t.builtin));
|
||||
assert!(templates.iter().any(|t| t.name == "日记"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_template_overrides_builtin_with_same_name() {
|
||||
let root = temp_root("override");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/空白笔记.md"), "用户自己的模板 {{title}}").unwrap();
|
||||
let templates = list(&root);
|
||||
let blank = templates.iter().find(|t| t.name == "空白笔记").unwrap();
|
||||
assert!(!blank.builtin, "同名时用户模板应覆盖内置");
|
||||
assert!(blank.body.contains("用户自己的模板"));
|
||||
assert_eq!(
|
||||
templates.iter().filter(|t| t.name == "空白笔记").count(),
|
||||
1,
|
||||
"不该出现两份同名模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_substitutes_variables() {
|
||||
let out = render("---\ntitle: {{title}}\ncreated: {{datetime}}\n---\n\n# {{title}} {{date}}\n", "周会", "");
|
||||
assert!(out.contains("title: 周会"));
|
||||
assert!(out.contains("# 周会 "));
|
||||
assert!(!out.contains("{{"), "所有占位符都应被替换: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_for_new_note_falls_back_to_blank() {
|
||||
let root = temp_root("fallback");
|
||||
let out = render_for_new_note(&root, "user:不存在", "标题", "");
|
||||
assert!(out.contains("标题"));
|
||||
assert!(!out.contains("{{"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_builtin_does_not_overwrite() {
|
||||
let root = temp_root("export");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/日记.md"), "我的日记模板").unwrap();
|
||||
let written = export_builtin(&root).unwrap();
|
||||
assert!(!written.contains(&"日记".to_string()), "{written:?}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("templates/日记.md")).unwrap(),
|
||||
"我的日记模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_only_for_user_templates() {
|
||||
assert_eq!(
|
||||
relative_path("user:会议纪要"),
|
||||
Some("templates/会议纪要.md".to_string())
|
||||
);
|
||||
assert_eq!(relative_path("builtin:日记"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_note_name_is_date_shaped() {
|
||||
let name = daily_note_name();
|
||||
assert_eq!(name.len(), 10, "{name}");
|
||||
assert_eq!(name.matches('-').count(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! 笔记模块的数据模型。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/notes/settings.json`(与 ai / translate / terminal 同一范式)。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
|
||||
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
|
||||
//!
|
||||
//! 笔记正文**不在这里**:它以 `.md` 文件为准(见 `library.rs`),
|
||||
//! 本结构只保存「库根 + 编辑器偏好」这类模块级设置。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 结构版本号。字段增减时递增,由 [`NoteSettings::heal`] 推进。
|
||||
pub const NOTES_SETTINGS_VERSION: u32 = 2;
|
||||
|
||||
/// 同步方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyncDirection {
|
||||
/// 双向同步(默认)
|
||||
Bidirectional,
|
||||
/// 只上传(本地覆盖远端)—— 等价于「推送到远端备份」
|
||||
Upload,
|
||||
/// 只下载(远端覆盖本地)—— 换机器恢复时用
|
||||
Download,
|
||||
}
|
||||
|
||||
impl Default for SyncDirection {
|
||||
fn default() -> Self {
|
||||
Self::Bidirectional
|
||||
}
|
||||
}
|
||||
|
||||
/// 两侧都改动时的冲突策略。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConflictPolicy {
|
||||
/// 保留较新的(mtime 大的一方;无法判定时保守选本地)
|
||||
Newer,
|
||||
/// 本地覆盖远端
|
||||
LocalWins,
|
||||
/// 远端覆盖本地
|
||||
RemoteWins,
|
||||
/// 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径)
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
impl Default for ConflictPolicy {
|
||||
fn default() -> Self {
|
||||
// 默认「都留」:冲突时最保守的选择,绝不丢数据(规划 §7 R6)
|
||||
Self::KeepBoth
|
||||
}
|
||||
}
|
||||
|
||||
/// WebDAV 设置(密码**不在这里** —— 它进 keyring,见 `webdav/mod.rs`)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct WebdavSettings {
|
||||
/// 服务地址(`https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
/// 远端根目录(相对 `url`;空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
pub direction: SyncDirection,
|
||||
pub conflict: ConflictPolicy,
|
||||
/// 应用启动后自动同步一次
|
||||
pub auto_sync_on_launch: bool,
|
||||
/// 保留的 zip 快照份数(上传备份时轮转)
|
||||
pub backup_keep: u32,
|
||||
}
|
||||
|
||||
impl Default for WebdavSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
url: String::new(),
|
||||
username: String::new(),
|
||||
remote_root: "thing-notes".to_string(),
|
||||
direction: SyncDirection::Bidirectional,
|
||||
conflict: ConflictPolicy::KeepBoth,
|
||||
auto_sync_on_launch: false,
|
||||
backup_keep: 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WebdavSettings {
|
||||
/// 是否已经填了连接信息(决定设置页显示「未配置」还是「已配置」)。
|
||||
pub fn is_configured(&self) -> bool {
|
||||
!self.url.trim().is_empty() && !self.username.trim().is_empty()
|
||||
}
|
||||
|
||||
/// 填写是否足以发起请求。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步进度(事件 `notes-sync-progress` 的负载)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncProgress {
|
||||
/// 已完成条数
|
||||
pub done: u32,
|
||||
/// 总条数
|
||||
pub total: u32,
|
||||
/// 当前处理的相对路径
|
||||
pub current: String,
|
||||
/// 动作类型(`upload` / `download` / …,见 `webdav::sync::SyncActionKind::as_str`)
|
||||
pub kind: String,
|
||||
/// 附加说明(如「正在打包快照」)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 一份远端备份快照。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupSnapshot {
|
||||
/// 远端文件名(`thing-notes-20260930-1530.zip`)
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 备份结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupReport {
|
||||
/// 上传的快照名
|
||||
pub name: String,
|
||||
/// 快照字节数
|
||||
pub bytes: u64,
|
||||
/// 打包的笔记数
|
||||
pub files: u32,
|
||||
/// 因超出保留份数而被删除的旧快照
|
||||
pub pruned: Vec<String>,
|
||||
}
|
||||
|
||||
/// 导入结果。
|
||||
#[derive(Debug, Clone, Default, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportReport {
|
||||
/// 导入的笔记数
|
||||
pub imported: u32,
|
||||
/// 因重名而被改名的数量
|
||||
pub renamed: u32,
|
||||
/// 跳过的非 Markdown 文件数
|
||||
pub skipped: u32,
|
||||
/// 失败明细(最多若干条)
|
||||
pub failures: Vec<String>,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器设置根结构。
|
||||
///
|
||||
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
|
||||
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NoteSettings {
|
||||
/// 结构版本号
|
||||
pub version: u32,
|
||||
/// 自定义库根(`None` = 用默认 `{app_data_dir}/notes/library`)
|
||||
pub library_root: Option<String>,
|
||||
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
|
||||
pub editor_theme: String,
|
||||
/// 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准)
|
||||
pub follow_app_theme: bool,
|
||||
/// 编辑器字体族(空串 = 用内置等宽字体栈)
|
||||
pub font_family: String,
|
||||
/// 字号(px)
|
||||
pub font_size: u32,
|
||||
/// 行高倍数
|
||||
pub line_height: f64,
|
||||
/// 是否启用字体连字(ligatures)
|
||||
pub ligatures: bool,
|
||||
/// Tab 宽度(空格数)
|
||||
pub tab_size: u32,
|
||||
/// 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮)
|
||||
pub live_preview: bool,
|
||||
/// 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S)
|
||||
pub autosave_ms: u32,
|
||||
/// 默认视图:"wysiwyg" | "source"
|
||||
pub default_view: String,
|
||||
/// 是否显示行号
|
||||
pub show_line_numbers: bool,
|
||||
/// 是否显示大纲侧栏(P1)
|
||||
pub show_outline: bool,
|
||||
/// 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭)
|
||||
pub autocomplete: bool,
|
||||
/// 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
|
||||
/// 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
|
||||
pub max_file_size_mb: u32,
|
||||
/// 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链)
|
||||
pub wikilink: bool,
|
||||
/// 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口)
|
||||
pub reuse_window: bool,
|
||||
/// WebDAV 备份 / 同步设置(P2)
|
||||
pub webdav: WebdavSettings,
|
||||
/// 新建笔记时是否弹出模板选择(P2)
|
||||
pub show_template_picker: bool,
|
||||
/// 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白)
|
||||
pub export_highlight: bool,
|
||||
/// 全局快捷键:新建笔记(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
|
||||
/// 触发时只发 `notes-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub new_note_shortcut: String,
|
||||
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
|
||||
pub open_editor_shortcut: String,
|
||||
}
|
||||
|
||||
impl Default for NoteSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: NOTES_SETTINGS_VERSION,
|
||||
library_root: None,
|
||||
editor_theme: "system".to_string(),
|
||||
follow_app_theme: true,
|
||||
font_family: String::new(),
|
||||
font_size: 14,
|
||||
line_height: 1.7,
|
||||
ligatures: false,
|
||||
tab_size: 2,
|
||||
live_preview: true,
|
||||
autosave_ms: 800,
|
||||
default_view: "wysiwyg".to_string(),
|
||||
show_line_numbers: true,
|
||||
show_outline: true,
|
||||
autocomplete: true,
|
||||
max_file_size_mb: 5,
|
||||
wikilink: true,
|
||||
reuse_window: true,
|
||||
webdav: WebdavSettings::default(),
|
||||
show_template_picker: true,
|
||||
export_highlight: true,
|
||||
new_note_shortcut: String::new(),
|
||||
open_editor_shortcut: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NoteSettings {
|
||||
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
|
||||
/// 返回是否发生了变更(由调用方决定是否落盘)。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
let clamp_u32 = |value: &mut u32, min: u32, max: u32, changed: &mut bool| {
|
||||
let next = (*value).clamp(min, max);
|
||||
if next != *value {
|
||||
*value = next;
|
||||
*changed = true;
|
||||
}
|
||||
};
|
||||
clamp_u32(&mut self.font_size, 10, 32, &mut changed);
|
||||
clamp_u32(&mut self.tab_size, 1, 8, &mut changed);
|
||||
clamp_u32(&mut self.autosave_ms, 0, 10_000, &mut changed);
|
||||
// 上限 100MB:再大就不该用编辑器打开(也不该走 IPC 把全文搬进 WebView)
|
||||
clamp_u32(&mut self.max_file_size_mb, 1, 100, &mut changed);
|
||||
// 快照保留份数:至少 1 份(0 份等于「备份完就删」,显然是误配)
|
||||
clamp_u32(&mut self.webdav.backup_keep, 1, 100, &mut changed);
|
||||
|
||||
if !(1.0..=3.0).contains(&self.line_height) {
|
||||
self.line_height = 1.7;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.editor_theme.trim().is_empty() {
|
||||
self.editor_theme = "system".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.default_view != "wysiwyg" && self.default_view != "source" {
|
||||
self.default_view = "wysiwyg".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if let Some(root) = &self.library_root {
|
||||
if root.trim().is_empty() {
|
||||
self.library_root = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if self.version < NOTES_SETTINGS_VERSION {
|
||||
self.version = NOTES_SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
/// 库内一个条目(文件或目录)的扁平描述。
|
||||
///
|
||||
/// **刻意用扁平列表而不是树**:递归类型在 specta 的 `Type` 派生下容易生成
|
||||
/// 无穷展开的 TS 类型;扁平结构由前端组装成树,更稳也更简单。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryEntry {
|
||||
/// 显示名(不含目录前缀)
|
||||
pub name: String,
|
||||
/// 相对库根的路径,统一用 `/` 分隔(如 `2026/09/meeting.md`)
|
||||
pub rel_path: String,
|
||||
/// 父目录的相对路径(库根为 `""`)
|
||||
pub parent_rel: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 文件字节数(目录为 0)
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// 库状态概览(主模块页横幅与设置页用)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryInfo {
|
||||
/// 当前生效的库根绝对路径
|
||||
pub root: String,
|
||||
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`)
|
||||
pub is_custom: bool,
|
||||
/// `.md` 笔记数量(不含目录)
|
||||
pub note_count: u32,
|
||||
}
|
||||
|
||||
/// 单篇笔记的读取/写入结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteDoc {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 显示名(含扩展名)
|
||||
pub name: String,
|
||||
/// 完整文件内容(含 front-matter)
|
||||
pub content: String,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
//! WebDAV 客户端:`PROPFIND` / `MKCOL` / `GET` / `PUT` / `DELETE` / `MOVE`。
|
||||
//!
|
||||
//! # 定位:备份 / 同步目标,不是工作区
|
||||
//!
|
||||
//! 这条边界是产品级的(规划 §3.6 已确认):笔记的真相永远在本地文件系统,
|
||||
//! WebDAV 只接收「本地 → 远端」的推送与「远端 → 本地」的拉取,**不做远端直连读写**
|
||||
//! (不把远端当工作目录)。这样即使远端服务商限流、掉线、或者把文件改坏,本地
|
||||
//! 那份始终是完整可用的。
|
||||
//!
|
||||
//! # XML 解析为什么用 quick-xml
|
||||
//!
|
||||
//! `PROPFIND` 的响应是 `<D:multistatus>` 里套一堆 `<D:response>`,命名空间前缀
|
||||
//! 由服务端随意指定(`D:` / `d:` / `lp1:` / 甚至没有前缀)。因此**不能按前缀匹配**,
|
||||
//! 只能按 local name 匹配。这里用 quick-xml 的事件流手写一小段状态机:遇到
|
||||
//! `response` 开始收集,遇到 `href` / `getlastmodified` / `getcontentlength` /
|
||||
//! `resourcetype` 各自记录,`response` 结束时产出一条 [`RemoteEntry`]。
|
||||
//! 手写而不是上 `serde` 反序列化,是因为各家 NAS(群晖、威联通、Alist)的字段
|
||||
//! 集合与顺序都不一致,宽容的事件流比严格的结构体映射稳。
|
||||
//!
|
||||
//! # 请求节流与退避
|
||||
//!
|
||||
//! 坚果云一类服务对请求频率有硬限制(超限直接 503)。这里的策略是:
|
||||
//! `REQ_INTERVAL_MS` 之内的**连续请求之间强制 sleep**,并且对 429/503 做指数退避
|
||||
//! 重试。同步一个几百篇的库会发几百个请求,不节流几乎必然被限流。
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use base64::Engine as _;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::Reader;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 连续请求之间的最小间隔(坚果云等服务的限流底线)。
|
||||
const REQ_INTERVAL_MS: u64 = 60;
|
||||
|
||||
/// 单次请求超时(连接 15s / 整体 180s)。
|
||||
///
|
||||
/// 整体超时给得比一般的 HTTP 调用长:`PROPFIND` 一个几千文件的目录、
|
||||
/// 或者上传一个几十 MB 的 zip 备份都可能耗时,短超时会表现为「同步随机失败」。
|
||||
const TIMEOUT: Duration = Duration::from_secs(180);
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// 退避重试:遇到 429/503 时的等待序列(毫秒)。
|
||||
const BACKOFF_MS: [u64; 4] = [500, 1500, 4000, 9000];
|
||||
|
||||
/// 远端一个文件/目录的条目。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteEntry {
|
||||
/// 相对远端根的路径(统一 `/` 分隔,无前导斜杠)
|
||||
pub rel_path: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 字节数(目录为 0)
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒;服务端未提供时为 0)
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 连接与认证配置(密码从 keyring 单独取,不进这里)。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WebdavConfig {
|
||||
/// 服务地址(如 `https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
/// 远端根目录(相对 `url`,空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
impl WebdavConfig {
|
||||
/// 是否具备发起请求的最小条件。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拼接「远端根 + 相对路径」为完整 URL 路径(已做百分号编码)。
|
||||
fn url_for(&self, rel: &str) -> String {
|
||||
let base = self.url.trim_end_matches('/');
|
||||
let root = self.remote_root.trim().trim_matches('/');
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if !root.is_empty() {
|
||||
for segment in root.split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
for segment in rel.replace('\\', "/").split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
// 指向目录时必须带尾斜杠:部分服务端(IIS、nginx 的 dav 模块)在缺尾斜杠时
|
||||
// 会回 301,而 `PROPFIND` 遇到 301 有些实现不会自动跟(跟了也可能丢 Depth 头)
|
||||
format!("{base}/")
|
||||
} else {
|
||||
format!("{base}/{}", parts.join("/"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 父目录的相对路径(用于 `MKCOL` 逐级创建)。
|
||||
fn parent_of(rel: &str) -> String {
|
||||
match rel.rfind('/') {
|
||||
Some(index) => rel[..index].to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把一个路径段做百分号编码(只放过 unreserved 字符)。
|
||||
///
|
||||
/// 手写而不用 `urlencoding`:本文件已经为 `quick-xml` 加了一个依赖,
|
||||
/// 再为「编码一个路径段」加第二个不划算;规则本身只有十几行。
|
||||
fn encode_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.as_bytes() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(*byte as char)
|
||||
}
|
||||
other => out.push_str(&format!("%{other:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 百分号解码(服务端回传的 `href` 是编码过的)。
|
||||
fn decode_segment(segment: &str) -> String {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'%' && index + 2 < bytes.len() {
|
||||
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).unwrap_or("");
|
||||
if let Ok(value) = u8::from_str_radix(hex, 16) {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// WebDAV 客户端(`blocking` 是刻意的:见 `lib.rs` 的依赖注释)。
|
||||
pub struct WebdavClient {
|
||||
http: reqwest::blocking::Client,
|
||||
config: WebdavConfig,
|
||||
/// 上次请求时间(节流用)
|
||||
last_request: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
impl WebdavClient {
|
||||
pub fn new(config: WebdavConfig) -> Result<Self, String> {
|
||||
config.validate()?;
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.timeout(TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// 跟随重定向:不少服务端在「目录缺尾斜杠」时回 301
|
||||
.redirect(reqwest::redirect::Policy::limited(5))
|
||||
.user_agent("Thing-Notes/1.0")
|
||||
.build()
|
||||
.map_err(|e| format!("创建 HTTP 客户端失败: {e}"))?;
|
||||
Ok(Self {
|
||||
http,
|
||||
config,
|
||||
last_request: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// 节流:保证两次请求之间至少间隔 [`REQ_INTERVAL_MS`]。
|
||||
fn throttle(&self) { let mut slot = match self.last_request.lock() {
|
||||
Ok(slot) => slot,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
if let Some(previous) = *slot {
|
||||
let elapsed = previous.elapsed();
|
||||
let min = Duration::from_millis(REQ_INTERVAL_MS);
|
||||
if elapsed < min {
|
||||
std::thread::sleep(min - elapsed);
|
||||
}
|
||||
}
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
|
||||
/// 目录型 URL(`remote_root` 与每一层子目录都用它)。
|
||||
///
|
||||
/// `WebdavConfig::url_for("")` 只有在 `remote_root` 为空时才带尾斜杠;
|
||||
/// `remote_root` 非空时拼出来的是纯路径(如 `.../thing%20notes`),
|
||||
/// 而**目录请求必须带尾斜杠**(见 `url_for` 的注释)。
|
||||
fn dir_url(&self, rel: &str) -> String {
|
||||
let url = self.config.url_for(rel);
|
||||
if url.ends_with('/') {
|
||||
url
|
||||
} else {
|
||||
format!("{url}/")
|
||||
}
|
||||
}
|
||||
|
||||
/// 带 Basic 认证与节流的请求构造。
|
||||
fn request(&self, method: reqwest::Method, url: &str) -> reqwest::blocking::RequestBuilder {
|
||||
self.throttle();
|
||||
let mut builder = self.http.request(method, url);
|
||||
if !self.config.username.is_empty() || !self.config.password.is_empty() {
|
||||
let token = base64::engine::general_purpose::STANDARD
|
||||
.encode(format!("{}:{}", self.config.username, self.config.password));
|
||||
builder = builder.header("Authorization", format!("Basic {token}"));
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
/// 发请求并做退避重试(对 429/503 与网络错误重试)。
|
||||
fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
url: &str,
|
||||
body: Option<Vec<u8>>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> Result<reqwest::blocking::Response, String> {
|
||||
let mut attempt = 0usize;
|
||||
loop {
|
||||
let mut builder = self.request(method.clone(), url);
|
||||
for (name, value) in headers {
|
||||
builder = builder.header(*name, *value);
|
||||
}
|
||||
if let Some(content_type) = content_type {
|
||||
builder = builder.header("Content-Type", content_type);
|
||||
}
|
||||
if let Some(body) = &body {
|
||||
builder = builder.body(body.clone());
|
||||
}
|
||||
|
||||
let result = builder.send();
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let status = response.status().as_u16();
|
||||
// 429(限流)与 503(服务不可用)是可重试的;其余 4xx 是请求本身的问题
|
||||
if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"notes",
|
||||
&format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Ok(response);
|
||||
}
|
||||
Err(e) => {
|
||||
if attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"notes",
|
||||
&format!("WebDAV 请求失败({e}),{wait}ms 后重试"),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Err(format!("WebDAV 请求失败: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把响应状态翻译成「人能看懂的错误」。
|
||||
fn ensure_success(response: &reqwest::blocking::Response, what: &str) -> Result<(), String> {
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
let code = status.as_u16();
|
||||
let hint = match code {
|
||||
401 => "(用户名或密码/应用密码不正确)",
|
||||
403 => "(账号无此目录权限)",
|
||||
404 => "(路径不存在)",
|
||||
405 => "(服务端不允许该操作,可能不是标准 WebDAV)",
|
||||
409 => "(父目录不存在)",
|
||||
507 => "(远端空间不足)",
|
||||
_ => "",
|
||||
};
|
||||
Err(format!("{what}失败:HTTP {code}{hint}"))
|
||||
}
|
||||
|
||||
/// 探测远端根目录是否存在(返回条目列表;不存在返回 `None`)。
|
||||
pub fn list(&self, rel: &str) -> Result<Option<Vec<RemoteEntry>>, String> {
|
||||
let url = self.dir_url(rel);
|
||||
let body = br#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<D:propfind xmlns:D="DAV:"><D:prop>
|
||||
<D:resourcetype/><D:getcontentlength/><D:getlastmodified/>
|
||||
</D:prop></D:propfind>"#
|
||||
.to_vec();
|
||||
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"PROPFIND").unwrap_or(reqwest::Method::GET),
|
||||
&url,
|
||||
Some(body),
|
||||
Some("application/xml; charset=utf-8"),
|
||||
&[("Depth", "1")],
|
||||
)?;
|
||||
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(None);
|
||||
}
|
||||
Self::ensure_success(&response, "列目录")?;
|
||||
|
||||
let text = response
|
||||
.text()
|
||||
.map_err(|e| format!("读取 PROPFIND 响应失败: {e}"))?;
|
||||
let entries = parse_multistatus(&text, &self.config.url, &self.config.remote_root, rel)?;
|
||||
Ok(Some(entries))
|
||||
}
|
||||
|
||||
/// 确认远端根可用(不存在则创建)。
|
||||
///
|
||||
/// 自检的意义在于:把「地址写错 / 密码错 / 目录不存在」这三类问题在用户点下
|
||||
/// 「立即同步」**之前**就暴露出来,而不是让同步跑到一半报错。
|
||||
pub fn ensure_root(&self) -> Result<Vec<String>, String> {
|
||||
self.config.validate()?;
|
||||
let mut created: Vec<String> = Vec::new();
|
||||
|
||||
// 逐级创建 remote_root(服务端不会自动补父目录)
|
||||
let root = self.config.remote_root.trim().trim_matches('/').to_string();
|
||||
if !root.is_empty() {
|
||||
for next in Self::segments(&root) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
// 201 = 建成;405 = 已存在(各家服务端口径不一,两者都算成功)
|
||||
if code == 201 {
|
||||
created.push(next);
|
||||
} else if code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 最后列一次,确认真的可读
|
||||
match self.list("")? {
|
||||
Some(_) => Ok(created),
|
||||
None => Err("远端根目录不存在且无法创建".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归列出远端某目录下的全部文件(跳过 [`should_skip`] 命中的路径)。
|
||||
pub fn list_recursive(&self) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut out: Vec<RemoteEntry> = Vec::new();
|
||||
let mut queue: Vec<String> = vec![String::new()];
|
||||
// 深度上限:远端目录结构异常(成环的软链)时不至于无限翻页
|
||||
let mut depth = 0usize;
|
||||
|
||||
while let Some(dir) = queue.pop() {
|
||||
depth += 1;
|
||||
if depth > 4096 {
|
||||
crate::logger::log_warn("notes", "远端目录过多,提前结束遍历");
|
||||
break;
|
||||
}
|
||||
let Some(entries) = self.list(&dir)? else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries {
|
||||
if entry.rel_path.is_empty() || entry.rel_path == dir {
|
||||
continue;
|
||||
}
|
||||
if should_skip(&entry.rel_path) {
|
||||
continue;
|
||||
}
|
||||
if entry.is_dir {
|
||||
queue.push(entry.rel_path.clone());
|
||||
} else {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 创建目录(含父级)。
|
||||
pub fn mkdir_all(&self, rel: &str) -> Result<(), String> {
|
||||
for next in Self::segments(rel) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
if code != 201 && code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 `a/b/c` 展开成 `["a", "a/b", "a/b/c"]`(逐级创建用)。
|
||||
fn segments(rel: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut prefix = String::new();
|
||||
for segment in rel.trim_matches('/').split('/') {
|
||||
if segment.is_empty() {
|
||||
continue;
|
||||
}
|
||||
prefix = if prefix.is_empty() {
|
||||
segment.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{segment}")
|
||||
};
|
||||
out.push(prefix.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 读取远端文件内容。
|
||||
pub fn get(&self, rel: &str) -> Result<Vec<u8>, String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::GET, &url, None, None, &[])?;
|
||||
Self::ensure_success(&response, &format!("下载 {rel}"))?;
|
||||
let mut out = Vec::new();
|
||||
response
|
||||
.take(512 * 1024 * 1024)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("读取下载内容失败: {e}"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 上传文件内容(必要时先建父目录)。
|
||||
pub fn put(&self, rel: &str, bytes: Vec<u8>) -> Result<(), String> {
|
||||
let parent = WebdavConfig::parent_of(rel);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(
|
||||
reqwest::Method::PUT,
|
||||
&url,
|
||||
Some(bytes),
|
||||
Some("application/octet-stream"),
|
||||
&[],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("上传 {rel}"))
|
||||
}
|
||||
|
||||
/// 删除文件(404 视为成功 —— 目标已经不存在,结果一致)。
|
||||
pub fn delete(&self, rel: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::DELETE, &url, None, None, &[])?;
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(());
|
||||
}
|
||||
Self::ensure_success(&response, &format!("删除远端 {rel}"))
|
||||
}
|
||||
|
||||
/// 移动 / 重命名(`MOVE`,覆盖写)。
|
||||
pub fn move_to(&self, from: &str, to: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(from);
|
||||
let parent = WebdavConfig::parent_of(to);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let destination = self.config.url_for(to);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MOVE").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[("Destination", destination.as_str()), ("Overwrite", "T")],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("移动 {from} → {to}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析 `multistatus` 响应。
|
||||
///
|
||||
/// 按 **local name** 匹配(忽略命名空间前缀),并把 `href` 归一化成「相对远端根的
|
||||
/// 路径」。`base_url` 与 `remote_root` 用于剥掉服务端回传的完整 URL 前缀。
|
||||
fn parse_multistatus(
|
||||
xml: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
reader.config_mut().trim_text(true);
|
||||
|
||||
let mut entries: Vec<RemoteEntry> = Vec::new();
|
||||
let mut in_response = false;
|
||||
let mut current_href = String::new();
|
||||
let mut current_is_dir = false;
|
||||
let mut current_size = 0u64;
|
||||
let mut current_modified = 0u64;
|
||||
// 当前正在读的字段(`href` 可能在 propstat 里出现多次,只取第一个)
|
||||
let mut field = String::new();
|
||||
|
||||
loop {
|
||||
match reader.read_event() {
|
||||
Ok(Event::Start(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
match local.as_str() {
|
||||
"response" => {
|
||||
in_response = true;
|
||||
current_href.clear();
|
||||
current_is_dir = false;
|
||||
current_size = 0;
|
||||
current_modified = 0;
|
||||
}
|
||||
"href" | "getcontentlength" | "getlastmodified" | "collection" => {
|
||||
field = local;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::Empty(element)) => {
|
||||
// `<D:collection/>` 是「这是目录」的标志
|
||||
let name = element.name();
|
||||
if local_name(name.as_ref()) == "collection" {
|
||||
current_is_dir = true;
|
||||
}
|
||||
}
|
||||
Ok(Event::Text(text)) => {
|
||||
// quick-xml 0.42 的 `BytesText` 直接 `Deref<Target = str>`(Reader 是
|
||||
// `from_str` 建的,输入本身就是 UTF-8,不需要再 decode/unescape)。
|
||||
// 这里拷成 owned String 是因为 `field` 的匹配在借用结束之后才用。
|
||||
let value: String = text.as_ref().to_string();
|
||||
match field.as_str() {
|
||||
"href" if current_href.is_empty() => current_href = value,
|
||||
"getcontentlength" => current_size = value.trim().parse().unwrap_or(0),
|
||||
"getlastmodified" => current_modified = parse_http_date(&value).unwrap_or(0),
|
||||
"collection" => current_is_dir = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::End(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
if local == "response" && in_response {
|
||||
in_response = false;
|
||||
let rel = normalize_href(¤t_href, base_url, remote_root, listing_dir);
|
||||
if let Some(rel) = rel {
|
||||
entries.push(RemoteEntry {
|
||||
rel_path: rel,
|
||||
is_dir: current_is_dir,
|
||||
size: if current_is_dir { 0 } else { current_size },
|
||||
modified: current_modified,
|
||||
});
|
||||
}
|
||||
}
|
||||
field.clear();
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(format!("解析 WebDAV 响应失败: {e}")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// 取 XML 元素的 local name(去掉 `D:` / `lp1:` 之类前缀)。
|
||||
///
|
||||
/// quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`(更早的版本是 `&[u8]`)——
|
||||
/// 这也是本文件里唯一需要跟着版本走的细节。
|
||||
fn local_name(raw: &str) -> String {
|
||||
match raw.rsplit(':').next() {
|
||||
Some(name) => name.to_ascii_lowercase(),
|
||||
None => raw.to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把服务端回传的 `href` 归一化成相对远端根的路径。
|
||||
///
|
||||
/// 服务端的三种形态都要吃下:
|
||||
/// 1. 完整 URL(`https://host/dav/root/a.md`)—— 剥掉 `base_url` 与 `remote_root`;
|
||||
/// 2. 绝对路径(`/dav/root/a.md`)—— 同上;
|
||||
/// 3. 相对路径(`a.md`)—— 拼到当前列出的目录之后再归一化。
|
||||
fn normalize_href(
|
||||
href: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Option<String> {
|
||||
if href.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 去掉协议与主机
|
||||
let path = if let Some(rest) = href.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "/",
|
||||
}
|
||||
} else {
|
||||
href
|
||||
};
|
||||
let decoded = decode_segment(path);
|
||||
let trimmed_base = base_url.trim_end_matches('/');
|
||||
// 剥掉 base 的路径部分(如 `/dav`)
|
||||
let base_path = if let Some(rest) = trimmed_base.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "",
|
||||
}
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut rel = decoded.as_str();
|
||||
if !base_path.is_empty() {
|
||||
if let Some(rest) = rel.strip_prefix(base_path) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let root = remote_root.trim().trim_matches('/');
|
||||
if !root.is_empty() {
|
||||
let with_slash = format!("/{root}");
|
||||
if let Some(rest) = rel.strip_prefix(with_slash.as_str()) {
|
||||
rel = rest;
|
||||
} else if let Some(rest) = rel.strip_prefix(root) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let clean = rel.trim_matches('/').to_string();
|
||||
if clean.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 相对 href:拼到 listing_dir 后面
|
||||
let full = if !path.starts_with('/') && !listing_dir.trim().is_empty() {
|
||||
format!("{}/{}", listing_dir.trim_matches('/'), clean)
|
||||
} else {
|
||||
clean
|
||||
};
|
||||
Some(full)
|
||||
}
|
||||
|
||||
/// 解析 HTTP 日期(RFC 1123,如 `Wed, 21 Oct 2015 07:28:00 GMT`)为 Unix 毫秒。
|
||||
///
|
||||
/// 用 `chrono::DateTime::parse_from_rfc2822`:RFC 2822 与 RFC 1123 的日期部分兼容,
|
||||
/// 而 chrono 正好提供这个解析器(不引入第二个时间库)。
|
||||
fn parse_http_date(value: &str) -> Option<u64> {
|
||||
let parsed = chrono::DateTime::parse_from_rfc2822(value.trim()).ok()?;
|
||||
Some(parsed.timestamp_millis().max(0) as u64)
|
||||
}
|
||||
|
||||
/// 该远端路径是否应当排除在同步之外。
|
||||
///
|
||||
/// `.notes/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
|
||||
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
|
||||
pub fn should_skip(rel: &str) -> bool {
|
||||
let normalized = rel.replace('\\', "/");
|
||||
normalized.split('/').any(|part| {
|
||||
part.starts_with('.') || part.eq_ignore_ascii_case("node_modules")
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn url_join_and_encoding() {
|
||||
let config = WebdavConfig {
|
||||
url: "https://dav.example.com/dav/".to_string(),
|
||||
remote_root: "thing notes".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
config.url_for("a/b.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a/b.md"
|
||||
);
|
||||
// 文件路径不带尾斜杠
|
||||
assert_eq!(
|
||||
config.url_for("a.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a.md"
|
||||
);
|
||||
// 目录请求必须带尾斜杠(否则部分服务端 301,PROPFIND 会丢 Depth 头)
|
||||
let client = WebdavClient::new(config).unwrap();
|
||||
assert_eq!(
|
||||
client.dir_url(""),
|
||||
"https://dav.example.com/dav/thing%20notes/"
|
||||
);
|
||||
assert_eq!(
|
||||
client.dir_url("sub"),
|
||||
"https://dav.example.com/dav/thing%20notes/sub/"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_bad_url() {
|
||||
let mut config = WebdavConfig::default();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "dav.example.com".to_string();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "https://dav.example.com".to_string();
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multistatus_parsing_tolerates_namespace_prefixes() {
|
||||
// 三家服务的常见形态:D: / d: / lp1: / 无前缀
|
||||
let xml = r#"<?xml version="1.0"?>
|
||||
<D:multistatus xmlns:D="DAV:">
|
||||
<D:response>
|
||||
<D:href>/dav/root/</D:href>
|
||||
<D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat>
|
||||
</D:response>
|
||||
<d:response xmlns:d="DAV:">
|
||||
<d:href>https://host/dav/root/notes/meeting.md</d:href>
|
||||
<d:propstat><d:prop>
|
||||
<d:resourcetype/>
|
||||
<d:getcontentlength>1234</d:getcontentlength>
|
||||
<d:getlastmodified>Wed, 21 Oct 2015 07:28:00 GMT</d:getlastmodified>
|
||||
</d:prop></d:propstat>
|
||||
</d:response>
|
||||
<response>
|
||||
<href>/dav/root/notes/%E4%B8%AD%E6%96%87.md</href>
|
||||
<propstat><prop><resourcetype/></prop></propstat>
|
||||
</response>
|
||||
</D:multistatus>"#;
|
||||
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
// 根目录自身被剥成空路径 → 不产出条目
|
||||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||||
|
||||
let meeting = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/meeting.md")
|
||||
.expect("应解析出 notes/meeting.md");
|
||||
assert!(!meeting.is_dir);
|
||||
assert_eq!(meeting.size, 1234);
|
||||
assert!(meeting.modified > 0, "应解析出 RFC1123 日期");
|
||||
|
||||
let chinese = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/中文.md")
|
||||
.expect("百分号编码的 href 应被解码");
|
||||
assert!(!chinese.is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_is_detected_as_directory() {
|
||||
let xml = r#"<multistatus xmlns="DAV:"><response>
|
||||
<href>/dav/root/sub</href>
|
||||
<propstat><prop><resourcetype><collection/></resourcetype></prop></propstat>
|
||||
</response></multistatus>"#;
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert!(entries[0].is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skip_rules_exclude_private_dir() {
|
||||
assert!(should_skip(".notes/notes.db"));
|
||||
assert!(should_skip("a/.hidden/b.md"));
|
||||
assert!(should_skip("node_modules/x.md"));
|
||||
assert!(!should_skip("notes/a.md"));
|
||||
assert!(!should_skip("a/b/c.md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percent_encoding_roundtrip() {
|
||||
let encoded = encode_segment("中文 名字.md");
|
||||
assert_eq!(decode_segment(&encoded), "中文 名字.md");
|
||||
// 特殊字符(`?` / `#` / `/`)必须编码,否则会被服务端当查询串或路径分隔
|
||||
assert!(!encode_segment("a?b#c/d").contains('?'));
|
||||
assert!(!encode_segment("a?b#c/d").contains('#'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_date_parsing() {
|
||||
let ms = parse_http_date("Wed, 21 Oct 2015 07:28:00 GMT").unwrap();
|
||||
assert_eq!(ms, 1_445_412_480_000);
|
||||
assert!(parse_http_date("不是日期").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! WebDAV 子模块:客户端与会话层。
|
||||
//!
|
||||
//! ```text
|
||||
//! client.rs ── 协议层:PROPFIND / MKCOL / GET / PUT / DELETE / MOVE(quick-xml 解析)
|
||||
//! mod.rs ── 会话层:读设置 → 取 keyring 密码 → 建客户端(供命令层一步调用)
|
||||
//! sync.rs ── 引擎层:清单比对 / 冲突策略 / 执行与基线维护
|
||||
//! ```
|
||||
//!
|
||||
//! 备份(zip 快照)在 `super::backup`:它只用 `PUT`,与同步是两条独立的路径
|
||||
//! (规划 §3.6 的取舍:对「只是要个备份」的用户,快照比双向同步可靠得多)。
|
||||
|
||||
pub mod client;
|
||||
pub mod sync;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::notes::types::WebdavSettings;
|
||||
use client::WebdavClient;
|
||||
|
||||
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
|
||||
pub const KEYRING_PASSWORD: &str = "notes.webdav.password";
|
||||
|
||||
/// 连接自检结果(设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavTestResult {
|
||||
/// 是否连通
|
||||
pub ok: bool,
|
||||
/// 远端根目录中已有的条目数(自检时顺带列出)
|
||||
pub entries: u32,
|
||||
/// 本次自检自动创建的目录
|
||||
pub created: Vec<String>,
|
||||
/// 人话结论(失败时是原因)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 由设置构造客户端(密码从 keyring 取,**不落盘**)。
|
||||
///
|
||||
/// 密码走系统凭据管理器而不是 `settings.json`:设置文件是明文 JSON,用户可能把库
|
||||
/// 连同设置一起放到同步目录里(那就等于把密码公开了)。keyring 的键是
|
||||
/// [`KEYRING_PASSWORD`],服务名沿用项目统一的 `"Thing"`。
|
||||
pub fn client_from(settings: &WebdavSettings) -> Result<WebdavClient, String> {
|
||||
settings.validate()?;
|
||||
let password = crate::secrets::secret_read(KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
WebdavClient::new(client::WebdavConfig {
|
||||
url: settings.url.trim().to_string(),
|
||||
username: settings.username.trim().to_string(),
|
||||
password,
|
||||
remote_root: settings.remote_root.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 连接自检:验证地址/凭据,并按需逐级创建远端根目录。
|
||||
pub fn test_connection(settings: &WebdavSettings) -> Result<WebdavTestResult, String> {
|
||||
let client = client_from(settings)?;
|
||||
let created = client.ensure_root()?;
|
||||
let entries = client.list_recursive()?.len() as u32;
|
||||
Ok(WebdavTestResult {
|
||||
ok: true,
|
||||
entries,
|
||||
created,
|
||||
message: format!("连接正常,远端已有 {entries} 个文件"),
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,6 +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::process_manager::{ProcessManager, start_monitoring_thread};
|
||||
use crate::terminal::TerminalManager;
|
||||
use crate::translate::TranslateManager;
|
||||
@@ -83,6 +84,21 @@ 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 =====
|
||||
// 仅注册状态:库扫描与读写都在命令调用时按需触发,启动阶段只创建目录结构。
|
||||
let notes = NotesManager::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);
|
||||
}
|
||||
|
||||
// ===== 翻译模块:TranslateManager =====
|
||||
// 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求
|
||||
// (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "thing",
|
||||
"version": "26.9.4",
|
||||
"version": "26.9.5",
|
||||
"identifier": "thing.lfeng.me",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -38,6 +38,14 @@
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": ["binaries/*", "resources/thing-extension/**/*"],
|
||||
"fileAssociations": [
|
||||
{
|
||||
"ext": ["md", "markdown", "mdx"],
|
||||
"name": "Markdown 笔记",
|
||||
"description": "用 Thing 打开 Markdown 笔记",
|
||||
"role": "Editor"
|
||||
}
|
||||
],
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"compression": "lzma"
|
||||
|
||||
@@ -920,6 +920,138 @@ export const commands = {
|
||||
dshLogClear: () => __TAURI_INVOKE<void>("dsh_log_clear"),
|
||||
/** 在资源管理器中打开 dsh 模块目录。 */
|
||||
dshOpenDir: () => __TAURI_INVOKE<null>("dsh_open_dir"),
|
||||
/** 读取笔记模块设置。 */
|
||||
notesGetSettings: () => __TAURI_INVOKE<NoteSettings>("notes_get_settings"),
|
||||
/** 保存笔记模块设置(自愈后落盘,并广播给各窗口)。 */
|
||||
notesSaveSettings: (settings: NoteSettings) => __TAURI_INVOKE<NoteSettings>("notes_save_settings", { settings }),
|
||||
/** 当前库状态概览(库根 / 是否自定义 / 笔记数)。 */
|
||||
notesLibraryInfo: () => __TAURI_INVOKE<LibraryInfo>("notes_library_info"),
|
||||
/** 设置库根(`None` 或空串 = 恢复默认库根)。 */
|
||||
notesSetLibraryRoot: (root: string | null) => __TAURI_INVOKE<LibraryInfo>("notes_set_library_root", { root }),
|
||||
/** 扫描库,返回扁平条目列表(前端组树)。 */
|
||||
notesScanLibrary: () => __TAURI_INVOKE<LibraryEntry[]>("notes_scan_library"),
|
||||
/** 读取一篇笔记。 */
|
||||
notesReadNote: (relPath: string) => __TAURI_INVOKE<NoteDoc>("notes_read_note", { relPath }),
|
||||
/** 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。 */
|
||||
notesSaveNote: (relPath: string, content: string) => __TAURI_INVOKE<NoteDoc>("notes_save_note", { relPath, content }),
|
||||
/**
|
||||
* 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
*
|
||||
* `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
* 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
*/
|
||||
notesCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE<NoteDoc>("notes_create_note", { dirRel, name, templateId }),
|
||||
/** 新建文件夹。 */
|
||||
notesCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE<null>("notes_create_folder", { dirRel, name }),
|
||||
/** 重命名条目,返回新相对路径。 */
|
||||
notesRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE<string>("notes_rename_entry", { relPath, newName }),
|
||||
/** 删除条目(目录递归删除)。 */
|
||||
notesDeleteEntry: (relPath: string) => __TAURI_INVOKE<null>("notes_delete_entry", { relPath }),
|
||||
/** 全量重建索引(设置页「重建索引」)。文件不受影响。 */
|
||||
notesRebuildIndex: () => __TAURI_INVOKE<NoteIndexReport>("notes_rebuild_index"),
|
||||
/** 增量同步索引(打开编辑器 / 手动刷新时调用)。 */
|
||||
notesSyncIndex: () => __TAURI_INVOKE<NoteIndexReport>("notes_sync_index"),
|
||||
/** 全文检索 / 按标签 / 按目录筛选。 */
|
||||
notesSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE<NoteSearchPage>("notes_search_notes", { query }),
|
||||
/** 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。 */
|
||||
notesListNotes: (limit: number | null) => __TAURI_INVOKE<NoteSearchHit[]>("notes_list_notes", { limit }),
|
||||
/** 标签及计数。 */
|
||||
notesTags: () => __TAURI_INVOKE<NoteTagCount[]>("notes_tags"),
|
||||
/** 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。 */
|
||||
notesIndexStats: () => __TAURI_INVOKE<NoteIndexStats>("notes_index_stats"),
|
||||
/**
|
||||
* 打开(读取)库外任意文件。
|
||||
*
|
||||
* 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
* 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
*/
|
||||
notesOpenFile: (path: string) => __TAURI_INVOKE<FileDoc>("notes_open_file", { path }),
|
||||
/** 保存库外任意文件(按前端回传的编码与换行写回)。 */
|
||||
notesWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE<FileDoc>("notes_write_file", { path, content, encoding, eol }),
|
||||
/**
|
||||
* 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
|
||||
*
|
||||
* 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板,
|
||||
* 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
|
||||
* 安全得多(写的位置由后端决定,且只落在 `assets/`)。
|
||||
*/
|
||||
notesWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE<string>("notes_write_asset", { fileName, ext, dataBase64 }),
|
||||
/**
|
||||
* 显式登记一个路径为「可写」。
|
||||
*
|
||||
* 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`,
|
||||
* 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
*/
|
||||
notesAuthorizeFile: (path: string) => __TAURI_INVOKE<null>("notes_authorize_file", { path }),
|
||||
/**
|
||||
* 列出可用模板(用户模板优先,同名覆盖内置)。
|
||||
*
|
||||
* 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
|
||||
* 就能直接写文件,不需要用户先去资源管理器建目录。
|
||||
*/
|
||||
notesListTemplates: () => __TAURI_INVOKE<NoteTemplate[]>("notes_list_templates"),
|
||||
/**
|
||||
* 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
|
||||
*
|
||||
* 三种用法:
|
||||
* - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
|
||||
* - 传 `name` + `body`:新建一个自定义模板。
|
||||
*/
|
||||
notesAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE<string[]>("notes_add_template", { name, body }),
|
||||
/**
|
||||
* 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
|
||||
*
|
||||
* 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
|
||||
* 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
|
||||
*/
|
||||
notesReadTemplate: (templateId: string) => __TAURI_INVOKE<TemplateSource>("notes_read_template", { templateId }),
|
||||
/** 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。 */
|
||||
notesDailyNote: () => __TAURI_INVOKE<NoteDoc>("notes_daily_note"),
|
||||
/** 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 */
|
||||
notesImport: (source: string, destDir: string) => __TAURI_INVOKE<ImportReport>("notes_import", { source, destDir }),
|
||||
/**
|
||||
* 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
|
||||
*
|
||||
* HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
|
||||
* 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
|
||||
*/
|
||||
notesExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE<string>("notes_export_note", { relPath, html, dest }),
|
||||
/** 把整库(或某个目录)打包成 zip,返回落盘路径。 */
|
||||
notesExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE<string>("notes_export_zip", { dest, dirRel }),
|
||||
/**
|
||||
* 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
*
|
||||
* 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
* 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
* 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
*/
|
||||
notesExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE<string>("notes_export_snapshot_local", { dest }),
|
||||
/** 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。 */
|
||||
notesWebdavStatus: () => __TAURI_INVOKE<WebdavStatus>("notes_webdav_status"),
|
||||
/** 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。 */
|
||||
notesSetWebdavPassword: (password: string) => __TAURI_INVOKE<null>("notes_set_webdav_password", { password }),
|
||||
/** 连接自检(建目录 + 列远端)。 */
|
||||
notesTestWebdav: () => __TAURI_INVOKE<WebdavTestResult>("notes_test_webdav"),
|
||||
/** 立即同步(并按设置决定是否追加一次快照备份)。 */
|
||||
notesSyncNow: () => __TAURI_INVOKE<SyncOutcome>("notes_sync_now"),
|
||||
/** 只做一次 zip 快照备份(不上传增量)。 */
|
||||
notesBackupNow: () => __TAURI_INVOKE<BackupReport>("notes_backup_now"),
|
||||
/** 列出远端已有快照。 */
|
||||
notesListBackups: () => __TAURI_INVOKE<BackupSnapshot[]>("notes_list_backups"),
|
||||
/** 从远端快照恢复(不覆盖本地已有文件)。 */
|
||||
notesRestoreBackup: (name: string) => __TAURI_INVOKE<ImportReport>("notes_restore_backup", { name }),
|
||||
/** 一篇笔记的链接关系(出链 + 入链)。 */
|
||||
notesBacklinks: (relPath: string) => __TAURI_INVOKE<NoteBacklinks>("notes_backlinks", { relPath }),
|
||||
/** 全库链接图(已解析的内部链接边)。 */
|
||||
notesLinkGraph: () => __TAURI_INVOKE<LinkEdge[]>("notes_link_graph"),
|
||||
/**
|
||||
* 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
*
|
||||
* 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
|
||||
* 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。
|
||||
*/
|
||||
notesTakePendingFile: () => __TAURI_INVOKE<string | null>("notes_take_pending_file"),
|
||||
notesReadAsset: (relPath: string) => __TAURI_INVOKE<string | null>("notes_read_asset", { relPath }),
|
||||
};
|
||||
|
||||
/* Types */
|
||||
@@ -1184,6 +1316,26 @@ export type AudioState = {
|
||||
failed: boolean,
|
||||
};
|
||||
|
||||
/** 备份结果。 */
|
||||
export type BackupReport = {
|
||||
/** 上传的快照名 */
|
||||
name: string,
|
||||
/** 快照字节数 */
|
||||
bytes: number,
|
||||
/** 打包的笔记数 */
|
||||
files: number,
|
||||
/** 因超出保留份数而被删除的旧快照 */
|
||||
pruned: string[],
|
||||
};
|
||||
|
||||
/** 一份远端备份快照。 */
|
||||
export type BackupSnapshot = {
|
||||
/** 远端文件名(`thing-notes-20260930-1530.zip`) */
|
||||
name: string,
|
||||
size: number,
|
||||
modified: number,
|
||||
};
|
||||
|
||||
/** BT 种子内文件条目(多文件任务用;阶段1下载全部文件,但保留列表供 UI 展示) */
|
||||
export type BtFileInfo = {
|
||||
/** 文件在种子内的索引 */
|
||||
@@ -1346,6 +1498,17 @@ export type CommandSuggestion = {
|
||||
description: string,
|
||||
};
|
||||
|
||||
/** 两侧都改动时的冲突策略。 */
|
||||
export type ConflictPolicy =
|
||||
/** 保留较新的(mtime 大的一方;无法判定时保守选本地) */
|
||||
"newer" |
|
||||
/** 本地覆盖远端 */
|
||||
"localWins" |
|
||||
/** 远端覆盖本地 */
|
||||
"remoteWins" |
|
||||
/** 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径) */
|
||||
"keepBoth";
|
||||
|
||||
/** 自定义命令 */
|
||||
export type CustomCommand = {
|
||||
id: string,
|
||||
@@ -1673,6 +1836,28 @@ export type FeiniuConnection = {
|
||||
relay?: boolean,
|
||||
};
|
||||
|
||||
/** 一个已打开文件的完整状态(前端据此显示编码/换行,并原样写回)。 */
|
||||
export type FileDoc = {
|
||||
/** 绝对路径(Windows 下已剥掉 `\\?\` 前缀) */
|
||||
path: string,
|
||||
/** 显示名(文件名) */
|
||||
name: string,
|
||||
/** 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原) */
|
||||
content: string,
|
||||
/** 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …) */
|
||||
encoding: string,
|
||||
/** 换行风格:"lf" | "crlf" */
|
||||
eol: string,
|
||||
/** 文件字节数 */
|
||||
size: number,
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number,
|
||||
/** 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全) */
|
||||
large: boolean,
|
||||
/** 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略) */
|
||||
lines: number,
|
||||
};
|
||||
|
||||
export type FileEntry = {
|
||||
name: string,
|
||||
path: string,
|
||||
@@ -1778,6 +1963,18 @@ export type HostView = {
|
||||
issue: string | null,
|
||||
};
|
||||
|
||||
/** 导入结果。 */
|
||||
export type ImportReport = {
|
||||
/** 导入的笔记数 */
|
||||
imported: number,
|
||||
/** 因重名而被改名的数量 */
|
||||
renamed: number,
|
||||
/** 跳过的非 Markdown 文件数 */
|
||||
skipped: number,
|
||||
/** 失败明细(最多若干条) */
|
||||
failures: string[],
|
||||
};
|
||||
|
||||
/** 索引状态(返回给前端) */
|
||||
export type IndexStats = {
|
||||
total: number,
|
||||
@@ -1896,6 +2093,46 @@ export type LayoutSettings = {
|
||||
maxPanes?: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* 库内一个条目(文件或目录)的扁平描述。
|
||||
*
|
||||
* **刻意用扁平列表而不是树**:递归类型在 specta 的 `Type` 派生下容易生成
|
||||
* 无穷展开的 TS 类型;扁平结构由前端组装成树,更稳也更简单。
|
||||
*/
|
||||
export type LibraryEntry = {
|
||||
/** 显示名(不含目录前缀) */
|
||||
name: string,
|
||||
/** 相对库根的路径,统一用 `/` 分隔(如 `2026/09/meeting.md`) */
|
||||
relPath: string,
|
||||
/** 父目录的相对路径(库根为 `""`) */
|
||||
parentRel: string,
|
||||
/** 是否目录 */
|
||||
isDir: boolean,
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number,
|
||||
/** 文件字节数(目录为 0) */
|
||||
size: number,
|
||||
};
|
||||
|
||||
/** 库状态概览(主模块页横幅与设置页用)。 */
|
||||
export type LibraryInfo = {
|
||||
/** 当前生效的库根绝对路径 */
|
||||
root: string,
|
||||
/** 是否为用户自定义库根(false = 默认 `{app_data_dir}/notes/library`) */
|
||||
isCustom: boolean,
|
||||
/** `.md` 笔记数量(不含目录) */
|
||||
noteCount: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* 链接图的一条边(用 `from`/`to` 而不是元组:元组序列化成数组后前端得按下标取值,
|
||||
* 改一次顺序就静默错位 —— 与 `terminal/history.rs` 的 `HistorySource` 同一理由)。
|
||||
*/
|
||||
export type LinkEdge = {
|
||||
from: string,
|
||||
to: string,
|
||||
};
|
||||
|
||||
/** 环境状态(返回前端,设置页「环境检查」面板展示) */
|
||||
export type MusicEnvStatus = {
|
||||
/** 系统 Python 版本(如 "3.14.5"),无则 None */
|
||||
@@ -1998,6 +2235,202 @@ export type NodeStatus = {
|
||||
required: string,
|
||||
};
|
||||
|
||||
/** 一篇笔记的链接关系(出链 + 入链)。 */
|
||||
export type NoteBacklinks = {
|
||||
/** 本篇指向别处的链接 */
|
||||
outgoing: NoteLink[],
|
||||
/** 别处指向本篇的链接 */
|
||||
incoming: NoteLink[],
|
||||
/** 入链去重后的来源笔记数(面板标题显示「被 N 篇引用」) */
|
||||
incomingSources: number,
|
||||
};
|
||||
|
||||
/** 单篇笔记的读取/写入结果。 */
|
||||
export type NoteDoc = {
|
||||
/** 相对库根的路径(`/` 分隔) */
|
||||
relPath: string,
|
||||
/** 显示名(含扩展名) */
|
||||
name: string,
|
||||
/** 完整文件内容(含 front-matter) */
|
||||
content: string,
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number,
|
||||
};
|
||||
|
||||
/** 一次索引同步的结果(命令返回值)。 */
|
||||
export type NoteIndexReport = {
|
||||
indexed: number,
|
||||
removed: number,
|
||||
skipped: number,
|
||||
/** 同步后索引里的笔记数(前端直接显示,省一次统计往返) */
|
||||
noteCount: number,
|
||||
};
|
||||
|
||||
/** 索引状态(设置页展示 / 诊断用)。 */
|
||||
export type NoteIndexStats = {
|
||||
/** 索引中的笔记数 */
|
||||
noteCount: number,
|
||||
/** 库中实际存在的 `.md` 文件数 */
|
||||
fileCount: number,
|
||||
/** 标签数 */
|
||||
tagCount: number,
|
||||
/** 库结构版本 */
|
||||
schemaVersion: number,
|
||||
/** 索引文件路径 */
|
||||
dbPath: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* 一条链接(出链或入链)。
|
||||
*
|
||||
* 出链与入链共用同一个结构,因为面板里展示的信息完全一样(标题 + 路径 + 原始目标)。
|
||||
* `resolved` 区分「已解析到库内某篇笔记」与「未解析」(`[[不存在的笔记]]`)——
|
||||
* 后者不是错误,而是反链面板里最有价值的提示:用户点一下就能建那篇笔记。
|
||||
*/
|
||||
export type NoteLink = {
|
||||
/** 原始写法(`[[会议纪要]]` 里的 `会议纪要`,或 `[x](notes/a.md)` 里的 `notes/a.md`) */
|
||||
target: string,
|
||||
/** 解析出的库内相对路径(未解析时为空串) */
|
||||
relPath: string,
|
||||
/** 目标笔记的标题(未解析时为原始 target) */
|
||||
title: string,
|
||||
/** 是否已解析到库内笔记 */
|
||||
resolved: boolean,
|
||||
/** `wiki` | `md` | `url` */
|
||||
kind: string,
|
||||
};
|
||||
|
||||
/** 单篇笔记的索引记录(返回给前端的搜索结果项)。 */
|
||||
export type NoteSearchHit = {
|
||||
/** 稳定 ID(front-matter 的 `id`;缺失时为空串) */
|
||||
id: string,
|
||||
/** 相对库根的路径(`/` 分隔) */
|
||||
relPath: string,
|
||||
/** 显示标题(front-matter 的 `title`,缺失时取首个一级标题,再缺则取文件名) */
|
||||
title: string,
|
||||
/** 命中片段(含 [`HL_OPEN`] / [`HL_CLOSE`] 定界符;无关键词搜索时为空) */
|
||||
snippet: string,
|
||||
/** 标签 */
|
||||
tags: string[],
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* 一次搜索的结果(含总数,供「共 N 条」显示)。
|
||||
*
|
||||
* 名字带 `Note` 前缀不是啰嗦:`tauri-specta` 的类型注册表按**类型名全局唯一**,
|
||||
* 重名会让 `export_bindings()` 直接 panic(`terminal/history.rs` 的
|
||||
* `TerminalHistoryPage` 就是为这个改的名)。
|
||||
*/
|
||||
export type NoteSearchPage = {
|
||||
items: NoteSearchHit[],
|
||||
/** 满足条件的总条数(**不受 limit/offset 影响**) */
|
||||
total: number,
|
||||
};
|
||||
|
||||
/**
|
||||
* 搜索筛选条件。
|
||||
*
|
||||
* 用结构体而不是一长串位置参数:命令层把前端 payload 原样转发,而多个同类型
|
||||
* 位置参数在调用点顺序写错时编译器不会报错(`terminal/history.rs` 同一理由)。
|
||||
*/
|
||||
export type NoteSearchQuery = {
|
||||
/** 关键词(空格分隔的多个词按 AND 处理;空串 = 只按标签/目录筛选) */
|
||||
keyword?: string,
|
||||
/** 只看带该标签的笔记(空 = 不筛选) */
|
||||
tag?: string,
|
||||
/** 只看该目录(含子目录)下的笔记(空 = 全库) */
|
||||
dir?: string,
|
||||
/** 分页偏移 */
|
||||
offset?: number,
|
||||
/** 分页大小 */
|
||||
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,
|
||||
count: number,
|
||||
};
|
||||
|
||||
/** 一个模板。 */
|
||||
export type NoteTemplate = {
|
||||
/** 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`) */
|
||||
id: string,
|
||||
/** 显示名(文件名去掉扩展名) */
|
||||
name: string,
|
||||
/** 说明(内置模板手写;用户模板取正文首行非空文本) */
|
||||
description: string,
|
||||
/** 是否为内置模板(前端据此提示「不可删除」) */
|
||||
builtin: boolean,
|
||||
/** 模板正文(含 front-matter) */
|
||||
body: string,
|
||||
};
|
||||
|
||||
/** 划词结果悬浮窗外观(P1 生效)。 */
|
||||
export type PopupSettings = {
|
||||
/** 正文字号(逻辑像素) */
|
||||
@@ -2520,6 +2953,37 @@ export type SshHost = {
|
||||
injectShellIntegration?: boolean,
|
||||
};
|
||||
|
||||
/** 同步方向。 */
|
||||
export type SyncDirection =
|
||||
/** 双向同步(默认) */
|
||||
"bidirectional" |
|
||||
/** 只上传(本地覆盖远端)—— 等价于「推送到远端备份」 */
|
||||
"upload" |
|
||||
/** 只下载(远端覆盖本地)—— 换机器恢复时用 */
|
||||
"download";
|
||||
|
||||
/** 一次同步的结果(报告 + 可选快照)。 */
|
||||
export type SyncOutcome = {
|
||||
report: SyncReport,
|
||||
backup: BackupReport | null,
|
||||
};
|
||||
|
||||
/** 一次同步的统计结果。 */
|
||||
export type SyncReport = {
|
||||
uploaded: number,
|
||||
downloaded: number,
|
||||
/** 改名 / 移动的条数 */
|
||||
moved: number,
|
||||
deletedRemote: number,
|
||||
deletedLocal: number,
|
||||
conflicts: number,
|
||||
failed: number,
|
||||
/** 失败明细(最多 [`MAX_FAILURES`] 条,避免把 IPCE 撑爆) */
|
||||
failures: string[],
|
||||
/** 同步用时(毫秒) */
|
||||
elapsedMs: number,
|
||||
};
|
||||
|
||||
/** 任务下载协议类型 */
|
||||
export type TaskProtocol =
|
||||
/** HTTP/HTTPS 直链 */
|
||||
@@ -2555,6 +3019,12 @@ export type TemplateEntry = {
|
||||
label?: string,
|
||||
};
|
||||
|
||||
/** 模板正文与它在库内的位置(`path` 为 `None` = 内置模板)。 */
|
||||
export type TemplateSource = {
|
||||
body: string,
|
||||
path: string | null,
|
||||
};
|
||||
|
||||
/**
|
||||
* 一次查询的结果(含总数,供前端显示「共 N 条」)。
|
||||
*
|
||||
@@ -2822,6 +3292,42 @@ export type UpdateCheckResult = {
|
||||
assets: UpdateAsset[],
|
||||
};
|
||||
|
||||
/** WebDAV 设置(密码**不在这里** —— 它进 keyring,见 `webdav/mod.rs`)。 */
|
||||
export type WebdavSettings = {
|
||||
/** 服务地址(`https://dav.jianguoyun.com/dav`) */
|
||||
url?: string,
|
||||
username?: string,
|
||||
/** 远端根目录(相对 `url`;空串 = 直接用 `url` 指向的目录) */
|
||||
remoteRoot?: string,
|
||||
direction?: SyncDirection,
|
||||
conflict?: ConflictPolicy,
|
||||
/** 应用启动后自动同步一次 */
|
||||
autoSyncOnLaunch?: boolean,
|
||||
/** 保留的 zip 快照份数(上传备份时轮转) */
|
||||
backupKeep?: number,
|
||||
};
|
||||
|
||||
/** WebDAV 配置状态(不包含密码本身)。 */
|
||||
export type WebdavStatus = {
|
||||
/** 地址与用户名是否已填 */
|
||||
configured: boolean,
|
||||
/** keyring 里是否已存密码 */
|
||||
hasPassword: boolean,
|
||||
remoteRoot: string,
|
||||
};
|
||||
|
||||
/** 连接自检结果(设置页展示)。 */
|
||||
export type WebdavTestResult = {
|
||||
/** 是否连通 */
|
||||
ok: boolean,
|
||||
/** 远端根目录中已有的条目数(自检时顺带列出) */
|
||||
entries: number,
|
||||
/** 本次自检自动创建的目录 */
|
||||
created: string[],
|
||||
/** 人话结论(失败时是原因) */
|
||||
message: string,
|
||||
};
|
||||
|
||||
/** 窗口信息(窗口拾取 / 枚举) */
|
||||
export type WindowInfo = {
|
||||
hwnd: number,
|
||||
|
||||
@@ -27,6 +27,8 @@ export const WINDOWS = {
|
||||
* 时,webview 仍可正常加载与交互,只是拿不到 IPC)。
|
||||
*/
|
||||
dshWeb: 'dsh-web',
|
||||
/** 笔记独立窗口前缀,实际 label = `${notesWindow}-<n>`(可多开) */
|
||||
notesWindow: 'notes-window',
|
||||
} as const
|
||||
|
||||
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
|
||||
@@ -147,6 +149,20 @@ export const EVENTS = {
|
||||
dshServerState: 'dsh-server-state',
|
||||
/** 全局快捷键按下:打开 dsh 独立窗口(无负载) */
|
||||
dshOpenWindow: 'dsh-open-window',
|
||||
/** 笔记:设置已保存(无负载)。各窗口据此重读设置,实现跨窗口同步 */
|
||||
notesSettings: 'notes-settings',
|
||||
/** 笔记:库内容已变更(新建/保存/重命名/删除/切换库根,无负载) */
|
||||
notesLibraryChanged: 'notes-library-changed',
|
||||
/** 笔记:库内文件在应用外被改动(负载见 src/types/notes.ts 的 NoteFileEvent) */
|
||||
notesFileChanged: 'notes-file-changed',
|
||||
/** 笔记:WebDAV 同步进度(负载见 src/types/notes.ts 的 SyncProgress) */
|
||||
notesSyncProgress: 'notes-sync-progress',
|
||||
/** 笔记:全局快捷键「新建笔记」被按下(无负载;主窗口据此打开新建对话框) */
|
||||
notesNewNote: 'notes-new-note',
|
||||
/** 笔记:全局快捷键「打开编辑器」被按下(无负载) */
|
||||
notesOpenEditor: 'notes-open-editor',
|
||||
/** 笔记:需要打开一个磁盘文件(负载 `{ path }`;来自文件关联 / 命令行) */
|
||||
notesOpenFile: 'notes-open-file',
|
||||
} as const
|
||||
|
||||
/** localStorage 存储键 */
|
||||
@@ -172,4 +188,6 @@ 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
|
||||
+5
-2
@@ -43,18 +43,21 @@ 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')],
|
||||
]
|
||||
|
||||
const winHash = window.location.hash
|
||||
|
||||
// #screenshot-overlay 带窗口号参数(多屏)、#download-window 带 ?task= 参数,
|
||||
// #terminal-window 带 /{session_id} 路径参数,均按前缀匹配;其余精确匹配
|
||||
// #terminal-window 带 /{session_id} 路径参数、#notes-window 带 ?file=(库内笔记)
|
||||
// 或 ?path=(库外文件)参数,均按前缀匹配;其余精确匹配
|
||||
const matched = standaloneWindowApps.find(([hash]) => {
|
||||
if (
|
||||
hash === '#screenshot-overlay' ||
|
||||
hash === '#screenshot-scroll' ||
|
||||
hash === '#download-window' ||
|
||||
hash === '#terminal-window'
|
||||
hash === '#terminal-window' ||
|
||||
hash === '#notes-window'
|
||||
)
|
||||
return winHash.startsWith(hash)
|
||||
return winHash === hash
|
||||
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
Music,
|
||||
Languages,
|
||||
SquareTerminal,
|
||||
Bot
|
||||
Bot,
|
||||
NotebookPen
|
||||
} from '@lucide/vue'
|
||||
|
||||
/**
|
||||
@@ -33,7 +34,8 @@ export const moduleIconMap: Record<string, Component> = {
|
||||
music: Music,
|
||||
translate: Languages,
|
||||
terminal: SquareTerminal,
|
||||
dsh: Bot
|
||||
dsh: Bot,
|
||||
notes: NotebookPen
|
||||
}
|
||||
|
||||
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
||||
|
||||
@@ -14,6 +14,7 @@ import { moduleConfig as music } from './music'
|
||||
import { moduleConfig as translate } from './translate'
|
||||
import { moduleConfig as terminal } from './terminal'
|
||||
import { moduleConfig as dsh } from './dsh'
|
||||
import { moduleConfig as notes } from './notes'
|
||||
|
||||
const allModules: ModuleConfig[] = [
|
||||
proxy,
|
||||
@@ -27,7 +28,8 @@ const allModules: ModuleConfig[] = [
|
||||
music,
|
||||
translate,
|
||||
terminal,
|
||||
dsh
|
||||
dsh,
|
||||
notes
|
||||
]
|
||||
|
||||
// 启动时注册所有模块
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import {
|
||||
CircleAlert,
|
||||
Cloud,
|
||||
FolderOpen,
|
||||
HardDrive,
|
||||
@@ -327,6 +328,9 @@ const GRID = { gridTemplateColumns: '28px 36px minmax(0,1fr) 74px 28px' }
|
||||
|
||||
const listEmptyHint = computed(() => {
|
||||
if (view.value === 'feiniu') {
|
||||
// 拉取失败优先于「曲库为空」:一首都没有且请求失败时,只写「曲库为空」
|
||||
// 会被读成「NAS 上确实没歌」,而真正的原因(如服务端 unknown error)看不到
|
||||
if (store.libraryError) return store.libraryError
|
||||
return store.config.loggedIn ? '曲库为空,试试刷新或检查 NAS 曲库目录' : '请先在「设置 → 飞牛音乐连接」登录'
|
||||
}
|
||||
return '暂无本地音乐,点击「扫描本地曲库」,或到「设置 → 存储与上传」添加本地曲库目录'
|
||||
@@ -554,8 +558,11 @@ const listEmptyHint = computed(() => {
|
||||
<Loader2 class="size-4 animate-spin" /> 加载曲库…
|
||||
</div>
|
||||
<Empty v-else-if="!store.tracks.length">
|
||||
<EmptyMedia><Music2 class="size-8 text-muted-foreground" /></EmptyMedia>
|
||||
<EmptyTitle>曲库为空</EmptyTitle>
|
||||
<EmptyMedia>
|
||||
<CircleAlert v-if="store.libraryError" class="size-8 text-destructive" />
|
||||
<Music2 v-else class="size-8 text-muted-foreground" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>{{ store.libraryError ? '曲库加载失败' : '曲库为空' }}</EmptyTitle>
|
||||
<EmptyDescription>{{ listEmptyHint }}</EmptyDescription>
|
||||
</Empty>
|
||||
<Empty v-else-if="!filteredTracks.length">
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记模块主页面 —— **只做设置与管理,不做编辑**。
|
||||
*
|
||||
* 编辑发生在独立窗口(`openNotesWindow()`),本页负责:库状态与入口、库根管理、
|
||||
* 编辑器偏好。所有设置**即时生效、无保存按钮**。
|
||||
*
|
||||
* 版式遵循 `UI_DESIGN_SYSTEM.md`:
|
||||
* - 模块根 `min-h-full p-5`(滚动归属主滚动区,模块自身不建滚动容器)
|
||||
* - **不渲染 Tab 行**,Tab 注册给标题栏常驻切换器(`useModuleTabs` + `alwaysVisible`)
|
||||
* - 概览用「状态横幅 + 卡片」(§3.4);设置页用「多张 Card + 卡内标题 + `SettingRow`」
|
||||
* (与 dsh / 音乐设置页一致,`SettingGroup` 留给全局设置页那种多分组场景)
|
||||
* - 空态一律 `StateBlock`,不手写占位文案
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
BookOpen,
|
||||
CalendarDays,
|
||||
Copy,
|
||||
Database,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
FolderOpen,
|
||||
Keyboard,
|
||||
Library,
|
||||
NotebookPen,
|
||||
Palette,
|
||||
RefreshCw,
|
||||
Tags
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { openNotesWindow } from './openWindow'
|
||||
import { notesClient } from './notesClient'
|
||||
import { EDITOR_THEME_OPTIONS } from './editor/themes'
|
||||
import WebdavPanel from './components/WebdavPanel.vue'
|
||||
import ImportExportPanel from './components/ImportExportPanel.vue'
|
||||
import NewNoteDialog from './components/NewNoteDialog.vue'
|
||||
import type { NoteSettings } from '@/types/notes'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const activeTab = ref('overview')
|
||||
// Tab 结构(规划 §8-Q5):概览 / 库 / 编辑器 / 同步。
|
||||
// 「关于」并入概览(模块信息量不足以独占一页),设置项按主题归入对应页。
|
||||
useModuleTabs(
|
||||
'notes',
|
||||
activeTab,
|
||||
[
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'library', label: '库' },
|
||||
{ value: 'editor', label: '编辑器' },
|
||||
{ value: 'sync', label: '同步' }
|
||||
],
|
||||
{ alwaysVisible: true }
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void store.init()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
store.disposeListeners()
|
||||
})
|
||||
|
||||
// ===== 全局快捷键请求(Rust 只发事件,这里负责开对话框 / 开窗口)=====
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
watch(
|
||||
() => store.newNoteRequest,
|
||||
() => {
|
||||
activeTab.value = 'overview'
|
||||
newNoteOpen.value = true
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => store.openEditorRequest,
|
||||
() => void openEditor()
|
||||
)
|
||||
|
||||
/**
|
||||
* 冷启动的「用 Thing 打开」:命令行留下的文件路径取到后,直接开一个笔记窗口。
|
||||
*
|
||||
* **只在主窗口做**:笔记窗口内部也会渲染本模块(`#notes-window` 是独立入口,
|
||||
* 不走这里),但它的 hash 里已经带了 `?path=`,由 `NotesWindow` 自己打开 ——
|
||||
* 这里再响应一次就会开第二个窗口。
|
||||
*/
|
||||
watch(
|
||||
() => store.pendingOpenPath,
|
||||
path => {
|
||||
if (!path || isNotesWindow()) return
|
||||
void openNotesWindow({ path }).catch(e => toast.error(`打开文件失败:${String(e)}`))
|
||||
}
|
||||
)
|
||||
|
||||
/** 当前是否运行在笔记独立窗口里(hash 形如 `#notes-window?...`)。 */
|
||||
function isNotesWindow(): boolean {
|
||||
return window.location.hash.startsWith(`#${WINDOWS.notesWindow}`)
|
||||
}
|
||||
|
||||
// ===== 设置写入(即时生效) =====
|
||||
function commit(patch: Partial<NoteSettings>): void {
|
||||
void store.patchSettings(patch)
|
||||
}
|
||||
|
||||
function onNumber(
|
||||
patchKey: 'fontSize' | 'lineHeight' | 'tabSize' | 'autosaveMs' | 'maxFileSizeMb',
|
||||
event: Event
|
||||
) {
|
||||
const value = Number((event.target as HTMLInputElement).value)
|
||||
if (!Number.isFinite(value)) return
|
||||
commit({ [patchKey]: value } as Partial<NoteSettings>)
|
||||
}
|
||||
|
||||
// ===== 库根 =====
|
||||
const resetRootOpen = ref(false)
|
||||
|
||||
async function pickLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({ directory: true, multiple: false, title: '选择笔记库目录' })
|
||||
if (typeof selected !== 'string') return
|
||||
await store.setLibraryRoot(selected)
|
||||
toast.success('已切换笔记库')
|
||||
} catch (e) {
|
||||
toast.error(`切换失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resetLibraryRoot(): Promise<void> {
|
||||
try {
|
||||
await store.setLibraryRoot(null)
|
||||
toast.success('已恢复默认库目录')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
resetRootOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revealRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await openPath(store.libraryRoot)
|
||||
} catch (e) {
|
||||
toast.error(`打开目录失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRoot(): Promise<void> {
|
||||
if (!store.libraryRoot) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(store.libraryRoot)
|
||||
toast.success('库路径已复制')
|
||||
} catch {
|
||||
toast.error('复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function openEditor(): Promise<void> {
|
||||
try {
|
||||
await openNotesWindow()
|
||||
} catch (e) {
|
||||
toast.error(`打开编辑器失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 在编辑器窗口里直接打开磁盘文件(路径来自系统对话框,选择即授权)。 */
|
||||
async function openExternalFile(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: '打开文件'
|
||||
})
|
||||
if (typeof selected !== 'string') return
|
||||
await notesClient.authorizeFile(selected)
|
||||
await openNotesWindow({ path: selected })
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const rebuilding = ref(false)
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
rebuilding.value = true
|
||||
try {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
} catch (e) {
|
||||
toast.error(`重建索引失败:${String(e)}`)
|
||||
} finally {
|
||||
rebuilding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开今天的日记(不存在则按日记模板创建)。 */
|
||||
async function openDailyNote(): Promise<void> {
|
||||
try {
|
||||
await store.openDailyNote()
|
||||
await openNotesWindow({ relPath: store.currentRelPath })
|
||||
} catch (e) {
|
||||
toast.error(`打开日记失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const noteCount = computed(() => store.info?.noteCount ?? 0)
|
||||
const rootKind = computed(() => (store.info?.isCustom ? '自定义' : '默认'))
|
||||
/** 索引状态摘要(横幅右侧;索引未就绪时显示占位) */
|
||||
const indexSummary = computed(() => {
|
||||
const stats = store.indexStats
|
||||
if (!stats) return '索引准备中'
|
||||
return `索引 ${stats.noteCount} / 文件 ${stats.fileCount}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-full p-5">
|
||||
<Tabs v-model="activeTab" class="flex min-h-full w-full flex-col">
|
||||
<!-- ===== 概览 ===== -->
|
||||
<TabsContent value="overview" class="tab-animate">
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- 状态横幅:状态区 → 指标区 → 操作区(§3.4) -->
|
||||
<Card class="!py-0 !gap-0">
|
||||
<CardContent class="flex flex-wrap items-center gap-x-6 gap-y-3 px-4 py-4">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span
|
||||
v-if="!store.info"
|
||||
class="flex items-center gap-1.5 text-[13px] text-muted-foreground"
|
||||
>
|
||||
<span class="size-2 rounded-full bg-muted-foreground" />加载中
|
||||
</span>
|
||||
<template v-else>
|
||||
<span class="flex items-center gap-1.5 text-[13px] text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已就绪
|
||||
</span>
|
||||
</template>
|
||||
<span class="text-[13px] text-fg-secondary">本地 Markdown 笔记库</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">笔记数</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ noteCount }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-24 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库类型</span>
|
||||
<span class="text-lg font-semibold tabular-nums">{{ rootKind }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">库目录</span>
|
||||
<span class="truncate font-mono text-[13px] text-fg-secondary">
|
||||
{{ store.libraryRoot || '—' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-28 flex-col gap-0.5">
|
||||
<span class="text-[11px] text-muted-foreground">索引</span>
|
||||
<span class="truncate text-[13px] text-fg-secondary">
|
||||
{{ store.indexing ? '同步中…' : indexSummary }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="ml-auto flex flex-wrap gap-2">
|
||||
<Button size="sm" variant="outline" @click="openDailyNote">
|
||||
<CalendarDays class="size-3.5" />今日日记
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />打开目录
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" @click="openExternalFile">
|
||||
<FolderOpen class="size-3.5" />打开文件
|
||||
</Button>
|
||||
<Button size="sm" @click="openEditor">
|
||||
<NotebookPen class="size-3.5" />打开编辑器
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 最近打开 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<BookOpen class="size-4 text-primary" />
|
||||
最近打开
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<StateBlock
|
||||
v-if="!store.recent.length"
|
||||
variant="empty"
|
||||
title="还没有打开过笔记"
|
||||
description="点上方「打开编辑器」新建或打开一篇笔记"
|
||||
:min-height="140"
|
||||
/>
|
||||
<div v-else class="flex flex-col divide-y divide-divider">
|
||||
<button
|
||||
v-for="item in store.recent"
|
||||
:key="item.relPath"
|
||||
type="button"
|
||||
class="flex min-h-13 items-center gap-4 py-2 text-left transition-colors duration-150 outline-none hover:text-primary focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
@click="openNotesWindow({ relPath: item.relPath })"
|
||||
>
|
||||
<span class="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span class="truncate text-[13px] text-foreground">
|
||||
{{ item.name.replace(/\.md$/i, '') }}
|
||||
</span>
|
||||
<span class="truncate text-xs text-muted-foreground">{{ item.relPath }}</span>
|
||||
</span>
|
||||
<ExternalLink class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 库(库根 / 索引 / 导入导出) ===== -->
|
||||
<TabsContent value="library" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 笔记库 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Library class="size-4 text-primary" />
|
||||
笔记库
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
笔记以 Markdown 文件形式保存在该目录;切换库只改变指向,原目录内容不会被移动
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="库目录" :description="store.libraryRoot || '—'">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="copyRoot">
|
||||
<Copy class="size-3.5" />复制
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!store.libraryRoot" @click="revealRoot">
|
||||
<FolderOpen class="size-3.5" />浏览
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="pickLibraryRoot">
|
||||
<NotebookPen class="size-3.5" />切换…
|
||||
</Button>
|
||||
<Button
|
||||
v-if="store.info?.isCustom"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="resetRootOpen = true"
|
||||
>
|
||||
恢复默认
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重新扫描" description="在应用外新增或修改文件后,手动刷新库内容">
|
||||
<Button variant="outline" size="sm" @click="store.refreshLibrary()">
|
||||
<RefreshCw class="size-3.5" />刷新
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 索引与检索(P1) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Database class="size-4 text-primary" />
|
||||
索引与检索
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
全文检索与标签依赖一份 SQLite 索引(存放在库内 <code class="font-mono">.notes/</code>)。
|
||||
它只是加速层:删掉也能从 Markdown 文件完整重建,不影响笔记本身。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="索引状态"
|
||||
:description="store.indexStats?.dbPath || '尚未建立索引'"
|
||||
>
|
||||
<div class="flex items-center gap-3 text-[13px] text-fg-secondary">
|
||||
<span class="tabular-nums">笔记 {{ store.indexStats?.noteCount ?? 0 }}</span>
|
||||
<span class="tabular-nums">文件 {{ store.indexStats?.fileCount ?? 0 }}</span>
|
||||
<span class="flex items-center gap-1 tabular-nums">
|
||||
<Tags class="size-3.5" />{{ store.indexStats?.tagCount ?? 0 }}
|
||||
</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="重建索引" description="按文件重新解析标题、标签与双链(库很大时需要一点时间)">
|
||||
<Button variant="outline" size="sm" :disabled="rebuilding || store.indexing" @click="rebuildIndex">
|
||||
<RefreshCw class="size-3.5" :class="rebuilding && 'animate-spin'" />重建
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="外部改动监听" description="库内文件在应用外被修改时提醒(监听始终开启)">
|
||||
<span class="flex items-center gap-1.5 text-xs text-success">
|
||||
<span class="size-2 rounded-full bg-success" />已启用
|
||||
</span>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="单文件大小上限"
|
||||
description="超过该大小的文件会关闭所见即所得 / 折叠 / 补全,单位 MB"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="store.settings.maxFileSizeMb"
|
||||
@change="onNumber('maxFileSizeMb', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 导入 / 导出(P2) -->
|
||||
<ImportExportPanel />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 编辑器 ===== -->
|
||||
<TabsContent value="editor" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<!-- 编辑器外观 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Palette class="size-4 text-primary" />
|
||||
编辑器外观
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="配色方案" description="跟随应用时按应用深浅自动选深/浅变体" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => commit({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="跟随应用深浅" description="开关打开时,配色方案仅作为取色基准">
|
||||
<Switch
|
||||
:model-value="store.settings.followAppTheme"
|
||||
@update:model-value="v => commit({ followAppTheme: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体族" description="留空使用内置等宽字体栈" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.fontFamily"
|
||||
placeholder="Cascadia Code, Consolas, …"
|
||||
@change="(e: Event) => commit({ fontFamily: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字号" description="单位 px" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="10"
|
||||
max="32"
|
||||
:model-value="store.settings.fontSize"
|
||||
@change="onNumber('fontSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="行高" description="倍数,建议 1.5 ~ 2.0" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
min="1"
|
||||
max="3"
|
||||
:model-value="store.settings.lineHeight"
|
||||
@change="onNumber('lineHeight', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="字体连字" description="启用 ligatures(如 => 显示为箭头)">
|
||||
<Switch
|
||||
:model-value="store.settings.ligatures"
|
||||
@update:model-value="v => commit({ ligatures: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="显示行号">
|
||||
<Switch
|
||||
:model-value="store.settings.showLineNumbers"
|
||||
@update:model-value="v => commit({ showLineNumbers: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="显示大纲"
|
||||
description="在编辑器侧栏显示标题树(Ctrl+Shift+L 可临时切换)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showOutline"
|
||||
@update:model-value="v => commit({ showOutline: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 编辑器行为 -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Eye class="size-4 text-primary" />
|
||||
编辑器行为
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow
|
||||
label="所见即所得"
|
||||
description="Live Preview:语法符号在非光标行隐藏、光标行显形;关闭后为纯源码 + 高亮"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.livePreview"
|
||||
@update:model-value="v => commit({ livePreview: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="默认视图" description="新开编辑器窗口时的初始视图" control-width="wide">
|
||||
<Select
|
||||
:model-value="String(store.settings.defaultView)"
|
||||
@update:model-value="v => commit({ defaultView: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="wysiwyg">所见即所得</SelectItem>
|
||||
<SelectItem value="source">源码</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="自动保存" description="停止输入后延迟保存,单位毫秒;0 = 关闭(仅 Ctrl+S)" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
max="10000"
|
||||
step="100"
|
||||
:model-value="store.settings.autosaveMs"
|
||||
@change="onNumber('autosaveMs', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="Tab 宽度" description="按空格数计" control-width="wide">
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="8"
|
||||
:model-value="store.settings.tabSize"
|
||||
@change="onNumber('tabSize', $event)"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="自动补全"
|
||||
description="括号自动闭合与代码补全(大文件会临时关闭)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.autocomplete"
|
||||
@update:model-value="v => commit({ autocomplete: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="识别 [[双链]]"
|
||||
description="按 Obsidian 语义解析双链并写入索引(反链面板留待后续)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.wikilink"
|
||||
@update:model-value="v => commit({ wikilink: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="复用文档窗口"
|
||||
description="同一篇笔记重复打开时聚焦已有窗口,而不是开出第二个(两个窗口会自动保存,后写的覆盖先写的)"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.reuseWindow"
|
||||
@update:model-value="v => commit({ reuseWindow: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="导出时高亮代码"
|
||||
description="关闭后导出的 HTML 里代码块是纯黑白,适合黑白打印机"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.exportHighlight"
|
||||
@update:model-value="v => commit({ exportHighlight: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="新建时选模板"
|
||||
description="关闭后用上次选中的模板直接新建"
|
||||
>
|
||||
<Switch
|
||||
:model-value="store.settings.showTemplatePicker"
|
||||
@update:model-value="v => commit({ showTemplatePicker: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 全局快捷键(P2) -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Keyboard class="size-4 text-primary" />
|
||||
全局快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
留空即不注册。格式如 <code class="font-mono">Ctrl+Shift+N</code>;与本应用其它模块
|
||||
的快捷键冲突时会注册失败(日志里会写明是谁占了)。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="新建笔记" description="任意界面按下都打开新建对话框" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.newNoteShortcut"
|
||||
placeholder="Ctrl+Shift+N"
|
||||
@change="(e: Event) => commit({ newNoteShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="打开编辑器窗口" control-width="wide">
|
||||
<Input
|
||||
:model-value="store.settings.openEditorShortcut"
|
||||
placeholder="未设置"
|
||||
@change="(e: Event) => commit({ openEditorShortcut: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<!-- ===== 同步(WebDAV) ===== -->
|
||||
<TabsContent value="sync" class="tab-animate">
|
||||
<div class="flex flex-col gap-4 pb-4">
|
||||
<WebdavPanel />
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="resetRootOpen"
|
||||
title="恢复默认库目录"
|
||||
description="笔记不会丢失:仅把库根指回应用数据目录下的默认位置,原目录内容保持不动。"
|
||||
confirm-text="恢复默认"
|
||||
@confirm="resetLibraryRoot"
|
||||
/>
|
||||
|
||||
<!-- 全局快捷键(Ctrl+Shift+N)触发的新建对话框:落在库根 -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" dir-rel="" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,525 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记独立窗口根组件(`#notes-window`)。
|
||||
*
|
||||
* # 为什么是独立窗口
|
||||
*
|
||||
* 主模块页只做设置与管理;真正的编辑发生在这里 —— 可多开、可拖到副屏,
|
||||
* 编辑体验接近一个独立应用(与终端 / 下载 / 翻译窗口同一范式)。
|
||||
*
|
||||
* # 生命周期要点
|
||||
*
|
||||
* - 窗口由 `openWindow.ts` **隐藏创建**,本组件 `applyTheme` 之后才 `show`
|
||||
* (否则深色模式下会先闪一下纯白窗口);
|
||||
* - 自带一份 Pinia(`main.ts` 里为独立窗口注入),store 通过 IPC 与 Rust 对齐;
|
||||
* - 监听 `notes-settings` / `notes-library-changed` / `notes-file-changed`
|
||||
* 实现与主窗口及外部编辑器的实时同步。
|
||||
*
|
||||
* # P1 新增的三种「异步危险」
|
||||
*
|
||||
* 1. **外部改动**:库文件在别的编辑器里被改了,而我们这边有未保存内容 —— 不能
|
||||
* 静默重载(会丢掉用户刚敲的字),弹出横幅让用户选;
|
||||
* 2. **打开库外文件**:路径来自系统对话框,必须先 `authorize` 才能写回;
|
||||
* 3. **大文件**:超过阈值时关掉 Live Preview / 折叠 / 补全(降级在 `core.ts`,
|
||||
* 这里只负责把 `large` 标记和提示露出来)。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { Effect, EffectState, getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { AlertTriangle, Minus, NotebookPen, PanelLeft, Square, X } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { ConfirmDialog, StateBlock } from '@/components/common'
|
||||
import { STORAGE_KEYS } from '@/lib/constants'
|
||||
import { applyStoredAccent } from '@/lib/theme'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import LibrarySidebar from './components/LibrarySidebar.vue'
|
||||
import EditorHost from './components/EditorHost.vue'
|
||||
import EditorToolbar from './components/EditorToolbar.vue'
|
||||
import QuickOpen from './components/QuickOpen.vue'
|
||||
import type { NoteViewMode } from '@/types/notes'
|
||||
import type { Command, EditorView } from '@codemirror/view'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
const win = getCurrentWindow()
|
||||
const store = useNotesStore()
|
||||
|
||||
const isDark = ref(false)
|
||||
const sidebarVisible = ref(true)
|
||||
const viewMode = ref<NoteViewMode>('wysiwyg')
|
||||
const hostRef = ref<InstanceType<typeof EditorHost> | null>(null)
|
||||
const sidebarRef = ref<InstanceType<typeof LibrarySidebar> | null>(null)
|
||||
const quickOpen = ref(false)
|
||||
const cursorLine = ref(0)
|
||||
const cursorColumn = ref(1)
|
||||
|
||||
// ===== 主题与窗口效果(与主应用同步) =====
|
||||
function readMainTheme(): { theme: string; effect: string } {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||
if (raw) {
|
||||
const s = JSON.parse(raw) as { theme?: string; effect?: string }
|
||||
return { theme: s.theme ?? 'system', effect: s.effect ?? 'mica' }
|
||||
}
|
||||
} catch {
|
||||
/* 设置不可读时按默认处理 */
|
||||
}
|
||||
return { theme: 'system', effect: 'mica' }
|
||||
}
|
||||
|
||||
function resolveIsDark(theme: string): boolean {
|
||||
if (theme === 'dark') return true
|
||||
if (theme === 'light') return false
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
async function applyTheme(): Promise<void> {
|
||||
const root = document.documentElement
|
||||
const { theme, effect } = readMainTheme()
|
||||
|
||||
try {
|
||||
await win.setTheme(theme === 'system' ? null : (theme as 'dark' | 'light'))
|
||||
} catch {
|
||||
/* 平台不支持时忽略 */
|
||||
}
|
||||
|
||||
const dark = resolveIsDark(theme)
|
||||
isDark.value = dark
|
||||
root.classList.remove('dark', 'effect-mica', 'effect-acrylic', 'effect-normal')
|
||||
root.classList.add(`effect-${effect}`)
|
||||
if (dark) root.classList.add('dark')
|
||||
applyStoredAccent(root, dark ? 'dark' : 'light', STORAGE_KEYS.appSettings)
|
||||
|
||||
try {
|
||||
// setEffects 会直接覆盖当前效果,无需 clearEffects(那个命令未在 capability 中授权)
|
||||
if (effect === 'mica') {
|
||||
await win.setEffects({
|
||||
effects: [Effect.Mica],
|
||||
state: EffectState.FollowsWindowActiveState,
|
||||
color: dark ? [30, 41, 59, 0] : [248, 250, 252, 0]
|
||||
})
|
||||
await win.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else if (effect === 'acrylic') {
|
||||
await win.setEffects({
|
||||
effects: [Effect.Acrylic],
|
||||
state: EffectState.FollowsWindowActiveState,
|
||||
color: dark ? [30, 41, 59, 0] : [248, 250, 252, 0]
|
||||
})
|
||||
await win.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else {
|
||||
const bg = dark ? '#16161a' : '#ffffff'
|
||||
await win.setBackgroundColor(bg)
|
||||
root.style.setProperty('--popup-bg', bg)
|
||||
}
|
||||
} catch {
|
||||
/* 忽略效果设置失败 */
|
||||
}
|
||||
}
|
||||
|
||||
const darkMedia = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const onThemeChange = () => void applyTheme()
|
||||
const onStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEYS.appSettings) void applyTheme()
|
||||
}
|
||||
|
||||
// ===== 窗口控制 =====
|
||||
const doMinimize = () => win.minimize().catch(() => undefined)
|
||||
const doToggleMaximize = () => win.toggleMaximize().catch(() => undefined)
|
||||
|
||||
/** 关闭确认(有未保存改动时) */
|
||||
const closeConfirmOpen = ref(false)
|
||||
|
||||
async function doClose(): Promise<void> {
|
||||
if (store.dirty) {
|
||||
closeConfirmOpen.value = true
|
||||
return
|
||||
}
|
||||
await forceClose()
|
||||
}
|
||||
|
||||
async function forceClose(): Promise<void> {
|
||||
try {
|
||||
await store.saveCurrent()
|
||||
} catch {
|
||||
/* 保存失败不阻塞关闭;脏数据仍在编辑器里 */
|
||||
}
|
||||
win.close().catch(() => undefined)
|
||||
}
|
||||
|
||||
const startDrag = () => {
|
||||
win.startDragging().catch(() => undefined)
|
||||
}
|
||||
|
||||
// ===== 编辑器命令转发 =====
|
||||
function applyCommand(command: Command): void {
|
||||
const view = hostRef.value?.getView() as EditorView | null | undefined
|
||||
if (view) command(view)
|
||||
}
|
||||
|
||||
async function doSave(): Promise<void> {
|
||||
try {
|
||||
await store.saveCurrent()
|
||||
toast.success('已保存')
|
||||
} catch (e) {
|
||||
toast.error(`保存失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function onCursorMoved(line: number, column: number): void {
|
||||
cursorLine.value = line
|
||||
cursorColumn.value = column
|
||||
sidebarRef.value?.setCursorLine(line)
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击 `[[wikilink]]`。
|
||||
*
|
||||
* 目标是**库内相对路径**(`名字.md`)—— 与 Rust 侧 `resolve_link` 的「按名字 + 相对
|
||||
* 当前目录」判据保持一致。找不到就按这个名字在当前笔记所在目录新建一篇:
|
||||
* 「先写链接、后补内容」是双链笔记的标准用法,静默失败会让这个习惯立刻失效。
|
||||
*/
|
||||
async function onWikilink(target: string): Promise<void> {
|
||||
const name = target.trim()
|
||||
if (!name) return
|
||||
const dir = store.currentRelPath.split('/').slice(0, -1).join('/')
|
||||
const relPath = dir ? `${dir}/${name}.md` : `${name}.md`
|
||||
if (store.entries.some(entry => entry.relPath === relPath)) {
|
||||
await store.openNote(relPath)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.createNote(dir, name)
|
||||
toast.success(`已新建「${name}」`)
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 打开库外文件 =====
|
||||
async function doOpenFile(): Promise<void> {
|
||||
try {
|
||||
const selected = await open({
|
||||
multiple: false,
|
||||
directory: false,
|
||||
title: '打开文件',
|
||||
filters: [
|
||||
{ name: '文本 / 代码', extensions: ['md', 'txt', 'json', 'yaml', 'yml', 'toml', 'ini', 'log', 'csv'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
})
|
||||
if (typeof selected !== 'string') return
|
||||
await store.openFile(selected)
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 外部改动 =====
|
||||
const externalConfirmOpen = ref(false)
|
||||
|
||||
async function reloadFromExternal(): Promise<void> {
|
||||
try {
|
||||
await store.reloadCurrent()
|
||||
store.externalChange = null
|
||||
toast.success('已重新载入')
|
||||
} catch (e) {
|
||||
toast.error(`重新载入失败:${String(e)}`)
|
||||
} finally {
|
||||
externalConfirmOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 「保留我的改动」:只清掉提示,磁盘上的版本仍是外部那份(用户下次保存会覆盖它) */
|
||||
function keepLocal(): void {
|
||||
store.externalChange = null
|
||||
externalConfirmOpen.value = false
|
||||
}
|
||||
|
||||
// ===== 全局按键(窗口级) =====
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const mod = event.ctrlKey || event.metaKey
|
||||
if (!mod) return
|
||||
const key = event.key.toLowerCase()
|
||||
|
||||
if (key === 's') {
|
||||
event.preventDefault()
|
||||
void doSave()
|
||||
} else if (key === 'p' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
quickOpen.value = true
|
||||
} else if (key === 'o') {
|
||||
event.preventDefault()
|
||||
void doOpenFile()
|
||||
} else if (key === 'f' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showSearch()
|
||||
} else if (key === 'm' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
viewMode.value = viewMode.value === 'wysiwyg' ? 'source' : 'wysiwyg'
|
||||
} else if (key === 'l' && event.shiftKey) {
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showOutline()
|
||||
} else if (key === 'n' && event.shiftKey) {
|
||||
// 与全局快捷键同义:窗口内有焦点时在本窗口直接开对话框,不必绕 Rust 一圈
|
||||
event.preventDefault()
|
||||
sidebarVisible.value = true
|
||||
sidebarRef.value?.showNewNote()
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 hash 查询串解析初始要打开的文档(`file` = 库内笔记,`path` = 库外文件)。 */
|
||||
function initialTarget(): { relPath: string; path: string } {
|
||||
const hash = window.location.hash
|
||||
const queryIndex = hash.indexOf('?')
|
||||
if (queryIndex < 0) return { relPath: '', path: '' }
|
||||
const params = new URLSearchParams(hash.slice(queryIndex + 1))
|
||||
return { relPath: params.get('file') ?? '', path: params.get('path') ?? '' }
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
darkMedia.addEventListener('change', onThemeChange)
|
||||
window.addEventListener('storage', onStorageChange)
|
||||
window.addEventListener('keydown', onKeydown, true)
|
||||
|
||||
// 主题 → 显示(窗口是隐藏创建的,这一步之后用户才第一次看到它)
|
||||
await applyTheme()
|
||||
try {
|
||||
await win.show()
|
||||
await win.setFocus()
|
||||
} catch (e) {
|
||||
logger.warn(`显示笔记窗口失败:${String(e)}`)
|
||||
}
|
||||
|
||||
await store.init()
|
||||
viewMode.value = store.settings.defaultView === 'source' ? 'source' : 'wysiwyg'
|
||||
|
||||
const { relPath: targetRel, path: targetPath } = initialTarget()
|
||||
if (targetRel) {
|
||||
await store.openNote(targetRel)
|
||||
} else if (targetPath) {
|
||||
try {
|
||||
await store.openFile(targetPath)
|
||||
} catch (e) {
|
||||
toast.error(`打开文件失败:${String(e)}`)
|
||||
}
|
||||
} else if (store.recent.length) {
|
||||
await store.openNote(store.recent[0].relPath)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
darkMedia.removeEventListener('change', onThemeChange)
|
||||
window.removeEventListener('storage', onStorageChange)
|
||||
window.removeEventListener('keydown', onKeydown, true)
|
||||
store.disposeListeners()
|
||||
})
|
||||
|
||||
// ===== 状态栏 =====
|
||||
const title = computed(() => store.currentName || '笔记')
|
||||
const statusText = computed(() => {
|
||||
if (store.saving) return '保存中…'
|
||||
if (store.dirty) return '未保存'
|
||||
if (!store.hasDocument) return '未打开文档'
|
||||
return '已保存'
|
||||
})
|
||||
/** 编码 / 换行只在库外文件里有意义(笔记永远是 UTF-8 + 换行跟随原文) */
|
||||
const encodingLabel = computed(() => (store.kind === 'file' ? store.fileDoc?.encoding ?? '' : ''))
|
||||
const eolLabel = computed(() => {
|
||||
if (store.kind !== 'file') return ''
|
||||
return store.fileDoc?.eol === 'crlf' ? 'CRLF' : 'LF'
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="notes-window flex h-screen flex-col overflow-hidden text-foreground">
|
||||
<!-- 自绘标题栏:仅标题区是拖动区,右侧按钮区不是(否则鼠标事件被拖动拦截) -->
|
||||
<header class="flex h-9 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<div
|
||||
class="flex h-full min-w-0 flex-1 items-center gap-2 pl-1"
|
||||
data-tauri-drag-region
|
||||
@mousedown="startDrag"
|
||||
>
|
||||
<NotebookPen class="size-3.5 shrink-0 text-primary" />
|
||||
<span class="pointer-events-none truncate text-xs font-medium">{{ title }}</span>
|
||||
<span
|
||||
v-if="store.kind === 'file'"
|
||||
class="pointer-events-none shrink-0 rounded-sm bg-muted px-1 text-[10px] text-fg-secondary"
|
||||
>
|
||||
文件
|
||||
</span>
|
||||
<span v-if="store.dirty" class="size-1.5 shrink-0 rounded-full bg-primary" />
|
||||
</div>
|
||||
|
||||
<div class="w-px h-4 bg-border shrink-0" />
|
||||
|
||||
<TooltipProvider :delay-duration="400">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="sidebarVisible = !sidebarVisible">
|
||||
<PanelLeft class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">切换侧栏</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="doMinimize">
|
||||
<Minus class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">最小化</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" @click="doToggleMaximize">
|
||||
<Square class="size-3" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">最大化 / 还原</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="hover:!bg-destructive hover:!text-destructive-foreground"
|
||||
@click="doClose"
|
||||
>
|
||||
<X class="size-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">关闭窗口</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</header>
|
||||
|
||||
<!-- 工具栏 -->
|
||||
<EditorToolbar
|
||||
:apply="applyCommand"
|
||||
:view-mode="viewMode"
|
||||
:dirty="store.dirty"
|
||||
:saving="store.saving"
|
||||
:name="store.currentName"
|
||||
@update:view-mode="viewMode = $event"
|
||||
@save="doSave"
|
||||
@open-file="doOpenFile"
|
||||
@quick-open="quickOpen = true"
|
||||
/>
|
||||
|
||||
<!-- 外部改动提示(有未保存改动时才会出现) -->
|
||||
<div
|
||||
v-if="store.externalChange"
|
||||
class="flex shrink-0 items-center gap-2 border-b border-border bg-warning-soft px-3 py-1.5 text-xs"
|
||||
>
|
||||
<AlertTriangle class="size-3.5 shrink-0 text-warning" />
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
该文件已在应用外被
|
||||
{{ store.externalChange.kind === 'removed' ? '删除' : '修改' }}
|
||||
—— 你的未保存改动仍在编辑器里
|
||||
</span>
|
||||
<Button variant="outline" size="sm" @click="keepLocal">保留我的改动</Button>
|
||||
<Button variant="outline" size="sm" @click="externalConfirmOpen = true">查看并重载</Button>
|
||||
</div>
|
||||
|
||||
<!-- 大文件降级提示 -->
|
||||
<div
|
||||
v-if="store.fileDoc?.large"
|
||||
class="flex shrink-0 items-center gap-2 border-b border-border bg-muted px-3 py-1 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<AlertTriangle class="size-3 shrink-0" />
|
||||
文件较大,已关闭「所见即所得 / 折叠 / 自动补全」以保证输入流畅
|
||||
</div>
|
||||
|
||||
<!-- 主体:侧栏 + 编辑器 -->
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<LibrarySidebar
|
||||
v-if="sidebarVisible"
|
||||
ref="sidebarRef"
|
||||
@open="store.openNote($event)"
|
||||
@jump="hostRef?.jumpTo($event)"
|
||||
/>
|
||||
<main class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div v-if="!store.hasDocument" class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<StateBlock
|
||||
variant="empty"
|
||||
title="未打开文档"
|
||||
description="从左侧选择一篇笔记、新建一篇,或用 Ctrl+O 打开磁盘上的文件"
|
||||
:min-height="200"
|
||||
>
|
||||
<template #action>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" size="sm" @click="sidebarVisible = true">
|
||||
<PanelLeft class="size-3.5" />打开侧栏
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="doOpenFile">打开文件…</Button>
|
||||
</div>
|
||||
</template>
|
||||
</StateBlock>
|
||||
</div>
|
||||
<EditorHost
|
||||
v-show="store.hasDocument"
|
||||
ref="hostRef"
|
||||
:is-dark="isDark"
|
||||
:live-preview="viewMode === 'wysiwyg'"
|
||||
@cursor-moved="onCursorMoved"
|
||||
@wikilink="onWikilink"
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- 状态栏 -->
|
||||
<footer
|
||||
class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<span>{{ statusText }}</span>
|
||||
<span v-if="store.hasDocument" class="tabular-nums">
|
||||
{{ store.wordCount }} 字 · {{ store.lineCount }} 行
|
||||
</span>
|
||||
<span v-if="store.hasDocument" class="tabular-nums">行 {{ cursorLine }} : {{ cursorColumn }}</span>
|
||||
<span v-if="store.kind === 'note'" class="rounded-sm bg-muted px-1.5 py-0.5 text-[10px]">
|
||||
{{ store.languageLabel }}
|
||||
</span>
|
||||
<span v-if="encodingLabel" class="uppercase">{{ encodingLabel }}</span>
|
||||
<span v-if="eolLabel">{{ eolLabel }}</span>
|
||||
<span class="ml-auto truncate">{{ store.fileDoc?.path || store.libraryRoot }}</span>
|
||||
</footer>
|
||||
|
||||
<!-- 快速打开(Ctrl+P) -->
|
||||
<QuickOpen v-model:open="quickOpen" @select="store.openNote($event)" />
|
||||
|
||||
<!-- 关闭确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="closeConfirmOpen"
|
||||
title="有未保存的改动"
|
||||
description="关闭窗口会丢失这些改动(自动保存会对未保存内容做最后一次尝试)。"
|
||||
confirm-text="保存并关闭"
|
||||
@confirm="forceClose"
|
||||
/>
|
||||
|
||||
<!-- 重载确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="externalConfirmOpen"
|
||||
title="重新载入将丢弃未保存的改动"
|
||||
description="磁盘上的版本会覆盖编辑器里的内容,你当前的改动无法恢复。"
|
||||
variant="danger"
|
||||
confirm-text="丢弃并重载"
|
||||
@confirm="reloadFromExternal"
|
||||
/>
|
||||
|
||||
<Toaster />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 窗口根容器:mica/acrylic 下透明,普通模式用不透明底色(--popup-bg 由 applyTheme 写入) */
|
||||
.notes-window {
|
||||
background: var(--popup-bg, var(--background));
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,218 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 反链面板:当前笔记的**出链**与**入链**。
|
||||
*
|
||||
* # 数据从哪来
|
||||
*
|
||||
* 全部来自 SQLite 索引的 `links` 表(写入索引时已把 `[[名字]]` 按 Obsidian 语义
|
||||
* 「全库按名解析」成库内相对路径)。因此这里不需要扫全库 —— 一次 `notes_backlinks`
|
||||
* 调用就把两侧都取回。
|
||||
*
|
||||
* # 未解析链接为什么值得显示
|
||||
*
|
||||
* `[[还不存在的笔记]]` 在 Obsidian 里是一个**新建入口**,不是错误。面板把它单独列在
|
||||
* 「未解析」分组下并允许一键创建 —— 这正是双链笔记「先写链接、后补内容」的用法。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ArrowUpRight, Link2, Link2Off, Loader2, RefreshCw } from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import type { NoteBacklinks, NoteLink } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前笔记的库内相对路径(空串 = 没有笔记,面板显示空态) */
|
||||
relPath: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 打开某篇笔记 */
|
||||
open: [relPath: string]
|
||||
/** 已用某个名字新建了一篇(未解析链接的一键创建);上层据此展开树 */
|
||||
create: [name: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const data = ref<NoteBacklinks | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
/** 已解析的出链 */
|
||||
const resolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.resolved)
|
||||
)
|
||||
/** 未解析的出链(可一键新建) */
|
||||
const unresolvedOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => !item.resolved && item.kind !== 'url')
|
||||
)
|
||||
/** 外部链接(`[](https://…)`):只展示不可跳转到库内 */
|
||||
const externalOutgoing = computed(() =>
|
||||
(data.value?.outgoing ?? []).filter(item => item.kind === 'url')
|
||||
)
|
||||
|
||||
async function load(): Promise<void> {
|
||||
if (!props.relPath) {
|
||||
data.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
data.value = await notesClient.backlinks(props.relPath)
|
||||
} catch (e) {
|
||||
// 索引还没建立时这里会失败:不是错误,只是「暂时没有数据」
|
||||
data.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.relPath, store.indexStats?.noteCount],
|
||||
() => void load(),
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
/** 点击未解析链接:按名字新建一篇(`createNote` 会顺带把它打开)。 */
|
||||
async function createMissing(link: NoteLink): Promise<void> {
|
||||
try {
|
||||
await store.createNote(currentDirOf(props.relPath), link.target)
|
||||
emit('create', link.target)
|
||||
await load()
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新笔记落在当前笔记所在目录(与 Obsidian「同目录优先」的习惯一致)。 */
|
||||
function currentDirOf(relPath: string): string {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
function targetOf(link: NoteLink): string {
|
||||
// URL 类型直接交给系统浏览器由上层处理;这里统一用 relPath(可能为空)
|
||||
return link.relPath || link.target
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<Link2 class="size-3" />
|
||||
<span>双链</span>
|
||||
<span class="ml-auto tabular-nums">
|
||||
被 {{ data?.incomingSources ?? 0 }} 篇引用 · 出链 {{ resolvedOutgoing.length + unresolvedOutgoing.length }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="刷新"
|
||||
@click="load"
|
||||
>
|
||||
<RefreshCw class="size-3" :class="loading && 'animate-spin'" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<div v-if="loading && !data" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在查询链接…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!relPath"
|
||||
variant="empty"
|
||||
title="未打开笔记"
|
||||
description="打开一篇笔记后这里会显示它的双链"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!data?.incoming.length && !data?.outgoing.length"
|
||||
variant="empty"
|
||||
title="还没有链接"
|
||||
description="在正文里写 [[另一篇笔记]],或在别处引用这篇"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<!-- 入链 -->
|
||||
<p v-if="data?.incoming.length" class="px-1 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase">
|
||||
被引用({{ data.incomingSources }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in data?.incoming ?? []"
|
||||
:key="`in-${link.relPath}-${link.target}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', link.relPath)"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
<span class="ml-auto shrink-0 truncate text-[10px] text-fg-disabled">{{ link.relPath }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 已解析出链 -->
|
||||
<p
|
||||
v-if="resolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
指向({{ resolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in resolvedOutgoing"
|
||||
:key="`out-${link.relPath}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', targetOf(link))"
|
||||
>
|
||||
<Link2 class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.title }}</span>
|
||||
</button>
|
||||
|
||||
<!-- 未解析出链(可一键新建) -->
|
||||
<p
|
||||
v-if="unresolvedOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
未解析({{ unresolvedOutgoing.length }})
|
||||
</p>
|
||||
<button
|
||||
v-for="link in unresolvedOutgoing"
|
||||
:key="`miss-${link.target}`"
|
||||
type="button"
|
||||
class="group flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-left text-xs text-muted-foreground transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
title="点击新建这篇笔记"
|
||||
@click="createMissing(link)"
|
||||
>
|
||||
<Link2Off class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
<span class="ml-auto shrink-0 text-[10px] opacity-0 group-hover:opacity-100">新建</span>
|
||||
</button>
|
||||
|
||||
<!-- 外部链接 -->
|
||||
<p
|
||||
v-if="externalOutgoing.length"
|
||||
class="px-1 pt-3 pb-1 text-[10px] font-medium tracking-wide text-fg-disabled uppercase"
|
||||
>
|
||||
外部链接({{ externalOutgoing.length }})
|
||||
</p>
|
||||
<a
|
||||
v-for="link in externalOutgoing"
|
||||
:key="`url-${link.target}`"
|
||||
class="flex w-full items-center gap-1.5 rounded-sm px-1 py-1 text-xs text-fg-secondary transition-colors duration-150 hover:bg-row-hover hover:text-foreground"
|
||||
:href="link.target"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
>
|
||||
<ArrowUpRight class="size-3 shrink-0 opacity-70" />
|
||||
<span class="truncate">{{ link.target }}</span>
|
||||
</a>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,245 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* CM6 编辑器宿主。
|
||||
*
|
||||
* 职责:装配 EditorView、把文档变更回写 store(含自动保存防抖)、
|
||||
* 按设置热重配置(主题/排版/行号/Live Preview 开关/语言)。
|
||||
*
|
||||
* # 编辑器实例为什么不是响应式的
|
||||
*
|
||||
* EditorView 存普通变量、不进 `ref`:把它放进 Vue 响应式系统会让整个 CM state 树
|
||||
* 被 Proxy 包一层,既慢又容易被误触发(CM6 的 state 是不可变对象,语义上就不该
|
||||
* 被 Vue 追踪)。
|
||||
*
|
||||
* # 「整篇替换」的判据是 docRevision,不是内容字符串
|
||||
*
|
||||
* 只比对内容会把用户自己的每一次输入也当成外部替换(光标被弹回行首);
|
||||
* 只比对路径又漏掉「同一篇被外部改动后重载」。因此用 store 里的自增
|
||||
* `docRevision`:只有在**整篇装载**(打开/重载)时才替换文档。
|
||||
*
|
||||
* # 语言是异步来的
|
||||
*
|
||||
* 语言包按需 `import()`(见 `editor/languages.ts`)。这里 watch 的是
|
||||
* `store.language`(一个 thunk),拿到后就地 `setLanguageExtension`;
|
||||
* 旧语言的过期结果由 store 里的令牌机制丢弃,这里不需要再判一次。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import {
|
||||
createEditorState,
|
||||
jumpToPosition,
|
||||
reconfigureEditor,
|
||||
replaceDoc,
|
||||
setLanguageExtension,
|
||||
type EditorConfig
|
||||
} from '../editor/core'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Extension } from '@codemirror/state'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
|
||||
const props = defineProps<{
|
||||
/** 应用当前是否深色(跟随应用主题时用于取深/浅变体) */
|
||||
isDark: boolean
|
||||
/** 是否启用 Live Preview */
|
||||
livePreview: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
/** 光标移动(行号 1 起,列号 1 起) */
|
||||
'cursor-moved': [line: number, column: number]
|
||||
/** 点击了 `[[wikilink]]`(`target` 是去掉 `#` 与别名后的笔记名) */
|
||||
'wikilink': [target: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const hostRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
let view: EditorView | null = null
|
||||
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
|
||||
/** 程序化替换文档期间抑制「变更 → 置脏」 */
|
||||
let applyingDoc = false
|
||||
/** 已应用的文档版本,避免重复整篇替换 */
|
||||
let appliedRevision = -1
|
||||
/** 语言令牌:丢弃过期的异步加载结果(与 store 里的令牌是两层保险) */
|
||||
let languageSeq = 0
|
||||
|
||||
function currentConfig(): EditorConfig {
|
||||
const s = store.settings
|
||||
const large = store.fileDoc?.large ?? false
|
||||
return {
|
||||
livePreview: props.livePreview,
|
||||
showLineNumbers: s.showLineNumbers,
|
||||
tabSize: s.tabSize,
|
||||
fontFamily: s.fontFamily,
|
||||
fontSize: s.fontSize,
|
||||
lineHeight: s.lineHeight,
|
||||
ligatures: s.ligatures,
|
||||
theme: String(s.editorTheme),
|
||||
followAppTheme: s.followAppTheme,
|
||||
isDark: props.isDark,
|
||||
// 初始语言留空:语言由 applyLanguage 单独设置(见下方 watch),
|
||||
// 放在这里会让每次 reconfigure 都把语言重置一遍(异步加载的结果被抹掉)
|
||||
language: () => null,
|
||||
largeFile: large,
|
||||
autocomplete: s.autocomplete,
|
||||
wikilink: s.wikilink && store.kind === 'note',
|
||||
onWikilink: target => emit('wikilink', target),
|
||||
// 图片预览只在库内笔记里有意义(库外文件没有库根上下文)
|
||||
currentRelPath: store.kind === 'note' ? store.currentRelPath : '',
|
||||
images: store.kind === 'note'
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleAutosave(): void {
|
||||
const ms = store.settings.autosaveMs
|
||||
if (!ms) return
|
||||
if (autosaveTimer) clearTimeout(autosaveTimer)
|
||||
autosaveTimer = setTimeout(() => {
|
||||
autosaveTimer = null
|
||||
void store.saveCurrent().catch(() => undefined)
|
||||
}, ms)
|
||||
}
|
||||
|
||||
function flushAutosave(): void {
|
||||
if (autosaveTimer) {
|
||||
clearTimeout(autosaveTimer)
|
||||
autosaveTimer = null
|
||||
}
|
||||
void store.saveCurrent().catch(() => undefined)
|
||||
}
|
||||
|
||||
/** 加载并应用当前文档的语言扩展。 */
|
||||
async function applyLanguage(seq: number): Promise<void> {
|
||||
if (!view) return
|
||||
let extension: Extension | null = null
|
||||
try {
|
||||
extension = await store.language()
|
||||
} catch (e) {
|
||||
logger.warn(`语言扩展加载失败:${String(e)}`)
|
||||
}
|
||||
// 期间用户又切了文档 → 这次结果作废
|
||||
if (seq !== languageSeq || !view) return
|
||||
setLanguageExtension(view, extension)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (!hostRef.value) return
|
||||
view = new EditorView({
|
||||
parent: hostRef.value,
|
||||
state: createEditorState({
|
||||
doc: store.content,
|
||||
config: currentConfig(),
|
||||
onDocChanged: doc => {
|
||||
if (applyingDoc) return
|
||||
store.setContent(doc)
|
||||
scheduleAutosave()
|
||||
},
|
||||
onSelectionChanged: (line, column) => emit('cursor-moved', line, column)
|
||||
})
|
||||
})
|
||||
appliedRevision = store.docRevision
|
||||
void applyLanguage(++languageSeq)
|
||||
})
|
||||
|
||||
/**
|
||||
* 整篇装载(打开笔记 / 打开文件 / 重载):替换文档。
|
||||
*
|
||||
* 用 `docRevision` 而不是路径:重载同一篇时路径没变,但内容必须被换掉。
|
||||
*/
|
||||
watch(
|
||||
() => store.docRevision,
|
||||
() => {
|
||||
if (!view) return
|
||||
if (autosaveTimer) {
|
||||
clearTimeout(autosaveTimer)
|
||||
autosaveTimer = null
|
||||
}
|
||||
if (appliedRevision === store.docRevision) return
|
||||
appliedRevision = store.docRevision
|
||||
applyingDoc = true
|
||||
replaceDoc(view, store.content)
|
||||
applyingDoc = false
|
||||
void applyLanguage(++languageSeq)
|
||||
}
|
||||
)
|
||||
|
||||
/** 语言变化(异步加载完成 / 切换到另一种语言)。 */
|
||||
watch(
|
||||
() => store.language,
|
||||
() => {
|
||||
void applyLanguage(++languageSeq)
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* 切换笔记:Live Preview 的图片预览按「相对当前笔记所在目录」解析目标,
|
||||
* 因此换一篇就要重建一次装饰(把新的 `currentRelPath` 交给它)。
|
||||
*
|
||||
* 只动 mode 与 wikilink 两个 compartment:语言由 `applyLanguage` 单独负责,
|
||||
* 在这里一并 reconfigure 会把刚异步加载好的语言重置掉。
|
||||
*/
|
||||
watch(
|
||||
() => store.currentRelPath,
|
||||
() => {
|
||||
if (!view) return
|
||||
try {
|
||||
reconfigureEditor(view, currentConfig())
|
||||
} catch (e) {
|
||||
logger.error(`切换笔记后重配置失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** 设置 / 深浅 / 视图模式 / 文档类型变化:热重配置,不重建编辑器。 */
|
||||
watch(
|
||||
() => [store.settings, props.isDark, props.livePreview, store.fileDoc?.large],
|
||||
() => {
|
||||
if (!view) return
|
||||
try {
|
||||
reconfigureEditor(view, currentConfig())
|
||||
} catch (e) {
|
||||
logger.error(`重配置编辑器失败:${String(e)}`)
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
flushAutosave()
|
||||
view?.destroy()
|
||||
view = null
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
focus: () => view?.focus(),
|
||||
getView: () => view,
|
||||
/** 大纲点击跳转 */
|
||||
jumpTo: (position: number) => {
|
||||
if (view) jumpToPosition(view, position)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="hostRef" class="notes-editor-host h-full min-h-0 overflow-hidden" />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.notes-editor-host :deep(.cm-editor) {
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
}
|
||||
.notes-editor-host :deep(.cm-scroller) {
|
||||
padding: 12px 8px 32px;
|
||||
overflow: auto;
|
||||
}
|
||||
.notes-editor-host :deep(.cm-editor.cm-focused) {
|
||||
outline: none;
|
||||
}
|
||||
/* 笔记正文里正文与标题之间留些气口,Live Preview 下更接近阅读视图 */
|
||||
.notes-editor-host :deep(.cm-content) {
|
||||
padding-bottom: 24vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,243 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 编辑器工具栏:格式化按钮 + 视图切换 + 保存 + 配色快切 + 打开文件。
|
||||
*
|
||||
* 格式化命令通过 `apply` 由父级(NotesWindow)转发到当前 EditorView ——
|
||||
* 工具栏本身不持有编辑器实例(实例在 EditorHost 内部,非响应式)。
|
||||
*
|
||||
* 控件尺寸与图标写法对齐项目约定:按钮图标显式 `size-3.5`、下拉用 `Select`。
|
||||
*
|
||||
* # 文件模式下藏掉 Markdown 格式按钮
|
||||
*
|
||||
* `.py` 文件里的「加粗 / 引用 / 任务列表」没有任何意义,留着只会让人以为按了
|
||||
* 会有用。因此按 `store.kind` 切换:笔记显示格式化组,文件显示「打开 / 快速打开 /
|
||||
* 编码与换行信息」,两者共用保存与配色。
|
||||
*/
|
||||
import {
|
||||
Bold,
|
||||
Code,
|
||||
Eye,
|
||||
FileDown,
|
||||
FileSearch,
|
||||
FolderOpen,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
Italic,
|
||||
Link,
|
||||
List,
|
||||
ListChecks,
|
||||
Loader2,
|
||||
Quote,
|
||||
Save,
|
||||
SquareCode,
|
||||
Strikethrough
|
||||
} from '@lucide/vue'
|
||||
import { ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { toast } from 'vue-sonner'
|
||||
import type { Command } from '@codemirror/view'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import { notesCommands } from '../editor/keymap'
|
||||
import { EDITOR_THEME_OPTIONS } from '../editor/themes'
|
||||
import type { NoteViewMode } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{
|
||||
apply: (command: Command) => void
|
||||
viewMode: NoteViewMode
|
||||
dirty: boolean
|
||||
saving: boolean
|
||||
name: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:viewMode': [value: NoteViewMode]
|
||||
save: []
|
||||
'open-file': []
|
||||
'quick-open': []
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const run = (command: Command) => props.apply(command)
|
||||
|
||||
const exporting = ref(false)
|
||||
|
||||
/**
|
||||
* 导出当前笔记为 HTML。
|
||||
*
|
||||
* 渲染链路(markdown-it + DOMPurify + highlight.js)**按需 import**:
|
||||
* 它约 1MB,而导出是低频动作 —— 静态引入会让「打开编辑器窗口」这个最常见的动作
|
||||
* 也背上这份体积。
|
||||
*/
|
||||
async function exportHtml(): Promise<void> {
|
||||
if (!store.currentRelPath) return
|
||||
exporting.value = true
|
||||
try {
|
||||
const doc = await notesClient.readNote(store.currentRelPath)
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
title: store.currentName || doc.name.replace(/\.md$/i, ''),
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: `${doc.name.replace(/\.md$/i, '')}.html`,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
const saved = await notesClient.exportNote(store.currentRelPath, html, dest)
|
||||
toast.success(`已导出:${saved}`)
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-3">
|
||||
<!-- 文档名 + 未保存标记 -->
|
||||
<div class="mr-2 flex min-w-0 items-center gap-1.5">
|
||||
<span class="truncate text-[13px] font-medium text-foreground">
|
||||
{{ name || '未打开文档' }}
|
||||
</span>
|
||||
<span
|
||||
v-if="dirty"
|
||||
class="size-1.5 shrink-0 rounded-full bg-primary"
|
||||
title="有未保存的改动"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<!-- ===== 笔记模式:Markdown 格式化 ===== -->
|
||||
<template v-if="store.kind === 'note'">
|
||||
<Button variant="ghost" size="icon-sm" title="加粗 (Ctrl+B)" @click="run(notesCommands.bold)">
|
||||
<Bold class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="斜体 (Ctrl+I)" @click="run(notesCommands.italic)">
|
||||
<Italic class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="删除线 (Ctrl+Shift+X)"
|
||||
@click="run(notesCommands.strikethrough)"
|
||||
>
|
||||
<Strikethrough class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="行内代码 (Ctrl+E)"
|
||||
@click="run(notesCommands.inlineCode)"
|
||||
>
|
||||
<Code class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="链接 (Ctrl+K)" @click="run(notesCommands.link)">
|
||||
<Link class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<Button variant="ghost" size="icon-sm" title="一级标题 (Ctrl+1)" @click="run(notesCommands.heading(1))">
|
||||
<Heading1 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="二级标题 (Ctrl+2)" @click="run(notesCommands.heading(2))">
|
||||
<Heading2 class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="三级标题 (Ctrl+3)" @click="run(notesCommands.heading(3))">
|
||||
<Heading3 class="size-3.5" />
|
||||
</Button>
|
||||
|
||||
<div class="h-4 w-px shrink-0 bg-divider" />
|
||||
|
||||
<Button variant="ghost" size="icon-sm" title="无序列表" @click="run(notesCommands.bulletList)">
|
||||
<List class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="任务列表" @click="run(notesCommands.taskList)">
|
||||
<ListChecks class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="引用" @click="run(notesCommands.quote)">
|
||||
<Quote class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="代码块 (Ctrl+Shift+C)" @click="run(notesCommands.codeBlock)">
|
||||
<SquareCode class="size-3.5" />
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<!-- ===== 文件模式 ===== -->
|
||||
<template v-else>
|
||||
<Button variant="ghost" size="sm" title="打开磁盘文件 (Ctrl+O)" @click="emit('open-file')">
|
||||
<FolderOpen class="size-3.5" />打开
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" title="快速打开 (Ctrl+P)" @click="emit('quick-open')">
|
||||
<FileSearch class="size-3.5" />快速打开
|
||||
</Button>
|
||||
</template>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-2">
|
||||
<!-- 导出当前笔记为 HTML(低频动作:渲染链路按需加载) -->
|
||||
<Button
|
||||
v-if="store.kind === 'note' && store.currentRelPath"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
:disabled="exporting"
|
||||
title="导出为独立 HTML(可离线打开或系统打印成 PDF)"
|
||||
@click="exportHtml"
|
||||
>
|
||||
<Loader2 v-if="exporting" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
导出
|
||||
</Button>
|
||||
<!-- 配色快切(与设置页同一份取值) -->
|
||||
<Select
|
||||
:model-value="String(store.settings.editorTheme)"
|
||||
@update:model-value="v => store.patchSettings({ editorTheme: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="h-7 w-40 text-xs"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in EDITOR_THEME_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<!-- 视图切换(只对 Markdown 有意义) -->
|
||||
<TooltipProvider v-if="store.kind === 'note'" :delay-duration="400">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="emit('update:viewMode', viewMode === 'wysiwyg' ? 'source' : 'wysiwyg')"
|
||||
>
|
||||
<Eye class="size-3.5" />
|
||||
{{ viewMode === 'wysiwyg' ? '所见即所得' : '源码' }}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">切换视图 (Ctrl+Shift+M)</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<Button variant="outline" size="sm" :disabled="!dirty || saving" @click="emit('save')">
|
||||
<Save class="size-3.5" />
|
||||
保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,314 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 导入 / 导出面板(主模块页「库」区)。
|
||||
*
|
||||
* # 三条链路,各自的风险点
|
||||
*
|
||||
* - **导入**:批量写库,唯一硬规则是「绝不覆盖」(重名加序号),选择即授权;
|
||||
* - **导出 HTML**:渲染在前端(`markdownExport`),落盘在后端 —— 后端不碰渲染、
|
||||
* 前端不碰文件系统,各自只做自己擅长且可审计的那一半;
|
||||
* - **导出 zip**:整库或某个目录打包,方便分享/迁移。
|
||||
*
|
||||
* # 为什么导出 HTML 的路径要用户选两次(先选笔记、再选保存位置)
|
||||
*
|
||||
* 批量导出(一次选目录、每篇一个 HTML)看起来更省事,但「一篇笔记配一个 assets 目录」
|
||||
* 的结构很难在浏览器里可靠实现(`<base>` 与相对路径在不同浏览器行为不一致)。
|
||||
* 这里只做**单篇 → 单文件**,路径语义清晰:导出文件和笔记在库内同级时相对路径依然有效。
|
||||
*/
|
||||
import { computed, ref } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { openPath } from '@tauri-apps/plugin-opener'
|
||||
import {
|
||||
FileDown,
|
||||
FileUp,
|
||||
FolderInput,
|
||||
FolderOutput,
|
||||
Loader2,
|
||||
NotebookPen
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { SettingRow } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
const busy = ref<'import' | 'export' | 'zip' | null>(null)
|
||||
|
||||
/**
|
||||
* 「当前打开的笔记」这个选项的哨兵值。
|
||||
*
|
||||
* **不能用空串**:reka-ui 的 `Select` 把空串保留给「清空选择、显示 placeholder」,
|
||||
* 放一个 `value=""` 的 `SelectItem` 会直接抛
|
||||
* 「A <SelectItem /> must have a value prop that is not an empty string」。
|
||||
* 用哨兵值 + 调用点翻译,比「把空串当合法值」更清楚:哨兵名本身就说明了语义。
|
||||
*/
|
||||
const CURRENT_NOTE = '__current__'
|
||||
/** 「整个库」这个选项的哨兵值(同上,空串留给 placeholder) */
|
||||
const WHOLE_LIBRARY = '__all__'
|
||||
|
||||
/** 导出 HTML 的目标笔记(`CURRENT_NOTE` = 当前打开的笔记) */
|
||||
const exportTarget = ref(CURRENT_NOTE)
|
||||
|
||||
/** 库内目录选项(导出 zip 时限定范围) */
|
||||
const dirOptions = computed(() => {
|
||||
const dirs = store.entries.filter(e => e.isDir).map(e => e.relPath)
|
||||
return [{ value: WHOLE_LIBRARY, label: '整个库' }, ...dirs.map(d => ({ value: d, label: d }))]
|
||||
})
|
||||
/** 导出 zip 的范围(`WHOLE_LIBRARY` = 整库) */
|
||||
const zipScope = ref(WHOLE_LIBRARY)
|
||||
|
||||
/**
|
||||
* 可导出的笔记。
|
||||
*
|
||||
* 当前笔记只作为**第一个选项**出现(而不是「空串代表当前」)—— 这样列表里每一项
|
||||
* 都有明确的值,用户也能在「当前笔记」与具体路径之间切换。
|
||||
*/
|
||||
const noteOptions = computed(() => {
|
||||
const files = store.entries.filter(e => !e.isDir)
|
||||
const options: Array<{ value: string; label: string }> = []
|
||||
if (store.currentRelPath) {
|
||||
options.push({ value: CURRENT_NOTE, label: `当前笔记(${store.currentName})` })
|
||||
}
|
||||
options.push(...files.map(f => ({ value: f.relPath, label: f.relPath })))
|
||||
return options
|
||||
})
|
||||
|
||||
/** 导入:文件 / 目录 / zip 都走同一个入口(后端按扩展名判别)。 */
|
||||
async function doImport(kind: 'file' | 'dir'): Promise<void> {
|
||||
try {
|
||||
const selected = await open(
|
||||
kind === 'dir'
|
||||
? { directory: true, multiple: false, title: '选择要导入的文件夹' }
|
||||
: {
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title: '选择要导入的文件或 zip',
|
||||
filters: [
|
||||
{ name: 'Markdown / Zip', extensions: ['md', 'markdown', 'zip'] },
|
||||
{ name: '全部文件', extensions: ['*'] }
|
||||
]
|
||||
}
|
||||
)
|
||||
if (typeof selected !== 'string') return
|
||||
busy.value = 'import'
|
||||
const report = await notesClient.import(selected, '')
|
||||
await store.refreshLibrary()
|
||||
await store.syncIndex()
|
||||
const renamed = report.renamed ? `,${report.renamed} 篇重名已加序号` : ''
|
||||
const skipped = report.skipped ? `,跳过 ${report.skipped} 个非笔记文件` : ''
|
||||
toast.success(`导入 ${report.imported} 个文件${renamed}${skipped}`)
|
||||
if (report.failures.length) {
|
||||
toast.warning(`${report.failures.length} 条失败:${report.failures[0]}`)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`导入失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出单篇 HTML:渲染在本地做,落盘交给后端。 */
|
||||
async function doExportHtml(): Promise<void> {
|
||||
// 哨兵值翻译成真实路径(见 `CURRENT_NOTE` 的说明)
|
||||
const relPath = exportTarget.value === CURRENT_NOTE ? store.currentRelPath : exportTarget.value
|
||||
if (!relPath) {
|
||||
toast.error(store.currentRelPath ? '请先选择要导出的笔记' : '请先在编辑器里打开一篇笔记')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const doc = await notesClient.readNote(relPath)
|
||||
// **动态引入**:`markdownExport` 会拉进 markdown-it + DOMPurify + highlight.js
|
||||
// (实测约 1MB),而导出是低频动作。静态引入会让「笔记」模块页一打开就下载
|
||||
// 这三个包(chunk 从 ~130kB 涨到 1.1MB),把首屏拖垮。
|
||||
const { renderNoteHtml } = await import('../editor/markdownExport')
|
||||
const html = renderNoteHtml({
|
||||
// 标题用笔记自己的显示名,而不是「当前笔记」那个下拉标签
|
||||
title: doc.name.replace(/\.md$/i, ''),
|
||||
fileName: doc.name,
|
||||
markdown: doc.content,
|
||||
highlight: store.settings.exportHighlight
|
||||
})
|
||||
const suggested = doc.name.replace(/\.md$/i, '') + '.html'
|
||||
const dest = await open({
|
||||
title: '导出为 HTML',
|
||||
defaultPath: suggested,
|
||||
filters: [{ name: 'HTML 文件', extensions: ['html'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'export'
|
||||
const saved = await notesClient.exportNote(relPath, html, dest)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开', onClick: () => void openPath(saved) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出 zip(整库或某个目录)。 */
|
||||
async function doExportZip(): Promise<void> {
|
||||
try {
|
||||
// 哨兵值翻译:`WHOLE_LIBRARY` → 不传范围(后端按「整库」处理)
|
||||
const scope = zipScope.value === WHOLE_LIBRARY ? '' : zipScope.value
|
||||
const scopeLabel = scope ? scope.replace(/\//g, '-') : 'thing-notes'
|
||||
const dest = await open({
|
||||
title: '导出 zip',
|
||||
defaultPath: `${scopeLabel}.zip`,
|
||||
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
busy.value = 'zip'
|
||||
const saved = await notesClient.exportZip(dest, scope || undefined)
|
||||
toast.success(`已导出:${saved}`, {
|
||||
action: { label: '打开目录', onClick: () => void openPath(saved.replace(/[\\/][^\\/]+$/, '')) }
|
||||
})
|
||||
} catch (e) {
|
||||
toast.error(`导出失败:${String(e)}`)
|
||||
} finally {
|
||||
busy.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 把内置模板写到库内 `templates/`,方便用户直接改。 */
|
||||
async function exportTemplates(): Promise<void> {
|
||||
try {
|
||||
const written = await store.exportBuiltinTemplates()
|
||||
if (written.length) {
|
||||
toast.success(`已写入 ${written.length} 个内置模板到 templates/`)
|
||||
} else {
|
||||
toast.info('templates/ 里已有这些模板,未覆盖')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`写入模板失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- ===== 导入 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileUp class="size-4 text-primary" />
|
||||
导入
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
导入 Markdown 目录 / 单文件 / zip 包。**同名笔记不会被覆盖**,会自动加序号;
|
||||
图片等附件进 <code class="font-mono">assets/</code>,其它类型文件忽略。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导入文件夹" description="保留子目录结构,跳过隐藏目录与 __MACOSX">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!!busy"
|
||||
@click="doImport('dir')"
|
||||
>
|
||||
<Loader2 v-if="busy === 'import'" class="size-3.5 animate-spin" />
|
||||
<FolderInput v-else class="size-3.5" />
|
||||
选择文件夹
|
||||
</Button>
|
||||
</SettingRow>
|
||||
<SettingRow label="导入文件 / zip" description="单个 .md 或一个压缩包">
|
||||
<Button variant="outline" size="sm" :disabled="!!busy" @click="doImport('file')">
|
||||
<FileUp class="size-3.5" />选择文件
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 导出 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FileDown class="size-4 text-primary" />
|
||||
导出
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
HTML 为**单文件、零外链**(样式内联),可离线双击打开或直接用系统打印成 PDF;
|
||||
正文经过消毒,笔记里嵌的脚本不会被执行。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="导出笔记" description="Markdown → 独立 HTML" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="exportTarget">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in noteOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportHtml"
|
||||
>
|
||||
<Loader2 v-if="busy === 'export'" class="size-3.5 animate-spin" />
|
||||
<FileDown v-else class="size-3.5" />
|
||||
导出 HTML
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="导出 zip" description="整库或某个目录(含 assets/,不含 .notes/)" control-width="wide">
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<Select v-model="zipScope">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in dirOptions" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="self-start"
|
||||
:disabled="!!busy"
|
||||
@click="doExportZip"
|
||||
>
|
||||
<Loader2 v-if="busy === 'zip'" class="size-3.5 animate-spin" />
|
||||
<FolderOutput v-else class="size-3.5" />
|
||||
导出 zip
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="内置模板"
|
||||
description="把日记 / 会议纪要等内置模板写到库内 templates/,改完即刻生效"
|
||||
>
|
||||
<Button variant="outline" size="sm" @click="exportTemplates">
|
||||
<NotebookPen class="size-3.5" />写入 templates/
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 说明:导入目标目录固定为库根(保持与 zip 内结构一致),因此这里只给提示 -->
|
||||
<p class="px-1 text-[11px] text-muted-foreground">
|
||||
提示:导入的笔记都落在库根下(保留源目录结构)。想放到别处,导入后拖到目标目录即可。
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,466 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记库侧栏:目录树 / 全文检索 / 大纲 三视图 + 新建/重命名/删除 + 最近打开。
|
||||
*
|
||||
* 版式对齐终端「文件管理器」的 `FilePane`(同类场景:独立窗口里的分栏列表):
|
||||
* - 局部滚动一律用 `ScrollArea`(不写原生 `overflow-y-auto`,见 UI_DESIGN_SYSTEM §3.2)
|
||||
* - 选中态 `bg-row-selected` / hover 态 `hover:bg-row-hover`(两态不混用同一色)
|
||||
* - 紧凑输入 `h-7 text-xs`(与 FilePane 的筛选框一致)
|
||||
* - 空态用 `StateBlock`,不手写占位文案
|
||||
*
|
||||
* 树用「展开集合 + 扁平化」渲染,而不是递归子组件 —— 扁平列表能把过滤
|
||||
* (只保留命中项及其祖先)一并做掉。
|
||||
*
|
||||
* # 三视图为什么在同一个侧栏里切换
|
||||
*
|
||||
* 目录树 / 检索 / 大纲三者是**同一时刻只需一个**的导航手段,各自单开一个面板会
|
||||
* 把编辑器挤窄。用分段导航切换既省宽度,也让「我在找什么」始终只有一个答案。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
FilePlus,
|
||||
FileText,
|
||||
Folder,
|
||||
FolderPlus,
|
||||
Link2,
|
||||
ListTree,
|
||||
Loader2,
|
||||
Pencil,
|
||||
RotateCw,
|
||||
Search,
|
||||
Trash2,
|
||||
X
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { ConfirmDialog, SegmentedNav, StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import type { LibraryEntry, LibraryTreeNode } from '@/types/notes'
|
||||
import SearchPanel from './SearchPanel.vue'
|
||||
import MarkdownOutline from './MarkdownOutline.vue'
|
||||
import BacklinksPanel from './BacklinksPanel.vue'
|
||||
import NewNoteDialog from './NewNoteDialog.vue'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string]; jump: [from: number] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 侧栏视图 */
|
||||
const view = ref<'files' | 'search' | 'outline' | 'links'>('files')
|
||||
/** 已展开的目录 */
|
||||
const expanded = ref<Set<string>>(new Set())
|
||||
/** 名称过滤 */
|
||||
const filter = ref('')
|
||||
/** 当前选中的目录(新建目标;空串 = 库根) */
|
||||
const selectedDir = ref('')
|
||||
/** 编辑器光标行(大纲高亮用;由 NotesWindow 传入) */
|
||||
const cursorLine = ref(0)
|
||||
|
||||
defineExpose({
|
||||
/** 由 NotesWindow 在光标移动时调用 */
|
||||
setCursorLine: (line: number) => {
|
||||
cursorLine.value = line
|
||||
},
|
||||
/** 由 NotesWindow 在快捷键触发时调用 */
|
||||
showSearch: () => {
|
||||
view.value = 'search'
|
||||
},
|
||||
showOutline: () => {
|
||||
view.value = 'outline'
|
||||
},
|
||||
showFiles: () => {
|
||||
view.value = 'files'
|
||||
},
|
||||
/** 由 NotesWindow 在 Ctrl+Shift+N 时调用 */
|
||||
showNewNote: () => {
|
||||
view.value = 'files'
|
||||
void startNewNote()
|
||||
}
|
||||
})
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ value: 'files', label: '文件', icon: FileText },
|
||||
{ value: 'search', label: '检索', icon: Search },
|
||||
{ value: 'outline', label: '大纲', icon: ListTree },
|
||||
{ value: 'links', label: '双链', icon: Link2 }
|
||||
]
|
||||
|
||||
// ===== 扁平化 + 过滤 =====
|
||||
const flatNodes = computed(() => {
|
||||
const keyword = filter.value.trim().toLowerCase()
|
||||
const out: Array<{ entry: LibraryEntry; depth: number }> = []
|
||||
|
||||
const matches = (node: LibraryTreeNode): boolean => {
|
||||
if (!keyword) return true
|
||||
if (node.entry.name.toLowerCase().includes(keyword)) return true
|
||||
return node.children.some(matches)
|
||||
}
|
||||
|
||||
const walk = (nodes: LibraryTreeNode[], depth: number) => {
|
||||
for (const node of nodes) {
|
||||
if (!matches(node)) continue
|
||||
out.push({ entry: node.entry, depth })
|
||||
const open = expanded.value.has(node.entry.relPath) || !!keyword
|
||||
if (node.entry.isDir && open) walk(node.children, depth + 1)
|
||||
}
|
||||
}
|
||||
walk(store.tree, 0)
|
||||
return out
|
||||
})
|
||||
|
||||
watch(
|
||||
() => store.currentRelPath,
|
||||
relPath => {
|
||||
if (!relPath) return
|
||||
// 展开当前笔记的所有祖先目录,保证选中项可见
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
let prefix = ''
|
||||
const next = new Set(expanded.value)
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const isExpanded = (relPath: string) => expanded.value.has(relPath)
|
||||
|
||||
const toggleDir = (entry: LibraryEntry) => {
|
||||
const next = new Set(expanded.value)
|
||||
if (next.has(entry.relPath)) next.delete(entry.relPath)
|
||||
else next.add(entry.relPath)
|
||||
expanded.value = next
|
||||
selectedDir.value = entry.relPath
|
||||
}
|
||||
|
||||
const onRowClick = (entry: LibraryEntry) => {
|
||||
if (entry.isDir) {
|
||||
toggleDir(entry)
|
||||
return
|
||||
}
|
||||
emit('open', entry.relPath)
|
||||
}
|
||||
|
||||
const targetLabel = computed(() => (selectedDir.value ? selectedDir.value : '库根'))
|
||||
|
||||
// ===== 新建笔记(走带模板选择的对话框) =====
|
||||
const newNoteOpen = ref(false)
|
||||
|
||||
/**
|
||||
* 新建笔记入口。
|
||||
*
|
||||
* `showTemplatePicker` 关闭时**跳过对话框**,用「未命名」+ 上次的模板直接建 ——
|
||||
* 这是「快速记一笔」的路径,多一个对话框就多一次打断。名字建好后可以就地重命名。
|
||||
*/
|
||||
async function startNewNote(): Promise<void> {
|
||||
if (store.settings.showTemplatePicker) {
|
||||
newNoteOpen.value = true
|
||||
return
|
||||
}
|
||||
try {
|
||||
const stamp = new Date()
|
||||
const name = `未命名 ${stamp.getHours()}${String(stamp.getMinutes()).padStart(2, '0')}`
|
||||
await store.createNote(selectedDir.value, name, store.lastTemplateId || undefined)
|
||||
if (store.currentRelPath) revealNote(store.currentRelPath)
|
||||
} catch (e) {
|
||||
toast.error(`新建失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 新建完成后展开新笔记的祖先目录,让它在树里可见 */
|
||||
function revealNote(relPath: string): void {
|
||||
const parts = relPath.split('/')
|
||||
parts.pop()
|
||||
const next = new Set(expanded.value)
|
||||
let prefix = ''
|
||||
for (const part of parts) {
|
||||
prefix = prefix ? `${prefix}/${part}` : part
|
||||
next.add(prefix)
|
||||
}
|
||||
expanded.value = next
|
||||
view.value = 'files'
|
||||
}
|
||||
|
||||
function onCreated(relPath: string): void {
|
||||
revealNote(relPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 反链面板里点了「未解析链接」→ 已按名字新建了一篇。
|
||||
*
|
||||
* 新建动作由面板内部完成(它知道 link 的原始名字),这里只负责把树展开到新笔记、
|
||||
* 并把它打开 —— 面板不持有「打开哪一篇」的知识,`store.currentRelPath` 由
|
||||
* `createNote` 自己更新。
|
||||
*/
|
||||
function onLinkCreated(): void {
|
||||
if (store.currentRelPath) revealNote(store.currentRelPath)
|
||||
}
|
||||
|
||||
// ===== 名称输入对话框(新建文件夹 / 重命名) =====
|
||||
type PromptMode = 'folder' | 'rename'
|
||||
const promptOpen = ref(false)
|
||||
const promptMode = ref<PromptMode>('folder')
|
||||
const promptValue = ref('')
|
||||
const promptTarget = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const promptTitle = computed(() => (promptMode.value === 'folder' ? '新建文件夹' : '重命名'))
|
||||
|
||||
function openPrompt(mode: PromptMode, target: string, initial = '') {
|
||||
promptMode.value = mode
|
||||
promptTarget.value = target
|
||||
promptValue.value = initial
|
||||
promptOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmPrompt() {
|
||||
const name = promptValue.value.trim()
|
||||
if (!name) {
|
||||
toast.error('名称不能为空')
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (promptMode.value === 'folder') {
|
||||
await store.createFolder(selectedDir.value, name)
|
||||
} else {
|
||||
await store.renameEntry(promptTarget.value, name)
|
||||
}
|
||||
promptOpen.value = false
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 删除确认 =====
|
||||
const confirmOpen = ref(false)
|
||||
const deleteTarget = ref<LibraryEntry | null>(null)
|
||||
|
||||
function askDelete(entry: LibraryEntry) {
|
||||
deleteTarget.value = entry
|
||||
confirmOpen.value = true
|
||||
}
|
||||
|
||||
async function doDelete() {
|
||||
const entry = deleteTarget.value
|
||||
if (!entry) return
|
||||
try {
|
||||
await store.deleteEntry(entry.relPath)
|
||||
toast.success(`已删除「${entry.name}」`)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
confirmOpen.value = false
|
||||
deleteTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function rebuildIndex(): Promise<void> {
|
||||
await store.rebuildIndex()
|
||||
await store.refreshLibrary()
|
||||
toast.success('索引已重建')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="flex h-full min-h-0 w-64 shrink-0 flex-col border-r border-border">
|
||||
<!-- 头部操作 -->
|
||||
<div class="flex h-11 shrink-0 items-center gap-1 border-b border-border px-2">
|
||||
<span class="ml-1 text-[13px] font-medium text-foreground">笔记库</span>
|
||||
<div class="ml-auto flex items-center gap-0.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.settings.showTemplatePicker ? '新建笔记(可选模板)' : '新建笔记'"
|
||||
@click="startNewNote"
|
||||
>
|
||||
<FilePlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="新建文件夹" @click="openPrompt('folder', selectedDir)">
|
||||
<FolderPlus class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:title="store.indexing ? '正在重建索引…' : '重建索引'"
|
||||
:disabled="store.indexing"
|
||||
@click="rebuildIndex"
|
||||
>
|
||||
<RotateCw class="size-3.5" :class="store.indexing && 'animate-spin'" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视图切换 -->
|
||||
<div class="shrink-0 px-2 pt-2">
|
||||
<SegmentedNav v-model="view" :items="NAV_ITEMS" block />
|
||||
</div>
|
||||
|
||||
<!-- ===== 文件视图 ===== -->
|
||||
<template v-if="view === 'files'">
|
||||
<div class="shrink-0 px-2 py-2">
|
||||
<div class="relative">
|
||||
<Input v-model="filter" placeholder="按名称过滤…" class="h-7 pr-6 text-xs" />
|
||||
<button
|
||||
v-if="filter"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="filter = ''"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1.5 px-0.5 text-[11px] text-muted-foreground">
|
||||
新建目标:<span class="text-fg-secondary">{{ targetLabel }}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 pb-2">
|
||||
<div v-if="store.loading" class="flex items-center justify-center gap-2 p-4">
|
||||
<Loader2 class="size-3.5 animate-spin text-muted-foreground" />
|
||||
<span class="text-xs text-muted-foreground">正在扫描库…</span>
|
||||
</div>
|
||||
|
||||
<StateBlock
|
||||
v-else-if="!flatNodes.length"
|
||||
variant="empty"
|
||||
:title="filter ? '没有匹配的笔记' : '笔记库为空'"
|
||||
:description="filter ? undefined : '点上方按钮新建第一篇笔记'"
|
||||
:min-height="140"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="item in flatNodes"
|
||||
:key="item.entry.relPath"
|
||||
class="group flex h-7 cursor-pointer items-center gap-1 rounded-sm pr-1 transition-colors duration-150"
|
||||
:class="
|
||||
store.currentRelPath === item.entry.relPath
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${item.depth * 12 + 4}px` }"
|
||||
@click="onRowClick(item.entry)"
|
||||
>
|
||||
<component
|
||||
:is="
|
||||
item.entry.isDir
|
||||
? isExpanded(item.entry.relPath)
|
||||
? ChevronDown
|
||||
: ChevronRight
|
||||
: FileText
|
||||
"
|
||||
class="size-3.5 shrink-0 opacity-70"
|
||||
/>
|
||||
<Folder v-if="item.entry.isDir" class="size-3.5 shrink-0 opacity-80" />
|
||||
<span class="truncate">{{ item.entry.name }}</span>
|
||||
|
||||
<div class="ml-auto flex shrink-0 items-center gap-0.5 opacity-0 group-hover:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="重命名"
|
||||
@click.stop="openPrompt('rename', item.entry.relPath, item.entry.name)"
|
||||
>
|
||||
<Pencil class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-sm p-0.5 hover:bg-active"
|
||||
title="删除"
|
||||
@click.stop="askDelete(item.entry)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<!-- 最近打开 -->
|
||||
<div v-if="store.recent.length" class="shrink-0 border-t border-border px-2 py-2">
|
||||
<p class="px-0.5 pb-1 text-[11px] font-medium text-muted-foreground">最近打开</p>
|
||||
<ScrollArea class="max-h-32">
|
||||
<div class="px-0.5">
|
||||
<button
|
||||
v-for="item in store.recent"
|
||||
:key="item.relPath"
|
||||
type="button"
|
||||
class="flex h-6 w-full items-center truncate rounded-sm px-1 text-left text-xs text-fg-secondary hover:bg-row-hover hover:text-foreground"
|
||||
@click="emit('open', item.relPath)"
|
||||
>
|
||||
{{ item.name.replace(/\.md$/i, '') }}
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ===== 检索视图 ===== -->
|
||||
<SearchPanel v-else-if="view === 'search'" class="min-h-0 flex-1" @open="emit('open', $event)" />
|
||||
|
||||
<!-- ===== 大纲视图 ===== -->
|
||||
<MarkdownOutline
|
||||
v-else-if="view === 'outline'"
|
||||
class="min-h-0 flex-1"
|
||||
:cursor-line="cursorLine"
|
||||
@jump="emit('jump', $event)"
|
||||
/>
|
||||
|
||||
<!-- ===== 双链视图 ===== -->
|
||||
<BacklinksPanel
|
||||
v-else
|
||||
class="min-h-0 flex-1"
|
||||
:rel-path="store.currentRelPath"
|
||||
@open="emit('open', $event)"
|
||||
@create="onLinkCreated"
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<!-- 名称输入对话框 -->
|
||||
<Dialog :open="promptOpen" @update:open="promptOpen = $event">
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{{ promptTitle }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
v-model="promptValue"
|
||||
:placeholder="promptMode === 'folder' ? '文件夹名称' : '名称'"
|
||||
@keydown.enter="confirmPrompt"
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="promptOpen = false">取消</Button>
|
||||
<Button :disabled="busy" @click="confirmPrompt">确定</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<!-- 删除确认 -->
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="删除确认"
|
||||
variant="danger"
|
||||
confirm-text="删除"
|
||||
:description="
|
||||
deleteTarget?.isDir
|
||||
? `将删除文件夹「${deleteTarget?.name}」及其全部内容,此操作不可撤销。`
|
||||
: `将删除「${deleteTarget?.name}」,此操作不可撤销。`
|
||||
"
|
||||
@confirm="doDelete"
|
||||
/>
|
||||
|
||||
<!-- 新建笔记(名称 + 模板) -->
|
||||
<NewNoteDialog v-model:open="newNoteOpen" :dir-rel="selectedDir" @created="onCreated" />
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 笔记大纲(标题树)。
|
||||
*
|
||||
* 结构与渲染分离:标题提取是纯函数 `extractOutline`(可单测,见 `editor/outline.ts`),
|
||||
* 本组件只负责「层级缩进 + 当前标题高亮 + 点击跳转」。
|
||||
*
|
||||
* # 当前标题怎么算
|
||||
*
|
||||
* 用编辑器的光标行号(由 `NotesWindow` 通过 props 传入)与标题行号比较,取
|
||||
* 「最后一个行号 ≤ 光标行」的标题。**不用滚动位置**:Live Preview 下装饰会让
|
||||
* 每行高度不一致,按像素反推当前标题很容易差一行,而光标位置是精确的。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import { Hash, ListTree } from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 编辑器当前光标所在行(1 起;0 = 未知) */
|
||||
cursorLine: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ jump: [from: number] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 最浅一级标题的层级(让缩进从 0 开始,而不是每篇都从 h2 缩进一档) */
|
||||
const minLevel = computed(() =>
|
||||
store.outline.reduce((min, item) => Math.min(min, item.level), 6)
|
||||
)
|
||||
|
||||
const currentIndex = computed(() => {
|
||||
if (!props.cursorLine) return -1
|
||||
let found = -1
|
||||
for (let index = 0; index < store.outline.length; index++) {
|
||||
const heading = store.outline[index]
|
||||
if (heading && heading.line <= props.cursorLine) found = index
|
||||
else break
|
||||
}
|
||||
return found
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex h-6 shrink-0 items-center gap-1.5 border-b border-border px-2 text-[11px] text-muted-foreground">
|
||||
<ListTree class="size-3" />
|
||||
<span>大纲</span>
|
||||
<span class="ml-auto tabular-nums">{{ store.outline.length }} 个标题</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<StateBlock
|
||||
v-if="!store.outline.length"
|
||||
variant="empty"
|
||||
title="还没有标题"
|
||||
description="用 # 开头写一行标题,这里会自动生成大纲"
|
||||
:min-height="120"
|
||||
/>
|
||||
<button
|
||||
v-for="(heading, index) in store.outline"
|
||||
:key="`${heading.line}-${heading.from}`"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1 rounded-sm py-1 pr-1 text-left text-xs transition-colors duration-150"
|
||||
:class="
|
||||
index === currentIndex
|
||||
? 'bg-row-selected text-primary-soft-text'
|
||||
: 'text-fg-secondary hover:bg-row-hover hover:text-foreground'
|
||||
"
|
||||
:style="{ paddingLeft: `${(heading.level - minLevel) * 12 + 6}px` }"
|
||||
@click="emit('jump', heading.from)"
|
||||
>
|
||||
<Hash class="size-3 shrink-0 opacity-60" />
|
||||
<span class="truncate" :class="heading.level <= 2 ? 'font-medium' : ''">
|
||||
{{ heading.text || '(空标题)' }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 新建笔记对话框(名称 + 模板)。
|
||||
*
|
||||
* # 为什么把模板选择放进「新建」而不是设置页
|
||||
*
|
||||
* 模板是**每次新建时的决策**(今天写日记、明天写会议纪要),把它藏在设置里意味着
|
||||
* 用户得先改设置再新建、改两次。这里做成对话框里的一个下拉:默认选中上次用过的那个,
|
||||
* 一路回车就能建。
|
||||
*
|
||||
* # 名称即标题
|
||||
*
|
||||
* 输入的名称同时作为文件名与 front-matter 里的 `title`。不额外要一个「标题」字段:
|
||||
* 「文件名和标题不一样」在文件即真相的模型里只会带来困惑(重命名文件后标题不同步)。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { NotebookPen } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** 新建目标目录(库内相对路径,空串 = 库根) */
|
||||
dirRel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
created: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const name = ref('')
|
||||
const templateId = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
const dirLabel = computed(() => props.dirRel || '库根')
|
||||
|
||||
/** 默认选中:上次用过的模板 → 空白笔记 → 第一个可用模板 */
|
||||
function pickDefaultTemplate(): void {
|
||||
if (templateId.value) return
|
||||
if (store.lastTemplateId && store.templates.some(t => t.id === store.lastTemplateId)) {
|
||||
templateId.value = store.lastTemplateId
|
||||
return
|
||||
}
|
||||
const blank = store.templates.find(t => t.name === '空白笔记')
|
||||
templateId.value = blank?.id ?? store.templates[0]?.id ?? ''
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
name.value = ''
|
||||
busy.value = false
|
||||
if (!store.templates.length) await store.loadTemplates()
|
||||
pickDefaultTemplate()
|
||||
}
|
||||
)
|
||||
|
||||
async function confirm(): Promise<void> {
|
||||
const title = name.value.trim()
|
||||
if (!title) return
|
||||
busy.value = true
|
||||
try {
|
||||
await store.createNote(props.dirRel, title, templateId.value || undefined)
|
||||
emit('created', store.currentRelPath)
|
||||
emit('update:open', false)
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="emit('update:open', $event)">
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建笔记</DialogTitle>
|
||||
<DialogDescription>
|
||||
目标目录:{{ dirLabel }} · 名称同时作为文件名与 front-matter 的 title
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div class="flex flex-col gap-3">
|
||||
<Input
|
||||
v-model="name"
|
||||
placeholder="笔记名称"
|
||||
autofocus
|
||||
@keydown.enter="confirm"
|
||||
/>
|
||||
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-xs text-muted-foreground">模板</span>
|
||||
<Select v-model="templateId">
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="item in store.templates" :key="item.id" :value="item.id">
|
||||
{{ item.name }}{{ item.builtin ? '(内置)' : '' }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span
|
||||
v-if="store.templates.find(t => t.id === templateId)?.description"
|
||||
class="line-clamp-2 text-[11px] text-muted-foreground"
|
||||
>
|
||||
{{ store.templates.find(t => t.id === templateId)?.description }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" :disabled="busy" @click="emit('update:open', false)">取消</Button>
|
||||
<Button :disabled="busy || !name.trim()" @click="confirm">
|
||||
<NotebookPen class="size-3.5" />新建
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,185 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 快速打开(`Ctrl+P`):库内文件跳转,类 VS Code。
|
||||
*
|
||||
* # 为什么在本地过滤而不是每次都查后端
|
||||
*
|
||||
* 库内笔记清单在打开面板时一次性取回(上限 1000 条,`notes_list_notes`),
|
||||
* 之后的每一次按键都只是对这份内存清单做子串匹配。这样输入零延迟 —— 而「按关键词
|
||||
* 找文件」本来就是模糊匹配,走 FTS5 反而会因为分词器把文件名切碎而给出意外结果
|
||||
* (FTS 是给正文用的)。
|
||||
*
|
||||
* # 排序:连续匹配 > 前缀 > 词首 > 位置靠前
|
||||
*
|
||||
* 单纯按「是否包含」排序会让 `笔记.md` 与 `我的笔记归档.md` 并列,用户真正想找的
|
||||
* 通常是名字更短、匹配更靠前的那个。这里用一个小的评分函数把「匹配质量」显式化,
|
||||
* 而不是依赖清单的顺序。
|
||||
*/
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { CornerDownLeft, FileText, Search } from '@lucide/vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import type { NoteSearchHit } from '@/types/notes'
|
||||
|
||||
const props = defineProps<{ open: boolean }>()
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
select: [relPath: string]
|
||||
}>()
|
||||
|
||||
const store = useNotesStore()
|
||||
const keyword = ref('')
|
||||
const active = ref(0)
|
||||
const panelRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
/** 输入框聚焦:`Input` 是对 reka-ui 的包装,不保证暴露内部 `<input>`,直接查 DOM。 */
|
||||
async function focusInput(): Promise<void> {
|
||||
await nextTick()
|
||||
panelRef.value?.querySelector('input')?.focus()
|
||||
}
|
||||
|
||||
/** 匹配质量评分(越小越靠前)。 */
|
||||
function score(hit: NoteSearchHit, needle: string): number {
|
||||
const title = hit.title.toLowerCase()
|
||||
const path = hit.relPath.toLowerCase()
|
||||
const at = title.indexOf(needle)
|
||||
if (at === 0) return 0
|
||||
if (at > 0) return 1
|
||||
if (path.includes(`/${needle}`)) return 2
|
||||
if (path.includes(needle)) return 3
|
||||
return 99
|
||||
}
|
||||
|
||||
const results = computed<NoteSearchHit[]>(() => {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return store.quickOpenList.slice(0, 200)
|
||||
return store.quickOpenList
|
||||
.map(hit => ({ hit, rank: score(hit, needle) }))
|
||||
.filter(item => item.rank < 99)
|
||||
.sort((a, b) => a.rank - b.rank || b.hit.modified - a.hit.modified)
|
||||
.slice(0, 200)
|
||||
.map(item => item.hit)
|
||||
})
|
||||
|
||||
/** 标题里命中关键词的位置(渲染高亮用)。 */
|
||||
function titleParts(hit: NoteSearchHit): Array<{ text: string; hit: boolean }> {
|
||||
const needle = keyword.value.trim().toLowerCase()
|
||||
if (!needle) return [{ text: hit.title, hit: false }]
|
||||
const at = hit.title.toLowerCase().indexOf(needle)
|
||||
if (at < 0) return [{ text: hit.title, hit: false }]
|
||||
return [
|
||||
{ text: hit.title.slice(0, at), hit: false },
|
||||
{ text: hit.title.slice(at, at + needle.length), hit: true },
|
||||
{ text: hit.title.slice(at + needle.length), hit: false }
|
||||
].filter(part => part.text.length > 0)
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function choose(hit: NoteSearchHit | undefined): void {
|
||||
if (!hit) return
|
||||
emit('select', hit.relPath)
|
||||
close()
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'ArrowDown') {
|
||||
event.preventDefault()
|
||||
active.value = Math.min(active.value + 1, results.value.length - 1)
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
event.preventDefault()
|
||||
active.value = Math.max(active.value - 1, 0)
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
choose(results.value[active.value])
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async open => {
|
||||
if (!open) return
|
||||
keyword.value = ''
|
||||
active.value = 0
|
||||
await store.loadQuickOpen()
|
||||
await focusInput()
|
||||
}
|
||||
)
|
||||
|
||||
watch(keyword, () => {
|
||||
active.value = 0
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition
|
||||
enter-active-class="transition-opacity duration-150"
|
||||
leave-active-class="transition-opacity duration-150"
|
||||
enter-from-class="opacity-0"
|
||||
leave-to-class="opacity-0"
|
||||
>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-start justify-center bg-black/40 pt-[12vh]"
|
||||
@click.self="close"
|
||||
>
|
||||
<div
|
||||
ref="panelRef"
|
||||
class="flex max-h-[60vh] w-[min(560px,92vw)] flex-col overflow-hidden rounded-lg border border-border bg-popup shadow-lg"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<div class="relative shrink-0 border-b border-border p-2">
|
||||
<Search class="absolute top-1/2 left-4 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="keyword"
|
||||
placeholder="按名称跳转到笔记…"
|
||||
class="h-8 border-0 bg-transparent pl-7 text-[13px] shadow-none focus-visible:ring-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="p-1">
|
||||
<StateBlock
|
||||
v-if="!results.length"
|
||||
variant="empty"
|
||||
title="没有匹配的笔记"
|
||||
:min-height="100"
|
||||
/>
|
||||
<button
|
||||
v-for="(hit, index) in results"
|
||||
:key="hit.relPath"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left"
|
||||
:class="index === active ? 'bg-row-selected text-primary-soft-text' : 'hover:bg-row-hover'"
|
||||
@mouseenter="active = index"
|
||||
@click="choose(hit)"
|
||||
>
|
||||
<FileText class="size-3.5 shrink-0 opacity-70" />
|
||||
<span class="min-w-0 flex-1 truncate text-xs">
|
||||
<template v-for="(part, partIndex) in titleParts(hit)" :key="partIndex">
|
||||
<mark v-if="part.hit" class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text">{{ part.text }}</mark>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
<span class="max-w-[45%] shrink-0 truncate text-[10px] text-fg-disabled">{{ hit.relPath }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<div class="flex h-7 shrink-0 items-center gap-3 border-t border-border px-3 text-[10px] text-muted-foreground">
|
||||
<span class="flex items-center gap-1"><CornerDownLeft class="size-3" />打开</span>
|
||||
<span>↑↓ 选择</span>
|
||||
<span>Esc 关闭</span>
|
||||
<span class="ml-auto tabular-nums">{{ results.length }} / {{ store.quickOpenList.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -0,0 +1,173 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 库内全文检索面板(FTS5)。
|
||||
*
|
||||
* # 检索由 Rust 做,前端只做「输入 → 查询 → 渲染」
|
||||
*
|
||||
* 匹配、排序(标题权重高于正文)、片段提取、分页全部在 SQL 里完成:把候选集拉回
|
||||
* 前端再过滤会在大库上卡住主线程,而且「命中总数」会变成假的(前端只拿到了当页)。
|
||||
* 这里的防抖只是**省请求**,不是正确性的一部分。
|
||||
*
|
||||
* # 高亮片段为什么不用 v-html
|
||||
*
|
||||
* 片段来自用户笔记正文,直接 `v-html` 就是一个自找的 XSS 面。Rust 侧回传的是
|
||||
* 用 `\u0002` / `\u0003` 定界的纯文本,这里切成数组后用 `<mark>` 渲染
|
||||
* (见 `splitHighlight`)—— 文本永远走插值,不经过 HTML 解析。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { FileText, Loader2, Search, Tag, X } from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { splitHighlight } from '@/types/notes'
|
||||
|
||||
const emit = defineEmits<{ open: [relPath: string] }>()
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 输入框的值与「已提交的关键词」分开:前者每次按键都变,后者只在防抖后提交 */
|
||||
const input = ref(store.searchKeyword)
|
||||
const activeTag = ref(store.searchTag)
|
||||
|
||||
let debounce: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function submit(immediate = false): void {
|
||||
if (debounce) clearTimeout(debounce)
|
||||
const run = () => {
|
||||
debounce = null
|
||||
void store.search({ keyword: input.value, tag: activeTag.value })
|
||||
}
|
||||
// 回车/点按钮时立即查,打字时防抖 250ms
|
||||
if (immediate) run()
|
||||
else debounce = setTimeout(run, 250)
|
||||
}
|
||||
|
||||
function pickTag(tag: string): void {
|
||||
activeTag.value = activeTag.value === tag ? '' : tag
|
||||
submit(true)
|
||||
}
|
||||
|
||||
function clearAll(): void {
|
||||
input.value = ''
|
||||
activeTag.value = ''
|
||||
store.clearSearch()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => store.searchTag,
|
||||
tag => {
|
||||
if (tag !== activeTag.value) activeTag.value = tag
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void store.loadTags()
|
||||
// 首次进入若已有结果就保留,否则给一个空关键词查询(把最近改动的笔记列出来)
|
||||
if (!store.searchHits.length) submit(true)
|
||||
})
|
||||
|
||||
const hasQuery = computed(() => !!input.value.trim() || !!activeTag.value)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<!-- 关键词 -->
|
||||
<div class="shrink-0 px-2 pb-2">
|
||||
<div class="relative">
|
||||
<Search class="absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="input"
|
||||
placeholder="搜索标题与正文…"
|
||||
class="h-7 pl-7 pr-6 text-xs"
|
||||
@input="submit()"
|
||||
@keydown.enter="submit(true)"
|
||||
/>
|
||||
<button
|
||||
v-if="input"
|
||||
type="button"
|
||||
class="absolute top-1/2 right-1.5 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="input = ''; submit(true)"
|
||||
>
|
||||
<X class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 标签筛选 -->
|
||||
<div v-if="store.tags.length" class="mt-2 flex flex-wrap gap-1">
|
||||
<button
|
||||
v-for="item in store.tags.slice(0, 12)"
|
||||
:key="item.tag"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-[11px] transition-colors duration-150"
|
||||
:class="
|
||||
activeTag === item.tag
|
||||
? 'bg-primary-soft text-primary-soft-text'
|
||||
: 'bg-muted text-fg-secondary hover:bg-hover hover:text-foreground'
|
||||
"
|
||||
@click="pickTag(item.tag)"
|
||||
>
|
||||
<Tag class="size-2.5" />
|
||||
{{ item.tag }}
|
||||
<span class="tabular-nums opacity-70">{{ item.count }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果统计 -->
|
||||
<div class="flex h-6 shrink-0 items-center gap-2 border-y border-border px-2 text-[11px] text-muted-foreground">
|
||||
<span v-if="store.searching" class="flex items-center gap-1.5">
|
||||
<Loader2 class="size-3 animate-spin" />检索中…
|
||||
</span>
|
||||
<span v-else>共 {{ store.searchTotal }} 条</span>
|
||||
<button
|
||||
v-if="hasQuery"
|
||||
type="button"
|
||||
class="ml-auto text-muted-foreground hover:text-foreground"
|
||||
@click="clearAll"
|
||||
>
|
||||
重置
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 结果列表 -->
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-1.5 py-2">
|
||||
<StateBlock
|
||||
v-if="!store.searchHits.length && !store.searching"
|
||||
variant="empty"
|
||||
:title="hasQuery ? '没有匹配的笔记' : '还没有可搜索的内容'"
|
||||
:description="hasQuery ? '换个关键词,或点「重置」看全部' : '索引同步完成后这里会列出库内笔记'"
|
||||
:min-height="120"
|
||||
/>
|
||||
|
||||
<button
|
||||
v-for="hit in store.searchHits"
|
||||
:key="hit.relPath"
|
||||
type="button"
|
||||
class="flex w-full flex-col gap-0.5 rounded-sm px-2 py-1.5 text-left transition-colors duration-150 hover:bg-row-hover"
|
||||
@click="emit('open', hit.relPath)"
|
||||
>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<FileText class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span class="truncate text-xs font-medium text-foreground">{{ hit.title }}</span>
|
||||
</span>
|
||||
<span v-if="hit.snippet" class="line-clamp-2 pl-5 text-[11px] leading-relaxed text-muted-foreground">
|
||||
<template v-for="(part, index) in splitHighlight(hit.snippet)" :key="index">
|
||||
<mark v-if="part.hit" class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text">{{ part.text }}</mark>
|
||||
<template v-else>{{ part.text }}</template>
|
||||
</template>
|
||||
</span>
|
||||
<span class="truncate pl-5 text-[10px] text-fg-disabled">{{ hit.relPath }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="store.searchHasMore" class="mt-1 flex justify-center">
|
||||
<Button variant="ghost" size="sm" :disabled="store.searching" @click="store.searchMore()">
|
||||
加载更多
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,490 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* WebDAV 设置与同步面板(主模块页「同步」区)。
|
||||
*
|
||||
* # 三块内容,对应三种使用姿态
|
||||
*
|
||||
* 1. **连接**:地址 / 账号 / 应用密码 / 远端根 —— 密码进系统凭据管理器,不回显;
|
||||
* 2. **同步**:方向、冲突策略、立即同步 —— 双向默认,冲突默认「两侧都留」;
|
||||
* 3. **备份**:zip 快照(立即备份 / 快照列表 / 恢复)—— 「只是要个备份」的路径,
|
||||
* 比同步简单也更不容易出事(规划 §3.6)。
|
||||
*
|
||||
* # 为什么设置改动要显式 `commitSettings`
|
||||
*
|
||||
* 别的设置(主题/字体)改动即落盘没问题,因为它们只影响本机显示;同步设置改错会让
|
||||
* **下一次同步按错误的方向跑**(比如把「只上传」误当成双向)。因此这里同样即时保存,
|
||||
* 但在切换方向 / 冲突策略时给出明确文案,而不是静默生效。
|
||||
*/
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import {
|
||||
AlertTriangle,
|
||||
ArrowDownToLine,
|
||||
ArrowUpFromLine,
|
||||
CloudUpload,
|
||||
Database,
|
||||
HardDriveDownload,
|
||||
Loader2,
|
||||
PlugZap,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
Trash2
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import { ConfirmDialog, SettingRow, StateBlock } from '@/components/common'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
import { notesClient } from '../notesClient'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import type { ConflictPolicy, SyncDirection } from '@/types/notes'
|
||||
|
||||
const store = useNotesStore()
|
||||
|
||||
/** 密码输入框(提交后立刻清空,不留内存态) */
|
||||
const password = ref('')
|
||||
const testing = ref(false)
|
||||
const restoring = ref<string | null>(null)
|
||||
/** 待恢复的快照名(非空即弹出确认框) */
|
||||
const restoreTarget = ref<string | null>(null)
|
||||
/** 确认框的 open 必须是 boolean:`restoreTarget` 同时承载「点了哪一个」,
|
||||
* 因此这里显式做一次类型转换,而不是把 `string | null` 直接塞给 `open` */
|
||||
const restoreOpen = computed({
|
||||
get: () => restoreTarget.value !== null,
|
||||
set: (value: boolean) => {
|
||||
if (!value) restoreTarget.value = null
|
||||
}
|
||||
})
|
||||
|
||||
const webdav = computed(() => store.settings.webdav)
|
||||
const configured = computed(() => store.webdavStatus?.configured ?? false)
|
||||
const hasPassword = computed(() => store.webdavStatus?.hasPassword ?? false)
|
||||
|
||||
const DIRECTION_OPTIONS: Array<{ value: SyncDirection; label: string; hint: string }> = [
|
||||
{ value: 'bidirectional', label: '双向同步', hint: '两侧都改时按冲突策略处理' },
|
||||
{ value: 'upload', label: '仅上传(本地 → 远端)', hint: '把本地当作唯一真相,远端只作备份' },
|
||||
{ value: 'download', label: '仅下载(远端 → 本地)', hint: '换机器恢复时用,本地改动不会被上传' }
|
||||
]
|
||||
|
||||
const CONFLICT_OPTIONS: Array<{ value: ConflictPolicy; label: string }> = [
|
||||
{ value: 'keepBoth', label: '两侧都留(最保守)' },
|
||||
{ value: 'newer', label: '保留较新的' },
|
||||
{ value: 'localWins', label: '本地覆盖远端' },
|
||||
{ value: 'remoteWins', label: '远端覆盖本地' }
|
||||
]
|
||||
|
||||
/** 局部更新 webdav 设置(`webdav` 是嵌套对象,整体替换) */
|
||||
function patchWebdav(patch: Partial<typeof webdav.value>): void {
|
||||
void store.patchSettings({ webdav: { ...webdav.value, ...patch } })
|
||||
}
|
||||
|
||||
async function savePassword(): Promise<void> {
|
||||
const value = password.value
|
||||
if (!value.trim()) {
|
||||
toast.error('密码不能为空')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await store.refreshWebdav(value)
|
||||
password.value = ''
|
||||
toast.success('密码已保存到系统凭据管理器')
|
||||
} catch (e) {
|
||||
toast.error(`保存密码失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function clearPassword(): Promise<void> {
|
||||
try {
|
||||
await store.refreshWebdav('')
|
||||
toast.success('已清除保存的密码')
|
||||
} catch (e) {
|
||||
toast.error(`清除密码失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function testConnection(): Promise<void> {
|
||||
testing.value = true
|
||||
try {
|
||||
const result = await notesClient.testWebdav()
|
||||
if (result.created.length) {
|
||||
toast.success(`${result.message}(新建了 ${result.created.length} 层目录)`)
|
||||
} else {
|
||||
toast.success(result.message)
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(`连接失败:${String(e)}`)
|
||||
} finally {
|
||||
testing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function syncNow(): Promise<void> {
|
||||
try {
|
||||
const report = await store.syncNow()
|
||||
if (!report) return
|
||||
if (report.failed > 0) {
|
||||
toast.warning(
|
||||
`同步完成但 ${report.failed} 条失败(上传 ${report.uploaded} / 下载 ${report.downloaded})`
|
||||
)
|
||||
} else {
|
||||
toast.success(
|
||||
`同步完成:上传 ${report.uploaded} · 下载 ${report.downloaded} · 改名 ${report.moved} · 删除 ${report.deletedRemote + report.deletedLocal} · 冲突 ${report.conflicts}(${report.elapsedMs}ms)`
|
||||
)
|
||||
}
|
||||
void store.loadBackups()
|
||||
} catch (e) {
|
||||
toast.error(`同步失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function backupNow(): Promise<void> {
|
||||
try {
|
||||
const report = await store.backupNow()
|
||||
toast.success(`快照已上传:${report.name}(${report.files} 个文件,${formatBytes(report.bytes)})`)
|
||||
void store.loadBackups()
|
||||
} catch (e) {
|
||||
toast.error(`备份失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出本地快照(不连远端)。 */
|
||||
async function exportLocalSnapshot(): Promise<void> {
|
||||
try {
|
||||
const dest = await open({
|
||||
title: '保存快照',
|
||||
defaultPath: `thing-notes-${new Date().toISOString().slice(0, 10)}.zip`,
|
||||
filters: [{ name: 'Zip 压缩包', extensions: ['zip'] }]
|
||||
})
|
||||
if (typeof dest !== 'string') return
|
||||
const saved = await notesClient.exportSnapshotLocal(dest)
|
||||
toast.success(`快照已导出:${saved}`)
|
||||
} catch (e) {
|
||||
toast.error(`导出快照失败:${String(e)}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function doRestore(): Promise<void> {
|
||||
const name = restoreTarget.value
|
||||
if (!name) return
|
||||
restoring.value = name
|
||||
try {
|
||||
await store.restoreBackup(name)
|
||||
toast.success('恢复完成(已存在的本地文件未被覆盖)')
|
||||
} catch (e) {
|
||||
toast.error(`恢复失败:${String(e)}`)
|
||||
} finally {
|
||||
restoring.value = null
|
||||
restoreTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function formatTime(ms: number): string {
|
||||
if (!ms) return '—'
|
||||
return new Date(ms).toLocaleString()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void store.loadWebdavStatus()
|
||||
void store.loadBackups()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<!-- ===== 连接 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<PlugZap class="size-4 text-primary" />
|
||||
WebDAV 连接
|
||||
<span
|
||||
class="ml-auto rounded-sm px-1.5 py-0.5 text-[11px]"
|
||||
:class="configured ? 'bg-success/15 text-success' : 'bg-muted text-muted-foreground'"
|
||||
>
|
||||
{{ configured ? '已配置' : '未配置' }}
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
兼容 Nextcloud / 群晖 / 坚果云 / Alist 等标准 WebDAV 服务。密码保存在 Windows
|
||||
凭据管理器(服务名 <code class="font-mono">Thing</code>),不写入设置文件。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="服务地址" description="含协议与路径,例如 https://dav.jianguoyun.com/dav" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.url"
|
||||
placeholder="https://dav.example.com/dav"
|
||||
@change="(e: Event) => patchWebdav({ url: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="账号" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.username"
|
||||
placeholder="邮箱或用户名"
|
||||
@change="(e: Event) => patchWebdav({ username: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="密码 / 应用密码"
|
||||
:description="hasPassword ? '已保存(留空即不修改)' : '尚未保存'"
|
||||
control-width="wide"
|
||||
>
|
||||
<div class="flex w-full items-center gap-2">
|
||||
<Input
|
||||
v-model="password"
|
||||
type="password"
|
||||
:placeholder="hasPassword ? '••••••••(已保存)' : '应用密码'"
|
||||
autocomplete="new-password"
|
||||
/>
|
||||
<Button size="sm" :disabled="!password.trim()" @click="savePassword">保存</Button>
|
||||
<Button
|
||||
v-if="hasPassword"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="text-muted-foreground"
|
||||
@click="clearPassword"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="远端根目录" description="该目录不存在时会自动逐级创建" control-width="wide">
|
||||
<Input
|
||||
:model-value="webdav.remoteRoot"
|
||||
placeholder="thing-notes"
|
||||
@change="(e: Event) => patchWebdav({ remoteRoot: (e.target as HTMLInputElement).value })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="连接自检" description="验证地址与凭据,并列出远端已有文件数">
|
||||
<Button variant="outline" size="sm" :disabled="testing" @click="testConnection">
|
||||
<Loader2 v-if="testing" class="size-3.5 animate-spin" />
|
||||
<ShieldCheck v-else class="size-3.5" />
|
||||
测试连接
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 同步 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<CloudUpload class="size-4 text-primary" />
|
||||
同步
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
同步以本地库为准:远端只接收推送与拉取,不作为工作目录。库内
|
||||
<code class="font-mono">.notes/</code>(索引与同步基线)永不参与同步。
|
||||
</p>
|
||||
<div class="flex flex-col divide-y divide-divider">
|
||||
<SettingRow label="同步方向" :description="DIRECTION_OPTIONS.find(o => o.value === webdav.direction)?.hint" control-width="wide">
|
||||
<Select
|
||||
:model-value="webdav.direction"
|
||||
@update:model-value="v => patchWebdav({ direction: v as SyncDirection })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in DIRECTION_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="冲突策略"
|
||||
description="仅双向同步时生效:两侧都改过的文件怎么处理"
|
||||
control-width="wide"
|
||||
>
|
||||
<Select
|
||||
:model-value="webdav.conflict"
|
||||
@update:model-value="v => patchWebdav({ conflict: v as ConflictPolicy })"
|
||||
>
|
||||
<SelectTrigger class="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in CONFLICT_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label="启动时自动同步" description="应用启动后后台跑一次(失败只记日志,不打扰)">
|
||||
<Switch
|
||||
:model-value="webdav.autoSyncOnLaunch"
|
||||
@update:model-value="v => patchWebdav({ autoSyncOnLaunch: v === true })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
label="快照保留份数"
|
||||
description="远端 backups/ 目录里保留的 zip 数量,超出后删最旧的"
|
||||
control-width="wide"
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
:model-value="webdav.backupKeep"
|
||||
@change="(e: Event) => patchWebdav({ backupKeep: Number((e.target as HTMLInputElement).value) || 7 })"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<!-- 进度 -->
|
||||
<div v-if="store.syncing" class="flex flex-col gap-2 py-3">
|
||||
<div class="flex items-center gap-2 text-[13px] text-fg-secondary">
|
||||
<Loader2 class="size-3.5 shrink-0 animate-spin" />
|
||||
<span class="truncate">
|
||||
{{ store.syncProgress?.message || '同步中…' }}
|
||||
<span v-if="store.syncProgress?.current" class="text-muted-foreground">
|
||||
· {{ store.syncProgress.current }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="store.syncProgress?.total" class="ml-auto shrink-0 tabular-nums">
|
||||
{{ store.syncProgress.done }} / {{ store.syncProgress.total }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 w-full overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
class="h-full bg-primary transition-all duration-200"
|
||||
:style="{
|
||||
width: store.syncProgress?.total
|
||||
? `${Math.round(((store.syncProgress?.done ?? 0) / store.syncProgress.total) * 100)}%`
|
||||
: '8%'
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingRow label="立即操作" description="同步后会顺带上传一份 zip 快照(先同步再备份)">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button size="sm" :disabled="!configured || store.syncing" @click="syncNow">
|
||||
<ArrowUpFromLine class="size-3.5" />立即同步
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!configured || store.syncing" @click="backupNow">
|
||||
<Database class="size-3.5" />仅快照
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="!configured || store.syncing" @click="exportLocalSnapshot">
|
||||
<ArrowDownToLine class="size-3.5" />导出到本地
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
<!-- 最近一次结果 -->
|
||||
<div v-if="store.lastSyncReport" class="flex flex-wrap gap-x-4 gap-y-1 py-2 text-[11px] text-muted-foreground">
|
||||
<span>上次同步:上传 {{ store.lastSyncReport.uploaded }}</span>
|
||||
<span>下载 {{ store.lastSyncReport.downloaded }}</span>
|
||||
<span>改名 {{ store.lastSyncReport.moved }}</span>
|
||||
<span>删除 {{ store.lastSyncReport.deletedRemote + store.lastSyncReport.deletedLocal }}</span>
|
||||
<span :class="store.lastSyncReport.conflicts ? 'text-warning' : ''">
|
||||
冲突 {{ store.lastSyncReport.conflicts }}
|
||||
</span>
|
||||
<span :class="store.lastSyncReport.failed ? 'text-danger' : ''">
|
||||
失败 {{ store.lastSyncReport.failed }}
|
||||
</span>
|
||||
<span class="tabular-nums">{{ store.lastSyncReport.elapsedMs }}ms</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="store.lastSyncReport?.failures.length"
|
||||
class="flex flex-col gap-1 rounded-sm bg-danger/10 p-2 text-[11px] text-danger"
|
||||
>
|
||||
<span class="flex items-center gap-1 font-medium">
|
||||
<AlertTriangle class="size-3" />失败明细
|
||||
</span>
|
||||
<span v-for="(item, index) in store.lastSyncReport.failures" :key="index" class="truncate">
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 快照列表 ===== -->
|
||||
<Card class="!gap-2 !py-4">
|
||||
<CardHeader class="!px-4">
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<HardDriveDownload class="size-4 text-primary" />
|
||||
远端快照
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="ml-auto"
|
||||
:disabled="!configured || store.loadingBackups"
|
||||
title="刷新快照列表"
|
||||
@click="store.loadBackups()"
|
||||
>
|
||||
<RefreshCw class="size-3.5" :class="store.loadingBackups && 'animate-spin'" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="!px-4">
|
||||
<p class="pb-2 text-xs text-muted-foreground">
|
||||
恢复只会**补上本地缺失的文件**,不会覆盖你已有的笔记 —— 需要整库回退时,请先在
|
||||
资源管理器里移走旧库再恢复。
|
||||
</p>
|
||||
<StateBlock
|
||||
v-if="!store.backups.length"
|
||||
variant="empty"
|
||||
:title="configured ? '远端还没有快照' : '尚未配置 WebDAV'"
|
||||
:description="configured ? '点「仅快照」上传第一份' : undefined"
|
||||
:min-height="100"
|
||||
/>
|
||||
<div v-else class="flex flex-col divide-y divide-divider">
|
||||
<div
|
||||
v-for="item in store.backups"
|
||||
:key="item.name"
|
||||
class="flex items-center gap-3 py-2 text-[13px]"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate font-mono text-xs text-fg-secondary">
|
||||
{{ item.name }}
|
||||
</span>
|
||||
<span class="shrink-0 tabular-nums text-xs text-muted-foreground">
|
||||
{{ formatBytes(item.size) }}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-muted-foreground">{{ formatTime(item.modified) }}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!!restoring"
|
||||
@click="restoreTarget = item.name"
|
||||
>
|
||||
<Loader2 v-if="restoring === item.name" class="size-3.5 animate-spin" />
|
||||
恢复
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="restoreOpen"
|
||||
title="从快照恢复"
|
||||
:description="`将把快照「${restoreTarget ?? ''}」里本地缺失的文件补进库根。已存在的文件不会被覆盖。`"
|
||||
confirm-text="开始恢复"
|
||||
@confirm="doRestore"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* CM6 编辑器核心:扩展集组装 + 按设置热重配置 + 语言热切换。
|
||||
*
|
||||
* # 为什么用 Compartment
|
||||
*
|
||||
* 主题、排版、行号、Tab 宽度、Live Preview 开关、语言都必须在**不重建编辑器**的
|
||||
* 前提下即时生效(项目约定:设置改动立即应用,无保存按钮)。`Compartment` 正是为此
|
||||
* 而生:用 `reconfigure` 替换其中一组扩展,文档与光标位置完整保留。
|
||||
*
|
||||
* # 大文件降级(P1)
|
||||
*
|
||||
* 超过「大文件阈值」的文件会关掉 Live Preview、折叠、括号匹配、自动补全 —— 这些都
|
||||
* 需要遍历语法树或做全量分析,几十万行的日志文件开着它们只会让输入延迟肉眼可见。
|
||||
* 降级后仍保留高亮与行号:那是用户打开的**理由**(看代码),不该被省掉。
|
||||
*/
|
||||
import { Compartment, EditorState, type Extension } from '@codemirror/state'
|
||||
import {
|
||||
EditorView,
|
||||
crosshairCursor,
|
||||
drawSelection,
|
||||
dropCursor,
|
||||
highlightActiveLine,
|
||||
highlightActiveLineGutter,
|
||||
highlightSpecialChars,
|
||||
keymap,
|
||||
lineNumbers,
|
||||
rectangularSelection
|
||||
} from '@codemirror/view'
|
||||
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands'
|
||||
import {
|
||||
bracketMatching,
|
||||
foldGutter,
|
||||
foldKeymap,
|
||||
indentOnInput,
|
||||
syntaxHighlighting,
|
||||
defaultHighlightStyle
|
||||
} from '@codemirror/language'
|
||||
import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete'
|
||||
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search'
|
||||
|
||||
import { notesKeymap } from './keymap'
|
||||
import { markdownLivePreview } from './markdownLivePreview'
|
||||
import { editorTypography, resolveEditorTheme } from './themes'
|
||||
import { wikilinkExtension, type WikilinkHandlers } from './wikilink'
|
||||
import { type LanguageLoader } from './languages'
|
||||
|
||||
/** 语言加载器的形态由 `languages.ts` 定义(这里只做转出,避免两处定义漂移) */
|
||||
export type { LanguageLoader }
|
||||
|
||||
/** 编辑器配置(由模块设置映射而来)。 */
|
||||
export interface EditorConfig {
|
||||
/** 是否启用 Live Preview(false = 纯源码 / 代码高亮) */
|
||||
livePreview: boolean
|
||||
showLineNumbers: boolean
|
||||
tabSize: number
|
||||
fontFamily: string
|
||||
fontSize: number
|
||||
lineHeight: number
|
||||
ligatures: boolean
|
||||
theme: string
|
||||
followAppTheme: boolean
|
||||
/** 应用当前是否为深色(跟随应用时用于取深/浅变体) */
|
||||
isDark: boolean
|
||||
/** 语言扩展加载器 */
|
||||
language: LanguageLoader
|
||||
/** 大文件降级(关闭重扩展) */
|
||||
largeFile: boolean
|
||||
/** 是否启用自动补全 / 括号闭合 */
|
||||
autocomplete: boolean
|
||||
/** 是否识别 `[[wikilink]]`(点击跳转;关闭则只当普通文本) */
|
||||
wikilink: boolean
|
||||
/** wikilink 点击回调(`wikilink` 为真时必需) */
|
||||
onWikilink?: WikilinkHandlers['onOpen']
|
||||
/**
|
||||
* 当前文档的库内相对路径(空串 = 库外文件)。
|
||||
*
|
||||
* Live Preview 的图片预览需要它来解析「相对当前笔记目录」的图片目标;
|
||||
* 库外文件不做图片预览(没有库根上下文,路径语义不同)。
|
||||
*/
|
||||
currentRelPath: string
|
||||
/** 是否启用图片内联预览 */
|
||||
images: boolean
|
||||
}
|
||||
|
||||
const themeCompartment = new Compartment()
|
||||
const typographyCompartment = new Compartment()
|
||||
const modeCompartment = new Compartment()
|
||||
const lineNumbersCompartment = new Compartment()
|
||||
const tabSizeCompartment = new Compartment()
|
||||
const languageCompartment = new Compartment()
|
||||
const heavyCompartment = new Compartment()
|
||||
const wikilinkCompartment = new Compartment()
|
||||
|
||||
/** 行号 + 活动行行号(开启/关闭由 compartment 控制)。 */
|
||||
const gutterExtensions: Extension = [lineNumbers(), highlightActiveLineGutter()]
|
||||
|
||||
/** 文档/光标之外的静态扩展(一次装配,之后不再变)。 */
|
||||
const baseExtensions: Extension = [
|
||||
highlightSpecialChars(),
|
||||
history(),
|
||||
drawSelection(),
|
||||
dropCursor(),
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
indentOnInput(),
|
||||
highlightActiveLine(),
|
||||
highlightSelectionMatches(),
|
||||
rectangularSelection(),
|
||||
crosshairCursor(),
|
||||
// 兜底高亮:自建主题自带 HighlightStyle,但 Stream/未知语言可能没有对应标签,
|
||||
// 这一层保证「总有点颜色」,且在所有主题下都安全
|
||||
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
|
||||
EditorView.lineWrapping
|
||||
]
|
||||
|
||||
/** 重扩展(大文件时全部关闭)。 */
|
||||
function heavyExtensions(config: EditorConfig): Extension {
|
||||
if (config.largeFile) return []
|
||||
const parts: Extension[] = [bracketMatching(), foldGutter()]
|
||||
if (config.autocomplete) parts.push(closeBrackets())
|
||||
return parts
|
||||
}
|
||||
|
||||
/** 由配置解析出各 compartment 的内容。 */
|
||||
function compartmentExtensions(config: EditorConfig) {
|
||||
return {
|
||||
theme: resolveEditorTheme(config.theme, config.followAppTheme, config.isDark),
|
||||
typography: editorTypography({
|
||||
fontFamily: config.fontFamily,
|
||||
fontSize: config.fontSize,
|
||||
lineHeight: config.lineHeight,
|
||||
ligatures: config.ligatures
|
||||
}),
|
||||
// Live Preview 只对 Markdown 有意义;大文件一律关闭。
|
||||
// 传 currentRelPath 是为了图片预览能按「相对当前笔记」解析目标。
|
||||
mode:
|
||||
config.livePreview && !config.largeFile
|
||||
? markdownLivePreview({
|
||||
currentRelPath: config.currentRelPath,
|
||||
images: config.images
|
||||
})
|
||||
: [],
|
||||
lineNumbers: config.showLineNumbers ? gutterExtensions : [],
|
||||
tabSize: EditorState.tabSize.of(config.tabSize),
|
||||
heavy: heavyExtensions(config),
|
||||
// wikilink 只对笔记(Markdown)有意义;代码文件里的 `[[x]]` 是数组/属性访问,
|
||||
// 给它加上点下划线会平白制造噪声
|
||||
wikilink: config.wikilink
|
||||
? wikilinkExtension({ onOpen: config.onWikilink ?? (() => undefined) })
|
||||
: []
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建编辑器状态。 */
|
||||
export function createEditorState(options: {
|
||||
doc: string
|
||||
config: EditorConfig
|
||||
onDocChanged: (doc: string) => void
|
||||
/** 选区/光标变化(状态栏行号、大纲当前项用;可省略) */
|
||||
onSelectionChanged?: (line: number, column: number) => void
|
||||
}): EditorState {
|
||||
const c = compartmentExtensions(options.config)
|
||||
return EditorState.create({
|
||||
doc: options.doc,
|
||||
extensions: [
|
||||
lineNumbersCompartment.of(c.lineNumbers),
|
||||
baseExtensions,
|
||||
tabSizeCompartment.of(c.tabSize),
|
||||
themeCompartment.of(c.theme),
|
||||
typographyCompartment.of(c.typography),
|
||||
modeCompartment.of(c.mode),
|
||||
languageCompartment.of([]),
|
||||
heavyCompartment.of(c.heavy),
|
||||
wikilinkCompartment.of(c.wikilink),
|
||||
keymap.of([
|
||||
...notesKeymap,
|
||||
...closeBracketsKeymap,
|
||||
...defaultKeymap,
|
||||
...searchKeymap,
|
||||
...historyKeymap,
|
||||
...foldKeymap,
|
||||
indentWithTab
|
||||
]),
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged) options.onDocChanged(update.state.doc.toString())
|
||||
if (update.selectionSet || update.docChanged) {
|
||||
const head = update.state.selection.main.head
|
||||
const line = update.state.doc.lineAt(head)
|
||||
options.onSelectionChanged?.(line.number, head - line.from + 1)
|
||||
}
|
||||
})
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/** 按新配置热重配置(不重建编辑器,不丢文档与光标)。 */
|
||||
export function reconfigureEditor(view: EditorView, config: EditorConfig): void {
|
||||
const c = compartmentExtensions(config)
|
||||
view.dispatch({
|
||||
effects: [
|
||||
themeCompartment.reconfigure(c.theme),
|
||||
typographyCompartment.reconfigure(c.typography),
|
||||
modeCompartment.reconfigure(c.mode),
|
||||
lineNumbersCompartment.reconfigure(c.lineNumbers),
|
||||
tabSizeCompartment.reconfigure(c.tabSize),
|
||||
heavyCompartment.reconfigure(c.heavy),
|
||||
wikilinkCompartment.reconfigure(c.wikilink)
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 热切换语言(异步加载完成后调用)。
|
||||
*
|
||||
* 语言包是按需 `import()` 的,因此这里是「先设空、加载完再设」的两步;调用方
|
||||
* (`EditorHost`)用一个自增令牌丢弃过期结果,避免快速切换文件时旧语言覆盖新语言。
|
||||
*/
|
||||
export function setLanguageExtension(view: EditorView, extension: Extension | null): void {
|
||||
view.dispatch({
|
||||
effects: languageCompartment.reconfigure(extension ?? [])
|
||||
})
|
||||
}
|
||||
|
||||
/** 用新文档整体替换(切换笔记 / 打开文件时)。 */
|
||||
export function replaceDoc(view: EditorView, doc: string): void {
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: doc },
|
||||
selection: { anchor: 0 },
|
||||
scrollIntoView: true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 把光标移到某个字符偏移并滚动到可见位置(大纲点击跳转用)。
|
||||
*
|
||||
* 越界偏移一律夹到文档范围内:大纲是基于**刚提取时**的内容算出来的,而用户可能
|
||||
* 在此之后又编辑过(行变短、标题被删)。夹取比抛异常更合适 —— 跳到一个近似位置,
|
||||
* 好过整个面板报错。
|
||||
*/
|
||||
export function jumpToPosition(view: EditorView, position: number): void {
|
||||
const max = view.state.doc.length
|
||||
const anchor = Math.max(0, Math.min(position, max))
|
||||
view.dispatch({
|
||||
selection: { anchor },
|
||||
scrollIntoView: true
|
||||
})
|
||||
view.focus()
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* 图片内联预览(Live Preview 的一部分)。
|
||||
*
|
||||
* # 为什么单独一个文件
|
||||
*
|
||||
* 图片预览需要**异步 IO**(把库内图片读成 data URL),而 `markdownLivePreview.ts`
|
||||
* 是一个纯同步的装饰构建器。把异步塞进去会让那个文件的每次选区变化都背上
|
||||
* 「可能触发磁盘读取」的心智负担;独立出来后:
|
||||
* - 本文件负责「解析图片目标 → 取字节(带缓存)→ 通知编辑器重建装饰」;
|
||||
* - Live Preview 只问一句「这个目标当前有没有可用的 data URL」。
|
||||
*
|
||||
* # 缓存与失效
|
||||
*
|
||||
* 同一个图片在视口里可能被引用多次、重建装饰也会反复问同一个目标,因此必须缓存。
|
||||
* 缓存键是**库内相对路径**,值为 `data URL | null`(`null` 表示「读过但不可预览」,
|
||||
* 例如非图片或超过大小上限 —— 缓存它同样重要,否则每次重建都会白读一次磁盘)。
|
||||
*
|
||||
* 缓存不主动失效:用户替换了同名图片的场景很罕见,而「每 3 秒清一次缓存」会让
|
||||
* 滚动长文档时反复读盘。切库时由 `resetImageCache()` 清空。
|
||||
*/
|
||||
import { notesClient } from '../notesClient'
|
||||
|
||||
/** 缓存:库内相对路径 → data URL(`null` = 已确认不可预览) */
|
||||
const cache = new Map<string, string | null>()
|
||||
/** 正在读取中的目标(避免同一张图并发读多次) */
|
||||
const inflight = new Map<string, Promise<string | null>>()
|
||||
|
||||
/** 清空缓存(切库 / 重建索引后调用)。 */
|
||||
export function resetImageCache(): void {
|
||||
cache.clear()
|
||||
inflight.clear()
|
||||
}
|
||||
|
||||
/** 已经拿到结果的缓存(同步查询,供装饰构建器使用)。 */
|
||||
export function cachedImage(relPath: string): string | null | undefined {
|
||||
return cache.get(relPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Markdown 图片目标为「库内相对路径」。
|
||||
*
|
||||
* 规则与 `notes_read_asset` 的安全模型一致:
|
||||
* - 绝对 URL(`http://` / `https://` / `data:`)→ `null`(外链不内联,交给浏览器);
|
||||
* - 以 `/` 开头 → 视为**库根相对**路径;
|
||||
* - 其余 → 相对当前笔记所在目录解析,支持 `./` 与 `../`。
|
||||
*
|
||||
* 返回 `null` 表示「这个目标不该内联预览」。
|
||||
*/
|
||||
export function resolveImagePath(target: string, currentRelPath: string): string | null {
|
||||
let raw = target.trim()
|
||||
if (!raw) return null
|
||||
// 去掉可选的 title(`path "标题"` 或 `path '标题'`)
|
||||
raw = raw.split(/\s+["']/)[0] ?? raw
|
||||
// 去掉锚点与查询串(本地图片用不上)
|
||||
raw = (raw.split('#')[0] ?? '').split('?')[0] ?? ''
|
||||
if (!raw) return null
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) return null // 绝对 URL / data:
|
||||
|
||||
const normalized = raw.replace(/\\/g, '/')
|
||||
if (normalized.startsWith('/')) {
|
||||
return normalized.replace(/^\/+/, '')
|
||||
}
|
||||
|
||||
const base = currentRelPath.split('/').slice(0, -1)
|
||||
const parts = [...base]
|
||||
for (const segment of normalized.split('/')) {
|
||||
if (!segment || segment === '.') continue
|
||||
if (segment === '..') {
|
||||
parts.pop()
|
||||
continue
|
||||
}
|
||||
parts.push(segment)
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
/**
|
||||
* 预取一个图片(幂等)。
|
||||
*
|
||||
* 返回 data URL 或 `null`。调用方拿到新结果后应触发一次编辑器重建
|
||||
* (Live Preview 会在重建时读到新缓存)。
|
||||
*/
|
||||
export async function fetchImage(relPath: string): Promise<string | null> {
|
||||
const cached = cache.get(relPath)
|
||||
if (cached !== undefined) return cached
|
||||
const pending = inflight.get(relPath)
|
||||
if (pending) return pending
|
||||
|
||||
const task = notesClient
|
||||
.readAsset(relPath)
|
||||
.then(value => {
|
||||
cache.set(relPath, value)
|
||||
return value
|
||||
})
|
||||
.catch(() => {
|
||||
// 读取失败(权限、目录穿越被拒)也缓存成 null:不预览,但不反复重试
|
||||
cache.set(relPath, null)
|
||||
return null
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(relPath)
|
||||
})
|
||||
|
||||
inflight.set(relPath, task)
|
||||
return task
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 编辑器格式化命令与快捷键(Live Preview / 源码两种模式通用)。
|
||||
*
|
||||
* 命令都通过 `state.changeByRange` 表达,保证多光标下每个选区都被正确处理。
|
||||
*/
|
||||
import { EditorSelection, type EditorState } from '@codemirror/state'
|
||||
import { type Command, type KeyBinding } from '@codemirror/view'
|
||||
|
||||
/** 用标记包裹选区;若选区两侧已是该标记,则取消包裹(可反复切换)。 */
|
||||
function wrapSelection(before: string, after: string = before): Command {
|
||||
return view => {
|
||||
view.dispatch(
|
||||
view.state.changeByRange(range => {
|
||||
const text = view.state.sliceDoc(range.from, range.to)
|
||||
const outerFrom = range.from - before.length
|
||||
const outerTo = range.to + after.length
|
||||
|
||||
// 已包裹 → 取消
|
||||
if (
|
||||
outerFrom >= 0 &&
|
||||
outerTo <= view.state.doc.length &&
|
||||
view.state.sliceDoc(outerFrom, range.from) === before &&
|
||||
view.state.sliceDoc(range.to, outerTo) === after
|
||||
) {
|
||||
return {
|
||||
changes: [
|
||||
{ from: outerFrom, to: range.from, insert: '' },
|
||||
{ from: range.to, to: outerTo, insert: '' }
|
||||
],
|
||||
range: EditorSelection.range(outerFrom, outerFrom + text.length)
|
||||
}
|
||||
}
|
||||
|
||||
const insert = before + text + after
|
||||
return {
|
||||
changes: { from: range.from, to: range.to, insert },
|
||||
range: EditorSelection.range(
|
||||
range.from + before.length,
|
||||
range.from + before.length + text.length
|
||||
)
|
||||
}
|
||||
})
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置/取消标题层级(作用于主选区所在行)。 */
|
||||
function setHeading(level: number): Command {
|
||||
return view => {
|
||||
const { state } = view
|
||||
const pos = state.selection.main.head
|
||||
const line = state.doc.lineAt(pos)
|
||||
const match = /^(#{1,6})\s+/.exec(line.text)
|
||||
const existing = match ? match[1].length : 0
|
||||
const removeLen = match ? match[0].length : 0
|
||||
const prefix = existing === level ? '' : `${'#'.repeat(level)} `
|
||||
view.dispatch({
|
||||
changes: { from: line.from, to: line.from + removeLen, insert: prefix },
|
||||
selection: { anchor: line.from + prefix.length + Math.max(0, pos - line.from - removeLen) }
|
||||
})
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** 行首前缀开关(引用 / 列表)。 */
|
||||
function toggleLinePrefix(prefix: string): Command {
|
||||
return view => {
|
||||
const { state } = view
|
||||
const pos = state.selection.main.head
|
||||
const line = state.doc.lineAt(pos)
|
||||
if (line.text.startsWith(prefix)) {
|
||||
view.dispatch({ changes: { from: line.from, to: line.from + prefix.length, insert: '' } })
|
||||
} else {
|
||||
view.dispatch({ changes: { from: line.from, insert: prefix } })
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** 插入链接:`[文字](url)`,并选中 `url` 占位便于直接替换。 */
|
||||
const insertLink: Command = view => {
|
||||
const { state } = view
|
||||
const range = state.selection.main
|
||||
const text = state.sliceDoc(range.from, range.to) || '链接文字'
|
||||
const insert = `[${text}](url)`
|
||||
const urlFrom = range.from + text.length + 3
|
||||
view.dispatch({
|
||||
changes: { from: range.from, to: range.to, insert },
|
||||
selection: EditorSelection.range(urlFrom, urlFrom + 3)
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
/** 代码块:包围选区,或新起一个空代码块。 */
|
||||
const insertCodeBlock: Command = view => {
|
||||
const { state } = view
|
||||
const range = state.selection.main
|
||||
const text = state.sliceDoc(range.from, range.to)
|
||||
const insert = `\`\`\`\n${text}\n\`\`\``
|
||||
view.dispatch({
|
||||
changes: { from: range.from, to: range.to, insert },
|
||||
selection: EditorSelection.cursor(range.from + 4 + text.length)
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
/** 编辑器快捷键(优先级高于全局快捷键)。 */
|
||||
export const notesKeymap: KeyBinding[] = [
|
||||
{ key: 'Mod-b', run: wrapSelection('**'), preventDefault: true },
|
||||
{ key: 'Mod-i', run: wrapSelection('*'), preventDefault: true },
|
||||
{ key: 'Mod-Shift-x', run: wrapSelection('~~'), preventDefault: true },
|
||||
{ key: 'Mod-e', run: wrapSelection('`'), preventDefault: true },
|
||||
{ key: 'Mod-k', run: insertLink, preventDefault: true },
|
||||
{ key: 'Mod-Shift-c', run: insertCodeBlock, preventDefault: true },
|
||||
{ key: 'Mod-1', run: setHeading(1), preventDefault: true },
|
||||
{ key: 'Mod-2', run: setHeading(2), preventDefault: true },
|
||||
{ key: 'Mod-3', run: setHeading(3), preventDefault: true },
|
||||
{ key: 'Mod-Shift-8', run: toggleLinePrefix('- '), preventDefault: true },
|
||||
{ key: 'Mod-Shift-9', run: toggleLinePrefix('- [ ] '), preventDefault: true },
|
||||
{ key: 'Mod-Shift-.', run: toggleLinePrefix('> '), preventDefault: true }
|
||||
]
|
||||
|
||||
/** 供工具栏按钮调用的命令集合。 */
|
||||
export const notesCommands = {
|
||||
bold: wrapSelection('**'),
|
||||
italic: wrapSelection('*'),
|
||||
strikethrough: wrapSelection('~~'),
|
||||
inlineCode: wrapSelection('`'),
|
||||
link: insertLink,
|
||||
codeBlock: insertCodeBlock,
|
||||
heading: setHeading,
|
||||
bulletList: toggleLinePrefix('- '),
|
||||
taskList: toggleLinePrefix('- [ ] '),
|
||||
quote: toggleLinePrefix('> ')
|
||||
}
|
||||
|
||||
/** 判断某一行是否以给定前缀开头(工具栏高亮态用)。 */
|
||||
export function lineHasPrefix(state: EditorState, prefix: string): boolean {
|
||||
const line = state.doc.lineAt(state.selection.main.head)
|
||||
return line.text.startsWith(prefix)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 语言支持:扩展名 → CM6 语言扩展,**按需动态加载**。
|
||||
*
|
||||
* # 为什么必须懒加载
|
||||
*
|
||||
* `@codemirror/language-data` 的便利之处是「一个入口拿到所有语言」,代价是把
|
||||
* 30 多个语言包全挂在依赖图上。若静态 `import`,Vite 会把它们塞进主 chunk ——
|
||||
* 本项目首屏还要承载模块系统、终端、音乐等一堆东西,没有余量给「可能永远用不到
|
||||
* 的 .cpp 语法」。这里手写一张显式映射表,每个语言一个 `import()`,Vite 自动切成
|
||||
* 独立 chunk:用户打开 `.rs` 才下载 rust 的解析器(约 10~30 kB)。
|
||||
*
|
||||
* # 为什么不用 languageData 的 `LanguageDescription.matchFilename`
|
||||
*
|
||||
* 那个 API 是给「Markdown 内嵌代码块」用的,它按 name/alias 匹配,覆盖不到
|
||||
* `.vue`、`.toml`、`.ps1` 这类扩展名(以及一大批我们想要的别名)。手写表虽然
|
||||
* 啰嗦,但**行为完全可预期**:前端没有「这个扩展名到底映射到哪个语言」的推理,
|
||||
* 只有一张查表。
|
||||
*
|
||||
* # 围栏代码块的内嵌高亮(P2)
|
||||
*
|
||||
* Markdown 里 ```rust 这类代码块本可由 `codeLanguages: languages` 内嵌高亮,
|
||||
* 但 language-data 的清单需要异步加载,而 `markdown()` 是同步构建设置的。
|
||||
* P1 先不做:没有内嵌高亮只是「代码块内是单色」,而异步清单会引入一次
|
||||
* 「打开笔记 → 重配置编辑器」的抖动,得不偿失。
|
||||
*
|
||||
* # 未内置的语言
|
||||
*
|
||||
* 表格之外的一律退回纯文本(不加载任何扩展)。三类常见的缺口及理由:
|
||||
* - `.scss` / `.less`:`@codemirror/lang-css` 只导出 `css()`,SCSS/Less 需要
|
||||
* `@codemirror/lang-sass`(更重且语法覆盖不全)。CSS 变量为主的样式表用
|
||||
* `css()` 就够,因此不引入;
|
||||
* - `.sh` / `.ps1` / `.toml` / `.ini`:本来可以经 `@codemirror/legacy-modes` 的
|
||||
* 流式解析补上,但那需要另一套高亮标签(Stream Language 的 token 名与 Lezer
|
||||
* 高亮标签并非一一对应),P1 先不做;
|
||||
* - 其余未知扩展名:纯文本。
|
||||
*
|
||||
* 统一原则:宁可「没高亮但能正常编辑」,也不要「高亮错乱」。
|
||||
*/
|
||||
|
||||
import { markdown, markdownLanguage } from '@codemirror/lang-markdown'
|
||||
import { GFM } from '@lezer/markdown'
|
||||
import { type Extension } from '@codemirror/state'
|
||||
|
||||
/**
|
||||
* 语言加载器:返回扩展(可同步、可异步)。
|
||||
*
|
||||
* **允许返回 `null`**:表示「这个文件没有内置语言」。用 `null` 而不是空数组表达
|
||||
* 「本来就没有」,是为了让调用方(`EditorHost`)能在日志里区分「没有语言」与
|
||||
* 「有语言但被卸下」;两者在 CM6 的 Compartment 里行为相同,但语义不同。
|
||||
*/
|
||||
export type LanguageLoader = () => Extension | null | Promise<Extension | null>
|
||||
|
||||
interface LanguageEntry {
|
||||
/** 状态栏展示名 */
|
||||
label: string
|
||||
load: LanguageLoader
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展名(小写,不含点)→ 语言。
|
||||
*
|
||||
* 值写成 thunk 而不是已加载的扩展:`import()` 只在真正调用时执行,
|
||||
* 表本身的构建不产生任何网络/打包开销。
|
||||
*/
|
||||
const LOADERS: Record<string, LanguageEntry> = {
|
||||
// ===== 前端 =====
|
||||
js: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
|
||||
mjs: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
|
||||
cjs: { label: 'JavaScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript()) },
|
||||
jsx: { label: 'JSX', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ jsx: true })) },
|
||||
ts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
|
||||
mts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
|
||||
cts: { label: 'TypeScript', load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })) },
|
||||
tsx: {
|
||||
label: 'TSX',
|
||||
load: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true, jsx: true }))
|
||||
},
|
||||
vue: { label: 'Vue', load: () => import('@codemirror/lang-vue').then(m => m.vue()) },
|
||||
html: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
|
||||
htm: { label: 'HTML', load: () => import('@codemirror/lang-html').then(m => m.html()) },
|
||||
css: { label: 'CSS', load: () => import('@codemirror/lang-css').then(m => m.css()) },
|
||||
|
||||
// ===== 数据与配置 =====
|
||||
json: { label: 'JSON', load: () => import('@codemirror/lang-json').then(m => m.json()) },
|
||||
jsonc: { label: 'JSON', load: () => import('@codemirror/lang-json').then(m => m.json()) },
|
||||
yaml: { label: 'YAML', load: () => import('@codemirror/lang-yaml').then(m => m.yaml()) },
|
||||
yml: { label: 'YAML', load: () => import('@codemirror/lang-yaml').then(m => m.yaml()) },
|
||||
xml: { label: 'XML', load: () => import('@codemirror/lang-xml').then(m => m.xml()) },
|
||||
svg: { label: 'SVG', load: () => import('@codemirror/lang-xml').then(m => m.xml()) },
|
||||
sql: { label: 'SQL', load: () => import('@codemirror/lang-sql').then(m => m.sql()) },
|
||||
|
||||
// ===== 后端与系统 =====
|
||||
py: { label: 'Python', load: () => import('@codemirror/lang-python').then(m => m.python()) },
|
||||
pyw: { label: 'Python', load: () => import('@codemirror/lang-python').then(m => m.python()) },
|
||||
rs: { label: 'Rust', load: () => import('@codemirror/lang-rust').then(m => m.rust()) },
|
||||
go: { label: 'Go', load: () => import('@codemirror/lang-go').then(m => m.go()) },
|
||||
java: { label: 'Java', load: () => import('@codemirror/lang-java').then(m => m.java()) },
|
||||
c: { label: 'C', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
|
||||
h: { label: 'C/C++ Header', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
|
||||
cc: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
|
||||
cpp: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
|
||||
cxx: { label: 'C++', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) },
|
||||
hpp: { label: 'C++ Header', load: () => import('@codemirror/lang-cpp').then(m => m.cpp()) }
|
||||
}
|
||||
|
||||
/** 语言缓存:同一个语言只解析一次,之后复用已加载的扩展。 */
|
||||
const cache = new Map<string, Promise<Extension | null>>()
|
||||
|
||||
/** 从文件名取扩展名(小写、不含点;无扩展名返回空串)。 */
|
||||
export function extensionOf(fileName: string): string {
|
||||
const base = fileName.split(/[\\/]/).pop() ?? ''
|
||||
const dot = base.lastIndexOf('.')
|
||||
if (dot <= 0 || dot === base.length - 1) return ''
|
||||
return base.slice(dot + 1).toLowerCase()
|
||||
}
|
||||
|
||||
/** 该文件名是否有内置语言支持。 */
|
||||
export function hasLanguage(fileName: string): boolean {
|
||||
return !!LOADERS[extensionOf(fileName)]
|
||||
}
|
||||
|
||||
/** 文件名对应的语言展示信息(无支持时返回「纯文本」)。 */
|
||||
export function languageLabel(fileName: string): string {
|
||||
return LOADERS[extensionOf(fileName)]?.label ?? '纯文本'
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析文件名对应的语言扩展。
|
||||
*
|
||||
* 返回 `null` 表示「没有内置语言」——调用方据此保持纯文本,而不是传空数组:
|
||||
* 空数组与 `null` 在 Compartment 里语义相同,但 `null` 表达的是「本来就没有」,
|
||||
* 而 `[]` 表达的是「有语言但选了无」,两者的日志与调试含义不同。
|
||||
*/
|
||||
export async function loadLanguage(fileName: string): Promise<Extension | null> {
|
||||
const ext = extensionOf(fileName)
|
||||
const entry = LOADERS[ext]
|
||||
if (!entry) return null
|
||||
|
||||
const cached = cache.get(ext)
|
||||
if (cached) return cached
|
||||
|
||||
const pending = Promise.resolve(entry.load()).catch(error => {
|
||||
// 加载失败(离线 / chunk 404)时**不要**把失败的 promise 留在缓存里:
|
||||
// 用户重连后再打开同一类型文件应当能成功
|
||||
cache.delete(ext)
|
||||
throw error
|
||||
})
|
||||
cache.set(ext, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
/**
|
||||
* 笔记(Markdown)模式的语言扩展。
|
||||
*
|
||||
* # 为什么显式加 GFM 扩展
|
||||
*
|
||||
* `markdown()` 默认只用**基础 CommonMark** 语法:表格(`| a | b |`)、任务列表
|
||||
* (`- [ ]`)、删除线(`~~x~~`)都不会被解析成对应节点,于是
|
||||
* - Live Preview 拿不到 `Table` / `TaskMarker` 节点,表格与复选框渲染不出来;
|
||||
* - 大纲提取虽然是自己扫文本(不依赖语法树),但**编辑器内的**高亮与折叠也会缺一块。
|
||||
*
|
||||
* `@lezer/markdown` 导出 `GFM`(= Table + TaskList + Strikethrough + Autolink 的扩展包),
|
||||
* 交给 `extensions` 即可。注意它只影响**解析**,不改变渲染 —— 渲染仍由
|
||||
* `markdownLivePreview.ts` 的装饰负责。
|
||||
*
|
||||
* 与代码文件走同一条 `loadLanguage` 通道(`md` → Markdown),因此笔记与代码
|
||||
* 在「语言如何装配」上没有第二条路径。
|
||||
*/
|
||||
export function markdownLoader(): LanguageLoader {
|
||||
return () =>
|
||||
markdown({
|
||||
base: markdownLanguage,
|
||||
extensions: GFM
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* markdownExport 单测(Node 内置 test runner)。
|
||||
*
|
||||
* # 为什么用 `renderMarkdownFragmentRaw`
|
||||
*
|
||||
* DOMPurify 需要 `window`/`document`:Node 里 `isSupported === false` 且对象上**根本
|
||||
* 没有** `sanitize`,所以「消毒后的片段」在纯 Node 下无法断言(本文件里如实
|
||||
* `t.skip()`,不装 jsdom、更不为跑通测试降低消毒强度)。
|
||||
* 但「fence 语言识别、任务列表、表格、链接、图片」这些**渲染**行为是纯字符串逻辑,
|
||||
* 必须能脱离浏览器回归,所以走模块里明确标注为「仅供单测」的未消毒入口。
|
||||
*
|
||||
* # 为什么两个方向都断言
|
||||
*
|
||||
* 一边断言「未消毒的片段里确实带着 `onerror=` / `<script>`」(证明消毒不是可选项),
|
||||
* 一边断言「无 DOM 时消毒入口失败关闭,返回空串而不是原文」(证明降级方向是安全的那
|
||||
* 一侧)。有 DOM 的环境(浏览器/未来的 DOM shim)会自动改跑真正的消毒断言。
|
||||
*/
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import DOMPurify from 'dompurify'
|
||||
import {
|
||||
markdownToPlainText,
|
||||
renderMarkdownFragment,
|
||||
renderMarkdownFragmentRaw,
|
||||
renderNoteHtml,
|
||||
stripFrontMatter
|
||||
} from './markdownExport.ts'
|
||||
|
||||
/** 当前环境能不能真消毒(浏览器/happy-dom 之类为 true,纯 Node 为 false) */
|
||||
const domAvailable = DOMPurify.isSupported && typeof DOMPurify.sanitize === 'function'
|
||||
|
||||
// ===== front-matter =====
|
||||
|
||||
test('stripFrontMatter:剥掉闭合的 front-matter', () => {
|
||||
const src = ['---', 'title: 周报', 'tags:', ' - 工作', '---', '# 正文', '', '内容'].join('\n')
|
||||
assert.equal(stripFrontMatter(src), '# 正文\n\n内容')
|
||||
})
|
||||
|
||||
test('stripFrontMatter:闭合行是末行(末尾没有换行)也能处理', () => {
|
||||
assert.equal(stripFrontMatter('---\ntitle: x\n---'), '')
|
||||
assert.equal(stripFrontMatter('---\ntitle: x\n---\n正文'), '正文')
|
||||
})
|
||||
|
||||
test('stripFrontMatter:未闭合时整篇当正文,一个字符都不吃', () => {
|
||||
const unclosed = '---\ntitle: x\n# 正文\n--- 少了点什么'
|
||||
assert.equal(stripFrontMatter(unclosed), unclosed)
|
||||
// 只有一行 `---` 时同样不认
|
||||
assert.equal(stripFrontMatter('---'), '---')
|
||||
})
|
||||
|
||||
test('stripFrontMatter:CRLF 与 UTF-8 BOM', () => {
|
||||
assert.equal(stripFrontMatter('---\r\ntitle: x\r\n---\r\n正文\r\n'), '正文\r\n')
|
||||
assert.equal(stripFrontMatter('\uFEFF---\r\ntitle: x\r\n---\r\n正文'), '正文')
|
||||
// 没有 front-matter 时也要剥 BOM:留着它 markdown-it 会渲染成不可见怪字符
|
||||
assert.equal(stripFrontMatter('\uFEFF# 正文'), '# 正文')
|
||||
})
|
||||
|
||||
test('stripFrontMatter:第一行不是整行 --- 时不认', () => {
|
||||
assert.equal(stripFrontMatter('--- x\na: 1\n---\n正文'), '--- x\na: 1\n---\n正文')
|
||||
assert.equal(stripFrontMatter(' ---\na: 1\n---\n正文'), ' ---\na: 1\n---\n正文')
|
||||
})
|
||||
|
||||
test('stripFrontMatter:只剥第一段,正文里的 --- 原样保留', () => {
|
||||
assert.equal(stripFrontMatter('---\na: 1\n---\n正文\n---\n更多'), '正文\n---\n更多')
|
||||
})
|
||||
|
||||
// ===== 纯文本摘要 =====
|
||||
|
||||
test('markdownToPlainText:去掉标记、保留文字、折叠空白', () => {
|
||||
const src = [
|
||||
'---',
|
||||
'title: 元数据不该出现',
|
||||
'---',
|
||||
'# 标题一',
|
||||
'',
|
||||
'这是 **粗体**、*斜体*、`行内代码`,还有 [链接文字](https://example.com/a) 和 。',
|
||||
'',
|
||||
'> 引用行',
|
||||
'',
|
||||
'- [ ] 待办',
|
||||
'- 普通项',
|
||||
'',
|
||||
'```js',
|
||||
'const a = 1',
|
||||
'```',
|
||||
'',
|
||||
'<p>html 段落</p>'
|
||||
].join('\n')
|
||||
const text = markdownToPlainText(src)
|
||||
assert.ok(!text.includes('元数据不该出现'), 'front-matter 必须被剥掉')
|
||||
for (const kept of ['标题一', '粗体', '斜体', '行内代码', '链接文字', '图片说明', '引用行', '待办', '普通项', 'const a = 1', 'html 段落']) {
|
||||
assert.ok(text.includes(kept), `摘要应保留「${kept}」:${text}`)
|
||||
}
|
||||
for (const dropped of ['**', '`', '](', 'https://example.com', 'images/x.png', '<p>', '#', '>']) {
|
||||
assert.ok(!text.includes(dropped), `摘要不该残留「${dropped}」:${text}`)
|
||||
}
|
||||
assert.ok(!/ {2}/.test(text), `空白应折叠成单空格:${text}`)
|
||||
})
|
||||
|
||||
test('markdownToPlainText:默认 120 字符截断并加省略号', () => {
|
||||
const text = markdownToPlainText(`# ${'x'.repeat(200)}`)
|
||||
assert.equal(text.length, 121)
|
||||
assert.ok(text.endsWith('…'))
|
||||
assert.equal(text, `${'x'.repeat(120)}…`)
|
||||
})
|
||||
|
||||
test('markdownToPlainText:按码点截断,emoji 不会被劈成半个', () => {
|
||||
const text = markdownToPlainText('😀'.repeat(10), 3)
|
||||
assert.equal(text, '😀😀😀…')
|
||||
assert.equal(Array.from(text).length, 4)
|
||||
})
|
||||
|
||||
test('markdownToPlainText:maxChars 为 0 时返回空串', () => {
|
||||
assert.equal(markdownToPlainText('随便什么内容', 0), '')
|
||||
})
|
||||
|
||||
test('markdownToPlainText:#tag 不算标题,分隔线要清干净', () => {
|
||||
// 与 outline.ts 同一套判断:`#` 后必须有空白才算 ATX 标题
|
||||
assert.equal(markdownToPlainText('#hashtag 不是标题'), '#hashtag 不是标题')
|
||||
assert.equal(markdownToPlainText('* * *\n\n正文'), '正文')
|
||||
assert.equal(markdownToPlainText('***'), '')
|
||||
assert.equal(markdownToPlainText('标题\n==='), '标题')
|
||||
// 表格:对齐分隔行是纯标记,要丢;单元格文字留着
|
||||
const table = markdownToPlainText('| 模块 | 状态 |\n| --- | --- |\n| 导出 | 完成 |')
|
||||
assert.ok(!table.includes('---'), table)
|
||||
assert.ok(table.includes('模块'), table)
|
||||
assert.ok(table.includes('导出'), table)
|
||||
})
|
||||
|
||||
// ===== 渲染(未消毒片段)=====
|
||||
|
||||
test('围栏代码块:info string 命中注册表时按该语言高亮', () => {
|
||||
const html = renderMarkdownFragmentRaw('```ts\nconst n: number = 1\n```')
|
||||
assert.match(html, /<pre class="hljs">/)
|
||||
assert.match(html, /<code class="hljs language-ts">/)
|
||||
assert.match(html, /hljs-keyword/)
|
||||
})
|
||||
|
||||
test('围栏代码块:`.js` 这类写法也能归一成语言名', () => {
|
||||
const html = renderMarkdownFragmentRaw('```.js\nlet a = 1\n```')
|
||||
assert.match(html, /<code class="hljs language-js">/)
|
||||
})
|
||||
|
||||
test('围栏代码块:未注册的语言不抛错,猜不准的散文保持纯文本', () => {
|
||||
const html = renderMarkdownFragmentRaw('```notalang\nplain text here\n```')
|
||||
assert.match(html, /<pre class="hljs">/)
|
||||
assert.match(html, /plain text here/)
|
||||
// 相关度低于下限时不许上色:给散文瞎上色比没颜色更糟
|
||||
assert.match(html, /<code class="hljs">/)
|
||||
assert.doesNotMatch(html, /language-notalang/)
|
||||
})
|
||||
|
||||
test('围栏代码块:语言名拼错时在候选集里自动识别', () => {
|
||||
const html = renderMarkdownFragmentRaw('```typescrpt\ndef f(x):\n return x + 1\n```')
|
||||
assert.match(html, /<code class="hljs language-python">/)
|
||||
assert.match(html, /hljs-keyword/)
|
||||
})
|
||||
|
||||
test('围栏代码块:内容被转义,原始 HTML 不会漏出去', () => {
|
||||
const html = renderMarkdownFragmentRaw('```\n<b>&"x\n```')
|
||||
assert.match(html, /<b>&"x/)
|
||||
assert.doesNotMatch(html, /<b>/)
|
||||
})
|
||||
|
||||
test('表格渲染', () => {
|
||||
const html = renderMarkdownFragmentRaw('| 列 A | 列 B |\n| --- | --- |\n| 1 | 2 |')
|
||||
assert.match(html, /<table>/)
|
||||
assert.match(html, /<th>列 A<\/th>/)
|
||||
assert.match(html, /<td>2<\/td>/)
|
||||
})
|
||||
|
||||
test('任务列表渲染成 disabled 复选框', () => {
|
||||
const html = renderMarkdownFragmentRaw('- [ ] 未完成\n- [x] 已完成\n- 普通项')
|
||||
assert.match(html, /<input class="task-list-item-checkbox" type="checkbox" disabled>/)
|
||||
assert.match(html, /type="checkbox" disabled checked>/)
|
||||
assert.match(html, /class="task-list-item"/)
|
||||
assert.match(html, /普通项/)
|
||||
})
|
||||
|
||||
test('链接渲染与裸 URL 自动识别', () => {
|
||||
const html = renderMarkdownFragmentRaw('[Thing](https://example.com/a) 与 https://example.org/b')
|
||||
assert.match(html, /<a href="https:\/\/example\.com\/a">Thing<\/a>/)
|
||||
assert.match(html, /href="https:\/\/example\.org\/b"/)
|
||||
})
|
||||
|
||||
test('图片渲染(保留相对路径与 alt)', () => {
|
||||
const html = renderMarkdownFragmentRaw('')
|
||||
assert.match(html, /<img src="images\/demo\.png" alt="示意图">/)
|
||||
})
|
||||
|
||||
test('未消毒片段确实会带出 XSS 载荷(说明消毒不是可选项)', () => {
|
||||
const raw = renderMarkdownFragmentRaw('<img src=x onerror=alert(1)>\n\n<script>alert(1)</script>')
|
||||
assert.match(raw, /onerror=/)
|
||||
assert.match(raw, /<script>/)
|
||||
})
|
||||
|
||||
// ===== 消毒 =====
|
||||
|
||||
test('无 DOM 环境:消毒入口失败关闭,返回空串而不是原文', t => {
|
||||
if (domAvailable) {
|
||||
t.skip('本环境有 DOM,消毒可用,该降级分支不适用')
|
||||
return
|
||||
}
|
||||
assert.equal(renderMarkdownFragment('<script>alert(1)</script>'), '')
|
||||
assert.equal(renderMarkdownFragment('# 正常标题'), '')
|
||||
})
|
||||
|
||||
test('XSS:<script>、onerror、javascript: 被剥掉,该留的留着', t => {
|
||||
if (!domAvailable) {
|
||||
t.skip('Node 无 window/document:DOMPurify.isSupported=false,无 sanitize 可调')
|
||||
return
|
||||
}
|
||||
const dirty = [
|
||||
'<script>alert(1)</script>',
|
||||
'',
|
||||
'<img src=x onerror=alert(1)>',
|
||||
'',
|
||||
'[点我](javascript:alert(1))',
|
||||
'',
|
||||
'<span style="position:fixed;top:0">覆盖界面</span>',
|
||||
'',
|
||||
'<img src="a.png" srcset="https://evil.example/x.png 1x">',
|
||||
'',
|
||||
'<style>body{display:none}</style>'
|
||||
].join('\n')
|
||||
const html = renderMarkdownFragment(dirty)
|
||||
assert.ok(!html.includes('onerror='), html)
|
||||
assert.ok(!html.includes('<script'), html)
|
||||
assert.ok(!html.includes('javascript:'), html)
|
||||
assert.ok(!html.includes('style='), html)
|
||||
assert.ok(!html.includes('srcset='), html)
|
||||
assert.ok(!html.includes('<style'), html)
|
||||
|
||||
const kept = renderMarkdownFragment(
|
||||
'```ts\nconst a = 1\n```\n\n| a |\n| --- |\n| 1 |\n\n- [x] 完成\n\n\n\n<a href="https://example.com" target="_blank">外链</a>'
|
||||
)
|
||||
assert.match(kept, /class="hljs"/)
|
||||
assert.match(kept, /<table>/)
|
||||
assert.match(kept, /type="checkbox" disabled checked/)
|
||||
assert.match(kept, /<img src="a\.png"/)
|
||||
assert.match(kept, /target="_blank"/)
|
||||
})
|
||||
|
||||
// ===== 导出文档 =====
|
||||
|
||||
test('renderNoteHtml:结构完整、<title> 与页首标题都转义', () => {
|
||||
const html = renderNoteHtml({
|
||||
title: 'A & B <C>',
|
||||
fileName: 'a.md',
|
||||
markdown: '# 正文',
|
||||
exportedAt: new Date(2026, 0, 2, 3, 4)
|
||||
})
|
||||
assert.ok(html.startsWith('<!doctype html>'))
|
||||
assert.ok(html.includes('<html lang="zh-CN">'))
|
||||
assert.ok(html.includes('<meta charset="utf-8">'))
|
||||
assert.ok(html.includes('name="viewport"'))
|
||||
assert.ok(html.includes('<title>A & B <C></title>'))
|
||||
assert.ok(html.includes('<h1 class="note-title">A & B <C></h1>'))
|
||||
assert.ok(html.includes('导出自 Thing · 2026-01-02 03:04'))
|
||||
assert.ok(html.includes('@media print'))
|
||||
})
|
||||
|
||||
test('renderNoteHtml:内联样式自带排版与高亮配色,不依赖外部资源', () => {
|
||||
const html = renderNoteHtml({ title: '排版', fileName: 'style.md', markdown: '正文' })
|
||||
assert.ok(html.includes('780px'))
|
||||
assert.ok(html.includes('line-height: 1.7'))
|
||||
assert.ok(html.includes('overflow-x: auto'))
|
||||
assert.ok(html.includes('background: #f6f8fa'))
|
||||
assert.ok(html.includes('border-collapse: collapse'))
|
||||
assert.ok(html.includes('border-left: 4px solid'))
|
||||
assert.ok(html.includes('img { max-width: 100%'))
|
||||
assert.ok(html.includes('.note-body mark'))
|
||||
for (const token of ['hljs-keyword', 'hljs-string', 'hljs-comment', 'hljs-number', 'hljs-title', 'hljs-attr']) {
|
||||
assert.ok(html.includes(`.${token}`), `缺少高亮配色 ${token}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('renderNoteHtml:样式与外壳里没有任何外部地址', () => {
|
||||
const html = renderNoteHtml({
|
||||
title: '离线笔记',
|
||||
fileName: 'offline.md',
|
||||
markdown: '# 标题\n\n纯文本,没有任何链接。'
|
||||
})
|
||||
const style = /<style>([\s\S]*?)<\/style>/.exec(html)?.[1] ?? ''
|
||||
assert.ok(style.length > 0)
|
||||
assert.ok(!/https?:\/\//.test(style), '内联样式里不能出现外链')
|
||||
assert.ok(!/https?:\/\//.test(html), '正文没有链接时整份文档都不该有外链')
|
||||
assert.ok(!/<link|<script|@import/i.test(html))
|
||||
})
|
||||
|
||||
test('renderNoteHtml:标题为空串时用 fileName 兜底,时间缺省用当前时间', () => {
|
||||
const html = renderNoteHtml({ title: ' ', fileName: '周报.md', markdown: '正文' })
|
||||
assert.ok(html.includes('<title>周报.md</title>'))
|
||||
assert.ok(html.includes('<h1 class="note-title">周报.md</h1>'))
|
||||
assert.match(html, /导出自 Thing · \d{4}-\d{2}-\d{2} \d{2}:\d{2}/)
|
||||
})
|
||||
@@ -0,0 +1,550 @@
|
||||
/**
|
||||
* 笔记导出 —— 把 Markdown 渲染成「能双击打开、能直接打印」的独立 HTML 文档。
|
||||
*
|
||||
* # 为什么产出一整份单文件 HTML
|
||||
*
|
||||
* 导出物必须能脱离本应用存在:发给别人、丢进归档、直接 Ctrl+P。所以这里吐出的是
|
||||
* 完整的 `<!doctype html>`,样式内联、**零外部请求**(无 CDN、无外链字体/CSS/JS)
|
||||
* —— 离线、换机器、几年后再打开都得是同一个样子。反过来这也意味着不能引用
|
||||
* `highlight.js/styles/*.css` 这类现成主题:它们会变成一个 `<link>`,文件一挪窝就
|
||||
* 掉样式。高亮配色改成在 [`EXPORT_STYLE`] 里内联一份最小 token 表。
|
||||
*
|
||||
* # 安全:这条链路的头号风险是 XSS
|
||||
*
|
||||
* 正文是用户内容,还可能来自别人的笔记库(导入/同步)。`markdown-it` 开了
|
||||
* `html: true`(笔记里嵌原生 HTML 很常见,刻意放行),所以渲染出的片段**必然**能
|
||||
* 包含 `<script>` / `onerror=` / `javascript:`。唯一出口是 `DOMPurify.sanitize()`:
|
||||
* 对外函数只返回消毒后的字符串;模块里唯一的「原始片段」函数
|
||||
* [`renderMarkdownFragmentRaw`] 明确标注为仅供单测,生产代码不要用。
|
||||
*
|
||||
* 消毒配置([`SANITIZE_CONFIG`])的取舍:
|
||||
* - **走 DOMPurify 默认 HTML 白名单,只做减法加两个属性**。默认白名单已经精确覆盖
|
||||
* 要保留的东西:`pre`/`code`(`class` 在默认属性表里,`hljs` token 靠它活下来)、
|
||||
* `table` 全家族、`img`(相对路径天然合法,`javascript:` 会被 URI 校验拦下)、
|
||||
* `input`(`type` / `disabled` / `checked` 都在默认属性表里,任务列表靠它)。
|
||||
* `on*` 事件属性不在白名单里,天然被剥 —— 这比自己手写一份 `ALLOWED_TAGS` 再漏一个
|
||||
* 标签安全得多,白名单越小越好维护。
|
||||
* - `FORBID_TAGS: ['style']`:DOMPurify **不解析 CSS**(官方文档明确说明)。`<style>`
|
||||
* 能重排/遮挡宿主界面(预览场景就在应用里渲染),必须拿掉。`script` 本来就在默认
|
||||
* `FORBID_CONTENTS` 里,元素**连内容**一起丢,不会留下 `alert(1)` 这种残渣文本。
|
||||
* - `FORBID_ATTR: ['style', 'srcset']`:内联 `style` 里的 `url()` 会拉外部资源,与本模块
|
||||
* 「导出文件零外链」的承诺直接冲突,`position:fixed` 之类还能盖住界面。`srcset` 同理是
|
||||
* 一条静默的外链通道(默认白名单里有它,而 markdown-it 永远生成不出来)。笔记里的格式
|
||||
* 用 Markdown 表达足够,这点保真度不值得换两个风险。
|
||||
* - `ADD_ATTR: ['target', 'rel']`:实测默认属性表里**没有** `target`(`rel` 有),而导出
|
||||
* 文档里点开外链应当新标签页打开;这是唯一的「加法」,加的是无脚本能力的属性。
|
||||
*
|
||||
* 消毒器不可用时**失败关闭**(fail-closed):DOMPurify 依赖 DOM,Node 里
|
||||
* `isSupported === false` 且根本没有 `sanitize`(实测 3.4.x:返回的对象上连该方法都
|
||||
* 不存在)。此时宁可返回空串,也绝不回退成「输出原文」。
|
||||
*
|
||||
* # 高亮
|
||||
*
|
||||
* `highlight.js` 是**同步** API:`getLanguage()` 查注册表、`highlight()` 出 token、
|
||||
* 未注册的语言用 `highlightAuto()` 兜底。三点必须注意:
|
||||
* 1. **不能拿未注册的语言直接撞 `highlight()`** —— 它会抛 `Unknown language`(还顺手
|
||||
* 打一条 console.error),一抛就把整篇渲染带崩,所以先 `getLanguage()` 过滤。
|
||||
* 2. 自动识别不能贪心:不限定候选集时 `highlightAuto` 会遍历全量 190+ 语言(实测首轮
|
||||
* 530ms、之后 ~30ms),答案还离谱(`const a = 1` → abnf)。所以只在「声明了语言却
|
||||
* 不在注册表」时用,候选集限定在 [`AUTO_DETECT_SUBSET`],相关度低于
|
||||
* [`AUTO_DETECT_MIN_RELEVANCE`] 就退回纯文本 —— 宁可没颜色,不要瞎上色。
|
||||
* 3. 任何一步抛错都退化成「转义后的纯文本」,高亮失败绝不影响正文。
|
||||
*
|
||||
* 这里用 `highlight.js` 全量包(190+ 语言,同步可用,任何 info string 都有机会命中)。
|
||||
* 代价是 NotesWindow chunk 变大:在 Tauri 里它从本地磁盘加载,换「```toml /
|
||||
* ```powershell / ```diff 也有高亮」是划算的。若哪天 chunk 预算吃紧,换成
|
||||
* `highlight.js/lib/core` + 精选语言注册即可,其余逻辑一行都不用动。
|
||||
*
|
||||
* # 边界与坑
|
||||
*
|
||||
* - front-matter 只认「第一行就是整行 `---`」,且必须再找到下一个整行 `---`;未闭合时
|
||||
* 整篇当正文(绝不能把笔记正文当元数据吃掉)。BOM 一律先剥:它留在正文里会被
|
||||
* markdown-it 当普通字符渲染出来,变成一个看不见的怪字符。
|
||||
* - 逐行扫描 + 偏移推进,而不是 `split` 再拼回去:CRLF 的正文必须原样保留。
|
||||
* - 导出时间手写格式化,不用 `toLocaleString`:输出稳定、可测、不随系统 locale 变样。
|
||||
* - 不碰 Vue 与 CodeMirror,只依赖 markdown-it / DOMPurify / highlight.js,可以脱离
|
||||
* 编辑器单测(`markdownExport.test.ts`)。
|
||||
*/
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import type { StateCore } from 'markdown-it'
|
||||
import DOMPurify from 'dompurify'
|
||||
import type { Config as DomPurifyConfig } from 'dompurify'
|
||||
import hljs from 'highlight.js'
|
||||
|
||||
/** 单篇笔记导出为 HTML 所需的输入 */
|
||||
export interface NoteHtmlInput {
|
||||
/** 笔记标题(用于 <title> 与页首大标题;空串则用 fileName 兜底) */
|
||||
title: string
|
||||
/** 文件名(含 .md,作为标题兜底) */
|
||||
fileName: string
|
||||
/** Markdown 原文(**含 front-matter**,函数内部负责剥离) */
|
||||
markdown: string
|
||||
/** 导出时间(用于页脚;不传则用当前时间) */
|
||||
exportedAt?: Date
|
||||
/**
|
||||
* 是否对围栏代码块做语法高亮(默认 `true`)。
|
||||
*
|
||||
* 关掉它的场景是「打印」:黑白打印机上浅色 token 常常淡到看不见,而不上色至少是
|
||||
* 稳定的黑字。对应设置项 `NoteSettings.exportHighlight`。
|
||||
*/
|
||||
highlight?: boolean
|
||||
}
|
||||
|
||||
/** 正文最大宽度(px):A4 打印约 180mm,屏幕上也是舒服的阅读行宽 */
|
||||
const BODY_MAX_WIDTH = 780
|
||||
|
||||
/** 自动识别的相关度下限:低于它说明 highlight.js 只是在瞎猜,不如不上色 */
|
||||
const AUTO_DETECT_MIN_RELEVANCE = 3
|
||||
|
||||
/** 超过这个长度的代码块不做自动识别:长文本上自动识别是性能地雷(哪怕有候选集限制) */
|
||||
const AUTO_DETECT_MAX_CHARS = 20000
|
||||
|
||||
/**
|
||||
* 未注册语言的自动识别候选集。**必须给候选集**:不给的话 `highlightAuto` 会遍历全量
|
||||
* 190+ 语言 —— 实测首轮 530ms、之后每次 ~30ms,而且答案离谱(`plain text here` →
|
||||
* applescript、`const a = 1` → abnf)。限定在常用语言上只要 0.5~15ms,答案也合理得多。
|
||||
* 名字都是 highlight.js 注册表里的正式名/别名,未注册的名字会被它自己过滤掉。
|
||||
*/
|
||||
const AUTO_DETECT_SUBSET = [
|
||||
'javascript',
|
||||
'typescript',
|
||||
'json',
|
||||
'bash',
|
||||
'python',
|
||||
'java',
|
||||
'c',
|
||||
'cpp',
|
||||
'csharp',
|
||||
'go',
|
||||
'rust',
|
||||
'sql',
|
||||
'yaml',
|
||||
'xml',
|
||||
'css',
|
||||
'markdown',
|
||||
'diff',
|
||||
'ini',
|
||||
'powershell'
|
||||
]
|
||||
|
||||
/** 文本/属性转义表:文本节点用 `&<>`,双引号属性再加 `"` 与 `'` */
|
||||
const HTML_ESCAPES: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}
|
||||
|
||||
/** HTML 文本/属性转义:导出的每个动态值(标题、语言名、时间)都必须过这里 */
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replace(/[&<>"']/g, ch => HTML_ESCAPES[ch] ?? ch)
|
||||
}
|
||||
|
||||
/** 纯文本摘要里要还原的常见实体(` ` 还原成空格,交给后续空白折叠处理) */
|
||||
const ENTITY_TEXTS: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'",
|
||||
' ': ' '
|
||||
}
|
||||
|
||||
/** 行是不是 front-matter 分隔线:整行 `---`(允许行尾空格/制表符,CRLF 的 `\r` 先摘掉) */
|
||||
function isFrontMatterDelimiter(line: string): boolean {
|
||||
const withoutCr = line.endsWith('\r') ? line.slice(0, -1) : line
|
||||
return /^---[ \t]*$/.test(withoutCr)
|
||||
}
|
||||
|
||||
/** 本地时间 `YYYY-MM-DD HH:mm`:手写格式化,避免 `toLocaleString` 随系统 locale 变样 */
|
||||
function formatLocalTimestamp(date: Date): string {
|
||||
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||
const ymd = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
|
||||
return `${ymd} ${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 剥掉 YAML front-matter,返回正文(无 front-matter 时原样返回)。
|
||||
*
|
||||
* 「原样」的唯一例外是 BOM:UTF-8 BOM 不是正文,留着它 markdown-it 会渲染出一个
|
||||
* 不可见字符,所以无论有没有 front-matter 都先剥掉。未闭合时**整篇**当正文返回
|
||||
* (只剥 BOM),绝不为了「看起来像元数据」把正文吃掉。
|
||||
*/
|
||||
export function stripFrontMatter(markdown: string): string {
|
||||
const text = markdown.charCodeAt(0) === 0xfeff ? markdown.slice(1) : markdown
|
||||
const firstBreak = text.indexOf('\n')
|
||||
// 连第一行都不是整行 `---`(或整个文件只有一行)→ 不可能有闭合
|
||||
if (firstBreak === -1 || !isFrontMatterDelimiter(text.slice(0, firstBreak))) return text
|
||||
// 逐行找闭合的整行 `---`;按偏移推进,正文的 CRLF 才能原样带回
|
||||
let lineStart = firstBreak + 1
|
||||
while (lineStart <= text.length) {
|
||||
const breakAt = text.indexOf('\n', lineStart)
|
||||
const lineEnd = breakAt === -1 ? text.length : breakAt
|
||||
if (isFrontMatterDelimiter(text.slice(lineStart, lineEnd))) {
|
||||
// 闭合行正好是末行(末尾没有换行)时,正文为空
|
||||
return breakAt === -1 ? '' : text.slice(breakAt + 1)
|
||||
}
|
||||
if (breakAt === -1) break
|
||||
lineStart = breakAt + 1
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Markdown 原文里提取纯文本摘要(用于列表/搜索展示;折叠空白,最多 maxChars 字符)。
|
||||
*
|
||||
* 截断按**码点**算(`Array.from`),不是 UTF-16 长度:不然 emoji 会被劈成半个代理对,
|
||||
* 摘要末尾显示成一个方块。`maxChars` 之后追加的 `…` 不计入上限,所以结果最长是
|
||||
* `maxChars + 1` 个字符。
|
||||
*/
|
||||
export function markdownToPlainText(markdown: string, maxChars = 120): string {
|
||||
const limit = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 0
|
||||
if (limit === 0) return ''
|
||||
let text = stripFrontMatter(markdown)
|
||||
|
||||
// 围栏只去掉标记行,代码内容保留(摘要里代码往往正是要搜的东西)
|
||||
text = text.replace(/^[ \t]*(?:```|~~~).*$/gm, '')
|
||||
// 行级标记:引用、标题、分隔线(分隔线必须在列表标记之前处理,否则 `* * *` 会被啃成残渣)、列表
|
||||
text = text.replace(/^[ \t]*>[ \t]?/gm, '')
|
||||
text = text.replace(/^[ \t]{0,3}#{1,6}(?:[ \t]+|$)/gm, '')
|
||||
text = text.replace(/^[ \t]*(?:[-*_=][ \t]*){3,}$/gm, '')
|
||||
// 表格对齐分隔行(`| --- | --- |`)是纯标记,整行丢掉;单元格的 `|` 保留(shell 管道也是它)
|
||||
text = text.replace(/^[ \t]*\|[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|[ \t]*$/gm, '')
|
||||
text = text.replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, '')
|
||||
// 图片(保留 alt)必须先于链接(保留文字)处理,否则 `` 会被链接规则切碎
|
||||
text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||||
text = text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||||
text = text.replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1')
|
||||
text = text.replace(/^[ \t]*\[[^\]]+\]:[^\n]*$/gm, '')
|
||||
// 任务列表标记 `[ ]` / `[x]`
|
||||
text = text.replace(/\[[ xX]\][ \t]+/g, '')
|
||||
// 强调:只在成对出现时剥标记,避免把 `snake_case` 里的下划线也吃掉
|
||||
text = text.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g, '$2')
|
||||
text = text.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g, '$2')
|
||||
text = text.replace(/(\*|_)(?=\S)([^*_]*?\S)\1/g, '$2')
|
||||
text = text.replace(/~~(?=\S)([\s\S]*?\S)~~/g, '$1')
|
||||
text = text.replace(/`+([^`]*)`+/g, '$1')
|
||||
// 行内 HTML 标签(含注释):整体换成空格,保证 `<p>a</p><p>b</p>` 不会粘成 "ab"
|
||||
text = text.replace(/<[^>]*>/g, ' ')
|
||||
text = text.replace(/&(?:amp|lt|gt|quot|#39|nbsp);/g, entity => ENTITY_TEXTS[entity] ?? entity)
|
||||
text = text.replace(/\s+/g, ' ').trim()
|
||||
|
||||
const chars = Array.from(text)
|
||||
return chars.length > limit ? `${chars.slice(0, limit).join('')}…` : text
|
||||
}
|
||||
|
||||
/** markdown-it 实例类型:默认导出是可调用的构造器,这里把实例类型取回来给插件签名用 */
|
||||
type MarkdownItInstance = ReturnType<typeof MarkdownIt>
|
||||
|
||||
/**
|
||||
* 最小 GFM 任务列表支持。
|
||||
*
|
||||
* markdown-it 本体不认 `- [ ]`(它只是普通文本),而任务列表是笔记里最常用的语法之一。
|
||||
* 这里不改源码,而是在 core 规则里把列表项首个子节点从 `[ ] foo` 改写成
|
||||
* 「disabled 复选框 + foo」的 `html_inline` token —— 生成的 `<input type="checkbox"
|
||||
* disabled>` 同样要过 DOMPurify 配置(已确认保留),所以就算以后换别的列表解析器,
|
||||
* 安全边界也不变。复选框一律 `disabled`:导出文档里它只是**状态展示**,可点的复选框
|
||||
* 会产生「改了但没保存」的错觉。
|
||||
*/
|
||||
function taskListPlugin(md: MarkdownItInstance): void {
|
||||
md.core.ruler.after('inline', 'thing-task-list', (state: StateCore): void => {
|
||||
const tokens = state.tokens
|
||||
for (let i = 2; i < tokens.length; i++) {
|
||||
if (tokens[i].type !== 'inline') continue
|
||||
// 标准嵌套是 list_item_open → paragraph_open → inline
|
||||
if (tokens[i - 1].type !== 'paragraph_open' || tokens[i - 2].type !== 'list_item_open') continue
|
||||
const children = tokens[i].children
|
||||
if (!children || children.length === 0) continue
|
||||
const first = children[0]
|
||||
if (first.type !== 'text') continue
|
||||
const matched = /^\[([ xX])\][ \t]+/.exec(first.content)
|
||||
if (!matched) continue
|
||||
first.content = first.content.slice(matched[0].length)
|
||||
const checkbox = new state.Token('html_inline', '', 0)
|
||||
const checked = matched[1] === ' ' ? '' : ' checked'
|
||||
checkbox.content = `<input class="task-list-item-checkbox" type="checkbox" disabled${checked}> `
|
||||
children.unshift(checkbox)
|
||||
tokens[i - 2].attrJoin('class', 'task-list-item')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 把围栏的 info string 归一成 highlight.js 认的语言名。
|
||||
*
|
||||
* markdown-it 传进来的 `lang` 通常已经是第一个词,但仍要容忍 `.js`、`{.py}`、
|
||||
* `python title="x"` 这些写法:只取第一段、去掉首尾的花括号与点、再截到第一个非语言字符。
|
||||
*/
|
||||
function normalizeFenceLanguage(rawLanguage: string): string {
|
||||
const firstWord = rawLanguage
|
||||
.trim()
|
||||
.split(/\s+/)[0]
|
||||
.replace(/^[.{}]+/, '')
|
||||
.replace(/[},]+$/, '')
|
||||
const matched = /^[a-z0-9+#_-]+/i.exec(firstWord)
|
||||
return matched ? matched[0].toLowerCase() : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一段代码渲染成 `<pre class="hljs"><code>…</code></pre>`。
|
||||
*
|
||||
* 返回值以 `<pre` 开头是 markdown-it 的约定:命中这个前缀它就原样采用,不再自己包一层
|
||||
* `<pre><code>`。整个过程不允许抛错 —— 任何异常都退化成转义后的纯文本,因为
|
||||
* markdown-it 不会替我们兜住 `highlight` 回调里的异常,一抛就是整篇渲染失败。
|
||||
*/
|
||||
function renderCodeBlock(code: string, rawLanguage: string): string {
|
||||
const language = normalizeFenceLanguage(rawLanguage)
|
||||
let inner = ''
|
||||
let highlighted = ''
|
||||
try {
|
||||
if (language && hljs.getLanguage(language)) {
|
||||
inner = hljs.highlight(code, { language, ignoreIllegals: true }).value
|
||||
highlighted = language
|
||||
} else if (language && code.length <= AUTO_DETECT_MAX_CHARS) {
|
||||
// 声明了语言却不在注册表(拼错、或全量包里也没有):在候选集里试一把
|
||||
const auto = hljs.highlightAuto(code, AUTO_DETECT_SUBSET)
|
||||
if (auto.language !== undefined && auto.relevance >= AUTO_DETECT_MIN_RELEVANCE) {
|
||||
inner = auto.value
|
||||
highlighted = auto.language
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
inner = ''
|
||||
highlighted = ''
|
||||
}
|
||||
if (inner === '') inner = escapeHtml(code)
|
||||
const codeClass = highlighted === '' ? ' class="hljs"' : ` class="hljs language-${escapeHtml(highlighted)}"`
|
||||
return `<pre class="hljs"><code${codeClass}>${inner}</code></pre>`
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染选项(模块级可变开关)。
|
||||
*
|
||||
* markdown-it 的 `highlight` 回调是**构造时**绑定的,而 `md` 是单例。这里用一个
|
||||
* 模块级开关让回调按当前调用决定行为 —— 比「为了关高亮再造一个 MarkdownIt 实例」
|
||||
* 简单,也比「把开关写进单例」(那会让一次导出永久影响后续所有渲染)安全:
|
||||
* [`renderWithOptions`] 进入时设、`finally` 里复位,不存在跨调用残留。
|
||||
*/
|
||||
let highlightEnabled = true
|
||||
|
||||
/**
|
||||
* markdown-it 实例。配置三件套的取舍:
|
||||
* - `html: true`:笔记里嵌原生 HTML 很常见,放行;安全由 DOMPurify 负责,不由解析器负责。
|
||||
* - `linkify: true`:裸 URL 变可点链接(导出文档里很实用)。
|
||||
* - `breaks: false`:与编辑器预览一致 —— 单换行仍是软换行,不变成 `<br>`。
|
||||
* - `typographer: false`:中文场景下智能标点收益小、翻车多(中文引号被替换),关掉。
|
||||
*/
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
breaks: false,
|
||||
typographer: false,
|
||||
highlight: (code, lang) => (highlightEnabled ? renderCodeBlock(code, lang) : '')
|
||||
})
|
||||
md.use(taskListPlugin)
|
||||
|
||||
/**
|
||||
* 按选项渲染 Markdown。
|
||||
*
|
||||
* `highlight: false` 时回调返回空串,markdown-it 会自己把代码转义并包进
|
||||
* `<pre><code>` —— 因此「关掉高亮」不需要再实现一遍代码块渲染。
|
||||
*/
|
||||
function renderWithOptions(markdown: string, highlight: boolean): string {
|
||||
const previous = highlightEnabled
|
||||
highlightEnabled = highlight
|
||||
try {
|
||||
return md.render(stripFrontMatter(markdown))
|
||||
} finally {
|
||||
highlightEnabled = previous
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DOMPurify 配置:默认 HTML 白名单 + 减法(见文件头「安全」一节的完整理由)。
|
||||
* 两个 `FORBID` 都是「默认白名单里有、但我们明确不要」的项,而不是自定义白名单。
|
||||
*/
|
||||
const SANITIZE_CONFIG: DomPurifyConfig = {
|
||||
FORBID_TAGS: ['style'],
|
||||
FORBID_ATTR: ['style', 'srcset'],
|
||||
ADD_ATTR: ['target', 'rel']
|
||||
}
|
||||
|
||||
/**
|
||||
* 消毒的唯一入口。
|
||||
*
|
||||
* 失败关闭:DOMPurify 需要 `window`/`document`,无 DOM 环境(Node 单测、SSR)里
|
||||
* `isSupported === false` 且 `sanitize` 根本不存在。此时返回空串 —— 宁可导出空白,
|
||||
* 也绝不把未消毒的 HTML 交给调用方。`try/catch` 同理:消毒环节出任何意外,出口都是
|
||||
* 「空」,不是「原文」。
|
||||
*/
|
||||
function sanitizeHtml(dirty: string): string {
|
||||
if (!DOMPurify.isSupported || typeof DOMPurify.sanitize !== 'function') return ''
|
||||
try {
|
||||
return DOMPurify.sanitize(dirty, SANITIZE_CONFIG)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown → **未消毒**的 HTML 片段(含 front-matter 时先剥)。
|
||||
*
|
||||
* ⚠️ 仅供单测与本模块内部使用:返回的字符串里可以带着 `<script>` 和 `onerror=`。
|
||||
* 之所以导出,是因为 DOMPurify 需要 DOM、Node 单测里跑不了,而「围栏语言识别、任务
|
||||
* 列表、表格、链接」这些**渲染**行为必须能脱离浏览器回归。浏览器/生产代码请一律走
|
||||
* [`renderMarkdownFragment`]。
|
||||
*/
|
||||
export function renderMarkdownFragmentRaw(markdown: string): string {
|
||||
return renderWithOptions(markdown, true)
|
||||
}
|
||||
|
||||
/** Markdown → 已消毒的 HTML 片段(不含 <html>/<style>;供预览/嵌入用) */
|
||||
export function renderMarkdownFragment(markdown: string): string {
|
||||
return sanitizeHtml(renderMarkdownFragmentRaw(markdown))
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出文档的全部样式(内联进 `<style>`)。
|
||||
*
|
||||
* 三条硬约束:① 不出现任何外部 URL —— 无 `@import`、无外链字体,双击离线可看;
|
||||
* ② 打印优先 —— 高亮配色只有一套(浅底深字),`@media print` 里再去掉底色与阴影,
|
||||
* 保证黑白打印仍然可读;③ 只管导出文档自己的外观,不假设宿主环境。
|
||||
*/
|
||||
const EXPORT_STYLE = `
|
||||
:root { color-scheme: light; }
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 32px 16px 64px;
|
||||
background: #f5f6f8;
|
||||
color: #1f2328;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.note {
|
||||
max-width: ${BODY_MAX_WIDTH}px;
|
||||
margin: 0 auto;
|
||||
padding: 40px 44px 28px;
|
||||
background: #ffffff;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 1px 3px rgba(31, 35, 40, 0.12);
|
||||
}
|
||||
.note-title { margin: 0 0 4px; font-size: 1.9em; line-height: 1.3; font-weight: 600; }
|
||||
.note-body > :first-child { margin-top: 0; }
|
||||
.note-body h1, .note-body h2, .note-body h3, .note-body h4, .note-body h5, .note-body h6 {
|
||||
margin: 1.6em 0 0.6em;
|
||||
line-height: 1.35;
|
||||
font-weight: 600;
|
||||
}
|
||||
.note-body h1 { font-size: 1.6em; padding-bottom: 0.3em; border-bottom: 1px solid #d8dee4; }
|
||||
.note-body h2 { font-size: 1.35em; padding-bottom: 0.3em; border-bottom: 1px solid #d8dee4; }
|
||||
.note-body h3 { font-size: 1.15em; }
|
||||
.note-body p { margin: 0 0 1em; }
|
||||
.note-body a { color: #0969da; text-decoration: none; border-bottom: 1px solid rgba(9, 105, 218, 0.35); }
|
||||
.note-body a:hover { border-bottom-color: currentColor; }
|
||||
.note-body strong { font-weight: 600; }
|
||||
.note-body mark { padding: 0 0.15em; background: #fff8c5; color: inherit; border-radius: 2px; }
|
||||
.note-body img { max-width: 100%; height: auto; border-radius: 6px; }
|
||||
.note-body blockquote {
|
||||
margin: 0 0 1em;
|
||||
padding: 0.2em 0 0.2em 1em;
|
||||
border-left: 4px solid #d0d7de;
|
||||
color: #59636e;
|
||||
}
|
||||
.note-body blockquote > :last-child { margin-bottom: 0; }
|
||||
.note-body ul, .note-body ol { margin: 0 0 1em; padding-left: 1.6em; }
|
||||
.note-body li { margin: 0.25em 0; }
|
||||
.note-body li.task-list-item { margin-left: -1.35em; list-style: none; }
|
||||
.note-body input[type="checkbox"] { margin-right: 0.45em; vertical-align: middle; }
|
||||
.note-body code {
|
||||
padding: 0.15em 0.35em;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
||||
font-size: 0.9em;
|
||||
background: rgba(129, 139, 152, 0.16);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.note-body pre {
|
||||
margin: 0 0 1em;
|
||||
padding: 12px 14px;
|
||||
overflow-x: auto;
|
||||
background: #f6f8fa;
|
||||
border: 1px solid #d8dee4;
|
||||
border-radius: 6px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.note-body pre code { padding: 0; font-size: 0.875em; background: transparent; white-space: pre; }
|
||||
.note-body table { display: block; max-width: 100%; margin: 0 0 1em; overflow-x: auto; border-collapse: collapse; }
|
||||
.note-body th, .note-body td { padding: 6px 12px; border: 1px solid #d0d7de; }
|
||||
.note-body th { font-weight: 600; background: #f6f8fa; }
|
||||
.note-body hr { height: 1px; margin: 1.8em 0; border: 0; background: #d8dee4; }
|
||||
/* 最小高亮配色:只有一套(白底可读),打印时不掉色 */
|
||||
.note-body pre.hljs { color: #1f2328; }
|
||||
.hljs-comment, .hljs-quote { color: #6e7781; font-style: italic; }
|
||||
.hljs-keyword, .hljs-selector-tag, .hljs-literal, .hljs-section { color: #cf222e; }
|
||||
.hljs-string, .hljs-regexp, .hljs-addition { color: #0a3069; }
|
||||
.hljs-number, .hljs-symbol, .hljs-bullet { color: #0550ae; }
|
||||
.hljs-title, .hljs-name, .hljs-selector-id, .hljs-selector-class { color: #8250df; }
|
||||
.hljs-attr, .hljs-attribute, .hljs-variable, .hljs-template-variable { color: #953800; }
|
||||
.hljs-built_in, .hljs-type { color: #0550ae; }
|
||||
.hljs-meta, .hljs-doctag, .hljs-deletion { color: #82071e; }
|
||||
.hljs-tag { color: #116329; }
|
||||
.hljs-emphasis { font-style: italic; }
|
||||
.hljs-strong { font-weight: 600; }
|
||||
.note-footer {
|
||||
margin-top: 40px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid #d8dee4;
|
||||
color: #6e7781;
|
||||
font-size: 0.8125em;
|
||||
text-align: center;
|
||||
}
|
||||
@media print {
|
||||
body { margin: 0; padding: 0; background: #ffffff; color: #000000; font-size: 12pt; }
|
||||
.note { max-width: none; padding: 0; border-radius: 0; box-shadow: none; }
|
||||
.note-body a { color: inherit; border-bottom: 0; }
|
||||
.note-body pre, .note-body code, .note-body th, .note-body mark { background: transparent; }
|
||||
.note-body pre { border-color: #999999; }
|
||||
.note-body pre, .note-body table, .note-body blockquote { page-break-inside: avoid; }
|
||||
}
|
||||
`
|
||||
|
||||
/**
|
||||
* 渲染单篇笔记为完整 HTML 文档字符串(含 <style>,不依赖外部资源)。
|
||||
*
|
||||
* 页面结构:页首 `<h1>`(标题)、正文(已消毒的 Markdown 片段)、页脚一行
|
||||
* 「导出自 Thing · 时间」。标题只做转义、不做 `fileName` 去扩展名之类的加工 ——
|
||||
* 调用方给什么就是什么,`fileName`(含 `.md`)仅作为空标题的兜底。
|
||||
*/
|
||||
export function renderNoteHtml(input: NoteHtmlInput): string {
|
||||
const title = input.title.trim() || input.fileName.trim() || '未命名笔记'
|
||||
const exportedAt =
|
||||
input.exportedAt !== undefined && !Number.isNaN(input.exportedAt.getTime()) ? input.exportedAt : new Date()
|
||||
const footer = `导出自 Thing · ${formatLocalTimestamp(exportedAt)}`
|
||||
// 消毒后插入;`highlight: false` 时围栏代码块不带 hljs token 样式(打印友好)
|
||||
const body = sanitizeHtml(renderWithOptions(input.markdown, input.highlight !== false))
|
||||
return (
|
||||
[
|
||||
'<!doctype html>',
|
||||
'<html lang="zh-CN">',
|
||||
'<head>',
|
||||
'<meta charset="utf-8">',
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
||||
`<title>${escapeHtml(title)}</title>`,
|
||||
`<style>${EXPORT_STYLE}</style>`,
|
||||
'</head>',
|
||||
'<body>',
|
||||
'<article class="note">',
|
||||
`<h1 class="note-title">${escapeHtml(title)}</h1>`,
|
||||
'<div class="note-body">',
|
||||
body,
|
||||
'</div>',
|
||||
`<footer class="note-footer">${escapeHtml(footer)}</footer>`,
|
||||
'</article>',
|
||||
'</body>',
|
||||
'</html>',
|
||||
''
|
||||
].join('\n')
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
/**
|
||||
* Live Preview 扩展 —— CM6 上的「所见即所得」。
|
||||
*
|
||||
* # 范式说明(重要)
|
||||
*
|
||||
* CodeMirror 是源码编辑器,没有块模型。这里的「所见即所得」= **Live Preview**
|
||||
* (Typora / Obsidian 式):遍历 Lezer Markdown 语法树,
|
||||
*
|
||||
* - **非光标行**:隐藏 Markdown 语法符号(`#` `**` `[]()` `>` `-` …),
|
||||
* 让渲染结果直接可见;
|
||||
* - **光标行**(当前选区所覆盖的行):语法符号「显形」,恢复为可编辑源码;
|
||||
* - **结构性元素**用装饰表达标签无法表达的部分:标题字号、行内代码底色、
|
||||
* 引用条、代码块底色、分隔线 widget、任务复选框 widget(可点击改写文档)。
|
||||
*
|
||||
* 颜色(标题色 / 加粗 / 斜体 / 链接色)由主题的 HighlightStyle 负责,
|
||||
* 这里只管结构与「隐藏」。
|
||||
*
|
||||
* # 性能
|
||||
*
|
||||
* 装饰只对 `view.visibleRanges` 计算(长文档不做全文遍历),
|
||||
* 且文档/选区/视口变化时整批重建(见文件末的 ViewPlugin)。
|
||||
*/
|
||||
import {
|
||||
Decoration,
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
WidgetType,
|
||||
type DecorationSet,
|
||||
type ViewUpdate
|
||||
} from '@codemirror/view'
|
||||
import { type Extension, type Range } from '@codemirror/state'
|
||||
import { syntaxTree } from '@codemirror/language'
|
||||
import { type SyntaxNode } from '@lezer/common'
|
||||
import { cachedImage, fetchImage, resolveImagePath } from './images'
|
||||
|
||||
/** Live Preview 的可选配置(图片预览需要知道「当前是哪篇笔记」)。 */
|
||||
export interface LivePreviewOptions {
|
||||
/**
|
||||
* 当前笔记的库内相对路径(空串 = 库外文件,不做图片预览)。
|
||||
*
|
||||
* 图片目标按「相对当前笔记所在目录」解析,因此必须有这个上下文。
|
||||
*/
|
||||
currentRelPath?: string
|
||||
/** 是否启用图片预览(默认 true) */
|
||||
images?: boolean
|
||||
}
|
||||
|
||||
/** 隐藏语法符号(替换为空) */
|
||||
const HIDE = Decoration.replace({})
|
||||
|
||||
/** 取节点的「内部内容」区间(跳过首尾的语法标记子节点)。 */
|
||||
function innerRange(node: SyntaxNode): { from: number; to: number } {
|
||||
const first = node.firstChild
|
||||
const last = node.lastChild
|
||||
if (!first || !last) return { from: node.from, to: node.to }
|
||||
const from = first.to
|
||||
const to = last.from
|
||||
return from < to ? { from, to } : { from: node.from, to: node.to }
|
||||
}
|
||||
|
||||
/** 任务复选框:点击在 `[ ]` / `[x]` 间切换。 */
|
||||
class CheckboxWidget extends WidgetType {
|
||||
constructor(
|
||||
readonly checked: boolean,
|
||||
readonly from: number,
|
||||
readonly to: number
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
eq(other: CheckboxWidget): boolean {
|
||||
return other.checked === this.checked && other.from === this.from
|
||||
}
|
||||
|
||||
toDOM(view: EditorView): HTMLElement {
|
||||
const input = document.createElement('input')
|
||||
input.type = 'checkbox'
|
||||
input.checked = this.checked
|
||||
input.className = 'cm-md-checkbox'
|
||||
input.addEventListener('mousedown', event => {
|
||||
event.preventDefault()
|
||||
view.dispatch({
|
||||
changes: { from: this.from, to: this.to, insert: this.checked ? '[ ]' : '[x]' }
|
||||
})
|
||||
})
|
||||
return input
|
||||
}
|
||||
|
||||
ignoreEvent(): boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 分隔线:把 `---` / `***` 渲染成一条水平线。 */
|
||||
class HorizontalRuleWidget extends WidgetType {
|
||||
eq(): boolean {
|
||||
return true
|
||||
}
|
||||
toDOM(): HTMLElement {
|
||||
const el = document.createElement('span')
|
||||
el.className = 'cm-md-hr'
|
||||
return el
|
||||
}
|
||||
ignoreEvent(): boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 内联图片预览。
|
||||
*
|
||||
* 只在「该 Markdown 图片独占一行、且不在光标行上」时替换整段 `` ——
|
||||
* 与行内混排的图片(`见  所示`)保持源码形态:把行内图片换成块级
|
||||
* `<img>` 会撑高这一行,光标位置与视觉行对不上。
|
||||
*
|
||||
* 高度上限用 CSS 控制(`max-height: 320px`),而不是在 widget 里算 —— 算高度就
|
||||
* 得等 `load` 事件,那会让装饰重建与图片加载互相触发。
|
||||
*/
|
||||
class InlineImageWidget extends WidgetType {
|
||||
constructor(
|
||||
readonly src: string,
|
||||
readonly alt: string,
|
||||
/** 文档里的完整原始片段(预览不可用时原样显示) */
|
||||
readonly raw: string
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
eq(other: InlineImageWidget): boolean {
|
||||
return other.src === this.src && other.alt === this.alt
|
||||
}
|
||||
|
||||
toDOM(): HTMLElement {
|
||||
const wrapper = document.createElement('span')
|
||||
wrapper.className = 'cm-md-image'
|
||||
const img = document.createElement('img')
|
||||
img.src = this.src
|
||||
img.alt = this.alt
|
||||
img.loading = 'lazy'
|
||||
// 拖拽图片应当拖「图片文件」而不是让编辑器选中文本
|
||||
img.draggable = false
|
||||
wrapper.appendChild(img)
|
||||
if (this.alt) {
|
||||
const caption = document.createElement('span')
|
||||
caption.className = 'cm-md-image-alt'
|
||||
caption.textContent = this.alt
|
||||
wrapper.appendChild(caption)
|
||||
}
|
||||
return wrapper
|
||||
}
|
||||
|
||||
ignoreEvent(): boolean {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否为「链接类」节点的子 URL(决定是否随链接一起隐藏)。 */
|
||||
function isLinkUrl(node: SyntaxNode): boolean {
|
||||
const parent = node.parent
|
||||
return parent?.name === 'Link' || parent?.name === 'Image'
|
||||
}
|
||||
|
||||
/** 取出一个 `Image` 节点的原始目标(`` 里 `target` 的原文)。 */
|
||||
function imageTarget(raw: string): { alt: string; target: string } | null {
|
||||
// 结构固定为 ``:找第一个 `](`,再从末尾去掉 `)`
|
||||
const open = raw.indexOf('](')
|
||||
if (open < 0 || !raw.endsWith(')')) return null
|
||||
const alt = raw.slice(2, open)
|
||||
const target = raw.slice(open + 2, -1)
|
||||
return { alt, target }
|
||||
}
|
||||
|
||||
/**
|
||||
* 「装饰构建器」旁表:`EditorView` → 重建函数。
|
||||
*
|
||||
* 图片是异步取字节的,拿到之后需要重算一次装饰。插件本身不把实例暴露给外部,
|
||||
* 而是把重建函数登记在这里 —— 宿主(或本文件内部的图片回调)拿着同一个 view
|
||||
* 就能触发重建,`ViewPlugin` 的 `update` 生命周期不会被外部伸手破坏。
|
||||
*
|
||||
* 用 `WeakMap`:编辑器销毁后条目自动消失,不会因为「关掉的窗口」泄漏。
|
||||
*/
|
||||
const builders = new WeakMap<EditorView, (view: EditorView) => void>()
|
||||
|
||||
/** 让某个编辑器重建 Live Preview 装饰(图片取到字节后调用)。 */
|
||||
export function refreshDecorations(view: EditorView): void {
|
||||
builders.get(view)?.(view)
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建装饰集。
|
||||
*
|
||||
* 做成工厂(而不是模块级函数)是因为图片预览需要闭包持有「当前笔记路径」——
|
||||
* 那是**每个 EditorView 实例**的上下文,放进模块级单例会在多窗口/多编辑器之间串味。
|
||||
*/
|
||||
function createBuilder(options: LivePreviewOptions) {
|
||||
const currentRelPath = options.currentRelPath ?? ''
|
||||
const imagesEnabled = options.images !== false && currentRelPath !== ''
|
||||
|
||||
return function buildDecorations(view: EditorView): DecorationSet {
|
||||
const state = view.state
|
||||
const doc = state.doc
|
||||
const decos: Range<Decoration>[] = []
|
||||
|
||||
// 光标/选区覆盖的行:这些行内的语法符号显形(保持可编辑)
|
||||
const activeLines = new Set<number>()
|
||||
for (const range of state.selection.ranges) {
|
||||
const startLine = doc.lineAt(range.from).number
|
||||
const endLine = doc.lineAt(range.to).number
|
||||
for (let n = startLine; n <= endLine; n++) activeLines.add(n)
|
||||
}
|
||||
const isActive = (pos: number) => activeLines.has(doc.lineAt(pos).number)
|
||||
|
||||
const mark = (from: number, to: number, cls: string) => {
|
||||
if (from < to) decos.push({ from, to, value: Decoration.mark({ class: cls }) })
|
||||
}
|
||||
const line = (pos: number, cls: string) => {
|
||||
const l = doc.lineAt(pos)
|
||||
decos.push({ from: l.from, to: l.from, value: Decoration.line({ class: cls }) })
|
||||
}
|
||||
const replace = (from: number, to: number, value: Decoration) => {
|
||||
if (from < to) decos.push({ from, to, value })
|
||||
}
|
||||
const hide = (from: number, to: number, swallowSpace = false) => {
|
||||
let end = to
|
||||
while (swallowSpace && end < doc.length && doc.sliceString(end, end + 1) === ' ') end++
|
||||
replace(from, end, HIDE)
|
||||
}
|
||||
|
||||
for (const { from, to } of view.visibleRanges) {
|
||||
syntaxTree(state).iterate({
|
||||
from,
|
||||
to,
|
||||
enter: node => {
|
||||
const name = node.name
|
||||
const active = isActive(node.from)
|
||||
const n = node.node
|
||||
|
||||
switch (name) {
|
||||
// ===== 标题:行级样式(字号/字重),符号在非光标行隐藏 =====
|
||||
case 'ATXHeading1':
|
||||
case 'ATXHeading2':
|
||||
case 'ATXHeading3':
|
||||
case 'ATXHeading4':
|
||||
case 'ATXHeading5':
|
||||
case 'ATXHeading6':
|
||||
line(node.from, `cm-md-h${name.slice(-1)}`)
|
||||
break
|
||||
case 'SetextHeading1':
|
||||
case 'SetextHeading2':
|
||||
line(node.from, `cm-md-h${name.slice(-1)}`)
|
||||
break
|
||||
|
||||
// ===== 语法标记:非光标行隐藏 =====
|
||||
case 'HeaderMark':
|
||||
if (!active) hide(node.from, node.to, true)
|
||||
break
|
||||
case 'EmphasisMark':
|
||||
case 'StrikethroughMark':
|
||||
if (!active) hide(node.from, node.to)
|
||||
break
|
||||
case 'LinkMark':
|
||||
if (!active) hide(node.from, node.to)
|
||||
break
|
||||
case 'URL':
|
||||
if (!active && isLinkUrl(n)) hide(node.from, node.to)
|
||||
break
|
||||
case 'QuoteMark':
|
||||
if (!active) hide(node.from, node.to, true)
|
||||
break
|
||||
case 'ListMark':
|
||||
if (!active) hide(node.from, node.to, true)
|
||||
break
|
||||
case 'CodeMark':
|
||||
// 仅行内代码的反引号隐藏;围栏代码块的 ``` 保留(保留语言标注)
|
||||
if (!active && n.parent?.name === 'InlineCode') hide(node.from, node.to)
|
||||
break
|
||||
|
||||
// ===== 行内代码:底色 + 内边距(标签只给颜色) =====
|
||||
case 'InlineCode': {
|
||||
const inner = innerRange(n)
|
||||
mark(inner.from, inner.to, 'cm-md-inlinecode')
|
||||
break
|
||||
}
|
||||
|
||||
// ===== 引用:整块左侧竖线 =====
|
||||
case 'Blockquote': {
|
||||
let pos = node.from
|
||||
while (pos <= node.to) {
|
||||
const l = doc.lineAt(pos)
|
||||
line(l.from, 'cm-md-quote')
|
||||
if (l.to >= node.to) break
|
||||
pos = l.to + 1
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// ===== 围栏代码块:整块底色 =====
|
||||
case 'FencedCode': {
|
||||
let pos = node.from
|
||||
while (pos <= node.to) {
|
||||
const l = doc.lineAt(pos)
|
||||
line(l.from, 'cm-md-codeblock')
|
||||
if (l.to >= node.to) break
|
||||
pos = l.to + 1
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// ===== 分隔线:非光标行渲染为水平线 =====
|
||||
case 'HorizontalRule':
|
||||
if (!active) {
|
||||
replace(node.from, node.to, Decoration.replace({ widget: new HorizontalRuleWidget() }))
|
||||
}
|
||||
break
|
||||
|
||||
// ===== 任务列表:复选框 widget(任何状态下都可点击切换) =====
|
||||
case 'TaskMarker': {
|
||||
const text = doc.sliceString(node.from, node.to)
|
||||
const checked = /\[[xX]\]/.test(text)
|
||||
replace(
|
||||
node.from,
|
||||
node.to,
|
||||
Decoration.replace({ widget: new CheckboxWidget(checked, node.from, node.to) })
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
// ===== 图片:独占一行 + 非光标行时内联预览 =====
|
||||
case 'Image': {
|
||||
if (!imagesEnabled || active) break
|
||||
const startLine = doc.lineAt(node.from)
|
||||
const endLine = doc.lineAt(node.to)
|
||||
if (startLine.number !== endLine.number) break
|
||||
// 只预览「这一行除了图片没有别的可见内容」的情况
|
||||
const lineText = doc.sliceString(startLine.from, startLine.to).trim()
|
||||
const raw = doc.sliceString(node.from, node.to)
|
||||
if (lineText !== raw.trim()) break
|
||||
|
||||
const parsed = imageTarget(raw)
|
||||
if (!parsed) break
|
||||
const relPath = resolveImagePath(parsed.target, currentRelPath)
|
||||
if (!relPath) break
|
||||
|
||||
const cached = cachedImage(relPath)
|
||||
if (cached === undefined) {
|
||||
// 首次见到:异步取字节,取到后重建这一篇的装饰
|
||||
void fetchImage(relPath).then(() => {
|
||||
const refresh = builders.get(view)
|
||||
if (refresh) refresh(view)
|
||||
})
|
||||
break
|
||||
}
|
||||
if (cached === null) break // 已确认不可预览 → 保持源码形态
|
||||
replace(
|
||||
node.from,
|
||||
node.to,
|
||||
Decoration.replace({
|
||||
widget: new InlineImageWidget(cached, parsed.alt, raw)
|
||||
})
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return Decoration.set(decos, true)
|
||||
}
|
||||
}
|
||||
|
||||
/** Live Preview 的结构样式(颜色交给主题;这里只做标签表达不了的部分)。 */
|
||||
const livePreviewTheme = EditorView.baseTheme({
|
||||
'.cm-md-h1': { fontSize: '1.6em', fontWeight: '700', lineHeight: '1.4' },
|
||||
'.cm-md-h2': { fontSize: '1.4em', fontWeight: '700', lineHeight: '1.4' },
|
||||
'.cm-md-h3': { fontSize: '1.22em', fontWeight: '600' },
|
||||
'.cm-md-h4': { fontSize: '1.1em', fontWeight: '600' },
|
||||
'.cm-md-h5': { fontSize: '1em', fontWeight: '600' },
|
||||
'.cm-md-h6': { fontSize: '0.94em', fontWeight: '600', opacity: '0.85' },
|
||||
'.cm-md-quote': {
|
||||
borderLeft: '3px solid currentColor',
|
||||
opacity: '0.9',
|
||||
paddingLeft: '12px'
|
||||
},
|
||||
'.cm-md-codeblock': {
|
||||
backgroundColor: 'rgba(127, 127, 127, 0.12)'
|
||||
},
|
||||
'.cm-md-inlinecode': {
|
||||
backgroundColor: 'rgba(127, 127, 127, 0.16)',
|
||||
borderRadius: '4px',
|
||||
padding: '0.1em 0.35em',
|
||||
fontFamily: "'Cascadia Code', 'JetBrains Mono', Consolas, monospace"
|
||||
},
|
||||
'.cm-md-hr': {
|
||||
display: 'inline-block',
|
||||
width: '100%',
|
||||
borderTop: '1px solid currentColor',
|
||||
opacity: '0.35',
|
||||
verticalAlign: 'middle'
|
||||
},
|
||||
'.cm-md-checkbox': {
|
||||
marginRight: '6px',
|
||||
verticalAlign: 'middle',
|
||||
cursor: 'pointer'
|
||||
},
|
||||
'.cm-md-image': {
|
||||
display: 'inline-flex',
|
||||
flexDirection: 'column',
|
||||
gap: '4px',
|
||||
maxWidth: '100%',
|
||||
verticalAlign: 'top'
|
||||
},
|
||||
// 高度上限交给 CSS:算高度要等 `load` 事件,会让装饰重建与图片加载互相触发
|
||||
'.cm-md-image img': {
|
||||
maxWidth: '100%',
|
||||
maxHeight: '320px',
|
||||
borderRadius: '6px',
|
||||
objectFit: 'contain'
|
||||
},
|
||||
'.cm-md-image-alt': {
|
||||
fontSize: '0.8em',
|
||||
opacity: '0.6',
|
||||
fontStyle: 'italic'
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Live Preview 扩展工厂。
|
||||
*
|
||||
* 必须按编辑器实例构造(内部的 ViewPlugin 闭包持有该实例的笔记路径):
|
||||
* 若做成模块级单例,多窗口/多编辑器会共用同一份闭包上下文 —— 在 A 笔记里预览的图片
|
||||
* 会按 B 笔记的目录去解析。
|
||||
*/
|
||||
export function markdownLivePreview(options: LivePreviewOptions = {}): Extension {
|
||||
const buildDecorations = createBuilder(options)
|
||||
return [
|
||||
livePreviewTheme,
|
||||
ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = buildDecorations(view)
|
||||
builders.set(view, next => {
|
||||
this.decorations = buildDecorations(next)
|
||||
// `Decoration.set` 换新对象后必须让 CM 知道视口需要重绘
|
||||
next.requestMeasure()
|
||||
})
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged || update.selectionSet || update.viewportChanged) {
|
||||
this.decorations = buildDecorations(update.view)
|
||||
}
|
||||
}
|
||||
},
|
||||
{ decorations: value => value.decorations }
|
||||
)
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* 大纲提取单测(Node 内置 test runner)。
|
||||
*
|
||||
* # 断言为什么全是「显式数字」
|
||||
*
|
||||
* `from` 的语义只有一条:**标题所在行的行首偏移**(ATX 含行首缩进)。这里一律写
|
||||
* 死数字而不是 `doc.indexOf(...)` —— 用 indexOf 会把实现里的偏移错误「自我印证」
|
||||
* 掉(实现取错锚点时,测试跟着错,永远绿)。
|
||||
*
|
||||
* # 已修正的期望(原稿手算有误)
|
||||
*
|
||||
* - 裸 `#` / `# `(空标题):`from` 是行首(0 / 2),不是「`#` 后一位」
|
||||
* - Setext 标题:`from` 是**标题那一行**的行首,不是下划线的位置
|
||||
* - CRLF:行首偏移按原始长度推进(`\r` 计入),标题行内容不含 `\r`
|
||||
*
|
||||
* 数字由脚本按「行首偏移累加」算出后写死(见提交说明),不是实现输出。
|
||||
*/
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { extractOutline } from './outline.ts'
|
||||
|
||||
test('ATX 各级标题:层级、文本、行号、偏移', () => {
|
||||
const doc = ['# H1', '## H2', '### H3', '#### H4', '##### H5', '###### H6'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 1, text: 'H1', line: 1, from: 0 },
|
||||
{ level: 2, text: 'H2', line: 2, from: 5 },
|
||||
{ level: 3, text: 'H3', line: 3, from: 11 },
|
||||
{ level: 4, text: 'H4', line: 4, from: 18 },
|
||||
{ level: 5, text: 'H5', line: 5, from: 26 },
|
||||
{ level: 6, text: 'H6', line: 6, from: 35 }
|
||||
])
|
||||
})
|
||||
|
||||
test('ATX 必须 # 后有空白:#tag / #hashtag / #中文 不算标题', () => {
|
||||
const doc = ['#tag 不是标题', '#hashtag', '#中文标题', '正文 # 号在中间'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [])
|
||||
})
|
||||
|
||||
test('裸 # 也算标题(# 后必须有空白,但内容可为空)', () => {
|
||||
const doc = ['#', '# '].join('\n')
|
||||
// `from` 一律是行首偏移:空标题没有「正文起点」可指,行首是唯一无歧义的锚点
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 1, text: '', line: 1, from: 0 },
|
||||
{ level: 1, text: '', line: 2, from: 2 }
|
||||
])
|
||||
})
|
||||
|
||||
test('ATX 内容保留原文(不解析行内语法)且 trim', () => {
|
||||
const doc = '# **bold** `code` [x](y) '
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 1, text: '**bold** `code` [x](y)', line: 1, from: 0 }
|
||||
])
|
||||
})
|
||||
|
||||
test('ATX 闭合 # 序列剥离,但内容中间的 # 与无空白的 # 保留', () => {
|
||||
const doc = ['## 标题 ##', '# 中间 # 号 ##', '### 内容末尾 #x ###', '# 只剥结尾 ###'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 2, text: '标题', line: 1, from: 0 },
|
||||
{ level: 1, text: '中间 # 号', line: 2, from: 9 },
|
||||
{ level: 3, text: '内容末尾 #x', line: 3, from: 21 },
|
||||
{ level: 1, text: '只剥结尾', line: 4, from: 37 }
|
||||
])
|
||||
})
|
||||
|
||||
test('ATX 允许最多 3 空格缩进,4 空格(缩进代码)不认', () => {
|
||||
const doc = [' # 缩进三级', ' # 缩进四级'].join('\n')
|
||||
// `from` 是行首(含缩进):跳到「这一行」,不是跳到 `#`
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '缩进三级', line: 1, from: 0 }])
|
||||
})
|
||||
|
||||
test('7 个以上 # 不是标题', () => {
|
||||
assert.deepEqual(extractOutline('####### 七个井号'), [])
|
||||
})
|
||||
|
||||
test('Setext 标题:=== 为 1 级,--- 为 2 级', () => {
|
||||
const doc = ['一级标题', '===', '', '二级标题', '---', '', '带下划线', '====='].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 1, text: '一级标题', line: 1, from: 0 },
|
||||
{ level: 2, text: '二级标题', line: 4, from: 10 },
|
||||
{ level: 1, text: '带下划线', line: 7, from: 20 }
|
||||
])
|
||||
})
|
||||
|
||||
test('Setext:前面是空行 / 分隔线 / 列表项时不当标题', () => {
|
||||
const doc = ['', '---', '~~~text', '- 列表项', '---', '> 引用', '==='].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [])
|
||||
})
|
||||
|
||||
test('front-matter 整块跳过,闭合 --- 不当 Setext 下划线', () => {
|
||||
const doc = ['---', 'title: "# 假标题"', 'tags:', ' - a', '---', '# 真标题'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 6, from: 35 }])
|
||||
})
|
||||
|
||||
test('front-matter 结束后,后面的 Setext 正常识别', () => {
|
||||
const doc = ['---', 'desc: 描述行', '---', '正文', 'Title', '---'].join('\n')
|
||||
// 第 5 行的 `---` 把上一行 Title 提升为二级标题;第 2 行的 `---` 是 front-matter
|
||||
// 闭合行,绝不能把 `desc: 描述行` 提升成标题(这是实现里真实踩过的坑)
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 2, text: 'Title', line: 5, from: 21 }])
|
||||
})
|
||||
|
||||
test('围栏代码块(``` 与 ~~~)内的 # 与其后内容被跳过', () => {
|
||||
const doc = [
|
||||
'# 标题一',
|
||||
'```md',
|
||||
'# 假标题',
|
||||
'## 也假',
|
||||
'```',
|
||||
'~~~',
|
||||
'# 波浪号里也假',
|
||||
'~~~',
|
||||
'# 标题二'
|
||||
].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [
|
||||
{ level: 1, text: '标题一', line: 1, from: 0 },
|
||||
{ level: 1, text: '标题二', line: 9, from: 45 }
|
||||
])
|
||||
})
|
||||
|
||||
test('代码块内 Setext 下划线与围栏内未闭合围栏都不产生标题', () => {
|
||||
const doc = ['```', '假标题', '---', '```', '真标题', '==='].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 5, from: 16 }])
|
||||
})
|
||||
|
||||
test('未闭合围栏吞到文档末尾', () => {
|
||||
const doc = ['# 保留', '```ts', '# 被吞', '## 也被吞'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '保留', line: 1, from: 0 }])
|
||||
})
|
||||
|
||||
test('围栏闭合行不能带语言标注', () => {
|
||||
const doc = ['```', '```js', '# 仍在围栏内', '```', '# 出来啦'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '出来啦', line: 5, from: 22 }])
|
||||
})
|
||||
|
||||
test('缩进代码块(4 空格 / Tab)内的 # 被跳过', () => {
|
||||
const doc = ['', ' # 缩进代码', '\t# Tab 代码', '', '# 真标题'].join('\n')
|
||||
assert.deepEqual(extractOutline(doc), [{ level: 1, text: '真标题', line: 5, from: 23 }])
|
||||
})
|
||||
|
||||
test('CRLF:行内容不含 \\r,行号与 from 偏移正确', () => {
|
||||
const crlf = '# 一\r\n\r\n## 二\r\nSetext\r\n==='
|
||||
// 行首偏移按原始长度推进:`# 一`(4+1) → 5……`\r\n` 的两行各占 1+1
|
||||
assert.deepEqual(extractOutline(crlf), [
|
||||
{ level: 1, text: '一', line: 1, from: 0 },
|
||||
{ level: 2, text: '二', line: 3, from: 7 },
|
||||
{ level: 1, text: 'Setext', line: 4, from: 13 }
|
||||
])
|
||||
})
|
||||
|
||||
test('CRLF 下标题文本不残留 \\r', () => {
|
||||
const headings = extractOutline('# 标题\r\n## 二级 ##\r\n')
|
||||
// `# 标题` 占 4+1 字节,加 `\r\n` 的 `\r`(在 split 后归上一行)→ 第二行行首为 6
|
||||
assert.deepEqual(headings, [
|
||||
{ level: 1, text: '标题', line: 1, from: 0 },
|
||||
{ level: 2, text: '二级', line: 2, from: 6 }
|
||||
])
|
||||
})
|
||||
|
||||
test('空文档 / 无标题 / 只有空白行', () => {
|
||||
assert.deepEqual(extractOutline(''), [])
|
||||
assert.deepEqual(extractOutline('\n\n \n\t\n'), [])
|
||||
assert.deepEqual(extractOutline('普通段落\n再来一行'), [])
|
||||
})
|
||||
|
||||
test('from 指向标题行行首:ATX 含行首缩进', () => {
|
||||
const doc = '前言\n\n ## 缩进二级\n\n正文 # 井号'
|
||||
const headings = extractOutline(doc)
|
||||
assert.deepEqual(headings, [{ level: 2, text: '缩进二级', line: 3, from: 4 }])
|
||||
// 行首偏移 → 能直接取回该行(含缩进):' ## 缩进二级' 共 2+2+1+4 = 9 个字符
|
||||
assert.equal(doc.slice(4, 4 + 9), ' ## 缩进二级')
|
||||
})
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* 大纲提取 —— 从 Markdown 原文里捞出标题,供大纲面板渲染与点击跳转。
|
||||
*
|
||||
* # 为什么不用 CodeMirror 的语法树
|
||||
*
|
||||
* 编辑器里已经有 Lezer Markdown 语法树,但语法树只在视口(`visibleRanges`)内
|
||||
* 才保证完整,而大纲需要**全文**的标题;另外大纲面板要能脱离编辑器单测。
|
||||
* 所以这里做成「纯字符串进、纯数据出」的函数:无 DOM、无 CM 依赖、无第三方依赖。
|
||||
* 代价是得自己实现一遍分块规则,边界以 CommonMark 为准做**务实子集**:
|
||||
* 围栏代码块和 4 空格缩进代码块要跳过,行内语法一律不解析(标题文本保留原文)。
|
||||
*
|
||||
* # 关键取舍
|
||||
*
|
||||
* - **逐行扫描**:行号与偏移天然是行级的,比正则全文匹配更省心,也不会被
|
||||
* 「跨行匹配」坑到。CRLF 下行内容先剥掉 `\r`,偏移仍按**原始长度**推进。
|
||||
* - **`from` 一律是标题所在行的行首偏移**(ATX 含行首缩进)。语义只有一条:
|
||||
* 「跳到这一行」。指向正文起点会让空标题(`#`、`# `)没有合法取值;指向 `#`
|
||||
* 又因 `# ` 与 `# `(多个空格)长度不同而难以预期 —— 行首是唯一无歧义的锚点。
|
||||
* - **ATX 必须 `#` 后跟空白**:否则 `#tag` / `#标题`(中文前无空格)会被误判成标题,
|
||||
* 这类写法在笔记里太常见。收紧后误判为「不是标题」远比误判成标题安全。
|
||||
* - **Setext 只在「上一行是自然段落文本」时才认**:空行 / ATX 标题 / 引用 /
|
||||
* 列表项 / 缩进代码 后面跟的 `===` `---` 都不是 Setext 下划线(CommonMark
|
||||
* 不允许这些块的惰性延续被 Setext 打断),`---` 更可能是分隔线,宁可漏也不要错。
|
||||
* - **front-matter 是状态机而不是布尔量**:首行的 `---` 是**开头**,闭合要靠
|
||||
* 「再遇到一个整行 `---`」。用布尔量会在第 0 行就把状态关掉,于是闭合行反而
|
||||
* 把它上面那行元数据(`desc: xx`)提升成 Setext 标题 —— 真实踩过的坑,
|
||||
* 详见 [`FrontMatterState`]。
|
||||
* - **缩进代码块是启发式的**:只在「前面有空行」时才开始跳过 4 空格 / 1 Tab 行,
|
||||
* 到第一个非空非缩进行结束。列表项内的相对缩进(如 2 空格续行)识别不了,
|
||||
* 那种情况下带 4 空格的 `#` 会被当成标题 —— 这是有意接受的漏判。
|
||||
*/
|
||||
|
||||
/** 大纲中的一个标题节点 */
|
||||
export interface OutlineHeading {
|
||||
/** 标题层级 1..6 */
|
||||
level: number
|
||||
/** 标题文本(已去掉 # 与首尾空白、去掉结尾的 # 闭合标记) */
|
||||
text: string
|
||||
/** 标题所在行号(1 起) */
|
||||
line: number
|
||||
/** 标题所在行的行首偏移(ATX 含行首缩进),点击跳转直接用它 */
|
||||
from: number
|
||||
}
|
||||
|
||||
/** 围栏代码块:行首最多 3 空格缩进 + 3 个以上连续 ` 或 ~。 */
|
||||
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/
|
||||
|
||||
/** ATX 标题:行首最多 3 空格缩进 + 1~6 个 `#`(`#` 后可有空白与内容)。 */
|
||||
const ATX_RE = /^ {0,3}(#{1,6})(?:[ \t]+(.*))?$/
|
||||
|
||||
/** front-matter 分隔线:整行就是 `---`。 */
|
||||
const FRONT_MATTER_FENCE_RE = /^-{3,}[ \t]*$/
|
||||
|
||||
/** Setext 下划线:最多 3 空格缩进 + 只有 `=` 或只有 `-`(+ 尾随空白)。 */
|
||||
const SETEXT_UNDERLINE_RE = /^ {0,3}(=+|-+)[ \t]*$/
|
||||
|
||||
/** 引用块行首。 */
|
||||
const BLOCKQUOTE_RE = /^ {0,3}>/
|
||||
|
||||
/** 无序列表项行首。 */
|
||||
const BULLET_RE = /^ {0,3}[-+*](?:[ \t]|$)/
|
||||
|
||||
/** 有序列表项行首。 */
|
||||
const ORDERED_RE = /^ {0,3}\d{1,9}[.)](?:[ \t]|$)/
|
||||
|
||||
/**
|
||||
* front-matter 的三态。
|
||||
*
|
||||
* 首行就是 `---` 时,**这一行是开头而不是结尾**。用单个布尔量表示「是否在
|
||||
* front-matter 内」会立刻在第 0 行把它关掉,随后第 2 行的闭合 `---` 就被当成
|
||||
* 普通分隔线,把它上面那行 `desc: xx` 提升成 Setext 标题 —— 症状是
|
||||
* 「元数据凭空变成大纲第一条」。
|
||||
*
|
||||
* 用常量对象而不是 `enum`:Node 的 TypeScript 支持是**只剥类型**(strip-only),
|
||||
* `enum` 会生成运行时代码因而被拒绝(`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`),
|
||||
* 单测就再也跑不起来。
|
||||
*/
|
||||
const FrontMatter = {
|
||||
/** 首行不是 `---`:文档没有 front-matter */
|
||||
None: 'none',
|
||||
/** 首行是开头标记,正在元数据内 */
|
||||
Inside: 'inside',
|
||||
/** 已闭合;`frontMatterEndLine` 记录闭合行号,它不得再被当作 Setext 下划线 */
|
||||
Closed: 'closed'
|
||||
} as const
|
||||
|
||||
type FrontMatterState = (typeof FrontMatter)[keyof typeof FrontMatter]
|
||||
|
||||
/** 取数组中第 index 项;越界(`noUncheckedIndexedAccess` 的 `undefined`)退化为空串。 */
|
||||
function at(list: string[], index: number): string {
|
||||
return list[index] ?? ''
|
||||
}
|
||||
|
||||
/** 行首缩进宽度(Tab 记 4)。 */
|
||||
function indentWidth(line: string): number {
|
||||
let width = 0
|
||||
for (const ch of line) {
|
||||
if (ch === ' ') width += 1
|
||||
else if (ch === '\t') width += 4
|
||||
else break
|
||||
}
|
||||
return width
|
||||
}
|
||||
|
||||
/** 剥掉 ATX 结尾的 ` #` 闭合序列(CommonMark:闭合序列前必须有空白)。 */
|
||||
function stripClosingHashes(value: string): string {
|
||||
return value.replace(/[ \t]+#+[ \t]*$/, '')
|
||||
}
|
||||
|
||||
/** 解析围栏行;不是围栏返回 null。反引号围栏的 info 里禁止再出现反引号。 */
|
||||
function parseFence(line: string): { char: '`' | '~'; count: number } | null {
|
||||
const match = FENCE_RE.exec(line)
|
||||
if (!match) return null
|
||||
const run = match[1] ?? ''
|
||||
const rest = match[2] ?? ''
|
||||
const char = run.charAt(0) as '`' | '~'
|
||||
if (char === '`' && rest.includes('`')) return null
|
||||
return { char, count: run.length }
|
||||
}
|
||||
|
||||
/** 是否是某个围栏的合法闭合行(同字符、不短于开栏、除尾随空白外无其它字符)。 */
|
||||
function isFenceClose(line: string, char: '`' | '~', count: number): boolean {
|
||||
const match = FENCE_RE.exec(line)
|
||||
if (!match) return false
|
||||
const run = match[1] ?? ''
|
||||
if ((match[2] ?? '').trim() !== '') return false
|
||||
return run.charAt(0) === char && run.length >= count
|
||||
}
|
||||
|
||||
/** 上一行是否算「自然段落文本」——只有它才允许被下一行的 `===` / `---` 提升为标题。 */
|
||||
function isParagraphText(previous: string): boolean {
|
||||
if (previous.trim() === '') return false
|
||||
if (previous.startsWith(' ') || previous.startsWith('\t')) return false
|
||||
if (previous.trimStart().startsWith('#')) return false
|
||||
if (BLOCKQUOTE_RE.test(previous)) return false
|
||||
if (BULLET_RE.test(previous)) return false
|
||||
if (ORDERED_RE.test(previous)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
/** 提取 Markdown 大纲。 */
|
||||
export function extractOutline(doc: string): OutlineHeading[] {
|
||||
const headings: OutlineHeading[] = []
|
||||
if (doc === '') return headings
|
||||
|
||||
const lines = doc.split('\n')
|
||||
/**
|
||||
* 每行的行首偏移。
|
||||
*
|
||||
* **必须先算出来,不能在循环里「减回去」**:CRLF 下行内容的长度比原始行长少 1,
|
||||
* 用 `当前偏移 - 上一行长度 - 1` 反推行首时,LF 恰好对、CRLF 一律偏 1 ——
|
||||
* 这种「只在一种换行下错」的 bug 在 Windows 上几乎必然踩到。
|
||||
*/
|
||||
const lineStarts: number[] = []
|
||||
{
|
||||
let cursor = 0
|
||||
for (const line of lines) {
|
||||
lineStarts.push(cursor)
|
||||
cursor += line.length + 1
|
||||
}
|
||||
}
|
||||
|
||||
const firstRaw = at(lines, 0)
|
||||
const firstLine = firstRaw.endsWith('\r') ? firstRaw.slice(0, -1) : firstRaw
|
||||
let frontMatter: FrontMatterState = FRONT_MATTER_FENCE_RE.test(firstLine)
|
||||
? FrontMatter.Inside
|
||||
: FrontMatter.None
|
||||
/** front-matter 闭合行的行号(-1 = 无) */
|
||||
let frontMatterEndLine = -1
|
||||
|
||||
let fenceChar: '`' | '~' | null = null
|
||||
let fenceCount = 0
|
||||
let inIndentedCode = false
|
||||
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const raw = at(lines, index)
|
||||
const lineFrom = lineStarts[index] ?? 0
|
||||
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
|
||||
|
||||
if (frontMatter === FrontMatter.Inside) {
|
||||
// 元数据内:只有「整行 ---」才算闭合,且首行(index 0)就是那个开头本身
|
||||
if (index > 0 && FRONT_MATTER_FENCE_RE.test(line.trim())) {
|
||||
frontMatter = FrontMatter.Closed
|
||||
frontMatterEndLine = index
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
const fence = parseFence(line)
|
||||
|
||||
if (fenceChar !== null) {
|
||||
// 围栏内:只看闭合行,其余(含 `#`)全部无视
|
||||
if (isFenceClose(line, fenceChar, fenceCount)) fenceChar = null
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
inIndentedCode = false
|
||||
continue
|
||||
}
|
||||
|
||||
const indent = indentWidth(line)
|
||||
if (indent >= 4) {
|
||||
// 缩进代码块启发式:前有空行才起块;块内(含其中的 `#`)全跳过
|
||||
if (inIndentedCode) continue
|
||||
if (index > 0 && at(lines, index - 1).trim() === '') {
|
||||
inIndentedCode = true
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
inIndentedCode = false
|
||||
}
|
||||
|
||||
if (fence !== null) {
|
||||
fenceChar = fence.char
|
||||
fenceCount = fence.count
|
||||
continue
|
||||
}
|
||||
|
||||
const atx = ATX_RE.exec(line)
|
||||
if (atx) {
|
||||
const markerLen = (atx[1] ?? '').length
|
||||
const body = line.slice(indent + markerLen)
|
||||
const text = stripClosingHashes(body.trim()).trim()
|
||||
headings.push({ level: markerLen, text, line: index + 1, from: lineFrom })
|
||||
continue
|
||||
}
|
||||
|
||||
// Setext:当前行是下划线,上一行才是标题文本
|
||||
const underline = SETEXT_UNDERLINE_RE.exec(line)
|
||||
if (!underline) continue
|
||||
if (index === 0) continue
|
||||
// front-matter 的闭合 `---` 不是下划线:否则它上面那行元数据会被提升成标题
|
||||
if (index - 1 === frontMatterEndLine) continue
|
||||
const previous = at(lines, index - 1)
|
||||
if (!isParagraphText(previous)) continue
|
||||
const title = previous.trim()
|
||||
if (title === '') continue
|
||||
headings.push({
|
||||
level: (underline[1] ?? '').charAt(0) === '=' ? 1 : 2,
|
||||
text: title,
|
||||
// 行号/偏移都指回标题文本那一行(1 起行号 = index)
|
||||
line: index,
|
||||
from: lineStarts[index - 1] ?? 0
|
||||
})
|
||||
}
|
||||
|
||||
return headings
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* 编辑器配色方案与排版。
|
||||
*
|
||||
* # 为什么自建而不是堆第三方主题包
|
||||
*
|
||||
* 与终端模块 `terminalThemes.ts` 同一套取舍:常见的主题包把几十套颜色硬编码在一个
|
||||
* 文件里(大部分用不上),且数值与 VS Code / JetBrains 的官方定义常有小幅偏差。
|
||||
* 这里只保留实际提供的几套,色值取自各主题官方定义,保证「选了 vscode-dark
|
||||
* 就和 VS Code 一致」。
|
||||
*
|
||||
* # 两层解耦
|
||||
*
|
||||
* - **配色**(本文件的 `createTheme` / `oneDark`):只负责颜色,是 CM6 的 `Extension`。
|
||||
* - **排版**([`editorTypography`]):字体 / 字号 / 行高 / 连字,与配色独立可配。
|
||||
*
|
||||
* 主题 key 必须与 Rust 侧 `NoteSettings.editorTheme` 的取值保持一致,
|
||||
* 否则用户选了主题却静默回落默认(终端模块踩过这个坑)。
|
||||
*/
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import { type Extension } from '@codemirror/state'
|
||||
import { type TagStyle } from '@codemirror/language'
|
||||
import { oneDark } from '@codemirror/theme-one-dark'
|
||||
import { createTheme } from '@uiw/codemirror-themes'
|
||||
import { tags as t } from '@lezer/highlight'
|
||||
|
||||
/** 主题的亮暗归属(供「跟随应用」取对应侧) */
|
||||
interface ThemeDefinition {
|
||||
dark: boolean
|
||||
extension: Extension
|
||||
}
|
||||
|
||||
const VSCODE_DARK: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#6a9955' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#569cd6' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#ce9178' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#b5cea8' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#9cdcfe' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#dcdcaa' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#4ec9b0' },
|
||||
{ tag: [t.operator], color: '#d4d4d4' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#569cd6' },
|
||||
{ tag: t.strong, color: '#d4d4d4', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#d4d4d4', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#d4d4d4', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#4fc1ff', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#ce9178' },
|
||||
{ tag: t.quote, color: '#6a9955' }
|
||||
]
|
||||
|
||||
const VSCODE_LIGHT: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#008000' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#0000ff' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#a31515' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#098658' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#001080' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#795e26' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#267f99' },
|
||||
{ tag: [t.operator], color: '#333333' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#0000ff' },
|
||||
{ tag: t.strong, color: '#333333', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#333333', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#333333', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#0451a5', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#a31515' },
|
||||
{ tag: t.quote, color: '#008000' }
|
||||
]
|
||||
|
||||
const DRACULA: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#6272a4' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#ff79c6' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#f1fa8c' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#bd93f9' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#f8f8f2' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#50fa7b' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#8be9fd' },
|
||||
{ tag: [t.operator], color: '#ff79c6' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#bd93f9' },
|
||||
{ tag: t.strong, color: '#f8f8f2', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#f8f8f2', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#f8f8f2', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#8be9fd', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#f1fa8c' },
|
||||
{ tag: t.quote, color: '#6272a4' }
|
||||
]
|
||||
|
||||
const SOLARIZED_DARK: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#586e75' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#859900' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#2aa198' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#d33682' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#b58900' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#268bd2' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#b58900' },
|
||||
{ tag: [t.operator], color: '#859900' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#cb4b16' },
|
||||
{ tag: t.strong, color: '#93a1a1', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#93a1a1', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#93a1a1', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#268bd2', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#2aa198' },
|
||||
{ tag: t.quote, color: '#586e75' }
|
||||
]
|
||||
|
||||
const SOLARIZED_LIGHT: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#93a1a1' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#859900' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#2aa198' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#d33682' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#b58900' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#268bd2' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#b58900' },
|
||||
{ tag: [t.operator], color: '#859900' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#cb4b16' },
|
||||
{ tag: t.strong, color: '#586e75', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#586e75', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#586e75', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#268bd2', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#2aa198' },
|
||||
{ tag: t.quote, color: '#93a1a1' }
|
||||
]
|
||||
|
||||
// ===== JetBrains 系列(P1,用户点名)=====
|
||||
//
|
||||
// CM6 没有官方的 JetBrains 配色包,因此按 JetBrains 各 IDE 的**默认配色方案**手校。
|
||||
// 色值取自 IntelliJ 平台内置 scheme(Darcula / IntelliJ Light / Monokai Pro)的
|
||||
// 常用取值;与终端模块「只保留实际提供的、数值取自官方」的策略一致。
|
||||
//
|
||||
// 一处刻意的取舍:JetBrains 的**关键字**在 Darcula 里是橙色(`#cc7832`)而不是
|
||||
// 紫色 —— 直接套用「VS Code 式」的紫色关键字会让这个主题看起来一点都不像 IDEA。
|
||||
|
||||
const JETBRAINS_DARCULA: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#808080', fontStyle: 'italic' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#cc7832' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#6a8759' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#6897bb' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#a9b7c6' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#ffc66d' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#a9b7c6' },
|
||||
{ tag: [t.operator], color: '#a9b7c6' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#ffc66d' },
|
||||
{ tag: t.strong, color: '#a9b7c6', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#a9b7c6', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#a9b7c6', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#287bde', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#6a8759' },
|
||||
{ tag: t.quote, color: '#808080' }
|
||||
]
|
||||
|
||||
const INTELLIJ_LIGHT: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#8c8c8c', fontStyle: 'italic' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#0033b3' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#067d17' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#1750eb' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#000000' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#00627a' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#000000' },
|
||||
{ tag: [t.operator], color: '#000000' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#00627a' },
|
||||
{ tag: t.strong, color: '#000000', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#000000', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#000000', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#0000ff', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#067d17' },
|
||||
{ tag: t.quote, color: '#8c8c8c' }
|
||||
]
|
||||
|
||||
const MONOKAI_PRO: TagStyle[] = [
|
||||
{ tag: [t.comment, t.lineComment, t.blockComment], color: '#727072', fontStyle: 'italic' },
|
||||
{ tag: [t.keyword, t.controlKeyword, t.operatorKeyword, t.moduleKeyword], color: '#ff6188' },
|
||||
{ tag: [t.string, t.special(t.string)], color: '#ffd866' },
|
||||
{ tag: [t.number, t.bool, t.null, t.atom], color: '#ab9df2' },
|
||||
{ tag: [t.variableName, t.propertyName], color: '#fcfcfa' },
|
||||
{ tag: [t.function(t.variableName), t.definition(t.variableName)], color: '#a9dc76' },
|
||||
{ tag: [t.typeName, t.className, t.tagName], color: '#78dce8' },
|
||||
{ tag: [t.operator], color: '#ff6188' },
|
||||
{ tag: [t.heading1, t.heading2, t.heading3, t.heading4, t.heading5, t.heading6], color: '#a9dc76' },
|
||||
{ tag: t.strong, color: '#fcfcfa', fontWeight: 'bold' },
|
||||
{ tag: t.emphasis, color: '#fcfcfa', fontStyle: 'italic' },
|
||||
{ tag: t.strikethrough, color: '#fcfcfa', textDecoration: 'line-through' },
|
||||
{ tag: [t.link, t.url], color: '#78dce8', textDecoration: 'underline' },
|
||||
{ tag: t.monospace, color: '#ffd866' },
|
||||
{ tag: t.quote, color: '#727072' }
|
||||
]
|
||||
|
||||
/** 主题注册表(key 与 Rust 侧取值一致) */
|
||||
export const EDITOR_THEMES: Record<string, ThemeDefinition> = {
|
||||
'vscode-dark': {
|
||||
dark: true,
|
||||
extension: createTheme({
|
||||
theme: 'dark',
|
||||
settings: {
|
||||
background: '#1e1e1e',
|
||||
foreground: '#d4d4d4',
|
||||
caret: '#aeafad',
|
||||
selection: '#264f78',
|
||||
selectionMatch: '#264f7866',
|
||||
lineHighlight: '#ffffff0a',
|
||||
gutterBackground: '#1e1e1e',
|
||||
gutterForeground: '#858585',
|
||||
gutterActiveForeground: '#cccccc',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: VSCODE_DARK
|
||||
})
|
||||
},
|
||||
'vscode-light': {
|
||||
dark: false,
|
||||
extension: createTheme({
|
||||
theme: 'light',
|
||||
settings: {
|
||||
background: '#ffffff',
|
||||
foreground: '#333333',
|
||||
caret: '#000000',
|
||||
selection: '#add6ff',
|
||||
selectionMatch: '#add6ff80',
|
||||
lineHighlight: '#00000008',
|
||||
gutterBackground: '#ffffff',
|
||||
gutterForeground: '#237893',
|
||||
gutterActiveForeground: '#0b216f',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: VSCODE_LIGHT
|
||||
})
|
||||
},
|
||||
'one-dark': {
|
||||
dark: true,
|
||||
extension: oneDark
|
||||
},
|
||||
dracula: {
|
||||
dark: true,
|
||||
extension: createTheme({
|
||||
theme: 'dark',
|
||||
settings: {
|
||||
background: '#282a36',
|
||||
foreground: '#f8f8f2',
|
||||
caret: '#f8f8f2',
|
||||
selection: '#44475a',
|
||||
selectionMatch: '#44475a80',
|
||||
lineHighlight: '#ffffff08',
|
||||
gutterBackground: '#282a36',
|
||||
gutterForeground: '#6272a4',
|
||||
gutterActiveForeground: '#f8f8f2',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: DRACULA
|
||||
})
|
||||
},
|
||||
'solarized-dark': {
|
||||
dark: true,
|
||||
extension: createTheme({
|
||||
theme: 'dark',
|
||||
settings: {
|
||||
background: '#002b36',
|
||||
foreground: '#839496',
|
||||
caret: '#93a1a1',
|
||||
selection: '#073642',
|
||||
selectionMatch: '#07364280',
|
||||
lineHighlight: '#ffffff08',
|
||||
gutterBackground: '#002b36',
|
||||
gutterForeground: '#586e75',
|
||||
gutterActiveForeground: '#93a1a1',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: SOLARIZED_DARK
|
||||
})
|
||||
},
|
||||
'solarized-light': {
|
||||
dark: false,
|
||||
extension: createTheme({
|
||||
theme: 'light',
|
||||
settings: {
|
||||
background: '#fdf6e3',
|
||||
foreground: '#657b83',
|
||||
caret: '#586e75',
|
||||
selection: '#eee8d5',
|
||||
selectionMatch: '#eee8d580',
|
||||
lineHighlight: '#00000008',
|
||||
gutterBackground: '#fdf6e3',
|
||||
gutterForeground: '#93a1a1',
|
||||
gutterActiveForeground: '#586e75',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: SOLARIZED_LIGHT
|
||||
})
|
||||
},
|
||||
'jetbrains-darcula': {
|
||||
dark: true,
|
||||
extension: createTheme({
|
||||
theme: 'dark',
|
||||
settings: {
|
||||
background: '#2b2b2b',
|
||||
foreground: '#a9b7c6',
|
||||
caret: '#bbbbbb',
|
||||
selection: '#214283',
|
||||
selectionMatch: '#21428380',
|
||||
lineHighlight: '#ffffff08',
|
||||
gutterBackground: '#313335',
|
||||
gutterForeground: '#606366',
|
||||
gutterActiveForeground: '#a1a3a5',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: JETBRAINS_DARCULA
|
||||
})
|
||||
},
|
||||
'intellij-light': {
|
||||
dark: false,
|
||||
extension: createTheme({
|
||||
theme: 'light',
|
||||
settings: {
|
||||
background: '#ffffff',
|
||||
foreground: '#000000',
|
||||
caret: '#000000',
|
||||
selection: '#a6d2ff',
|
||||
selectionMatch: '#a6d2ff80',
|
||||
lineHighlight: '#00000008',
|
||||
gutterBackground: '#ffffff',
|
||||
gutterForeground: '#999999',
|
||||
gutterActiveForeground: '#666666',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: INTELLIJ_LIGHT
|
||||
})
|
||||
},
|
||||
'monokai-pro': {
|
||||
dark: true,
|
||||
extension: createTheme({
|
||||
theme: 'dark',
|
||||
settings: {
|
||||
background: '#2d2a2e',
|
||||
foreground: '#fcfcfa',
|
||||
caret: '#ffd866',
|
||||
selection: '#5b595c',
|
||||
selectionMatch: '#5b595c80',
|
||||
lineHighlight: '#ffffff08',
|
||||
gutterBackground: '#2d2a2e',
|
||||
gutterForeground: '#727072',
|
||||
gutterActiveForeground: '#fcfcfa',
|
||||
gutterBorder: '#00000000'
|
||||
},
|
||||
styles: MONOKAI_PRO
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置页下拉选项(`system` 置于首位) */
|
||||
export const EDITOR_THEME_OPTIONS: Array<{ value: string; label: string }> = [
|
||||
{ value: 'system', label: '跟随应用' },
|
||||
{ value: 'vscode-dark', label: 'VS Code 深色' },
|
||||
{ value: 'vscode-light', label: 'VS Code 浅色' },
|
||||
{ value: 'one-dark', label: 'One Dark' },
|
||||
{ value: 'dracula', label: 'Dracula' },
|
||||
{ value: 'solarized-dark', label: 'Solarized 深色' },
|
||||
{ value: 'solarized-light', label: 'Solarized 浅色' },
|
||||
{ value: 'jetbrains-darcula', label: 'JetBrains Darcula' },
|
||||
{ value: 'intellij-light', label: 'IntelliJ Light' },
|
||||
{ value: 'monokai-pro', label: 'Monokai Pro' }
|
||||
]
|
||||
|
||||
/** 亮暗成对:选深色主题但当前是浅色应用时,回落到对应浅色(避免浅底套深色) */
|
||||
const THEME_PAIRS: Record<string, { light: string; dark: string }> = {
|
||||
'vscode-dark': { light: 'vscode-light', dark: 'vscode-dark' },
|
||||
'vscode-light': { light: 'vscode-light', dark: 'vscode-dark' },
|
||||
'one-dark': { light: 'vscode-light', dark: 'one-dark' },
|
||||
dracula: { light: 'vscode-light', dark: 'dracula' },
|
||||
'solarized-dark': { light: 'solarized-light', dark: 'solarized-dark' },
|
||||
'solarized-light': { light: 'solarized-light', dark: 'solarized-dark' },
|
||||
// JetBrains 三套各自成对:Darcula ↔ IntelliJ Light(Monokai Pro 只有深色,
|
||||
// 浅色侧回落到 IntelliJ Light —— 它的色系与 Monokai 的浅色变体最接近)
|
||||
'jetbrains-darcula': { light: 'intellij-light', dark: 'jetbrains-darcula' },
|
||||
'intellij-light': { light: 'intellij-light', dark: 'jetbrains-darcula' },
|
||||
'monokai-pro': { light: 'intellij-light', dark: 'monokai-pro' },
|
||||
system: { light: 'vscode-light', dark: 'vscode-dark' }
|
||||
}
|
||||
|
||||
/** 求实际生效的主题名。 */
|
||||
export function effectiveThemeName(
|
||||
theme: string,
|
||||
followAppTheme: boolean,
|
||||
isDark: boolean
|
||||
): string {
|
||||
if (followAppTheme) {
|
||||
const pair = THEME_PAIRS[theme] ?? THEME_PAIRS.system
|
||||
return isDark ? pair.dark : pair.light
|
||||
}
|
||||
if (theme === 'system') return isDark ? 'vscode-dark' : 'vscode-light'
|
||||
return EDITOR_THEMES[theme] ? theme : 'vscode-dark'
|
||||
}
|
||||
|
||||
/** 解析为主题扩展。 */
|
||||
export function resolveEditorTheme(
|
||||
theme: string,
|
||||
followAppTheme: boolean,
|
||||
isDark: boolean
|
||||
): Extension {
|
||||
const name = effectiveThemeName(theme, followAppTheme, isDark)
|
||||
return (EDITOR_THEMES[name] ?? EDITOR_THEMES['vscode-dark']).extension
|
||||
}
|
||||
|
||||
/** 编辑器排版(字体 / 字号 / 行高 / 连字),与配色独立。 */
|
||||
export function editorTypography(opts: {
|
||||
fontFamily: string
|
||||
fontSize: number
|
||||
lineHeight: number
|
||||
ligatures: boolean
|
||||
}): Extension {
|
||||
const family =
|
||||
opts.fontFamily.trim() ||
|
||||
"'Cascadia Code', 'JetBrains Mono', Consolas, 'Courier New', monospace"
|
||||
return EditorView.theme({
|
||||
'&': {
|
||||
fontFamily: family,
|
||||
fontSize: `${opts.fontSize}px`,
|
||||
fontVariantLigatures: opts.ligatures ? 'contextual' : 'none'
|
||||
},
|
||||
'.cm-content, .cm-gutter': { lineHeight: String(opts.lineHeight) },
|
||||
'.cm-scroller': { fontFamily: family }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* `[[wikilink]]` 的显示与点击。
|
||||
*
|
||||
* # 为什么单独一个扩展
|
||||
*
|
||||
* Live Preview(`markdownLivePreview.ts`)负责**隐藏 Markdown 语法符号**,但它刻意
|
||||
* 不处理 wikilink:那是 Obsidian 的扩展语法,Lezer 的 Markdown 语法树里根本没有对应
|
||||
* 节点(`[[x]]` 会被解析成 `[` + `[x]` + `]` 这种普通链接片段),只能靠文本扫描识别。
|
||||
* 把它塞进 Live Preview 会让那个文件同时承担两件事(语法树装饰 + 文本扫描),
|
||||
* 因此独立成一层:**只做文本匹配与「可点击」**,不做任何隐藏。
|
||||
*
|
||||
* # 用 `Decoration.mark` 而不是 `replace`
|
||||
*
|
||||
* `replace` 会把 `[[` `]]` 从文档里「视觉删除」,但用户一旦把光标移进去就会看到
|
||||
* 位置错乱(替换装饰与光标位置相互影响)。这里给整段加 class(`cm-wikilink`),
|
||||
* 由 CSS 把方括号弱化显示 —— 既看得见语法(诚实),又一眼能认出是链接。
|
||||
*
|
||||
* # 点击行为
|
||||
*
|
||||
* 三种目标分别处理(与 Rust 侧 `resolve_link` 的判据一致):
|
||||
* - `[[名字]]` / `[[名字|别名]]` → 按库内相对路径解析(`名字.md`),命中则打开;
|
||||
* - `[[名字#小节]]` → 去掉 `#` 之后的部分,只按笔记名打开;
|
||||
* - `[[缺失的笔记]]` → 回调交给上层(弹「新建这篇笔记」而不是静默失败)。
|
||||
*/
|
||||
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from '@codemirror/view'
|
||||
import { type Extension, type Range } from '@codemirror/state'
|
||||
|
||||
/** `[[目标]]` 或 `[[目标|别名]]`;目标里不允许出现 `]`。 */
|
||||
const WIKILINK_RE = /\[\[([^\]\n|]+)(?:\|([^\]\n]*))?\]\]/g
|
||||
|
||||
export interface WikilinkHandlers {
|
||||
/** 点击一个链接(`target` 是去掉 `#` 与别名后的原始目标) */
|
||||
onOpen: (target: string) => void
|
||||
}
|
||||
|
||||
/** 解析 `[[...]]` 的内容为「笔记名 + 可选小节」。 */
|
||||
export function parseWikilink(raw: string): { name: string; anchor: string } {
|
||||
const [name, anchor = ''] = raw.split('#')
|
||||
return { name: (name ?? '').trim(), anchor: anchor.trim() }
|
||||
}
|
||||
|
||||
function buildDecorations(view: EditorView): DecorationSet {
|
||||
const decos: Range<Decoration>[] = []
|
||||
const doc = view.state.doc
|
||||
for (const { from, to } of view.visibleRanges) {
|
||||
// 按**行**扫:跨行不可能是 wikilink(正则里已禁 `\n`,这里再按行限制可以避免
|
||||
// 在超长行上做无谓的大范围扫描)
|
||||
let pos = from
|
||||
while (pos <= to) {
|
||||
const line = doc.lineAt(pos)
|
||||
const text = doc.sliceString(line.from, line.to)
|
||||
WIKILINK_RE.lastIndex = 0
|
||||
let match = WIKILINK_RE.exec(text)
|
||||
while (match) {
|
||||
const start = line.from + match.index
|
||||
const end = start + match[0].length
|
||||
const raw = match[1] ?? ''
|
||||
const { name } = parseWikilink(raw)
|
||||
if (name) {
|
||||
decos.push({
|
||||
from: start,
|
||||
to: end,
|
||||
value: Decoration.mark({
|
||||
class: 'cm-wikilink',
|
||||
attributes: {
|
||||
'data-wikilink': name,
|
||||
title: `打开「${name}」`
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
match = WIKILINK_RE.exec(text)
|
||||
}
|
||||
if (line.to >= to) break
|
||||
pos = line.to + 1
|
||||
}
|
||||
}
|
||||
return Decoration.set(decos, true)
|
||||
}
|
||||
|
||||
/** wikilink 外观 + 点击处理。 */
|
||||
export function wikilinkExtension(handlers: WikilinkHandlers): Extension {
|
||||
const theme = EditorView.baseTheme({
|
||||
'.cm-wikilink': {
|
||||
color: 'currentColor',
|
||||
textDecoration: 'underline',
|
||||
textDecorationStyle: 'dotted',
|
||||
textUnderlineOffset: '3px',
|
||||
cursor: 'pointer'
|
||||
},
|
||||
'.cm-wikilink:hover': {
|
||||
backgroundColor: 'rgba(127, 127, 127, 0.18)',
|
||||
borderRadius: '3px'
|
||||
}
|
||||
})
|
||||
|
||||
const plugin = ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = buildDecorations(view)
|
||||
}
|
||||
update(update: ViewUpdate) {
|
||||
if (update.docChanged || update.viewportChanged) {
|
||||
this.decorations = buildDecorations(update.view)
|
||||
}
|
||||
}
|
||||
},
|
||||
{ decorations: value => value.decorations }
|
||||
)
|
||||
|
||||
return [
|
||||
theme,
|
||||
plugin,
|
||||
EditorView.domEventHandlers({
|
||||
/**
|
||||
* 用 `pointerdown` 而不是 `mousedown`。
|
||||
*
|
||||
* `mousedown` 触发时 CodeMirror 已经先把光标移到了点击位置 —— 于是
|
||||
* 「点一下链接」会先改选区再跳转,看起来像「点了两次」。`pointerdown` 早于
|
||||
* 选区更新,能干净地 `preventDefault()` 并直接跳转。
|
||||
*
|
||||
* 命中判定用 Decoration.mark 写上的 `data-wikilink` 属性(而不是按坐标反查
|
||||
* 文档位置):属性是装饰渲染出来的,最可靠,也不依赖 `posAtCoords` 的取整行为。
|
||||
*/
|
||||
pointerdown(event, view) {
|
||||
if (event.button !== 0) return false
|
||||
const element = event.target as HTMLElement | null
|
||||
const name = element?.getAttribute?.('data-wikilink')
|
||||
if (!name) return false
|
||||
|
||||
// 不带修饰键时:这是「点链接」,不是「选文字」—— 抢掉事件直接跳转。
|
||||
// 带 Shift/Alt 时放行,让用户可以正常拖选链接文字。
|
||||
if (event.shiftKey || event.altKey) return false
|
||||
|
||||
event.preventDefault()
|
||||
// `preventDefault` 也吃掉了浏览器默认的「点击聚焦」,因此要手动 focus
|
||||
view.focus()
|
||||
// 顺带把光标放到链接起点,用户跳转后再回来时位置合理
|
||||
const pos = view.posAtDOM(element as HTMLElement, 0)
|
||||
view.dispatch({ selection: { anchor: pos } })
|
||||
handlers.onOpen(name)
|
||||
return true
|
||||
}
|
||||
})
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||
|
||||
/**
|
||||
* 全局搜索索引(本模块无内部 Tab,`tab` 一律省略 —— 搜索后直接落在模块页)。
|
||||
*/
|
||||
const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '笔记',
|
||||
description: 'Markdown 笔记库:所见即所得编辑、本地存储、WebDAV 备份',
|
||||
keywords: ['笔记', 'notes', 'note', 'markdown', 'md', '文档', 'wiki', '知识库']
|
||||
},
|
||||
{
|
||||
title: '打开笔记编辑器',
|
||||
description: '在新窗口中打开笔记 / 编辑器(可多开)',
|
||||
keywords: ['打开', '编辑器', '窗口', '独立窗口', 'editor', '工作区']
|
||||
},
|
||||
{
|
||||
title: '新建笔记',
|
||||
description: '在笔记库中新建一篇 Markdown 笔记',
|
||||
keywords: ['新建', '新建笔记', 'new', '创建', 'create']
|
||||
},
|
||||
{
|
||||
title: '笔记库设置',
|
||||
description: '库根目录、编辑器主题、字体字号、自动保存',
|
||||
keywords: ['设置', '主题', '字体', '字号', '库目录', '库根', '自动保存', 'vscode', 'darcula']
|
||||
}
|
||||
]
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'notes',
|
||||
name: '笔记',
|
||||
icon: 'notes',
|
||||
description: 'Markdown 笔记库与代码编辑器(所见即所得 + 多语言高亮 + 独立窗口)',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./NotesModule.vue'),
|
||||
searchItems,
|
||||
// 默认排在终端(40)之后
|
||||
order: 45
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 笔记模块的 IPC 客户端:命令名的**唯一落点**。
|
||||
*
|
||||
* # 为什么不直接在组件/ store 里写 `invoke('notes_xxx')`
|
||||
*
|
||||
* P0 阶段本项目还没有为新增命令重新生成 `src/lib/bindings.ts`(那需要一次
|
||||
* debug 构建跑 `export_bindings`),于是新增命令的类型只能手写。手写类型散落在
|
||||
* 十几处调用点时会同步腐坏:后端改个字段,前端在另一个文件里仍然编译通过。
|
||||
* 因此这里做一层薄封装 —— **命令名与返回类型只在本文件出现一次**,
|
||||
* 待 `bindings.ts` 重新生成后,改这一个文件即可完成切换。
|
||||
*
|
||||
* 参数名一律用 snake_case 形态的 camelCase(`relPath` / `dirRel` …),与
|
||||
* tauri-specta 生成的调用约定一致;改错参数名会被 Tauri 在运行时报
|
||||
* `invalid args`,所以这里刻意不做「参数对象透传」的花活,只做显式形参。
|
||||
*/
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import type {
|
||||
BackupReport,
|
||||
BackupSnapshot,
|
||||
ImportReport,
|
||||
LibraryEntry,
|
||||
LibraryInfo,
|
||||
LinkEdge,
|
||||
NoteBacklinks,
|
||||
NoteDoc,
|
||||
NoteFileDoc,
|
||||
NoteIndexReport,
|
||||
NoteIndexStats,
|
||||
NoteSearchPage,
|
||||
NoteSearchQuery,
|
||||
NoteSettings,
|
||||
NoteTagCount,
|
||||
SyncOutcome,
|
||||
TemplateSource,
|
||||
WebdavStatus,
|
||||
WebdavTestResult
|
||||
} from '@/types/notes'
|
||||
import type { NoteSearchHit, NoteTemplate } from '@/types/notes'
|
||||
|
||||
export const notesClient = {
|
||||
// ===== 设置 =====
|
||||
getSettings: () => invoke<NoteSettings>('notes_get_settings'),
|
||||
saveSettings: (settings: NoteSettings) =>
|
||||
invoke<NoteSettings>('notes_save_settings', { settings }),
|
||||
|
||||
// ===== 库 =====
|
||||
libraryInfo: () => invoke<LibraryInfo>('notes_library_info'),
|
||||
setLibraryRoot: (root: string | null) => invoke<LibraryInfo>('notes_set_library_root', { root }),
|
||||
scanLibrary: () => invoke<LibraryEntry[]>('notes_scan_library'),
|
||||
readNote: (relPath: string) => invoke<NoteDoc>('notes_read_note', { relPath }),
|
||||
saveNote: (relPath: string, content: string) =>
|
||||
invoke<NoteDoc>('notes_save_note', { relPath, content }),
|
||||
createNote: (dirRel: string, name: string, templateId?: string) =>
|
||||
invoke<NoteDoc>('notes_create_note', { dirRel, name, templateId: templateId ?? null }),
|
||||
createFolder: (dirRel: string, name: string) =>
|
||||
invoke<null>('notes_create_folder', { dirRel, name }),
|
||||
renameEntry: (relPath: string, newName: string) =>
|
||||
invoke<string>('notes_rename_entry', { relPath, newName }),
|
||||
deleteEntry: (relPath: string) => invoke<null>('notes_delete_entry', { relPath }),
|
||||
/** 打开(或创建)今天的日记 */
|
||||
dailyNote: () => invoke<NoteDoc>('notes_daily_note'),
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
rebuildIndex: () => invoke<NoteIndexReport>('notes_rebuild_index'),
|
||||
syncIndex: () => invoke<NoteIndexReport>('notes_sync_index'),
|
||||
/** 全文检索 / 标签 / 目录筛选(`query` 与 Rust 侧 `NoteSearchQuery` 一一对应) */
|
||||
search: (query: NoteSearchQuery) => invoke<NoteSearchPage>('notes_search_notes', { query }),
|
||||
listNotes: (limit?: number) => invoke<NoteSearchHit[]>('notes_list_notes', { limit: limit ?? null }),
|
||||
tags: () => invoke<NoteTagCount[]>('notes_tags'),
|
||||
indexStats: () => invoke<NoteIndexStats>('notes_index_stats'),
|
||||
/** 一篇笔记的出链 / 入链 */
|
||||
backlinks: (relPath: string) => invoke<NoteBacklinks>('notes_backlinks', { relPath }),
|
||||
/** 全库链接图(已解析的内部链接边) */
|
||||
linkGraph: () => invoke<LinkEdge[]>('notes_link_graph'),
|
||||
/**
|
||||
* 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
*
|
||||
* 冷启动时 Rust 无法 `emit`(前端还没注册监听),因此改为前端主动取一次。
|
||||
*/
|
||||
takePendingFile: () => invoke<string | null>('notes_take_pending_file'),
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
openFile: (path: string) => invoke<NoteFileDoc>('notes_open_file', { path }),
|
||||
writeFile: (path: string, content: string, encoding: string, eol: string) =>
|
||||
invoke<NoteFileDoc>('notes_write_file', { path, content, encoding, eol }),
|
||||
/** 登记系统对话框选中的路径为「可写」(它不是经 `openFile` 打开的) */
|
||||
authorizeFile: (path: string) => invoke<null>('notes_authorize_file', { path }),
|
||||
/** 把 base64 图片写进库根 `assets/`,返回可插入 Markdown 的相对路径 */
|
||||
writeAsset: (fileName: string, ext: string, dataBase64: string) =>
|
||||
invoke<string>('notes_write_asset', { fileName, ext, dataBase64 }),
|
||||
/**
|
||||
* 把库内图片读成 `data:` URL(内联预览用)。
|
||||
*
|
||||
* 返回 `null` 表示「不适合预览」(非图片扩展名 / 超过大小上限)——
|
||||
* 不是错误,调用方按普通文本渲染即可。
|
||||
*/
|
||||
readAsset: (relPath: string) => invoke<string | null>('notes_read_asset', { relPath }),
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
listTemplates: () => invoke<NoteTemplate[]>('notes_list_templates'),
|
||||
/** 不带参数 = 把全部内置模板导出到库内 `templates/` */
|
||||
addTemplate: (name?: string, body?: string) =>
|
||||
invoke<string[]>('notes_add_template', { name: name ?? null, body: body ?? null }),
|
||||
readTemplate: (templateId: string) =>
|
||||
invoke<TemplateSource>('notes_read_template', { templateId }),
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
import: (source: string, destDir: string) =>
|
||||
invoke<ImportReport>('notes_import', { source, destDir }),
|
||||
/** 把渲染好的 HTML 写到用户选定的位置(渲染在前端,落盘在后端) */
|
||||
exportNote: (relPath: string, html: string, dest: string) =>
|
||||
invoke<string>('notes_export_note', { relPath, html, dest }),
|
||||
exportZip: (dest: string, dirRel?: string) =>
|
||||
invoke<string>('notes_export_zip', { dest, dirRel: dirRel ?? null }),
|
||||
exportSnapshotLocal: (dest?: string) =>
|
||||
invoke<string>('notes_export_snapshot_local', { dest: dest ?? null }),
|
||||
|
||||
// ===== WebDAV(P2) =====
|
||||
webdavStatus: () => invoke<WebdavStatus>('notes_webdav_status'),
|
||||
setWebdavPassword: (password: string) =>
|
||||
invoke<null>('notes_set_webdav_password', { password }),
|
||||
testWebdav: () => invoke<WebdavTestResult>('notes_test_webdav'),
|
||||
syncNow: () => invoke<SyncOutcome>('notes_sync_now'),
|
||||
backupNow: () => invoke<BackupReport>('notes_backup_now'),
|
||||
listBackups: () => invoke<BackupSnapshot[]>('notes_list_backups'),
|
||||
restoreBackup: (name: string) => invoke<ImportReport>('notes_restore_backup', { name })
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 笔记「独立窗口」的创建入口(由前端创建,范式同 terminal/openWindow.ts)。
|
||||
*
|
||||
* - label 前缀 `notes-window-` 命中 `capabilities/notes-window.json` 的 `notes-window-*` 授权;
|
||||
* - **隐藏创建**:窗口初始底色是白的,而主题要等前端读 localStorage 后才应用 ——
|
||||
* 直接显示会先闪一下纯白。由 NotesWindow.vue 应用完主题(含窗口效果)再自己 show;
|
||||
* - **同目标判重聚焦**(规划 §8-Q1 选 (a)):窗口默认多开,但「同一个文件开两个窗口」
|
||||
* 几乎总是误操作 —— 两个窗口各自自动保存,后写的会覆盖先写的。
|
||||
*
|
||||
* # label 里为什么是哈希而不是明文路径
|
||||
*
|
||||
* 判重需要「由目标反推出窗口 label」。用 `notes-window-<目标>` 最直观,但窗口 label
|
||||
* 会出现在系统任务栏与调试面板里,把绝对路径(含用户名、项目名)塞进去既不雅也
|
||||
* 不必要。改用 FNV-1a 哈希:**同样稳定、可反推 label、但不泄露路径**。
|
||||
* 哈希碰撞的后果只是「两个不同文件被当成同一个窗口」——32 位空间下这在单次会话里
|
||||
* 可以忽略,而代价(不判重)远小于把路径写进 label。
|
||||
*/
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { WINDOWS } from '@/lib/constants'
|
||||
import { useNotesStore } from '@/stores/notesStore'
|
||||
|
||||
const logger = createLogger('notes')
|
||||
|
||||
/** label 前缀必须落在 `notes-window-*`(capability 的 glob)里 */
|
||||
const LABEL_PREFIX = `${WINDOWS.notesWindow}-`
|
||||
|
||||
/** FNV-1a 32 位哈希 → base36(稳定、短、无特殊字符)。 */
|
||||
function hashTarget(target: string): string {
|
||||
let hash = 0x811c9dc5
|
||||
for (let index = 0; index < target.length; index++) {
|
||||
hash ^= target.charCodeAt(index)
|
||||
hash = Math.imul(hash, 0x01000193) >>> 0
|
||||
}
|
||||
return hash.toString(36)
|
||||
}
|
||||
|
||||
/** 目标(相对路径或绝对路径)对应的窗口 label。 */
|
||||
export function labelForTarget(target: string): string {
|
||||
return `${LABEL_PREFIX}t${hashTarget(target)}`
|
||||
}
|
||||
|
||||
/** 聚焦已经打开该目标的窗口(找到返回 true)。 */
|
||||
async function focusTarget(target: string): Promise<boolean> {
|
||||
const existing = await WebviewWindow.getByLabel(labelForTarget(target))
|
||||
if (!existing) return false
|
||||
try {
|
||||
await existing.show()
|
||||
await existing.setFocus()
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个笔记窗口。
|
||||
*
|
||||
* @param options.relPath 可选:打开时直达的笔记(相对库根路径)
|
||||
* @param options.path 可选:打开时直达的**库外文件**(绝对路径,供 P1 的「打开文件」用)
|
||||
* @param options.dedupe 同一目标已开窗口时聚焦它(默认 true)
|
||||
*/
|
||||
export async function openNotesWindow(options?: {
|
||||
relPath?: string
|
||||
path?: string
|
||||
dedupe?: boolean
|
||||
}): Promise<void> {
|
||||
const isFile = !options?.relPath && !!options?.path
|
||||
const target = options?.relPath ?? options?.path ?? ''
|
||||
const query = target
|
||||
? `?${isFile ? 'path' : 'file'}=${encodeURIComponent(target)}`
|
||||
: ''
|
||||
|
||||
if (target && options?.dedupe !== false) {
|
||||
// 「复用文档窗口」是可关闭的设置(默认开)。关掉时每次新建窗口 ——
|
||||
// 有些用户确实想并排对照同一篇的不同位置。
|
||||
const reuse = useNotesStore().settings.reuseWindow
|
||||
if (reuse) {
|
||||
const focused = await focusTarget(target)
|
||||
if (focused) return
|
||||
}
|
||||
}
|
||||
|
||||
// 有目标时 label 由目标决定(于是「再点一次同一个文件」会命中上面那段判重)
|
||||
const label = target ? labelForTarget(target) : `${LABEL_PREFIX}${Date.now().toString(36)}`
|
||||
// label 已存在但判重被显式关掉:加时间戳后缀,避免 create 直接抛错
|
||||
const taken = await WebviewWindow.getByLabel(label)
|
||||
const finalLabel = taken ? `${label}-${Date.now().toString(36)}` : label
|
||||
|
||||
const win = new WebviewWindow(finalLabel, {
|
||||
url: `index.html#${WINDOWS.notesWindow}${query}`,
|
||||
title: '笔记',
|
||||
width: 1200,
|
||||
height: 800,
|
||||
minWidth: 760,
|
||||
minHeight: 480,
|
||||
resizable: true,
|
||||
decorations: false,
|
||||
// 透明通道用于承载 mica / acrylic(与主窗口一致的观感)
|
||||
transparent: true,
|
||||
shadow: true,
|
||||
center: true,
|
||||
visible: false,
|
||||
focus: false
|
||||
})
|
||||
|
||||
win.once('tauri://error', e => {
|
||||
logger.error(`打开笔记窗口失败:${String(e)}`)
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
win.once('tauri://created', () => resolve())
|
||||
win.once('tauri://error', e => reject(new Error(String(e))))
|
||||
})
|
||||
}
|
||||
@@ -173,6 +173,14 @@ export const useFeiniuStore = defineStore('feiniu', () => {
|
||||
/** 后台静默刷新中(已有数据时不阻塞展示,仅用于按钮转圈等轻提示) */
|
||||
const refreshing = ref(false)
|
||||
const loadingMore = ref(false)
|
||||
/**
|
||||
* 最近一次曲库拉取失败的原因(成功即清空)。
|
||||
*
|
||||
* 曲库页进入时是**静默刷新**(失败不弹 toast,列表照常展示旧数据),
|
||||
* 于是「一首都没有 + 拉取失败」时画面只剩一句「曲库为空」,
|
||||
* 看不出到底是没歌还是 NAS 侧出错。把它留下来给空态直接展示。
|
||||
*/
|
||||
const libraryError = ref('')
|
||||
/** 上次成功拉取曲库的时间戳:判断「重新进入曲库页是否还需要请求」 */
|
||||
let tracksFetchedAt = 0
|
||||
/** 在途拉取:并发进入时复用同一个请求,避免重复打 NAS */
|
||||
@@ -778,6 +786,7 @@ export const useFeiniuStore = defineStore('feiniu', () => {
|
||||
await invoke('feiniu_activate_connection', { id })
|
||||
// 换了激活连接:旧列表属于上一个 NAS,清掉并作废缓存,避免串库
|
||||
tracks.value = []
|
||||
libraryError.value = ''
|
||||
invalidateLibrary()
|
||||
await refreshConnections()
|
||||
if (config.value.loggedIn) await refreshMediaPrefix()
|
||||
@@ -816,6 +825,7 @@ export const useFeiniuStore = defineStore('feiniu', () => {
|
||||
config.value.loggedIn = false
|
||||
mediaPrefix.value = ''
|
||||
tracks.value = []
|
||||
libraryError.value = ''
|
||||
invalidateLibrary()
|
||||
clearPlayback()
|
||||
}
|
||||
@@ -885,9 +895,12 @@ export const useFeiniuStore = defineStore('feiniu', () => {
|
||||
tracks.value = append ? [...tracks.value, ...mapped] : mapped
|
||||
total.value = fetchedTotal ?? mapped.length
|
||||
page.value = p
|
||||
libraryError.value = ''
|
||||
if (first) tracksFetchedAt = Date.now()
|
||||
} catch (e) {
|
||||
logger.error(String(e))
|
||||
// 空列表时的失败原因留给空态展示(见 libraryError 的说明)
|
||||
if (!append) libraryError.value = String(e)
|
||||
throw e
|
||||
} finally {
|
||||
loading.value = false
|
||||
@@ -1827,6 +1840,8 @@ export const useFeiniuStore = defineStore('feiniu', () => {
|
||||
loading,
|
||||
refreshing,
|
||||
loadingMore,
|
||||
/** 最近一次曲库拉取失败原因(供曲库页空态展示) */
|
||||
libraryError,
|
||||
hasMoreTracks,
|
||||
searchKeyword,
|
||||
localTracks,
|
||||
|
||||
@@ -0,0 +1,846 @@
|
||||
/**
|
||||
* 笔记模块前端状态(主模块页与独立窗口共用同一份逻辑)。
|
||||
*
|
||||
* # 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
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,384 @@
|
||||
/**
|
||||
* 笔记 / 编辑器模块的前端类型。
|
||||
*
|
||||
* 这些结构在 Rust 侧有同名定义(`src-tauri/src/notes/types.rs`)。
|
||||
* 待 `bindings.ts` 生成后可由 `commands.notes_*` 的返回类型替代;
|
||||
* P0 阶段先在此声明,避免为了类型而强依赖一次 debug 构建。
|
||||
*/
|
||||
|
||||
/** 库内条目(扁平;树由前端组装) */
|
||||
export interface LibraryEntry {
|
||||
/** 显示名(不含目录前缀) */
|
||||
name: string
|
||||
/** 相对库根的路径,统一 `/` 分隔 */
|
||||
relPath: string
|
||||
/** 父目录相对路径(库根为 `''`) */
|
||||
parentRel: string
|
||||
isDir: boolean
|
||||
/** 最后修改时间(Unix 毫秒) */
|
||||
modified: number
|
||||
/** 文件字节数(目录为 0) */
|
||||
size: number
|
||||
}
|
||||
|
||||
/** 库状态概览 */
|
||||
export interface LibraryInfo {
|
||||
root: string
|
||||
isCustom: boolean
|
||||
noteCount: number
|
||||
}
|
||||
|
||||
/** 单篇笔记的读写结果 */
|
||||
export interface NoteDoc {
|
||||
relPath: string
|
||||
name: string
|
||||
/** 完整文件内容(含 front-matter) */
|
||||
content: string
|
||||
modified: number
|
||||
}
|
||||
|
||||
/** 库外任意文件的读写结果(对应 Rust `notes::files::FileDoc`) */
|
||||
export interface NoteFileDoc {
|
||||
/** 绝对路径(Windows 下已剥掉 `\\?\` 前缀) */
|
||||
path: string
|
||||
name: string
|
||||
/** 文本内容(换行已统一为 `\n`) */
|
||||
content: string
|
||||
/** 探测到的编码:`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / … */
|
||||
encoding: string
|
||||
/** 换行风格:"lf" | "crlf" */
|
||||
eol: string
|
||||
size: number
|
||||
modified: number
|
||||
/** 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全) */
|
||||
large: boolean
|
||||
lines: number
|
||||
}
|
||||
|
||||
/** 搜索命中的一篇笔记 */
|
||||
export interface NoteSearchHit {
|
||||
id: string
|
||||
relPath: string
|
||||
title: string
|
||||
/** 命中片段,含 `\u0002` / `\u0003` 高亮定界符(见 `splitHighlight`) */
|
||||
snippet: string
|
||||
tags: string[]
|
||||
modified: number
|
||||
}
|
||||
|
||||
/** 一次搜索的结果 */
|
||||
export interface NoteSearchPage {
|
||||
items: NoteSearchHit[]
|
||||
total: number
|
||||
}
|
||||
|
||||
/** 搜索筛选条件(与 Rust `NoteSearchQuery` 一一对应) */
|
||||
export interface NoteSearchQuery {
|
||||
keyword?: string
|
||||
tag?: string
|
||||
dir?: string
|
||||
offset?: number
|
||||
limit?: number
|
||||
}
|
||||
|
||||
/** 标签及计数 */
|
||||
export interface NoteTagCount {
|
||||
tag: string
|
||||
count: number
|
||||
}
|
||||
|
||||
/** 一条链接(出链或入链) */
|
||||
export interface NoteLink {
|
||||
/** 原始写法(`[[会议纪要]]` 里的 `会议纪要`) */
|
||||
target: string
|
||||
/** 解析出的库内相对路径(未解析时为空串) */
|
||||
relPath: string
|
||||
/** 目标笔记标题(未解析时为原始 target) */
|
||||
title: string
|
||||
/** 是否已解析到库内笔记 */
|
||||
resolved: boolean
|
||||
/** `wiki` | `md` | `url` */
|
||||
kind: string
|
||||
}
|
||||
|
||||
/** 一篇笔记的链接关系 */
|
||||
export interface NoteBacklinks {
|
||||
outgoing: NoteLink[]
|
||||
incoming: NoteLink[]
|
||||
/** 入链去重后的来源笔记数 */
|
||||
incomingSources: number
|
||||
}
|
||||
|
||||
/** 链接图的一条边 */
|
||||
export interface LinkEdge {
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
/** 「用 Thing 打开」事件负载 */
|
||||
export interface OpenFilePayload {
|
||||
path: string
|
||||
}
|
||||
|
||||
/** 索引状态 */
|
||||
export interface NoteIndexStats {
|
||||
noteCount: number
|
||||
fileCount: number
|
||||
tagCount: number
|
||||
schemaVersion: number
|
||||
dbPath: string
|
||||
}
|
||||
|
||||
/** 一次索引同步的结果 */
|
||||
export interface NoteIndexReport {
|
||||
indexed: number
|
||||
removed: number
|
||||
skipped: number
|
||||
noteCount: number
|
||||
}
|
||||
|
||||
/** 库内文件在应用外被改动的通知(对应 Rust `NoteFileEvent`) */
|
||||
export interface NoteFileEvent {
|
||||
relPath: string
|
||||
/** 磁盘上的绝对路径(库外文件靠它匹配) */
|
||||
absPath: string
|
||||
/** "modified" | "removed" */
|
||||
kind: string
|
||||
at: number
|
||||
fromApp: boolean
|
||||
}
|
||||
|
||||
// ===== P2:模板 / 导入导出 / WebDAV =====
|
||||
|
||||
/** 一个笔记模板 */
|
||||
export interface NoteTemplate {
|
||||
/** `builtin:<名>` 或 `user:<名>` */
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
/** 内置模板不可删除 */
|
||||
builtin: boolean
|
||||
body: string
|
||||
}
|
||||
|
||||
/** 模板正文与其库内位置(`path` 为 null = 内置模板) */
|
||||
export interface TemplateSource {
|
||||
body: string
|
||||
path: string | null
|
||||
}
|
||||
|
||||
/** 导入结果 */
|
||||
export interface ImportReport {
|
||||
imported: number
|
||||
renamed: number
|
||||
skipped: number
|
||||
failures: string[]
|
||||
}
|
||||
|
||||
/** 同步方向 */
|
||||
export type SyncDirection = 'bidirectional' | 'upload' | 'download'
|
||||
|
||||
/** 冲突策略 */
|
||||
export type ConflictPolicy = 'newer' | 'localWins' | 'remoteWins' | 'keepBoth'
|
||||
|
||||
/** WebDAV 设置(密码不在其中,它进系统凭据管理器) */
|
||||
export interface WebdavSettings {
|
||||
url: string
|
||||
username: string
|
||||
remoteRoot: string
|
||||
direction: SyncDirection
|
||||
conflict: ConflictPolicy
|
||||
autoSyncOnLaunch: boolean
|
||||
/** 远端保留的快照份数 */
|
||||
backupKeep: number
|
||||
}
|
||||
|
||||
/** WebDAV 配置状态(不回传密码本身) */
|
||||
export interface WebdavStatus {
|
||||
configured: boolean
|
||||
hasPassword: boolean
|
||||
remoteRoot: string
|
||||
}
|
||||
|
||||
/** 连接自检结果 */
|
||||
export interface WebdavTestResult {
|
||||
ok: boolean
|
||||
entries: number
|
||||
created: string[]
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 同步进度(事件 `notes-sync-progress` 的负载) */
|
||||
export interface SyncProgress {
|
||||
done: number
|
||||
total: number
|
||||
current: string
|
||||
/** `prepare` / `upload` / `download` / `move` / `remoteDelete` / `localDelete` / `conflict*` */
|
||||
kind: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 一次同步的报告 */
|
||||
export interface SyncReport {
|
||||
uploaded: number
|
||||
downloaded: number
|
||||
moved: number
|
||||
deletedRemote: number
|
||||
deletedLocal: number
|
||||
conflicts: number
|
||||
failed: number
|
||||
failures: string[]
|
||||
elapsedMs: number
|
||||
}
|
||||
|
||||
/** 一份远端快照 */
|
||||
export interface BackupSnapshot {
|
||||
name: string
|
||||
size: number
|
||||
modified: number
|
||||
}
|
||||
|
||||
/** 备份结果 */
|
||||
export interface BackupReport {
|
||||
name: string
|
||||
bytes: number
|
||||
files: number
|
||||
pruned: string[]
|
||||
}
|
||||
|
||||
/** 同步 + 备份的结果 */
|
||||
export interface SyncOutcome {
|
||||
report: SyncReport
|
||||
backup: BackupReport | null
|
||||
}
|
||||
|
||||
/** 片段高亮的定界符(必须与 Rust `index.rs` 的 `HL_OPEN` / `HL_CLOSE` 一致) */
|
||||
export const SNIPPET_HL_OPEN = '\u0002'
|
||||
export const SNIPPET_HL_CLOSE = '\u0003'
|
||||
|
||||
/** 把带定界符的片段切成 [{ text, hit }],供模板里用 `<mark>` 渲染(不注入 HTML) */
|
||||
export function splitHighlight(snippet: string): Array<{ text: string; hit: boolean }> {
|
||||
const parts: Array<{ text: string; hit: boolean }> = []
|
||||
let rest = snippet
|
||||
while (rest.length) {
|
||||
const open = rest.indexOf(SNIPPET_HL_OPEN)
|
||||
if (open < 0) {
|
||||
parts.push({ text: rest, hit: false })
|
||||
break
|
||||
}
|
||||
if (open > 0) parts.push({ text: rest.slice(0, open), hit: false })
|
||||
const close = rest.indexOf(SNIPPET_HL_CLOSE, open + 1)
|
||||
if (close < 0) {
|
||||
parts.push({ text: rest.slice(open + 1), hit: true })
|
||||
break
|
||||
}
|
||||
parts.push({ text: rest.slice(open + 1, close), hit: true })
|
||||
rest = rest.slice(close + 1)
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
/** 编辑器配色标识 */
|
||||
export type EditorThemeId =
|
||||
| 'system'
|
||||
| 'vscode-dark'
|
||||
| 'vscode-light'
|
||||
| 'one-dark'
|
||||
| 'dracula'
|
||||
| 'solarized-dark'
|
||||
| 'solarized-light'
|
||||
| 'jetbrains-darcula'
|
||||
| 'intellij-light'
|
||||
| 'monokai-pro'
|
||||
|
||||
/** 默认视图 */
|
||||
export type NoteViewMode = 'wysiwyg' | 'source'
|
||||
|
||||
/** 模块设置(与 Rust `NoteSettings` 字段一一对应) */
|
||||
export interface NoteSettings {
|
||||
version: number
|
||||
/** 自定义库根;`null` = 默认 `{appData}/notes/library` */
|
||||
libraryRoot: string | null
|
||||
editorTheme: EditorThemeId | string
|
||||
followAppTheme: boolean
|
||||
fontFamily: string
|
||||
fontSize: number
|
||||
lineHeight: number
|
||||
ligatures: boolean
|
||||
tabSize: number
|
||||
/** 是否启用 Live Preview(关闭 = 纯源码 + 高亮) */
|
||||
livePreview: boolean
|
||||
/** 自动保存防抖毫秒;0 = 关闭(仅手动保存) */
|
||||
autosaveMs: number
|
||||
/** 默认视图 */
|
||||
defaultView: NoteViewMode | string
|
||||
showLineNumbers: boolean
|
||||
/** 是否显示大纲侧栏(P1) */
|
||||
showOutline: boolean
|
||||
/** 是否启用自动补全 / 括号闭合(P1;大文件会强制关闭) */
|
||||
autocomplete: boolean
|
||||
/** 单文件大小上限(MB):超过则编辑器降级为纯高亮 + 行号(P1) */
|
||||
maxFileSizeMb: number
|
||||
/** 是否识别 `[[wikilink]]`(P1) */
|
||||
wikilink: boolean
|
||||
/** 多窗口是否复用同一文档的窗口(P1) */
|
||||
reuseWindow: boolean
|
||||
/** WebDAV 备份 / 同步设置(P2) */
|
||||
webdav: WebdavSettings
|
||||
/** 新建笔记时是否弹出模板选择(P2) */
|
||||
showTemplatePicker: boolean
|
||||
/** 导出 HTML 时是否内联代码高亮样式(P2) */
|
||||
exportHighlight: boolean
|
||||
/** 全局快捷键:新建笔记(空串 = 不注册) */
|
||||
newNoteShortcut: string
|
||||
/** 全局快捷键:打开编辑器窗口(空串 = 不注册) */
|
||||
openEditorShortcut: string
|
||||
}
|
||||
|
||||
/** 侧栏树节点 */
|
||||
export interface LibraryTreeNode {
|
||||
entry: LibraryEntry
|
||||
children: LibraryTreeNode[]
|
||||
}
|
||||
|
||||
/** 默认值(与 Rust `NoteSettings::default` 保持一致) */
|
||||
export function defaultNoteSettings(): NoteSettings {
|
||||
return {
|
||||
version: 2,
|
||||
libraryRoot: null,
|
||||
editorTheme: 'system',
|
||||
followAppTheme: true,
|
||||
fontFamily: '',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.7,
|
||||
ligatures: false,
|
||||
tabSize: 2,
|
||||
livePreview: true,
|
||||
autosaveMs: 800,
|
||||
defaultView: 'wysiwyg',
|
||||
showLineNumbers: true,
|
||||
showOutline: true,
|
||||
autocomplete: true,
|
||||
maxFileSizeMb: 5,
|
||||
wikilink: true,
|
||||
reuseWindow: true,
|
||||
webdav: defaultWebdavSettings(),
|
||||
showTemplatePicker: true,
|
||||
exportHighlight: true,
|
||||
newNoteShortcut: '',
|
||||
openEditorShortcut: ''
|
||||
}
|
||||
}
|
||||
|
||||
/** WebDAV 设置默认值(与 Rust `WebdavSettings::default` 保持一致) */
|
||||
export function defaultWebdavSettings(): WebdavSettings {
|
||||
return {
|
||||
url: '',
|
||||
username: '',
|
||||
remoteRoot: 'thing-notes',
|
||||
direction: 'bidirectional',
|
||||
conflict: 'keepBoth',
|
||||
autoSyncOnLaunch: false,
|
||||
backupKeep: 7
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user