Compare commits

..
99 Commits
Author SHA1 Message Date
Yuri Karamian e1f1ef0b02 Harden v1.3.6 data safety and editor lifecycle
Protect file mutations, backup restoration, and WebDAV synchronization from data loss. Preserve editor drafts across concurrent saves, external changes, and window or vault transitions. Integrate toolbar customization inline and extend regression coverage.
2026-09-29 14:05:46 +02:00
Yuri Karamian 806c63aa65 Add desktop toolbar customization and fix pane toggle icons 2026-09-28 23:28:56 +02:00
Yuri Karamian 4157beddf7 Remove GitLab CI 2026-09-28 21:15:55 +02:00
Yuri Karamian 923cb9571c Improve search and show save errors
- Show search results in the right notebook or All Notes list
- Scroll to the selected note and highlight matching text
- Keep unsaved edits safe and ignore old or cancelled searches
- Show save errors with a Retry button
- Run graph and vault statistics scans in the background
- Fix folder checks when counting vault files
- Keep desktop window-close code out of mobile builds
2026-09-28 21:06:28 +02:00
Yuri Karamian 640b5e3d10 Improve editor performance and harden note saving
Replace the source editor with CodeMirror and reduce typing-time work.
Virtualize note lists, apply targeted refreshes, and batch search indexing.
Improve vault and in-note search, and bound graph layout work.
Make saves revision-safe and flush pending changes before navigation or close.
Preserve originating-vault ownership across async operations and detached windows.
Harden sync, attachment writes, and notebook/tag appearance updates.
Keep Trash previews read-only and skip restoring trashed notes.
Update AI model presets and isolate streamed responses by request.
Fix local image rendering and preserve portable image paths.
Include regression tests for the changed behavior.
2026-09-28 07:50:46 +02:00
Yuri Karamian 3607cf1b3f Merge branch 'main' into 'main'
feat: add custom tag icons and colors

See merge request ArkHost/HelixNotes!9
2026-09-21 09:08:33 +00:00
Blake Boone 245cdacb68 feat: add custom tag icons and colors 2026-09-21 09:08:33 +00:00
Yuri Karamian 2983e3db29 Merge branch 'main' into 'main'
Merge branch 'fix/sort-theme-list-alphabetically' into 'main'

Closes #250

See merge request ArkHost/HelixNotes!7
2026-09-17 12:30:52 +00:00
Shawn cc7c9e2b49 Merge branch HelixNotes:main into main 2026-09-15 16:09:56 +00:00
Shawn 2240231f61 Merge branch 'fix/sort-theme-list-alphabetically' into 'main'
fix: sort theme list alphabetically

See merge request locodarwin/HelixNotes!1
2026-09-15 15:36:44 +00:00
Yuri Karamian b2d0c7175e test: cover built-in theme preset ordering 2026-09-15 15:04:51 +02:00
Shawn Olson 1bc0026731 fix: sort theme list alphabetically 2026-09-14 14:42:06 -07:00
Yuri Karamian 41c0e4c993 fix: preserve Linux window title and configuration 2026-09-10 16:50:54 +02:00
Yuri Karamian 34a0f9efa3 fix: keep mobile navigation visible with collapsed desktop sidebar 2026-09-06 22:46:11 +02:00
Yuri Karamian 9d92489586 Merge branch 'fix/macos-escape-overlay-fullscreen' into 'main'
Prevent Escape from exiting fullscreen when closing overlays

See merge request ArkHost/HelixNotes!4
2026-09-04 13:00:47 +00:00
Vijay c45efb60ab Prevent Escape from exiting fullscreen when closing overlays 2026-09-04 13:00:46 +00:00
Yuri Karamian 0d11fd01dd fix: preserve hidden note title across editor modes 2026-09-04 14:46:30 +02:00
Yuri Karamian 0aaa05ce5c Merge branch 'fix/context-menu-paste-image' into 'main'
fix: paste images from the editor context menu

See merge request ArkHost/HelixNotes!6
2026-09-04 08:54:04 +00:00
Sridhar 77e92ef25c fix: paste images from the editor context menu 2026-09-04 08:54:04 +00:00
Yuri Karamian d7e4be7f3a Merge branch 'fix/webkitgtk-clipboard-image-paste' into 'main'
fix: paste images copied from a browser on WebKitGTK

Closes #245

See merge request ArkHost/HelixNotes!5
2026-09-03 19:07:34 +00:00
Sridhar 2aa572dcaa fix: paste images copied from a browser on WebKitGTK 2026-09-03 19:07:34 +00:00
Yuri Karamian 32f270ce9e Update v1.3.5 download documentation 2026-08-27 00:37:30 +02:00
Yuri Karamian a15b267614 Add scroll font size preference and bump v1.3.5 2026-08-26 17:16:16 +02:00
Yuri Karamian ce48d77cd8 fix: stop wiki links extending after autocomplete 2026-08-23 15:38:57 +02:00
Yuri Karamian 221625aabd fix: override vulnerable cookie dependency 2026-08-17 21:17:53 +02:00
Yuri Karamian 1bd4cd8138 chore: set Rust MSRV to 1.88 2026-08-17 21:15:11 +02:00
Yuri Karamian dd748776b2 test: add local verification command 2026-08-17 21:08:31 +02:00
Yuri Karamian 0391a60c1b fix: block private image proxy requests 2026-08-17 21:06:50 +02:00
Yuri Karamian 33d77cf2fd fix: restrict external file access 2026-08-17 21:02:05 +02:00
Yuri Karamian 81e4e26290 fix: restrict asset protocol to vaults 2026-08-17 20:14:34 +02:00
Yuri Karamian 111d819f92 fix: improve editor accessibility 2026-08-17 19:55:00 +02:00
Yuri Karamian c37818de1a fix: improve settings accessibility 2026-08-17 19:49:05 +02:00
Yuri Karamian 95dab8cf74 fix: improve note list accessibility 2026-08-17 19:46:50 +02:00
Yuri Karamian 62365f52b1 fix: mark resize handles presentational 2026-08-17 19:45:19 +02:00
Yuri Karamian 6eb1ec6eb2 fix: improve sidebar interactions 2026-08-17 19:44:35 +02:00
Yuri Karamian 527c6a7a91 fix: label storage location choices 2026-08-17 19:43:31 +02:00
Yuri Karamian 45e3c389e4 fix: handle info overlay clicks 2026-08-17 19:42:47 +02:00
Yuri Karamian 9ccbf3aff5 fix: make layout references reactive 2026-08-17 19:31:21 +02:00
Yuri Karamian 695664913a fix: make graph state reactive 2026-08-17 19:28:48 +02:00
Yuri Karamian d0fb87cf3a style: format Rust code 2026-08-17 19:27:05 +02:00
Yuri Karamian ac7c79af04 fix: resolve Rust lints 2026-08-17 19:24:32 +02:00
Yuri Karamian 1ebf2a9843 fix: resolve type errors 2026-08-17 19:04:21 +02:00
Yuri Karamian 44dcfbe24a fix: tighten app permissions 2026-08-17 18:57:56 +02:00
Yuri Karamian 00196ecedb fix: protect config files 2026-08-17 18:53:53 +02:00
Yuri Karamian c4d2d1b2d1 fix: validate version paths 2026-08-17 18:52:40 +02:00
Yuri Karamian 3a9a5129c4 fix: restrict backup paths 2026-08-17 18:50:57 +02:00
Yuri Karamian a964ee1930 fix: restrict vault paths 2026-08-17 18:49:32 +02:00
Yuri Karamian 2d57577338 fix: update Rust dependencies 2026-08-17 18:43:11 +02:00
Yuri Karamian 206faed113 fix: update frontend dependencies 2026-08-17 18:37:57 +02:00
Yuri Karamian b3c292d6e2 test(paths): cover cross-platform asset resolution 2026-08-17 18:35:26 +02:00
Yuri Karamian 43f15962f7 Revert "chore(release): prepare v1.3.5"
This reverts commit ade146f9f3.
2026-08-17 17:03:01 +02:00
Yuri Karamian ade146f9f3 chore(release): prepare v1.3.5 2026-08-17 16:50:14 +02:00
Yuri Karamian b253ec4121 fix(paths): preserve cross-platform asset paths 2026-08-17 15:58:20 +02:00
Yuri Karamian c4a91b8f1c fix(sorting): sort numeric names naturally 2026-08-15 16:18:22 +02:00
Yuri Karamian 87c879bcac fix(notebooks): normalize icon paths across platforms 2026-08-15 01:40:14 +02:00
Yuri Karamian 27609fb4f3 Fix Windows internal note links 2026-08-11 02:41:39 +02:00
Yuri Karamian b0555fe648 Add Clear Formatting action to editor context menu 2026-08-08 23:53:27 +02:00
Yuri Karamian 32ef51161d Scroll code block into view after fence input rule 2026-08-07 21:50:34 +02:00
Yuri Karamian 23abd0a19a Add Maintenance tab for vault statistics and cleanup 2026-08-07 17:12:15 +02:00
Yuri Karamian 5f726eb01f Move orphaned attachment cleanup from About to Settings 2026-08-07 17:01:41 +02:00
Yuri Karamian 73f7604187 Speed up note switcher and sync window scaling 2026-08-07 16:51:06 +02:00
Yuri Karamian 7ca226d918 Merge remote-tracking branch 'origin/main' 2026-08-07 01:06:32 +02:00
Yuri Karamian 1cbdf704bd Add opt-in title bar note switcher 2026-08-07 00:56:54 +02:00
Yuri Karamian b5bd5ea151 Document Linux installation options 2026-08-07 00:48:40 +02:00
Yuri Karamian bdf94e2494 Keep Note Info open across note changes 2026-08-06 15:13:43 +02:00
Yuri Karamian 1950c4cc3c Fix system theme pair integration 2026-08-06 15:12:43 +02:00
Yuri Karamian aeddcc6e58 Merge branch 'system-theme-pair' into 'main' 2026-08-06 14:07:34 +02:00
Yuri Karamian bb9d01f57c Merge branch 'custom-theme-derived-vars' into 'main' 2026-08-06 14:03:37 +02:00
Yuri Karamian ac25dfd773 Move note trash action into Note Info 2026-08-06 14:01:47 +02:00
Hadrian Chio e61c66dc26 Add light and dark theme pair for the system appearance setting 2026-08-05 09:24:06 +02:00
Hadrian Chio 3e8aa7f10d Fix custom themes falling back to light divider and tertiary text colors 2026-08-05 08:57:55 +02:00
Yuri Karamian 2dd0985ea9 Add Android image pinch zoom (Closes #115) 2026-08-03 16:56:38 +02:00
Yuri Karamian 18bb6bb702 Fix Linux startup theme flash (#195) 2026-08-03 15:54:17 +02:00
Yuri Karamian fcf48a5b7a Fix Markdown mark round-trips (#219) 2026-08-03 14:04:49 +02:00
Yuri Karamian c7906f4069 Keep source mode last in editor toolbar 2026-08-03 13:31:54 +02:00
Yuri Karamian e6e1ed1ed6 Add note duplication (#24) 2026-08-03 13:23:18 +02:00
Yuri Karamian 1a880a4f96 Add open-note trash action (#177) 2026-08-03 10:45:59 +02:00
Yuri Karamian f4e05ed9c4 Add Markdown source highlighting (#173) 2026-08-03 09:00:43 +02:00
Yuri Karamian 4a1045b41e Preserve collapsible code blocks (#138) 2026-08-03 03:26:06 +02:00
Yuri Karamian c305b5f8dd Add Android camera image capture (#131) 2026-08-03 03:13:04 +02:00
Yuri Karamian b5962af466 Add collapsible section shortcut (#129) 2026-08-03 02:56:42 +02:00
Yuri Karamian 13e83b6689 Restore note scroll positions (#127) 2026-08-03 02:43:40 +02:00
Yuri Karamian 432e4f472a Keep local tests out of repository 2026-08-03 02:31:55 +02:00
Yuri Karamian 8731ca4ec1 Support mixed nested lists (#39) 2026-08-03 02:26:39 +02:00
Yuri Karamian 6b165059cc Refine note info path and history 2026-08-03 02:03:58 +02:00
Yuri Karamian 213797a38e Fix mobile outline navigation (#109) 2026-08-03 01:53:29 +02:00
Yuri Karamian fc3e388b80 Refine custom icon size guidance 2026-08-03 01:53:25 +02:00
Yuri Karamian 1c0359e540 Add custom icon size guidance 2026-08-03 01:33:38 +02:00
Yuri Karamian da859e581b Copy active note path from Info panel 2026-08-03 01:16:30 +02:00
Yuri Karamian 763e673738 Show vault location in Info panel 2026-08-03 01:12:50 +02:00
Yuri Karamian 550d3ab3e9 Add per-notebook icons and sync 2026-08-03 01:05:07 +02:00
Yuri Karamian e62404d4c0 Fix dragging selected notes to notebooks 2026-08-03 00:27:18 +02:00
Yuri Karamian 54e051ba02 Add configurable startup view 2026-08-03 00:12:55 +02:00
Yuri Karamian 344728dbe8 Fix macOS traffic lights after window state changes
Reapply the native traffic-light alignment after resize, focus, scale, and theme events so AppKit window-state transitions cannot leave the controls at their default position.
2026-08-02 23:53:26 +02:00
Yuri Karamian 818e9ad82a Merge branch 'nix-build-fix' into 'main'
fix(nix): Update flake.lock and increment fetcher version

Closes #230

See merge request ArkHost/HelixNotes!1
2026-08-02 21:41:20 +00:00
jervw 4931ee3fab fix(nix): Update flake.lock and increment fetcher version 2026-08-02 21:41:20 +00:00
Yuri Karamian 65e09e8fdd fix(mobile): expose notebook actions 2026-07-25 17:51:33 +02:00
Yuri Karamian 64e521d549 fix(ios): poll vault changes to avoid file descriptor exhaustion 2026-07-25 17:14:42 +02:00
Yuri Karamian b8308d89e8 Update README downloads for v1.3.4 2026-07-24 22:38:47 +02:00
102 changed files with 23342 additions and 6298 deletions

No files matched your search

+44 -23
View File
@@ -1,7 +1,7 @@
# HelixNotes # HelixNotes
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](https://gitlab.com/ArkHost/HelixNotes/-/blob/main/LICENSE) [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](https://gitlab.com/ArkHost/HelixNotes/-/blob/main/LICENSE)
[![Latest Release](https://img.shields.io/badge/release-v1.3.3-green)](https://gitlab.com/ArkHost/HelixNotes/-/releases) [![Latest Release](https://img.shields.io/badge/release-v1.3.5-green)](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.5)
[![Website](https://img.shields.io/badge/web-helixnotes.com-purple)](https://helixnotes.com) [![Website](https://img.shields.io/badge/web-helixnotes.com-purple)](https://helixnotes.com)
[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20Windows%20%7C%20macOS%20%7C%20Android-lightgrey)]() [![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20Windows%20%7C%20macOS%20%7C%20Android-lightgrey)]()
@@ -10,29 +10,45 @@ A local markdown note-taking app built with Tauri, SvelteKit, and Rust.
Your notes are stored as standard Markdown files on your local filesystem. Your notes are stored as standard Markdown files on your local filesystem.
No cloud, no lock-in. No cloud, no lock-in.
## Download (v1.3.3) ## Download (v1.3.5)
### Linux ### Linux
#### Arch / Manjaro (AUR) #### AppImage
The AppImage works only on Fedora 43+, Arch Linux, and openSUSE Tumbleweed (x86_64).
[Download AppImage](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_amd64.AppImage)
#### Distro-specific packages
##### Fedora 43+ (DNF)
```bash ```bash
yay -S helixnotes-appimage-bin sudo dnf config-manager addrepo \
--from-repofile=https://repo.arkhost.com/helixnotes.repo
sudo dnf install helix-notes
``` ```
#### Debian / Ubuntu / Mint (APT) ##### Debian / Ubuntu / Mint (APT)
```bash ```bash
curl -fsSL https://repo.arkhost.com/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/arkhost.gpg && echo "deb [signed-by=/usr/share/keyrings/arkhost.gpg arch=amd64] https://repo.arkhost.com stable main" | sudo tee /etc/apt/sources.list.d/helixnotes.list && sudo apt update && sudo apt install helix-notes curl -fsSL https://repo.arkhost.com/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/arkhost.gpg && echo "deb [signed-by=/usr/share/keyrings/arkhost.gpg arch=amd64] https://repo.arkhost.com stable main" | sudo tee /etc/apt/sources.list.d/helixnotes.list && sudo apt update && sudo apt install helix-notes
``` ```
#### Solus (EOPKG) ##### Arch / Manjaro (AUR)
```bash
yay -S helixnotes-appimage-bin
```
##### Solus (EOPKG)
```bash ```bash
sudo eopkg it helixnotes sudo eopkg it helixnotes
``` ```
#### NixOS ##### NixOS
<details> <details>
<summary>flake.nix</summary> <summary>flake.nix</summary>
@@ -90,33 +106,30 @@ sudo eopkg it helixnotes
``` ```
</details> </details>
#### AppImage (Arch, Fedora 43+, openSUSE Tumbleweed) #### Manual package downloads
[Download AppImage](https://download.helixnotes.com/releases/v1.3.3/HelixNotes_1.3.3_amd64.AppImage) - [.deb](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_amd64.deb) (Ubuntu 22.04+)
- [.rpm](https://download.helixnotes.com/releases/v1.3.5/HelixNotes-1.3.5-1.x86_64.rpm)
#### .deb (manual)
[Download .deb](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.3/downloads/HelixNotes_1.3.3_amd64.deb) (Ubuntu 22.04+)
### Windows ### Windows
[Download Installer](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.3/downloads/HelixNotes_1.3.3_x64-setup.exe) (Windows 10/11) [Download Installer](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_x64-setup.exe) (Windows 10/11)
### macOS ### macOS
[Download .dmg (Apple Silicon)](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.3/downloads/HelixNotes_1.3.3_aarch64.dmg) (M-series Macs) [Download .dmg (Apple Silicon)](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_aarch64.dmg) (M-series Macs)
[Download .dmg (Intel)](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.3/downloads/HelixNotes_1.3.3_x64.dmg) (older Macs, or Apple Silicon via Rosetta) [Download .dmg (Intel)](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_x64.dmg)
> **"HelixNotes is damaged and can't be opened"?** The app isn't damaged. The macOS build isn't notarized by Apple yet, so Gatekeeper blocks it on Apple Silicon. Run this once in Terminal, then open it normally (you'll need to redo it after each update): The Apple Silicon build is signed and notarized by Apple. The Intel build may still trigger a Gatekeeper warning. If macOS reports that the Intel build is damaged, run this once after installing or updating it:
>
> ```bash ```bash
> xattr -cr /Applications/HelixNotes.app xattr -cr /Applications/HelixNotes.app
> ``` ```
### Android ### Android
[Download APK](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.3/downloads/HelixNotes_1.3.3_android.apk) [Download APK](https://download.helixnotes.com/releases/v1.3.5/HelixNotes_1.3.5_android.apk)
--- ---
@@ -155,7 +168,7 @@ Full documentation: [helixnotes.com/docs](https://helixnotes.com/docs.html)
### Prerequisites ### Prerequisites
- [Rust](https://rustup.rs/) (1.77+) - [Rust](https://rustup.rs/) (1.88+)
- [Node.js](https://nodejs.org/) (18+) - [Node.js](https://nodejs.org/) (18+)
- [pnpm](https://pnpm.io/) - [pnpm](https://pnpm.io/)
- System dependencies for Tauri: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/) - System dependencies for Tauri: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/)
@@ -167,6 +180,14 @@ pnpm install
pnpm tauri dev pnpm tauri dev
``` ```
### Verification
Run the frontend checks and tests, Rust tests and lints, and production frontend build with one command:
```bash
pnpm verify
```
### Production Build ### Production Build
```bash ```bash
Generated
+3 -3
View File
@@ -20,11 +20,11 @@
}, },
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1782959384, "lastModified": 1785571196,
"narHash": "sha256-xnJJk+ct+D2+wdRxj1wk36w5zV9RVESwRqcklPdt3fM=", "narHash": "sha256-KoTsyMQqnXQZq8deCEnu4QkyldkwH/bpMMhUcfMdGIw=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "65179426c83bb3f6bc14898b42ea1c6f01d374b0", "rev": "148bab9c1c3c53136ecb44a6ea356a0ed5b39b06",
"type": "github" "type": "github"
}, },
"original": { "original": {
+3 -3
View File
@@ -26,13 +26,13 @@
inherit pname version; inherit pname version;
src = ./.; src = ./.;
cargoHash = "sha256-oPShWgL5DjucCmQgqKbIBaxRwqyWnae52+Hj/YVIqbE="; cargoHash = "sha256-P0iXImWYKYPxVj7q2JSuDmd8JvjcKW4DzFUzXeUQZPk=C";
pnpmDeps = pkgs.fetchPnpmDeps { pnpmDeps = pkgs.fetchPnpmDeps {
inherit pname version; inherit pname version;
src = ./.; src = ./.;
fetcherVersion = 3; fetcherVersion = 4;
hash = "sha256-0TFLZY9zmRFNHPFJEiU2U8zMqSSPkeCl4bhORAbcdZY="; hash = "sha256-odUNKO2D50DG+VpuoTEo5FLMYy5pQSHQBtfHJrhJt78=";
}; };
nativeBuildInputs = with pkgs; [ nativeBuildInputs = with pkgs; [
+22 -12
View File
@@ -2,8 +2,9 @@
"name": "helixnotes", "name": "helixnotes",
"private": true, "private": true,
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"version": "1.3.4", "version": "1.3.6",
"type": "module", "type": "module",
"packageManager": "pnpm@11.18.0",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
"build": "vite build", "build": "vite build",
@@ -11,6 +12,10 @@
"prepare": "svelte-kit sync || echo ''", "prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test": "node --test tests/*.test.mjs src/lib/utils/*.test.mjs",
"test:rust": "cargo test --manifest-path src-tauri/Cargo.toml",
"lint:rust": "cargo fmt --manifest-path src-tauri/Cargo.toml --check && cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings",
"verify": "pnpm check && pnpm test && pnpm test:rust && pnpm lint:rust && pnpm build",
"tauri": "tauri", "tauri": "tauri",
"tauri:dev": "tauri dev", "tauri:dev": "tauri dev",
"tauri:build": "tauri build" "tauri:build": "tauri build"
@@ -18,31 +23,36 @@
"devDependencies": { "devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0", "@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-static": "^3.0.10", "@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.2", "@sveltejs/kit": "^2.70.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4", "@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4.3.3",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.3.3",
"@tauri-apps/cli": "^2.10.0", "@tauri-apps/cli": "^2.10.0",
"svelte": "^5.49.2", "@types/node": "26.2.0",
"svelte": "^5.56.9",
"svelte-check": "^4.3.6", "svelte-check": "^4.3.6",
"tailwindcss": "^4.1.18", "tailwindcss": "^4.3.3",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.3.1" "vite": "^7.3.6"
}, },
"dependencies": { "dependencies": {
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.12.4",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.4",
"@tauri-apps/api": "^2.10.1", "@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.6.0", "@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-fs": "^2.4.5", "@tauri-apps/plugin-fs": "^2.4.5",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-updater": "^2.10.0", "@tauri-apps/plugin-updater": "^2.10.0",
"@tiptap/core": "^3.19.0", "@tiptap/core": "^3.19.0",
"@tiptap/extension-code-block-lowlight": "^3.19.0", "@tiptap/extension-code-block": "^3.19.0",
"@tiptap/extension-color": "^3.19.0", "@tiptap/extension-color": "^3.19.0",
"@tiptap/extension-details": "^3.19.0", "@tiptap/extension-details": "^3.19.0",
"@tiptap/extension-highlight": "^3.19.0", "@tiptap/extension-highlight": "^3.19.0",
"@tiptap/extension-image": "^3.19.0", "@tiptap/extension-image": "^3.19.0",
"@tiptap/extension-link": "^3.19.0", "@tiptap/extension-link": "^3.19.0",
"@tiptap/extension-placeholder": "^3.19.0",
"@tiptap/extension-subscript": "^3.19.0", "@tiptap/extension-subscript": "^3.19.0",
"@tiptap/extension-superscript": "^3.19.0", "@tiptap/extension-superscript": "^3.19.0",
"@tiptap/extension-table": "^3.19.0", "@tiptap/extension-table": "^3.19.0",
@@ -62,11 +72,11 @@
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"katex": "^0.16.28", "katex": "^0.16.28",
"lowlight": "^3.3.0", "lowlight": "^3.3.0",
"markdown-it": "^14.1.0", "markdown-it": "^14.3.0",
"markdown-it-mark": "^4.0.0", "markdown-it-mark": "^4.0.0",
"markdown-it-sub": "^2.0.0", "markdown-it-sub": "^2.0.0",
"markdown-it-sup": "^2.0.0", "markdown-it-sup": "^2.0.0",
"markdown-it-task-lists": "^2.1.1", "markdown-it-task-lists": "^2.1.1",
"mermaid": "^11.14.0" "mermaid": "^11.16.1"
} }
} }
+782 -713
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
allowBuilds:
esbuild: true
overrides:
cookie: 0.7.2
+73 -276
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "adler2" name = "adler2"
@@ -8,17 +8,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "ahash"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
dependencies = [
"getrandom 0.2.17",
"once_cell",
"version_check",
]
[[package]] [[package]]
name = "ahash" name = "ahash"
version = "0.8.12" version = "0.8.12"
@@ -138,12 +127,6 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]] [[package]]
name = "async-broadcast" name = "async-broadcast"
version = "0.7.2" version = "0.7.2"
@@ -346,18 +329,6 @@ dependencies = [
"crunchy", "crunchy",
] ]
[[package]]
name = "bitvec"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c"
dependencies = [
"funty",
"radium",
"tap",
"wyz",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.4" version = "0.10.4"
@@ -389,29 +360,6 @@ dependencies = [
"piper", "piper",
] ]
[[package]]
name = "borsh"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f"
dependencies = [
"borsh-derive",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0686c856aa6aac0c4498f936d7d6a02df690f614c03e4d906d1018062b5c5e2c"
dependencies = [
"once_cell",
"proc-macro-crate 3.4.0",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]] [[package]]
name = "brotli" name = "brotli"
version = "8.0.2" version = "8.0.2"
@@ -439,40 +387,6 @@ version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "byte-unit"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c6d47a4e2961fb8721bcfc54feae6455f2f64e7054f9bc67e875f0e77f4c58d"
dependencies = [
"rust_decimal",
"schemars 1.2.1",
"serde",
"utf8-width",
]
[[package]]
name = "bytecheck"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2"
dependencies = [
"bytecheck_derive",
"ptr_meta",
"simdutf8",
]
[[package]]
name = "bytecheck_derive"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "bytemuck" name = "bytemuck"
version = "1.25.0" version = "1.25.0"
@@ -624,6 +538,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chacha20"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
"rand_core 0.10.1",
]
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.44" version = "0.4.44"
@@ -738,6 +663,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "cpufeatures"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.5.0" version = "1.5.0"
@@ -768,9 +702,9 @@ dependencies = [
[[package]] [[package]]
name = "crossbeam-epoch" name = "crossbeam-epoch"
version = "0.9.18" version = "0.9.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
dependencies = [ dependencies = [
"crossbeam-utils", "crossbeam-utils",
] ]
@@ -1314,12 +1248,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "funty"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]] [[package]]
name = "futf" name = "futf"
version = "0.1.5" version = "0.1.5"
@@ -1590,11 +1518,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi", "r-efi",
"wasip2", "wasip2",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1604,10 +1530,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"r-efi", "r-efi",
"rand_core 0.10.1",
"wasip2", "wasip2",
"wasip3", "wasip3",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -1796,9 +1725,6 @@ name = "hashbrown"
version = "0.12.3" version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash 0.7.8",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
@@ -1806,7 +1732,7 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [ dependencies = [
"ahash 0.8.12", "ahash",
"allocator-api2", "allocator-api2",
] ]
@@ -1850,19 +1776,23 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "helixnotes" name = "helixnotes"
version = "1.3.4" version = "1.3.6"
dependencies = [ dependencies = [
"aho-corasick",
"arboard", "arboard",
"chrono", "chrono",
"dirs", "dirs",
"fs4",
"futures", "futures",
"gray_matter", "gray_matter",
"image", "image",
"libc",
"log", "log",
"notify", "notify",
"objc2-app-kit", "objc2-app-kit",
"parking_lot",
"png 0.17.16", "png 0.17.16",
"quick-xml 0.36.2", "quick-xml",
"rayon", "rayon",
"regex", "regex",
"reqwest 0.12.28", "reqwest 0.12.28",
@@ -1883,6 +1813,7 @@ dependencies = [
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"tauri-plugin-window-state", "tauri-plugin-window-state",
"tempfile",
"tokio", "tokio",
"urlencoding", "urlencoding",
"uuid", "uuid",
@@ -2554,9 +2485,6 @@ name = "log"
version = "0.4.29" version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
dependencies = [
"value-bag",
]
[[package]] [[package]]
name = "lru" name = "lru"
@@ -2575,9 +2503,9 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]] [[package]]
name = "lz4_flex" name = "lz4_flex"
version = "0.11.5" version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08ab2867e3eeeca90e844d1940eab391c9dc5228783db2ed999acbc0a9ed375a" checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"
[[package]] [[package]]
name = "mac" name = "mac"
@@ -3417,13 +3345,13 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]] [[package]]
name = "plist" name = "plist"
version = "1.8.0" version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"indexmap 2.13.0", "indexmap 2.13.0",
"quick-xml 0.38.4", "quick-xml",
"serde", "serde",
"time", "time",
] ]
@@ -3576,26 +3504,6 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "ptr_meta"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "pure-rust-locales" name = "pure-rust-locales"
version = "0.8.2" version = "0.8.2"
@@ -3619,18 +3527,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]] [[package]]
name = "quick-xml" name = "quick-xml"
version = "0.36.2" version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe" checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.38.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@@ -3657,14 +3556,15 @@ dependencies = [
[[package]] [[package]]
name = "quinn-proto" name = "quinn-proto"
version = "0.11.13" version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"
dependencies = [ dependencies = [
"bytes", "bytes",
"getrandom 0.3.4", "getrandom 0.4.1",
"lru-slab", "lru-slab",
"rand 0.9.2", "rand 0.10.2",
"rand_pcg 0.10.2",
"ring", "ring",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
"rustls", "rustls",
@@ -3705,12 +3605,6 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "radium"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
[[package]] [[package]]
name = "rand" name = "rand"
version = "0.7.3" version = "0.7.3"
@@ -3722,7 +3616,7 @@ dependencies = [
"rand_chacha 0.2.2", "rand_chacha 0.2.2",
"rand_core 0.5.1", "rand_core 0.5.1",
"rand_hc", "rand_hc",
"rand_pcg", "rand_pcg 0.2.1",
] ]
[[package]] [[package]]
@@ -3738,12 +3632,13 @@ dependencies = [
[[package]] [[package]]
name = "rand" name = "rand"
version = "0.9.2" version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [ dependencies = [
"rand_chacha 0.9.0", "chacha20",
"rand_core 0.9.5", "getrandom 0.4.1",
"rand_core 0.10.1",
] ]
[[package]] [[package]]
@@ -3766,16 +3661,6 @@ dependencies = [
"rand_core 0.6.4", "rand_core 0.6.4",
] ]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.5.1" version = "0.5.1"
@@ -3796,12 +3681,9 @@ dependencies = [
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.9.5" version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
dependencies = [
"getrandom 0.3.4",
]
[[package]] [[package]]
name = "rand_distr" name = "rand_distr"
@@ -3831,6 +3713,15 @@ dependencies = [
"rand_core 0.5.1", "rand_core 0.5.1",
] ]
[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
"rand_core 0.10.1",
]
[[package]] [[package]]
name = "raw-window-handle" name = "raw-window-handle"
version = "0.6.2" version = "0.6.2"
@@ -3935,15 +3826,6 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rend"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c"
dependencies = [
"bytecheck",
]
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.12.28" version = "0.12.28"
@@ -4063,35 +3945,6 @@ dependencies = [
"windows-sys 0.52.0", "windows-sys 0.52.0",
] ]
[[package]]
name = "rkyv"
version = "0.7.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1"
dependencies = [
"bitvec",
"bytecheck",
"bytes",
"hashbrown 0.12.3",
"ptr_meta",
"rend",
"rkyv_derive",
"seahash",
"tinyvec",
"uuid",
]
[[package]]
name = "rkyv_derive"
version = "0.7.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "rust-stemmers" name = "rust-stemmers"
version = "1.2.0" version = "1.2.0"
@@ -4102,22 +3955,6 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "rust_decimal"
version = "1.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61f703d19852dbf87cbc513643fa81428361eb6940f1ac14fd58155d295a3eb0"
dependencies = [
"arrayvec",
"borsh",
"bytes",
"num-traits",
"rand 0.8.5",
"rkyv",
"serde",
"serde_json",
]
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "1.1.0" version = "1.1.0"
@@ -4231,9 +4068,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]] [[package]]
name = "rustls-webpki" name = "rustls-webpki"
version = "0.103.9" version = "0.103.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a"
dependencies = [ dependencies = [
"ring", "ring",
"rustls-pki-types", "rustls-pki-types",
@@ -4327,12 +4164,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "seahash"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]] [[package]]
name = "security-framework" name = "security-framework"
version = "3.7.0" version = "3.7.0"
@@ -4574,7 +4405,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures", "cpufeatures 0.2.17",
"digest", "digest",
] ]
@@ -4600,12 +4431,6 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "0.3.11" version = "0.3.11"
@@ -5007,17 +4832,11 @@ dependencies = [
"syn 2.0.117", "syn 2.0.117",
] ]
[[package]]
name = "tap"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]] [[package]]
name = "tar" name = "tar"
version = "0.4.44" version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [ dependencies = [
"filetime", "filetime",
"libc", "libc",
@@ -5214,12 +5033,11 @@ dependencies = [
[[package]] [[package]]
name = "tauri-plugin-log" name = "tauri-plugin-log"
version = "2.8.0" version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7545bd67f070a4500432c826e2e0682146a1d6712aee22a2786490156b574d93" checksum = "6792296e6f389268016c77db21ebae1fc0568f2fccf88b1ec7e2ea71330afb4c"
dependencies = [ dependencies = [
"android_logger", "android_logger",
"byte-unit",
"fern", "fern",
"log", "log",
"objc2", "objc2",
@@ -5964,12 +5782,6 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba"
[[package]]
name = "utf8-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1292c0d970b54115d14f2492fe0170adf21d68a1de108eebc51c1df4f346a091"
[[package]] [[package]]
name = "utf8_iter" name = "utf8_iter"
version = "1.0.4" version = "1.0.4"
@@ -5988,12 +5800,6 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "value-bag"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
[[package]] [[package]]
name = "version-compare" name = "version-compare"
version = "0.2.1" version = "0.2.1"
@@ -6246,12 +6052,12 @@ dependencies = [
[[package]] [[package]]
name = "wayland-scanner" name = "wayland-scanner"
version = "0.31.8" version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5423e94b6a63e68e439803a3e153a9252d5ead12fd853334e2ad33997e3889e3" checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quick-xml 0.38.4", "quick-xml",
"quote", "quote",
] ]
@@ -7007,15 +6813,6 @@ dependencies = [
"x11-dl", "x11-dl",
] ]
[[package]]
name = "wyz"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
dependencies = [
"tap",
]
[[package]] [[package]]
name = "x11" name = "x11"
version = "2.21.0" version = "2.21.0"
+17 -3
View File
@@ -1,11 +1,15 @@
[package] [package]
name = "helixnotes" name = "helixnotes"
version = "1.3.4" version = "1.3.6"
description = "Local markdown note-taking app" description = "Local markdown note-taking app"
authors = ["HelixNotes"] authors = ["HelixNotes"]
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
edition = "2021" edition = "2021"
rust-version = "1.77.2" rust-version = "1.88"
[lints.clippy]
# This style lint is version-dependent and produces over 100 legacy-only diagnostics on Rust 1.88.
uninlined_format_args = "allow"
[lib] [lib]
name = "app_lib" name = "app_lib"
@@ -14,6 +18,9 @@ crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies] [build-dependencies]
tauri-build = { version = "2", features = [] } tauri-build = { version = "2", features = [] }
[dev-dependencies]
tauri = { version = "2", features = ["test"] }
[dependencies] [dependencies]
tauri = { version = "2", features = ["protocol-asset", "tray-icon", "image-png"] } tauri = { version = "2", features = ["protocol-asset", "tray-icon", "image-png"] }
tauri-plugin-log = "2" tauri-plugin-log = "2"
@@ -25,7 +32,9 @@ serde_json = "1"
serde_yaml = "0.9" serde_yaml = "0.9"
log = "0.4" log = "0.4"
notify = "8" notify = "8"
parking_lot = "0.12"
walkdir = "2" walkdir = "2"
tempfile = "3"
chrono = { version = "0.4", features = ["serde", "unstable-locales"] } chrono = { version = "0.4", features = ["serde", "unstable-locales"] }
sys-locale = "0.3" sys-locale = "0.3"
uuid = { version = "1", features = ["v4"] } uuid = { version = "1", features = ["v4"] }
@@ -34,17 +43,22 @@ gray_matter = "0.2"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
dirs = "6" dirs = "6"
regex = "1" regex = "1"
aho-corasick = "1"
zip = { version = "2", default-features = false, features = ["deflate"] } zip = { version = "2", default-features = false, features = ["deflate"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "blocking"] } reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "blocking"] }
futures = "0.3" futures = "0.3"
rayon = "1" rayon = "1"
quick-xml = "0.36" quick-xml = "0.41"
urlencoding = "2" urlencoding = "2"
sha2 = "0.10" sha2 = "0.10"
fs4 = { version = "0.8", default-features = false }
rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] } rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
objc2-app-kit = "0.3.2" objc2-app-kit = "0.3.2"
[target.'cfg(target_os = "android")'.dependencies]
libc = "0.2"
[target.'cfg(target_os = "ios")'.dependencies] [target.'cfg(target_os = "ios")'.dependencies]
tauri-plugin-ios-vault-access = { path = "plugins/ios-vault-access" } tauri-plugin-ios-vault-access = { path = "plugins/ios-vault-access" }
+2 -27
View File
@@ -11,6 +11,7 @@
"core:window:allow-minimize", "core:window:allow-minimize",
"core:window:allow-toggle-maximize", "core:window:allow-toggle-maximize",
"core:window:allow-close", "core:window:allow-close",
"core:window:allow-show",
"core:window:allow-is-maximized", "core:window:allow-is-maximized",
"core:window:allow-set-decorations", "core:window:allow-set-decorations",
"core:window:allow-is-fullscreen", "core:window:allow-is-fullscreen",
@@ -23,32 +24,6 @@
"dialog:allow-message", "dialog:allow-message",
"dialog:allow-ask", "dialog:allow-ask",
"dialog:allow-confirm", "dialog:allow-confirm",
"fs:default", "fs:allow-read-file"
"fs:allow-read",
"fs:allow-write",
"fs:allow-exists",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-copy-file",
"fs:allow-stat",
"fs:allow-read-dir",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-watch",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "/**" }]
},
{
"identifier": "opener:allow-open-url",
"allow": [
{ "url": "https://**" },
{ "url": "http://**" },
{ "url": "mailto:*" }
]
},
"opener:allow-reveal-item-in-dir"
] ]
} }
@@ -35,6 +35,16 @@ class MainActivity : TauriActivity() {
webView.settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.NORMAL webView.settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.NORMAL
} }
override fun onPause() {
// Give the editor a chance to persist its current document before Android
// suspends the WebView. The save remains best-effort when the process is killed.
webView?.evaluateJavascript(
"window.dispatchEvent(new Event('app-lifecycle-flush'))",
null
)
super.onPause()
}
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
if (hasStoragePermission()) { if (hasStoragePermission()) {
+95 -51
View File
@@ -8,6 +8,7 @@ const ANTHROPIC_API_URL: &str = "https://api.anthropic.com/v1/messages";
const OPENAI_API_URL: &str = "https://api.openai.com/v1/chat/completions"; const OPENAI_API_URL: &str = "https://api.openai.com/v1/chat/completions";
const OLLAMA_DEFAULT_URL: &str = "http://localhost:11434"; const OLLAMA_DEFAULT_URL: &str = "http://localhost:11434";
#[allow(clippy::too_many_arguments)]
pub fn ai_request( pub fn ai_request(
app: AppHandle, app: AppHandle,
provider: String, provider: String,
@@ -22,7 +23,11 @@ pub fn ai_request(
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { rt.block_on(async {
// Handle all API keys as optional; ollama and v1 completions doesnt always require it. // Handle all API keys as optional; ollama and v1 completions doesnt always require it.
let key_opt = if api_key.is_empty() { None } else { Some(api_key.as_str()) }; let key_opt = if api_key.is_empty() {
None
} else {
Some(api_key.as_str())
};
let result = match provider.as_str() { let result = match provider.as_str() {
"openai" => { "openai" => {
stream_openai( stream_openai(
@@ -84,6 +89,7 @@ pub fn ai_request(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.clone(),
event_type: "error".to_string(), event_type: "error".to_string(),
text: None, text: None,
error: Some(e), error: Some(e),
@@ -98,7 +104,37 @@ pub fn ai_request(
/// so both `https://host` and `https://host/v1` work (we append `/v1/chat/completions`). /// so both `https://host` and `https://host/v1` work (we append `/v1/chat/completions`).
fn normalize_openai_base(base: &str) -> String { fn normalize_openai_base(base: &str) -> String {
let b = base.trim().trim_end_matches('/'); let b = base.trim().trim_end_matches('/');
b.strip_suffix("/v1").unwrap_or(b).trim_end_matches('/').to_string() b.strip_suffix("/v1")
.unwrap_or(b)
.trim_end_matches('/')
.to_string()
}
fn openai_request_body(
model: &str,
system_prompt: Option<&str>,
user_message: &str,
stream: bool,
max_tokens: u32,
) -> serde_json::Value {
// GPT-5/6 reject legacy output limits and sampling with their default reasoning.
let reasoning = model.starts_with("gpt-5") || model.starts_with("gpt-6");
let token_key = if reasoning {
"max_completion_tokens"
} else {
"max_tokens"
};
let mut messages = Vec::with_capacity(if system_prompt.is_some() { 2 } else { 1 });
if let Some(system) = system_prompt {
messages.push(json!({ "role": "system", "content": system }));
}
messages.push(json!({ "role": "user", "content": user_message }));
let mut body =
json!({ "model": model, "stream": stream, token_key: max_tokens, "messages": messages });
if stream && !reasoning {
body["temperature"] = json!(0.7);
}
body
} }
async fn stream_anthropic( async fn stream_anthropic(
@@ -107,7 +143,7 @@ async fn stream_anthropic(
model: &str, model: &str,
system_prompt: &str, system_prompt: &str,
user_message: &str, user_message: &str,
_request_id: &str, request_id: &str,
) -> Result<(), String> { ) -> Result<(), String> {
let client = Client::new(); let client = Client::new();
@@ -160,6 +196,7 @@ async fn stream_anthropic(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -177,6 +214,7 @@ async fn stream_anthropic(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "text".to_string(), event_type: "text".to_string(),
text: Some(text.to_string()), text: Some(text.to_string()),
error: None, error: None,
@@ -188,6 +226,7 @@ async fn stream_anthropic(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -202,6 +241,7 @@ async fn stream_anthropic(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "error".to_string(), event_type: "error".to_string(),
text: None, text: None,
error: Some(msg.to_string()), error: Some(msg.to_string()),
@@ -220,6 +260,7 @@ async fn stream_anthropic(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -236,41 +277,13 @@ async fn stream_openai(
model: &str, model: &str,
system_prompt: &str, system_prompt: &str,
user_message: &str, user_message: &str,
_request_id: &str, request_id: &str,
) -> Result<(), String> { ) -> Result<(), String> {
let client = Client::new(); let client = Client::new();
let is_gpt5 = model.starts_with("gpt-5"); let body = openai_request_body(model, Some(system_prompt), user_message, true, 4096);
let token_key = if is_gpt5 {
"max_completion_tokens"
} else {
"max_tokens"
};
let mut body = json!({ let mut req = client.post(url).header("content-type", "application/json");
"model": model,
"stream": true,
token_key: 4096,
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": user_message
}
]
});
// GPT-5 models don't support temperature
if !is_gpt5 {
body["temperature"] = json!(0.7);
}
let mut req = client
.post(url)
.header("content-type", "application/json");
if let Some(key) = api_key { if let Some(key) = api_key {
req = req.header("Authorization", format!("Bearer {}", key)); req = req.header("Authorization", format!("Bearer {}", key));
@@ -306,6 +319,7 @@ async fn stream_openai(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -321,6 +335,7 @@ async fn stream_openai(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "text".to_string(), event_type: "text".to_string(),
text: Some(content.to_string()), text: Some(content.to_string()),
error: None, error: None,
@@ -335,6 +350,7 @@ async fn stream_openai(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -349,6 +365,7 @@ async fn stream_openai(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "error".to_string(), event_type: "error".to_string(),
text: None, text: None,
error: Some(err.to_string()), error: Some(err.to_string()),
@@ -365,6 +382,7 @@ async fn stream_openai(
let _ = app.emit( let _ = app.emit(
"ai-stream", "ai-stream",
AiStreamEvent { AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(), event_type: "done".to_string(),
text: None, text: None,
error: None, error: None,
@@ -380,7 +398,11 @@ pub async fn test_connection(
model: &str, model: &str,
base_url: Option<&str>, base_url: Option<&str>,
) -> Result<String, String> { ) -> Result<String, String> {
let key_opt = if api_key.is_empty() { None } else { Some(api_key) }; let key_opt = if api_key.is_empty() {
None
} else {
Some(api_key)
};
match provider { match provider {
"openai" => test_openai(OPENAI_API_URL, Some(api_key), model).await, "openai" => test_openai(OPENAI_API_URL, Some(api_key), model).await,
"ollama" => { "ollama" => {
@@ -435,23 +457,9 @@ async fn test_anthropic(api_key: &str, model: &str) -> Result<String, String> {
async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<String, String> { async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<String, String> {
let client = Client::new(); let client = Client::new();
let is_gpt5 = model.starts_with("gpt-5"); let body = openai_request_body(model, None, "Hi", false, 20);
let token_key = if is_gpt5 { "max_completion_tokens" } else { "max_tokens" };
let body = json!({ let mut req = client.post(url).header("content-type", "application/json");
"model": model,
token_key: 20,
"messages": [
{
"role": "user",
"content": "Hi"
}
]
});
let mut req = client
.post(url)
.header("content-type", "application/json");
if let Some(key) = api_key { if let Some(key) = api_key {
req = req.header("Authorization", format!("Bearer {}", key)); req = req.header("Authorization", format!("Bearer {}", key));
@@ -471,3 +479,39 @@ async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<St
Err(format!("API error {}: {}", status, body_text)) Err(format!("API error {}: {}", status, body_text))
} }
} }
#[cfg(test)]
mod request_tests {
use super::*;
#[test]
fn gpt6_streaming_requests_use_supported_parameters() {
let body = openai_request_body(
"gpt-6-astra",
Some("Return Markdown"),
"Revise this",
true,
4096,
);
assert_eq!(body["max_completion_tokens"], 4096);
assert!(body.get("max_tokens").is_none());
assert!(body.get("temperature").is_none());
}
#[test]
fn prior_openai_and_local_models_keep_their_parameter_contract() {
let prior = openai_request_body("gpt-5.5", None, "Hi", false, 20);
assert!(prior.get("max_completion_tokens").is_some());
assert!(prior.get("max_tokens").is_none());
let local = openai_request_body(
"gemma3:4b",
Some("Return Markdown"),
"Revise this",
true,
4096,
);
assert_eq!(local["max_tokens"], 4096);
assert_eq!(local["temperature"], 0.7);
assert!(local.get("max_completion_tokens").is_none());
}
}
+111
View File
@@ -0,0 +1,111 @@
use std::path::Path;
use tauri::{AppHandle, Manager, Runtime};
/// Grants asset-protocol access only to a vault selected by the user.
/// `.helixnotes` is added explicitly because Unix glob matching excludes hidden paths.
pub fn allow_vault_assets<R: Runtime>(app: &AppHandle<R>, vault_path: &Path) -> Result<(), String> {
// Keep the canonical native path: Tauri's scope normalizes Unix paths plus
// Windows drive, verbatim, and UNC prefixes when matching asset requests.
let vault = std::fs::canonicalize(vault_path).map_err(|error| {
format!(
"Failed to resolve vault asset path '{}': {error}",
vault_path.display()
)
})?;
let scope = app.asset_protocol_scope();
scope
.allow_directory(&vault, true)
.map_err(|error| error.to_string())?;
scope
.allow_directory(vault.join(".helixnotes"), true)
.map_err(|error| error.to_string())
}
/// Grants access to relative assets next to a Markdown file explicitly opened by the user.
pub fn allow_external_note_assets<R: Runtime>(
app: &AppHandle<R>,
note_path: &Path,
) -> Result<(), String> {
let note = std::fs::canonicalize(note_path).map_err(|error| {
format!(
"Failed to resolve external note path '{}': {error}",
note_path.display()
)
})?;
let parent = note
.parent()
.ok_or_else(|| "External note has no parent directory".to_string())?;
app.asset_protocol_scope()
.allow_directory(parent, true)
.map_err(|error| error.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn test_directory(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("helixnotes-{name}-{}", uuid::Uuid::new_v4()))
}
#[test]
fn static_asset_scope_does_not_expose_the_filesystem() {
let config: serde_json::Value =
serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
let scope = &config["app"]["security"]["assetProtocol"]["scope"];
assert_eq!(scope["allow"], serde_json::json!([]));
assert_eq!(scope["deny"], serde_json::json!([]));
assert_eq!(scope["requireLiteralLeadingDot"], true);
}
#[test]
fn runtime_scope_allows_only_the_selected_vault() {
let root = test_directory("asset-scope");
let vault = root.join("Vault [Cross Platform]");
let attachments = vault.join(".helixnotes").join("attachments");
fs::create_dir_all(&attachments).unwrap();
let note_image = vault.join("images").join("note image.png");
fs::create_dir_all(note_image.parent().unwrap()).unwrap();
fs::write(&note_image, b"image").unwrap();
let attachment = attachments.join("attachment.png");
fs::write(&attachment, b"attachment").unwrap();
let outside = root.join("outside.png");
fs::write(&outside, b"outside").unwrap();
let app = tauri::test::mock_app();
allow_vault_assets(app.handle(), &vault).unwrap();
let scope = app.asset_protocol_scope();
assert!(scope.is_allowed(&note_image));
assert!(scope.is_allowed(&attachment));
assert!(!scope.is_allowed(&outside));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn external_note_scope_allows_relative_assets_only_below_its_directory() {
let root = test_directory("external-note-assets");
let note_dir = root.join("shared note");
let assets = note_dir.join("images");
fs::create_dir_all(&assets).unwrap();
let note = note_dir.join("note.md");
let image = assets.join("image.png");
let outside = root.join("outside.png");
fs::write(&note, b"note").unwrap();
fs::write(&image, b"image").unwrap();
fs::write(&outside, b"outside").unwrap();
let app = tauri::test::mock_app();
allow_external_note_assets(app.handle(), &note).unwrap();
let scope = app.asset_protocol_scope();
assert!(scope.is_allowed(&note));
assert!(scope.is_allowed(&image));
assert!(!scope.is_allowed(&outside));
fs::remove_dir_all(root).unwrap();
}
}
+993 -165
View File
File diff suppressed because it is too large. Load diff
+2750 -615
View File
File diff suppressed because it is too large. Load diff
+193 -72
View File
@@ -1,48 +1,122 @@
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use crate::types::VersionEntry; use crate::types::VersionEntry;
fn safe_path_component<'a>(value: &'a str, label: &str) -> Result<&'a str, String> {
let mut components = Path::new(value).components();
if value.is_empty()
|| !matches!(components.next(), Some(Component::Normal(_)))
|| components.next().is_some()
{
return Err(format!("Invalid {label}"));
}
Ok(value)
}
/// Directory: .helixnotes/history/<note-id>/ /// Directory: .helixnotes/history/<note-id>/
fn history_dir(vault_path: &str, note_id: &str) -> PathBuf { fn history_dir(vault_path: &str, note_id: &str) -> Result<PathBuf, String> {
Path::new(vault_path) Ok(Path::new(vault_path)
.join(".helixnotes") .join(".helixnotes")
.join("history") .join("history")
.join(note_id) .join(safe_path_component(note_id, "note ID")?))
}
fn snapshot_path(dir: &Path, raw_content: &str) -> Result<(), String> {
use std::io::Write;
let mut temporary = tempfile::Builder::new()
.prefix(".helixnotes-history-")
.tempfile_in(dir)
.map_err(|error| error.to_string())?;
temporary
.write_all(raw_content.as_bytes())
.map_err(|error| error.to_string())?;
temporary
.as_file()
.sync_all()
.map_err(|error| error.to_string())?;
let mut instant = Utc::now();
loop {
// Fractional seconds keep timestamps valid RFC3339 for the UI while
// allowing multiple versions within one second.
let timestamp = instant.format("%Y-%m-%dT%H-%M-%S%.3f");
let path = dir.join(format!("{timestamp}.md"));
match temporary.persist_noclobber(&path) {
Ok(_) => return Ok(()),
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => {
temporary = error.file;
instant += chrono::Duration::milliseconds(1);
}
Err(error) => return Err(error.error.to_string()),
}
}
}
fn version_timestamp(filename: &str) -> String {
match (filename.get(..13), filename.get(14..16), filename.get(17..)) {
(Some(hour), Some(minute), Some(rest))
if filename.as_bytes().get(10) == Some(&b'T')
&& filename.as_bytes().get(13) == Some(&b'-')
&& filename.as_bytes().get(16) == Some(&b'-') =>
{
format!("{hour}:{minute}:{rest}Z")
}
_ => filename.to_string(),
}
}
fn snapshot_filename(timestamp: &str) -> String {
let time = timestamp.strip_suffix('Z').unwrap_or(timestamp);
match (time.get(..13), time.get(14..16), time.get(17..)) {
(Some(hour), Some(minute), Some(rest))
if time.as_bytes().get(10) == Some(&b'T')
&& time.as_bytes().get(13) == Some(&b':')
&& time.as_bytes().get(16) == Some(&b':') =>
{
format!("{hour}-{minute}-{rest}.md")
}
_ => format!("{timestamp}.md"),
}
} }
/// Save a version snapshot if enough time has passed since the last one. /// Save a version snapshot if enough time has passed since the last one.
/// Minimum interval: 5 minutes between snapshots. /// Minimum interval: 5 minutes between snapshots.
pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) { pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) {
let dir = history_dir(vault_path, note_id); let Ok(dir) = history_dir(vault_path, note_id) else {
log::warn!("Skipping history snapshot with an invalid note ID");
return;
};
// Check if we should create a snapshot (5 min cooldown) // Old second-resolution and new fractional-second names share the first
// 19 ASCII bytes. Ignore arbitrary files (including malformed Unicode).
if let Ok(entries) = fs::read_dir(&dir) { if let Ok(entries) = fs::read_dir(&dir) {
let mut files: Vec<String> = entries let latest = entries
.filter_map(|e| e.ok()) .filter_map(|entry| {
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string())) let name = entry.ok()?.file_name();
.filter(|n| n.ends_with(".md")) let name = name.to_str()?;
.collect(); if !name.ends_with(".md") {
files.sort(); return None;
if let Some(last) = files.last() {
if let Some(ts) = last.strip_suffix(".md") {
// Parse timestamp: 2026-02-08T18-30-00.md
if let Some(t_pos) = ts.find('T') {
let date_part = &ts[..t_pos];
let time_part = &ts[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
let iso = format!("{}T{}Z", date_part, time_colons);
if let Ok(last_time) = iso.parse::<DateTime<Utc>>() {
let elapsed = Utc::now() - last_time;
if elapsed.num_minutes() < 5 {
return; // Too soon, skip
}
}
} }
let (Some(hour), Some(minute), Some(second)) =
(name.get(..13), name.get(14..16), name.get(17..19))
else {
return None;
};
if name.as_bytes().get(10) != Some(&b'T')
|| name.as_bytes().get(13) != Some(&b'-')
|| name.as_bytes().get(16) != Some(&b'-')
{
return None;
} }
format!("{hour}:{minute}:{second}Z")
.parse::<DateTime<Utc>>()
.ok()
})
.max();
if latest.is_some_and(|last| (Utc::now() - last).num_minutes() < 5) {
return;
} }
} }
@@ -52,12 +126,8 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
return; return;
} }
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string(); if let Err(error) = snapshot_path(&dir, raw_content) {
let filename = format!("{}.md", timestamp); eprintln!("Failed to write version snapshot: {error}");
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
return; return;
} }
@@ -68,31 +138,26 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
} }
/// Force-create a version snapshot, bypassing the cooldown. /// Force-create a version snapshot, bypassing the cooldown.
pub fn force_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) { pub fn force_snapshot(
let dir = history_dir(vault_path, note_id); vault_path: &str,
note_id: &str,
raw_content: &str,
max_versions: u32,
) -> Result<(), String> {
let dir = history_dir(vault_path, note_id)?;
fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
if let Err(e) = fs::create_dir_all(&dir) { snapshot_path(&dir, raw_content)?;
eprintln!("Failed to create history dir: {}", e);
return;
}
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("{}.md", timestamp);
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
return;
}
if max_versions > 0 { if max_versions > 0 {
let _ = prune_versions(&dir, max_versions); prune_versions(&dir, max_versions)?;
} }
Ok(())
} }
/// List all version snapshots for a note, newest first. /// List all version snapshots for a note, newest first.
pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry>, String> { pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry>, String> {
let dir = history_dir(vault_path, note_id); let dir = history_dir(vault_path, note_id)?;
if !dir.exists() { if !dir.exists() {
return Ok(Vec::new()); return Ok(Vec::new());
} }
@@ -102,7 +167,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
for entry in fs::read_dir(&dir).map_err(|e| e.to_string())? { for entry in fs::read_dir(&dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?; let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path(); let path = entry.path();
if path.extension().map_or(false, |ext| ext == "md") { if path.extension().is_some_and(|ext| ext == "md") {
let filename = path let filename = path
.file_stem() .file_stem()
.unwrap_or_default() .unwrap_or_default()
@@ -110,16 +175,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
.to_string(); .to_string();
let meta = fs::metadata(&path).map_err(|e| e.to_string())?; let meta = fs::metadata(&path).map_err(|e| e.to_string())?;
// Parse timestamp from filename let timestamp = version_timestamp(&filename);
let timestamp = if let Some(t_pos) = filename.find('T') {
let date_part = &filename[..t_pos];
let time_part = &filename[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
format!("{}T{}Z", date_part, time_colons)
} else {
filename.clone()
};
entries.push(VersionEntry { entries.push(VersionEntry {
timestamp, timestamp,
size: meta.len(), size: meta.len(),
@@ -134,17 +190,11 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
/// Get the raw content of a specific version. /// Get the raw content of a specific version.
pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<String, String> { pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<String, String> {
// Convert ISO timestamp back to filename: 2026-02-08T18:30:00Z → 2026-02-08T18-30-00.md safe_path_component(timestamp, "version timestamp")?;
let filename = if let Some(t_pos) = timestamp.find('T') { // Accept both legacy second-resolution names and unique suffixes.
let date_part = &timestamp[..t_pos]; let filename = snapshot_filename(timestamp);
let time_part = timestamp[t_pos + 1..].trim_end_matches('Z');
let time_dashes = time_part.replace(':', "-");
format!("{}.md", format!("{}T{}", date_part, time_dashes))
} else {
format!("{}.md", timestamp)
};
let path = history_dir(vault_path, note_id).join(&filename); let path = history_dir(vault_path, note_id)?.join(&filename);
fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e)) fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e))
} }
@@ -154,7 +204,7 @@ fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
.filter_map(|e| e.ok()) .filter_map(|e| e.ok())
.map(|e| e.path()) .map(|e| e.path())
.filter(|p| p.extension().map_or(false, |ext| ext == "md")) .filter(|p| p.extension().is_some_and(|ext| ext == "md"))
.collect(); .collect();
// Sort by name (timestamps sort lexicographically) - newest last // Sort by name (timestamps sort lexicographically) - newest last
@@ -169,3 +219,74 @@ fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::{get_version, list_versions};
use std::fs;
use uuid::Uuid;
#[test]
fn rejects_history_path_traversal() {
let vault =
std::env::temp_dir().join(format!("helixnotes-history-test-{}", Uuid::new_v4()));
let metadata = vault.join(".helixnotes");
let escaped_history = metadata.join("escaped");
fs::create_dir_all(&escaped_history).unwrap();
fs::write(escaped_history.join("2026-01-01T00-00-00.md"), "escaped").unwrap();
fs::create_dir_all(metadata.join("history").join("safe")).unwrap();
fs::write(metadata.join("secret.md"), "secret").unwrap();
assert!(list_versions(&vault.to_string_lossy(), "../escaped").is_err());
assert!(get_version(&vault.to_string_lossy(), "safe", "../../secret").is_err());
fs::remove_dir_all(vault).unwrap();
}
#[test]
fn rapid_forced_versions_are_individually_retrievable_and_prunable() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
for index in 0..200 {
super::force_snapshot(root, "note", &format!("snapshot {index}"), 0).unwrap();
}
let versions = list_versions(root, "note").unwrap();
assert_eq!(versions.len(), 200);
let contents: std::collections::HashSet<_> = versions
.iter()
.map(|version| get_version(root, "note", &version.timestamp).unwrap())
.collect();
assert_eq!(contents.len(), 200);
assert!(contents.contains("snapshot 0"));
assert!(contents.contains("snapshot 199"));
super::force_snapshot(root, "note", "latest", 10).unwrap();
let retained = list_versions(root, "note").unwrap();
assert_eq!(retained.len(), 10);
assert_eq!(
get_version(root, "note", &retained[0].timestamp).unwrap(),
"latest"
);
}
#[test]
fn legacy_versions_remain_readable_and_recent_unique_versions_observe_cooldown() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
let history = vault.path().join(".helixnotes/history/note");
fs::create_dir_all(&history).unwrap();
fs::write(history.join("2026-01-01T00-00-00.md"), "legacy").unwrap();
fs::write(history.join("2026-01-01T1é-00-00.md"), "unusual filename").unwrap();
super::force_snapshot(root, "note", "new", 0).unwrap();
super::maybe_snapshot(root, "note", "too soon", 0);
let versions = list_versions(root, "note").unwrap();
assert_eq!(versions.len(), 3);
assert_eq!(
get_version(root, "note", "2026-01-01T00:00:00Z").unwrap(),
"legacy"
);
assert_eq!(
get_version(root, "note", &versions[0].timestamp).unwrap(),
"new"
);
}
}
+245
View File
@@ -0,0 +1,245 @@
use reqwest::{blocking::Client, redirect::Policy, Url};
use std::io::Read;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::time::Duration;
const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;
pub struct ImageResponse {
pub content_type: String,
pub body: Vec<u8>,
}
pub enum ProxyError {
Invalid(String),
Blocked(String),
Fetch(String),
}
impl ProxyError {
pub fn status(&self) -> u16 {
match self {
Self::Invalid(_) => 400,
Self::Blocked(_) => 403,
Self::Fetch(_) => 502,
}
}
pub fn message(&self) -> &str {
match self {
Self::Invalid(message) | Self::Blocked(message) | Self::Fetch(message) => message,
}
}
}
fn is_public_ipv4(ip: Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
!(a == 0
|| a == 10
|| a == 127
|| a >= 224
|| (a == 100 && (64..=127).contains(&b))
|| (a == 169 && b == 254)
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 168)
|| (a == 192 && b == 0 && c == 0)
|| (a == 192 && b == 0 && c == 2)
|| (a == 198 && (b == 18 || b == 19))
|| (a == 198 && b == 51 && c == 100)
|| (a == 203 && b == 0 && c == 113))
}
fn is_public_ipv6(ip: Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.to_ipv4().is_some() {
return false;
}
let first = ip.segments()[0];
(0x2000..=0x3fff).contains(&first) && ip.segments()[..2] != [0x2001, 0x0db8]
}
fn is_public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => is_public_ipv4(ip),
IpAddr::V6(ip) => is_public_ipv6(ip),
}
}
fn normalized_host(host: &str) -> String {
host.trim_start_matches('[')
.trim_end_matches(']')
.trim_end_matches('.')
.to_ascii_lowercase()
}
fn validate_url(raw_url: &str) -> Result<Url, ProxyError> {
let url = Url::parse(raw_url).map_err(|_| ProxyError::Invalid("Invalid image URL".into()))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(ProxyError::Invalid(
"Only HTTP and HTTPS images are supported".into(),
));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(ProxyError::Invalid(
"Image URLs must not contain credentials".into(),
));
}
let expected_port = if url.scheme() == "https" { 443 } else { 80 };
if url.port_or_known_default() != Some(expected_port) {
return Err(ProxyError::Blocked("Non-standard image URL port".into()));
}
let host = url
.host_str()
.ok_or_else(|| ProxyError::Invalid("Image URL has no host".into()))?;
if host.ends_with('.') {
return Err(ProxyError::Invalid(
"Image URL host must not have a trailing dot".into(),
));
}
let normalized = normalized_host(host);
if normalized == "localhost" || normalized.ends_with(".localhost") {
return Err(ProxyError::Blocked(
"Local image hosts are not allowed".into(),
));
}
if let Ok(ip) = normalized.parse::<IpAddr>() {
if !is_public_ip(ip) {
return Err(ProxyError::Blocked(
"Private image addresses are not allowed".into(),
));
}
}
Ok(url)
}
fn resolve_public_host(url: &Url) -> Result<(String, Vec<SocketAddr>), ProxyError> {
let host = url
.host_str()
.ok_or_else(|| ProxyError::Invalid("Image URL has no host".into()))?;
let host = normalized_host(host);
let port = url
.port_or_known_default()
.ok_or_else(|| ProxyError::Invalid("Image URL has no port".into()))?;
let addresses: Vec<_> = (host.as_str(), port)
.to_socket_addrs()
.map_err(|error| ProxyError::Fetch(format!("Could not resolve image host: {error}")))?
.collect();
if addresses.is_empty() {
return Err(ProxyError::Fetch(
"Image host resolved to no addresses".into(),
));
}
if addresses.iter().any(|address| !is_public_ip(address.ip())) {
return Err(ProxyError::Blocked(
"Image host resolves to a private address".into(),
));
}
Ok((host, addresses))
}
fn image_client(host: &str, addresses: &[SocketAddr]) -> Result<Client, ProxyError> {
let redirect_host = host.to_string();
Client::builder()
.timeout(Duration::from_secs(30))
.redirect(Policy::custom(move |attempt| {
let redirected_elsewhere = match attempt.url().host_str() {
Some(host) => normalized_host(host) != redirect_host,
None => true,
};
if attempt.previous().len() >= 5
|| redirected_elsewhere
|| validate_url(attempt.url().as_str()).is_err()
{
attempt.stop()
} else {
attempt.follow()
}
}))
.resolve_to_addrs(host, addresses)
.build()
.map_err(|error| ProxyError::Fetch(format!("Could not create image client: {error}")))
}
pub fn fetch(raw_url: &str) -> Result<ImageResponse, ProxyError> {
let url = validate_url(raw_url)?;
let (host, addresses) = resolve_public_host(&url)?;
let client = image_client(&host, &addresses)?;
let mut response = client
.get(url)
.send()
.map_err(|error| ProxyError::Fetch(format!("Image request failed: {error}")))?;
if !response.status().is_success() {
return Err(ProxyError::Fetch(format!(
"Image server returned {}",
response.status()
)));
}
if response
.content_length()
.is_some_and(|length| length > MAX_IMAGE_BYTES)
{
return Err(ProxyError::Blocked("Image exceeds the 20 MiB limit".into()));
}
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_string();
if !content_type.to_ascii_lowercase().starts_with("image/") {
return Err(ProxyError::Blocked(
"Remote resource is not an image".into(),
));
}
let mut body = Vec::new();
response
.by_ref()
.take(MAX_IMAGE_BYTES + 1)
.read_to_end(&mut body)
.map_err(|error| ProxyError::Fetch(format!("Could not read image: {error}")))?;
if body.len() as u64 > MAX_IMAGE_BYTES {
return Err(ProxyError::Blocked("Image exceeds the 20 MiB limit".into()));
}
Ok(ImageResponse { content_type, body })
}
#[cfg(test)]
mod tests {
use super::{is_public_ip, validate_url};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
#[test]
fn blocks_local_and_private_networks() {
for ip in [
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254)),
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
IpAddr::V6(Ipv6Addr::LOCALHOST),
"fc00::1".parse().unwrap(),
"fe80::1".parse().unwrap(),
] {
assert!(!is_public_ip(ip), "{ip}");
}
assert!(is_public_ip("93.184.216.34".parse().unwrap()));
assert!(is_public_ip(
"2606:2800:220:1:248:1893:25c8:1946".parse().unwrap()
));
}
#[test]
fn validates_only_public_web_image_urls() {
for url in [
"file:///etc/passwd",
"http://localhost/image.png",
"http://127.0.0.1/image.png",
"http://[::1]/image.png",
"http://example.com:8080/image.png",
"https://example.com./image.png",
"https://user:pass@example.com/image.png",
] {
assert!(validate_url(url).is_err(), "{url}");
}
assert!(validate_url("https://example.com/image.png").is_ok());
assert!(validate_url("http://93.184.216.34/image.png").is_ok());
}
}
+145 -97
View File
@@ -1,7 +1,9 @@
mod ai; mod ai;
mod asset_scope;
mod backup; mod backup;
mod commands; mod commands;
mod history; mod history;
mod image_proxy;
mod search; mod search;
mod state; mod state;
mod sync; mod sync;
@@ -11,6 +13,7 @@ mod vault;
use state::AppState; use state::AppState;
#[allow(unused_imports)] #[allow(unused_imports)]
use tauri::{Emitter, Manager}; use tauri::{Emitter, Manager};
use tauri_plugin_fs::FsExt;
#[cfg(desktop)] #[cfg(desktop)]
use tauri::{ use tauri::{
@@ -34,8 +37,6 @@ pub fn run() {
let config = commands::load_app_config(); let config = commands::load_app_config();
#[cfg(desktop)] #[cfg(desktop)]
let show_tray = config.show_tray_icon; let show_tray = config.show_tray_icon;
#[cfg(desktop)]
let close_to_tray = config.close_to_tray && show_tray;
let app_state = AppState::new(config); let app_state = AppState::new(config);
// Inject the compile-time platform so the frontend never sniffs the (sometimes // Inject the compile-time platform so the frontend never sniffs the (sometimes
@@ -56,19 +57,22 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.on_webview_event(|webview, event| {
if let tauri::WebviewEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
let scope = webview.fs_scope();
for path in paths {
if path.is_file() {
let _ = scope.allow_file(path);
}
}
}
})
.on_page_load(|webview, payload| { .on_page_load(|webview, payload| {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
if webview.label() == "main" if webview.label() == "main"
&& matches!( && matches!(payload.event(), tauri::webview::PageLoadEvent::Finished)
payload.event(),
tauri::webview::PageLoadEvent::Finished
)
{ {
let window = webview.window(); queue_macos_traffic_light_fix(&webview.window());
let window_on_main = window.clone();
let _ = window.run_on_main_thread(move || {
fix_macos_traffic_lights(&window_on_main);
});
} }
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let _ = (webview, payload); let _ = (webview, payload);
@@ -100,6 +104,20 @@ pub fn run() {
}); });
} }
let active_vault = app
.state::<AppState>()
.config
.lock()
.ok()
.and_then(|config| config.active_vault.clone());
if let Some(vault_path) = active_vault {
if let Err(error) =
asset_scope::allow_vault_assets(app.handle(), std::path::Path::new(&vault_path))
{
log::warn!("Failed to restore the vault asset scope: {error}");
}
}
#[cfg(desktop)] #[cfg(desktop)]
if show_tray { if show_tray {
setup_tray(app)?; setup_tray(app)?;
@@ -119,10 +137,18 @@ pub fn run() {
std::env::current_dir().unwrap_or_default().join(&path) std::env::current_dir().unwrap_or_default().join(&path)
}; };
if let Some(resolved_str) = resolved.to_str() { if let Some(resolved_str) = resolved.to_str() {
if resolved.is_file() {
let _ = app.fs_scope().allow_file(&resolved);
if let Some(parent) = resolved.parent() {
let _ = app.fs_scope().allow_directory(parent, true);
}
let _ =
asset_scope::allow_external_note_assets(app.handle(), &resolved);
}
let app_state = app.state::<AppState>(); let app_state = app.state::<AppState>();
let _ = app_state.pending_open_file.lock().map(|mut p| { if let Err(error) = app_state.enqueue_open_file(resolved_str.to_string()) {
*p = Some(resolved_str.to_string()); log::error!("Could not queue startup file: {error}");
}); }
} }
} }
} }
@@ -136,13 +162,18 @@ pub fn run() {
commands::restore_external_vault, commands::restore_external_vault,
commands::remove_vault, commands::remove_vault,
commands::get_app_config, commands::get_app_config,
#[cfg(desktop)]
commands::complete_window_close,
commands::set_theme, commands::set_theme,
commands::set_system_themes,
commands::set_accent_color, commands::set_accent_color,
commands::save_custom_theme, commands::save_custom_theme,
commands::delete_custom_theme, commands::delete_custom_theme,
commands::export_custom_theme, commands::export_custom_theme,
commands::import_custom_themes, commands::import_custom_themes,
commands::set_font_size, commands::set_font_size,
commands::set_scroll_to_change_font_size,
commands::set_toolbar_layout,
commands::set_font_family, commands::set_font_family,
commands::set_line_height, commands::set_line_height,
commands::set_ui_scale, commands::set_ui_scale,
@@ -157,12 +188,14 @@ pub fn run() {
commands::read_note, commands::read_note,
commands::save_note, commands::save_note,
commands::create_note, commands::create_note,
commands::duplicate_note,
commands::create_daily_note, commands::create_daily_note,
commands::rename_note, commands::rename_note,
commands::delete_note, commands::delete_note,
commands::move_note, commands::move_note,
commands::get_all_tags, commands::get_all_tags,
commands::get_all_note_titles, commands::get_all_note_titles,
commands::get_note_switcher_titles,
commands::get_graph_data, commands::get_graph_data,
commands::get_tasks, commands::get_tasks,
commands::set_task_done, commands::set_task_done,
@@ -177,12 +210,17 @@ pub fn run() {
commands::empty_trash, commands::empty_trash,
commands::load_vault_state, commands::load_vault_state,
commands::save_vault_state, commands::save_vault_state,
commands::copy_text_to_clipboard,
commands::read_clipboard_image, commands::read_clipboard_image,
commands::copy_image_to_clipboard, commands::copy_image_to_clipboard,
commands::save_image, commands::save_image,
commands::save_attachment, commands::save_attachment,
commands::get_notebook_icons, commands::get_notebook_icons,
commands::set_notebook_icon, commands::set_notebook_icon,
commands::import_notebook_icon,
commands::get_tag_styles,
commands::set_tag_style,
commands::import_tag_icon,
commands::set_general_settings, commands::set_general_settings,
commands::get_quick_access, commands::get_quick_access,
commands::add_quick_access, commands::add_quick_access,
@@ -193,6 +231,7 @@ pub fn run() {
commands::trash_orphaned_attachments, commands::trash_orphaned_attachments,
commands::import_obsidian, commands::import_obsidian,
commands::open_file, commands::open_file,
commands::reveal_file,
commands::open_url, commands::open_url,
commands::copy_file_to, commands::copy_file_to,
commands::write_bytes_to, commands::write_bytes_to,
@@ -214,78 +253,30 @@ pub fn run() {
commands::get_install_type, commands::get_install_type,
commands::is_mobile_platform, commands::is_mobile_platform,
commands::get_pending_open_file, commands::get_pending_open_file,
commands::ack_pending_open_file,
#[cfg(desktop)]
commands::cancel_window_close,
]) ])
.register_asynchronous_uri_scheme_protocol("imgproxy", |_ctx, request, responder| { .register_asynchronous_uri_scheme_protocol("imgproxy", |_ctx, request, responder| {
let path = request.uri().path().to_string(); let path = request.uri().path().to_string();
std::thread::spawn(move || { std::thread::spawn(move || {
let encoded = path.strip_prefix('/').unwrap_or(&path); let encoded = path.strip_prefix('/').unwrap_or(&path);
let external_url = percent_decode(encoded); let external_url = percent_decode(encoded);
let response = match image_proxy::fetch(&external_url) {
if !external_url.starts_with("http://") && !external_url.starts_with("https://") { Ok(image) => tauri::http::Response::builder()
let _ = responder.respond( .status(200)
.header("Content-Type", image.content_type)
.header("Access-Control-Allow-Origin", "*")
.header("X-Content-Type-Options", "nosniff")
.body(image.body),
Err(error) => {
log::warn!("Blocked external image request: {}", error.message());
tauri::http::Response::builder() tauri::http::Response::builder()
.status(400) .status(error.status())
.body(Vec::new()) .body(Vec::new())
.unwrap(),
);
return;
}
let client = match reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
{
Ok(c) => c,
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
return;
} }
}; };
responder.respond(response.expect("valid image proxy response"));
match client.get(&external_url).send() {
Ok(resp) => {
let content_type = resp
.headers()
.get("content-type")
.and_then(|h| h.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
let status = resp.status().as_u16();
match resp.bytes() {
Ok(bytes) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(status)
.header("Content-Type", &content_type)
.header("Access-Control-Allow-Origin", "*")
.body(bytes.to_vec())
.unwrap(),
);
}
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
}
}
}
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
}
}
}); });
}); });
@@ -312,42 +303,91 @@ pub fn run() {
std::path::Path::new(&cwd).join(path) std::path::Path::new(&cwd).join(path)
}; };
if let Some(resolved_str) = resolved.to_str() { if let Some(resolved_str) = resolved.to_str() {
let _ = app.emit("open-file", resolved_str.to_string()); if resolved.is_file() {
let _ = app.fs_scope().allow_file(&resolved);
if let Some(parent) = resolved.parent() {
let _ = app.fs_scope().allow_directory(parent, true);
}
let _ = asset_scope::allow_external_note_assets(app, &resolved);
}
if let Err(error) = app
.state::<AppState>()
.enqueue_open_file(resolved_str.to_string())
{
log::error!("Could not queue open file: {error}");
} else {
let _ = app.emit("open-file-pending", ());
}
} }
} }
})); }));
builder = builder.plugin(tauri_plugin_updater::Builder::new().build()); builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
builder = builder.plugin(tauri_plugin_window_state::Builder::default().build()); let window_state_builder = tauri_plugin_window_state::Builder::default();
#[cfg(target_os = "linux")]
let window_state_builder = window_state_builder.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
| tauri_plugin_window_state::StateFlags::MAXIMIZED
| tauri_plugin_window_state::StateFlags::DECORATIONS
| tauri_plugin_window_state::StateFlags::FULLSCREEN,
);
builder = builder.plugin(window_state_builder.build());
builder = builder.on_window_event(move |window, event| { builder = builder.on_window_event(move |window, event| {
match event { #[cfg(target_os = "macos")]
tauri::WindowEvent::CloseRequested { api, .. } => { if window.label() == "main"
// Only hide to tray for the main window && matches!(
if close_to_tray && window.label() == "main" { event,
api.prevent_close(); tauri::WindowEvent::Resized(_)
let _ = window.hide(); | tauri::WindowEvent::Focused(true)
| tauri::WindowEvent::ScaleFactorChanged { .. }
| tauri::WindowEvent::ThemeChanged(_)
)
{
// AppKit can restore the default button Y position after window-state
// changes. Queue this pass so it runs after AppKit finishes its layout.
queue_macos_traffic_light_fix(window);
} }
}
tauri::WindowEvent::Destroyed => { // Closing the main window also requests a save-aware close of note windows.
// When main window is destroyed, close all note windows if matches!(event, tauri::WindowEvent::Destroyed) && window.label() == "main" {
if window.label() == "main" { for (label, win) in window.app_handle().webview_windows() {
let app = window.app_handle();
for (label, win) in app.webview_windows() {
if label.starts_with("note-") { if label.starts_with("note-") {
let _ = win.close(); let _ = win.close();
} }
} }
} }
}
_ => {}
}
}); });
} }
builder let app = builder
.run(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while building tauri application");
app.run(|app, event| {
#[cfg(desktop)]
if let tauri::RunEvent::ExitRequested {
code: Some(_), api, ..
} = event
{
let windows = app.webview_windows();
if !windows.is_empty() {
// Menu/tray Quit must give each editor the same save opportunity
// as a window close. The app exits once the last window closes.
api.prevent_exit();
app.state::<AppState>()
.quitting
.store(true, std::sync::atomic::Ordering::Relaxed);
for window in windows.values() {
if let Err(error) = window.close() {
log::error!("Failed to close window during quit: {error}");
}
}
}
}
#[cfg(mobile)]
let _ = (app, event);
});
} }
#[cfg(desktop)] #[cfg(desktop)]
@@ -356,7 +396,7 @@ fn setup_tray(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?; let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?; let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;
let _tray = TrayIconBuilder::new() let _tray = TrayIconBuilder::with_id("helixnotes")
.icon( .icon(
Image::from_path("icons/32x32.png") Image::from_path("icons/32x32.png")
.unwrap_or_else(|_| app.default_window_icon().cloned().unwrap()), .unwrap_or_else(|_| app.default_window_icon().cloned().unwrap()),
@@ -410,6 +450,14 @@ fn percent_decode(input: &str) -> String {
String::from_utf8_lossy(&output).to_string() String::from_utf8_lossy(&output).to_string()
} }
#[cfg(target_os = "macos")]
fn queue_macos_traffic_light_fix(window: &tauri::Window) {
let window_on_main = window.clone();
let _ = window.run_on_main_thread(move || {
fix_macos_traffic_lights(&window_on_main);
});
}
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn fix_macos_traffic_lights(window: &tauri::Window) { fn fix_macos_traffic_lights(window: &tauri::Window) {
use objc2_app_kit::{NSView, NSWindow, NSWindowButton}; use objc2_app_kit::{NSView, NSWindow, NSWindowButton};
+1509 -209
View File
File diff suppressed because it is too large. Load diff
+290 -8
View File
@@ -1,30 +1,312 @@
use crate::search::SearchIndex; use crate::search::{SearchIndex, SearchIndexShutdown};
use crate::types::AppConfig; use crate::types::AppConfig;
use notify::RecommendedWatcher; use crate::vault::watcher::VaultWatcher;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use std::sync::Mutex; use std::sync::{Arc, Mutex, Weak};
use std::sync::Arc; use tauri::AppHandle;
#[cfg(desktop)]
use tauri::{Manager, Runtime, Url};
#[cfg(desktop)]
fn is_detached_window_for_vault(label: &str, url: &Url, target_path: &str) -> bool {
label.starts_with("note-")
&& url
.query_pairs()
.any(|(key, value)| key == "vault" && value == target_path)
}
struct CachedSearchIndex {
index: Weak<SearchIndex>,
shutdown: Arc<SearchIndexShutdown>,
}
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PendingOpenFile {
pub id: u64,
pub path: String,
}
#[derive(Default)]
struct PendingOpenFiles {
next_id: u64,
requests: VecDeque<PendingOpenFile>,
}
pub struct AppState { pub struct AppState {
pub config: Mutex<AppConfig>, pub config: Mutex<AppConfig>,
pub search_index: Mutex<Option<Arc<SearchIndex>>>, pub search_index: Mutex<Option<Arc<SearchIndex>>>,
pub watcher: Mutex<Option<RecommendedWatcher>>, search_indexes: Mutex<HashMap<String, CachedSearchIndex>>,
pub watchers: Mutex<HashMap<String, VaultWatcher>>,
pub vault_transition: tokio::sync::Mutex<()>, pub vault_transition: tokio::sync::Mutex<()>,
pub vault_maintenance: Arc<tokio::sync::Mutex<()>>,
pub note_save: Arc<tokio::sync::Mutex<()>>,
pub importing: AtomicBool, pub importing: AtomicBool,
pub syncing: AtomicBool, pub syncing: AtomicBool,
pub pending_open_file: Mutex<Option<String>>, #[cfg(desktop)]
pub quitting: AtomicBool,
pending_open_files: Mutex<PendingOpenFiles>,
} }
impl AppState { impl AppState {
pub fn enqueue_open_file(&self, path: String) -> Result<(), String> {
let mut pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
pending.next_id += 1;
let id = pending.next_id;
pending.requests.push_back(PendingOpenFile { id, path });
Ok(())
}
pub fn peek_pending_open_file(&self) -> Result<Option<PendingOpenFile>, String> {
let pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
Ok(pending.requests.front().cloned())
}
pub fn ack_pending_open_file(&self, id: u64) -> Result<bool, String> {
let mut pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
if pending
.requests
.front()
.is_some_and(|request| request.id == id)
{
pending.requests.pop_front();
Ok(true)
} else {
Ok(false)
}
}
pub fn ensure_vault_watcher(&self, app: &AppHandle, vault_path: &str) -> Result<(), String> {
let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?;
if !watchers.contains_key(vault_path) {
let watcher = crate::vault::watcher::start_watcher(app.clone(), vault_path.to_owned())?;
watchers.insert(vault_path.to_owned(), watcher);
}
Ok(())
}
pub fn retain_vault_watchers(&self) -> Result<(), String> {
let configured: HashSet<String> = {
let config = self.config.lock().map_err(|error| error.to_string())?;
config
.vaults
.iter()
.map(|vault| vault.path.clone())
.chain(config.active_vault.clone())
.collect()
};
let removed = {
let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?;
let removed: Vec<String> = watchers
.keys()
.filter(|path| !configured.contains(*path))
.cloned()
.collect();
removed
.into_iter()
.filter_map(|path| watchers.remove(&path))
.collect::<Vec<_>>()
};
drop(removed);
Ok(())
}
#[cfg(desktop)]
pub fn ensure_no_detached_windows<R: Runtime>(
app: &AppHandle<R>,
target_path: &str,
) -> Result<(), String> {
for (label, window) in app.webview_windows() {
if is_detached_window_for_vault(
&label,
&window.url().map_err(|error| error.to_string())?,
target_path,
) {
return Err(
"Close this vault's detached note windows before forgetting it.".into(),
);
}
}
Ok(())
}
// A refresh worker may outlive a vault switch. Reuse its writer when opening
// that vault again instead of competing for Tantivy's exclusive writer lock.
pub fn search_index_for_vault(&self, vault_path: &str) -> Result<Arc<SearchIndex>, String> {
let mut indexes = self
.search_indexes
.lock()
.map_err(|error| error.to_string())?;
indexes
.retain(|_, cached| cached.index.strong_count() > 0 || !cached.shutdown.is_finished());
if let Some(cached) = indexes.get(vault_path) {
if let Some(index) = cached.index.upgrade() {
return Ok(index);
}
// The last Arc is gone, but its writer may still be shutting down.
cached.shutdown.wait();
}
let index = Arc::new(SearchIndex::new(vault_path)?);
indexes.insert(
vault_path.to_owned(),
CachedSearchIndex {
index: Arc::downgrade(&index),
shutdown: index.shutdown_signal(),
},
);
Ok(index)
}
pub fn validate_vault(&self, vault_path: &str) -> Result<(), String> {
let config = self.config.lock().map_err(|error| error.to_string())?;
if config.active_vault.as_deref() == Some(vault_path)
|| config.vaults.iter().any(|vault| vault.path == vault_path)
{
Ok(())
} else {
Err("Unknown vault".to_string())
}
}
pub fn vault_snapshot(&self, vault_path: &str) -> Result<Option<Arc<SearchIndex>>, String> {
let search = self
.search_index
.lock()
.map_err(|error| error.to_string())?;
let config = self.config.lock().map_err(|error| error.to_string())?;
if config.active_vault.as_deref() == Some(vault_path) {
return Ok(search.clone());
}
if !config.vaults.iter().any(|vault| vault.path == vault_path) {
return Err("Unknown vault".to_string());
}
drop(config);
drop(search);
// Detached windows retain access to configured vaults. Never pair their
// writes with the main window's index, nor hold config during disk I/O.
self.search_index_for_vault(vault_path).map(Some)
}
pub fn active_vault_snapshot(&self) -> Result<(String, Option<Arc<SearchIndex>>), String> {
// Match vault transition and watcher lock order. The vault and its
// optional index must remain paired even if a switch follows the read.
let search = self
.search_index
.lock()
.map_err(|error| error.to_string())?;
let config = self.config.lock().map_err(|error| error.to_string())?;
Ok((
config.active_vault.clone().ok_or("No active vault")?,
search.clone(),
))
}
pub fn active_search(&self) -> Result<(Arc<SearchIndex>, String), String> {
let (vault_path, search) = self.active_vault_snapshot()?;
Ok((search.ok_or("Search index not initialized")?, vault_path))
}
#[cfg(desktop)]
pub fn should_hide_to_tray(&self, label: &str, tray_available: bool) -> Result<bool, String> {
if label != "main"
|| !tray_available
|| self.quitting.load(std::sync::atomic::Ordering::Relaxed)
{
return Ok(false);
}
let config = self.config.lock().map_err(|error| error.to_string())?;
Ok(config.show_tray_icon && config.close_to_tray)
}
pub fn new(config: AppConfig) -> Self { pub fn new(config: AppConfig) -> Self {
Self { Self {
config: Mutex::new(config), config: Mutex::new(config),
search_index: Mutex::new(None), search_index: Mutex::new(None),
watcher: Mutex::new(None), search_indexes: Mutex::new(HashMap::new()),
watchers: Mutex::new(HashMap::new()),
vault_transition: tokio::sync::Mutex::new(()), vault_transition: tokio::sync::Mutex::new(()),
vault_maintenance: Arc::new(tokio::sync::Mutex::new(())),
note_save: Arc::new(tokio::sync::Mutex::new(())),
importing: AtomicBool::new(false), importing: AtomicBool::new(false),
syncing: AtomicBool::new(false), syncing: AtomicBool::new(false),
pending_open_file: Mutex::new(None), #[cfg(desktop)]
quitting: AtomicBool::new(false),
pending_open_files: Mutex::new(PendingOpenFiles::default()),
} }
} }
} }
#[cfg(all(test, desktop))]
mod tests {
use super::*;
#[test]
fn pending_open_requests_survive_reads_and_only_acknowledge_head() {
let state = AppState::new(AppConfig::default());
state.enqueue_open_file("one.md".into()).unwrap();
state.enqueue_open_file("two.md".into()).unwrap();
let first = state.peek_pending_open_file().unwrap().unwrap();
assert_eq!(first.path, "one.md");
assert_eq!(
state.peek_pending_open_file().unwrap().unwrap().id,
first.id
);
assert!(!state.ack_pending_open_file(first.id + 1).unwrap());
assert_eq!(
state.peek_pending_open_file().unwrap().unwrap().id,
first.id
);
assert!(state.ack_pending_open_file(first.id).unwrap());
let second = state.peek_pending_open_file().unwrap().unwrap();
assert_eq!(second.path, "two.md");
assert!(!state.ack_pending_open_file(first.id).unwrap());
assert!(state.ack_pending_open_file(second.id).unwrap());
assert!(state.peek_pending_open_file().unwrap().is_none());
}
#[test]
fn detached_window_owner_matches_encoded_vault_path_only() {
let url = Url::parse("tauri://localhost/?note=a.md&vault=%2Fvaults%2FA%26B").unwrap();
assert!(is_detached_window_for_vault(
"note-123",
&url,
"/vaults/A&B"
));
assert!(!is_detached_window_for_vault("note-123", &url, "/vaults/A"));
assert!(!is_detached_window_for_vault("main", &url, "/vaults/A&B"));
}
#[test]
fn close_policy_respects_live_settings_window_type_and_explicit_quit() {
let mut state = AppState::new(AppConfig {
show_tray_icon: true,
close_to_tray: true,
..AppConfig::default()
});
assert!(state.should_hide_to_tray("main", true).unwrap());
assert!(!state.should_hide_to_tray("note-123", true).unwrap());
assert!(!state.should_hide_to_tray("main", false).unwrap());
state
.quitting
.store(true, std::sync::atomic::Ordering::Relaxed);
assert!(!state.should_hide_to_tray("main", true).unwrap());
state
.quitting
.store(false, std::sync::atomic::Ordering::Relaxed);
state.config.get_mut().unwrap().close_to_tray = false;
assert!(!state.should_hide_to_tray("main", true).unwrap());
state.config.get_mut().unwrap().close_to_tray = true;
state.config.get_mut().unwrap().show_tray_icon = false;
assert!(!state.should_hide_to_tray("main", true).unwrap());
}
}
+1067 -229
View File
File diff suppressed because it is too large. Load diff
+188 -5
View File
@@ -42,6 +42,37 @@ pub struct NotebookEntry {
pub note_count: usize, pub note_count: usize,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct TagStyle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
pub enum TagStyleChange {
Icon(Option<String>),
Color(Option<String>),
Reset,
}
impl TagStyle {
pub fn is_empty(&self) -> bool {
self.icon
.as_ref()
.map(|value| value.trim().is_empty())
.unwrap_or(true)
&& self
.color
.as_ref()
.map(|value| value.trim().is_empty())
.unwrap_or(true)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteContent { pub struct NoteContent {
pub path: String, pub path: String,
@@ -73,6 +104,8 @@ pub struct VaultConfig {
pub sync_interval_minutes: u32, pub sync_interval_minutes: u32,
#[serde(default)] #[serde(default)]
pub last_sync_time: Option<String>, pub last_sync_time: Option<String>,
#[serde(default)]
pub last_backup_time: Option<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -96,6 +129,23 @@ pub struct CustomTheme {
pub colors: CustomThemeColors, pub colors: CustomThemeColors,
} }
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StartupView {
Daily,
QuickAccess,
Tasks,
#[default]
#[serde(other)]
All,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolbarLayout {
pub main: Vec<String>,
pub more: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig { pub struct AppConfig {
pub vaults: Vec<VaultConfig>, pub vaults: Vec<VaultConfig>,
@@ -103,10 +153,20 @@ pub struct AppConfig {
#[serde(default)] #[serde(default)]
pub active_bookmark_id: Option<String>, pub active_bookmark_id: Option<String>,
pub theme: String, pub theme: String,
/// Themes used when `theme` is "system": the frontend picks one by the OS color scheme.
/// Default to the plain "light"/"dark" schemes so existing configs keep their behavior.
#[serde(default = "default_system_light_theme")]
pub system_light_theme: String,
#[serde(default = "default_system_dark_theme")]
pub system_dark_theme: String,
#[serde(default)] #[serde(default)]
pub accent_color: Option<String>, pub accent_color: Option<String>,
#[serde(default)] #[serde(default)]
pub font_size: Option<u32>, pub font_size: Option<u32>,
#[serde(default = "default_true")]
pub scroll_to_change_font_size: bool,
#[serde(default)]
pub toolbar_layout: Option<ToolbarLayout>,
#[serde(default)] #[serde(default)]
pub font_family: Option<String>, pub font_family: Option<String>,
#[serde(default)] #[serde(default)]
@@ -120,6 +180,8 @@ pub struct AppConfig {
#[serde(default = "default_true")] #[serde(default = "default_true")]
pub show_note_dates: bool, pub show_note_dates: bool,
#[serde(default)] #[serde(default)]
pub show_note_switcher: bool,
#[serde(default)]
pub time_format: String, pub time_format: String,
#[serde(default = "default_week_start")] #[serde(default = "default_week_start")]
pub week_start: String, pub week_start: String,
@@ -160,8 +222,6 @@ pub struct AppConfig {
#[serde(default)] #[serde(default)]
pub backup_location: Option<String>, pub backup_location: Option<String>,
#[serde(default)] #[serde(default)]
pub last_backup_time: Option<String>,
#[serde(default)]
pub backup_include_attachments: bool, pub backup_include_attachments: bool,
#[serde(default = "default_max_versions")] #[serde(default = "default_max_versions")]
pub max_versions_per_note: u32, pub max_versions_per_note: u32,
@@ -186,12 +246,16 @@ pub struct AppConfig {
#[serde(default)] #[serde(default)]
pub default_view_mode: bool, pub default_view_mode: bool,
#[serde(default)] #[serde(default)]
pub new_notes_in_source_mode: bool,
#[serde(default)]
pub show_tray_icon: bool, pub show_tray_icon: bool,
#[serde(default)] #[serde(default)]
pub close_to_tray: bool, pub close_to_tray: bool,
#[serde(default = "default_true")] #[serde(default = "default_true")]
pub enable_wiki_links: bool, pub enable_wiki_links: bool,
#[serde(default)] #[serde(default)]
pub startup_view: StartupView,
#[serde(default)]
pub restore_last_session: bool, pub restore_last_session: bool,
// DEPRECATED: WebDAV sync moved to per-vault VaultConfig. Kept for one release to migrate old configs. // DEPRECATED: WebDAV sync moved to per-vault VaultConfig. Kept for one release to migrate old configs.
#[serde(default)] #[serde(default)]
@@ -251,7 +315,15 @@ fn default_max_versions() -> u32 {
} }
fn default_ai_model() -> String { fn default_ai_model() -> String {
"claude-sonnet-4-6".to_string() "claude-sonnet-5".to_string()
}
fn default_system_light_theme() -> String {
"light".to_string()
}
fn default_system_dark_theme() -> String {
"dark".to_string()
} }
impl Default for AppConfig { impl Default for AppConfig {
@@ -261,14 +333,19 @@ impl Default for AppConfig {
active_vault: None, active_vault: None,
active_bookmark_id: None, active_bookmark_id: None,
theme: "system".to_string(), theme: "system".to_string(),
system_light_theme: default_system_light_theme(),
system_dark_theme: default_system_dark_theme(),
accent_color: None, accent_color: None,
font_size: None, font_size: None,
scroll_to_change_font_size: true,
toolbar_layout: None,
font_family: None, font_family: None,
line_height: None, line_height: None,
ui_scale: None, ui_scale: None,
content_width: None, content_width: None,
compact_notes: false, compact_notes: false,
show_note_dates: true, show_note_dates: true,
show_note_switcher: false,
time_format: "relative".to_string(), time_format: "relative".to_string(),
week_start: "monday".to_string(), week_start: "monday".to_string(),
daily_title_format: "localized".to_string(), daily_title_format: "localized".to_string(),
@@ -289,7 +366,6 @@ impl Default for AppConfig {
backup_frequency: "24h".to_string(), backup_frequency: "24h".to_string(),
backup_max_count: 10, backup_max_count: 10,
backup_location: None, backup_location: None,
last_backup_time: None,
backup_include_attachments: false, backup_include_attachments: false,
max_versions_per_note: 20, max_versions_per_note: 20,
ai_provider: None, ai_provider: None,
@@ -299,12 +375,14 @@ impl Default for AppConfig {
ollama_api_key: None, ollama_api_key: None,
openai_compatible_base_url: None, openai_compatible_base_url: None,
openai_compatible_api_key: None, openai_compatible_api_key: None,
ai_model: "claude-sonnet-4-6".to_string(), ai_model: default_ai_model(),
ai_writing_style: None, ai_writing_style: None,
default_view_mode: false, default_view_mode: false,
new_notes_in_source_mode: false,
show_tray_icon: false, show_tray_icon: false,
close_to_tray: false, close_to_tray: false,
enable_wiki_links: true, enable_wiki_links: true,
startup_view: StartupView::All,
restore_last_session: false, restore_last_session: false,
sync_provider: None, sync_provider: None,
webdav_url: None, webdav_url: None,
@@ -380,18 +458,57 @@ impl Default for VaultState {
} }
} }
/// Half-open UTF-16 offsets into the corresponding plain-text result field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchMatch {
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SearchTargetField {
Body,
Title,
Tags,
}
/// Half-open UTF-16 offsets into the indexed field, with exact source context.
/// Body excludes frontmatter; tags use the indexed space-joined values.
/// Text is capped at 240 Unicode scalars and each context at 32 scalars.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchTarget {
pub field: SearchTargetField,
pub start: usize,
pub end: usize,
pub text: String,
pub before: String,
pub after: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult { pub struct SearchResult {
pub path: String, pub path: String,
pub title: String, pub title: String,
pub snippet: String, pub snippet: String,
pub score: f32, pub score: f32,
pub title_matches: Vec<SearchMatch>,
pub snippet_matches: Vec<SearchMatch>,
pub match_target: Option<SearchTarget>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchPage {
pub results: Vec<SearchResult>,
pub total: usize,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEvent { pub struct FileEvent {
pub vault_path: String,
pub event_type: String, pub event_type: String,
pub path: String, pub path: String,
pub note: Option<NoteEntry>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -428,6 +545,7 @@ pub struct VersionEntry {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiStreamEvent { pub struct AiStreamEvent {
pub request_id: String,
pub event_type: String, // "text", "done", "error" pub event_type: String, // "text", "done", "error"
pub text: Option<String>, pub text: Option<String>,
pub error: Option<String>, pub error: Option<String>,
@@ -469,3 +587,68 @@ pub struct TaskItem {
pub due: Option<String>, pub due: Option<String>,
pub priority: Option<String>, pub priority: Option<String>,
} }
#[cfg(test)]
mod startup_view_tests {
use super::{AppConfig, StartupView};
#[test]
fn serializes_supported_startup_views() {
for (view, expected) in [
(StartupView::All, "\"all\""),
(StartupView::QuickAccess, "\"quickaccess\""),
(StartupView::Tasks, "\"tasks\""),
(StartupView::Daily, "\"daily\""),
] {
assert_eq!(serde_json::to_string(&view).unwrap(), expected);
}
}
#[test]
fn unknown_startup_view_falls_back_to_all_notes() {
assert_eq!(
serde_json::from_str::<StartupView>("\"future-view\"").unwrap(),
StartupView::All
);
}
#[test]
fn existing_configs_default_system_theme_pair() {
let mut value = serde_json::to_value(AppConfig::default()).unwrap();
let object = value.as_object_mut().unwrap();
object.remove("system_light_theme");
object.remove("system_dark_theme");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert_eq!(config.system_light_theme, "light");
assert_eq!(config.system_dark_theme, "dark");
}
#[test]
fn note_switcher_is_opt_in_for_new_and_existing_configs() {
let config = AppConfig::default();
assert!(!config.show_note_switcher);
let mut value = serde_json::to_value(config).unwrap();
value.as_object_mut().unwrap().remove("show_note_switcher");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert!(!config.show_note_switcher);
}
#[test]
fn scroll_font_sizing_stays_enabled_for_new_and_existing_configs() {
let config = AppConfig::default();
assert!(config.scroll_to_change_font_size);
let mut value = serde_json::to_value(config).unwrap();
value
.as_object_mut()
.unwrap()
.remove("scroll_to_change_font_size");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert!(config.scroll_to_change_font_size);
}
}
+5 -5
View File
@@ -108,7 +108,7 @@ pub fn serialize_frontmatter(meta: &NoteMeta) -> String {
"[{}]", "[{}]",
meta.tags meta.tags
.iter() .iter()
.map(|t| format!("{}", t)) .map(|t| t.to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
) )
@@ -279,7 +279,7 @@ fn strip_html_and_markdown(input: &str) -> String {
chars.next(); // skip '[' chars.next(); // skip '['
let mut depth = 1; let mut depth = 1;
// Skip alt text // Skip alt text
while let Some(c) = chars.next() { for c in chars.by_ref() {
if c == '[' { if c == '[' {
depth += 1; depth += 1;
} }
@@ -294,7 +294,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if chars.peek() == Some(&'(') { if chars.peek() == Some(&'(') {
chars.next(); chars.next();
let mut depth = 1; let mut depth = 1;
while let Some(c) = chars.next() { for c in chars.by_ref() {
if c == '(' { if c == '(' {
depth += 1; depth += 1;
} }
@@ -313,7 +313,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if ch == '[' { if ch == '[' {
let mut link_text = String::new(); let mut link_text = String::new();
let mut depth = 1; let mut depth = 1;
while let Some(c) = chars.next() { for c in chars.by_ref() {
if c == '[' { if c == '[' {
depth += 1; depth += 1;
} }
@@ -329,7 +329,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if chars.peek() == Some(&'(') { if chars.peek() == Some(&'(') {
chars.next(); chars.next();
let mut depth = 1; let mut depth = 1;
while let Some(c) = chars.next() { for c in chars.by_ref() {
if c == '(' { if c == '(' {
depth += 1; depth += 1;
} }
+383 -143
View File
@@ -1,5 +1,7 @@
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::Path; use std::fs::OpenOptions;
use std::io;
use std::path::{Path, PathBuf};
use chrono::Utc; use chrono::Utc;
use gray_matter::engine::YAML; use gray_matter::engine::YAML;
@@ -9,23 +11,16 @@ use uuid::Uuid;
use crate::types::{ImportResult, NoteMeta}; use crate::types::{ImportResult, NoteMeta};
use crate::vault::frontmatter; use crate::vault::frontmatter;
use crate::vault::operations::replace_file_atomically;
pub fn import(vault_path: &str) -> Result<ImportResult, String> { pub fn import(vault_path: &str) -> Result<ImportResult, String> {
let vault = Path::new(vault_path); let vault = Path::new(vault_path);
let file_index = build_file_index(vault); let file_index = build_file_index(vault)?;
let md_files: Vec<_> = walkdir::WalkDir::new(vault) let md_files: Vec<_> = scanned_files(vault)?
.into_iter() .into_iter()
.filter_map(|e| e.ok()) .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md"))
.filter(|e| {
let p = e.path();
p.is_file()
&& p.extension().and_then(|x| x.to_str()) == Some("md")
&& !p.to_string_lossy().contains("/.helixnotes/")
&& !p.to_string_lossy().contains("/.trash/")
})
.map(|e| e.path().to_path_buf())
.collect(); .collect();
let wiki_embed_re = let wiki_embed_re =
@@ -46,10 +41,8 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
}; };
for path in &md_files { for path in &md_files {
let raw = match std::fs::read_to_string(path) { let raw = std::fs::read_to_string(path)
Ok(c) => c, .map_err(|e| format!("Reading {}: {e}", path.display()))?;
Err(_) => continue,
};
let note_dir = path.parent().unwrap_or(Path::new("")); let note_dir = path.parent().unwrap_or(Path::new(""));
let mut content = raw.clone(); let mut content = raw.clone();
@@ -112,13 +105,15 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
"png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "bmp" | "ico" | "pdf" "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "bmp" | "ico" | "pdf"
); );
if is_embeddable { if is_embeddable {
let alt = if is_dimension_spec(alt_param) { "" } else { alt_param }; let alt = if is_dimension_spec(alt_param) {
""
} else {
alt_param
};
result.links_converted += 1; result.links_converted += 1;
format!("![{}]({})", alt, link_target) format!("![{}]({})", alt, link_target)
} else { } else {
let display = if alt_param.is_empty() { let display = if alt_param.is_empty() || is_dimension_spec(alt_param) {
file_part.rsplit('/').next().unwrap_or(file_part)
} else if is_dimension_spec(alt_param) {
file_part.rsplit('/').next().unwrap_or(file_part) file_part.rsplit('/').next().unwrap_or(file_part)
} else { } else {
alt_param alt_param
@@ -137,7 +132,11 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
let (file_part, anchor) = split_anchor(note_ref); let (file_part, anchor) = split_anchor(note_ref);
if file_part.is_empty() { if file_part.is_empty() {
if let Some(a) = anchor { if let Some(a) = anchor {
let display = if display_param.is_empty() { a } else { display_param }; let display = if display_param.is_empty() {
a
} else {
display_param
};
result.links_converted += 1; result.links_converted += 1;
return format!("[{}](#{})", display, a); return format!("[{}](#{})", display, a);
} }
@@ -165,15 +164,30 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
.to_string(); .to_string();
content = after_links; content = after_links;
content = fix_md_image_refs(&content, &md_img_re, vault, note_dir, &file_index, &mut result.links_converted); content = fix_md_image_refs(
content = fix_md_link_refs(&content, &md_link_re, vault, note_dir, &file_index, &mut result.links_converted); &content,
&md_img_re,
vault,
note_dir,
&file_index,
&mut result.links_converted,
);
content = fix_md_link_refs(
&content,
&md_link_re,
vault,
note_dir,
&file_index,
&mut result.links_converted,
);
if result.links_converted > links_before { if result.links_converted > links_before {
changed = true; changed = true;
} }
if changed { if changed {
let _ = std::fs::write(path, &content); replace_file_atomically(path, content.as_bytes())
.map_err(|e| format!("Writing {}: {e}", path.display()))?;
result.files_converted += 1; result.files_converted += 1;
} }
} }
@@ -183,30 +197,65 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
if !moved.is_empty() { if !moved.is_empty() {
rewrite_attachment_refs(vault, &moved)?; rewrite_attachment_refs(vault, &moved)?;
for old_rel in moved.keys() {
let src_path = vault.join(old_rel);
std::fs::remove_file(&src_path)
.map_err(|e| format!("Removing {} after copying: {e}", src_path.display()))?;
}
} }
cleanup_empty_dirs(vault); cleanup_empty_dirs(vault)?;
Ok(result) Ok(result)
} }
fn build_file_index(vault: &Path) -> HashMap<String, String> { fn is_excluded_dir(path: &Path) -> bool {
let mut index = HashMap::new(); matches!(
for entry in walkdir::WalkDir::new(vault) path.file_name().and_then(|name| name.to_str()),
Some(".helixnotes" | ".obsidian" | ".trash" | ".stfolder" | ".claude")
)
}
fn vault_entries(
vault: &Path,
) -> impl Iterator<Item = Result<walkdir::DirEntry, walkdir::Error>> + '_ {
walkdir::WalkDir::new(vault)
.into_iter() .into_iter()
.filter_map(|e| e.ok()) .filter_entry(|entry| {
{ entry.depth() == 0 || !entry.file_type().is_dir() || !is_excluded_dir(entry.path())
let path = entry.path(); })
if !path.is_file() { }
fn scanned_files(vault: &Path) -> Result<Vec<PathBuf>, String> {
vault_entries(vault)
.filter_map(|entry| match entry {
Ok(entry) if entry.file_type().is_file() => Some(Ok(entry.into_path())),
Ok(_) => None,
Err(e) => Some(Err(e)),
})
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("Scanning {}: {e}", vault.display()))
}
fn vault_relative(path: &Path, vault: &Path) -> Result<String, String> {
path.strip_prefix(vault)
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
.map_err(|e| format!("Relativizing {}: {e}", path.display()))
}
fn build_file_index(vault: &Path) -> Result<HashMap<String, String>, String> {
let mut index = HashMap::new();
for entry in vault_entries(vault) {
let entry = entry.map_err(|e| format!("Scanning {}: {e}", vault.display()))?;
if !entry.file_type().is_file() {
continue; continue;
} }
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if let Ok(rel) = path.strip_prefix(vault) { index.insert(name.to_string(), vault_relative(path, vault)?);
index.insert(name.to_string(), rel.to_string_lossy().to_string());
} }
} }
} Ok(index)
index
} }
fn rename_deprecated_properties(raw: &str) -> String { fn rename_deprecated_properties(raw: &str) -> String {
@@ -231,12 +280,10 @@ fn rename_deprecated_properties(raw: &str) -> String {
mapping.insert(new_key, val); mapping.insert(new_key, val);
renamed = true; renamed = true;
} }
} else { } else if mapping.remove(&old_key).is_some() {
if mapping.remove(&old_key).is_some() {
renamed = true; renamed = true;
} }
} }
}
if !renamed { if !renamed {
return raw.to_string(); return raw.to_string();
@@ -267,7 +314,7 @@ fn normalize_frontmatter(raw: &str, path: &Path) -> (NoteMeta, String) {
let tags = normalize_tags(&mapping); let tags = normalize_tags(&mapping);
let title = mapping let title = mapping
.get(&serde_yaml::Value::String("title".into())) .get(serde_yaml::Value::String("title".into()))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.map(|s| s.to_string()) .map(|s| s.to_string())
.unwrap_or_else(|| { .unwrap_or_else(|| {
@@ -283,7 +330,7 @@ fn normalize_frontmatter(raw: &str, path: &Path) -> (NoteMeta, String) {
}); });
let id = mapping let id = mapping
.get(&serde_yaml::Value::String("id".into())) .get(serde_yaml::Value::String("id".into()))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.map(|s| s.to_string()) .map(|s| s.to_string())
.filter(|s| !s.is_empty()) .filter(|s| !s.is_empty())
@@ -293,9 +340,9 @@ fn normalize_frontmatter(raw: &str, path: &Path) -> (NoteMeta, String) {
.iter() .iter()
.find_map(|key| { .find_map(|key| {
mapping mapping
.get(&serde_yaml::Value::String((*key).into())) .get(serde_yaml::Value::String((*key).into()))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.and_then(|s| frontmatter::parse_date_flexible(s)) .and_then(frontmatter::parse_date_flexible)
}) })
.or_else(|| file_created(path)) .or_else(|| file_created(path))
.unwrap_or_else(Utc::now); .unwrap_or_else(Utc::now);
@@ -304,15 +351,15 @@ fn normalize_frontmatter(raw: &str, path: &Path) -> (NoteMeta, String) {
.iter() .iter()
.find_map(|key| { .find_map(|key| {
mapping mapping
.get(&serde_yaml::Value::String((*key).into())) .get(serde_yaml::Value::String((*key).into()))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.and_then(|s| frontmatter::parse_date_flexible(s)) .and_then(frontmatter::parse_date_flexible)
}) })
.or_else(|| file_modified(path)) .or_else(|| file_modified(path))
.unwrap_or_else(Utc::now); .unwrap_or_else(Utc::now);
let pinned = mapping let pinned = mapping
.get(&serde_yaml::Value::String("pinned".into())) .get(serde_yaml::Value::String("pinned".into()))
.and_then(|v| v.as_bool()) .and_then(|v| v.as_bool())
.unwrap_or(false); .unwrap_or(false);
@@ -332,7 +379,7 @@ fn normalize_tags(mapping: &serde_yaml::Mapping) -> Vec<String> {
let mut seen = HashSet::new(); let mut seen = HashSet::new();
for key in &["tags", "tag"] { for key in &["tags", "tag"] {
if let Some(val) = mapping.get(&serde_yaml::Value::String((*key).into())) { if let Some(val) = mapping.get(serde_yaml::Value::String((*key).into())) {
for raw in yaml_value_to_strings(val) { for raw in yaml_value_to_strings(val) {
let cleaned = raw.trim().trim_start_matches('#').trim().to_string(); let cleaned = raw.trim().trim_start_matches('#').trim().to_string();
if !cleaned.is_empty() && seen.insert(cleaned.to_lowercase()) { if !cleaned.is_empty() && seen.insert(cleaned.to_lowercase()) {
@@ -389,9 +436,7 @@ fn file_created(path: &Path) -> Option<chrono::DateTime<Utc>> {
.ok() .ok()
.and_then(|m| m.created().ok()) .and_then(|m| m.created().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.and_then(|d| { .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos()))
chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos())
})
} }
fn file_modified(path: &Path) -> Option<chrono::DateTime<Utc>> { fn file_modified(path: &Path) -> Option<chrono::DateTime<Utc>> {
@@ -399,9 +444,7 @@ fn file_modified(path: &Path) -> Option<chrono::DateTime<Utc>> {
.ok() .ok()
.and_then(|m| m.modified().ok()) .and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.and_then(|d| { .and_then(|d| chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos()))
chrono::DateTime::from_timestamp(d.as_secs() as i64, d.subsec_nanos())
})
} }
fn convert_syntax(content: &str, highlight_re: &Regex, comment_re: &Regex) -> String { fn convert_syntax(content: &str, highlight_re: &Regex, comment_re: &Regex) -> String {
@@ -513,7 +556,9 @@ fn fix_md_link_refs(
let display = &caps[1]; let display = &caps[1];
let href = &caps[2]; let href = &caps[2];
let decoded = percent_decode(href); let decoded = percent_decode(href);
if decoded.starts_with("http") || decoded.starts_with('/') || decoded.starts_with("data:") if decoded.starts_with("http")
|| decoded.starts_with('/')
|| decoded.starts_with("data:")
|| decoded.starts_with('#') || decoded.starts_with('#')
{ {
return format!("[{}]({})", display, href); return format!("[{}]({})", display, href);
@@ -549,82 +594,117 @@ fn fix_md_link_refs(
.to_string() .to_string()
} }
fn move_attachments( fn ensure_attachment_parent(
vault: &Path, vault: &Path,
) -> Result<HashMap<String, String>, String> { canonical_vault: &Path,
parent: &Path,
) -> Result<(), String> {
let relative = parent
.strip_prefix(vault)
.map_err(|e| format!("Invalid attachment destination {}: {e}", parent.display()))?;
let mut current = vault.to_path_buf();
let mut relative_path = PathBuf::new();
for component in relative.components() {
current.push(component);
relative_path.push(component);
match std::fs::create_dir(&current) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(format!("Creating {}: {e}", current.display())),
}
let canonical = std::fs::canonicalize(&current)
.map_err(|e| format!("Resolving {}: {e}", current.display()))?;
if !current.is_dir() || canonical != canonical_vault.join(&relative_path) {
return Err(format!(
"Attachment destination escapes vault: {}",
current.display()
));
}
}
Ok(())
}
fn move_attachments(vault: &Path) -> Result<HashMap<String, String>, String> {
let attachments_dir = vault.join(".helixnotes").join("attachments"); let attachments_dir = vault.join(".helixnotes").join("attachments");
let _ = std::fs::create_dir_all(&attachments_dir); let attachment_files: Vec<_> = scanned_files(vault)?
let attachment_files: Vec<_> = walkdir::WalkDir::new(vault)
.into_iter() .into_iter()
.filter_map(|e| e.ok()) .filter(|p| p.extension().and_then(|x| x.to_str()) != Some("md"))
.filter(|e| {
let p = e.path();
if !p.is_file() {
return false;
}
if p.extension().and_then(|x| x.to_str()) == Some("md") {
return false;
}
let path_str = p.to_string_lossy();
!path_str.contains("/.helixnotes/")
&& !path_str.contains("/.obsidian/")
&& !path_str.contains("/.trash/")
&& !path_str.contains("/.stfolder")
&& !path_str.contains("/.claude/")
})
.map(|e| e.path().to_path_buf())
.collect(); .collect();
let canonical_vault =
std::fs::canonicalize(vault).map_err(|e| format!("Resolving {}: {e}", vault.display()))?;
let mut moved: HashMap<String, String> = HashMap::new(); let mut moved = HashMap::new();
for src_path in attachment_files {
let old_rel = vault_relative(&src_path, vault)?;
let preferred = attachments_dir.join(&old_rel);
let parent = preferred.parent().expect("attachment has a parent");
ensure_attachment_parent(vault, &canonical_vault, parent)?;
for src_path in &attachment_files { // Reserve the destination atomically: neither rename nor std::fs::copy protects
let old_rel = match src_path.strip_prefix(vault) { // a pre-existing attachment (or one created concurrently) from replacement.
Ok(r) => r.to_string_lossy().to_string(), let mut suffix = 0u64;
Err(_) => continue, let (dest_path, mut dest) = loop {
let candidate = if suffix == 0 {
preferred.clone()
} else {
let stem = preferred.file_stem().unwrap_or_default().to_string_lossy();
let ext = preferred
.extension()
.map(|ext| format!(".{}", ext.to_string_lossy()))
.unwrap_or_default();
preferred.with_file_name(format!("{stem}-{suffix}{ext}"))
}; };
let new_rel = format!(".helixnotes/attachments/{}", old_rel); match OpenOptions::new()
let dest_path = vault.join(&new_rel); .write(true)
.create_new(true)
if let Some(parent) = dest_path.parent() { .open(&candidate)
let _ = std::fs::create_dir_all(parent);
}
if std::fs::rename(src_path, &dest_path).is_ok()
|| std::fs::copy(src_path, &dest_path)
.and_then(|_| std::fs::remove_file(src_path))
.is_ok()
{ {
moved.insert(old_rel, new_rel); Ok(file) => break (candidate, file),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
suffix = suffix
.checked_add(1)
.ok_or("Too many attachment collisions")?;
} }
Err(e) => return Err(format!("Creating {}: {e}", candidate.display())),
}
};
let copied = (|| -> io::Result<()> {
let mut src = std::fs::File::open(&src_path)?;
io::copy(&mut src, &mut dest)?;
dest.sync_all()?;
Ok(())
})();
drop(dest);
if let Err(e) = copied {
std::fs::remove_file(&dest_path).map_err(|cleanup| {
format!(
"Copying {} to {}: {e}; removing incomplete copy: {cleanup}",
src_path.display(),
dest_path.display()
)
})?;
return Err(format!(
"Copying {} to {}: {e}",
src_path.display(),
dest_path.display()
));
}
moved.insert(old_rel, vault_relative(&dest_path, vault)?);
} }
Ok(moved) Ok(moved)
} }
fn rewrite_attachment_refs( fn rewrite_attachment_refs(vault: &Path, moved: &HashMap<String, String>) -> Result<(), String> {
vault: &Path,
moved: &HashMap<String, String>,
) -> Result<(), String> {
let md_ref = Regex::new(r"(!?\[[^\]]*\])\(([^)]+)\)").map_err(|e| e.to_string())?; let md_ref = Regex::new(r"(!?\[[^\]]*\])\(([^)]+)\)").map_err(|e| e.to_string())?;
let md_files: Vec<_> = walkdir::WalkDir::new(vault) let md_files: Vec<_> = scanned_files(vault)?
.into_iter() .into_iter()
.filter_map(|e| e.ok()) .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md"))
.filter(|e| {
let p = e.path();
p.is_file()
&& p.extension().and_then(|x| x.to_str()) == Some("md")
&& !p.to_string_lossy().contains("/.helixnotes/")
&& !p.to_string_lossy().contains("/.trash/")
})
.map(|e| e.path().to_path_buf())
.collect(); .collect();
for path in &md_files { for path in &md_files {
let content = match std::fs::read_to_string(path) { let content = std::fs::read_to_string(path)
Ok(c) => c, .map_err(|e| format!("Reading {}: {e}", path.display()))?;
Err(_) => continue,
};
let note_dir = path.parent().unwrap_or(Path::new("")); let note_dir = path.parent().unwrap_or(Path::new(""));
let new_content = md_ref let new_content = md_ref
@@ -632,28 +712,29 @@ fn rewrite_attachment_refs(
let prefix = &caps[1]; let prefix = &caps[1];
let href = &caps[2]; let href = &caps[2];
let decoded_href = percent_decode(href); let decoded_href = percent_decode(href);
let (reference, suffix) = decoded_href
.find(['#', '?'])
.map(|index| decoded_href.split_at(index))
.unwrap_or((&decoded_href, ""));
if decoded_href.starts_with("http") || decoded_href.starts_with("data:") { if reference.starts_with("http")
|| reference.starts_with("data:")
|| reference.starts_with('/')
{
return format!("{}({})", prefix, href); return format!("{}({})", prefix, href);
} }
let abs_from_note = note_dir.join(&decoded_href); let rel_from_note = note_dir
let rel_from_note = abs_from_note
.strip_prefix(vault) .strip_prefix(vault)
.ok() .ok()
.map(|r| r.to_string_lossy().to_string()); .and_then(|base| resolve_relative_ref(base, reference));
let rel_from_vault = decoded_href.clone();
let old_vault_rel = rel_from_note let old_vault_rel = rel_from_note
.as_ref() .as_ref()
.filter(|r| moved.contains_key(r.as_str())) .filter(|r| moved.contains_key(r.as_str()))
.cloned() .cloned()
.or_else(|| { .or_else(|| {
if moved.contains_key(&rel_from_vault) { resolve_relative_ref(Path::new(""), reference)
Some(rel_from_vault) .filter(|r| moved.contains_key(r.as_str()))
} else {
None
}
}); });
if let Some(old_rel) = old_vault_rel { if let Some(old_rel) = old_vault_rel {
@@ -664,7 +745,12 @@ fn rewrite_attachment_refs(
note_dir.to_str().unwrap_or(""), note_dir.to_str().unwrap_or(""),
) )
.unwrap_or(new_rel.clone()); .unwrap_or(new_rel.clone());
return format!("{}({})", prefix, new_note_rel.replace(' ', "%20")); return format!(
"{}({}{})",
prefix,
new_note_rel.replace('\\', "/").replace(' ', "%20"),
suffix
);
} }
} }
format!("{}({})", prefix, href) format!("{}({})", prefix, href)
@@ -672,33 +758,59 @@ fn rewrite_attachment_refs(
.to_string(); .to_string();
if new_content != content { if new_content != content {
let _ = std::fs::write(path, new_content); replace_file_atomically(path, new_content.as_bytes())
.map_err(|e| format!("Writing {}: {e}", path.display()))?;
} }
} }
Ok(()) Ok(())
} }
fn cleanup_empty_dirs(root: &Path) { fn resolve_relative_ref(base: &Path, reference: &str) -> Option<String> {
let mut dirs: Vec<_> = walkdir::WalkDir::new(root) let mut rel = base.to_path_buf();
.into_iter() for component in Path::new(&reference.replace('\\', "/")).components() {
.filter_map(|e| e.ok()) match component {
.filter(|e| e.path().is_dir()) std::path::Component::Normal(name) => rel.push(name),
.map(|e| e.path().to_path_buf()) std::path::Component::ParentDir => {
.collect(); if !rel.pop() {
return None;
}
}
std::path::Component::CurDir => {}
_ => return None,
}
}
Some(rel.to_string_lossy().replace('\\', "/"))
}
dirs.sort_by(|a, b| b.components().count().cmp(&a.components().count())); fn cleanup_empty_dirs(root: &Path) -> Result<(), String> {
let mut dirs: Vec<_> = vault_entries(root)
.filter_map(|entry| match entry {
Ok(entry) if entry.file_type().is_dir() => Some(Ok(entry.into_path())),
Ok(_) => None,
Err(e) => Some(Err(e)),
})
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("Scanning {}: {e}", root.display()))?;
dirs.sort_by_key(|path| std::cmp::Reverse(path.components().count()));
for dir in dirs { for dir in dirs {
let dir_str = dir.to_string_lossy(); if dir == root {
if dir_str.contains("/.helixnotes") || dir_str.contains("/.obsidian") || dir == root {
continue; continue;
} }
if let Ok(mut entries) = std::fs::read_dir(&dir) { let mut entries =
if entries.next().is_none() { std::fs::read_dir(&dir).map_err(|e| format!("Reading {}: {e}", dir.display()))?;
let _ = std::fs::remove_dir(&dir); if entries
} .next()
.transpose()
.map_err(|e| format!("Reading {}: {e}", dir.display()))?
.is_none()
{
std::fs::remove_dir(&dir)
.map_err(|e| format!("Removing empty directory {}: {e}", dir.display()))?;
} }
} }
Ok(())
} }
fn split_anchor(reference: &str) -> (&str, Option<&str>) { fn split_anchor(reference: &str) -> (&str, Option<&str>) {
@@ -719,7 +831,8 @@ fn is_dimension_spec(s: &str) -> bool {
if s.is_empty() { if s.is_empty() {
return false; return false;
} }
s.chars().all(|c| c.is_ascii_digit() || c == 'x' || c == 'X') s.chars()
.all(|c| c.is_ascii_digit() || c == 'x' || c == 'X')
} }
fn resolve_wiki_ref(file_index: &HashMap<String, String>, reference: &str) -> String { fn resolve_wiki_ref(file_index: &HashMap<String, String>, reference: &str) -> String {
@@ -766,7 +879,7 @@ fn pathdiff(target: &str, base: &str) -> Result<String, ()> {
for component in &target_components[common..] { for component in &target_components[common..] {
result.push(component); result.push(component);
} }
Ok(result.to_string_lossy().to_string()) Ok(result.to_string_lossy().replace('\\', "/"))
} }
fn percent_decode(s: &str) -> String { fn percent_decode(s: &str) -> String {
@@ -907,7 +1020,10 @@ mod tests {
extract_heading_title("# My Title\n\nBody"), extract_heading_title("# My Title\n\nBody"),
Some("My Title".to_string()) Some("My Title".to_string())
); );
assert_eq!(extract_heading_title("\n\n# Spaced Title"), Some("Spaced Title".to_string())); assert_eq!(
extract_heading_title("\n\n# Spaced Title"),
Some("Spaced Title".to_string())
);
assert_eq!(extract_heading_title("Body without heading"), None); assert_eq!(extract_heading_title("Body without heading"), None);
assert_eq!(extract_heading_title("## Subheading"), None); assert_eq!(extract_heading_title("## Subheading"), None);
assert_eq!(extract_heading_title(""), None); assert_eq!(extract_heading_title(""), None);
@@ -947,8 +1063,7 @@ mod tests {
#[test] #[test]
fn test_normalize_tags_strips_hash() { fn test_normalize_tags_strips_hash() {
let mapping: serde_yaml::Mapping = let mapping: serde_yaml::Mapping = serde_yaml::from_str("tags:\n - \"#hashed\"").unwrap();
serde_yaml::from_str("tags:\n - \"#hashed\"").unwrap();
let tags = normalize_tags(&mapping); let tags = normalize_tags(&mapping);
assert_eq!(tags, vec!["hashed"]); assert_eq!(tags, vec!["hashed"]);
} }
@@ -999,6 +1114,131 @@ mod tests {
assert_eq!(result, raw); assert_eq!(result, raw);
} }
#[test]
fn import_keeps_colliding_attachments_and_rewrites_note_relative_links() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path();
let note_dir = root.join("Notes");
let stored = root.join(".helixnotes/attachments/Notes");
std::fs::create_dir_all(&note_dir).unwrap();
std::fs::create_dir_all(&stored).unwrap();
std::fs::write(note_dir.join("pic.png"), b"NEW").unwrap();
std::fs::write(stored.join("pic.png"), b"OLD").unwrap();
std::fs::write(stored.join("pic-1.png"), b"OLDER").unwrap();
std::fs::write(
note_dir.join("Entry.md"),
"# Entry\n\n![picture](pic.png) [picture](./pic.png#preview)",
)
.unwrap();
let result = import(root.to_str().unwrap()).unwrap();
assert_eq!(result.attachments_moved, 1);
assert_eq!(std::fs::read(stored.join("pic.png")).unwrap(), b"OLD");
assert_eq!(std::fs::read(stored.join("pic-1.png")).unwrap(), b"OLDER");
assert_eq!(std::fs::read(stored.join("pic-2.png")).unwrap(), b"NEW");
assert!(!note_dir.join("pic.png").exists());
let note = std::fs::read_to_string(note_dir.join("Entry.md")).unwrap();
assert!(note.contains("![picture](../.helixnotes/attachments/Notes/pic-2.png)"));
assert!(note.contains("[picture](../.helixnotes/attachments/Notes/pic-2.png#preview)"));
}
#[test]
fn import_prunes_metadata_directories_at_every_depth() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path();
for hidden in [".helixnotes", ".obsidian", ".trash", ".stfolder", ".claude"] {
for base in [root.to_path_buf(), root.join("Notebook")] {
let hidden_dir = base.join(hidden).join("history");
std::fs::create_dir_all(&hidden_dir).unwrap();
std::fs::write(hidden_dir.join("Secret.md"), "==untouched==").unwrap();
std::fs::write(hidden_dir.join("asset.bin"), b"untouched").unwrap();
}
}
let visible_dir = root.join("Notebook/stfolder-visible");
std::fs::create_dir_all(&visible_dir).unwrap();
std::fs::write(visible_dir.join("asset.bin"), b"visible").unwrap();
std::fs::write(
root.join("Note.md"),
"# Note\n\n![file](Notebook/stfolder-visible/asset.bin)",
)
.unwrap();
let result = import(root.to_str().unwrap()).unwrap();
assert_eq!(result.attachments_moved, 1);
assert_eq!(
std::fs::read(root.join(".helixnotes/attachments/Notebook/stfolder-visible/asset.bin"))
.unwrap(),
b"visible"
);
for hidden in [".helixnotes", ".obsidian", ".trash", ".stfolder", ".claude"] {
for base in [root.to_path_buf(), root.join("Notebook")] {
let hidden_dir = base.join(hidden).join("history");
assert_eq!(
std::fs::read_to_string(hidden_dir.join("Secret.md")).unwrap(),
"==untouched=="
);
assert_eq!(
std::fs::read(hidden_dir.join("asset.bin")).unwrap(),
b"untouched"
);
}
}
}
#[test]
fn destination_io_failure_leaves_original_attachment_in_place() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path();
std::fs::create_dir(root.join(".helixnotes")).unwrap();
std::fs::write(root.join(".helixnotes/attachments"), b"existing metadata").unwrap();
std::fs::write(root.join("asset.bin"), b"original").unwrap();
assert!(import(root.to_str().unwrap()).is_err());
assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original");
assert_eq!(
std::fs::read(root.join(".helixnotes/attachments")).unwrap(),
b"existing metadata"
);
}
#[test]
fn readonly_note_does_not_lose_original_or_attachment() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path();
let note = root.join("Note.md");
let original = "# Note\n\n![asset](asset.bin)";
std::fs::write(&note, original).unwrap();
std::fs::write(root.join("asset.bin"), b"original").unwrap();
let original_permissions = std::fs::metadata(&note).unwrap().permissions();
let mut permissions = original_permissions.clone();
permissions.set_readonly(true);
std::fs::set_permissions(&note, permissions).unwrap();
let result = import(root.to_str().unwrap());
assert!(result.is_err());
assert_eq!(std::fs::read_to_string(&note).unwrap(), original);
assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original");
std::fs::set_permissions(&note, original_permissions).unwrap();
}
#[cfg(unix)]
#[test]
fn attachment_directory_symlink_cannot_escape_vault() {
let vault = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let root = vault.path();
std::fs::create_dir(root.join(".helixnotes")).unwrap();
std::os::unix::fs::symlink(outside.path(), root.join(".helixnotes/attachments")).unwrap();
std::fs::write(root.join("asset.bin"), b"original").unwrap();
assert!(import(root.to_str().unwrap()).is_err());
assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original");
assert!(!outside.path().join("asset.bin").exists());
}
#[test] #[test]
fn test_split_anchor_same_note() { fn test_split_anchor_same_note() {
let (file, anchor) = split_anchor("#Heading"); let (file, anchor) = split_anchor("#Heading");
File diff suppressed because it is too large. Load diff
+344 -47
View File
@@ -1,78 +1,213 @@
use notify::{Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher}; use notify::event::{CreateKind, ModifyKind, RemoveKind, RenameMode};
use std::path::Path; use notify::{Config, Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::mpsc; use std::sync::mpsc;
use std::time::Duration; use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter, Manager}; use tauri::{AppHandle, Emitter, Manager};
use crate::state::AppState; use crate::state::AppState;
use crate::types::FileEvent; use crate::types::FileEvent;
use crate::vault::operations::helixnotes_dir; use crate::vault::operations::{is_hidden, read_note_entry_fast};
pub fn start_watcher(app: AppHandle, vault_path: String) -> Result<RecommendedWatcher, String> { const IOS_POLL_INTERVAL: Duration = Duration::from_secs(10);
const NATIVE_POLL_INTERVAL: Duration = Duration::from_secs(1);
const EVENT_BATCH_INTERVAL: Duration = Duration::from_millis(50);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WatcherBackend {
Recommended,
Poll,
}
const fn watcher_backend_for_target(is_ios: bool) -> WatcherBackend {
if is_ios {
WatcherBackend::Poll
} else {
WatcherBackend::Recommended
}
}
const fn poll_interval_for_backend(backend: WatcherBackend) -> Duration {
match backend {
WatcherBackend::Recommended => NATIVE_POLL_INTERVAL,
WatcherBackend::Poll => IOS_POLL_INTERVAL,
}
}
pub enum VaultWatcher {
Recommended(RecommendedWatcher),
Poll(PollWatcher),
}
impl VaultWatcher {
fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> notify::Result<()> {
match self {
Self::Recommended(watcher) => watcher.watch(path, recursive_mode),
Self::Poll(watcher) => watcher.watch(path, recursive_mode),
}
}
}
fn collect_changes(event: Event, vault_root: &Path, changes: &mut HashMap<PathBuf, &'static str>) {
let (default_type, may_be_directory) = match event.kind {
EventKind::Create(kind) => ("create", kind != CreateKind::File),
EventKind::Remove(kind) => ("remove", kind != RemoveKind::File),
EventKind::Modify(ModifyKind::Name(_)) => ("modify", true),
EventKind::Modify(_) => ("modify", false),
_ => return,
};
for (index, path) in event.paths.into_iter().enumerate() {
let Ok(relative) = path.strip_prefix(vault_root) else {
continue;
};
if !relative.components().all(|component| match component {
Component::Normal(name) => !is_hidden(Path::new(name)),
Component::CurDir => true,
_ => false,
}) {
continue;
}
// Removed/renamed directories no longer pass is_dir(). Retain unknown
// missing paths so external notebook changes still reach the UI.
if path.extension().and_then(|extension| extension.to_str()) != Some("md")
&& !path.is_dir()
&& !(may_be_directory && !path.exists())
{
continue;
}
let event_type = match event.kind {
EventKind::Modify(ModifyKind::Name(RenameMode::From)) => "remove",
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) if index == 0 => "remove",
_ => default_type,
};
changes.insert(path, event_type);
}
}
pub(crate) fn changed_entry(path: PathBuf, event_type: &str, vault_root: &Path) -> FileEvent {
let is_note =
path.extension().and_then(|extension| extension.to_str()) == Some("md") && path.is_file();
let note = if is_note {
read_note_entry_fast(&path, vault_root).ok()
} else {
None
};
// Atomic replacement may also report removal of the old destination. The
// final filesystem state, not the platform's rename spelling, is authoritative.
let event_type = if path.exists() {
if event_type == "remove" {
"modify"
} else {
event_type
}
} else {
"remove"
};
FileEvent {
vault_path: vault_root.to_string_lossy().to_string(),
event_type: event_type.to_string(),
path: path.to_string_lossy().to_string(),
note,
}
}
pub fn start_watcher(app: AppHandle, vault_path: String) -> Result<VaultWatcher, String> {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
let mut watcher = RecommendedWatcher::new( let backend = watcher_backend_for_target(cfg!(target_os = "ios"));
tx, let config = Config::default().with_poll_interval(poll_interval_for_backend(backend));
Config::default().with_poll_interval(Duration::from_secs(1)), let mut watcher = match backend {
) WatcherBackend::Recommended => VaultWatcher::Recommended(
.map_err(|e| e.to_string())?; RecommendedWatcher::new(tx, config).map_err(|e| e.to_string())?,
),
WatcherBackend::Poll => {
VaultWatcher::Poll(PollWatcher::new(tx, config).map_err(|e| e.to_string())?)
}
};
watcher watcher
.watch(Path::new(&vault_path), RecursiveMode::Recursive) .watch(Path::new(&vault_path), RecursiveMode::Recursive)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let hn_dir = helixnotes_dir(&vault_path);
std::thread::spawn(move || { std::thread::spawn(move || {
while let Ok(result) = rx.recv() { let vault_root = Path::new(&vault_path);
let mut changes = HashMap::new();
let mut search = None;
loop {
let first = if changes.is_empty() {
match rx.recv() {
Ok(event) => Some(event),
Err(_) => return,
}
} else {
match rx.recv_timeout(EVENT_BATCH_INTERVAL) {
Ok(event) => Some(event),
Err(mpsc::RecvTimeoutError::Timeout) => None,
Err(mpsc::RecvTimeoutError::Disconnected) => return,
}
};
let deadline = Instant::now() + EVENT_BATCH_INTERVAL;
let mut next = first;
while let Some(result) = next {
match result { match result {
Ok(event) => { Ok(event) => {
// Skip all file events while importing collect_changes(event, vault_root, &mut changes);
}
Err(error) => log::error!("File watcher error: {error}"),
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
break;
}
next = rx.recv_timeout(remaining).ok();
}
let state = app.state::<AppState>(); let state = app.state::<AppState>();
// Native note mutations hold note_save through their path event.
// Read and emit only after they finish, so the watcher cannot
// publish an intermediate rename or stale note contents.
let _save_guard = state.note_save.blocking_lock();
// Keep the batch while muted, rather than losing concurrent external
// edits. Nothing is indexed or emitted until local imports finish.
if state.importing.load(std::sync::atomic::Ordering::Relaxed) { if state.importing.load(std::sync::atomic::Ordering::Relaxed) {
continue; continue;
} }
// Skip .helixnotes directory events // Each watcher belongs to its own vault. A detached note window may
let dominated_by_hn = event.paths.iter().all(|p| p.starts_with(&hn_dir)); // still need changes from a vault that is no longer active; never
if dominated_by_hn { // index those changes into the main window's active search index.
if state.validate_vault(&vault_path).is_err() {
continue; continue;
} }
if search.is_none() {
// Only care about .md file events match state.vault_snapshot(&vault_path) {
let has_md = event.paths.iter().any(|p| { Ok(index) => search = index,
p.extension().and_then(|x| x.to_str()) == Some("md") || p.is_dir() Err(error) => {
}); log::error!("Could not open search index for watched vault: {error}");
if !has_md {
continue; continue;
} }
let event_type = match event.kind {
EventKind::Create(_) => "create",
EventKind::Modify(_) => "modify",
EventKind::Remove(_) => "remove",
_ => continue,
};
for path in &event.paths {
let fe = FileEvent {
event_type: event_type.to_string(),
path: path.to_string_lossy().to_string(),
};
let _ = app.emit("file-changed", &fe);
} }
}
// On mobile, throttle event emission to prevent IPC flooding let mut refresh_vault = false;
// on FUSE filesystems where Syncthing/other apps generate for (path, event_type) in changes.drain() {
// constant file activity that blocks the Tauri command channel. if path.extension().and_then(|extension| extension.to_str()) == Some("md")
#[cfg(mobile)] && !path.is_dir()
{ {
std::thread::sleep(Duration::from_secs(2)); if let Some(search) = &search {
while rx.try_recv().is_ok() {} if let Err(error) = search.queue_index_note(&path.to_string_lossy()) {
log::error!("Could not queue external note for search: {error}");
} }
} }
Err(e) => { } else {
log::error!("File watcher error: {}", e); refresh_vault = true;
}
let event = changed_entry(path, event_type, vault_root);
let _ = app.emit("file-changed", &event);
}
if refresh_vault {
if let Some(search) = &search {
if let Err(error) = search.queue_vault_refresh(&vault_path) {
log::error!("Could not queue notebook search refresh: {error}");
}
} }
} }
} }
@@ -80,3 +215,165 @@ pub fn start_watcher(app: AppHandle, vault_path: String) -> Result<RecommendedWa
Ok(watcher) Ok(watcher)
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ios_uses_polling_backend() {
assert_eq!(watcher_backend_for_target(true), WatcherBackend::Poll);
}
#[test]
fn other_platforms_keep_recommended_backend() {
assert_eq!(
watcher_backend_for_target(false),
WatcherBackend::Recommended
);
}
#[test]
fn watcher_backends_use_the_expected_intervals() {
assert_eq!(
poll_interval_for_backend(WatcherBackend::Poll),
Duration::from_secs(10)
);
assert_eq!(
poll_interval_for_backend(WatcherBackend::Recommended),
Duration::from_secs(1)
);
}
fn mapped_events(events: Vec<Event>, vault_root: &Path) -> Vec<FileEvent> {
let mut changes = HashMap::new();
for event in events {
collect_changes(event, vault_root, &mut changes);
}
changes
.into_iter()
.map(|(path, event_type)| changed_entry(path, event_type, vault_root))
.collect()
}
#[test]
fn atomic_replace_emits_only_enriched_destination() {
let vault = tempfile::tempdir().unwrap();
let target = vault.path().join("Note.md");
let temporary = vault.path().join(".helixnotes-save-123");
std::fs::write(&target, "---\ntitle: New title\n---\nUpdated preview.").unwrap();
let events = mapped_events(
vec![
Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Both)))
.add_path(temporary)
.add_path(target.clone()),
Event::new(EventKind::Remove(RemoveKind::File)).add_path(target.clone()),
Event::new(EventKind::Create(CreateKind::File))
.add_path(vault.path().join(".helixnotes/history/snapshot.md")),
Event::new(EventKind::Create(CreateKind::File))
.add_path(vault.path().join(".hidden/secret.md")),
],
vault.path(),
);
assert_eq!(events.len(), 1);
assert_eq!(events[0].path, target.to_string_lossy());
assert_eq!(events[0].event_type, "modify");
let note = events[0].note.as_ref().unwrap();
assert_eq!(note.meta.title, "New title");
assert_eq!(note.relative_path, "Note.md");
assert_eq!(note.preview, "Updated preview.");
}
#[test]
fn external_note_and_directory_renames_keep_both_sides() {
let vault = tempfile::tempdir().unwrap();
let old_note = vault.path().join("Before.md");
let new_note = vault.path().join("After.md");
let old_directory = vault.path().join("Old.notebook");
let new_directory = vault.path().join("New.notebook");
std::fs::write(&new_note, "renamed note").unwrap();
std::fs::create_dir(&new_directory).unwrap();
let events = mapped_events(
vec![
Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Both)))
.add_path(old_note.clone())
.add_path(new_note.clone()),
Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Both)))
.add_path(old_directory.clone())
.add_path(new_directory.clone()),
],
vault.path(),
);
for removed in [old_note, old_directory] {
let event = events
.iter()
.find(|event| event.path == removed.to_string_lossy())
.unwrap();
assert_eq!(event.event_type, "remove");
assert!(event.note.is_none());
}
let note = events
.iter()
.find(|event| event.path == new_note.to_string_lossy())
.unwrap();
assert_eq!(note.event_type, "modify");
assert!(note.note.is_some());
let directory = events
.iter()
.find(|event| event.path == new_directory.to_string_lossy())
.unwrap();
assert_eq!(directory.event_type, "modify");
assert!(directory.note.is_none());
}
#[test]
fn batching_keeps_distinct_external_changes_and_deleted_directories() {
let vault = tempfile::tempdir().unwrap();
let first = vault.path().join("First.md");
let second = vault.path().join("Second.md");
let removed = vault.path().join("Removed.notebook");
std::fs::write(&first, "first external change").unwrap();
std::fs::write(&second, "second external change").unwrap();
let events = mapped_events(
vec![
Event::new(EventKind::Create(CreateKind::File)).add_path(first.clone()),
Event::new(EventKind::Modify(ModifyKind::Any)).add_path(first.clone()),
Event::new(EventKind::Create(CreateKind::File)).add_path(second.clone()),
Event::new(EventKind::Remove(RemoveKind::Folder)).add_path(removed.clone()),
],
vault.path(),
);
let first_event = events
.iter()
.find(|event| event.path == first.to_string_lossy())
.unwrap();
assert_eq!(
first_event.note.as_ref().unwrap().preview,
"first external change"
);
let second_event = events
.iter()
.find(|event| event.path == second.to_string_lossy())
.unwrap();
assert_eq!(
second_event.note.as_ref().unwrap().preview,
"second external change"
);
let removed_event = events
.iter()
.find(|event| event.path == removed.to_string_lossy())
.unwrap();
assert_eq!(removed_event.event_type, "remove");
assert!(removed_event.note.is_none());
assert_eq!(
events
.iter()
.filter(|event| event.path == first.to_string_lossy())
.count(),
1
);
}
}
+7 -3
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "HelixNotes", "productName": "HelixNotes",
"version": "1.3.4", "version": "1.3.6",
"identifier": "com.helixnotes.app", "identifier": "com.helixnotes.app",
"build": { "build": {
"frontendDist": "../build", "frontendDist": "../build",
@@ -24,10 +24,14 @@
} }
], ],
"security": { "security": {
"csp": "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' asset: http://asset.localhost imgproxy: http://imgproxy.localhost https: blob: data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self' asset: http://asset.localhost", "csp": "default-src 'self'; img-src 'self' asset: http://asset.localhost imgproxy: http://imgproxy.localhost https: blob: data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self' asset: http://asset.localhost",
"assetProtocol": { "assetProtocol": {
"enable": true, "enable": true,
"scope": ["**/*", "/**", "**/.helixnotes/**"] "scope": {
"allow": [],
"deny": [],
"requireLiteralLeadingDot": true
}
} }
} }
}, },
+18
View File
@@ -0,0 +1,18 @@
{
"app": {
"windows": [
{
"title": "HelixNotes",
"label": "main",
"width": 1200,
"height": 800,
"minWidth": 800,
"minHeight": 500,
"resizable": true,
"fullscreen": false,
"decorations": false,
"visible": false
}
]
}
}
+168 -68
View File
@@ -7,15 +7,20 @@ import type {
NoteMeta, NoteMeta,
NotebookEntry, NotebookEntry,
NoteTitleEntry, NoteTitleEntry,
SearchResult, SearchPage,
TrashContents, TrashContents,
VaultState, VaultState,
VaultStats, VaultStats,
TagStyle,
TagStyleChange,
ImportResult, ImportResult,
BackupEntry, BackupEntry,
VersionEntry, VersionEntry,
TaskItem, TaskItem,
ExternalVaultResult, ExternalVaultResult,
StartupView,
ToolbarLayout,
PendingOpenFile,
} from "./types"; } from "./types";
export async function openVault(path: string): Promise<void> { export async function openVault(path: string): Promise<void> {
@@ -38,10 +43,22 @@ export async function getAppConfig(): Promise<AppConfig> {
return invoke("get_app_config"); return invoke("get_app_config");
} }
export async function completeWindowClose(): Promise<void> {
return invoke("complete_window_close");
}
export async function cancelWindowClose(): Promise<void> {
return invoke("cancel_window_close");
}
export async function setTheme(theme: string): Promise<void> { export async function setTheme(theme: string): Promise<void> {
return invoke("set_theme", { theme }); return invoke("set_theme", { theme });
} }
export async function setSystemThemes(light: string, dark: string): Promise<void> {
return invoke("set_system_themes", { light, dark });
}
export async function setAccentColor(color: string): Promise<void> { export async function setAccentColor(color: string): Promise<void> {
return invoke("set_accent_color", { color }); return invoke("set_accent_color", { color });
} }
@@ -66,6 +83,14 @@ export async function setFontSize(size: number): Promise<void> {
return invoke("set_font_size", { size }); return invoke("set_font_size", { size });
} }
export async function setScrollToChangeFontSize(enabled: boolean): Promise<void> {
return invoke("set_scroll_to_change_font_size", { enabled });
}
export async function setToolbarLayout(layout: ToolbarLayout | null): Promise<void> {
return invoke("set_toolbar_layout", { layout });
}
export async function setFontFamily(family: string): Promise<void> { export async function setFontFamily(family: string): Promise<void> {
return invoke("set_font_family", { family }); return invoke("set_font_family", { family });
} }
@@ -91,28 +116,31 @@ export async function countRootNotes(): Promise<number> {
} }
export async function createNotebook( export async function createNotebook(
vaultPath: string,
parentRelative: string | null, parentRelative: string | null,
name: string, name: string,
): Promise<NotebookEntry> { ): Promise<NotebookEntry> {
return invoke("create_notebook", { parentRelative, name }); return invoke("create_notebook", { vaultPath, parentRelative, name });
} }
export async function renameNotebook( export async function renameNotebook(
vaultPath: string,
path: string, path: string,
newName: string, newName: string,
): Promise<string> { ): Promise<string> {
return invoke("rename_notebook", { path, newName }); return invoke("rename_notebook", { vaultPath, path, newName });
} }
export async function deleteNotebook(path: string): Promise<void> { export async function deleteNotebook(vaultPath: string, path: string): Promise<void> {
return invoke("delete_notebook", { path }); return invoke("delete_notebook", { vaultPath, path });
} }
export async function moveNotebook( export async function moveNotebook(
vaultPath: string,
notebookPath: string, notebookPath: string,
destParent: string, destParent: string,
): Promise<string> { ): Promise<string> {
return invoke("move_notebook", { notebookPath, destParent }); return invoke("move_notebook", { vaultPath, notebookPath, destParent });
} }
export async function getNotes( export async function getNotes(
@@ -121,64 +149,80 @@ export async function getNotes(
return invoke("get_notes", { notebookPath }); return invoke("get_notes", { notebookPath });
} }
export async function readNote(path: string): Promise<NoteContent> { export async function readNote(vaultPath: string, path: string): Promise<NoteContent> {
return invoke("read_note", { path }); return invoke("read_note", { vaultPath, path });
} }
export async function saveNote( export async function saveNote(
vaultPath: string,
path: string, path: string,
meta: NoteMeta, meta: NoteMeta,
body: string, body: string,
): Promise<void> { expectedRaw: string,
return invoke("save_note", { path, meta, body }); ): Promise<NoteContent> {
return invoke("save_note", { vaultPath, path, meta, body, expectedRaw });
} }
export async function createNote( export async function createNote(
vaultPath: string,
notebookRelative: string | null, notebookRelative: string | null,
title: string, title: string,
): Promise<NoteEntry> { ): Promise<NoteEntry> {
return invoke("create_note", { notebookRelative, title }); return invoke("create_note", { vaultPath, notebookRelative, title });
} }
export async function createDailyNote(date?: string): Promise<NoteEntry> { export async function duplicateNote(vaultPath: string, path: string): Promise<NoteEntry> {
return invoke("create_daily_note", { date: date ?? null }); return invoke("duplicate_note", { vaultPath, path });
}
export async function createDailyNote(vaultPath: string, date?: string): Promise<NoteEntry> {
return invoke("create_daily_note", { vaultPath, date: date ?? null });
} }
export async function renameNote( export async function renameNote(
vaultPath: string,
path: string, path: string,
newTitle: string, newTitle: string,
): Promise<string> { ): Promise<string> {
return invoke("rename_note", { path, newTitle }); return invoke("rename_note", { vaultPath, path, newTitle });
} }
export async function deleteNote(path: string): Promise<void> { export async function deleteNote(vaultPath: string, path: string): Promise<void> {
return invoke("delete_note", { path }); return invoke("delete_note", { vaultPath, path });
} }
export async function moveNote( export async function moveNote(
vaultPath: string,
notePath: string, notePath: string,
destNotebook: string, destNotebook: string,
): Promise<string> { ): Promise<string> {
return invoke("move_note", { notePath, destNotebook }); return invoke("move_note", { vaultPath, notePath, destNotebook });
} }
export async function getAllTags(): Promise<[string, number][]> { export async function getAllTags(): Promise<[string, number][]> {
return invoke("get_all_tags"); return invoke("get_all_tags");
} }
export async function getAllNoteTitles(): Promise<NoteTitleEntry[]> { export async function getAllNoteTitles(vaultPath: string): Promise<NoteTitleEntry[]> {
return invoke("get_all_note_titles"); return invoke("get_all_note_titles", { vaultPath });
} }
export async function getGraphData(): Promise<{ nodes: { title: string; path: string }[]; edges: { source: number; target: number }[] }> { export async function getNoteSwitcherTitles(
return invoke("get_graph_data"); recentPaths: string[],
): Promise<NoteTitleEntry[]> {
return invoke("get_note_switcher_titles", { recentPaths });
}
export async function getGraphData(vaultPath: string): Promise<{ nodes: { title: string; path: string }[]; edges: { source: number; target: number; bidirectional: boolean }[] }> {
return invoke("get_graph_data", { vaultPath });
} }
export async function searchNotes( export async function searchNotes(
query: string, query: string,
limit?: number, limit?: number,
): Promise<SearchResult[]> { offset?: number,
return invoke("search_notes", { query, limit }); ): Promise<SearchPage> {
return invoke("search_notes", { query, limit, offset });
} }
export async function reindex(): Promise<void> { export async function reindex(): Promise<void> {
@@ -190,30 +234,35 @@ export async function getTrash(): Promise<TrashContents> {
} }
export async function restoreNote( export async function restoreNote(
vaultPath: string,
trashPath: string, trashPath: string,
destNotebook: string | null, destNotebook: string | null,
): Promise<string> { ): Promise<string> {
return invoke("restore_note", { trashPath, destNotebook }); return invoke("restore_note", { vaultPath, trashPath, destNotebook });
} }
export async function restoreNotebook(trashPath: string): Promise<string> { export async function restoreNotebook(vaultPath: string, trashPath: string): Promise<string> {
return invoke("restore_notebook", { trashPath }); return invoke("restore_notebook", { vaultPath, trashPath });
} }
export async function permanentDelete(path: string): Promise<void> { export async function permanentDelete(vaultPath: string, path: string): Promise<void> {
return invoke("permanent_delete", { path }); return invoke("permanent_delete", { vaultPath, path });
} }
export async function emptyTrash(): Promise<void> { export async function emptyTrash(vaultPath: string): Promise<void> {
return invoke("empty_trash"); return invoke("empty_trash", { vaultPath });
} }
export async function loadVaultState(): Promise<VaultState> { export async function loadVaultState(vaultPath: string): Promise<VaultState> {
return invoke("load_vault_state"); return invoke("load_vault_state", { vaultPath });
} }
export async function saveVaultState(vaultState: VaultState): Promise<void> { export async function saveVaultState(vaultPath: string, vaultState: VaultState): Promise<void> {
return invoke("save_vault_state", { vaultState }); return invoke("save_vault_state", { vaultPath, vaultState });
}
export async function copyTextToClipboard(text: string): Promise<void> {
return invoke("copy_text_to_clipboard", { text });
} }
export async function readClipboardImage(): Promise<number[]> { export async function readClipboardImage(): Promise<number[]> {
@@ -224,26 +273,58 @@ export async function copyImageToClipboard(path: string): Promise<void> {
return invoke("copy_image_to_clipboard", { path }); return invoke("copy_image_to_clipboard", { path });
} }
export async function saveImage(name: string, data: number[]): Promise<string> { export async function saveImage(vaultPath: string, name: string, data: number[]): Promise<string> {
return invoke("save_image", { name, data }); return invoke("save_image", { vaultPath, name, data });
} }
export async function saveAttachment( export async function saveAttachment(
vaultPath: string,
name: string, name: string,
data: number[], data: number[],
): Promise<string> { ): Promise<string> {
return invoke("save_attachment", { name, data }); return invoke("save_attachment", { vaultPath, name, data });
} }
export async function getNotebookIcons(): Promise<Record<string, string>> { export async function getNotebookIcons(vaultPath: string): Promise<Record<string, string>> {
return invoke("get_notebook_icons"); return invoke("get_notebook_icons", { vaultPath });
} }
export async function setNotebookIcon( export async function setNotebookIcon(
vaultPath: string,
notebookRelative: string, notebookRelative: string,
iconRelative: string | null, iconRelative: string | null,
): Promise<void> { ): Promise<void> {
return invoke("set_notebook_icon", { notebookRelative, iconRelative }); return invoke("set_notebook_icon", { vaultPath, notebookRelative, iconRelative });
}
export async function getTagStyles(vaultPath: string): Promise<Record<string, TagStyle>> {
return invoke("get_tag_styles", { vaultPath });
}
export async function setTagStyle(
vaultPath: string,
tag: string,
change: TagStyleChange,
): Promise<TagStyle | null> {
return invoke("set_tag_style", { vaultPath, tag, change });
}
export async function importNotebookIcon(
vaultPath: string,
notebookRelative: string,
name: string,
data: number[],
): Promise<string> {
return invoke("import_notebook_icon", { vaultPath, notebookRelative, name, data });
}
export async function importTagIcon(
vaultPath: string,
tag: string,
name: string,
data: number[],
): Promise<TagStyle> {
return invoke("import_tag_icon", { vaultPath, tag, name, data });
} }
export async function setGeneralSettings( export async function setGeneralSettings(
@@ -260,10 +341,13 @@ export async function setGeneralSettings(
showLineNumbers: boolean, showLineNumbers: boolean,
showLinkArrows: boolean, showLinkArrows: boolean,
defaultViewMode: boolean, defaultViewMode: boolean,
newNotesInSourceMode: boolean,
showTrayIcon: boolean, showTrayIcon: boolean,
closeToTray: boolean, closeToTray: boolean,
enableWikiLinks: boolean, enableWikiLinks: boolean,
showNoteDates: boolean, showNoteDates: boolean,
showNoteSwitcher: boolean,
startupView: StartupView,
restoreLastSession: boolean, restoreLastSession: boolean,
showAllNotes: boolean, showAllNotes: boolean,
showQuickAccess: boolean, showQuickAccess: boolean,
@@ -285,10 +369,13 @@ export async function setGeneralSettings(
showLineNumbers, showLineNumbers,
showLinkArrows, showLinkArrows,
defaultViewMode, defaultViewMode,
newNotesInSourceMode,
showTrayIcon, showTrayIcon,
closeToTray, closeToTray,
enableWikiLinks, enableWikiLinks,
showNoteDates, showNoteDates,
showNoteSwitcher,
startupView,
restoreLastSession, restoreLastSession,
showAllNotes, showAllNotes,
showQuickAccess, showQuickAccess,
@@ -298,16 +385,16 @@ export async function setGeneralSettings(
}); });
} }
export async function getQuickAccess(): Promise<NoteEntry[]> { export async function getQuickAccess(vaultPath: string): Promise<NoteEntry[]> {
return invoke("get_quick_access"); return invoke("get_quick_access", { vaultPath });
} }
export async function addQuickAccess(noteRelative: string): Promise<void> { export async function addQuickAccess(vaultPath: string, noteRelative: string): Promise<void> {
return invoke("add_quick_access", { noteRelative }); return invoke("add_quick_access", { vaultPath, noteRelative });
} }
export async function removeQuickAccess(noteRelative: string): Promise<void> { export async function removeQuickAccess(vaultPath: string, noteRelative: string): Promise<void> {
return invoke("remove_quick_access", { noteRelative }); return invoke("remove_quick_access", { vaultPath, noteRelative });
} }
export async function reorderQuickAccess(paths: string[]): Promise<void> { export async function reorderQuickAccess(paths: string[]): Promise<void> {
@@ -323,12 +410,12 @@ export interface OrphanAttachment {
size: number; size: number;
} }
export async function findOrphanedAttachments(): Promise<OrphanAttachment[]> { export async function findOrphanedAttachments(vaultPath: string): Promise<OrphanAttachment[]> {
return invoke("find_orphaned_attachments"); return invoke("find_orphaned_attachments", { vaultPath });
} }
export async function trashOrphanedAttachments(names: string[]): Promise<number> { export async function trashOrphanedAttachments(vaultPath: string, names: string[]): Promise<number> {
return invoke("trash_orphaned_attachments", { names }); return invoke("trash_orphaned_attachments", { vaultPath, names });
} }
export async function importObsidian(): Promise<void> { export async function importObsidian(): Promise<void> {
@@ -339,6 +426,10 @@ export async function openFile(path: string): Promise<void> {
return invoke("open_file", { path }); return invoke("open_file", { path });
} }
export async function revealFile(path: string): Promise<void> {
return invoke("reveal_file", { path });
}
export async function openUrl(url: string): Promise<void> { export async function openUrl(url: string): Promise<void> {
return invoke("open_url", { url }); return invoke("open_url", { url });
} }
@@ -363,20 +454,20 @@ export async function copyPngToClipboard(data: Uint8Array): Promise<void> {
// ── Backup ── // ── Backup ──
export async function createBackup(): Promise<void> { export async function createBackup(vaultPath: string): Promise<void> {
return invoke("create_backup"); return invoke("create_backup", { vaultPath });
} }
export async function listBackups(): Promise<BackupEntry[]> { export async function listBackups(vaultPath: string): Promise<BackupEntry[]> {
return invoke("list_backups"); return invoke("list_backups", { vaultPath });
} }
export async function restoreBackup(backupPath: string): Promise<void> { export async function restoreBackup(vaultPath: string, backupPath: string): Promise<void> {
return invoke("restore_backup", { backupPath }); return invoke("restore_backup", { vaultPath, backupPath });
} }
export async function deleteBackup(backupPath: string): Promise<void> { export async function deleteBackup(vaultPath: string, backupPath: string): Promise<void> {
return invoke("delete_backup", { backupPath }); return invoke("delete_backup", { vaultPath, backupPath });
} }
export async function setBackupSettings( export async function setBackupSettings(
@@ -397,35 +488,38 @@ export async function setBackupSettings(
// ── Tasks ── // ── Tasks ──
export async function getTasks(): Promise<TaskItem[]> { export async function getTasks(notePath?: string): Promise<TaskItem[]> {
return invoke("get_tasks"); return invoke("get_tasks", { notePath: notePath ?? null });
} }
export async function setTaskDone( export async function setTaskDone(
vaultPath: string,
notePath: string, notePath: string,
line: number, line: number,
rawLine: string, rawLine: string,
done: boolean, done: boolean,
): Promise<void> { ): Promise<void> {
return invoke("set_task_done", { notePath, line, rawLine, done }); return invoke("set_task_done", { vaultPath, notePath, line, rawLine, done });
} }
export async function setTaskPriority( export async function setTaskPriority(
vaultPath: string,
notePath: string, notePath: string,
line: number, line: number,
rawLine: string, rawLine: string,
priority: string | null, priority: string | null,
): Promise<void> { ): Promise<void> {
return invoke("set_task_priority", { notePath, line, rawLine, priority }); return invoke("set_task_priority", { vaultPath, notePath, line, rawLine, priority });
} }
export async function setTaskDue( export async function setTaskDue(
vaultPath: string,
notePath: string, notePath: string,
line: number, line: number,
rawLine: string, rawLine: string,
due: string | null, due: string | null,
): Promise<void> { ): Promise<void> {
return invoke("set_task_due", { notePath, line, rawLine, due }); return invoke("set_task_due", { vaultPath, notePath, line, rawLine, due });
} }
// ── Sync (WebDAV) ── // ── Sync (WebDAV) ──
@@ -452,22 +546,24 @@ export async function syncNow(): Promise<void> {
// ── Version History ── // ── Version History ──
export async function getNoteVersions(noteId: string): Promise<VersionEntry[]> { export async function getNoteVersions(vaultPath: string, noteId: string): Promise<VersionEntry[]> {
return invoke("get_note_versions", { noteId }); return invoke("get_note_versions", { vaultPath, noteId });
} }
export async function getNoteVersionContent( export async function getNoteVersionContent(
vaultPath: string,
noteId: string, noteId: string,
timestamp: string, timestamp: string,
): Promise<string> { ): Promise<string> {
return invoke("get_note_version_content", { noteId, timestamp }); return invoke("get_note_version_content", { vaultPath, noteId, timestamp });
} }
export async function createVersion( export async function createVersion(
vaultPath: string,
path: string, path: string,
noteId: string, noteId: string,
): Promise<void> { ): Promise<void> {
return invoke("create_version", { path, noteId }); return invoke("create_version", { vaultPath, path, noteId });
} }
// ── AI ── // ── AI ──
@@ -509,6 +605,10 @@ export async function isMobilePlatform(): Promise<boolean> {
return invoke("is_mobile_platform"); return invoke("is_mobile_platform");
} }
export async function getPendingOpenFile(): Promise<string | null> { export async function getPendingOpenFile(): Promise<PendingOpenFile | null> {
return invoke("get_pending_open_file"); return invoke("get_pending_open_file");
} }
export async function ackPendingOpenFile(id: number): Promise<void> {
return invoke("ack_pending_open_file", { id });
}
File diff suppressed because it is too large. Load diff
+10 -6
View File
@@ -89,7 +89,6 @@
action: () => { action: () => {
$theme = 'system'; $theme = 'system';
setTheme('system'); setTheme('system');
applyTheme('system');
$showCommandPalette = false; $showCommandPalette = false;
} }
}, },
@@ -165,10 +164,15 @@
} }
}); });
function handleKeydown(e: KeyboardEvent) { function handleEscape(e: KeyboardEvent) {
if (e.key === 'Escape') { if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
$showCommandPalette = false; $showCommandPalette = false;
} else if (e.key === 'ArrowDown') { }
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'ArrowDown') {
e.preventDefault(); e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, filteredCommands.length - 1); selectedIndex = Math.min(selectedIndex + 1, filteredCommands.length - 1);
} else if (e.key === 'ArrowUp') { } else if (e.key === 'ArrowUp') {
@@ -187,7 +191,7 @@
if (namedThemes.includes(t)) { if (namedThemes.includes(t)) {
root.setAttribute('data-theme', t); root.setAttribute('data-theme', t);
if (darkThemes.includes(t)) root.classList.add('dark'); if (darkThemes.includes(t)) root.classList.add('dark');
} else if (t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) { } else if (t === 'dark') {
root.classList.add('dark'); root.classList.add('dark');
} }
} }
@@ -195,7 +199,7 @@
{#if $showCommandPalette} {#if $showCommandPalette}
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="palette-overlay" onclick={() => ($showCommandPalette = false)} onkeydown={handleKeydown}> <div class="palette-overlay" onclick={() => ($showCommandPalette = false)} onkeydowncapture={handleEscape} onkeydown={handleKeydown}>
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="palette-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}> <div class="palette-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
<div class="palette-input-wrapper"> <div class="palette-input-wrapper">
File diff suppressed because it is too large. Load diff
+70 -93
View File
@@ -1,8 +1,9 @@
<script lang="ts"> <script lang="ts">
import { onDestroy } from 'svelte'; import { onDestroy, untrack } from 'svelte';
import { getGraphData } from '$lib/api'; import { getGraphData } from '$lib/api';
import { activeNotePath, appConfig } from '$lib/stores/app'; import { activeNotePath, appConfig } from '$lib/stores/app';
import { isMobile } from '$lib/platform'; import { isMobile } from '$lib/platform';
import { applyGraphRepulsion } from '$lib/utils/graph-layout';
let { onclose, onnavigate }: { let { onclose, onnavigate }: {
onclose: () => void; onclose: () => void;
@@ -14,18 +15,18 @@
let searchQuery = $state(''); let searchQuery = $state('');
let localMode = $state(true); // default: show only active note's neighborhood let localMode = $state(true); // default: show only active note's neighborhood
const dataPromise = getGraphData(); const dataPromise = getGraphData($appConfig!.active_vault!);
interface GraphNode { id: string; title: string; path: string; x: number; y: number; vx: number; vy: number; } interface GraphNode { id: string; title: string; path: string; x: number; y: number; vx: number; vy: number; }
interface GraphEdge { sourceIdx: number; targetIdx: number; bidirectional: boolean; } interface GraphEdge { sourceIdx: number; targetIdx: number; bidirectional: boolean; }
interface LabelRect { x: number; y: number; w: number; h: number; } interface LabelRect { x: number; y: number; w: number; h: number; }
let nodes: GraphNode[] = []; let nodes = $state.raw<GraphNode[]>([]);
let edges: GraphEdge[] = []; let edges = $state.raw<GraphEdge[]>([]);
let nodeIndexMap: Map<string, number> = new Map(); let nodeIndexMap: Map<string, number> = new Map();
let connectedSet: Set<number> = new Set(); let connectedSet: Set<number> = new Set();
let nodeDegree: number[] = []; let nodeDegree: number[] = [];
let searchMatchSet: Set<number> | null = null; let searchMatchSet = $state.raw<Set<number> | null>(null);
let folderColorMap = new Map<string, string>(); let folderColorMap = new Map<string, string>();
let pan = { x: 0, y: 0 }; let pan = { x: 0, y: 0 };
@@ -39,14 +40,15 @@
let hoveredIdx = -1; let hoveredIdx = -1;
let hoveredNeighborSet: Set<number> = new Set(); let hoveredNeighborSet: Set<number> = new Set();
let hoveredEdgeSet: Set<number> = new Set(); let hoveredEdgeSet: Set<number> = new Set();
let glowPhase = 0; let activeNodeIdx = $state(-1);
let activeNodeIdx = -1;
let navigatedFromGraph = false; let navigatedFromGraph = false;
// Combined animation loop // Physics runs in short yielded batches; the completed graph is static.
let physicsRemaining = 0; let physicsRemaining = 0;
let animFrameId = 0; let physicsStep: Generator<void> | null = null;
let lastGlowTs = 0; const layoutChannel = new MessageChannel();
let layoutScheduled = false;
let disposed = false;
// DPI fix // DPI fix
let dpr = 1; let dpr = 1;
@@ -156,6 +158,7 @@
loading = true; loading = true;
try { try {
const data = await dataPromise; const data = await dataPromise;
if (disposed) return;
const w = canvasW || 800; const w = canvasW || 800;
const h = canvasH || 600; const h = canvasH || 600;
@@ -188,7 +191,6 @@
} catch (e) { } catch (e) {
console.error('Failed to build graph:', e); console.error('Failed to build graph:', e);
} }
loading = false;
startSimulation(); startSimulation();
} }
@@ -232,83 +234,60 @@
} }
function startSimulation() { function startSimulation() {
// Initial settle - enough for a rough layout, camera set after full physics // Keep the original initial layout; omit the animated settling tail.
for (let i = 0; i < 80; i++) simulate(); physicsRemaining = nodes.length > 0 ? 80 : 0;
physicsStep = null;
// Show the full graph while physics finishes settling
fitToView();
draw();
// Queue remaining physics - camera will snap to active note when done
physicsRemaining = Math.min(400, Math.max(150, nodes.length * 3));
startAnimLoop();
}
function startAnimLoop() {
if (animFrameId) cancelAnimationFrame(animFrameId);
lastGlowTs = 0;
function loop(ts: number) {
let needsDraw = false;
// Physics batch
if (physicsRemaining > 0) {
const batch = Math.min(20, physicsRemaining);
for (let i = 0; i < batch; i++) simulate();
physicsRemaining -= batch;
// When physics is fully settled, snap camera to active note
if (physicsRemaining === 0) { if (physicsRemaining === 0) {
if (activeNodeIdx >= 0) centerOnActiveNote(); else fitToView(); loading = false;
} draw();
needsDraw = true;
}
// Glow pulse for active node - throttled to ~30fps
if (activeNodeIdx >= 0) {
const elapsed = lastGlowTs > 0 ? Math.min(ts - lastGlowTs, 100) : 16.67;
if (lastGlowTs === 0 || ts - lastGlowTs >= 33) {
glowPhase += 0.04 * (elapsed / 16.67);
lastGlowTs = ts;
needsDraw = true;
}
}
if (needsDraw) draw();
if (physicsRemaining > 0 || activeNodeIdx >= 0) {
animFrameId = requestAnimationFrame(loop);
} else { } else {
animFrameId = 0; startLayoutLoop();
} }
} }
animFrameId = requestAnimationFrame(loop);
}
function simulate() { function startLayoutLoop() {
const nodeCount = nodes.length; if (disposed || layoutScheduled || physicsRemaining === 0) return;
function loop() {
layoutScheduled = false;
if (disposed) return;
// Yield between repulsion rows, including within a large physics step.
const deadline = performance.now() + 8;
do {
physicsStep ??= simulate();
if (physicsStep.next().done) {
physicsStep = null;
physicsRemaining--;
}
} while (physicsRemaining > 0 && performance.now() < deadline);
if (physicsRemaining === 0) {
loading = false;
if (activeNodeIdx >= 0) centerOnActiveNote(); else fitToView();
draw();
} else {
layoutScheduled = true;
layoutChannel.port2.postMessage(null);
}
}
// A queued task yields to input without waiting for a display frame or timer clamp.
layoutChannel.port1.onmessage = loop;
layoutScheduled = true;
layoutChannel.port2.postMessage(null);
}
function* simulate(): Generator<void> {
const graphNodes = nodes;
const nodeCount = graphNodes.length;
if (nodeCount === 0) return; if (nodeCount === 0) return;
const w = canvasW || 800, h = canvasH || 600; const w = canvasW || 800, h = canvasH || 600;
const centerX = w / 2, centerY = h / 2; const centerX = w / 2, centerY = h / 2;
// Repulsion yield* applyGraphRepulsion(graphNodes);
for (let i = 0; i < nodeCount; i++) {
const a = nodes[i];
for (let j = i + 1; j < nodeCount; j++) {
const b = nodes[j];
const dx = b.x - a.x, dy = b.y - a.y;
const distSq = dx * dx + dy * dy;
if (distSq > 360000) continue;
const d = distSq || 1;
const force = 1500 / d;
const dist = Math.sqrt(d);
const fx = (dx / dist) * force, fy = (dy / dist) * force;
a.vx -= fx; a.vy -= fy; b.vx += fx; b.vy += fy;
}
}
// Spring attraction along edges // Spring attraction along edges
for (const edge of edges) { for (const edge of edges) {
const a = nodes[edge.sourceIdx], b = nodes[edge.targetIdx]; const a = graphNodes[edge.sourceIdx], b = graphNodes[edge.targetIdx];
const dx = b.x - a.x, dy = b.y - a.y; const dx = b.x - a.x, dy = b.y - a.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1; const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = (dist - 130) * 0.012; const force = (dist - 130) * 0.012;
@@ -318,14 +297,14 @@
// Center gravity - weaker for isolated nodes so they spread instead of clustering // Center gravity - weaker for isolated nodes so they spread instead of clustering
for (let i = 0; i < nodeCount; i++) { for (let i = 0; i < nodeCount; i++) {
const node = nodes[i]; const node = graphNodes[i];
const gravity = (nodeDegree[i] || 0) === 0 ? 0.0002 : 0.0008; const gravity = (nodeDegree[i] || 0) === 0 ? 0.0002 : 0.0008;
node.vx += (centerX - node.x) * gravity; node.vx += (centerX - node.x) * gravity;
node.vy += (centerY - node.y) * gravity; node.vy += (centerY - node.y) * gravity;
} }
// Damping + integration // Damping + integration
for (const node of nodes) { for (const node of graphNodes) {
if (node === dragging) continue; if (node === dragging) continue;
node.vx *= 0.85; node.vy *= 0.85; node.vx *= 0.85; node.vy *= 0.85;
node.x += node.vx; node.y += node.vy; node.x += node.vx; node.y += node.vy;
@@ -333,7 +312,7 @@
} }
function draw() { function draw() {
if (!canvas) return; if (!canvas || loading) return;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (!ctx) return; if (!ctx) return;
@@ -345,7 +324,6 @@
const { border: borderColor, text: textColor, textSec, accent, bg: bgColor } = getStyles(); const { border: borderColor, text: textColor, textSec, accent, bg: bgColor } = getStyles();
const activePath = $activeNotePath || ''; const activePath = $activeNotePath || '';
const pulse = 0.5 + 0.5 * Math.sin(glowPhase);
const isHovering = hoveredIdx >= 0; const isHovering = hoveredIdx >= 0;
const isSearching = searchMatchSet !== null; const isSearching = searchMatchSet !== null;
@@ -497,12 +475,11 @@
const radius = getNodeRadius(i, isActive); const radius = getNodeRadius(i, isActive);
// Active glow ring - opacity pulse, no radius change // Keep the active note highlighted without redrawing an idle graph.
if (isActive) { if (isActive) {
const glowR = radius + 12; const glowR = radius + 12;
const glow = ctx.createRadialGradient(node.x, node.y, radius, node.x, node.y, glowR); const glow = ctx.createRadialGradient(node.x, node.y, radius, node.x, node.y, glowR);
const glowAlpha = Math.round((0.25 + pulse * 0.45) * 255).toString(16).padStart(2, '0'); glow.addColorStop(0, accent + '80');
glow.addColorStop(0, accent + glowAlpha);
glow.addColorStop(1, accent + '00'); glow.addColorStop(1, accent + '00');
ctx.globalAlpha = 1; ctx.globalAlpha = 1;
ctx.beginPath(); ctx.beginPath();
@@ -524,9 +501,9 @@
} }
ctx.fill(); ctx.fill();
// Active outer ring - static, alpha pulse only // Static active outer ring.
if (isActive) { if (isActive) {
ctx.globalAlpha = 0.35 + pulse * 0.3; ctx.globalAlpha = 0.5;
ctx.beginPath(); ctx.beginPath();
ctx.arc(node.x, node.y, radius + 3, 0, Math.PI * 2); ctx.arc(node.x, node.y, radius + 3, 0, Math.PI * 2);
ctx.strokeStyle = accent; ctx.strokeStyle = accent;
@@ -587,7 +564,7 @@
} }
function getNodeAt(clientX: number, clientY: number): GraphNode | null { function getNodeAt(clientX: number, clientY: number): GraphNode | null {
if (!canvas) return null; if (!canvas || loading) return null;
const rect = canvas.getBoundingClientRect(); const rect = canvas.getBoundingClientRect();
const x = (clientX - rect.left - pan.x) / zoom; const x = (clientX - rect.left - pan.x) / zoom;
const y = (clientY - rect.top - pan.y) / zoom; const y = (clientY - rect.top - pan.y) / zoom;
@@ -627,8 +604,7 @@
if (node !== hoveredNode) { if (node !== hoveredNode) {
updateHoveredState(node); updateHoveredState(node);
if (canvas) canvas.style.cursor = node ? 'pointer' : 'grab'; if (canvas) canvas.style.cursor = node ? 'pointer' : 'grab';
// Restart loop if it stopped (for immediate hover redraws) if (!layoutScheduled) draw();
if (!animFrameId) draw();
} }
} }
} }
@@ -754,20 +730,21 @@
navigatedFromGraph = false; navigatedFromGraph = false;
centerOnActiveNote(); centerOnActiveNote();
} }
if (newIdx >= 0 && !animFrameId && canvas) startAnimLoop(); if (!layoutScheduled && canvas) untrack(draw);
else if (newIdx < 0 && !animFrameId && canvas) draw(); // remove stale glow immediately
}); });
// React to search query changes // React to search query changes
$effect(() => { $effect(() => {
const _q = searchQuery; // track const _q = searchQuery; // track
updateSearchMatch(); updateSearchMatch();
if (canvas && !animFrameId) draw(); if (canvas && !layoutScheduled) untrack(draw);
if (activeNodeIdx >= 0 && !animFrameId && canvas) startAnimLoop();
}); });
onDestroy(() => { onDestroy(() => {
if (animFrameId) cancelAnimationFrame(animFrameId); disposed = true;
layoutChannel.port1.onmessage = null;
layoutChannel.port1.close();
layoutChannel.port2.close();
}); });
</script> </script>
+386
View File
@@ -0,0 +1,386 @@
<script lang="ts">
import { onMount } from 'svelte';
let { src, alt = '', onclose }: {
src: string;
alt?: string;
onclose: () => void;
} = $props();
const MIN_SCALE = 1;
const MAX_SCALE = 5;
const DOUBLE_TAP_MS = 300;
const TAP_MOVE_THRESHOLD = 6;
type Point = { x: number; y: number };
type ViewerGesture =
| { kind: 'pan'; start: Point; pan: Point }
| { kind: 'pinch'; distance: number; imagePoint: Point };
let canvasElement = $state<HTMLDivElement | null>(null);
let imageElement = $state<HTMLImageElement | null>(null);
let closeButton = $state<HTMLButtonElement | null>(null);
let scale = $state(1);
let panX = $state(0);
let panY = $state(0);
let interacting = $state(false);
let gesture: ViewerGesture | null = null;
let touchMoved = false;
let lastTapAt = 0;
let zoomPercent = $derived(Math.round(scale * 100));
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
function midpoint(first: Touch, second: Touch): Point {
return {
x: (first.clientX + second.clientX) / 2,
y: (first.clientY + second.clientY) / 2,
};
}
function touchDistance(first: Touch, second: Touch): number {
return Math.hypot(second.clientX - first.clientX, second.clientY - first.clientY);
}
function panLimits(nextScale: number): Point {
const canvasWidth = canvasElement?.clientWidth ?? window.innerWidth;
const canvasHeight = canvasElement?.clientHeight ?? window.innerHeight;
const imageWidth = imageElement?.clientWidth ?? 0;
const imageHeight = imageElement?.clientHeight ?? 0;
return {
x: Math.max(0, (imageWidth * nextScale - canvasWidth) / 2),
y: Math.max(0, (imageHeight * nextScale - canvasHeight) / 2),
};
}
function applyTransform(nextScale: number, nextPanX: number, nextPanY: number) {
const clampedScale = clamp(nextScale, MIN_SCALE, MAX_SCALE);
const limits = panLimits(clampedScale);
scale = clampedScale;
panX = clamp(nextPanX, -limits.x, limits.x);
panY = clamp(nextPanY, -limits.y, limits.y);
}
function resetViewer() {
interacting = false;
gesture = null;
applyTransform(MIN_SCALE, 0, 0);
}
function zoomAt(point: Point, nextScale: number) {
const canvasRect = canvasElement?.getBoundingClientRect();
const centerX = canvasRect ? canvasRect.left + canvasRect.width / 2 : window.innerWidth / 2;
const centerY = canvasRect ? canvasRect.top + canvasRect.height / 2 : window.innerHeight / 2;
const imageX = (point.x - centerX - panX) / scale;
const imageY = (point.y - centerY - panY) / scale;
applyTransform(
nextScale,
point.x - centerX - imageX * nextScale,
point.y - centerY - imageY * nextScale,
);
}
function beginPan(touch: Touch) {
gesture = {
kind: 'pan',
start: { x: touch.clientX, y: touch.clientY },
pan: { x: panX, y: panY },
};
}
function beginPinch(first: Touch, second: Touch) {
const point = midpoint(first, second);
const canvasRect = canvasElement?.getBoundingClientRect();
const centerX = canvasRect ? canvasRect.left + canvasRect.width / 2 : window.innerWidth / 2;
const centerY = canvasRect ? canvasRect.top + canvasRect.height / 2 : window.innerHeight / 2;
gesture = {
kind: 'pinch',
distance: Math.max(1, touchDistance(first, second)),
imagePoint: {
x: (point.x - centerX - panX) / scale,
y: (point.y - centerY - panY) / scale,
},
};
}
function handleTouchStart(event: TouchEvent) {
event.preventDefault();
interacting = true;
if (event.touches.length >= 2) {
touchMoved = true;
beginPinch(event.touches[0], event.touches[1]);
return;
}
if (event.touches.length === 1) {
touchMoved = false;
beginPan(event.touches[0]);
}
}
function handleTouchMove(event: TouchEvent) {
event.preventDefault();
if (event.touches.length >= 2) {
if (gesture?.kind !== 'pinch') beginPinch(event.touches[0], event.touches[1]);
if (gesture?.kind !== 'pinch') return;
const point = midpoint(event.touches[0], event.touches[1]);
const canvasRect = canvasElement?.getBoundingClientRect();
const centerX = canvasRect ? canvasRect.left + canvasRect.width / 2 : window.innerWidth / 2;
const centerY = canvasRect ? canvasRect.top + canvasRect.height / 2 : window.innerHeight / 2;
const nextScale = clamp(
scale * (touchDistance(event.touches[0], event.touches[1]) / gesture.distance),
MIN_SCALE,
MAX_SCALE,
);
gesture.distance = Math.max(1, touchDistance(event.touches[0], event.touches[1]));
applyTransform(
nextScale,
point.x - centerX - gesture.imagePoint.x * nextScale,
point.y - centerY - gesture.imagePoint.y * nextScale,
);
touchMoved = true;
return;
}
if (event.touches.length === 1 && gesture?.kind === 'pan') {
const dx = event.touches[0].clientX - gesture.start.x;
const dy = event.touches[0].clientY - gesture.start.y;
if (Math.hypot(dx, dy) > TAP_MOVE_THRESHOLD) touchMoved = true;
applyTransform(scale, gesture.pan.x + dx, gesture.pan.y + dy);
}
}
function handleTouchEnd(event: TouchEvent) {
event.preventDefault();
if (event.touches.length >= 2) {
beginPinch(event.touches[0], event.touches[1]);
return;
}
if (event.touches.length === 1) {
beginPan(event.touches[0]);
touchMoved = true;
return;
}
interacting = false;
gesture = null;
if (!touchMoved && event.changedTouches.length > 0) {
const now = performance.now();
const touch = event.changedTouches[0];
if (now - lastTapAt <= DOUBLE_TAP_MS) {
if (scale > MIN_SCALE + 0.01) resetViewer();
else zoomAt({ x: touch.clientX, y: touch.clientY }, 2);
lastTapAt = 0;
} else {
lastTapAt = now;
}
}
}
function handleTouchCancel(event: TouchEvent) {
event.preventDefault();
interacting = false;
gesture = null;
touchMoved = false;
applyTransform(scale, panX, panY);
}
function attachTouchGestures(node: HTMLElement) {
node.addEventListener('touchstart', handleTouchStart, { passive: false });
node.addEventListener('touchmove', handleTouchMove, { passive: false });
node.addEventListener('touchend', handleTouchEnd, { passive: false });
node.addEventListener('touchcancel', handleTouchCancel, { passive: false });
return {
destroy() {
node.removeEventListener('touchstart', handleTouchStart);
node.removeEventListener('touchmove', handleTouchMove);
node.removeEventListener('touchend', handleTouchEnd);
node.removeEventListener('touchcancel', handleTouchCancel);
},
};
}
onMount(() => {
closeButton?.focus();
const handleResize = () => applyTransform(scale, panX, panY);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
});
</script>
<div
class="image-viewer"
role="dialog"
aria-modal="true"
aria-label={alt ? `Image viewer: ${alt}` : 'Image viewer'}
tabindex="-1"
onkeydown={(event) => {
if (event.key === 'Escape') {
event.preventDefault();
onclose();
}
}}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="image-viewer-canvas"
bind:this={canvasElement}
use:attachTouchGestures
onclick={(event) => {
if (event.target === event.currentTarget) onclose();
}}
onkeydown={(event) => {
if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) onclose();
}}
>
<img
bind:this={imageElement}
class:interacting
crossorigin="anonymous"
src={src}
alt={alt}
draggable="false"
style:transform={`translate3d(${panX}px, ${panY}px, 0) scale(${scale})`}
onload={resetViewer}
/>
</div>
<div class="image-viewer-controls">
<button
type="button"
class="image-viewer-reset"
onclick={resetViewer}
disabled={scale === MIN_SCALE && panX === 0 && panY === 0}
aria-label={`Reset zoom, currently ${zoomPercent}%`}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 12a9 9 0 1 0 3-6.7" />
<path d="M3 4v6h6" />
</svg>
<span>{zoomPercent}%</span>
</button>
<button bind:this={closeButton} type="button" class="image-viewer-close" onclick={onclose} aria-label="Close image viewer">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</div>
<div class="image-viewer-hint" aria-hidden="true">Pinch to zoom · drag to move · double-tap to zoom or reset</div>
<span class="sr-only" aria-live="polite">Zoom {zoomPercent}%</span>
</div>
<style>
.image-viewer {
position: fixed;
inset: 0;
z-index: 10000;
background: #06080c;
color: #fff;
overflow: hidden;
overscroll-behavior: contain;
}
.image-viewer-canvas {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
touch-action: none;
user-select: none;
-webkit-user-select: none;
}
.image-viewer-canvas img {
display: block;
max-width: calc(100vw - 24px);
max-height: calc(100dvh - 24px);
object-fit: contain;
transform-origin: center center;
transition: transform 160ms ease-out;
will-change: transform;
-webkit-user-drag: none;
user-select: none;
}
.image-viewer-canvas img.interacting {
transition: none;
}
.image-viewer-controls {
position: absolute;
inset: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) auto max(12px, env(safe-area-inset-left));
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.image-viewer-controls button {
min-height: 44px;
border: 1px solid rgba(255, 255, 255, 0.18);
background: rgba(20, 23, 30, 0.86);
color: #fff;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
pointer-events: auto;
}
.image-viewer-reset {
display: flex;
align-items: center;
gap: 8px;
padding: 0 14px;
border-radius: 10px;
font: inherit;
font-size: 13px;
font-weight: 600;
}
.image-viewer-reset:disabled {
opacity: 0.45;
}
.image-viewer-close {
display: grid;
place-items: center;
width: 44px;
padding: 0;
border-radius: 50%;
}
.image-viewer-hint {
position: absolute;
left: 50%;
bottom: max(18px, calc(env(safe-area-inset-bottom) + 10px));
transform: translateX(-50%);
width: max-content;
max-width: calc(100vw - 32px);
padding: 8px 12px;
border-radius: 8px;
background: rgba(20, 23, 30, 0.82);
color: rgba(255, 255, 255, 0.72);
font-size: 12px;
line-height: 1.35;
text-align: center;
pointer-events: none;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (prefers-reduced-motion: reduce) {
.image-viewer-canvas img {
transition: none;
}
}
</style>
+16 -184
View File
@@ -1,10 +1,7 @@
<script lang="ts"> <script lang="ts">
import { showInfo, appConfig } from '$lib/stores/app'; import { showInfo } from '$lib/stores/app';
import { getVaultStats, findOrphanedAttachments, trashOrphanedAttachments } from '$lib/api';
import type { OrphanAttachment } from '$lib/api';
import { openUrl } from '$lib/api'; import { openUrl } from '$lib/api';
import { getVersion } from '@tauri-apps/api/app'; import { getVersion } from '@tauri-apps/api/app';
import type { VaultStats } from '$lib/types';
import { import {
ACTIONS, ACTIONS,
keybindings, keybindings,
@@ -84,13 +81,8 @@
if (capturingId === id) stopCapture(); if (capturingId === id) stopCapture();
} }
let stats = $state<VaultStats | null>(null);
let activeTab = $state<'about' | 'shortcuts'>(isMobile ? 'about' : 'shortcuts'); let activeTab = $state<'about' | 'shortcuts'>(isMobile ? 'about' : 'shortcuts');
let appVersion = $state('...'); let appVersion = $state('...');
let orphans = $state<OrphanAttachment[] | null>(null);
let scanning = $state(false);
let trashing = $state(false);
const orphanTotal = $derived((orphans ?? []).reduce((a, o) => a + o.size, 0));
getVersion().then(v => appVersion = v).catch(() => appVersion = '0.0.0'); getVersion().then(v => appVersion = v).catch(() => appVersion = '0.0.0');
@@ -99,52 +91,31 @@
activeTab = isMobile ? 'about' : 'shortcuts'; activeTab = isMobile ? 'about' : 'shortcuts';
} }
function closeFromOverlay(event: MouseEvent) {
if (event.target === event.currentTarget) close();
}
function handleEscape(event: KeyboardEvent) {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
close();
}
function openLink(url: string) { function openLink(url: string) {
openUrl(url).catch(console.error); openUrl(url).catch(console.error);
} }
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
$effect(() => {
if ($showInfo) {
getVaultStats().then((s) => { stats = s; }).catch(console.error);
} else {
stats = null;
orphans = null;
}
});
async function scanOrphans() {
scanning = true;
try { orphans = await findOrphanedAttachments(); }
catch (e) { console.error(e); }
finally { scanning = false; }
}
async function trashOrphans() {
if (!orphans || orphans.length === 0) return;
trashing = true;
try {
await trashOrphanedAttachments(orphans.map((o) => o.name));
orphans = null;
getVaultStats().then((sv) => { stats = sv; }).catch(console.error);
} catch (e) { console.error(e); }
finally { trashing = false; }
}
</script> </script>
{#if $showInfo} {#if $showInfo}
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="info-overlay" onclick={close} onkeydown={(e) => { if (e.key === 'Escape') close(); }}> <div class="info-overlay" onclick={closeFromOverlay} onkeydowncapture={handleEscape} onkeydown={handleEscape}>
<!-- svelte-ignore a11y_no_static_element_interactions --> <div class="info-panel">
<div class="info-panel" onclick={(e) => e.stopPropagation()}>
<div class="info-header"> <div class="info-header">
<h2>Info</h2> <h2>Info</h2>
<button class="close-btn" onclick={close}> <button class="close-btn" onclick={close} aria-label="Close info">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" /> <line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" /> <line x1="6" y1="6" x2="18" y2="18" />
@@ -176,49 +147,7 @@
<p class="app-version">v{appVersion}</p> <p class="app-version">v{appVersion}</p>
<p class="app-description">A local markdown note-taking app.</p> <p class="app-description">A local markdown note-taking app.</p>
{#if stats}
<div class="info-stats">
<div class="stat-row">
<span class="stat-label">Notes</span>
<span class="stat-value">{stats.total_notes}</span>
</div>
<div class="stat-row">
<span class="stat-label">Attachments</span>
<span class="stat-value">{stats.total_attachments}</span>
</div>
<div class="stat-row">
<span class="stat-label">Notes size</span>
<span class="stat-value">{formatSize(stats.notes_size)}</span>
</div>
<div class="stat-row">
<span class="stat-label">Attachments size</span>
<span class="stat-value">{formatSize(stats.attachments_size)}</span>
</div>
<div class="stat-row stat-total">
<span class="stat-label">Total vault size</span>
<span class="stat-value">{formatSize(stats.total_size)}</span>
</div>
</div>
{/if}
{#if stats}
<div class="info-cleanup">
{#if orphans === null}
<button class="cleanup-btn" onclick={scanOrphans} disabled={scanning}>{#if scanning}<svg class="spinner-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" opacity="0.25" /><path d="M12 2a10 10 0 019.95 9" /></svg>Scanning…{:else}Find orphaned attachments{/if}</button>
{:else if orphans.length === 0}
<p class="cleanup-msg">No orphaned attachments. Nothing to clean up.</p>
{:else}
<p class="cleanup-msg">{orphans.length} {orphans.length === 1 ? 'attachment is' : 'attachments are'} not referenced by any note ({formatSize(orphanTotal)}).</p>
<div class="cleanup-list">
{#each orphans as o}
<div class="cleanup-row"><span class="cleanup-name" title={o.name}>{o.name}</span><span class="cleanup-size">{formatSize(o.size)}</span></div>
{/each}
</div>
<button class="cleanup-btn" onclick={trashOrphans} disabled={trashing}>{#if trashing}<svg class="spinner-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" opacity="0.25" /><path d="M12 2a10 10 0 019.95 9" /></svg>Moving…{:else}Move {orphans.length} to Trash{/if}</button>
<p class="cleanup-hint">Moved to the vault's trash folder (recoverable), not permanently deleted.</p>
{/if}
</div>
{/if}
<div class="info-credits"> <div class="info-credits">
<p>Created by <strong>Yuri Karamian</strong></p> <p>Created by <strong>Yuri Karamian</strong></p>
@@ -273,6 +202,7 @@
<div class="shortcut-row"><span class="shortcut-desc">Strikethrough</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Strikethrough</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Code</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>E</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Code</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>E</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Link</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>K</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Link</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>K</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Collapsible section</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>.</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Z</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Move line up / down</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd>↑↓</kbd></span></div> <div class="shortcut-row"><span class="shortcut-desc">Move line up / down</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd>↑↓</kbd></span></div>
@@ -416,39 +346,6 @@
margin-top: 4px; margin-top: 4px;
} }
.info-stats {
width: 100%;
margin-top: 20px;
background: var(--bg-secondary);
border: 1px solid var(--border-light);
border-radius: 10px;
padding: 4px 0;
}
.stat-row {
display: flex;
justify-content: space-between;
padding: 7px 16px;
}
.stat-label {
font-size: 13px;
color: var(--text-secondary);
}
.stat-value {
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
}
.stat-total {
border-top: 1px solid var(--border-light);
}
.stat-total .stat-value {
color: var(--accent);
}
.info-credits { .info-credits {
margin-top: 20px; margin-top: 20px;
@@ -480,71 +377,6 @@
.info-link:hover { .info-link:hover {
background: var(--accent-light); background: var(--accent-light);
} }
.info-cleanup {
width: 100%;
margin-top: 16px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.cleanup-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 8px;
color: var(--text-primary);
font-size: 13px;
padding: 7px 14px;
cursor: pointer;
}
.cleanup-btn:hover:not(:disabled) { background: var(--bg-hover); }
.cleanup-btn:disabled { opacity: 0.6; cursor: default; }
.cleanup-msg {
font-size: 13px;
color: var(--text-secondary);
text-align: center;
}
.cleanup-list {
width: 100%;
max-height: 140px;
overflow-y: auto;
background: var(--bg-secondary);
border: 1px solid var(--border-light);
border-radius: 8px;
}
.cleanup-row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 5px 12px;
font-size: 12px;
}
.cleanup-name {
color: var(--text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cleanup-size {
color: var(--text-tertiary);
flex-shrink: 0;
}
.cleanup-hint {
font-size: 11px;
color: var(--text-tertiary);
text-align: center;
}
.spinner-icon {
animation: spin 0.8s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.shortcuts-section { .shortcuts-section {
width: 100%; width: 100%;
File diff suppressed because it is too large. Load diff
+466
View File
@@ -0,0 +1,466 @@
<script lang="ts">
import { tick } from 'svelte';
import { activeNote, activeNotePath, appConfig, navHistory } from '$lib/stores/app';
import { getNoteSwitcherTitles, getQuickAccess } from '$lib/api';
import { openNoteWindow } from '$lib/utils/window';
import {
buildNoteSwitcherRequestPaths,
buildNoteSwitcherSections,
type NoteSwitcherNote,
type NoteSwitcherRow,
type NoteSwitcherSections
} from '$lib/utils/note-switcher';
import type { NoteEntry, NoteTitleEntry } from '$lib/types';
let { onSelectNote = async () => false }: {
onSelectNote?: (path: string) => Promise<boolean>;
} = $props();
let wrapper: HTMLDivElement;
let trigger: HTMLButtonElement;
let popover = $state<HTMLDivElement | null>(null);
let open = $state(false);
let loading = $state(false);
let selectingPath = $state<string | null>(null);
let sections = $state<NoteSwitcherSections>({ recent: [], quickAccess: [] });
let loadGeneration = 0;
let loadedVaultPath = $state<string | null | undefined>(undefined);
function normalizedPath(path: string): string {
return path.replace(/\\/g, '/').replace(/\/$/, '');
}
function isInsideVault(path: string, vaultPath: string): boolean {
return normalizedPath(path).startsWith(`${normalizedPath(vaultPath)}/`);
}
function vaultRelativePath(path: string, vaultPath: string): string {
return normalizedPath(path).slice(normalizedPath(vaultPath).length + 1);
}
function joinVaultPath(vaultPath: string, relativePath: string): string {
const separator = vaultPath.includes('\\') && !vaultPath.includes('/') ? '\\' : '/';
const root = vaultPath.replace(/[\\/]+$/, '');
return `${root}${separator}${relativePath.replace(/[\\/]/g, separator)}`;
}
function titleEntryToNote(entry: NoteTitleEntry, vaultPath: string): NoteSwitcherNote | null {
const relativePath = entry.path.replace(/\\/g, '/').replace(/^\/+/, '');
if (!relativePath || relativePath.split('/').includes('..')) return null;
const path = joinVaultPath(vaultPath, relativePath);
if (!isInsideVault(path, vaultPath)) return null;
return { path, title: entry.title, relativePath };
}
function quickAccessEntryToNote(entry: NoteEntry, vaultPath: string): NoteSwitcherNote | null {
if (!isInsideVault(entry.path, vaultPath)) return null;
return {
path: entry.path,
title: entry.meta.title,
relativePath: entry.relative_path.replace(/\\/g, '/')
};
}
async function focusInitialRow() {
await tick();
if (!open) return;
const current = wrapper.querySelector<HTMLButtonElement>('.note-primary[aria-current="true"]');
const first = wrapper.querySelector<HTMLButtonElement>('.note-primary');
(current ?? first ?? popover)?.focus();
}
async function refreshSections(generation: number) {
const vaultPath = $appConfig?.active_vault;
if (!vaultPath) {
sections = { recent: [], quickAccess: [] };
loadedVaultPath = null;
loading = false;
await focusInitialRow();
return;
}
const requestPaths = buildNoteSwitcherRequestPaths($activeNotePath, $navHistory.stack);
const [titlesResult, quickAccessResult] = await Promise.allSettled([
getNoteSwitcherTitles(requestPaths),
getQuickAccess(vaultPath)
]);
if (!open || generation !== loadGeneration) return;
if (titlesResult.status === 'rejected') {
console.error('Failed to load notes for note switcher:', titlesResult.reason);
}
if (quickAccessResult.status === 'rejected') {
console.error('Failed to load Quick Access for note switcher:', quickAccessResult.reason);
}
const knownNotes = titlesResult.status === 'fulfilled'
? titlesResult.value
.map((entry) => titleEntryToNote(entry, vaultPath))
.filter((entry): entry is NoteSwitcherNote => entry !== null)
: [];
const currentPath = $activeNotePath;
if (currentPath && isInsideVault(currentPath, vaultPath)) {
const currentKey = normalizedPath(currentPath);
if (!knownNotes.some((note) => normalizedPath(note.path) === currentKey)) {
knownNotes.push({
path: currentPath,
title: $activeNote?.meta.title || currentPath.split(/[\\/]/).pop()?.replace(/\.md$/i, '') || 'Untitled',
relativePath: vaultRelativePath(currentPath, vaultPath)
});
}
}
const quickAccessNotes = quickAccessResult.status === 'fulfilled'
? quickAccessResult.value
.map((entry) => quickAccessEntryToNote(entry, vaultPath))
.filter((entry): entry is NoteSwitcherNote => entry !== null)
: [];
for (const note of quickAccessNotes) {
if (!knownNotes.some((knownNote) => normalizedPath(knownNote.path) === normalizedPath(note.path))) {
knownNotes.push(note);
}
}
sections = buildNoteSwitcherSections({
currentPath,
historyPaths: $navHistory.stack,
knownNotes,
quickAccessNotes
});
loadedVaultPath = vaultPath;
loading = false;
await focusInitialRow();
}
function refreshAfterPopoverPaint(generation: number) {
requestAnimationFrame(() => {
window.setTimeout(() => {
if (!open || generation !== loadGeneration) return;
void refreshSections(generation);
}, 0);
});
}
function toggleSwitcher() {
if (open) {
open = false;
loadGeneration += 1;
return;
}
const vaultPath = $appConfig?.active_vault ?? null;
const hasCachedSections = loadedVaultPath === vaultPath;
open = true;
loading = !hasCachedSections;
selectingPath = null;
if (!hasCachedSections) sections = { recent: [], quickAccess: [] };
loadGeneration += 1;
const generation = loadGeneration;
if (hasCachedSections) void focusInitialRow();
refreshAfterPopoverPaint(generation);
}
async function closeSwitcher(restoreTriggerFocus: boolean) {
open = false;
loadGeneration += 1;
if (restoreTriggerFocus) {
await tick();
trigger?.focus();
}
}
async function selectNote(row: NoteSwitcherRow) {
if (selectingPath !== null) return;
selectingPath = row.path;
try {
if (await onSelectNote(row.path)) await closeSwitcher(false);
} finally {
selectingPath = null;
}
}
function handlePopoverKeydown(event: KeyboardEvent) {
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
const buttons = Array.from(wrapper.querySelectorAll<HTMLButtonElement>('.note-primary:not(:disabled)'));
if (buttons.length === 0) return;
event.preventDefault();
const activeRow = (document.activeElement as HTMLElement | null)?.closest('.note-row');
const activeButton = activeRow?.querySelector<HTMLButtonElement>('.note-primary') ?? null;
const currentIndex = activeButton ? buttons.indexOf(activeButton) : -1;
let nextIndex: number;
if (event.key === 'Home') nextIndex = 0;
else if (event.key === 'End') nextIndex = buttons.length - 1;
else if (event.key === 'ArrowDown') nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % buttons.length;
else nextIndex = currentIndex < 0 ? buttons.length - 1 : (currentIndex - 1 + buttons.length) % buttons.length;
buttons[nextIndex].focus();
}
$effect(() => {
if (!open) return;
const handleOutsideMouseDown = (event: MouseEvent) => {
if (!wrapper.contains(event.target as Node)) void closeSwitcher(false);
};
const handleEscape = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
void closeSwitcher(true);
};
document.addEventListener('mousedown', handleOutsideMouseDown, true);
document.addEventListener('keydown', handleEscape, true);
return () => {
document.removeEventListener('mousedown', handleOutsideMouseDown, true);
document.removeEventListener('keydown', handleEscape, true);
};
});
</script>
<div class="note-switcher" bind:this={wrapper}>
<button
bind:this={trigger}
class="switcher-trigger"
type="button"
aria-label="Switch note"
aria-haspopup="dialog"
aria-expanded={open}
onclick={toggleSwitcher}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="7" y="4" width="12" height="14" rx="2" />
<path d="M5 7H4a2 2 0 00-2 2v9a2 2 0 002 2h9a2 2 0 002-2v-1" />
</svg>
</button>
{#if open}
<div
bind:this={popover}
class="switcher-popover"
role="dialog"
aria-label="Note switcher"
tabindex="-1"
onkeydown={handlePopoverKeydown}
>
{#if loading}
<div class="switcher-status">Loading notes…</div>
{:else if sections.recent.length === 0 && sections.quickAccess.length === 0}
<div class="switcher-status">No notes available</div>
{:else}
{#each [
{ label: 'Recent', rows: sections.recent },
{ label: 'Quick Access', rows: sections.quickAccess }
] as section (section.label)}
{#if section.rows.length > 0}
<section class="switcher-section" aria-labelledby={`note-switcher-${section.label.replace(' ', '-').toLowerCase()}`}>
<h2 id={`note-switcher-${section.label.replace(' ', '-').toLowerCase()}`}>{section.label}</h2>
{#each section.rows as row (row.path)}
<div class="note-row" class:current-row={row.current}>
{#if row.current}<span class="current-marker" aria-hidden="true"></span>{/if}
<button
class="note-primary"
type="button"
aria-current={row.current ? 'true' : undefined}
disabled={selectingPath !== null}
onclick={() => selectNote(row)}
>
<span class="note-title">{row.title}</span>
<span class="note-folder">{row.folder}</span>
</button>
<button
class="open-window"
type="button"
aria-label={`Open ${row.title} in new window`}
title={`Open ${row.title} in new window`}
onclick={() => { if (loadedVaultPath) void openNoteWindow(loadedVaultPath, row.path, row.title); }}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="4" y="4" width="13" height="13" rx="2" />
<path d="M10 14L20 4m-6 0h6v6" />
</svg>
</button>
</div>
{/each}
</section>
{/if}
{/each}
{/if}
</div>
{/if}
</div>
<style>
.note-switcher {
position: relative;
-webkit-app-region: no-drag;
}
.switcher-trigger {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--text-secondary);
cursor: pointer;
transition: background 0.15s, color 0.15s;
}
.switcher-trigger:hover,
.switcher-trigger[aria-expanded='true'] {
background: var(--bg-tertiary, var(--bg-hover));
color: var(--text-primary);
}
.switcher-trigger:focus-visible,
.note-primary:focus-visible,
.open-window:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.switcher-popover {
position: absolute;
top: calc(100% + 6px);
left: 0;
z-index: 1000;
width: min(320px, calc(100vw - 24px));
max-height: min(420px, calc(100vh - 58px));
overflow-y: auto;
padding: 6px;
border: 1px solid var(--border-color);
border-radius: 10px;
background: var(--bg-secondary);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
color: var(--text-primary);
user-select: none;
-webkit-app-region: no-drag;
}
.switcher-section + .switcher-section {
margin-top: 5px;
padding-top: 5px;
border-top: 1px solid var(--border-color);
}
h2 {
margin: 0;
padding: 5px 8px 4px;
color: var(--text-tertiary);
font-size: 10px;
font-weight: 600;
letter-spacing: 0.06em;
line-height: 1.2;
text-transform: uppercase;
}
.note-row {
position: relative;
display: flex;
align-items: center;
min-height: 42px;
border-radius: 7px;
}
.note-row:hover,
.note-row:focus-within {
background: var(--bg-hover);
}
.note-row.current-row {
background: color-mix(in srgb, var(--accent) 9%, transparent);
}
.current-marker {
position: absolute;
left: 7px;
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--accent);
}
.note-primary {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
align-items: flex-start;
gap: 2px;
padding: 6px 38px 6px 12px;
border: 0;
border-radius: 7px;
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
}
.current-row .note-primary {
padding-left: 18px;
}
.note-primary:disabled {
cursor: wait;
}
.note-title,
.note-folder {
display: block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.note-title {
font-size: 12px;
font-weight: 500;
line-height: 1.25;
}
.note-folder {
color: var(--text-tertiary);
font-size: 10.5px;
line-height: 1.2;
}
.open-window {
position: absolute;
right: 5px;
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
padding: 0;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--text-tertiary);
cursor: pointer;
opacity: 0;
pointer-events: none;
transition: opacity 0.12s, background 0.12s, color 0.12s;
}
.note-row:hover .open-window,
.note-row:focus-within .open-window {
opacity: 1;
pointer-events: auto;
}
.open-window:hover {
background: var(--bg-tertiary, var(--bg-hover));
color: var(--text-primary);
}
.switcher-status {
padding: 22px 12px;
color: var(--text-tertiary);
font-size: 11px;
text-align: center;
}
</style>
+162 -37
View File
@@ -1,33 +1,47 @@
<script lang="ts"> <script lang="ts">
import { onMount, onDestroy } from 'svelte'; import { onMount, onDestroy, untrack } from 'svelte';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
import { getCurrentWebview } from '@tauri-apps/api/webview';
import { getCurrentWindow } from '@tauri-apps/api/window'; import { getCurrentWindow } from '@tauri-apps/api/window';
import Editor from './Editor.svelte'; import Editor from './Editor.svelte';
import { import {
appConfig,
activeNote, activeNote,
activeNotePath, activeNotePath,
editorDirty, editorDirty,
readOnly, readOnly,
sourceMode, sourceMode,
theme tagStyles
} from '$lib/stores/app'; } from '$lib/stores/app';
import { readNote } from '$lib/api'; import { completeWindowClose, cancelWindowClose, getTagStyles, readNote } from '$lib/api';
import { keybindings, matchAction } from '$lib/keybindings'; import { keybindings, matchAction } from '$lib/keybindings';
import { isMobile } from '$lib/platform';
import type { FileEvent } from '$lib/types'; import type { FileEvent } from '$lib/types';
import { isCurrentVaultEvent } from '$lib/utils/note-list-updates';
import { beginNoteNavigation, isCurrentNoteNavigation, cancelNoteNavigation } from '$lib/utils/note-navigation';
let { notePath }: { notePath: string } = $props(); let { notePath, vaultPath }: { notePath: string; vaultPath: string | null } = $props();
const ownerVault = untrack(() => vaultPath);
import { darkThemes } from '$lib/platform';
const appWindow = getCurrentWindow(); const appWindow = getCurrentWindow();
const appWebview = getCurrentWebview();
const isMac = navigator.platform.startsWith('Mac'); const isMac = navigator.platform.startsWith('Mac');
let editor = $state<Editor>(null!); let editor = $state<Editor>(null!);
let unlistenFileChange: (() => void) | null = null; let unlistenFileChange: (() => void) | null = null;
let unlistenUiScale: (() => void) | null = null;
let unlistenClose: (() => void) | null = null;
let unlistenVaultRestored: (() => void) | null = null;
let removeMobileFlushListeners: (() => void) | null = null;
let maximized = $state(false); let maximized = $state(false);
let loadError = $state<string | null>(null); let loadError = $state<string | null>(null);
let disposed = false;
let initialNavigationToken: number | null = null;
let initialLoadTimer: ReturnType<typeof setTimeout> | null = null;
let fileRefreshRequest = 0;
async function checkMaximized() { async function checkMaximized() {
maximized = await appWindow.isMaximized(); const value = await appWindow.isMaximized();
if (!disposed) maximized = value;
} }
$effect(() => { $effect(() => {
@@ -35,21 +49,12 @@
const unlisten = appWindow.onResized(() => checkMaximized()); const unlisten = appWindow.onResized(() => checkMaximized());
return () => { unlisten.then(fn => fn()); }; return () => { unlisten.then(fn => fn()); };
}); });
$effect(() => { $effect(() => {
const t = $theme || 'system'; const title = $activeNote?.meta.title;
const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark']; if (title && !disposed) void appWindow.setTitle(`${title} - HelixNotes`);
const root = document.documentElement;
root.classList.remove('dark');
root.removeAttribute('data-theme');
if (namedThemes.includes(t)) {
root.setAttribute('data-theme', t);
if (darkThemes.includes(t)) root.classList.add('dark');
} else if (t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
}
}); });
let lastMouseDown = 0; let lastMouseDown = 0;
const RESIZE_EDGE = 6; const RESIZE_EDGE = 6;
@@ -84,38 +89,158 @@
} }
} }
onMount(async () => { async function applyUiScale(scale: number) {
try { try {
const content = await readNote(notePath); await appWebview.setZoom(scale);
$activeNote = content;
$activeNotePath = notePath;
$editorDirty = false;
setTimeout(() => {
editor?.loadNote(notePath, content.content);
appWindow.setTitle(`${content.meta.title} - HelixNotes`);
}, 50);
} catch (e) { } catch (e) {
loadError = String(e); console.error('Failed to apply interface scale to note window:', e);
}
} }
unlistenFileChange = await listen<FileEvent>('file-changed', async (event) => { onMount(() => {
if (event.payload.path === notePath && event.payload.event_type === 'modify') { const vault = ownerVault;
if (!$editorDirty) { const path = notePath;
const token = beginNoteNavigation();
initialNavigationToken = token;
const isCurrentOwner = () => !disposed && (vault === null || vault === $appConfig?.active_vault);
if (isMobile) {
const flush = () => {
if (isCurrentOwner()) void editor?.flushSave();
};
const onVisibilityChange = () => {
if (document.visibilityState === 'hidden') flush();
};
document.addEventListener('visibilitychange', onVisibilityChange);
window.addEventListener('pagehide', flush);
window.addEventListener('app-lifecycle-flush', flush);
removeMobileFlushListeners = () => {
document.removeEventListener('visibilitychange', onVisibilityChange);
window.removeEventListener('pagehide', flush);
window.removeEventListener('app-lifecycle-flush', flush);
};
}
async function initialize() {
if (!isMobile) {
const closeListener = await appWindow.onCloseRequested(async (event) => {
event.preventDefault();
if (!isCurrentOwner()) { await cancelWindowClose(); return; }
try { try {
const content = await readNote(notePath); if (editor && !(await editor.flushSave())) { await cancelWindowClose(); return; }
// Ignore the file-watcher echo of our own save; only reload genuine external edits. if (!isCurrentOwner()) { await cancelWindowClose(); return; }
if (content.content.trim() !== (editor?.getCurrentBody() ?? '').trim()) { await completeWindowClose();
} catch (error) {
console.error('Failed to close window:', error);
try { await cancelWindowClose(); } catch (cancelError) { console.error('Failed to cancel window close:', cancelError); }
}
});
if (!isCurrentOwner()) {
closeListener();
return;
}
unlistenClose = closeListener;
}
if (!ownerVault) {
loadError = 'This note window has no valid originating vault.';
return;
}
const scaleListener = await listen<number>('ui-scale-changed', (event) => {
if (isCurrentOwner()) void applyUiScale(event.payload);
});
if (!isCurrentOwner()) {
scaleListener();
return;
}
unlistenUiScale = scaleListener;
await applyUiScale($appConfig?.ui_scale ?? 1);
if (!isCurrentOwner()) return;
try {
const styles = await getTagStyles(ownerVault!);
if (!isCurrentOwner()) return;
$tagStyles = styles;
} catch (e) {
console.error('Failed to load tag styles:', e);
}
if (!isCurrentOwner()) return;
if (isCurrentNoteNavigation(token)) {
try {
const content = await readNote(ownerVault!, path);
if (!isCurrentOwner()) return;
if (isCurrentNoteNavigation(token)) {
$activeNote = content; $activeNote = content;
editor?.loadNote(notePath, content.content); $activeNotePath = path;
$editorDirty = false;
initialLoadTimer = setTimeout(() => {
initialLoadTimer = null;
if (!isCurrentOwner() || !isCurrentNoteNavigation(token)
|| $activeNotePath !== path || $activeNote !== content || $editorDirty) return;
editor?.loadNote(path, content.content);
}, 50);
} }
} catch (_) {} } catch (e) {
if (isCurrentOwner() && isCurrentNoteNavigation(token)) loadError = String(e);
} }
} }
if (!isCurrentOwner()) return;
async function refreshOpenNote(restored = false) {
const path = $activeNotePath;
const openingNote = $activeNote;
if (!path || !openingNote) return;
const request = ++fileRefreshRequest;
try {
const content = await readNote(ownerVault!, path);
if (!isCurrentOwner() || request !== fileRefreshRequest || $activeNotePath !== path) return;
if ($editorDirty) {
if (restored && content.raw !== editor?.getAcceptedRaw()) editor?.flagExternalConflict();
return;
}
if ($activeNote !== openingNote || openingNote.raw === content.raw) return;
$activeNote = content;
editor?.loadNote(path, content.content);
} catch (error) {
if (restored && isCurrentOwner() && request === fileRefreshRequest && $activeNotePath === path) {
if ($editorDirty) editor?.flagExternalConflict();
else {
$activeNote = null;
$activeNotePath = null;
loadError = 'This note was removed by the vault restore.';
}
} else if (!restored) console.error('Failed to refresh note window:', error);
}
}
const fileListener = await listen<FileEvent>('file-changed', (event) => {
if (!isCurrentOwner() || !isCurrentVaultEvent(event.payload, vault ?? null)) return;
if (event.payload.note?.path === $activeNotePath) void refreshOpenNote();
});
if (!isCurrentOwner()) {
fileListener();
return;
}
unlistenFileChange = fileListener;
unlistenVaultRestored = await listen<{ vault_path: string }>('vault-restored', ({ payload }) => {
if (isCurrentOwner() && payload.vault_path === vault) void refreshOpenNote(true);
});
if (!isCurrentOwner()) { unlistenVaultRestored(); return; }
}
void initialize().catch(error => {
if (isCurrentOwner()) console.error('Failed to initialize note window:', error);
}); });
}); });
onDestroy(() => { onDestroy(() => {
disposed = true;
if (initialNavigationToken !== null) cancelNoteNavigation(initialNavigationToken);
if (initialLoadTimer !== null) clearTimeout(initialLoadTimer);
unlistenFileChange?.(); unlistenFileChange?.();
unlistenVaultRestored?.();
removeMobileFlushListeners?.();
unlistenUiScale?.();
unlistenClose?.();
}); });
</script> </script>
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import type { NotebookIconId } from '$lib/utils/notebook-icons';
let { icon, size = 18 }: { icon: NotebookIconId; size?: number } = $props();
</script>
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
{#if icon === 'book'}
<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z" />
{:else if icon === 'folder'}
<path d="M3 6.5A2.5 2.5 0 0 1 5.5 4H9l2 2.5h7.5A2.5 2.5 0 0 1 21 9v8.5a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5Z" />
{:else if icon === 'briefcase'}
<rect x="3" y="7" width="18" height="13" rx="2" />
<path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M3 12h18M10 12v2h4v-2" />
{:else if icon === 'home'}
<path d="m3 11 9-8 9 8" />
<path d="M5 10v11h14V10M9 21v-7h6v7" />
{:else if icon === 'star'}
<path d="m12 2 3.1 6.3 6.9 1-5 4.8 1.2 6.9-6.2-3.3L5.8 21 7 14.1l-5-4.8 6.9-1Z" />
{:else if icon === 'heart'}
<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8l1.1 1.1L12 21l7.8-7.5 1.1-1.1a5.5 5.5 0 0 0-.1-7.8Z" />
{:else if icon === 'lightbulb'}
<path d="M9 18h6M10 22h4" />
<path d="M8.2 15.5A7 7 0 1 1 15.8 15.5c-.7.5-.8 1.1-.8 2.5H9c0-1.4-.1-2-.8-2.5Z" />
{:else if icon === 'code'}
<path d="m8 9-4 3 4 3M16 9l4 3-4 3M14 5l-4 14" />
{:else if icon === 'flask'}
<path d="M9 3h6M10 3v6l-5.5 9.5A1.7 1.7 0 0 0 6 21h12a1.7 1.7 0 0 0 1.5-2.5L14 9V3" />
<path d="M7 16h10" />
{:else if icon === 'graduation'}
<path d="m2 9 10-5 10 5-10 5Z" />
<path d="M6 11.5V16c3.5 2.7 8.5 2.7 12 0v-4.5M22 9v6" />
{:else if icon === 'calendar'}
<rect x="3" y="5" width="18" height="16" rx="2" />
<path d="M16 3v4M8 3v4M3 10h18M8 14h.01M12 14h.01M16 14h.01M8 18h.01M12 18h.01" />
{:else if icon === 'tasks'}
<rect x="3" y="3" width="18" height="18" rx="2" />
<path d="m7 8 1.5 1.5L11 7M13 9h4M7 14l1.5 1.5L11 13M13 15h4" />
{:else if icon === 'archive'}
<path d="M4 8v12h16V8M3 4h18v4H3ZM9 12h6" />
{:else if icon === 'globe'}
<circle cx="12" cy="12" r="9" />
<path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" />
{:else if icon === 'plane'}
<path d="M22 2 9.5 14.5M22 2l-7 20-4-8-8-4Z" />
{:else}
<path d="M12 3a9 9 0 1 0 0 18h1.5a1.5 1.5 0 0 0 0-3H12a1.5 1.5 0 0 1 0-3h3a6 6 0 0 0 0-12Z" />
<path d="M7.5 10h.01M9.5 6.5h.01M14.5 6.5h.01M17 10h.01" />
{/if}
</svg>
+8 -8
View File
@@ -30,14 +30,14 @@
{#if appWindow && !maximized} {#if appWindow && !maximized}
<div class="resize-layer" aria-hidden="true"> <div class="resize-layer" aria-hidden="true">
<div class="rz rz-n" onmousedown={(e) => start(e, 'North')}></div> <div class="rz rz-n" role="presentation" onmousedown={(e) => start(e, 'North')}></div>
<div class="rz rz-s" onmousedown={(e) => start(e, 'South')}></div> <div class="rz rz-s" role="presentation" onmousedown={(e) => start(e, 'South')}></div>
<div class="rz rz-w" onmousedown={(e) => start(e, 'West')}></div> <div class="rz rz-w" role="presentation" onmousedown={(e) => start(e, 'West')}></div>
<div class="rz rz-e" onmousedown={(e) => start(e, 'East')}></div> <div class="rz rz-e" role="presentation" onmousedown={(e) => start(e, 'East')}></div>
<div class="rz rz-nw" onmousedown={(e) => start(e, 'NorthWest')}></div> <div class="rz rz-nw" role="presentation" onmousedown={(e) => start(e, 'NorthWest')}></div>
<div class="rz rz-ne" onmousedown={(e) => start(e, 'NorthEast')}></div> <div class="rz rz-ne" role="presentation" onmousedown={(e) => start(e, 'NorthEast')}></div>
<div class="rz rz-sw" onmousedown={(e) => start(e, 'SouthWest')}></div> <div class="rz rz-sw" role="presentation" onmousedown={(e) => start(e, 'SouthWest')}></div>
<div class="rz rz-se" onmousedown={(e) => start(e, 'SouthEast')}></div> <div class="rz rz-se" role="presentation" onmousedown={(e) => start(e, 'SouthEast')}></div>
</div> </div>
{/if} {/if}
+225 -92
View File
@@ -1,92 +1,160 @@
<script lang="ts"> <script lang="ts">
import { showSearch, activeNote, activeNotePath, editorDirty, appConfig, mobileView, notebooks, activeNotebook, activeTag, viewMode } from '$lib/stores/app'; import { tick } from 'svelte';
import { searchNotes, readNote } from '$lib/api'; import { showSearch, appConfig, notebooks } from '$lib/stores/app';
import { debounce } from '$lib/utils/debounce'; import { searchNotes } from '$lib/api';
import type { SearchResult, NotebookEntry } from '$lib/types'; import { relativePath } from '$lib/utils/paths';
import type { SearchResult, SearchMatch, NotebookEntry } from '$lib/types';
import { isMobile } from '$lib/platform'; import { isMobile } from '$lib/platform';
let { onSelectNote }: {
onSelectNote: (result: SearchResult, notebook: NotebookEntry | null, isCurrent: () => boolean) => Promise<boolean>;
} = $props();
const PAGE_SIZE = 20;
const currentVault = $derived($appConfig?.active_vault ?? null);
let query = $state(''); let query = $state('');
let results = $state<SearchResult[]>([]); let results = $state.raw<SearchResult[]>([]);
let total = $state(0);
let offset = $state(0);
let loading = $state(false);
let opening = $state(false);
let error = $state('');
let composing = $state(false);
let selectedIndex = $state(0); let selectedIndex = $state(0);
let inputEl = $state<HTMLInputElement>(null!); let inputEl = $state<HTMLInputElement>(null!);
let resultsEl = $state<HTMLDivElement>(null!); let resultsEl = $state<HTMLDivElement>(null!);
let requestGeneration = 0;
let searchTimer: ReturnType<typeof setTimeout> | null = null;
const rows = $derived(results.map(result => ({
result,
title: textParts(result.title, result.title_matches),
snippet: textParts(result.snippet, result.snippet_matches),
})));
const doSearch = debounce(async (q: string) => { function cancelSearch() {
if (!q.trim()) { requestGeneration++;
results = []; if (searchTimer !== null) clearTimeout(searchTimer);
return; searchTimer = null;
} }
function isCurrent(generation: number, vault: string | null) {
return generation === requestGeneration && $showSearch && vault === currentVault;
}
async function runSearch(q: string, pageOffset: number, generation: number, vault: string | null) {
searchTimer = null;
if (!isCurrent(generation, vault)) return;
try { try {
results = await searchNotes(q, 20); const page = await searchNotes(q, PAGE_SIZE, pageOffset);
if (!isCurrent(generation, vault)) return;
results = page.results;
total = page.total;
selectedIndex = 0; selectedIndex = 0;
} catch (e) { await tick();
console.error('Search failed:', e); if (isCurrent(generation, vault) && resultsEl) resultsEl.scrollTop = 0;
} catch (cause) {
if (!isCurrent(generation, vault)) return;
error = cause instanceof Error ? cause.message : String(cause);
} finally {
if (isCurrent(generation, vault)) loading = false;
}
}
function startSearch(value: string, pageOffset = 0, immediate = false) {
cancelSearch();
query = value;
results = []; results = [];
selectedIndex = 0;
error = '';
opening = false;
offset = pageOffset;
if (pageOffset === 0) total = 0;
const q = value.trim();
loading = !!q && !composing;
if (!loading) return;
const generation = requestGeneration;
const vault = currentVault;
if (immediate) void runSearch(q, pageOffset, generation, vault);
else searchTimer = setTimeout(() => void runSearch(q, pageOffset, generation, vault), 150);
} }
}, 150);
$effect(() => { $effect(() => {
if ($showSearch && inputEl) { const open = $showSearch;
const vault = currentVault;
const input = inputEl;
cancelSearch();
query = ''; query = '';
results = []; results = [];
total = 0;
offset = 0;
selectedIndex = 0; selectedIndex = 0;
setTimeout(() => inputEl?.focus(), 50); loading = false;
opening = false;
composing = false;
error = '';
if (open && input) {
const generation = requestGeneration;
void tick().then(() => { if (isCurrent(generation, vault)) input.focus(); });
} }
return cancelSearch;
}); });
function handleInput() { function handleInput(event: Event) {
doSearch(query); if ((event as InputEvent).isComposing) composing = true;
startSearch((event.currentTarget as HTMLInputElement).value);
} }
function scrollToSelected() { function scrollToSelected() {
if (!resultsEl) return; void tick().then(() => {
const item = resultsEl.children[selectedIndex] as HTMLElement; const item = resultsEl?.children[selectedIndex] as HTMLElement | undefined;
if (item) item.scrollIntoView({ block: 'nearest' }); item?.scrollIntoView({ block: 'nearest' });
});
}
function handleEscape(e: KeyboardEvent) {
if (e.key !== 'Escape' || e.isComposing) return;
e.preventDefault();
e.stopPropagation();
close();
} }
function handleKeydown(e: KeyboardEvent) { function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') { e.stopPropagation();
$showSearch = false; if (e.isComposing || composing || loading || opening) return;
} else if (e.key === 'ArrowDown') { if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault(); e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, results.length - 1); if (!results.length) return;
selectedIndex = Math.max(0, Math.min(results.length - 1, selectedIndex + (e.key === 'ArrowDown' ? 1 : -1)));
inputEl?.focus({ preventScroll: true });
scrollToSelected(); scrollToSelected();
} else if (e.key === 'ArrowUp') { } else if (e.key === 'Enter' && e.target === inputEl && results[selectedIndex]) {
e.preventDefault(); e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0); void openResult(results[selectedIndex]);
scrollToSelected();
} else if (e.key === 'Enter' && results.length > 0) {
openResult(results[selectedIndex]);
} }
} }
function getNotebook(path: string): string { function getNotebook(path: string): string {
const vault = $appConfig?.active_vault; if (!currentVault) return '';
if (!vault) return ''; const rel = relativePath(currentVault, path);
let rel = path;
if (rel.startsWith(vault + '/')) rel = rel.substring(vault.length + 1);
const lastSlash = rel.lastIndexOf('/'); const lastSlash = rel.lastIndexOf('/');
if (lastSlash <= 0) return ''; return lastSlash > 0 ? rel.substring(0, lastSlash) : '';
return rel.substring(0, lastSlash);
} }
function highlightSnippet(snippet: string, q: string): string { function textParts(text: string, matches: SearchMatch[]) {
if (!q.trim() || !snippet) return escapeHtml(snippet); const parts: { text: string; matched: boolean }[] = [];
const words = q.trim().split(/\s+/).filter(w => w.length > 1); let cursor = 0;
if (words.length === 0) return escapeHtml(snippet); for (const { start, end } of matches) {
const escaped = escapeHtml(snippet); if (start > cursor) parts.push({ text: text.slice(cursor, start), matched: false });
const pattern = words.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'); parts.push({ text: text.slice(start, end), matched: true });
const re = new RegExp(`(${pattern})`, 'gi'); cursor = end;
return escaped.replace(re, '<mark>$1</mark>');
} }
if (cursor < text.length) parts.push({ text: text.slice(cursor), matched: false });
function escapeHtml(str: string): string { return parts;
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
} }
function findNotebookByPath(nbs: NotebookEntry[], target: string): NotebookEntry | null { function findNotebookByPath(nbs: NotebookEntry[], target: string): NotebookEntry | null {
for (const nb of nbs) { for (const nb of nbs) {
if (nb.path === target) return nb; if (relativePath(nb.path, target) === '.') return nb;
if (nb.children.length) { if (nb.children.length) {
const found = findNotebookByPath(nb.children, target); const found = findNotebookByPath(nb.children, target);
if (found) return found; if (found) return found;
@@ -96,41 +164,43 @@
} }
async function openResult(result: SearchResult) { async function openResult(result: SearchResult) {
if (loading || opening || !$showSearch || !results.includes(result)) return;
const generation = requestGeneration;
const vault = currentVault;
opening = true;
error = '';
try { try {
const content = await readNote(result.path); const normalized = result.path.replace(/\\/g, '/');
$activeNote = content; const parentDir = normalized.slice(0, normalized.lastIndexOf('/'));
$activeNotePath = result.path; const notebook = parentDir ? findNotebookByPath($notebooks, parentDir) : null;
$editorDirty = false; const opened = await onSelectNote(result, notebook, () => isCurrent(generation, vault));
$showSearch = false; if (!isCurrent(generation, vault)) return;
// Reveal the note in the notes list: switch to its notebook (or All Notes). if (!opened) {
const sep = result.path.includes('\\') ? '\\' : '/'; error = 'Could not open this note.';
const parentDir = result.path.slice(0, result.path.lastIndexOf(sep)); return;
const nb = parentDir ? findNotebookByPath($notebooks, parentDir) : null;
if (nb) {
$activeNotebook = nb;
$activeTag = null;
$viewMode = 'notebook';
} else {
$activeNotebook = null;
$activeTag = null;
$viewMode = 'all';
} }
if (isMobile) $mobileView = 'editor'; close();
} catch (e) { } catch (cause) {
console.error('Failed to open search result:', e); if (isCurrent(generation, vault)) error = cause instanceof Error ? cause.message : String(cause);
} finally {
if (isCurrent(generation, vault)) opening = false;
} }
} }
function previousPage() {
const lastPage = Math.max(0, Math.floor((total - 1) / PAGE_SIZE) * PAGE_SIZE);
startSearch(query, Math.max(0, Math.min(offset - PAGE_SIZE, lastPage)), true);
}
function close() { function close() {
cancelSearch();
$showSearch = false; $showSearch = false;
} }
</script> </script>
{#if $showSearch} {#if $showSearch}
<!-- svelte-ignore a11y_no_static_element_interactions --> <div class="search-overlay" role="presentation" onclick={close} onkeydowncapture={handleEscape}>
<div class="search-overlay" onclick={close} onkeydown={handleKeydown}> <div class="search-panel" role="dialog" aria-modal="true" aria-label="Search notes" tabindex="-1" onclick={(e) => e.stopPropagation()} onkeydown={handleKeydown}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="search-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
<div class="search-input-wrapper"> <div class="search-input-wrapper">
<svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /> <circle cx="11" cy="11" r="8" />
@@ -140,18 +210,36 @@
bind:this={inputEl} bind:this={inputEl}
type="text" type="text"
placeholder="Search notes..." placeholder="Search notes..."
role="combobox"
aria-label="Search notes"
aria-controls="global-search-results"
aria-expanded={results.length > 0}
aria-autocomplete="list"
aria-activedescendant={results.length ? `global-search-result-${selectedIndex}` : undefined}
bind:value={query} bind:value={query}
oninput={handleInput} oninput={handleInput}
onkeydown={handleKeydown} oncompositionstart={() => { composing = true; cancelSearch(); results = []; total = 0; error = ''; loading = false; }}
oncompositionend={(e) => { composing = false; startSearch(e.currentTarget.value); }}
/> />
{#if !isMobile}<kbd class="search-esc">Esc</kbd>{/if} {#if !isMobile}<kbd class="search-esc">Esc</kbd>{/if}
</div> </div>
{#if results.length > 0} {#if error}<div class="search-error" role="alert">{error}</div>{/if}
<div class="search-results" bind:this={resultsEl}> {#if composing}
{#each results as result, i} <div class="search-empty">Type to search across all notes</div>
{:else if loading}
<div class="search-empty" role="status">Searching…</div>
{:else if results.length > 0}
<div class="search-results" id="global-search-results" role="listbox" aria-label="Search results" bind:this={resultsEl}>
{#each rows as row, i (row.result.path)}
{@const result = row.result}
<button <button
class="result-item" class="result-item"
id={`global-search-result-${i}`}
role="option"
aria-selected={i === selectedIndex}
tabindex="-1"
disabled={opening}
class:selected={i === selectedIndex} class:selected={i === selectedIndex}
onclick={() => openResult(result)} onclick={() => openResult(result)}
onmouseenter={() => (selectedIndex = i)} onmouseenter={() => (selectedIndex = i)}
@@ -163,25 +251,18 @@
<line x1="16" y1="13" x2="8" y2="13" /> <line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" /> <line x1="16" y1="17" x2="8" y2="17" />
</svg> </svg>
<span class="result-title">{result.title}</span> <span class="result-title">{#each row.title as part}{#if part.matched}<mark>{part.text}</mark>{:else}{part.text}{/if}{/each}</span>
{#if getNotebook(result.path)} {#if getNotebook(result.path)}
<span class="result-notebook">{getNotebook(result.path)}</span> <span class="result-notebook">{getNotebook(result.path)}</span>
{/if} {/if}
</div> </div>
{#if result.snippet} {#if result.snippet}
<span class="result-snippet">{@html highlightSnippet(result.snippet, query)}</span> <span class="result-snippet">{#each row.snippet as part}{#if part.matched}<mark>{part.text}</mark>{:else}{part.text}{/if}{/each}</span>
{/if} {/if}
</button> </button>
{/each} {/each}
</div> </div>
<div class="search-footer"> {:else if query.trim() && !error}
<span class="search-count">{results.length} result{results.length !== 1 ? 's' : ''}</span>
<span class="search-hints">
<kbd>&uarr;</kbd><kbd>&darr;</kbd> navigate
<kbd>&crarr;</kbd> open
</span>
</div>
{:else if query.trim()}
<div class="no-results"> <div class="no-results">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity="0.3"> <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity="0.3">
<circle cx="11" cy="11" r="8" /> <circle cx="11" cy="11" r="8" />
@@ -189,13 +270,29 @@
<line x1="8" y1="8" x2="14" y2="14" /> <line x1="8" y1="8" x2="14" y2="14" />
<line x1="14" y1="8" x2="8" y2="14" /> <line x1="14" y1="8" x2="8" y2="14" />
</svg> </svg>
<span>No results for "{query}"</span> <span>{total > 0 ? 'Results changed. Choose an earlier page.' : `No results for "${query}"`}</span>
</div> </div>
{:else} {:else if !error}
<div class="search-empty"> <div class="search-empty">
<span>Type to search across all notes</span> <span>Type to search across all notes</span>
</div> </div>
{/if} {/if}
{#if total > 0}
<div class="search-footer">
<span class="search-count" role="status">
{#if results.length}{offset + 1}–{offset + results.length} of {total}{:else}{total} result{total !== 1 ? 's' : ''}{/if}
</span>
{#if total > PAGE_SIZE || offset > 0}
<div class="search-pages" aria-label="Result pages">
<button onclick={previousPage} disabled={loading || opening || offset === 0} aria-label="Previous results page">Previous</button>
<button onclick={() => startSearch(query, offset + PAGE_SIZE, true)} disabled={loading || opening || offset + PAGE_SIZE >= total} aria-label="Next results page">Next</button>
</div>
{/if}
{#if !isMobile}
<span class="search-hints"><kbd>&uarr;</kbd><kbd>&darr;</kbd> navigate <kbd>&crarr;</kbd> open</span>
{/if}
</div>
{/if}
</div> </div>
</div> </div>
{/if} {/if}
@@ -230,8 +327,8 @@
border: 1px solid var(--border-color); border: 1px solid var(--border-color);
border-radius: 14px; border-radius: 14px;
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.05) inset; box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.05) inset;
width: 620px; width: min(620px, calc(100vw - 32px));
max-height: 460px; max-height: min(460px, calc(85dvh - 24px));
overflow: hidden; overflow: hidden;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -257,6 +354,7 @@
.search-input-wrapper input { .search-input-wrapper input {
flex: 1; flex: 1;
min-width: 0;
border: none; border: none;
background: none; background: none;
color: var(--text-primary); color: var(--text-primary);
@@ -339,18 +437,23 @@
} }
.result-snippet { .result-snippet {
display: block; display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;
font-size: 12px; font-size: 12px;
color: var(--text-tertiary); color: var(--text-tertiary);
margin-top: 4px; margin-top: 4px;
margin-left: 24px; margin-left: 24px;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: normal;
overflow-wrap: anywhere;
line-height: 1.4; line-height: 1.4;
} }
.result-snippet :global(mark) { .result-title mark,
.result-snippet mark {
background: color-mix(in srgb, var(--accent) 25%, transparent); background: color-mix(in srgb, var(--accent) 25%, transparent);
color: var(--text-accent); color: var(--text-accent);
border-radius: 2px; border-radius: 2px;
@@ -359,6 +462,8 @@
.search-footer { .search-footer {
display: flex; display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 8px 18px; padding: 8px 18px;
@@ -406,4 +511,32 @@
color: var(--text-tertiary); color: var(--text-tertiary);
font-size: 13px; font-size: 13px;
} }
.search-error {
padding: 12px 18px;
color: var(--text-primary);
font-size: 13px;
overflow-wrap: anywhere;
}
.search-pages {
display: flex;
gap: 6px;
}
.search-pages button {
padding: 4px 8px;
border: 1px solid var(--border-color);
border-radius: 4px;
background: var(--bg-secondary);
color: var(--text-primary);
font: inherit;
font-size: 12px;
cursor: pointer;
}
.search-pages button:disabled {
opacity: 0.45;
cursor: default;
}
</style> </style>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
<script lang="ts">
import { onMount } from 'svelte';
import type { SourceController } from '$lib/editor/source/controller';
let { controller, readonly = false, numbers = false, visible = true, mobile = false }: {
controller: SourceController;
readonly?: boolean;
numbers?: boolean;
visible?: boolean;
mobile?: boolean;
} = $props();
let host: HTMLDivElement;
onMount(() => {
const detach = controller.attach(host);
const measure = () => controller.view?.requestMeasure();
const appearance = new MutationObserver(measure);
appearance.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });
document.fonts.addEventListener('loadingdone', measure);
return () => {
appearance.disconnect();
document.fonts.removeEventListener('loadingdone', measure);
detach();
};
});
$effect(() => { controller.configure(readonly, numbers); });
$effect(() => { if (visible) controller.view?.requestMeasure(); });
</script>
<div class="source-editor" class:mobile class:with-line-numbers={numbers} style:display={visible ? undefined : 'none'} bind:this={host}></div>
<style>
.source-editor {
width: 100%;
height: 100%;
min-height: 0;
max-width: var(--editor-content-width, none);
margin: 0 auto;
user-select: text;
}
.source-editor.with-line-numbers { max-width: none; }
.source-editor.mobile :global(.cm-editor) { font-size: var(--editor-font-size, 15px); }
.source-editor.mobile :global(.cm-content) { padding: 8px 16px max(220px, var(--editor-scroll-past-end, 65vh)); }
</style>
+143
View File
@@ -0,0 +1,143 @@
<script lang="ts">
import { convertFileSrc } from '@tauri-apps/api/core';
import { appConfig, tagStyles } from '$lib/stores/app';
import NotebookGlyph from './NotebookGlyph.svelte';
import { decodeBuiltinNotebookIcon } from '$lib/utils/notebook-icons';
import { isValidTagColor, lookupTagStyle } from '$lib/utils/tag-styles';
let {
name,
size = 14,
tone = 'none',
showName = true
}: {
name: string;
size?: number;
tone?: 'none' | 'accent' | 'muted';
showName?: boolean;
} = $props();
const style = $derived(lookupTagStyle(name, $tagStyles));
const color = $derived.by(() => {
const value = style?.color;
return isValidTagColor(value) ? value : null;
});
const builtinIcon = $derived(decodeBuiltinNotebookIcon(style?.icon));
const imageSrc = $derived.by(() => {
const icon = style?.icon;
const vault = $appConfig?.active_vault;
if (!icon || builtinIcon || icon.startsWith('builtin:') || !vault) return null;
return convertFileSrc(`${vault}/${icon}`);
});
</script>
<span
class={[
'tag-label',
`tone-${tone}`,
{ 'has-color': !!color, 'has-icon': !!(builtinIcon || imageSrc) }
]}
style:--tag-color={color}
title={`#${name}`}
>
<span class="tag-icon" style:width={`${size}px`} style:height={`${size}px`}>
{#if builtinIcon}
<NotebookGlyph icon={builtinIcon} {size} />
{:else if imageSrc}
<img class="tag-image" crossorigin="anonymous" src={imageSrc} alt="" width={size} height={size} />
{:else}
<span class="tag-hash">#</span>
{/if}
</span>
{#if showName}<span class="tag-name">{name}</span>{/if}
</span>
<style>
.tag-label {
display: inline-flex;
align-items: center;
gap: 4px;
min-width: 0;
max-width: 100%;
color: inherit;
line-height: 1.2;
}
.tag-label.has-color {
color: var(--tag-color);
}
.tag-icon,
.tag-image,
.tag-hash {
flex-shrink: 0;
}
.tag-icon {
display: flex;
align-items: center;
justify-content: center;
line-height: 1;
color: inherit;
}
.tag-image {
border-radius: 3px;
object-fit: cover;
}
.tag-hash {
font-weight: 600;
color: inherit;
opacity: 0.72;
}
.tag-label.has-color .tag-hash,
.tag-label.has-icon .tag-hash,
.tone-accent .tag-hash,
.tone-muted .tag-hash {
opacity: 1;
}
.tag-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tone-accent {
gap: 3px;
padding: 1px 5px;
border-radius: 3px;
background: var(--accent-light);
color: var(--text-accent);
font-size: 10px;
}
.tone-accent.has-color {
color: var(--tag-color);
background: color-mix(in srgb, var(--tag-color) 18%, transparent);
}
.tone-muted {
gap: 3px;
padding: 1px 7px;
border-radius: 10px;
background: var(--bg-tertiary);
color: var(--text-tertiary);
font-size: 11px;
letter-spacing: 0.01em;
}
.tone-muted.has-color {
color: var(--tag-color);
background: color-mix(in srgb, var(--tag-color) 16%, var(--bg-tertiary));
}
.tone-accent .tag-hash,
.tone-muted .tag-hash {
color: inherit;
font-weight: 600;
}
</style>
+464
View File
@@ -0,0 +1,464 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { readFile } from '@tauri-apps/plugin-fs';
import { get } from 'svelte/store';
import { appConfig, tagStyles } from '$lib/stores/app';
import { importTagIcon, setTagStyle } from '$lib/api';
import type { TagStyle, TagStyleChange } from '$lib/types';
import { tagAppearance } from '$lib/utils/appearance-mutations';
import { isMobile } from '$lib/platform';
import NotebookGlyph from './NotebookGlyph.svelte';
import TagLabel from './TagLabel.svelte';
import {
NOTEBOOK_ICON_OPTIONS,
encodeBuiltinNotebookIcon,
type NotebookIconId
} from '$lib/utils/notebook-icons';
import {
TAG_COLOR_PRESETS,
applyCommittedTagStyle,
lookupTagStyle,
tagColor
} from '$lib/utils/tag-styles';
let {
tag,
onclose
}: {
tag: string;
onclose: () => void;
} = $props();
let dialogEl = $state<HTMLDivElement | null>(null);
const ownerVault = get(appConfig)?.active_vault ?? null;
let disposed = false;
let error = $state('');
const ownerIsCurrent = () => !disposed && get(appConfig)?.active_vault === ownerVault;
onDestroy(() => { disposed = true; });
const current = $derived(lookupTagStyle(tag, $tagStyles));
const activeIcon = $derived(current?.icon ?? null);
const activeColor = $derived(tagColor(tag, $tagStyles));
const colorInputValue = $derived(expandHex(activeColor) ?? '#5b6abf');
const hasStyle = $derived(!!(activeIcon || activeColor));
function publishStyle(target: string, next: TagStyle | null) {
if (get(appConfig)?.active_vault !== ownerVault) return;
tagStyles.update(styles => applyCommittedTagStyle(styles, target, next));
}
onMount(() => dialogEl?.focus());
function expandHex(color: string | null): string | null {
if (!color) return null;
if (color.length === 4) {
return `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`;
}
return color;
}
function baseOf(path: string): string {
return path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1);
}
async function persist(change: TagStyleChange): Promise<boolean> {
if (!ownerVault || !ownerIsCurrent()) return false;
const target = tag;
const key = target.trim().toLowerCase();
let latest: () => boolean;
if (change.kind === 'reset') {
tagAppearance.choose(ownerVault, `${key}:icon`);
tagAppearance.choose(ownerVault, `${key}:color`);
latest = () => true;
} else {
latest = tagAppearance.choose(ownerVault, `${key}:${change.kind}`);
}
error = '';
try {
await tagAppearance.run(ownerVault, key, latest,
() => setTagStyle(ownerVault, target, change),
(next) => publishStyle(target, next));
return true;
} catch (cause) {
if (ownerIsCurrent() && tag === target && latest()) error = String(cause);
return false;
}
}
function handleBuiltinIcon(icon: NotebookIconId) {
void persist({ kind: 'icon', value: encodeBuiltinNotebookIcon(icon) });
}
async function handleCustomIcon() {
if (!ownerVault || !ownerIsCurrent()) return;
const target = tag;
const key = target.trim().toLowerCase();
const latest = tagAppearance.choose(ownerVault, `${key}:icon`);
error = '';
try {
const selected = await openDialog({
multiple: false,
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'] }]
});
if (!selected || !ownerIsCurrent() || tag !== target || !latest()) return;
const filePath = selected as string;
const data = await readFile(filePath);
if (!ownerIsCurrent() || tag !== target || !latest()) return;
const fileName = baseOf(filePath) || 'icon.png';
await tagAppearance.run(ownerVault, key, latest,
() => importTagIcon(ownerVault, target, `tag-icon-${fileName}`, Array.from(data)),
(next) => publishStyle(target, next));
} catch (cause) {
if (ownerIsCurrent() && tag === target && latest()) error = String(cause);
}
}
async function handleReset() {
const target = tag;
if (await persist({ kind: 'reset' }) && ownerIsCurrent() && tag === target) onclose();
}
function onColorInput(e: Event) {
void persist({ kind: 'color', value: (e.currentTarget as HTMLInputElement).value });
}
</script>
<svelte:window
onkeydown={(e) => {
if (e.key === 'Escape') {
e.preventDefault();
onclose();
}
}}
/>
<div class="icon-picker-overlay" class:mobile={isMobile}>
<button class="icon-picker-backdrop" aria-label="Close tag appearance picker" onclick={onclose}></button>
<div
bind:this={dialogEl}
class="icon-picker"
role="dialog"
aria-modal="true"
aria-label={`Choose an icon and color for ${tag}`}
tabindex="-1"
>
<header class="icon-picker-header">
<div>
<h3>Tag appearance</h3>
<p>
<TagLabel name={tag} size={14} />
</p>
</div>
<button type="button" class="icon-picker-close" aria-label="Close tag appearance picker" onclick={onclose}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
</button>
</header>
{#if error}<div class="picker-error" role="alert">{error}</div>{/if}
<div class="icon-picker-grid">
{#each NOTEBOOK_ICON_OPTIONS as option (option.id)}
<button
type="button"
class="icon-picker-option"
class:active={activeIcon === encodeBuiltinNotebookIcon(option.id)}
aria-label={option.label}
title={option.label}
onclick={() => handleBuiltinIcon(option.id)}
>
<NotebookGlyph icon={option.id} size={20} />
<span>{option.label}</span>
</button>
{/each}
</div>
<div class="color-section">
<span class="color-label">Color</span>
<div class="swatches">
<button
type="button"
class="swatch none"
class:active={!activeColor}
aria-label="Use default color"
title="Default color"
onclick={() => persist({ kind: 'color', value: null })}
></button>
{#each TAG_COLOR_PRESETS as preset (preset)}
<button
type="button"
class="swatch"
class:active={activeColor?.toLowerCase() === preset}
style:background={preset}
aria-label={`Use ${preset}`}
title={preset}
onclick={() => persist({ kind: 'color', value: preset })}
></button>
{/each}
<label class="swatch custom" title="Custom color">
<input type="color" value={colorInputValue} oninput={onColorInput} aria-label="Custom tag color" />
</label>
</div>
</div>
<div class="icon-picker-actions">
<button type="button" onclick={handleCustomIcon}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><path d="m21 15-5-5L5 21" /></svg>
Custom image...
</button>
{#if hasStyle}
<button type="button" class="remove" onclick={handleReset}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 7h16M9 7V4h6v3M7 7l1 13h8l1-13" /></svg>
Use default
</button>
{/if}
<p class="icon-picker-recommendation">Icons and colors are optional. Recommended image size: <strong>1:1</strong></p>
</div>
</div>
</div>
<style>
.picker-error {
padding: 8px 16px;
font-size: 13px;
color: var(--text-primary);
overflow-wrap: anywhere;
}
.icon-picker-overlay {
position: fixed;
inset: 0;
z-index: 1100;
display: grid;
place-items: center;
padding: 20px;
}
.icon-picker-backdrop {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
padding: 0;
border: none;
background: rgba(8, 10, 18, 0.42);
cursor: default;
}
.icon-picker {
position: relative;
z-index: 1;
width: min(360px, 100%);
max-height: calc(100dvh - 40px);
overflow-y: auto;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 14px;
box-shadow: var(--shadow-lg);
}
.icon-picker-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 16px 18px 12px;
border-bottom: 1px solid var(--border-light);
}
.icon-picker-header h3,
.icon-picker-header p {
margin: 0;
}
.icon-picker-header h3 {
color: var(--text-primary);
font-size: 15px;
font-weight: 650;
}
.icon-picker-header p {
margin-top: 6px;
color: var(--text-tertiary);
font-size: 12px;
}
.icon-picker-close {
width: 32px;
height: 32px;
display: grid;
place-items: center;
padding: 0;
border: none;
border-radius: 8px;
background: transparent;
color: var(--text-tertiary);
cursor: pointer;
}
.icon-picker-close:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.icon-picker-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 7px;
padding: 14px;
}
.icon-picker-option {
min-width: 0;
min-height: 60px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 5px;
padding: 7px 3px 6px;
border: 1px solid transparent;
border-radius: 9px;
background: var(--bg-secondary);
color: var(--text-secondary);
cursor: pointer;
}
.icon-picker-option span {
max-width: 100%;
overflow: hidden;
color: var(--text-tertiary);
font-size: 10px;
line-height: 1.1;
text-overflow: ellipsis;
white-space: nowrap;
}
.icon-picker-option:hover {
border-color: var(--border-color);
background: var(--bg-hover);
color: var(--text-primary);
}
.icon-picker-option.active {
border-color: var(--accent);
background: var(--accent-light);
color: var(--accent);
}
.icon-picker-option.active span {
color: var(--accent);
}
.color-section {
display: flex;
flex-direction: column;
gap: 8px;
padding: 0 14px 12px;
}
.color-label {
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
}
.swatches {
display: flex;
flex-wrap: wrap;
gap: 7px;
align-items: center;
}
.swatch {
width: 22px;
height: 22px;
padding: 0;
border: 2px solid transparent;
border-radius: 50%;
background: var(--bg-tertiary);
cursor: pointer;
}
.swatch:hover,
.swatch.active {
border-color: var(--text-primary);
}
.swatch.none {
background:
linear-gradient(to bottom right, transparent calc(50% - 1px), var(--text-tertiary) calc(50% - 1px), var(--text-tertiary) calc(50% + 1px), transparent calc(50% + 1px)),
var(--bg-secondary);
border-color: var(--border-color);
}
.swatch.custom {
display: grid;
place-items: center;
overflow: hidden;
background: conic-gradient(from 90deg, #e11d48, #eab308, #22c55e, #3b82f6, #8b5cf6, #e11d48);
}
.swatch.custom input {
width: 28px;
height: 28px;
padding: 0;
border: none;
background: none;
cursor: pointer;
transform: scale(1.4);
}
.icon-picker-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 12px 14px 14px;
border-top: 1px solid var(--border-light);
}
.icon-picker-recommendation {
flex: 0 0 100%;
margin: 2px 0 0;
color: var(--text-tertiary);
font-size: 11px;
line-height: 1.3;
text-align: center;
}
.icon-picker-actions button {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
padding: 9px 12px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-secondary);
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
}
.icon-picker-actions button:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.icon-picker-actions button.remove {
color: var(--text-tertiary);
}
.icon-picker-overlay.mobile {
padding: 12px;
align-items: end;
}
.icon-picker-overlay.mobile .icon-picker {
width: 100%;
max-height: min(86dvh, 640px);
}
.icon-picker-overlay.mobile .icon-picker-option {
min-height: 64px;
}
.icon-picker-overlay.mobile .icon-picker-actions button {
min-height: 44px;
}
</style>
+5 -2
View File
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { tags } from '$lib/stores/app'; import { tags } from '$lib/stores/app';
import TagLabel from './TagLabel.svelte';
let { existing = [], placeholder = 'Add tag...', onsubmit, oncancel }: { let { existing = [], placeholder = 'Add tag...', onsubmit, oncancel }: {
existing?: string[]; existing?: string[];
@@ -69,14 +70,14 @@
/> />
{#if suggestions.length} {#if suggestions.length}
<div class="tag-suggest-list"> <div class="tag-suggest-list">
{#each suggestions as s, i} {#each suggestions as s, i (s)}
<button <button
type="button" type="button"
class="tag-suggest-item" class="tag-suggest-item"
class:selected={i === selIndex} class:selected={i === selIndex}
onmouseenter={() => (selIndex = i)} onmouseenter={() => (selIndex = i)}
onmousedown={(e) => { e.preventDefault(); submit(s); }} onmousedown={(e) => { e.preventDefault(); submit(s); }}
>#{s}</button> ><TagLabel name={s} size={12} /></button>
{/each} {/each}
</div> </div>
{/if} {/if}
@@ -110,6 +111,8 @@
gap: 1px; gap: 1px;
} }
.tag-suggest-item { .tag-suggest-item {
display: flex;
align-items: center;
text-align: left; text-align: left;
padding: 5px 8px; padding: 5px 8px;
border: none; border: none;
+70 -10
View File
@@ -6,6 +6,7 @@
import { tasksLayout, tasksHideCompleted, tasksOnlyFlagged, tasksSort, appConfig } from '$lib/stores/app'; import { tasksLayout, tasksHideCompleted, tasksOnlyFlagged, tasksSort, appConfig } from '$lib/stores/app';
import { isAndroid } from '$lib/platform'; import { isAndroid } from '$lib/platform';
import type { TaskItem, FileEvent } from '$lib/types'; import type { TaskItem, FileEvent } from '$lib/types';
import { isCurrentVaultEvent } from '$lib/utils/note-list-updates';
let { onOpenTask = (_t: TaskItem) => {}, onToggleTask = async (_t: TaskItem) => {}, onSetTaskPriority = async (_t: TaskItem, _p: string | null) => {}, onSetTaskDue = async (_t: TaskItem, _d: string | null) => {} }: { let { onOpenTask = (_t: TaskItem) => {}, onToggleTask = async (_t: TaskItem) => {}, onSetTaskPriority = async (_t: TaskItem, _p: string | null) => {}, onSetTaskDue = async (_t: TaskItem, _d: string | null) => {} }: {
onOpenTask?: (t: TaskItem) => void; onOpenTask?: (t: TaskItem) => void;
@@ -18,23 +19,82 @@
let loading = $state(true); let loading = $state(true);
let taskQuery = $state(''); let taskQuery = $state('');
let unlisten: (() => void) | null = null; let unlisten: (() => void) | null = null;
let disposed = false;
let fullLoad = 0;
let revision = 0;
const noteRevisions = new Map<string, number>();
async function load() { async function load() {
if (disposed) return;
const request = ++fullLoad;
const startedAt = revision;
try { try {
tasks = await getTasks(); const loaded = await getTasks();
if (disposed || request !== fullLoad) return;
// Keep per-note updates/removals that arrived during the full scan.
const changedPaths = new Set(
[...noteRevisions].filter(([, changedAt]) => changedAt > startedAt).map(([path]) => path),
);
tasks = [
...loaded.filter((task) => !changedPaths.has(task.note_path)),
...tasks.filter((task) => changedPaths.has(task.note_path)),
];
} catch (e) { } catch (e) {
console.error('Failed to load tasks:', e); console.error('Failed to load tasks:', e);
tasks = []; } finally {
if (!disposed && request === fullLoad) loading = false;
}
}
async function loadNote(path: string) {
if (disposed) return;
const request = ++revision;
const generation = fullLoad;
noteRevisions.set(path, request);
try {
const loaded = await getTasks(path);
if (disposed || generation !== fullLoad || noteRevisions.get(path) !== request) return;
tasks = [...tasks.filter((task) => task.note_path !== path), ...loaded];
} catch (e) {
console.error('Failed to refresh note tasks:', e);
} }
loading = false;
} }
const debouncedLoad = debounce(load, 400); const debouncedLoad = debounce(load, 400);
function handleFileChange(event: FileEvent) {
if (disposed || !isCurrentVaultEvent(event, $appConfig?.active_vault ?? null)) return;
if (event.event_type === 'remove') {
const isDescendant = (path: string) =>
path.startsWith(event.path + '/') || path.startsWith(event.path + '\\');
const removedPaths = new Set([
event.path,
...tasks.filter((task) => isDescendant(task.note_path)).map((task) => task.note_path),
...[...noteRevisions.keys()].filter(isDescendant),
]);
for (const path of removedPaths) noteRevisions.set(path, ++revision);
tasks = tasks.filter((task) => !removedPaths.has(task.note_path));
if (event.path.endsWith('.md') && removedPaths.size === 1) return;
} else if (event.note) {
void loadNote(event.note.path);
return;
}
// Directory/unknown events need the full scan; ordinary note saves do not.
fullLoad += 1;
debouncedLoad();
}
onMount(() => { onMount(() => {
load(); void load();
listen<FileEvent>('file-changed', () => debouncedLoad()).then((u) => (unlisten = u)); listen<FileEvent>('file-changed', ({ payload }) => handleFileChange(payload)).then((u) => {
return () => { unlisten?.(); }; if (disposed) u();
else unlisten = u;
});
return () => {
disposed = true;
fullLoad += 1;
unlisten?.();
};
}); });
// Local YYYY-MM-DD (en-CA gives ISO-style date) // Local YYYY-MM-DD (en-CA gives ISO-style date)
@@ -83,7 +143,7 @@
async function toggle(t: TaskItem) { async function toggle(t: TaskItem) {
await onToggleTask(t); await onToggleTask(t);
await load(); await loadNote(t.note_path);
} }
let prioMenuFor = $state<string | null>(null); let prioMenuFor = $state<string | null>(null);
@@ -93,13 +153,13 @@
async function choosePriority(t: TaskItem, p: string | null) { async function choosePriority(t: TaskItem, p: string | null) {
prioMenuFor = null; prioMenuFor = null;
await onSetTaskPriority(t, p); await onSetTaskPriority(t, p);
await load(); await loadNote(t.note_path);
} }
async function chooseDue(t: TaskItem, d: string | null) { async function chooseDue(t: TaskItem, d: string | null) {
dueMenuFor = null; dueMenuFor = null;
await onSetTaskDue(t, d); await onSetTaskDue(t, d);
await load(); await loadNote(t.note_path);
} }
// ── Calendar ── // ── Calendar ──
@@ -183,7 +243,7 @@
dragOverDate = null; dragOverDate = null;
if (!t || t.due === date) return; if (!t || t.due === date) return;
await onSetTaskDue(t, date); await onSetTaskDue(t, date);
await load(); await loadNote(t.note_path);
} }
</script> </script>
+27 -6
View File
@@ -1,11 +1,20 @@
<script lang="ts"> <script lang="ts">
import { getCurrentWindow } from '@tauri-apps/api/window'; import { getCurrentWindow } from '@tauri-apps/api/window';
import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, activeVaultConfig, syncState } from '$lib/stores/app'; import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, activeNotePath, activeVaultConfig, syncState } from '$lib/stores/app';
import { syncNow } from '$lib/api'; import { syncNow } from '$lib/api';
import NoteSwitcher from './NoteSwitcher.svelte';
import { isTrashedNote } from '$lib/utils/paths';
let { onNewNote = () => {}, onDailyNote = () => {} }: { let {
onNewNote = () => {},
onDailyNote = () => {},
onSelectNote,
onBeforeVaultSwitch
}: {
onNewNote?: () => void; onNewNote?: () => void;
onDailyNote?: () => void; onDailyNote?: () => void;
onSelectNote?: (path: string) => Promise<boolean>;
onBeforeVaultSwitch: () => Promise<boolean>;
} = $props(); } = $props();
const appWindow = getCurrentWindow(); const appWindow = getCurrentWindow();
@@ -30,7 +39,7 @@
function handleMouseDown(e: MouseEvent) { function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return; if (e.button !== 0) return;
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions')) return; if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions') || target.closest('.titlebar-note-switcher')) return;
// Don't start dragging near window edges - let Tauri handle resize // Don't start dragging near window edges - let Tauri handle resize
if (!maximized) { if (!maximized) {
@@ -81,8 +90,13 @@
</button> </button>
{/if} {/if}
</div> </div>
{#if $appConfig?.show_note_switcher}
<div class="titlebar-note-switcher">
<NoteSwitcher {onSelectNote} />
</div>
{/if}
<div class="titlebar-actions"> <div class="titlebar-actions">
<button class="switch-vault-btn" onclick={() => ($vaultReady = false)} title="Switch Vault"> <button class="switch-vault-btn" onclick={async () => { if (await onBeforeVaultSwitch()) $vaultReady = false; }} title="Switch Vault">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" /> <path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
</svg> </svg>
@@ -92,7 +106,7 @@
<path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"/> <path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"/>
</svg> </svg>
</button> </button>
<button class="switch-vault-btn" class:active={$readOnly} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Switch to Edit Mode' : 'Switch to View Mode'}> <button class="switch-vault-btn" class:active={$readOnly} disabled={isTrashedNote($activeNotePath, $appConfig?.active_vault)} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Switch to Edit Mode' : 'Switch to View Mode'}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
{#if $readOnly} {#if $readOnly}
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /> <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
@@ -173,7 +187,13 @@
gap: 8px; gap: 8px;
padding-left: 14px; padding-left: 14px;
pointer-events: none; pointer-events: none;
flex: 1; }
.titlebar-note-switcher {
display: flex;
align-items: center;
margin-left: 16px;
-webkit-app-region: no-drag;
} }
.titlebar-title { .titlebar-title {
@@ -205,6 +225,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 6px; gap: 6px;
margin-left: auto;
margin-right: 8px; margin-right: 8px;
-webkit-app-region: no-drag; -webkit-app-region: no-drag;
} }
+24 -8
View File
@@ -1,8 +1,9 @@
<script lang="ts"> <script lang="ts">
import { onMount, untrack } from 'svelte';
import { open } from '@tauri-apps/plugin-dialog'; import { open } from '@tauri-apps/plugin-dialog';
import { getCurrentWindow } from '@tauri-apps/api/window'; import { getCurrentWindow } from '@tauri-apps/api/window';
import { documentDir } from '@tauri-apps/api/path'; import { documentDir } from '@tauri-apps/api/path';
import { chooseExternalVault, getAppConfig, openVault, removeVault, restoreExternalVault } from '$lib/api'; import { chooseExternalVault, completeWindowClose, getAppConfig, openVault, removeVault, restoreExternalVault } from '$lib/api';
import { appConfig, vaultReady } from '$lib/stores/app'; import { appConfig, vaultReady } from '$lib/stores/app';
import { isAndroid, isIOS, isMobile } from '$lib/platform'; import { isAndroid, isIOS, isMobile } from '$lib/platform';
import type { VaultConfig } from '$lib/types'; import type { VaultConfig } from '$lib/types';
@@ -10,17 +11,30 @@
let { initialError = '' }: { initialError?: string } = $props(); let { initialError = '' }: { initialError?: string } = $props();
const appWindow = getCurrentWindow(); const appWindow = getCurrentWindow();
onMount(() => {
let disposed = false;
let unlisten: (() => void) | undefined;
appWindow.onCloseRequested(async (event) => {
event.preventDefault();
try {
await completeWindowClose();
} catch (error) {
console.error('Failed to close window:', error);
}
}).then((stop) => {
if (disposed) stop();
else unlisten = stop;
});
return () => { disposed = true; unlisten?.(); };
});
let recentVaults: VaultConfig[] = $derived($appConfig?.vaults ?? []); let recentVaults: VaultConfig[] = $derived($appConfig?.vaults ?? []);
let loading = $state(false); let loading = $state(false);
let error = $state(''); let error = $state(untrack(() => initialError));
let vaultName = $state('HelixNotes'); let vaultName = $state('HelixNotes');
let hasPermission = $state(!isAndroid); let hasPermission = $state(!isAndroid);
let selectedLocation = $state('Documents'); let selectedLocation = $state('Documents');
$effect(() => {
if (initialError && !error) error = initialError;
});
let customPath = $state(''); let customPath = $state('');
let iosBasePath = $state(''); let iosBasePath = $state('');
@@ -214,19 +228,21 @@
{/if} {/if}
{#if isAndroid} {#if isAndroid}
<div class="location-selector"> <div class="location-selector" role="group" aria-labelledby="storage-location-label">
<label class="location-label">Location</label> <span id="storage-location-label" class="location-label">Location</span>
<div class="location-options"> <div class="location-options">
{#each storageLocations as loc} {#each storageLocations as loc}
<button <button
class="location-option" class="location-option"
class:active={selectedLocation === loc.label} class:active={selectedLocation === loc.label}
aria-pressed={selectedLocation === loc.label}
onclick={() => selectedLocation = loc.label} onclick={() => selectedLocation = loc.label}
>{loc.label}</button> >{loc.label}</button>
{/each} {/each}
<button <button
class="location-option" class="location-option"
class:active={selectedLocation === 'Custom'} class:active={selectedLocation === 'Custom'}
aria-pressed={selectedLocation === 'Custom'}
onclick={() => selectedLocation = 'Custom'} onclick={() => selectedLocation = 'Custom'}
>Custom</button> >Custom</button>
</div> </div>
@@ -267,7 +283,7 @@
</button> </button>
{/if} {/if}
{#if $appConfig?.active_vault} {#if $appConfig?.active_vault && !initialError}
<button class="btn-back" onclick={() => ($vaultReady = true)}> <button class="btn-back" onclick={() => ($vaultReady = true)}>
Back Back
</button> </button>
+81
View File
@@ -0,0 +1,81 @@
import type { Editor } from '@tiptap/core';
import type { Schema } from '@tiptap/pm/model';
import type { Transaction } from '@tiptap/pm/state';
import { liftTarget } from '@tiptap/pm/transform';
// Marks that carry content (URLs, note references) rather than visual
// formatting. Clearing formatting must never destroy these.
const CONTENT_MARKS: Record<string, true> = { link: true, wikiLink: true };
// Block types reset to plain paragraphs. Lists, callouts, collapsible
// sections and tables keep their structure so no state (checkboxes,
// nesting, cells) is lost.
const DEMOTE_BLOCKS: Record<string, true> = { heading: true, codeBlock: true };
// Outermost-first position of the first blockquote intersecting [from, to].
function findBlockquote(tr: Transaction, from: number, to: number): number | null {
let found: number | null = null;
tr.doc.nodesBetween(from, to, (node, pos) => {
if (found !== null) return false;
if (node.type.name === 'blockquote') {
found = pos;
return false;
}
return true;
});
return found;
}
/**
* Strips inline formatting and demotes heading/code-block/blockquote
* structure over the transaction's selection. An empty (cursor) selection
* is expanded to the whole current text block, so a single invocation can
* reset one messy line without highlighting it first.
*/
export function applyClearFormatting(schema: Schema, tr: Transaction): void {
const { selection } = tr;
const { $from } = selection;
const expandToBlock = selection.empty && $from.parent.isTextblock;
const from = expandToBlock ? $from.start() : selection.from;
const to = expandToBlock ? $from.end() : selection.to;
// 1. Strip formatting marks, keep content-bearing ones.
for (const mark of Object.values(schema.marks)) {
if (!CONTENT_MARKS[mark.name]) tr.removeMark(from, to, mark);
}
// 2. Demote headings and code blocks to paragraphs. Mark removal and
// retyping never move content, so the original positions stay valid.
tr.doc.nodesBetween(from, to, (node, pos) => {
if (DEMOTE_BLOCKS[node.type.name]) tr.setNodeMarkup(pos, schema.nodes.paragraph);
return true;
});
// 3. Lift blockquote contents out of the quote wrapper, one pass per
// nesting level. Lifts move positions, so remap and rescan each pass.
for (let guard = 0; guard < 20; guard++) {
const quotePos = findBlockquote(tr, tr.mapping.map(from, 1), tr.mapping.map(to, -1));
if (quotePos === null) break;
// The range must span the blockquote's content: a collapsed
// blockRange starts one depth up and wraps the quote itself.
const quote = tr.doc.nodeAt(quotePos);
if (!quote) break;
const range = tr.doc.resolve(quotePos + 1).blockRange(tr.doc.resolve(quotePos + quote.nodeSize - 1));
if (!range) break;
const target = liftTarget(range);
if (target === null) break;
tr.lift(range, target);
}
}
/** Clears formatting for the editor's current selection (or current line). */
export function clearFormatting(editor: Editor): boolean {
return editor
.chain()
.focus()
.command(({ state, tr }) => {
applyClearFormatting(state.schema, tr);
return true;
})
.run();
}
+75
View File
@@ -0,0 +1,75 @@
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
import type { EditorState } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
const COPY_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
const CHECK_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
export function buildCodeCopyDecorations(doc: ProseMirrorNode): DecorationSet {
const decorations: Decoration[] = [];
doc.descendants((node, pos) => {
if (node.type.name !== 'codeBlock') return !node.isTextblock;
decorations.push(Decoration.widget(pos + 1, (view, getPos) => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'code-copy-btn';
button.title = 'Copy code';
button.innerHTML = COPY_ICON;
button.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
const position = getPos();
if (position === undefined || view.isDestroyed) return;
const current = view.state.doc.resolve(position).parent;
if (current.type.name !== 'codeBlock') return;
void navigator.clipboard.writeText(current.textContent).then(() => {
if (!button.isConnected) return;
button.innerHTML = CHECK_ICON;
button.classList.add('copied');
setTimeout(() => { button.innerHTML = COPY_ICON; button.classList.remove('copied'); }, 1500);
}).catch((error) => console.error('Failed to copy code:', error));
});
return button;
}, { side: -1, key: `copy-btn:${pos}` }));
return false;
});
return DecorationSet.create(doc, decorations);
}
const priority = /(^|\s)(!(?:high|medium|med|low))\b/gi;
const due = /\bdue:\d{4}-\d{2}-\d{2}\b/gi;
export function buildTaskMetaDecorations(doc: ProseMirrorNode): DecorationSet {
const decorations: Decoration[] = [];
doc.descendants((node, pos) => {
// A prose-only note never traverses inline text or resolves a position.
if (node.type.name !== 'taskItem') return !node.isTextblock;
// One traversal covers the whole task subtree, including nested tasks.
node.descendants((child, offset) => {
if (!child.isText || !child.text) return;
const start = pos + 1 + offset;
for (const match of child.text.matchAll(priority)) {
const from = start + match.index! + match[1].length;
decorations.push(Decoration.inline(from, from + match[2].length, { class: 'task-meta-dim' }));
}
for (const match of child.text.matchAll(due)) {
const from = start + match.index!;
decorations.push(Decoration.inline(from, from + match[0].length, { class: 'task-meta-dim' }));
}
});
return false;
});
return DecorationSet.create(doc, decorations);
}
/** Placeholder only needs the caret's empty textblock, not a recursive document emptiness scan. */
export function focusedPlaceholderDecorations(state: EditorState): DecorationSet {
const { $anchor } = state.selection;
const node = $anchor.parent;
if (!$anchor.depth || !node.isTextblock || node.content.size) return DecorationSet.empty;
const pos = $anchor.before();
const placeholder = node.type.name === 'detailsSummary' ? 'Section title...' : 'Start writing...';
return DecorationSet.create(state.doc, [Decoration.node(pos, pos + node.nodeSize, {
class: 'is-empty', 'data-placeholder': placeholder,
})]);
}
@@ -0,0 +1,130 @@
import CodeBlock, { type CodeBlockOptions } from '@tiptap/extension-code-block';
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
interface HighlightNode {
type: string;
value?: string;
properties?: { className?: unknown };
children?: HighlightNode[];
}
export interface CodeHighlighter {
registered(language: string): boolean;
highlight(language: string, text: string): { children: HighlightNode[] };
highlightAuto(text: string): { children: HighlightNode[] };
}
type HighlightSpan = { from: number; to: number; className: string };
type HighlightState = { blocks: Map<number, ProseMirrorNode>; decorations: DecorationSet };
export function createCodeBlockHighlightPlugin({
name = 'codeBlock',
lowlight,
defaultLanguage = null,
}: {
name?: string;
lowlight: CodeHighlighter;
defaultLanguage?: string | null;
}) {
// Nodes are immutable. Relative spans survive moves and undo without retaining
// deleted documents, and never leak between editor/highlighter instances.
const cache = new WeakMap<ProseMirrorNode, HighlightSpan[]>();
function highlight(node: ProseMirrorNode): HighlightSpan[] {
const cached = cache.get(node);
if (cached) return cached;
const language = node.attrs.language || defaultLanguage;
const tree = language && lowlight.registered(language)
? lowlight.highlight(language, node.textContent)
: lowlight.highlightAuto(node.textContent);
const spans: HighlightSpan[] = [];
let offset = 0;
function visit(nodes: HighlightNode[], inheritedClass: string) {
for (const child of nodes) {
if (child.type === 'element' && child.children) {
const classes = child.properties?.className;
const ownClass = Array.isArray(classes) ? classes.join(' ') : typeof classes === 'string' ? classes : '';
visit(child.children, [inheritedClass, ownClass].filter(Boolean).join(' '));
} else if (child.type === 'text' && child.value !== undefined) {
const end = offset + child.value.length;
if (inheritedClass && end > offset) spans.push({ from: offset, to: end, className: inheritedClass });
offset = end;
}
}
}
visit(tree.children, '');
cache.set(node, spans);
return spans;
}
function collect(doc: ProseMirrorNode) {
const blocks = new Map<number, ProseMirrorNode>();
doc.descendants((node, pos) => {
if (node.type.name !== name) return !node.isTextblock;
blocks.set(pos, node);
return false;
});
return blocks;
}
function decorate(blocks: Map<number, ProseMirrorNode>, retained?: Set<number>) {
const decorations: Decoration[] = [];
for (const [pos, node] of blocks) {
if (retained?.has(pos)) continue;
for (const span of highlight(node)) {
decorations.push(Decoration.inline(pos + 1 + span.from, pos + 1 + span.to, { class: span.className }));
}
}
return decorations;
}
const plugin: Plugin<HighlightState> = new Plugin({
key: new PluginKey('cachedCodeBlockLowlight'),
state: {
init: (_, { doc }) => {
const blocks = collect(doc);
return { blocks, decorations: DecorationSet.create(doc, decorate(blocks)) };
},
apply(transaction, previous) {
// Cursor motion must not even walk the document.
if (!transaction.docChanged) return previous;
const blocks = collect(transaction.doc);
const retained = new Set<number>();
const removed: Decoration[] = [];
for (const [pos, node] of previous.blocks) {
const from = transaction.mapping.mapResult(pos, 1);
const to = transaction.mapping.mapResult(pos + node.nodeSize, -1);
if (!from.deleted && !to.deleted && to.pos - from.pos === node.nodeSize && blocks.get(from.pos) === node) {
retained.add(from.pos);
} else {
removed.push(...previous.decorations.find(pos + 1, pos + node.nodeSize - 1));
}
}
// Drop changed/removed blocks before mapping, including code converted to
// a paragraph where a markup-only step leaves its text positions intact.
const mapped = previous.decorations.remove(removed).map(transaction.mapping, transaction.doc);
return { blocks, decorations: mapped.add(transaction.doc, decorate(blocks, retained)) };
},
},
props: {
decorations(state) {
return plugin.getState(state)?.decorations;
},
},
});
return plugin;
}
export const CachedCodeBlockLowlight = CodeBlock.extend<CodeBlockOptions & { lowlight: CodeHighlighter | null }>({
addOptions() {
return { ...this.parent!(), lowlight: null };
},
addProseMirrorPlugins() {
if (!this.options.lowlight) throw new Error('Code block highlighting requires a lowlight instance');
return [
...(this.parent?.() ?? []),
createCodeBlockHighlightPlugin({ name: this.name, lowlight: this.options.lowlight, defaultLanguage: this.options.defaultLanguage }),
];
},
});
@@ -0,0 +1,49 @@
import { Extension } from '@tiptap/core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
const CODE_FENCE_PATTERN = /^(?:```|~~~)(?:[a-z]+)?$/;
function isInputRulesPlugin(plugin: Plugin) {
return 'isInputRules' in plugin.spec && plugin.spec.isInputRules === true;
}
export function createCodeBlockInputScrollPlugin() {
return new Plugin({
key: new PluginKey('codeBlockInputScroll'),
appendTransaction(transactions, oldState, newState) {
const inputRulesPlugin = oldState.plugins.find(isInputRulesPlugin);
const wasKeyboardInputRule =
inputRulesPlugin !== undefined &&
transactions.some((transaction) => {
const metadata: unknown = transaction.getMeta(inputRulesPlugin);
return (
typeof metadata === 'object' &&
metadata !== null &&
'transform' in metadata &&
metadata.transform === transaction &&
'text' in metadata &&
metadata.text === '\n'
);
});
const { selection } = oldState;
const wasFenceParagraph =
selection.empty &&
selection.$from.parent.type.name === 'paragraph' &&
CODE_FENCE_PATTERN.test(selection.$from.parent.textContent);
const isCodeBlock = newState.selection.$from.parent.type.name === 'codeBlock';
return wasKeyboardInputRule && wasFenceParagraph && isCodeBlock
? newState.tr.scrollIntoView()
: null;
},
});
}
export const CodeBlockInputScroll = Extension.create({
name: 'codeBlockInputScroll',
addProseMirrorPlugins() {
return [createCodeBlockInputScrollPlugin()];
},
});
+143
View File
@@ -0,0 +1,143 @@
import type { Mark, Node as ProseMirrorNode } from '@tiptap/pm/model';
type AssetSourceNormalizer = (source: string) => string;
type MarkdownMark = {
key: string;
priority: number;
open: string;
close: string;
};
const identityAssetSource: AssetSourceNormalizer = (source) => source;
function stringAttr(mark: Mark, name: string): string {
const value = mark.attrs?.[name];
return typeof value === 'string' ? value : '';
}
function markdownMark(mark: Mark, text: string): MarkdownMark | null {
switch (mark.type.name) {
case 'bold':
return { key: 'bold', priority: 10, open: '**', close: '**' };
case 'italic':
return { key: 'italic', priority: 20, open: '*', close: '*' };
case 'strike':
return { key: 'strike', priority: 30, open: '~~', close: '~~' };
case 'underline':
return { key: 'underline', priority: 40, open: '<u>', close: '</u>' };
case 'subscript':
return { key: 'subscript', priority: 50, open: '~', close: '~' };
case 'superscript':
return { key: 'superscript', priority: 60, open: '^', close: '^' };
case 'highlight': {
const color = stringAttr(mark, 'color');
return color
? {
key: `highlight:${color}`,
priority: 70,
open: `<mark data-color="${color}">`,
close: '</mark>',
}
: { key: 'highlight', priority: 70, open: '==', close: '==' };
}
case 'textStyle': {
const color = stringAttr(mark, 'color');
return color
? {
key: `textStyle:${color}`,
priority: 80,
open: `<span style="color: ${color}">`,
close: '</span>',
}
: null;
}
case 'code':
return { key: 'code', priority: 90, open: '`', close: '`' };
case 'link': {
const href = stringAttr(mark, 'href');
return {
key: `link:${href}`,
priority: 100,
open: '[',
close: `](${href})`,
};
}
case 'wikiLink': {
const title = stringAttr(mark, 'title') || text;
const aliased = mark.attrs?.aliased === true || title !== text;
return {
key: `wikiLink:${title}:${aliased}`,
priority: 110,
open: aliased ? `[[${title}|` : '[[',
close: ']]',
};
}
default:
return null;
}
}
function marksForText(node: ProseMirrorNode): MarkdownMark[] {
return node.marks
.map((mark) => markdownMark(mark, node.text || ''))
.filter((mark): mark is MarkdownMark => mark !== null)
.sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
}
function commonMarkCount(active: MarkdownMark[], next: MarkdownMark[]): number {
const length = Math.min(active.length, next.length);
let index = 0;
while (index < length && active[index].key === next[index].key) index += 1;
return index;
}
export function serializeInlineMarkdown(
node: ProseMirrorNode,
normalizeAssetSource: AssetSourceNormalizer = identityAssetSource,
): string {
let result = '';
let activeMarks: MarkdownMark[] = [];
const transitionMarks = (nextMarks: MarkdownMark[]) => {
const shared = commonMarkCount(activeMarks, nextMarks);
for (let index = activeMarks.length - 1; index >= shared; index -= 1) {
result += activeMarks[index].close;
}
for (let index = shared; index < nextMarks.length; index += 1) {
result += nextMarks[index].open;
}
activeMarks = nextMarks;
};
node.forEach((child, _offset, index) => {
if (child.isText) {
transitionMarks(marksForText(child));
let text = child.text || '';
if (index === 0) {
text = text.replace(/^[\t\u2003]+/, (whitespace) => '&emsp;'.repeat(whitespace.length));
}
result += text;
return;
}
transitionMarks([]);
if (child.type.name === 'image') {
const source = normalizeAssetSource(child.attrs.src || '');
if (!source) return;
const alt = child.attrs.alt || '';
const size = child.attrs['data-size'] || child.attrs.size || 'full';
const sizeSuffix = size && size !== 'full' ? `|size=${size}` : '';
if (result) result += '\n';
result += `![${alt}${sizeSuffix}](${source})`;
} else if (child.type.name === 'mathInline') {
result += `$${child.attrs.tex || ''}$`;
} else if (child.type.name === 'hardBreak') {
result += ' \n';
}
});
transitionMarks([]);
return result;
}
+27
View File
@@ -0,0 +1,27 @@
import type { Node as ProseMirrorNode, Schema } from '@tiptap/pm/model';
export type MixedListName = 'bulletList' | 'taskList';
export function convertListNode(
schema: Schema,
listNode: ProseMirrorNode,
targetListName: MixedListName,
): ProseMirrorNode | null {
if (
(listNode.type.name !== 'bulletList' && listNode.type.name !== 'taskList') ||
listNode.type.name === targetListName
) {
return null;
}
const targetListType = schema.nodes[targetListName];
const targetItemType = schema.nodes[targetListName === 'taskList' ? 'taskItem' : 'listItem'];
if (!targetListType || !targetItemType) return null;
const itemAttrs = targetListName === 'taskList' ? { checked: false } : null;
const convertedItems = listNode.content.content.map((item) =>
targetItemType.create(itemAttrs, item.content, item.marks)
);
return targetListType.create(null, convertedItems, listNode.marks);
}
+109
View File
@@ -0,0 +1,109 @@
import type { SearchTarget } from '../types';
import type { NoteSearchMatch } from './search';
import { stripTitleHeading } from './titleVisibility.ts';
function isTextBoundary(text: string, offset: number): boolean {
const previous = text.charCodeAt(offset - 1);
const next = text.charCodeAt(offset);
return !(previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff);
}
function isLineBoundary(text: string, offset: number): boolean {
return !(text.charCodeAt(offset - 1) === 13 && text.charCodeAt(offset) === 10);
}
function validMatch(text: string, match: NoteSearchMatch): boolean {
return Number.isInteger(match.from) && Number.isInteger(match.to)
&& match.from >= 0 && match.to > match.from && match.to <= text.length
&& isTextBoundary(text, match.from) && isTextBoundary(text, match.to);
}
function normalizeLines(text: string): string {
return text.includes('\r') ? text.replace(/\r\n?/g, '\n') : text;
}
function normalizedOffset(text: string, offset: number): number {
let removed = 0;
for (let i = text.indexOf('\r'); i >= 0 && i < offset; i = text.indexOf('\r', i + 1)) {
if (text.charCodeAt(i + 1) === 10 && i + 1 < offset) removed++;
}
return offset - removed;
}
// Compare the bounded anchor against the original string, retaining its coordinates.
function matchAnchorAt(
text: string, anchor: string, offset: number, start: number, end: number,
): NoteSearchMatch | null {
if (!isTextBoundary(text, offset) || !isLineBoundary(text, offset)) return null;
let cursor = offset;
let from = offset;
let to = offset;
for (let i = 0; i < anchor.length; i++) {
if (i === start) from = cursor;
if (i === end) to = cursor;
const character = text.charCodeAt(cursor);
if ((character === 13 ? 10 : character) !== anchor.charCodeAt(i)) return null;
cursor += character === 13 && text.charCodeAt(cursor + 1) === 10 ? 2 : 1;
}
if (end === anchor.length) to = cursor;
const match = { from, to };
return validMatch(text, match) && isTextBoundary(text, cursor) ? match : null;
}
/** Resolve an indexed anchor to UTF-16 offsets in the supplied, unmodified text. */
export function resolveSearchTarget(text: string, target: SearchTarget): NoteSearchMatch | null {
if (!Number.isInteger(target.start) || !Number.isInteger(target.end)
|| target.start < target.before.length || target.end <= target.start
|| target.end - target.start !== target.text.length
|| [target.before, target.text, target.after].some((part) => /[\ud800-\udfff]/u.test(part))) return null;
const anchor = target.before + target.text + target.after;
const anchorStart = target.start - target.before.length;
const recorded = { from: target.start, to: target.end };
if (validMatch(text, recorded) && text.startsWith(anchor, anchorStart)
&& isTextBoundary(text, anchorStart) && isTextBoundary(text, anchorStart + anchor.length)) {
return recorded;
}
// A boundary inside CRLF has no unique equivalent in an LF-only document.
const start = target.before.length;
const end = start + target.text.length;
if (!isLineBoundary(anchor, start) || !isLineBoundary(anchor, end)) return null;
const normalized = normalizeLines(anchor);
const matchStart = normalizedOffset(anchor, start);
const matchEnd = normalizedOffset(anchor, end);
const first = normalized.charCodeAt(0);
let found: NoteSearchMatch | null = null;
for (let offset = 0; offset < text.length; offset++) {
const character = text.charCodeAt(offset);
if ((character === 13 ? 10 : character) !== first) continue;
const candidate = matchAnchorAt(text, normalized, offset, matchStart, matchEnd);
if (!candidate) continue;
if (found) return null;
found = candidate;
}
return found;
}
/** Project a body range into the editor's LF-only, optionally title-hidden Markdown. */
export function visibleSearchTarget(
body: string, title: string | undefined, hideTitle: boolean, match: NoteSearchMatch,
): { markdown: string; match: NoteSearchMatch | null; hiddenTitle: boolean } {
const { markdown, removedRange } = stripTitleHeading(normalizeLines(body), title, hideTitle);
if (!validMatch(body, match) || !isLineBoundary(body, match.from) || !isLineBoundary(body, match.to)) {
return { markdown, match: null, hiddenTitle: false };
}
const visible = { from: normalizedOffset(body, match.from), to: normalizedOffset(body, match.to) };
if (removedRange) {
if (visible.from < removedRange.to && visible.to > removedRange.from) {
return { markdown, match: null, hiddenTitle: true };
}
if (visible.from >= removedRange.to) {
const removed = removedRange.to - removedRange.from;
visible.from -= removed;
visible.to -= removed;
}
}
return { markdown, match: visible, hiddenTitle: false };
}
+77
View File
@@ -0,0 +1,77 @@
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
export interface NoteSearchMatch { from: number; to: number }
export interface NoteSearchOptions { matchCase: boolean; wholeWord: boolean }
const wordCharacter = /[\p{L}\p{N}\p{M}\p{Pc}\u200c\u200d]/u;
function characterBefore(text: string, offset: number): string {
if (!offset) return '';
const last = text.charCodeAt(offset - 1);
return text.slice(offset - (last >= 0xdc00 && last <= 0xdfff && offset > 1 ? 2 : 1), offset);
}
function literalMatcher(query: string, options: NoteSearchOptions) {
// Unicode regexp case folding preserves original UTF-16 offsets, unlike lowercasing
// the document (for example, U+0130 lowercases to two code points).
const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), options.matchCase ? 'gu' : 'giu');
return (text: string, base: number, results: NoteSearchMatch[]) => {
pattern.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text))) {
const from = match.index;
const to = from + match[0].length;
if (!options.wholeWord || (
!wordCharacter.test(characterBefore(text, from)) &&
!wordCharacter.test(to < text.length ? String.fromCodePoint(text.codePointAt(to)!) : '')
)) results.push({ from: base + from, to: base + to });
// Keep overlapping occurrences, but never start inside a surrogate pair.
pattern.lastIndex = from + (text.codePointAt(from)! > 0xffff ? 2 : 1);
}
};
}
export function findSourceMatches(text: string, query: string, options: NoteSearchOptions): NoteSearchMatch[] {
const results: NoteSearchMatch[] = [];
if (query) literalMatcher(query, options)(text, 0, results);
return results;
}
export function findDocumentMatches(doc: ProseMirrorNode, query: string, options: NoteSearchOptions): NoteSearchMatch[] {
const results: NoteSearchMatch[] = [];
if (!query) return results;
const match = literalMatcher(query, options);
doc.descendants((block, pos) => {
if (!block.isTextblock) return;
let text = '';
let start = 0;
const flush = () => {
if (text) match(text, start, results);
text = '';
};
block.forEach((child, offset) => {
if (!child.isText) {
// Hard breaks, images and inline atoms are real boundaries, not marks.
flush();
return;
}
if (!text) start = pos + 1 + offset;
text += child.text;
});
flush();
return false;
});
return results;
}
export function closestSearchMatch(results: NoteSearchMatch[], anchor: number): number {
if (!results.length) return 0;
let lo = 0;
let hi = results.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (results[mid].from < anchor) lo = mid + 1; else hi = mid;
}
return Math.min(lo, results.length - 1);
}
+174
View File
@@ -0,0 +1,174 @@
import { Annotation, Compartment, EditorSelection, EditorState, StateEffect, StateField, Transaction, type ChangeDesc, type Extension, type StateCommand, type TransactionSpec } from '@codemirror/state';
import { Decoration, EditorView, drawSelection, keymap, lineNumbers, placeholder, type DecorationSet } from '@codemirror/view';
import { defaultKeymap, history, historyKeymap, indentWithTab, redo, undo } from '@codemirror/commands';
import { HighlightStyle, indentUnit, syntaxHighlighting } from '@codemirror/language';
import { markdown } from '@codemirror/lang-markdown';
import { tags } from '@lezer/highlight';
import { getSelectionPair } from '../selectionPairs.ts';
import type { NoteSearchMatch } from '../search';
const representationChange = Annotation.define<boolean>();
const activeMatch = StateEffect.define<NoteSearchMatch | null>();
export const sourceSearchDecoration = StateField.define<DecorationSet>({
create: () => Decoration.none,
update(value, transaction) {
value = value.map(transaction.changes);
for (const effect of transaction.effects) {
if (effect.is(activeMatch)) {
const match = effect.value;
value = match && match.to > match.from
? Decoration.set([Decoration.mark({ class: 'source-search-current' }).range(match.from, match.to)])
: Decoration.none;
}
}
return value;
},
provide: (field) => EditorView.decorations.from(field),
});
/** Insert just the wrappers, preserving the selected immutable text and its direction. */
export function wrapSourceSelection(state: EditorState, key: string): TransactionSpec | null {
const close = getSelectionPair(key);
if (state.readOnly || !close || state.selection.main.empty) return null;
return {
...state.changeByRange((range) => range.empty ? { range } : ({
changes: [{ from: range.from, insert: key }, { from: range.to, insert: close }],
range: EditorSelection.range(range.anchor + key.length, range.head + key.length),
})),
userEvent: 'input.type',
scrollIntoView: true,
};
}
export const sourceHardBreak: StateCommand = ({ state, dispatch }) => {
if (state.readOnly) return false;
dispatch(state.update(state.replaceSelection(' \n'), { userEvent: 'input.type', scrollIntoView: true }));
return true;
};
const sourceTheme = EditorView.theme({
'&': { height: '100%', color: 'var(--text-primary)', backgroundColor: 'transparent', fontSize: 'var(--editor-font-size, 14px)' },
'&.cm-focused': { outline: 'none' },
'.cm-scroller': { overflow: 'auto', fontFamily: "var(--editor-font-family, 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace)", lineHeight: 'var(--editor-line-height, 1.3)' },
'.cm-content': { padding: '0 0 var(--editor-scroll-past-end, 65vh)', caretColor: 'var(--text-primary)' },
'.cm-line': { padding: '0 4px' },
'.cm-gutters': { backgroundColor: 'var(--bg-primary)', color: 'var(--text-secondary)', border: 'none' },
'.cm-cursor': { borderLeftColor: 'var(--text-primary)' },
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': { backgroundColor: 'color-mix(in srgb, var(--accent) 25%, transparent)' },
'.source-search-current': { backgroundColor: 'color-mix(in srgb, var(--accent) 40%, transparent)', outline: '1px solid var(--accent)' },
'.cm-placeholder': { color: 'var(--text-secondary)' },
});
const sourceSyntax = HighlightStyle.define([
{ tag: [tags.heading, tags.strong], color: 'var(--accent)' },
{ tag: [tags.link, tags.url, tags.emphasis], color: 'color-mix(in srgb, var(--accent) 78%, var(--text-primary))' },
{ tag: [tags.processingInstruction, tags.list, tags.meta], color: 'var(--success)' },
{ tag: [tags.quote, tags.monospace, tags.comment], color: 'var(--text-secondary)' },
]);
export class SourceController {
private configuration = new Compartment();
private readOnly = false;
private numbers = false;
private extensions: Extension[];
private onChange: (changes: ChangeDesc, edited: boolean) => void;
state: EditorState;
view: EditorView | null = null;
constructor(onChange: (changes: ChangeDesc, edited: boolean) => void = () => {}, events: {
paste?: (event: ClipboardEvent) => boolean;
drop?: (event: DragEvent) => boolean;
} = {}) {
this.onChange = onChange;
this.extensions = [
markdown(), history(), drawSelection(), sourceSearchDecoration, sourceTheme,
syntaxHighlighting(sourceSyntax), indentUnit.of('\t'), EditorState.tabSize.of(4),
placeholder('Start writing...'),
EditorView.contentAttributes.of({ 'aria-label': 'Markdown source', tabindex: '0', spellcheck: 'false', autocapitalize: 'off' }),
keymap.of([{ key: 'Shift-Enter', run: sourceHardBreak }, indentWithTab, ...historyKeymap, ...defaultKeymap]),
EditorView.domEventHandlers({
keydown: (event, view) => {
if (event.ctrlKey || event.metaKey || event.altKey || event.isComposing) return false;
const transaction = wrapSourceSelection(view.state, event.key);
if (!transaction) return false;
view.dispatch(transaction);
return true;
},
paste: (event, view) => !view.state.readOnly && (events.paste?.(event) ?? false),
drop: (event, view) => !view.state.readOnly && (events.drop?.(event) ?? false),
}),
this.configuration.of(this.settings()),
];
this.state = EditorState.create({ extensions: this.extensions });
}
private settings(): Extension[] {
return [EditorState.readOnly.of(this.readOnly), EditorView.editable.of(!this.readOnly),
this.numbers ? lineNumbers() : EditorView.lineWrapping];
}
configure(readOnly: boolean, numbers: boolean): void {
if (readOnly === this.readOnly && numbers === this.numbers) return;
this.readOnly = readOnly;
this.numbers = numbers;
this.dispatch({ effects: this.configuration.reconfigure(this.settings()) });
}
attach(parent: HTMLElement): () => void {
const view = new EditorView({
parent, state: this.state,
dispatchTransactions: (transactions, current) => {
current.update(transactions);
this.state = current.state;
for (const transaction of transactions) this.changed(transaction);
},
});
this.view = view;
return () => {
if (this.view === view) this.view = null;
view.destroy();
};
}
private changed(transaction: Transaction): void {
if (transaction.docChanged) this.onChange(transaction.changes, !transaction.annotation(representationChange));
}
dispatch(spec: TransactionSpec | Transaction): void {
const transaction = spec instanceof Transaction ? spec : this.state.update(spec);
if (this.view) this.view.dispatch(transaction);
else {
this.state = transaction.state;
this.changed(transaction);
}
}
/** New note/mode conversion: drop undo history, never mark dirty or focus. */
load(content: string): void {
this.state = EditorState.create({ doc: content, extensions: this.extensions });
// A fresh state starts with the original compartment; retain live settings.
this.state = this.state.update({ effects: this.configuration.reconfigure(this.settings()) }).state;
this.view?.setState(this.state);
}
replace(content: string, from = 0, to = this.state.doc.length, representationOnly = false): void {
this.dispatch({ changes: { from, to, insert: content },
annotations: representationOnly ? [representationChange.of(true), Transaction.addToHistory.of(false)] : undefined,
userEvent: representationOnly ? undefined : 'input' });
}
select(from: number, to = from, scroll = false): void {
const length = this.state.doc.length;
this.dispatch({ selection: { anchor: Math.min(from, length), head: Math.min(to, length) },
effects: scroll ? EditorView.scrollIntoView(Math.min(from, length), { y: 'center' }) : undefined });
}
highlight(match: NoteSearchMatch | null, reveal = false): void {
this.dispatch({ effects: activeMatch.of(match),
...(match && reveal ? { selection: { anchor: match.from, head: match.to },
effects: [activeMatch.of(match), EditorView.scrollIntoView(match.from, { y: 'center' })] } : {}) });
}
focus(): void { this.view?.focus(); }
undo(): boolean { return undo({ state: this.state, dispatch: (tr) => this.dispatch(tr) }); }
redo(): boolean { return redo({ state: this.state, dispatch: (tr) => this.dispatch(tr) }); }
}
-14
View File
@@ -1,14 +0,0 @@
import { getSelectionPair } from '../selectionPairs';
// Pure source-mode helper: computes the wrapped textarea value and preserved
// inner selection so Svelte event handlers stay as glue code.
export function wrapTextareaSelection(value: string, start: number, end: number, key: string) {
const close = getSelectionPair(key);
if (!close || start === end) return null;
return {
value: value.slice(0, start) + key + value.slice(start, end) + close + value.slice(end),
selectionStart: start + key.length,
selectionEnd: end + key.length,
};
}
+60
View File
@@ -0,0 +1,60 @@
export type HiddenTitleHeading = {
headingPrefix: string;
title: string;
};
type TitleHeadingResult = {
markdown: string;
hiddenTitle: HiddenTitleHeading | null;
removedRange?: { from: number; to: number };
};
function normalizeTitle(value: string): string {
return value.trim().toLowerCase().replace(/[\s\-_\u2014]+/g, ' ');
}
export function stripTitleHeading(
markdown: string,
title: string | undefined,
hideTitle: boolean,
): TitleHeadingResult {
if (!hideTitle || !title) return { markdown, hiddenTitle: null };
const lines = markdown.split('\n');
let lineStart = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === '') {
lineStart += lines[i].length + 1;
continue;
}
const match = line.match(/^(#{1,6})\s+(.+)$/);
if (match && normalizeTitle(match[2]) === normalizeTitle(title)) {
const hiddenTitle = { headingPrefix: match[1], title: title.trim() };
const count = i + 1 < lines.length && lines[i + 1].trim() === '' ? 2 : 1;
const reachesEnd = i + count === lines.length;
const removedRange = {
from: reachesEnd ? Math.max(0, lineStart - 1) : lineStart,
to: reachesEnd ? markdown.length
: lineStart + lines[i].length + 1 + (count === 2 ? lines[i + 1].length + 1 : 0),
};
return {
markdown: markdown.slice(0, removedRange.from) + markdown.slice(removedRange.to),
hiddenTitle,
removedRange,
};
}
break;
}
return { markdown, hiddenTitle: null };
}
export function restoreTitleHeading(
markdown: string,
hiddenTitle: HiddenTitleHeading | null,
): string {
if (!hiddenTitle) return markdown;
return `${hiddenTitle.headingPrefix} ${hiddenTitle.title}\n\n${markdown}`;
}
+107
View File
@@ -0,0 +1,107 @@
import type { ToolbarLayout } from '../types';
export const toolbarLabels = {
insert: 'Insert',
heading: 'Heading',
bold: 'Bold',
italic: 'Italic',
underline: 'Underline',
strike: 'Strikethrough',
'text-color': 'Text color',
link: 'Link',
'bullet-list': 'Bullet list',
'ordered-list': 'Numbered list',
'task-list': 'Task list',
undo: 'Undo',
redo: 'Redo',
'inline-code': 'Inline code',
'code-block': 'Code block',
quote: 'Quote',
details: 'Collapsible section',
callout: 'Callout',
table: 'Table',
'horizontal-rule': 'Horizontal rule',
highlight: 'Highlight',
subscript: 'Subscript',
superscript: 'Superscript',
alignment: 'Text alignment',
indent: 'Indent',
outdent: 'Outdent',
'date-time': 'Date and time',
'ai-actions': 'AI actions',
} as const;
export type ToolbarButtonId = keyof typeof toolbarLabels;
export type ToolbarArea = 'main' | 'more';
export type ResolvedToolbarLayout = Record<ToolbarArea, ToolbarButtonId[]>;
const desktopGroups: readonly (readonly ToolbarButtonId[])[] = [
['insert'], ['heading'], ['bold', 'italic', 'underline', 'strike', 'text-color'],
['link'], ['bullet-list', 'ordered-list', 'task-list'], ['undo', 'redo'],
['inline-code', 'code-block', 'quote', 'details', 'callout', 'table', 'horizontal-rule'],
['highlight', 'subscript', 'superscript'], ['alignment'], ['indent', 'outdent'],
];
const mobileGroups: readonly (readonly ToolbarButtonId[])[] = [
['insert'], ['heading'], ['bold', 'italic', 'underline', 'strike'], ['link'],
['bullet-list', 'ordered-list', 'task-list', 'indent', 'outdent'],
['highlight'], ['date-time'], ['undo', 'redo'], ['ai-actions'],
];
export function toolbarGroups(mobile: boolean, hasAi: boolean): ToolbarButtonId[][] {
return (mobile ? mobileGroups : desktopGroups)
.map((group) => group.filter((id) => id !== 'ai-actions' || hasAi))
.filter((group) => group.length > 0);
}
export function resolveToolbarLayout(
layout: ToolbarLayout | null | undefined, mobile: boolean, hasAi: boolean,
): ResolvedToolbarLayout {
const available = toolbarGroups(mobile, hasAi).flat();
if (mobile || !layout) return { main: available, more: [] };
const allowed = new Set<string>(available);
const seen = new Set<string>();
const take = (ids: readonly string[]) => ids.filter((id): id is ToolbarButtonId => {
if (!allowed.has(id) || seen.has(id)) return false;
seen.add(id);
return true;
});
const main = take(layout.main);
const more = take(layout.more);
// Newly added controls stay reachable without changing the user's saved order.
main.push(...available.filter((id) => !seen.has(id)));
return { main, more };
}
export function groupToolbarButtons(ids: readonly ToolbarButtonId[], mobile: boolean): ToolbarButtonId[][] {
const defaults = mobile ? mobileGroups : desktopGroups;
const groups: ToolbarButtonId[][] = [];
let previous = -1;
for (const id of ids) {
const group = defaults.findIndex((items) => items.includes(id));
if (group !== previous || groups.length === 0) groups.push([]);
groups[groups.length - 1].push(id);
previous = group;
}
return groups;
}
/** Index is an insertion gap in the destination list before removing the dragged item. */
export function moveToolbarButton(
layout: ResolvedToolbarLayout, id: ToolbarButtonId, area: ToolbarArea, index: number,
): ResolvedToolbarLayout {
const from = layout.main.includes(id) ? 'main' : 'more';
const oldIndex = layout[from].indexOf(id);
if (oldIndex < 0) return layout;
const gap = Math.max(0, Math.min(index, layout[area].length));
const target = gap - (from === area && oldIndex < gap ? 1 : 0);
if (from === area && target === oldIndex) return layout;
const next = { main: layout.main.filter((item) => item !== id), more: layout.more.filter((item) => item !== id) };
next[area].splice(target, 0, id);
return next;
}
export function toolbarLayoutPreference(layout: ResolvedToolbarLayout): ToolbarLayout | null {
const defaults = desktopGroups.flat();
return layout.more.length === 0 && layout.main.length === defaults.length
&& layout.main.every((id, index) => id === defaults[index]) ? null : layout;
}
+22
View File
@@ -0,0 +1,22 @@
import { TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state';
export type WikiLinkAttributes = {
title: string;
path: string;
aliased: boolean;
};
export function replaceWithWikiLink(
state: EditorState,
from: number,
to: number,
text: string,
attrs: WikiLinkAttributes
): Transaction {
const wikiLinkMark = state.schema.marks.wikiLink.create(attrs);
const textNode = state.schema.text(text, [wikiLinkMark]);
const transaction = state.tr.replaceWith(from, to, textNode);
transaction.setSelection(TextSelection.create(transaction.doc, from + text.length));
transaction.setStoredMarks([]);
return transaction;
}
+84 -22
View File
@@ -1,5 +1,6 @@
import { writable, derived, get } from "svelte/store"; import { writable, derived, get } from "svelte/store";
import { isMobile } from "$lib/platform"; import { isMobile } from "$lib/platform";
import { compareNaturalNames } from "$lib/utils/natural-sort";
import type { import type {
AppConfig, AppConfig,
CustomTheme, CustomTheme,
@@ -10,6 +11,7 @@ import type {
VaultState, VaultState,
ViewMode, ViewMode,
SortMode, SortMode,
TagStyle,
} from "$lib/types"; } from "$lib/types";
// App state // App state
@@ -46,6 +48,7 @@ export const showSettings = writable(false);
export const settingsTab = writable<string | null>(null); export const settingsTab = writable<string | null>(null);
export const showInfo = writable(false); export const showInfo = writable(false);
export const notebookIcons = writable<Record<string, string>>({}); export const notebookIcons = writable<Record<string, string>>({});
export const tagStyles = writable<Record<string, TagStyle>>({});
export const quickAccessPaths = writable<string[]>([]); export const quickAccessPaths = writable<string[]>([]);
export const collapsedNotebooks = writable<string[]>([]); export const collapsedNotebooks = writable<string[]>([]);
@@ -89,6 +92,29 @@ export const readOnly = writable(false);
export const theme = writable<string>("system"); export const theme = writable<string>("system");
export const customThemes = derived(appConfig, ($c): CustomTheme[] => $c?.custom_themes ?? []); export const customThemes = derived(appConfig, ($c): CustomTheme[] => $c?.custom_themes ?? []);
// Whether the OS is currently in dark mode. Held in a store (rather than read at each call site)
// so the theme re-resolves when the user flips appearance while the app is open.
const darkQuery =
typeof window !== "undefined" ? window.matchMedia("(prefers-color-scheme: dark)") : null;
export const systemPrefersDark = writable<boolean>(darkQuery?.matches ?? false);
darkQuery?.addEventListener("change", (e) => systemPrefersDark.set(e.matches));
// The theme to actually render: "system" resolves to the configured light/dark pair, everything
// else passes through. Falls back to the plain schemes when no pair is configured yet.
export const resolvedTheme = derived(
[theme, appConfig, systemPrefersDark],
([$theme, $config, $prefersDark]): string => {
if ($theme !== "system") return $theme;
const fallback = $prefersDark ? "dark" : "light";
const paired = $prefersDark ? $config?.system_dark_theme : $config?.system_light_theme;
if (!paired) return fallback;
if (paired.startsWith("custom-") && !$config?.custom_themes.some((item) => item.id === paired)) {
return fallback;
}
return paired;
},
);
// Sync (WebDAV) - global status so the top-bar button reflects any sync, // Sync (WebDAV) - global status so the top-bar button reflects any sync,
// whoever triggered it (manual button, settings, interval, on-change). // whoever triggered it (manual button, settings, interval, on-change).
export const syncState = writable<{ running: boolean; error: string | null }>({ export const syncState = writable<{ running: boolean; error: string | null }>({
@@ -166,13 +192,33 @@ function createNavHistory() {
const store = writable<NavHistoryState>({ stack: [], index: -1, skipping: false }); const store = writable<NavHistoryState>({ stack: [], index: -1, skipping: false });
return { return {
subscribe: store.subscribe, subscribe: store.subscribe,
clear() {
store.set({ stack: [], index: -1, skipping: false });
},
push(path: string) { push(path: string) {
store.update(s => { store.update(s => {
if (s.skipping) return { ...s, skipping: false }; if (s.skipping) return { ...s, skipping: false };
if (s.stack[s.index] === path) return s;
const trimmed = s.stack.slice(0, s.index + 1); const trimmed = s.stack.slice(0, s.index + 1);
return { stack: [...trimmed, path], index: trimmed.length, skipping: false }; return { stack: [...trimmed, path], index: trimmed.length, skipping: false };
}); });
}, },
remap(oldPrefix: string, newPrefix: string) {
const oldRoot = oldPrefix.replace(/\\/g, '/').replace(/\/+$/, '');
const newRoot = newPrefix.replace(/[\\/]+$/, '');
const insensitive = /^[A-Za-z]:\//.test(oldRoot) || oldRoot.startsWith('//');
const matchRoot = insensitive ? oldRoot.toLowerCase() : oldRoot;
store.update(s => ({
...s,
stack: s.stack.map(path => {
const normalized = path.replace(/\\/g, '/');
const candidate = insensitive ? normalized.toLowerCase() : normalized;
return candidate === matchRoot || candidate.startsWith(`${matchRoot}/`)
? newRoot + path.slice(oldRoot.length)
: path;
}),
}));
},
go(direction: -1 | 1): string | null { go(direction: -1 | 1): string | null {
let target: string | null = null; let target: string | null = null;
store.update(s => { store.update(s => {
@@ -189,6 +235,34 @@ export const navHistory = createNavHistory();
export const canGoBack = derived(navHistory, $h => $h.index > 0); export const canGoBack = derived(navHistory, $h => $h.index > 0);
export const canGoForward = derived(navHistory, $h => $h.index < $h.stack.length - 1); export const canGoForward = derived(navHistory, $h => $h.index < $h.stack.length - 1);
let dataVaultPath: string | null = null;
/** Never expose the previous vault's editable note while a new vault loads. */
export function activateVaultData(vaultPath: string | null): void {
if (dataVaultPath === vaultPath) return;
dataVaultPath = vaultPath;
activeNote.set(null);
activeNotePath.set(null);
activeNotebook.set(null);
activeTag.set(null);
viewerNote.set(null);
editorDirty.set(false);
notes.set([]);
notebooks.set([]);
tags.set([]);
rootNoteCount.set(0);
quickAccessPaths.set([]);
notebookIcons.set({});
tagStyles.set({});
collapsedNotebooks.set([]);
notebookOrder.set({});
noteOrder.set({});
viewMode.set("all");
sortMode.set("modified");
groupNotesByDate.set(false);
navHistory.clear();
}
// Derived // Derived
export const sortedNotes = derived( export const sortedNotes = derived(
[notes, sortMode, viewMode, noteOrder], [notes, sortMode, viewMode, noteOrder],
@@ -200,35 +274,23 @@ export const sortedNotes = derived(
const pinned = $notes.filter((n) => n.meta.pinned); const pinned = $notes.filter((n) => n.meta.pinned);
const unpinned = $notes.filter((n) => !n.meta.pinned); const unpinned = $notes.filter((n) => !n.meta.pinned);
const dateField = $sortMode === "title" || ($sortMode === "custom" && customSortable)
? null
: $sortMode === "created" ? "created" : "modified";
const timestamps = dateField ? new Map<NoteEntry, number>() : null;
if (dateField && timestamps) {
for (const note of $notes) timestamps.set(note, Date.parse(note.meta[dateField]));
}
const sortFn = (a: NoteEntry, b: NoteEntry) => { const sortFn = (a: NoteEntry, b: NoteEntry) => {
switch ($sortMode) { if (timestamps) return timestamps.get(b)! - timestamps.get(a)!;
case "custom": { if ($sortMode === "custom") {
if (!customSortable) {
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
const oa = $noteOrder[a.path] ?? Number.MAX_SAFE_INTEGER; const oa = $noteOrder[a.path] ?? Number.MAX_SAFE_INTEGER;
const ob = $noteOrder[b.path] ?? Number.MAX_SAFE_INTEGER; const ob = $noteOrder[b.path] ?? Number.MAX_SAFE_INTEGER;
if (oa !== ob) return oa - ob; if (oa !== ob) return oa - ob;
return a.meta.title.localeCompare(b.meta.title); return a.meta.title.localeCompare(b.meta.title);
} }
case "title": return compareNaturalNames(a.meta.title, b.meta.title);
return a.meta.title.localeCompare(b.meta.title);
case "created":
return (
new Date(b.meta.created).getTime() -
new Date(a.meta.created).getTime()
);
case "modified":
default:
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
}; };
return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)]; return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)];
+55 -1
View File
@@ -34,6 +34,16 @@ export interface NotebookEntry {
note_count: number; note_count: number;
} }
export interface TagStyle {
icon?: string | null;
color?: string | null;
}
export type TagStyleChange =
| { kind: "icon"; value: string | null }
| { kind: "color"; value: string | null }
| { kind: "reset" };
export interface NoteContent { export interface NoteContent {
path: string; path: string;
meta: NoteMeta; meta: NoteMeta;
@@ -54,6 +64,12 @@ export interface VaultConfig {
sync_on_change?: boolean; sync_on_change?: boolean;
sync_interval_minutes?: number; sync_interval_minutes?: number;
last_sync_time?: string | null; last_sync_time?: string | null;
last_backup_time?: string | null;
}
export interface PendingOpenFile {
id: number;
path: string;
} }
export interface ExternalVaultResult { export interface ExternalVaultResult {
@@ -81,19 +97,31 @@ export interface CustomTheme {
colors: CustomThemeColors; colors: CustomThemeColors;
} }
export type StartupView = "all" | "quickaccess" | "tasks" | "daily";
export interface ToolbarLayout {
main: string[];
more: string[];
}
export interface AppConfig { export interface AppConfig {
vaults: VaultConfig[]; vaults: VaultConfig[];
active_vault: string | null; active_vault: string | null;
active_bookmark_id?: string | null; active_bookmark_id?: string | null;
theme: string; theme: string;
system_light_theme: string;
system_dark_theme: string;
accent_color: string | null; accent_color: string | null;
font_size: number | null; font_size: number | null;
scroll_to_change_font_size: boolean;
toolbar_layout: ToolbarLayout | null;
font_family: string | null; font_family: string | null;
line_height: number | null; line_height: number | null;
ui_scale: number | null; ui_scale: number | null;
content_width: number | null; content_width: number | null;
compact_notes: boolean; compact_notes: boolean;
show_note_dates: boolean; show_note_dates: boolean;
show_note_switcher: boolean;
time_format: string; time_format: string;
week_start: string; week_start: string;
daily_title_format: string; daily_title_format: string;
@@ -114,7 +142,6 @@ export interface AppConfig {
backup_frequency: string; backup_frequency: string;
backup_max_count: number; backup_max_count: number;
backup_location: string | null; backup_location: string | null;
last_backup_time: string | null;
backup_include_attachments: boolean; backup_include_attachments: boolean;
max_versions_per_note: number; max_versions_per_note: number;
ai_provider: string | null; ai_provider: string | null;
@@ -127,9 +154,11 @@ export interface AppConfig {
ai_model: string; ai_model: string;
ai_writing_style: string | null; ai_writing_style: string | null;
default_view_mode: boolean; default_view_mode: boolean;
new_notes_in_source_mode: boolean;
show_tray_icon: boolean; show_tray_icon: boolean;
close_to_tray: boolean; close_to_tray: boolean;
enable_wiki_links: boolean; enable_wiki_links: boolean;
startup_view: StartupView;
restore_last_session: boolean; restore_last_session: boolean;
sync_provider: string | null; sync_provider: string | null;
webdav_url: string | null; webdav_url: string | null;
@@ -164,16 +193,40 @@ export interface VaultState {
tasks_sort?: string; tasks_sort?: string;
} }
export interface SearchMatch {
start: number;
end: number;
}
export interface SearchTarget {
field: 'body' | 'title' | 'tags';
start: number;
end: number;
text: string;
before: string;
after: string;
}
export interface SearchResult { export interface SearchResult {
path: string; path: string;
title: string; title: string;
snippet: string; snippet: string;
score: number; score: number;
title_matches: SearchMatch[];
snippet_matches: SearchMatch[];
match_target: SearchTarget | null;
}
export interface SearchPage {
results: SearchResult[];
total: number;
} }
export interface FileEvent { export interface FileEvent {
vault_path: string;
event_type: string; event_type: string;
path: string; path: string;
note?: NoteEntry | null;
} }
export interface ImportResult { export interface ImportResult {
@@ -205,6 +258,7 @@ export interface VersionEntry {
} }
export interface AiStreamEvent { export interface AiStreamEvent {
request_id: string;
event_type: string; event_type: string;
text: string | null; text: string | null;
error: string | null; error: string | null;
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { AppearanceMutations } from './appearance-mutations.ts';
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
test('appearance reads started before or during a write cannot restore an old snapshot', async () => {
const changes = new AppearanceMutations();
const before = changes.snapshot('A');
const gate = deferred();
const write = changes.run('A', 'notebook', () => true, () => gate.promise, () => {});
const during = changes.snapshot('A');
assert.equal(changes.acceptsSnapshot('A', before), false);
assert.equal(changes.acceptsSnapshot('A', during), false);
assert.equal(changes.acceptsSnapshot('B', changes.snapshot('B')), true);
gate.resolve();
await write;
assert.equal(changes.acceptsSnapshot('A', before), false);
assert.equal(changes.acceptsSnapshot('A', during), false);
assert.equal(changes.acceptsSnapshot('A', changes.snapshot('A')), true);
});
test('an upload and later field patch commit in order without losing either field', async () => {
const changes = new AppearanceMutations();
const gate = deferred();
let persisted = { color: '#abcdef' };
let visible;
const upload = changes.run('A', 'work', () => true, async () => {
const original = persisted;
await gate.promise;
persisted = { ...original, icon: 'uploaded.svg' };
return persisted;
}, next => { visible = next; });
const color = changes.run('A', 'work', () => true, async () => {
persisted = { ...persisted, color: '#123456' };
return persisted;
}, next => { visible = next; });
gate.resolve();
await Promise.all([upload, color]);
assert.deepEqual(persisted, { icon: 'uploaded.svg', color: '#123456' });
assert.deepEqual(visible, persisted);
});
test('a superseded queued choice cannot write over the newer choice', async () => {
const changes = new AppearanceMutations();
const gate = deferred();
const blocker = changes.run('A', 'work', () => true, () => gate.promise, () => {});
const oldChoice = changes.choose('A', 'work:icon');
let persisted = 'original';
const old = changes.run('A', 'work', oldChoice, async () => { persisted = 'old'; }, () => {});
const latest = changes.choose('A', 'work:icon');
const next = changes.run('A', 'work', latest, async () => { persisted = 'new'; }, () => {});
gate.resolve();
await Promise.all([blocker, old, next]);
assert.equal(persisted, 'new');
assert.equal(oldChoice(), false);
assert.equal(latest(), true);
});
test('a failed later choice does not hide the successful earlier commit or poison the queue', async () => {
const changes = new AppearanceMutations();
let visible = 'original';
const first = changes.run('A', 'work', () => true, async () => 'uploaded.svg', value => { visible = value; });
const failed = changes.run('A', 'work', () => true, async () => { throw new Error('disk full'); }, value => { visible = value; });
await first;
await assert.rejects(failed, /disk full/);
assert.equal(visible, 'uploaded.svg');
await changes.run('A', 'work', () => true, async () => 'builtin:star', value => { visible = value; });
assert.equal(visible, 'builtin:star');
assert.equal(changes.acceptsSnapshot('A', changes.snapshot('A')), true);
});
test('different vaults do not share choice cancellation or a write queue', async () => {
const changes = new AppearanceMutations();
const aChoice = changes.choose('A', 'work');
changes.choose('B', 'work');
const gate = deferred();
const a = changes.run('A', 'work', aChoice, () => gate.promise, () => {});
let bSaved = false;
await changes.run('B', 'work', () => true, async () => { bSaved = true; }, () => {});
assert.equal(aChoice(), true);
assert.equal(bSaved, true);
gate.resolve();
await a;
});
+67
View File
@@ -0,0 +1,67 @@
interface VaultChanges {
revision: number;
pending: number;
choices: Map<string, number>;
tails: Map<string, Promise<void>>;
}
/** Keep old refresh snapshots and late choices from replacing committed appearances. */
export class AppearanceMutations {
private vaults = new Map<string, VaultChanges>();
private state(vault: string): VaultChanges {
let state = this.vaults.get(vault);
if (!state) {
state = { revision: 0, pending: 0, choices: new Map(), tails: new Map() };
this.vaults.set(vault, state);
}
return state;
}
snapshot(vault: string): number {
return this.state(vault).revision;
}
acceptsSnapshot(vault: string, revision: number): boolean {
const state = this.state(vault);
return state.pending === 0 && state.revision === revision;
}
choose(vault: string, key: string): () => boolean {
const choices = this.state(vault).choices;
const choice = (choices.get(key) ?? 0) + 1;
choices.set(key, choice);
return () => choices.get(key) === choice;
}
async run<T>(
vault: string,
key: string,
canRun: () => boolean,
operation: () => Promise<T>,
publish: (result: T) => void,
): Promise<void> {
const state = this.state(vault);
state.revision++;
state.pending++;
const previous = state.tails.get(key) ?? Promise.resolve();
const work = previous.catch(() => {}).then(async () => {
if (!canRun()) return;
const result = await operation();
// Publish committed state in queue order, including when a later choice
// fails or a later file dialog is cancelled.
publish(result);
});
state.tails.set(key, work);
try {
await work;
} finally {
state.pending--;
state.revision++;
if (state.tails.get(key) === work) state.tails.delete(key);
}
}
}
export const notebookAppearance = new AppearanceMutations();
export const tagAppearance = new AppearanceMutations();
+35
View File
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const { getWheelFontSizeAction } = await import(
new URL('./editor-zoom.ts', import.meta.url)
);
test('blocks modified wheel input when scroll font sizing is disabled', () => {
assert.equal(
getWheelFontSizeAction({ ctrlKey: false, metaKey: true, deltaY: -1 }, false),
'block'
);
assert.equal(
getWheelFontSizeAction({ ctrlKey: true, metaKey: false, deltaY: 1 }, false),
'block'
);
});
test('changes font size from modified wheel input when enabled', () => {
assert.equal(
getWheelFontSizeAction({ ctrlKey: false, metaKey: true, deltaY: -1 }, true),
'increase'
);
assert.equal(
getWheelFontSizeAction({ ctrlKey: true, metaKey: false, deltaY: 1 }, true),
'decrease'
);
});
test('ignores unmodified wheel input', () => {
assert.equal(
getWheelFontSizeAction({ ctrlKey: false, metaKey: false, deltaY: -1 }, false),
'ignore'
);
});
+16
View File
@@ -0,0 +1,16 @@
export type WheelFontSizeAction = 'ignore' | 'block' | 'increase' | 'decrease';
interface WheelModifierInput {
ctrlKey: boolean;
metaKey: boolean;
deltaY: number;
}
export function getWheelFontSizeAction(
event: WheelModifierInput,
scrollToChangeFontSize: boolean,
): WheelFontSizeAction {
if (!event.ctrlKey && !event.metaKey) return 'ignore';
if (!scrollToChangeFontSize) return 'block';
return event.deltaY < 0 ? 'increase' : 'decrease';
}
+110
View File
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyGraphRepulsion } from './graph-layout.ts';
const node = (x, y) => ({ x, y, vx: 0, vy: 0 });
function run(nodes) {
for (const _ of applyGraphRepulsion(nodes)) { /* finish one physics step */ }
}
// Independent pairwise reference: an optimization must not change the force law.
function reference(nodes) {
return nodes.map((a, index) => {
let vx = a.vx, vy = a.vy;
for (let other = 0; other < nodes.length; other++) {
if (index === other) continue;
const dx = a.x - nodes[other].x;
const dy = a.y - nodes[other].y;
const squared = dx * dx + dy * dy;
if (squared > 600 * 600 || squared === 0) continue;
const scale = 1500 / (squared * Math.sqrt(squared));
vx += dx * scale;
vy += dy * scale;
}
return { ...a, vx, vy };
});
}
function assertForce(actual, expected) {
for (let i = 0; i < actual.length; i++) {
assert.equal(actual[i].x, expected[i].x, 'repulsion must not move a node mid-step');
assert.equal(actual[i].y, expected[i].y);
for (const axis of ['vx', 'vy']) {
const tolerance = 1e-10 * Math.max(1, Math.abs(expected[i][axis]));
assert.ok(Math.abs(actual[i][axis] - expected[i][axis]) <= tolerance,
`node ${i} ${axis}: ${actual[i][axis]} != ${expected[i][axis]}`);
}
}
}
test('repulsion preserves nearby forces across negative coordinates and cell boundaries', () => {
const nodes = [
node(-601, -601), node(-599, -599), node(-1, -1), node(1, 1),
node(599, 599), node(601, 601), node(-599, 599), node(599, -599),
node(1800, 1800), node(10000, -10000),
];
nodes[0].vx = 3;
nodes[2].vy = -2;
const expected = reference(nodes);
run(nodes);
assertForce(nodes, expected);
});
test('the exact 600-unit cutoff is included, but farther nodes have no effect', () => {
for (const offset of [[600, 0], [360, 480], [-600, 0], [0, -600]]) {
const nodes = [node(-10, -20), node(-10 + offset[0], -20 + offset[1])];
const expected = reference(nodes);
run(nodes);
assertForce(nodes, expected);
assert.ok(Math.hypot(nodes[0].vx, nodes[0].vy) > 0);
}
const distant = [node(0, 0), node(600.001, 0)];
run(distant);
assert.deepEqual(distant, [node(0, 0), node(600.001, 0)]);
});
test('dense and coincident nodes remain finite and preserve equal-and-opposite forces', () => {
const nodes = Array.from({ length: 120 }, (_, i) => node((i % 12) * 17 - 100, Math.floor(i / 12) * 19 - 90));
nodes.push(node(nodes[0].x, nodes[0].y));
const expected = reference(nodes);
run(nodes);
assertForce(nodes, expected);
assert.ok(Math.abs(nodes.reduce((sum, n) => sum + n.vx, 0)) < 1e-9);
assert.ok(Math.abs(nodes.reduce((sum, n) => sum + n.vy, 0)) < 1e-9);
});
test('moving across cells between steps updates which nodes interact', () => {
const nodes = [node(0, 0), node(1800, 0), node(1810, 10)];
run(nodes);
assert.equal(nodes[0].vx, 0);
nodes[1].x = 300;
nodes[2].x = 310;
const expected = reference(nodes);
run(nodes);
assertForce(nodes, expected);
assert.ok(nodes[0].vx < 0);
});
test('sparse graphs do not read coordinates for every distant pair', () => {
let coordinateReads = 0;
const nodes = Array.from({ length: 1200 }, (_, i) => {
const x = Math.floor(i / 3) * 1800 + (i % 3) * 20;
return {
get x() { coordinateReads++; return x; },
get y() { coordinateReads++; return 0; },
vx: 0, vy: 0,
};
});
run(nodes);
// A generous work bound, independent of wall-clock speed or exact bucket implementation.
assert.ok(coordinateReads < nodes.length * 64,
`distant-pair work grew quadratically: ${coordinateReads} coordinate reads`);
assert.ok(nodes[0].vx < 0 && nodes[2].vx > 0, 'nearby triples must still repel');
});
test('empty and singleton graphs leave velocities unchanged', () => {
run([]);
const singleton = [{ x: 5, y: -8, vx: 2, vy: -3 }];
run(singleton);
assert.deepEqual(singleton, [{ x: 5, y: -8, vx: 2, vy: -3 }]);
});
+50
View File
@@ -0,0 +1,50 @@
export interface RepulsionNode {
x: number;
y: number;
vx: number;
vy: number;
}
/** Update velocities without moving nodes; yield between rows for cooperative layout. */
export function* applyGraphRepulsion(nodes: readonly RepulsionNode[]): Generator<void> {
// The force already has a 600-unit cutoff. Only the same cell and its
// eight neighbours can contain nodes inside that radius.
const cellSize = 600;
const columns = new Map<number, Map<number, number[]>>();
for (let i = 0; i < nodes.length; i++) {
const x = Math.floor(nodes[i].x / cellSize);
const y = Math.floor(nodes[i].y / cellSize);
let column = columns.get(x);
if (!column) columns.set(x, column = new Map());
let bucket = column.get(y);
if (!bucket) column.set(y, bucket = []);
bucket.push(i);
}
for (let i = 0; i < nodes.length; i++) {
const a = nodes[i];
const ax = a.x, ay = a.y;
const cellX = Math.floor(ax / cellSize), cellY = Math.floor(ay / cellSize);
for (let offsetX = -1; offsetX <= 1; offsetX++) {
const column = columns.get(cellX + offsetX);
if (!column) continue;
for (let offsetY = -1; offsetY <= 1; offsetY++) {
const bucket = column.get(cellY + offsetY);
if (!bucket) continue;
for (const j of bucket) {
if (j <= i) continue;
const b = nodes[j];
const dx = b.x - ax, dy = b.y - ay;
const distSq = dx * dx + dy * dy;
if (distSq > cellSize * cellSize) continue;
const d = distSq || 1;
const force = 1500 / d;
const dist = Math.sqrt(d);
const fx = (dx / dist) * force, fy = (dy / dist) * force;
a.vx -= fx; a.vy -= fy; b.vx += fx; b.vy += fy;
}
}
}
yield;
}
}
+5
View File
@@ -0,0 +1,5 @@
const naturalNameCollator = new Intl.Collator(undefined, { numeric: true });
export function compareNaturalNames(left: string, right: string): number {
return naturalNameCollator.compare(left, right);
}
+7
View File
@@ -0,0 +1,7 @@
export function encodeNoteDragPaths(paths: Iterable<string>): string {
return [...paths].join("\n");
}
export function decodeNoteDragPaths(payload: string): string[] {
return payload.split(/\r?\n/).filter((path) => path.length > 0);
}
+62
View File
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { isCurrentVaultEvent, updateNoteList, sameNoteTags } from './note-list-updates.ts';
const note = {
path: '/vault/Work/Plan.md', relative_path: 'Work/Plan.md', preview: 'Before',
meta: { id: 'plan', title: 'Plan', tags: ['work'], pinned: false, created: '2026-01-01', modified: '2026-01-02' },
};
test('a body save updates preview and modification date without changing unrelated notes', () => {
const other = { ...note, path: '/vault/Other.md', relative_path: 'Other.md' };
const changed = { ...note, preview: 'After', meta: { ...note.meta, modified: '2026-01-03' } };
const result = updateNoteList([note, other], changed, 'all', []);
assert.deepEqual(result, [changed, other]);
assert.equal(result[1], other);
assert.equal(sameNoteTags(note, changed), true);
});
test('tag edits remove and insert notes in the appropriate cached views', () => {
const changed = { ...note, meta: { ...note.meta, tags: ['personal'] } };
assert.deepEqual(updateNoteList([note], changed, 'tag:work', []), []);
assert.deepEqual(updateNoteList([], changed, 'tag:personal', []), [changed]);
assert.equal(sameNoteTags(note, changed), false);
});
test('notebook views contain direct children only, with native path separators', () => {
const windows = { ...note, path: 'C:\\vault\\Work\\Plan.md', relative_path: 'Work\\Plan.md' };
assert.deepEqual(updateNoteList([], windows, 'nb:C:/vault/Work', []), [windows]);
assert.deepEqual(updateNoteList([], windows, 'nb:C:/vault', []), []);
assert.deepEqual(updateNoteList([], windows, 'nb:C:/vault/Workshop', []), []);
});
test('daily, quick access and trash views keep their membership constraints', () => {
const daily = { ...note, path: '/vault/Daily/2026-01-03.md', relative_path: 'Daily/2026-01-03.md' };
assert.deepEqual(updateNoteList([], daily, 'daily', []), [daily]);
assert.deepEqual(updateNoteList([], note, 'daily', []), []);
assert.deepEqual(updateNoteList([], note, 'quickaccess', ['Work\\Plan.md']), [note]);
assert.deepEqual(updateNoteList([note], note, 'quickaccess', []), []);
assert.deepEqual(updateNoteList([], note, 'trash', []), []);
});
test('duplicate watcher notifications leave an already current list unchanged', () => {
const list = [note];
assert.equal(updateNoteList(list, structuredClone(note), 'all', []), list);
});
test('delayed events cannot cross vaults, including nested vaults sharing note paths', () => {
const event = { vault_path: '/vault', event_type: 'modify', path: '/vault/nested/Note.md', note };
assert.equal(isCurrentVaultEvent(event, '/vault'), true);
assert.equal(isCurrentVaultEvent(event, '/other'), false);
assert.equal(isCurrentVaultEvent(event, '/vault/nested'), false);
assert.equal(isCurrentVaultEvent({ ...event, vault_path: '/vault/nested' }, '/vault'), false);
assert.equal(isCurrentVaultEvent(event, null), false);
const unscoped = JSON.parse('{"event_type":"modify","path":"/vault/nested/Note.md"}');
assert.equal(isCurrentVaultEvent(unscoped, '/vault'), false);
});
test('vault event identity handles native Windows separators and trailing slashes', () => {
const event = { vault_path: 'C:\\Notes\\Vault\\', event_type: 'remove', path: 'C:\\Notes\\Vault\\Old.md' };
assert.equal(isCurrentVaultEvent(event, 'C:/Notes/Vault'), true);
assert.equal(isCurrentVaultEvent(event, 'C:/Notes/Vault-copy'), false);
});
+43
View File
@@ -0,0 +1,43 @@
import type { FileEvent, NoteEntry } from '../types';
const normalize = (path: string) => path.replace(/\\/g, '/');
/** A delayed watcher/sync batch must not update a different (even nested) vault. */
export function isCurrentVaultEvent(event: FileEvent, vaultPath: string | null): boolean {
if (!vaultPath || typeof event.vault_path !== 'string') return false;
return normalize(event.vault_path).replace(/\/+$/, '') === normalize(vaultPath).replace(/\/+$/, '');
}
export function sameNoteTags(left: NoteEntry, right: NoteEntry): boolean {
return left.meta.tags.length === right.meta.tags.length &&
left.meta.tags.every((tag) => right.meta.tags.includes(tag));
}
function belongsToList(note: NoteEntry, key: string, quickAccess: string[]): boolean {
if (key.startsWith('tag:')) return note.meta.tags.includes(key.slice(4));
if (key.startsWith('nb:')) {
const path = normalize(note.path);
return path.slice(0, path.lastIndexOf('/')) === normalize(key.slice(3));
}
if (key === 'daily') return /^Daily\/[^/]+$/.test(normalize(note.relative_path));
if (key === 'quickaccess') return quickAccess.some((path) => normalize(path) === normalize(note.relative_path));
return key === 'all';
}
/** Patch one note without rescanning the vault, including changes to tag membership. */
export function updateNoteList(list: NoteEntry[], note: NoteEntry, key: string, quickAccess: string[]): NoteEntry[] {
if (key === 'trash') return list;
const index = list.findIndex((entry) => normalize(entry.path) === normalize(note.path));
if (!belongsToList(note, key, quickAccess)) {
return index < 0 ? list : list.filter((_, i) => i !== index);
}
if (index < 0) return [...list, note];
const previous = list[index];
if (previous.preview === note.preview && previous.relative_path === note.relative_path &&
previous.meta.id === note.meta.id && previous.meta.title === note.meta.title &&
previous.meta.pinned === note.meta.pinned && previous.meta.created === note.meta.created &&
previous.meta.modified === note.meta.modified && sameNoteTags(previous, note)) return list;
const updated = list.slice();
updated[index] = note;
return updated;
}
+89
View File
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildNoteListRows, noteListOffsets, noteListWindow, noteListRevealScrollTop } from './note-list-window.ts';
const today = new Date(2026, 8, 26, 12);
function note(index, daysAgo = 0, pinned = false) {
const date = new Date(2026, 8, 26 - daysAgo, 12).toISOString();
return {
path: `/vault/${index}.md`, relative_path: `${index}.md`, preview: 'Preview',
meta: { id: String(index), title: `Note ${index}`, pinned, tags: [], created: date, modified: date },
};
}
test('grouped rows retain pinned/date sections and original note indexes', () => {
const notes = [note(0, 60, true), note(1), note(2, 1), note(3, 1)];
const rows = buildNoteListRows(notes, 'modified', today);
assert.deepEqual(rows.filter(row => row.kind === 'section').map(row => row.label), ['Pinned', 'Today', 'Yesterday']);
assert.deepEqual(rows.filter(row => row.kind === 'note').map(row => [row.note.path, row.noteIndex]),
notes.map((entry, index) => [entry.path, index]));
assert.equal(new Set(rows.map(row => row.key)).size, rows.length);
});
test('measured heights select the correct rows across section boundaries', () => {
const rows = buildNoteListRows([note(0), note(1), note(2, 1)], 'modified', today);
const heights = new Map(rows.map((row, index) => [row.key, [24, 60, 100, 32, 80][index]]));
const offsets = noteListOffsets(rows, heights, 62, 32);
assert.deepEqual(offsets, [0, 24, 84, 184, 216, 296]);
const window = noteListWindow(offsets, 90, 40, 0);
assert.deepEqual(rows.slice(window.start, window.end).map(row => row.key), ['note:/vault/1.md']);
assert.equal(window.top, 84);
assert.equal(window.bottom, 112);
const crossing = noteListWindow(offsets, 175, 60, 0);
assert.deepEqual(rows.slice(crossing.start, crossing.end).map(row => row.kind), ['note', 'section', 'note']);
});
test('thousands of grouped notes keep a bounded viewport and can reach the final note', () => {
const notes = Array.from({ length: 3000 }, (_, index) => note(index));
const rows = buildNoteListRows(notes, 'created', today);
const offsets = noteListOffsets(rows, new Map(), 62, 32);
for (const scrollTop of [0, 60000, offsets.at(-1) - 900]) {
const window = noteListWindow(offsets, scrollTop, 900);
assert.ok(window.end - window.start <= 38, 'only the viewport and overscan should render');
assert.ok(offsets[window.start] <= scrollTop);
assert.ok(offsets[window.end] >= scrollTop + 900);
assert.equal(window.top + offsets[window.end] - offsets[window.start] + window.bottom, offsets.at(-1));
}
const last = noteListWindow(offsets, offsets.at(-1) - 900, 900);
assert.equal(rows[last.end - 1].note.path, '/vault/2999.md');
});
test('empty lists and a viewport above the note rows have safe padding', () => {
assert.deepEqual(noteListWindow([0], 0, 900), { start: 0, end: 0, anchor: 0, top: 0, bottom: 0 });
const rows = buildNoteListRows([note(0), note(1)], null, today);
const offsets = noteListOffsets(rows, new Map(), 62, 32);
const window = noteListWindow(offsets, -250, 900);
assert.equal(window.start, 0);
assert.equal(window.end, 2);
assert.equal(window.top, 0);
assert.equal(window.bottom, 0);
assert.deepEqual(rows.map(row => row.noteIndex), [0, 1]);
});
test('revealing a distant grouped note puts its row inside the virtual window', () => {
const notes = Array.from({ length: 3000 }, (_, index) => note(index, index, index < 3));
const rows = buildNoteListRows(notes, 'created', today);
const offsets = noteListOffsets(rows, new Map(), 62, 32);
const index = rows.findIndex(row => row.kind === 'note' && row.note.path === notes[2550].path);
const top = noteListRevealScrollTop(offsets, index, 0, 600);
const window = noteListWindow(offsets, top, 600);
assert.ok(index >= window.start && index < window.end);
assert.ok(offsets[index] >= top);
assert.ok(offsets[index + 1] <= top + 600);
});
test('revealing keeps visible notes stationary and accounts for content above the list', () => {
const offsets = [0, 30, 90, 150, 210];
assert.equal(noteListRevealScrollTop(offsets, 1, 25, 100), 25);
assert.equal(noteListRevealScrollTop(offsets, 3, 0, 100), 130);
assert.equal(noteListRevealScrollTop(offsets, 2, 0, 100, 180), 250);
assert.equal(noteListRevealScrollTop(offsets, 0, 200, 100), 0);
});
test('revealing oversized notes shows their beginning and ignores unavailable rows', () => {
assert.equal(noteListRevealScrollTop([0, 200, 260], 0, 100, 80, 20), 20);
assert.equal(noteListRevealScrollTop([0], 0, 42, 600), 42);
assert.equal(noteListRevealScrollTop([0, 62], -1, 42, 600), 42);
assert.equal(noteListRevealScrollTop([0, 62], 1, 42, 600), 42);
assert.equal(noteListRevealScrollTop([0, 62], 0, 42, 0), 42);
});
+81
View File
@@ -0,0 +1,81 @@
import type { NoteEntry } from '../types';
import { dateBucketLabel } from './time.ts';
export type NoteListRow =
| { kind: 'section'; key: string; label: string }
| { kind: 'note'; key: string; note: NoteEntry; noteIndex: number };
export function buildNoteListRows(
notes: NoteEntry[],
groupBy: 'created' | 'modified' | null,
now = new Date(),
): NoteListRow[] {
const rows: NoteListRow[] = [];
let previousLabel: string | undefined;
let section = 0;
for (let noteIndex = 0; noteIndex < notes.length; noteIndex++) {
const note = notes[noteIndex];
if (groupBy) {
const label = note.meta.pinned ? 'Pinned' : dateBucketLabel(note.meta[groupBy], now);
if (label !== previousLabel) {
rows.push({ kind: 'section', key: `section:${section++}:${label}`, label });
previousLabel = label;
}
}
rows.push({ kind: 'note', key: `note:${note.path}`, note, noteIndex });
}
return rows;
}
/** Prefix offsets are rebuilt when rows or measured heights change, not on scroll. */
export function noteListOffsets(
rows: NoteListRow[],
heights: ReadonlyMap<string, number>,
noteHeight: number,
sectionHeight: number,
): number[] {
const offsets = new Array<number>(rows.length + 1);
offsets[0] = 0;
for (let index = 0; index < rows.length; index++) {
const row = rows[index];
offsets[index + 1] = offsets[index] +
(heights.get(row.key) ?? (row.kind === 'note' ? noteHeight : sectionHeight));
}
return offsets;
}
function rowAt(offsets: number[], position: number): number {
let low = 0;
let high = offsets.length - 1;
while (low < high) {
const middle = Math.floor((low + high + 1) / 2);
if (offsets[middle] <= position) low = middle;
else high = middle - 1;
}
return Math.min(low, Math.max(0, offsets.length - 2));
}
export function noteListWindow(offsets: number[], scrollTop: number, height: number, overscan = 10) {
const count = offsets.length - 1;
if (count === 0) return { start: 0, end: 0, anchor: 0, top: 0, bottom: 0 };
const anchor = rowAt(offsets, Math.max(0, scrollTop));
const start = Math.max(0, anchor - overscan);
const end = Math.min(count, rowAt(offsets, Math.max(0, scrollTop + height)) + 1 + overscan);
return { start, end, anchor, top: offsets[start], bottom: offsets[count] - offsets[end] };
}
/** Keep visible rows stationary; request a centered offset for off-screen rows. */
export function noteListRevealScrollTop(
offsets: number[],
rowIndex: number,
scrollTop: number,
height: number,
listOrigin = 0,
): number {
if (rowIndex < 0 || rowIndex + 1 >= offsets.length || height <= 0) return scrollTop;
const top = listOrigin + offsets[rowIndex];
const bottom = listOrigin + offsets[rowIndex + 1];
if (top >= scrollTop && bottom <= scrollTop + height) return scrollTop;
// The scrolling element clamps the upper bound, including its bottom padding.
return Math.max(0, top - Math.max(0, height - (bottom - top)) / 2);
}
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { beginNoteNavigation, isCurrentNoteNavigation, cancelNoteNavigation } from './note-navigation.ts';
function deferred() {
let resolve;
const promise = new Promise(res => { resolve = res; });
return { promise, resolve };
}
function navigationConsumer(initialSelection) {
let selected = initialSelection;
let ownedToken;
return {
get selected() { return selected; },
async select(path, read) {
const token = beginNoteNavigation();
ownedToken = token;
if (path === selected.path) return;
const note = await read;
if (isCurrentNoteNavigation(token)) selected = note;
},
dispose() {
if (ownedToken !== undefined) cancelNoteNavigation(ownedToken);
},
};
}
test('a slower earlier note read cannot replace a newer selection', async () => {
const navigation = navigationConsumer({ path: 'initial.md', body: 'initial' });
const older = deferred();
const newer = deferred();
const oldSelection = navigation.select('older.md', older.promise);
const newSelection = navigation.select('newer.md', newer.promise);
newer.resolve({ path: 'newer.md', body: 'newer note' });
await newSelection;
older.resolve({ path: 'older.md', body: 'older note' });
await oldSelection;
assert.deepEqual(navigation.selected, { path: 'newer.md', body: 'newer note' });
});
test('selecting the already-open note cancels a different pending selection', async () => {
const currentNote = { path: 'current.md', body: 'current note' };
const navigation = navigationConsumer(currentNote);
const pending = deferred();
const selection = navigation.select('other.md', pending.promise);
await navigation.select('current.md');
pending.resolve({ path: 'other.md', body: 'other note' });
await selection;
assert.equal(navigation.selected, currentNote);
});
test('disposing the owner prevents its unfinished read from publishing', async () => {
const currentNote = { path: 'current.md', body: 'current note' };
const navigation = navigationConsumer(currentNote);
const pending = deferred();
const selection = navigation.select('other.md', pending.promise);
navigation.dispose();
pending.resolve({ path: 'other.md', body: 'old vault content' });
await selection;
assert.equal(navigation.selected, currentNote);
});
test('disposing an older owner does not cancel a replacement owner selection', async () => {
const oldNote = { path: 'old-vault/current.md', body: 'old vault' };
const oldOwner = navigationConsumer(oldNote);
const newOwner = navigationConsumer({ path: 'new-vault/current.md', body: 'new vault' });
const oldRead = deferred();
const newRead = deferred();
const oldSelection = oldOwner.select('old-vault/other.md', oldRead.promise);
const newSelection = newOwner.select('new-vault/other.md', newRead.promise);
oldOwner.dispose();
oldRead.resolve({ path: 'old-vault/other.md', body: 'stale old vault' });
newRead.resolve({ path: 'new-vault/other.md', body: 'latest new vault' });
await Promise.all([oldSelection, newSelection]);
assert.equal(oldOwner.selected, oldNote);
assert.deepEqual(newOwner.selected, { path: 'new-vault/other.md', body: 'latest new vault' });
});
+15
View File
@@ -0,0 +1,15 @@
let currentNoteNavigation = 0;
/** Start an intent before any await, including selections of the already-open note. */
export function beginNoteNavigation(): number {
return ++currentNoteNavigation;
}
export function isCurrentNoteNavigation(token: number): boolean {
return token === currentNoteNavigation;
}
/** A disposed owner may invalidate its own intent, but never a newer owner's intent. */
export function cancelNoteNavigation(token: number): void {
if (isCurrentNoteNavigation(token)) currentNoteNavigation++;
}
+104
View File
@@ -0,0 +1,104 @@
export interface NoteSwitcherNote {
path: string;
title: string;
relativePath: string;
}
export interface NoteSwitcherRow {
path: string;
title: string;
folder: string;
current: boolean;
}
export interface NoteSwitcherSections {
recent: NoteSwitcherRow[];
quickAccess: NoteSwitcherRow[];
}
interface BuildNoteSwitcherSectionsOptions {
currentPath: string | null;
historyPaths: readonly string[];
knownNotes: readonly NoteSwitcherNote[];
quickAccessNotes: readonly NoteSwitcherNote[];
recentLimit?: number;
}
function pathKey(path: string): string {
return path.replace(/\\/g, '/');
}
export function buildNoteSwitcherRequestPaths(
currentPath: string | null,
historyPaths: readonly string[]
): string[] {
const paths: string[] = [];
const seen = new Set<string>();
const addPath = (path: string | null) => {
if (!path) return;
const key = pathKey(path);
if (seen.has(key)) return;
seen.add(key);
paths.push(path);
};
addPath(currentPath);
for (let index = historyPaths.length - 1; index >= 0; index -= 1) {
addPath(historyPaths[index]);
}
return paths;
}
function folderLabel(relativePath: string): string {
const parts = relativePath.replace(/\\/g, '/').split('/').filter(Boolean);
parts.pop();
return parts.join('/') || 'Unfiled';
}
function toRow(note: NoteSwitcherNote, currentPathKey: string | null): NoteSwitcherRow {
return {
path: note.path,
title: note.title,
folder: folderLabel(note.relativePath),
current: currentPathKey !== null && pathKey(note.path) === currentPathKey
};
}
export function buildNoteSwitcherSections({
currentPath,
historyPaths,
knownNotes,
quickAccessNotes,
recentLimit = 6
}: BuildNoteSwitcherSectionsOptions): NoteSwitcherSections {
const knownByPath = new Map(knownNotes.map((note) => [pathKey(note.path), note]));
const currentPathKey = currentPath ? pathKey(currentPath) : null;
const recent: NoteSwitcherRow[] = [];
const shownPaths = new Set<string>();
const limit = Math.max(0, Math.floor(recentLimit));
const addRecent = (path: string | null) => {
if (!path || recent.length >= limit) return;
const key = pathKey(path);
if (shownPaths.has(key)) return;
const note = knownByPath.get(key);
if (!note) return;
shownPaths.add(key);
recent.push(toRow(note, currentPathKey));
};
for (const path of buildNoteSwitcherRequestPaths(currentPath, historyPaths)) {
if (recent.length >= limit) break;
addRecent(path);
}
const quickAccess: NoteSwitcherRow[] = [];
for (const note of quickAccessNotes) {
const key = pathKey(note.path);
if (shownPaths.has(key) || !knownByPath.has(key)) continue;
shownPaths.add(key);
quickAccess.push(toRow(note, currentPathKey));
}
return { recent, quickAccess };
}
+54
View File
@@ -0,0 +1,54 @@
export const NOTEBOOK_ICON_OPTIONS = [
{ id: 'book', label: 'Book' },
{ id: 'folder', label: 'Folder' },
{ id: 'briefcase', label: 'Work' },
{ id: 'home', label: 'Home' },
{ id: 'star', label: 'Star' },
{ id: 'heart', label: 'Heart' },
{ id: 'lightbulb', label: 'Ideas' },
{ id: 'code', label: 'Code' },
{ id: 'flask', label: 'Research' },
{ id: 'graduation', label: 'Study' },
{ id: 'calendar', label: 'Calendar' },
{ id: 'tasks', label: 'Tasks' },
{ id: 'archive', label: 'Archive' },
{ id: 'globe', label: 'Globe' },
{ id: 'plane', label: 'Travel' },
{ id: 'palette', label: 'Creative' }
] as const;
export type NotebookIconId = (typeof NOTEBOOK_ICON_OPTIONS)[number]['id'];
const BUILTIN_PREFIX = 'builtin:';
const BUILTIN_IDS: Record<NotebookIconId, true> = {
book: true,
folder: true,
briefcase: true,
home: true,
star: true,
heart: true,
lightbulb: true,
code: true,
flask: true,
graduation: true,
calendar: true,
tasks: true,
archive: true,
globe: true,
plane: true,
palette: true
};
export function normalizeNotebookIconKey(path: string): string {
return path.replace(/\\/g, '/');
}
export function encodeBuiltinNotebookIcon(icon: NotebookIconId): string {
return `${BUILTIN_PREFIX}${icon}`;
}
export function decodeBuiltinNotebookIcon(value: string | null | undefined): NotebookIconId | null {
if (!value?.startsWith(BUILTIN_PREFIX)) return null;
const icon = value.slice(BUILTIN_PREFIX.length);
return Object.hasOwn(BUILTIN_IDS, icon) ? icon as NotebookIconId : null;
}
+115
View File
@@ -26,3 +26,118 @@ export function relativePath(fromDirectory: string, targetPath: string): string
const result = [...Array(from.length - common).fill('..'), ...target.slice(common)]; const result = [...Array(from.length - common).fill('..'), ...target.slice(common)];
return result.join('/') || '.'; return result.join('/') || '.';
} }
export function normalizeLocalAssetPath(path: string): string {
return path
.replace(/\\/g, '/')
.replace(/^\/([A-Za-z]:\/)/, '$1');
}
export function assetUrlToLocalPath(source: string): string | null {
if (!source.startsWith('asset:') && !source.startsWith('http://asset.localhost') && !source.startsWith('https://asset.localhost')) {
return null;
}
try {
const path = normalizeLocalAssetPath(decodeURIComponent(new URL(source).pathname));
// Tauri prepends a URL-path slash to POSIX and UNC paths.
return path.startsWith('//') ? path.substring(1) : path;
} catch {
return null;
}
}
export function resolveVaultFilePath(
targetPath: string,
notePath: string | null,
vaultRoot: string | null,
): string {
const target = normalizeLocalAssetPath(targetPath);
if (target.startsWith('/') || /^[A-Za-z]:\//.test(target)) return target;
const root = vaultRoot?.replace(/\\/g, '/').replace(/\/$/, '') ?? '';
if (target.startsWith('.helixnotes/') && root) {
return resolvePathFromFile(`${root}/.vault-root`, target);
}
if (notePath) return resolvePathFromFile(notePath, target);
if (root) return resolvePathFromFile(`${root}/.vault-root`, target);
return target;
}
export function assetSourceToMarkdown(
source: string,
notePath: string | null,
vaultRoot: string | null,
): string {
if (source.startsWith('blob:')) return '';
if (source.startsWith('imgproxy:') || source.startsWith('http://imgproxy.localhost') || source.startsWith('https://imgproxy.localhost')) {
try {
return decodeURIComponent(new URL(source).pathname.substring(1));
} catch {
return source;
}
}
const absolutePath = assetUrlToLocalPath(source);
if (absolutePath === null) return source;
const normalizedRoot = vaultRoot?.replace(/\\/g, '/').replace(/\/$/, '');
if (!normalizedRoot || !absolutePath.startsWith(normalizedRoot + '/')) return absolutePath;
const vaultRelative = absolutePath.substring(normalizedRoot.length + 1);
if (vaultRelative.startsWith('.helixnotes/')) return vaultRelative;
if (!notePath) return vaultRelative;
const normalizedNotePath = notePath.replace(/\\/g, '/');
const noteDirectory = normalizedNotePath.substring(0, normalizedNotePath.lastIndexOf('/'));
return relativePath(noteDirectory, absolutePath);
}
export function resolvePathFromFile(filePath: string, targetPath: string): string {
const normalizedFile = filePath.replace(/\\/g, '/');
const normalizedTarget = targetPath.replace(/\\/g, '/');
const lastSeparator = normalizedFile.lastIndexOf('/');
const fileDirectory = lastSeparator >= 0 ? normalizedFile.slice(0, lastSeparator) : '';
const combined = normalizedTarget.startsWith('/') || /^[A-Za-z]:\//.test(normalizedTarget)
? normalizedTarget
: `${fileDirectory}/${normalizedTarget}`;
const drive = combined.match(/^([A-Za-z]:)\//);
const unc = combined.startsWith('//');
const absolute = !unc && combined.startsWith('/');
let prefix = '';
let remainder = combined;
if (drive) {
prefix = `${drive[1]}/`;
remainder = combined.slice(drive[0].length);
} else if (unc) {
prefix = '//';
remainder = combined.slice(2);
} else if (absolute) {
prefix = '/';
remainder = combined.slice(1);
}
const resolved: string[] = [];
for (const segment of remainder.split('/')) {
if (!segment || segment === '.') continue;
if (segment === '..') {
resolved.pop();
} else {
resolved.push(segment);
}
}
return prefix + resolved.join('/');
}
/** Lexical ownership for the UI; native code enforces filesystem access. */
export function isPathInDirectory(path: string, directory: string | null): boolean {
if (!directory) return false;
let root = resolvePathFromFile('', directory).replace(/\/+$/, '');
let target = resolvePathFromFile('', path);
if (/^[A-Za-z]:\//.test(root) || root.startsWith('//')) {
root = root.toLowerCase();
target = target.toLowerCase();
}
return target.startsWith(`${root}/`);
}
export function isTrashedNote(path: string | null, vaultRoot: string | null | undefined): boolean {
return !!path && !!vaultRoot && isPathInDirectory(path, `${vaultRoot}/.helixnotes/trash`);
}
+220
View File
@@ -0,0 +1,220 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { RevisionSaveQueue } from './revision-save.ts';
function deferred() {
let resolve;
let reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
test('an edit during a pending save stays dirty and the next save persists it', async () => {
const saves = new RevisionSaveQueue();
const started = deferred();
const diskWrite = deferred();
let disk = 'initial';
saves.markChanged();
const first = saves.save(saves.capture(), async () => {
started.resolve();
await diskWrite.promise;
disk = 'first edit';
});
await started.promise;
saves.markChanged();
diskWrite.resolve();
assert.equal(await first, false, 'a stale completion must not authorize navigation');
assert.equal(saves.dirty, true);
assert.equal(await saves.save(saves.capture(), async () => { disk = 'second edit'; }), true);
assert.equal(disk, 'second edit');
assert.equal(saves.dirty, false);
});
test('failed saves stay dirty and do not poison an explicit retry', async () => {
const saves = new RevisionSaveQueue();
let disk = 'initial';
saves.markChanged();
const snapshot = saves.capture();
await assert.rejects(saves.save(snapshot, async () => { throw new Error('disk full'); }), /disk full/);
assert.equal(saves.dirty, true);
assert.equal(disk, 'initial');
assert.equal(await saves.save(snapshot, async () => { disk = 'retried edit'; }), true);
assert.equal(disk, 'retried edit');
assert.equal(saves.dirty, false);
});
test('flush waits behind autosave and an older captured snapshot cannot overwrite it', async () => {
const saves = new RevisionSaveQueue();
const started = deferred();
const diskWrite = deferred();
const writes = [];
saves.markChanged();
const older = saves.capture();
const autoSave = saves.save(older, async () => {
started.resolve();
await diskWrite.promise;
writes.push('autosave');
});
await started.promise;
saves.markChanged();
const flush = saves.save(saves.capture(), async () => { writes.push('flush'); });
const staleFlush = saves.save(older, async () => { writes.push('stale'); });
assert.deepEqual(writes, []);
diskWrite.resolve();
assert.equal(await autoSave, false);
assert.equal(await flush, true);
assert.equal(await staleFlush, false);
assert.deepEqual(writes, ['autosave', 'flush']);
});
test('returning to the same note starts a new session that an older completion cannot clean', async () => {
const saves = new RevisionSaveQueue();
const started = deferred();
const diskWrite = deferred();
const writes = [];
saves.markChanged();
const leaving = saves.save(saves.capture(), async () => {
started.resolve();
await diskWrite.promise;
writes.push(['A.md', 'before leaving']);
});
await started.promise;
saves.startSession();
saves.markChanged();
const otherNote = saves.save(saves.capture(), async () => { writes.push(['B.md', 'other note']); });
saves.startSession();
saves.markChanged();
diskWrite.resolve();
assert.equal(await leaving, false);
assert.equal(await otherNote, false);
assert.equal(saves.dirty, true);
assert.equal(await saves.save(saves.capture(), async () => { writes.push(['A.md', 'after returning']); }), true);
assert.deepEqual(writes, [
['A.md', 'before leaving'],
['B.md', 'other note'],
['A.md', 'after returning'],
]);
assert.equal(saves.dirty, false);
});
test('queued saves advance the exact accepted raw baseline even when newer typing remains dirty', async () => {
const saves = new RevisionSaveQueue();
const firstWrite = deferred();
const started = deferred();
let disk = '---\nmodified: old\n---\noriginal';
saves.startSession(disk);
saves.markChanged();
const first = saves.save(saves.capture(), async (expectedRaw) => {
assert.equal(expectedRaw, disk);
started.resolve();
await firstWrite.promise;
disk = '---\nmodified: first\n---\nfirst edit';
return disk;
});
await started.promise;
saves.markChanged();
firstWrite.resolve();
assert.equal(await first, false);
assert.equal(saves.dirty, true);
assert.equal(saves.raw, disk, 'a successful older save advances the active session baseline');
const second = saves.save(saves.capture(), async (expectedRaw) => {
assert.equal(expectedRaw, disk, 'later queued saves compare against the preceding accepted raw');
disk = '---\nmodified: second\n---\nsecond edit';
return disk;
});
assert.equal(await second, true);
assert.equal(saves.raw, disk);
assert.equal(saves.dirty, false);
});
test('external disk changes reject an edit without losing its baseline or silently replacing disk', async () => {
const saves = new RevisionSaveQueue();
saves.startSession('original');
saves.markChanged();
let disk = 'external';
const snapshot = saves.capture();
const write = async (expectedRaw) => {
if (expectedRaw !== disk) throw new Error('Save conflict: changed outside the app');
disk = 'draft';
return disk;
};
await assert.rejects(saves.save(snapshot, write), /Save conflict/);
assert.equal(disk, 'external');
assert.equal(saves.raw, 'original');
assert.equal(saves.dirty, true);
await assert.rejects(saves.save(snapshot, write), /Save conflict/);
assert.equal(disk, 'external');
});
test('native rename advances a dirty draft baseline only for its accepted raw', async () => {
const saves = new RevisionSaveQueue();
saves.startSession('before rename');
saves.markChanged();
assert.equal(saves.adoptMovedRaw('stale unrelated revision', 'renamed'), false);
assert.equal(saves.raw, 'before rename');
assert.equal(saves.adoptMovedRaw('before rename', 'renamed'), true);
assert.equal(saves.dirty, true, 'native path migration does not claim the draft was saved');
let disk = 'renamed';
assert.equal(await saves.save(saves.capture(), async (expectedRaw) => {
assert.equal(expectedRaw, disk);
disk = 'renamed with draft';
return disk;
}), true);
assert.equal(saves.raw, disk);
assert.equal(saves.dirty, false);
});
test('overlapping manual saves and a clean save do not rewrite the same revision', async () => {
const saves = new RevisionSaveQueue();
let writes = 0;
const persist = async () => { writes++; };
assert.equal(await saves.save(saves.capture(), persist), true);
assert.equal(writes, 0);
saves.markChanged();
const snapshot = saves.capture();
assert.deepEqual(await Promise.all([saves.save(snapshot, persist), saves.save(snapshot, persist)]), [true, true]);
assert.equal(await saves.save(saves.capture(), persist), true);
assert.equal(writes, 1);
});
test('autosave waits for idle but continuous typing cannot postpone it indefinitely', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const saves = new RevisionSaveQueue();
let now = 0;
const writes = [];
const save = () => { writes.push(now); };
saves.schedule(save);
for (let second = 1; second <= 9; second++) {
now = second * 1_000;
t.mock.timers.tick(1_000);
saves.schedule(save);
}
assert.deepEqual(writes, []);
now = 10_000;
t.mock.timers.tick(1_000);
assert.deepEqual(writes, [10_000]);
saves.schedule(save);
now = 12_999;
t.mock.timers.tick(2_999);
assert.deepEqual(writes, [10_000]);
now = 13_000;
t.mock.timers.tick(1);
assert.deepEqual(writes, [10_000, 13_000]);
});
test('explicit saves and note switches cancel both pending autosave deadlines', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const saves = new RevisionSaveQueue();
const writes = [];
saves.schedule(() => { writes.push('cancelled by flush'); });
t.mock.timers.tick(1_000);
saves.cancelScheduled();
t.mock.timers.tick(10_000);
saves.schedule(() => { writes.push('previous note'); });
t.mock.timers.tick(1_000);
saves.startSession();
t.mock.timers.tick(10_000);
saves.schedule(() => { writes.push('current note'); });
t.mock.timers.tick(3_000);
assert.deepEqual(writes, ['current note']);
});
+91
View File
@@ -0,0 +1,91 @@
interface SaveSession {
revision: number;
savedRevision: number;
raw: string;
}
export interface SaveRevision {
readonly session: SaveSession;
readonly revision: number;
}
/** Serializes immutable save snapshots without letting an old completion mark newer edits clean. */
export class RevisionSaveQueue {
private session: SaveSession = { revision: 0, savedRevision: 0, raw: '' };
private tail: Promise<void> = Promise.resolve();
private idleTimer: ReturnType<typeof setTimeout> | null = null;
private maxWaitTimer: ReturnType<typeof setTimeout> | null = null;
startSession(raw = ''): void {
this.cancelScheduled();
this.session = { revision: 0, savedRevision: 0, raw };
}
markChanged(): void {
this.session.revision++;
}
schedule(save: () => void): void {
if (this.idleTimer !== null) clearTimeout(this.idleTimer);
const session = this.session;
const run = () => {
this.cancelScheduled();
if (session === this.session) save();
};
this.idleTimer = setTimeout(run, 3_000);
if (this.maxWaitTimer === null) this.maxWaitTimer = setTimeout(run, 10_000);
}
cancelScheduled(): void {
if (this.idleTimer !== null) clearTimeout(this.idleTimer);
if (this.maxWaitTimer !== null) clearTimeout(this.maxWaitTimer);
this.idleTimer = null;
this.maxWaitTimer = null;
}
capture(): SaveRevision {
return { session: this.session, revision: this.session.revision };
}
isCurrentSession(snapshot: SaveRevision): boolean {
return snapshot.session === this.session;
}
isCurrent(snapshot: SaveRevision): boolean {
return this.isCurrentSession(snapshot) && snapshot.revision === this.session.revision;
}
get raw(): string {
return this.session.raw;
}
/** Adopt a native rename's serialized baseline only when it moved our accepted revision. */
adoptMovedRaw(oldRaw: string, newRaw: string): boolean {
if (this.session.raw !== oldRaw) return false;
this.session.raw = newRaw;
return true;
}
get dirty(): boolean {
return this.session.revision !== this.session.savedRevision;
}
save(snapshot: SaveRevision, persist: (expectedRaw: string) => Promise<string | void>): Promise<boolean> {
const queued = this.tail.then(async () => {
// An explicit flush may capture the same revision as an already queued autosave.
if (snapshot.revision > snapshot.session.savedRevision) {
const nextRaw = await persist(snapshot.session.raw);
if (typeof nextRaw === 'string') snapshot.session.raw = nextRaw;
snapshot.session.savedRevision = snapshot.revision;
}
return this.isCurrent(snapshot);
});
// Recover the queue, not the caller's result: a failed save stays dirty and remains retryable.
this.tail = queued.then(() => {}, () => {});
return queued;
}
async idle(): Promise<void> {
await this.tail;
}
}
+57
View File
@@ -0,0 +1,57 @@
import type { StartupView } from "../types";
type RestorableListView = StartupView | "trash";
export type StartupTarget =
| { mode: RestorableListView }
| { mode: "notebook"; notebookPath: string }
| { mode: "tag"; tag: string };
export interface StartupState {
startupView: unknown;
restoreLastSession: boolean;
lastViewMode: unknown;
lastNotebook: string | null;
lastTag: string | null;
}
export function normalizeStartupView(value: unknown): StartupView {
switch (value) {
case "daily":
case "quickaccess":
case "tasks":
return value;
default:
return "all";
}
}
function restorableListView(value: unknown): RestorableListView | null {
switch (value) {
case "all":
case "daily":
case "quickaccess":
case "tasks":
case "trash":
return value;
default:
return null;
}
}
export function resolveStartupTarget(state: StartupState): StartupTarget {
const fallback: StartupTarget = {
mode: normalizeStartupView(state.startupView),
};
if (!state.restoreLastSession) return fallback;
if (state.lastViewMode === "notebook" && typeof state.lastNotebook === "string") {
return { mode: "notebook", notebookPath: state.lastNotebook };
}
if (state.lastViewMode === "tag" && state.lastTag) {
return { mode: "tag", tag: state.lastTag };
}
const listView = restorableListView(state.lastViewMode);
return listView ? { mode: listView } : fallback;
}
+66
View File
@@ -0,0 +1,66 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const {
applyCommittedTagStyle,
isValidTagColor,
lookupTagStyle,
normalizeTagStyleKey,
tagColor,
tagCustomImagePath,
tagIterationKey,
tagStyleKeyEquals
} = await import(new URL('./tag-styles.ts', import.meta.url));
test('normalizes tag style keys by trimming', () => {
assert.equal(normalizeTagStyleKey(' work '), 'work');
});
test('accepts 3 and 6 digit hex colors only', () => {
assert.equal(isValidTagColor('#e11'), true);
assert.equal(isValidTagColor('#e11d48'), true);
assert.equal(isValidTagColor('#E11D48'), true);
assert.equal(isValidTagColor('red'), false);
assert.equal(isValidTagColor('#gg0000'), false);
assert.equal(isValidTagColor('#e11d48aa'), false);
});
test('looks up tag styles with a case-insensitive fallback', () => {
const styles = { Work: { icon: 'builtin:briefcase', color: '#e11d48' } };
assert.equal(lookupTagStyle('Work', styles)?.icon, 'builtin:briefcase');
assert.equal(lookupTagStyle('work', styles)?.color, '#e11d48');
assert.equal(tagColor('missing', styles), null);
assert.equal(tagStyleKeyEquals('Work', 'work'), true);
});
test('treats non-builtin icons as custom image paths', () => {
const styles = { daily: { icon: '.helixnotes/attachments/tag.png' } };
assert.equal(tagCustomImagePath('daily', styles), '.helixnotes/attachments/tag.png');
assert.equal(tagCustomImagePath('daily', { daily: { icon: 'builtin:calendar' } }), null);
});
test('resetting a differently cased tag removes the stored style', () => {
const styles = { Work: { icon: 'builtin:briefcase', color: '#e11d48' } };
assert.deepEqual(applyCommittedTagStyle(styles, 'work', null), {});
});
test('saving a style replaces a differently cased stored key', () => {
const styles = { Work: { icon: 'builtin:briefcase' } };
const next = applyCommittedTagStyle(styles, 'work', {
icon: 'builtin:star',
color: '#ec4899'
});
assert.deepEqual(next, {
Work: { icon: 'builtin:star', color: '#ec4899' }
});
assert.equal(Object.hasOwn(next, 'work'), false);
});
test('duplicate tag names still get unique each keys', () => {
const tags = ['work', 'work'];
const keys = tags.map((tag, index) => tagIterationKey(tag, index));
assert.deepEqual(keys, ['0:work', '1:work']);
assert.equal(new Set(keys).size, keys.length);
});
+93
View File
@@ -0,0 +1,93 @@
export interface TagStyleFields {
icon?: string | null;
color?: string | null;
}
export const TAG_COLOR_PRESETS = [
'#e11d48',
'#f97316',
'#eab308',
'#22c55e',
'#14b8a6',
'#3b82f6',
'#8b5cf6',
'#ec4899',
'#64748b'
];
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
const BUILTIN_PREFIX = 'builtin:';
export function normalizeTagStyleKey(tag: string): string {
return tag.trim();
}
export function isValidTagColor(value: string | null | undefined): value is string {
return typeof value === 'string' && HEX_COLOR.test(value);
}
export function tagStyleKeyEquals(a: string, b: string): boolean {
return normalizeTagStyleKey(a).toLowerCase() === normalizeTagStyleKey(b).toLowerCase();
}
export function existingTagStyleKey(
tag: string,
styles: Record<string, TagStyleFields>
): string | undefined {
const key = normalizeTagStyleKey(tag);
if (!key) return undefined;
if (Object.hasOwn(styles, key)) return key;
const lower = key.toLowerCase();
return Object.keys(styles).find((name) => name.toLowerCase() === lower);
}
export function lookupTagStyle(
tag: string,
styles: Record<string, TagStyleFields>
): TagStyleFields | undefined {
const storedKey = existingTagStyleKey(tag, styles);
return storedKey ? styles[storedKey] : undefined;
}
/** Stable `{#each}` key when a note can contain duplicate tag names. */
export function tagIterationKey(tag: string, index: number): string {
return `${index}:${tag}`;
}
export function tagColor(
tag: string,
styles: Record<string, TagStyleFields>
): string | null {
const color = lookupTagStyle(tag, styles)?.color;
return isValidTagColor(color) ? color : null;
}
export function tagCustomImagePath(
tag: string,
styles: Record<string, TagStyleFields>
): string | null {
const icon = lookupTagStyle(tag, styles)?.icon;
if (!icon || icon.startsWith(BUILTIN_PREFIX)) return null;
return icon;
}
export function applyCommittedTagStyle(
styles: Record<string, TagStyleFields>,
tag: string,
next: TagStyleFields | null
): Record<string, TagStyleFields> {
const result = { ...styles };
const key = normalizeTagStyleKey(tag);
if (!key) return result;
const lower = key.toLowerCase();
for (const name of Object.keys(result)) {
if (name.toLowerCase() === lower) delete result[name];
}
if (next) {
const storedKey = existingTagStyleKey(tag, styles) ?? key;
result[storedKey] = next;
}
return result;
}
+18 -10
View File
@@ -1,5 +1,17 @@
const shortDateFormatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
const fullDateFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const monthFormatter = new Intl.DateTimeFormat(undefined, { month: 'long' });
const monthYearFormatter = new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
export function formatRelativeTime(dateStr: string): string { export function formatRelativeTime(dateStr: string): string {
const date = new Date(dateStr); const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return date.toString();
const now = new Date(); const now = new Date();
const diff = now.getTime() - date.getTime(); const diff = now.getTime() - date.getTime();
const seconds = Math.floor(diff / 1000); const seconds = Math.floor(diff / 1000);
@@ -12,17 +24,12 @@ export function formatRelativeTime(dateStr: string): string {
if (hours < 24) return `${hours}h ago`; if (hours < 24) return `${hours}h ago`;
if (days < 7) return `${days}d ago`; if (days < 7) return `${days}d ago`;
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); return shortDateFormatter.format(date);
} }
export function formatDate(dateStr: string): string { export function formatDate(dateStr: string): string {
return new Date(dateStr).toLocaleDateString(undefined, { const date = new Date(dateStr);
year: 'numeric', return Number.isNaN(date.getTime()) ? date.toString() : fullDateFormatter.format(date);
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
} }
// Relative-date bucket label for grouping the notes list: // Relative-date bucket label for grouping the notes list:
@@ -30,6 +37,7 @@ export function formatDate(dateStr: string): string {
// Buckets are contiguous, so a list already sorted by date groups by consecutive label. // Buckets are contiguous, so a list already sorted by date groups by consecutive label.
export function dateBucketLabel(dateStr: string, now: Date = new Date()): string { export function dateBucketLabel(dateStr: string, now: Date = new Date()): string {
const d = new Date(dateStr); const d = new Date(dateStr);
if (Number.isNaN(d.getTime())) return d.toString();
const dayMs = 86400000; const dayMs = 86400000;
const startOfDay = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime(); const startOfDay = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
const today = startOfDay(now); const today = startOfDay(now);
@@ -38,6 +46,6 @@ export function dateBucketLabel(dateStr: string, now: Date = new Date()): string
if (day >= today - dayMs) return 'Yesterday'; if (day >= today - dayMs) return 'Yesterday';
if (day >= today - 7 * dayMs) return 'Previous 7 Days'; if (day >= today - 7 * dayMs) return 'Previous 7 Days';
if (day >= today - 30 * dayMs) return 'Previous 30 Days'; if (day >= today - 30 * dayMs) return 'Previous 30 Days';
if (d.getFullYear() === now.getFullYear()) return d.toLocaleDateString(undefined, { month: 'long' }); if (d.getFullYear() === now.getFullYear()) return monthFormatter.format(d);
return d.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }); return monthYearFormatter.format(d);
} }
+3 -3
View File
@@ -2,7 +2,7 @@ import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
const openNoteWindows = new Map<string, string>(); const openNoteWindows = new Map<string, string>();
export async function openNoteWindow(notePath: string, noteTitle: string) { export async function openNoteWindow(vaultPath: string, notePath: string, noteTitle: string) {
const existingLabel = openNoteWindows.get(notePath); const existingLabel = openNoteWindows.get(notePath);
if (existingLabel) { if (existingLabel) {
const existing = await WebviewWindow.getByLabel(existingLabel); const existing = await WebviewWindow.getByLabel(existingLabel);
@@ -15,8 +15,8 @@ export async function openNoteWindow(notePath: string, noteTitle: string) {
openNoteWindows.delete(notePath); openNoteWindows.delete(notePath);
} }
const label = `note-${Date.now()}`; const label = `note-${crypto.randomUUID()}`;
const url = `/?note=${encodeURIComponent(notePath)}`; const url = `/?note=${encodeURIComponent(notePath)}&vault=${encodeURIComponent(vaultPath)}`;
const noteWindow = new WebviewWindow(label, { const noteWindow = new WebviewWindow(label, {
url, url,
+20 -35
View File
@@ -1,18 +1,21 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import '../app.css'; import '../app.css';
import { theme, appConfig, activeNote, activeNotePath, installType, platformIsMobile, checkForUpdate, checkForUpdateMobile, isManagedInstall, customThemes } from '$lib/stores/app'; import { resolvedTheme, appConfig, activeNotePath, installType, platformIsMobile, checkForUpdate, checkForUpdateMobile, isManagedInstall, customThemes } from '$lib/stores/app';
import { openFile, openUrl, readNote, getInstallType, isMobilePlatform } from '$lib/api'; import { openFile, openUrl, getInstallType, isMobilePlatform } from '$lib/api';
import { get } from 'svelte/store'; import { get } from 'svelte/store';
import { darkThemes, isMobile, isAndroid } from '$lib/platform'; import { darkThemes, isMobile, isAndroid } from '$lib/platform';
import type { CustomTheme } from '$lib/types'; import type { CustomTheme } from '$lib/types';
import ResizeHandles from '$lib/components/ResizeHandles.svelte'; import ResizeHandles from '$lib/components/ResizeHandles.svelte';
import { resolveVaultFilePath } from '$lib/utils/paths';
let { children } = $props(); let { children } = $props();
// Reactively apply theme class to <html> whenever $theme or custom themes change // Reactively apply theme class to <html> whenever the resolved theme or custom themes change.
// $resolvedTheme already maps "system" onto the configured light/dark pair, so flipping the OS
// appearance re-runs this effect.
$effect(() => { $effect(() => {
applyTheme($theme, $customThemes); applyTheme($resolvedTheme, $customThemes);
}); });
// Apply link arrow visibility from config // Apply link arrow visibility from config
@@ -26,8 +29,13 @@
'--bg-primary', '--bg-secondary', '--bg-tertiary', '--bg-primary', '--bg-secondary', '--bg-tertiary',
'--bg-hover', '--bg-active', '--bg-editor', '--bg-hover', '--bg-active', '--bg-editor',
'--text-primary', '--text-secondary', '--border-color', '--text-primary', '--text-secondary', '--border-color',
'--border-light', '--text-tertiary',
]; ];
// A custom theme carries nine colors, but the stylesheet also reads --border-light and
// --text-tertiary. Named themes set those in their own :root[data-theme] block; a custom theme
// has no such block, so without these they fall back to the light defaults in app.css and a dark
// custom theme draws near-white dividers. Derive them from the closest color the theme does have.
function applyCustomThemeVars(root: HTMLElement, ct: CustomTheme) { function applyCustomThemeVars(root: HTMLElement, ct: CustomTheme) {
root.style.setProperty('--bg-primary', ct.colors.bg_primary); root.style.setProperty('--bg-primary', ct.colors.bg_primary);
root.style.setProperty('--bg-secondary', ct.colors.bg_secondary); root.style.setProperty('--bg-secondary', ct.colors.bg_secondary);
@@ -38,6 +46,8 @@
root.style.setProperty('--text-primary', ct.colors.text_primary); root.style.setProperty('--text-primary', ct.colors.text_primary);
root.style.setProperty('--text-secondary', ct.colors.text_secondary); root.style.setProperty('--text-secondary', ct.colors.text_secondary);
root.style.setProperty('--border-color', ct.colors.border_color); root.style.setProperty('--border-color', ct.colors.border_color);
root.style.setProperty('--border-light', ct.colors.border_color);
root.style.setProperty('--text-tertiary', ct.colors.text_secondary);
} }
function clearCustomThemeVars(root: HTMLElement) { function clearCustomThemeVars(root: HTMLElement) {
@@ -64,16 +74,6 @@
} }
} }
function normalizePath(p: string): string {
const parts = p.split('/');
const resolved: string[] = [];
for (const seg of parts) {
if (seg === '..') resolved.pop();
else if (seg !== '.') resolved.push(seg);
}
return resolved.join('/');
}
function openLocalFile(path: string) { function openLocalFile(path: string) {
if (isAndroid) { if (isAndroid) {
const bridge = (window as any).Android; const bridge = (window as any).Android;
@@ -89,30 +89,15 @@
if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('mailto:') || href.startsWith('tel:') || href.startsWith('sms:')) { if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('mailto:') || href.startsWith('tel:') || href.startsWith('sms:')) {
openUrl(href).catch((err) => console.error('Failed to open URL:', err)); openUrl(href).catch((err) => console.error('Failed to open URL:', err));
} else if (!href.startsWith('#')) { } else if (!href.startsWith('#')) {
const decoded = decodeURIComponent(href);
const config = get(appConfig); const config = get(appConfig);
const vaultRoot = config?.active_vault; const absPath = resolveVaultFilePath(
let absPath = decoded; decodeURIComponent(href),
if (!decoded.startsWith('/') && vaultRoot) { get(activeNotePath),
// .helixnotes/ paths are always relative to vault root, not the note's directory config?.active_vault ?? null,
if (decoded.startsWith('.helixnotes/')) { );
absPath = normalizePath(`${vaultRoot}/${decoded}`);
} else {
const notePath = get(activeNotePath);
if (notePath) {
const noteDir = notePath.substring(0, notePath.lastIndexOf('/'));
absPath = normalizePath(`${noteDir}/${decoded}`);
} else {
absPath = normalizePath(`${vaultRoot}/${decoded}`);
}
}
}
// Internal .md note link - navigate within the app // Internal .md note link - navigate within the app
if (absPath.endsWith('.md')) { if (absPath.endsWith('.md')) {
readNote(absPath).then((content) => { window.dispatchEvent(new CustomEvent('helixnotes-open-note', { detail: absPath }));
activeNote.set({ ...content, content: content.content });
activeNotePath.set(absPath);
}).catch((err) => console.error('Failed to navigate to note:', err));
} else { } else {
openLocalFile(absPath); openLocalFile(absPath);
} }
+84 -19
View File
@@ -1,35 +1,61 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount, tick } from 'svelte';
import { appConfig, vaultReady, theme } from '$lib/stores/app'; import { appConfig, vaultReady, theme } from '$lib/stores/app';
import { getAppConfig, openVault, restoreExternalVault, setFontSize } from '$lib/api'; import { getAppConfig, openVault, restoreExternalVault, setFontSize } from '$lib/api';
import { darkThemes, isIOS } from '$lib/platform'; import { darkThemes, isIOS, isMobile } from '$lib/platform';
import { getWheelFontSizeAction } from '$lib/utils/editor-zoom';
import { getCurrentWebview } from '@tauri-apps/api/webview'; import { getCurrentWebview } from '@tauri-apps/api/webview';
import { listen } from '@tauri-apps/api/event'; import { listen } from '@tauri-apps/api/event';
import { getCurrentWindow } from '@tauri-apps/api/window';
import VaultPicker from '$lib/components/VaultPicker.svelte'; import VaultPicker from '$lib/components/VaultPicker.svelte';
import AppLayout from '$lib/components/AppLayout.svelte'; import AppLayout from '$lib/components/AppLayout.svelte';
import NoteWindow from '$lib/components/NoteWindow.svelte'; import NoteWindow from '$lib/components/NoteWindow.svelte';
let loading = $state(true); let loading = $state(true);
let noteWindowPath = $state<string | null>(null); let noteWindowPath = $state<string | null>(null);
let noteWindowVault = $state<string | null>(null);
let startupVaultError = $state(''); let startupVaultError = $state('');
let fontSizeSaveTimer: ReturnType<typeof setTimeout> | null = null; let fontSizeSaveTimer: ReturnType<typeof setTimeout> | null = null;
let removeEditorZoomShortcuts: (() => void) | null = null; let removeEditorZoomShortcuts: (() => void) | null = null;
let removeFontSizeListener: (() => void) | null = null; let removeFontSizeListener: (() => void) | null = null;
let removeScrollFontSizeListener: (() => void) | null = null;
let startupRevealTimer: ReturnType<typeof setTimeout> | null = null;
let startupWindowRevealed = false;
const STARTUP_REVEAL_FAILSAFE_MS = 4000;
async function revealStartupWindow() {
if (isMobile || startupWindowRevealed) return;
await tick();
// Force style resolution while the native window is still hidden so its first
// compositor frame already uses the selected theme.
getComputedStyle(document.body).backgroundColor;
try {
await getCurrentWindow().show();
startupWindowRevealed = true;
if (startupRevealTimer) {
clearTimeout(startupRevealTimer);
startupRevealTimer = null;
}
} catch {
// Plain-browser development has no Tauri window to reveal.
}
}
const defaultEditorFontSize = 14; const defaultEditorFontSize = 14;
const minEditorFontSize = 10; const minEditorFontSize = 10;
const maxEditorFontSize = 32; const maxEditorFontSize = 32;
function getEditorScrollSurface(): HTMLElement | HTMLTextAreaElement | null { function getEditorScrollSurface(): HTMLElement | null {
const sourceEditor = document.querySelector<HTMLTextAreaElement>('.source-editor'); const sourceEditor = document.querySelector<HTMLElement>('.source-editor .cm-scroller');
if (sourceEditor && getComputedStyle(sourceEditor).display !== 'none') return sourceEditor; if (sourceEditor && sourceEditor.clientHeight > 0) return sourceEditor;
return document.querySelector<HTMLElement>('.editor-body'); return document.querySelector<HTMLElement>('.editor-body');
} }
function preserveEditorViewportAfterLayout(scrollSurface: HTMLElement | HTMLTextAreaElement | null) { function preserveEditorViewportAfterLayout(scrollSurface: HTMLElement | null) {
if (!scrollSurface) return () => {}; if (!scrollSurface) return () => {};
const isSourceEditor = scrollSurface instanceof HTMLTextAreaElement; const isSourceEditor = scrollSurface.classList.contains('cm-scroller');
const maxScroll = scrollSurface.scrollHeight - scrollSurface.clientHeight; const maxScroll = scrollSurface.scrollHeight - scrollSurface.clientHeight;
const scrollRatio = maxScroll > 0 ? scrollSurface.scrollTop / maxScroll : 0; const scrollRatio = maxScroll > 0 ? scrollSurface.scrollTop / maxScroll : 0;
const rect = scrollSurface.getBoundingClientRect(); const rect = scrollSurface.getBoundingClientRect();
@@ -98,10 +124,15 @@
}; };
const handleWheel = (event: WheelEvent) => { const handleWheel = (event: WheelEvent) => {
if (!event.ctrlKey && !event.metaKey) return; const action = getWheelFontSizeAction(
event,
$appConfig?.scroll_to_change_font_size ?? true
);
if (action === 'ignore') return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
zoomEditor(event.deltaY < 0 ? 1 : -1); if (action === 'increase') zoomEditor(1);
else if (action === 'decrease') zoomEditor(-1);
}; };
window.addEventListener('keydown', handleKeydown); window.addEventListener('keydown', handleKeydown);
@@ -114,23 +145,47 @@
} }
onMount(async () => { onMount(async () => {
if (!isMobile) {
startupRevealTimer = setTimeout(() => void revealStartupWindow(), STARTUP_REVEAL_FAILSAFE_MS);
}
// Check for note window mode // Check for note window mode
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
const notePath = params.get('note'); const notePath = params.get('note');
if (notePath) { if (notePath) {
noteWindowPath = notePath; noteWindowPath = notePath;
noteWindowVault = params.get('vault');
} }
try { try {
const config = await getAppConfig(); const config = await getAppConfig();
if (noteWindowPath) {
const origin = config.vaults.find(vault => vault.path === noteWindowVault);
if (noteWindowVault && (origin || config.active_vault === noteWindowVault)) {
// This is window-local state, not a native vault switch.
config.active_vault = noteWindowVault;
config.active_bookmark_id = origin?.bookmark_id ?? null;
} else {
noteWindowPath = null;
noteWindowVault = null;
startupVaultError = 'This note window’s vault is no longer available. Choose a vault to continue.';
}
}
$appConfig = config; $appConfig = config;
removeFontSizeListener = await listen<number>('editor-font-size-changed', (event) => { removeFontSizeListener = await listen<number>('editor-font-size-changed', (event) => {
if ($appConfig?.font_size !== event.payload) applyEditorFontSize(event.payload); if ($appConfig?.font_size !== event.payload) applyEditorFontSize(event.payload);
}); });
removeScrollFontSizeListener = await listen<boolean>('scroll-to-change-font-size-changed', (event) => {
if ($appConfig) $appConfig.scroll_to_change_font_size = event.payload;
});
$theme = config.theme || 'system'; $theme = config.theme || 'system';
// Apply theme immediately to prevent flash // Apply theme immediately to prevent flash. Runs before the stores settle, so resolve
const themeValue = config.theme || 'system'; // "system" against the configured pair here the same way resolvedTheme does.
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const rawTheme = config.theme || 'system';
const themeValue = rawTheme === 'system'
? (prefersDark ? config.system_dark_theme || 'dark' : config.system_light_theme || 'light')
: rawTheme;
const root = document.documentElement; const root = document.documentElement;
const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark']; const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark'];
root.classList.remove('dark'); root.classList.remove('dark');
@@ -138,7 +193,7 @@
if (namedThemes.includes(themeValue)) { if (namedThemes.includes(themeValue)) {
root.setAttribute('data-theme', themeValue); root.setAttribute('data-theme', themeValue);
if (darkThemes.includes(themeValue)) root.classList.add('dark'); if (darkThemes.includes(themeValue)) root.classList.add('dark');
} else if (themeValue === 'dark' || (themeValue === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) { } else if (themeValue === 'dark') {
root.classList.add('dark'); root.classList.add('dark');
} }
@@ -166,8 +221,8 @@
} }
// Apply saved accent // Apply saved accent
if (config.accent_color) { if (config.accent_color) {
const themeVal = config.theme || 'light'; const customTheme = config.custom_themes.find(theme => theme.id === themeValue);
const isDark = darkThemes.includes(themeVal) || (themeVal === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches); const isDark = darkThemes.includes(themeValue) || (customTheme?.is_dark ?? false);
let color: string | null = null; let color: string | null = null;
if (config.accent_color.startsWith('#')) { if (config.accent_color.startsWith('#')) {
color = config.accent_color; color = config.accent_color;
@@ -209,6 +264,7 @@
console.error('Failed to apply interface scale:', e); console.error('Failed to apply interface scale:', e);
} }
} }
await revealStartupWindow();
removeEditorZoomShortcuts = installEditorZoomShortcuts(); removeEditorZoomShortcuts = installEditorZoomShortcuts();
// Auto-open last vault if available // Auto-open last vault if available
@@ -230,8 +286,10 @@
} }
$vaultReady = true; $vaultReady = true;
} catch (e) { } catch (e) {
if (isIOS && activeVault?.bookmark_id) { $vaultReady = false;
startupVaultError = String(e); startupVaultError = `Could not open the last vault: ${String(e)}`;
// A saved path is not proof that the vault was initialized.
// Do not let the picker navigate back into a failed startup.
$appConfig = { $appConfig = {
...config, ...config,
active_vault: null, active_vault: null,
@@ -239,17 +297,24 @@
}; };
} }
} }
}
} catch { } catch {
// First launch or no config // First launch or no config
} } finally {
loading = false; loading = false;
await revealStartupWindow();
if (startupRevealTimer) {
clearTimeout(startupRevealTimer);
startupRevealTimer = null;
}
}
}); });
onDestroy(() => { onDestroy(() => {
removeEditorZoomShortcuts?.(); removeEditorZoomShortcuts?.();
removeFontSizeListener?.(); removeFontSizeListener?.();
removeScrollFontSizeListener?.();
if (fontSizeSaveTimer) clearTimeout(fontSizeSaveTimer); if (fontSizeSaveTimer) clearTimeout(fontSizeSaveTimer);
if (startupRevealTimer) clearTimeout(startupRevealTimer);
}); });
</script> </script>
@@ -258,7 +323,7 @@
<div class="spinner"></div> <div class="spinner"></div>
</div> </div>
{:else if noteWindowPath} {:else if noteWindowPath}
<NoteWindow notePath={noteWindowPath} /> <NoteWindow notePath={noteWindowPath} vaultPath={noteWindowVault} />
{:else if $vaultReady} {:else if $vaultReady}
<AppLayout /> <AppLayout />
{:else} {:else}
+150
View File
@@ -0,0 +1,150 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, TextSelection } from '@tiptap/pm/state';
import { history, undo, redo } from '@tiptap/pm/history';
import { common, createLowlight } from 'lowlight';
import { createCodeBlockHighlightPlugin } from '../src/lib/editor/extensions/cachedCodeBlockLowlight.ts';
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { content: 'text*', group: 'block' },
blockquote: { content: 'block+', group: 'block' },
codeBlock: { content: 'text*', group: 'block', code: true, attrs: { language: { default: null } } },
text: { group: 'inline' },
},
});
function codeBlock(text, language = 'javascript') {
return schema.node('codeBlock', { language }, text ? schema.text(text) : null);
}
function setup(blocks, defaultLanguage = 'text') {
const lowlight = createLowlight(common);
const calls = [];
const plugin = createCodeBlockHighlightPlugin({
defaultLanguage,
lowlight: {
...lowlight,
highlight(language, text) {
calls.push({ language, text });
return lowlight.highlight(language, text);
},
highlightAuto(text) {
calls.push({ language: 'auto', text });
return lowlight.highlightAuto(text);
},
},
});
const state = EditorState.create({ schema, doc: schema.node('doc', null, blocks), plugins: [history(), plugin] });
return { state, plugin, calls };
}
function keywordRanges(plugin, state) {
return plugin.getState(state).decorations.find()
.filter((decoration) => decoration.type.attrs.class.split(' ').includes('hljs-keyword'))
.map(({ from, to }) => ({ from, to, text: state.doc.textBetween(from, to) }));
}
function expectedKeywords(doc) {
const ranges = [];
doc.descendants((node, pos) => {
if (node.type.name === 'codeBlock' && node.attrs.language === 'javascript') {
const offset = node.textContent.indexOf('const');
if (offset >= 0) ranges.push({ from: pos + 1 + offset, to: pos + 6 + offset, text: 'const' });
}
});
return ranges;
}
test('typing highlights only the changed block; selection-only transactions reuse plugin state', () => {
const fixture = setup(Array.from({ length: 80 }, (_, i) => codeBlock(`const item${i} = 1;`)));
let { state } = fixture;
const { plugin, calls } = fixture;
assert.equal(calls.length, 80);
calls.length = 0;
state = state.apply(state.tr.insertText('2', 1 + 'const item0 = 1'.length));
assert.deepEqual(calls, [{ language: 'javascript', text: 'const item0 = 12;' }]);
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
calls.length = 0;
const beforeSelection = plugin.getState(state);
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, state.doc.content.size - 1)));
assert.equal(plugin.getState(state), beforeSelection);
assert.deepEqual(calls, []);
});
test('insertions, moves, nested blocks, and deletions keep cached spans at their new positions', () => {
const first = codeBlock('const first = 1;');
const second = codeBlock('const second = 2;');
const fixture = setup([first, schema.node('blockquote', null, [second])]);
let { state } = fixture;
const { plugin, calls } = fixture;
calls.length = 0;
const prefix = schema.node('paragraph', null, schema.text('Inserted before code'));
state = state.apply(state.tr.insert(0, prefix));
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
const move = state.tr.delete(prefix.nodeSize, prefix.nodeSize + first.nodeSize);
move.insert(move.doc.content.size, first);
state = state.apply(move);
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
state = state.apply(state.tr.delete(prefix.nodeSize, prefix.nodeSize + second.nodeSize + 2));
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
assert.deepEqual(calls, []);
});
test('language changes, code-to-paragraph conversion, and full replacement discard obsolete decorations', () => {
const original = codeBlock('const value = 1;');
const fixture = setup([original, codeBlock('const other = 2;')]);
let { state } = fixture;
const { plugin, calls } = fixture;
calls.length = 0;
state = state.apply(state.tr.setNodeMarkup(0, undefined, { language: 'text' }));
assert.deepEqual(calls, [{ language: 'text', text: original.textContent }]);
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
calls.length = 0;
state = state.apply(state.tr.setNodeMarkup(original.nodeSize, schema.nodes.paragraph));
assert.deepEqual(plugin.getState(state).decorations.find(), []);
assert.deepEqual(calls, []);
state = state.apply(state.tr.replaceWith(0, state.doc.content.size, original));
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
assert.deepEqual(calls, [], 'reused immutable nodes retain their relative highlighting');
});
test('undo and redo restore token ranges without highlighting unrelated blocks', () => {
const fixture = setup([codeBlock('const first = 1;'), codeBlock('const second = 2;')]);
let { state } = fixture;
const { plugin, calls } = fixture;
const before = state.doc;
state = state.apply(state.tr.insertText('/*new*/ ', 1));
const after = state.doc;
calls.length = 0;
assert.equal(undo(state, (transaction) => { state = state.apply(transaction); }), true);
assert.ok(state.doc.eq(before));
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
assert.ok(calls.length <= 1);
assert.ok(calls.every(({ text }) => text === 'const first = 1;'));
calls.length = 0;
assert.equal(redo(state, (transaction) => { state = state.apply(transaction); }), true);
assert.ok(state.doc.eq(after));
assert.deepEqual(keywordRanges(plugin, state), expectedKeywords(state.doc));
assert.ok(calls.length <= 1);
assert.ok(calls.every(({ text }) => text === '/*new*/ const first = 1;'));
});
test('cache ownership respects highlighter/default-language boundaries and empty blocks', () => {
const shared = codeBlock('const value = 1;', null);
const javascript = setup([shared], 'javascript');
const plaintext = setup([shared], 'text');
assert.equal(javascript.plugin.getState(javascript.state).decorations.find()[0].type.attrs.class, 'hljs-keyword');
assert.deepEqual(plaintext.plugin.getState(plaintext.state).decorations.find(), []);
const empty = codeBlock('');
const fixture = setup([empty]);
let { state } = fixture;
fixture.calls.length = 0;
state = state.apply(state.tr.insert(0, schema.node('paragraph')));
assert.deepEqual(fixture.calls, []);
state = state.apply(state.tr.insertText('const x = 1;', 3));
assert.deepEqual(fixture.calls, [{ language: 'javascript', text: 'const x = 1;' }]);
assert.deepEqual(keywordRanges(fixture.plugin, state), expectedKeywords(state.doc));
});
+43
View File
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, TextSelection } from '@tiptap/pm/state';
import { buildTaskMetaDecorations, focusedPlaceholderDecorations } from '../src/lib/editor/decorations.ts';
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { group: 'block', content: 'inline*' },
taskList: { group: 'block', content: 'taskItem+' },
taskItem: { content: 'paragraph block*' },
text: { group: 'inline' },
},
marks: { bold: {} },
});
const p = (value = '') => schema.node('paragraph', null, value ? schema.text(value) : undefined);
const item = (...children) => schema.node('taskItem', null, children);
const list = (...items) => schema.node('taskList', null, items);
test('task decorations include nested tasks once, but never style ordinary prose tokens', () => {
const doc = schema.node('doc', null, [
p('ordinary !high due:2026-09-27'),
list(item(p('parent !low'), list(item(p('nested !high due:2026-09-28')))), item(p('sibling !med'))),
p('ordinary !low'),
]);
const tokens = buildTaskMetaDecorations(doc).find().map(({ from, to }) => doc.textBetween(from, to));
assert.deepEqual(tokens, ['!low', '!high', 'due:2026-09-28', '!med']);
assert.deepEqual(buildTaskMetaDecorations(schema.node('doc', null, [p('!high'), p('due:2026-09-27')])).find(), []);
});
test('placeholder follows an empty nested paragraph and disappears when that paragraph gains content', () => {
const doc = schema.node('doc', null, [p('before'), list(item(p()))]);
let emptyPosition;
doc.descendants((node, pos) => { if (node.type.name === 'paragraph' && !node.content.size) emptyPosition = pos; });
let state = EditorState.create({ doc, selection: TextSelection.create(doc, emptyPosition + 1) });
const decorations = focusedPlaceholderDecorations(state).find();
assert.deepEqual(decorations.map(({ from, to }) => [from, to]), [[emptyPosition, emptyPosition + 2]]);
state = state.apply(state.tr.insertText('written'));
assert.deepEqual(focusedPlaceholderDecorations(state).find(), []);
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1)));
assert.deepEqual(focusedPlaceholderDecorations(state).find(), []);
});
+77
View File
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Schema } from '@tiptap/pm/model';
import { findDocumentMatches, findSourceMatches, closestSearchMatch } from '../src/lib/editor/search.ts';
const options = { matchCase: false, wholeWord: false };
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { group: 'block', content: 'inline*' },
text: { group: 'inline' },
hard_break: { group: 'inline', inline: true },
image: { group: 'inline', inline: true, atom: true },
},
marks: { bold: {}, italic: {} },
});
const text = (value, marks = []) => schema.text(value, marks.map((name) => schema.mark(name)));
const paragraph = (...children) => schema.node('paragraph', null, children);
const doc = (...children) => schema.node('doc', null, children);
test('rich phrases span adjacent text nodes regardless of formatting', () => {
const document = doc(paragraph(text('A '), text('formatted', ['bold']), text(' phrase repeats. A formatted phrase repeats.')));
const results = findDocumentMatches(document, 'formatted phrase', options);
assert.deepEqual(results, [{ from: 3, to: 19 }, { from: 31, to: 47 }]);
assert.deepEqual(results.map(({ from, to }) => document.textBetween(from, to)), ['formatted phrase', 'formatted phrase']);
});
test('rich search does not bridge paragraphs, hard breaks or inline atoms', () => {
for (const document of [
doc(paragraph(text('hello ')), paragraph(text('world'))),
doc(paragraph(text('hello '), schema.node('hard_break'), text('world'))),
doc(paragraph(text('hello '), schema.node('image'), text('world'))),
]) assert.deepEqual(findDocumentMatches(document, 'hello world', options), []);
});
test('Unicode case folding keeps original UTF-16 positions and supplementary letters intact', () => {
const source = 'İ 😀 FoO 𐐀 Σςσ K';
assert.deepEqual(findSourceMatches(source, 'foo', options), [{ from: 5, to: 8 }]);
assert.deepEqual(findSourceMatches(source, '𐐨', options), [{ from: 9, to: 11 }]);
assert.deepEqual(findSourceMatches(source, 'σ', options), [{ from: 12, to: 13 }, { from: 13, to: 14 }, { from: 14, to: 15 }]);
assert.deepEqual(findSourceMatches(source, 'k', options), [{ from: 16, to: 17 }]);
const document = doc(paragraph(text('İ 😀 '), text('FoO', ['italic'])));
assert.deepEqual(findDocumentMatches(document, 'foo', options), [{ from: 6, to: 9 }]);
});
test('case-sensitive matches retain literal punctuation and overlapping occurrences', () => {
assert.deepEqual(findSourceMatches('Foo foo FOO', 'foo', { ...options, matchCase: true }), [{ from: 4, to: 7 }]);
assert.deepEqual(findSourceMatches('a.b a?b a.b', 'a.b', options), [{ from: 0, to: 3 }, { from: 8, to: 11 }]);
assert.deepEqual(findSourceMatches('banana', 'ana', options), [{ from: 1, to: 4 }, { from: 3, to: 6 }]);
assert.deepEqual(findSourceMatches('😀😀😀', '😀😀', options), [{ from: 0, to: 4 }, { from: 2, to: 6 }]);
assert.deepEqual(findSourceMatches('anything', '', options), []);
});
test('whole-word boundaries include Unicode letters, marks, numbers and connectors', () => {
const source = 'cat scatter cat_ cat2 écat caté cat\u0301 cat\u200d (cat) 😀cat😀';
const results = findSourceMatches(source, 'cat', { ...options, wholeWord: true });
assert.deepEqual(results.map(({ from }) => from), [0, source.indexOf('(cat)') + 1, source.indexOf('😀cat😀') + 2]);
assert.deepEqual(findSourceMatches('中文 中文字', '中文', options), [{ from: 0, to: 2 }, { from: 3, to: 5 }]);
assert.deepEqual(findSourceMatches('中文 中文字', '中文', { ...options, wholeWord: true }), [{ from: 0, to: 2 }]);
const document = doc(paragraph(text('cat'), text('apult', ['bold']), text(' cat')));
assert.deepEqual(findDocumentMatches(document, 'cat', { ...options, wholeWord: true }), [{ from: 10, to: 13 }]);
});
test('rescanning edited documents adds and removes occurrences without changing documents', () => {
const before = doc(paragraph(text('word WORD')));
const after = doc(paragraph(text('word WORD word')));
assert.deepEqual(findDocumentMatches(before, 'word', options), [{ from: 1, to: 5 }, { from: 6, to: 10 }]);
const results = findDocumentMatches(after, 'word', options);
assert.deepEqual(results, [{ from: 1, to: 5 }, { from: 6, to: 10 }, { from: 11, to: 15 }]);
assert.equal(closestSearchMatch(results, 6), 1);
assert.equal(closestSearchMatch(results, 8), 2);
assert.equal(closestSearchMatch(results, 100), 2);
assert.equal(closestSearchMatch([], 100), 0);
assert.equal(before.textContent, 'word WORD');
assert.equal(after.textContent, 'word WORD word');
});
+118
View File
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import MarkdownIt from 'markdown-it';
import { Schema } from '@tiptap/pm/model';
import { transformWithEsbuild } from 'vite';
const source = await readFile(
new URL('../src/lib/editor/markdown.ts', import.meta.url),
'utf8'
);
const { code } = await transformWithEsbuild(source, 'markdown.ts', {
loader: 'ts',
format: 'esm',
target: 'esnext'
});
const { serializeInlineMarkdown } = await import(
`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
);
// Link intentionally precedes formatting marks in the schema. This matches the
// mark order produced by the app and reproduces the original per-text-node bug.
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { content: 'text*', group: 'block' },
text: { group: 'inline' }
},
marks: {
link: { attrs: { href: {} } },
bold: {},
italic: {},
wikiLink: {
attrs: {
title: { default: null },
aliased: { default: false }
}
}
}
});
const markdown = new MarkdownIt({ html: true, linkify: false, breaks: false });
const bold = schema.marks.bold.create();
const italic = schema.marks.italic.create();
const link = schema.marks.link.create({ href: 'https://example.com' });
function paragraph(segments) {
return schema.node(
'paragraph',
null,
segments.map(({ text, marks }) => schema.text(text, marks))
);
}
function assertMarkdown(segments, expected, expectedHtml) {
const serialized = serializeInlineMarkdown(paragraph(segments));
assert.equal(serialized, expected);
assert.equal(markdown.render(serialized), `${expectedHtml}\n`);
}
test('keeps bold open when a link ends the marked span', () => {
assertMarkdown(
[
{ text: 'Bold ', marks: [bold] },
{ text: 'link', marks: [link, bold] }
],
'**Bold [link](https://example.com)**',
'<p><strong>Bold <a href="https://example.com">link</a></strong></p>'
);
});
test('keeps bold open when a link starts the marked span', () => {
assertMarkdown(
[
{ text: 'link', marks: [link, bold] },
{ text: ' bold', marks: [bold] }
],
'**[link](https://example.com) bold**',
'<p><strong><a href="https://example.com">link</a> bold</strong></p>'
);
});
test('keeps one bold span around a link in the middle', () => {
assertMarkdown(
[
{ text: 'Before ', marks: [bold] },
{ text: 'link', marks: [link, bold] },
{ text: ' after', marks: [bold] }
],
'**Before [link](https://example.com) after**',
'<p><strong>Before <a href="https://example.com">link</a> after</strong></p>'
);
});
test('keeps nested bold and italic marks open across a link', () => {
assertMarkdown(
[
{ text: 'Nested ', marks: [bold, italic] },
{ text: 'link', marks: [link, bold, italic] },
{ text: ' marks', marks: [bold, italic] }
],
'***Nested [link](https://example.com) marks***',
'<p><em><strong>Nested <a href="https://example.com">link</a> marks</strong></em></p>'
);
});
test('preserves wiki-link aliases inside a bold span', () => {
const wikiLink = schema.marks.wikiLink.create({ title: 'Target note', aliased: true });
const serialized = serializeInlineMarkdown(
paragraph([
{ text: 'See ', marks: [bold] },
{ text: 'this note', marks: [wikiLink, bold] },
{ text: ' now', marks: [bold] }
])
);
assert.equal(serialized, '**See [[Target note|this note]] now**');
});
+115
View File
@@ -0,0 +1,115 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { createContext, Script } from 'node:vm';
import { compile, parse } from 'svelte/compiler';
import { get, writable } from 'svelte/store';
const source = await readFile(
new URL('../src/lib/components/Sidebar.svelte', import.meta.url),
'utf8'
);
const ast = parse(source, { modern: true });
function elementWithClass(nodes, className) {
return nodes.find((node) => node.attributes?.some((attribute) =>
attribute.name === 'class' && attribute.value[0]?.data === className
));
}
const aside = elementWithClass(ast.fragment.nodes, 'sidebar');
const blocks = aside.fragment.nodes.filter((node) => node.type === 'IfBlock');
const content = blocks.find((node) => elementWithClass(node.consequent.nodes, 'section'));
const header = blocks.find((node) => elementWithClass(node.consequent.nodes, 'sidebar-header'));
const toggle = elementWithClass(
elementWithClass(header.consequent.nodes, 'sidebar-header').fragment.nodes,
'collapse-btn'
);
function expressionScript(expression) {
assert.ok(expression, 'expected a component expression');
return new Script(`(${source.slice(expression.start, expression.end)})`);
}
// Execute the actual template conditions, not a copy of the collapse logic.
const expressions = {
contentVisible: expressionScript(content.test),
collapsedClass: expressionScript(aside.attributes.find((attribute) =>
attribute.type === 'ClassDirective' && attribute.name === 'collapsed'
).expression),
toggleVisible: expressionScript(header.test)
};
const toggleScript = expressionScript(
toggle.attributes.find((attribute) => attribute.name === 'onclick').value.expression
);
function sidebarContext(isMobile, stored) {
const sidebarCollapsed = writable(stored);
const context = createContext({
isMobile,
get $sidebarCollapsed() { return get(sidebarCollapsed); },
set $sidebarCollapsed(value) { sidebarCollapsed.set(value); }
});
return { context, sidebarCollapsed };
}
function evaluate(context) {
return Object.fromEntries(Object.entries(expressions).map(([name, script]) =>
[name, script.runInContext(context)]
));
}
const scenarios = [
{
platform: 'desktop', isMobile: false,
expanded: { contentVisible: true, collapsedClass: false, toggleVisible: true },
collapsed: { contentVisible: false, collapsedClass: true, toggleVisible: true }
},
{
platform: 'mobile', isMobile: true,
expanded: { contentVisible: true, collapsedClass: false, toggleVisible: false },
collapsed: { contentVisible: true, collapsedClass: false, toggleVisible: false }
}
];
for (const scenario of scenarios) {
for (const stored of [false, true]) {
test(`${scenario.platform} navigation with stored sidebar_collapsed=${stored}`, () => {
const { context, sidebarCollapsed } = sidebarContext(scenario.isMobile, stored);
assert.deepEqual(evaluate(context), stored ? scenario.collapsed : scenario.expanded);
assert.equal(get(sidebarCollapsed), stored, 'rendering must preserve the stored preference');
});
}
test(`${scenario.platform} navigation follows late false -> true -> false store updates`, () => {
const { context, sidebarCollapsed } = sidebarContext(scenario.isMobile, false);
assert.deepEqual(evaluate(context), scenario.expanded);
sidebarCollapsed.set(true);
assert.deepEqual(evaluate(context), scenario.collapsed);
assert.equal(get(sidebarCollapsed), true, 'rendering must not reset the loaded preference');
sidebarCollapsed.set(false);
assert.deepEqual(evaluate(context), scenario.expanded);
assert.equal(get(sidebarCollapsed), false);
});
}
test('desktop collapse toggle still collapses and expands the sidebar', () => {
const { context, sidebarCollapsed } = sidebarContext(false, false);
const toggleSidebar = toggleScript.runInContext(context);
toggleSidebar();
assert.equal(get(sidebarCollapsed), true);
assert.deepEqual(evaluate(context), scenarios[0].collapsed);
toggleSidebar();
assert.equal(get(sidebarCollapsed), false);
assert.deepEqual(evaluate(context), scenarios[0].expanded);
});
test('Sidebar compiles for the client', () => {
assert.doesNotThrow(() => compile(source, {
filename: 'src/lib/components/Sidebar.svelte',
generate: 'client'
}));
});
+32
View File
@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const { compareNaturalNames } = await import(
new URL('../src/lib/utils/natural-sort.ts', import.meta.url)
);
test('sorts numeric name segments by numeric value', () => {
const names = ['10g', '11g', '12g', '5g', '6g', '7g', '8g', '9g'];
assert.deepEqual(names.sort(compareNaturalNames), [
'5g',
'6g',
'7g',
'8g',
'9g',
'10g',
'11g',
'12g'
]);
});
test('sorts numbers naturally wherever they appear in a name', () => {
const names = ['Class 10b', 'Class 2b', 'Class 10a', 'Class 2a'];
assert.deepEqual(names.sort(compareNaturalNames), [
'Class 2a',
'Class 2b',
'Class 10a',
'Class 10b'
]);
});
+143
View File
@@ -0,0 +1,143 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { transformWithEsbuild } from 'vite';
const source = await readFile(
new URL('../src/lib/utils/paths.ts', import.meta.url),
'utf8'
);
const { code } = await transformWithEsbuild(source, 'paths.ts', {
loader: 'ts',
format: 'esm',
target: 'esnext'
});
const {
assetSourceToMarkdown,
assetUrlToLocalPath,
normalizeLocalAssetPath,
isPathInDirectory,
isTrashedNote,
resolvePathFromFile,
resolveVaultFilePath
} = await import(
`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
);
test('resolves note links relative to Windows note paths', () => {
assert.equal(
resolvePathFromFile('C:\\Vault\\Current.md', './Target.md'),
'C:/Vault/Target.md'
);
assert.equal(
resolvePathFromFile('C:\\Vault\\Folder\\Current.md', '../Target.md'),
'C:/Vault/Target.md'
);
assert.equal(
resolvePathFromFile('\\\\server\\share\\Folder\\Current.md', '../Target.md'),
'//server/share/Target.md'
);
});
test('preserves Linux relative note-link resolution', () => {
assert.equal(
resolvePathFromFile('/vault/folder/Current.md', '../Target.md'),
'/vault/Target.md'
);
});
test('converts Windows asset URLs back to portable attachment paths', () => {
assert.equal(
normalizeLocalAssetPath('/C:\\Users\\user\\Vault\\image.png'),
'C:/Users/user/Vault/image.png'
);
assert.equal(
assetSourceToMarkdown(
'http://asset.localhost/C%3A%5CUsers%5Cuser%5CVault%5C.helixnotes%5Cattachments%5Cimage.png',
'C:\\Users\\user\\Vault\\Note.md',
'C:\\Users\\user\\Vault'
),
'.helixnotes/attachments/image.png'
);
});
test('preserves portable asset paths on Linux and macOS', () => {
assert.equal(
assetSourceToMarkdown(
'asset://localhost/%2Fhome%2Fuser%2FVault%2F.helixnotes%2Fattachments%2Fimage.png',
'/home/user/Vault/Note.md',
'/home/user/Vault'
),
'.helixnotes/attachments/image.png'
);
assert.equal(
assetSourceToMarkdown(
'asset://localhost/%2FUsers%2Fuser%2FVault%2Fassets%2Fimage.png',
'/Users/user/Vault/notes/Note.md',
'/Users/user/Vault'
),
'../assets/image.png'
);
assert.equal(
assetSourceToMarkdown('../assets/image.png', '/vault/notes/Note.md', '/vault'),
'../assets/image.png'
);
});
test('decodes local asset URLs without damaging platform roots', () => {
assert.equal(
assetUrlToLocalPath('http://asset.localhost/C%3A%5CUsers%5Cuser%5CVault%5Cimage.png'),
'C:/Users/user/Vault/image.png'
);
assert.equal(
assetUrlToLocalPath('asset://localhost/%2Fhome%2Fuser%2FVault%2Fimage.png'),
'/home/user/Vault/image.png'
);
assert.equal(
assetUrlToLocalPath('http://asset.localhost/%5C%5Cserver%5Cshare%5CVault%5Cimage.png'),
'//server/share/Vault/image.png'
);
});
test('resolves vault files consistently across platforms', () => {
assert.equal(
resolveVaultFilePath('../assets/image.png', 'C:\\Vault\\notes\\Note.md', 'C:\\Vault'),
'C:/Vault/assets/image.png'
);
assert.equal(
resolveVaultFilePath('.helixnotes/attachments/image.png', 'C:\\Vault\\notes\\Note.md', 'C:\\Vault'),
'C:/Vault/.helixnotes/attachments/image.png'
);
assert.equal(
resolveVaultFilePath('../assets/image.png', '/vault/notes/Note.md', '/vault'),
'/vault/assets/image.png'
);
assert.equal(
resolveVaultFilePath('../assets/image.png', '\\\\server\\share\\Vault\\notes\\Note.md', '\\\\server\\share\\Vault'),
'//server/share/Vault/assets/image.png'
);
});
test('restored Windows and UNC notes remain vault-owned across separator and case differences', () => {
assert.equal(isPathInDirectory('C:\\NOTES\\Alpha.md', 'c:\\Notes\\'), true);
assert.equal(isPathInDirectory('C:/Notes/Folder/Alpha.md', 'C:\\Notes'), true);
assert.equal(isPathInDirectory('\\\\SERVER\\SHARE\\Notes\\Alpha.md', '//server/share/notes/'), true);
});
test('vault ownership normalizes trailing separators and dot segments without accepting siblings', () => {
assert.equal(isPathInDirectory('/vault/folder/../Alpha.md', '/vault/'), true);
assert.equal(isPathInDirectory('/vault/folder/../../Outside.md', '/vault'), false);
assert.equal(isPathInDirectory('/vault-extra/Alpha.md', '/vault'), false);
assert.equal(isPathInDirectory('D:\\Notes\\Alpha.md', 'C:\\Notes'), false);
assert.equal(isPathInDirectory('/Vault/Alpha.md', '/vault'), false);
assert.equal(isPathInDirectory('/vault/Alpha.md', null), false);
});
test('trash previews are protected without blocking ordinary notebooks or other vaults', () => {
assert.equal(isTrashedNote('/vault/.helixnotes/trash/deleted.md', '/vault'), true);
assert.equal(isTrashedNote('C:\\Vault\\.helixnotes\\trash\\deleted.md', 'c:/vault/'), true);
assert.equal(isTrashedNote('/vault/Trash/note.md', '/vault'), false);
assert.equal(isTrashedNote('/vault/.helixnotes/trash-backup/note.md', '/vault'), false);
assert.equal(isTrashedNote('/other/.helixnotes/trash/deleted.md', '/vault'), false);
assert.equal(isTrashedNote(null, '/vault'), false);
});
+182
View File
@@ -0,0 +1,182 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
resolveSearchTarget,
visibleSearchTarget,
} from '../src/lib/editor/search-target.ts';
function targetIn(source, text, before = '', after = '', from = source.indexOf(text)) {
return Object.freeze({ field: 'body', start: from, end: from + text.length, text, before, after });
}
function rangeIn(source, text) {
const from = source.indexOf(text);
return Object.freeze({ from, to: from + text.length });
}
test('recorded UTF-16 offsets require exact source text and surrounding context', () => {
const source = 'prefix Needle suffix / prefix Needle suffix';
const target = targetIn(source, 'Needle', 'prefix ', ' suffix', source.lastIndexOf('Needle'));
assert.deepEqual(resolveSearchTarget(source, target), { from: target.start, to: target.end });
assert.equal(resolveSearchTarget(source.toLowerCase(), target), null);
});
test('relocates a unique full anchor rather than the first occurrence of its text', () => {
const original = 'prefix needle suffix';
const target = targetIn(original, 'needle', 'prefix ', ' suffix');
const changed = 'needle without context\nnew paragraph\n' + original;
const resolved = resolveSearchTarget(changed, target);
assert.deepEqual(resolved, { from: changed.lastIndexOf('needle'), to: changed.lastIndexOf('needle') + 6 });
assert.equal(changed.slice(resolved.from, resolved.to), target.text);
});
test('does not choose an ambiguous relocated anchor or overlapping occurrence', () => {
const original = 'prefix needle suffix';
assert.equal(resolveSearchTarget('moved\n' + original + '\n' + original,
targetIn(original, 'needle', 'prefix ', ' suffix')), null);
assert.equal(resolveSearchTarget('x banana', targetIn('ana', 'ana')), null);
});
test('removed matches and changed context do not fall back to a remaining word', () => {
const original = 'prefix needle suffix';
const target = targetIn(original, 'needle', 'prefix ', ' suffix');
for (const changed of [
'prefix removed suffix',
'prefix removed suffix / different needle context',
'PREFIX needle suffix',
'prefix needle SUFFIX',
]) assert.equal(resolveSearchTarget(changed, target), null);
});
test('an entire-field anchor can move only when its exact text is unique', () => {
const target = targetIn('needle', 'needle');
assert.deepEqual(resolveSearchTarget('new needle', target), { from: 4, to: 10 });
assert.equal(resolveSearchTarget('new needle needle', target), null);
});
test('Unicode anchors preserve exact supplementary characters and source offsets', () => {
const original = '😀 prefix 𐐀needle tail 😃';
const target = targetIn(original, '𐐀needle', '😀 prefix ', ' tail 😃');
const changed = 'intro 🧭\n' + original;
assert.deepEqual(resolveSearchTarget(original, target), { from: target.start, to: target.end });
assert.deepEqual(resolveSearchTarget(changed, target), {
from: changed.indexOf('𐐀needle'), to: changed.indexOf('𐐀needle') + '𐐀needle'.length,
});
assert.equal(resolveSearchTarget(changed.replace('𐐀', '𐐨'), target), null);
});
test('invalid offsets and split-surrogate targets never produce a range', () => {
const source = '😀 needle 😃';
const target = targetIn(source, 'needle', '😀 ', ' 😃');
for (const invalid of [
{ ...target, start: -1 },
{ ...target, start: 3.5 },
{ ...target, end: NaN },
{ ...target, end: target.end + 1 },
{ ...target, text: '', end: target.start },
{ ...target, before: '\ude00 ' },
{ ...target, after: ' \ud83d' },
targetIn(source, '\ud83d', '', '', 0),
targetIn(source, '\ude00', '', '', 1),
]) assert.equal(resolveSearchTarget(source, invalid), null);
assert.equal(resolveSearchTarget('😀', targetIn('\ud83d', '\ud83d')), null);
});
test('CRLF anchors resolve against LF text without retaining old line offsets', () => {
const original = 'lead\r\nprefix\r\nneedle\r\nsuffix\r\nend';
const target = targetIn(original, 'needle\r\nsuffix', '\r\nprefix\r\n', '\r\nend');
const normalized = original.replaceAll('\r\n', '\n');
assert.deepEqual(resolveSearchTarget(original, target), { from: target.start, to: target.end });
assert.deepEqual(resolveSearchTarget(normalized, target), {
from: normalized.indexOf('needle'), to: normalized.indexOf('\nend'),
});
const lfTarget = targetIn(normalized, 'needle\nsuffix', '\nprefix\n', '\nend');
assert.deepEqual(resolveSearchTarget(original, lfTarget), { from: target.start, to: target.end });
});
test('line-ending equivalence cannot make a duplicated relocated anchor unique', () => {
const original = 'prefix\r\nneedle\r\nsuffix';
const target = targetIn(original, 'needle', 'prefix\r\n', '\r\nsuffix');
assert.equal(resolveSearchTarget('moved\n' + original + '\n' + original.replaceAll('\r\n', '\n'), target), null);
});
test('a target boundary inside CRLF is not relocated into an LF-only document', () => {
const source = 'prefix\r\nneedle';
const target = targetIn(source, '\nneedle', 'prefix\r');
assert.equal(resolveSearchTarget(source.replaceAll('\r\n', '\n'), target), null);
});
test('visible source offsets remain unchanged without a matching hidden heading', () => {
const body = '# Note title\n\nBody 😀 match';
const match = rangeIn(body, '😀 match');
for (const [title, hideTitle] of [['Note title', false], ['Different title', true], [undefined, true]]) {
assert.deepEqual(visibleSearchTarget(body, title, hideTitle, match), { markdown: body, match, hiddenTitle: false });
}
const laterHeading = 'Intro\n\n# Note title\n\nBody match';
assert.deepEqual(visibleSearchTarget(laterHeading, 'Note title', true, rangeIn(laterHeading, 'match')), {
markdown: laterHeading, match: rangeIn(laterHeading, 'match'), hiddenTitle: false,
});
});
test('hidden H1 offsets include its following blank line but preserve body matches', () => {
const body = '# Note title\n\nBody 😀 match\n';
const markdown = 'Body 😀 match\n';
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, '😀 match')), {
markdown, match: rangeIn(markdown, '😀 match'), hiddenTitle: false,
});
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, 'Note title')), {
markdown, match: null, hiddenTitle: true,
});
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, 'title\n\nBody')), {
markdown, match: null, hiddenTitle: true,
});
});
test('leading blanks retain their positions while later body matches shift', () => {
const body = ' \n\n# Note title\n\nBody match';
const markdown = ' \n\nBody match';
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, 'match')), {
markdown, match: rangeIn(markdown, 'match'), hiddenTitle: false,
});
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, { from: 0, to: 1 }), {
markdown, match: { from: 0, to: 1 }, hiddenTitle: false,
});
});
test('title-only notes hide their range, including leading-blank and missing-newline cases', () => {
for (const body of ['# Note title', '# Note title\n', '\n\n# Note title', '\n\n# Note title\n']) {
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, 'Note title')), {
markdown: body.startsWith('\n\n') ? '\n' : '', match: null, hiddenTitle: true,
});
}
});
test('heading normalization preserves the existing matching-title behavior', () => {
const body = ' ### note—title \n\nBody match';
assert.deepEqual(visibleSearchTarget(body, 'Note_title', true, rangeIn(body, 'match')), {
markdown: 'Body match', match: { from: 5, to: 10 }, hiddenTitle: false,
});
});
test('CRLF and bare CR become CodeMirror LF offsets before title removal', () => {
const body = '\r\n# Note title\r\n\r\nBody 😀\r\nnext match\rend';
const markdown = '\nBody 😀\nnext match\nend';
assert.deepEqual(visibleSearchTarget(body, 'Note title', true, rangeIn(body, '😀\r\nnext match')), {
markdown, match: rangeIn(markdown, '😀\nnext match'), hiddenTitle: false,
});
const visibleHeading = body.replace(/\r\n?/g, '\n');
assert.deepEqual(visibleSearchTarget(body, 'Note title', false, rangeIn(body, 'match\rend')), {
markdown: visibleHeading, match: rangeIn(visibleHeading, 'match\nend'), hiddenTitle: false,
});
});
test('visible ranges reject split surrogate pairs, split CRLF and invalid bounds', () => {
const body = '😀\r\nword';
for (const match of [
{ from: 0, to: 1 }, { from: 1, to: 2 }, { from: 3, to: 5 },
{ from: 0, to: 3 }, { from: -1, to: 1 }, { from: 2, to: 100 },
{ from: 4, to: 4 }, { from: 4.5, to: 6 },
]) assert.deepEqual(visibleSearchTarget(body, undefined, false, match), {
markdown: '😀\nword', match: null, hiddenTitle: false,
});
});
+102
View File
@@ -0,0 +1,102 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { EditorSelection } from '@codemirror/state';
import { indentMore, indentLess, moveLineDown } from '@codemirror/commands';
import { SourceController, sourceHardBreak, sourceSearchDecoration, wrapSourceSelection } from '../src/lib/editor/source/controller.ts';
import { closestSearchMatch, findSourceMatches } from '../src/lib/editor/search.ts';
const options = { matchCase: false, wholeWord: false };
const run = (editor, command) => command({ state: editor.state, dispatch: (tr) => editor.dispatch(tr) });
test('source edits preserve immutable save snapshots and isolate undo when another note loads', () => {
let dirty = 0;
const editor = new SourceController((_, edited) => { if (edited) dirty++; });
editor.load('# First\r\n日本語 😀\r\n');
const saved = editor.state.doc;
editor.select(saved.length);
editor.replace('tail', saved.length);
assert.equal(saved.toString(), '# First\n日本語 😀\n');
assert.equal(editor.state.doc.toString(), '# First\n日本語 😀\ntail');
assert.equal(dirty, 1);
assert.equal(editor.undo(), true);
assert.equal(editor.state.doc.toString(), saved.toString());
assert.equal(editor.redo(), true);
assert.equal(editor.state.doc.toString(), '# First\n日本語 😀\ntail');
editor.load('Second note');
assert.equal(editor.undo(), false);
assert.equal(editor.state.doc.toString(), 'Second note');
});
test('source pair wrapping keeps backwards Unicode selection and undo restores it', () => {
const editor = new SourceController();
editor.load('before 日本語😀 after');
editor.dispatch({ selection: EditorSelection.single(12, 7) });
editor.dispatch(wrapSourceSelection(editor.state, '('));
assert.equal(editor.state.doc.toString(), 'before (日本語😀) after');
assert.equal(editor.state.selection.main.anchor, 13);
assert.equal(editor.state.selection.main.head, 8);
assert.equal(editor.state.sliceDoc(8, 13), '日本語😀');
editor.undo();
assert.equal(editor.state.doc.toString(), 'before 日本語😀 after');
assert.equal(editor.state.selection.main.anchor, 12);
assert.equal(editor.state.selection.main.head, 7);
});
test('hard breaks, indentation and line moves are undoable and respect read-only mode', () => {
const editor = new SourceController();
editor.load('first\nsecond');
editor.select(5);
assert.equal(run(editor, sourceHardBreak), true);
assert.equal(editor.state.doc.toString(), 'first \n\nsecond');
editor.undo();
editor.select(1);
run(editor, indentMore);
assert.equal(editor.state.doc.toString(), '\tfirst\nsecond');
run(editor, indentLess);
run(editor, moveLineDown);
assert.equal(editor.state.doc.toString(), 'second\nfirst');
editor.configure(true, true);
const before = editor.state.doc;
assert.equal(run(editor, sourceHardBreak), false);
assert.equal(run(editor, indentMore), false);
assert.equal(run(editor, moveLineDown), false);
assert.equal(wrapSourceSelection(editor.state, '['), null);
assert.equal(editor.state.doc, before);
});
test('live source search maps the current occurrence without resetting caret or dirty state', () => {
let changes = 0;
let anchor = 0;
const editor = new SourceController((mapping) => { changes++; anchor = mapping.mapPos(anchor); });
editor.load('İ 😀 中文 cat cat');
let matches = findSourceMatches(editor.state.doc.toString(), 'cat', options);
anchor = matches[1].from;
editor.highlight(matches[1], true);
assert.equal(changes, 0);
editor.replace('prefix ', 0, 0);
const selection = editor.state.selection;
matches = findSourceMatches(editor.state.doc.toString(), 'cat', options);
const index = closestSearchMatch(matches, anchor);
assert.equal(index, 1);
editor.highlight(matches[index]);
assert.equal(editor.state.selection, selection);
assert.equal(changes, 1);
const ranges = [];
editor.state.field(sourceSearchDecoration).between(0, editor.state.doc.length, (from, to) => ranges.push({ from, to }));
assert.deepEqual(ranges, [matches[1]]);
editor.undo();
matches = findSourceMatches(editor.state.doc.toString(), 'cat', options);
assert.equal(closestSearchMatch(matches, anchor), 1);
});
test('asset representation updates do not clear edits or become their own undo steps', () => {
let dirty = 0;
const editor = new SourceController((_, edited) => { if (edited) dirty++; });
editor.load('![image](blob:image)');
editor.replace(' user edit', editor.state.doc.length);
editor.replace('.helixnotes/attachments/image.png', 9, 19, true);
assert.equal(dirty, 1);
assert.equal(editor.state.doc.toString(), '![image](.helixnotes/attachments/image.png) user edit');
editor.undo();
assert.equal(editor.state.doc.toString(), '![image](.helixnotes/attachments/image.png)');
});
+42
View File
@@ -0,0 +1,42 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
const source = await readFile(
new URL('../src/lib/components/SettingsPanel.svelte', import.meta.url),
'utf8'
);
const initialization = source.match(
/(const\s+themePresets\s*=\s*\[[\s\S]*?\];)[\s\S]*?(?=\bconst\s+accentPresets\s*=)/
);
assert.ok(initialization, 'theme presets initialization was not found');
// Evaluate only the trusted repository declaration and its initialization code.
const unsorted = new Function(`${initialization[1]}\nreturn themePresets;`)();
const presets = new Function(`${initialization[0]}\nreturn themePresets;`)();
test('pins System, Light, and Dark in that exact order', () => {
assert.deepEqual(presets.slice(0, 3).map(({ id, label }) => ({ id, label })), [
{ id: 'system', label: 'System' },
{ id: 'light', label: 'Light' },
{ id: 'dark', label: 'Dark' }
]);
});
test('orders remaining built-in labels alphabetically, including Rosé Pine', () => {
const labels = presets.slice(3).map((preset) => preset.label);
assert.ok(labels.includes('Rosé Pine'));
assert.deepEqual(labels, [...labels].sort());
});
test('preserves every theme ID, label, and color without duplicates', () => {
assert.equal(presets.length, unsorted.length);
for (const themes of [unsorted, presets]) {
assert.equal(new Set(themes.map((preset) => preset.id)).size, themes.length);
assert.equal(new Set(themes.map((preset) => preset.label)).size, themes.length);
}
assert.deepEqual(
Object.fromEntries(presets.map((preset) => [preset.id, preset])),
Object.fromEntries(unsorted.map((preset) => [preset.id, preset]))
);
});
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more