diff --git a/bun.lock b/bun.lock index 61a62ea..0404974 100644 --- a/bun.lock +++ b/bun.lock @@ -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=="], diff --git a/AI_DEV_GUIDE.md b/doc/AI_DEV_GUIDE.md similarity index 100% rename from AI_DEV_GUIDE.md rename to doc/AI_DEV_GUIDE.md diff --git a/doc/EDITOR_MODULE_PLAN.md b/doc/EDITOR_MODULE_PLAN.md new file mode 100644 index 0000000..0839768 --- /dev/null +++ b/doc/EDITOR_MODULE_PLAN.md @@ -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` | **走系统回收站**(复用 `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. **`` 不能用空串 `value`**:reka-ui 把空串保留给 placeholder,会直接抛异常。用显式哨兵值(`'__all__'` / `'__current__'`)在调用点翻译。报错栈指向 `SelectItem.vue` 而不是调用方 —— 先搜 `value: ''`。 +2. **`cargo add ` 会连带升级整个 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>>`,前端注册完监听后主动取走。 +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\\.cargo\bin\cargo.exe" check --message-format short # 必须 0 warning +& "C:\Users\\.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=` 或 `?note=`);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) | +| 二进制文件编辑 | 编码/换行模型只对文本成立;识别为二进制时明确拒绝并提示用外部工具 | diff --git a/MUSIC_DECRYPT_PLAN.md b/doc/MUSIC_DECRYPT_PLAN.md similarity index 100% rename from MUSIC_DECRYPT_PLAN.md rename to doc/MUSIC_DECRYPT_PLAN.md diff --git a/MUSIC_REMOTE_PLAN.md b/doc/MUSIC_REMOTE_PLAN.md similarity index 100% rename from MUSIC_REMOTE_PLAN.md rename to doc/MUSIC_REMOTE_PLAN.md diff --git a/TERMINAL_MODULE_PLAN.md b/doc/TERMINAL_MODULE_PLAN.md similarity index 100% rename from TERMINAL_MODULE_PLAN.md rename to doc/TERMINAL_MODULE_PLAN.md diff --git a/UI_DESIGN_SYSTEM.md b/doc/UI_DESIGN_SYSTEM.md similarity index 100% rename from UI_DESIGN_SYSTEM.md rename to doc/UI_DESIGN_SYSTEM.md diff --git a/package.json b/package.json index 4ec8ad8..822e2e3 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index cd5c3cb..c23d652 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -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", ] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index fab34cb..ea046db 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -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 diff --git a/src-tauri/capabilities/notes-window.json b/src-tauri/capabilities/notes-window.json new file mode 100644 index 0000000..f54cd26 --- /dev/null +++ b/src-tauri/capabilities/notes-window.json @@ -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-). 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" + ] +} \ No newline at end of file diff --git a/src-tauri/src/constants.rs b/src-tauri/src/constants.rs index 75911cc..901f151 100644 --- a/src-tauri/src/constants.rs +++ b/src-tauri/src/constants.rs @@ -26,6 +26,9 @@ pub mod windows { /// 因此**不登记 capability**:远端页面不应获得任何 Tauri 权限)。 #[allow(dead_code)] pub const DSH_WEB: &str = "dsh-web"; + /// 笔记 / 编辑器独立窗口前缀,实际 label = `${NOTES_WINDOW}-`(可多开) + #[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"; } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 24fcae8..556f915 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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| { diff --git a/src-tauri/src/music/feiniu/mod.rs b/src-tauri/src/music/feiniu/mod.rs index 95e763c..54e6aa0 100644 --- a/src-tauri/src/music/feiniu/mod.rs +++ b/src-tauri/src/music/feiniu/mod.rs @@ -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>, 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::() + ), + ); 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::() + ), + ); + // 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()) } diff --git a/src-tauri/src/notes/args.rs b/src-tauri/src/notes/args.rs new file mode 100644 index 0000000..071a59e --- /dev/null +++ b/src-tauri/src/notes/args.rs @@ -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>> = std::sync::OnceLock::new(); + +fn pending_slot() -> &'static Mutex> { + 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 { + 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>(args: I) -> Option { + 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()); + } +} diff --git a/src-tauri/src/notes/backup.rs b/src-tauri/src/notes/backup.rs new file mode 100644 index 0000000..e92e6a6 --- /dev/null +++ b/src-tauri/src/notes/backup.rs @@ -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, 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 { + 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, 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, 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), 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 { + 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 = (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); + } +} diff --git a/src-tauri/src/notes/commands.rs b/src-tauri/src/notes/commands.rs new file mode 100644 index 0000000..304df4d --- /dev/null +++ b/src-tauri/src/notes/commands.rs @@ -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 { + 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 { + Ok(state.load_settings()) +} + +/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。 +#[tauri::command] +#[specta::specta] +pub fn notes_save_settings( + app: AppHandle, + state: State<'_, NotesManager>, + settings: NoteSettings, +) -> Result { + 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 { + library_info(&state) +} + +/// 设置库根(`None` 或空串 = 恢复默认库根)。 +#[tauri::command] +#[specta::specta] +pub fn notes_set_library_root( + app: AppHandle, + state: State<'_, NotesManager>, + root: Option, +) -> Result { + 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, 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 { + 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 { + 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, +) -> Result { + 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 { + 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 { + 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 { + 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 { + 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 { + 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, +) -> Result, 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, 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 { + let service = indexed(&app, &state)?; + service.backlinks(&rel_path) +} + +/// 全库链接图(已解析的内部链接边)。 +#[tauri::command] +#[specta::specta] +pub fn notes_link_graph( + app: AppHandle, + state: State<'_, NotesManager>, +) -> Result, 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 { + let service = indexed(&app, &state)?; + service.stats() +} + +// ===== 库外任意文件 ===== + +/// 把库内图片读成 `data:` URL(供编辑器内联预览)。 +/// +/// # 为什么走 data URL 而不是 asset 协议 +/// +/// 库根是用户自选目录,可以用 `convertFileSrc` + `assetProtocol.scope` 直接把磁盘路径 +/// 交给 ``。但那条路要求把「用户选的任意目录」加进 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, 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` 而不是报错 —— 正文里写个 + // `![](../notes.md)` 不该让编辑器弹错误。 + _ => 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, 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 { + 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 { + 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 { + 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, 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, + body: Option, +) -> Result, 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 { + 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, +} + +// ===== 导入 / 导出(P2) ===== + +/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 +#[tauri::command] +#[specta::specta] +pub fn notes_import( + app: AppHandle, + state: State<'_, NotesManager>, + source: String, + dest_dir: String, +) -> Result { + 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 { + 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, +) -> Result { + 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, +) -> Result { + 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 { + 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 { + 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 { + 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, +} + +/// 只做一次 zip 快照备份(不上传增量)。 +#[tauri::command] +#[specta::specta] +pub async fn notes_backup_now( + state: State<'_, NotesManager>, +) -> Result { + 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, 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 { + 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(task: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + match tokio::task::spawn_blocking(task).await { + Ok(result) => result, + Err(e) => Err(format!("后台任务执行失败: {e}")), + } +} diff --git a/src-tauri/src/notes/export.rs b/src-tauri/src/notes/export.rs new file mode 100644 index 0000000..c75c63e --- /dev/null +++ b/src-tauri/src/notes/export.rs @@ -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, 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) -> Vec { + 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); + } +} diff --git a/src-tauri/src/notes/files.rs b/src-tauri/src/notes/files.rs new file mode 100644 index 0000000..96ae951 --- /dev/null +++ b/src-tauri/src/notes/files.rs @@ -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>> = std::sync::OnceLock::new(); + +fn authorized() -> &'static Mutex> { + 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, 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 { + 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 { + 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 { + 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); + } +} diff --git a/src-tauri/src/notes/import.rs b/src-tauri/src/notes/import.rs new file mode 100644 index 0000000..c38009d --- /dev/null +++ b/src-tauri/src/notes/import.rs @@ -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 { + 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 { + 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 { + 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")); + }} diff --git a/src-tauri/src/notes/index.rs b/src-tauri/src/notes/index.rs new file mode 100644 index 0000000..e58b79d --- /dev/null +++ b/src-tauri/src/notes/index.rs @@ -0,0 +1,1454 @@ +//! 笔记索引:SQLite + FTS5 全文检索、标签、双链。 +//! +//! # 索引不是真相 +//! +//! 真相永远是库根下的 `.md` 文件(见 `library.rs`)。本模块只是**可随时丢弃重建** +//! 的加速层:删掉 `{库根}/.notes/notes.db` 的唯一后果是下次搜索前要做一次全量扫描。 +//! 因此这里不写「强一致」逻辑,只保证「一次同步之后索引与文件一致」—— +//! 增量同步靠 `(mtime, size)` 快速筛掉未变文件,变了才读内容算 hash。 +//! +//! # 为什么索引放在库根里(而不是 app_data) +//! +//! 库是可切换的(设置里的自定义目录)。索引跟库走有两个好处:换库自然换索引, +//! 不需要维护「库 → 索引文件」的映射;把整个库目录拷走时索引一起走,新机器上 +//! 第一次搜索只做增量校验而不是全量重建。 +//! +//! 代价是「数据库落在用户看得见的目录里」,所以目录名用点号前缀 `.notes/`: +//! 库扫描(`library::scan`)本来就跳过点号开头的目录,它不会出现在侧栏树里; +//! P2 的 WebDAV 同步也会按约定排除它。 +//! +//! # 分词器为什么选 trigram +//! +//! 笔记正文以中文为主,而 FTS5 默认的 `unicode61` 分词器把连续汉字切成**一整个** +//! 词元:搜「会议」匹配不到「周会议纪要」。`trigram` 按 3 字符 n-gram 建索引, +//! 中文任意子串(≥3 字)都能命中;代价是**查询词短于 3 字符时静默返回空**, +//! 所以 [`FTS_MIN_CHARS`] 以下的词回退到 `LIKE` 扫描(笔记库规模下完全够用)。 +//! 这与 `terminal/history.rs` 的取舍同源。 + +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +use rusqlite::{params, Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use sha2::{Digest, Sha256}; +use walkdir::WalkDir; + +use super::library::{self, ASSETS_DIR}; + +/// 库结构版本(与 `PRAGMA user_version` 对应)。 +/// +/// 索引全部可由文件重建,因此迁移策略取最简的一种:**版本不等就整库 DROP 重建** +/// (与 `translate/history.rs` 同一取舍,而未采用 `terminal/history.rs` 的增量迁移—— +/// 那里一条记录是用户敲过的命令,丢了就没了;这里一条记录是 `.md` 文件的投影, +/// 文件还在就什么都没丢)。 +const SCHEMA_VERSION: i64 = 1; + +/// 走 FTS 索引所需的最小字符数(trigram 的 3 字符下限,见模块头)。 +const FTS_MIN_CHARS: usize = 3; + +/// 正文入库上限(字节)。 +/// +/// 索引里的正文只服务于「生成高亮片段」,不用于回显全文。超大文件(用户把日志 +/// 改名成 `.md` 之类)截断存储,避免数据库被单篇笔记撑爆;`notes` 表仍记录真实 +/// 的 size/hash,改动检测不受影响。 +const MAX_BODY_BYTES: usize = 512 * 1024; + +/// 单次搜索返回条数上限(前端分页步长 30,500 已远超一屏)。 +const MAX_SEARCH_LIMIT: i64 = 200; + +/// 高亮片段的分隔标记。 +/// +/// **刻意不用 ``**:片段要在前端渲染,而笔记正文是用户内容,回传 HTML 就等于 +/// 把 XSS 风险引进渲染路径(P2 的导出链路才需要真正的 HTML 渲染 + 消毒)。 +/// 用两个 ASCII 控制字符当定界符,前端在文本层切分即可,注入无从发生。 +const HL_OPEN: char = '\u{2}'; +const HL_CLOSE: char = '\u{3}'; + +// ===== 对外数据结构 ===== + +/// 单篇笔记的索引记录(返回给前端的搜索结果项)。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteSearchHit { + /// 稳定 ID(front-matter 的 `id`;缺失时为空串) + pub id: String, + /// 相对库根的路径(`/` 分隔) + pub rel_path: String, + /// 显示标题(front-matter 的 `title`,缺失时取首个一级标题,再缺则取文件名) + pub title: String, + /// 命中片段(含 [`HL_OPEN`] / [`HL_CLOSE`] 定界符;无关键词搜索时为空) + pub snippet: String, + /// 标签 + pub tags: Vec, + /// 最后修改时间(Unix 毫秒) + pub modified: u64, +} + +/// 一次搜索的结果(含总数,供「共 N 条」显示)。 +/// +/// 名字带 `Note` 前缀不是啰嗦:`tauri-specta` 的类型注册表按**类型名全局唯一**, +/// 重名会让 `export_bindings()` 直接 panic(`terminal/history.rs` 的 +/// `TerminalHistoryPage` 就是为这个改的名)。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteSearchPage { + pub items: Vec, + /// 满足条件的总条数(**不受 limit/offset 影响**) + pub total: i64, +} + +/// 标签及其笔记数。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteTagCount { + pub tag: String, + pub count: i64, +} + +/// 一条链接(出链或入链)。 +/// +/// 出链与入链共用同一个结构,因为面板里展示的信息完全一样(标题 + 路径 + 原始目标)。 +/// `resolved` 区分「已解析到库内某篇笔记」与「未解析」(`[[不存在的笔记]]`)—— +/// 后者不是错误,而是反链面板里最有价值的提示:用户点一下就能建那篇笔记。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteLink { + /// 原始写法(`[[会议纪要]]` 里的 `会议纪要`,或 `[x](notes/a.md)` 里的 `notes/a.md`) + pub target: String, + /// 解析出的库内相对路径(未解析时为空串) + pub rel_path: String, + /// 目标笔记的标题(未解析时为原始 target) + pub title: String, + /// 是否已解析到库内笔记 + pub resolved: bool, + /// `wiki` | `md` | `url` + pub kind: String, +} + +/// 一篇笔记的链接关系(出链 + 入链)。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteBacklinks { + /// 本篇指向别处的链接 + pub outgoing: Vec, + /// 别处指向本篇的链接 + pub incoming: Vec, + /// 入链去重后的来源笔记数(面板标题显示「被 N 篇引用」) + pub incoming_sources: u32, +} + +/// 索引状态(设置页展示 / 诊断用)。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteIndexStats { + /// 索引中的笔记数 + pub note_count: i64, + /// 库中实际存在的 `.md` 文件数 + pub file_count: i64, + /// 标签数 + pub tag_count: i64, + /// 库结构版本 + pub schema_version: i64, + /// 索引文件路径 + pub db_path: String, +} + +/// 搜索筛选条件。 +/// +/// 用结构体而不是一长串位置参数:命令层把前端 payload 原样转发,而多个同类型 +/// 位置参数在调用点顺序写错时编译器不会报错(`terminal/history.rs` 同一理由)。 +#[derive(Debug, Clone, Default, Deserialize, Type)] +#[serde(rename_all = "camelCase", default)] +pub struct NoteSearchQuery { + /// 关键词(空格分隔的多个词按 AND 处理;空串 = 只按标签/目录筛选) + pub keyword: String, + /// 只看带该标签的笔记(空 = 不筛选) + pub tag: String, + /// 只看该目录(含子目录)下的笔记(空 = 全库) + pub dir: String, + /// 分页偏移 + pub offset: i64, + /// 分页大小 + pub limit: i64, +} + +impl NoteSearchQuery { + fn normalized(mut self) -> Self { + if self.limit <= 0 { + self.limit = 50; + } + if self.limit > MAX_SEARCH_LIMIT { + self.limit = MAX_SEARCH_LIMIT; + } + if self.offset < 0 { + self.offset = 0; + } + self + } +} + +// ===== front-matter 解析 ===== + +/// 一篇笔记解析出的元数据(不落盘,只用于写索引)。 +struct NoteMeta { + id: String, + title: String, + tags: Vec, + created: String, + updated: String, + body: String, + links: Vec, +} + +/// 拆出 front-matter 与正文。 +/// +/// 只认「文件第一行就是 `---`」的形式(标准 front-matter)。未闭合的 `---` 一律 +/// 当作正文:把一篇以 `---` 开头的普通笔记误判成「全是元数据」会让整篇内容从索引里 +/// 消失,而反过来只是标题退化成文件名 —— 两种误判代价不对称,这里选代价小的。 +fn split_front_matter(content: &str) -> (Option<&str>, &str) { + let normalized = content.strip_prefix('\u{feff}').unwrap_or(content); + let mut lines = normalized.split_inclusive('\n'); + let Some(first) = lines.next() else { + return (None, normalized); + }; + if first.trim_end() != "---" { + return (None, normalized); + } + + let mut offset = first.len(); + for line in lines { + let trimmed = line.trim_end(); + if trimmed == "---" || trimmed == "..." { + let fm = &normalized[first.len()..offset]; + let body = &normalized[offset + line.len()..]; + return (Some(fm), body); + } + offset += line.len(); + } + (None, normalized) +} + +/// 从 YAML 值里取字符串(容忍被引号包住、或写成数字/布尔的情况)。 +fn yaml_str(value: &serde_yaml::Value) -> String { + match value { + serde_yaml::Value::String(s) => s.trim().to_string(), + serde_yaml::Value::Number(n) => n.to_string(), + serde_yaml::Value::Bool(b) => b.to_string(), + _ => String::new(), + } +} + +/// 解析 `tags` 字段:YAML 里它可能是列表、逗号分隔串、或单个标签。 +fn parse_tags(value: Option<&serde_yaml::Value>) -> Vec { + let mut out: Vec = Vec::new(); + let mut push = |raw: &str| { + for part in raw.split([',', ',']) { + let tag = part.trim().trim_matches(['[', ']', '"', '\''].as_ref()).trim(); + if !tag.is_empty() && !out.iter().any(|t| t == tag) { + out.push(tag.to_string()); + } + } + }; + match value { + Some(serde_yaml::Value::Sequence(items)) => { + for item in items { + push(&yaml_str(item)); + } + } + Some(serde_yaml::Value::String(s)) => push(s), + Some(other) => push(&yaml_str(other)), + None => {} + } + out +} + +/// 首个**一级**标题的文本(front-matter 没写 title 时的兜底)。 +/// +/// 只认 `# `:把第一个碰到的任意级别标题当书名号会让「## 小节」抢走标题位 +/// (一篇笔记往往先写小节、再补一级标题)。 +fn first_h1(body: &str) -> Option { + body.lines().find_map(|line| { + let trimmed = line.trim_end().trim_start(); + // 用 `strip_prefix` 而不是「算 `#` 个数再切片」:后者是字节索引,缩进或多字节 + // 字符时容易切到非字符边界上。`?` 在闭包里是「这一行不是 H1」而不是「整篇结束」 + // —— `find_map` 的闭包返回 `Option`,`?` 只会让当次迭代返回 `None`。 + let title = trimmed.strip_prefix("# ")?.trim(); + if title.is_empty() { + None + } else { + Some(title.to_string()) + } + }) +} + +/// 收集正文里的链接目标:`[[wikilink]]` 与 `[text](target)`。 +fn collect_links(body: &str) -> Vec { + let mut out: Vec = Vec::new(); + let bytes = body.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + // [[wiki]] —— 忽略后面紧跟 `(` 的 `[[`(那是 `[[]](...)` 的少见写法) + if bytes[i] == b'[' && i + 1 < bytes.len() && bytes[i + 1] == b'[' { + if let Some(end) = body[i + 2..].find("]]") { + let target = body[i + 2..i + 2 + end].split('|').next().unwrap_or("").trim(); + if !target.is_empty() { + out.push(target.to_string()); + } + i += 2 + end + 2; + continue; + } + } + // [text](target) + if bytes[i] == b']' && i + 1 < bytes.len() && bytes[i + 1] == b'(' { + if let Some(end) = body[i + 2..].find(')') { + let target = body[i + 2..i + 2 + end].trim(); + let target = target.split_whitespace().next().unwrap_or(""); + if !target.is_empty() && !target.starts_with('#') { + out.push(target.to_string()); + } + i += 2 + end + 1; + continue; + } + } + i += 1; + } + out +} + +/// 解析一篇笔记的元数据与正文(不读磁盘,输入是文件内容)。 +fn parse_note(rel_path: &str, content: &str) -> NoteMeta { + let (front, body) = split_front_matter(content); + let mut id = String::new(); + let mut title = String::new(); + let mut tags: Vec = Vec::new(); + let mut created = String::new(); + let mut updated = String::new(); + + if let Some(front) = front { + if let Ok(serde_yaml::Value::Mapping(map)) = serde_yaml::from_str::(front) + { + let get = |keys: &[&str]| -> Option<&serde_yaml::Value> { + map.iter().find_map(|(k, v)| { + let key = yaml_str(k); + if keys.iter().any(|want| key.eq_ignore_ascii_case(want)) { + Some(v) + } else { + None + } + }) + }; + id = get(&["id", "uuid"]).map(yaml_str).unwrap_or_default(); + title = get(&["title"]).map(yaml_str).unwrap_or_default(); + tags = parse_tags(get(&["tags", "tag"])); + created = get(&["created", "date", "created_at"]) + .map(yaml_str) + .unwrap_or_default(); + updated = get(&["updated", "modified", "updated_at"]) + .map(yaml_str) + .unwrap_or_default(); + } + } + + if title.trim().is_empty() { + title = first_h1(body).unwrap_or_else(|| { + Path::new(rel_path) + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| rel_path.to_string()) + }); + } + + NoteMeta { + id, + title, + tags, + created, + updated, + body: body.to_string(), + links: collect_links(body), + } +} + +/// 文件内容 hash(用于「mtime 未变但内容确实变了」之外的改动判定, +/// 以及同步(P2)时的清单比对基准)。取前 16 字节十六进制即可。 +pub fn content_hash(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + let digest = hasher.finalize(); + let mut out = String::with_capacity(32); + for byte in digest.iter().take(16) { + out.push_str(&format!("{byte:02x}")); + } + out +} + +// ===== 索引本体 ===== + +/// 一次同步的统计结果。 +#[derive(Debug, Clone, Default, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct NoteSyncReport { + /// 本次新索引(或内容变化后重索引)的笔记数 + pub indexed: i64, + /// 本次从索引中移除的笔记数(文件已删除/改名) + pub removed: i64, + /// 因 (mtime, size) 未变而跳过的笔记数 + pub skipped: i64, +} + +/// 笔记索引(持有 SQLite 连接 + 当前库根)。 +pub struct NotesIndex { + conn: Connection, + /// 索引所属的库根(库切换时整个索引实例被替换) + root: PathBuf, + /// 索引文件绝对路径(诊断展示用) + db_path: PathBuf, +} + +impl NotesIndex { + /// 打开(或创建)某个库根对应的索引。 + /// + /// 库根切换后由命令层用新库根调用本函数重建实例 —— 索引与库一一对应, + /// 不做「一份索引服务多个库」的多态(那需要为每张表加 root 列,得不偿失)。 + pub fn open(root: &Path) -> Result { + let dir = root.join(".notes"); + std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?; + let db_path = dir.join("notes.db"); + let conn = Connection::open(&db_path).map_err(|e| format!("打开笔记索引失败: {e}"))?; + conn.busy_timeout(std::time::Duration::from_secs(3)) + .map_err(|e| format!("设置索引超时失败: {e}"))?; + // WAL:读(搜索)与写(索引同步)互不阻塞,与 terminal / translate 的历史库一致 + let _ = conn.pragma_update(None, "journal_mode", "WAL"); + let _ = conn.pragma_update(None, "synchronous", "NORMAL"); + + let mut index = Self { + conn, + root: root.to_path_buf(), + db_path, + }; + index.ensure_schema()?; + Ok(index) + } + + /// 库根(供调用方判断是否需要换库)。 + pub fn root(&self) -> &Path { + &self.root + } + + /// 索引文件路径。 + pub fn db_path(&self) -> &Path { + &self.db_path + } + + /// 建表 + 版本检查(版本不等则整库重建,见 [`SCHEMA_VERSION`])。 + fn ensure_schema(&mut self) -> Result<(), String> { + let version: i64 = self + .conn + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .unwrap_or(0); + + if version != 0 && version != SCHEMA_VERSION { + crate::logger::log_warn( + "notes", + &format!("索引结构版本 {version} → {SCHEMA_VERSION},按文件重建索引"), + ); + self.drop_all()?; + } + + self.conn + .execute_batch( + " + CREATE TABLE IF NOT EXISTS notes ( + rel_path TEXT PRIMARY KEY, + id TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + tags TEXT NOT NULL DEFAULT '', + created TEXT NOT NULL DEFAULT '', + updated TEXT NOT NULL DEFAULT '', + mtime INTEGER NOT NULL DEFAULT 0, + size INTEGER NOT NULL DEFAULT 0, + hash TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL DEFAULT '' + ); + CREATE INDEX IF NOT EXISTS idx_notes_mtime ON notes(mtime DESC); + + -- 外部内容表:索引只存倒排表,正文只在 notes 里一份。 + -- 代价是不会自动感知主表变化,靠下面三个触发器同步。 + CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5( + title, body, + content='notes', content_rowid='rowid', + tokenize='trigram' + ); + + CREATE TRIGGER IF NOT EXISTS notes_fts_ai AFTER INSERT ON notes BEGIN + INSERT INTO notes_fts(rowid, title, body) VALUES (new.rowid, new.title, new.body); + END; + CREATE TRIGGER IF NOT EXISTS notes_fts_ad AFTER DELETE ON notes BEGIN + INSERT INTO notes_fts(notes_fts, rowid, title, body) + VALUES ('delete', old.rowid, old.title, old.body); + END; + CREATE TRIGGER IF NOT EXISTS notes_fts_au AFTER UPDATE ON notes BEGIN + INSERT INTO notes_fts(notes_fts, rowid, title, body) + VALUES ('delete', old.rowid, old.title, old.body); + INSERT INTO notes_fts(rowid, title, body) VALUES (new.rowid, new.title, new.body); + END; + + CREATE TABLE IF NOT EXISTS tags ( + name TEXT PRIMARY KEY + ); + CREATE TABLE IF NOT EXISTS note_tags ( + rel_path TEXT NOT NULL, + tag TEXT NOT NULL, + PRIMARY KEY (rel_path, tag) + ); + CREATE INDEX IF NOT EXISTS idx_note_tags_tag ON note_tags(tag); + + -- 双链 / 未解析链接。dst_path 为解析出的库内相对路径(尽力而为), + -- 解析不到时只留原始 target —— 「未解析链接」本身就是反链面板要展示的信息。 + CREATE TABLE IF NOT EXISTS links ( + src_path TEXT NOT NULL, + target TEXT NOT NULL, + dst_path TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL DEFAULT 'md' + ); + CREATE INDEX IF NOT EXISTS idx_links_src ON links(src_path); + CREATE INDEX IF NOT EXISTS idx_links_dst ON links(dst_path); + ", + ) + .map_err(|e| format!("初始化笔记索引表失败: {e}"))?; + + self.conn + .pragma_update(None, "user_version", SCHEMA_VERSION) + .map_err(|e| format!("写入索引版本失败: {e}"))?; + Ok(()) + } + + /// 清空全部索引结构(版本迁移用;文件不受影响)。 + fn drop_all(&mut self) -> Result<(), String> { + self.conn + .execute_batch( + "DROP TABLE IF EXISTS notes_fts; + DROP TABLE IF EXISTS note_tags; + DROP TABLE IF EXISTS tags; + DROP TABLE IF EXISTS links; + DROP TABLE IF EXISTS notes;", + ) + .map_err(|e| format!("重建索引表失败: {e}")) + } + + /// 全量重建:清空索引后重新扫描整个库。 + pub fn rebuild(&mut self) -> Result { + self.drop_all()?; + self.conn + .pragma_update(None, "user_version", 0) + .map_err(|e| format!("重置索引版本失败: {e}"))?; + self.ensure_schema()?; + self.sync() + } + + /// 增量同步:扫描库根,只对「mtime/size 变化或索引里没有」的文件重新解析。 + pub fn sync(&mut self) -> Result { + let mut report = NoteSyncReport::default(); + let root = self.root.clone(); + + // 1) 先收集磁盘现状(顺带拿到 (mtime, size) 用于快速筛) + let mut seen: Vec<(String, u64, u64, PathBuf)> = Vec::new(); + for entry in WalkDir::new(&root) + .max_depth(library::MAX_DEPTH) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() { + continue; + } + let path = entry.path(); + // 跳过点号目录(含 `.notes/` 自身)与根级 assets/ + if skip_path(&root, path) { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if !name.to_ascii_lowercase().ends_with(".md") { + continue; + } + let Ok(meta) = entry.metadata() else { continue }; + let rel = library::rel_string(&root, path); + seen.push((rel, modified_ms(&meta), meta.len(), path.to_path_buf())); + } + + // 2) 文件名 → 相对路径映射(wikilink 按名解析用,见 resolve_link) + let mut stems: std::collections::HashMap = std::collections::HashMap::new(); + for (rel, ..) in &seen { + if let Some(stem) = Path::new(rel).file_stem() { + stems + .entry(stem.to_string_lossy().to_ascii_lowercase()) + .or_insert_with(|| rel.clone()); + } + } + + // 3) 索引里有、磁盘上没有的 → 删 + let existing: Vec = { + let mut stmt = self + .conn + .prepare("SELECT rel_path FROM notes") + .map_err(|e| format!("读取索引清单失败: {e}"))?; + let rows = stmt + .query_map([], |row| row.get::<_, String>(0)) + .map_err(|e| format!("读取索引清单失败: {e}"))?; + rows.filter_map(Result::ok).collect() + }; + for rel in existing { + if !seen.iter().any(|(path, ..)| *path == rel) { + self.remove_note(&rel)?; + report.removed += 1; + } + } + + // 4) 逐个文件:未变跳过,变了重解析 + for (rel, mtime, size, path) in seen { + let cached: Option<(i64, i64)> = self + .conn + .query_row( + "SELECT mtime, size FROM notes WHERE rel_path = ?1", + params![rel], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .map_err(|e| format!("查询笔记索引失败: {e}"))?; + if let Some((cached_mtime, cached_size)) = cached { + if cached_mtime as u64 == mtime && cached_size as u64 == size { + report.skipped += 1; + continue; + } + } + + // 读文件:非 UTF-8 按有损解码 —— 索引里出现替换字符好过整库索引失败 + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) => { + crate::logger::log_warn("notes", &format!("索引读取失败 {rel}: {e}")); + continue; + } + }; + let content = String::from_utf8_lossy(&bytes); + self.upsert_note(&rel, &content, mtime, size, &content_hash(&bytes), &stems)?; + report.indexed += 1; + } + + Ok(report) + } + + /// 写入/更新一篇笔记的索引(含标签与链接)。 + /// + /// `stems` 供 wikilink 按文件名解析;单篇保存时调用方若不想扫全库, + /// 可以先 `list_notes` 现搭一份小映射(见 `commands.rs`),或传空表退化为 + /// 「按相对路径解析」。 + pub fn upsert_note( + &mut self, + rel_path: &str, + content: &str, + mtime: u64, + size: u64, + hash: &str, + stems: &std::collections::HashMap, + ) -> Result<(), String> { + let meta = parse_note(rel_path, content); + let body: String = { + let mut body = meta.body.clone(); + if body.len() > MAX_BODY_BYTES { + // 按字符边界截断,避免切出半个 UTF-8 序列 + let mut cut = MAX_BODY_BYTES; + while cut > 0 && !body.is_char_boundary(cut) { + cut -= 1; + } + body.truncate(cut); + } + body + }; + + let tx = self + .conn + .transaction() + .map_err(|e| format!("开启索引事务失败: {e}"))?; + tx.execute( + "INSERT INTO notes (rel_path, id, title, tags, created, updated, mtime, size, hash, body) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) + ON CONFLICT(rel_path) DO UPDATE SET + id = excluded.id, title = excluded.title, tags = excluded.tags, + created = excluded.created, updated = excluded.updated, + mtime = excluded.mtime, size = excluded.size, hash = excluded.hash, + body = excluded.body", + params![ + rel_path, + meta.id, + meta.title, + meta.tags.join(","), + meta.created, + meta.updated, + mtime as i64, + size as i64, + hash, + body + ], + ) + .map_err(|e| format!("写入笔记索引失败: {e}"))?; + + // 标签:先删后插(改标签是最常见的编辑动作之一,diff 不值得) + tx.execute("DELETE FROM note_tags WHERE rel_path = ?1", params![rel_path]) + .map_err(|e| format!("清理标签失败: {e}"))?; + for tag in &meta.tags { + tx.execute("INSERT OR IGNORE INTO tags (name) VALUES (?1)", params![tag]) + .map_err(|e| format!("写入标签失败: {e}"))?; + tx.execute( + "INSERT OR REPLACE INTO note_tags (rel_path, tag) VALUES (?1, ?2)", + params![rel_path, tag], + ) + .map_err(|e| format!("关联标签失败: {e}"))?; + } + + // 链接:同样先删后插 + tx.execute("DELETE FROM links WHERE src_path = ?1", params![rel_path]) + .map_err(|e| format!("清理链接失败: {e}"))?; + for link in &meta.links { + let (dst, kind) = resolve_link(rel_path, link, stems); + tx.execute( + "INSERT INTO links (src_path, target, dst_path, kind) VALUES (?1, ?2, ?3, ?4)", + params![rel_path, link, dst, kind], + ) + .map_err(|e| format!("写入链接失败: {e}"))?; + } + + tx.commit().map_err(|e| format!("提交索引事务失败: {e}")) + } + + /// 从索引里移除一篇笔记(文件被删除/改名)。 + pub fn remove_note(&mut self, rel_path: &str) -> Result<(), String> { + let tx = self + .conn + .transaction() + .map_err(|e| format!("开启索引事务失败: {e}"))?; + tx.execute("DELETE FROM notes WHERE rel_path = ?1", params![rel_path]) + .map_err(|e| format!("删除索引项失败: {e}"))?; + tx.execute("DELETE FROM note_tags WHERE rel_path = ?1", params![rel_path]) + .map_err(|e| format!("清理标签失败: {e}"))?; + tx.execute("DELETE FROM links WHERE src_path = ?1", params![rel_path]) + .map_err(|e| format!("清理链接失败: {e}"))?; + // 顺手清掉「已无人引用」的标签,避免标签云里堆着一堆 0 计数条目 + tx.execute( + "DELETE FROM tags WHERE name NOT IN (SELECT DISTINCT tag FROM note_tags)", + [], + ) + .map_err(|e| format!("清理空标签失败: {e}"))?; + tx.commit().map_err(|e| format!("提交索引事务失败: {e}")) + } + + /// 全文检索 / 筛选。 + pub fn search(&self, query: NoteSearchQuery) -> Result { + let query = query.normalized(); + let keyword = query.keyword.trim(); + let tag = query.tag.trim(); + let dir = query.dir.trim().trim_matches('/'); + + // 关键词走 FTS 时额外套一层子查询,便于把「筛选条件」与「命中排序」解耦 + let use_fts = keyword.chars().count() >= FTS_MIN_CHARS; + let mut joins = String::new(); + let mut wheres: Vec = Vec::new(); + let mut args: Vec> = Vec::new(); + + if use_fts { + joins.push_str(" JOIN notes_fts f ON f.rowid = notes.rowid"); + wheres.push("notes_fts MATCH ?".to_string()); + args.push(Box::new(fts_query(keyword))); + } + if !keyword.is_empty() && !use_fts { + // 短词回退:trigram 对 <3 字符的查询静默返回空,这里退化成子串匹配 + wheres.push("(notes.title LIKE ? OR notes.body LIKE ?)".to_string()); + let like = format!("%{keyword}%"); + args.push(Box::new(like.clone())); + args.push(Box::new(like)); + } + if !tag.is_empty() { + wheres.push("EXISTS (SELECT 1 FROM note_tags nt WHERE nt.rel_path = notes.rel_path AND nt.tag = ?)".to_string()); + args.push(Box::new(tag.to_string())); + } + if !dir.is_empty() { + // 目录筛选含子目录:'dir/%' 前缀匹配;根目录(空串)已在上面归一化掉 + wheres.push("notes.rel_path LIKE ?".to_string()); + args.push(Box::new(format!("{dir}/%"))); + } + + let where_sql = if wheres.is_empty() { + String::new() + } else { + format!(" WHERE {}", wheres.join(" AND ")) + }; + + let total: i64 = { + let sql = format!("SELECT COUNT(*) FROM notes{joins}{where_sql}"); + let refs: Vec<&dyn rusqlite::ToSql> = args.iter().map(|b| b.as_ref()).collect(); + self.conn + .query_row(&sql, refs.as_slice(), |row| row.get(0)) + .map_err(|e| format!("统计检索结果失败: {e}"))? + }; + + // 片段:走 FTS 时用 snippet()(列索引 `-1` = **让 FTS 自己挑最佳列**)。 + // + // 不写死列号的原因:关键词常常命中**标题**(中文笔记尤其如此 —— 「周会」就在 + // 标题「周会纪要」里),写死正文列会得到一个与命中位置无关的片段。 + // 短词回退 LIKE 时另有 Rust 侧生成的片段(见 `make_snippet`),这里留空。 + let snippet_expr = if use_fts { + format!( + "snippet(notes_fts, -1, '{}', '{}', '…', 18)", + HL_OPEN, HL_CLOSE + ) + } else { + "''".to_string() + }; + let order = if use_fts { + "bm25(notes_fts, 8.0, 1.0)".to_string() + } else { + "notes.mtime DESC".to_string() + }; + // 短词回退时一并取回正文,用于生成片段(正文列已在写索引时截断过长度) + let body_expr = if use_fts { "''" } else { "notes.body" }; + + let sql = format!( + "SELECT notes.rel_path, notes.id, notes.title, notes.tags, notes.mtime, {snippet_expr}, {body_expr} + FROM notes{joins}{where_sql} ORDER BY {order} LIMIT ? OFFSET ?" + ); + let mut stmt = self + .conn + .prepare(&sql) + .map_err(|e| format!("准备检索语句失败: {e}"))?; + + let mut all: Vec> = args; + all.push(Box::new(query.limit)); + all.push(Box::new(query.offset)); + let refs: Vec<&dyn rusqlite::ToSql> = all.iter().map(|b| b.as_ref()).collect(); + + let rows = stmt + .query_map(refs.as_slice(), |row| { + let tags: String = row.get(3)?; + Ok(( + NoteSearchHit { + rel_path: row.get(0)?, + id: row.get(1)?, + title: row.get(2)?, + tags: tags + .split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect(), + modified: row.get::<_, i64>(4)? as u64, + snippet: row.get(5)?, + }, + row.get::<_, String>(6)?, + )) + }) + .map_err(|e| format!("检索失败: {e}"))?; + + let mut items: Vec = Vec::new(); + for row in rows.filter_map(Result::ok) { + let (mut hit, body) = row; + if hit.snippet.is_empty() && !keyword.is_empty() { + // 短词回退(LIKE)路径:FTS 不给片段,这里自己截 + hit.snippet = make_snippet(&hit.title, &body, keyword); + } + items.push(hit); + } + Ok(NoteSearchPage { items, total }) + } + + /// 查询一篇笔记的链接关系(出链 + 入链)。 + /// + /// # 入链为什么按 `dst_path` 匹配 + /// + /// 写索引时已经把链接目标**尽力解析**成库内相对路径(含 Obsidian 式「全库按名解析」)。 + /// 因此「谁引用了我」只需要 `links.dst_path = 本篇路径`。未解析的链接 + /// (`dst_path = ''`)自然不会被算作任何一篇的入链 —— 这正是期望行为: + /// 指向不存在笔记的链接不该在别处显示成反链。 + /// + /// # 出链为什么用 LEFT JOIN + /// + /// 出链里既有已解析的(`dst_path` 命中 `notes`)也有未解析的(空串或指向不存在的 + /// 目标)。用 LEFT JOIN 一次取回,未解析的那些 `rel_path` 为空、`title` 回退成原始 + /// target —— 前端据此把它们渲染成「点一下就能新建」的入口。 + pub fn backlinks(&self, rel_path: &str) -> Result { + let outgoing = { + let mut stmt = self + .conn + .prepare( + "SELECT links.target, links.kind, + COALESCE(notes.rel_path, ''), COALESCE(notes.title, '') + FROM links LEFT JOIN notes ON notes.rel_path = links.dst_path + WHERE links.src_path = ?1 + ORDER BY links.target", + ) + .map_err(|e| format!("准备出链语句失败: {e}"))?; + let rows = stmt + .query_map(params![rel_path], |row| { + let target: String = row.get(0)?; + let kind: String = row.get(1)?; + let dst: String = row.get(2)?; + let title: String = row.get(3)?; + Ok(NoteLink { + title: if title.is_empty() { + target.clone() + } else { + title + }, + resolved: !dst.is_empty(), + rel_path: dst, + target, + kind, + }) + }) + .map_err(|e| format!("查询出链失败: {e}"))?; + rows.filter_map(Result::ok).collect::>() + }; + + let incoming = { + let mut stmt = self + .conn + .prepare( + "SELECT links.target, links.kind, links.src_path, COALESCE(notes.title, '') + FROM links LEFT JOIN notes ON notes.rel_path = links.src_path + WHERE links.dst_path = ?1 + ORDER BY links.src_path", + ) + .map_err(|e| format!("准备入链语句失败: {e}"))?; + let rows = stmt + .query_map(params![rel_path], |row| { + let target: String = row.get(0)?; + let kind: String = row.get(1)?; + let src: String = row.get(2)?; + let title: String = row.get(3)?; + Ok(NoteLink { + title: if title.is_empty() { + src.clone() + } else { + title + }, + // 入链的「目标」就是来源笔记本身 + resolved: true, + rel_path: src, + target, + kind, + }) + }) + .map_err(|e| format!("查询入链失败: {e}"))?; + rows.filter_map(Result::ok).collect::>() + }; + + let incoming_sources = { + let mut set: Vec<&str> = incoming.iter().map(|l| l.rel_path.as_str()).collect(); + set.sort_unstable(); + set.dedup(); + set.len() as u32 + }; + + Ok(NoteBacklinks { + outgoing, + incoming, + incoming_sources, + }) + } + + /// 全库链接图(`{ 源路径: [目标路径] }`,只含已解析的内部链接)。 + /// + /// 供「双链图谱」用。只返回已解析的边:指向不存在笔记的链接在图上没有节点可连。 + pub fn link_graph(&self) -> Result, String> { + let mut stmt = self + .conn + .prepare( + "SELECT src_path, dst_path FROM links + WHERE dst_path <> '' AND kind <> 'url' + ORDER BY src_path, dst_path", + ) + .map_err(|e| format!("准备图谱语句失败: {e}"))?; + let rows = stmt + .query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))) + .map_err(|e| format!("查询图谱失败: {e}"))?; + Ok(rows.filter_map(Result::ok).collect()) + } + + /// 快速打开用的轻量清单(只取路径/标题/时间,不带正文与片段)。 + pub fn list_notes(&self, limit: i64) -> Result, String> { + let limit = limit.clamp(1, 2000); + let mut stmt = self + .conn + .prepare( + "SELECT rel_path, id, title, tags, mtime FROM notes ORDER BY mtime DESC LIMIT ?1", + ) + .map_err(|e| format!("准备清单语句失败: {e}"))?; + let rows = stmt + .query_map(params![limit], |row| { + let tags: String = row.get(3)?; + Ok(NoteSearchHit { + rel_path: row.get(0)?, + id: row.get(1)?, + title: row.get(2)?, + tags: tags + .split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect(), + modified: row.get::<_, i64>(4)? as u64, + snippet: String::new(), + }) + }) + .map_err(|e| format!("读取笔记清单失败: {e}"))?; + Ok(rows.filter_map(Result::ok).collect()) + } + + /// 标签及计数(按计数降序、同计数按名称)。 + pub fn tags(&self) -> Result, String> { let mut stmt = self + .conn + .prepare( + "SELECT tag, COUNT(*) AS n FROM note_tags GROUP BY tag ORDER BY n DESC, tag ASC", + ) + .map_err(|e| format!("准备标签语句失败: {e}"))?; + let rows = stmt + .query_map([], |row| { + Ok(NoteTagCount { + tag: row.get(0)?, + count: row.get(1)?, + }) + }) + .map_err(|e| format!("读取标签失败: {e}"))?; + Ok(rows.filter_map(Result::ok).collect()) + } + + /// 索引状态。 + pub fn stats(&self) -> Result { + let note_count: i64 = self + .conn + .query_row("SELECT COUNT(*) FROM notes", [], |row| row.get(0)) + .unwrap_or(0); + let tag_count: i64 = self + .conn + .query_row("SELECT COUNT(*) FROM tags", [], |row| row.get(0)) + .unwrap_or(0); + let file_count = WalkDir::new(&self.root) + .max_depth(library::MAX_DEPTH) + .into_iter() + .filter_map(Result::ok) + .filter(|e| { + e.file_type().is_file() + && !skip_path(&self.root, e.path()) + && e.file_name() + .to_string_lossy() + .to_ascii_lowercase() + .ends_with(".md") + }) + .count() as i64; + Ok(NoteIndexStats { + note_count, + file_count, + tag_count, + schema_version: SCHEMA_VERSION, + db_path: self.db_path.to_string_lossy().to_string(), + }) + } +} + +// ===== 辅助 ===== + +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) +} + +/// 该绝对路径是否应当排除在索引之外(点号目录 / 根级 assets)。 +fn skip_path(root: &Path, path: &Path) -> bool { + let rel = library::rel_string(root, path); + if rel.is_empty() { + return false; + } + let parts: Vec<&str> = rel.split('/').collect(); + // 任何一层是点号开头 → 排除(`.notes/` 索引自身、`.git/` 等) + if parts.iter().any(|p| p.starts_with('.')) { + return true; + } + // 根级 assets/ 是图片仓库,不是笔记(与 library::scan 的口径一致) + parts.first() == Some(&ASSETS_DIR) +} + +/// 为「短词回退 LIKE」路径生成命中片段。 +/// +/// FTS 的 `snippet()` 只服务于 FTS 查询;短于 3 字符的关键词走 LIKE(trigram 的 +/// 下限),那条路径没有片段可拿。若就此返回空片段,用户在结果列表里只看到一个标题、 +/// 不知道为什么会命中 —— 于是这里自己截一段上下文。 +/// +/// # 顺序 +/// +/// 优先在**正文**里找关键词(正文命中才是「检索」的价值所在),找不到再看标题。 +/// 命中处两侧各留 [`SNIPPET_CONTEXT`] 个**字符**(`chars` 而不是字节:中文笔记里按 +/// 字节截会切出乱码),并加上高亮定界符。 +fn make_snippet(title: &str, body: &str, keyword: &str) -> String { + const SNIPPET_CONTEXT: usize = 24; + if keyword.is_empty() { + return String::new(); + } + let Some((source, at)) = find_ci(body, keyword) + .map(|at| (body, at)) + .or_else(|| find_ci(title, keyword).map(|at| (title, at))) + else { + return String::new(); + }; + + // 归一化换行:片段是单行展示的,正文里的 `\n` 会让它断成两截 + let flat = source.replace(['\n', '\r'], " "); + let chars: Vec = flat.chars().collect(); + let keyword_chars = keyword.chars().count(); + let at_chars = source[..at].chars().count().min(chars.len()); + let start = at_chars.saturating_sub(SNIPPET_CONTEXT); + let end = (at_chars + keyword_chars + SNIPPET_CONTEXT).min(chars.len()); + + let mut out = String::new(); + if start > 0 { + out.push('…'); + } + out.extend(&chars[start..at_chars]); + out.push(HL_OPEN); + out.extend(&chars[at_chars..(at_chars + keyword_chars).min(chars.len())]); + out.push(HL_CLOSE); + out.extend(&chars[(at_chars + keyword_chars).min(chars.len())..end]); + if end < chars.len() { + out.push('…'); + } + out +} + +/// 大小写无关的字节查找(返回字节下标;找不到返回 None)。 +fn find_ci(haystack: &str, needle: &str) -> Option { + haystack + .to_lowercase() + .find(&needle.to_lowercase()) +} + +/// 把 FTS5 查询串安全地转成「多个短语的 AND」。 +/// FTS5 的 `MATCH` 有自己一套查询语法(`-` `*` `(` `^` `"` `:` `+` 都是操作符)。 +/// 用户输入是笔记标题里的普通词,直接塞进去轻则语义错、重则整个查询报语法错误。 +/// 做法与 `terminal/history.rs` 一致:每个词包成双引号短语、内部引号翻倍, +/// 词与词之间用空格(FTS5 的空格即 AND)。 +fn fts_query(keyword: &str) -> String { + keyword + .split_whitespace() + .map(|word| format!("\"{}\"", word.replace('"', "\"\""))) + .collect::>() + .join(" ") +} + +/// 把链接目标尽力解析成「库内相对路径」。 +/// +/// 解析不了就返回空串 —— 这不是失败,而是「未解析链接」,反链面板要靠它提示用户 +/// 目标不存在(`[[不存在的笔记]]` 在 Obsidian 里正是「新建入口」)。 +/// +/// `stems` 是「文件名(不含扩展名)→ 库内相对路径」的全库映射,专治 `[[笔记名]]` +/// 这种**不带目录**的写法:Obsidian 的 wikilink 语义是「全库按名查」,只按相对路径 +/// 猜会把 `[[周会]]` 解析到错的目录去(或干脆解析不到)。 +fn resolve_link( + src_rel: &str, + target: &str, + stems: &std::collections::HashMap, +) -> (String, String) { + let is_wiki = target.ends_with(".md") || !target.contains('.'); + if target.contains("://") { + return (String::new(), "url".to_string()); + } + let clean = target.split('#').next().unwrap_or("").trim(); + let kind = if is_wiki { "wiki" } else { "md" }; + if clean.is_empty() { + return (String::new(), kind.to_string()); + } + + // wikilink 优先按「全库文件名」解析(Obsidian 语义),命中即用 + if is_wiki && !clean.contains('/') { + if let Some(hit) = stems.get(&clean.to_ascii_lowercase()) { + return (hit.clone(), kind.to_string()); + } + } + + // 相对当前笔记所在目录解析 + let base = Path::new(src_rel).parent().unwrap_or(Path::new("")); + let joined = if clean.starts_with('/') { + clean.trim_start_matches('/').to_string() + } else { + let mut parts: Vec = Vec::new(); + for part in base.to_string_lossy().replace('\\', "/").split('/') { + if !part.is_empty() { + parts.push(part.to_string()); + } + } + for part in clean.replace('\\', "/").split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop(); + } + other => parts.push(other.to_string()), + } + } + parts.join("/") + }; + + let with_ext = if joined.to_ascii_lowercase().ends_with(".md") { + joined + } else { + format!("{joined}.md") + }; + (with_ext, kind.to_string()) +} + +// ===== 测试 ===== + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn front_matter_split_and_parse() { + let content = "---\nid: abc\ntitle: 会议纪要\ntags: [工作, 周会]\n---\n\n# 会议纪要\n\n正文\n"; + let meta = parse_note("2026/09/meeting.md", content); + assert_eq!(meta.id, "abc"); + assert_eq!(meta.title, "会议纪要"); + assert_eq!(meta.tags, vec!["工作", "周会"]); + assert!(meta.body.contains("正文")); + assert!(!meta.body.contains("id: abc")); + } + + #[test] + fn unterminated_front_matter_is_body() { + // 未闭合的 `---` 必须当正文:宁可标题退化,也不能让整篇内容从索引里消失 + let content = "---\n这不是元数据\n\n# 标题\n"; + let meta = parse_note("a.md", content); + assert!(meta.body.contains("这不是元数据")); + assert_eq!(meta.title, "标题"); + } + + #[test] + fn title_falls_back_to_h1_then_filename() { + let meta = parse_note("dir/无元数据.md", "## 二级\n\n# 一级标题\n"); + assert_eq!(meta.title, "一级标题"); + let meta = parse_note("dir/只有文件名.md", "普通正文\n"); + assert_eq!(meta.title, "只有文件名"); + } + + #[test] + fn tags_accept_three_shapes() { + let list = parse_note("a.md", "---\ntags: [a, b]\n---\nx"); + assert_eq!(list.tags, vec!["a", "b"]); + let csv = parse_note("a.md", "---\ntags: a, b\n---\nx"); + assert_eq!(csv.tags, vec!["a", "b"]); + let one = parse_note("a.md", "---\ntag: 单个\n---\nx"); + assert_eq!(one.tags, vec!["单个"]); + } + + #[test] + fn links_parsed_from_both_syntaxes() { + let meta = parse_note("notes/a.md", "见 [[另一篇]] 与 [名](notes/b.md#小节)\n"); + assert!(meta.links.contains(&"另一篇".to_string())); + assert!(meta.links.contains(&"notes/b.md#小节".to_string())); + } + + #[test] + fn resolve_link_uses_source_dir() { + let stems = std::collections::HashMap::new(); + let (dst, kind) = resolve_link("notes/2026/a.md", "b", &stems); + assert_eq!(dst, "notes/2026/b.md"); + assert_eq!(kind, "wiki"); + let (dst, _) = resolve_link("notes/a.md", "../assets/x.png", &stems); + assert_eq!(dst, "assets/x.png.md"); + let (dst, kind) = resolve_link("a.md", "https://example.com/x", &stems); + assert!(dst.is_empty()); + assert_eq!(kind, "url"); + } + + #[test] + fn resolve_link_prefers_library_wide_stem() { + // Obsidian 的 wikilink 语义是全库按名查:`[[周会]]` 应当落到真实所在目录, + // 而不是被硬按「相对当前目录」猜错位置 + let mut stems = std::collections::HashMap::new(); + stems.insert("周会".to_string(), "archive/2025/周会.md".to_string()); + let (dst, kind) = resolve_link("notes/today.md", "周会", &stems); + assert_eq!(dst, "archive/2025/周会.md"); + assert_eq!(kind, "wiki"); + } + + #[test] + fn fts_query_neutralizes_operators() { + // 每个词都被包成短语,`-` `*` 这类操作符不会再被解释 + assert_eq!(fts_query("a-b"), "\"a-b\""); + assert_eq!(fts_query("会议 纪要"), "\"会议\" \"纪要\""); + assert_eq!(fts_query("he said \"hi\""), "\"he\" \"said\" \"\"\"hi\"\"\""); + } + + /// 端到端:真的建一个临时库,落盘 `.md`,同步索引,然后检索。 + /// + /// 覆盖的是「单测覆盖不到的那一层」:建表语句、触发器、FTS5 MATCH 语法、 + /// trigram 中文子串匹配、标签 JOIN —— 这些只有真跑一次 SQLite 才能确认。 + #[test] + fn index_roundtrip_search_tags_and_rebuild() { + let root = std::env::temp_dir().join(format!( + "thing-notes-index-test-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("notes")).unwrap(); + std::fs::create_dir_all(root.join("assets")).unwrap(); + + std::fs::write( + root.join("notes/会议纪要.md"), + "---\ntitle: 周会纪要\ntags: [工作, 周会]\n---\n\n本周讨论了三件事,其中一件是检索。\n", + ) + .unwrap(); + std::fs::write( + root.join("notes/随手记.md"), + "# 随手记\n\n买牛奶。参见 [[会议纪要]] 与 [外链](https://example.com)。\n", + ) + .unwrap(); + // 非 .md 与点号目录都不该被索引 + std::fs::write(root.join("notes/notes.txt"), "不该被索引").unwrap(); + + // 先打开索引(顺带创建 `.notes/` 目录),再往里塞一个「不该被索引」的 .md + let mut index = NotesIndex::open(&root).unwrap(); + std::fs::write(root.join(".notes/ignored.md"), "也不该被索引").unwrap(); + + let report = index.sync().unwrap(); + assert_eq!(report.indexed, 2, "只应索引两篇 .md"); + assert_eq!(report.removed, 0); + + // 第二次同步:没有任何变化 → 全部跳过 + let again = index.sync().unwrap(); + assert_eq!(again.indexed, 0); + assert_eq!(again.skipped, 2); + + // 中文子串检索(trigram 的价值所在:「周会」要能命中「周会纪要」) + let page = index + .search(NoteSearchQuery { + keyword: "周会".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(page.total, 1, "{:?}", page.items); + assert_eq!(page.items[0].title, "周会纪要"); + // 2 字符关键词在 trigram 下**不命中 FTS**(3 字符下限),走 LIKE 回退; + // 片段由 Rust 侧 make_snippet 生成,同样带高亮定界符 + assert!( + page.items[0].snippet.contains(HL_OPEN), + "短词命中也应有高亮片段: {:?}", + page.items[0].snippet + ); + + // 3 字符关键词走 FTS,片段由 snippet() 生成 + let fts_page = index + .search(NoteSearchQuery { + keyword: "周会纪".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(fts_page.total, 1); + assert!( + fts_page.items[0].snippet.contains(HL_OPEN), + "FTS 命中的片段应带高亮: {:?}", + fts_page.items[0].snippet + ); + + // 正文命中(关键词只出现在 body) + let body_hit = index + .search(NoteSearchQuery { + keyword: "检索".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(body_hit.total, 1); + + // 短词回退 LIKE(trigram 对 <3 字符静默返回空,必须走 LIKE) + let short = index + .search(NoteSearchQuery { + keyword: "牛奶".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(short.total, 1, "两字关键词应能命中"); + assert!( + short.items[0].snippet.contains(HL_OPEN) && short.items[0].snippet.contains("牛奶"), + "短词片段应包含关键词并带高亮: {:?}", + short.items[0].snippet + ); + + // 标签筛选 + let tagged = index + .search(NoteSearchQuery { + tag: "工作".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(tagged.total, 1); + let tag_names: Vec = index.tags().unwrap().into_iter().map(|t| t.tag).collect(); + assert!(tag_names.contains(&"工作".to_string()), "{tag_names:?}"); + assert!(tag_names.contains(&"周会".to_string()), "{tag_names:?}"); + + // wikilink 解析:[[会议纪要]] 应解析到真实路径 + let dst: String = index + .conn + .query_row( + "SELECT dst_path FROM links WHERE src_path LIKE '%随手记%' AND kind = 'wiki'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(dst, "notes/会议纪要.md"); + + // 删除文件后同步 → 索引里也应消失(含标签清理) + std::fs::remove_file(root.join("notes/随手记.md")).unwrap(); + let after_delete = index.sync().unwrap(); + assert_eq!(after_delete.removed, 1); + assert_eq!(index.stats().unwrap().note_count, 1); + + // 全量重建:索引数应与文件数一致 + let rebuilt = index.rebuild().unwrap(); + assert_eq!(rebuilt.indexed, 1); + let stats = index.stats().unwrap(); + assert_eq!(stats.note_count, 1); + assert_eq!(stats.file_count, 1); + + let _ = std::fs::remove_dir_all(&root); + } + + /// 诊断用的探针已删除:它验证的结论是「trigram 下 2 字符关键词不命中 FTS」, + /// 该结论现已固化到 [`make_snippet`] 的存在理由里(短词回退 LIKE + 自建片段)。 + + /// front-matter 里的 `id` / `created` 也要进索引(P2 同步靠它做稳定标识)。 + #[test] + fn front_matter_id_and_dates_are_indexed() { + let root = std::env::temp_dir().join(format!( + "thing-notes-index-fm-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("notes")).unwrap(); + std::fs::write( + root.join("notes/a.md"), + "---\nid: 01J9Z8\ntitle: 标题\ncreated: 2026-09-30T10:00:00+08:00\nupdated: 2026-09-30T11:20:00+08:00\ntags: 单独\n---\n\n正文\n", + ) + .unwrap(); + + let mut index = NotesIndex::open(&root).unwrap(); + index.sync().unwrap(); + let page = index + .search(NoteSearchQuery { + keyword: "标题".to_string(), + ..Default::default() + }) + .unwrap(); + assert_eq!(page.items.len(), 1); + assert_eq!(page.items[0].id, "01J9Z8"); + assert_eq!(page.items[0].tags, vec!["单独"]); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src-tauri/src/notes/index_service.rs b/src-tauri/src/notes/index_service.rs new file mode 100644 index 0000000..1a33ad8 --- /dev/null +++ b/src-tauri/src/notes/index_service.rs @@ -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 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>), + /// 全量重建 + Rebuild(Sender>), + /// 同步单个文件(监听器投递;文件不存在则从索引移除) + SyncPath(PathBuf, bool), + /// 全文检索 + Search(NoteSearchQuery, Sender>), + /// 快速打开清单 + List(i64, Sender, String>>), + /// 标签清单 + Tags(Sender, String>>), + /// 一篇笔记的出链 / 入链 + Backlinks(String, Sender>), + /// 全库链接图 + LinkGraph(Sender, String>>), + /// 索引状态 + Stats(Sender>), + /// 重建监听器(库根变化后) + Retarget(PathBuf, Sender>), +} + +/// 索引服务的句柄(命令层只拿到这个)。 +pub struct IndexService { + tx: Sender, + /// 自我保存抑制的时间点(`notes_write_*` 写入) + last_write: Mutex>, +} + +static SERVICE: std::sync::OnceLock = 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::(); + 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 { + 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 { + 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 { + 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, 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, 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 { + 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 { + 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, 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, handle_tx: Sender) { + let mut index: Option = None; + let mut watcher: Option = None; + let mut watched_root: Option = None; + let mut root: Option = 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( + app: &AppHandle, + index: &mut Option, + root: &mut Option, + run: impl FnOnce(&mut NotesIndex) -> Result, +) -> Result { + 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, 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, + watched_root: &mut Option, + root: &Path, + tx: &Sender, +) { + 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, + watched_root: &mut Option, + root: &Path, + tx: &Sender, +) -> 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| { + 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 { + 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 { + let doc = files::read_file(path, max_mb)?; + files::authorize(Path::new(&doc.path)); + Ok(doc) +} diff --git a/src-tauri/src/notes/library.rs b/src-tauri/src/notes/library.rs new file mode 100644 index 0000000..b3303ae --- /dev/null +++ b/src-tauri/src/notes/library.rs @@ -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 { + 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 { + 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, 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, 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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(()) +} \ No newline at end of file diff --git a/src-tauri/src/notes/mod.rs b/src-tauri/src/notes/mod.rs new file mode 100644 index 0000000..ede3831 --- /dev/null +++ b/src-tauri/src/notes/mod.rs @@ -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>, +} + +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::(&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(()) + } +} \ No newline at end of file diff --git a/src-tauri/src/notes/templates.rs b/src-tauri/src/notes/templates.rs new file mode 100644 index 0000000..0696468 --- /dev/null +++ b/src-tauri/src/notes/templates.rs @@ -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 { + let mut out: Vec = Vec::new(); + + // 用户模板:`{库根}/templates/*.md` + let dir = root.join("templates"); + if dir.is_dir() { + let mut files: Vec = 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 { + 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, 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 { + id.strip_prefix("user:") + .map(|name| format!("templates/{name}.md")) +} + +/// 校验模板名(新建模板时用)。 +pub fn validate_name(name: &str) -> Result { + 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); + } +} diff --git a/src-tauri/src/notes/types.rs b/src-tauri/src/notes/types.rs new file mode 100644 index 0000000..a51e701 --- /dev/null +++ b/src-tauri/src/notes/types.rs @@ -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, +} + +/// 导入结果。 +#[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, +} + +/// 笔记 / 编辑器设置根结构。 +/// +/// 字段取值必须与前端 `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, + /// 编辑器配色方案 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, +} \ No newline at end of file diff --git a/src-tauri/src/notes/webdav/client.rs b/src-tauri/src/notes/webdav/client.rs new file mode 100644 index 0000000..5fbd2d1 --- /dev/null +++ b/src-tauri/src/notes/webdav/client.rs @@ -0,0 +1,797 @@ +//! WebDAV 客户端:`PROPFIND` / `MKCOL` / `GET` / `PUT` / `DELETE` / `MOVE`。 +//! +//! # 定位:备份 / 同步目标,不是工作区 +//! +//! 这条边界是产品级的(规划 §3.6 已确认):笔记的真相永远在本地文件系统, +//! WebDAV 只接收「本地 → 远端」的推送与「远端 → 本地」的拉取,**不做远端直连读写** +//! (不把远端当工作目录)。这样即使远端服务商限流、掉线、或者把文件改坏,本地 +//! 那份始终是完整可用的。 +//! +//! # XML 解析为什么用 quick-xml +//! +//! `PROPFIND` 的响应是 `` 里套一堆 ``,命名空间前缀 +//! 由服务端随意指定(`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 = 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 = 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>, +} + +impl WebdavClient { + pub fn new(config: WebdavConfig) -> Result { + 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>, + content_type: Option<&str>, + headers: &[(&str, &str)], + ) -> Result { + 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>, String> { + let url = self.dir_url(rel); + let body = br#" + + +"# + .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, String> { + self.config.validate()?; + let mut created: Vec = 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, String> { + let mut out: Vec = Vec::new(); + let mut queue: Vec = 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 { + let mut out: Vec = 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, 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) -> 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, String> { + let mut reader = Reader::from_str(xml); + reader.config_mut().trim_text(true); + + let mut entries: Vec = 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)) => { + // `` 是「这是目录」的标志 + 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`(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 { + 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 { + 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#" + + + /dav/root/ + + + + https://host/dav/root/notes/meeting.md + + + 1234 + Wed, 21 Oct 2015 07:28:00 GMT + + + + /dav/root/notes/%E4%B8%AD%E6%96%87.md + + +"#; + + 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#" + /dav/root/sub + + "#; + 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()); + } +} diff --git a/src-tauri/src/notes/webdav/mod.rs b/src-tauri/src/notes/webdav/mod.rs new file mode 100644 index 0000000..7add611 --- /dev/null +++ b/src-tauri/src/notes/webdav/mod.rs @@ -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, + /// 人话结论(失败时是原因) + pub message: String, +} + +/// 由设置构造客户端(密码从 keyring 取,**不落盘**)。 +/// +/// 密码走系统凭据管理器而不是 `settings.json`:设置文件是明文 JSON,用户可能把库 +/// 连同设置一起放到同步目录里(那就等于把密码公开了)。keyring 的键是 +/// [`KEYRING_PASSWORD`],服务名沿用项目统一的 `"Thing"`。 +pub fn client_from(settings: &WebdavSettings) -> Result { + 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 { + 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} 个文件"), + }) +} diff --git a/src-tauri/src/notes/webdav/sync.rs b/src-tauri/src/notes/webdav/sync.rs new file mode 100644 index 0000000..f42ac68 --- /dev/null +++ b/src-tauri/src/notes/webdav/sync.rs @@ -0,0 +1,1092 @@ +//! 同步引擎:清单比对、冲突策略、排除规则、快照备份。 +//! +//! # 状态存在哪、为什么不是「靠时间戳猜」 +//! +//! `{库根}/.notes/sync.json` 记录**上次成功同步时**每个文件的两侧指纹: +//! 本地内容的 hash + 本地 mtime,以及远端的 mtime。有了基线才能回答「谁改的」: +//! +//! - 本地 hash ≠ 基线 hash → 本地改了; +//! - 远端 mtime ≠ 基线远端 mtime → 远端改了; +//! - 两侧都改 → **冲突**(这时才需要按策略裁决)。 +//! +//! 没有基线就只能比 mtime,而 mtime 在不同机器/时区的时钟偏差下必然误判 —— +//! 「本地比远端新」在两台机器上都可以成立。基线是为了把「改动」这件事变成 +//! **可证伪**的判断(内容 hash),而不是猜。 +//! +//! # 同步方向 +//! +//! - `bidirectional`:双向(默认)。冲突按 [`ConflictPolicy`] 裁决。 +//! - `upload`:只上传(本地覆盖远端),等价于「备份」。 +//! - `download`:只下载(远端覆盖本地),用于「换机器恢复」。 +//! +//! 单向模式下**不做冲突判定**:用户的意图已经很明确,判定只会碍事。 +//! +//! # 删除的语义(保守优先) +//! +//! 一侧文件消失时,只有在**另一侧没有被改动**的情况下才跟着删;否则宁可 +//! 「保留孤儿文件」也不删 —— 数据丢失的代价远高于留一个多余文件。 + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +use serde::{Deserialize, Serialize}; +use specta::Type; +use tauri::{AppHandle, Emitter}; + +use super::client::{should_skip, WebdavClient}; +use crate::constants::events; +use crate::notes::index::content_hash; +use crate::notes::library; +use crate::notes::types::{ConflictPolicy, SyncDirection, WebdavSettings}; + +/// 同步状态文件名(位于库根 `.notes/` 下,永不参与同步)。 +const SYNC_STATE_FILE: &str = "sync.json"; +/// 状态文件结构版本。 +const SYNC_STATE_VERSION: u32 = 1; + +/// 单个文件的基线(上次同步时的两侧指纹)。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct BaselineEntry { + /// 本地内容 hash(SHA-256 前 16 字节十六进制) + pub hash: String, + /// 本地 mtime(Unix 毫秒) + pub local_mtime: u64, + /// 远端 mtime(Unix 毫秒) + pub remote_mtime: u64, +} + +/// 同步状态(落盘 `sync.json`)。 +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct SyncState { + pub version: u32, + /// 上次同步完成时间(Unix 毫秒) + pub last_sync: u64, + /// 上次同步的远端根(远端根变了,基线全部作废) + pub remote_root: String, + /// 相对路径 → 基线 + pub entries: BTreeMap, +} + +impl SyncState { + /// 从库根读取状态(缺失/损坏都回退空状态 —— 最坏结果是「下次同步当作首次」)。 + pub fn load(root: &Path, remote_root: &str) -> Self { + let path = root.join(".notes").join(SYNC_STATE_FILE); + let mut state: SyncState = std::fs::read_to_string(&path) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default(); + if state.version != SYNC_STATE_VERSION || state.remote_root != remote_root { + // 远端根换了:远端那些 mtime 与新根无关,留着只会误判成「远端改过」 + state = SyncState { + version: SYNC_STATE_VERSION, + remote_root: remote_root.to_string(), + ..Default::default() + }; + } + state + } + + /// 落盘。 + pub fn save(&self, root: &Path) -> Result<(), String> { + let dir = root.join(".notes"); + std::fs::create_dir_all(&dir).map_err(|e| format!("创建索引目录失败: {e}"))?; + let text = serde_json::to_string_pretty(self).map_err(|e| format!("序列化同步状态失败: {e}"))?; + std::fs::write(dir.join(SYNC_STATE_FILE), text).map_err(|e| format!("写入同步状态失败: {e}")) + } +} + +/// 本地文件快照。 +#[derive(Debug, Clone)] +pub struct LocalFile { + pub hash: String, + pub mtime: u64, + pub size: u64, +} + +/// 待执行的同步动作。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum SyncActionKind { + /// 本地 → 远端(新增或覆盖) + Upload, + /// 远端 → 本地(新增或覆盖) + Download, + /// 删除远端 + RemoteDelete, + /// 删除本地 + LocalDelete, + /// 改名 / 移动(本地 `rename`,远端 `MOVE`) + /// + /// 只在「内容完全一致、路径变了」时产生。它不只是省流量:**保留文件的历史** + /// 只在路径不变时成立,而「删除 + 新建」在用户的同步盘上表现为两个事件, + /// 用 MOVE/rename 才能让对端看到「同一篇被改名了」。 + Move, + /// 冲突:按策略保留一侧,另一侧写冲突副本 + ConflictKeepLocal, + ConflictKeepRemote, + /// 冲突:两侧都留(远端那份 `MOVE` 成冲突副本,本地那份留在原路径) + ConflictKeepBoth, + /// 跳过(无需处理) + Skip, +} + +impl SyncActionKind { + /// 稳定字符串(前端与事件用;`Type` 派生对 enum 生成的是联合类型,这里额外给出字符串便于日志)。 + pub fn as_str(self) -> &'static str { + match self { + SyncActionKind::Upload => "upload", + SyncActionKind::Download => "download", + SyncActionKind::RemoteDelete => "remoteDelete", + SyncActionKind::LocalDelete => "localDelete", + SyncActionKind::Move => "move", + SyncActionKind::ConflictKeepLocal => "conflictKeepLocal", + SyncActionKind::ConflictKeepRemote => "conflictKeepRemote", + SyncActionKind::ConflictKeepBoth => "conflictKeepBoth", + SyncActionKind::Skip => "skip", + } + } +} + +/// 一条同步动作。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyncAction { + pub kind: SyncActionKind, + /// 相对库根的路径 + pub rel_path: String, + /// 冲突时另一侧改用的路径(仅 `ConflictKeepBoth` 有值) + pub alt_path: Option, + /// 传输字节数(上传/下载用;其余为 0) + pub bytes: u64, +} + +/// 同步计划(纯计算结果,不触网)—— 它的可测性是本文件存在的理由之一。 +#[derive(Debug, Clone, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyncPlan { + pub actions: Vec, + /// 冲突数(前端要单独提示) + pub conflicts: u32, + pub uploads: u32, + pub downloads: u32, + pub deletions: u32, + /// 改名 / 移动条数 + pub moves: u32, +} + +/// 把「本地 + 远端 + 基线」三方比对成一张计划表。**纯函数**,可单测。 +/// +/// 名字不叫 `plan`:测试里 `let plan = plan(...)` 会让函数名被自己的返回值遮蔽, +/// 第二个测试开始就变成「调用一个 `SyncPlan`」,编译期报 E0618 而原因不直观。 +/// +/// `local` 与 `remote` 都只含两端**实际存在**的文件。 +pub fn build_sync_plan( + baseline: &BTreeMap, + local: &BTreeMap, + remote: &BTreeMap, + direction: SyncDirection, + policy: ConflictPolicy, +) -> SyncPlan { + let mut actions: Vec = Vec::new(); + let mut conflicts = 0u32; + + // 全集:三方任何一个出现过的路径 + let mut all: BTreeSet<&String> = BTreeSet::new(); + all.extend(local.keys()); + all.extend(remote.keys()); + all.extend(baseline.keys()); + + // 「本地改名」识别:基线里被删掉的内容,出现在一个新的本地文件里 —— 那多半是 + // 用户把 `a.md` 改成了 `b.md`。识别出来后用 MOVE/rename 代替「远端删 + 重新上传」, + // 除了省一次全量上传,也让远端看到的是「改名」而不是「删了又建」。 + let rename_map = detect_local_renames(baseline, local, remote); + let mut renamed_old: BTreeSet = BTreeSet::new(); + + for rel in all { + let base = baseline.get(rel); + let local_file = local.get(rel); + let remote_time = remote.get(rel).copied(); + + // 被识别成「改名来源」的旧路径:不在这里处理,由新路径那条动作一并搬走 + if renamed_old.contains(rel) { + continue; + } + if let Some((old_path, _)) = rename_map.get(rel) { + if local_file.is_some() { + renamed_old.insert(old_path.clone()); + actions.push(action(SyncActionKind::Move, old_path, Some(rel.clone()), 0)); + continue; + } + } + + // 单向模式:不做冲突判定(用户意图明确) + if direction == SyncDirection::Upload { + if let Some(file) = local_file { + let same = base + .map(|b| b.hash == file.hash && b.remote_mtime == remote_time.unwrap_or(0)) + .unwrap_or(false); + if !same { + actions.push(action(SyncActionKind::Upload, rel, None, file.size)); + } + } else if base.is_some() && remote_time.is_some() { + actions.push(action(SyncActionKind::RemoteDelete, rel, None, 0)); + } + continue; + } + if direction == SyncDirection::Download { + if let Some(time) = remote_time { + let same = base + .map(|b| b.remote_mtime == time && local_file.is_some()) + .unwrap_or(false); + if !same { + actions.push(action( + SyncActionKind::Download, + rel, + None, + local_file.map(|f| f.size).unwrap_or(0), + )); + } + } else if base.is_some() && local_file.is_some() { + actions.push(action(SyncActionKind::LocalDelete, rel, None, 0)); + } + continue; + } + + // ===== 双向 ===== + match (local_file, remote_time, base) { + // 两侧都在 + (Some(file), Some(time), base) => { + let local_changed = base.map(|b| b.hash != file.hash).unwrap_or(true); + let remote_changed = base.map(|b| b.remote_mtime != time).unwrap_or(true); + if !local_changed && !remote_changed { + continue; // 一致 + } + if local_changed && !remote_changed { + actions.push(action(SyncActionKind::Upload, rel, None, file.size)); + } else if !local_changed && remote_changed { + actions.push(action(SyncActionKind::Download, rel, None, file.size)); + } else { + // 冲突 + conflicts += 1; + match policy { + ConflictPolicy::Newer => { + // 本地 mtime 与远端 mtime 比大小;无法判定时保守选本地 + // (本地是用户正在编辑的那份,且它一定完整可读) + let remote_is_newer = time > file.mtime && time - file.mtime > 2000; + if remote_is_newer { + actions.push(action(SyncActionKind::ConflictKeepRemote, rel, None, file.size)); + } else { + actions.push(action(SyncActionKind::ConflictKeepLocal, rel, None, file.size)); + } + } + ConflictPolicy::LocalWins => { + actions.push(action(SyncActionKind::ConflictKeepLocal, rel, None, file.size)) + } + ConflictPolicy::RemoteWins => { + actions.push(action(SyncActionKind::ConflictKeepRemote, rel, None, file.size)) + } + ConflictPolicy::KeepBoth => { + let alt = conflict_path(rel, local, remote); + // 远端那份 `MOVE` 成冲突副本(原路径留给本地那份,随后上传) + actions.push(action(SyncActionKind::ConflictKeepBoth, rel, Some(alt), file.size)); + } + } + } + } + // 仅本地有 + (Some(file), None, base) => { + if base.is_none() { + // 本地新增 → 上传 + actions.push(action(SyncActionKind::Upload, rel, None, file.size)); + } else { + // 基线有、远端没有 → 远端删过。仅当本地也没改时才跟着删 + let local_changed = base.map(|b| b.hash != file.hash).unwrap_or(true); + if local_changed { + actions.push(action(SyncActionKind::Upload, rel, None, file.size)); + } else { + actions.push(action(SyncActionKind::LocalDelete, rel, None, 0)); + } + } + } + // 仅远端有 + (None, Some(time), base) => { + if base.is_none() { + actions.push(action(SyncActionKind::Download, rel, None, 0)); + } else { + let remote_changed = base.map(|b| b.remote_mtime != time).unwrap_or(true); + if remote_changed { + actions.push(action(SyncActionKind::Download, rel, None, 0)); + } else { + actions.push(action(SyncActionKind::RemoteDelete, rel, None, 0)); + } + } + } + // 两侧都没有、只有基线 → 两边都删了 → 清掉基线即可 + (None, None, _) => {} + } + } + + let uploads = actions + .iter() + .filter(|a| { + matches!( + a.kind, + SyncActionKind::Upload + | SyncActionKind::ConflictKeepLocal + | SyncActionKind::ConflictKeepBoth + ) + }) + .count() as u32; + let downloads = actions + .iter() + .filter(|a| { + matches!( + a.kind, + SyncActionKind::Download | SyncActionKind::ConflictKeepRemote + ) + }) + .count() as u32; + let deletions = actions + .iter() + .filter(|a| { + matches!( + a.kind, + SyncActionKind::RemoteDelete | SyncActionKind::LocalDelete + ) + }) + .count() as u32; + let moves = actions + .iter() + .filter(|a| a.kind == SyncActionKind::Move) + .count() as u32; + + SyncPlan { + actions, + conflicts, + uploads, + downloads, + deletions, + moves, + } +} + +fn action(kind: SyncActionKind, rel: &str, alt: Option, bytes: u64) -> SyncAction { + SyncAction { + kind, + rel_path: rel.to_string(), + alt_path: alt, + bytes, + } +} + +/// 识别「本地改名」:返回 `新路径 → (旧路径, hash)`。 +/// +/// 判据严格三项同时成立,避免把「删一篇 + 新建一篇同内容」误判成改名: +/// 1. 旧路径在上次基线里存在,现在**本地没有**(本地那份不见了); +/// 2. 新路径本地有、基线里没有(新出现的文件); +/// 3. 两者内容 hash 相同(`local` 里带的就是内容 hash)。 +/// +/// 第 1 条刻意**不要求远端也没有**:用户改名时通常还没来得及同步,远端仍然是旧名字 —— +/// 那恰恰是这个识别最该生效的时刻。真正防误判的是第 3 条(内容 hash 一致)。 +fn detect_local_renames( + baseline: &BTreeMap, + local: &BTreeMap, + _remote: &BTreeMap, +) -> BTreeMap { + // 待认领的「本地已消失的旧文件」:hash → 旧路径 + let mut orphans: BTreeMap<&str, &str> = BTreeMap::new(); + for (path, base) in baseline { + if local.contains_key(path) { + continue; // 本地还在,不可能是改名来源 + } + // 「本地删了、远端还在」与「两端都没了」都算候选:后者对应「用户先删了旧名字、 + // 又用新名字新建了同样内容」;前者是标准的改名场景。 + // 用 `or_insert` 而不是 `insert`:多份内容相同的旧文件只留第一个作候选, + // 否则它们会互相抢同一个新名字(那是重复内容,判给谁都一样) + orphans.entry(base.hash.as_str()).or_insert(path.as_str()); + } + if orphans.is_empty() { + return BTreeMap::new(); + } + + let mut out: BTreeMap = BTreeMap::new(); + let mut claimed: BTreeSet<&str> = BTreeSet::new(); + for (path, file) in local { + if baseline.contains_key(path) { + continue; // 不是新文件 + } + if let Some(old) = orphans.get(file.hash.as_str()) { + if claimed.contains(old) { + continue; // 一份旧内容只认领一个新名字 + } + claimed.insert(old); + out.insert(path.clone(), (old.to_string(), file.hash.clone())); + } + } + out +} + +/// 给冲突副本找一个不冲突的名字:`笔记.sync-conflict-20260930-1530.md`。 +fn conflict_path( + rel: &str, + local: &BTreeMap, + remote: &BTreeMap, +) -> String { + let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string(); + let path = Path::new(rel); + let stem = path + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "note".to_string()); + let ext = path + .extension() + .map(|s| format!(".{}", s.to_string_lossy())) + .unwrap_or_default(); + let dir = match rel.rfind('/') { + Some(index) => format!("{}/", &rel[..index]), + None => String::new(), + }; + let mut candidate = format!("{dir}{stem}.sync-conflict-{stamp}{ext}"); + let mut index = 1; + while local.contains_key(&candidate) || remote.contains_key(&candidate) { + candidate = format!("{dir}{stem}.sync-conflict-{stamp}-{index}{ext}"); + index += 1; + if index > 99 { + break; + } + } + candidate +} + +/// 扫描本地库,算出每个文件的内容 hash / mtime / size。 +/// +/// 只收 `.md`:与索引口径一致(附件暂不参与同步,见规划 §3.6 的取舍 —— +/// 图片往往几十 MB,把它们塞进每一轮同步会让「同步」变成一个不敢点的按钮)。 +pub fn scan_local(root: &Path) -> Result, String> { + let mut out = BTreeMap::new(); + 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() || should_skip(&rel) { + continue; + } + if !rel.to_ascii_lowercase().ends_with(".md") { + continue; + } + let Ok(bytes) = std::fs::read(entry.path()) else { + continue; + }; + let meta = entry.metadata().ok(); + out.insert( + rel, + LocalFile { + hash: content_hash(&bytes), + mtime: meta + .as_ref() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0), + size: bytes.len() as u64, + }, + ); + } + Ok(out) +} + +// ===== 执行 ===== + +/// 一次同步的统计结果。 +#[derive(Debug, Clone, Default, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyncReport { + pub uploaded: u32, + pub downloaded: u32, + /// 改名 / 移动的条数 + pub moved: u32, + pub deleted_remote: u32, + pub deleted_local: u32, + pub conflicts: u32, + pub failed: u32, + /// 失败明细(最多 [`MAX_FAILURES`] 条,避免把 IPCE 撑爆) + pub failures: Vec, + /// 同步用时(毫秒) + pub elapsed_ms: u64, +} + +/// 失败明细上限。一次同步失败几百条时,前端只需要知道「有 N 条失败 + 前几条为什么」。 +const MAX_FAILURES: usize = 20; + +/// 同步执行器:按计划触网,逐条汇报进度。 +pub struct SyncRunner<'a> { + client: &'a WebdavClient, + root: PathBuf, + app: &'a AppHandle, + total: usize, +} + +impl<'a> SyncRunner<'a> { + pub fn new(client: &'a WebdavClient, root: &Path, app: &'a AppHandle, total: usize) -> Self { + Self { + client, + root: root.to_path_buf(), + app, + total, + } + } + + /// 发进度事件(前端据此画进度条)。 + fn progress(&self, done: usize, current: &str, kind: &str) { + let payload = crate::notes::types::SyncProgress { + done: done as u32, + total: self.total as u32, + current: current.to_string(), + kind: kind.to_string(), + message: String::new(), + }; + let _ = self.app.emit(events::NOTES_SYNC_PROGRESS, payload); + } + + /// 执行整个计划。 + pub fn run( + &self, + plan: &SyncPlan, + state: &mut SyncState, + remote: &BTreeMap, + ) -> SyncReport { + let started = std::time::Instant::now(); + let mut report = SyncReport { + conflicts: plan.conflicts, + ..Default::default() + }; + let mut done = 0usize; + + for item in &plan.actions { + done += 1; + self.progress(done, &item.rel_path, item.kind.as_str()); + let result = self.apply(item, state, remote); + if let Err(e) = result { + report.failed += 1; + if report.failures.len() < MAX_FAILURES { + report.failures.push(format!("{}:{e}", item.rel_path)); + } + crate::logger::log_warn("notes", &format!("同步 {} 失败: {e}", item.rel_path)); + continue; + } + match item.kind { + SyncActionKind::Upload + | SyncActionKind::ConflictKeepLocal + | SyncActionKind::ConflictKeepBoth => report.uploaded += 1, + SyncActionKind::Download | SyncActionKind::ConflictKeepRemote => { + report.downloaded += 1 + } + SyncActionKind::Move => report.moved += 1, + SyncActionKind::RemoteDelete => report.deleted_remote += 1, + SyncActionKind::LocalDelete => report.deleted_local += 1, + SyncActionKind::Skip => {} + } + } + + report.elapsed_ms = started.elapsed().as_millis() as u64; + report + } + + /// 执行单条动作,并更新基线。 + fn apply( + &self, + item: &SyncAction, + state: &mut SyncState, + remote: &BTreeMap, + ) -> Result<(), String> { + let local_path = library::safe_join(&self.root, &item.rel_path)?; + + match item.kind { + SyncActionKind::Upload | SyncActionKind::ConflictKeepLocal => { + let bytes = std::fs::read(&local_path).map_err(|e| format!("读取本地文件失败: {e}"))?; + self.client.put(&item.rel_path, bytes.clone())?; + self.record(state, &item.rel_path, &bytes, remote.get(&item.rel_path).copied()); + } + SyncActionKind::ConflictKeepBoth => { + // 两侧都留:先把**远端那份移到冲突副本名**(`MOVE` 保住它的历史), + // 再把本地那份上传到原路径。这样「原路径」在两端都等于本地的版本, + // 而远端副本带着远端那份的完整历史,谁也没被覆盖掉。 + let alt = item + .alt_path + .clone() + .ok_or_else(|| "冲突副本路径缺失".to_string())?; + self.client.move_to(&item.rel_path, &alt)?; + let bytes = std::fs::read(&local_path).map_err(|e| format!("读取本地文件失败: {e}"))?; + self.client.put(&item.rel_path, bytes.clone())?; + self.record(state, &item.rel_path, &bytes, remote.get(&item.rel_path).copied()); + // 远端副本的内容与远端原文件相同,但我们手上没有它的字节,无法算 hash; + // 基线里不记它 —— 下一轮它会作为一个「仅远端有」的新文件被下载到本地 + state.entries.remove(&alt); + } + SyncActionKind::Download | SyncActionKind::ConflictKeepRemote => { + let bytes = self.client.get(&item.rel_path)?; + if let Some(parent) = local_path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?; + } + std::fs::write(&local_path, &bytes).map_err(|e| format!("写入本地文件失败: {e}"))?; + self.record( + state, + &item.rel_path, + &bytes, + remote.get(&item.rel_path).copied(), + ); + } + SyncActionKind::RemoteDelete => { + self.client.delete(&item.rel_path)?; + state.entries.remove(&item.rel_path); + } + SyncActionKind::LocalDelete => { + if local_path.is_file() { + std::fs::remove_file(&local_path).map_err(|e| format!("删除本地文件失败: {e}"))?; + } + state.entries.remove(&item.rel_path); + } + SyncActionKind::Move => { + // 本地改名 + 远端 `MOVE`(只搬路径,不重传内容) + let target = item + .alt_path + .clone() + .ok_or_else(|| "移动目标缺失".to_string())?; + let target_path = library::safe_join(&self.root, &target)?; + if let Some(parent) = target_path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?; + } + std::fs::rename(&local_path, &target_path).map_err(|e| format!("本地改名失败: {e}"))?; + self.client.move_to(&item.rel_path, &target)?; + // 基线的键要跟着搬:内容没变,远端时间也不会变 + if let Some(entry) = state.entries.remove(&item.rel_path) { + state.entries.insert(target, entry); + } + } + SyncActionKind::Skip => {} + } + Ok(()) + } + + /// 记录基线(上传后用刚写的字节算 hash,保证与磁盘一致)。 + fn record( + &self, + state: &mut SyncState, + rel: &str, + bytes: &[u8], + remote_time: Option, + ) { + let path = library::safe_join(&self.root, rel).unwrap_or_default(); + let mtime = std::fs::metadata(&path) + .ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + state.entries.insert( + rel.to_string(), + BaselineEntry { + hash: content_hash(bytes), + local_mtime: mtime, + // 上传后服务端的 mtime 要下次 PROPFIND 才知道;这里先沿用旧值, + // 下一轮比对时若与远端不一致会被判成「远端改了」→ 一次多余的下载。 + // 为避免这个抖动,上传后把远端时间记为「与本地相同」(同一时钟下 + // 服务端通常保留客户端 mtime,或至少不会更旧)。 + remote_mtime: remote_time.unwrap_or(mtime), + }, + ); + } +} + +/// 组装一次同步所需的全部输入(供命令层调用)。 +pub fn build_plan( + root: &Path, + settings: &WebdavSettings, + client: &WebdavClient, +) -> Result<(SyncPlan, SyncState, BTreeMap), String> { + let mut state = SyncState::load(root, &settings.remote_root); + let local = scan_local(root)?; + let remote_entries = client.list_recursive()?; + let remote: BTreeMap = remote_entries + .into_iter() + .map(|entry| (entry.rel_path, entry.modified)) + .collect(); + + let direction = settings.direction; + let policy = settings.conflict; + let plan = build_sync_plan(&state.entries, &local, &remote, direction, policy); + // `state` 会被执行器就地更新 + state.version = SYNC_STATE_VERSION; + state.remote_root = settings.remote_root.clone(); + Ok((plan, state, remote)) +} + +// ===== 测试 ===== + +#[cfg(test)] +mod tests { + use super::*; + + fn local(hash: &str, mtime: u64) -> LocalFile { + LocalFile { + hash: hash.to_string(), + mtime, + size: 100, + } + } + + fn baseline(hash: &str, remote_mtime: u64) -> BaselineEntry { + BaselineEntry { + hash: hash.to_string(), + local_mtime: 1000, + remote_mtime, + } + } + + fn kinds(plan: &SyncPlan) -> Vec<(String, SyncActionKind)> { + plan.actions + .iter() + .map(|a| (a.rel_path.clone(), a.kind)) + .collect() + } + + #[test] + fn unchanged_files_produce_no_actions() { + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h1", 1000)); + let mut rem = BTreeMap::new(); + rem.insert("a.md".to_string(), 5000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert!(plan.actions.is_empty(), "{:?}", kinds(&plan)); + assert_eq!(plan.conflicts, 0); + } + + #[test] + fn local_only_change_uploads() { + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h2", 2000)); + let mut rem = BTreeMap::new(); + rem.insert("a.md".to_string(), 5000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!(kinds(&plan), vec![("a.md".to_string(), SyncActionKind::Upload)]); + } + + #[test] + fn remote_only_change_downloads() { + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h1", 1000)); + let mut rem = BTreeMap::new(); + rem.insert("a.md".to_string(), 9000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!( + kinds(&plan), + vec![("a.md".to_string(), SyncActionKind::Download)] + ); + } + + #[test] + fn both_changed_is_conflict_and_policy_decides() { + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h2", 2000)); + let mut rem = BTreeMap::new(); + rem.insert("a.md".to_string(), 9000); + + let keep_local = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::LocalWins, + ); + assert_eq!(keep_local.conflicts, 1); + assert_eq!(keep_local.actions[0].kind, SyncActionKind::ConflictKeepLocal); + + let keep_remote = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::RemoteWins, + ); + assert_eq!(keep_remote.actions[0].kind, SyncActionKind::ConflictKeepRemote); + + // 远端明显更新(>2s)→ Newer 策略选远端 + let newer = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::Newer, + ); + assert_eq!(newer.actions[0].kind, SyncActionKind::ConflictKeepRemote); + + // 时限内(时钟抖动)→ 保守选本地 + let mut rem_close = BTreeMap::new(); + rem_close.insert("a.md".to_string(), 2100); + let close = build_sync_plan( + &base, + &loc, + &rem_close, + SyncDirection::Bidirectional, + ConflictPolicy::Newer, + ); + assert_eq!(close.actions[0].kind, SyncActionKind::ConflictKeepLocal); + } + + #[test] + fn keep_both_generates_conflict_copy_path() { + let mut base = BTreeMap::new(); + base.insert("dir/a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("dir/a.md".to_string(), local("h2", 2000)); + let mut rem = BTreeMap::new(); + rem.insert("dir/a.md".to_string(), 9000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!(plan.actions[0].kind, SyncActionKind::ConflictKeepBoth); + let alt = plan.actions[0].alt_path.clone().unwrap(); + assert!(alt.starts_with("dir/a.sync-conflict-"), "{alt}"); + assert!(alt.ends_with(".md"), "{alt}"); + } + + #[test] + fn new_local_file_uploads_and_new_remote_file_downloads() { + let base = BTreeMap::new(); + let mut loc = BTreeMap::new(); + loc.insert("new-local.md".to_string(), local("h", 1)); + let mut rem = BTreeMap::new(); + rem.insert("new-remote.md".to_string(), 42); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + let items = kinds(&plan); + assert!(items.contains(&("new-local.md".to_string(), SyncActionKind::Upload))); + assert!(items.contains(&("new-remote.md".to_string(), SyncActionKind::Download))); + } + + #[test] + fn deletion_propagates_only_when_other_side_untouched() { + // 远端删了、本地没改 → 本地也删 + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h1", 1000)); + let plan = build_sync_plan( + &base, + &loc, + &BTreeMap::new(), + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!(kinds(&plan), vec![("a.md".to_string(), SyncActionKind::LocalDelete)]); + + // 远端删了、本地改过 → 本地那份重新上传(不跟着删) + let mut loc_changed = BTreeMap::new(); + loc_changed.insert("a.md".to_string(), local("h2", 2000)); + let plan = build_sync_plan( + &base, + &loc_changed, + &BTreeMap::new(), + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!( + kinds(&plan), + vec![("a.md".to_string(), SyncActionKind::Upload)], + "本地有改动时不能跟着删除" + ); + + // 本地删了、远端没改 → 远端也删 + let plan = build_sync_plan( + &base, + &BTreeMap::new(), + &BTreeMap::from([("a.md".to_string(), 5000)]), + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!( + kinds(&plan), + vec![("a.md".to_string(), SyncActionKind::RemoteDelete)] + ); + } + + #[test] + fn upload_only_ignores_remote_and_never_downloads() { + let mut base = BTreeMap::new(); + base.insert("a.md".to_string(), baseline("h1", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("a.md".to_string(), local("h2", 2000)); + let mut rem = BTreeMap::new(); + rem.insert("a.md".to_string(), 9000); + rem.insert("only-remote.md".to_string(), 1); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Upload, + ConflictPolicy::KeepBoth, + ); + assert_eq!(plan.downloads, 0); + assert_eq!(kinds(&plan), vec![("a.md".to_string(), SyncActionKind::Upload)]); + } + + #[test] + fn download_only_ignores_local_only_files() { + let base = BTreeMap::new(); + let mut loc = BTreeMap::new(); + loc.insert("only-local.md".to_string(), local("h", 1)); + let mut rem = BTreeMap::new(); + rem.insert("only-remote.md".to_string(), 1); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Download, + ConflictPolicy::KeepBoth, + ); + assert_eq!( + kinds(&plan), + vec![("only-remote.md".to_string(), SyncActionKind::Download)] + ); + } + + #[test] + fn state_roundtrip_and_remote_root_change_resets() { + let root = std::env::temp_dir().join(format!("thing-notes-sync-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + + let mut state = SyncState { + version: SYNC_STATE_VERSION, + remote_root: "root-a".to_string(), + ..Default::default() + }; + state.entries.insert("a.md".to_string(), baseline("h1", 5)); + state.save(&root).unwrap(); + + let loaded = SyncState::load(&root, "root-a"); + assert_eq!(loaded.entries.len(), 1); + assert_eq!(loaded.entries["a.md"].hash, "h1"); + + // 远端根变化 → 基线作废(否则远端 mtime 会被误判成「远端改过」) + let reset = SyncState::load(&root, "root-b"); + assert!(reset.entries.is_empty()); + + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn local_rename_becomes_move_not_delete_plus_upload() { + // 基线里 `old.md`,用户在本地把它改名成 `new.md`(内容一模一样), + // 远端还是 `old.md` 且没被改过 + let mut base = BTreeMap::new(); + base.insert("old.md".to_string(), baseline("same-hash", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("new.md".to_string(), local("same-hash", 3000)); + let mut rem = BTreeMap::new(); + rem.insert("old.md".to_string(), 5000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!(plan.moves, 1, "{:?}", kinds(&plan)); + assert_eq!(plan.uploads, 0, "改名不该变成重新上传: {:?}", kinds(&plan)); + let item = plan.actions.iter().find(|a| a.kind == SyncActionKind::Move).unwrap(); + assert_eq!(item.rel_path, "old.md"); + assert_eq!(item.alt_path.as_deref(), Some("new.md")); + } + + #[test] + fn different_content_is_not_treated_as_rename() { + // 内容不同的「删一篇 + 新建一篇」不能被误判成改名 + let mut base = BTreeMap::new(); + base.insert("old.md".to_string(), baseline("hash-a", 5000)); + let mut loc = BTreeMap::new(); + loc.insert("new.md".to_string(), local("hash-b", 3000)); + let mut rem = BTreeMap::new(); + rem.insert("old.md".to_string(), 5000); + + let plan = build_sync_plan( + &base, + &loc, + &rem, + SyncDirection::Bidirectional, + ConflictPolicy::KeepBoth, + ); + assert_eq!(plan.moves, 0, "{:?}", kinds(&plan)); + // 远端那份没改过 → 跟着旧路径删除;新文件上传 + assert!(kinds(&plan).contains(&("old.md".to_string(), SyncActionKind::RemoteDelete))); + assert!(kinds(&plan).contains(&("new.md".to_string(), SyncActionKind::Upload))); + } + + #[test] + fn scan_local_skips_private_and_non_markdown() { + let root = std::env::temp_dir().join(format!("thing-notes-scan-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("notes")).unwrap(); + std::fs::create_dir_all(root.join(".notes")).unwrap(); + std::fs::write(root.join("notes/a.md"), "x").unwrap(); + std::fs::write(root.join("notes/b.txt"), "x").unwrap(); + std::fs::write(root.join(".notes/notes.db"), "x").unwrap(); + + let map = scan_local(&root).unwrap(); + let keys: Vec<&String> = map.keys().collect(); + assert_eq!(keys, vec![&"notes/a.md".to_string()], "{keys:?}"); + + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/src-tauri/src/setup.rs b/src-tauri/src/setup.rs index 6e48e41..b699ac5 100644 --- a/src-tauri/src/setup.rs +++ b/src-tauri/src/setup.rs @@ -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) -> Result<(), Box> { 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 ===== // 仅注册状态:设置与密钥都在命令调用时按需读取,启动阶段不发任何网络请求 // (模型可用性校验因此改为懒校验:首次翻译失败时解释原因 + 设置页手动拉取模型列表)。 diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c683593..dc85bca 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -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" diff --git a/src/lib/bindings.ts b/src/lib/bindings.ts index 30b27c8..9b6210a 100644 --- a/src/lib/bindings.ts +++ b/src/lib/bindings.ts @@ -920,6 +920,138 @@ export const commands = { dshLogClear: () => __TAURI_INVOKE("dsh_log_clear"), /** 在资源管理器中打开 dsh 模块目录。 */ dshOpenDir: () => __TAURI_INVOKE("dsh_open_dir"), + /** 读取笔记模块设置。 */ + notesGetSettings: () => __TAURI_INVOKE("notes_get_settings"), + /** 保存笔记模块设置(自愈后落盘,并广播给各窗口)。 */ + notesSaveSettings: (settings: NoteSettings) => __TAURI_INVOKE("notes_save_settings", { settings }), + /** 当前库状态概览(库根 / 是否自定义 / 笔记数)。 */ + notesLibraryInfo: () => __TAURI_INVOKE("notes_library_info"), + /** 设置库根(`None` 或空串 = 恢复默认库根)。 */ + notesSetLibraryRoot: (root: string | null) => __TAURI_INVOKE("notes_set_library_root", { root }), + /** 扫描库,返回扁平条目列表(前端组树)。 */ + notesScanLibrary: () => __TAURI_INVOKE("notes_scan_library"), + /** 读取一篇笔记。 */ + notesReadNote: (relPath: string) => __TAURI_INVOKE("notes_read_note", { relPath }), + /** 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。 */ + notesSaveNote: (relPath: string, content: string) => __TAURI_INVOKE("notes_save_note", { relPath, content }), + /** + * 新建笔记(自动补 `.md`、重名加序号),返回新文档。 + * + * `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 —— + * 模板文件被删掉不该让「新建笔记」这个核心动作失败)。 + */ + notesCreateNote: (dirRel: string, name: string, templateId: string | null) => __TAURI_INVOKE("notes_create_note", { dirRel, name, templateId }), + /** 新建文件夹。 */ + notesCreateFolder: (dirRel: string, name: string) => __TAURI_INVOKE("notes_create_folder", { dirRel, name }), + /** 重命名条目,返回新相对路径。 */ + notesRenameEntry: (relPath: string, newName: string) => __TAURI_INVOKE("notes_rename_entry", { relPath, newName }), + /** 删除条目(目录递归删除)。 */ + notesDeleteEntry: (relPath: string) => __TAURI_INVOKE("notes_delete_entry", { relPath }), + /** 全量重建索引(设置页「重建索引」)。文件不受影响。 */ + notesRebuildIndex: () => __TAURI_INVOKE("notes_rebuild_index"), + /** 增量同步索引(打开编辑器 / 手动刷新时调用)。 */ + notesSyncIndex: () => __TAURI_INVOKE("notes_sync_index"), + /** 全文检索 / 按标签 / 按目录筛选。 */ + notesSearchNotes: (query: NoteSearchQuery) => __TAURI_INVOKE("notes_search_notes", { query }), + /** 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。 */ + notesListNotes: (limit: number | null) => __TAURI_INVOKE("notes_list_notes", { limit }), + /** 标签及计数。 */ + notesTags: () => __TAURI_INVOKE("notes_tags"), + /** 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。 */ + notesIndexStats: () => __TAURI_INVOKE("notes_index_stats"), + /** + * 打开(读取)库外任意文件。 + * + * 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数), + * 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。 + */ + notesOpenFile: (path: string) => __TAURI_INVOKE("notes_open_file", { path }), + /** 保存库外任意文件(按前端回传的编码与换行写回)。 */ + notesWriteFile: (path: string, content: string, encoding: string, eol: string) => __TAURI_INVOKE("notes_write_file", { path, content, encoding, eol }), + /** + * 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。 + * + * 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板, + * 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」 + * 安全得多(写的位置由后端决定,且只落在 `assets/`)。 + */ + notesWriteAsset: (fileName: string, ext: string, dataBase64: string) => __TAURI_INVOKE("notes_write_asset", { fileName, ext, dataBase64 }), + /** + * 显式登记一个路径为「可写」。 + * + * 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `notes_open_file`, + * 但用户确实是用系统对话框选的,属于「用户显式选择」)。 + */ + notesAuthorizeFile: (path: string) => __TAURI_INVOKE("notes_authorize_file", { path }), + /** + * 列出可用模板(用户模板优先,同名覆盖内置)。 + * + * 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击 + * 就能直接写文件,不需要用户先去资源管理器建目录。 + */ + notesListTemplates: () => __TAURI_INVOKE("notes_list_templates"), + /** + * 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。 + * + * 三种用法: + * - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点); + * - 传 `name` + `body`:新建一个自定义模板。 + */ + notesAddTemplate: (name: string | null, body: string | null) => __TAURI_INVOKE("notes_add_template", { name, body }), + /** + * 读取一个模板的正文(界面上「查看 / 编辑模板」用)。 + * + * 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` —— + * 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。 + */ + notesReadTemplate: (templateId: string) => __TAURI_INVOKE("notes_read_template", { templateId }), + /** 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。 */ + notesDailyNote: () => __TAURI_INVOKE("notes_daily_note"), + /** 从磁盘路径导入(文件 / 目录 / zip 自动判别)。 */ + notesImport: (source: string, destDir: string) => __TAURI_INVOKE("notes_import", { source, destDir }), + /** + * 把一篇笔记导出为独立 HTML 文件,返回落盘路径。 + * + * HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把 + * 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。 + */ + notesExportNote: (relPath: string, html: string, dest: string) => __TAURI_INVOKE("notes_export_note", { relPath, html, dest }), + /** 把整库(或某个目录)打包成 zip,返回落盘路径。 */ + notesExportZip: (dest: string, dirRel: string | null) => __TAURI_INVOKE("notes_export_zip", { dest, dirRel }), + /** + * 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。 + * + * 与 [`notes_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」, + * 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为 + * 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。 + */ + notesExportSnapshotLocal: (dest: string | null) => __TAURI_INVOKE("notes_export_snapshot_local", { dest }), + /** 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。 */ + notesWebdavStatus: () => __TAURI_INVOKE("notes_webdav_status"), + /** 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。 */ + notesSetWebdavPassword: (password: string) => __TAURI_INVOKE("notes_set_webdav_password", { password }), + /** 连接自检(建目录 + 列远端)。 */ + notesTestWebdav: () => __TAURI_INVOKE("notes_test_webdav"), + /** 立即同步(并按设置决定是否追加一次快照备份)。 */ + notesSyncNow: () => __TAURI_INVOKE("notes_sync_now"), + /** 只做一次 zip 快照备份(不上传增量)。 */ + notesBackupNow: () => __TAURI_INVOKE("notes_backup_now"), + /** 列出远端已有快照。 */ + notesListBackups: () => __TAURI_INVOKE("notes_list_backups"), + /** 从远端快照恢复(不覆盖本地已有文件)。 */ + notesRestoreBackup: (name: string) => __TAURI_INVOKE("notes_restore_backup", { name }), + /** 一篇笔记的链接关系(出链 + 入链)。 */ + notesBacklinks: (relPath: string) => __TAURI_INVOKE("notes_backlinks", { relPath }), + /** 全库链接图(已解析的内部链接边)。 */ + notesLinkGraph: () => __TAURI_INVOKE("notes_link_graph"), + /** + * 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。 + * + * 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完, + * 事件会直接丢掉(见 `notes/args.rs` 的 `PENDING` 注释)。 + */ + notesTakePendingFile: () => __TAURI_INVOKE("notes_take_pending_file"), + notesReadAsset: (relPath: string) => __TAURI_INVOKE("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, diff --git a/src/lib/constants.ts b/src/lib/constants.ts index 232be65..f8c8348 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -27,6 +27,8 @@ export const WINDOWS = { * 时,webview 仍可正常加载与交互,只是拿不到 IPC)。 */ dshWeb: 'dsh-web', + /** 笔记独立窗口前缀,实际 label = `${notesWindow}-`(可多开) */ + 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 diff --git a/src/main.ts b/src/main.ts index 5797227..fbfaafd 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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 diff --git a/src/modules/icons.ts b/src/modules/icons.ts index 7b64b2d..79214c3 100644 --- a/src/modules/icons.ts +++ b/src/modules/icons.ts @@ -11,7 +11,8 @@ import { Music, Languages, SquareTerminal, - Bot + Bot, + NotebookPen } from '@lucide/vue' /** @@ -33,7 +34,8 @@ export const moduleIconMap: Record = { music: Music, translate: Languages, terminal: SquareTerminal, - dsh: Bot + dsh: Bot, + notes: NotebookPen } /** 获取模块图标组件,未找到时回退到 Settings 图标 */ diff --git a/src/modules/index.ts b/src/modules/index.ts index ff1e693..73e97f9 100644 --- a/src/modules/index.ts +++ b/src/modules/index.ts @@ -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 ] // 启动时注册所有模块 diff --git a/src/modules/music/components/MyMusicLibrary.vue b/src/modules/music/components/MyMusicLibrary.vue index 86f863b..8f4053b 100644 --- a/src/modules/music/components/MyMusicLibrary.vue +++ b/src/modules/music/components/MyMusicLibrary.vue @@ -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(() => { 加载曲库… - - 曲库为空 + + + + + {{ store.libraryError ? '曲库加载失败' : '曲库为空' }} {{ listEmptyHint }} diff --git a/src/modules/notes/NotesModule.vue b/src/modules/notes/NotesModule.vue new file mode 100644 index 0000000..b767e48 --- /dev/null +++ b/src/modules/notes/NotesModule.vue @@ -0,0 +1,697 @@ + + + \ No newline at end of file diff --git a/src/modules/notes/NotesWindow.vue b/src/modules/notes/NotesWindow.vue new file mode 100644 index 0000000..169ab60 --- /dev/null +++ b/src/modules/notes/NotesWindow.vue @@ -0,0 +1,525 @@ + + + + + diff --git a/src/modules/notes/components/BacklinksPanel.vue b/src/modules/notes/components/BacklinksPanel.vue new file mode 100644 index 0000000..faa361b --- /dev/null +++ b/src/modules/notes/components/BacklinksPanel.vue @@ -0,0 +1,218 @@ + + + diff --git a/src/modules/notes/components/EditorHost.vue b/src/modules/notes/components/EditorHost.vue new file mode 100644 index 0000000..932a6c5 --- /dev/null +++ b/src/modules/notes/components/EditorHost.vue @@ -0,0 +1,245 @@ + + + + + diff --git a/src/modules/notes/components/EditorToolbar.vue b/src/modules/notes/components/EditorToolbar.vue new file mode 100644 index 0000000..ac4ec85 --- /dev/null +++ b/src/modules/notes/components/EditorToolbar.vue @@ -0,0 +1,243 @@ + + + diff --git a/src/modules/notes/components/ImportExportPanel.vue b/src/modules/notes/components/ImportExportPanel.vue new file mode 100644 index 0000000..9f584e3 --- /dev/null +++ b/src/modules/notes/components/ImportExportPanel.vue @@ -0,0 +1,314 @@ + + + diff --git a/src/modules/notes/components/LibrarySidebar.vue b/src/modules/notes/components/LibrarySidebar.vue new file mode 100644 index 0000000..4bdc507 --- /dev/null +++ b/src/modules/notes/components/LibrarySidebar.vue @@ -0,0 +1,466 @@ + + + diff --git a/src/modules/notes/components/MarkdownOutline.vue b/src/modules/notes/components/MarkdownOutline.vue new file mode 100644 index 0000000..5b766ff --- /dev/null +++ b/src/modules/notes/components/MarkdownOutline.vue @@ -0,0 +1,84 @@ + + + diff --git a/src/modules/notes/components/NewNoteDialog.vue b/src/modules/notes/components/NewNoteDialog.vue new file mode 100644 index 0000000..7fc5afc --- /dev/null +++ b/src/modules/notes/components/NewNoteDialog.vue @@ -0,0 +1,136 @@ + + + diff --git a/src/modules/notes/components/QuickOpen.vue b/src/modules/notes/components/QuickOpen.vue new file mode 100644 index 0000000..d30a39a --- /dev/null +++ b/src/modules/notes/components/QuickOpen.vue @@ -0,0 +1,185 @@ + + + diff --git a/src/modules/notes/components/SearchPanel.vue b/src/modules/notes/components/SearchPanel.vue new file mode 100644 index 0000000..1616047 --- /dev/null +++ b/src/modules/notes/components/SearchPanel.vue @@ -0,0 +1,173 @@ + + + diff --git a/src/modules/notes/components/WebdavPanel.vue b/src/modules/notes/components/WebdavPanel.vue new file mode 100644 index 0000000..2abcd0c --- /dev/null +++ b/src/modules/notes/components/WebdavPanel.vue @@ -0,0 +1,490 @@ + + + diff --git a/src/modules/notes/editor/core.ts b/src/modules/notes/editor/core.ts new file mode 100644 index 0000000..e567186 --- /dev/null +++ b/src/modules/notes/editor/core.ts @@ -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() +} diff --git a/src/modules/notes/editor/images.ts b/src/modules/notes/editor/images.ts new file mode 100644 index 0000000..f950018 --- /dev/null +++ b/src/modules/notes/editor/images.ts @@ -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() +/** 正在读取中的目标(避免同一张图并发读多次) */ +const inflight = new Map>() + +/** 清空缓存(切库 / 重建索引后调用)。 */ +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 { + 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 +} diff --git a/src/modules/notes/editor/keymap.ts b/src/modules/notes/editor/keymap.ts new file mode 100644 index 0000000..bd61cde --- /dev/null +++ b/src/modules/notes/editor/keymap.ts @@ -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) +} \ No newline at end of file diff --git a/src/modules/notes/editor/languages.ts b/src/modules/notes/editor/languages.ts new file mode 100644 index 0000000..e1dc309 --- /dev/null +++ b/src/modules/notes/editor/languages.ts @@ -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 + +interface LanguageEntry { + /** 状态栏展示名 */ + label: string + load: LanguageLoader +} + +/** + * 扩展名(小写,不含点)→ 语言。 + * + * 值写成 thunk 而不是已加载的扩展:`import()` 只在真正调用时执行, + * 表本身的构建不产生任何网络/打包开销。 + */ +const LOADERS: Record = { + // ===== 前端 ===== + 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>() + +/** 从文件名取扩展名(小写、不含点;无扩展名返回空串)。 */ +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 { + 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 + }) +} diff --git a/src/modules/notes/editor/markdownExport.test.ts b/src/modules/notes/editor/markdownExport.test.ts new file mode 100644 index 0000000..81431f1 --- /dev/null +++ b/src/modules/notes/editor/markdownExport.test.ts @@ -0,0 +1,296 @@ +/** + * markdownExport 单测(Node 内置 test runner)。 + * + * # 为什么用 `renderMarkdownFragmentRaw` + * + * DOMPurify 需要 `window`/`document`:Node 里 `isSupported === false` 且对象上**根本 + * 没有** `sanitize`,所以「消毒后的片段」在纯 Node 下无法断言(本文件里如实 + * `t.skip()`,不装 jsdom、更不为跑通测试降低消毒强度)。 + * 但「fence 语言识别、任务列表、表格、链接、图片」这些**渲染**行为是纯字符串逻辑, + * 必须能脱离浏览器回归,所以走模块里明确标注为「仅供单测」的未消毒入口。 + * + * # 为什么两个方向都断言 + * + * 一边断言「未消毒的片段里确实带着 `onerror=` / `') + assert.match(raw, /onerror=/) + assert.match(raw, /'), '') + assert.equal(renderMarkdownFragment('# 正常标题'), '') +}) + +test('XSS:', + '', + '', + '', + '[点我](javascript:alert(1))', + '', + '覆盖界面', + '', + '', + '', + '' + ].join('\n') + const html = renderMarkdownFragment(dirty) + assert.ok(!html.includes('onerror='), html) + assert.ok(!html.includes('外链' + ) + assert.match(kept, /class="hljs"/) + assert.match(kept, //) + assert.match(kept, /type="checkbox" disabled checked/) + assert.match(kept, / 与页首标题都转义', () => { + const html = renderNoteHtml({ + title: 'A & B ', + fileName: 'a.md', + markdown: '# 正文', + exportedAt: new Date(2026, 0, 2, 3, 4) + }) + assert.ok(html.startsWith('')) + assert.ok(html.includes('')) + assert.ok(html.includes('')) + assert.ok(html.includes('name="viewport"')) + assert.ok(html.includes('A & B <C>')) + assert.ok(html.includes('

A & B <C>

')) + 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 = /`, + '', + '', + '
', + `

${escapeHtml(title)}

`, + '
', + body, + '
', + `
${escapeHtml(footer)}
`, + '
', + '', + '', + '' + ].join('\n') + ) +} diff --git a/src/modules/notes/editor/markdownLivePreview.ts b/src/modules/notes/editor/markdownLivePreview.ts new file mode 100644 index 0000000..7343dc0 --- /dev/null +++ b/src/modules/notes/editor/markdownLivePreview.ts @@ -0,0 +1,461 @@ +/** + * Live Preview 扩展 —— CM6 上的「所见即所得」。 + * + * # 范式说明(重要) + * + * CodeMirror 是源码编辑器,没有块模型。这里的「所见即所得」= **Live Preview** + * (Typora / Obsidian 式):遍历 Lezer Markdown 语法树, + * + * - **非光标行**:隐藏 Markdown 语法符号(`#` `**` `[]()` `>` `-` …), + * 让渲染结果直接可见; + * - **光标行**(当前选区所覆盖的行):语法符号「显形」,恢复为可编辑源码; + * - **结构性元素**用装饰表达标签无法表达的部分:标题字号、行内代码底色、 + * 引用条、代码块底色、分隔线 widget、任务复选框 widget(可点击改写文档)。 + * + * 颜色(标题色 / 加粗 / 斜体 / 链接色)由主题的 HighlightStyle 负责, + * 这里只管结构与「隐藏」。 + * + * # 性能 + * + * 装饰只对 `view.visibleRanges` 计算(长文档不做全文遍历), + * 且文档/选区/视口变化时整批重建(见文件末的 ViewPlugin)。 + */ +import { + Decoration, + EditorView, + ViewPlugin, + WidgetType, + type DecorationSet, + type ViewUpdate +} from '@codemirror/view' +import { type Extension, type Range } from '@codemirror/state' +import { syntaxTree } from '@codemirror/language' +import { type SyntaxNode } from '@lezer/common' +import { cachedImage, fetchImage, resolveImagePath } from './images' + +/** Live Preview 的可选配置(图片预览需要知道「当前是哪篇笔记」)。 */ +export interface LivePreviewOptions { + /** + * 当前笔记的库内相对路径(空串 = 库外文件,不做图片预览)。 + * + * 图片目标按「相对当前笔记所在目录」解析,因此必须有这个上下文。 + */ + currentRelPath?: string + /** 是否启用图片预览(默认 true) */ + images?: boolean +} + +/** 隐藏语法符号(替换为空) */ +const HIDE = Decoration.replace({}) + +/** 取节点的「内部内容」区间(跳过首尾的语法标记子节点)。 */ +function innerRange(node: SyntaxNode): { from: number; to: number } { + const first = node.firstChild + const last = node.lastChild + if (!first || !last) return { from: node.from, to: node.to } + const from = first.to + const to = last.from + return from < to ? { from, to } : { from: node.from, to: node.to } +} + +/** 任务复选框:点击在 `[ ]` / `[x]` 间切换。 */ +class CheckboxWidget extends WidgetType { + constructor( + readonly checked: boolean, + readonly from: number, + readonly to: number + ) { + super() + } + + eq(other: CheckboxWidget): boolean { + return other.checked === this.checked && other.from === this.from + } + + toDOM(view: EditorView): HTMLElement { + const input = document.createElement('input') + input.type = 'checkbox' + input.checked = this.checked + input.className = 'cm-md-checkbox' + input.addEventListener('mousedown', event => { + event.preventDefault() + view.dispatch({ + changes: { from: this.from, to: this.to, insert: this.checked ? '[ ]' : '[x]' } + }) + }) + return input + } + + ignoreEvent(): boolean { + return false + } +} + +/** 分隔线:把 `---` / `***` 渲染成一条水平线。 */ +class HorizontalRuleWidget extends WidgetType { + eq(): boolean { + return true + } + toDOM(): HTMLElement { + const el = document.createElement('span') + el.className = 'cm-md-hr' + return el + } + ignoreEvent(): boolean { + return false + } +} + +/** + * 内联图片预览。 + * + * 只在「该 Markdown 图片独占一行、且不在光标行上」时替换整段 `![alt](src)` —— + * 与行内混排的图片(`见 ![图](a.png) 所示`)保持源码形态:把行内图片换成块级 + * `` 会撑高这一行,光标位置与视觉行对不上。 + * + * 高度上限用 CSS 控制(`max-height: 320px`),而不是在 widget 里算 —— 算高度就 + * 得等 `load` 事件,那会让装饰重建与图片加载互相触发。 + */ +class InlineImageWidget extends WidgetType { + constructor( + readonly src: string, + readonly alt: string, + /** 文档里的完整原始片段(预览不可用时原样显示) */ + readonly raw: string + ) { + super() + } + + eq(other: InlineImageWidget): boolean { + return other.src === this.src && other.alt === this.alt + } + + toDOM(): HTMLElement { + const wrapper = document.createElement('span') + wrapper.className = 'cm-md-image' + const img = document.createElement('img') + img.src = this.src + img.alt = this.alt + img.loading = 'lazy' + // 拖拽图片应当拖「图片文件」而不是让编辑器选中文本 + img.draggable = false + wrapper.appendChild(img) + if (this.alt) { + const caption = document.createElement('span') + caption.className = 'cm-md-image-alt' + caption.textContent = this.alt + wrapper.appendChild(caption) + } + return wrapper + } + + ignoreEvent(): boolean { + return false + } +} + +/** 是否为「链接类」节点的子 URL(决定是否随链接一起隐藏)。 */ +function isLinkUrl(node: SyntaxNode): boolean { + const parent = node.parent + return parent?.name === 'Link' || parent?.name === 'Image' +} + +/** 取出一个 `Image` 节点的原始目标(`![alt](target)` 里 `target` 的原文)。 */ +function imageTarget(raw: string): { alt: string; target: string } | null { + // 结构固定为 `![alt](target)`:找第一个 `](`,再从末尾去掉 `)` + const open = raw.indexOf('](') + if (open < 0 || !raw.endsWith(')')) return null + const alt = raw.slice(2, open) + const target = raw.slice(open + 2, -1) + return { alt, target } +} + +/** + * 「装饰构建器」旁表:`EditorView` → 重建函数。 + * + * 图片是异步取字节的,拿到之后需要重算一次装饰。插件本身不把实例暴露给外部, + * 而是把重建函数登记在这里 —— 宿主(或本文件内部的图片回调)拿着同一个 view + * 就能触发重建,`ViewPlugin` 的 `update` 生命周期不会被外部伸手破坏。 + * + * 用 `WeakMap`:编辑器销毁后条目自动消失,不会因为「关掉的窗口」泄漏。 + */ +const builders = new WeakMap 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[] = [] + + // 光标/选区覆盖的行:这些行内的语法符号显形(保持可编辑) + const activeLines = new Set() + 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 } + ) + ] +} \ No newline at end of file diff --git a/src/modules/notes/editor/outline.test.ts b/src/modules/notes/editor/outline.test.ts new file mode 100644 index 0000000..ac63ab6 --- /dev/null +++ b/src/modules/notes/editor/outline.test.ts @@ -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), ' ## 缩进二级') +}) diff --git a/src/modules/notes/editor/outline.ts b/src/modules/notes/editor/outline.ts new file mode 100644 index 0000000..a602b1d --- /dev/null +++ b/src/modules/notes/editor/outline.ts @@ -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 +} diff --git a/src/modules/notes/editor/themes.ts b/src/modules/notes/editor/themes.ts new file mode 100644 index 0000000..60edc8b --- /dev/null +++ b/src/modules/notes/editor/themes.ts @@ -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 = { + '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 = { + '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 } + }) +} \ No newline at end of file diff --git a/src/modules/notes/editor/wikilink.ts b/src/modules/notes/editor/wikilink.ts new file mode 100644 index 0000000..ddf7f9e --- /dev/null +++ b/src/modules/notes/editor/wikilink.ts @@ -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[] = [] + 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 + } + }) + ] +} diff --git a/src/modules/notes/index.ts b/src/modules/notes/index.ts new file mode 100644 index 0000000..feef25d --- /dev/null +++ b/src/modules/notes/index.ts @@ -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 +} \ No newline at end of file diff --git a/src/modules/notes/notesClient.ts b/src/modules/notes/notesClient.ts new file mode 100644 index 0000000..da13662 --- /dev/null +++ b/src/modules/notes/notesClient.ts @@ -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('notes_get_settings'), + saveSettings: (settings: NoteSettings) => + invoke('notes_save_settings', { settings }), + + // ===== 库 ===== + libraryInfo: () => invoke('notes_library_info'), + setLibraryRoot: (root: string | null) => invoke('notes_set_library_root', { root }), + scanLibrary: () => invoke('notes_scan_library'), + readNote: (relPath: string) => invoke('notes_read_note', { relPath }), + saveNote: (relPath: string, content: string) => + invoke('notes_save_note', { relPath, content }), + createNote: (dirRel: string, name: string, templateId?: string) => + invoke('notes_create_note', { dirRel, name, templateId: templateId ?? null }), + createFolder: (dirRel: string, name: string) => + invoke('notes_create_folder', { dirRel, name }), + renameEntry: (relPath: string, newName: string) => + invoke('notes_rename_entry', { relPath, newName }), + deleteEntry: (relPath: string) => invoke('notes_delete_entry', { relPath }), + /** 打开(或创建)今天的日记 */ + dailyNote: () => invoke('notes_daily_note'), + + // ===== 索引与检索 ===== + rebuildIndex: () => invoke('notes_rebuild_index'), + syncIndex: () => invoke('notes_sync_index'), + /** 全文检索 / 标签 / 目录筛选(`query` 与 Rust 侧 `NoteSearchQuery` 一一对应) */ + search: (query: NoteSearchQuery) => invoke('notes_search_notes', { query }), + listNotes: (limit?: number) => invoke('notes_list_notes', { limit: limit ?? null }), + tags: () => invoke('notes_tags'), + indexStats: () => invoke('notes_index_stats'), + /** 一篇笔记的出链 / 入链 */ + backlinks: (relPath: string) => invoke('notes_backlinks', { relPath }), + /** 全库链接图(已解析的内部链接边) */ + linkGraph: () => invoke('notes_link_graph'), + /** + * 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。 + * + * 冷启动时 Rust 无法 `emit`(前端还没注册监听),因此改为前端主动取一次。 + */ + takePendingFile: () => invoke('notes_take_pending_file'), + + // ===== 库外任意文件 ===== + openFile: (path: string) => invoke('notes_open_file', { path }), + writeFile: (path: string, content: string, encoding: string, eol: string) => + invoke('notes_write_file', { path, content, encoding, eol }), + /** 登记系统对话框选中的路径为「可写」(它不是经 `openFile` 打开的) */ + authorizeFile: (path: string) => invoke('notes_authorize_file', { path }), + /** 把 base64 图片写进库根 `assets/`,返回可插入 Markdown 的相对路径 */ + writeAsset: (fileName: string, ext: string, dataBase64: string) => + invoke('notes_write_asset', { fileName, ext, dataBase64 }), + /** + * 把库内图片读成 `data:` URL(内联预览用)。 + * + * 返回 `null` 表示「不适合预览」(非图片扩展名 / 超过大小上限)—— + * 不是错误,调用方按普通文本渲染即可。 + */ + readAsset: (relPath: string) => invoke('notes_read_asset', { relPath }), + + // ===== 模板(P2) ===== + listTemplates: () => invoke('notes_list_templates'), + /** 不带参数 = 把全部内置模板导出到库内 `templates/` */ + addTemplate: (name?: string, body?: string) => + invoke('notes_add_template', { name: name ?? null, body: body ?? null }), + readTemplate: (templateId: string) => + invoke('notes_read_template', { templateId }), + + // ===== 导入 / 导出(P2) ===== + import: (source: string, destDir: string) => + invoke('notes_import', { source, destDir }), + /** 把渲染好的 HTML 写到用户选定的位置(渲染在前端,落盘在后端) */ + exportNote: (relPath: string, html: string, dest: string) => + invoke('notes_export_note', { relPath, html, dest }), + exportZip: (dest: string, dirRel?: string) => + invoke('notes_export_zip', { dest, dirRel: dirRel ?? null }), + exportSnapshotLocal: (dest?: string) => + invoke('notes_export_snapshot_local', { dest: dest ?? null }), + + // ===== WebDAV(P2) ===== + webdavStatus: () => invoke('notes_webdav_status'), + setWebdavPassword: (password: string) => + invoke('notes_set_webdav_password', { password }), + testWebdav: () => invoke('notes_test_webdav'), + syncNow: () => invoke('notes_sync_now'), + backupNow: () => invoke('notes_backup_now'), + listBackups: () => invoke('notes_list_backups'), + restoreBackup: (name: string) => invoke('notes_restore_backup', { name }) +} diff --git a/src/modules/notes/openWindow.ts b/src/modules/notes/openWindow.ts new file mode 100644 index 0000000..541b2bc --- /dev/null +++ b/src/modules/notes/openWindow.ts @@ -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 { + 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 { + 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((resolve, reject) => { + win.once('tauri://created', () => resolve()) + win.once('tauri://error', e => reject(new Error(String(e)))) + }) +} diff --git a/src/stores/feiniuStore.ts b/src/stores/feiniuStore.ts index 87d89e9..ccc04e9 100644 --- a/src/stores/feiniuStore.ts +++ b/src/stores/feiniuStore.ts @@ -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, diff --git a/src/stores/notesStore.ts b/src/stores/notesStore.ts new file mode 100644 index 0000000..7966926 --- /dev/null +++ b/src/stores/notesStore.ts @@ -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() + 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 | 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 { + try { + this.settings = await notesClient.getSettings() + } catch (e) { + logger.error(`读取笔记设置失败: ${String(e)}`) + } finally { + this.ready = true + } + }, + + /** 局部更新设置(即时生效并落盘;返回值已由 Rust 自愈规范化)。 */ + async patchSettings(patch: Partial): Promise { + const next: NoteSettings = { ...this.settings, ...patch } + try { + this.settings = await notesClient.saveSettings(next) + } catch (e) { + logger.error(`保存笔记设置失败: ${String(e)}`) + } + }, + + // ===== 库 ===== + + async refreshLibrary(): Promise { + 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 { + this.info = await notesClient.setLibraryRoot(root) + await this.refreshLibrary() + // 库换了,索引也要跟着换:重建比「猜差量」稳,且此时用户本来就在等 + await this.rebuildIndex() + }, + + // ===== 索引与检索 ===== + + /** 增量同步索引(打开编辑器时调用一次,外部改动后由文件事件触发)。 */ + async syncIndex(): Promise { + 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 { + 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 { + try { + this.indexStats = await notesClient.indexStats() + } catch (e) { + logger.error(`读取索引状态失败: ${String(e)}`) + } + }, + + async loadTags(): Promise { + 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 { + 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 { + 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 { + try { + this.quickOpenList = await notesClient.listNotes(1000) + } catch (e) { + logger.error(`读取文件清单失败: ${String(e)}`) + } + }, + + // ===== 笔记文档 ===== + + async openNote(relPath: string, options?: { keepDirty?: boolean }): Promise { + 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 { + 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 { + 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 { + try { + this.templates = await notesClient.listTemplates() + } catch (e) { + logger.error(`读取模板失败: ${String(e)}`) + } + }, + + /** 新建模板(同名会失败,由调用方提示)。 */ + async addTemplate(name: string, body: string): Promise { + await notesClient.addTemplate(name, body) + await this.loadTemplates() + }, + + /** 把内置模板导出到库内 `templates/`,返回新写入的名字。 */ + async exportBuiltinTemplates(): Promise { + const written = await notesClient.addTemplate() + await this.loadTemplates() + return written + }, + + /** 打开(或创建)今天的日记。 */ + async openDailyNote(): Promise { + 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 { + try { + this.webdavStatus = await notesClient.webdavStatus() + } catch (e) { + logger.error(`读取 WebDAV 状态失败: ${String(e)}`) + } + }, + + /** + * 立即同步(进度由 `notes-sync-progress` 事件驱动)。 + * + * 同步可能改变本地文件(下载覆盖、删除传播),因此结束后必须重载当前文档 —— + * 否则编辑器里显示的还是同步之前的旧内容,用户一保存就把同步结果覆盖回去了。 + */ + async syncNow(): Promise { + 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 { + 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 { + 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 { + 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 { + if (password !== undefined) { + await notesClient.setWebdavPassword(password) + } + await this.loadWebdavStatus() + }, + + async createFolder(dirRel: string, name: string): Promise { + await notesClient.createFolder(dirRel, name) + await this.refreshLibrary() + }, + + async renameEntry(relPath: string, newName: string): Promise { + const nextRel = await notesClient.renameEntry(relPath, newName) + if (this.currentRelPath === relPath) this.currentRelPath = nextRel + await this.refreshLibrary() + }, + + async deleteEntry(relPath: string): Promise { + await notesClient.deleteEntry(relPath) + if (this.currentRelPath === relPath) { + this.resetDocument() + } + await this.refreshLibrary() + }, + + // ===== 库外文件 ===== + + /** + * 打开一个库外文件。 + * + * 若该文件同时也在库内(例如用「打开文件」选了笔记库里的 `.md`), + * 仍然按**文件**处理:文件语义(编码/换行/大文件降级)是用户从系统对话框 + * 选择时更可预期的行为,而库语义(front-matter、库内相对路径)需要库上下文。 + */ + async openFile(path: string): Promise { + 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 { + 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 { + 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 { + 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(EVENTS.notesFileChanged, event => { + void this.onExternalChange(event.payload) + }) + const unSync = await listen(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(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 { + 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 { + 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 { + 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 + } + } + } +}) diff --git a/src/types/notes.ts b/src/types/notes.ts new file mode 100644 index 0000000..5381498 --- /dev/null +++ b/src/types/notes.ts @@ -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 }],供模板里用 `` 渲染(不注入 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 + } +} \ No newline at end of file