mirror of
https://gitlab.com/ArkHost/HelixNotes.git
synced 2026-11-21 11:04:56 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
458bff3eac | ||
|
|
882006feb7 | ||
|
|
d5dc7147ab | ||
|
|
59b171af0a | ||
|
|
d36ac5e9fa | ||
|
|
4787559af5 | ||
|
|
ceb3a7d647 | ||
|
|
b9074ec550 | ||
|
|
c8277bb01c | ||
|
|
17f1af4294 | ||
|
|
fbabcf5099 | ||
|
|
338db1e7b0 | ||
|
|
ac4b85fd0f | ||
|
|
6716fec63a | ||
|
|
237bf799e3 | ||
|
|
77164427f1 | ||
|
|
523d1a5511 | ||
|
|
6ecde99f25 | ||
|
|
a466df85ed | ||
|
|
3858f8e455 | ||
|
|
64266969f3 | ||
|
|
a80425e084 | ||
|
|
2d554c6a9d | ||
|
|
1676f9fbd1 | ||
|
|
3c8b320892 | ||
|
|
b5189cf0e5 | ||
|
|
3d21a74d24 | ||
|
|
3b59d34fed | ||
|
|
c7bcb993bb | ||
|
|
4e2c87434d | ||
|
|
76919d6f1c | ||
|
|
5e49051ecb | ||
|
|
a6798d31e2 | ||
|
|
648cf48dcc | ||
|
|
3a9cae27c4 | ||
|
|
31d19a9faf | ||
|
|
d8e6228f13 | ||
|
|
48e39a0cbc | ||
|
|
2ddefc51e4 | ||
|
|
557f625947 | ||
|
|
043d2bd6c4 | ||
|
|
7100ac637c | ||
|
|
c0058f43f4 | ||
|
|
6986546f20 | ||
|
|
578bf9d253 | ||
|
|
94b477d072 | ||
|
|
5b21e1c3a1 | ||
|
|
630e6ea878 | ||
|
|
1289e865ce | ||
|
|
0f946ca330 | ||
|
|
39c56f7e13 | ||
|
|
8f07a24d62 | ||
|
|
9b8602e20f | ||
|
|
90795bea73 | ||
|
|
66fe9c8344 | ||
|
|
05249a3c81 | ||
|
|
af35b4dd75 | ||
|
|
b8821dd6fb | ||
|
|
5185f9a040 | ||
|
|
7db8d3f9d3 | ||
|
|
9f9c7e6c07 | ||
|
|
1ad948d4f0 | ||
|
|
6341fa8c9b | ||
|
|
21ab7ac49e | ||
|
|
3b25992a15 | ||
|
|
33514f28c9 | ||
|
|
6e2165661c | ||
|
|
e168f4e004 | ||
|
|
2014365e4a | ||
|
|
8df5efacb8 | ||
|
|
f87b8af238 | ||
|
|
f0bf0ac5e3 | ||
|
|
0ecacbe1dd | ||
|
|
455b059fb5 | ||
|
|
f4c6649c0a | ||
|
|
6c4d1c2e93 | ||
|
|
32b1e091fd | ||
|
|
9aa9ca7d3e | ||
|
|
0b94d9ff32 | ||
|
|
bd86fb8a4d | ||
|
|
ec479ced8e | ||
|
|
add45ad9dd | ||
|
|
076234974a | ||
|
|
6d9b29343f | ||
|
|
504461bfe7 | ||
|
|
4aa72e4c76 | ||
|
|
ea4a5eae26 | ||
|
|
8d3338ef89 | ||
|
|
b2c306d69f | ||
|
|
ac2c0aef94 | ||
|
|
f07241dd3a | ||
|
|
14b2a3e8a2 | ||
|
|
505ed2b890 | ||
|
|
b03d7fd12c | ||
|
|
e1f1ef0b02 | ||
|
|
806c63aa65 | ||
|
|
4157beddf7 | ||
|
|
923cb9571c | ||
|
|
640b5e3d10 | ||
|
|
3607cf1b3f | ||
|
|
245cdacb68 | ||
|
|
2983e3db29 | ||
|
|
cc7c9e2b49 | ||
|
|
2240231f61 | ||
|
|
b2d0c7175e | ||
|
|
1bc0026731 | ||
|
|
41c0e4c993 | ||
|
|
34a0f9efa3 | ||
|
|
9d92489586 | ||
|
|
c45efb60ab | ||
|
|
0d11fd01dd | ||
|
|
0aaa05ce5c | ||
|
|
77e92ef25c | ||
|
|
d7e4be7f3a | ||
|
|
2aa572dcaa | ||
|
|
32f270ce9e |
No files matched your search
@@ -13,9 +13,6 @@ bun.lockb
|
||||
/.svelte-kit
|
||||
/build
|
||||
|
||||
# Local tests
|
||||
/tests/
|
||||
|
||||
# Nix
|
||||
/result
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "packaging/flatpak/shared-modules"]
|
||||
path = packaging/flatpak/shared-modules
|
||||
url = https://github.com/flathub/shared-modules.git
|
||||
@@ -1,7 +1,7 @@
|
||||
# HelixNotes
|
||||
|
||||
[](https://gitlab.com/ArkHost/HelixNotes/-/blob/main/LICENSE)
|
||||
[](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.4)
|
||||
[](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.6)
|
||||
[](https://helixnotes.com)
|
||||
[]()
|
||||
|
||||
@@ -10,7 +10,7 @@ A local markdown note-taking app built with Tauri, SvelteKit, and Rust.
|
||||
Your notes are stored as standard Markdown files on your local filesystem.
|
||||
No cloud, no lock-in.
|
||||
|
||||
## Download (v1.3.4)
|
||||
## Download (v1.3.6)
|
||||
|
||||
### Linux
|
||||
|
||||
@@ -18,7 +18,7 @@ No cloud, no lock-in.
|
||||
|
||||
The AppImage works only on Fedora 43+, Arch Linux, and openSUSE Tumbleweed (x86_64).
|
||||
|
||||
[Download AppImage](https://download.helixnotes.com/releases/v1.3.4/HelixNotes_1.3.4_amd64.AppImage)
|
||||
[Download AppImage](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_amd64.AppImage)
|
||||
|
||||
#### Distro-specific packages
|
||||
|
||||
@@ -108,26 +108,28 @@ sudo eopkg it helixnotes
|
||||
|
||||
#### Manual package downloads
|
||||
|
||||
- [.deb](https://download.helixnotes.com/releases/v1.3.4/HelixNotes_1.3.4_amd64.deb) (Ubuntu 22.04+)
|
||||
- [.rpm](https://download.helixnotes.com/releases/v1.3.4/HelixNotes-1.3.4-1.x86_64.rpm)
|
||||
- [.deb](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_amd64.deb) (Ubuntu 22.04+)
|
||||
- [.rpm](https://download.helixnotes.com/releases/v1.3.6/HelixNotes-1.3.6-1.x86_64.rpm)
|
||||
|
||||
### Windows
|
||||
|
||||
[Download Installer](https://download.helixnotes.com/releases/v1.3.4/HelixNotes_1.3.4_x64-setup.exe) (Windows 10/11)
|
||||
[Download Installer](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_x64-setup.exe) (Windows 10/11)
|
||||
|
||||
### macOS
|
||||
|
||||
[Download .dmg (Apple Silicon)](https://download.helixnotes.com/releases/v1.3.4/HelixNotes_1.3.4_aarch64.dmg) (M-series Macs)
|
||||
[Download .dmg (Apple Silicon)](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_aarch64.dmg) (M-series Macs)
|
||||
|
||||
> **"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):
|
||||
>
|
||||
> ```bash
|
||||
> xattr -cr /Applications/HelixNotes.app
|
||||
> ```
|
||||
[Download .dmg (Intel)](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_x64.dmg)
|
||||
|
||||
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
|
||||
xattr -cr /Applications/HelixNotes.app
|
||||
```
|
||||
|
||||
### Android
|
||||
|
||||
[Download APK](https://download.helixnotes.com/releases/v1.3.4/HelixNotes_1.3.4_android.apk)
|
||||
[Download APK](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_android.apk)
|
||||
|
||||
---
|
||||
|
||||
@@ -136,24 +138,44 @@ All releases: [gitlab.com/ArkHost/HelixNotes/-/releases](https://gitlab.com/ArkH
|
||||
## Features
|
||||
|
||||
- Markdown editor with toolbar, slash commands, source mode, code highlighting
|
||||
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, work in a list or a calendar (drag a task to reschedule)
|
||||
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, filter Today or Overdue tasks, work in a list or a calendar (drag a task to reschedule)
|
||||
- `[[Wiki-links]]` and graph view
|
||||
- Full-text search (Tantivy), CJK-aware for Chinese, Japanese, and Korean
|
||||
- Outline panel, daily notes with calendar view, tags with autocomplete, drag-and-drop
|
||||
- Live KaTeX math editor (`/math`, `/imath`) with modal preview, double-click to edit
|
||||
- Mermaid diagrams (opt-in render, copy as PNG, save as PNG/SVG)
|
||||
- Encrypted secret blocks (`/secret`) stored as portable `helix-secret` markdown fences
|
||||
- Insert date/time (`/date`, `/time`, `/now`), color swatches (`/color`), configurable week start
|
||||
- Insert date/time (`/date`, `/time`, `/now`) with 12-hour or 24-hour timestamps, color swatches (`/color`), configurable week start
|
||||
- Manual notebook sorting (drag to reorder above, into, or below)
|
||||
- External `.md` viewer mode with import-to-vault flow
|
||||
- PDF preview, Obsidian import, "Show in File Manager"
|
||||
- AI writing tools (Ollama / OpenAI-compatible / Anthropic / OpenAI)
|
||||
- **Optional WebDAV sync** to your own server (Nextcloud, ownCloud, a NAS): manual or automatic, with keep-both conflict copies
|
||||
- Version history with diffs, automatic backups
|
||||
- Version history with main-area diffs and rendered read-only snapshots, automatic backups
|
||||
- Multi-window, file associations, focus mode, view mode
|
||||
- Themes (light, dark, and 14 palettes), accent colors, fonts, 80-200% interface scale
|
||||
- Themes (light, dark, and 14 palettes), accent colors, fonts including bundled Ubuntu and Ubuntu Mono, 80-200% interface scale
|
||||
- Local plain-text files, no company cloud
|
||||
|
||||
### Version history
|
||||
|
||||
Changes compares the selected snapshot with the current editor contents, including unsaved edits. Added and removed lines show what restoring that version would change; long unchanged sections can be expanded.
|
||||
|
||||
Snapshot displays the stored note read-only, with View source available for its Markdown body. Metadata is separate and is not restored. Snapshot links are inactive, secrets stay locked, and diagrams render only when requested.
|
||||
|
||||
Restore replaces the current note's body and asks for confirmation if it would replace an unsaved draft. Inspecting versions does not replace the live editor contents or reset their undo history.
|
||||
|
||||
### Note Info
|
||||
|
||||
Open **Note info** from the editor toolbar. Expand **Frontmatter** to inspect the original YAML header, including custom keys, without editing it. This shows the last loaded or saved metadata; unsaved changes are not included, and the display updates after saving.
|
||||
|
||||
### Saving notes
|
||||
|
||||
Notes autosave after three seconds without edits. During continuous typing, a save is queued at least every ten seconds. Ctrl+S (Cmd+S on macOS), switching notes, and closing an editor flush pending changes immediately. A failed save leaves the note marked **Unsaved** and blocks leaving that editor.
|
||||
|
||||
Note writes run off the UI thread and replace the file atomically. Unchanged notes are not rewritten. Ordinary saves update only the affected note in the list, wiki-link cache, and Tasks view; search-index updates are batched in the background. External file changes are still picked up by the watcher.
|
||||
|
||||
With **Close to tray** enabled and a tray icon available, closing the main window hides it after saving. With the setting off, closing the main window closes the application. The close-to-tray setting takes effect immediately; enabling the tray icon itself requires a restart. Explicit **Quit** exits rather than hiding to the tray.
|
||||
|
||||
Full documentation: [helixnotes.com/docs](https://helixnotes.com/docs.html)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
+11
-3
@@ -2,8 +2,9 @@
|
||||
"name": "helixnotes",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.7",
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@11.18.0",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
@@ -35,18 +36,23 @@
|
||||
"vite": "^7.3.6"
|
||||
},
|
||||
"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/plugin-dialog": "^2.6.0",
|
||||
"@tauri-apps/plugin-fs": "^2.4.5",
|
||||
"@tauri-apps/plugin-updater": "^2.10.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-details": "^3.19.0",
|
||||
"@tiptap/extension-highlight": "^3.19.0",
|
||||
"@tiptap/extension-image": "^3.19.0",
|
||||
"@tiptap/extension-link": "^3.19.0",
|
||||
"@tiptap/extension-placeholder": "^3.19.0",
|
||||
"@tiptap/extension-subscript": "^3.19.0",
|
||||
"@tiptap/extension-superscript": "^3.19.0",
|
||||
"@tiptap/extension-table": "^3.19.0",
|
||||
@@ -63,6 +69,8 @@
|
||||
"@tiptap/starter-kit": "^3.19.0",
|
||||
"@types/katex": "^0.16.8",
|
||||
"@types/markdown-it": "^14.1.2",
|
||||
"diff": "^9.0.0",
|
||||
"dompurify": "^3.4.13",
|
||||
"highlight.js": "^11.11.1",
|
||||
"katex": "^0.16.28",
|
||||
"lowlight": "^3.3.0",
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# Flatpak
|
||||
|
||||
This builds the Git revision pinned in the manifest inside the GNOME 51 SDK. Rust
|
||||
and Node dependencies are pinned by the existing lockfiles and downloaded before
|
||||
the sandboxed, offline build. The shared-modules submodule supplies the Ayatana
|
||||
tray libraries.
|
||||
|
||||
## ArkHost repository
|
||||
|
||||
HelixNotes is distributed through ArkHost's signed Flatpak repository at
|
||||
`https://repo.arkhost.com/flatpak/`, served by Shiny. Install using
|
||||
[HelixNotes.flatpakref](https://repo.arkhost.com/flatpak/HelixNotes.flatpakref).
|
||||
The public catalog advertises version 1.3.7.
|
||||
|
||||
The application ID is `com.helixnotes.HelixNotes`; the repository collection ID is
|
||||
`com.arkhost.Flatpak`. Keep both stable so installed applications receive future
|
||||
updates from the same repository.
|
||||
|
||||
Signing fingerprint: `B66171BA8BBE0F590D067B86D02631809E3F7AE2`.
|
||||
The initial publication was checked using a separate temporary Flatpak store:
|
||||
the install descriptor, catalog version, signatures and package download passed.
|
||||
That check did not deploy or launch the application.
|
||||
|
||||
`prepare-repository.py` imports a built bundle, prepares AppStream metadata and
|
||||
static deltas, and signs the application and repository metadata with an OpenPGP
|
||||
key. It exports only the public key. The signing key stays in the local keyring.
|
||||
Keep an offline backup of that permanent signing identity.
|
||||
|
||||
After building the bundle, prepare a fresh signed output:
|
||||
|
||||
```sh
|
||||
python3 packaging/flatpak/prepare-repository.py \
|
||||
src-tauri/target/flatpak/HelixNotes_1.3.7_x86_64.flatpak \
|
||||
--output /path/to/arkhost-flatpak-1.3.7 \
|
||||
--gpg-key FULL_OPENPGP_FINGERPRINT
|
||||
```
|
||||
|
||||
The script uses the `ostree` command when available, or the system's OSTree
|
||||
GObject bindings to initialize repositories. This Fedora workstation already
|
||||
has those bindings. For subsequent releases, add
|
||||
`--previous-directory /path/to/previous-output` to preserve the publication
|
||||
history. Always choose a new output directory.
|
||||
|
||||
If the signing identity is not ready, `--unsigned` can replace `--gpg-key` for a
|
||||
local preview. The output will be visibly marked as unsigned and will contain no
|
||||
install descriptors.
|
||||
|
||||
The signed output contains:
|
||||
|
||||
```text
|
||||
repo/ Application repository and update metadata
|
||||
arkhost.flatpakrepo Adds the ArkHost remote
|
||||
HelixNotes.flatpakref Adds the remote and installs HelixNotes
|
||||
```
|
||||
|
||||
Unsigned staging omits install links and is not a publishable repository. Keep
|
||||
the previous signed output when preparing an update so repository history and
|
||||
delta updates are retained.
|
||||
|
||||
Publish the prepared public files under
|
||||
`/srv/www/repo.arkhost.com/flatpak/` on Shiny using the existing repository
|
||||
deployment workflow. The publisher prepares local files; it does not connect to
|
||||
Shiny or change its web configuration. Serve the tree over HTTPS with HTTP
|
||||
keep-alive enabled. Keep repository summaries and install descriptors fresh in
|
||||
any HTTP cache; content-addressed objects can be cached longer.
|
||||
Keep updates scoped to this `flatpak/` subtree. APT/RPM deployments must preserve
|
||||
it, and Flatpak deployments must preserve the other repository subtrees.
|
||||
|
||||
HelixNotes and its updates come from ArkHost. The shared GNOME runtime continues
|
||||
to come from its existing upstream repository. Users install through
|
||||
`HelixNotes.flatpakref` and receive updates through Discover, GNOME Software or
|
||||
`flatpak update`.
|
||||
|
||||
## Build
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
```sh
|
||||
git submodule update --init packaging/flatpak/shared-modules
|
||||
flatpak install --user flathub org.flatpak.Builder org.gnome.Platform//51 org.gnome.Sdk//51 org.freedesktop.Sdk.Extension.node24//26.08 org.freedesktop.Sdk.Extension.rust-stable//26.08
|
||||
flatpak run org.flatpak.Builder --user --force-clean --collection-id=com.arkhost.Flatpak --state-dir=src-tauri/target/flatpak/state --repo=src-tauri/target/flatpak/arkhost-origin src-tauri/target/flatpak/build packaging/flatpak/com.helixnotes.HelixNotes.yml
|
||||
flatpak build-bundle src-tauri/target/flatpak/arkhost-origin src-tauri/target/flatpak/HelixNotes_1.3.7_x86_64.flatpak com.helixnotes.HelixNotes stable --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
```
|
||||
|
||||
The commands require a user-local Flathub remote. If only a system remote exists,
|
||||
add the user remote first:
|
||||
|
||||
```sh
|
||||
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
```
|
||||
|
||||
## Install and run
|
||||
|
||||
```sh
|
||||
flatpak install --user https://repo.arkhost.com/flatpak/HelixNotes.flatpakref
|
||||
flatpak run com.helixnotes.HelixNotes
|
||||
```
|
||||
|
||||
Choose vault folders using the folder picker. Flatpak grants access to the chosen
|
||||
folders through its document portal; the package does not request access to the
|
||||
whole home directory. Its settings are separate from native installations.
|
||||
The document portal does not forward external file-change notifications, so this
|
||||
build checks visible notes and notebooks about every two seconds in small vaults.
|
||||
The interval grows with scan cost in larger vaults to limit background CPU use.
|
||||
It compares file size and precise modification/change timestamps, including changes made
|
||||
while preserving a note's modification time. Attachments and hidden app data are
|
||||
excluded from these scans; note contents are read only when a change is detected.
|
||||
|
||||
The build sets `HELIXNOTES_INSTALL_TYPE=flatpak`, which suppresses the in-app
|
||||
updater. Discover, GNOME Software or `flatpak update` handle updates for installs
|
||||
from the ArkHost repository. The bundle references Flathub for its runtime, which
|
||||
is installed separately.
|
||||
|
||||
## Refresh dependencies
|
||||
|
||||
Regenerate both source lists whenever their lockfiles change. The initial lists
|
||||
were generated with flatpak-builder-tools commit
|
||||
`9d86d336a39b9af38b86f114b6ce5820fe260f91`:
|
||||
|
||||
```sh
|
||||
uv run --project /path/to/flatpak-builder-tools/node python -m flatpak_node_generator --no-requests-cache --pnpm-store-version v11 --node-sdk-extension org.freedesktop.Sdk.Extension.node24//26.08 -o packaging/flatpak/node-sources.json pnpm pnpm-lock.yaml
|
||||
uv run /path/to/flatpak-builder-tools/cargo/flatpak-cargo-generator.py -o packaging/flatpak/cargo-sources.json src-tauri/Cargo.lock
|
||||
```
|
||||
|
||||
Keep the pinned pnpm archive/version in the manifest in step with
|
||||
`package.json`'s `packageManager`. pnpm 11 uses the v11 store; the generator's
|
||||
default v10 store does not work with it.
|
||||
|
||||
The offline install uses `--trust-lockfile` for this reviewed, pinned lockfile.
|
||||
Flatpak verifies the downloaded sources against the generated checksums. This
|
||||
keeps pnpm from querying registry metadata and attestations during the offline
|
||||
build; it does not grant network access to the build sandbox.
|
||||
|
||||
The store developer is Yuri Karamian. The Flatpak build overrides Tauri's
|
||||
identifier only for this package; native packages retain their existing ID.
|
||||
|
||||
Version 1.3.7 is published in the ArkHost Flatpak repository with stable package
|
||||
metadata dated 2026-11-10. GitLab release tags and other platform channels are
|
||||
managed separately. Keep the manifest pinned to the matching source revision.
|
||||
|
||||
The published package targets x86_64. The earlier test bundle in Nextcloud uses
|
||||
the `com.helixnotes.app` ID and has not been overwritten. Install through the
|
||||
public link once to use the permanent ID and receive repository updates. The new
|
||||
ID has a separate Flatpak profile; select the same notes folder through the system
|
||||
picker.
|
||||
|
||||
## Optional Flathub submission
|
||||
|
||||
The separate Flathub submission draft has not been checked with Flathub's build
|
||||
wrapper or linter. See the [submission guide](https://docs.flathub.org/docs/for-app-authors/submission)
|
||||
and [current requirements](https://docs.flathub.org/docs/for-app-authors/requirements).
|
||||
|
||||
The Flathub repository needs these files at its root:
|
||||
|
||||
- `com.helixnotes.HelixNotes.yml`
|
||||
- `cargo-sources.json`
|
||||
- `node-sources.json`
|
||||
- `flathub.json`
|
||||
- The `shared-modules` Git submodule, pinned to
|
||||
`6be1f986ac28a2b7d745e5ff45a3f8a2d3345083`
|
||||
|
||||
Desktop, icon and MetaInfo files are installed from the pinned application source.
|
||||
The source currently includes the packaging metadata and the Flatpak watcher fix.
|
||||
It is a preparation revision, not a published v1.3.7 release tag.
|
||||
|
||||
Use a branch based on `flathub/flathub`'s `new-pr` branch. Preserve the upstream
|
||||
submission template. Author the submission description and any review replies
|
||||
yourself, following Flathub's current requirements. This preparation does not
|
||||
create a GitHub pull request or publish an application.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=HelixNotes
|
||||
Comment=Write and organize local Markdown notes
|
||||
Exec=helixnotes %f
|
||||
Icon=com.helixnotes.HelixNotes
|
||||
Terminal=false
|
||||
Categories=Office;
|
||||
MimeType=text/markdown;text/x-markdown;
|
||||
Keywords=Markdown;tasks;wiki;
|
||||
@@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Copyright 2026 Yuri Karamian -->
|
||||
<component type="desktop-application">
|
||||
<id>com.helixnotes.HelixNotes</id>
|
||||
<metadata_license>CC0-1.0</metadata_license>
|
||||
<project_license>AGPL-3.0-or-later</project_license>
|
||||
<name>HelixNotes</name>
|
||||
<summary>Write and organize local Markdown notes</summary>
|
||||
<developer id="com.helixnotes">
|
||||
<name>Yuri Karamian</name>
|
||||
</developer>
|
||||
<description>
|
||||
<p>HelixNotes keeps your notes as Markdown files in a folder you choose.
|
||||
Organize them into notebooks, add tags, link related notes and search across
|
||||
your collection.</p>
|
||||
<p>The Tasks view brings together checklists from your notes in a list or
|
||||
calendar.</p>
|
||||
</description>
|
||||
<launchable type="desktop-id">com.helixnotes.HelixNotes.desktop</launchable>
|
||||
<url type="homepage">https://helixnotes.com</url>
|
||||
<url type="vcs-browser">https://gitlab.com/ArkHost/HelixNotes</url>
|
||||
<url type="bugtracker">https://gitlab.com/ArkHost/HelixNotes/-/issues</url>
|
||||
<content_rating type="oars-1.1"/>
|
||||
<releases>
|
||||
<release version="1.3.7" type="stable" date="2026-11-10">
|
||||
<description>
|
||||
<p>Add notebook and tag icons, ten themes, mobile layout fixes and a
|
||||
Flatpak package.</p>
|
||||
</description>
|
||||
</release>
|
||||
</releases>
|
||||
<provides>
|
||||
<binary>helixnotes</binary>
|
||||
</provides>
|
||||
<screenshots>
|
||||
<screenshot type="default">
|
||||
<caption>Markdown editor</caption>
|
||||
<image type="source">https://cdn.helixnotes.com/assets/screenshots/screenshot-1.png</image>
|
||||
</screenshot>
|
||||
<screenshot>
|
||||
<caption>Tasks calendar</caption>
|
||||
<image type="source">https://cdn.helixnotes.com/assets/screenshots/screenshot-2.png</image>
|
||||
</screenshot>
|
||||
</screenshots>
|
||||
</component>
|
||||
@@ -0,0 +1,71 @@
|
||||
app-id: com.helixnotes.HelixNotes
|
||||
runtime: org.gnome.Platform
|
||||
runtime-version: '51'
|
||||
sdk: org.gnome.Sdk
|
||||
branch: stable
|
||||
command: helixnotes
|
||||
sdk-extensions:
|
||||
- org.freedesktop.Sdk.Extension.node24
|
||||
- org.freedesktop.Sdk.Extension.rust-stable
|
||||
|
||||
finish-args:
|
||||
- --socket=wayland
|
||||
- --socket=fallback-x11
|
||||
- --share=ipc
|
||||
- --device=dri
|
||||
- --share=network
|
||||
- --filesystem=xdg-run/tray-icon:create
|
||||
- --talk-name=org.kde.StatusNotifierWatcher
|
||||
- --talk-name=org.freedesktop.FileManager1
|
||||
|
||||
build-options:
|
||||
append-path: /usr/lib/sdk/node24/bin:/usr/lib/sdk/rust-stable/bin
|
||||
|
||||
cleanup:
|
||||
- /include
|
||||
- /lib/pkgconfig
|
||||
- /lib/*.a
|
||||
- /lib/*.la
|
||||
|
||||
modules:
|
||||
- shared-modules/libayatana-appindicator/libayatana-appindicator-gtk3.json
|
||||
|
||||
- name: pnpm
|
||||
buildsystem: simple
|
||||
build-commands:
|
||||
- mkdir -p /app/lib/pnpm /app/bin
|
||||
- cp -a . /app/lib/pnpm/
|
||||
- ln -s ../lib/pnpm/bin/pnpm.mjs /app/bin/pnpm
|
||||
cleanup:
|
||||
- '*'
|
||||
sources:
|
||||
- type: archive
|
||||
url: https://registry.npmjs.org/pnpm/-/pnpm-11.18.0.tgz
|
||||
sha256: 29c35ca8d2a287988fdee3e0f36e07d9b93783f567b579b7fd5b798a4563dd81
|
||||
|
||||
- name: helixnotes
|
||||
buildsystem: simple
|
||||
build-options:
|
||||
env:
|
||||
CARGO_HOME: /run/build/helixnotes/cargo
|
||||
CARGO_NET_OFFLINE: 'true'
|
||||
CARGO_BUILD_JOBS: '4'
|
||||
XDG_CACHE_HOME: /run/build/helixnotes/flatpak-node/cache
|
||||
HELIXNOTES_INSTALL_TYPE: flatpak
|
||||
build-commands:
|
||||
- pnpm install --offline --frozen-lockfile --trust-lockfile
|
||||
- pnpm tauri build --no-bundle --config '{"identifier":"com.helixnotes.HelixNotes"}'
|
||||
- install -Dm755 src-tauri/target/release/helixnotes /app/bin/helixnotes
|
||||
- install -Dm644 packaging/flatpak/com.helixnotes.HelixNotes.desktop /app/share/applications/com.helixnotes.HelixNotes.desktop
|
||||
- install -Dm644 packaging/flatpak/com.helixnotes.HelixNotes.metainfo.xml /app/share/metainfo/com.helixnotes.HelixNotes.metainfo.xml
|
||||
- install -Dm644 src-tauri/icons/icon.svg /app/share/icons/hicolor/scalable/apps/com.helixnotes.HelixNotes.svg
|
||||
- install -Dm644 src-tauri/icons/128x128.png /app/share/icons/hicolor/128x128/apps/com.helixnotes.HelixNotes.png
|
||||
- install -Dm644 src-tauri/icons/128x128@2x.png /app/share/icons/hicolor/256x256/apps/com.helixnotes.HelixNotes.png
|
||||
- install -Dm644 LICENSE /app/share/licenses/com.helixnotes.HelixNotes/LICENSE
|
||||
sources:
|
||||
- type: git
|
||||
url: https://gitlab.com/ArkHost/HelixNotes.git
|
||||
commit: d5dc7147ab9c8d3fa7a8ce034339e9f2a5b5e260
|
||||
disable-submodules: true
|
||||
- cargo-sources.json
|
||||
- node-sources.json
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"only-arches": ["x86_64"]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Executable
+235
@@ -0,0 +1,235 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare a local ArkHost Flatpak repository; never upload or deploy it.
|
||||
|
||||
Signed example:
|
||||
./prepare-repository.py HelixNotes.flatpak --output /tmp/arkhost-signed \
|
||||
--gpg-key FULL_OPENPGP_FINGERPRINT
|
||||
|
||||
For an update, add --previous-directory /path/to/previous/output. Its repository
|
||||
is copied, preserving old commits and deltas; the previous output is untouched.
|
||||
The output must be a fresh directory outside the previous directory.
|
||||
|
||||
Use --unsigned for local staging while a signing key is unavailable. Unsigned
|
||||
staging produces no public-key files or installation descriptors. Prepare a new
|
||||
signed output before distribution; never disable client signature verification.
|
||||
|
||||
Requires Python 3, Flatpak, OSTree (CLI or Python GObject bindings) and, for
|
||||
signed output, GnuPG. Signing uses the normal
|
||||
GPG agent/pinentry. Only the public key is exported. The input bundle should be
|
||||
exported with collection ID com.arkhost.Flatpak and contain the canonical app's
|
||||
x86_64/stable ref. No packages are installed and no network commands are run.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import configparser
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
APP_ID = "com.helixnotes.HelixNotes"
|
||||
APP_REF = f"app/{APP_ID}/x86_64/stable"
|
||||
COLLECTION_ID = "com.arkhost.Flatpak"
|
||||
RUNTIME_REPO = "https://dl.flathub.org/repo/flathub.flatpakrepo"
|
||||
DEFAULT_URL = "https://repo.arkhost.com/flatpak/"
|
||||
|
||||
|
||||
def run(*args, capture=False, binary=False):
|
||||
return subprocess.run(
|
||||
[str(arg) for arg in args],
|
||||
check=True,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
text=not binary,
|
||||
env={**os.environ, "LC_ALL": "C"},
|
||||
).stdout
|
||||
|
||||
|
||||
def initialize_repository(repository):
|
||||
repository.mkdir(parents=True, exist_ok=False)
|
||||
if shutil.which("ostree"):
|
||||
run("ostree", f"--repo={repository}", "init", "--mode=archive-z2")
|
||||
else:
|
||||
# Fedora already supplies these native bindings with Flatpak. Keep the
|
||||
# fallback isolated so installations with the CLI do not require them.
|
||||
run(sys.executable, "-c", (
|
||||
"import sys, gi; gi.require_version('OSTree', '1.0'); "
|
||||
"from gi.repository import Gio, OSTree; "
|
||||
"repo = OSTree.Repo.new(Gio.File.new_for_path(sys.argv[1])); "
|
||||
"repo.create(OSTree.RepoMode.ARCHIVE_Z2, None)"
|
||||
), repository)
|
||||
run("flatpak", "build-update-repo", "--no-update-appstream",
|
||||
f"--collection-id={COLLECTION_ID}", repository)
|
||||
|
||||
|
||||
def validate_repository(repository):
|
||||
"""Inspect Flatpak's summary and app metadata, not the bundle's binary format."""
|
||||
branches = run("flatpak", "repo", "--branches", repository, capture=True)
|
||||
refs = {
|
||||
line.split()[0]
|
||||
for line in branches.splitlines()
|
||||
if line.split() and line.split()[0].startswith(("app/", "runtime/"))
|
||||
}
|
||||
if refs != {APP_REF}:
|
||||
raise ValueError(f"Expected only {APP_REF}; found {sorted(refs)}")
|
||||
metadata = configparser.ConfigParser(interpolation=None)
|
||||
metadata.read_string(
|
||||
run("flatpak", "repo", f"--metadata={APP_REF}", repository, capture=True)
|
||||
)
|
||||
if metadata.get("Application", "name", fallback="") != APP_ID:
|
||||
raise ValueError("Imported application metadata has an unexpected ID")
|
||||
runtime = metadata.get("Application", "runtime", fallback="")
|
||||
if not runtime.startswith("org.gnome.Platform/x86_64/"):
|
||||
raise ValueError(f"Expected the GNOME x86_64 runtime; found {runtime!r}")
|
||||
|
||||
|
||||
def write_descriptor(path, section, fields):
|
||||
descriptor = configparser.ConfigParser(interpolation=None)
|
||||
descriptor.optionxform = str
|
||||
descriptor[section] = fields
|
||||
with path.open("x", encoding="utf-8") as stream:
|
||||
descriptor.write(stream, space_around_delimiters=False)
|
||||
|
||||
|
||||
def prepare(args):
|
||||
bundle = args.bundle.expanduser().resolve(strict=True)
|
||||
output = args.output.expanduser().absolute()
|
||||
if not bundle.is_file():
|
||||
raise ValueError("The bundle must be a regular file")
|
||||
if os.path.lexists(output):
|
||||
raise ValueError("Output already exists; choose a fresh staging directory")
|
||||
previous = None
|
||||
if args.previous_directory:
|
||||
previous = args.previous_directory.expanduser().resolve(strict=True)
|
||||
if output.resolve().is_relative_to(previous):
|
||||
raise ValueError("Output must be outside the previous directory")
|
||||
if not (previous / "repo").is_dir():
|
||||
raise ValueError("Previous directory must contain a repo directory")
|
||||
validate_repository(previous / "repo")
|
||||
old_fingerprint = previous / "gpg-fingerprint.txt"
|
||||
if args.gpg_key and not old_fingerprint.exists():
|
||||
raise ValueError("Signing an update requires a previous signed output; omit --previous-directory for the first signed publication")
|
||||
if args.gpg_key:
|
||||
if old_fingerprint.read_text().strip().upper() != args.gpg_key:
|
||||
raise ValueError("Previous repository uses another signing key; key rotation requires a separate plan")
|
||||
for command in ("flatpak", "gpg") if args.gpg_key else ("flatpak",):
|
||||
if shutil.which(command) is None:
|
||||
raise ValueError(f"Required command not found: {command}")
|
||||
homedir = []
|
||||
if args.gpg_homedir:
|
||||
keyring = args.gpg_homedir.expanduser().resolve(strict=True)
|
||||
if not keyring.is_dir():
|
||||
raise ValueError("GPG homedir must be an existing directory")
|
||||
homedir = [f"--gpg-homedir={keyring}"]
|
||||
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
incomplete = output / "INCOMPLETE.txt"
|
||||
incomplete.write_text("Local preparation has not completed. Do not publish this directory.\n")
|
||||
repository = output / "repo"
|
||||
# An empty temporary import makes it impossible for an old repo ref to mask
|
||||
# an input bundle with the wrong app, architecture or branch.
|
||||
with tempfile.TemporaryDirectory(prefix=".flatpak-import-", dir=output) as scratch:
|
||||
imported = Path(scratch) / "repo"
|
||||
initialize_repository(imported)
|
||||
print("Importing and checking the canonical application bundle", flush=True)
|
||||
run("flatpak", "build-import-bundle", "--no-update-summary", imported, bundle)
|
||||
# `flatpak repo` reads summary metadata, so create a private preflight
|
||||
# summary before inspecting the import. The signed summary comes later.
|
||||
run("flatpak", "build-update-repo", "--no-update-appstream", imported)
|
||||
validate_repository(imported)
|
||||
if previous:
|
||||
print("Copying the previous repository without pruning its history", flush=True)
|
||||
shutil.copytree(previous / "repo", repository, copy_function=shutil.copy2)
|
||||
else:
|
||||
initialize_repository(repository)
|
||||
# Recommit onto the hosted branch so each update descends from its last
|
||||
# published head and uses this repository's collection binding.
|
||||
run("flatpak", "build-commit-from", f"--src-repo={imported}",
|
||||
f"--src-ref={APP_REF}", "--no-update-summary", repository, APP_REF)
|
||||
|
||||
signing = []
|
||||
public_key = None
|
||||
if args.gpg_key:
|
||||
public_key = output / "arkhost-flatpak.gpg"
|
||||
gpg_homedir = []
|
||||
if args.gpg_homedir:
|
||||
gpg_homedir = ["--homedir", str(keyring)]
|
||||
exported = run("gpg", "--batch", *gpg_homedir, "--export", args.gpg_key,
|
||||
capture=True, binary=True)
|
||||
if not exported:
|
||||
raise ValueError("GPG exported no public key for the requested fingerprint")
|
||||
public_key.write_bytes(exported)
|
||||
signing = [f"--gpg-sign={args.gpg_key}", *homedir]
|
||||
print("Signing the application commit", flush=True)
|
||||
run("flatpak", "build-sign", "--arch=x86_64", *signing,
|
||||
repository, APP_ID, "stable")
|
||||
|
||||
print("Updating AppStream, summary and static deltas", flush=True)
|
||||
run("flatpak", "build-update-repo", "--generate-static-deltas",
|
||||
"--default-branch=stable", f"--collection-id={COLLECTION_ID}",
|
||||
"--title=ArkHost Flatpak Repository", "--homepage=https://arkhost.com",
|
||||
*signing, *([f"--gpg-import={public_key}"] if public_key else []), repository)
|
||||
validate_repository(repository)
|
||||
|
||||
if args.unsigned:
|
||||
(output / "UNSIGNED-STAGING.txt").write_text(
|
||||
"UNSIGNED LOCAL STAGING. Do not publish this repository.\n"
|
||||
"No installation descriptors or public-key files were generated.\n"
|
||||
"Prepare a fresh output with --gpg-key before distribution.\n"
|
||||
)
|
||||
print(f"Unsigned staging ready: {output}. No installation links generated.", flush=True)
|
||||
else:
|
||||
(output / "gpg-fingerprint.txt").write_text(args.gpg_key + "\n")
|
||||
encoded_key = base64.b64encode(exported).decode("ascii")
|
||||
repository_url = args.url.rstrip("/") + "/repo/"
|
||||
common = {"Url": repository_url, "GPGKey": encoded_key,
|
||||
"DeploySideloadCollectionID": COLLECTION_ID}
|
||||
write_descriptor(output / "arkhost.flatpakrepo", "Flatpak Repo", {
|
||||
"Title": "ArkHost Flatpak Repository", "Homepage": "https://arkhost.com",
|
||||
"DefaultBranch": "stable", **common,
|
||||
})
|
||||
write_descriptor(output / "HelixNotes.flatpakref", "Flatpak Ref", {
|
||||
"Title": "HelixNotes", "Name": APP_ID, "Branch": "stable",
|
||||
"IsRuntime": "false", "SuggestRemoteName": "arkhost",
|
||||
"RuntimeRepo": RUNTIME_REPO,
|
||||
"Description": "Local Markdown notes by Yuri Karamian.", **common,
|
||||
})
|
||||
print(f"Signed repository and installation descriptors ready: {output}", flush=True)
|
||||
incomplete.unlink()
|
||||
print("Nothing was uploaded, deployed or installed.", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("bundle", type=Path, help="Canonical HelixNotes x86_64/stable .flatpak bundle")
|
||||
parser.add_argument("--output", required=True, type=Path, help="Fresh output directory")
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument("--gpg-key", help="Full signing-key fingerprint (40 or 64 hexadecimal characters)")
|
||||
mode.add_argument("--unsigned", action="store_true", help="Local staging only; generate no installation descriptors")
|
||||
parser.add_argument("--gpg-homedir", type=Path, help="Existing GPG home; otherwise use the normal keyring")
|
||||
parser.add_argument("--url", default=DEFAULT_URL, help="Public base URL, excluding the repo/ suffix")
|
||||
parser.add_argument("--previous-directory", type=Path, help="Previous prepared output whose repo/history must be retained")
|
||||
args = parser.parse_args()
|
||||
if args.gpg_key:
|
||||
args.gpg_key = args.gpg_key.upper()
|
||||
if not re.fullmatch(r"(?:[0-9A-F]{40}|[0-9A-F]{64})", args.gpg_key):
|
||||
parser.error("--gpg-key must be a complete hexadecimal fingerprint")
|
||||
if args.gpg_homedir and args.unsigned:
|
||||
parser.error("--gpg-homedir requires --gpg-key")
|
||||
url = urlsplit(args.url)
|
||||
if (url.scheme != "https" or not url.netloc or url.username or url.password
|
||||
or url.query or url.fragment or any(ord(c) < 33 for c in args.url)):
|
||||
parser.error("--url must be an absolute HTTPS base URL without credentials, query or fragment")
|
||||
try:
|
||||
prepare(args)
|
||||
except (OSError, ValueError, configparser.Error, subprocess.CalledProcessError) as error:
|
||||
parser.exit(1, f"Preparation stopped: {error}\nAny partial output was preserved; choose a fresh output to retry.\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Submodule
+1
Submodule packaging/flatpak/shared-modules added at 6be1f986ac.
Generated
+206
-31
@@ -11,6 +11,24 @@ importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@codemirror/commands':
|
||||
specifier: ^6.11.1
|
||||
version: 6.11.1
|
||||
'@codemirror/lang-markdown':
|
||||
specifier: ^6.5.2
|
||||
version: 6.5.2
|
||||
'@codemirror/language':
|
||||
specifier: ^6.12.4
|
||||
version: 6.12.4
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.13
|
||||
version: 6.43.13
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.4
|
||||
version: 1.2.4
|
||||
'@tauri-apps/api':
|
||||
specifier: ^2.10.1
|
||||
version: 2.10.1
|
||||
@@ -26,9 +44,9 @@ importers:
|
||||
'@tiptap/core':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/pm@3.19.0)
|
||||
'@tiptap/extension-code-block-lowlight':
|
||||
'@tiptap/extension-code-block':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/extension-code-block@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)(highlight.js@11.11.1)(lowlight@3.3.0)
|
||||
version: 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
'@tiptap/extension-color':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/extension-text-style@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0)))
|
||||
@@ -44,9 +62,6 @@ importers:
|
||||
'@tiptap/extension-link':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
'@tiptap/extension-placeholder':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/extensions@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0))
|
||||
'@tiptap/extension-subscript':
|
||||
specifier: ^3.19.0
|
||||
version: 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
@@ -95,6 +110,12 @@ importers:
|
||||
'@types/markdown-it':
|
||||
specifier: ^14.1.2
|
||||
version: 14.1.2
|
||||
diff:
|
||||
specifier: ^9.0.0
|
||||
version: 9.0.0
|
||||
dompurify:
|
||||
specifier: ^3.4.13
|
||||
version: 3.4.13
|
||||
highlight.js:
|
||||
specifier: ^11.11.1
|
||||
version: 11.11.1
|
||||
@@ -178,6 +199,36 @@ packages:
|
||||
'@chevrotain/types@11.1.2':
|
||||
resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==}
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==}
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==}
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==}
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==}
|
||||
|
||||
'@codemirror/language@6.12.4':
|
||||
resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==}
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==}
|
||||
|
||||
'@codemirror/view@6.43.13':
|
||||
resolution: {integrity: sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==}
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -356,6 +407,30 @@ packages:
|
||||
'@jridgewell/trace-mapping@0.3.31':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@lezer/common@1.5.3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
|
||||
'@lezer/css@1.3.8':
|
||||
resolution: {integrity: sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og==}
|
||||
|
||||
'@lezer/highlight@1.2.4':
|
||||
resolution: {integrity: sha512-4UeRVFO0lsBaM7GA32zOqbmqNPme9jedo8Ey+5c5656MU3MLitMLIA8aCZTYjUMEpEsuSeXEm78Uea6Iq3bvSg==}
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
|
||||
|
||||
'@lezer/javascript@1.5.5':
|
||||
resolution: {integrity: sha512-sWg4yX1J6XW67AaAynVt0iwF0M5c+np36TEu+P2ifAJ8haRYvHnWDV28r1jdwnJehWCwXECutAUy56K4RBZIyg==}
|
||||
|
||||
'@lezer/lr@1.4.10':
|
||||
resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
|
||||
|
||||
'@lezer/markdown@1.7.2':
|
||||
resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==}
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4':
|
||||
resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
|
||||
|
||||
'@mermaid-js/parser@1.2.0':
|
||||
resolution: {integrity: sha512-oYPyv8A4As1yH5Bx+04iQEQxXuIQDe0GKCNSRgao6z8AM9jixXIfP0vsppRLvGf+nKIOb9/LdpWA4YuJiVvESA==}
|
||||
|
||||
@@ -764,15 +839,6 @@ packages:
|
||||
peerDependencies:
|
||||
'@tiptap/extension-list': ^3.19.0
|
||||
|
||||
'@tiptap/extension-code-block-lowlight@3.19.0':
|
||||
resolution: {integrity: sha512-P8O8i1J+XozEVA7bF/Ijwf/r1rVqrh1DBQ7dXxBcrUvLpIGyVjtxX228jBF/kD4kf2xOlphvjDhV2fLa8XOVsg==}
|
||||
peerDependencies:
|
||||
'@tiptap/core': ^3.19.0
|
||||
'@tiptap/extension-code-block': ^3.19.0
|
||||
'@tiptap/pm': ^3.19.0
|
||||
highlight.js: ^11
|
||||
lowlight: ^2 || ^3
|
||||
|
||||
'@tiptap/extension-code-block@3.19.0':
|
||||
resolution: {integrity: sha512-b/2qR+tMn8MQb+eaFYgVk4qXnLNkkRYmwELQ8LEtEDQPxa5Vl7J3eu8+4OyoIFhZrNDZvvoEp80kHMCP8sI6rg==}
|
||||
peerDependencies:
|
||||
@@ -874,11 +940,6 @@ packages:
|
||||
peerDependencies:
|
||||
'@tiptap/core': ^3.19.0
|
||||
|
||||
'@tiptap/extension-placeholder@3.19.0':
|
||||
resolution: {integrity: sha512-i15OfgyI4IDCYAcYSKUMnuZkYuUInfanjf9zquH8J2BETiomf/jZldVCp/QycMJ8DOXZ38fXDc99wOygnSNySg==}
|
||||
peerDependencies:
|
||||
'@tiptap/extensions': ^3.19.0
|
||||
|
||||
'@tiptap/extension-strike@3.19.0':
|
||||
resolution: {integrity: sha512-xYpabHsv7PccLUBQaP8AYiFCnYbx6P93RHPd0lgNwhdOjYFd931Zy38RyoxPHAgbYVmhf1iyx7lpuLtBnhS5dA==}
|
||||
peerDependencies:
|
||||
@@ -1318,6 +1379,10 @@ packages:
|
||||
devlop@1.1.0:
|
||||
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
|
||||
|
||||
diff@9.0.0:
|
||||
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
|
||||
engines: {node: '>=0.3.1'}
|
||||
|
||||
dompurify@3.4.13:
|
||||
resolution: {integrity: sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==}
|
||||
|
||||
@@ -1680,6 +1745,9 @@ packages:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
style-mod@4.1.4:
|
||||
resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==}
|
||||
|
||||
stylis@4.4.0:
|
||||
resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==}
|
||||
|
||||
@@ -1800,6 +1868,86 @@ snapshots:
|
||||
|
||||
'@chevrotain/types@11.1.2': {}
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.8
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.8
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.5
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/markdown': 1.7.2
|
||||
|
||||
'@codemirror/language@6.12.4':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.4
|
||||
'@lezer/lr': 1.4.10
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
crelt: 1.0.6
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
dependencies:
|
||||
'@marijn/find-cluster-break': 1.0.4
|
||||
|
||||
'@codemirror/view@6.43.13':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
crelt: 1.0.6
|
||||
style-mod: 4.1.4
|
||||
w3c-keyname: 2.2.8
|
||||
|
||||
'@esbuild/aix-ppc64@0.28.2':
|
||||
optional: true
|
||||
|
||||
@@ -1905,6 +2053,41 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
|
||||
'@lezer/common@1.5.3': {}
|
||||
|
||||
'@lezer/css@1.3.8':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.4
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/highlight@1.2.4':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.4
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/javascript@1.5.5':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.4
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/lr@1.4.10':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/markdown@1.7.2':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.4
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4': {}
|
||||
|
||||
'@mermaid-js/parser@1.2.0':
|
||||
dependencies:
|
||||
'@chevrotain/types': 11.1.2
|
||||
@@ -2195,14 +2378,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@tiptap/extension-list': 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
|
||||
'@tiptap/extension-code-block-lowlight@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/extension-code-block@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)(highlight.js@11.11.1)(lowlight@3.3.0)':
|
||||
dependencies:
|
||||
'@tiptap/core': 3.19.0(@tiptap/pm@3.19.0)
|
||||
'@tiptap/extension-code-block': 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
'@tiptap/pm': 3.19.0
|
||||
highlight.js: 11.11.1
|
||||
lowlight: 3.3.0
|
||||
|
||||
'@tiptap/extension-code-block@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)':
|
||||
dependencies:
|
||||
'@tiptap/core': 3.19.0(@tiptap/pm@3.19.0)
|
||||
@@ -2286,10 +2461,6 @@ snapshots:
|
||||
dependencies:
|
||||
'@tiptap/core': 3.19.0(@tiptap/pm@3.19.0)
|
||||
|
||||
'@tiptap/extension-placeholder@3.19.0(@tiptap/extensions@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0))':
|
||||
dependencies:
|
||||
'@tiptap/extensions': 3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))(@tiptap/pm@3.19.0)
|
||||
|
||||
'@tiptap/extension-strike@3.19.0(@tiptap/core@3.19.0(@tiptap/pm@3.19.0))':
|
||||
dependencies:
|
||||
'@tiptap/core': 3.19.0(@tiptap/pm@3.19.0)
|
||||
@@ -2785,6 +2956,8 @@ snapshots:
|
||||
dependencies:
|
||||
dequal: 2.0.3
|
||||
|
||||
diff@9.0.0: {}
|
||||
|
||||
dompurify@3.4.13:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
@@ -3193,6 +3366,8 @@ snapshots:
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
|
||||
style-mod@4.1.4: {}
|
||||
|
||||
stylis@4.4.0: {}
|
||||
|
||||
svelte-check@4.3.6(picomatch@4.0.5)(svelte@5.56.9)(typescript@5.9.3):
|
||||
|
||||
Generated
+7
-2
@@ -1,6 +1,6 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
@@ -1776,17 +1776,21 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "helixnotes"
|
||||
version = "1.3.5"
|
||||
version = "1.3.7"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"arboard",
|
||||
"chrono",
|
||||
"dirs",
|
||||
"fs4",
|
||||
"futures",
|
||||
"gray_matter",
|
||||
"image",
|
||||
"libc",
|
||||
"log",
|
||||
"notify",
|
||||
"objc2-app-kit",
|
||||
"parking_lot",
|
||||
"png 0.17.16",
|
||||
"quick-xml",
|
||||
"rayon",
|
||||
@@ -1809,6 +1813,7 @@ dependencies = [
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tauri-plugin-window-state",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"urlencoding",
|
||||
"uuid",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "helixnotes"
|
||||
version = "1.3.5"
|
||||
version = "1.3.7"
|
||||
description = "Local markdown note-taking app"
|
||||
authors = ["HelixNotes"]
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -32,7 +32,9 @@ serde_json = "1"
|
||||
serde_yaml = "0.9"
|
||||
log = "0.4"
|
||||
notify = "8"
|
||||
parking_lot = "0.12"
|
||||
walkdir = "2"
|
||||
tempfile = "3"
|
||||
chrono = { version = "0.4", features = ["serde", "unstable-locales"] }
|
||||
sys-locale = "0.3"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
@@ -41,6 +43,7 @@ gray_matter = "0.2"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
dirs = "6"
|
||||
regex = "1"
|
||||
aho-corasick = "1"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "blocking"] }
|
||||
futures = "0.3"
|
||||
@@ -48,10 +51,14 @@ rayon = "1"
|
||||
quick-xml = "0.41"
|
||||
urlencoding = "2"
|
||||
sha2 = "0.10"
|
||||
fs4 = { version = "0.8", default-features = false }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] }
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2-app-kit = "0.3.2"
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies]
|
||||
tauri-plugin-ios-vault-access = { path = "plugins/ios-vault-access" }
|
||||
|
||||
|
||||
@@ -33,6 +33,19 @@ class MainActivity : TauriActivity() {
|
||||
// paragraph font-size and line-height from viewport heuristics and ignores our CSS (only
|
||||
// size + line-height were affected; font-family was fine). NORMAL turns it off. (#100)
|
||||
webView.settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.NORMAL
|
||||
// Honor the viewport meta tag's scale, which is how the Interface Scale setting is applied
|
||||
// on Android (WebView zoom APIs are not exposed through Tauri here). (#288)
|
||||
webView.settings.useWideViewPort = true
|
||||
}
|
||||
|
||||
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() {
|
||||
|
||||
+78
-46
@@ -89,6 +89,7 @@ pub fn ai_request(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.clone(),
|
||||
event_type: "error".to_string(),
|
||||
text: None,
|
||||
error: Some(e),
|
||||
@@ -109,13 +110,40 @@ fn normalize_openai_base(base: &str) -> String {
|
||||
.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(
|
||||
app: &AppHandle,
|
||||
api_key: &str,
|
||||
model: &str,
|
||||
system_prompt: &str,
|
||||
user_message: &str,
|
||||
_request_id: &str,
|
||||
request_id: &str,
|
||||
) -> Result<(), String> {
|
||||
let client = Client::new();
|
||||
|
||||
@@ -168,6 +196,7 @@ async fn stream_anthropic(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -185,6 +214,7 @@ async fn stream_anthropic(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "text".to_string(),
|
||||
text: Some(text.to_string()),
|
||||
error: None,
|
||||
@@ -196,6 +226,7 @@ async fn stream_anthropic(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -210,6 +241,7 @@ async fn stream_anthropic(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "error".to_string(),
|
||||
text: None,
|
||||
error: Some(msg.to_string()),
|
||||
@@ -228,6 +260,7 @@ async fn stream_anthropic(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -244,37 +277,11 @@ async fn stream_openai(
|
||||
model: &str,
|
||||
system_prompt: &str,
|
||||
user_message: &str,
|
||||
_request_id: &str,
|
||||
request_id: &str,
|
||||
) -> Result<(), String> {
|
||||
let client = Client::new();
|
||||
|
||||
let is_gpt5 = model.starts_with("gpt-5");
|
||||
let token_key = if is_gpt5 {
|
||||
"max_completion_tokens"
|
||||
} else {
|
||||
"max_tokens"
|
||||
};
|
||||
|
||||
let mut body = 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 body = openai_request_body(model, Some(system_prompt), user_message, true, 4096);
|
||||
|
||||
let mut req = client.post(url).header("content-type", "application/json");
|
||||
|
||||
@@ -312,6 +319,7 @@ async fn stream_openai(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -327,6 +335,7 @@ async fn stream_openai(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "text".to_string(),
|
||||
text: Some(content.to_string()),
|
||||
error: None,
|
||||
@@ -341,6 +350,7 @@ async fn stream_openai(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -355,6 +365,7 @@ async fn stream_openai(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "error".to_string(),
|
||||
text: None,
|
||||
error: Some(err.to_string()),
|
||||
@@ -371,6 +382,7 @@ async fn stream_openai(
|
||||
let _ = app.emit(
|
||||
"ai-stream",
|
||||
AiStreamEvent {
|
||||
request_id: request_id.to_owned(),
|
||||
event_type: "done".to_string(),
|
||||
text: None,
|
||||
error: None,
|
||||
@@ -445,23 +457,7 @@ 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> {
|
||||
let client = Client::new();
|
||||
let is_gpt5 = model.starts_with("gpt-5");
|
||||
let token_key = if is_gpt5 {
|
||||
"max_completion_tokens"
|
||||
} else {
|
||||
"max_tokens"
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
token_key: 20,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Hi"
|
||||
}
|
||||
]
|
||||
});
|
||||
let body = openai_request_body(model, None, "Hi", false, 20);
|
||||
|
||||
let mut req = client.post(url).header("content-type", "application/json");
|
||||
|
||||
@@ -483,3 +479,39 @@ async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<St
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,38 @@
|
||||
use std::path::Path;
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
use tauri_plugin_fs::FsExt;
|
||||
|
||||
/// Only configured user-selected vaults may provide an external note's vault-relative root.
|
||||
pub fn external_note_root<R: Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
note_path: &Path,
|
||||
) -> Result<std::path::PathBuf, String> {
|
||||
let note = std::fs::canonicalize(note_path).map_err(|error| error.to_string())?;
|
||||
if let Some(state) = app.try_state::<crate::state::AppState>() {
|
||||
let (active, mut roots) = {
|
||||
let config = state.config.lock().map_err(|error| error.to_string())?;
|
||||
(
|
||||
config.active_vault.clone(),
|
||||
config
|
||||
.vaults
|
||||
.iter()
|
||||
.map(|vault| vault.path.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
};
|
||||
roots.sort_by_key(|root| std::cmp::Reverse(root.len()));
|
||||
for root in active.into_iter().chain(roots) {
|
||||
if let Ok(root) = std::fs::canonicalize(root) {
|
||||
if note.starts_with(&root) {
|
||||
return Ok(root);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
note.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.ok_or_else(|| "External note has no parent directory".into())
|
||||
}
|
||||
|
||||
/// Grants asset-protocol access only to a vault selected by the user.
|
||||
/// `.helixnotes` is added explicitly because Unix glob matching excludes hidden paths.
|
||||
@@ -37,7 +70,23 @@ pub fn allow_external_note_assets<R: Runtime>(
|
||||
.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())
|
||||
.map_err(|error| error.to_string())?;
|
||||
let root = external_note_root(app, ¬e)?;
|
||||
let attachments = root.join(".helixnotes/attachments");
|
||||
// Never follow a hidden attachment-directory symlink when extending either scope.
|
||||
if std::fs::canonicalize(&attachments)
|
||||
.is_ok_and(|canonical| canonical == attachments && canonical.is_dir())
|
||||
{
|
||||
app.asset_protocol_scope()
|
||||
.allow_directory(&attachments, true)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if let Some(scope) = app.try_fs_scope() {
|
||||
scope
|
||||
.allow_directory(&attachments, true)
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -85,6 +134,101 @@ mod tests {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_note_scopes_include_its_attachments_but_not_hidden_private_metadata() {
|
||||
use tauri_plugin_fs::FsExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let parent = root.path().join("external");
|
||||
let attachments = parent.join(".helixnotes/attachments");
|
||||
fs::create_dir_all(&attachments).unwrap();
|
||||
fs::create_dir_all(parent.join(".helixnotes/history")).unwrap();
|
||||
fs::create_dir_all(parent.join(".ssh")).unwrap();
|
||||
let note = parent.join("Note.md");
|
||||
let image = attachments.join("image.png");
|
||||
let history = parent.join(".helixnotes/history/snapshot.md");
|
||||
let private = parent.join(".ssh/private.bin");
|
||||
for file in [¬e, &image, &history, &private] {
|
||||
fs::write(file, b"fixture").unwrap();
|
||||
}
|
||||
let app = tauri::test::mock_builder()
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.build(tauri::test::mock_context(tauri::test::noop_assets()))
|
||||
.unwrap();
|
||||
app.fs_scope().allow_file(¬e).unwrap();
|
||||
app.fs_scope().allow_directory(&parent, true).unwrap();
|
||||
let before_private = [
|
||||
app.fs_scope().is_allowed(&history),
|
||||
app.fs_scope().is_allowed(&private),
|
||||
];
|
||||
allow_external_note_assets(app.handle(), ¬e).unwrap();
|
||||
assert!(
|
||||
app.fs_scope().is_allowed(&image),
|
||||
"import must be able to read its managed attachments"
|
||||
);
|
||||
assert!(
|
||||
app.asset_protocol_scope().is_allowed(&image),
|
||||
"the viewer must display managed attachments"
|
||||
);
|
||||
for (file, previous) in [&history, &private].into_iter().zip(before_private) {
|
||||
assert_eq!(
|
||||
app.fs_scope().is_allowed(file),
|
||||
previous,
|
||||
"attachment grants must not widen private metadata access"
|
||||
);
|
||||
assert!(!app.asset_protocol_scope().is_allowed(file));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_notebook_uses_its_registered_vault_root_for_attachment_scopes() {
|
||||
use tauri_plugin_fs::FsExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let vault = root.path().join("source");
|
||||
fs::create_dir_all(vault.join("Notebook")).unwrap();
|
||||
fs::create_dir_all(vault.join(".helixnotes/attachments")).unwrap();
|
||||
let note = vault.join("Notebook/Note.md");
|
||||
let image = vault.join(".helixnotes/attachments/image.png");
|
||||
fs::write(¬e, b"Note").unwrap();
|
||||
fs::write(&image, b"Image").unwrap();
|
||||
let app = tauri::test::mock_builder()
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.manage(crate::state::AppState::new(crate::types::AppConfig {
|
||||
vaults: vec![crate::types::VaultConfig {
|
||||
path: vault.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}))
|
||||
.build(tauri::test::mock_context(tauri::test::noop_assets()))
|
||||
.unwrap();
|
||||
allow_external_note_assets(app.handle(), ¬e).unwrap();
|
||||
assert!(app.asset_protocol_scope().is_allowed(&image));
|
||||
assert!(app.fs_scope().is_allowed(&image));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_attachment_scope_does_not_follow_hidden_directory_symlinks() {
|
||||
use tauri_plugin_fs::FsExt;
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let parent = root.path().join("external");
|
||||
let private = root.path().join("private");
|
||||
fs::create_dir_all(parent.join(".helixnotes")).unwrap();
|
||||
fs::create_dir(&private).unwrap();
|
||||
let note = parent.join("Note.md");
|
||||
let file = private.join("private.bin");
|
||||
fs::write(¬e, b"Note").unwrap();
|
||||
fs::write(&file, b"private fixture").unwrap();
|
||||
std::os::unix::fs::symlink(&private, parent.join(".helixnotes/attachments")).unwrap();
|
||||
let app = tauri::test::mock_builder()
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.build(tauri::test::mock_context(tauri::test::noop_assets()))
|
||||
.unwrap();
|
||||
allow_external_note_assets(app.handle(), ¬e).unwrap();
|
||||
assert!(!app.fs_scope().is_allowed(&file));
|
||||
assert!(!app.asset_protocol_scope().is_allowed(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_note_scope_allows_relative_assets_only_below_its_directory() {
|
||||
let root = test_directory("external-note-assets");
|
||||
|
||||
+1077
-172
File diff suppressed because it is too large.
Load diff
+3526
-875
File diff suppressed because it is too large.
Load diff
+241
-59
@@ -18,10 +18,101 @@ fn safe_path_component<'a>(value: &'a str, label: &str) -> Result<&'a str, Strin
|
||||
|
||||
/// Directory: .helixnotes/history/<note-id>/
|
||||
fn history_dir(vault_path: &str, note_id: &str) -> Result<PathBuf, String> {
|
||||
Ok(Path::new(vault_path)
|
||||
.join(".helixnotes")
|
||||
.join("history")
|
||||
.join(safe_path_component(note_id, "note ID")?))
|
||||
let mut dir = PathBuf::from(vault_path);
|
||||
// Each level must be a real folder. A link here (carried in by git, a file-sync tool or an
|
||||
// extracted archive) would send snapshots, and the pruning that deletes old ones, to whatever
|
||||
// folder it points at.
|
||||
for part in [
|
||||
".helixnotes",
|
||||
"history",
|
||||
safe_path_component(note_id, "note ID")?,
|
||||
] {
|
||||
dir.push(part);
|
||||
if fs::symlink_metadata(&dir).is_ok_and(|meta| !meta.file_type().is_dir()) {
|
||||
return Err("Version history folder is not a real folder".to_string());
|
||||
}
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// `2026-01-02T03-04-05.md` or `2026-01-02T03-04-05.678.md`: the only names snapshots are given.
|
||||
fn is_snapshot_name(name: &str) -> bool {
|
||||
let Some(stem) = name.strip_suffix(".md") else {
|
||||
return false;
|
||||
};
|
||||
let (Some(time), Some(fraction)) = (stem.get(..19), stem.get(19..)) else {
|
||||
return false;
|
||||
};
|
||||
chrono::NaiveDateTime::parse_from_str(time, "%Y-%m-%dT%H-%M-%S").is_ok()
|
||||
&& (fraction.is_empty()
|
||||
|| fraction.strip_prefix('.').is_some_and(|digits| {
|
||||
!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
|
||||
}))
|
||||
}
|
||||
|
||||
/// A snapshot the app wrote: a regular file (never a link) with a snapshot name.
|
||||
fn is_snapshot_file(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(is_snapshot_name)
|
||||
&& fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file())
|
||||
}
|
||||
|
||||
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 crate::vault::operations::persist_without_replacing(temporary, &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.
|
||||
@@ -32,31 +123,34 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
|
||||
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) {
|
||||
let mut files: Vec<String> = entries
|
||||
.filter_map(|e| e.ok())
|
||||
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
|
||||
.filter(|n| n.ends_with(".md"))
|
||||
.collect();
|
||||
files.sort();
|
||||
|
||||
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 latest = entries
|
||||
.filter_map(|entry| {
|
||||
let name = entry.ok()?.file_name();
|
||||
let name = name.to_str()?;
|
||||
if !name.ends_with(".md") {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,12 +160,8 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
|
||||
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);
|
||||
if let Err(error) = snapshot_path(&dir, raw_content) {
|
||||
eprintln!("Failed to write version snapshot: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -91,11 +181,7 @@ pub fn force_snapshot(
|
||||
let dir = history_dir(vault_path, note_id)?;
|
||||
fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
|
||||
|
||||
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
|
||||
let filename = format!("{}.md", timestamp);
|
||||
let path = dir.join(&filename);
|
||||
|
||||
fs::write(&path, raw_content).map_err(|error| error.to_string())?;
|
||||
snapshot_path(&dir, raw_content)?;
|
||||
|
||||
if max_versions > 0 {
|
||||
prune_versions(&dir, max_versions)?;
|
||||
@@ -115,7 +201,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())? {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
let path = entry.path();
|
||||
if path.extension().is_some_and(|ext| ext == "md") {
|
||||
if is_snapshot_file(&path) {
|
||||
let filename = path
|
||||
.file_stem()
|
||||
.unwrap_or_default()
|
||||
@@ -123,16 +209,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
|
||||
.to_string();
|
||||
let meta = fs::metadata(&path).map_err(|e| e.to_string())?;
|
||||
|
||||
// Parse timestamp from 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()
|
||||
};
|
||||
|
||||
let timestamp = version_timestamp(&filename);
|
||||
entries.push(VersionEntry {
|
||||
timestamp,
|
||||
size: meta.len(),
|
||||
@@ -148,17 +225,13 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
|
||||
/// Get the raw content of a specific version.
|
||||
pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<String, String> {
|
||||
safe_path_component(timestamp, "version timestamp")?;
|
||||
// Convert ISO timestamp back to filename: 2026-02-08T18:30:00Z → 2026-02-08T18-30-00.md
|
||||
let filename = if let Some(t_pos) = timestamp.find('T') {
|
||||
let date_part = ×tamp[..t_pos];
|
||||
let time_part = timestamp[t_pos + 1..].trim_end_matches('Z');
|
||||
let time_dashes = time_part.replace(':', "-");
|
||||
format!("{date_part}T{time_dashes}.md")
|
||||
} else {
|
||||
format!("{}.md", timestamp)
|
||||
};
|
||||
// Accept both legacy second-resolution names and unique suffixes.
|
||||
let filename = snapshot_filename(timestamp);
|
||||
|
||||
let path = history_dir(vault_path, note_id)?.join(&filename);
|
||||
if !is_snapshot_file(&path) {
|
||||
return Err("Version not found".to_string());
|
||||
}
|
||||
fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e))
|
||||
}
|
||||
|
||||
@@ -168,7 +241,8 @@ fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
|
||||
.map_err(|e| e.to_string())?
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|ext| ext == "md"))
|
||||
// Only snapshots are counted and removed, never other Markdown files that ended up here.
|
||||
.filter(|p| is_snapshot_file(p))
|
||||
.collect();
|
||||
|
||||
// Sort by name (timestamps sort lexicographically) - newest last
|
||||
@@ -206,4 +280,112 @@ mod tests {
|
||||
|
||||
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();
|
||||
// The file that is not named like a snapshot is neither a version nor in the way.
|
||||
assert_eq!(versions.len(), 2);
|
||||
assert_eq!(
|
||||
get_version(root, "note", "2026-01-01T00:00:00Z").unwrap(),
|
||||
"legacy"
|
||||
);
|
||||
assert_eq!(
|
||||
get_version(root, "note", &versions[0].timestamp).unwrap(),
|
||||
"new"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_linked_history_folder_is_never_written_to_or_pruned() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let root = vault.path().to_str().unwrap();
|
||||
// A folder of ordinary notes somewhere else, more than the pruning limit.
|
||||
for index in 0..25 {
|
||||
fs::write(
|
||||
outside.path().join(format!("note-{index:02}.md")),
|
||||
"precious",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let history = vault.path().join(".helixnotes/history");
|
||||
fs::create_dir_all(&history).unwrap();
|
||||
symlink(outside.path(), history.join("linked")).unwrap();
|
||||
|
||||
assert!(super::force_snapshot(root, "linked", "new", 20).is_err());
|
||||
super::maybe_snapshot(root, "linked", "new", 20);
|
||||
assert!(list_versions(root, "linked").is_err());
|
||||
assert!(get_version(root, "linked", "note-00").is_err());
|
||||
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 25);
|
||||
|
||||
// The same when a higher level is the link.
|
||||
let second = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(second.path().join(".helixnotes")).unwrap();
|
||||
symlink(outside.path(), second.path().join(".helixnotes/history")).unwrap();
|
||||
assert!(super::force_snapshot(second.path().to_str().unwrap(), "note", "new", 20).is_err());
|
||||
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pruning_and_listing_only_touch_snapshots() {
|
||||
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();
|
||||
// Markdown files that are not snapshots, sorting before and after real ones.
|
||||
fs::write(history.join("README.md"), "keep").unwrap();
|
||||
fs::write(history.join("zz-00.md"), "keep").unwrap();
|
||||
fs::write(history.join("2026-01-01T00-00-00.md"), "old").unwrap();
|
||||
fs::write(history.join("2026-01-02T00-00-00.123.md"), "newer").unwrap();
|
||||
super::force_snapshot(root, "note", "newest", 2).unwrap();
|
||||
let versions = list_versions(root, "note").unwrap();
|
||||
assert_eq!(versions.len(), 2);
|
||||
assert!(!history.join("2026-01-01T00-00-00.md").exists());
|
||||
assert!(history.join("README.md").exists() && history.join("zz-00.md").exists());
|
||||
assert!(get_version(root, "note", "zz-00").is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let target = vault.path().join("secret.md");
|
||||
fs::write(&target, "outside history").unwrap();
|
||||
std::os::unix::fs::symlink(&target, history.join("2026-01-03T00-00-00.md")).unwrap();
|
||||
assert!(get_version(root, "note", "2026-01-03T00:00:00Z").is_err());
|
||||
assert_eq!(list_versions(root, "note").unwrap().len(), 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
use reqwest::{blocking::Client, redirect::Policy, Url};
|
||||
use reqwest::{
|
||||
blocking::{Client, Response},
|
||||
redirect::Policy,
|
||||
StatusCode, 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;
|
||||
const MAX_REDIRECTS: usize = 5;
|
||||
|
||||
pub struct ImageResponse {
|
||||
pub content_type: String,
|
||||
@@ -136,37 +141,55 @@ fn resolve_public_host(url: &Url) -> Result<(String, Vec<SocketAddr>), ProxyErro
|
||||
Ok((host, addresses))
|
||||
}
|
||||
|
||||
// Redirects are followed by `fetch`, one hop at a time, so every hop gets the same checks.
|
||||
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()
|
||||
}
|
||||
}))
|
||||
.redirect(Policy::none())
|
||||
.resolve_to_addrs(host, addresses)
|
||||
.build()
|
||||
.map_err(|error| ProxyError::Fetch(format!("Could not create image client: {error}")))
|
||||
}
|
||||
|
||||
/// The validated target of a redirect response, or `None` when the response is not a redirect.
|
||||
fn redirect_target(
|
||||
url: &Url,
|
||||
status: StatusCode,
|
||||
location: Option<&str>,
|
||||
) -> Result<Option<Url>, ProxyError> {
|
||||
if !matches!(status.as_u16(), 301 | 302 | 303 | 307 | 308) {
|
||||
return Ok(None);
|
||||
}
|
||||
let target = location
|
||||
.and_then(|location| url.join(location).ok())
|
||||
.ok_or_else(|| ProxyError::Fetch("Image redirect has no usable target".into()))?;
|
||||
validate_url(target.as_str()).map(Some)
|
||||
}
|
||||
|
||||
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}")))?;
|
||||
let mut url = validate_url(raw_url)?;
|
||||
for _ in 0..=MAX_REDIRECTS {
|
||||
// Each hop is resolved, checked for private addresses and pinned to that answer,
|
||||
// so a redirect cannot reach a host that a direct image URL could not.
|
||||
let (host, addresses) = resolve_public_host(&url)?;
|
||||
let client = image_client(&host, &addresses)?;
|
||||
let response = client
|
||||
.get(url.clone())
|
||||
.send()
|
||||
.map_err(|error| ProxyError::Fetch(format!("Image request failed: {error}")))?;
|
||||
let location = response
|
||||
.headers()
|
||||
.get(reqwest::header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok());
|
||||
match redirect_target(&url, response.status(), location)? {
|
||||
Some(target) => url = target,
|
||||
None => return read_image(response),
|
||||
}
|
||||
}
|
||||
Err(ProxyError::Fetch("Image redirected too many times".into()))
|
||||
}
|
||||
|
||||
fn read_image(mut response: Response) -> Result<ImageResponse, ProxyError> {
|
||||
if !response.status().is_success() {
|
||||
return Err(ProxyError::Fetch(format!(
|
||||
"Image server returned {}",
|
||||
@@ -204,7 +227,8 @@ pub fn fetch(raw_url: &str) -> Result<ImageResponse, ProxyError> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{is_public_ip, validate_url};
|
||||
use super::{is_public_ip, redirect_target, validate_url};
|
||||
use reqwest::{StatusCode, Url};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
|
||||
#[test]
|
||||
@@ -242,4 +266,39 @@ mod tests {
|
||||
assert!(validate_url("https://example.com/image.png").is_ok());
|
||||
assert!(validate_url("http://93.184.216.34/image.png").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirects_are_followed_to_other_public_hosts_only() {
|
||||
let url = Url::parse("https://example.com/a/image.png").unwrap();
|
||||
let target = |status: u16, location: Option<&str>| {
|
||||
redirect_target(&url, StatusCode::from_u16(status).unwrap(), location)
|
||||
};
|
||||
let ok = |status, location| target(status, Some(location)).ok().unwrap().unwrap();
|
||||
assert_eq!(
|
||||
ok(301, "https://cdn.example.net/image.png").as_str(),
|
||||
"https://cdn.example.net/image.png"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(302, "/b/image.png").as_str(),
|
||||
"https://example.com/b/image.png"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(307, "other.png").as_str(),
|
||||
"https://example.com/a/other.png"
|
||||
);
|
||||
assert!(target(200, None).ok().unwrap().is_none());
|
||||
assert!(target(304, None).ok().unwrap().is_none());
|
||||
for location in [
|
||||
"http://localhost/image.png",
|
||||
"http://127.0.0.1/image.png",
|
||||
"http://169.254.169.254/latest/meta-data",
|
||||
"http://[::1]/image.png",
|
||||
"https://example.net:8443/image.png",
|
||||
"https://user:pass@example.net/image.png",
|
||||
"file:///etc/passwd",
|
||||
] {
|
||||
assert!(target(302, Some(location)).is_err(), "{location}");
|
||||
}
|
||||
assert!(target(302, None).is_err());
|
||||
}
|
||||
}
|
||||
+56
-27
@@ -37,8 +37,6 @@ pub fn run() {
|
||||
let config = commands::load_app_config();
|
||||
#[cfg(desktop)]
|
||||
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);
|
||||
|
||||
// Inject the compile-time platform so the frontend never sniffs the (sometimes
|
||||
@@ -148,9 +146,9 @@ pub fn run() {
|
||||
asset_scope::allow_external_note_assets(app.handle(), &resolved);
|
||||
}
|
||||
let app_state = app.state::<AppState>();
|
||||
let _ = app_state.pending_open_file.lock().map(|mut p| {
|
||||
*p = Some(resolved_str.to_string());
|
||||
});
|
||||
if let Err(error) = app_state.enqueue_open_file(resolved_str.to_string()) {
|
||||
log::error!("Could not queue startup file: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,6 +162,8 @@ pub fn run() {
|
||||
commands::restore_external_vault,
|
||||
commands::remove_vault,
|
||||
commands::get_app_config,
|
||||
#[cfg(desktop)]
|
||||
commands::complete_window_close,
|
||||
commands::set_theme,
|
||||
commands::set_system_themes,
|
||||
commands::set_accent_color,
|
||||
@@ -173,6 +173,7 @@ pub fn run() {
|
||||
commands::import_custom_themes,
|
||||
commands::set_font_size,
|
||||
commands::set_scroll_to_change_font_size,
|
||||
commands::set_toolbar_layout,
|
||||
commands::set_font_family,
|
||||
commands::set_line_height,
|
||||
commands::set_ui_scale,
|
||||
@@ -186,6 +187,7 @@ pub fn run() {
|
||||
commands::get_notes,
|
||||
commands::read_note,
|
||||
commands::save_note,
|
||||
commands::import_note,
|
||||
commands::create_note,
|
||||
commands::duplicate_note,
|
||||
commands::create_daily_note,
|
||||
@@ -210,12 +212,17 @@ pub fn run() {
|
||||
commands::load_vault_state,
|
||||
commands::save_vault_state,
|
||||
commands::copy_text_to_clipboard,
|
||||
commands::read_clipboard_contents,
|
||||
commands::read_clipboard_image,
|
||||
commands::copy_image_to_clipboard,
|
||||
commands::save_image,
|
||||
commands::save_attachment,
|
||||
commands::get_notebook_icons,
|
||||
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::get_quick_access,
|
||||
commands::add_quick_access,
|
||||
@@ -248,6 +255,9 @@ pub fn run() {
|
||||
commands::get_install_type,
|
||||
commands::is_mobile_platform,
|
||||
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| {
|
||||
let path = request.uri().path().to_string();
|
||||
@@ -302,7 +312,14 @@ pub fn run() {
|
||||
}
|
||||
let _ = asset_scope::allow_external_note_assets(app, &resolved);
|
||||
}
|
||||
let _ = app.emit("open-file", resolved_str.to_string());
|
||||
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", ());
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
@@ -335,32 +352,44 @@ pub fn run() {
|
||||
queue_macos_traffic_light_fix(window);
|
||||
}
|
||||
|
||||
match event {
|
||||
tauri::WindowEvent::CloseRequested { api, .. } => {
|
||||
// Only hide to tray for the main window
|
||||
if close_to_tray && window.label() == "main" {
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
// Closing the main window also requests a save-aware close of note windows.
|
||||
if matches!(event, tauri::WindowEvent::Destroyed) && window.label() == "main" {
|
||||
for (label, win) in window.app_handle().webview_windows() {
|
||||
if label.starts_with("note-") {
|
||||
let _ = win.close();
|
||||
}
|
||||
}
|
||||
tauri::WindowEvent::Destroyed
|
||||
// When main window is destroyed, close all note windows
|
||||
if window.label() == "main" => {
|
||||
let app = window.app_handle();
|
||||
for (label, win) in app.webview_windows() {
|
||||
if label.starts_with("note-") {
|
||||
let _ = win.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
builder
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
let app = builder
|
||||
.build(tauri::generate_context!())
|
||||
.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)]
|
||||
@@ -369,7 +398,7 @@ fn setup_tray(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
|
||||
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;
|
||||
|
||||
let _tray = TrayIconBuilder::new()
|
||||
let _tray = TrayIconBuilder::with_id("helixnotes")
|
||||
.icon(
|
||||
Image::from_path("icons/32x32.png")
|
||||
.unwrap_or_else(|_| app.default_window_icon().cloned().unwrap()),
|
||||
|
||||
+1510
-216
File diff suppressed because it is too large.
Load diff
+289
-7
@@ -1,30 +1,312 @@
|
||||
use crate::search::SearchIndex;
|
||||
use crate::search::{SearchIndex, SearchIndexShutdown};
|
||||
use crate::types::AppConfig;
|
||||
use crate::vault::watcher::VaultWatcher;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
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 config: Mutex<AppConfig>,
|
||||
pub search_index: Mutex<Option<Arc<SearchIndex>>>,
|
||||
pub watcher: Mutex<Option<VaultWatcher>>,
|
||||
search_indexes: Mutex<HashMap<String, CachedSearchIndex>>,
|
||||
pub watchers: Mutex<HashMap<String, VaultWatcher>>,
|
||||
pub vault_transition: tokio::sync::Mutex<()>,
|
||||
pub vault_maintenance: Arc<tokio::sync::Mutex<()>>,
|
||||
pub note_save: Arc<tokio::sync::Mutex<()>>,
|
||||
pub importing: AtomicBool,
|
||||
pub syncing: AtomicBool,
|
||||
pub pending_open_file: Mutex<Option<String>>,
|
||||
#[cfg(desktop)]
|
||||
pub quitting: AtomicBool,
|
||||
pending_open_files: Mutex<PendingOpenFiles>,
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
config: Mutex::new(config),
|
||||
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_maintenance: Arc::new(tokio::sync::Mutex::new(())),
|
||||
note_save: Arc::new(tokio::sync::Mutex::new(())),
|
||||
importing: 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());
|
||||
}
|
||||
}
|
||||
+2188
-272
File diff suppressed because it is too large.
Load diff
+124
-6
@@ -42,6 +42,37 @@ pub struct NotebookEntry {
|
||||
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)]
|
||||
pub struct NoteContent {
|
||||
pub path: String,
|
||||
@@ -71,8 +102,13 @@ pub struct VaultConfig {
|
||||
pub sync_on_change: bool,
|
||||
#[serde(default)]
|
||||
pub sync_interval_minutes: u32,
|
||||
/// Folders to list on the server at once; 0 means the default.
|
||||
#[serde(default)]
|
||||
pub sync_folder_requests: u32,
|
||||
#[serde(default)]
|
||||
pub last_sync_time: Option<String>,
|
||||
#[serde(default)]
|
||||
pub last_backup_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -108,7 +144,41 @@ pub enum StartupView {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ToolbarLayout {
|
||||
pub main: Vec<String>,
|
||||
pub more: Vec<String>,
|
||||
}
|
||||
|
||||
/// Keeps the entries of a list that still parse and drops the rest, so one damaged entry (a custom
|
||||
/// theme missing a color, say) does not make the whole configuration unreadable.
|
||||
fn lenient_list<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
let values = Vec::<serde_json::Value>::deserialize(deserializer).unwrap_or_default();
|
||||
Ok(values
|
||||
.into_iter()
|
||||
.filter_map(|value| serde_json::from_value(value).ok())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// An optional setting that no longer parses is treated as not set.
|
||||
fn lenient_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
let value = serde_json::Value::deserialize(deserializer).unwrap_or(serde_json::Value::Null);
|
||||
Ok(serde_json::from_value(value).ok())
|
||||
}
|
||||
|
||||
// Missing keys take their default: a configuration written by an older version, or edited by
|
||||
// hand, must still load instead of being replaced by a blank one.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct AppConfig {
|
||||
#[serde(deserialize_with = "lenient_list")]
|
||||
pub vaults: Vec<VaultConfig>,
|
||||
pub active_vault: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -124,8 +194,14 @@ pub struct AppConfig {
|
||||
pub accent_color: Option<String>,
|
||||
#[serde(default)]
|
||||
pub font_size: Option<u32>,
|
||||
/// The size chosen in Appearance. Zooming changes `font_size` only, and resetting the zoom
|
||||
/// returns to this.
|
||||
#[serde(default)]
|
||||
pub preferred_font_size: Option<u32>,
|
||||
#[serde(default = "default_true")]
|
||||
pub scroll_to_change_font_size: bool,
|
||||
#[serde(default, deserialize_with = "lenient_option")]
|
||||
pub toolbar_layout: Option<ToolbarLayout>,
|
||||
#[serde(default)]
|
||||
pub font_family: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -181,8 +257,6 @@ pub struct AppConfig {
|
||||
#[serde(default)]
|
||||
pub backup_location: Option<String>,
|
||||
#[serde(default)]
|
||||
pub last_backup_time: Option<String>,
|
||||
#[serde(default)]
|
||||
pub backup_include_attachments: bool,
|
||||
#[serde(default = "default_max_versions")]
|
||||
pub max_versions_per_note: u32,
|
||||
@@ -235,7 +309,7 @@ pub struct AppConfig {
|
||||
pub sync_interval_minutes: u32,
|
||||
#[serde(default)]
|
||||
pub last_sync_time: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(default, deserialize_with = "lenient_list")]
|
||||
pub custom_themes: Vec<CustomTheme>,
|
||||
}
|
||||
|
||||
@@ -276,7 +350,7 @@ fn default_max_versions() -> u32 {
|
||||
}
|
||||
|
||||
fn default_ai_model() -> String {
|
||||
"claude-sonnet-4-6".to_string()
|
||||
"claude-sonnet-5".to_string()
|
||||
}
|
||||
|
||||
fn default_system_light_theme() -> String {
|
||||
@@ -298,7 +372,9 @@ impl Default for AppConfig {
|
||||
system_dark_theme: default_system_dark_theme(),
|
||||
accent_color: None,
|
||||
font_size: None,
|
||||
preferred_font_size: None,
|
||||
scroll_to_change_font_size: true,
|
||||
toolbar_layout: None,
|
||||
font_family: None,
|
||||
line_height: None,
|
||||
ui_scale: None,
|
||||
@@ -326,7 +402,6 @@ impl Default for AppConfig {
|
||||
backup_frequency: "24h".to_string(),
|
||||
backup_max_count: 10,
|
||||
backup_location: None,
|
||||
last_backup_time: None,
|
||||
backup_include_attachments: false,
|
||||
max_versions_per_note: 20,
|
||||
ai_provider: None,
|
||||
@@ -336,7 +411,7 @@ impl Default for AppConfig {
|
||||
ollama_api_key: None,
|
||||
openai_compatible_base_url: None,
|
||||
openai_compatible_api_key: None,
|
||||
ai_model: "claude-sonnet-4-6".to_string(),
|
||||
ai_model: default_ai_model(),
|
||||
ai_writing_style: None,
|
||||
default_view_mode: false,
|
||||
new_notes_in_source_mode: false,
|
||||
@@ -419,18 +494,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)]
|
||||
pub struct SearchResult {
|
||||
pub path: String,
|
||||
pub title: String,
|
||||
pub snippet: String,
|
||||
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)]
|
||||
pub struct FileEvent {
|
||||
pub vault_path: String,
|
||||
pub event_type: String,
|
||||
pub path: String,
|
||||
pub note: Option<NoteEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -457,6 +571,9 @@ pub struct BackupEntry {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub created: String,
|
||||
/// The archive was made from a different vault folder. All vaults share one backup folder.
|
||||
#[serde(default)]
|
||||
pub other_vault: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -467,6 +584,7 @@ pub struct VersionEntry {
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AiStreamEvent {
|
||||
pub request_id: String,
|
||||
pub event_type: String, // "text", "done", "error"
|
||||
pub text: Option<String>,
|
||||
pub error: Option<String>,
|
||||
|
||||
@@ -1,9 +1,70 @@
|
||||
use crate::types::NoteMeta;
|
||||
use chrono::{NaiveDate, NaiveDateTime, Utc};
|
||||
use gray_matter::engine::YAML;
|
||||
use gray_matter::Matter;
|
||||
use gray_matter::engine::{Engine, YAML as UnboundedYaml};
|
||||
use gray_matter::{Matter, Pod};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MAX_FRONTMATTER_BYTES: usize = 64 * 1024;
|
||||
const MAX_FRONTMATTER_ALIASES: usize = 16;
|
||||
const MAX_FRONTMATTER_INDENT: usize = 200;
|
||||
const MAX_FRONTMATTER_INDICATORS: usize = 32;
|
||||
|
||||
/// YAML frontmatter engine for notes, which are untrusted input (sync, import, shared vaults).
|
||||
/// The underlying loader expands every alias by copying and recurses once per nesting level, so a
|
||||
/// note of a few hundred bytes could take gigabytes or overflow the stack and take the app down
|
||||
/// at every start. Frontmatter outside these bounds is treated as carrying no metadata.
|
||||
pub struct BoundedYaml;
|
||||
|
||||
impl Engine for BoundedYaml {
|
||||
fn parse(content: &str) -> Pod {
|
||||
if frontmatter_within_bounds(content) {
|
||||
UnboundedYaml::parse(content)
|
||||
} else {
|
||||
Pod::Null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn frontmatter_within_bounds(content: &str) -> bool {
|
||||
if content.len() > MAX_FRONTMATTER_BYTES {
|
||||
return false;
|
||||
}
|
||||
// Aliases multiply: with few of them the expansion stays small whatever they point at.
|
||||
let bytes = content.as_bytes();
|
||||
let aliases = bytes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(index, &byte)| {
|
||||
byte == b'*'
|
||||
&& (index == 0
|
||||
|| matches!(
|
||||
bytes[index - 1],
|
||||
b' ' | b'\t' | b'\n' | b'[' | b',' | b':' | b'-' | b'{'
|
||||
))
|
||||
&& bytes
|
||||
.get(index + 1)
|
||||
.is_some_and(|next| next.is_ascii_alphanumeric() || matches!(next, b'_' | b'-'))
|
||||
})
|
||||
.count();
|
||||
if aliases > MAX_FRONTMATTER_ALIASES {
|
||||
return false;
|
||||
}
|
||||
// Block nesting deepens by indentation, or by indicators chained on one line (`- - - x`).
|
||||
content.lines().all(|line| {
|
||||
let indent = line.len() - line.trim_start_matches(' ').len();
|
||||
let mut rest = &line.as_bytes()[indent..];
|
||||
let mut indicators = 0;
|
||||
while let [b'-' | b'?' | b':', b' ' | b'\t', tail @ ..] = rest {
|
||||
indicators += 1;
|
||||
rest = tail;
|
||||
while let [b' ' | b'\t', tail @ ..] = rest {
|
||||
rest = tail;
|
||||
}
|
||||
}
|
||||
indent <= MAX_FRONTMATTER_INDENT && indicators <= MAX_FRONTMATTER_INDICATORS
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
struct RawFrontmatter {
|
||||
id: Option<String>,
|
||||
@@ -40,14 +101,60 @@ pub fn parse_date_flexible(s: &str) -> Option<chrono::DateTime<Utc>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Reads the known keys one by one. Frontmatter written by other editors is often shaped a little
|
||||
/// differently (`tags: work`, `pinned: yes`, a numeric title or id); reading it as one strict
|
||||
/// record dropped every field when a single one did not fit, and the next save then wrote a new id,
|
||||
/// the file name as title and no tags over the originals.
|
||||
fn read_frontmatter(data: Option<Pod>) -> RawFrontmatter {
|
||||
let Some(serde_json::Value::Object(fields)) =
|
||||
data.and_then(|data| data.deserialize::<serde_json::Value>().ok())
|
||||
else {
|
||||
return RawFrontmatter::default();
|
||||
};
|
||||
let text = |value: &serde_json::Value| match value {
|
||||
serde_json::Value::String(text) => Some(text.clone()),
|
||||
serde_json::Value::Number(number) => Some(number.to_string()),
|
||||
serde_json::Value::Bool(flag) => Some(flag.to_string()),
|
||||
_ => None,
|
||||
};
|
||||
let tags = fields.get("tags").map(|value| match value {
|
||||
serde_json::Value::Array(items) => items.iter().filter_map(text).collect(),
|
||||
// `tags: work` and `tags: a, b` are common outside this app.
|
||||
other => text(other)
|
||||
.map(|joined| {
|
||||
joined
|
||||
.split(',')
|
||||
.map(|tag| tag.trim().to_string())
|
||||
.filter(|tag| !tag.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
let pinned = fields.get("pinned").and_then(|value| match value {
|
||||
serde_json::Value::Bool(flag) => Some(*flag),
|
||||
serde_json::Value::Number(number) => Some(number.as_f64() != Some(0.0)),
|
||||
serde_json::Value::String(word) => match word.trim().to_ascii_lowercase().as_str() {
|
||||
"true" | "yes" | "on" | "1" => Some(true),
|
||||
"false" | "no" | "off" | "0" => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
});
|
||||
RawFrontmatter {
|
||||
id: fields.get("id").and_then(text),
|
||||
title: fields.get("title").and_then(text),
|
||||
tags,
|
||||
pinned,
|
||||
created: fields.get("created").and_then(text),
|
||||
modified: fields.get("modified").and_then(text),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
|
||||
let matter = Matter::<YAML>::new();
|
||||
let matter = Matter::<BoundedYaml>::new();
|
||||
let result = matter.parse(raw);
|
||||
|
||||
let fm: RawFrontmatter = result
|
||||
.data
|
||||
.and_then(|d| d.deserialize().ok())
|
||||
.unwrap_or_default();
|
||||
let fm = read_frontmatter(result.data);
|
||||
|
||||
let title = fm.title.unwrap_or_else(|| filename_to_title(filename));
|
||||
|
||||
@@ -77,18 +184,15 @@ pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
|
||||
(meta, content)
|
||||
}
|
||||
|
||||
/// Ensure the body starts with `# Title` heading for external app compatibility.
|
||||
/// If the body already starts with `# Title`, leave it as-is.
|
||||
/// Ensure the body starts with a top-level heading for external app compatibility, adding
|
||||
/// `# Title` when it has none. A body that already opens with a top-level heading is left alone
|
||||
/// even when that heading differs from the title: adding another one above it stacked a new
|
||||
/// heading on every title change (`# New`, `# Old`, ...).
|
||||
fn ensure_title_heading(body: &str, title: &str) -> String {
|
||||
let trimmed = body.trim_start();
|
||||
|
||||
// Check if body already starts with `# Title`
|
||||
if let Some(rest) = trimmed.strip_prefix("# ") {
|
||||
let first_line_end = rest.find('\n').unwrap_or(rest.len());
|
||||
let heading_text = rest[..first_line_end].trim();
|
||||
if heading_text.eq_ignore_ascii_case(title.trim()) {
|
||||
return body.to_string();
|
||||
}
|
||||
if trimmed.starts_with("# ") {
|
||||
return body.to_string();
|
||||
}
|
||||
|
||||
// Don't add heading to empty notes (new/blank notes)
|
||||
@@ -100,29 +204,24 @@ fn ensure_title_heading(body: &str, title: &str) -> String {
|
||||
format!("# {}\n\n{}", title, body)
|
||||
}
|
||||
|
||||
/// The frontmatter block for a note that has none yet. Written through the YAML serializer like
|
||||
/// `merge_frontmatter`: assembled by hand, a title with a backslash or a tag such as `2024`,
|
||||
/// `true` or `a: b` came out as YAML the app could not read back.
|
||||
pub fn serialize_frontmatter(meta: &NoteMeta) -> String {
|
||||
let tags_str = if meta.tags.is_empty() {
|
||||
"[]".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"[{}]",
|
||||
meta.tags
|
||||
.iter()
|
||||
.map(|t| t.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
};
|
||||
|
||||
format!(
|
||||
"---\nid: \"{}\"\ntitle: \"{}\"\ntags: {}\npinned: {}\ncreated: {}\nmodified: {}\n---\n",
|
||||
meta.id,
|
||||
meta.title.replace('"', "\\\""),
|
||||
tags_str,
|
||||
meta.pinned,
|
||||
meta.created.to_rfc3339(),
|
||||
meta.modified.to_rfc3339(),
|
||||
)
|
||||
let text = |value: &str| serde_yaml::Value::String(value.to_string());
|
||||
let mut mapping = serde_yaml::Mapping::new();
|
||||
mapping.insert(text("id"), text(&meta.id));
|
||||
mapping.insert(text("title"), text(&meta.title));
|
||||
mapping.insert(
|
||||
text("tags"),
|
||||
serde_yaml::Value::Sequence(meta.tags.iter().map(|tag| text(tag)).collect()),
|
||||
);
|
||||
mapping.insert(text("pinned"), serde_yaml::Value::Bool(meta.pinned));
|
||||
mapping.insert(text("created"), text(&meta.created.to_rfc3339()));
|
||||
mapping.insert(text("modified"), text(&meta.modified.to_rfc3339()));
|
||||
let yaml = serde_yaml::to_string(&serde_yaml::Value::Mapping(mapping))
|
||||
.expect("strings, booleans and a list always serialize");
|
||||
format!("---\n{yaml}---\n")
|
||||
}
|
||||
|
||||
pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
|
||||
@@ -134,7 +233,7 @@ pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
|
||||
/// Merge NoteMeta fields into existing frontmatter, preserving unknown YAML keys.
|
||||
/// Falls back to serialize_frontmatter() if the original has no frontmatter.
|
||||
pub fn merge_frontmatter(original_raw: &str, meta: &NoteMeta, body: &str) -> String {
|
||||
let matter = Matter::<YAML>::new();
|
||||
let matter = Matter::<BoundedYaml>::new();
|
||||
let parsed = matter.parse(original_raw);
|
||||
|
||||
// If original had no frontmatter, use the simple serializer
|
||||
@@ -214,13 +313,9 @@ pub fn filename_to_title(filename: &str) -> String {
|
||||
|
||||
/// Quick title extraction from raw note content (frontmatter only, no full parse)
|
||||
pub fn extract_title(raw: &str) -> Option<String> {
|
||||
let matter = Matter::<YAML>::new();
|
||||
let matter = Matter::<BoundedYaml>::new();
|
||||
let result = matter.parse(raw);
|
||||
let fm: RawFrontmatter = result
|
||||
.data
|
||||
.and_then(|d| d.deserialize().ok())
|
||||
.unwrap_or_default();
|
||||
fm.title
|
||||
read_frontmatter(result.data).title
|
||||
}
|
||||
|
||||
pub fn extract_preview(content: &str, max_len: usize) -> String {
|
||||
@@ -422,4 +517,215 @@ mod tests {
|
||||
eprintln!("Stripped: {:?}", stripped);
|
||||
assert!(stripped.contains("Telefoonnummer"));
|
||||
}
|
||||
fn alias_bomb(levels: usize, width: usize) -> String {
|
||||
let mut note = format!(
|
||||
"---\ntitle: Bomb\na0: &a0 [{}]\n",
|
||||
vec!["1"; width].join(",")
|
||||
);
|
||||
for level in 1..levels {
|
||||
let alias = format!("*a{}", level - 1);
|
||||
note.push_str(&format!(
|
||||
"a{level}: &a{level} [{}]\n",
|
||||
vec![alias.as_str(); width].join(",")
|
||||
));
|
||||
}
|
||||
note.push_str("---\nbody\n");
|
||||
note
|
||||
}
|
||||
|
||||
/// Runs on a stack the size of the app's worker threads, where the unbounded loader overflowed.
|
||||
fn on_worker_stack<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(2 * 1024 * 1024)
|
||||
.spawn(work)
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_frontmatter_is_read_as_a_note_without_metadata() {
|
||||
let nested_on_one_line = format!("---\nt: {}x\n---\nbody\n", "- ".repeat(2400));
|
||||
let mut nested_by_indent = String::from("---\nt:\n");
|
||||
for depth in 0..400 {
|
||||
note_line(&mut nested_by_indent, depth);
|
||||
}
|
||||
nested_by_indent.push_str("---\nbody\n");
|
||||
let oversized = format!(
|
||||
"---\ntitle: Big\nfiller: \"{}\"\n---\nbody\n",
|
||||
"x".repeat(MAX_FRONTMATTER_BYTES)
|
||||
);
|
||||
for note in [
|
||||
alias_bomb(10, 8),
|
||||
alias_bomb(40, 2),
|
||||
nested_on_one_line,
|
||||
nested_by_indent,
|
||||
oversized,
|
||||
] {
|
||||
let started = std::time::Instant::now();
|
||||
let (title, content, extracted, merged) = on_worker_stack(move || {
|
||||
let (meta, content) = parse_note(¬e, "Fallback Name.md");
|
||||
let merged = merge_frontmatter(¬e, &meta, &content);
|
||||
(meta.title, content, extract_title(¬e), merged)
|
||||
});
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(2));
|
||||
// No metadata is taken from it, and the body is still split off as usual.
|
||||
assert_eq!(title, "Fallback Name");
|
||||
assert_eq!(content, "body");
|
||||
assert_eq!(extracted, None);
|
||||
assert!(
|
||||
merged.ends_with("body"),
|
||||
"{}",
|
||||
&merged[merged.len().saturating_sub(40)..]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn note_line(note: &mut String, depth: usize) {
|
||||
note.push_str(&" ".repeat(depth));
|
||||
note.push_str("-\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_frontmatter_is_unaffected_by_the_bounds() {
|
||||
let (meta, content) = parse_note(
|
||||
"---\nid: abc\ntitle: \"*Starred* title: 5*3\"\ntags:\n - one\n - two\npinned: true\n---\n# Body\n",
|
||||
"x.md",
|
||||
);
|
||||
assert_eq!(meta.id, "abc");
|
||||
assert_eq!(meta.title, "*Starred* title: 5*3");
|
||||
assert_eq!(meta.tags, vec!["one", "two"]);
|
||||
assert!(meta.pinned);
|
||||
assert_eq!(content, "# Body");
|
||||
// A few aliases and modest nesting are ordinary YAML.
|
||||
let (meta, _) = parse_note(
|
||||
"---\ntitle: Shared\nbase: &base [a, b]\ntags: *base\nextra:\n - - nested\n - list\n---\nbody\n",
|
||||
"x.md",
|
||||
);
|
||||
assert_eq!(meta.title, "Shared");
|
||||
assert_eq!(meta.tags, vec!["a", "b"]);
|
||||
assert!(frontmatter_within_bounds(&format!(
|
||||
"title: {}",
|
||||
"x".repeat(MAX_FRONTMATTER_BYTES - 16)
|
||||
)));
|
||||
}
|
||||
#[test]
|
||||
fn one_field_of_another_shape_no_longer_drops_the_rest() {
|
||||
let note = |extra: &str| format!("---\nid: keep-me\ntitle: Kept\n{extra}\n---\nbody\n");
|
||||
let (meta, _) = parse_note(¬e("tags: work"), "File.md");
|
||||
assert_eq!((meta.id.as_str(), meta.title.as_str()), ("keep-me", "Kept"));
|
||||
assert_eq!(meta.tags, vec!["work"]);
|
||||
let (meta, _) = parse_note(¬e("tags: a, b ,c\npinned: yes"), "File.md");
|
||||
assert_eq!(meta.tags, vec!["a", "b", "c"]);
|
||||
assert!(meta.pinned);
|
||||
assert_eq!(meta.id, "keep-me");
|
||||
// Numbers where text is expected are read as text.
|
||||
let (meta, _) = parse_note(
|
||||
"---\nid: 20231014\ntitle: 2024\ntags: [1, two, true]\npinned: 0\n---\nbody\n",
|
||||
"File.md",
|
||||
);
|
||||
assert_eq!(
|
||||
(meta.id.as_str(), meta.title.as_str()),
|
||||
("20231014", "2024")
|
||||
);
|
||||
assert_eq!(meta.tags, vec!["1", "two", "true"]);
|
||||
assert!(!meta.pinned);
|
||||
assert_eq!(
|
||||
extract_title("---\ntitle: 2024\ntags: work\n---\nbody\n").as_deref(),
|
||||
Some("2024")
|
||||
);
|
||||
// A field that makes no sense is skipped on its own.
|
||||
let (meta, _) = parse_note(¬e("tags: {a: b}\npinned: maybe"), "File.md");
|
||||
assert_eq!(meta.id, "keep-me");
|
||||
assert!(meta.tags.is_empty());
|
||||
assert!(!meta.pinned);
|
||||
// Saving keeps the identity and writes the tags as a list.
|
||||
let (meta, content) = parse_note(¬e("tags: work\naliases: [x]"), "File.md");
|
||||
let saved = merge_frontmatter(¬e("tags: work\naliases: [x]"), &meta, &content);
|
||||
let (again, _) = parse_note(&saved, "File.md");
|
||||
assert_eq!(
|
||||
(again.id.as_str(), again.title.as_str()),
|
||||
("keep-me", "Kept")
|
||||
);
|
||||
assert_eq!(again.tags, vec!["work"]);
|
||||
assert!(saved.contains("aliases:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_frontmatter_reads_back_whatever_the_title_and_tags_contain() {
|
||||
for (title, tags) in [
|
||||
("C:\\Users\\tom", vec!["2024", "true"]),
|
||||
("Plain", vec!["foo: bar", "a,b"]),
|
||||
("Say \"hi\" and 'bye'", vec!["#hash", "- dash"]),
|
||||
("\\sum x", vec!["null", "~", "1.5"]),
|
||||
(
|
||||
"Tab\there: colon # hash",
|
||||
vec!["[x]", "{y}", "*star", "&"],
|
||||
),
|
||||
("- leading dash", vec![]),
|
||||
("", vec!["yes"]),
|
||||
] {
|
||||
let meta = NoteMeta {
|
||||
id: "the-id".into(),
|
||||
title: title.into(),
|
||||
tags: tags.iter().map(|tag| tag.to_string()).collect(),
|
||||
pinned: true,
|
||||
created: Utc::now(),
|
||||
modified: Utc::now(),
|
||||
};
|
||||
let raw = update_note_raw(&meta, "body\n");
|
||||
let (back, content) = parse_note(&raw, "Fallback.md");
|
||||
assert_eq!(back.id, "the-id", "{raw}");
|
||||
assert_eq!(back.title, title, "{raw}");
|
||||
assert_eq!(back.tags, meta.tags, "{raw}");
|
||||
assert!(back.pinned);
|
||||
assert_eq!(back.created.timestamp(), meta.created.timestamp());
|
||||
assert!(content.ends_with("body"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_heading_is_added_only_when_the_body_has_no_top_level_heading() {
|
||||
let meta = |title: &str| NoteMeta {
|
||||
id: "id".into(),
|
||||
title: title.into(),
|
||||
tags: vec![],
|
||||
pinned: false,
|
||||
created: Utc::now(),
|
||||
modified: Utc::now(),
|
||||
};
|
||||
let body_of = |raw: String| parse_note(&raw, "x.md").1;
|
||||
// No heading yet: the title becomes one.
|
||||
assert_eq!(
|
||||
body_of(update_note_raw(&meta("New"), "Text.\n")),
|
||||
"# New\n\nText."
|
||||
);
|
||||
// A heading that differs from the title is not buried under a second one.
|
||||
assert_eq!(
|
||||
body_of(update_note_raw(&meta("New"), "# Old\n\nText.\n")),
|
||||
"# Old\n\nText."
|
||||
);
|
||||
let original = "---\nid: id\ntitle: Old\n---\n# Old\n\nText.\n";
|
||||
assert_eq!(
|
||||
body_of(merge_frontmatter(
|
||||
original,
|
||||
&meta("New"),
|
||||
"# Old\n\nText.\n"
|
||||
)),
|
||||
"# Old\n\nText."
|
||||
);
|
||||
// Saving again and again never grows the note.
|
||||
let once = merge_frontmatter(original, &meta("New"), "# Old\n\nText.\n");
|
||||
let (_, body) = parse_note(&once, "x.md");
|
||||
assert_eq!(
|
||||
body_of(merge_frontmatter(&once, &meta("Newer"), &body)),
|
||||
"# Old\n\nText."
|
||||
);
|
||||
// Lower-level headings and empty notes behave as before.
|
||||
assert_eq!(
|
||||
body_of(update_note_raw(&meta("New"), "## Section\n")),
|
||||
"# New\n\n## Section"
|
||||
);
|
||||
assert!(update_note_raw(&meta("New"), "\n").ends_with("---\n\n"));
|
||||
}
|
||||
}
|
||||
+460
-129
@@ -1,31 +1,29 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::vault::frontmatter::BoundedYaml;
|
||||
use chrono::Utc;
|
||||
use gray_matter::engine::YAML;
|
||||
use gray_matter::Matter;
|
||||
use regex::Regex;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::types::{ImportResult, NoteMeta};
|
||||
use crate::vault::frontmatter;
|
||||
use crate::vault::operations::replace_file_atomically;
|
||||
|
||||
pub fn import(vault_path: &str) -> Result<ImportResult, String> {
|
||||
let vault = Path::new(vault_path);
|
||||
// Folders that are empty before the import are notebooks the user made; only folders the
|
||||
// import itself empties are removed afterwards.
|
||||
let already_empty = empty_dirs(vault)?;
|
||||
|
||||
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()
|
||||
.filter_map(|e| e.ok())
|
||||
.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())
|
||||
.filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md"))
|
||||
.collect();
|
||||
|
||||
let wiki_embed_re =
|
||||
@@ -46,10 +44,8 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
|
||||
};
|
||||
|
||||
for path in &md_files {
|
||||
let raw = match std::fs::read_to_string(path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let raw = std::fs::read_to_string(path)
|
||||
.map_err(|e| format!("Reading {}: {e}", path.display()))?;
|
||||
let note_dir = path.parent().unwrap_or(Path::new(""));
|
||||
|
||||
let mut content = raw.clone();
|
||||
@@ -193,7 +189,8 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -203,34 +200,69 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
|
||||
|
||||
if !moved.is_empty() {
|
||||
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, &already_empty)?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn build_file_index(vault: &Path) -> HashMap<String, String> {
|
||||
let mut index = HashMap::new();
|
||||
for entry in walkdir::WalkDir::new(vault)
|
||||
/// Hidden files and folders are never imported, moved or cleaned up. The app's own `.helixnotes`
|
||||
/// and Obsidian's `.obsidian` and `.trash` are among them, and so is `.git`: every file that is
|
||||
/// not a note becomes an attachment and its original is deleted, which took a repository apart.
|
||||
fn is_hidden_entry(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with('.'))
|
||||
}
|
||||
|
||||
fn vault_entries(
|
||||
vault: &Path,
|
||||
) -> impl Iterator<Item = Result<walkdir::DirEntry, walkdir::Error>> + '_ {
|
||||
walkdir::WalkDir::new(vault)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
{
|
||||
let path = entry.path();
|
||||
if !path.is_file() {
|
||||
.filter_entry(|entry| entry.depth() == 0 || !is_hidden_entry(entry.path()))
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
let path = entry.path();
|
||||
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(), rel.to_string_lossy().to_string());
|
||||
}
|
||||
index.insert(name.to_string(), vault_relative(path, vault)?);
|
||||
}
|
||||
}
|
||||
index
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn rename_deprecated_properties(raw: &str) -> String {
|
||||
let matter = Matter::<YAML>::new();
|
||||
let matter = Matter::<BoundedYaml>::new();
|
||||
let result = matter.parse(raw);
|
||||
|
||||
if result.matter.trim().is_empty() {
|
||||
@@ -269,7 +301,7 @@ fn rename_deprecated_properties(raw: &str) -> String {
|
||||
}
|
||||
|
||||
fn normalize_frontmatter(raw: &str, path: &Path) -> (NoteMeta, String) {
|
||||
let matter = Matter::<YAML>::new();
|
||||
let matter = Matter::<BoundedYaml>::new();
|
||||
let result = matter.parse(raw);
|
||||
let yaml_str = result.matter.trim();
|
||||
|
||||
@@ -565,52 +597,102 @@ fn fix_md_link_refs(
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn ensure_attachment_parent(
|
||||
vault: &Path,
|
||||
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(¤t) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => return Err(format!("Creating {}: {e}", current.display())),
|
||||
}
|
||||
let canonical = std::fs::canonicalize(¤t)
|
||||
.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 _ = std::fs::create_dir_all(&attachments_dir);
|
||||
|
||||
let attachment_files: Vec<_> = walkdir::WalkDir::new(vault)
|
||||
let attachment_files: Vec<_> = scanned_files(vault)?
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
.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())
|
||||
.filter(|p| p.extension().and_then(|x| x.to_str()) != Some("md"))
|
||||
.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 {
|
||||
let old_rel = match src_path.strip_prefix(vault) {
|
||||
Ok(r) => r.to_string_lossy().to_string(),
|
||||
Err(_) => continue,
|
||||
// Reserve the destination atomically: neither rename nor std::fs::copy protects
|
||||
// a pre-existing attachment (or one created concurrently) from replacement.
|
||||
let mut suffix = 0u64;
|
||||
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}"))
|
||||
};
|
||||
match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&candidate)
|
||||
{
|
||||
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 new_rel = format!(".helixnotes/attachments/{}", old_rel);
|
||||
let dest_path = vault.join(&new_rel);
|
||||
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
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);
|
||||
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)
|
||||
}
|
||||
@@ -618,24 +700,14 @@ fn move_attachments(vault: &Path) -> Result<HashMap<String, String>, String> {
|
||||
fn rewrite_attachment_refs(vault: &Path, moved: &HashMap<String, String>) -> Result<(), 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()
|
||||
.filter_map(|e| e.ok())
|
||||
.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())
|
||||
.filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md"))
|
||||
.collect();
|
||||
|
||||
for path in &md_files {
|
||||
let content = match std::fs::read_to_string(path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let content = std::fs::read_to_string(path)
|
||||
.map_err(|e| format!("Reading {}: {e}", path.display()))?;
|
||||
let note_dir = path.parent().unwrap_or(Path::new(""));
|
||||
|
||||
let new_content = md_ref
|
||||
@@ -643,28 +715,29 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap<String, String>) -> Res
|
||||
let prefix = &caps[1];
|
||||
let href = &caps[2];
|
||||
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);
|
||||
}
|
||||
|
||||
let abs_from_note = note_dir.join(&decoded_href);
|
||||
let rel_from_note = abs_from_note
|
||||
let rel_from_note = note_dir
|
||||
.strip_prefix(vault)
|
||||
.ok()
|
||||
.map(|r| r.to_string_lossy().to_string());
|
||||
let rel_from_vault = decoded_href.clone();
|
||||
|
||||
.and_then(|base| resolve_relative_ref(base, reference));
|
||||
let old_vault_rel = rel_from_note
|
||||
.as_ref()
|
||||
.filter(|r| moved.contains_key(r.as_str()))
|
||||
.cloned()
|
||||
.or_else(|| {
|
||||
if moved.contains_key(&rel_from_vault) {
|
||||
Some(rel_from_vault)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
resolve_relative_ref(Path::new(""), reference)
|
||||
.filter(|r| moved.contains_key(r.as_str()))
|
||||
});
|
||||
|
||||
if let Some(old_rel) = old_vault_rel {
|
||||
@@ -675,7 +748,12 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap<String, String>) -> Res
|
||||
note_dir.to_str().unwrap_or(""),
|
||||
)
|
||||
.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)
|
||||
@@ -683,33 +761,72 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap<String, String>) -> Res
|
||||
.to_string();
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
fn cleanup_empty_dirs(root: &Path) {
|
||||
let mut dirs: Vec<_> = walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.path().is_dir())
|
||||
.map(|e| e.path().to_path_buf())
|
||||
.collect();
|
||||
fn resolve_relative_ref(base: &Path, reference: &str) -> Option<String> {
|
||||
let mut rel = base.to_path_buf();
|
||||
for component in Path::new(&reference.replace('\\', "/")).components() {
|
||||
match component {
|
||||
std::path::Component::Normal(name) => rel.push(name),
|
||||
std::path::Component::ParentDir => {
|
||||
if !rel.pop() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn empty_dirs(root: &Path) -> Result<HashSet<PathBuf>, String> {
|
||||
let mut empty = HashSet::new();
|
||||
for entry in vault_entries(root) {
|
||||
let entry = entry.map_err(|e| format!("Scanning {}: {e}", root.display()))?;
|
||||
if entry.file_type().is_dir()
|
||||
&& std::fs::read_dir(entry.path()).is_ok_and(|mut entries| entries.next().is_none())
|
||||
{
|
||||
empty.insert(entry.into_path());
|
||||
}
|
||||
}
|
||||
Ok(empty)
|
||||
}
|
||||
|
||||
fn cleanup_empty_dirs(root: &Path, keep: &HashSet<PathBuf>) -> 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 {
|
||||
let dir_str = dir.to_string_lossy();
|
||||
if dir_str.contains("/.helixnotes") || dir_str.contains("/.obsidian") || dir == root {
|
||||
if dir == root || keep.contains(&dir) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(mut entries) = std::fs::read_dir(&dir) {
|
||||
if entries.next().is_none() {
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
let mut entries =
|
||||
std::fs::read_dir(&dir).map_err(|e| format!("Reading {}: {e}", dir.display()))?;
|
||||
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>) {
|
||||
@@ -778,34 +895,123 @@ fn pathdiff(target: &str, base: &str) -> Result<String, ()> {
|
||||
for component in &target_components[common..] {
|
||||
result.push(component);
|
||||
}
|
||||
Ok(result.to_string_lossy().to_string())
|
||||
Ok(result.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let mut result = String::with_capacity(s.len());
|
||||
let mut chars = s.bytes();
|
||||
while let Some(b) = chars.next() {
|
||||
if b == b'%' {
|
||||
let hi = chars.next();
|
||||
let lo = chars.next();
|
||||
if let (Some(h), Some(l)) = (hi, lo) {
|
||||
if let Ok(byte) = u8::from_str_radix(&format!("{}{}", h as char, l as char), 16) {
|
||||
result.push(byte as char);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push('%');
|
||||
} else {
|
||||
result.push(b as char);
|
||||
}
|
||||
}
|
||||
result
|
||||
// Keep the complete original reference if escaped bytes are not valid UTF-8.
|
||||
urlencoding::decode(s)
|
||||
.map(|decoded| decoded.into_owned())
|
||||
.unwrap_or_else(|_| s.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn percent_decode_preserves_unicode_plus_and_malformed_escapes() {
|
||||
for (input, expected) in [
|
||||
("café 雪+.png", "café 雪+.png"),
|
||||
("caf%C3%A9%20%E9%9B%AA+.png", "café 雪+.png"),
|
||||
("bad%GG%20name.png", "bad%GG name.png"),
|
||||
("tail%", "tail%"),
|
||||
("tail%2", "tail%2"),
|
||||
("雪%FF%20+%GG", "雪%FF%20+%GG"),
|
||||
("%E9%9B", "%E9%9B"),
|
||||
] {
|
||||
assert_eq!(percent_decode(input), expected, "input {input:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_leaves_hidden_files_and_existing_empty_folders_alone() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let root = vault.path();
|
||||
// A git-backed vault with dotfiles, an empty notebook, and a folder of attachments only.
|
||||
std::fs::create_dir_all(root.join(".git/objects/ab")).unwrap();
|
||||
std::fs::write(root.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::write(root.join(".git/objects/ab/cdef"), b"blob").unwrap();
|
||||
std::fs::write(root.join(".gitignore"), ".obsidian/workspace.json\n").unwrap();
|
||||
std::fs::create_dir_all(root.join(".stversions")).unwrap();
|
||||
std::fs::write(root.join(".stversions/old.png"), b"old").unwrap();
|
||||
std::fs::create_dir(root.join("Empty notebook")).unwrap();
|
||||
std::fs::create_dir(root.join("Pictures")).unwrap();
|
||||
std::fs::write(root.join("Pictures/photo.png"), b"png").unwrap();
|
||||
std::fs::write(root.join("Note.md"), "# Note\n\n\n").unwrap();
|
||||
|
||||
let result = import(root.to_str().unwrap()).unwrap();
|
||||
|
||||
assert_eq!(result.attachments_moved, 1);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join(".git/HEAD")).unwrap(),
|
||||
"ref: refs/heads/main\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".git/objects/ab/cdef")).unwrap(),
|
||||
b"blob"
|
||||
);
|
||||
assert!(root.join(".gitignore").is_file());
|
||||
assert!(root.join(".stversions/old.png").is_file());
|
||||
// Nothing hidden was copied into the attachments either.
|
||||
assert!(!root.join(".helixnotes/attachments/.git").exists());
|
||||
assert!(!root.join(".helixnotes/attachments/.gitignore").exists());
|
||||
// The folder the import emptied is gone; the one that was empty already is kept.
|
||||
assert!(!root.join("Pictures").exists());
|
||||
assert!(root.join("Empty notebook").is_dir());
|
||||
assert!(root
|
||||
.join(".helixnotes/attachments/Pictures/photo.png")
|
||||
.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_rewrites_unicode_encoded_and_malformed_attachment_references() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let root = vault.path();
|
||||
let note_dir = root.join("笔记");
|
||||
std::fs::create_dir(¬e_dir).unwrap();
|
||||
let attachments = [
|
||||
"café 雪+.png",
|
||||
"bad%GG.png",
|
||||
"tail%.png",
|
||||
"tail%2.png",
|
||||
"bytes%FF%20.png",
|
||||
];
|
||||
for name in attachments {
|
||||
std::fs::write(note_dir.join(name), name.as_bytes()).unwrap();
|
||||
}
|
||||
let note_path = note_dir.join("Entry.md");
|
||||
std::fs::write(
|
||||
¬e_path,
|
||||
"# Entry\n\n\n\
|
||||
[encoded](caf%C3%A9%20%E9%9B%AA+.png#preview)\n\
|
||||
\n\n\
|
||||
[short](tail%2.png)\n[invalid UTF-8](bytes%FF%20.png)\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let result = import(root.to_str().unwrap()).unwrap();
|
||||
assert_eq!(result.attachments_moved, attachments.len() as u64);
|
||||
let note = std::fs::read_to_string(¬e_path).unwrap();
|
||||
for reference in [
|
||||
"",
|
||||
"[encoded](../.helixnotes/attachments/笔记/café%20雪+.png#preview)",
|
||||
"",
|
||||
"",
|
||||
"[short](../.helixnotes/attachments/笔记/tail%2.png)",
|
||||
"[invalid UTF-8](../.helixnotes/attachments/笔记/bytes%FF%20.png)",
|
||||
] {
|
||||
assert!(note.contains(reference), "missing {reference:?} in {note}");
|
||||
}
|
||||
for name in attachments {
|
||||
assert!(!note_dir.join(name).exists());
|
||||
assert_eq!(
|
||||
std::fs::read(root.join(".helixnotes/attachments/笔记").join(name)).unwrap(),
|
||||
name.as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_normalize_tags_comma_string() {
|
||||
let mapping: serde_yaml::Mapping = serde_yaml::from_str("tags: \"a, b, c\"").unwrap();
|
||||
@@ -1013,6 +1219,131 @@ mod tests {
|
||||
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(¬e_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#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(""));
|
||||
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",
|
||||
)
|
||||
.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";
|
||||
std::fs::write(¬e, original).unwrap();
|
||||
std::fs::write(root.join("asset.bin"), b"original").unwrap();
|
||||
let original_permissions = std::fs::metadata(¬e).unwrap().permissions();
|
||||
let mut permissions = original_permissions.clone();
|
||||
permissions.set_readonly(true);
|
||||
std::fs::set_permissions(¬e, permissions).unwrap();
|
||||
|
||||
let result = import(root.to_str().unwrap());
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(std::fs::read_to_string(¬e).unwrap(), original);
|
||||
assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original");
|
||||
std::fs::set_permissions(¬e, 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]
|
||||
fn test_split_anchor_same_note() {
|
||||
let (file, anchor) = split_anchor("#Heading");
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
pub mod frontmatter;
|
||||
pub mod import;
|
||||
pub mod operations;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod portal_watcher;
|
||||
pub mod watcher;
|
||||
|
||||
#[cfg(test)]
|
||||
mod note_import_tests;
|
||||
@@ -0,0 +1,495 @@
|
||||
use super::operations::{
|
||||
ensure_vault_structure, import_note as import_from_root, ExternalNoteReference,
|
||||
};
|
||||
|
||||
fn import_note(
|
||||
vault: &str,
|
||||
source: &str,
|
||||
notebook: Option<&str>,
|
||||
raw: &str,
|
||||
references: Vec<ExternalNoteReference>,
|
||||
authorize: impl Fn(&Path) -> Result<(), String>,
|
||||
) -> Result<crate::types::NoteContent, String> {
|
||||
import_from_root(
|
||||
vault,
|
||||
source,
|
||||
Path::new(source).parent().unwrap(),
|
||||
notebook,
|
||||
raw,
|
||||
references,
|
||||
authorize,
|
||||
)
|
||||
}
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn reference(raw: &str, original: &str, href: &str, html: bool) -> ExternalNoteReference {
|
||||
let from = raw.find(original).unwrap();
|
||||
ExternalNoteReference {
|
||||
from,
|
||||
to: from + original.len(),
|
||||
href: href.into(),
|
||||
html,
|
||||
pdf: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture(raw: &str) -> (tempfile::TempDir, String, PathBuf) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let vault = root.path().join("vault").to_string_lossy().into_owned();
|
||||
ensure_vault_structure(&vault).unwrap();
|
||||
let external = root.path().join("external");
|
||||
fs::create_dir_all(external.join("images")).unwrap();
|
||||
let source = external.join("External.md");
|
||||
fs::write(&source, raw).unwrap();
|
||||
(root, vault, source)
|
||||
}
|
||||
|
||||
fn attachments(vault: &str) -> Vec<PathBuf> {
|
||||
fs::read_dir(Path::new(vault).join(".helixnotes/attachments"))
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_relative_files_once_preserving_originals_frontmatter_and_literal_content() {
|
||||
let raw = "---\r\ntitle: Portable\r\ncustom: 雪 📝\r\n---\r\n\r\n\r\n<a href=\"images/report.pdf#page=2&mode=fit\">PDF</a>\r\n\r\n~~~md\r\n\r\n~~~\r\n";
|
||||
for notebook in [None, Some("Projects/Nested")] {
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
let parent = source.parent().unwrap();
|
||||
fs::write(parent.join("images/café 雪.png"), b"image bytes").unwrap();
|
||||
fs::write(parent.join("images/report.pdf"), b"pdf bytes").unwrap();
|
||||
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
|
||||
let references = vec![
|
||||
reference(raw, "images/café%20雪.png", "images/café%20雪.png", false),
|
||||
reference(
|
||||
raw,
|
||||
"images/./café%20雪.png",
|
||||
"images/./café%20雪.png",
|
||||
false,
|
||||
),
|
||||
reference(
|
||||
raw,
|
||||
"images/report.pdf#page=2&mode=fit",
|
||||
"images/report.pdf#page=2&mode=fit",
|
||||
true,
|
||||
),
|
||||
];
|
||||
let note = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
notebook,
|
||||
raw,
|
||||
references,
|
||||
|path| {
|
||||
if path.starts_with(parent) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Not selected".into())
|
||||
}
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(note
|
||||
.raw
|
||||
.starts_with("---\r\ntitle: Portable\r\ncustom: 雪 📝\r\n---\r\n"));
|
||||
assert!(note.raw.contains(""));
|
||||
assert!(note.raw.contains("#page=2&mode=fit"));
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
|
||||
assert_eq!(fs::read_to_string(¬e.path).unwrap(), note.raw);
|
||||
let files = attachments(&vault);
|
||||
assert_eq!(
|
||||
files.len(),
|
||||
2,
|
||||
"aliases of one file share one portable copy"
|
||||
);
|
||||
for file in files {
|
||||
let filename = urlencoding::encode(file.file_name().unwrap().to_str().unwrap());
|
||||
let relative = format!(".helixnotes/attachments/{filename}");
|
||||
assert!(note.raw.contains(&relative));
|
||||
assert!(Path::new(&vault)
|
||||
.join(urlencoding::decode(&relative).unwrap().as_ref())
|
||||
.is_file());
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(parent.join("images/café 雪.png")).unwrap(),
|
||||
b"image bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(parent.join("images/report.pdf")).unwrap(),
|
||||
b"pdf bytes"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_pdf_embeds_keep_the_vault_root_path_convention_in_nested_notebooks() {
|
||||
let raw = "<div data-pdf-src=\"images/report.pdf\" data-pdf-name=\"Report\"></div>";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
fs::write(source.parent().unwrap().join("images/report.pdf"), b"pdf").unwrap();
|
||||
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
|
||||
let mut pdf = reference(raw, "images/report.pdf", "images/report.pdf", true);
|
||||
pdf.pdf = true;
|
||||
let note = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
Some("Projects/Nested"),
|
||||
raw,
|
||||
vec![pdf],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(note.raw.contains("data-pdf-src=\".helixnotes/attachments/"));
|
||||
assert!(note.raw.contains("data-pdf-name=\"Report\""));
|
||||
assert_eq!(attachments(&vault).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_document_links_remain_managed_and_stable_after_note_and_notebook_moves() {
|
||||
let raw = "[Report](images/report.pdf#page=2)";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
fs::write(source.parent().unwrap().join("images/report.pdf"), b"pdf").unwrap();
|
||||
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
|
||||
fs::create_dir_all(Path::new(&vault).join("Archive")).unwrap();
|
||||
let note = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
Some("Projects/Nested"),
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/report.pdf#page=2",
|
||||
"images/report.pdf#page=2",
|
||||
false,
|
||||
)],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
note.raw.starts_with("[Report](.helixnotes/attachments/"),
|
||||
"managed links must not depend on notebook depth"
|
||||
);
|
||||
let href = note
|
||||
.raw
|
||||
.strip_prefix("[Report](")
|
||||
.unwrap()
|
||||
.strip_suffix(')')
|
||||
.unwrap();
|
||||
let attachment = Path::new(&vault).join(
|
||||
urlencoding::decode(href.split('#').next().unwrap())
|
||||
.unwrap()
|
||||
.as_ref(),
|
||||
);
|
||||
assert_eq!(fs::read(attachment).unwrap(), b"pdf");
|
||||
let moved = super::operations::move_note(&vault, ¬e.path, &vault)
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(fs::read_to_string(moved).unwrap(), note.raw);
|
||||
// Imported managed paths remain stable when their containing notebook is moved too.
|
||||
let second = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
Some("Projects/Nested"),
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/report.pdf#page=2",
|
||||
"images/report.pdf#page=2",
|
||||
false,
|
||||
)],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.unwrap();
|
||||
super::operations::move_notebook(
|
||||
&vault,
|
||||
Path::new(&vault).join("Projects").to_str().unwrap(),
|
||||
Path::new(&vault).join("Archive").to_str().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(Path::new(&vault).join("Archive/Projects/Nested/External.md")).unwrap(),
|
||||
second.raw
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_does_not_replace_existing_note_or_same_named_attachment() {
|
||||
let raw = "";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
fs::write(
|
||||
source.parent().unwrap().join("images/photo.png"),
|
||||
b"new image",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(Path::new(&vault).join("External.md"), b"keep note").unwrap();
|
||||
fs::write(
|
||||
Path::new(&vault).join(".helixnotes/attachments/photo.png"),
|
||||
b"keep image",
|
||||
)
|
||||
.unwrap();
|
||||
let note = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/photo.png",
|
||||
"images/photo.png",
|
||||
false,
|
||||
)],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(note.path.ends_with("External (2).md"));
|
||||
assert_eq!(
|
||||
fs::read(Path::new(&vault).join("External.md")).unwrap(),
|
||||
b"keep note"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(Path::new(&vault).join(".helixnotes/attachments/photo.png")).unwrap(),
|
||||
b"keep image"
|
||||
);
|
||||
assert_eq!(attachments(&vault).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_sources_missing_files_and_denied_attachments_publish_nothing() {
|
||||
let raw = "";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
let plan = || {
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/photo.png",
|
||||
"images/photo.png",
|
||||
false,
|
||||
)]
|
||||
};
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
"stale",
|
||||
plan(),
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
assert!(
|
||||
import_note(&vault, source.to_str().unwrap(), None, raw, plan(), |_| Ok(
|
||||
()
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
|
||||
let denied = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
plan(),
|
||||
|path| {
|
||||
if path == source {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Attachment not selected".into())
|
||||
}
|
||||
},
|
||||
);
|
||||
assert!(denied.unwrap_err().contains("not selected"));
|
||||
assert!(attachments(&vault).is_empty());
|
||||
assert!(!Path::new(&vault).join("External.md").exists());
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_destinations_ranges_and_absolute_references_are_rejected() {
|
||||
let raw = "雪 ";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
Some("../escape"),
|
||||
raw,
|
||||
vec![],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
for href in [
|
||||
"/private.png",
|
||||
"%2Fprivate.png",
|
||||
"C:/private.png",
|
||||
"https://example.com/file.png",
|
||||
"Related.md",
|
||||
] {
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(raw, "images/photo.png", href, false)],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![ExternalNoteReference {
|
||||
from: 1,
|
||||
to: 3,
|
||||
href: "images/photo.png".into(),
|
||||
html: false,
|
||||
pdf: false,
|
||||
}],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
let plan = vec![
|
||||
reference(raw, "images/photo.png", "images/photo.png", false),
|
||||
reference(raw, "images/photo.png", "images/photo.png", false),
|
||||
];
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
plan,
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
assert!(attachments(&vault).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_note_publication_removes_only_its_new_attachments() {
|
||||
let raw = "";
|
||||
let (_root, vault, source) = fixture(raw);
|
||||
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
|
||||
fs::write(Path::new(&vault).join("External.md"), b"keep").unwrap();
|
||||
for number in 2..=100 {
|
||||
fs::write(
|
||||
Path::new(&vault).join(format!("External ({number}).md")),
|
||||
b"keep",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let original_asset = Path::new(&vault).join(".helixnotes/attachments/original.png");
|
||||
fs::write(&original_asset, b"keep attachment").unwrap();
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/photo.png",
|
||||
"images/photo.png",
|
||||
false
|
||||
)],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
assert_eq!(attachments(&vault), vec![original_asset]);
|
||||
assert_eq!(
|
||||
fs::read(Path::new(&vault).join("External.md")).unwrap(),
|
||||
b"keep"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
|
||||
assert!(!fs::read_dir(&vault).unwrap().any(|entry| entry
|
||||
.unwrap()
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with(".helixnotes-import-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_content_cannot_import_parent_files_or_hidden_secrets_from_a_broad_scope() {
|
||||
let raw = "[File](asset.bin)";
|
||||
let (root, vault, source) = fixture(raw);
|
||||
let parent = source.parent().unwrap();
|
||||
for name in [
|
||||
".ssh/key.bin",
|
||||
".helixnotes/history/private.bin",
|
||||
".helixnotes/attachments/photo.bin",
|
||||
] {
|
||||
let file = parent.join(name);
|
||||
fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
fs::write(file, b"private fixture").unwrap();
|
||||
}
|
||||
fs::write(root.path().join("private.bin"), b"private outside fixture").unwrap();
|
||||
for href in [
|
||||
"../private.bin",
|
||||
".ssh/key.bin",
|
||||
".helixnotes/history/private.bin",
|
||||
] {
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(raw, "asset.bin", href, false)],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
assert!(attachments(&vault).is_empty());
|
||||
assert!(!Path::new(&vault).join("External.md").exists());
|
||||
}
|
||||
let note = import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"asset.bin",
|
||||
".helixnotes/attachments/photo.bin",
|
||||
false,
|
||||
)],
|
||||
|_| Ok(()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(note.raw.contains(".helixnotes/attachments/"));
|
||||
assert_eq!(attachments(&vault).len(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn import_rejects_attachment_and_notebook_destinations_that_follow_symlinks() {
|
||||
let raw = "";
|
||||
let (root, vault, source) = fixture(raw);
|
||||
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
|
||||
let outside = root.path().join("outside");
|
||||
fs::create_dir(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, Path::new(&vault).join("Notebook")).unwrap();
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
Some("Notebook"),
|
||||
raw,
|
||||
vec![],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
let directory = Path::new(&vault).join(".helixnotes/attachments");
|
||||
fs::remove_dir(&directory).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &directory).unwrap();
|
||||
assert!(import_note(
|
||||
&vault,
|
||||
source.to_str().unwrap(),
|
||||
None,
|
||||
raw,
|
||||
vec![reference(
|
||||
raw,
|
||||
"images/photo.png",
|
||||
"images/photo.png",
|
||||
false
|
||||
)],
|
||||
|_| Ok(())
|
||||
)
|
||||
.is_err());
|
||||
assert!(fs::read_dir(outside).unwrap().next().is_none());
|
||||
}
|
||||
+3200
-263
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,353 @@
|
||||
//! Metadata polling for portal directories that do not forward host inotify events.
|
||||
use notify::event::{CreateKind, ModifyKind, RemoveKind};
|
||||
use notify::{Event, EventKind};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, Metadata};
|
||||
use std::io::ErrorKind;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use super::operations::is_hidden;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Fingerprint {
|
||||
Directory,
|
||||
Note {
|
||||
size: u64,
|
||||
modified: (i64, i64),
|
||||
changed: (i64, i64),
|
||||
},
|
||||
}
|
||||
|
||||
impl Fingerprint {
|
||||
fn from_metadata(metadata: &Metadata) -> Self {
|
||||
if metadata.is_dir() {
|
||||
// Track directory presence, not child mutations or synthetic portal inode IDs.
|
||||
Self::Directory
|
||||
} else {
|
||||
Self::Note {
|
||||
size: metadata.len(),
|
||||
modified: (metadata.mtime(), metadata.mtime_nsec()),
|
||||
changed: (metadata.ctime(), metadata.ctime_nsec()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Snapshot = HashMap<PathBuf, Fingerprint>;
|
||||
|
||||
fn scan(root: &Path) -> notify::Result<Snapshot> {
|
||||
let metadata =
|
||||
fs::metadata(root).map_err(|error| notify::Error::io(error).add_path(root.to_owned()))?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(
|
||||
notify::Error::generic("Vault root is not a directory").add_path(root.to_owned())
|
||||
);
|
||||
}
|
||||
let mut snapshot = Snapshot::new();
|
||||
let entries = WalkDir::new(root)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|entry| entry.depth() == 0 || !is_hidden(entry.path()));
|
||||
for entry in entries {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(error)
|
||||
if error.depth() > 0
|
||||
&& error
|
||||
.io_error()
|
||||
.is_some_and(|error| error.kind() == ErrorKind::NotFound) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(notify::Error::generic(&error.to_string())
|
||||
.add_path(error.path().unwrap_or(root).to_owned()));
|
||||
}
|
||||
};
|
||||
let path = entry.path();
|
||||
if !entry.file_type().is_dir()
|
||||
&& path.extension().and_then(|extension| extension.to_str()) != Some("md")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let metadata = match fs::metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if entry.depth() > 0 && error.kind() == ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(notify::Error::io(error).add_path(path.to_owned())),
|
||||
};
|
||||
// Match note scanning's file symlinks without traversing directory symlinks.
|
||||
if metadata.is_file() || (metadata.is_dir() && !entry.file_type().is_symlink()) {
|
||||
snapshot.insert(path.to_owned(), Fingerprint::from_metadata(&metadata));
|
||||
}
|
||||
}
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
fn changes(before: &Snapshot, after: &Snapshot) -> Vec<Event> {
|
||||
let mut events = Vec::new();
|
||||
for (path, fingerprint) in after {
|
||||
let kind = match before.get(path) {
|
||||
None => EventKind::Create(CreateKind::Any),
|
||||
Some(previous) if previous != fingerprint => EventKind::Modify(ModifyKind::Any),
|
||||
Some(_) => continue,
|
||||
};
|
||||
events.push(Event::new(kind).add_path(path.clone()));
|
||||
}
|
||||
for path in before.keys().filter(|path| !after.contains_key(*path)) {
|
||||
events.push(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path.clone()));
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub struct PortalWatcher {
|
||||
_stop: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl PortalWatcher {
|
||||
pub fn start(
|
||||
root: PathBuf,
|
||||
events: mpsc::Sender<notify::Result<Event>>,
|
||||
interval: Duration,
|
||||
) -> Result<Self, String> {
|
||||
let started = Instant::now();
|
||||
let mut previous = scan(&root).map_err(|error| error.to_string())?;
|
||||
// Portal metadata calls consume host daemon CPU too. Large vaults trade
|
||||
// detection latency for idle time instead of scanning continuously.
|
||||
let mut delay = interval.max(started.elapsed().saturating_mul(20));
|
||||
let (stop, stopped) = mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("portal-vault-watch".into())
|
||||
.spawn(move || {
|
||||
while matches!(stopped.recv_timeout(delay), Err(RecvTimeoutError::Timeout)) {
|
||||
let started = Instant::now();
|
||||
match scan(&root) {
|
||||
Ok(current) => {
|
||||
for event in changes(&previous, ¤t) {
|
||||
if events.send(Ok(event)).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
Err(error) => {
|
||||
// A partial or inaccessible scan cannot prove that notes were deleted.
|
||||
if events.send(Err(error)).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
delay = interval.max(started.elapsed().saturating_mul(20));
|
||||
}
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(Self { _stop: stop })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::{File, FileTimes};
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn set_modified(path: &Path, time: SystemTime) {
|
||||
File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(time))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn assert_modified(before: &Snapshot, root: &Path, note: &Path) {
|
||||
let events = changes(before, &scan(root).unwrap());
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert_eq!(events[0].paths, [note]);
|
||||
assert_eq!(events[0].kind, EventKind::Modify(ModifyKind::Any));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_size_edit_with_restored_mtime_uses_ctime() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let note = vault.path().join("Note.md");
|
||||
fs::write(¬e, "before").unwrap();
|
||||
let modified = fs::metadata(¬e).unwrap().modified().unwrap();
|
||||
let before = scan(vault.path()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
fs::write(¬e, "after!").unwrap();
|
||||
set_modified(¬e, modified);
|
||||
assert_eq!(fs::metadata(¬e).unwrap().modified().unwrap(), modified);
|
||||
assert_modified(&before, vault.path(), ¬e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backdated_and_fractional_modification_times_are_detected() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let note = vault.path().join("Note.md");
|
||||
fs::write(¬e, "before").unwrap();
|
||||
set_modified(¬e, UNIX_EPOCH + Duration::new(1000, 100));
|
||||
let before = scan(vault.path()).unwrap();
|
||||
fs::write(¬e, "after!").unwrap();
|
||||
set_modified(¬e, UNIX_EPOCH + Duration::new(1000, 200));
|
||||
let metadata = fs::metadata(¬e).unwrap();
|
||||
assert_eq!((metadata.mtime(), metadata.mtime_nsec()), (1000, 200));
|
||||
assert_modified(&before, vault.path(), ¬e);
|
||||
let before = scan(vault.path()).unwrap();
|
||||
set_modified(¬e, UNIX_EPOCH + Duration::from_secs(10));
|
||||
assert_modified(&before, vault.path(), ¬e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_replacement_with_preserved_mtime_changes_ctime() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let note = vault.path().join("Note.md");
|
||||
let temporary = vault.path().join(".replacement");
|
||||
fs::write(¬e, "before").unwrap();
|
||||
let metadata = fs::metadata(¬e).unwrap();
|
||||
let before = scan(vault.path()).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
fs::write(&temporary, "after!").unwrap();
|
||||
set_modified(&temporary, metadata.modified().unwrap());
|
||||
fs::rename(&temporary, ¬e).unwrap();
|
||||
let replaced = fs::metadata(¬e).unwrap();
|
||||
assert_eq!(replaced.modified().unwrap(), metadata.modified().unwrap());
|
||||
assert_ne!(
|
||||
(replaced.ctime(), replaced.ctime_nsec()),
|
||||
(metadata.ctime(), metadata.ctime_nsec())
|
||||
);
|
||||
assert_modified(&before, vault.path(), ¬e);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_directory_create_rename_and_remove_keep_both_sides() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let before = scan(vault.path()).unwrap();
|
||||
let old = vault.path().join("Old");
|
||||
fs::create_dir_all(old.join("Nested")).unwrap();
|
||||
fs::write(old.join("Nested/Note.md"), "note").unwrap();
|
||||
let current = scan(vault.path()).unwrap();
|
||||
let created = changes(&before, ¤t);
|
||||
assert_eq!(created.len(), 3);
|
||||
assert!(created.iter().all(|event| event.kind.is_create()));
|
||||
let new = vault.path().join("New");
|
||||
fs::rename(&old, &new).unwrap();
|
||||
let renamed = scan(vault.path()).unwrap();
|
||||
let events = changes(¤t, &renamed);
|
||||
assert_eq!(
|
||||
events.iter().filter(|event| event.kind.is_create()).count(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
events.iter().filter(|event| event.kind.is_remove()).count(),
|
||||
3
|
||||
);
|
||||
fs::remove_dir_all(&new).unwrap();
|
||||
let events = changes(&renamed, &scan(vault.path()).unwrap());
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(events.iter().all(|event| event.kind.is_remove()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_resources_and_attachment_changes_are_excluded() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
for name in [
|
||||
".helixnotes",
|
||||
".hidden",
|
||||
"assets",
|
||||
"_attachments",
|
||||
"node_modules",
|
||||
] {
|
||||
fs::create_dir(vault.path().join(name)).unwrap();
|
||||
fs::write(vault.path().join(name).join("Hidden.md"), "hidden").unwrap();
|
||||
}
|
||||
let before = scan(vault.path()).unwrap();
|
||||
assert_eq!(
|
||||
before.len(),
|
||||
1,
|
||||
"only the explicitly selected vault root should be present"
|
||||
);
|
||||
fs::write(vault.path().join("image.png"), "attachment").unwrap();
|
||||
fs::write(vault.path().join(".hidden.md"), "hidden").unwrap();
|
||||
assert!(changes(&before, &scan(vault.path()).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_symlinks_are_watched_without_following_directory_symlinks() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let note = vault.path().join("Note.md");
|
||||
let alias = vault.path().join("Alias.md");
|
||||
fs::write(¬e, "before").unwrap();
|
||||
fs::write(outside.path().join("Outside.md"), "outside").unwrap();
|
||||
symlink(¬e, &alias).unwrap();
|
||||
symlink(outside.path(), vault.path().join("Directory.md")).unwrap();
|
||||
symlink(
|
||||
vault.path().join("Missing.md"),
|
||||
vault.path().join("Broken.md"),
|
||||
)
|
||||
.unwrap();
|
||||
let before = scan(vault.path()).unwrap();
|
||||
assert_eq!(before.len(), 3);
|
||||
assert!(before.contains_key(&alias));
|
||||
set_modified(¬e, UNIX_EPOCH + Duration::from_secs(1000));
|
||||
let events = changes(&before, &scan(vault.path()).unwrap());
|
||||
assert_eq!(events.len(), 2);
|
||||
assert!(events.iter().all(|event| event.kind.is_modify()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_errors_do_not_publish_partial_snapshots_and_recovery_detects_edits() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let note = vault.path().join("Note.md");
|
||||
fs::write(¬e, "before").unwrap();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let watcher =
|
||||
PortalWatcher::start(vault.path().to_owned(), sender, Duration::from_millis(20))
|
||||
.unwrap();
|
||||
let broken = vault.path().join("Loop.md");
|
||||
symlink(&broken, &broken).unwrap();
|
||||
assert!(receiver
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.unwrap()
|
||||
.is_err());
|
||||
set_modified(¬e, UNIX_EPOCH + Duration::from_secs(1000));
|
||||
fs::remove_file(&broken).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let event = receiver
|
||||
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
|
||||
.unwrap();
|
||||
if let Ok(event) = event {
|
||||
assert_eq!(event.paths.as_slice(), std::slice::from_ref(¬e));
|
||||
assert!(event.kind.is_modify());
|
||||
break;
|
||||
}
|
||||
}
|
||||
drop(watcher);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_failure_is_synchronous_and_drop_wakes_a_long_poll() {
|
||||
let vault = tempfile::tempdir().unwrap();
|
||||
let (sender, _receiver) = mpsc::channel();
|
||||
assert!(PortalWatcher::start(
|
||||
vault.path().join("Missing"),
|
||||
sender,
|
||||
Duration::from_secs(60)
|
||||
)
|
||||
.is_err());
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let watcher =
|
||||
PortalWatcher::start(vault.path().to_owned(), sender, Duration::from_secs(60)).unwrap();
|
||||
drop(watcher);
|
||||
assert!(matches!(
|
||||
receiver.recv_timeout(Duration::from_secs(2)),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected)
|
||||
));
|
||||
}
|
||||
}
|
||||
+340
-81
@@ -1,121 +1,241 @@
|
||||
use notify::{Config, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use std::path::Path;
|
||||
use notify::event::{CreateKind, ModifyKind, RemoveKind, RenameMode};
|
||||
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::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use crate::state::AppState;
|
||||
use crate::types::FileEvent;
|
||||
use crate::vault::operations::helixnotes_dir;
|
||||
use crate::vault::operations::{is_hidden, read_note_entry_fast};
|
||||
#[cfg(target_os = "linux")]
|
||||
use crate::vault::portal_watcher::PortalWatcher;
|
||||
|
||||
const IOS_POLL_INTERVAL: Duration = Duration::from_secs(10);
|
||||
const FLATPAK_POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||
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,
|
||||
#[cfg(target_os = "linux")]
|
||||
Portal,
|
||||
}
|
||||
|
||||
const fn watcher_backend_for_target(is_ios: bool) -> WatcherBackend {
|
||||
const fn watcher_backend_for_target(is_ios: bool, is_flatpak: bool) -> WatcherBackend {
|
||||
if is_ios {
|
||||
WatcherBackend::Poll
|
||||
} else if is_flatpak {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
WatcherBackend::Portal
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
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,
|
||||
const fn poll_interval_for_target(is_ios: bool, is_flatpak: bool) -> Duration {
|
||||
if is_ios {
|
||||
IOS_POLL_INTERVAL
|
||||
} else if is_flatpak {
|
||||
FLATPAK_POLL_INTERVAL
|
||||
} else {
|
||||
NATIVE_POLL_INTERVAL
|
||||
}
|
||||
}
|
||||
|
||||
pub enum VaultWatcher {
|
||||
Recommended(RecommendedWatcher),
|
||||
Poll(PollWatcher),
|
||||
Recommended {
|
||||
_watcher: RecommendedWatcher,
|
||||
},
|
||||
Poll {
|
||||
_watcher: PollWatcher,
|
||||
},
|
||||
#[cfg(target_os = "linux")]
|
||||
Portal {
|
||||
_watcher: PortalWatcher,
|
||||
},
|
||||
}
|
||||
|
||||
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 backend = watcher_backend_for_target(cfg!(target_os = "ios"));
|
||||
let config = Config::default().with_poll_interval(poll_interval_for_backend(backend));
|
||||
let mut watcher = match backend {
|
||||
WatcherBackend::Recommended => VaultWatcher::Recommended(
|
||||
RecommendedWatcher::new(tx, config).map_err(|e| e.to_string())?,
|
||||
),
|
||||
WatcherBackend::Poll => {
|
||||
VaultWatcher::Poll(PollWatcher::new(tx, config).map_err(|e| e.to_string())?)
|
||||
let is_ios = cfg!(target_os = "ios");
|
||||
// Portal paths do not forward inotify events. Their precise change times
|
||||
// detect external writes even when a sync client preserves modification time.
|
||||
let is_flatpak = option_env!("HELIXNOTES_INSTALL_TYPE") == Some("flatpak");
|
||||
let backend = watcher_backend_for_target(is_ios, is_flatpak);
|
||||
let config = Config::default().with_poll_interval(poll_interval_for_target(is_ios, is_flatpak));
|
||||
let watcher = match backend {
|
||||
WatcherBackend::Recommended => {
|
||||
let mut watcher = RecommendedWatcher::new(tx, config).map_err(|e| e.to_string())?;
|
||||
watcher
|
||||
.watch(Path::new(&vault_path), RecursiveMode::Recursive)
|
||||
.map_err(|e| e.to_string())?;
|
||||
VaultWatcher::Recommended { _watcher: watcher }
|
||||
}
|
||||
WatcherBackend::Poll => {
|
||||
let mut watcher = PollWatcher::new(tx, config).map_err(|e| e.to_string())?;
|
||||
watcher
|
||||
.watch(Path::new(&vault_path), RecursiveMode::Recursive)
|
||||
.map_err(|e| e.to_string())?;
|
||||
VaultWatcher::Poll { _watcher: watcher }
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
WatcherBackend::Portal => VaultWatcher::Portal {
|
||||
_watcher: PortalWatcher::start(PathBuf::from(&vault_path), tx, FLATPAK_POLL_INTERVAL)?,
|
||||
},
|
||||
};
|
||||
|
||||
watcher
|
||||
.watch(Path::new(&vault_path), RecursiveMode::Recursive)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let hn_dir = helixnotes_dir(&vault_path);
|
||||
|
||||
std::thread::spawn(move || {
|
||||
while let Ok(result) = rx.recv() {
|
||||
match result {
|
||||
Ok(event) => {
|
||||
// Skip all file events while importing
|
||||
let state = app.state::<AppState>();
|
||||
if state.importing.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
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 {
|
||||
Ok(event) => {
|
||||
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>();
|
||||
// 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) {
|
||||
continue;
|
||||
}
|
||||
// Each watcher belongs to its own vault. A detached note window may
|
||||
// still need changes from a vault that is no longer active; never
|
||||
// index those changes into the main window's active search index.
|
||||
if state.validate_vault(&vault_path).is_err() {
|
||||
continue;
|
||||
}
|
||||
if search.is_none() {
|
||||
match state.vault_snapshot(&vault_path) {
|
||||
Ok(index) => search = index,
|
||||
Err(error) => {
|
||||
log::error!("Could not open search index for watched vault: {error}");
|
||||
continue;
|
||||
}
|
||||
// Skip .helixnotes directory events
|
||||
let dominated_by_hn = event.paths.iter().all(|p| p.starts_with(&hn_dir));
|
||||
if dominated_by_hn {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only care about .md file events
|
||||
let has_md = event.paths.iter().any(|p| {
|
||||
p.extension().and_then(|x| x.to_str()) == Some("md") || p.is_dir()
|
||||
});
|
||||
|
||||
if !has_md {
|
||||
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
|
||||
// on FUSE filesystems where Syncthing/other apps generate
|
||||
// constant file activity that blocks the Tauri command channel.
|
||||
#[cfg(mobile)]
|
||||
{
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
while rx.try_recv().is_ok() {}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("File watcher error: {}", e);
|
||||
}
|
||||
let mut refresh_vault = false;
|
||||
for (path, event_type) in changes.drain() {
|
||||
if path.extension().and_then(|extension| extension.to_str()) == Some("md")
|
||||
&& !path.is_dir()
|
||||
{
|
||||
if let Some(search) = &search {
|
||||
if let Err(error) = search.queue_index_note(&path.to_string_lossy()) {
|
||||
log::error!("Could not queue external note for search: {error}");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,26 +250,165 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn ios_uses_polling_backend() {
|
||||
assert_eq!(watcher_backend_for_target(true), WatcherBackend::Poll);
|
||||
assert_eq!(
|
||||
watcher_backend_for_target(true, false),
|
||||
WatcherBackend::Poll
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_platforms_keep_recommended_backend() {
|
||||
assert_eq!(
|
||||
watcher_backend_for_target(false),
|
||||
watcher_backend_for_target(false, false),
|
||||
WatcherBackend::Recommended
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn watcher_backends_use_the_expected_intervals() {
|
||||
fn watcher_targets_use_the_expected_intervals() {
|
||||
assert_eq!(
|
||||
poll_interval_for_backend(WatcherBackend::Poll),
|
||||
poll_interval_for_target(true, false),
|
||||
Duration::from_secs(10)
|
||||
);
|
||||
assert_eq!(
|
||||
poll_interval_for_backend(WatcherBackend::Recommended),
|
||||
poll_interval_for_target(false, true),
|
||||
Duration::from_secs(2)
|
||||
);
|
||||
assert_eq!(
|
||||
poll_interval_for_target(false, false),
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "HelixNotes",
|
||||
"version": "1.3.5",
|
||||
"version": "1.3.7",
|
||||
"identifier": "com.helixnotes.app",
|
||||
"build": {
|
||||
"frontendDist": "../build",
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "HelixNotes",
|
||||
"label": "main",
|
||||
"width": 1200,
|
||||
"height": 800,
|
||||
"minWidth": 800,
|
||||
"minHeight": 500,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": false,
|
||||
"visible": false
|
||||
}
|
||||
]
|
||||
|
||||
+328
@@ -152,6 +152,65 @@
|
||||
src: url("/fonts/open-sans/OpenSans-BoldItalic.woff2") format("woff2");
|
||||
}
|
||||
|
||||
/* Ubuntu families - unmodified upstream fonts, Ubuntu Font Licence 1.0.
|
||||
Copyright and licence notices are bundled beside each family's local assets. */
|
||||
@font-face {
|
||||
font-family: "Ubuntu";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu/Ubuntu-R.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu";
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu/Ubuntu-B.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu";
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu/Ubuntu-RI.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu";
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu/Ubuntu-BI.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu Mono";
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu-mono/UbuntuMono-R.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu Mono";
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu-mono/UbuntuMono-B.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu Mono";
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu-mono/UbuntuMono-RI.ttf") format("truetype");
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Ubuntu Mono";
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url("/fonts/ubuntu-mono/UbuntuMono-BI.ttf") format("truetype");
|
||||
}
|
||||
|
||||
:root {
|
||||
/* Light theme */
|
||||
--bg-primary: #ffffff;
|
||||
@@ -1015,6 +1074,256 @@
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
:root[data-theme="matrix"] {
|
||||
--bg-primary: #0a0f0a;
|
||||
--bg-secondary: #060a06;
|
||||
--bg-tertiary: #0e150e;
|
||||
--bg-hover: #142014;
|
||||
--bg-active: #1a2a1a;
|
||||
--bg-editor: #0a0f0a;
|
||||
--text-primary: #b8f5b8;
|
||||
--text-secondary: #5fb95f;
|
||||
--text-tertiary: #3a7a3a;
|
||||
--text-accent: #00ff66;
|
||||
--border-color: #142014;
|
||||
--border-light: #0e150e;
|
||||
--accent: #00ff66;
|
||||
--accent-hover: #00e65c;
|
||||
--accent-light: color-mix(in srgb, #00ff66 12%, transparent);
|
||||
--danger: #ff5f56;
|
||||
--danger-hover: #e84a42;
|
||||
--success: #00ff66;
|
||||
--warning: #ffd700;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.6);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
|
||||
:root[data-theme="amber-crt"] {
|
||||
--bg-primary: #180f00;
|
||||
--bg-secondary: #120b00;
|
||||
--bg-tertiary: #201600;
|
||||
--bg-hover: #2a1e00;
|
||||
--bg-active: #352700;
|
||||
--bg-editor: #180f00;
|
||||
--text-primary: #ffcf70;
|
||||
--text-secondary: #c99a3e;
|
||||
--text-tertiary: #8a6a28;
|
||||
--text-accent: #ffb000;
|
||||
--border-color: #2a1e00;
|
||||
--border-light: #201600;
|
||||
--accent: #ffb000;
|
||||
--accent-hover: #e89e00;
|
||||
--accent-light: color-mix(in srgb, #ffb000 12%, transparent);
|
||||
--danger: #ff6b4a;
|
||||
--danger-hover: #e85638;
|
||||
--success: #b8c900;
|
||||
--warning: #ffd700;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.6);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.7);
|
||||
}
|
||||
|
||||
:root[data-theme="sepia"] {
|
||||
--bg-primary: #f4ecd8;
|
||||
--bg-secondary: #ebe0c7;
|
||||
--bg-tertiary: #e2d5b5;
|
||||
--bg-hover: #d9c9a3;
|
||||
--bg-active: #cebc92;
|
||||
--bg-editor: #f4ecd8;
|
||||
--text-primary: #433422;
|
||||
--text-secondary: #6b5538;
|
||||
--text-tertiary: #937a56;
|
||||
--text-accent: #9a6a3a;
|
||||
--border-color: #ddcdab;
|
||||
--border-light: #e2d5b5;
|
||||
--accent: #9a6a3a;
|
||||
--accent-hover: #875b2f;
|
||||
--accent-light: color-mix(in srgb, #9a6a3a 8%, transparent);
|
||||
--danger: #b5452f;
|
||||
--danger-hover: #9f3c29;
|
||||
--success: #6b8e23;
|
||||
--warning: #c08a2c;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
:root[data-theme="deep-ocean"] {
|
||||
--bg-primary: #081821;
|
||||
--bg-secondary: #05121a;
|
||||
--bg-tertiary: #0b2330;
|
||||
--bg-hover: #103040;
|
||||
--bg-active: #153c4e;
|
||||
--bg-editor: #081821;
|
||||
--text-primary: #cfeef5;
|
||||
--text-secondary: #86b8c4;
|
||||
--text-tertiary: #4f8290;
|
||||
--text-accent: #35c4d4;
|
||||
--border-color: #103040;
|
||||
--border-light: #0b2330;
|
||||
--accent: #35c4d4;
|
||||
--accent-hover: #26b0c0;
|
||||
--accent-light: color-mix(in srgb, #35c4d4 12%, transparent);
|
||||
--danger: #ff6b7d;
|
||||
--danger-hover: #e85566;
|
||||
--success: #4fd4a8;
|
||||
--warning: #f5c56b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
:root[data-theme="sandstone"] {
|
||||
--bg-primary: #faf3e8;
|
||||
--bg-secondary: #f1e6d3;
|
||||
--bg-tertiary: #e8d9c0;
|
||||
--bg-hover: #ddcaab;
|
||||
--bg-active: #d1bb98;
|
||||
--bg-editor: #faf3e8;
|
||||
--text-primary: #3a2c1c;
|
||||
--text-secondary: #6a543c;
|
||||
--text-tertiary: #9a8160;
|
||||
--text-accent: #c76b3f;
|
||||
--border-color: #e2d2b8;
|
||||
--border-light: #e8d9c0;
|
||||
--accent: #c76b3f;
|
||||
--accent-hover: #b45a30;
|
||||
--accent-light: color-mix(in srgb, #c76b3f 8%, transparent);
|
||||
--danger: #c0392b;
|
||||
--danger-hover: #a93226;
|
||||
--success: #7a8c3a;
|
||||
--warning: #d98e2b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
:root[data-theme="lavender"] {
|
||||
--bg-primary: #f6f3fc;
|
||||
--bg-secondary: #ece6f7;
|
||||
--bg-tertiary: #e1d8f0;
|
||||
--bg-hover: #d4c8e8;
|
||||
--bg-active: #c6b6df;
|
||||
--bg-editor: #f6f3fc;
|
||||
--text-primary: #2e2540;
|
||||
--text-secondary: #564a70;
|
||||
--text-tertiary: #8577a0;
|
||||
--text-accent: #7c5cc4;
|
||||
--border-color: #ddd3ee;
|
||||
--border-light: #e1d8f0;
|
||||
--accent: #7c5cc4;
|
||||
--accent-hover: #6b4bb0;
|
||||
--accent-light: color-mix(in srgb, #7c5cc4 8%, transparent);
|
||||
--danger: #d14d6a;
|
||||
--danger-hover: #ba4259;
|
||||
--success: #4fa06a;
|
||||
--warning: #d99a2b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
|
||||
:root[data-theme="graphite"] {
|
||||
--bg-primary: #17181a;
|
||||
--bg-secondary: #121315;
|
||||
--bg-tertiary: #1e2023;
|
||||
--bg-hover: #26282c;
|
||||
--bg-active: #303339;
|
||||
--bg-editor: #17181a;
|
||||
--text-primary: #d6d9dd;
|
||||
--text-secondary: #9ca0a6;
|
||||
--text-tertiary: #5f636a;
|
||||
--text-accent: #7f9cb3;
|
||||
--border-color: #26282c;
|
||||
--border-light: #1e2023;
|
||||
--accent: #7f9cb3;
|
||||
--accent-hover: #6d8aa1;
|
||||
--accent-light: color-mix(in srgb, #7f9cb3 12%, transparent);
|
||||
--danger: #e06c6c;
|
||||
--danger-hover: #cc5959;
|
||||
--success: #7fb37f;
|
||||
--warning: #d4b36b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
:root[data-theme="nebula"] {
|
||||
--bg-primary: #14102a;
|
||||
--bg-secondary: #0f0c21;
|
||||
--bg-tertiary: #1c1738;
|
||||
--bg-hover: #251e48;
|
||||
--bg-active: #2f2659;
|
||||
--bg-editor: #14102a;
|
||||
--text-primary: #e4ddf5;
|
||||
--text-secondary: #aba0cf;
|
||||
--text-tertiary: #6f6494;
|
||||
--text-accent: #b388ff;
|
||||
--border-color: #251e48;
|
||||
--border-light: #1c1738;
|
||||
--accent: #b388ff;
|
||||
--accent-hover: #9f73f0;
|
||||
--accent-light: color-mix(in srgb, #b388ff 14%, transparent);
|
||||
--danger: #ff6b8a;
|
||||
--danger-hover: #e85674;
|
||||
--success: #5fd4b0;
|
||||
--warning: #ffc46b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
:root[data-theme="wine"] {
|
||||
--bg-primary: #1c0f14;
|
||||
--bg-secondary: #160b10;
|
||||
--bg-tertiary: #26151c;
|
||||
--bg-hover: #311b24;
|
||||
--bg-active: #3d222c;
|
||||
--bg-editor: #1c0f14;
|
||||
--text-primary: #f0dde3;
|
||||
--text-secondary: #c49aa6;
|
||||
--text-tertiary: #8a606c;
|
||||
--text-accent: #d98ca0;
|
||||
--border-color: #311b24;
|
||||
--border-light: #26151c;
|
||||
--accent: #d98ca0;
|
||||
--accent-hover: #c8788d;
|
||||
--accent-light: color-mix(in srgb, #d98ca0 12%, transparent);
|
||||
--danger: #e85c5c;
|
||||
--danger-hover: #d14a4a;
|
||||
--success: #8cbf8c;
|
||||
--warning: #d9b36b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
:root[data-theme="jade"] {
|
||||
--bg-primary: #0b1a15;
|
||||
--bg-secondary: #071410;
|
||||
--bg-tertiary: #10261f;
|
||||
--bg-hover: #163128;
|
||||
--bg-active: #1d3d32;
|
||||
--bg-editor: #0b1a15;
|
||||
--text-primary: #d4f0e3;
|
||||
--text-secondary: #8cc4ac;
|
||||
--text-tertiary: #517a69;
|
||||
--text-accent: #2bbd8e;
|
||||
--border-color: #163128;
|
||||
--border-light: #10261f;
|
||||
--accent: #2bbd8e;
|
||||
--accent-hover: #22a87d;
|
||||
--accent-light: color-mix(in srgb, #2bbd8e 12%, transparent);
|
||||
--danger: #ff6b6b;
|
||||
--danger-hover: #e85656;
|
||||
--success: #2bbd8e;
|
||||
--warning: #e8c46b;
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.4);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
@@ -1232,6 +1541,25 @@ body.resizing {
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
|
||||
/* Image grids print as compact 2-column rows without their editing controls. */
|
||||
.ProseMirror .img-grid-header {
|
||||
display: none !important;
|
||||
}
|
||||
.ProseMirror .img-grid,
|
||||
.ProseMirror .img-grid[data-layout='masonry'] {
|
||||
display: grid !important;
|
||||
grid-template-columns: repeat(2, 1fr) !important;
|
||||
columns: auto !important;
|
||||
gap: 8px !important;
|
||||
break-inside: avoid;
|
||||
}
|
||||
.ProseMirror .img-grid img {
|
||||
margin: 0 !important;
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
break-inside: avoid;
|
||||
}
|
||||
|
||||
/* Avoid breaking inside these elements */
|
||||
h1,
|
||||
h2,
|
||||
|
||||
+162
-73
@@ -1,4 +1,5 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { ExternalNoteReference } from "./editor/externalNote";
|
||||
import type {
|
||||
AppConfig,
|
||||
CustomTheme,
|
||||
@@ -7,16 +8,20 @@ import type {
|
||||
NoteMeta,
|
||||
NotebookEntry,
|
||||
NoteTitleEntry,
|
||||
SearchResult,
|
||||
SearchPage,
|
||||
TrashContents,
|
||||
VaultState,
|
||||
VaultStats,
|
||||
TagStyle,
|
||||
TagStyleChange,
|
||||
ImportResult,
|
||||
BackupEntry,
|
||||
VersionEntry,
|
||||
TaskItem,
|
||||
ExternalVaultResult,
|
||||
StartupView,
|
||||
ToolbarLayout,
|
||||
PendingOpenFile,
|
||||
} from "./types";
|
||||
|
||||
export async function openVault(path: string): Promise<void> {
|
||||
@@ -39,6 +44,14 @@ export async function getAppConfig(): Promise<AppConfig> {
|
||||
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> {
|
||||
return invoke("set_theme", { theme });
|
||||
}
|
||||
@@ -67,14 +80,19 @@ export async function importCustomThemes(path: string): Promise<CustomTheme[]> {
|
||||
return invoke("import_custom_themes", { path });
|
||||
}
|
||||
|
||||
export async function setFontSize(size: number): Promise<void> {
|
||||
return invoke("set_font_size", { size });
|
||||
/** `preferred` marks a choice made in Appearance, which is what resetting the zoom returns to. */
|
||||
export async function setFontSize(size: number, preferred = false): Promise<void> {
|
||||
return invoke("set_font_size", { size, preferred });
|
||||
}
|
||||
|
||||
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> {
|
||||
return invoke("set_font_family", { family });
|
||||
}
|
||||
@@ -100,28 +118,31 @@ export async function countRootNotes(): Promise<number> {
|
||||
}
|
||||
|
||||
export async function createNotebook(
|
||||
vaultPath: string,
|
||||
parentRelative: string | null,
|
||||
name: string,
|
||||
): Promise<NotebookEntry> {
|
||||
return invoke("create_notebook", { parentRelative, name });
|
||||
return invoke("create_notebook", { vaultPath, parentRelative, name });
|
||||
}
|
||||
|
||||
export async function renameNotebook(
|
||||
vaultPath: string,
|
||||
path: string,
|
||||
newName: string,
|
||||
): Promise<string> {
|
||||
return invoke("rename_notebook", { path, newName });
|
||||
return invoke("rename_notebook", { vaultPath, path, newName });
|
||||
}
|
||||
|
||||
export async function deleteNotebook(path: string): Promise<void> {
|
||||
return invoke("delete_notebook", { path });
|
||||
export async function deleteNotebook(vaultPath: string, path: string): Promise<void> {
|
||||
return invoke("delete_notebook", { vaultPath, path });
|
||||
}
|
||||
|
||||
export async function moveNotebook(
|
||||
vaultPath: string,
|
||||
notebookPath: string,
|
||||
destParent: string,
|
||||
): Promise<string> {
|
||||
return invoke("move_notebook", { notebookPath, destParent });
|
||||
return invoke("move_notebook", { vaultPath, notebookPath, destParent });
|
||||
}
|
||||
|
||||
export async function getNotes(
|
||||
@@ -130,57 +151,72 @@ export async function getNotes(
|
||||
return invoke("get_notes", { notebookPath });
|
||||
}
|
||||
|
||||
export async function readNote(path: string): Promise<NoteContent> {
|
||||
return invoke("read_note", { path });
|
||||
export async function readNote(vaultPath: string, path: string): Promise<NoteContent> {
|
||||
return invoke("read_note", { vaultPath, path });
|
||||
}
|
||||
|
||||
export async function saveNote(
|
||||
vaultPath: string,
|
||||
path: string,
|
||||
meta: NoteMeta,
|
||||
body: string,
|
||||
): Promise<void> {
|
||||
return invoke("save_note", { path, meta, body });
|
||||
expectedRaw: string,
|
||||
): Promise<NoteContent> {
|
||||
return invoke("save_note", { vaultPath, path, meta, body, expectedRaw });
|
||||
}
|
||||
|
||||
export async function importNote(
|
||||
vaultPath: string,
|
||||
sourcePath: string,
|
||||
notebookRelative: string | null,
|
||||
expectedRaw: string,
|
||||
references: ExternalNoteReference[],
|
||||
): Promise<NoteContent> {
|
||||
return invoke("import_note", { vaultPath, sourcePath, notebookRelative, expectedRaw, references });
|
||||
}
|
||||
|
||||
export async function createNote(
|
||||
vaultPath: string,
|
||||
notebookRelative: string | null,
|
||||
title: string,
|
||||
): Promise<NoteEntry> {
|
||||
return invoke("create_note", { notebookRelative, title });
|
||||
return invoke("create_note", { vaultPath, notebookRelative, title });
|
||||
}
|
||||
|
||||
export async function duplicateNote(path: string): Promise<NoteEntry> {
|
||||
return invoke("duplicate_note", { path });
|
||||
export async function duplicateNote(vaultPath: string, path: string): Promise<NoteEntry> {
|
||||
return invoke("duplicate_note", { vaultPath, path });
|
||||
}
|
||||
|
||||
export async function createDailyNote(date?: string): Promise<NoteEntry> {
|
||||
return invoke("create_daily_note", { date: date ?? null });
|
||||
export async function createDailyNote(vaultPath: string, date?: string): Promise<NoteEntry> {
|
||||
return invoke("create_daily_note", { vaultPath, date: date ?? null });
|
||||
}
|
||||
|
||||
export async function renameNote(
|
||||
vaultPath: string,
|
||||
path: string,
|
||||
newTitle: string,
|
||||
): Promise<string> {
|
||||
return invoke("rename_note", { path, newTitle });
|
||||
return invoke("rename_note", { vaultPath, path, newTitle });
|
||||
}
|
||||
|
||||
export async function deleteNote(path: string): Promise<void> {
|
||||
return invoke("delete_note", { path });
|
||||
export async function deleteNote(vaultPath: string, path: string): Promise<void> {
|
||||
return invoke("delete_note", { vaultPath, path });
|
||||
}
|
||||
|
||||
export async function moveNote(
|
||||
vaultPath: string,
|
||||
notePath: string,
|
||||
destNotebook: string,
|
||||
): Promise<string> {
|
||||
return invoke("move_note", { notePath, destNotebook });
|
||||
return invoke("move_note", { vaultPath, notePath, destNotebook });
|
||||
}
|
||||
|
||||
export async function getAllTags(): Promise<[string, number][]> {
|
||||
return invoke("get_all_tags");
|
||||
}
|
||||
|
||||
export async function getAllNoteTitles(): Promise<NoteTitleEntry[]> {
|
||||
return invoke("get_all_note_titles");
|
||||
export async function getAllNoteTitles(vaultPath: string): Promise<NoteTitleEntry[]> {
|
||||
return invoke("get_all_note_titles", { vaultPath });
|
||||
}
|
||||
|
||||
export async function getNoteSwitcherTitles(
|
||||
@@ -189,15 +225,16 @@ export async function getNoteSwitcherTitles(
|
||||
return invoke("get_note_switcher_titles", { recentPaths });
|
||||
}
|
||||
|
||||
export async function getGraphData(): Promise<{ nodes: { title: string; path: string }[]; edges: { source: number; target: number; bidirectional: boolean }[] }> {
|
||||
return invoke("get_graph_data");
|
||||
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(
|
||||
query: string,
|
||||
limit?: number,
|
||||
): Promise<SearchResult[]> {
|
||||
return invoke("search_notes", { query, limit });
|
||||
offset?: number,
|
||||
): Promise<SearchPage> {
|
||||
return invoke("search_notes", { query, limit, offset });
|
||||
}
|
||||
|
||||
export async function reindex(): Promise<void> {
|
||||
@@ -209,30 +246,31 @@ export async function getTrash(): Promise<TrashContents> {
|
||||
}
|
||||
|
||||
export async function restoreNote(
|
||||
vaultPath: string,
|
||||
trashPath: string,
|
||||
destNotebook: string | null,
|
||||
): Promise<string> {
|
||||
return invoke("restore_note", { trashPath, destNotebook });
|
||||
return invoke("restore_note", { vaultPath, trashPath, destNotebook });
|
||||
}
|
||||
|
||||
export async function restoreNotebook(trashPath: string): Promise<string> {
|
||||
return invoke("restore_notebook", { trashPath });
|
||||
export async function restoreNotebook(vaultPath: string, trashPath: string): Promise<string> {
|
||||
return invoke("restore_notebook", { vaultPath, trashPath });
|
||||
}
|
||||
|
||||
export async function permanentDelete(path: string): Promise<void> {
|
||||
return invoke("permanent_delete", { path });
|
||||
export async function permanentDelete(vaultPath: string, path: string): Promise<void> {
|
||||
return invoke("permanent_delete", { vaultPath, path });
|
||||
}
|
||||
|
||||
export async function emptyTrash(): Promise<void> {
|
||||
return invoke("empty_trash");
|
||||
export async function emptyTrash(vaultPath: string): Promise<void> {
|
||||
return invoke("empty_trash", { vaultPath });
|
||||
}
|
||||
|
||||
export async function loadVaultState(): Promise<VaultState> {
|
||||
return invoke("load_vault_state");
|
||||
export async function loadVaultState(vaultPath: string): Promise<VaultState> {
|
||||
return invoke("load_vault_state", { vaultPath });
|
||||
}
|
||||
|
||||
export async function saveVaultState(vaultState: VaultState): Promise<void> {
|
||||
return invoke("save_vault_state", { vaultState });
|
||||
export async function saveVaultState(vaultPath: string, vaultState: VaultState): Promise<void> {
|
||||
return invoke("save_vault_state", { vaultPath, vaultState });
|
||||
}
|
||||
|
||||
export async function copyTextToClipboard(text: string): Promise<void> {
|
||||
@@ -243,30 +281,71 @@ export async function readClipboardImage(): Promise<number[]> {
|
||||
return invoke("read_clipboard_image");
|
||||
}
|
||||
|
||||
export interface ClipboardContents {
|
||||
text: string | null;
|
||||
html: string | null;
|
||||
}
|
||||
|
||||
export async function readClipboardContents(): Promise<ClipboardContents> {
|
||||
return invoke("read_clipboard_contents");
|
||||
}
|
||||
|
||||
export async function copyImageToClipboard(path: string): Promise<void> {
|
||||
return invoke("copy_image_to_clipboard", { path });
|
||||
}
|
||||
|
||||
export async function saveImage(name: string, data: number[]): Promise<string> {
|
||||
return invoke("save_image", { name, data });
|
||||
export async function saveImage(vaultPath: string, name: string, data: number[]): Promise<string> {
|
||||
return invoke("save_image", { vaultPath, name, data });
|
||||
}
|
||||
|
||||
export async function saveAttachment(
|
||||
vaultPath: string,
|
||||
name: string,
|
||||
data: number[],
|
||||
): Promise<string> {
|
||||
return invoke("save_attachment", { name, data });
|
||||
return invoke("save_attachment", { vaultPath, name, data });
|
||||
}
|
||||
|
||||
export async function getNotebookIcons(): Promise<Record<string, string>> {
|
||||
return invoke("get_notebook_icons");
|
||||
export async function getNotebookIcons(vaultPath: string): Promise<Record<string, string>> {
|
||||
return invoke("get_notebook_icons", { vaultPath });
|
||||
}
|
||||
|
||||
export async function setNotebookIcon(
|
||||
vaultPath: string,
|
||||
notebookRelative: string,
|
||||
iconRelative: string | null,
|
||||
): 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(
|
||||
@@ -327,16 +406,16 @@ export async function setGeneralSettings(
|
||||
});
|
||||
}
|
||||
|
||||
export async function getQuickAccess(): Promise<NoteEntry[]> {
|
||||
return invoke("get_quick_access");
|
||||
export async function getQuickAccess(vaultPath: string): Promise<NoteEntry[]> {
|
||||
return invoke("get_quick_access", { vaultPath });
|
||||
}
|
||||
|
||||
export async function addQuickAccess(noteRelative: string): Promise<void> {
|
||||
return invoke("add_quick_access", { noteRelative });
|
||||
export async function addQuickAccess(vaultPath: string, noteRelative: string): Promise<void> {
|
||||
return invoke("add_quick_access", { vaultPath, noteRelative });
|
||||
}
|
||||
|
||||
export async function removeQuickAccess(noteRelative: string): Promise<void> {
|
||||
return invoke("remove_quick_access", { noteRelative });
|
||||
export async function removeQuickAccess(vaultPath: string, noteRelative: string): Promise<void> {
|
||||
return invoke("remove_quick_access", { vaultPath, noteRelative });
|
||||
}
|
||||
|
||||
export async function reorderQuickAccess(paths: string[]): Promise<void> {
|
||||
@@ -352,12 +431,12 @@ export interface OrphanAttachment {
|
||||
size: number;
|
||||
}
|
||||
|
||||
export async function findOrphanedAttachments(): Promise<OrphanAttachment[]> {
|
||||
return invoke("find_orphaned_attachments");
|
||||
export async function findOrphanedAttachments(vaultPath: string): Promise<OrphanAttachment[]> {
|
||||
return invoke("find_orphaned_attachments", { vaultPath });
|
||||
}
|
||||
|
||||
export async function trashOrphanedAttachments(names: string[]): Promise<number> {
|
||||
return invoke("trash_orphaned_attachments", { names });
|
||||
export async function trashOrphanedAttachments(vaultPath: string, names: string[]): Promise<number> {
|
||||
return invoke("trash_orphaned_attachments", { vaultPath, names });
|
||||
}
|
||||
|
||||
export async function importObsidian(): Promise<void> {
|
||||
@@ -396,20 +475,20 @@ export async function copyPngToClipboard(data: Uint8Array): Promise<void> {
|
||||
|
||||
// ── Backup ──
|
||||
|
||||
export async function createBackup(): Promise<void> {
|
||||
return invoke("create_backup");
|
||||
export async function createBackup(vaultPath: string): Promise<void> {
|
||||
return invoke("create_backup", { vaultPath });
|
||||
}
|
||||
|
||||
export async function listBackups(): Promise<BackupEntry[]> {
|
||||
return invoke("list_backups");
|
||||
export async function listBackups(vaultPath: string): Promise<BackupEntry[]> {
|
||||
return invoke("list_backups", { vaultPath });
|
||||
}
|
||||
|
||||
export async function restoreBackup(backupPath: string): Promise<void> {
|
||||
return invoke("restore_backup", { backupPath });
|
||||
export async function restoreBackup(vaultPath: string, backupPath: string): Promise<void> {
|
||||
return invoke("restore_backup", { vaultPath, backupPath });
|
||||
}
|
||||
|
||||
export async function deleteBackup(backupPath: string): Promise<void> {
|
||||
return invoke("delete_backup", { backupPath });
|
||||
export async function deleteBackup(vaultPath: string, backupPath: string): Promise<void> {
|
||||
return invoke("delete_backup", { vaultPath, backupPath });
|
||||
}
|
||||
|
||||
export async function setBackupSettings(
|
||||
@@ -430,35 +509,38 @@ export async function setBackupSettings(
|
||||
|
||||
// ── Tasks ──
|
||||
|
||||
export async function getTasks(): Promise<TaskItem[]> {
|
||||
return invoke("get_tasks");
|
||||
export async function getTasks(notePath?: string): Promise<TaskItem[]> {
|
||||
return invoke("get_tasks", { notePath: notePath ?? null });
|
||||
}
|
||||
|
||||
export async function setTaskDone(
|
||||
vaultPath: string,
|
||||
notePath: string,
|
||||
line: number,
|
||||
rawLine: string,
|
||||
done: boolean,
|
||||
): 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(
|
||||
vaultPath: string,
|
||||
notePath: string,
|
||||
line: number,
|
||||
rawLine: string,
|
||||
priority: string | null,
|
||||
): 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(
|
||||
vaultPath: string,
|
||||
notePath: string,
|
||||
line: number,
|
||||
rawLine: string,
|
||||
due: string | null,
|
||||
): Promise<void> {
|
||||
return invoke("set_task_due", { notePath, line, rawLine, due });
|
||||
return invoke("set_task_due", { vaultPath, notePath, line, rawLine, due });
|
||||
}
|
||||
|
||||
// ── Sync (WebDAV) ──
|
||||
@@ -471,8 +553,9 @@ export async function setSyncSettings(
|
||||
syncOnOpen: boolean,
|
||||
syncOnChange: boolean,
|
||||
syncIntervalMinutes: number,
|
||||
syncFolderRequests: number,
|
||||
): Promise<void> {
|
||||
return invoke("set_sync_settings", { provider, url, username, password, syncOnOpen, syncOnChange, syncIntervalMinutes });
|
||||
return invoke("set_sync_settings", { provider, url, username, password, syncOnOpen, syncOnChange, syncIntervalMinutes, syncFolderRequests });
|
||||
}
|
||||
|
||||
export async function testSyncConnection(): Promise<void> {
|
||||
@@ -485,22 +568,24 @@ export async function syncNow(): Promise<void> {
|
||||
|
||||
// ── Version History ──
|
||||
|
||||
export async function getNoteVersions(noteId: string): Promise<VersionEntry[]> {
|
||||
return invoke("get_note_versions", { noteId });
|
||||
export async function getNoteVersions(vaultPath: string, noteId: string): Promise<VersionEntry[]> {
|
||||
return invoke("get_note_versions", { vaultPath, noteId });
|
||||
}
|
||||
|
||||
export async function getNoteVersionContent(
|
||||
vaultPath: string,
|
||||
noteId: string,
|
||||
timestamp: string,
|
||||
): Promise<string> {
|
||||
return invoke("get_note_version_content", { noteId, timestamp });
|
||||
return invoke("get_note_version_content", { vaultPath, noteId, timestamp });
|
||||
}
|
||||
|
||||
export async function createVersion(
|
||||
vaultPath: string,
|
||||
path: string,
|
||||
noteId: string,
|
||||
): Promise<void> {
|
||||
return invoke("create_version", { path, noteId });
|
||||
return invoke("create_version", { vaultPath, path, noteId });
|
||||
}
|
||||
|
||||
// ── AI ──
|
||||
@@ -542,6 +627,10 @@ export async function isMobilePlatform(): Promise<boolean> {
|
||||
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");
|
||||
}
|
||||
|
||||
export async function ackPendingOpenFile(id: number): Promise<void> {
|
||||
return invoke("ack_pending_open_file", { id });
|
||||
}
|
||||
+817
-264
File diff suppressed because it is too large.
Load diff
@@ -164,10 +164,15 @@
|
||||
}
|
||||
});
|
||||
|
||||
function handleEscape(e: KeyboardEvent) {
|
||||
if (e.key !== 'Escape') return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
$showCommandPalette = false;
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
$showCommandPalette = false;
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.min(selectedIndex + 1, filteredCommands.length - 1);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
@@ -179,7 +184,7 @@
|
||||
}
|
||||
|
||||
function applyTheme(t: string) {
|
||||
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', 'matrix', 'amber-crt', 'sepia', 'deep-ocean', 'sandstone', 'lavender', 'graphite', 'nebula', 'wine', 'jade'];
|
||||
const root = document.documentElement;
|
||||
root.classList.remove('dark');
|
||||
root.removeAttribute('data-theme');
|
||||
@@ -194,7 +199,7 @@
|
||||
|
||||
{#if $showCommandPalette}
|
||||
<!-- 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 -->
|
||||
<div class="palette-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
|
||||
<div class="palette-input-wrapper">
|
||||
|
||||
+4305
-2216
File diff suppressed because it is too large.
Load diff
+113
-145
@@ -1,8 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy } from 'svelte';
|
||||
import { onDestroy, untrack } from 'svelte';
|
||||
import { getGraphData } from '$lib/api';
|
||||
import { activeNotePath, appConfig } from '$lib/stores/app';
|
||||
import { isMobile } from '$lib/platform';
|
||||
import { applyGraphRepulsion } from '$lib/utils/graph-layout';
|
||||
import { buildGraphTopology, getGraphNeighborhood } from '$lib/utils/graph-topology';
|
||||
|
||||
let { onclose, onnavigate }: {
|
||||
onclose: () => void;
|
||||
@@ -14,7 +16,7 @@
|
||||
let searchQuery = $state('');
|
||||
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 GraphEdge { sourceIdx: number; targetIdx: number; bidirectional: boolean; }
|
||||
@@ -25,6 +27,7 @@
|
||||
let nodeIndexMap: Map<string, number> = new Map();
|
||||
let connectedSet: Set<number> = new Set();
|
||||
let nodeDegree: number[] = [];
|
||||
let incidentEdges = $state.raw<number[][]>([]);
|
||||
let searchMatchSet = $state.raw<Set<number> | null>(null);
|
||||
let folderColorMap = new Map<string, string>();
|
||||
|
||||
@@ -39,14 +42,18 @@
|
||||
let hoveredIdx = -1;
|
||||
let hoveredNeighborSet: Set<number> = new Set();
|
||||
let hoveredEdgeSet: Set<number> = new Set();
|
||||
let glowPhase = 0;
|
||||
let activeNodeIdx = $state(-1);
|
||||
// Svelte caches this until the active node or graph topology changes.
|
||||
let localNeighborhood = $derived(getGraphNeighborhood(activeNodeIdx, edges, incidentEdges));
|
||||
let navigatedFromGraph = false;
|
||||
|
||||
// Combined animation loop
|
||||
// Physics runs in short yielded batches; the completed graph is static.
|
||||
let physicsRemaining = 0;
|
||||
let animFrameId = 0;
|
||||
let lastGlowTs = 0;
|
||||
let physicsStep: Generator<void> | null = null;
|
||||
const layoutChannel = new MessageChannel();
|
||||
let layoutScheduled = false;
|
||||
let disposed = false;
|
||||
let drawFrame: number | null = null;
|
||||
|
||||
// DPI fix
|
||||
let dpr = 1;
|
||||
@@ -113,35 +120,9 @@
|
||||
function updateHoveredState(node: GraphNode | null) {
|
||||
hoveredNode = node;
|
||||
hoveredIdx = node ? nodes.indexOf(node) : -1;
|
||||
hoveredNeighborSet = new Set();
|
||||
hoveredEdgeSet = new Set();
|
||||
if (hoveredIdx < 0) return;
|
||||
hoveredNeighborSet.add(hoveredIdx);
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
const e = edges[i];
|
||||
if (e.sourceIdx === hoveredIdx || e.targetIdx === hoveredIdx) {
|
||||
hoveredEdgeSet.add(i);
|
||||
hoveredNeighborSet.add(e.sourceIdx);
|
||||
hoveredNeighborSet.add(e.targetIdx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nodes/edges visible in local mode (active note + direct neighbours)
|
||||
function computeLocalSets(): { nodeSet: Set<number>; edgeSet: Set<number> } {
|
||||
const nodeSet = new Set<number>();
|
||||
const edgeSet = new Set<number>();
|
||||
if (activeNodeIdx < 0) return { nodeSet, edgeSet };
|
||||
nodeSet.add(activeNodeIdx);
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
const e = edges[i];
|
||||
if (e.sourceIdx === activeNodeIdx || e.targetIdx === activeNodeIdx) {
|
||||
edgeSet.add(i);
|
||||
nodeSet.add(e.sourceIdx);
|
||||
nodeSet.add(e.targetIdx);
|
||||
}
|
||||
}
|
||||
return { nodeSet, edgeSet };
|
||||
const neighborhood = getGraphNeighborhood(hoveredIdx, edges, incidentEdges);
|
||||
hoveredNeighborSet = neighborhood.nodeSet;
|
||||
hoveredEdgeSet = neighborhood.edgeSet;
|
||||
}
|
||||
|
||||
function updateSearchMatch() {
|
||||
@@ -156,6 +137,7 @@
|
||||
loading = true;
|
||||
try {
|
||||
const data = await dataPromise;
|
||||
if (disposed) return;
|
||||
const w = canvasW || 800;
|
||||
const h = canvasH || 600;
|
||||
|
||||
@@ -172,15 +154,13 @@
|
||||
};
|
||||
});
|
||||
|
||||
connectedSet = new Set();
|
||||
nodeDegree = new Array(nodes.length).fill(0);
|
||||
edges = data.edges.map(e => {
|
||||
connectedSet.add(e.source);
|
||||
connectedSet.add(e.target);
|
||||
nodeDegree[e.source] = (nodeDegree[e.source] || 0) + 1;
|
||||
nodeDegree[e.target] = (nodeDegree[e.target] || 0) + 1;
|
||||
return { sourceIdx: e.source, targetIdx: e.target, bidirectional: e.bidirectional };
|
||||
});
|
||||
edges = data.edges.map(e => ({
|
||||
sourceIdx: e.source, targetIdx: e.target, bidirectional: e.bidirectional,
|
||||
}));
|
||||
const topology = buildGraphTopology(nodes.length, edges);
|
||||
connectedSet = topology.connectedSet;
|
||||
nodeDegree = topology.nodeDegree;
|
||||
incidentEdges = topology.incidentEdges;
|
||||
|
||||
buildFolderColors();
|
||||
updateSearchMatch();
|
||||
@@ -188,21 +168,16 @@
|
||||
} catch (e) {
|
||||
console.error('Failed to build graph:', e);
|
||||
}
|
||||
loading = false;
|
||||
startSimulation();
|
||||
}
|
||||
|
||||
function centerOnActiveNote() {
|
||||
if (!canvas || nodes.length === 0 || activeNodeIdx < 0) return;
|
||||
const activeNode = nodes[activeNodeIdx];
|
||||
const neighborhood: GraphNode[] = [activeNode];
|
||||
for (const edge of edges) {
|
||||
if (edge.sourceIdx === activeNodeIdx) neighborhood.push(nodes[edge.targetIdx]);
|
||||
else if (edge.targetIdx === activeNodeIdx) neighborhood.push(nodes[edge.sourceIdx]);
|
||||
}
|
||||
const neighborhood = localNeighborhood.nodeSet;
|
||||
const w = canvasW, h = canvasH, padding = 100;
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
for (const n of neighborhood) {
|
||||
for (const i of neighborhood) {
|
||||
const n = nodes[i];
|
||||
if (n.x < minX) minX = n.x; if (n.y < minY) minY = n.y;
|
||||
if (n.x > maxX) maxX = n.x; if (n.y > maxY) maxY = n.y;
|
||||
}
|
||||
@@ -228,87 +203,64 @@
|
||||
|
||||
function focusActive() {
|
||||
if (activeNodeIdx >= 0) centerOnActiveNote(); else fitToView();
|
||||
draw();
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function startSimulation() {
|
||||
// Initial settle - enough for a rough layout, camera set after full physics
|
||||
for (let i = 0; i < 80; i++) simulate();
|
||||
|
||||
// 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();
|
||||
// Keep the original initial layout; omit the animated settling tail.
|
||||
physicsRemaining = nodes.length > 0 ? 80 : 0;
|
||||
physicsStep = null;
|
||||
if (physicsRemaining === 0) {
|
||||
loading = false;
|
||||
requestDraw();
|
||||
} else {
|
||||
startLayoutLoop();
|
||||
}
|
||||
}
|
||||
|
||||
function startAnimLoop() {
|
||||
if (animFrameId) cancelAnimationFrame(animFrameId);
|
||||
lastGlowTs = 0;
|
||||
function startLayoutLoop() {
|
||||
if (disposed || layoutScheduled || physicsRemaining === 0) return;
|
||||
|
||||
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 (activeNodeIdx >= 0) centerOnActiveNote(); else fitToView();
|
||||
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--;
|
||||
}
|
||||
needsDraw = true;
|
||||
}
|
||||
} while (physicsRemaining > 0 && performance.now() < deadline);
|
||||
|
||||
// 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);
|
||||
if (physicsRemaining === 0) {
|
||||
loading = false;
|
||||
if (activeNodeIdx >= 0) centerOnActiveNote(); else fitToView();
|
||||
requestDraw();
|
||||
} else {
|
||||
animFrameId = 0;
|
||||
layoutScheduled = true;
|
||||
layoutChannel.port2.postMessage(null);
|
||||
}
|
||||
}
|
||||
animFrameId = requestAnimationFrame(loop);
|
||||
// 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() {
|
||||
const nodeCount = nodes.length;
|
||||
function* simulate(): Generator<void> {
|
||||
const graphNodes = nodes;
|
||||
const nodeCount = graphNodes.length;
|
||||
if (nodeCount === 0) return;
|
||||
const w = canvasW || 800, h = canvasH || 600;
|
||||
const centerX = w / 2, centerY = h / 2;
|
||||
|
||||
// Repulsion
|
||||
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;
|
||||
}
|
||||
}
|
||||
yield* applyGraphRepulsion(graphNodes);
|
||||
|
||||
// Spring attraction along 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 dist = Math.sqrt(dx * dx + dy * dy) || 1;
|
||||
const force = (dist - 130) * 0.012;
|
||||
@@ -318,22 +270,30 @@
|
||||
|
||||
// Center gravity - weaker for isolated nodes so they spread instead of clustering
|
||||
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;
|
||||
node.vx += (centerX - node.x) * gravity;
|
||||
node.vy += (centerY - node.y) * gravity;
|
||||
}
|
||||
|
||||
// Damping + integration
|
||||
for (const node of nodes) {
|
||||
for (const node of graphNodes) {
|
||||
if (node === dragging) continue;
|
||||
node.vx *= 0.85; node.vy *= 0.85;
|
||||
node.x += node.vx; node.y += node.vy;
|
||||
}
|
||||
}
|
||||
|
||||
function requestDraw() {
|
||||
if (disposed || drawFrame !== null) return;
|
||||
drawFrame = requestAnimationFrame(() => {
|
||||
drawFrame = null;
|
||||
draw();
|
||||
});
|
||||
}
|
||||
|
||||
function draw() {
|
||||
if (!canvas) return;
|
||||
if (disposed || !canvas || loading) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
@@ -345,19 +305,22 @@
|
||||
|
||||
const { border: borderColor, text: textColor, textSec, accent, bg: bgColor } = getStyles();
|
||||
const activePath = $activeNotePath || '';
|
||||
const pulse = 0.5 + 0.5 * Math.sin(glowPhase);
|
||||
const isHovering = hoveredIdx >= 0;
|
||||
const isSearching = searchMatchSet !== null;
|
||||
|
||||
// Local mode: restrict which nodes/edges are visible
|
||||
const { nodeSet: localNodeSet, edgeSet: localEdgeSet } = localMode ? computeLocalSets() : { nodeSet: null as Set<number> | null, edgeSet: null as Set<number> | null };
|
||||
const localNodeSet = localMode ? localNeighborhood.nodeSet : null;
|
||||
const localEdgeSet = localMode ? localNeighborhood.edgeSet : null;
|
||||
// Edge strokes and arrowheads keep their screen size when zoomed out; scaled with the
|
||||
// graph they thin out below a pixel and the links fade away from the nodes.
|
||||
const edgeScale = 1 / Math.min(zoom, 1);
|
||||
|
||||
// ── Edges ──────────────────────────────────────────────────────────────
|
||||
if (isHovering) {
|
||||
// Dimmed non-connected edges
|
||||
ctx.globalAlpha = 0.06;
|
||||
ctx.strokeStyle = borderColor;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.lineWidth = edgeScale;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
if (hoveredEdgeSet.has(i)) continue;
|
||||
@@ -370,9 +333,11 @@
|
||||
// Highlighted connected edges
|
||||
ctx.globalAlpha = 0.8;
|
||||
ctx.strokeStyle = accent;
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.lineWidth = 1.5 * edgeScale;
|
||||
ctx.beginPath();
|
||||
for (const i of hoveredEdgeSet) {
|
||||
// A neighbour's links to notes outside the local graph have no node to end on.
|
||||
if (localEdgeSet && !localEdgeSet.has(i)) continue;
|
||||
ctx.moveTo(nodes[edges[i].sourceIdx].x, nodes[edges[i].sourceIdx].y);
|
||||
ctx.lineTo(nodes[edges[i].targetIdx].x, nodes[edges[i].targetIdx].y);
|
||||
}
|
||||
@@ -381,16 +346,18 @@
|
||||
// Arrowheads on highlighted edges
|
||||
ctx.fillStyle = accent;
|
||||
ctx.globalAlpha = 0.8;
|
||||
const al = 7 * edgeScale, aw = 3.5 * edgeScale;
|
||||
const drawArrow = (tipX: number, tipY: number, ux: number, uy: number) => {
|
||||
const bx = tipX - ux * 7, by = tipY - uy * 7;
|
||||
const bx = tipX - ux * al, by = tipY - uy * al;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(tipX, tipY);
|
||||
ctx.lineTo(bx - uy * 3.5, by + ux * 3.5);
|
||||
ctx.lineTo(bx + uy * 3.5, by - ux * 3.5);
|
||||
ctx.lineTo(bx - uy * aw, by + ux * aw);
|
||||
ctx.lineTo(bx + uy * aw, by - ux * aw);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
};
|
||||
for (const i of hoveredEdgeSet) {
|
||||
if (localEdgeSet && !localEdgeSet.has(i)) continue;
|
||||
const e = edges[i];
|
||||
const src = nodes[e.sourceIdx];
|
||||
const tgt = nodes[e.targetIdx];
|
||||
@@ -410,7 +377,7 @@
|
||||
} else if (isSearching) {
|
||||
// All visible edges faint
|
||||
ctx.strokeStyle = borderColor;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.lineWidth = edgeScale;
|
||||
ctx.globalAlpha = 0.07;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
@@ -432,7 +399,7 @@
|
||||
ctx.stroke();
|
||||
} else {
|
||||
ctx.strokeStyle = borderColor;
|
||||
ctx.lineWidth = isMobile ? 1.5 : 1;
|
||||
ctx.lineWidth = (isMobile ? 1.5 : 1) * edgeScale;
|
||||
ctx.globalAlpha = isMobile ? 0.65 : 0.35;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
@@ -497,12 +464,11 @@
|
||||
|
||||
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) {
|
||||
const glowR = radius + 12;
|
||||
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 + glowAlpha);
|
||||
glow.addColorStop(0, accent + '80');
|
||||
glow.addColorStop(1, accent + '00');
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.beginPath();
|
||||
@@ -524,9 +490,9 @@
|
||||
}
|
||||
ctx.fill();
|
||||
|
||||
// Active outer ring - static, alpha pulse only
|
||||
// Static active outer ring.
|
||||
if (isActive) {
|
||||
ctx.globalAlpha = 0.35 + pulse * 0.3;
|
||||
ctx.globalAlpha = 0.5;
|
||||
ctx.beginPath();
|
||||
ctx.arc(node.x, node.y, radius + 3, 0, Math.PI * 2);
|
||||
ctx.strokeStyle = accent;
|
||||
@@ -587,7 +553,7 @@
|
||||
}
|
||||
|
||||
function getNodeAt(clientX: number, clientY: number): GraphNode | null {
|
||||
if (!canvas) return null;
|
||||
if (!canvas || loading) return null;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = (clientX - rect.left - pan.x) / zoom;
|
||||
const y = (clientY - rect.top - pan.y) / zoom;
|
||||
@@ -617,18 +583,17 @@
|
||||
dragging.x = (e.clientX - rect.left - pan.x) / zoom;
|
||||
dragging.y = (e.clientY - rect.top - pan.y) / zoom;
|
||||
dragging.vx = 0; dragging.vy = 0;
|
||||
draw();
|
||||
requestDraw();
|
||||
} else if (panning) {
|
||||
pan.x = e.clientX - panStart.x;
|
||||
pan.y = e.clientY - panStart.y;
|
||||
draw();
|
||||
requestDraw();
|
||||
} else if (!dragging) {
|
||||
const node = getNodeAt(e.clientX, e.clientY);
|
||||
if (node !== hoveredNode) {
|
||||
updateHoveredState(node);
|
||||
if (canvas) canvas.style.cursor = node ? 'pointer' : 'grab';
|
||||
// Restart loop if it stopped (for immediate hover redraws)
|
||||
if (!animFrameId) draw();
|
||||
if (!layoutScheduled) requestDraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -653,7 +618,7 @@
|
||||
zoom = Math.max(0.2, Math.min(5, zoom * (e.deltaY > 0 ? 0.9 : 1.1)));
|
||||
pan.x = mx - (mx - pan.x) * (zoom / oldZoom);
|
||||
pan.y = my - (my - pan.y) * (zoom / oldZoom);
|
||||
draw();
|
||||
requestDraw();
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
@@ -692,11 +657,11 @@
|
||||
dragging.x = (t.clientX - rect.left - pan.x) / zoom;
|
||||
dragging.y = (t.clientY - rect.top - pan.y) / zoom;
|
||||
dragging.vx = 0; dragging.vy = 0;
|
||||
draw();
|
||||
requestDraw();
|
||||
} else if (panning) {
|
||||
pan.x = t.clientX - panStart.x;
|
||||
pan.y = t.clientY - panStart.y;
|
||||
draw();
|
||||
requestDraw();
|
||||
}
|
||||
} else if (e.touches.length === 2) {
|
||||
const dx = e.touches[0].clientX - e.touches[1].clientX;
|
||||
@@ -711,7 +676,7 @@
|
||||
zoom = Math.max(0.2, Math.min(5, zoom * (dist / lastTouchDist)));
|
||||
pan.x = mx - (mx - pan.x) * (zoom / oldZoom);
|
||||
pan.y = my - (my - pan.y) * (zoom / oldZoom);
|
||||
draw();
|
||||
requestDraw();
|
||||
}
|
||||
lastTouchDist = dist;
|
||||
}
|
||||
@@ -754,20 +719,23 @@
|
||||
navigatedFromGraph = false;
|
||||
centerOnActiveNote();
|
||||
}
|
||||
if (newIdx >= 0 && !animFrameId && canvas) startAnimLoop();
|
||||
else if (newIdx < 0 && !animFrameId && canvas) draw(); // remove stale glow immediately
|
||||
if (!layoutScheduled && canvas) untrack(requestDraw);
|
||||
});
|
||||
|
||||
// React to search query changes
|
||||
$effect(() => {
|
||||
const _q = searchQuery; // track
|
||||
updateSearchMatch();
|
||||
if (canvas && !animFrameId) draw();
|
||||
if (activeNodeIdx >= 0 && !animFrameId && canvas) startAnimLoop();
|
||||
if (canvas && !layoutScheduled) untrack(requestDraw);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (animFrameId) cancelAnimationFrame(animFrameId);
|
||||
disposed = true;
|
||||
if (drawFrame !== null) cancelAnimationFrame(drawFrame);
|
||||
drawFrame = null;
|
||||
layoutChannel.port1.onmessage = null;
|
||||
layoutChannel.port1.close();
|
||||
layoutChannel.port2.close();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -798,7 +766,7 @@
|
||||
<div class="graph-stats">
|
||||
{#if !loading}
|
||||
{#if localMode && activeNodeIdx >= 0}
|
||||
{computeLocalSets().nodeSet.size} notes · {computeLocalSets().edgeSet.size} links
|
||||
{localNeighborhood.nodeSet.size} notes · {localNeighborhood.edgeSet.size} links
|
||||
{:else}
|
||||
{nodes.length} notes · {edges.length} links
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import SnapshotDocument from './SnapshotDocument.svelte';
|
||||
import { comparableBody, compareHistory, splitSnapshot, type HistoryComparison, type HistoryRow } from '$lib/utils/history-comparison';
|
||||
|
||||
let { raw, current, selected, loading, error, canRestore, onRetry, onRestore, renderSnapshot }: {
|
||||
raw: string | null;
|
||||
current: string;
|
||||
selected: string | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
canRestore: boolean;
|
||||
onRetry: () => void;
|
||||
onRestore: () => void;
|
||||
renderSnapshot: (body: string) => string;
|
||||
} = $props();
|
||||
|
||||
let view = $state<'changes' | 'snapshot'>('changes');
|
||||
let source = $state(false);
|
||||
let comparison = $state<HistoryComparison | null>(null);
|
||||
let comparing = $state(false);
|
||||
let comparisonError = $state<string | null>(null);
|
||||
let request = 0;
|
||||
const snapshot = $derived(splitSnapshot(raw ?? ''));
|
||||
const rendered = $derived.by(() => {
|
||||
if (view !== 'snapshot' || source || raw === null) return { html: '', error: '' };
|
||||
try {
|
||||
return { html: renderSnapshot(snapshot.body), error: '' };
|
||||
} catch (cause) {
|
||||
return { html: '', error: `Could not render this snapshot: ${String(cause)}` };
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const content = raw;
|
||||
const working = current;
|
||||
const body = snapshot.body;
|
||||
const generation = ++request;
|
||||
comparison = null;
|
||||
comparisonError = null;
|
||||
comparing = content !== null;
|
||||
if (content !== null) {
|
||||
compareHistory(comparableBody(working), comparableBody(body)).then((result) => {
|
||||
if (generation !== request) return;
|
||||
comparison = result;
|
||||
}).catch((cause) => {
|
||||
if (generation === request) comparisonError = `Could not compare this version: ${String(cause)}`;
|
||||
}).finally(() => {
|
||||
if (generation === request) comparing = false;
|
||||
});
|
||||
}
|
||||
return () => { request++; };
|
||||
});
|
||||
|
||||
async function navigateTabs(event: KeyboardEvent) {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
view = event.key === 'Home' ? 'changes' : event.key === 'End' ? 'snapshot' : view === 'changes' ? 'snapshot' : 'changes';
|
||||
await tick();
|
||||
document.getElementById(`history-tab-${view}`)?.focus();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet lines(rows: HistoryRow[])}
|
||||
{#each rows as row}
|
||||
<div class="diff-line {row.kind}">
|
||||
<span class="line-number" aria-label="Current note line">{row.currentLine ?? ''}</span>
|
||||
<span class="line-number" aria-label="Snapshot line">{row.snapshotLine ?? ''}</span>
|
||||
<span class="line-sign" aria-label={row.kind === 'added' ? 'Added by restoring' : row.kind === 'removed' ? 'Removed by restoring' : 'Unchanged'}>{row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}</span>
|
||||
<span class="line-text">{row.text || ' '}{#if !row.newline}<span class="line-ending">No final newline</span>{/if}</span>
|
||||
</div>
|
||||
{/each}
|
||||
{/snippet}
|
||||
|
||||
<section class="history-review" aria-label="Version review">
|
||||
<div class="review-header">
|
||||
<div class="review-heading">
|
||||
<strong>{selected ?? 'Version History'}</strong>
|
||||
<span>Read-only. Your current note stays unchanged.</span>
|
||||
</div>
|
||||
<div class="review-tabs" role="tablist" aria-label="Version view" tabindex="-1" onkeydown={navigateTabs}>
|
||||
<button id="history-tab-changes" role="tab" aria-selected={view === 'changes'} aria-controls="history-changes" tabindex={view === 'changes' ? 0 : -1} onclick={() => view = 'changes'}>Changes</button>
|
||||
<button id="history-tab-snapshot" role="tab" aria-selected={view === 'snapshot'} aria-controls="history-snapshot" tabindex={view === 'snapshot' ? 0 : -1} onclick={() => view = 'snapshot'}>Snapshot</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<p class="review-status" role="status">Loading version…</p>
|
||||
{:else if error}
|
||||
<div class="review-status" role="alert"><p>{error}</p><button class="review-button" onclick={onRetry}>Retry</button></div>
|
||||
{:else if raw === null}
|
||||
<p class="review-status">Select a version to review.</p>
|
||||
{:else if view === 'changes'}
|
||||
<div id="history-changes" class="review-panel" role="tabpanel" aria-labelledby="history-tab-changes" tabindex="0">
|
||||
<div class="comparison-heading">
|
||||
<span>Current note → selected version</span>
|
||||
{#if comparison}<span class="comparison-count"><span class="added-count">+{comparison.added}</span> <span class="removed-count">−{comparison.removed}</span> lines</span>{/if}
|
||||
</div>
|
||||
{#if comparing}
|
||||
<p class="review-status" role="status">Comparing…</p>
|
||||
{:else if comparisonError}
|
||||
<p class="review-status" role="alert">{comparisonError}</p>
|
||||
{:else if comparison && comparison.added === 0 && comparison.removed === 0}
|
||||
<p class="review-status">No content changes. Metadata is not restored.</p>
|
||||
{:else if comparison}
|
||||
<div class="history-diff">
|
||||
{#key raw}
|
||||
{#each comparison.chunks as chunk}
|
||||
{#if chunk.kind === 'unchanged'}
|
||||
<details class="unchanged-lines"><summary>{chunk.rows.length} unchanged {chunk.rows.length === 1 ? 'line' : 'lines'}</summary>{@render lines(chunk.rows)}</details>
|
||||
{:else}
|
||||
{@render lines(chunk.rows)}
|
||||
{/if}
|
||||
{/each}
|
||||
{/key}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div id="history-snapshot" class="review-panel" role="tabpanel" aria-labelledby="history-tab-snapshot" tabindex="0">
|
||||
<div class="snapshot-heading"><span>Selected snapshot</span><button class="source-toggle" aria-pressed={source} onclick={() => source = !source}>{source ? 'Rendered view' : 'View source'}</button></div>
|
||||
{#if snapshot.body === ''}
|
||||
<p class="review-status">This snapshot is empty.</p>
|
||||
{:else if source}
|
||||
<textarea class="snapshot-source" readonly aria-label="Snapshot Markdown, read-only" value={snapshot.body}></textarea>
|
||||
{:else if rendered.error}
|
||||
<p class="review-status" role="alert">{rendered.error} View source to inspect the stored body.</p>
|
||||
{:else}
|
||||
<SnapshotDocument html={rendered.html} />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if raw !== null && snapshot.metadata}
|
||||
<details class="history-metadata"><summary>Metadata (not restored)</summary><pre>{snapshot.metadata}</pre></details>
|
||||
{/if}
|
||||
{#if selected}
|
||||
<div class="review-actions"><span>Restore replaces the current note’s content only.</span><button class="history-restore-btn" disabled={!canRestore} onclick={onRestore}>Restore this version</button></div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.history-review { display: flex; flex-direction: column; flex: 1; min-width: 0; min-height: 0; background: var(--bg-primary); }
|
||||
.review-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; border-bottom: 1px solid var(--border-light); flex-shrink: 0; flex-wrap: wrap; }
|
||||
.review-heading { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.review-heading strong { font-size: 13px; overflow-wrap: anywhere; }
|
||||
.review-heading > span { font-size: 12px; color: var(--text-secondary); }
|
||||
.review-tabs { display: flex; gap: 2px; padding: 2px; border: 1px solid var(--border-color); border-radius: 6px; }
|
||||
.review-tabs button, .source-toggle, .review-button { padding: 6px 10px; border: none; border-radius: 4px; background: transparent; color: var(--text-secondary); font-size: 12px; cursor: pointer; }
|
||||
.review-tabs button[aria-selected="true"] { background: var(--accent-light); color: var(--accent); }
|
||||
.review-tabs button:focus-visible, .source-toggle:focus-visible, .review-button:focus-visible, summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.review-panel { flex: 1; min-height: 0; overflow: auto; outline-offset: -2px; }
|
||||
.review-panel:focus-visible { outline: 2px solid var(--accent); }
|
||||
.comparison-heading, .snapshot-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 10px 16px; font-size: 12px; color: var(--text-secondary); border-bottom: 1px solid var(--border-light); flex-wrap: wrap; }
|
||||
.comparison-count { font-family: var(--font-mono, monospace); }
|
||||
.added-count { color: var(--success); } .removed-count { color: var(--danger, #dc2626); }
|
||||
.review-status { margin: 0; padding: 20px 16px; color: var(--text-secondary); font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }
|
||||
.review-button { margin-top: 8px; border: 1px solid var(--border-color); background: var(--bg-secondary); color: var(--text-primary); }
|
||||
.history-diff { padding: 8px 0; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; }
|
||||
.diff-line { display: grid; grid-template-columns: 3.5em 3.5em 1.6em minmax(0, 1fr); align-items: start; padding: 1px 12px 1px 4px; }
|
||||
.diff-line.added { background: color-mix(in srgb, var(--success) 12%, var(--bg-primary)); }
|
||||
.diff-line.removed { background: color-mix(in srgb, var(--danger, #dc2626) 12%, var(--bg-primary)); }
|
||||
.line-number { padding-right: 8px; text-align: right; color: var(--text-tertiary); user-select: none; font-size: 10px; }
|
||||
.line-sign { color: var(--text-secondary); user-select: none; }
|
||||
.added .line-sign { color: var(--success); } .removed .line-sign { color: var(--danger, #dc2626); }
|
||||
.line-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.line-ending { display: block; color: var(--text-secondary); font-style: italic; font-size: 10px; }
|
||||
.unchanged-lines > summary { padding: 7px 16px; color: var(--text-secondary); background: var(--bg-secondary); cursor: pointer; font-family: var(--font-sans, inherit); font-size: 12px; }
|
||||
.snapshot-source { display: block; width: 100%; min-height: 100%; margin: 0; padding: 16px; resize: none; border: none; background: var(--bg-primary); color: var(--text-primary); font-family: var(--font-mono, monospace); font-size: 13px; line-height: 1.6; }
|
||||
.snapshot-source:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.history-metadata { flex-shrink: 0; border-top: 1px solid var(--border-light); font-size: 12px; color: var(--text-secondary); max-height: 30%; overflow: auto; }
|
||||
.history-metadata > summary { cursor: pointer; padding: 8px 16px; }
|
||||
.history-metadata pre { margin: 0; padding: 0 16px 12px; font-family: var(--font-mono, monospace); font-size: 11px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.review-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 16px; padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); border-top: 1px solid var(--border-light); background: var(--bg-secondary); flex-shrink: 0; flex-wrap: wrap; }
|
||||
.review-actions > span { font-size: 11px; color: var(--text-secondary); }
|
||||
.history-restore-btn { padding: 8px 14px; border: 1px solid var(--accent); border-radius: 6px; color: var(--accent); background: var(--accent-light); font-size: 12px; font-weight: 500; cursor: pointer; }
|
||||
.history-restore-btn:hover:not(:disabled) { background: var(--accent); color: var(--bg-primary); }
|
||||
.history-restore-btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.history-restore-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
@media (max-width: 600px) {
|
||||
.review-header { padding: 10px 12px; }
|
||||
.review-tabs { width: 100%; }
|
||||
.review-tabs button { flex: 1; min-height: 44px; }
|
||||
.source-toggle, .review-button, .history-restore-btn { min-height: 44px; }
|
||||
.diff-line { grid-template-columns: 2.8em 2.8em 1.4em minmax(0, 1fr); padding-right: 8px; }
|
||||
.review-actions { padding: 10px 12px; padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); }
|
||||
.review-actions > span, .history-restore-btn { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -236,6 +236,7 @@
|
||||
<img
|
||||
bind:this={imageElement}
|
||||
class:interacting
|
||||
crossorigin="anonymous"
|
||||
src={src}
|
||||
alt={alt}
|
||||
draggable="false"
|
||||
|
||||
@@ -95,6 +95,13 @@
|
||||
if (event.target === event.currentTarget) close();
|
||||
}
|
||||
|
||||
function handleEscape(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close();
|
||||
}
|
||||
|
||||
function openLink(url: string) {
|
||||
openUrl(url).catch(console.error);
|
||||
}
|
||||
@@ -104,7 +111,7 @@
|
||||
|
||||
{#if $showInfo}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="info-overlay" onclick={closeFromOverlay} onkeydown={(e) => { if (e.key === 'Escape') close(); }}>
|
||||
<div class="info-overlay" onclick={closeFromOverlay} onkeydowncapture={handleEscape} onkeydown={handleEscape}>
|
||||
<div class="info-panel">
|
||||
<div class="info-header">
|
||||
<h2>Info</h2>
|
||||
|
||||
+469
-236
File diff suppressed because it is too large.
Load diff
@@ -82,7 +82,7 @@
|
||||
const requestPaths = buildNoteSwitcherRequestPaths($activeNotePath, $navHistory.stack);
|
||||
const [titlesResult, quickAccessResult] = await Promise.allSettled([
|
||||
getNoteSwitcherTitles(requestPaths),
|
||||
getQuickAccess()
|
||||
getQuickAccess(vaultPath)
|
||||
]);
|
||||
if (!open || generation !== loadGeneration) return;
|
||||
|
||||
@@ -253,7 +253,7 @@
|
||||
<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}>
|
||||
<div class="note-row" class:current-row={row.current} title={row.path}>
|
||||
{#if row.current}<span class="current-marker" aria-hidden="true"></span>{/if}
|
||||
<button
|
||||
class="note-primary"
|
||||
@@ -270,7 +270,7 @@
|
||||
type="button"
|
||||
aria-label={`Open ${row.title} in new window`}
|
||||
title={`Open ${row.title} in new window`}
|
||||
onclick={() => openNoteWindow(row.path, row.title)}
|
||||
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" />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { onMount, onDestroy, untrack } from 'svelte';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { getCurrentWebview } from '@tauri-apps/api/webview';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
@@ -10,13 +10,18 @@
|
||||
activeNotePath,
|
||||
editorDirty,
|
||||
readOnly,
|
||||
sourceMode
|
||||
sourceMode,
|
||||
tagStyles
|
||||
} from '$lib/stores/app';
|
||||
import { readNote } from '$lib/api';
|
||||
import { completeWindowClose, cancelWindowClose, getTagStyles, readNote } from '$lib/api';
|
||||
import { keybindings, matchAction } from '$lib/keybindings';
|
||||
import { isMobile } from '$lib/platform';
|
||||
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);
|
||||
|
||||
const appWindow = getCurrentWindow();
|
||||
const appWebview = getCurrentWebview();
|
||||
@@ -24,11 +29,19 @@
|
||||
let editor = $state<Editor>(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 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() {
|
||||
maximized = await appWindow.isMaximized();
|
||||
const value = await appWindow.isMaximized();
|
||||
if (!disposed) maximized = value;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
@@ -36,6 +49,11 @@
|
||||
const unlisten = appWindow.onResized(() => checkMaximized());
|
||||
return () => { unlisten.then(fn => fn()); };
|
||||
});
|
||||
$effect(() => {
|
||||
const title = $activeNote?.meta.title;
|
||||
if (title && !disposed) void appWindow.setTitle(`${title} - HelixNotes`);
|
||||
});
|
||||
|
||||
|
||||
let lastMouseDown = 0;
|
||||
const RESIZE_EDGE = 6;
|
||||
@@ -79,44 +97,150 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
unlistenUiScale = await listen<number>('ui-scale-changed', (event) => {
|
||||
void applyUiScale(event.payload);
|
||||
});
|
||||
await applyUiScale($appConfig?.ui_scale ?? 1);
|
||||
|
||||
try {
|
||||
const content = await readNote(notePath);
|
||||
$activeNote = content;
|
||||
$activeNotePath = notePath;
|
||||
$editorDirty = false;
|
||||
setTimeout(() => {
|
||||
editor?.loadNote(notePath, content.content);
|
||||
appWindow.setTitle(`${content.meta.title} - HelixNotes`);
|
||||
}, 50);
|
||||
} catch (e) {
|
||||
loadError = String(e);
|
||||
onMount(() => {
|
||||
const vault = ownerVault;
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
||||
unlistenFileChange = await listen<FileEvent>('file-changed', async (event) => {
|
||||
if (event.payload.path === notePath && event.payload.event_type === 'modify') {
|
||||
if (!$editorDirty) {
|
||||
async function initialize() {
|
||||
if (!isMobile) {
|
||||
const closeListener = await appWindow.onCloseRequested(async (event) => {
|
||||
event.preventDefault();
|
||||
if (!isCurrentOwner()) { await cancelWindowClose(); return; }
|
||||
try {
|
||||
const content = await readNote(notePath);
|
||||
// Ignore the file-watcher echo of our own save; only reload genuine external edits.
|
||||
if (content.content.trim() !== (editor?.getCurrentBody() ?? '').trim()) {
|
||||
$activeNote = content;
|
||||
editor?.loadNote(notePath, content.content);
|
||||
}
|
||||
} catch (_) {}
|
||||
if (editor && !(await editor.flushSave())) { await cancelWindowClose(); return; }
|
||||
if (!isCurrentOwner()) { await cancelWindowClose(); return; }
|
||||
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;
|
||||
$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 (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(() => {
|
||||
disposed = true;
|
||||
if (initialNavigationToken !== null) cancelNoteNavigation(initialNavigationToken);
|
||||
if (initialLoadTimer !== null) clearTimeout(initialLoadTimer);
|
||||
unlistenFileChange?.();
|
||||
unlistenVaultRestored?.();
|
||||
removeMobileFlushListeners?.();
|
||||
unlistenUiScale?.();
|
||||
unlistenClose?.();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -54,6 +54,86 @@
|
||||
<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 if icon === 'music'}
|
||||
<path d="M9 18V5l12-2v13" />
|
||||
<circle cx="6" cy="18" r="3" />
|
||||
<circle cx="18" cy="16" r="3" />
|
||||
{:else if icon === 'camera'}
|
||||
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2Z" />
|
||||
<circle cx="12" cy="13" r="4" />
|
||||
{:else if icon === 'film'}
|
||||
<rect x="2" y="2" width="20" height="20" rx="2" />
|
||||
<path d="M7 2v20M17 2v20M2 12h20M2 7h5M2 17h5M17 17h5M17 7h5" />
|
||||
{:else if icon === 'gamepad'}
|
||||
<path d="M6 11h4M8 9v4M15 12h.01M18 10h.01" />
|
||||
<path d="M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5Z" />
|
||||
{:else if icon === 'cart'}
|
||||
<circle cx="9" cy="21" r="1" />
|
||||
<circle cx="20" cy="21" r="1" />
|
||||
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6" />
|
||||
{:else if icon === 'money'}
|
||||
<path d="M12 1v22M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
|
||||
{:else if icon === 'health'}
|
||||
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
|
||||
{:else if icon === 'food'}
|
||||
<path d="M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2M7 2v20M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7" />
|
||||
{:else if icon === 'coffee'}
|
||||
<path d="M18 8h1a4 4 0 0 1 0 8h-1M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4ZM6 1v3M10 1v3M14 1v3" />
|
||||
{:else if icon === 'leaf'}
|
||||
<path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z" />
|
||||
<path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12" />
|
||||
{:else if icon === 'users'}
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="9" cy="7" r="4" />
|
||||
<path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" />
|
||||
{:else if icon === 'chat'}
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z" />
|
||||
{:else if icon === 'mail'}
|
||||
<rect x="2" y="4" width="20" height="16" rx="2" />
|
||||
<path d="m22 6-10 7L2 6" />
|
||||
{:else if icon === 'lock'}
|
||||
<rect x="3" y="11" width="18" height="11" rx="2" />
|
||||
<path d="M7 11V7a5 5 0 0 1 10 0v4" />
|
||||
{:else if icon === 'wrench'}
|
||||
<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z" />
|
||||
{:else if icon === 'pen'}
|
||||
<path d="M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
|
||||
{:else if icon === 'tag'}
|
||||
<path d="M12.6 2.6a2 2 0 0 0-1.42-.6H4a2 2 0 0 0-2 2v7.17a2 2 0 0 0 .6 1.42l8.7 8.7a2.43 2.43 0 0 0 3.42 0l6.58-6.58a2.43 2.43 0 0 0 0-3.42Z" />
|
||||
<path d="M7.5 7.5h.01" />
|
||||
{:else if icon === 'clock'}
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 7v5l3.5 2" />
|
||||
{:else if icon === 'bell'}
|
||||
<path d="M10.27 21a2 2 0 0 0 3.46 0" />
|
||||
<path d="M3.26 15.33A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.67C19.41 13.96 18 12.5 18 8a6 6 0 0 0-12 0c0 4.5-1.41 5.96-2.74 7.33Z" />
|
||||
{:else if icon === 'pin'}
|
||||
<path d="M20 10c0 5-5.5 10.2-7.4 11.8a1 1 0 0 1-1.2 0C9.5 20.2 4 15 4 10a8 8 0 0 1 16 0Z" />
|
||||
<circle cx="12" cy="10" r="3" />
|
||||
{:else if icon === 'gift'}
|
||||
<rect x="3" y="8" width="18" height="4" rx="1" />
|
||||
<path d="M12 8v13M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7" />
|
||||
<path d="M7.5 8a2.5 2.5 0 0 1 0-5C11 3 12 8 12 8s1-5 4.5-5a2.5 2.5 0 0 1 0 5" />
|
||||
{:else if icon === 'trophy'}
|
||||
<path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6M18 9h1.5a2.5 2.5 0 0 0 0-5H18M4 22h16" />
|
||||
<path d="M10 14.7V17c0 .6-.5 1-1 1.2-1.2.5-2 2-2 3.8M14 14.7V17c0 .6.5 1 1 1.2 1.2.5 2 2 2 3.8M18 2H6v7a6 6 0 0 0 12 0V2Z" />
|
||||
{:else if icon === 'rocket'}
|
||||
<path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09Z" />
|
||||
<path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2Z" />
|
||||
<path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5" />
|
||||
{:else if icon === 'flag'}
|
||||
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1Z" />
|
||||
<path d="M4 22V3" />
|
||||
{:else if icon === 'shield'}
|
||||
<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1Z" />
|
||||
{:else if icon === 'gear'}
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" />
|
||||
{:else if icon === 'search'}
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<path d="m21 21-4.3-4.3" />
|
||||
{:else if icon === 'zap'}
|
||||
<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14Z" />
|
||||
{: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" />
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
<script lang="ts">
|
||||
let { onResize }: { onResize: (delta: number) => void } = $props();
|
||||
import { onDestroy } from 'svelte';
|
||||
|
||||
let { onResize, label, value, min, max, controls }: {
|
||||
onResize: (delta: number) => void;
|
||||
label?: string;
|
||||
value?: number;
|
||||
min?: number;
|
||||
max?: number;
|
||||
controls?: string;
|
||||
} = $props();
|
||||
let active = $state(false);
|
||||
let startX = 0;
|
||||
let rafId = 0;
|
||||
@@ -26,15 +35,31 @@
|
||||
}
|
||||
}
|
||||
|
||||
function onMouseUp() {
|
||||
function stopResize(flush: boolean) {
|
||||
if (active) document.body.classList.remove('resizing');
|
||||
active = false;
|
||||
document.body.classList.remove('resizing');
|
||||
if (rafId) { cancelAnimationFrame(rafId); rafId = 0; }
|
||||
if (pendingDelta) { onResize(pendingDelta); pendingDelta = 0; }
|
||||
if (flush && pendingDelta) onResize(pendingDelta);
|
||||
pendingDelta = 0;
|
||||
window.removeEventListener('mousemove', onMouseMove);
|
||||
window.removeEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
|
||||
function onMouseUp() { stopResize(true); }
|
||||
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (value === undefined || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) return;
|
||||
event.preventDefault();
|
||||
onResize((event.key === 'ArrowLeft' ? -1 : 1) * (event.shiftKey ? 32 : 16));
|
||||
}
|
||||
|
||||
onDestroy(() => stopResize(false));
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="resize-handle" class:active onmousedown={onMouseDown}></div>
|
||||
<!-- A separator with a supplied range is an interactive resize control. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
|
||||
<div class="resize-handle" class:active onmousedown={onMouseDown} onkeydown={onKeyDown}
|
||||
role={value === undefined ? 'presentation' : 'separator'} tabindex={value === undefined ? undefined : 0}
|
||||
aria-label={label} aria-orientation={value === undefined ? undefined : 'vertical'}
|
||||
aria-valuenow={value} aria-valuemin={min} aria-valuemax={max} aria-controls={controls}
|
||||
title={value === undefined ? undefined : 'Use Left and Right arrow keys to resize'}></div>
|
||||
@@ -1,92 +1,160 @@
|
||||
<script lang="ts">
|
||||
import { showSearch, activeNote, activeNotePath, editorDirty, appConfig, mobileView, notebooks, activeNotebook, activeTag, viewMode } from '$lib/stores/app';
|
||||
import { searchNotes, readNote } from '$lib/api';
|
||||
import { debounce } from '$lib/utils/debounce';
|
||||
import type { SearchResult, NotebookEntry } from '$lib/types';
|
||||
import { tick } from 'svelte';
|
||||
import { showSearch, appConfig, notebooks } from '$lib/stores/app';
|
||||
import { searchNotes } from '$lib/api';
|
||||
import { relativePath } from '$lib/utils/paths';
|
||||
import type { SearchResult, SearchMatch, NotebookEntry } from '$lib/types';
|
||||
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 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 inputEl = $state<HTMLInputElement>(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) => {
|
||||
if (!q.trim()) {
|
||||
results = [];
|
||||
return;
|
||||
}
|
||||
function cancelSearch() {
|
||||
requestGeneration++;
|
||||
if (searchTimer !== null) clearTimeout(searchTimer);
|
||||
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 {
|
||||
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;
|
||||
} catch (e) {
|
||||
console.error('Search failed:', e);
|
||||
results = [];
|
||||
await tick();
|
||||
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;
|
||||
}
|
||||
}, 150);
|
||||
}
|
||||
|
||||
function startSearch(value: string, pageOffset = 0, immediate = false) {
|
||||
cancelSearch();
|
||||
query = value;
|
||||
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);
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if ($showSearch && inputEl) {
|
||||
query = '';
|
||||
results = [];
|
||||
selectedIndex = 0;
|
||||
setTimeout(() => inputEl?.focus(), 50);
|
||||
const open = $showSearch;
|
||||
const vault = currentVault;
|
||||
const input = inputEl;
|
||||
cancelSearch();
|
||||
query = '';
|
||||
results = [];
|
||||
total = 0;
|
||||
offset = 0;
|
||||
selectedIndex = 0;
|
||||
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() {
|
||||
doSearch(query);
|
||||
function handleInput(event: Event) {
|
||||
if ((event as InputEvent).isComposing) composing = true;
|
||||
startSearch((event.currentTarget as HTMLInputElement).value);
|
||||
}
|
||||
|
||||
function scrollToSelected() {
|
||||
if (!resultsEl) return;
|
||||
const item = resultsEl.children[selectedIndex] as HTMLElement;
|
||||
if (item) item.scrollIntoView({ block: 'nearest' });
|
||||
void tick().then(() => {
|
||||
const item = resultsEl?.children[selectedIndex] as HTMLElement | undefined;
|
||||
item?.scrollIntoView({ block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
function handleEscape(e: KeyboardEvent) {
|
||||
if (e.key !== 'Escape' || e.isComposing) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close();
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
$showSearch = false;
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.stopPropagation();
|
||||
if (e.isComposing || composing || loading || opening) return;
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
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();
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
} else if (e.key === 'Enter' && e.target === inputEl && results[selectedIndex]) {
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.max(selectedIndex - 1, 0);
|
||||
scrollToSelected();
|
||||
} else if (e.key === 'Enter' && results.length > 0) {
|
||||
openResult(results[selectedIndex]);
|
||||
void openResult(results[selectedIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
function getNotebook(path: string): string {
|
||||
const vault = $appConfig?.active_vault;
|
||||
if (!vault) return '';
|
||||
let rel = path;
|
||||
if (rel.startsWith(vault + '/')) rel = rel.substring(vault.length + 1);
|
||||
if (!currentVault) return '';
|
||||
const rel = relativePath(currentVault, path);
|
||||
const lastSlash = rel.lastIndexOf('/');
|
||||
if (lastSlash <= 0) return '';
|
||||
return rel.substring(0, lastSlash);
|
||||
return lastSlash > 0 ? rel.substring(0, lastSlash) : '';
|
||||
}
|
||||
|
||||
function highlightSnippet(snippet: string, q: string): string {
|
||||
if (!q.trim() || !snippet) return escapeHtml(snippet);
|
||||
const words = q.trim().split(/\s+/).filter(w => w.length > 1);
|
||||
if (words.length === 0) return escapeHtml(snippet);
|
||||
const escaped = escapeHtml(snippet);
|
||||
const pattern = words.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
|
||||
const re = new RegExp(`(${pattern})`, 'gi');
|
||||
return escaped.replace(re, '<mark>$1</mark>');
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
function textParts(text: string, matches: SearchMatch[]) {
|
||||
const parts: { text: string; matched: boolean }[] = [];
|
||||
let cursor = 0;
|
||||
for (const { start, end } of matches) {
|
||||
if (start > cursor) parts.push({ text: text.slice(cursor, start), matched: false });
|
||||
parts.push({ text: text.slice(start, end), matched: true });
|
||||
cursor = end;
|
||||
}
|
||||
if (cursor < text.length) parts.push({ text: text.slice(cursor), matched: false });
|
||||
return parts;
|
||||
}
|
||||
|
||||
function findNotebookByPath(nbs: NotebookEntry[], target: string): NotebookEntry | null {
|
||||
for (const nb of nbs) {
|
||||
if (nb.path === target) return nb;
|
||||
if (relativePath(nb.path, target) === '.') return nb;
|
||||
if (nb.children.length) {
|
||||
const found = findNotebookByPath(nb.children, target);
|
||||
if (found) return found;
|
||||
@@ -96,41 +164,43 @@
|
||||
}
|
||||
|
||||
async function openResult(result: SearchResult) {
|
||||
if (loading || opening || !$showSearch || !results.includes(result)) return;
|
||||
const generation = requestGeneration;
|
||||
const vault = currentVault;
|
||||
opening = true;
|
||||
error = '';
|
||||
try {
|
||||
const content = await readNote(result.path);
|
||||
$activeNote = content;
|
||||
$activeNotePath = result.path;
|
||||
$editorDirty = false;
|
||||
$showSearch = false;
|
||||
// Reveal the note in the notes list: switch to its notebook (or All Notes).
|
||||
const sep = result.path.includes('\\') ? '\\' : '/';
|
||||
const parentDir = result.path.slice(0, result.path.lastIndexOf(sep));
|
||||
const nb = parentDir ? findNotebookByPath($notebooks, parentDir) : null;
|
||||
if (nb) {
|
||||
$activeNotebook = nb;
|
||||
$activeTag = null;
|
||||
$viewMode = 'notebook';
|
||||
} else {
|
||||
$activeNotebook = null;
|
||||
$activeTag = null;
|
||||
$viewMode = 'all';
|
||||
const normalized = result.path.replace(/\\/g, '/');
|
||||
const parentDir = normalized.slice(0, normalized.lastIndexOf('/'));
|
||||
const notebook = parentDir ? findNotebookByPath($notebooks, parentDir) : null;
|
||||
const opened = await onSelectNote(result, notebook, () => isCurrent(generation, vault));
|
||||
if (!isCurrent(generation, vault)) return;
|
||||
if (!opened) {
|
||||
error = 'Could not open this note.';
|
||||
return;
|
||||
}
|
||||
if (isMobile) $mobileView = 'editor';
|
||||
} catch (e) {
|
||||
console.error('Failed to open search result:', e);
|
||||
close();
|
||||
} catch (cause) {
|
||||
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() {
|
||||
cancelSearch();
|
||||
$showSearch = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if $showSearch}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="search-overlay" onclick={close} onkeydown={handleKeydown}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="search-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
|
||||
<div class="search-overlay" role="presentation" onclick={close} onkeydowncapture={handleEscape}>
|
||||
<div class="search-panel" role="dialog" aria-modal="true" aria-label="Search notes" tabindex="-1" onclick={(e) => e.stopPropagation()} onkeydown={handleKeydown}>
|
||||
<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">
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
@@ -140,18 +210,36 @@
|
||||
bind:this={inputEl}
|
||||
type="text"
|
||||
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}
|
||||
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}
|
||||
</div>
|
||||
|
||||
{#if results.length > 0}
|
||||
<div class="search-results" bind:this={resultsEl}>
|
||||
{#each results as result, i}
|
||||
{#if error}<div class="search-error" role="alert">{error}</div>{/if}
|
||||
{#if composing}
|
||||
<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
|
||||
class="result-item"
|
||||
id={`global-search-result-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === selectedIndex}
|
||||
tabindex="-1"
|
||||
disabled={opening}
|
||||
class:selected={i === selectedIndex}
|
||||
onclick={() => openResult(result)}
|
||||
onmouseenter={() => (selectedIndex = i)}
|
||||
@@ -163,25 +251,18 @@
|
||||
<line x1="16" y1="13" x2="8" y2="13" />
|
||||
<line x1="16" y1="17" x2="8" y2="17" />
|
||||
</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)}
|
||||
<span class="result-notebook">{getNotebook(result.path)}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#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}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="search-footer">
|
||||
<span class="search-count">{results.length} result{results.length !== 1 ? 's' : ''}</span>
|
||||
<span class="search-hints">
|
||||
<kbd>↑</kbd><kbd>↓</kbd> navigate
|
||||
<kbd>↵</kbd> open
|
||||
</span>
|
||||
</div>
|
||||
{:else if query.trim()}
|
||||
{:else if query.trim() && !error}
|
||||
<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">
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
@@ -189,13 +270,29 @@
|
||||
<line x1="8" y1="8" x2="14" y2="14" />
|
||||
<line x1="14" y1="8" x2="8" y2="14" />
|
||||
</svg>
|
||||
<span>No results for "{query}"</span>
|
||||
<span>{total > 0 ? 'Results changed. Choose an earlier page.' : `No results for "${query}"`}</span>
|
||||
</div>
|
||||
{:else}
|
||||
{:else if !error}
|
||||
<div class="search-empty">
|
||||
<span>Type to search across all notes</span>
|
||||
</div>
|
||||
{/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>↑</kbd><kbd>↓</kbd> navigate <kbd>↵</kbd> open</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -230,8 +327,8 @@
|
||||
border: 1px solid var(--border-color);
|
||||
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;
|
||||
width: 620px;
|
||||
max-height: 460px;
|
||||
width: min(620px, calc(100vw - 32px));
|
||||
max-height: min(460px, calc(85dvh - 24px));
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -257,6 +354,7 @@
|
||||
|
||||
.search-input-wrapper input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-primary);
|
||||
@@ -339,18 +437,23 @@
|
||||
}
|
||||
|
||||
.result-snippet {
|
||||
display: block;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
margin-top: 4px;
|
||||
margin-left: 24px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.result-snippet :global(mark) {
|
||||
.result-title mark,
|
||||
.result-snippet mark {
|
||||
background: color-mix(in srgb, var(--accent) 25%, transparent);
|
||||
color: var(--text-accent);
|
||||
border-radius: 2px;
|
||||
@@ -359,6 +462,8 @@
|
||||
|
||||
.search-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 18px;
|
||||
@@ -406,4 +511,32 @@
|
||||
color: var(--text-tertiary);
|
||||
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>
|
||||
@@ -1,16 +1,19 @@
|
||||
<script lang="ts">
|
||||
import { showSettings, theme, resolvedTheme, appConfig, platformIsMobile, activeVaultConfig, updateAvailable as globalUpdateAvailable, updateObj as globalUpdateObj, installType, settingsTab, vaultReady, androidApkUrl, checkForUpdateMobile, notebookSortMode, isManagedInstall, customThemes } from '$lib/stores/app';
|
||||
import { setTheme, setSystemThemes, setAccentColor, setFontSize, setScrollToChangeFontSize, setFontFamily, setLineHeight, setUiScale, setContentWidth, setGeneralSettings, importObsidian, createBackup, listBackups, restoreBackup, deleteBackup, setBackupSettings, setAiSettings, testAiConnection, setSyncSettings, testSyncConnection, syncNow, getAppConfig, saveCustomTheme, deleteCustomTheme, exportCustomTheme, importCustomThemes, getVaultStats, findOrphanedAttachments, trashOrphanedAttachments } from '$lib/api';
|
||||
import { untrack } from 'svelte';
|
||||
import { showSettings, syncState, theme, resolvedTheme, appConfig, platformIsMobile, activeVaultConfig, updateAvailable as globalUpdateAvailable, updateObj as globalUpdateObj, installType, settingsTab, vaultReady, androidApkUrl, checkForUpdateMobile, notebookSortMode, isManagedInstall, customThemes } from '$lib/stores/app';
|
||||
import { setTheme, setSystemThemes, setAccentColor, setFontSize, setScrollToChangeFontSize, setFontFamily, setLineHeight, setUiScale, setContentWidth, setGeneralSettings, importObsidian, createBackup, listBackups, restoreBackup, deleteBackup, setBackupSettings, setAiSettings, testAiConnection, setSyncSettings, testSyncConnection, syncNow, saveCustomTheme, deleteCustomTheme, exportCustomTheme, importCustomThemes, getVaultStats, findOrphanedAttachments, trashOrphanedAttachments } from '$lib/api';
|
||||
import { darkThemes, isMobile, isAndroid } from '$lib/platform';
|
||||
import { open as openDialog, save as saveDialog } from '@tauri-apps/plugin-dialog';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { getVersion } from '@tauri-apps/api/app';
|
||||
import { getCurrentWebview } from '@tauri-apps/api/webview';
|
||||
import { applyUiScale, defaultUiScale, uiScalePresets } from '$lib/ui-scale';
|
||||
import { openUrl } from '$lib/api';
|
||||
import type { OrphanAttachment } from '$lib/api';
|
||||
import type { ImportResult, BackupEntry, CustomTheme, CustomThemeColors, StartupView, VaultStats } from '$lib/types';
|
||||
import { normalizeStartupView } from '$lib/utils/startup-view';
|
||||
|
||||
let { onBeforeVaultSwitch }: { onBeforeVaultSwitch: () => Promise<boolean> } = $props();
|
||||
|
||||
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
|
||||
|
||||
type Tab = 'general' | 'editor' | 'styling' | 'import' | 'backup' | 'maintenance' | 'ai' | 'sync' | 'updates';
|
||||
@@ -123,9 +126,20 @@
|
||||
let orphanedAttachments = $state<OrphanAttachment[] | null>(null);
|
||||
let scanningOrphanedAttachments = $state(false);
|
||||
let trashingOrphanedAttachments = $state(false);
|
||||
let orphanedVault: string | null = null;
|
||||
let orphanError = $state('');
|
||||
let cleanupRequest = 0;
|
||||
const maintenanceVault = $derived($appConfig?.active_vault ?? null);
|
||||
const orphanedAttachmentTotal = $derived((orphanedAttachments ?? []).reduce((total, attachment) => total + attachment.size, 0));
|
||||
|
||||
$effect(() => {
|
||||
void maintenanceVault;
|
||||
cleanupRequest++;
|
||||
orphanedAttachments = null;
|
||||
orphanedVault = null;
|
||||
orphanError = '';
|
||||
scanningOrphanedAttachments = false;
|
||||
trashingOrphanedAttachments = false;
|
||||
if (!$showSettings) {
|
||||
vaultStats = null;
|
||||
vaultStatsError = false;
|
||||
@@ -136,10 +150,13 @@
|
||||
});
|
||||
|
||||
async function loadVaultStats() {
|
||||
const vault = maintenanceVault;
|
||||
vaultStatsError = false;
|
||||
try {
|
||||
vaultStats = await getVaultStats();
|
||||
const stats = await getVaultStats();
|
||||
if ($showSettings && maintenanceVault === vault) vaultStats = stats;
|
||||
} catch (error) {
|
||||
if (!$showSettings || maintenanceVault !== vault) return;
|
||||
vaultStats = null;
|
||||
vaultStatsError = true;
|
||||
console.error('Failed to load vault statistics:', error);
|
||||
@@ -154,27 +171,46 @@
|
||||
}
|
||||
|
||||
async function scanOrphanedAttachments() {
|
||||
const vault = maintenanceVault;
|
||||
if (!vault) return;
|
||||
const request = ++cleanupRequest;
|
||||
const current = () => request === cleanupRequest && $showSettings && maintenanceVault === vault;
|
||||
scanningOrphanedAttachments = true;
|
||||
orphanError = '';
|
||||
try {
|
||||
orphanedAttachments = await findOrphanedAttachments();
|
||||
if (!(await onBeforeVaultSwitch())) throw new Error('Save the current note before scanning attachments.');
|
||||
if (!current()) return;
|
||||
const found = await findOrphanedAttachments(vault);
|
||||
if (!current()) return;
|
||||
orphanedVault = vault;
|
||||
orphanedAttachments = found;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (current()) orphanError = String(error);
|
||||
} finally {
|
||||
scanningOrphanedAttachments = false;
|
||||
if (current()) scanningOrphanedAttachments = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function trashFoundOrphanedAttachments() {
|
||||
if (!orphanedAttachments || orphanedAttachments.length === 0) return;
|
||||
const vault = orphanedVault;
|
||||
if (!vault || vault !== maintenanceVault || !orphanedAttachments?.length) return;
|
||||
const names = orphanedAttachments.map(attachment => attachment.name);
|
||||
const request = ++cleanupRequest;
|
||||
const current = () => request === cleanupRequest && $showSettings && maintenanceVault === vault;
|
||||
trashingOrphanedAttachments = true;
|
||||
orphanError = '';
|
||||
try {
|
||||
await trashOrphanedAttachments(orphanedAttachments.map((attachment) => attachment.name));
|
||||
if (!(await onBeforeVaultSwitch())) throw new Error('Save the current note before cleaning attachments.');
|
||||
if (!current()) return;
|
||||
await trashOrphanedAttachments(vault, names);
|
||||
if (!current()) return;
|
||||
orphanedAttachments = null;
|
||||
orphanedVault = null;
|
||||
void loadVaultStats();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (current()) orphanError = String(error);
|
||||
} finally {
|
||||
trashingOrphanedAttachments = false;
|
||||
if (current()) trashingOrphanedAttachments = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,68 +219,127 @@
|
||||
let backupLoading = $state(false);
|
||||
let backupMessage = $state<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
let restoreConfirm = $state<BackupEntry | null>(null);
|
||||
let backupRequest = 0;
|
||||
let backupReadRequest = 0;
|
||||
let backupUnlisten: (() => void) | null = null;
|
||||
const lastBackupTime = $derived(activeVaultConfig($appConfig)?.last_backup_time ?? null);
|
||||
|
||||
$effect(() => {
|
||||
void maintenanceVault;
|
||||
void $showSettings;
|
||||
backupRequest++;
|
||||
backupReadRequest++;
|
||||
backupUnlisten?.();
|
||||
backupUnlisten = null;
|
||||
backupLoading = false;
|
||||
return () => {
|
||||
backupRequest++;
|
||||
backupReadRequest++;
|
||||
backupUnlisten?.();
|
||||
backupUnlisten = null;
|
||||
};
|
||||
});
|
||||
|
||||
async function loadBackups() {
|
||||
const vault = maintenanceVault;
|
||||
if (!vault) return;
|
||||
const request = ++backupReadRequest;
|
||||
try {
|
||||
backups = await listBackups();
|
||||
const loaded = await listBackups(vault);
|
||||
if (request === backupReadRequest && maintenanceVault === vault && $showSettings) backups = loaded;
|
||||
} catch (e) {
|
||||
console.error('Failed to load backups:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBackupNow() {
|
||||
const vault = maintenanceVault;
|
||||
if (!vault || backupLoading) return;
|
||||
const request = ++backupRequest;
|
||||
const current = () => request === backupRequest && maintenanceVault === vault && $showSettings;
|
||||
backupLoading = true;
|
||||
backupMessage = null;
|
||||
const unlisten = await listen<{ success: boolean; entry?: BackupEntry; error?: string }>('backup-done', async (event) => {
|
||||
const data = event.payload;
|
||||
if (data.success) {
|
||||
backupMessage = { type: 'success', text: 'Backup created successfully' };
|
||||
await loadBackups();
|
||||
if ($appConfig) {
|
||||
$appConfig = { ...$appConfig, last_backup_time: new Date().toISOString() };
|
||||
}
|
||||
} else {
|
||||
backupMessage = { type: 'error', text: `Backup failed: ${data.error}` };
|
||||
}
|
||||
backupLoading = false;
|
||||
unlisten();
|
||||
});
|
||||
let stop: (() => void) | undefined;
|
||||
let finished = false;
|
||||
try {
|
||||
await createBackup();
|
||||
if (!(await onBeforeVaultSwitch())) throw new Error('Save the current note before creating a backup.');
|
||||
if (!current()) return;
|
||||
stop = await listen<{ vault_path: string; success: boolean; entry?: BackupEntry; error?: string }>('backup-done', (event) => {
|
||||
const data = event.payload;
|
||||
if (data.vault_path !== vault || !current()) return;
|
||||
finished = true;
|
||||
stop?.();
|
||||
backupUnlisten = null;
|
||||
backupLoading = false;
|
||||
if (data.success) {
|
||||
backupMessage = { type: 'success', text: 'Backup created successfully' };
|
||||
const timestamp = data.entry?.created;
|
||||
const currentVault = activeVaultConfig($appConfig);
|
||||
if (timestamp && currentVault && $appConfig) {
|
||||
$appConfig = { ...$appConfig, vaults: $appConfig.vaults.map(item =>
|
||||
item === currentVault ? { ...item, last_backup_time: timestamp } : item) };
|
||||
}
|
||||
void loadBackups();
|
||||
} else {
|
||||
backupMessage = { type: 'error', text: `Backup failed: ${data.error}` };
|
||||
}
|
||||
});
|
||||
if (!current() || finished) { stop(); return; }
|
||||
backupUnlisten = stop;
|
||||
await createBackup(vault);
|
||||
} catch (e) {
|
||||
backupMessage = { type: 'error', text: `Backup failed: ${e}` };
|
||||
backupLoading = false;
|
||||
unlisten();
|
||||
stop?.();
|
||||
if (current()) {
|
||||
backupUnlisten = null;
|
||||
backupMessage = { type: 'error', text: `Backup failed: ${e}` };
|
||||
backupLoading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRestore(entry: BackupEntry) {
|
||||
const vault = maintenanceVault;
|
||||
if (!vault || backupLoading) return;
|
||||
const request = ++backupRequest;
|
||||
const current = () => request === backupRequest && maintenanceVault === vault && $showSettings;
|
||||
restoreConfirm = null;
|
||||
backupLoading = true;
|
||||
backupMessage = null;
|
||||
const unlisten = await listen<{ success: boolean; error?: string }>('restore-done', (event) => {
|
||||
const data = event.payload;
|
||||
if (data.success) {
|
||||
backupMessage = { type: 'success', text: 'Backup restored. Restart the app to see changes.' };
|
||||
} else {
|
||||
backupMessage = { type: 'error', text: `Restore failed: ${data.error}` };
|
||||
}
|
||||
backupLoading = false;
|
||||
unlisten();
|
||||
});
|
||||
let stop: (() => void) | undefined;
|
||||
let finished = false;
|
||||
try {
|
||||
await restoreBackup(entry.path);
|
||||
if (!(await onBeforeVaultSwitch())) throw new Error('Save the current note before restoring a backup.');
|
||||
if (!current()) return;
|
||||
stop = await listen<{ vault_path: string; success: boolean; error?: string }>('restore-done', (event) => {
|
||||
const data = event.payload;
|
||||
if (data.vault_path !== vault || !current()) return;
|
||||
finished = true;
|
||||
stop?.();
|
||||
backupUnlisten = null;
|
||||
backupMessage = data.success
|
||||
? { type: 'success', text: 'Backup restored successfully.' }
|
||||
: { type: 'error', text: `Restore failed: ${data.error}` };
|
||||
backupLoading = false;
|
||||
});
|
||||
if (!current() || finished) { stop(); return; }
|
||||
backupUnlisten = stop;
|
||||
await restoreBackup(vault, entry.path);
|
||||
} catch (e) {
|
||||
backupMessage = { type: 'error', text: `Restore failed: ${e}` };
|
||||
backupLoading = false;
|
||||
unlisten();
|
||||
stop?.();
|
||||
if (current()) {
|
||||
backupUnlisten = null;
|
||||
backupMessage = { type: 'error', text: `Restore failed: ${e}` };
|
||||
backupLoading = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteBackup(entry: BackupEntry) {
|
||||
const vault = maintenanceVault;
|
||||
if (!vault) return;
|
||||
try {
|
||||
await deleteBackup(entry.path);
|
||||
backups = backups.filter(b => b.path !== entry.path);
|
||||
await deleteBackup(vault, entry.path);
|
||||
if (maintenanceVault === vault) backups = backups.filter(b => b.path !== entry.path);
|
||||
} catch (e) {
|
||||
console.error('Failed to delete backup:', e);
|
||||
}
|
||||
@@ -293,7 +388,7 @@
|
||||
let _ollamaApiKey = $state($appConfig?.ollama_api_key ?? '');
|
||||
let _openaiCompatibleBaseUrl = $state($appConfig?.openai_compatible_base_url ?? '');
|
||||
let _openaiCompatibleKey = $state($appConfig?.openai_compatible_api_key ?? '');
|
||||
let aiModel = $state($appConfig?.ai_model ?? 'claude-sonnet-4-6');
|
||||
let aiModel = $state($appConfig?.ai_model ?? 'claude-sonnet-5');
|
||||
let aiWritingStyle = $state($appConfig?.ai_writing_style ?? '');
|
||||
let aiShowKey = $state(false);
|
||||
let aiShowCompatibleKey = $state(false);
|
||||
@@ -301,16 +396,17 @@
|
||||
let aiTestLoading = $state(false);
|
||||
let aiTestMessage = $state<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
|
||||
// General-purpose text models verified against provider catalogs on 2026-09-27.
|
||||
const anthropicModels = [
|
||||
{ value: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', desc: 'Balanced' },
|
||||
{ value: 'claude-opus-4-8', label: 'Claude Opus 4.8', desc: 'Most capable' },
|
||||
{ value: 'claude-sonnet-5', label: 'Claude Sonnet 5', desc: 'Balanced' },
|
||||
{ value: 'claude-opus-5-5', label: 'Claude Opus 5.5', desc: 'Complex work' },
|
||||
{ value: 'claude-fable-5-1', label: 'Claude Fable 5.1', desc: 'Deep reasoning' },
|
||||
{ value: 'claude-haiku-4-5-20251001', label: 'Claude Haiku 4.5', desc: 'Fast' },
|
||||
];
|
||||
const openaiModels = [
|
||||
{ value: 'gpt-5.5', label: 'GPT-5.5', desc: 'Most capable' },
|
||||
{ value: 'gpt-5.4', label: 'GPT-5.4', desc: 'Balanced' },
|
||||
{ value: 'gpt-5-mini', label: 'GPT-5 Mini', desc: 'Fast' },
|
||||
{ value: 'gpt-5.2', label: 'GPT-5.2', desc: 'Previous gen' },
|
||||
{ value: 'gpt-6-sol', label: 'GPT-6 Sol', desc: 'Balanced' },
|
||||
{ value: 'gpt-6-astra', label: 'GPT-6 Astra', desc: 'Deep reasoning' },
|
||||
{ value: 'gpt-6-luna', label: 'GPT-6 Luna', desc: 'Fast' },
|
||||
];
|
||||
let aiModels = $derived(aiProvider === 'openai' ? openaiModels : anthropicModels);
|
||||
|
||||
@@ -372,11 +468,15 @@
|
||||
let syncShowPassword = $state(false);
|
||||
let syncTestLoading = $state(false);
|
||||
let syncTestMessage = $state<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
let syncRunning = $state(false);
|
||||
let syncStarting = $state(false);
|
||||
const syncRunning = $derived(syncStarting || $syncState.running);
|
||||
let syncMessage = $state<{ type: 'success' | 'error'; text: string } | null>(null);
|
||||
let syncOnOpen = $state(activeVaultConfig($appConfig)?.sync_on_open ?? false);
|
||||
let syncOnChange = $state(activeVaultConfig($appConfig)?.sync_on_change ?? false);
|
||||
let syncIntervalMinutes = $state(activeVaultConfig($appConfig)?.sync_interval_minutes ?? 0);
|
||||
// 0 means never chosen, which the sync treats as DEFAULT_LISTING_PARALLELISM (6) in sync.rs.
|
||||
const defaultFolderRequests = 6;
|
||||
let syncFolderRequests = $state(activeVaultConfig($appConfig)?.sync_folder_requests ?? 0);
|
||||
|
||||
// Re-seed the sync form when the active vault changes, so Settings reflects the current vault.
|
||||
let lastSyncVault: string | null = null;
|
||||
@@ -396,10 +496,11 @@
|
||||
syncOnOpen = vc?.sync_on_open ?? false;
|
||||
syncOnChange = vc?.sync_on_change ?? false;
|
||||
syncIntervalMinutes = vc?.sync_interval_minutes ?? 0;
|
||||
syncFolderRequests = vc?.sync_folder_requests ?? 0;
|
||||
});
|
||||
|
||||
async function saveSyncSettings() {
|
||||
await setSyncSettings(syncProvider, syncUrl || null, syncUsername || null, syncPassword || null, syncOnOpen, syncOnChange, syncIntervalMinutes);
|
||||
await setSyncSettings(syncProvider, syncUrl || null, syncUsername || null, syncPassword || null, syncOnOpen, syncOnChange, syncIntervalMinutes, syncFolderRequests);
|
||||
// Reflect into the active vault's config in the store so the top-bar button and auto-sync
|
||||
// triggers update live, without an app restart.
|
||||
if ($appConfig) {
|
||||
@@ -416,6 +517,7 @@
|
||||
sync_on_open: syncOnOpen,
|
||||
sync_on_change: syncOnChange,
|
||||
sync_interval_minutes: syncIntervalMinutes,
|
||||
sync_folder_requests: syncFolderRequests,
|
||||
} : vault),
|
||||
};
|
||||
}
|
||||
@@ -442,40 +544,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSyncNow() {
|
||||
syncRunning = true;
|
||||
syncMessage = null;
|
||||
const unlisteners: Array<() => void> = [];
|
||||
const cleanup = () => { unlisteners.forEach((u) => u()); };
|
||||
unlisteners.push(await listen<{ success: boolean; summary?: { uploaded?: number; downloaded?: number; deleted_local?: number; deleted_remote?: number; conflicts?: number }; last_sync_time?: string }>('sync-done', async (event) => {
|
||||
const s = event.payload.summary ?? {};
|
||||
const parts: string[] = [];
|
||||
if (s.uploaded) parts.push(`${s.uploaded} uploaded`);
|
||||
if (s.downloaded) parts.push(`${s.downloaded} downloaded`);
|
||||
const deleted = (s.deleted_local ?? 0) + (s.deleted_remote ?? 0);
|
||||
if (deleted) parts.push(`${deleted} deleted`);
|
||||
if (s.conflicts) parts.push(`${s.conflicts} conflict copies`);
|
||||
syncMessage = { type: 'success', text: parts.length ? `Synced: ${parts.join(', ')}.` : 'Already up to date.' };
|
||||
syncRunning = false;
|
||||
if (event.payload.last_sync_time) {
|
||||
try {
|
||||
$appConfig = await getAppConfig();
|
||||
} catch {}
|
||||
// The outcome of the last sync, whether it was started here, from the title bar or automatically.
|
||||
$effect(() => {
|
||||
const state = $syncState;
|
||||
const vault = maintenanceVault;
|
||||
untrack(() => {
|
||||
if (state.running) syncMessage = null;
|
||||
else if (state.error) syncMessage = { type: 'error', text: state.error };
|
||||
else if (state.result && state.result.vault === vault) {
|
||||
const s = state.result.summary;
|
||||
const parts: string[] = [];
|
||||
if (s.uploaded) parts.push(`${s.uploaded} uploaded`);
|
||||
if (s.downloaded) parts.push(`${s.downloaded} downloaded`);
|
||||
const deleted = (s.deleted_local ?? 0) + (s.deleted_remote ?? 0);
|
||||
if (deleted) parts.push(`${deleted} deleted`);
|
||||
if (s.conflicts) parts.push(`${s.conflicts} conflict ${s.conflicts === 1 ? 'copy' : 'copies'}`);
|
||||
syncMessage = { type: 'success', text: parts.length ? `Synced: ${parts.join(', ')}.` : 'Already up to date.' };
|
||||
}
|
||||
cleanup();
|
||||
}));
|
||||
unlisteners.push(await listen<{ error?: string }>('sync-error', (event) => {
|
||||
syncMessage = { type: 'error', text: event.payload.error ?? 'Sync failed' };
|
||||
syncRunning = false;
|
||||
cleanup();
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
async function handleSyncNow() {
|
||||
if (!maintenanceVault || syncRunning) return;
|
||||
syncStarting = true;
|
||||
syncMessage = null;
|
||||
try {
|
||||
await saveSyncSettings();
|
||||
await syncNow();
|
||||
} catch (e) {
|
||||
syncMessage = { type: 'error', text: String(e) };
|
||||
syncRunning = false;
|
||||
cleanup();
|
||||
} finally {
|
||||
syncStarting = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,8 +618,29 @@
|
||||
{ id: 'cyberpunk', label: 'Cyberpunk', bg: '#0a0e17', sidebar: '#060911', accent: '#ff0080' },
|
||||
{ id: 'black', label: 'Black', bg: '#000000', sidebar: '#0a0a0a', accent: '#ffffff' },
|
||||
{ id: 'one-dark', label: 'One Dark', bg: '#282c34', sidebar: '#21252b', accent: '#61afef' },
|
||||
{ id: 'matrix', label: 'Matrix', bg: '#0a0f0a', sidebar: '#060a06', accent: '#00ff66' },
|
||||
{ id: 'amber-crt', label: 'Amber CRT', bg: '#180f00', sidebar: '#120b00', accent: '#ffb000' },
|
||||
{ id: 'sepia', label: 'Sepia', bg: '#f4ecd8', sidebar: '#ebe0c7', accent: '#9a6a3a' },
|
||||
{ id: 'deep-ocean', label: 'Deep Ocean', bg: '#081821', sidebar: '#05121a', accent: '#35c4d4' },
|
||||
{ id: 'sandstone', label: 'Sandstone', bg: '#faf3e8', sidebar: '#f1e6d3', accent: '#c76b3f' },
|
||||
{ id: 'lavender', label: 'Lavender', bg: '#f6f3fc', sidebar: '#ece6f7', accent: '#7c5cc4' },
|
||||
{ id: 'graphite', label: 'Graphite', bg: '#17181a', sidebar: '#121315', accent: '#7f9cb3' },
|
||||
{ id: 'nebula', label: 'Nebula', bg: '#14102a', sidebar: '#0f0c21', accent: '#b388ff' },
|
||||
{ id: 'wine', label: 'Wine', bg: '#1c0f14', sidebar: '#160b10', accent: '#d98ca0' },
|
||||
{ id: 'jade', label: 'Jade', bg: '#0b1a15', sidebar: '#071410', accent: '#2bbd8e' },
|
||||
];
|
||||
|
||||
// Keep the default themes pinned at the top and sort the rest alphabetically.
|
||||
const priorityThemeIds = ['system', 'light', 'dark'];
|
||||
themePresets.sort((a, b) => {
|
||||
const pa = priorityThemeIds.indexOf(a.id);
|
||||
const pb = priorityThemeIds.indexOf(b.id);
|
||||
if (pa !== -1 && pb !== -1) return pa - pb;
|
||||
if (pa !== -1) return -1;
|
||||
if (pb !== -1) return 1;
|
||||
return a.label.localeCompare(b.label);
|
||||
});
|
||||
|
||||
const accentPresets = [
|
||||
{ name: 'Indigo', light: '#5b6abf', dark: '#7b9bd4' },
|
||||
{ name: 'Rose', light: '#e11d48', dark: '#d4768a' },
|
||||
@@ -554,25 +674,18 @@
|
||||
{ name: 'Open Sans', value: 'opensans', stack: '"Open Sans", -apple-system, sans-serif' },
|
||||
{ name: 'Literata', value: 'literata', stack: '"Literata", Georgia, serif' },
|
||||
{ name: 'Mono', value: 'mono', stack: '"JetBrains Mono", "Fira Code", "Cascadia Code", monospace' },
|
||||
{ name: 'Ubuntu', value: 'ubuntu', stack: '"Ubuntu", -apple-system, sans-serif' },
|
||||
{ name: 'Ubuntu Mono', value: 'ubuntu-mono', stack: '"Ubuntu Mono", monospace' },
|
||||
];
|
||||
|
||||
const lineHeightPresets = [
|
||||
{ label: 'Single', value: 1.0 },
|
||||
{ label: 'Tight', value: 1.4 },
|
||||
{ label: 'Default', value: 1.6 },
|
||||
{ label: 'Relaxed', value: 1.8 },
|
||||
{ label: 'Loose', value: 2.0 },
|
||||
];
|
||||
|
||||
const uiScalePresets = [
|
||||
{ label: '80%', value: 0.8 },
|
||||
{ label: '90%', value: 0.9 },
|
||||
{ label: '100%', value: 1 },
|
||||
{ label: '125%', value: 1.25 },
|
||||
{ label: '150%', value: 1.5 },
|
||||
{ label: '175%', value: 1.75 },
|
||||
{ label: '200%', value: 2 },
|
||||
];
|
||||
|
||||
const contentWidthPresets: { label: string; value: number | null }[] = [
|
||||
{ label: 'Narrow', value: 600 },
|
||||
{ label: 'Medium', value: 760 },
|
||||
@@ -586,7 +699,7 @@
|
||||
let scrollToChangeFontSize = $state($appConfig?.scroll_to_change_font_size ?? true);
|
||||
let activeFontFamily = $state($appConfig?.font_family ?? 'system');
|
||||
let activeLineHeight = $state($appConfig?.line_height ?? 1.6);
|
||||
let activeUiScale = $state($appConfig?.ui_scale ?? 1);
|
||||
let activeUiScale = $state($appConfig?.ui_scale ?? defaultUiScale);
|
||||
let activeContentWidth = $state<number | null>($appConfig?.content_width ?? null);
|
||||
let themeDropdownOpen = $state(false);
|
||||
let accentDropdownOpen = $state(false);
|
||||
@@ -698,7 +811,7 @@
|
||||
root.classList.remove('dark');
|
||||
root.removeAttribute('data-theme');
|
||||
for (const v of varsToClear) root.style.removeProperty(v);
|
||||
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','matrix','amber-crt','sepia','deep-ocean','sandstone','lavender','graphite','nebula','wine','jade'];
|
||||
if ($resolvedTheme.startsWith('custom-')) {
|
||||
const ct = $customThemes.find(c => c.id === $resolvedTheme);
|
||||
if (ct) {
|
||||
@@ -984,8 +1097,11 @@
|
||||
function selectFontSize(size: number) {
|
||||
activeFontSize = size;
|
||||
applyFontSize(size);
|
||||
if ($appConfig) $appConfig.font_size = size;
|
||||
setFontSize(size).catch((e) => console.error('Failed to save font size:', e));
|
||||
if ($appConfig) {
|
||||
$appConfig.font_size = size;
|
||||
$appConfig.preferred_font_size = size;
|
||||
}
|
||||
setFontSize(size, true).catch((e) => console.error('Failed to save font size:', e));
|
||||
}
|
||||
|
||||
function toggleScrollToChangeFontSize() {
|
||||
@@ -1028,14 +1144,6 @@
|
||||
setUiScale(value).catch((e) => console.error('Failed to save interface scale:', e));
|
||||
}
|
||||
|
||||
async function applyUiScale(value: number) {
|
||||
try {
|
||||
await getCurrentWebview().setZoom(value);
|
||||
} catch (e) {
|
||||
console.error('Failed to apply interface scale:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function selectContentWidth(value: number | null) {
|
||||
activeContentWidth = value;
|
||||
applyContentWidth(value);
|
||||
@@ -1068,6 +1176,15 @@
|
||||
if (event.target === event.currentTarget) close();
|
||||
}
|
||||
|
||||
function handleEscape(event: KeyboardEvent) {
|
||||
if (event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (restoreConfirm) restoreConfirm = null;
|
||||
else if (customThemeEditorOpen) cancelCustomThemeEditor();
|
||||
else close();
|
||||
}
|
||||
|
||||
function dismissRestoreConfirm(event: MouseEvent) {
|
||||
if (event.target === event.currentTarget) restoreConfirm = null;
|
||||
}
|
||||
@@ -1148,7 +1265,7 @@
|
||||
|
||||
{#if $showSettings}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="settings-overlay" class:mobile={isMobile} onclick={closeSettingsFromOverlay} onkeydown={(e) => { if (e.key === 'Escape') close(); }}>
|
||||
<div class="settings-overlay" class:mobile={isMobile} onclick={closeSettingsFromOverlay} onkeydowncapture={handleEscape} onkeydown={handleEscape}>
|
||||
<div class="settings-panel" class:mobile={isMobile} role="dialog" aria-modal="true" aria-labelledby="settings-title" tabindex="-1">
|
||||
<div class="settings-header">
|
||||
<h2 id="settings-title">Settings</h2>
|
||||
@@ -1370,11 +1487,13 @@
|
||||
<div class="settings-section">
|
||||
<h3>Vault</h3>
|
||||
<p class="setting-desc" style="margin-bottom: 12px; color: var(--text-tertiary); font-size: 13px;">Current: <strong style="color: var(--text-primary);">{$appConfig?.active_vault?.split('/').pop() ?? 'Unknown'}</strong></p>
|
||||
<button class="import-btn" onclick={() => { $showSettings = false; $vaultReady = false; }}>
|
||||
<button class="import-btn" onclick={async () => { if (!(await onBeforeVaultSwitch())) return; $showSettings = false; $vaultReady = false; }}>
|
||||
<svg width="16" height="16" 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"/>
|
||||
<rect x="3" y="3" width="18" height="16" rx="2"/>
|
||||
<circle cx="12" cy="11" r="3.5"/>
|
||||
<path d="M12 7.5V6M12 16v-1.5M7 19v2M17 19v2"/>
|
||||
</svg>
|
||||
Switch Vault
|
||||
Manage Vaults
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1418,7 +1537,7 @@
|
||||
<label class="setting-toggle">
|
||||
<span class="setting-label">
|
||||
<span class="setting-name">Close to tray</span>
|
||||
<span class="setting-desc">Minimize to tray instead of quitting when closing the window (requires restart)</span>
|
||||
<span class="setting-desc">Minimize to tray instead of quitting when closing the window</span>
|
||||
</span>
|
||||
<button class="toggle-switch" class:on={closeToTray} role="switch" aria-checked={closeToTray} aria-label="Close to tray" onclick={() => { closeToTray = !closeToTray; saveGeneralSettings(); }}>
|
||||
<span class="toggle-knob"></span>
|
||||
@@ -1465,7 +1584,8 @@
|
||||
<div class="settings-section">
|
||||
<h3>Orphaned Attachments</h3>
|
||||
<div class="vault-maintenance">
|
||||
<p class="setting-desc">Find files in the vault's attachments folder that are not referenced by any note.</p>
|
||||
<p class="setting-desc">Review attachment files not referenced by saved notes or icon settings. Save changes in other note windows before scanning.</p>
|
||||
{#if orphanError}<p class="cleanup-message" role="alert">{orphanError}</p>{/if}
|
||||
{#if orphanedAttachments === null}
|
||||
<button class="import-btn cleanup-action" onclick={scanOrphanedAttachments} disabled={scanningOrphanedAttachments}>
|
||||
{#if scanningOrphanedAttachments}
|
||||
@@ -1813,7 +1933,7 @@
|
||||
<!-- Custom Theme Editor Modal -->
|
||||
{#if customThemeEditorOpen && customThemeEditing}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="custom-theme-modal-overlay" onclick={cancelCustomThemeFromOverlay} onkeydown={(e) => e.key === 'Escape' && cancelCustomThemeEditor()}>
|
||||
<div class="custom-theme-modal-overlay" onclick={cancelCustomThemeFromOverlay} onkeydown={handleEscape}>
|
||||
<div class="custom-theme-modal" role="dialog" aria-modal="true" aria-labelledby="custom-theme-title" tabindex="-1">
|
||||
<div class="custom-theme-modal-header">
|
||||
<h3 id="custom-theme-title">{customThemeEditing.id.startsWith('custom-') && $customThemes.some(c => c.id === customThemeEditing!.id) ? 'Edit Theme' : 'New Custom Theme'}</h3>
|
||||
@@ -1932,7 +2052,7 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !isMobile}
|
||||
{#if !isMobile || isAndroid}
|
||||
<div class="settings-section">
|
||||
<h3>Interface Scale</h3>
|
||||
<div class="font-size-options">
|
||||
@@ -1946,7 +2066,7 @@
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p class="setting-hint">Zooms the whole app: every panel, menu, and the editor. Use Default (100%) to reset.</p>
|
||||
<p class="setting-hint">Zooms the whole app: every panel, menu, and the editor. Use Default ({Math.round(defaultUiScale * 100)}%) to reset.</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1969,7 +2089,7 @@
|
||||
{/if}
|
||||
|
||||
<div class="settings-section">
|
||||
<h3>Line Height</h3>
|
||||
<h3>Line Spacing</h3>
|
||||
<div class="font-size-options">
|
||||
{#each lineHeightPresets as preset}
|
||||
<button
|
||||
@@ -1982,6 +2102,7 @@
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p class="setting-hint">Sets the spacing in the editor. Text copied to Word or email is pasted with single spacing.</p>
|
||||
</div>
|
||||
|
||||
<div class="settings-section">
|
||||
@@ -2068,8 +2189,8 @@
|
||||
</div>
|
||||
|
||||
<p class="backup-last-time">
|
||||
{#if $appConfig?.last_backup_time}
|
||||
Last backup: {formatBackupDate($appConfig.last_backup_time)}
|
||||
{#if lastBackupTime}
|
||||
Last backup: {formatBackupDate(lastBackupTime)}
|
||||
{:else}
|
||||
No backups yet
|
||||
{/if}
|
||||
@@ -2098,6 +2219,9 @@
|
||||
<div class="backup-info">
|
||||
<span class="backup-date">{formatBackupDate(entry.created)}</span>
|
||||
<span class="backup-size">{formatBackupSize(entry.size)}</span>
|
||||
{#if entry.other_vault}
|
||||
<span class="backup-size" title="This backup was made from a different vault folder">other vault</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="backup-item-actions">
|
||||
<button class="backup-action-btn" title="Restore" onclick={() => restoreConfirm = entry}>
|
||||
@@ -2121,10 +2245,13 @@
|
||||
|
||||
{#if restoreConfirm}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="restore-confirm-overlay" onclick={dismissRestoreConfirm} onkeydown={(e) => { if (e.key === 'Escape') restoreConfirm = null; }}>
|
||||
<div class="restore-confirm-overlay" onclick={dismissRestoreConfirm} onkeydown={handleEscape}>
|
||||
<div class="restore-confirm" role="alertdialog" aria-modal="true" aria-labelledby="restore-confirm-title" tabindex="-1">
|
||||
<h4 id="restore-confirm-title">Restore Backup?</h4>
|
||||
<p>This will replace all notes in your vault with the backup from <strong>{formatBackupDate(restoreConfirm.created)}</strong>. This action cannot be undone.</p>
|
||||
{#if restoreConfirm.other_vault}
|
||||
<p><strong>This backup was made from a different vault folder.</strong> Restoring it replaces this vault's notes with that vault's. Continue only if this vault was moved or renamed since then.</p>
|
||||
{/if}
|
||||
<div class="restore-confirm-actions">
|
||||
<button class="restore-cancel" onclick={() => restoreConfirm = null}>Cancel</button>
|
||||
<button class="restore-confirm-btn" onclick={() => handleRestore(restoreConfirm!)}>Restore</button>
|
||||
@@ -2188,8 +2315,8 @@
|
||||
<div class="setting-options" style="flex-wrap: wrap;">
|
||||
<button class="option-btn" class:active={!aiProvider} onclick={() => { if (!aiProvider) return; aiProvider = null; aiTestMessage = null; saveAiSettings(); }}>Disabled</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'ollama'} onclick={() => { if (aiProvider === 'ollama') return; aiProvider = 'ollama'; aiModel = 'gemma3:4b'; aiTestMessage = null; saveAiSettings(); }}>Ollama</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'anthropic'} onclick={() => { if (aiProvider === 'anthropic') return; aiProvider = 'anthropic'; aiModel = 'claude-sonnet-4-6'; aiTestMessage = null; saveAiSettings(); }}>Anthropic</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'openai'} onclick={() => { if (aiProvider === 'openai') return; aiProvider = 'openai'; aiModel = 'gpt-5.5'; aiTestMessage = null; saveAiSettings(); }}>OpenAI</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'anthropic'} onclick={() => { if (aiProvider === 'anthropic') return; aiProvider = 'anthropic'; aiModel = 'claude-sonnet-5'; aiTestMessage = null; saveAiSettings(); }}>Anthropic</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'openai'} onclick={() => { if (aiProvider === 'openai') return; aiProvider = 'openai'; aiModel = 'gpt-6-sol'; aiTestMessage = null; saveAiSettings(); }}>OpenAI</button>
|
||||
<button class="option-btn" class:active={aiProvider === 'openai_compatible'} onclick={() => { if (aiProvider === 'openai_compatible') return; aiProvider = 'openai_compatible'; aiModel = ''; aiTestMessage = null; saveAiSettings(); }}>OpenAI Compatible</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2320,6 +2447,9 @@
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if aiModel && !aiModels.some(model => model.value === aiModel)}
|
||||
<p class="setting-hint">Saved model: <code>{aiModel}</code>. It remains selected until you choose another model.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -2482,6 +2612,15 @@
|
||||
<button class="toggle-switch" class:on={syncOnOpen} role="switch" aria-checked={syncOnOpen} aria-label="Sync when the vault opens" onclick={() => { syncOnOpen = !syncOnOpen; saveSyncSettings(); }}><span class="toggle-knob"></span></button>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-section">
|
||||
<h3>Folder Request Parallelism</h3>
|
||||
<div class="setting-options">
|
||||
{#each [...new Set([1, 3, 6, 12, syncFolderRequests || defaultFolderRequests])].sort((a, b) => a - b) as opt}
|
||||
<button class="option-btn" class:active={(syncFolderRequests || defaultFolderRequests) === opt} onclick={() => { syncFolderRequests = opt; saveSyncSettings(); }}>{opt}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p class="setting-hint">How many folders are listed on the server at once. 6 suits most servers; choose 1 if yours rejects concurrent requests.</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -2565,7 +2704,7 @@
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>
|
||||
</svg>
|
||||
Download from Codeberg
|
||||
Download
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -3731,7 +3870,13 @@
|
||||
transform: translateX(18px);
|
||||
}
|
||||
|
||||
.settings-panel.mobile .setting-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(120px, 100%), 1fr));
|
||||
}
|
||||
|
||||
.settings-panel.mobile .option-btn {
|
||||
min-width: 0;
|
||||
padding: 12px 10px;
|
||||
font-size: 14px;
|
||||
}
|
||||
@@ -3741,7 +3886,10 @@
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.settings-panel.mobile .font-family-options,
|
||||
.settings-panel.mobile .font-size-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(85px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
@@ -3749,6 +3897,12 @@
|
||||
padding: 12px 6px;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.settings-panel.mobile .two-col-sections {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Custom Themes ── */
|
||||
.section-header-row {
|
||||
display: flex;
|
||||
|
||||
+439
-169
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import { onDestroy, tick } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import {
|
||||
notebooks,
|
||||
notes,
|
||||
@@ -7,6 +8,7 @@
|
||||
viewMode,
|
||||
activeNotebook,
|
||||
activeNotePath,
|
||||
editorDirty,
|
||||
activeNote,
|
||||
activeTag,
|
||||
showSearch,
|
||||
@@ -14,34 +16,59 @@
|
||||
showSettings,
|
||||
showInfo,
|
||||
notebookIcons,
|
||||
tagStyles,
|
||||
appConfig,
|
||||
quickAccessPaths,
|
||||
collapsedNotebooks,
|
||||
rootNoteCount,
|
||||
notebookSortMode,
|
||||
notebookOrder
|
||||
notebookOrder,
|
||||
noteOrder
|
||||
} from '$lib/stores/app';
|
||||
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, moveNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, countRootNotes } from '$lib/api';
|
||||
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, moveNotebook, getNotebookIcons, setNotebookIcon, getTagStyles, importNotebookIcon, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, countRootNotes } from '$lib/api';
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog';
|
||||
import { readFile } from '@tauri-apps/plugin-fs';
|
||||
import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
import type { NotebookEntry } from '$lib/types';
|
||||
import { isMobile } from '$lib/platform';
|
||||
import { decodeNoteDragPaths } from '$lib/utils/note-drag';
|
||||
import { notebookAppearance, tagAppearance } from '$lib/utils/appearance-mutations';
|
||||
import NotebookGlyph from './NotebookGlyph.svelte';
|
||||
import TagLabel from './TagLabel.svelte';
|
||||
import TagStylePicker from './TagStylePicker.svelte';
|
||||
import {
|
||||
NOTEBOOK_ICON_OPTIONS,
|
||||
decodeBuiltinNotebookIcon,
|
||||
COMMON_NOTEBOOK_ICON_COUNT,
|
||||
isCommonNotebookIcon,
|
||||
decodeNotebookIcon,
|
||||
encodeBuiltinNotebookIcon,
|
||||
normalizeNotebookIconKey,
|
||||
type NotebookIconId
|
||||
} from '$lib/utils/notebook-icons';
|
||||
import { TAG_COLOR_PRESETS } from '$lib/utils/tag-styles';
|
||||
|
||||
let { onViewChanged = () => {} }: {
|
||||
let { onViewChanged = () => {}, onBeforeNoteChange = async () => true, onBeforePathMutation = async () => null, onPathsMoved = async (_old: string, _next: string) => {} }: {
|
||||
onViewChanged?: () => void;
|
||||
onBeforeNoteChange?: () => Promise<boolean>;
|
||||
onBeforePathMutation?: () => Promise<(() => void) | null>;
|
||||
onPathsMoved?: (oldPath: string, nextPath: string) => Promise<void>;
|
||||
} = $props();
|
||||
|
||||
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
|
||||
const ownerVault = get(appConfig)?.active_vault ?? null;
|
||||
let disposed = false;
|
||||
let refreshRequest = 0;
|
||||
let tagRefreshRequest = 0;
|
||||
|
||||
function ownerIsCurrent() {
|
||||
return !disposed && (get(appConfig)?.active_vault ?? null) === ownerVault;
|
||||
}
|
||||
|
||||
onDestroy(() => {
|
||||
disposed = true;
|
||||
refreshRequest++;
|
||||
nbStopDragListeners();
|
||||
});
|
||||
|
||||
// Whether any top nav item (All Notes, Quick Access, Tasks, Daily Notes, Trash) is visible.
|
||||
// When all are hidden we drop the empty <nav> and its divider so the tree sits flush.
|
||||
@@ -58,6 +85,7 @@
|
||||
let renameInput: HTMLInputElement | null = $state(null);
|
||||
let newNotebookName = $state('');
|
||||
let showNewNotebook = $state(false);
|
||||
let iconError = $state('');
|
||||
let newNotebookInput: HTMLInputElement | null = $state(null);
|
||||
let dropTargetPath = $state<string | null>(null);
|
||||
let dropPosition = $state<'above' | 'into' | 'below' | null>(null);
|
||||
@@ -72,6 +100,26 @@
|
||||
const joinPath = (parent: string, name: string) => parent + (parent.includes('\\') ? '\\' : '/') + name;
|
||||
const isDescendant = (child: string, anc: string) => child.startsWith(anc + '/') || child.startsWith(anc + '\\');
|
||||
|
||||
function migratePaths(oldPath: string, newPath: string) {
|
||||
const replace = (path: string) => path === oldPath ? newPath
|
||||
: isDescendant(path, oldPath) ? newPath + path.slice(oldPath.length) : path;
|
||||
$collapsedNotebooks = $collapsedNotebooks.map(replace);
|
||||
$notebookOrder = Object.fromEntries(Object.entries($notebookOrder).map(([path, index]) => [replace(path), index]));
|
||||
$noteOrder = Object.fromEntries(Object.entries($noteOrder).map(([path, index]) => [replace(path), index]));
|
||||
if ($activeNotebook && replace($activeNotebook.path) !== $activeNotebook.path) {
|
||||
const path = replace($activeNotebook.path);
|
||||
$activeNotebook = {
|
||||
...$activeNotebook, path,
|
||||
relative_path: path.slice(ownerVault!.length + 1).replace(/\\/g, '/'),
|
||||
name: baseOf(path)
|
||||
};
|
||||
}
|
||||
$notes = $notes.map(note => {
|
||||
const path = replace(note.path);
|
||||
return path === note.path ? note : { ...note, path, relative_path: path.slice(ownerVault!.length + 1).replace(/\\/g, '/') };
|
||||
});
|
||||
}
|
||||
|
||||
// Apply manual ordering recursively when in 'manual' sort mode.
|
||||
// In 'alphabetical' mode the Rust scanner already sorts, so we pass through unchanged.
|
||||
function sortNotebooksTree(tree: NotebookEntry[]): NotebookEntry[] {
|
||||
@@ -89,8 +137,17 @@
|
||||
let contextMenu = $state<{ x: number; y: number; notebook: NotebookEntry } | null>(null);
|
||||
let iconPickerNotebook = $state<NotebookEntry | null>(null);
|
||||
let iconPickerElement = $state<HTMLDivElement | null>(null);
|
||||
let iconPickerColor = $state<string | null>(null);
|
||||
let iconPickerShowAll = $state<boolean | null>(null);
|
||||
const iconPickerActive = $derived(iconPickerNotebook
|
||||
? decodeNotebookIcon($notebookIcons[normalizeNotebookIconKey(iconPickerNotebook.relative_path)])?.icon ?? null
|
||||
: null);
|
||||
// Starts open when the current icon is one of the extra icons.
|
||||
const iconPickerExpanded = $derived(iconPickerShowAll ?? !isCommonNotebookIcon(iconPickerActive));
|
||||
let trashContextMenu = $state<{ x: number; y: number } | null>(null);
|
||||
let tagsCollapsed = $state(true);
|
||||
let tagContextMenu = $state<{ x: number; y: number; tag: string } | null>(null);
|
||||
let stylePickerTag = $state<string | null>(null);
|
||||
let deleteConfirm = $state<NotebookEntry | null>(null);
|
||||
function toggleCollapse(nb: NotebookEntry, e: Event) {
|
||||
e.stopPropagation();
|
||||
@@ -118,29 +175,46 @@
|
||||
}
|
||||
|
||||
|
||||
export async function refresh() {
|
||||
export async function refreshTags() {
|
||||
if (!ownerIsCurrent()) return;
|
||||
const request = ++tagRefreshRequest;
|
||||
try {
|
||||
if (isMobile) {
|
||||
// On mobile, parallelize and skip getAllTags (derive from $notes instead)
|
||||
const [nbs, icons, qaNotes, rootCount] = await Promise.all([
|
||||
getNotebooks(),
|
||||
getNotebookIcons(),
|
||||
getQuickAccess(),
|
||||
countRootNotes(),
|
||||
]);
|
||||
$notebooks = nbs;
|
||||
$notebookIcons = icons;
|
||||
$quickAccessPaths = qaNotes.map(n => n.relative_path);
|
||||
$rootNoteCount = rootCount;
|
||||
} else {
|
||||
const [nbs, rootCount] = await Promise.all([getNotebooks(), countRootNotes()]);
|
||||
$notebooks = nbs;
|
||||
$rootNoteCount = rootCount;
|
||||
$tags = await getAllTags();
|
||||
$notebookIcons = await getNotebookIcons();
|
||||
const qaNotes = await getQuickAccess();
|
||||
$quickAccessPaths = qaNotes.map(n => n.relative_path);
|
||||
const nextTags = await getAllTags();
|
||||
if (ownerIsCurrent() && request === tagRefreshRequest) $tags = nextTags;
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh tags:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function refresh() {
|
||||
if (!ownerIsCurrent()) return;
|
||||
const request = ++refreshRequest;
|
||||
const tagRequest = isMobile ? tagRefreshRequest : ++tagRefreshRequest;
|
||||
const iconRevision = notebookAppearance.snapshot(ownerVault!);
|
||||
const styleRevision = tagAppearance.snapshot(ownerVault!);
|
||||
try {
|
||||
// Mobile derives tags from notes instead of issuing another full-vault scan.
|
||||
const [nbs, appearances, qaNotes, rootCount, nextTags] = await Promise.all([
|
||||
getNotebooks(),
|
||||
Promise.allSettled([getNotebookIcons(ownerVault!), getTagStyles(ownerVault!)]),
|
||||
getQuickAccess(ownerVault!),
|
||||
countRootNotes(),
|
||||
isMobile ? Promise.resolve(null) : getAllTags(),
|
||||
]);
|
||||
if (!ownerIsCurrent() || request !== refreshRequest) return;
|
||||
$notebooks = nbs;
|
||||
const [icons, styles] = appearances;
|
||||
if (notebookAppearance.acceptsSnapshot(ownerVault!, iconRevision)) {
|
||||
if (icons.status === 'fulfilled') $notebookIcons = icons.value;
|
||||
else iconError = `Could not read notebook icons: ${String(icons.reason)}`;
|
||||
}
|
||||
if (tagAppearance.acceptsSnapshot(ownerVault!, styleRevision)) {
|
||||
if (styles.status === 'fulfilled') $tagStyles = styles.value;
|
||||
else iconError = `Could not read tag appearances: ${String(styles.reason)}`;
|
||||
}
|
||||
$quickAccessPaths = qaNotes.map(n => n.relative_path);
|
||||
$rootNoteCount = rootCount;
|
||||
if (nextTags && tagRequest === tagRefreshRequest) $tags = nextTags;
|
||||
} catch (e) {
|
||||
console.error('Failed to refresh sidebar:', e);
|
||||
}
|
||||
@@ -233,6 +307,7 @@
|
||||
|
||||
async function focusNewNotebookInput() {
|
||||
await tick();
|
||||
if (!ownerIsCurrent()) return;
|
||||
newNotebookInput?.focus();
|
||||
}
|
||||
|
||||
@@ -268,7 +343,8 @@
|
||||
const name = parentRel ? trimmedName : getNotebookNameSegments(trimmedName)?.join('/');
|
||||
if (!name) return;
|
||||
|
||||
await createNotebook(parentRel, name);
|
||||
await createNotebook(ownerVault!, parentRel, name);
|
||||
if (!ownerIsCurrent()) return;
|
||||
newNotebookName = '';
|
||||
showNewNotebook = false;
|
||||
newNotebookParent = null;
|
||||
@@ -312,12 +388,21 @@
|
||||
editingNotebook = null;
|
||||
return;
|
||||
}
|
||||
const release = await onBeforePathMutation();
|
||||
if (!release) return;
|
||||
try {
|
||||
await renameNotebook(nb.path, editValue.trim());
|
||||
if (!ownerIsCurrent()) return;
|
||||
const newPath = await renameNotebook(ownerVault!, nb.path, editValue.trim());
|
||||
if (!ownerIsCurrent()) return;
|
||||
migratePaths(nb.path, newPath);
|
||||
await onPathsMoved(nb.path, newPath);
|
||||
if (!ownerIsCurrent()) return;
|
||||
editingNotebook = null;
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
console.error('Failed to rename:', e);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +427,10 @@
|
||||
async function confirmDelete(nb: NotebookEntry) {
|
||||
deleteConfirm = null;
|
||||
try {
|
||||
await deleteNotebook(nb.path);
|
||||
if (!(await onBeforeNoteChange())) return;
|
||||
if (!ownerIsCurrent()) return;
|
||||
await deleteNotebook(ownerVault!, nb.path);
|
||||
if (!ownerIsCurrent()) return;
|
||||
if ($activeNotebook?.path === nb.path) {
|
||||
selectAllNotes();
|
||||
}
|
||||
@@ -359,28 +447,24 @@
|
||||
const notePaths = [...new Set(decodeNoteDragPaths(payload))]
|
||||
.filter((path) => norm(parentOf(path)) !== norm(nb.path));
|
||||
if (notePaths.length === 0) return;
|
||||
|
||||
const movedPaths = new Map<string, string>();
|
||||
for (const notePath of notePaths) {
|
||||
try {
|
||||
movedPaths.set(notePath, await moveNote(notePath, nb.path));
|
||||
} catch (e) {
|
||||
console.error('Failed to move note:', notePath, e);
|
||||
const release = await onBeforePathMutation();
|
||||
if (!release) return;
|
||||
try {
|
||||
if (!ownerIsCurrent()) return;
|
||||
for (const notePath of notePaths) {
|
||||
try {
|
||||
const newPath = await moveNote(ownerVault!, notePath, nb.path);
|
||||
if (!ownerIsCurrent()) return;
|
||||
migratePaths(notePath, newPath);
|
||||
await onPathsMoved(notePath, newPath);
|
||||
} catch (error) {
|
||||
console.error('Failed to move note:', notePath, error);
|
||||
}
|
||||
}
|
||||
if (ownerIsCurrent()) await refresh();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
if (movedPaths.size === 0) return;
|
||||
|
||||
$notes = $notes.filter((note) => !movedPaths.has(note.path));
|
||||
const activeNewPath = $activeNotePath ? movedPaths.get($activeNotePath) : undefined;
|
||||
if (activeNewPath) {
|
||||
$activeNotePath = activeNewPath;
|
||||
try {
|
||||
$activeNote = await readNote(activeNewPath);
|
||||
} catch (e) {
|
||||
console.error('Failed to reload moved note:', e);
|
||||
}
|
||||
}
|
||||
await refresh();
|
||||
}
|
||||
|
||||
async function handleNotebookDrop(e: DragEvent, destPath: string) {
|
||||
@@ -398,32 +482,23 @@
|
||||
// Don't move if already in that parent
|
||||
const parentDir = parentOf(srcPath);
|
||||
if (parentDir === destPath) return;
|
||||
const release = await onBeforePathMutation();
|
||||
if (!release) return;
|
||||
try {
|
||||
const oldName = baseOf(srcPath);
|
||||
const newBasePath = joinPath(destPath, oldName);
|
||||
await moveNotebook(srcPath, destPath);
|
||||
// Update collapsedNotebooks paths
|
||||
$collapsedNotebooks = $collapsedNotebooks.map(p => {
|
||||
if (p === srcPath) return newBasePath;
|
||||
if (isDescendant(p, srcPath)) return newBasePath + p.slice(srcPath.length);
|
||||
return p;
|
||||
});
|
||||
// Update active notebook/note if inside the moved notebook
|
||||
if ($activeNotebook?.path === srcPath || isDescendant($activeNotebook?.path ?? '', srcPath)) {
|
||||
selectAllNotes();
|
||||
}
|
||||
if ($activeNotePath && isDescendant($activeNotePath, srcPath)) {
|
||||
const newNotePath = newBasePath + $activeNotePath.slice(srcPath.length);
|
||||
$activeNotePath = newNotePath;
|
||||
$activeNote = await readNote(newNotePath);
|
||||
}
|
||||
$notebookIcons = await getNotebookIcons();
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
console.error('Failed to move notebook:', e);
|
||||
if (!ownerIsCurrent()) return;
|
||||
const newPath = await moveNotebook(ownerVault!, srcPath, destPath);
|
||||
if (!ownerIsCurrent()) return;
|
||||
migratePaths(srcPath, newPath);
|
||||
await onPathsMoved(srcPath, newPath);
|
||||
if (ownerIsCurrent()) await refresh();
|
||||
} catch (error) {
|
||||
console.error('Failed to move notebook:', error);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function nbStopDragListeners() {
|
||||
window.removeEventListener('pointermove', nbPointerMove);
|
||||
window.removeEventListener('pointerup', nbDragEnd);
|
||||
@@ -512,38 +587,18 @@
|
||||
const srcParent = parentOf(srcPath);
|
||||
const targetParent = parentOf(targetPath);
|
||||
let actualSrcPath = srcPath;
|
||||
|
||||
const release = srcParent !== targetParent ? await onBeforePathMutation() : () => {};
|
||||
if (!release) return;
|
||||
try {
|
||||
// Step 1: if different parents, move src into target's parent first
|
||||
if (srcParent !== targetParent) {
|
||||
const oldName = baseOf(srcPath);
|
||||
const newPath = joinPath(targetParent, oldName);
|
||||
await moveNotebook(srcPath, targetParent);
|
||||
// Migrate paths in collapsedNotebooks
|
||||
$collapsedNotebooks = $collapsedNotebooks.map(p => {
|
||||
if (p === srcPath) return newPath;
|
||||
if (isDescendant(p, srcPath)) return newPath + p.slice(srcPath.length);
|
||||
return p;
|
||||
});
|
||||
// Migrate paths in notebookOrder
|
||||
const migrated: Record<string, number> = {};
|
||||
for (const [p, v] of Object.entries($notebookOrder)) {
|
||||
if (p === srcPath) migrated[newPath] = v;
|
||||
else if (isDescendant(p, srcPath)) migrated[newPath + p.slice(srcPath.length)] = v;
|
||||
else migrated[p] = v;
|
||||
}
|
||||
$notebookOrder = migrated;
|
||||
// Update active notebook/note
|
||||
if ($activeNotebook?.path === srcPath || isDescendant($activeNotebook?.path ?? '', srcPath)) {
|
||||
selectAllNotes();
|
||||
}
|
||||
if ($activeNotePath && isDescendant($activeNotePath, srcPath)) {
|
||||
const newNotePath = newPath + $activeNotePath.slice(srcPath.length);
|
||||
$activeNotePath = newNotePath;
|
||||
$activeNote = await readNote(newNotePath);
|
||||
}
|
||||
$notebookIcons = await getNotebookIcons();
|
||||
if (!ownerIsCurrent()) return;
|
||||
const newPath = await moveNotebook(ownerVault!, srcPath, targetParent);
|
||||
if (!ownerIsCurrent()) return;
|
||||
migratePaths(srcPath, newPath);
|
||||
await onPathsMoved(srcPath, newPath);
|
||||
await refresh();
|
||||
if (!ownerIsCurrent()) return;
|
||||
actualSrcPath = newPath;
|
||||
}
|
||||
|
||||
@@ -571,6 +626,8 @@
|
||||
if ($notebookSortMode !== 'manual') $notebookSortMode = 'manual';
|
||||
} catch (e) {
|
||||
console.error('Failed to reorder notebook:', e);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -579,60 +636,90 @@
|
||||
editingNotebook = nb.path;
|
||||
editValue = nb.name;
|
||||
await tick();
|
||||
if (!ownerIsCurrent()) return;
|
||||
renameInput?.focus();
|
||||
renameInput?.select();
|
||||
}
|
||||
|
||||
async function openIconPicker(nb: NotebookEntry) {
|
||||
contextMenu = null;
|
||||
iconPickerColor = decodeNotebookIcon(get(notebookIcons)[normalizeNotebookIconKey(nb.relative_path)])?.color ?? null;
|
||||
iconPickerShowAll = null;
|
||||
iconPickerNotebook = nb;
|
||||
await tick();
|
||||
if (!ownerIsCurrent()) return;
|
||||
iconPickerElement?.focus();
|
||||
}
|
||||
|
||||
async function handleBuiltinIcon(nb: NotebookEntry, icon: NotebookIconId) {
|
||||
function publishNotebookIcon(key: string, value: string | null) {
|
||||
if (get(appConfig)?.active_vault !== ownerVault) return;
|
||||
const icons = { ...get(notebookIcons) };
|
||||
if (value === null) delete icons[key];
|
||||
else icons[key] = value;
|
||||
notebookIcons.set(icons);
|
||||
}
|
||||
|
||||
async function handleBuiltinIcon(nb: NotebookEntry, icon: NotebookIconId | null, close = true) {
|
||||
if (!ownerVault || !ownerIsCurrent()) return;
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
const latest = notebookAppearance.choose(ownerVault, key);
|
||||
const value = icon || iconPickerColor ? encodeBuiltinNotebookIcon(icon, iconPickerColor) : null;
|
||||
iconError = '';
|
||||
try {
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
const value = encodeBuiltinNotebookIcon(icon);
|
||||
await setNotebookIcon(key, value);
|
||||
$notebookIcons = { ...$notebookIcons, [key]: value };
|
||||
iconPickerNotebook = null;
|
||||
await notebookAppearance.run(ownerVault, key, latest,
|
||||
() => setNotebookIcon(ownerVault, key, value),
|
||||
() => publishNotebookIcon(key, value));
|
||||
if (close && ownerIsCurrent() && latest()) iconPickerNotebook = null;
|
||||
} catch (e) {
|
||||
console.error('Failed to set notebook icon:', e);
|
||||
if (ownerIsCurrent() && latest()) iconError = String(e);
|
||||
}
|
||||
}
|
||||
|
||||
// A custom image has no color; the choice is kept for the next built-in icon.
|
||||
function handleIconColor(nb: NotebookEntry, color: string | null) {
|
||||
iconPickerColor = color;
|
||||
const stored = get(notebookIcons)[normalizeNotebookIconKey(nb.relative_path)];
|
||||
const current = decodeNotebookIcon(stored);
|
||||
if (current || !stored) void handleBuiltinIcon(nb, current?.icon ?? null, false);
|
||||
}
|
||||
|
||||
async function handleCustomIcon(nb: NotebookEntry) {
|
||||
if (!ownerVault || !ownerIsCurrent()) return;
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
const latest = notebookAppearance.choose(ownerVault, key);
|
||||
iconPickerNotebook = null;
|
||||
iconError = '';
|
||||
try {
|
||||
const selected = await openDialog({
|
||||
multiple: false,
|
||||
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'] }]
|
||||
});
|
||||
if (!selected) return;
|
||||
if (!selected || !ownerIsCurrent() || !latest()) return;
|
||||
const filePath = selected as string;
|
||||
const data = await readFile(filePath);
|
||||
if (!ownerIsCurrent() || !latest()) return;
|
||||
const fileName = baseOf(filePath) || 'icon.png';
|
||||
const iconRelative = await saveAttachment(`notebook-icon-${fileName}`, Array.from(data));
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
await setNotebookIcon(key, iconRelative);
|
||||
$notebookIcons = { ...$notebookIcons, [key]: iconRelative };
|
||||
await notebookAppearance.run(ownerVault, key, latest,
|
||||
() => importNotebookIcon(ownerVault, key, `notebook-icon-${fileName}`, Array.from(data)),
|
||||
(value) => publishNotebookIcon(key, value));
|
||||
} catch (e) {
|
||||
console.error('Failed to set notebook icon:', e);
|
||||
if (ownerIsCurrent() && latest()) iconError = String(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveIcon(nb: NotebookEntry) {
|
||||
if (!ownerVault || !ownerIsCurrent()) return;
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
const latest = notebookAppearance.choose(ownerVault, key);
|
||||
contextMenu = null;
|
||||
iconPickerNotebook = null;
|
||||
iconError = '';
|
||||
try {
|
||||
const key = normalizeNotebookIconKey(nb.relative_path);
|
||||
await setNotebookIcon(key, null);
|
||||
const icons = { ...$notebookIcons };
|
||||
delete icons[key];
|
||||
$notebookIcons = icons;
|
||||
await notebookAppearance.run(ownerVault, key, latest,
|
||||
() => setNotebookIcon(ownerVault, key, null),
|
||||
() => publishNotebookIcon(key, null));
|
||||
} catch (e) {
|
||||
console.error('Failed to remove notebook icon:', e);
|
||||
if (ownerIsCurrent() && latest()) iconError = String(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,6 +757,26 @@
|
||||
contextMenu = null;
|
||||
}
|
||||
|
||||
function onTagContextMenu(e: MouseEvent, tag: string) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const { x, y } = clampMenu(e.clientX, e.clientY, 200, 80);
|
||||
tagContextMenu = { x, y, tag };
|
||||
}
|
||||
|
||||
function openTagMenu(e: Event, tag: string) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
const { x, y } = clampMenu(rect.right - 200, rect.bottom + 4, 200, 80);
|
||||
tagContextMenu = { x, y, tag };
|
||||
}
|
||||
|
||||
function openTagStylePicker(tag: string) {
|
||||
tagContextMenu = null;
|
||||
stylePickerTag = tag;
|
||||
}
|
||||
|
||||
function onTrashContextMenu(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -679,11 +786,16 @@
|
||||
|
||||
async function handleEmptyTrash() {
|
||||
trashContextMenu = null;
|
||||
const previous = $activeNote;
|
||||
const path = $activeNotePath;
|
||||
try {
|
||||
await emptyTrash();
|
||||
await emptyTrash(ownerVault!);
|
||||
if (!ownerIsCurrent()) return;
|
||||
// Clear selection and refresh the list (with cache invalidation)
|
||||
$activeNote = null;
|
||||
$activeNotePath = '';
|
||||
if ($activeNotePath === path && $activeNote === previous) {
|
||||
$activeNote = null;
|
||||
$activeNotePath = '';
|
||||
}
|
||||
onViewChanged();
|
||||
} catch (e) {
|
||||
console.error('Failed to empty trash:', e);
|
||||
@@ -695,12 +807,13 @@
|
||||
function handleWindowClick() {
|
||||
if (contextMenu) contextMenu = null;
|
||||
if (trashContextMenu) trashContextMenu = null;
|
||||
if (tagContextMenu) tagContextMenu = null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onclick={handleWindowClick} onkeydown={(e) => { if (e.key === 'Escape') iconPickerNotebook = null; }} />
|
||||
<svelte:window onclick={handleWindowClick} onkeydown={(e) => { if (e.key === 'Escape') { iconPickerNotebook = null; tagContextMenu = null; } }} />
|
||||
|
||||
<aside class="sidebar" class:collapsed={$sidebarCollapsed} class:mobile={isMobile} class:nav-empty={!anyNavItem}>
|
||||
<aside class="sidebar" class:collapsed={!isMobile && $sidebarCollapsed} class:mobile={isMobile} class:nav-empty={!anyNavItem}>
|
||||
{#if !isMobile}
|
||||
<div class="sidebar-header">
|
||||
<button class="collapse-btn" onclick={() => ($sidebarCollapsed = !$sidebarCollapsed)} title="Toggle sidebar">
|
||||
@@ -721,7 +834,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !$sidebarCollapsed}
|
||||
{#if isMobile || !$sidebarCollapsed}
|
||||
{#if anyNavItem}
|
||||
<nav class="sidebar-nav">
|
||||
{#if $appConfig?.show_all_notes !== false}
|
||||
@@ -857,6 +970,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if iconError}<div class="sidebar-error" role="alert">{iconError}</div>{/if}
|
||||
<div class="notebook-list">
|
||||
{#if $rootNoteCount > 0}
|
||||
<button
|
||||
@@ -866,10 +980,12 @@
|
||||
style="padding-left: 4px"
|
||||
>
|
||||
<span style="width:14px;flex-shrink:0"></span>
|
||||
<span class="notebook-icon-slot">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;opacity:0.6">
|
||||
<path d="M22 12h-6l-2 3h-4l-2-3H2" />
|
||||
<path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z" />
|
||||
</svg>
|
||||
</span>
|
||||
<span class="notebook-name">Unfiled Notes <span class="notebook-count">{$rootNoteCount}</span></span>
|
||||
</button>
|
||||
{/if}
|
||||
@@ -885,16 +1001,8 @@
|
||||
</button>
|
||||
{#if !tagsCollapsed}
|
||||
<div class="tag-list">
|
||||
{#each $tags as [tag, count]}
|
||||
<button
|
||||
class="tag-item"
|
||||
class:active={$viewMode === 'tag' && $activeTag === tag}
|
||||
onclick={() => selectTag(tag)}
|
||||
>
|
||||
<span class="tag-hash">#</span>
|
||||
<span class="tag-name">{tag}</span>
|
||||
<span class="tag-count">{count}</span>
|
||||
</button>
|
||||
{#each $tags as [tag, count] (tag)}
|
||||
{@render tagRow(tag, count)}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -910,16 +1018,8 @@
|
||||
</button>
|
||||
{#if !tagsCollapsed}
|
||||
<div class="tag-list">
|
||||
{#each $tags as [tag, count]}
|
||||
<button
|
||||
class="tag-item"
|
||||
class:active={$viewMode === 'tag' && $activeTag === tag}
|
||||
onclick={() => selectTag(tag)}
|
||||
>
|
||||
<span class="tag-hash">#</span>
|
||||
<span class="tag-name">{tag}</span>
|
||||
<span class="tag-count">{count}</span>
|
||||
</button>
|
||||
{#each $tags as [tag, count] (tag)}
|
||||
{@render tagRow(tag, count)}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -986,10 +1086,11 @@
|
||||
</button>
|
||||
</header>
|
||||
<div class="icon-picker-grid">
|
||||
{#each NOTEBOOK_ICON_OPTIONS as option}
|
||||
{#each iconPickerExpanded ? NOTEBOOK_ICON_OPTIONS : NOTEBOOK_ICON_OPTIONS.slice(0, COMMON_NOTEBOOK_ICON_COUNT) as option (option.id)}
|
||||
<button
|
||||
class="icon-picker-option"
|
||||
class:active={$notebookIcons[normalizeNotebookIconKey(iconPickerNotebook.relative_path)] === encodeBuiltinNotebookIcon(option.id)}
|
||||
class:active={iconPickerActive === option.id}
|
||||
style:color={iconPickerColor}
|
||||
aria-label={option.label}
|
||||
title={option.label}
|
||||
onclick={() => handleBuiltinIcon(iconPickerNotebook!, option.id)}
|
||||
@@ -998,6 +1099,39 @@
|
||||
<span>{option.label}</span>
|
||||
</button>
|
||||
{/each}
|
||||
<button class="icon-picker-more" aria-expanded={iconPickerExpanded} onclick={() => iconPickerShowAll = !iconPickerExpanded}>
|
||||
{iconPickerExpanded ? 'Fewer icons' : 'More icons'}
|
||||
</button>
|
||||
</div>
|
||||
<div class="icon-color-section">
|
||||
<span class="icon-color-label">Color</span>
|
||||
<div class="icon-swatches">
|
||||
<button
|
||||
class="icon-swatch none"
|
||||
class:active={!iconPickerColor}
|
||||
aria-label="Use default color"
|
||||
title="Default color"
|
||||
onclick={() => handleIconColor(iconPickerNotebook!, null)}
|
||||
></button>
|
||||
{#each TAG_COLOR_PRESETS as preset (preset)}
|
||||
<button
|
||||
class="icon-swatch"
|
||||
class:active={iconPickerColor === preset}
|
||||
style:background={preset}
|
||||
aria-label={`Use ${preset}`}
|
||||
title={preset}
|
||||
onclick={() => handleIconColor(iconPickerNotebook!, preset)}
|
||||
></button>
|
||||
{/each}
|
||||
<label class="icon-swatch custom" title="Custom color">
|
||||
<input
|
||||
type="color"
|
||||
value={iconPickerColor?.length === 7 ? iconPickerColor : '#5b6abf'}
|
||||
oninput={(e) => handleIconColor(iconPickerNotebook!, e.currentTarget.value)}
|
||||
aria-label="Custom icon color"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="icon-picker-actions">
|
||||
<button onclick={() => handleCustomIcon(iconPickerNotebook!)}>
|
||||
@@ -1010,12 +1144,29 @@
|
||||
Use default
|
||||
</button>
|
||||
{/if}
|
||||
<p class="icon-picker-recommendation">Recommended size: <strong>1:1 aspect ratio</strong></p>
|
||||
<p class="icon-picker-recommendation">Colors do not apply to custom images. Recommended image size: <strong>1:1 aspect ratio</strong></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if tagContextMenu}
|
||||
{#if isMobile}
|
||||
<button type="button" class="context-menu-backdrop" aria-label="Close tag actions" onclick={() => tagContextMenu = null}></button>
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="context-menu" class:mobile={isMobile} style="left: {tagContextMenu.x}px; top: {tagContextMenu.y}px" onmousedown={(e) => e.stopPropagation()}>
|
||||
<button onclick={() => openTagStylePicker(tagContextMenu!.tag)}>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10" /><path d="M8 14s1.5 2 4 2 4-2 4-2" /><line x1="9" y1="9" x2="9.01" y2="9" /><line x1="15" y1="9" x2="15.01" y2="9" /></svg>
|
||||
Customize...
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if stylePickerTag}
|
||||
<TagStylePicker tag={stylePickerTag} onclose={() => stylePickerTag = null} />
|
||||
{/if}
|
||||
|
||||
{#if trashContextMenu}
|
||||
{#if isMobile}
|
||||
<button type="button" class="context-menu-backdrop" aria-label="Close trash actions" onclick={() => trashContextMenu = null}></button>
|
||||
@@ -1045,11 +1196,37 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#snippet tagRow(tag: string, count: number)}
|
||||
<div class="tag-row">
|
||||
<button
|
||||
class="tag-item"
|
||||
class:active={$viewMode === 'tag' && $activeTag === tag}
|
||||
onclick={() => selectTag(tag)}
|
||||
oncontextmenu={(e) => onTagContextMenu(e, tag)}
|
||||
>
|
||||
<span class="tag-label-slot">
|
||||
<TagLabel name={tag} size={isMobile ? 16 : 14} />
|
||||
</span>
|
||||
<span class="tag-count">{count}</span>
|
||||
</button>
|
||||
{#if isMobile}
|
||||
<button
|
||||
type="button"
|
||||
class="notebook-actions-btn"
|
||||
aria-label={`Customize ${tag}`}
|
||||
onclick={(e) => openTagMenu(e, tag)}
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet notebookItem(nb: NotebookEntry, depth: number)}
|
||||
{@const hasChildren = nb.children.length > 0}
|
||||
{@const isCollapsed = $collapsedNotebooks.includes(nb.path)}
|
||||
{@const iconSrc = getNotebookIconSrc(nb)}
|
||||
{@const builtinIcon = decodeBuiltinNotebookIcon($notebookIcons[normalizeNotebookIconKey(nb.relative_path)])}
|
||||
{@const builtinIcon = decodeNotebookIcon($notebookIcons[normalizeNotebookIconKey(nb.relative_path)])}
|
||||
{#if editingNotebook === nb.path}
|
||||
<div class="notebook-item" style="padding-left: {4 + depth * 16}px">
|
||||
<input
|
||||
@@ -1140,22 +1317,24 @@
|
||||
{:else}
|
||||
<span class="chevron-spacer"></span>
|
||||
{/if}
|
||||
{#if builtinIcon}
|
||||
<span class="notebook-builtin-icon"><NotebookGlyph icon={builtinIcon} size={18} /></span>
|
||||
<span class="notebook-icon-slot" class:notebook-builtin-icon={!!builtinIcon?.icon} style:color={builtinIcon?.color}>
|
||||
{#if builtinIcon?.icon}
|
||||
<NotebookGlyph icon={builtinIcon.icon} size={18} />
|
||||
{:else if iconSrc}
|
||||
<img class="notebook-icon" src={iconSrc} alt="" />
|
||||
<img class="notebook-icon" crossorigin="anonymous" src={iconSrc} alt="" />
|
||||
{:else if isCollapsed || nb.children.length === 0}
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.6;flex-shrink:0">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0" style:opacity={builtinIcon?.color ? 1 : 0.6}>
|
||||
<path d="M2 6h4"/><path d="M2 10h4"/><path d="M2 14h4"/><path d="M2 18h4"/>
|
||||
<path d="M6 2h12a2 2 0 012 2v16a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"/>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.6;flex-shrink:0">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0" style:opacity={builtinIcon?.color ? 1 : 0.6}>
|
||||
<path d="M2 6h4"/><path d="M2 10h4"/><path d="M2 14h4"/><path d="M2 18h4"/>
|
||||
<path d="M6 2h12a2 2 0 012 2v16a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"/>
|
||||
<path d="M10 9h8"/><path d="M10 13h8"/><path d="M10 17h5"/>
|
||||
</svg>
|
||||
{/if}
|
||||
</span>
|
||||
<span class="notebook-name">{nb.name} <span class="notebook-count">{nb.note_count}</span></span>
|
||||
{#if $notebookSortMode === 'manual'}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
@@ -1188,6 +1367,13 @@
|
||||
{/snippet}
|
||||
|
||||
<style>
|
||||
.sidebar-error {
|
||||
padding: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -1497,15 +1683,19 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notebook-builtin-icon {
|
||||
.notebook-icon-slot {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.notebook-builtin-icon {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.notebook-name {
|
||||
flex: 1;
|
||||
text-align: left;
|
||||
@@ -1567,6 +1757,10 @@
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.tag-row {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tag-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1582,6 +1776,12 @@
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.tag-label-slot {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.tag-item:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
@@ -1591,16 +1791,6 @@
|
||||
color: var(--text-accent);
|
||||
}
|
||||
|
||||
.tag-hash {
|
||||
color: var(--text-tertiary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tag-name {
|
||||
flex: 1;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.tag-count {
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
@@ -1792,6 +1982,81 @@
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.icon-picker-more {
|
||||
grid-column: 1 / -1;
|
||||
padding: 7px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon-picker-more:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.icon-color-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 0 14px 12px;
|
||||
}
|
||||
|
||||
.icon-color-label {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.icon-swatches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.icon-swatch {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 2px solid transparent;
|
||||
border-radius: 50%;
|
||||
background: var(--bg-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon-swatch:hover,
|
||||
.icon-swatch.active {
|
||||
border-color: var(--text-primary);
|
||||
}
|
||||
|
||||
.icon-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);
|
||||
}
|
||||
|
||||
.icon-swatch.custom {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
background: conic-gradient(from 90deg, #e11d48, #eab308, #22c55e, #3b82f6, #8b5cf6, #e11d48);
|
||||
}
|
||||
|
||||
.icon-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;
|
||||
@@ -1851,6 +2116,11 @@
|
||||
min-height: 64px;
|
||||
}
|
||||
|
||||
.icon-picker-overlay.mobile .icon-picker-more {
|
||||
min-height: 44px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.icon-picker-overlay.mobile .icon-picker-actions button {
|
||||
min-height: 44px;
|
||||
font-size: 14px;
|
||||
@@ -1994,7 +2264,7 @@
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
.sidebar.mobile .notebook-builtin-icon {
|
||||
.sidebar.mobile .notebook-icon-slot {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
}
|
||||
@@ -2019,7 +2289,7 @@
|
||||
}
|
||||
|
||||
.sidebar.mobile .tag-item {
|
||||
padding: 10px 16px;
|
||||
padding: 10px 52px 10px 16px;
|
||||
min-height: 44px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
<script lang="ts" module>
|
||||
let diagramId = 0;
|
||||
// Mermaid has a shared configuration; serialize snapshot renders and restore it afterward.
|
||||
let diagramQueue = Promise.resolve();
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import createDOMPurify from 'dompurify';
|
||||
import katex from 'katex';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import { calloutGroup, calloutIcon, calloutLabel } from '$lib/editor/callouts';
|
||||
import { readSecretTitle } from '$lib/utils/secrets';
|
||||
|
||||
let { html, label = 'Snapshot preview' }: { html: string; label?: string } = $props();
|
||||
let root = $state<HTMLElement>();
|
||||
let purifier: ReturnType<typeof createDOMPurify>;
|
||||
|
||||
const documentTags = [
|
||||
'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup',
|
||||
'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'kbd', 'li',
|
||||
'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small',
|
||||
'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot',
|
||||
'th', 'thead', 'tr', 'u', 'ul', 'var', 'wbr',
|
||||
];
|
||||
const documentAttributes = [
|
||||
'alt', 'class', 'colspan', 'dir', 'height', 'href', 'lang', 'open', 'reversed',
|
||||
'rowspan', 'scope', 'span', 'src', 'start', 'style', 'title', 'value', 'width',
|
||||
'data-type', 'data-checked', 'data-size', 'data-language', 'data-secret-block',
|
||||
'data-math-inline', 'data-math-block', 'data-callout', 'data-callout-title',
|
||||
'data-callout-foldable', 'data-callout-folded',
|
||||
'data-wiki-link', 'data-path', 'data-title', 'data-aliased', 'data-bg-color',
|
||||
'data-pdf-src', 'data-pdf-name', 'data-page-break',
|
||||
];
|
||||
// Custom asset protocols are accepted only here, then checked specifically on images.
|
||||
const documentUris = /^(?:https?:|mailto:|tel:|asset:|imgproxy:|blob:|data:image\/(?:png|jpeg|gif|webp|avif|bmp);|#)/i;
|
||||
const formattingProperties = [
|
||||
'color', 'background-color', 'font-weight', 'font-style', 'font-size',
|
||||
'text-align', 'text-decoration-line', 'text-decoration-color', 'vertical-align',
|
||||
];
|
||||
|
||||
function message(text: string): HTMLParagraphElement {
|
||||
const node = document.createElement('p');
|
||||
node.className = 'snapshot-message';
|
||||
node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
function imageSourceAllowed(source: string): boolean {
|
||||
if (/[\u0000-\u0020\u007f]/.test(source)) return false;
|
||||
if (/^(?:asset|imgproxy):\/\//i.test(source)) return true;
|
||||
if (/^data:image\/(?:png|jpeg|gif|webp|avif|bmp);base64,[a-z\d+/=]+$/i.test(source)) return true;
|
||||
try {
|
||||
const url = new URL(source);
|
||||
if (url.protocol === 'blob:') return new URL(url.pathname).origin === window.location.origin;
|
||||
return ['http:', 'https:'].includes(url.protocol)
|
||||
&& ['asset.localhost', 'imgproxy.localhost'].includes(url.hostname)
|
||||
&& !url.username && !url.password && !url.port;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function keepFormatting(element: HTMLElement): void {
|
||||
const style = element.style;
|
||||
const values = formattingProperties.map((property) => [property, style.getPropertyValue(property)]);
|
||||
element.removeAttribute('style');
|
||||
for (const [property, value] of values) {
|
||||
// Only presentation properties; no URL-bearing CSS, variables, escapes or overlays.
|
||||
if (value && !/url\s*\(|var\s*\(|expression\s*\(|[\\@]/i.test(value)) {
|
||||
element.style.setProperty(property, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function prepareDocument(fragment: DocumentFragment): void {
|
||||
for (const element of fragment.querySelectorAll<HTMLElement>('*')) {
|
||||
keepFormatting(element);
|
||||
const language = element.tagName === 'CODE'
|
||||
? Array.from(element.classList).find((name) => /^language-[\w+-]+$/.test(name))
|
||||
: undefined;
|
||||
element.removeAttribute('class');
|
||||
if (language) element.className = language;
|
||||
if (element.hasAttribute('data-wiki-link')) {
|
||||
element.className = 'snapshot-wiki-link';
|
||||
element.title = `Wiki link to ${element.getAttribute('data-title') || element.textContent || ''} (inactive in snapshot preview)`;
|
||||
element.setAttribute('aria-disabled', 'true');
|
||||
}
|
||||
if (element.hasAttribute('data-page-break')) element.className = 'snapshot-page-break';
|
||||
// Snapshot links are readable but inert: inspection cannot navigate the live note.
|
||||
if (element.tagName === 'A') {
|
||||
const href = element.getAttribute('href');
|
||||
if (href) element.title = `${element.title ? element.title + ' — ' : ''}${href} (inactive in snapshot preview)`;
|
||||
element.removeAttribute('href');
|
||||
element.setAttribute('aria-disabled', 'true');
|
||||
}
|
||||
}
|
||||
for (const attachment of fragment.querySelectorAll<HTMLElement>('[data-pdf-src]')) {
|
||||
const name = attachment.getAttribute('data-pdf-name') || 'PDF attachment';
|
||||
const source = attachment.getAttribute('data-pdf-src') || '';
|
||||
attachment.prepend(message(`${name} — PDF attachment (inline PDF rendering is unavailable in snapshot previews). ${source}`));
|
||||
}
|
||||
for (const image of fragment.querySelectorAll<HTMLImageElement>('img')) {
|
||||
const source = image.getAttribute('src') || '';
|
||||
if (!imageSourceAllowed(source)) {
|
||||
image.replaceWith(message(`Image unavailable or blocked${image.alt ? ': ' + image.alt : '.'}`));
|
||||
continue;
|
||||
}
|
||||
image.crossOrigin = 'anonymous';
|
||||
image.loading = 'lazy';
|
||||
image.decoding = 'async';
|
||||
image.addEventListener('error', () => {
|
||||
image.replaceWith(message(`Image could not be loaded: ${image.alt || source}`));
|
||||
}, { once: true });
|
||||
}
|
||||
for (const item of fragment.querySelectorAll<HTMLElement>('li[data-type="taskItem"]')) {
|
||||
const body = document.createElement('div');
|
||||
while (item.firstChild) body.append(item.firstChild);
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = item.getAttribute('data-checked') === 'true';
|
||||
checkbox.disabled = true;
|
||||
checkbox.setAttribute('aria-label', checkbox.checked ? 'Completed task' : 'Incomplete task');
|
||||
item.className = 'snapshot-task';
|
||||
item.append(checkbox, body);
|
||||
}
|
||||
for (const table of fragment.querySelectorAll('table')) {
|
||||
const scroll = document.createElement('div');
|
||||
scroll.className = 'snapshot-table';
|
||||
scroll.tabIndex = 0;
|
||||
scroll.setAttribute('role', 'region');
|
||||
scroll.setAttribute('aria-label', 'Snapshot table');
|
||||
table.replaceWith(scroll);
|
||||
scroll.append(table);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSecrets(fragment: DocumentFragment): void {
|
||||
for (const node of fragment.querySelectorAll<HTMLElement>('[data-secret-block]')) {
|
||||
const stored = node.getAttribute('data-secret-block') || '';
|
||||
node.replaceChildren();
|
||||
node.className = 'snapshot-secret';
|
||||
const title = document.createElement('strong');
|
||||
let payload = stored;
|
||||
let error = '';
|
||||
try {
|
||||
payload = decodeURIComponent(stored);
|
||||
JSON.parse(payload);
|
||||
} catch {
|
||||
error = 'The stored secret payload is malformed; it cannot be previewed.';
|
||||
}
|
||||
title.textContent = readSecretTitle(payload);
|
||||
node.append(title, message('Locked encrypted content. Secrets are not unlocked in history previews.'));
|
||||
if (error) {
|
||||
const details = document.createElement('details');
|
||||
const summary = document.createElement('summary');
|
||||
summary.textContent = 'Stored secret payload';
|
||||
const code = document.createElement('pre');
|
||||
code.textContent = payload;
|
||||
details.append(summary, code);
|
||||
node.append(message(error), details);
|
||||
}
|
||||
// Do not retain ciphertext in the rendered DOM unless needed for a readable error.
|
||||
node.removeAttribute('data-secret-block');
|
||||
}
|
||||
}
|
||||
|
||||
function renderCallouts(fragment: DocumentFragment): void {
|
||||
// Innermost first so nested callout bodies keep their independently rendered headers.
|
||||
for (const node of Array.from(fragment.querySelectorAll<HTMLElement>('[data-callout]')).reverse()) {
|
||||
const type = node.getAttribute('data-callout') || 'note';
|
||||
const title = node.getAttribute('data-callout-title') || calloutLabel(type);
|
||||
const foldable = node.getAttribute('data-callout-foldable') === 'true';
|
||||
const wrapper = document.createElement(foldable ? 'details' : 'div');
|
||||
wrapper.className = 'snapshot-callout';
|
||||
const group = calloutGroup(type);
|
||||
wrapper.style.setProperty('--snapshot-callout-color', `var(--callout-${typeof group === 'string' ? group : 'custom'})`);
|
||||
if (wrapper instanceof HTMLDetailsElement) wrapper.open = node.getAttribute('data-callout-folded') !== 'true';
|
||||
const header = document.createElement(foldable ? 'summary' : 'div');
|
||||
header.className = 'snapshot-callout-header';
|
||||
const icon = document.createElement('span');
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
icon.append(purifier.sanitize(calloutIcon(type), { USE_PROFILES: { svg: true }, RETURN_DOM_FRAGMENT: true }));
|
||||
const heading = document.createElement('strong');
|
||||
heading.textContent = title;
|
||||
header.append(icon, heading);
|
||||
if (title !== calloutLabel(type)) {
|
||||
const kind = document.createElement('small');
|
||||
kind.textContent = calloutLabel(type);
|
||||
header.append(kind);
|
||||
}
|
||||
const body = document.createElement('div');
|
||||
body.className = 'snapshot-callout-body';
|
||||
while (node.firstChild) body.append(node.firstChild);
|
||||
wrapper.append(header, body);
|
||||
node.replaceWith(wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
function renderMath(fragment: DocumentFragment): void {
|
||||
for (const node of fragment.querySelectorAll<HTMLElement>('[data-math-inline], [data-math-block]')) {
|
||||
const block = node.hasAttribute('data-math-block');
|
||||
const stored = node.getAttribute(block ? 'data-math-block' : 'data-math-inline') || '';
|
||||
let tex = stored;
|
||||
node.className = block ? 'snapshot-math-block' : 'snapshot-math-inline';
|
||||
try {
|
||||
tex = decodeURIComponent(stored);
|
||||
const rendered = katex.renderToString(tex, { displayMode: block, trust: false, throwOnError: true });
|
||||
node.replaceChildren(purifier.sanitize(rendered, {
|
||||
USE_PROFILES: { html: true, mathMl: true, svg: true },
|
||||
FORBID_TAGS: ['style', 'a', 'img', 'image', 'foreignobject'],
|
||||
FORBID_ATTR: ['href', 'xlink:href', 'src'],
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
}));
|
||||
} catch (error) {
|
||||
const code = document.createElement('code');
|
||||
code.textContent = tex;
|
||||
const status = document.createElement('span');
|
||||
status.className = 'snapshot-message';
|
||||
status.textContent = ` Math could not be rendered: ${error instanceof Error ? error.message : String(error)}`;
|
||||
node.replaceChildren(code, status);
|
||||
}
|
||||
node.removeAttribute('data-math-inline');
|
||||
node.removeAttribute('data-math-block');
|
||||
}
|
||||
}
|
||||
|
||||
function prepareDiagrams(fragment: DocumentFragment, isCurrent: () => boolean): void {
|
||||
for (const code of fragment.querySelectorAll<HTMLElement>('pre > code.language-mermaid, pre[data-language="mermaid"] > code')) {
|
||||
const source = code.textContent || '';
|
||||
const controls = document.createElement('div');
|
||||
controls.className = 'snapshot-diagram';
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.textContent = '▶ Render diagram';
|
||||
const status = document.createElement('span');
|
||||
status.className = 'snapshot-message';
|
||||
status.setAttribute('role', 'status');
|
||||
const output = document.createElement('div');
|
||||
output.className = 'snapshot-diagram-output';
|
||||
controls.append(button, status, output);
|
||||
code.parentElement!.after(controls);
|
||||
button.addEventListener('click', async () => {
|
||||
button.disabled = true;
|
||||
status.textContent = 'Rendering diagram…';
|
||||
let staging: HTMLDivElement | undefined;
|
||||
let restoreConfig: (() => void) | undefined;
|
||||
let release!: () => void;
|
||||
const previousRender = diagramQueue;
|
||||
diagramQueue = new Promise<void>((resolve) => { release = resolve; });
|
||||
await previousRender;
|
||||
try {
|
||||
const { default: mermaid } = await import('mermaid');
|
||||
if (!isCurrent() || !controls.isConnected) return;
|
||||
const previousConfig = mermaid.mermaidAPI.getConfig();
|
||||
restoreConfig = () => mermaid.initialize(previousConfig);
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'strict',
|
||||
suppressErrorRendering: true,
|
||||
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'default',
|
||||
fontFamily: 'inherit',
|
||||
htmlLabels: false,
|
||||
flowchart: { htmlLabels: false },
|
||||
secure: [
|
||||
...(mermaid.mermaidAPI.defaultConfig.secure || []),
|
||||
'htmlLabels', 'flowchart', 'themeCSS', 'themeVariables', 'fontFamily', 'altFontFamily', 'dompurifyConfig',
|
||||
],
|
||||
});
|
||||
const parsed = await mermaid.mermaidAPI.getDiagramFromText(source);
|
||||
// Strict Mermaid still fetches image-shape URLs during layout, before SVG sanitization.
|
||||
// Inspect its parsed layout data rather than trying to rewrite the fence's source.
|
||||
if ('getData' in parsed.db && typeof parsed.db.getData === 'function') {
|
||||
const data: unknown = parsed.db.getData();
|
||||
if (data && typeof data === 'object' && 'nodes' in data && Array.isArray(data.nodes)
|
||||
&& data.nodes.some((node: unknown) => node && typeof node === 'object' && 'img' in node && node.img)) {
|
||||
throw new Error('Embedded Mermaid images are not loaded in snapshot previews.');
|
||||
}
|
||||
}
|
||||
if (!isCurrent() || !controls.isConnected) return;
|
||||
staging = document.createElement('div');
|
||||
staging.className = 'snapshot-diagram-staging';
|
||||
staging.setAttribute('aria-hidden', 'true');
|
||||
staging.inert = true;
|
||||
controls.append(staging);
|
||||
const { svg } = await mermaid.render(`snapshot-diagram-${++diagramId}`, source, staging);
|
||||
if (!isCurrent() || !controls.isConnected) return;
|
||||
const clean = purifier.sanitize(svg, {
|
||||
USE_PROFILES: { svg: true },
|
||||
FORBID_TAGS: ['style', 'foreignobject', 'image', 'use', 'a'],
|
||||
FORBID_ATTR: ['style', 'href', 'xlink:href'],
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
});
|
||||
const blockedContent = purifier.removed.some((entry) => 'element' in entry
|
||||
&& ['foreignobject', 'image', 'use'].includes(entry.element.nodeName.toLowerCase()));
|
||||
for (const element of clean.querySelectorAll('*')) {
|
||||
element.removeAttribute('class');
|
||||
for (const attribute of Array.from(element.attributes)) {
|
||||
if (/url\s*\(/i.test(attribute.value) && !/^url\(\s*#[\w:.-]+\s*\)$/i.test(attribute.value)) {
|
||||
element.removeAttribute(attribute.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
const diagram = clean.querySelector('svg');
|
||||
if (!diagram) throw new Error('No safe diagram output was produced.');
|
||||
diagram.setAttribute('role', 'img');
|
||||
diagram.setAttribute('aria-label', 'Rendered snapshot diagram; source is shown above');
|
||||
output.replaceChildren(clean);
|
||||
status.textContent = blockedContent
|
||||
? 'Rendered with unsupported embedded content blocked. Original source remains above.'
|
||||
: 'Rendered. Original source remains above.';
|
||||
button.textContent = '↻ Render again';
|
||||
} catch (error) {
|
||||
if (isCurrent() && controls.isConnected) {
|
||||
status.textContent = `Diagram could not be rendered: ${error instanceof Error ? error.message : String(error)} Original source remains above.`;
|
||||
button.textContent = '↻ Retry';
|
||||
}
|
||||
} finally {
|
||||
staging?.remove();
|
||||
try {
|
||||
restoreConfig?.();
|
||||
} finally {
|
||||
release();
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const source = html;
|
||||
const target = root;
|
||||
if (!target) return;
|
||||
let active = true;
|
||||
try {
|
||||
purifier ??= createDOMPurify(window);
|
||||
if (!purifier.isSupported) throw new Error('Safe HTML rendering is unavailable in this browser.');
|
||||
const fragment = purifier.sanitize(source, {
|
||||
ALLOWED_TAGS: documentTags,
|
||||
ALLOWED_ATTR: documentAttributes,
|
||||
ADD_URI_SAFE_ATTR: documentAttributes.filter((attribute) => attribute.startsWith('data-')),
|
||||
ALLOWED_NAMESPACES: ['http://www.w3.org/1999/xhtml'],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
ALLOW_ARIA_ATTR: false,
|
||||
ALLOWED_URI_REGEXP: documentUris,
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
});
|
||||
const blockedMarkup = purifier.removed.some((entry) => 'element' in entry
|
||||
&& ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'textarea', 'select', 'video', 'audio', 'svg', 'math']
|
||||
.includes(entry.element.nodeName.toLowerCase()));
|
||||
prepareDocument(fragment);
|
||||
renderSecrets(fragment);
|
||||
renderCallouts(fragment);
|
||||
renderMath(fragment);
|
||||
prepareDiagrams(fragment, () => active && target.isConnected);
|
||||
if (blockedMarkup) {
|
||||
const details = document.createElement('details');
|
||||
const summary = document.createElement('summary');
|
||||
summary.textContent = 'Active or unsupported embedded content was blocked. View supplied HTML as text.';
|
||||
const code = document.createElement('pre');
|
||||
code.textContent = source;
|
||||
details.append(summary, code);
|
||||
fragment.prepend(details);
|
||||
}
|
||||
target.replaceChildren(source.trim() ? fragment : message('This snapshot has no body content.'));
|
||||
} catch (error) {
|
||||
const code = document.createElement('pre');
|
||||
code.textContent = source;
|
||||
target.replaceChildren(message(`Snapshot could not be rendered: ${error instanceof Error ? error.message : String(error)} Showing supplied HTML as text.`), code);
|
||||
}
|
||||
return () => { active = false; };
|
||||
});
|
||||
</script>
|
||||
|
||||
<section class="snapshot-document" aria-label={label}>
|
||||
<div class="snapshot-body" bind:this={root}></div>
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.snapshot-document {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: 16px;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--editor-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif);
|
||||
font-size: var(--editor-font-size, 14px);
|
||||
line-height: var(--editor-line-height, 1.65);
|
||||
user-select: text;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.snapshot-body :global(p) { margin: 0 0 0.4em; }
|
||||
.snapshot-body :global(h1) { font-size: 1.75em; margin: 1.5em 0 0.5em; }
|
||||
.snapshot-body :global(h2) { font-size: 1.4em; margin: 1.25em 0 0.5em; }
|
||||
.snapshot-body :global(h3) { font-size: 1.2em; margin: 1em 0 0.5em; }
|
||||
.snapshot-body :global(h4), .snapshot-body :global(h5), .snapshot-body :global(h6) { margin: 0.9em 0 0.4em; }
|
||||
.snapshot-body :global(h1), .snapshot-body :global(h2), .snapshot-body :global(h3) { line-height: 1.3; }
|
||||
.snapshot-body > :global(:first-child) { margin-top: 0; }
|
||||
.snapshot-body :global(strong) { font-weight: 600; }
|
||||
.snapshot-body :global(a) { color: var(--text-accent); text-decoration: underline; }
|
||||
.snapshot-body :global(blockquote) { border-left: 3px solid var(--accent); padding-left: 16px; margin: 1em 0; color: var(--text-secondary); }
|
||||
.snapshot-body :global(code), .snapshot-body :global(kbd), .snapshot-body :global(pre) { font-family: var(--font-mono, monospace); }
|
||||
.snapshot-body :global(code) { background: color-mix(in srgb, var(--accent) 8%, var(--bg-tertiary)); padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
|
||||
.snapshot-body :global(pre) { overflow-x: auto; max-width: 100%; padding: 16px; margin: 1em 0; border-radius: 8px; background: color-mix(in srgb, var(--accent) 8%, var(--bg-tertiary)); white-space: pre; }
|
||||
.snapshot-body :global(pre code) { padding: 0; background: none; font-size: 0.93em; line-height: 1.5; }
|
||||
.snapshot-body :global(img) { max-width: 100%; height: auto; object-fit: contain; }
|
||||
.snapshot-body :global(img[data-size="small"]) { max-width: 33%; }
|
||||
.snapshot-body :global(img[data-size="medium"]) { max-width: 65%; }
|
||||
.snapshot-body :global(ul), .snapshot-body :global(ol) { padding-left: 1.5em; }
|
||||
.snapshot-body :global(ul[data-type="taskList"]) { padding-left: 0; list-style: none; }
|
||||
.snapshot-body :global(.snapshot-task) { display: flex; align-items: flex-start; gap: 8px; list-style: none; }
|
||||
.snapshot-body :global(.snapshot-task > input) { flex: none; margin-top: 0.4em; accent-color: var(--accent); }
|
||||
.snapshot-body :global(.snapshot-task > div) { flex: 1; min-width: 0; }
|
||||
.snapshot-body :global(details) { margin: 1em 0; }
|
||||
.snapshot-body :global(summary) { cursor: pointer; }
|
||||
.snapshot-body :global(.snapshot-table) { max-width: 100%; overflow-x: auto; margin: 1em 0; }
|
||||
.snapshot-body :global(table) { border-collapse: collapse; min-width: 100%; }
|
||||
.snapshot-body :global(th), .snapshot-body :global(td) { border: 1px solid var(--border); padding: 6px 10px; vertical-align: top; }
|
||||
.snapshot-body :global(th) { background: var(--bg-secondary); font-weight: 600; }
|
||||
.snapshot-body :global(.snapshot-secret) { margin: 1em 0; padding: 12px; border: 1px solid var(--border); border-radius: 8px; background: color-mix(in srgb, var(--accent) 7%, var(--bg-secondary)); }
|
||||
.snapshot-body :global(.snapshot-message) { color: var(--text-secondary); font-size: 0.9em; }
|
||||
.snapshot-body :global(.snapshot-wiki-link) { color: var(--text-accent); text-decoration: underline; text-decoration-style: dotted; }
|
||||
.snapshot-body :global(.snapshot-page-break) { margin: 1em 0; border-top: 1px dashed var(--border); }
|
||||
.snapshot-body :global(.snapshot-page-break)::before { content: 'Page break'; color: var(--text-tertiary); font-size: 0.8em; }
|
||||
.snapshot-body :global(.snapshot-callout) { border: 1px solid rgba(var(--snapshot-callout-color), 0.3); border-left: 3px solid rgb(var(--snapshot-callout-color)); border-radius: 8px; background: rgba(var(--snapshot-callout-color), 0.06); margin: 1em 0; }
|
||||
.snapshot-body :global(.snapshot-callout-header) { padding: 8px 12px; color: rgb(var(--snapshot-callout-color)); }
|
||||
.snapshot-body :global(.snapshot-callout-header > span) { display: inline-flex; vertical-align: middle; margin-right: 8px; }
|
||||
.snapshot-body :global(.snapshot-callout-header > small) { margin-left: 8px; }
|
||||
.snapshot-body :global(.snapshot-callout-body) { padding: 8px 14px 10px; }
|
||||
.snapshot-body :global(.snapshot-math-block) { overflow-x: auto; margin: 16px 0; padding: 12px; text-align: center; }
|
||||
.snapshot-body :global(.snapshot-math-block .katex-display) { margin: 0; }
|
||||
.snapshot-body :global(.snapshot-diagram) { position: relative; margin: -0.5em 0 1em; }
|
||||
.snapshot-body :global(.snapshot-diagram button) { border: 1px solid var(--border); border-radius: 6px; padding: 7px 14px; background: var(--bg-tertiary); color: var(--text-primary); font: inherit; font-size: 0.9em; cursor: pointer; }
|
||||
.snapshot-body :global(.snapshot-diagram button:hover:not(:disabled)) { border-color: var(--accent); }
|
||||
.snapshot-body :global(.snapshot-diagram button:disabled) { opacity: 0.6; cursor: wait; }
|
||||
.snapshot-body :global(.snapshot-diagram [role="status"]) { display: block; margin-top: 6px; }
|
||||
.snapshot-body :global(.snapshot-diagram-output) { overflow-x: auto; max-width: 100%; }
|
||||
.snapshot-body :global(.snapshot-diagram-output svg) { max-width: 100%; height: auto; color: var(--text-primary); }
|
||||
/* SVG stylesheets are removed; these local rules keep untrusted diagrams legible. */
|
||||
.snapshot-body :global(.snapshot-diagram-output svg text), .snapshot-body :global(.snapshot-diagram-output svg tspan) { fill: var(--text-primary); font-family: inherit; }
|
||||
.snapshot-body :global(.snapshot-diagram-output svg path), .snapshot-body :global(.snapshot-diagram-output svg line), .snapshot-body :global(.snapshot-diagram-output svg polyline) { stroke: var(--text-secondary); fill: none; }
|
||||
.snapshot-body :global(.snapshot-diagram-output svg rect), .snapshot-body :global(.snapshot-diagram-output svg circle), .snapshot-body :global(.snapshot-diagram-output svg ellipse), .snapshot-body :global(.snapshot-diagram-output svg polygon) { stroke: var(--text-secondary); fill: var(--bg-secondary); }
|
||||
.snapshot-body :global(.snapshot-diagram-output svg marker path) { fill: var(--text-secondary); }
|
||||
.snapshot-body :global(.snapshot-diagram-staging) { position: absolute; visibility: hidden; pointer-events: none; width: 100%; }
|
||||
.snapshot-body :global(summary:focus-visible), .snapshot-body :global(button:focus-visible), .snapshot-body :global(.snapshot-table:focus-visible) { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
</style>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,494 @@
|
||||
<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,
|
||||
COMMON_NOTEBOOK_ICON_COUNT,
|
||||
decodeBuiltinNotebookIcon,
|
||||
isCommonNotebookIcon,
|
||||
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));
|
||||
let showAll = $state<boolean | null>(null);
|
||||
// Starts open when the current icon is one of the extra icons.
|
||||
const expanded = $derived(showAll ?? !isCommonNotebookIcon(decodeBuiltinNotebookIcon(activeIcon)));
|
||||
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 expanded ? NOTEBOOK_ICON_OPTIONS : NOTEBOOK_ICON_OPTIONS.slice(0, COMMON_NOTEBOOK_ICON_COUNT) 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}
|
||||
<button type="button" class="icon-picker-more" aria-expanded={expanded} onclick={() => showAll = !expanded}>
|
||||
{expanded ? 'Fewer icons' : 'More icons'}
|
||||
</button>
|
||||
</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);
|
||||
}
|
||||
|
||||
.icon-picker-more {
|
||||
grid-column: 1 / -1;
|
||||
padding: 7px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.icon-picker-more:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.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-more {
|
||||
min-height: 44px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.icon-picker-overlay.mobile .icon-picker-actions button {
|
||||
min-height: 44px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { tags } from '$lib/stores/app';
|
||||
import TagLabel from './TagLabel.svelte';
|
||||
|
||||
let { existing = [], placeholder = 'Add tag...', onsubmit, oncancel }: {
|
||||
existing?: string[];
|
||||
@@ -69,14 +70,14 @@
|
||||
/>
|
||||
{#if suggestions.length}
|
||||
<div class="tag-suggest-list">
|
||||
{#each suggestions as s, i}
|
||||
{#each suggestions as s, i (s)}
|
||||
<button
|
||||
type="button"
|
||||
class="tag-suggest-item"
|
||||
class:selected={i === selIndex}
|
||||
onmouseenter={() => (selIndex = i)}
|
||||
onmousedown={(e) => { e.preventDefault(); submit(s); }}
|
||||
>#{s}</button>
|
||||
><TagLabel name={s} size={12} /></button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -110,6 +111,8 @@
|
||||
gap: 1px;
|
||||
}
|
||||
.tag-suggest-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-align: left;
|
||||
padding: 5px 8px;
|
||||
border: none;
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
import { getTasks } from '$lib/api';
|
||||
import { debounce } from '$lib/utils/debounce';
|
||||
import { tasksLayout, tasksHideCompleted, tasksOnlyFlagged, tasksSort, appConfig } from '$lib/stores/app';
|
||||
import { isAndroid } from '$lib/platform';
|
||||
import { isAndroid, isMobile } from '$lib/platform';
|
||||
import type { TaskItem, FileEvent } from '$lib/types';
|
||||
import { isCurrentVaultEvent } from '$lib/utils/note-list-updates';
|
||||
import { formatLocalDate } from '$lib/utils/time';
|
||||
import { matchesTaskDueFilter, type TaskDueFilter } from '$lib/utils/task-filter';
|
||||
|
||||
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;
|
||||
@@ -18,42 +21,120 @@
|
||||
let loading = $state(true);
|
||||
let taskQuery = $state('');
|
||||
let unlisten: (() => void) | null = null;
|
||||
let disposed = false;
|
||||
let fullLoad = 0;
|
||||
let revision = 0;
|
||||
const noteRevisions = new Map<string, number>();
|
||||
|
||||
async function load() {
|
||||
if (disposed) return;
|
||||
const request = ++fullLoad;
|
||||
const startedAt = revision;
|
||||
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) {
|
||||
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);
|
||||
|
||||
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(() => {
|
||||
load();
|
||||
listen<FileEvent>('file-changed', () => debouncedLoad()).then((u) => (unlisten = u));
|
||||
return () => { unlisten?.(); };
|
||||
void load();
|
||||
let dayTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const refreshDay = () => {
|
||||
const now = new Date();
|
||||
today = formatLocalDate(now);
|
||||
clearTimeout(dayTimer);
|
||||
const nextDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
|
||||
dayTimer = setTimeout(refreshDay, nextDay.getTime() - now.getTime() + 1);
|
||||
};
|
||||
const resumeDay = () => {
|
||||
if (document.visibilityState === 'visible') refreshDay();
|
||||
};
|
||||
refreshDay();
|
||||
document.addEventListener('visibilitychange', resumeDay);
|
||||
listen<FileEvent>('file-changed', ({ payload }) => handleFileChange(payload)).then((u) => {
|
||||
if (disposed) u();
|
||||
else unlisten = u;
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
fullLoad += 1;
|
||||
unlisten?.();
|
||||
clearTimeout(dayTimer);
|
||||
document.removeEventListener('visibilitychange', resumeDay);
|
||||
};
|
||||
});
|
||||
|
||||
// Local YYYY-MM-DD (en-CA gives ISO-style date)
|
||||
const today = new Date().toLocaleDateString('en-CA');
|
||||
let today = $state(formatLocalDate(new Date()));
|
||||
let dueFilter = $state<TaskDueFilter>('all');
|
||||
|
||||
const prioRank: Record<string, number> = { high: 0, med: 1, low: 2 };
|
||||
function prank(p: string | null) { return p ? (prioRank[p] ?? 3) : 3; }
|
||||
// Free-text task filter: matches the task text or its note title (case-insensitive).
|
||||
const normalizedTaskQuery = $derived(taskQuery.trim().toLowerCase());
|
||||
function matchesQuery(t: TaskItem): boolean {
|
||||
const q = taskQuery.trim().toLowerCase();
|
||||
if (!q) return true;
|
||||
return t.text.toLowerCase().includes(q) || t.note_title.toLowerCase().includes(q);
|
||||
if (!normalizedTaskQuery) return true;
|
||||
return t.text.toLowerCase().includes(normalizedTaskQuery) || t.note_title.toLowerCase().includes(normalizedTaskQuery);
|
||||
}
|
||||
|
||||
const matchingTasks = $derived(tasks.filter((t) =>
|
||||
(!$tasksHideCompleted || !t.completed)
|
||||
&& (!$tasksOnlyFlagged || !!t.due || !!t.priority)
|
||||
&& matchesQuery(t)
|
||||
&& matchesTaskDueFilter(t.due, dueFilter, today, t.completed)
|
||||
));
|
||||
|
||||
const filtered = $derived.by(() => {
|
||||
let list = tasks.slice();
|
||||
if ($tasksHideCompleted) list = list.filter((t) => !t.completed);
|
||||
if ($tasksOnlyFlagged) list = list.filter((t) => !!t.due || !!t.priority);
|
||||
list = list.filter(matchesQuery);
|
||||
const list = matchingTasks.slice();
|
||||
list.sort((a, b) => {
|
||||
if (a.completed !== b.completed) return a.completed ? 1 : -1; // done last
|
||||
if ($tasksSort === 'priority') {
|
||||
@@ -74,8 +155,8 @@
|
||||
|
||||
const openCount = $derived(tasks.filter((t) => !t.completed).length);
|
||||
|
||||
function dueClass(due: string | null): string {
|
||||
if (!due) return '';
|
||||
function dueClass(due: string | null, completed: boolean): string {
|
||||
if (!due || completed) return '';
|
||||
if (due < today) return 'overdue';
|
||||
if (due === today) return 'duetoday';
|
||||
return '';
|
||||
@@ -83,7 +164,7 @@
|
||||
|
||||
async function toggle(t: TaskItem) {
|
||||
await onToggleTask(t);
|
||||
await load();
|
||||
await loadNote(t.note_path);
|
||||
}
|
||||
|
||||
let prioMenuFor = $state<string | null>(null);
|
||||
@@ -93,13 +174,13 @@
|
||||
async function choosePriority(t: TaskItem, p: string | null) {
|
||||
prioMenuFor = null;
|
||||
await onSetTaskPriority(t, p);
|
||||
await load();
|
||||
await loadNote(t.note_path);
|
||||
}
|
||||
|
||||
async function chooseDue(t: TaskItem, d: string | null) {
|
||||
dueMenuFor = null;
|
||||
await onSetTaskDue(t, d);
|
||||
await load();
|
||||
await loadNote(t.note_path);
|
||||
}
|
||||
|
||||
// ── Calendar ──
|
||||
@@ -108,7 +189,7 @@
|
||||
const calNow = new Date();
|
||||
let calMonth = $state(calNow.getMonth());
|
||||
let calYear = $state(calNow.getFullYear());
|
||||
let selectedDate = $state(today);
|
||||
let selectedDate = $state(formatLocalDate(calNow));
|
||||
|
||||
const calMonthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
// 0 = Sunday, 1 = Monday (default). Day names + grid offset follow the setting.
|
||||
@@ -116,12 +197,9 @@
|
||||
const DOW = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
|
||||
const calDayNames = $derived([...DOW.slice(weekStartsOn), ...DOW.slice(0, weekStartsOn)]);
|
||||
|
||||
// Calendar tasks share the list's hide-completed filter (no sort).
|
||||
const calBase = $derived(tasks.filter((t) => (!$tasksHideCompleted || !t.completed) && (!$tasksOnlyFlagged || !!t.due || !!t.priority) && matchesQuery(t)));
|
||||
|
||||
const tasksByDate = $derived.by(() => {
|
||||
const m = new Map<string, TaskItem[]>();
|
||||
for (const t of calBase) {
|
||||
for (const t of matchingTasks) {
|
||||
if (!t.due) continue;
|
||||
const arr = m.get(t.due);
|
||||
if (arr) arr.push(t);
|
||||
@@ -130,7 +208,7 @@
|
||||
return m;
|
||||
});
|
||||
|
||||
const undatedTasks = $derived(calBase.filter((t) => !t.due));
|
||||
const undatedTasks = $derived(matchingTasks.filter((t) => !t.due));
|
||||
|
||||
function byPriority(a: TaskItem, b: TaskItem) {
|
||||
if (a.completed !== b.completed) return a.completed ? 1 : -1;
|
||||
@@ -183,17 +261,19 @@
|
||||
dragOverDate = null;
|
||||
if (!t || t.due === date) return;
|
||||
await onSetTaskDue(t, date);
|
||||
await load();
|
||||
await loadNote(t.note_path);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="tasks-view">
|
||||
<div class="tasks-view" class:mobile={isMobile}>
|
||||
{#if prioMenuFor || dueMenuFor}
|
||||
<!-- svelte-ignore a11y_consider_explicit_label -->
|
||||
<button class="prio-backdrop" onclick={() => { prioMenuFor = null; dueMenuFor = null; }} aria-label="Close menu"></button>
|
||||
{/if}
|
||||
<div class="tasks-controls">
|
||||
<input class="tasks-filter" type="text" placeholder="Filter tasks…" bind:value={taskQuery} onkeydown={(e) => { if (e.key === 'Escape') taskQuery = ''; }} aria-label="Filter tasks by text" />
|
||||
<button class="tasks-ctl" class:active={dueFilter === 'today'} aria-pressed={dueFilter === 'today'} onclick={() => { dueFilter = dueFilter === 'today' ? 'all' : 'today'; if (dueFilter === 'today') calToday(); }} title="Show tasks due today">Today</button>
|
||||
<button class="tasks-ctl" class:active={dueFilter === 'overdue'} aria-pressed={dueFilter === 'overdue'} onclick={() => { dueFilter = dueFilter === 'overdue' ? 'all' : 'overdue'; }} title="Show tasks due before today">Overdue</button>
|
||||
<button class="tasks-ctl" class:active={$tasksHideCompleted} onclick={() => ($tasksHideCompleted = !$tasksHideCompleted)} title="Hide completed tasks">Hide done</button>
|
||||
<button class="tasks-ctl" class:active={$tasksOnlyFlagged} onclick={() => ($tasksOnlyFlagged = !$tasksOnlyFlagged)} title="Only show tasks with a due date or priority">Flagged</button>
|
||||
{#if !isAndroid}
|
||||
@@ -246,7 +326,7 @@
|
||||
<span class="task-label">{t.text}</span>
|
||||
<span class="task-due-wrap">
|
||||
<button
|
||||
class="task-due {dueClass(t.due)}"
|
||||
class="task-due {dueClass(t.due, t.completed)}"
|
||||
class:set={!!t.due}
|
||||
title="Set due date"
|
||||
aria-label="Set due date"
|
||||
@@ -328,7 +408,15 @@
|
||||
</div>
|
||||
</div>
|
||||
{:else if filtered.length === 0}
|
||||
<div class="tasks-empty">No tasks. Add <code>- [ ] something</code> to any note.{#if openCount === 0 && tasks.length}{' '}All done!{/if}</div>
|
||||
<div class="tasks-empty">
|
||||
{#if tasks.length === 0}
|
||||
No tasks. Add <code>- [ ] something</code> to any note.
|
||||
{:else if $tasksHideCompleted && openCount === 0}
|
||||
All tasks are complete.
|
||||
{:else}
|
||||
No tasks match these filters.
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="tasks-list">
|
||||
{#each filtered as t (rowKey(t))}{@render taskRow(t, false)}{/each}
|
||||
@@ -384,6 +472,21 @@
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.tasks-view.mobile .tasks-filter {
|
||||
flex-basis: 100%;
|
||||
min-height: 44px;
|
||||
}
|
||||
.tasks-view.mobile .tasks-ctl {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
}
|
||||
/* Marking a task done is the main action on a phone: widen the tap area without changing how the box looks,
|
||||
staying clear of the priority control that follows it. */
|
||||
.tasks-view.mobile .task-check::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -16px -6px -16px -16px;
|
||||
}
|
||||
.tasks-filter::placeholder { color: var(--text-tertiary); }
|
||||
.tasks-filter:focus { outline: none; border-color: var(--accent); }
|
||||
.tasks-list {
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
<script lang="ts">
|
||||
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 NoteSwitcher from './NoteSwitcher.svelte';
|
||||
import { isTrashedNote } from '$lib/utils/paths';
|
||||
|
||||
let {
|
||||
onNewNote = () => {},
|
||||
onDailyNote = () => {},
|
||||
onSelectNote
|
||||
onSelectNote,
|
||||
onBeforeVaultSwitch
|
||||
}: {
|
||||
onNewNote?: () => void;
|
||||
onDailyNote?: () => void;
|
||||
onSelectNote?: (path: string) => Promise<boolean>;
|
||||
onBeforeVaultSwitch: () => Promise<boolean>;
|
||||
} = $props();
|
||||
|
||||
const appWindow = getCurrentWindow();
|
||||
@@ -93,9 +96,11 @@
|
||||
</div>
|
||||
{/if}
|
||||
<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="Manage Vaults" aria-label="Manage Vaults">
|
||||
<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" />
|
||||
<rect x="3" y="3" width="18" height="16" rx="2" />
|
||||
<circle cx="12" cy="11" r="3.5" />
|
||||
<path d="M12 7.5V6M12 16v-1.5M7 19v2M17 19v2" />
|
||||
</svg>
|
||||
</button>
|
||||
<button class="switch-vault-btn" onclick={() => ($focusMode = true)} title="Focus mode">
|
||||
@@ -103,7 +108,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"/>
|
||||
</svg>
|
||||
</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">
|
||||
{#if $readOnly}
|
||||
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack } from 'svelte';
|
||||
import { open } from '@tauri-apps/plugin-dialog';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
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 { isAndroid, isIOS, isMobile } from '$lib/platform';
|
||||
import type { VaultConfig } from '$lib/types';
|
||||
@@ -10,17 +11,30 @@
|
||||
let { initialError = '' }: { initialError?: string } = $props();
|
||||
|
||||
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 loading = $state(false);
|
||||
let error = $state('');
|
||||
let error = $state(untrack(() => initialError));
|
||||
let vaultName = $state('HelixNotes');
|
||||
let hasPermission = $state(!isAndroid);
|
||||
let selectedLocation = $state('Documents');
|
||||
|
||||
$effect(() => {
|
||||
if (initialError && !error) error = initialError;
|
||||
});
|
||||
let customPath = $state('');
|
||||
let iosBasePath = $state('');
|
||||
|
||||
@@ -269,7 +283,7 @@
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if $appConfig?.active_vault}
|
||||
{#if $appConfig?.active_vault && !initialError}
|
||||
<button class="btn-back" onclick={() => ($vaultReady = true)}>
|
||||
Back
|
||||
</button>
|
||||
|
||||
@@ -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,142 @@
|
||||
import CodeBlock, { type CodeBlockOptions } from '@tiptap/extension-code-block';
|
||||
import { toggleSelectedCode } from './toggleSelectedCode.ts';
|
||||
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;
|
||||
// A named language without a grammar (mermaid, a typo) stays plain: guessing would run
|
||||
// every registered grammar over the block on each edit.
|
||||
const tree = !language ? lowlight.highlightAuto(node.textContent)
|
||||
: lowlight.registered(language) ? lowlight.highlight(language, node.textContent)
|
||||
: { children: [] };
|
||||
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 };
|
||||
},
|
||||
addCommands() {
|
||||
return { ...this.parent?.(), toggleCodeBlock: (attributes) => toggleSelectedCode(attributes) };
|
||||
},
|
||||
addAttributes() {
|
||||
// A block written without a language keeps none, so a bare fence is not saved as the default
|
||||
// language. Highlighting still falls back to the default language for such blocks.
|
||||
const attributes: Record<string, object> = this.parent?.() ?? {};
|
||||
return { ...attributes, language: { ...attributes.language, default: 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,196 @@
|
||||
import { Node, mergeAttributes } from '@tiptap/core';
|
||||
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
|
||||
import { clampImgGridCols, normalizeImgGridLayout } from '../imageGrid.ts';
|
||||
|
||||
export interface ImageGridDrag {
|
||||
gridPos: number;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export interface ImageGridOptions {
|
||||
/** Replace the grid at `gridPos` with one image paragraph per image. */
|
||||
onUngroup: (gridPos: number) => void;
|
||||
/** Move image `fromIndex` of one grid before slot `toIndex` of the same or another grid. */
|
||||
onMoveImage: (fromGridPos: number, fromIndex: number, toGridPos: number, toIndex: number) => void;
|
||||
}
|
||||
|
||||
export interface ImageGridStorage {
|
||||
/** The grid image being dragged. Shared by every grid in the editor so images can move between grids. */
|
||||
drag: ImageGridDrag | null;
|
||||
}
|
||||
|
||||
declare module '@tiptap/core' {
|
||||
interface Storage {
|
||||
imageGrid: ImageGridStorage;
|
||||
}
|
||||
}
|
||||
|
||||
function controlButton(label: string, title: string, onClick: () => void): HTMLButtonElement {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'img-grid-control';
|
||||
button.title = title;
|
||||
button.textContent = label;
|
||||
button.addEventListener('mousedown', (event) => event.preventDefault());
|
||||
button.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
onClick();
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
/**
|
||||
* Side-by-side image grid (#254). Saved as a `:::img-grid` block (see imageGrid.ts). The content is
|
||||
* the editor's inline image nodes, so size, copy and the image toolbar work the same as elsewhere.
|
||||
*/
|
||||
export const ImageGrid = Node.create<ImageGridOptions, ImageGridStorage>({
|
||||
name: 'imageGrid',
|
||||
group: 'block',
|
||||
content: 'image+',
|
||||
defining: true,
|
||||
|
||||
addOptions() {
|
||||
return { onUngroup: () => {}, onMoveImage: () => {} };
|
||||
},
|
||||
|
||||
addStorage() {
|
||||
return { drag: null };
|
||||
},
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
cols: {
|
||||
default: 2,
|
||||
parseHTML: (element: HTMLElement) => clampImgGridCols(element.getAttribute('data-cols') ?? ''),
|
||||
renderHTML: (attributes: Record<string, unknown>) => ({ 'data-cols': String(clampImgGridCols(attributes.cols)) }),
|
||||
},
|
||||
layout: {
|
||||
default: 'grid',
|
||||
parseHTML: (element: HTMLElement) => normalizeImgGridLayout(element.getAttribute('data-layout')),
|
||||
renderHTML: (attributes: Record<string, unknown>) => ({ 'data-layout': normalizeImgGridLayout(attributes.layout) }),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [{ tag: 'div[data-img-grid]' }];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
// `data-img-grid` is what parseHTML matches, so copied grids paste back as grids.
|
||||
return ['div', mergeAttributes(HTMLAttributes, { 'data-img-grid': '', class: 'img-grid' }), 0];
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
const { onUngroup, onMoveImage } = this.options;
|
||||
const storage = this.storage;
|
||||
return ({ node, getPos, editor }) => {
|
||||
const dom = document.createElement('div');
|
||||
const header = document.createElement('div');
|
||||
const content = document.createElement('div');
|
||||
dom.className = 'img-grid-wrap';
|
||||
header.className = 'img-grid-header';
|
||||
header.contentEditable = 'false';
|
||||
dom.append(header, content);
|
||||
const position = (): number | null => (typeof getPos === 'function' ? getPos() ?? null : null);
|
||||
|
||||
const render = (current: ProseMirrorNode) => {
|
||||
const cols = clampImgGridCols(current.attrs.cols);
|
||||
const layout = normalizeImgGridLayout(current.attrs.layout);
|
||||
for (const element of [dom, content]) {
|
||||
element.setAttribute('data-img-grid', '');
|
||||
element.setAttribute('data-cols', String(cols));
|
||||
element.setAttribute('data-layout', layout);
|
||||
}
|
||||
content.className = 'img-grid';
|
||||
header.replaceChildren();
|
||||
if (!editor.isEditable) return;
|
||||
const setAttrs = (attrs: Record<string, unknown>) => {
|
||||
const pos = position();
|
||||
if (pos !== null) editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...attrs }));
|
||||
};
|
||||
header.append(
|
||||
controlButton(`${cols} col`, 'Cycle columns (2-4)', () => setAttrs({ cols: cols >= 4 ? 2 : cols + 1 })),
|
||||
controlButton(layout, 'Toggle grid / masonry', () => setAttrs({ layout: layout === 'masonry' ? 'grid' : 'masonry' })),
|
||||
controlButton('ungroup', 'Ungroup back to single images', () => {
|
||||
const pos = position();
|
||||
if (pos !== null) onUngroup(pos);
|
||||
}),
|
||||
);
|
||||
};
|
||||
render(node);
|
||||
|
||||
const clearDropMark = () => {
|
||||
content.classList.remove('img-grid-dropping');
|
||||
content.removeAttribute('data-drop-index');
|
||||
};
|
||||
const dropIndexAt = (x: number, y: number): number => {
|
||||
const images = Array.from(content.querySelectorAll('img'));
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
const rect = images[i].getBoundingClientRect();
|
||||
if (y < rect.top + rect.height / 2 - 4) return i;
|
||||
if (y <= rect.bottom + 4 && x < rect.left + rect.width / 2) return i;
|
||||
}
|
||||
return images.length;
|
||||
};
|
||||
content.addEventListener('dragstart', (event) => {
|
||||
if (!editor.isEditable) return;
|
||||
const image = (event.target as HTMLElement | null)?.closest?.('img');
|
||||
const pos = position();
|
||||
if (!image || !content.contains(image) || pos === null) return;
|
||||
const index = Array.from(content.querySelectorAll('img')).indexOf(image as HTMLImageElement);
|
||||
if (index >= 0) storage.drag = { gridPos: pos, index };
|
||||
});
|
||||
content.addEventListener('dragover', (event) => {
|
||||
if (!storage.drag || !editor.isEditable) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
|
||||
content.classList.add('img-grid-dropping');
|
||||
content.setAttribute('data-drop-index', String(dropIndexAt(event.clientX, event.clientY)));
|
||||
});
|
||||
content.addEventListener('dragleave', (event) => {
|
||||
const to = event.relatedTarget as globalThis.Node | null;
|
||||
if (!to || !content.contains(to)) clearDropMark();
|
||||
});
|
||||
content.addEventListener('dragend', () => {
|
||||
storage.drag = null;
|
||||
clearDropMark();
|
||||
});
|
||||
content.addEventListener('drop', (event) => {
|
||||
const drag = storage.drag;
|
||||
if (!drag) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const toIndex = dropIndexAt(event.clientX, event.clientY);
|
||||
clearDropMark();
|
||||
storage.drag = null;
|
||||
const pos = position();
|
||||
if (pos !== null) onMoveImage(drag.gridPos, drag.index, pos, toIndex);
|
||||
});
|
||||
|
||||
return {
|
||||
dom,
|
||||
contentDOM: content,
|
||||
update(updated) {
|
||||
if (updated.type.name !== 'imageGrid') return false;
|
||||
render(updated);
|
||||
return true;
|
||||
},
|
||||
ignoreMutation(mutation) {
|
||||
if (mutation.type === 'selection') return false;
|
||||
return !content.contains(mutation.target);
|
||||
},
|
||||
stopEvent(event) {
|
||||
if (header.contains(event.target as globalThis.Node)) return true;
|
||||
// Grid reordering handles its own drops; ProseMirror would insert a second copy.
|
||||
return (event.type === 'drop' || event.type === 'dragover') && !!storage.drag
|
||||
&& content.contains(event.target as globalThis.Node);
|
||||
},
|
||||
destroy() {
|
||||
clearDropMark();
|
||||
},
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Command } from '@tiptap/core';
|
||||
import { TextSelection } from '@tiptap/pm/state';
|
||||
|
||||
/** Convert a top-level text selection as a unit; leave complex structures to Tiptap. */
|
||||
export function toggleSelectedCode(attributes: Record<string, unknown> = {}): Command {
|
||||
return ({ state, tr, dispatch, commands }) => {
|
||||
const { selection, schema } = state;
|
||||
if (selection.empty) return commands.toggleNode('codeBlock', 'paragraph', attributes);
|
||||
|
||||
const blocks: { node: typeof state.doc; pos: number }[] = [];
|
||||
state.doc.forEach((node, pos) => {
|
||||
if (pos < selection.to && pos + node.nodeSize > selection.from) blocks.push({ node, pos });
|
||||
});
|
||||
const supported = blocks.length > 0 && blocks.every(({ node }) => {
|
||||
if (node.type.name !== 'paragraph' && node.type.name !== 'codeBlock') return false;
|
||||
let valid = true;
|
||||
node.forEach((child) => { if (!child.isText && child.type.name !== 'hardBreak') valid = false; });
|
||||
return valid;
|
||||
});
|
||||
// Keep the existing single-paragraph behaviour and do not flatten lists, images, etc.
|
||||
if (!supported || (blocks.length === 1 && blocks[0].node.type.name !== 'codeBlock')) {
|
||||
return commands.toggleNode('codeBlock', 'paragraph', attributes);
|
||||
}
|
||||
|
||||
const allCode = blocks.every(({ node }) => node.type.name === 'codeBlock');
|
||||
const text = blocks.map(({ node }) => node.textBetween(0, node.content.size, '\n', '\n')).join('\n');
|
||||
const replacement = allCode
|
||||
? text.split('\n').map((line) => schema.nodes.paragraph.create(null, line ? schema.text(line) : null))
|
||||
: [schema.nodes.codeBlock.create(attributes, text ? schema.text(text) : null)];
|
||||
const from = blocks[0].pos;
|
||||
const last = blocks[blocks.length - 1];
|
||||
const to = last.pos + last.node.nodeSize;
|
||||
if (dispatch) {
|
||||
tr.replaceWith(from, to, replacement);
|
||||
const end = from + replacement.reduce((size, node) => size + node.nodeSize, 0);
|
||||
tr.setSelection(TextSelection.create(tr.doc, from + 1, end - 1));
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,24 @@
|
||||
import { Extension } from '@tiptap/core';
|
||||
import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state';
|
||||
import { getSelectionPair } from '../selectionPairs';
|
||||
import { Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state';
|
||||
import { getSelectionPair } from '../selectionPairs.ts';
|
||||
|
||||
/**
|
||||
* Wrap the selected text in the typed pair, or null to let the input through.
|
||||
*
|
||||
* ProseMirror reports every text change of the DOM here, not only keystrokes. A compose key
|
||||
* or dead key shows what has been typed so far as a preedit (`·`, then `'` for Compose ' e)
|
||||
* and replaces it at each step, which arrives as a quote replacing a non-empty range. Only
|
||||
* the user's own selection is wrapped: the range must be the selection, outside composition.
|
||||
*/
|
||||
export function wrapSelection(state: EditorState, from: number, to: number, text: string, composing = false): Transaction | null {
|
||||
const close = getSelectionPair(text);
|
||||
if (!close || from === to || composing) return null;
|
||||
const { selection } = state;
|
||||
if (selection.empty || selection.from !== from || selection.to !== to) return null;
|
||||
const tr = state.tr.insertText(close, to).insertText(text, from);
|
||||
tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));
|
||||
return tr;
|
||||
}
|
||||
|
||||
// TipTap/ProseMirror behavior for wrapping a non-empty rich-editor selection
|
||||
// without flattening selected inline marks or content to plain text.
|
||||
@@ -12,14 +30,11 @@ export const WrapSelectedText = Extension.create({
|
||||
new Plugin({
|
||||
key: new PluginKey('wrapSelectedText'),
|
||||
props: {
|
||||
// Intercept only supported single-character text input over a range.
|
||||
// Intercept only supported single-character text input over the selection.
|
||||
// Everything else falls back to ProseMirror's normal input handling.
|
||||
handleTextInput(view, from, to, text) {
|
||||
const close = getSelectionPair(text);
|
||||
if (!close || from === to) return false;
|
||||
|
||||
const tr = view.state.tr.insertText(close, to).insertText(text, from);
|
||||
tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));
|
||||
const tr = wrapSelection(view.state, from, to, text, view.composing);
|
||||
if (!tr) return false;
|
||||
view.dispatch(tr);
|
||||
return true;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { markdownLanguage } from '@codemirror/lang-markdown';
|
||||
import { splitSnapshot } from '../utils/history-comparison.ts';
|
||||
import { createEditorMarkdownParser, displayMathRanges, inlineMathRanges, legacyLinkRanges } from './markdownParser.ts';
|
||||
|
||||
export interface ExternalNoteReference {
|
||||
from: number;
|
||||
to: number;
|
||||
href: string;
|
||||
html: boolean;
|
||||
pdf?: boolean;
|
||||
}
|
||||
|
||||
const markdown = createEditorMarkdownParser();
|
||||
// The editor never treats indented text as a code block, so an indented image is still an image here.
|
||||
const editorSyntax = (markdownLanguage.parser as unknown as {
|
||||
configure(spec: { remove: string[] }): typeof markdownLanguage.parser;
|
||||
}).configure({ remove: ['IndentedCode'] });
|
||||
|
||||
/** Byte ranges for local attachment destinations, without reserializing the user's Markdown. */
|
||||
export function externalNoteReferences(raw: string): ExternalNoteReference[] {
|
||||
const { body, metadata } = splitSnapshot(raw);
|
||||
const spans: ExternalNoteReference[] = [];
|
||||
const seen = new Set<string>();
|
||||
const legacy = legacyLinkRanges(body);
|
||||
const legacyByStart = new Map(legacy.map(range => [range.from, range]));
|
||||
const math = [...displayMathRanges(body), ...inlineMathRanges(body)];
|
||||
const environment: { references?: Record<string, { href: string }> } = {};
|
||||
markdown.parse(body, environment);
|
||||
const tree = editorSyntax.parse(body);
|
||||
const usedLabels = new Set<string>();
|
||||
const label = (node: { from: number; to: number }) => markdown.utils.normalizeReference(body.slice(node.from + 1, node.to - 1));
|
||||
tree.iterate({ enter(node) {
|
||||
if (!['Link', 'Image'].includes(node.name) || node.node.getChild('URL') || body[node.to] === '(' || math.some(range => node.from >= range.from && node.from < range.to)) return;
|
||||
for (let parent = node.node.parent; parent; parent = parent.parent) if (parent.name === 'Image') return false;
|
||||
const explicit = node.node.getChild('LinkLabel');
|
||||
let key = explicit ? label(explicit) : '';
|
||||
if (!key) {
|
||||
const closing = node.node.getChildren('LinkMark').find(mark => body.slice(mark.from, mark.to) === ']');
|
||||
if (closing) key = markdown.utils.normalizeReference(body.slice(node.from + (node.name === 'Image' ? 2 : 1), closing.from));
|
||||
}
|
||||
if (environment.references?.[key]) usedLabels.add(key);
|
||||
} });
|
||||
const selectedDefinitions = new Set<string>();
|
||||
const add = (from: number, to: number, html = false, pdf = false) => {
|
||||
if (math.some(range => from >= range.from && from < range.to)) return;
|
||||
const href = markdown.utils.unescapeAll(body.slice(from, to));
|
||||
let path = href.split(/[?#]/, 1)[0];
|
||||
try { path = decodeURIComponent(path); } catch { /* Native validation handles malformed escapes. */ }
|
||||
if (!path || /^[a-z][a-z\d+.-]*:/i.test(path) || /^[\\/]/.test(path) || /\.md$/i.test(path)) return;
|
||||
const key = `${from}:${to}`;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
spans.push({ from: metadata.length + from, to: metadata.length + to, href, html, pdf });
|
||||
};
|
||||
tree.iterate({
|
||||
enter(node) {
|
||||
// Links and HTML inside image alt text are labels, not additional attachments.
|
||||
let direct = true;
|
||||
for (let ancestor = node.node.parent; ancestor; ancestor = ancestor.parent) {
|
||||
if (ancestor.name === 'Image' && !(node.name === 'URL' && direct)) return false;
|
||||
direct = false;
|
||||
}
|
||||
if (node.name === 'URL' && ['Image', 'Link', 'LinkReference'].includes(node.node.parent?.name ?? '')) {
|
||||
const angle = body[node.from] === '<' && body[node.to - 1] === '>';
|
||||
const from = node.from + (angle ? 1 : 0);
|
||||
if (node.node.parent?.name === 'LinkReference') {
|
||||
const definition = node.node.parent.getChild('LinkLabel');
|
||||
if (!definition) return;
|
||||
const key = label(definition);
|
||||
const href = markdown.normalizeLink(markdown.utils.unescapeAll(body.slice(from, node.to - (angle ? 1 : 0))));
|
||||
if (!usedLabels.has(key) || selectedDefinitions.has(key) || environment.references?.[key]?.href !== href) return;
|
||||
selectedDefinitions.add(key);
|
||||
}
|
||||
const compatible = legacyByStart.get(from);
|
||||
add(from, compatible?.to ?? node.to - (angle ? 1 : 0));
|
||||
} else if (node.name === 'Paragraph' || /Heading[1-6]$/.test(node.name)) {
|
||||
for (const range of legacy) {
|
||||
if (range.from >= node.from && range.to <= node.to) add(range.from, range.to);
|
||||
}
|
||||
} else if (node.name === 'HTMLTag' || node.name === 'HTMLBlock') {
|
||||
const html = body.slice(node.from, node.to);
|
||||
// Skip comments and literal HTML code, not just Markdown fences.
|
||||
const tags = /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|pre|code)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)|<(img|a|div)\b(?:"[^"]*"|'[^']*'|[^'">])*>/gi;
|
||||
for (const tag of html.matchAll(tags)) {
|
||||
if (!tag[2]) continue;
|
||||
const attributes = /(?:^|\s)([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
|
||||
for (const attribute of tag[0].matchAll(attributes)) {
|
||||
const name = attribute[1].toLowerCase();
|
||||
const element = tag[2].toLowerCase();
|
||||
if (!(element === 'img' && name === 'src') && !(element === 'a' && name === 'href') && !(element === 'div' && name === 'data-pdf-src')) continue;
|
||||
const value = attribute[2] ?? attribute[3] ?? attribute[4];
|
||||
const quoted = attribute[2] !== undefined || attribute[3] !== undefined;
|
||||
const start = node.from + tag.index! + attribute.index! + attribute[0].length - value.length - (quoted ? 1 : 0);
|
||||
add(start, start + value.length, true, name === 'data-pdf-src');
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
spans.sort((a, b) => a.from - b.from);
|
||||
const encoder = new TextEncoder();
|
||||
let previous = 0;
|
||||
let bytes = 0;
|
||||
return spans.map(span => {
|
||||
bytes += encoder.encode(raw.slice(previous, span.from)).length;
|
||||
const from = bytes;
|
||||
bytes += encoder.encode(raw.slice(span.from, span.to)).length;
|
||||
previous = span.to;
|
||||
return { ...span, from, to: bytes };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Side-by-side / grid / masonry layout for images (#254).
|
||||
*
|
||||
* Portable syntax: a `:::` container whose lines are ordinary Markdown images. Other renderers
|
||||
* (GitHub, Typora, ...) show the images stacked, plus the literal header and closer lines.
|
||||
*
|
||||
* :::img-grid cols=3 masonry
|
||||
* 
|
||||
* 
|
||||
* :::
|
||||
*
|
||||
* Header: `:::img-grid`, optionally followed by `cols=2|3|4` and `masonry` / `grid` (also written
|
||||
* `layout=masonry` / `layout=grid`), in any order.
|
||||
* Body: one image per line. The closer is `:::` on its own line, or trailing the last image
|
||||
* (` :::`).
|
||||
*
|
||||
* Content is never partially converted. If any part of the block isn't understood (an unknown
|
||||
* option, a caption, a linked image, a blank line, a missing closer), the block is left as
|
||||
* ordinary Markdown. The parsing itself is a markdown-it block rule (`markdownParser.ts`), so a
|
||||
* grid example inside a code block is never converted.
|
||||
*/
|
||||
|
||||
export type ImgGridLayout = 'grid' | 'masonry';
|
||||
|
||||
export interface ImgGridAttrs {
|
||||
cols: number;
|
||||
layout: ImgGridLayout;
|
||||
}
|
||||
|
||||
export const IMG_GRID_MIN_COLS = 2;
|
||||
export const IMG_GRID_MAX_COLS = 4;
|
||||
export const IMG_GRID_DEFAULT_COLS = 2;
|
||||
export const IMG_GRID_CLOSER = ':::';
|
||||
|
||||
/** Clamp a column count from node attributes or the DOM into the supported range. */
|
||||
export function clampImgGridCols(value: unknown): number {
|
||||
const n = typeof value === 'string' ? parseInt(value, 10) : (value as number);
|
||||
if (!Number.isFinite(n)) return IMG_GRID_DEFAULT_COLS;
|
||||
return Math.min(IMG_GRID_MAX_COLS, Math.max(IMG_GRID_MIN_COLS, Math.floor(n)));
|
||||
}
|
||||
|
||||
export function normalizeImgGridLayout(value: unknown): ImgGridLayout {
|
||||
return value === 'masonry' ? 'masonry' : 'grid';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a `:::img-grid ...` header line (already stripped of container indentation), or null.
|
||||
* Any unknown or out-of-range option makes the whole line not a header, so it stays literal text
|
||||
* instead of being silently rewritten.
|
||||
*/
|
||||
export function parseImgGridHeader(line: string): ImgGridAttrs | null {
|
||||
const match = /^:::img-grid(?:[ \t]+(.*?))?[ \t]*$/.exec(line);
|
||||
if (!match) return null;
|
||||
let cols: number | null = null;
|
||||
let layout: ImgGridLayout | null = null;
|
||||
for (const token of (match[1] ?? '').split(/[ \t]+/).filter(Boolean)) {
|
||||
const colsMatch = /^cols=(\d)$/.exec(token);
|
||||
const layoutMatch = /^(?:layout=)?(grid|masonry)$/.exec(token);
|
||||
if (colsMatch && cols === null) {
|
||||
const n = Number(colsMatch[1]);
|
||||
if (n < IMG_GRID_MIN_COLS || n > IMG_GRID_MAX_COLS) return null;
|
||||
cols = n;
|
||||
} else if (layoutMatch && layout === null) {
|
||||
layout = layoutMatch[1] as ImgGridLayout;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return { cols: cols ?? IMG_GRID_DEFAULT_COLS, layout: layout ?? 'grid' };
|
||||
}
|
||||
|
||||
/** Canonical header for saving. Defaults are omitted: `:::img-grid`, `:::img-grid cols=3 masonry`. */
|
||||
export function serializeImgGridHeader(attrs: ImgGridAttrs): string {
|
||||
const cols = clampImgGridCols(attrs.cols);
|
||||
const options = [
|
||||
cols !== IMG_GRID_DEFAULT_COLS ? `cols=${cols}` : '',
|
||||
normalizeImgGridLayout(attrs.layout) === 'masonry' ? 'masonry' : '',
|
||||
].filter(Boolean);
|
||||
return [':::img-grid', ...options].join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole grid block for saving. `images` is the Markdown of the grid's images, one per line, as the
|
||||
* editor serializes inline images. Returns '' when there is nothing to save, so a grid whose images
|
||||
* all failed to resolve doesn't leave behind a header that would no longer parse.
|
||||
*/
|
||||
export function serializeImgGrid(attrs: ImgGridAttrs, images: string): string {
|
||||
const body = images.replace(/\n+$/, '');
|
||||
if (!body.trim()) return '';
|
||||
return `${serializeImgGridHeader(attrs)}\n${body}\n${IMG_GRID_CLOSER}\n`;
|
||||
}
|
||||
|
||||
/** Split a trailing ` :::` closer off the last image line: ` :::` gives ``. */
|
||||
export function splitTrailingCloser(line: string): string | null {
|
||||
const match = /^(.*\S)[ \t]+:::[ \t]*$/.exec(line);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/** New grids get one column per image, within 2 to 4. */
|
||||
export function defaultGridCols(imageCount: number): number {
|
||||
return clampImgGridCols(imageCount);
|
||||
}
|
||||
|
||||
/** One top-level block, for grouping neighboring images into a grid. */
|
||||
export interface ImageBlockInfo {
|
||||
isImage: boolean;
|
||||
imageCount: number;
|
||||
/** An empty paragraph. One of these before an image is how the editor holds the blank line above it. */
|
||||
isEmpty?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow from `target` across neighboring image-only blocks (image paragraphs and existing grids).
|
||||
* Images a blank line apart load with one empty paragraph between them, so a single empty paragraph
|
||||
* between two image blocks is part of the range, and so is the one directly above the first image:
|
||||
* left behind, it would be saved as an empty-paragraph marker above the grid.
|
||||
* Returns the block range and its image total, or null unless it holds at least two images.
|
||||
*/
|
||||
export function expandImageRange(
|
||||
blocks: readonly ImageBlockInfo[],
|
||||
target: number,
|
||||
): { start: number; end: number; total: number } | null {
|
||||
if (target < 0 || target >= blocks.length || !blocks[target].isImage) return null;
|
||||
const isImage = (index: number) => index >= 0 && index < blocks.length && blocks[index].isImage;
|
||||
const isEmpty = (index: number) => index >= 0 && index < blocks.length && !!blocks[index].isEmpty;
|
||||
let start = target;
|
||||
let end = target;
|
||||
for (;;) {
|
||||
if (isImage(start - 1)) start -= 1;
|
||||
else if (isEmpty(start - 1) && isImage(start - 2)) start -= 2;
|
||||
else break;
|
||||
}
|
||||
for (;;) {
|
||||
if (isImage(end + 1)) end += 1;
|
||||
else if (isEmpty(end + 1) && isImage(end + 2)) end += 2;
|
||||
else break;
|
||||
}
|
||||
let total = 0;
|
||||
for (let i = start; i <= end; i++) total += blocks[i].imageCount;
|
||||
if (total < 2) return null;
|
||||
if (isEmpty(start - 1)) start -= 1;
|
||||
return { start, end, total };
|
||||
}
|
||||
|
||||
/**
|
||||
* Index an item ends up at when it is dragged from `from` and dropped before slot `to` of the same
|
||||
* list (`to` counts slots in the list before removal, 0..length). Returns null for a no-op drop.
|
||||
*/
|
||||
export function reorderTarget(from: number, to: number, length: number): number | null {
|
||||
if (from < 0 || from >= length) return null;
|
||||
const target = Math.max(0, Math.min(length - 1, to > from ? to - 1 : to));
|
||||
return target === from ? null : target;
|
||||
}
|
||||
+397
-24
@@ -11,6 +11,111 @@ type MarkdownMark = {
|
||||
|
||||
const identityAssetSource: AssetSourceNormalizer = (source) => source;
|
||||
|
||||
function backtickDelimiter(text: string, minimum: number): string {
|
||||
let length = minimum;
|
||||
for (const match of text.matchAll(/`+/g)) {
|
||||
length = Math.max(length, match[0].length + 1);
|
||||
}
|
||||
return '`'.repeat(length);
|
||||
}
|
||||
|
||||
export interface MarkdownBlock {
|
||||
text: string;
|
||||
isImage: boolean;
|
||||
/** An empty paragraph, which is kept as a marker line so its vertical space round-trips. */
|
||||
isEmpty?: boolean;
|
||||
}
|
||||
|
||||
const EMPTY_PARAGRAPH_MARKER = '<!-- -->';
|
||||
|
||||
/**
|
||||
* ` "title"` suffix for an image destination, or '' without a title. Uses CommonMark backslash
|
||||
* escapes, which the parser undoes exactly, so a title survives any number of saves unchanged.
|
||||
* `&` is only escaped where it would otherwise read as an entity (`&`, `&`).
|
||||
*/
|
||||
export function serializeImageTitle(title: string | null | undefined): string {
|
||||
if (!title) return '';
|
||||
return ` "${title.replace(/[\\"]/g, '\\$&').replace(/&(?=#?[a-z0-9]+;)/gi, '\\&')}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join serialized top-level blocks into a note body. Blocks that already end in a blank line
|
||||
* (lists) get no extra separator, and an empty paragraph directly before an image is written as
|
||||
* the blank line the parser turns back into that paragraph, not as a marker glued to the image.
|
||||
*/
|
||||
export function joinMarkdownBlocks(blocks: readonly MarkdownBlock[]): string {
|
||||
const entries = [...blocks];
|
||||
while (entries.length > 0 && entries[entries.length - 1].isEmpty) entries.pop();
|
||||
const parts: string[] = [];
|
||||
// Only the last two characters decide the separator. Reading them from the growing result would
|
||||
// flatten it on every block, which makes joining a large note quadratic.
|
||||
let tail = '';
|
||||
const append = (piece: string) => {
|
||||
parts.push(piece);
|
||||
tail = (tail + piece).slice(-2);
|
||||
};
|
||||
entries.forEach((entry, index) => {
|
||||
if (entry.isEmpty && entries[index + 1]?.isImage) {
|
||||
if (index > 0 && tail !== '\n\n') append(tail.endsWith('\n') ? '\n' : '\n\n');
|
||||
return;
|
||||
}
|
||||
const text = entry.isEmpty ? EMPTY_PARAGRAPH_MARKER : entry.text;
|
||||
// Images follow their predecessor directly; every other block needs a blank line before it.
|
||||
if (index === 0) append(text);
|
||||
else append((entry.isImage || tail === '\n\n' ? '' : '\n') + text);
|
||||
});
|
||||
return parts.join('').trim() + '\n';
|
||||
}
|
||||
|
||||
export interface ListItemBlock {
|
||||
text: string;
|
||||
/** A nested bullet, numbered or task list. */
|
||||
isList: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join the serialized children of one list item. The first block follows the list marker; a nested
|
||||
* list is indented four spaces directly under it; any other block (a further paragraph, a code
|
||||
* block, a quote) is separated by a blank line and indented the same way so it stays in the item.
|
||||
*/
|
||||
export function joinListItemBlocks(blocks: readonly ListItemBlock[]): string {
|
||||
const parts: string[] = [];
|
||||
blocks.forEach((block, index) => {
|
||||
if (block.isList) {
|
||||
// A serialized list ends with a blank line; left in, it became an indented blank line here
|
||||
// and an extra empty line after the outer list.
|
||||
parts.push(block.text.replace(/\n+$/, '').split('\n').map((line) => (line ? ' ' + line : line)).join('\n'));
|
||||
} else if (index === 0) {
|
||||
parts.push(block.text);
|
||||
} else {
|
||||
const body = block.text.replace(/\n+$/, '');
|
||||
if (body.trim() === '') return;
|
||||
parts.push('', body.split('\n').map((line) => (line ? ' ' + line : line)).join('\n'));
|
||||
}
|
||||
});
|
||||
return parts.join('\n') + '\n';
|
||||
}
|
||||
|
||||
export function serializeCodeBlock(code: string, language: string = ''): string {
|
||||
const fence = backtickDelimiter(code, 3);
|
||||
return `${fence}${language}\n${code}\n${fence}\n`;
|
||||
}
|
||||
|
||||
function serializeCodeSpan(text: string): string {
|
||||
const delimiter = backtickDelimiter(text, 1);
|
||||
const needsPadding = text.startsWith('`') || text.endsWith('`')
|
||||
|| ((text.startsWith(' ') || text.endsWith(' ')) && /[^ ]/.test(text));
|
||||
const padding = needsPadding ? ' ' : '';
|
||||
return `${delimiter}${padding}${text}${padding}${delimiter}`;
|
||||
}
|
||||
|
||||
function serializeInlineMath(tex: string, forceEncoded: boolean): string {
|
||||
if (forceEncoded || !tex || /[\r\n$]/.test(tex) || /^\s|\s$/.test(tex) || /(?:^|[^\\])(?:\\\\)*\\$/.test(tex)) {
|
||||
return `<span data-math-inline="${encodeURIComponent(tex)}" class="math-inline"></span>`;
|
||||
}
|
||||
return `$${tex}$`;
|
||||
}
|
||||
|
||||
function stringAttr(mark: Mark, name: string): string {
|
||||
const value = mark.attrs?.[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
@@ -52,15 +157,14 @@ function markdownMark(mark: Mark, text: string): MarkdownMark | null {
|
||||
}
|
||||
: null;
|
||||
}
|
||||
case 'code':
|
||||
return { key: 'code', priority: 90, open: '`', close: '`' };
|
||||
case 'link': {
|
||||
const href = stringAttr(mark, 'href');
|
||||
const title = stringAttr(mark, 'title');
|
||||
return {
|
||||
key: `link:${href}`,
|
||||
key: `link:${href}:${title}`,
|
||||
priority: 100,
|
||||
open: '[',
|
||||
close: `](${href})`,
|
||||
close: `](${href}${serializeImageTitle(title)})`,
|
||||
};
|
||||
}
|
||||
case 'wikiLink': {
|
||||
@@ -78,8 +182,35 @@ function markdownMark(mark: Mark, text: string): MarkdownMark | null {
|
||||
}
|
||||
}
|
||||
|
||||
function marksForText(node: ProseMirrorNode): MarkdownMark[] {
|
||||
const escapeAttribute = (value: string) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
||||
|
||||
/**
|
||||
* Markdown for an image. One with a width or height (from HTML such as `<img width="80">`) is
|
||||
* written as HTML again, since Markdown images have no size.
|
||||
*/
|
||||
export function serializeImage(node: ProseMirrorNode, source: string): string {
|
||||
const alt = node.attrs.alt || '';
|
||||
const size = node.attrs['data-size'] || node.attrs.size || 'full';
|
||||
const width = String(node.attrs.width ?? '').trim();
|
||||
const height = String(node.attrs.height ?? '').trim();
|
||||
if (width || height) {
|
||||
const attributes = [
|
||||
`src="${escapeAttribute(source)}"`,
|
||||
`alt="${escapeAttribute(alt)}"`,
|
||||
node.attrs.title ? `title="${escapeAttribute(node.attrs.title)}"` : '',
|
||||
width ? `width="${escapeAttribute(width)}"` : '',
|
||||
height ? `height="${escapeAttribute(height)}"` : '',
|
||||
size && size !== 'full' ? `data-size="${escapeAttribute(size)}"` : '',
|
||||
].filter(Boolean);
|
||||
return `<img ${attributes.join(' ')}>`;
|
||||
}
|
||||
const sizeSuffix = size && size !== 'full' ? `|size=${size}` : '';
|
||||
return `})`;
|
||||
}
|
||||
|
||||
function marksForText(node: ProseMirrorNode, linksOnly = false): MarkdownMark[] {
|
||||
return node.marks
|
||||
.filter((mark) => !linksOnly || mark.type.name === 'link' || mark.type.name === 'wikiLink')
|
||||
.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));
|
||||
@@ -92,52 +223,294 @@ function commonMarkCount(active: MarkdownMark[], next: MarkdownMark[]): number {
|
||||
return index;
|
||||
}
|
||||
|
||||
export interface InlineSerializeOptions {
|
||||
/** Leave `$` unescaped (only backslashes before it are doubled); callers must check it cannot form math. */
|
||||
literalDollars?: boolean;
|
||||
/** Rewrites the text of a plain (non-code) text child before it is written; see `literalTextEscapes`. */
|
||||
literalText?: (text: string, childIndex: number) => string;
|
||||
}
|
||||
|
||||
export function serializeInlineMarkdown(
|
||||
node: ProseMirrorNode,
|
||||
normalizeAssetSource: AssetSourceNormalizer = identityAssetSource,
|
||||
options: InlineSerializeOptions = {},
|
||||
): string {
|
||||
let result = '';
|
||||
let activeMarks: MarkdownMark[] = [];
|
||||
// Length of `result` right after each active mark was opened, to tell when a mark holds nothing.
|
||||
let openEnds: number[] = [];
|
||||
|
||||
// `**word **` is not emphasis in Markdown: delimiters must touch the text they wrap. Spaces at the
|
||||
// edges of bold, italic and similar marks are therefore written outside the delimiters, and a mark
|
||||
// that covers only spaces is not written at all.
|
||||
const isDelimiter = (mark: MarkdownMark) => mark.open === mark.close && !mark.open.startsWith('<');
|
||||
|
||||
const transitionMarks = (nextMarks: MarkdownMark[]) => {
|
||||
const shared = commonMarkCount(activeMarks, nextMarks);
|
||||
for (let index = activeMarks.length - 1; index >= shared; index -= 1) {
|
||||
result += activeMarks[index].close;
|
||||
let trailing = '';
|
||||
if (activeMarks.slice(shared).some(isDelimiter)) {
|
||||
trailing = result.match(/[ \t\u00a0]+$/)?.[0] ?? '';
|
||||
if (trailing) result = result.slice(0, -trailing.length);
|
||||
}
|
||||
for (let index = activeMarks.length - 1; index >= shared; index -= 1) {
|
||||
const mark = activeMarks[index];
|
||||
if (isDelimiter(mark) && result.length === openEnds[index]) result = result.slice(0, result.length - mark.open.length);
|
||||
else result += mark.close;
|
||||
}
|
||||
result += trailing;
|
||||
openEnds = openEnds.slice(0, shared);
|
||||
for (let index = shared; index < nextMarks.length; index += 1) {
|
||||
result += nextMarks[index].open;
|
||||
openEnds.push(result.length);
|
||||
}
|
||||
activeMarks = nextMarks;
|
||||
};
|
||||
|
||||
node.forEach((child, _offset, index) => {
|
||||
for (let index = 0; index < node.childCount; index += 1) {
|
||||
const child = node.child(index);
|
||||
if (child.isText) {
|
||||
transitionMarks(marksForText(child));
|
||||
const isCode = child.marks.some((mark) => mark.type.name === 'code');
|
||||
let text = child.text || '';
|
||||
if (index === 0) {
|
||||
text = text.replace(/^[\t\u2003]+/, (whitespace) => ' '.repeat(whitespace.length));
|
||||
if (isCode) {
|
||||
// One code span per run of code text under the same link. Formatting that covers the whole
|
||||
// run is written around the span (**`code`**); formatting on only part of it is dropped,
|
||||
// since it cannot be written inside a code span.
|
||||
const links = marksForText(child, true);
|
||||
let marks = marksForText(child);
|
||||
while (index + 1 < node.childCount) {
|
||||
const next = node.child(index + 1);
|
||||
if (!next.isText || !next.marks.some((mark) => mark.type.name === 'code')) break;
|
||||
const nextLinks = marksForText(next, true);
|
||||
if (links.length !== nextLinks.length || commonMarkCount(links, nextLinks) !== links.length) break;
|
||||
const nextKeys = new Set(marksForText(next).map((mark) => mark.key));
|
||||
marks = marks.filter((mark) => nextKeys.has(mark.key));
|
||||
text += next.text || '';
|
||||
index += 1;
|
||||
}
|
||||
// Delimiters next to a code span sit between punctuation (the backtick) and the neighbor:
|
||||
// `**\`x\`**s` is not emphasis when a letter or digit follows, nor `a**\`x\`**` when one
|
||||
// precedes. Formatting that would open or close against such a neighbor is dropped.
|
||||
const after = index + 1 < node.childCount ? node.child(index + 1) : null;
|
||||
const afterKeys = new Set(after?.isText ? marksForText(after).map((mark) => mark.key) : []);
|
||||
const wordAfter = /^[\p{L}\p{N}_]/u.test(after?.isText ? after.text || '' : '');
|
||||
const wordBefore = /[\p{L}\p{N}_]$/u.test(result);
|
||||
marks = marks.filter((mark) => !isDelimiter(mark)
|
||||
|| !((wordAfter && !afterKeys.has(mark.key)) || (wordBefore && !activeMarks.some((active) => active.key === mark.key))));
|
||||
transitionMarks(marks);
|
||||
result += serializeCodeSpan(text);
|
||||
} else {
|
||||
if (options.literalText) text = options.literalText(text, index);
|
||||
if (index === 0) {
|
||||
text = text.replace(/^[\t\u2003]+/, (whitespace) => ' '.repeat(whitespace.length));
|
||||
}
|
||||
const marks = marksForText(child);
|
||||
const shared = commonMarkCount(activeMarks, marks);
|
||||
const leading = marks.slice(shared).some(isDelimiter) ? text.match(/^[ \t\u00a0]+/)?.[0] ?? '' : '';
|
||||
if (leading) {
|
||||
// Spaces before newly opened delimiters stay outside them.
|
||||
transitionMarks(marks.slice(0, shared));
|
||||
result += leading;
|
||||
text = text.slice(leading.length);
|
||||
if (!text) continue;
|
||||
}
|
||||
transitionMarks(marks);
|
||||
text = options.literalDollars
|
||||
? text.replace(/\\+(?=\$)/g, (backslashes) => backslashes + backslashes)
|
||||
: text.replace(/\\*\$/g, (match) => '\\'.repeat((match.length - 1) * 2 + 1) + '$');
|
||||
if (index + 1 < node.childCount && node.child(index + 1).type.name === 'mathInline') {
|
||||
text = text.replace(/\\+$/, (backslashes) => backslashes + backslashes);
|
||||
}
|
||||
result += text;
|
||||
}
|
||||
result += text;
|
||||
return;
|
||||
continue;
|
||||
}
|
||||
|
||||
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 += ``;
|
||||
} else if (child.type.name === 'mathInline') {
|
||||
result += `$${child.attrs.tex || ''}$`;
|
||||
if (!source) continue;
|
||||
// An image can sit inside a link (`[](https://site)`); other formatting closes.
|
||||
transitionMarks(marksForText(child, true));
|
||||
// Images go on their own line, except right after the link around them opens.
|
||||
if (result && result.length !== openEnds[openEnds.length - 1]) result += '\n';
|
||||
result += serializeImage(child, source);
|
||||
continue;
|
||||
}
|
||||
transitionMarks([]);
|
||||
if (child.type.name === 'mathInline') {
|
||||
const previous = index > 0 ? node.child(index - 1) : null;
|
||||
const next = index + 1 < node.childCount ? node.child(index + 1) : null;
|
||||
const forceEncoded = previous?.type.name === 'mathInline' || next?.type.name === 'mathInline'
|
||||
|| /\$$/.test(previous?.text || '') || /^[\d$]/.test(next?.text || '');
|
||||
result += serializeInlineMath(child.attrs.tex || '', forceEncoded);
|
||||
} else if (child.type.name === 'hardBreak') {
|
||||
result += ' \n';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
transitionMarks([]);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---- Keeping plain text plain
|
||||
// Text in the editor is literal: `*not italic*`, `<b>` or `&` typed or loaded as text must come
|
||||
// back as the same text. Written as they are, such characters can turn into formatting, HTML or an
|
||||
// entity on the next load. They are escaped with a backslash, but only where the parser would
|
||||
// otherwise read them differently, so ordinary notes are written exactly as before.
|
||||
|
||||
/**
|
||||
* Characters that can start or end inline formatting, HTML or an entity in the place they stand.
|
||||
* Cheap: no parsing. Brackets are left out on purpose: text that reads as a link or an image is
|
||||
* left to become one, as it always has (images damaged by an old save bug come back that way).
|
||||
*/
|
||||
const LITERAL_BACKSLASH = /\\(?=[!-#%-/:-@[-`{-~])/g;
|
||||
const LITERAL_DELIMITER = /[*`~^_]|<(?=[A-Za-z/!?])|&(?=#?[A-Za-z0-9]+;)|=(?==)/g;
|
||||
const LITERAL_CANDIDATE = /\\(?=[!-#%-/:-@[-`{-~])|[*`~^]|(?:^|[^\p{L}\p{N}])_|_(?![\p{L}\p{N}])|<(?=[A-Za-z/!?])|&(?=#?[A-Za-z0-9]+;)|==/u;
|
||||
const MAX_MINIMIZED_ESCAPES = 40;
|
||||
|
||||
/** Reads a string of inline Markdown back and returns the text it shows (formatting removed). */
|
||||
export type InlinePlainText = (markdown: string) => string;
|
||||
|
||||
const squash = (text: string) => text.replace(/[\s\u00a0\u2003]+/g, '');
|
||||
|
||||
/** A literal backslash before punctuation would be read as an escape, so it is always doubled. */
|
||||
function escapeBackslashes(text: string): string {
|
||||
return text.replace(LITERAL_BACKSLASH, '\\$&');
|
||||
}
|
||||
|
||||
function escapeEveryCandidate(text: string): string {
|
||||
return escapeBackslashes(text).replace(LITERAL_DELIMITER, '\\$&');
|
||||
}
|
||||
|
||||
/** The fewest backslashes that make `text`, on its own, read back as itself. */
|
||||
function escapeWhereNeeded(raw: string, plainText: InlinePlainText): string {
|
||||
const wanted = squash(raw);
|
||||
if (squash(plainText(raw)) === wanted) return raw;
|
||||
const text = escapeBackslashes(raw);
|
||||
if (squash(plainText(text)) === wanted) return text;
|
||||
const positions: number[] = [];
|
||||
for (const match of text.matchAll(LITERAL_DELIMITER)) positions.push(match.index);
|
||||
const build = (escaped: ReadonlySet<number>) => {
|
||||
let result = '';
|
||||
let from = 0;
|
||||
for (const position of positions) {
|
||||
if (!escaped.has(position)) continue;
|
||||
result += text.slice(from, position) + '\\';
|
||||
from = position;
|
||||
}
|
||||
return result + text.slice(from);
|
||||
};
|
||||
const escaped = new Set(positions);
|
||||
if (positions.length > MAX_MINIMIZED_ESCAPES) return build(escaped);
|
||||
// Last to first, so the backslashes that stay are the leading ones (`\\*not italic*`).
|
||||
for (const position of [...positions].reverse()) {
|
||||
escaped.delete(position);
|
||||
if (squash(plainText(build(escaped))) !== wanted) escaped.add(position);
|
||||
}
|
||||
return build(escaped);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides how the plain text children of `node` must be escaped so the whole line reads back as
|
||||
* the same text, and returns that as a `literalText` option (undefined when nothing needs it).
|
||||
* Tries the unescaped form first, then each text child fixed on its own, then every candidate
|
||||
* escaped; if even that does not read back, the line is left as it was written before.
|
||||
*/
|
||||
export function literalTextEscapes(
|
||||
node: ProseMirrorNode,
|
||||
normalizeAssetSource: AssetSourceNormalizer,
|
||||
plainText: InlinePlainText,
|
||||
): InlineSerializeOptions['literalText'] {
|
||||
// Nodes are immutable and reused between saves, so each line is judged once, not on every save.
|
||||
const known = literalDecisions.get(node);
|
||||
if (known) return known === 'none' ? undefined : known;
|
||||
const decision = decideLiteralText(node, normalizeAssetSource, plainText);
|
||||
literalDecisions.set(node, decision ?? 'none');
|
||||
return decision;
|
||||
}
|
||||
|
||||
const literalDecisions = new WeakMap<ProseMirrorNode, NonNullable<InlineSerializeOptions['literalText']> | 'none'>();
|
||||
|
||||
function decideLiteralText(
|
||||
node: ProseMirrorNode,
|
||||
normalizeAssetSource: AssetSourceNormalizer,
|
||||
plainText: InlinePlainText,
|
||||
): InlineSerializeOptions['literalText'] {
|
||||
let wanted = '';
|
||||
let plain = '';
|
||||
let formatted = false;
|
||||
node.forEach((child) => {
|
||||
if (!child.isText) return;
|
||||
wanted += child.text || '';
|
||||
if (child.marks.length) formatted = true;
|
||||
if (!child.marks.some((mark) => mark.type.name === 'code')) plain += (child.text || '') + '\n';
|
||||
});
|
||||
if (!LITERAL_CANDIDATE.test(plain)) return undefined;
|
||||
// Without formatting on the line, a delimiter needs a partner of its own kind to mean anything:
|
||||
// one `*`, `_`, `~`, `^` or backtick on its own stays text. This spares most lines the check.
|
||||
if (!formatted && !/\\(?=[!-#%-/:-@[-`{-~])|<(?=[A-Za-z/!?])|&(?=#?[A-Za-z0-9]+;)|==[^]*==/.test(plain)
|
||||
&& !/\*[^]*\*|_[^]*_|`[^]*`|~[^]*~|\^[^]*\^/.test(plain)) return undefined;
|
||||
wanted = squash(wanted);
|
||||
const readsBack = (literalText?: InlineSerializeOptions['literalText']) =>
|
||||
squash(plainText(serializeInlineMarkdown(node, normalizeAssetSource, { literalText }))) === wanted;
|
||||
if (readsBack()) return undefined;
|
||||
const minimal = new Map<string, string>();
|
||||
const each: InlineSerializeOptions['literalText'] = (text) => {
|
||||
if (!LITERAL_CANDIDATE.test(text)) return text;
|
||||
if (!minimal.has(text)) minimal.set(text, escapeWhereNeeded(text, plainText));
|
||||
return minimal.get(text)!;
|
||||
};
|
||||
if (readsBack(each)) return each;
|
||||
const all: InlineSerializeOptions['literalText'] = (text) => escapeEveryCandidate(text);
|
||||
return readsBack(all) ? all : undefined;
|
||||
}
|
||||
|
||||
/** Whether a serialized paragraph is still read as one paragraph. */
|
||||
export type ReadsAsParagraph = (markdown: string) => boolean;
|
||||
|
||||
/** Whether the note, as last loaded or saved, has this line (compared without indentation). */
|
||||
export type InNoteSource = (line: string) => boolean;
|
||||
|
||||
const BLOCK_START = /^ {0,3}(?:#{1,6}(?:\s|$)|>|[-+*](?:\s|$)|\d{1,9}[.)](?:\s|$)|`{3}|~{3}|=+\s*$|[-*_](?:\s*[-*_]){2,}\s*$|\[[^\]]*\]:|:::)/m;
|
||||
|
||||
/**
|
||||
* A paragraph whose line starts like a heading, quote, list item, fence, rule or link definition
|
||||
* would become that block on the next load. Such starts get a backslash, but only when the parser
|
||||
* confirms the paragraph would not come back as a paragraph.
|
||||
*
|
||||
* One exception keeps a long-standing behavior: the editor does not read indented code, so a
|
||||
* source line such as ` - item` is shown as text and has always been saved as `- item`, which
|
||||
* the next load reads as the list its author meant. A line the note's source already has in that
|
||||
* unescaped form is therefore left alone; only text from elsewhere (typed, pasted, or escaped in
|
||||
* the source) is escaped.
|
||||
*/
|
||||
export function escapeBlockStarts(markdown: string, readsAsParagraph: ReadsAsParagraph, inNoteSource?: InNoteSource): string {
|
||||
if (!BLOCK_START.test(markdown) || readsAsParagraph(markdown)) return markdown;
|
||||
return markdown
|
||||
.split('\n')
|
||||
.map((line) => (inNoteSource?.(line) ? line : line
|
||||
.replace(/^( {0,3})(\d{1,9})([.)])(?=\s|$)/, '$1$2\\$3')
|
||||
.replace(/^( {0,3})(#{1,6}(?:\s|$)|>|[-+*](?:\s|$)|`{3}|~{3}|=+\s*$|[-*_](?:\s*[-*_]){2,}\s*$|\[[^\]]*\]:|:::)/, '$1\\$2')))
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Like serializeInlineMarkdown, but writes a `$` as typed unless that could change the note's
|
||||
* math. `inlineMathPayloads` returns the TeX of each inline formula the parser finds in a string;
|
||||
* if plain dollars would add, remove or re-pair a formula, every `$` is escaped as before.
|
||||
*/
|
||||
export function serializeInlineMarkdownKeepingDollars(
|
||||
node: ProseMirrorNode,
|
||||
normalizeAssetSource: AssetSourceNormalizer,
|
||||
inlineMathPayloads: (markdown: string) => string[],
|
||||
plainText?: InlinePlainText,
|
||||
): string {
|
||||
const literalText = plainText ? literalTextEscapes(node, normalizeAssetSource, plainText) : undefined;
|
||||
const escaped = serializeInlineMarkdown(node, normalizeAssetSource, { literalText });
|
||||
if (!escaped.includes('$')) return escaped;
|
||||
const plain = serializeInlineMarkdown(node, normalizeAssetSource, { literalDollars: true, literalText });
|
||||
// A `$$` could start a display formula in a later block, so only single dollars are left alone.
|
||||
if (plain.includes('$$')) return escaped;
|
||||
const expected = inlineMathPayloads(escaped);
|
||||
const actual = inlineMathPayloads(plain);
|
||||
return actual.length === expected.length && actual.every((tex, index) => tex === expected[index]) ? plain : escaped;
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
import MarkdownIt from 'markdown-it';
|
||||
import type Token from 'markdown-it/lib/token.mjs';
|
||||
import type StateBlock from 'markdown-it/lib/rules_block/state_block.mjs';
|
||||
import type StateInline from 'markdown-it/lib/rules_inline/state_inline.mjs';
|
||||
import fenceRule from 'markdown-it/lib/rules_block/fence.mjs';
|
||||
import markdownItMark from 'markdown-it-mark';
|
||||
import markdownItSup from 'markdown-it-sup';
|
||||
import markdownItSub from 'markdown-it-sub';
|
||||
import { IMG_GRID_CLOSER, parseImgGridHeader, splitTrailingCloser } from './imageGrid.ts';
|
||||
|
||||
interface WikiTitle { path: string; title: string }
|
||||
export interface MarkdownEnvironment { wikiLinkTitles?: readonly WikiTitle[] }
|
||||
type WikiIndex = { paths: Map<string, string>; titles: Map<string, { path: string; depth: number }> };
|
||||
// One index per titles array: callers replace the array, never mutate it, when a title changes.
|
||||
const wikiIndexes = new WeakMap<readonly WikiTitle[], WikiIndex>();
|
||||
|
||||
function displayMath(state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean {
|
||||
const start = state.bMarks[startLine] + state.tShift[startLine];
|
||||
if (state.src.slice(start, state.eMarks[startLine]).trim() !== '$$') return false;
|
||||
let closing = startLine + 1;
|
||||
for (; closing < endLine; closing++) {
|
||||
if (state.sCount[closing] < state.blkIndent && !state.isEmpty(closing)) return false;
|
||||
const from = state.bMarks[closing] + state.tShift[closing];
|
||||
if (state.src.slice(from, state.eMarks[closing]).trim() === '$$') break;
|
||||
}
|
||||
if (closing === endLine) return false;
|
||||
if (silent) return true;
|
||||
const token = state.push('helix_math_block', 'div', 0);
|
||||
token.block = true;
|
||||
token.content = state.getLines(startLine + 1, closing, state.blkIndent, false).trim();
|
||||
token.map = [startLine, closing + 1];
|
||||
token.meta = { sourceStart: start };
|
||||
token.attrSet('data-math-block', encodeURIComponent(token.content));
|
||||
token.attrSet('class', 'math-block');
|
||||
state.line = closing + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
function inlineMath(state: StateInline, silent: boolean): boolean {
|
||||
const start = state.pos;
|
||||
if (state.src[start] !== '$' || state.src[start - 1] === '$' ||
|
||||
start + 1 >= state.posMax || /[\s$]/u.test(state.src[start + 1])) return false;
|
||||
let end = start + 1;
|
||||
for (; end < state.posMax; end++) {
|
||||
const char = state.src[end];
|
||||
if (char === '\n') return false;
|
||||
if (char === '\\') { end++; continue; }
|
||||
if (char === '$') break;
|
||||
}
|
||||
if (end >= state.posMax || end === start + 1 || /\s/u.test(state.src[end - 1]) ||
|
||||
state.src[end + 1] === '$' || /[0-9]/.test(state.src[end + 1] ?? '')) return false;
|
||||
if (!silent) {
|
||||
const token = state.push('helix_math_inline', 'span', 0);
|
||||
token.content = state.src.slice(start + 1, end).trim();
|
||||
token.meta = { from: start, to: end + 1 };
|
||||
token.attrSet('data-math-inline', encodeURIComponent(token.content));
|
||||
token.attrSet('class', 'math-inline');
|
||||
}
|
||||
state.pos = end + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
// markdown-it trims two spaces even when a code span contains only spaces.
|
||||
// Preserve CommonMark's all-space exception without replacing its normal backtick parser.
|
||||
function spaceCode(state: StateInline, silent: boolean): boolean {
|
||||
if (state.src[state.pos] !== '`') return false;
|
||||
let content = state.pos;
|
||||
while (content < state.posMax && state.src[content] === '`') content++;
|
||||
const length = content - state.pos;
|
||||
let closing = content;
|
||||
while (closing < state.posMax && (state.src[closing] === ' ' || state.src[closing] === '\n')) closing++;
|
||||
if (closing === content) return false;
|
||||
let end = closing;
|
||||
while (end < state.posMax && state.src[end] === '`') end++;
|
||||
if (end - closing !== length) return false;
|
||||
if (!silent) {
|
||||
const token = state.push('code_inline', 'code', 0);
|
||||
token.markup = state.src.slice(state.pos, content);
|
||||
token.content = state.src.slice(content, closing).replace(/\n/g, ' ');
|
||||
}
|
||||
state.pos = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
function installMath(md: MarkdownIt) {
|
||||
md.block.ruler.before('fence', 'helix_math_block', displayMath, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });
|
||||
md.inline.ruler.after('backticks', 'helix_math_inline', inlineMath);
|
||||
md.renderer.rules.helix_math_block = (tokens, index, _options, _env, renderer) =>
|
||||
`<div${renderer.renderAttrs(tokens[index])}></div>\n`;
|
||||
md.renderer.rules.helix_math_inline = (tokens, index, _options, _env, renderer) =>
|
||||
`<span${renderer.renderAttrs(tokens[index])}></span>`;
|
||||
}
|
||||
|
||||
function wikiLink(state: StateInline, silent: boolean): boolean {
|
||||
const notes: readonly WikiTitle[] | undefined = state.env.wikiLinkTitles;
|
||||
if (!notes || state.src.slice(state.pos, state.pos + 2) !== '[[') return false;
|
||||
const end = state.src.indexOf(']]', state.pos + 2);
|
||||
if (end < 0 || end + 2 > state.posMax) return false;
|
||||
const raw = state.src.slice(state.pos + 2, end);
|
||||
if (!raw || raw.includes(']')) return false;
|
||||
if (!silent) {
|
||||
let index = wikiIndexes.get(notes);
|
||||
if (!index) {
|
||||
index = { paths: new Map(), titles: new Map() };
|
||||
for (const note of notes) {
|
||||
if (!index.paths.has(note.path)) index.paths.set(note.path, note.path);
|
||||
const title = note.title.toLowerCase();
|
||||
let depth = 0;
|
||||
for (let i = 0; i < note.path.length; i++) if (note.path[i] === '/') depth++;
|
||||
const previous = index.titles.get(title);
|
||||
if (!previous || depth < previous.depth) index.titles.set(title, { path: note.path, depth });
|
||||
}
|
||||
wikiIndexes.set(notes, index);
|
||||
}
|
||||
const pipe = raw.indexOf('|');
|
||||
const reference = (pipe < 0 ? raw : raw.slice(0, pipe)).trim();
|
||||
const display = (pipe < 0 ? reference : raw.slice(pipe + 1)).trim();
|
||||
const title = reference.replace(/#.*$/, '').replace(/\^.*$/, '').trim();
|
||||
const basename = title.includes('/') ? title.slice(title.lastIndexOf('/') + 1) : title;
|
||||
const path = (title.includes('/') ? index.paths.get(title + '.md') : undefined)
|
||||
?? index.titles.get(basename.toLowerCase())?.path ?? '';
|
||||
const token = state.push('helix_wiki', 'span', 0);
|
||||
token.attrSet('data-wiki-link', '');
|
||||
token.attrSet('data-path', path);
|
||||
token.attrSet('data-title', reference);
|
||||
token.attrSet('class', 'wiki-link');
|
||||
token.content = display;
|
||||
}
|
||||
state.pos = end + 2;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a trailing `"title"` or `'title'` (preceded by whitespace or %20, optionally followed by %20) from a
|
||||
* legacy link destination. A single scan from the end: the equivalent regular expression is quadratic on a
|
||||
* long run of spaces.
|
||||
*/
|
||||
export function stripLinkTitle(destination: string): string {
|
||||
const skippableBefore = (index: number) => (index >= 3 && destination.startsWith('%20', index - 3) ? 3 : /\s/u.test(destination[index - 1] ?? '') ? 1 : 0);
|
||||
let end = destination.length;
|
||||
for (let width = skippableBefore(end); width; width = skippableBefore(end)) end -= width;
|
||||
const quote = destination[end - 1];
|
||||
if (quote !== '"' && quote !== "'") return destination.trim();
|
||||
const open = destination.lastIndexOf(quote, end - 2);
|
||||
if (open <= 0) return destination.trim();
|
||||
let start = open;
|
||||
for (let width = skippableBefore(start); width; width = skippableBefore(start)) start -= width;
|
||||
return start === open ? destination.trim() : destination.slice(0, start).trim();
|
||||
}
|
||||
|
||||
/** The title text after a legacy destination (`"title"` or `'title'`, maybe after `>` or %20), or null. */
|
||||
function legacyImageTitle(rest: string): string | null {
|
||||
let text = rest.startsWith('>') ? rest.slice(1) : rest;
|
||||
text = text.replace(/^(?:\s|%20)+/u, '');
|
||||
while (text.endsWith('%20') || /\s$/u.test(text)) text = text.endsWith('%20') ? text.slice(0, -3) : text.slice(0, -1);
|
||||
const quote = text[0];
|
||||
if ((quote !== '"' && quote !== "'") || text.length < 2 || text[text.length - 1] !== quote) return null;
|
||||
return text.slice(1, -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `src[start, end)` is a valid CommonMark destination with an optional title. Such images
|
||||
* are left to markdown-it's own image rule, which handles escaped quotes and `(title)` correctly.
|
||||
*/
|
||||
function isCommonMarkDestination(state: StateInline, start: number, end: number): boolean {
|
||||
const { helpers } = state.md;
|
||||
const skipSpace = (pos: number) => {
|
||||
while (pos < end && /[ \t\n]/u.test(state.src[pos])) pos++;
|
||||
return pos;
|
||||
};
|
||||
let pos = skipSpace(start);
|
||||
const destination = helpers.parseLinkDestination(state.src, pos, end);
|
||||
if (!destination.ok) return false;
|
||||
pos = destination.pos;
|
||||
const afterDestination = pos;
|
||||
pos = skipSpace(pos);
|
||||
if (pos < end && pos !== afterDestination) {
|
||||
const title = helpers.parseLinkTitle(state.src, pos, end);
|
||||
if (!title.ok) return false;
|
||||
pos = skipSpace(title.pos);
|
||||
}
|
||||
return pos === end;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looking for the `)` that ends a destination reads to the end of the line when there is none, and a
|
||||
* line can hold thousands of `[label](` starts (pasted or generated text), which made parsing it
|
||||
* quadratic. Two guards keep it linear: no search starts beyond the block's last `)`, and once the
|
||||
* searches that found nothing have read this many characters in one block, the rest of the block
|
||||
* is left to the CommonMark link rule.
|
||||
*/
|
||||
const LEGACY_LINK_SCAN_BUDGET = 2_000_000;
|
||||
const legacyLinkScans = new WeakMap<StateInline, { max: number; lastClose: number; wasted: number }>();
|
||||
|
||||
/** Preserve legacy space-containing and %20/title destinations only in real link syntax. */
|
||||
function legacyLink(state: StateInline, silent: boolean): boolean {
|
||||
const start = state.pos;
|
||||
const image = state.src[start] === '!' && state.src[start + 1] === '[';
|
||||
const labelStart = start + (image ? 1 : 0);
|
||||
if (state.src[labelStart] !== '[') return false;
|
||||
const labelEnd = state.md.helpers.parseLinkLabel(state, labelStart, !image);
|
||||
if (labelEnd < 0 || state.src[labelEnd + 1] !== '(') return false;
|
||||
const destinationStart = labelEnd + 2;
|
||||
let scans = legacyLinkScans.get(state);
|
||||
if (!scans || scans.max < state.posMax) {
|
||||
scans = { max: state.posMax, lastClose: state.src.lastIndexOf(')', state.posMax - 1), wasted: scans?.wasted ?? 0 };
|
||||
legacyLinkScans.set(state, scans);
|
||||
}
|
||||
if (destinationStart > scans.lastClose || scans.wasted > LEGACY_LINK_SCAN_BUDGET) return false;
|
||||
let end = destinationStart;
|
||||
let depth = 0;
|
||||
let quote = '';
|
||||
let angle = false;
|
||||
for (; end < state.posMax; end++) {
|
||||
const char = state.src[end];
|
||||
if (char === '\n') { scans.wasted += end - destinationStart; return false; }
|
||||
if (char === '\\') { end++; continue; }
|
||||
if (quote) { if (char === quote) quote = ''; continue; }
|
||||
if (angle) { if (char === '>') angle = false; continue; }
|
||||
if (char === '<') { angle = true; continue; }
|
||||
if ((char === '"' || char === "'") &&
|
||||
(/\s/u.test(state.src[end - 1]) || state.src.slice(end - 3, end) === '%20')) { quote = char; continue; }
|
||||
if (char === '(') depth++;
|
||||
else if (char === ')') { if (!depth) break; depth--; }
|
||||
}
|
||||
if (end >= state.posMax) { scans.wasted += end - destinationStart; return false; }
|
||||
const raw = state.src.slice(destinationStart, end);
|
||||
// Links and images with a valid CommonMark destination and title keep the native parser (and
|
||||
// their title). A `%20"title"` suffix (exported by some apps) is still legacy syntax, not part of the path.
|
||||
if (!/%20["'(]/u.test(raw) && isCommonMarkDestination(state, destinationStart, end)) return false;
|
||||
// Native CommonMark links, including nested destinations, retain their normal parser.
|
||||
if (!/\s|%20["'(]/u.test(raw)) return false;
|
||||
let destination = raw.trim();
|
||||
if (destination.startsWith('<')) {
|
||||
const angle = destination.match(/^<([^>]*)>(?:(?:\s|%20)*(?:"[^"]*"|'[^']*'|\([^)]*\)))?(?:\s|%20)*$/u);
|
||||
if (!angle) return false;
|
||||
destination = angle[1];
|
||||
} else {
|
||||
destination = stripLinkTitle(destination);
|
||||
}
|
||||
const href = state.md.normalizeLink(destination.replace(/ /g, '%20'));
|
||||
if (!state.md.validateLink(href)) return false;
|
||||
if (!silent) {
|
||||
const label = state.src.slice(labelStart + 1, labelEnd);
|
||||
const from = destinationStart + raw.indexOf(destination);
|
||||
const sourceHref = { from, to: from + destination.length };
|
||||
if (image) {
|
||||
const children: Token[] = [];
|
||||
state.md.inline.parse(label, state.md, state.env, children);
|
||||
const token = state.push('image', 'img', 0);
|
||||
token.meta = { sourceHref };
|
||||
token.attrSet('src', href.replace(/^\/{2,}(?=home\/)/u, '/'));
|
||||
token.attrSet('alt', '');
|
||||
const title = legacyImageTitle(raw.slice(raw.indexOf(destination) + destination.length));
|
||||
if (title) token.attrSet('title', state.md.utils.unescapeAll(title));
|
||||
token.children = children;
|
||||
token.content = label;
|
||||
} else {
|
||||
const token = state.push('link_open', 'a', 1);
|
||||
token.meta = { sourceHref };
|
||||
token.attrSet('href', href);
|
||||
const title = legacyImageTitle(raw.slice(raw.indexOf(destination) + destination.length));
|
||||
if (title) token.attrSet('title', state.md.utils.unescapeAll(title));
|
||||
const oldMax = state.posMax;
|
||||
state.pos = labelStart + 1;
|
||||
state.posMax = labelEnd;
|
||||
const linkState = state as StateInline & { linkLevel: number };
|
||||
linkState.linkLevel++;
|
||||
state.md.inline.tokenize(state);
|
||||
linkState.linkLevel--;
|
||||
state.push('link_close', 'a', -1);
|
||||
state.posMax = oldMax;
|
||||
}
|
||||
}
|
||||
state.pos = end + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
const EMPTY_PARAGRAPH_MARKER = '<!-- -->';
|
||||
|
||||
function emptyParagraph(state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean {
|
||||
const from = state.bMarks[startLine] + state.tShift[startLine];
|
||||
const line = state.src.slice(from, state.eMarks[startLine]);
|
||||
// Versions before 1.3.7 glued the marker to a following image (`<!-- -->`), which
|
||||
// reads as a raw HTML line and showed the image as text. Read it as the empty paragraph and the
|
||||
// image it was written from.
|
||||
const glued = line.startsWith(EMPTY_PARAGRAPH_MARKER) && line.slice(EMPTY_PARAGRAPH_MARKER.length).trimStart().startsWith('![');
|
||||
if (!glued && line.trim() !== EMPTY_PARAGRAPH_MARKER) return false;
|
||||
if (silent) return true;
|
||||
const token = state.push('helix_empty', 'p', 0);
|
||||
token.block = true;
|
||||
token.map = [startLine, startLine + 1];
|
||||
if (!glued) {
|
||||
state.line = startLine + 1;
|
||||
return true;
|
||||
}
|
||||
const rest = from + EMPTY_PARAGRAPH_MARKER.length;
|
||||
state.bMarks[startLine] = rest;
|
||||
state.tShift[startLine] = state.src.slice(rest, state.eMarks[startLine]).search(/\S/);
|
||||
state.md.block.tokenize(state, startLine, endLine);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** True when `text` is exactly one Markdown image and nothing else (no caption, no link around it). */
|
||||
function isSingleImage(state: StateBlock, text: string): boolean {
|
||||
if (!text.startsWith('![')) return false;
|
||||
const tokens: Token[] = [];
|
||||
state.md.inline.parse(text, state.md, state.env, tokens);
|
||||
return tokens.length === 1 && tokens[0].type === 'image';
|
||||
}
|
||||
|
||||
/**
|
||||
* `:::img-grid` image grids (see imageGrid.ts). As a block rule, it never sees lines inside code
|
||||
* blocks. A block that isn't a well-formed grid is left completely to the other rules.
|
||||
*/
|
||||
function imageGrid(state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean {
|
||||
if (state.sCount[startLine] - state.blkIndent >= 4) return false;
|
||||
const lineText = (line: number) => state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]);
|
||||
const header = lineText(startLine);
|
||||
if (!header.startsWith(':::img-grid')) return false;
|
||||
const attrs = parseImgGridHeader(header);
|
||||
if (!attrs) return false;
|
||||
const images: { line: number; content: string }[] = [];
|
||||
let closing = -1;
|
||||
for (let line = startLine + 1; line < endLine && closing < 0; line++) {
|
||||
if (state.isEmpty(line) || state.sCount[line] < state.blkIndent) return false;
|
||||
const text = lineText(line).replace(/[ \t]+$/, '');
|
||||
if (text === IMG_GRID_CLOSER) {
|
||||
closing = line;
|
||||
break;
|
||||
}
|
||||
const beforeCloser = splitTrailingCloser(text);
|
||||
const image = beforeCloser ?? text;
|
||||
if (!isSingleImage(state, image)) return false;
|
||||
images.push({ line, content: image });
|
||||
if (beforeCloser !== null) closing = line;
|
||||
}
|
||||
if (closing < 0 || images.length === 0) return false;
|
||||
if (silent) return true;
|
||||
const open = state.push('helix_img_grid_open', 'div', 1);
|
||||
open.block = true;
|
||||
open.map = [startLine, closing + 1];
|
||||
open.attrSet('data-img-grid', '');
|
||||
open.attrSet('data-cols', String(attrs.cols));
|
||||
open.attrSet('data-layout', attrs.layout);
|
||||
open.attrSet('class', 'img-grid');
|
||||
for (const image of images) {
|
||||
const inline = state.push('inline', '', 0);
|
||||
inline.content = image.content;
|
||||
inline.map = [image.line, image.line + 1];
|
||||
inline.children = [];
|
||||
}
|
||||
state.push('helix_img_grid_close', 'div', -1).block = true;
|
||||
state.line = closing + 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Elements a note may hold as HTML. Anything else written in angle brackets is the user's text,
|
||||
// such as `List<String>`, and a browser would drop it without a trace.
|
||||
const HTML_ELEMENTS = new Set((
|
||||
'a abbr address area article aside audio b base bdi bdo big blockquote body br button canvas caption center cite code '
|
||||
+ 'col colgroup data datalist dd del details dfn dialog dir div dl dt em embed fieldset figcaption figure font footer '
|
||||
+ 'form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link '
|
||||
+ 'main map mark menu meta meter nav nobr noscript object ol optgroup option output p param picture pre progress q rp '
|
||||
+ 'rt ruby s samp script search section select slot small source span strike strong style sub summary sup svg math '
|
||||
+ 'table tbody td template textarea tfoot th thead time title tr track tt u ul var video wbr'
|
||||
).split(' '));
|
||||
const HTML_PIECE = /<!--[\s\S]*?-->|<\/?([A-Za-z][A-Za-z0-9-]*)(?:\s[^<>]*)?\/?>/g;
|
||||
|
||||
/** Whether a tag or comment is shown as the text it is instead of being handed to the browser. */
|
||||
function isLiteralHtml(piece: string, tagName: string | undefined): boolean {
|
||||
// A comment would vanish on the first save; the empty one is the editor's own blank-line marker.
|
||||
if (piece.startsWith('<!--')) return piece.replace(/\s/g, '') !== '<!---->';
|
||||
return !!tagName && !HTML_ELEMENTS.has(tagName.toLowerCase());
|
||||
}
|
||||
|
||||
function literalHtml(state: { tokens: Token[]; md: MarkdownIt }): void {
|
||||
for (const token of state.tokens) {
|
||||
if (token.type === 'inline') {
|
||||
for (const child of token.children ?? []) {
|
||||
if (child.type !== 'html_inline') continue;
|
||||
HTML_PIECE.lastIndex = 0;
|
||||
const match = HTML_PIECE.exec(child.content);
|
||||
if (match && match[0] === child.content && isLiteralHtml(match[0], match[1])) child.type = 'text';
|
||||
}
|
||||
} else if (token.type === 'html_block') {
|
||||
let literal = false;
|
||||
const content = token.content.replace(HTML_PIECE, (piece, tagName) => {
|
||||
if (!isLiteralHtml(piece, tagName)) return piece;
|
||||
literal = true;
|
||||
return state.md.utils.escapeHtml(piece);
|
||||
});
|
||||
if (!literal) continue;
|
||||
// Text without an element around it becomes a paragraph that keeps its lines.
|
||||
token.content = content.startsWith('<')
|
||||
? `<p>${content.trim().split('\n').map((line) => line.trimEnd()).join('<br>')}</p>\n` : content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createEditorMarkdownParser(): MarkdownIt {
|
||||
const md = MarkdownIt({ html: true, linkify: false, breaks: false })
|
||||
.use(markdownItMark).use(markdownItSup).use(markdownItSub);
|
||||
// Existing editor convention: tab-indented prose does not become an indented code block.
|
||||
md.disable('code');
|
||||
installMath(md);
|
||||
md.inline.ruler.before('link', 'helix_wiki', wikiLink);
|
||||
md.inline.ruler.before('backticks', 'helix_space_code', spaceCode);
|
||||
md.inline.ruler.before('link', 'helix_legacy_link', legacyLink);
|
||||
md.block.ruler.before('html_block', 'helix_empty', emptyParagraph, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });
|
||||
md.block.ruler.before('fence', 'helix_img_grid', imageGrid, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });
|
||||
md.renderer.rules.helix_empty = () => '<p></p>\n';
|
||||
md.renderer.rules.helix_wiki = (tokens, index, _options, _env, renderer) =>
|
||||
`<span${renderer.renderAttrs(tokens[index])}>${md.utils.escapeHtml(tokens[index].content)}</span>`;
|
||||
|
||||
md.core.ruler.after('inline', 'helix_literal_html', literalHtml);
|
||||
|
||||
md.core.ruler.before('inline', 'helix_tasks', state => {
|
||||
const lists: { open: Token; firstItem: boolean; item: Token | null; firstParagraph: boolean }[] = [];
|
||||
for (const token of state.tokens) {
|
||||
if (token.type === 'bullet_list_open' || token.type === 'ordered_list_open') {
|
||||
lists.push({ open: token, firstItem: true, item: null, firstParagraph: true });
|
||||
} else if (token.type === 'bullet_list_close' || token.type === 'ordered_list_close') lists.pop();
|
||||
else if (token.type === 'list_item_open' && lists.length) {
|
||||
const list = lists[lists.length - 1];
|
||||
list.item = token;
|
||||
list.firstParagraph = true;
|
||||
} else if (token.type === 'list_item_close' && lists.length) {
|
||||
const list = lists[lists.length - 1];
|
||||
list.item = null;
|
||||
list.firstItem = false;
|
||||
} else if (token.type === 'inline' && lists.length) {
|
||||
const list = lists[lists.length - 1];
|
||||
if (!list.item || !list.firstParagraph || token.level !== list.item.level + 2) continue;
|
||||
list.firstParagraph = false;
|
||||
// Task items only exist in bullet lists; `1. [x] text` stays an ordinary numbered item.
|
||||
if (list.open.type !== 'bullet_list_open') continue;
|
||||
const checkbox = token.content.match(/^\[(x| )\](?:[^\S\n]+|$)/u);
|
||||
if (!checkbox) continue;
|
||||
token.content = token.content.slice(checkbox[0].length);
|
||||
list.item.attrSet('data-type', 'taskItem');
|
||||
list.item.attrSet('data-checked', checkbox[1] === 'x' ? 'true' : 'false');
|
||||
if (list.firstItem) list.open.attrSet('data-type', 'taskList');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
md.core.ruler.after('inline', 'helix_images', state => {
|
||||
let paragraph: Token | null = null;
|
||||
let cell: Token | null = null;
|
||||
// Tight list items render no <p>, so a simple item (open, hidden paragraph, inline, close) carries the marker.
|
||||
const items: { token: Token; index: number; hasCode: boolean }[] = [];
|
||||
let lines: string[] | undefined;
|
||||
for (const [index, token] of state.tokens.entries()) {
|
||||
if (token.type === 'paragraph_open' || token.type === 'heading_open') paragraph = token;
|
||||
else if (token.type === 'paragraph_close' || token.type === 'heading_close') paragraph = null;
|
||||
else if (token.type === 'th_open' || token.type === 'td_open') cell = token;
|
||||
else if (token.type === 'th_close' || token.type === 'td_close') cell = null;
|
||||
else if (token.type === 'list_item_open') items.push({ token, index, hasCode: false });
|
||||
else if (token.type === 'list_item_close') {
|
||||
const item = items.pop();
|
||||
if (item?.hasCode && index - item.index === 4) item.token.attrSet('data-helix-code', '');
|
||||
}
|
||||
if (token.type !== 'inline') continue;
|
||||
for (const child of token.children ?? []) {
|
||||
// ProseMirror's DOM parser otherwise collapses or drops whitespace-only code spans.
|
||||
if (child.type === 'code_inline') {
|
||||
child.attrSet('style', 'white-space: pre-wrap');
|
||||
paragraph?.attrSet('data-helix-code', '');
|
||||
cell?.attrSet('data-helix-code', '');
|
||||
if (paragraph?.hidden && items.length) items[items.length - 1].hasCode = true;
|
||||
}
|
||||
if (child.type === 'image') {
|
||||
const src = child.attrGet('src');
|
||||
if (src?.startsWith('//')) child.attrSet('src', src.replace(/^\/{2,}(?=home\/)/u, '/'));
|
||||
}
|
||||
}
|
||||
if (!paragraph || paragraph.type !== 'paragraph_open' || paragraph.level !== 0 || token.children?.length !== 1 ||
|
||||
token.children[0].type !== 'image' || !token.map || token.map[0] < 2) continue;
|
||||
lines ??= state.src.split('\n');
|
||||
const line = token.map[0];
|
||||
if (lines[line].startsWith('![') && lines[line - 1].trim() === '') paragraph.meta = { helixImageGap: true };
|
||||
}
|
||||
});
|
||||
// Callout rendering splits the title line from the body at the first newline of the opening
|
||||
// paragraph, so that one soft break must stay a newline instead of becoming a space.
|
||||
md.core.ruler.after('inline', 'helix_callout_title', state => {
|
||||
for (let index = 0; index + 2 < state.tokens.length; index++) {
|
||||
const [quote, paragraph, inline] = [state.tokens[index], state.tokens[index + 1], state.tokens[index + 2]];
|
||||
if (quote.type !== 'blockquote_open' || paragraph.type !== 'paragraph_open' || inline.type !== 'inline') continue;
|
||||
if (!/^\[![\w-]+\]/u.test(inline.content)) continue;
|
||||
const softbreak = inline.children?.find(child => child.type === 'softbreak');
|
||||
if (softbreak) softbreak.meta = { helixCalloutTitle: true };
|
||||
}
|
||||
});
|
||||
md.renderer.rules.paragraph_open = (tokens, index, options, _env, renderer) =>
|
||||
(tokens[index].meta?.helixImageGap ? '<p></p>\n' : '') + renderer.renderToken(tokens, index, options);
|
||||
|
||||
md.block.ruler.at('fence', (state, startLine, endLine, silent) => {
|
||||
if (!fenceRule(state, startLine, endLine, silent)) return false;
|
||||
if (silent) return true;
|
||||
const token = state.tokens[state.tokens.length - 1];
|
||||
if (token.info.trim() === 'helix-secret' && token.map) {
|
||||
const line = token.map[1] - 1;
|
||||
const closing = state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]);
|
||||
let length = 0;
|
||||
while (closing[length] === token.markup[0]) length++;
|
||||
const indentation = state.sCount[line] - state.blkIndent;
|
||||
token.meta = { helixSecretClosed: indentation >= 0 && indentation < 4 &&
|
||||
length >= token.markup.length && /^[ \t]*$/u.test(closing.slice(length)) };
|
||||
}
|
||||
return true;
|
||||
}, { alt: ['paragraph', 'reference', 'blockquote', 'list'] });
|
||||
const renderFence = md.renderer.rules.fence!;
|
||||
md.renderer.rules.fence = (tokens, index, options, env, renderer) => {
|
||||
const token = tokens[index];
|
||||
if (token.info.trim() === 'helix-secret' && token.meta?.helixSecretClosed) {
|
||||
return `<div data-secret-block="${md.utils.escapeHtml(encodeURIComponent(token.content.replace(/\n$/, '')))}"></div>\n`;
|
||||
}
|
||||
// Only the final structural LF is parser-added; leading and extra trailing blank lines are literal.
|
||||
return renderFence(tokens, index, options, env, renderer).replace(/\n<\/code>/u, '</code>');
|
||||
};
|
||||
md.renderer.rules.softbreak = (tokens, index) => (tokens[index].meta?.helixCalloutTitle ? '\n' : ' ');
|
||||
md.renderer.rules.hardbreak = () => '<br>';
|
||||
return md;
|
||||
}
|
||||
|
||||
const mathBlocks = MarkdownIt({ html: true });
|
||||
installMath(mathBlocks);
|
||||
mathBlocks.inline.ruler.before('link', 'helix_legacy_link', legacyLink);
|
||||
|
||||
/**
|
||||
* Inline tokens of each blank-line-separated block, parsed on its own like the editor does, with
|
||||
* source ranges relative to the whole note. Inline syntax such as a code span cannot pair across
|
||||
* blocks, so one stray backtick must not hide the links and formulas after it.
|
||||
*/
|
||||
function inlineTokensByBlock(source: string): Token[] {
|
||||
const tokens: Token[] = [];
|
||||
let start = 0;
|
||||
let offset = 0;
|
||||
const flush = (end: number) => {
|
||||
if (end <= start) return;
|
||||
const found: Token[] = [];
|
||||
mathBlocks.inline.parse(source.slice(start, end), mathBlocks, {}, found);
|
||||
for (const token of found) {
|
||||
if (token.meta?.sourceHref) {
|
||||
const { from, to } = token.meta.sourceHref;
|
||||
token.meta = { ...token.meta, sourceHref: { from: from + start, to: to + start } };
|
||||
} else if (token.type === 'helix_math_inline') {
|
||||
token.meta = { ...token.meta, from: token.meta.from + start, to: token.meta.to + start };
|
||||
}
|
||||
tokens.push(token);
|
||||
}
|
||||
};
|
||||
for (const line of source.split('\n')) {
|
||||
if (/^[ \t\r]*$/.test(line)) {
|
||||
flush(offset);
|
||||
start = offset + line.length + 1;
|
||||
}
|
||||
offset += line.length + 1;
|
||||
}
|
||||
flush(source.length);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Source destinations for the editor's legacy space/title link compatibility. */
|
||||
export function legacyLinkRanges(source: string): { from: number; to: number }[] {
|
||||
if (!source.includes('](')) return [];
|
||||
return inlineTokensByBlock(source).filter(token => token.meta?.sourceHref).map(token => token.meta.sourceHref);
|
||||
}
|
||||
|
||||
/** Inline math coordinates use the same delimiter and escape rules as rendering. */
|
||||
export function inlineMathRanges(source: string): { from: number; to: number }[] {
|
||||
if (!source.includes('$')) return [];
|
||||
return inlineTokensByBlock(source).filter(token => token.type === 'helix_math_inline').map(token => token.meta);
|
||||
}
|
||||
|
||||
/** Source coordinates of semantic display-math blocks, including nested containers. */
|
||||
export function displayMathRanges(source: string): { from: number; to: number; prefix: string }[] {
|
||||
if (!source.includes('$$')) return [];
|
||||
const tokens: Token[] = [];
|
||||
mathBlocks.block.parse(source, mathBlocks, {}, tokens);
|
||||
const ranges = tokens.filter(token => token.type === 'helix_math_block' && token.map);
|
||||
if (!ranges.length) return [];
|
||||
const starts = [0];
|
||||
for (let i = 0; i < source.length; i++) if (source[i] === '\n') starts.push(i + 1);
|
||||
return ranges.map(token => {
|
||||
const from = starts[token.map![0]];
|
||||
return { from, to: starts[token.map![1]] ?? source.length,
|
||||
prefix: source.slice(from, token.meta.sourceStart) };
|
||||
});
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
declare module 'markdown-it/lib/rules_block/fence.mjs' {
|
||||
import type StateBlock from 'markdown-it/lib/rules_block/state_block.mjs';
|
||||
const fence: (state: StateBlock, startLine: number, endLine: number, silent: boolean) => boolean;
|
||||
export default fence;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { markdownLanguage } from '@codemirror/lang-markdown';
|
||||
import { MapMode, type ChangeDesc, type EditorState } from '@codemirror/state';
|
||||
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
|
||||
import type { Mapping } from '@tiptap/pm/transform';
|
||||
import MarkdownIt from 'markdown-it';
|
||||
import type Token from 'markdown-it/lib/token.mjs';
|
||||
import markdownItMark from 'markdown-it-mark';
|
||||
import markdownItSub from 'markdown-it-sub';
|
||||
import markdownItSup from 'markdown-it-sup';
|
||||
import { displayMathRanges } from './markdownParser.ts';
|
||||
|
||||
export interface OutlineHeading {
|
||||
level: number;
|
||||
text: string;
|
||||
pos: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const inlineMarkdown = MarkdownIt({ html: true, linkify: false, breaks: false })
|
||||
.use(markdownItMark)
|
||||
.use(markdownItSub)
|
||||
.use(markdownItSup);
|
||||
|
||||
function inlineText(tokens: readonly Token[]): string {
|
||||
let text = '';
|
||||
for (const token of tokens) {
|
||||
if (token.children) text += inlineText(token.children);
|
||||
else if (token.type === 'text' || token.type === 'code_inline') text += token.content;
|
||||
else if (token.type === 'softbreak' || token.type === 'hardbreak' ||
|
||||
(token.type === 'html_inline' && /^<br\s*\/?\s*>$/i.test(token.content))) text += ' ';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
export function documentHeadings(doc: ProseMirrorNode): OutlineHeading[] {
|
||||
const headings: OutlineHeading[] = [];
|
||||
doc.descendants((node, pos) => {
|
||||
if (node.type.name !== 'heading') return;
|
||||
headings.push({ level: node.attrs.level, text: node.textContent, pos, end: pos + node.nodeSize });
|
||||
return false;
|
||||
});
|
||||
return headings;
|
||||
}
|
||||
|
||||
/** Match the rich editor's closed $$ blocks without shifting source coordinates. */
|
||||
function maskDisplayMath(markdown: string): string {
|
||||
const ranges = displayMathRanges(markdown);
|
||||
if (!ranges.length) return markdown;
|
||||
const parts: string[] = [];
|
||||
let copied = 0;
|
||||
for (const { from, to, prefix } of ranges) {
|
||||
parts.push(markdown.slice(copied, from), prefix, markdown.slice(from + prefix.length, to).replace(/[^\n]/g, ' '));
|
||||
copied = to;
|
||||
}
|
||||
parts.push(markdown.slice(copied));
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** Markdown headings only: raw HTML heading blocks are not interpreted as headings. */
|
||||
export function sourceHeadings(state: EditorState): OutlineHeading[] {
|
||||
const headings: OutlineHeading[] = [];
|
||||
// Parse the complete document, independent of CodeMirror's viewport/time-limited syntax tree.
|
||||
const markdown = state.doc.toString();
|
||||
const parsedMarkdown = maskDisplayMath(markdown);
|
||||
const tree = markdownLanguage.parser.parse(parsedMarkdown);
|
||||
const environment = {};
|
||||
// Resolve reference labels only when the document can contain link definitions.
|
||||
if (parsedMarkdown.includes(']:')) inlineMarkdown.parse(parsedMarkdown, environment);
|
||||
tree.iterate({
|
||||
enter(node) {
|
||||
if (!/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) return;
|
||||
const setext = node.name.startsWith('SetextHeading');
|
||||
const cursor = node.node.cursor();
|
||||
let from = node.from;
|
||||
let label = '';
|
||||
do {
|
||||
if (cursor.name !== 'HeaderMark' && cursor.name !== 'QuoteMark' && cursor.name !== 'ListMark') continue;
|
||||
// Setext's underline and its enclosing quote/list prefix are not label content.
|
||||
const to = setext && cursor.name === 'HeaderMark'
|
||||
? state.doc.lineAt(cursor.from).from : cursor.from;
|
||||
label += state.sliceDoc(from, Math.max(from, to));
|
||||
from = cursor.to;
|
||||
} while (cursor.next() && cursor.from < node.to);
|
||||
if (!setext) label += state.sliceDoc(from, node.to);
|
||||
headings.push({
|
||||
level: Number(node.name.at(-1)),
|
||||
text: inlineText(inlineMarkdown.parseInline(label, environment)).replace(/\s+/gu, ' ').trim(),
|
||||
pos: node.from,
|
||||
end: node.to,
|
||||
});
|
||||
return false;
|
||||
},
|
||||
});
|
||||
return headings;
|
||||
}
|
||||
|
||||
/** Headings are in document order; body content remains associated with the preceding heading. */
|
||||
export function activeHeadingIndex(headings: readonly OutlineHeading[], pos: number): number {
|
||||
let low = 0;
|
||||
let high = headings.length;
|
||||
while (low < high) {
|
||||
const middle = (low + high) >>> 1;
|
||||
if (headings[middle].pos <= pos) low = middle + 1;
|
||||
else high = middle;
|
||||
}
|
||||
return low - 1;
|
||||
}
|
||||
|
||||
/** Temporary anchors only; validate against fresh extraction before navigating. */
|
||||
export function mapSourceHeadings(headings: readonly OutlineHeading[], changes: ChangeDesc): OutlineHeading[] {
|
||||
const mapped: OutlineHeading[] = [];
|
||||
for (const heading of headings) {
|
||||
const pos = changes.mapPos(heading.pos, 1, MapMode.TrackAfter);
|
||||
const end = changes.mapPos(heading.end, -1);
|
||||
if (pos !== null && pos < end) mapped.push({ ...heading, pos, end });
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
|
||||
/** A replaced opening token no longer identifies the original semantic heading. */
|
||||
export function mapDocumentHeadings(headings: readonly OutlineHeading[], mapping: Mapping): OutlineHeading[] {
|
||||
const mapped: OutlineHeading[] = [];
|
||||
for (const heading of headings) {
|
||||
const start = mapping.mapResult(heading.pos, 1);
|
||||
const end = mapping.map(heading.end, -1);
|
||||
if (!start.deleted && start.pos < end) mapped.push({ ...heading, pos: start.pos, end });
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
/*
|
||||
* Renaming a note rewrites the links to it in every note that links there (see
|
||||
* `update_wikilinks_after_rename` in the backend). A note that is open with unsaved edits has to
|
||||
* follow in the editor, or its next save would write the old links back. These rules mirror the
|
||||
* backend's; both are checked against `tests/fixtures/renamed-links.json`.
|
||||
*/
|
||||
|
||||
export interface LinkRename {
|
||||
/** Vault-relative path of the note without `.md`, before and after. */
|
||||
old_ref: string;
|
||||
new_ref: string;
|
||||
old_title: string;
|
||||
new_title: string;
|
||||
/** Links written with the title follow (the title changed and no other note has it). */
|
||||
title_rules: boolean;
|
||||
/** No other note has this file name, so a bare file name or top-level path means this note. */
|
||||
file_rules?: boolean;
|
||||
}
|
||||
|
||||
export interface RenamedLink {
|
||||
ref: string;
|
||||
display: string | null;
|
||||
}
|
||||
|
||||
const lower = (value: string) => value.toLowerCase();
|
||||
|
||||
function splitRef(ref: string): [string, string] {
|
||||
const slash = ref.lastIndexOf('/');
|
||||
return slash < 0 ? ['', ref] : [ref.slice(0, slash), ref.slice(slash + 1)];
|
||||
}
|
||||
|
||||
const joinRef = (dir: string, name: string) => (dir ? `${dir}/${name}` : name);
|
||||
|
||||
/** `name` without a trailing `.md` (any capitals), and that extension as written. */
|
||||
function splitMdExt(name: string): [string, string] {
|
||||
return /\.md$/i.test(name) ? [name.slice(0, -3), name.slice(-3)] : [name, ''];
|
||||
}
|
||||
|
||||
const byPath = (renames: readonly LinkRename[], ref: string) =>
|
||||
renames.find((rename) => lower(rename.old_ref) === lower(ref));
|
||||
|
||||
/**
|
||||
* The wiki link `[[ref]]` or `[[ref|display]]` after the renames, or null when it is not affected.
|
||||
* `ref` may carry a heading or block (`Note#Part`, `Note^id`) and a `.md` extension; both are kept.
|
||||
*/
|
||||
export function renamedLink(ref: string, display: string | null, renames: LinkRename | readonly LinkRename[]): RenamedLink | null {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const anchorAt = ref.search(/[#^]/);
|
||||
const name = anchorAt < 0 ? ref : ref.slice(0, anchorAt);
|
||||
const anchor = anchorAt < 0 ? '' : ref.slice(anchorAt);
|
||||
const [base, ext] = splitMdExt(name);
|
||||
let rename = list.find((candidate) => candidate.title_rules && lower(candidate.old_title) === lower(base));
|
||||
let next = rename?.new_title;
|
||||
if (!rename) {
|
||||
rename = byPath(list, base.replace(/\\/g, '/'));
|
||||
if (!rename || rename.old_ref === rename.new_ref) return null;
|
||||
const stemChanges = splitRef(rename.old_ref)[1] !== splitRef(rename.new_ref)[1];
|
||||
// At the top of the vault the path is the bare name, as unsure as a title link.
|
||||
if (!rename.old_ref.includes('/') && !(rename.file_rules && stemChanges)) return null;
|
||||
next = rename.new_ref;
|
||||
}
|
||||
const followsTitle = display === rename.old_title && rename.old_title !== rename.new_title;
|
||||
return { ref: next + ext + anchor, display: followsTitle ? rename.new_title : display };
|
||||
}
|
||||
|
||||
/** Resolve `.` and `..` in a slash path; null when it climbs out of the vault. */
|
||||
function normalizeDir(path: string): string | null {
|
||||
const parts: string[] = [];
|
||||
for (const part of path.split('/')) {
|
||||
if (!part || part === '.') continue;
|
||||
if (part === '..') {
|
||||
if (!parts.length) return null;
|
||||
parts.pop();
|
||||
} else parts.push(part);
|
||||
}
|
||||
return parts.join('/');
|
||||
}
|
||||
|
||||
/** The `../`-style prefix that leads from folder `from` to folder `to`, ending in `/` unless empty. */
|
||||
function relativeDir(from: string, to: string): string {
|
||||
const a = from.split('/').filter(Boolean);
|
||||
const b = to.split('/').filter(Boolean);
|
||||
let common = 0;
|
||||
while (common < a.length && common < b.length && a[common] === b[common]) common++;
|
||||
return '../'.repeat(a.length - common) + b.slice(common).map((part) => `${part}/`).join('');
|
||||
}
|
||||
|
||||
function decode(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/** Characters a link destination without `<>` cannot hold as they are. */
|
||||
function encodeFileName(name: string): string {
|
||||
return name.replace(/[% \t()<>#]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
|
||||
}
|
||||
|
||||
const encodePath = (path: string, angled: boolean) => (angled ? path : path.split('/').map(encodeFileName).join('/'));
|
||||
|
||||
/**
|
||||
* The destination of a Markdown link (`Note.md`, `../Folder/Note%20name.md#Part`, `<Note name.md>`)
|
||||
* after the renames, or null when it does not point at a renamed note. `noteDir` is the
|
||||
* vault-relative folder of the note holding the link. The link keeps its form: relative stays
|
||||
* relative, from the vault root stays so, and a bare name stays bare when it still finds the note.
|
||||
*/
|
||||
export function renamedHref(href: string, noteDir: string, renames: LinkRename | readonly LinkRename[]): string | null {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const angled = href.length >= 2 && href.startsWith('<') && href.endsWith('>');
|
||||
const dest = angled ? href.slice(1, -1) : href;
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(dest) || !dest || dest.startsWith('#')) return null;
|
||||
const hashAt = dest.indexOf('#');
|
||||
const path = hashAt < 0 ? dest : dest.slice(0, hashAt);
|
||||
const anchor = hashAt < 0 ? '' : dest.slice(hashAt);
|
||||
const slash = path.lastIndexOf('/');
|
||||
const rawDir = slash < 0 ? '' : path.slice(0, slash + 1);
|
||||
const rawFile = path.slice(slash + 1);
|
||||
const [, ext] = splitMdExt(rawFile);
|
||||
if (!ext) return null;
|
||||
const [stem] = splitMdExt(decode(rawFile));
|
||||
const dir = decode(rawDir).replace(/\\/g, '/');
|
||||
let rename: LinkRename | undefined;
|
||||
let form: 'bare' | 'relative' | 'root' = 'relative';
|
||||
if (!dir) {
|
||||
rename = byPath(list, joinRef(noteDir, stem));
|
||||
if (!rename) {
|
||||
// A bare name from another folder finds the note by its unique file name.
|
||||
rename = list.find((candidate) => {
|
||||
const [, oldStem] = splitRef(candidate.old_ref);
|
||||
return candidate.file_rules && lower(oldStem) === lower(stem) && oldStem !== splitRef(candidate.new_ref)[1];
|
||||
});
|
||||
form = 'bare';
|
||||
}
|
||||
} else {
|
||||
const relative = dir.startsWith('/') ? null : normalizeDir(`${noteDir}/${dir}`);
|
||||
rename = relative === null ? undefined : byPath(list, joinRef(relative, stem));
|
||||
if (!rename) {
|
||||
const root = normalizeDir(dir);
|
||||
rename = root === null ? undefined : byPath(list, joinRef(root, stem));
|
||||
form = 'root';
|
||||
}
|
||||
}
|
||||
if (!rename || rename.old_ref === rename.new_ref) return null;
|
||||
const [oldDir] = splitRef(rename.old_ref);
|
||||
const [newDir, newStem] = splitRef(rename.new_ref);
|
||||
const file = encodePath(newStem + ext, angled);
|
||||
const prefix = lower(oldDir) === lower(newDir)
|
||||
? rawDir
|
||||
: form === 'bare'
|
||||
? ''
|
||||
: form === 'relative'
|
||||
? encodePath(relativeDir(noteDir, newDir), angled)
|
||||
: (dir.startsWith('/') ? '/' : '') + (newDir ? `${encodePath(newDir, angled)}/` : '');
|
||||
const next = prefix + file + anchor;
|
||||
return angled ? `<${next}>` : next;
|
||||
}
|
||||
|
||||
export interface TextChange {
|
||||
from: number;
|
||||
to: number;
|
||||
insert: string;
|
||||
}
|
||||
|
||||
/** Ranges of `text` outside fenced code blocks and inline code, where links are links. */
|
||||
function proseRanges(text: string): [number, number][] {
|
||||
const ranges: [number, number][] = [];
|
||||
let fence: { char: string; length: number } | null = null;
|
||||
let offset = 0;
|
||||
for (const line of text.split(/(?<=\n)/)) {
|
||||
const start = offset;
|
||||
offset += line.length;
|
||||
const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line.replace(/\r?\n$/, ''));
|
||||
if (fence) {
|
||||
if (opening && opening[1][0] === fence.char && opening[1].length >= fence.length && !opening[2].trim()) fence = null;
|
||||
continue;
|
||||
}
|
||||
if (opening && !(opening[1][0] === '`' && opening[2].includes('`'))) {
|
||||
fence = { char: opening[1][0], length: opening[1].length };
|
||||
continue;
|
||||
}
|
||||
let from = start;
|
||||
const ticks = /`+/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = ticks.exec(line))) {
|
||||
const closing = new RegExp(`(?<!\`)${match[0]}(?!\`)`, 'g');
|
||||
closing.lastIndex = match.index + match[0].length;
|
||||
const end = closing.exec(line);
|
||||
if (!end) continue;
|
||||
ranges.push([from, start + match.index]);
|
||||
from = start + end.index + end[0].length;
|
||||
ticks.lastIndex = end.index + end[0].length;
|
||||
}
|
||||
ranges.push([from, offset]);
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
const WIKI_LINK = /\[\[([^[\]\n]+?)\]\]/g;
|
||||
const MARKDOWN_LINK = /\[([^[\]\n]*)\]\((<[^<>\n]*>|(?:[^\s()<>]|\([^\s()<>]*\))+)([^)\n]*)\)/g;
|
||||
|
||||
/** The edits that bring the wiki and Markdown links in Markdown text in line with the rename. */
|
||||
export function renamedLinkChanges(text: string, renames: LinkRename | readonly LinkRename[], noteDir = ''): TextChange[] {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const changes: TextChange[] = [];
|
||||
for (const [from, to] of proseRanges(text)) {
|
||||
const prose = text.slice(from, to);
|
||||
for (const match of prose.matchAll(WIKI_LINK)) {
|
||||
const inner = match[1];
|
||||
// In a table cell the alias separator is written `\|`, since a bare `|` ends the cell.
|
||||
const bar = inner.indexOf('|');
|
||||
const escaped = bar > 0 && inner[bar - 1] === '\\';
|
||||
const ref = bar < 0 ? inner : inner.slice(0, escaped ? bar - 1 : bar);
|
||||
const display = bar < 0 ? null : inner.slice(bar + 1);
|
||||
const next = renamedLink(ref, display, list);
|
||||
if (!next) continue;
|
||||
const separator = escaped ? '\\|' : '|';
|
||||
const insert = next.display === null ? `[[${next.ref}]]` : `[[${next.ref}${separator}${next.display}]]`;
|
||||
if (insert !== match[0]) changes.push({ from: from + match.index!, to: from + match.index! + match[0].length, insert });
|
||||
}
|
||||
for (const match of prose.matchAll(MARKDOWN_LINK)) {
|
||||
const href = renamedHref(match[2], noteDir, list);
|
||||
if (href === null) continue;
|
||||
// Link text that was the old title follows the new one.
|
||||
const titled = list.find((rename) => rename.old_title === match[1] && rename.old_title !== rename.new_title);
|
||||
const label = titled ? titled.new_title : match[1];
|
||||
const insert = `[${label}](${href}${match[3]})`;
|
||||
if (insert !== match[0]) changes.push({ from: from + match.index!, to: from + match.index! + match[0].length, insert });
|
||||
}
|
||||
}
|
||||
return changes.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/** Matches may overlap ("aa" in "aaa"); replacing all of them takes each stretch of text once. */
|
||||
export function replaceableMatches(results: NoteSearchMatch[]): NoteSearchMatch[] {
|
||||
const picked: NoteSearchMatch[] = [];
|
||||
let end = -1;
|
||||
for (const match of results) {
|
||||
if (match.from < end) continue;
|
||||
picked.push(match);
|
||||
end = match.to;
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
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;
|
||||
scroll?: () => void;
|
||||
} = {}) {
|
||||
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),
|
||||
scroll: () => { events.scroll?.(); return 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) }); }
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Table } from '@tiptap/extension-table';
|
||||
import { columnResizing, tableEditing } from '@tiptap/pm/tables';
|
||||
|
||||
/**
|
||||
* TipTap registers the table node view together with its column-resizing plugin, and skips both
|
||||
* when the editor is created read-only. Without the node view there is no `.tableWrapper`, so a
|
||||
* wide table loses its horizontal scroll until the app is restarted in Edit mode.
|
||||
*
|
||||
* Keep the table view and its wrapper even when the initial state is View mode. The resizing
|
||||
* handlers already ignore non-editable views; this only makes the wrapper available to scroll.
|
||||
*/
|
||||
export const AlwaysResizableTable = Table.extend({
|
||||
addProseMirrorPlugins() {
|
||||
const plugins = [];
|
||||
if (this.options.resizable) {
|
||||
plugins.push(columnResizing({
|
||||
handleWidth: this.options.handleWidth,
|
||||
cellMinWidth: this.options.cellMinWidth,
|
||||
defaultCellMinWidth: this.options.cellMinWidth,
|
||||
View: this.options.View,
|
||||
lastColumnResizable: this.options.lastColumnResizable,
|
||||
}));
|
||||
}
|
||||
plugins.push(tableEditing({ allowTableNodeSelection: this.options.allowTableNodeSelection }));
|
||||
return plugins;
|
||||
},
|
||||
});
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -19,11 +19,15 @@ export interface ActionDef {
|
||||
|
||||
// Every customizable action and its factory-default binding. These mirror the
|
||||
// handlers in AppLayout.handleKeydown and the rows in InfoPanel's Shortcuts tab.
|
||||
const isMac = typeof navigator !== "undefined" && navigator.platform.startsWith("Mac");
|
||||
|
||||
export const ACTIONS: ActionDef[] = [
|
||||
{ id: "new-note", label: "New note", group: "General", default: { mod: true, code: "KeyN" } },
|
||||
{ id: "save", label: "Save", group: "General", default: { mod: true, code: "KeyS" } },
|
||||
{ id: "quick-open", label: "Quick open", group: "General", default: { mod: true, code: "KeyP" } },
|
||||
{ id: "find-in-note", label: "Find in note", group: "General", default: { mod: true, code: "KeyF" } },
|
||||
// Cmd+H hides the application on macOS.
|
||||
{ id: "replace-in-note", label: "Replace in note", group: "General", default: isMac ? { mod: true, alt: true, code: "KeyF" } : { mod: true, code: "KeyH" } },
|
||||
{ id: "search-vault", label: "Search vault", group: "General", default: { mod: true, shift: true, code: "KeyF" } },
|
||||
{ id: "open-new-window", label: "Open note in new window", group: "General", default: { mod: true, shift: true, code: "KeyW" } },
|
||||
|
||||
@@ -123,8 +127,6 @@ export function bindingsEqual(a: Binding, b: Binding): boolean {
|
||||
return !!a.mod === !!b.mod && !!a.shift === !!b.shift && !!a.alt === !!b.alt && a.code === b.code;
|
||||
}
|
||||
|
||||
const isMac = typeof navigator !== "undefined" && navigator.platform.startsWith("Mac");
|
||||
|
||||
const CODE_LABELS: Record<string, string> = {
|
||||
Backslash: "\\",
|
||||
BracketLeft: "[",
|
||||
|
||||
@@ -43,6 +43,13 @@ export const darkThemes = [
|
||||
'cyberpunk',
|
||||
'black',
|
||||
'one-dark',
|
||||
'matrix',
|
||||
'amber-crt',
|
||||
'deep-ocean',
|
||||
'graphite',
|
||||
'nebula',
|
||||
'wine',
|
||||
'jade',
|
||||
];
|
||||
|
||||
export function isDarkTheme(theme: string): boolean {
|
||||
|
||||
+84
-27
@@ -11,6 +11,7 @@ import type {
|
||||
VaultState,
|
||||
ViewMode,
|
||||
SortMode,
|
||||
TagStyle,
|
||||
} from "$lib/types";
|
||||
|
||||
// App state
|
||||
@@ -47,6 +48,7 @@ export const showSettings = writable(false);
|
||||
export const settingsTab = writable<string | null>(null);
|
||||
export const showInfo = writable(false);
|
||||
export const notebookIcons = writable<Record<string, string>>({});
|
||||
export const tagStyles = writable<Record<string, TagStyle>>({});
|
||||
export const quickAccessPaths = writable<string[]>([]);
|
||||
export const collapsedNotebooks = writable<string[]>([]);
|
||||
|
||||
@@ -115,9 +117,23 @@ export const resolvedTheme = derived(
|
||||
|
||||
// Sync (WebDAV) - global status so the top-bar button reflects any sync,
|
||||
// whoever triggered it (manual button, settings, interval, on-change).
|
||||
export const syncState = writable<{ running: boolean; error: string | null }>({
|
||||
export interface SyncSummary {
|
||||
uploaded?: number;
|
||||
downloaded?: number;
|
||||
deleted_local?: number;
|
||||
deleted_remote?: number;
|
||||
conflicts?: number;
|
||||
}
|
||||
// `result` is what the last finished sync did, so Settings reports the same outcome for every
|
||||
// way a sync can start.
|
||||
export const syncState = writable<{
|
||||
running: boolean;
|
||||
error: string | null;
|
||||
result: { vault: string; summary: SyncSummary } | null;
|
||||
}>({
|
||||
running: false,
|
||||
error: null,
|
||||
result: null,
|
||||
});
|
||||
|
||||
// Update state
|
||||
@@ -190,13 +206,33 @@ function createNavHistory() {
|
||||
const store = writable<NavHistoryState>({ stack: [], index: -1, skipping: false });
|
||||
return {
|
||||
subscribe: store.subscribe,
|
||||
clear() {
|
||||
store.set({ stack: [], index: -1, skipping: false });
|
||||
},
|
||||
push(path: string) {
|
||||
store.update(s => {
|
||||
if (s.skipping) return { ...s, skipping: false };
|
||||
if (s.stack[s.index] === path) return s;
|
||||
const trimmed = s.stack.slice(0, s.index + 1);
|
||||
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 {
|
||||
let target: string | null = null;
|
||||
store.update(s => {
|
||||
@@ -213,7 +249,38 @@ export const navHistory = createNavHistory();
|
||||
export const canGoBack = derived(navHistory, $h => $h.index > 0);
|
||||
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
|
||||
// Entries are replaced, not mutated, when a note changes, so a parsed date stays valid for its entry.
|
||||
const noteTimestamps = { created: new WeakMap<NoteEntry, number>(), modified: new WeakMap<NoteEntry, number>() };
|
||||
|
||||
export const sortedNotes = derived(
|
||||
[notes, sortMode, viewMode, noteOrder],
|
||||
([$notes, $sortMode, $viewMode, $noteOrder]) => {
|
||||
@@ -224,35 +291,25 @@ export const sortedNotes = derived(
|
||||
|
||||
const pinned = $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 ? noteTimestamps[dateField] : null;
|
||||
if (dateField && timestamps) {
|
||||
for (const note of $notes) {
|
||||
if (!timestamps.has(note)) timestamps.set(note, Date.parse(note.meta[dateField]));
|
||||
}
|
||||
}
|
||||
|
||||
const sortFn = (a: NoteEntry, b: NoteEntry) => {
|
||||
switch ($sortMode) {
|
||||
case "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 ob = $noteOrder[b.path] ?? Number.MAX_SAFE_INTEGER;
|
||||
if (oa !== ob) return oa - ob;
|
||||
return a.meta.title.localeCompare(b.meta.title);
|
||||
}
|
||||
case "title":
|
||||
return compareNaturalNames(a.meta.title, 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()
|
||||
);
|
||||
if (timestamps) return timestamps.get(b)! - timestamps.get(a)!;
|
||||
if ($sortMode === "custom") {
|
||||
const oa = $noteOrder[a.path] ?? Number.MAX_SAFE_INTEGER;
|
||||
const ob = $noteOrder[b.path] ?? Number.MAX_SAFE_INTEGER;
|
||||
if (oa !== ob) return oa - ob;
|
||||
return a.meta.title.localeCompare(b.meta.title);
|
||||
}
|
||||
return compareNaturalNames(a.meta.title, b.meta.title);
|
||||
};
|
||||
|
||||
return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)];
|
||||
|
||||
+51
-1
@@ -34,6 +34,16 @@ export interface NotebookEntry {
|
||||
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 {
|
||||
path: string;
|
||||
meta: NoteMeta;
|
||||
@@ -53,7 +63,14 @@ export interface VaultConfig {
|
||||
sync_on_open?: boolean;
|
||||
sync_on_change?: boolean;
|
||||
sync_interval_minutes?: number;
|
||||
sync_folder_requests?: number;
|
||||
last_sync_time?: string | null;
|
||||
last_backup_time?: string | null;
|
||||
}
|
||||
|
||||
export interface PendingOpenFile {
|
||||
id: number;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface ExternalVaultResult {
|
||||
@@ -83,6 +100,11 @@ export interface CustomTheme {
|
||||
|
||||
export type StartupView = "all" | "quickaccess" | "tasks" | "daily";
|
||||
|
||||
export interface ToolbarLayout {
|
||||
main: string[];
|
||||
more: string[];
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
vaults: VaultConfig[];
|
||||
active_vault: string | null;
|
||||
@@ -92,7 +114,9 @@ export interface AppConfig {
|
||||
system_dark_theme: string;
|
||||
accent_color: string | null;
|
||||
font_size: number | null;
|
||||
preferred_font_size?: number | null;
|
||||
scroll_to_change_font_size: boolean;
|
||||
toolbar_layout: ToolbarLayout | null;
|
||||
font_family: string | null;
|
||||
line_height: number | null;
|
||||
ui_scale: number | null;
|
||||
@@ -120,7 +144,6 @@ export interface AppConfig {
|
||||
backup_frequency: string;
|
||||
backup_max_count: number;
|
||||
backup_location: string | null;
|
||||
last_backup_time: string | null;
|
||||
backup_include_attachments: boolean;
|
||||
max_versions_per_note: number;
|
||||
ai_provider: string | null;
|
||||
@@ -172,16 +195,40 @@ export interface VaultState {
|
||||
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 {
|
||||
path: string;
|
||||
title: string;
|
||||
snippet: string;
|
||||
score: number;
|
||||
title_matches: SearchMatch[];
|
||||
snippet_matches: SearchMatch[];
|
||||
match_target: SearchTarget | null;
|
||||
}
|
||||
|
||||
export interface SearchPage {
|
||||
results: SearchResult[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface FileEvent {
|
||||
vault_path: string;
|
||||
event_type: string;
|
||||
path: string;
|
||||
note?: NoteEntry | null;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
@@ -205,6 +252,8 @@ export interface BackupEntry {
|
||||
path: string;
|
||||
size: number;
|
||||
created: string;
|
||||
/** Made from a different vault folder; all vaults share one backup folder. */
|
||||
other_vault?: boolean;
|
||||
}
|
||||
|
||||
export interface VersionEntry {
|
||||
@@ -213,6 +262,7 @@ export interface VersionEntry {
|
||||
}
|
||||
|
||||
export interface AiStreamEvent {
|
||||
request_id: string;
|
||||
event_type: string;
|
||||
text: string | null;
|
||||
error: string | null;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { getCurrentWebview } from '@tauri-apps/api/webview';
|
||||
import { isAndroid } from '$lib/platform';
|
||||
|
||||
// Interface scale (#288). The CSS is sized in desktop px, which reads too small on phones, so
|
||||
// Android starts one step up when the user hasn't picked a scale yet.
|
||||
export const defaultUiScale = isAndroid ? 1.15 : 1;
|
||||
|
||||
// Scaling up narrows the layout viewport. Keep it at least as wide as the widest mobile menus
|
||||
// (~290px) so they still fit on narrow phones. Uses the short side so rotating doesn't change it.
|
||||
const minAndroidLayoutWidth = 290;
|
||||
const maxAndroidUiScale =
|
||||
isAndroid && typeof screen !== 'undefined'
|
||||
? Math.max(1, Math.min(screen.width, screen.height) / minAndroidLayoutWidth)
|
||||
: Infinity;
|
||||
|
||||
export const uiScalePresets: { label: string; value: number }[] = isAndroid
|
||||
? [
|
||||
{ label: '100%', value: 1 },
|
||||
{ label: '115%', value: 1.15 },
|
||||
{ label: '125%', value: 1.25 },
|
||||
{ label: '140%', value: 1.4 },
|
||||
].filter((preset) => preset.value <= maxAndroidUiScale)
|
||||
: [
|
||||
{ label: '80%', value: 0.8 },
|
||||
{ label: '90%', value: 0.9 },
|
||||
{ label: '100%', value: 1 },
|
||||
{ label: '125%', value: 1.25 },
|
||||
{ label: '150%', value: 1.5 },
|
||||
{ label: '175%', value: 1.75 },
|
||||
{ label: '200%', value: 2 },
|
||||
];
|
||||
|
||||
// Android's WebView ignores setZoom (wry no-op), and CSS `zoom` would double-scale every popup
|
||||
// positioned from clientX/getBoundingClientRect. Pinning the viewport scale instead shrinks the
|
||||
// layout viewport, like the system "Display size" setting, so all coordinates stay in CSS px.
|
||||
// Needs useWideViewPort, which MainActivity enables.
|
||||
let androidUiScale = defaultUiScale;
|
||||
let androidResizeListenerInstalled = false;
|
||||
|
||||
function updateAndroidViewportScale() {
|
||||
const meta = document.querySelector('meta[name="viewport"]');
|
||||
if (!meta) return;
|
||||
const viewport = window.visualViewport;
|
||||
// WebView can keep its 980px fallback layout if only a scale is specified. Give it the
|
||||
// actual visible width in CSS px, including in landscape and split-screen windows.
|
||||
const availableWidth = Math.round(viewport ? viewport.width * viewport.scale : screen.width);
|
||||
const scale = Math.min(androidUiScale, maxAndroidUiScale, Math.max(1, availableWidth / minAndroidLayoutWidth));
|
||||
const width = Math.floor(availableWidth / scale);
|
||||
const content = `width=${width}, initial-scale=${scale}, minimum-scale=${scale}, maximum-scale=${scale}, user-scalable=no, viewport-fit=cover`;
|
||||
if (meta.getAttribute('content') !== content) meta.setAttribute('content', content);
|
||||
}
|
||||
|
||||
function applyAndroidViewportScale(scale: number) {
|
||||
androidUiScale = scale;
|
||||
updateAndroidViewportScale();
|
||||
if (!androidResizeListenerInstalled) {
|
||||
window.addEventListener('resize', updateAndroidViewportScale);
|
||||
androidResizeListenerInstalled = true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyUiScale(scale: number) {
|
||||
if (isAndroid) {
|
||||
applyAndroidViewportScale(scale);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await getCurrentWebview().setZoom(scale);
|
||||
} catch (e) {
|
||||
console.error('Failed to apply interface scale:', e);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
@@ -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();
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* HTML copies are styled for the receiving document. Word, LibreOffice and many email
|
||||
* editors apply their own Normal paragraph style (typically 1.08 line spacing plus space
|
||||
* after) to bare `<p>` tags, so a copied note arrives with more vertical space than it has
|
||||
* in HelixNotes. Inline single spacing keeps the note's own blank lines as the only
|
||||
* paragraph spacing; the generated HTML stays semantic (p, h1, li, ...).
|
||||
*/
|
||||
|
||||
const COPY_BLOCK_TAGS = 'p|h[1-6]|li|blockquote';
|
||||
const COPY_BLOCK_STYLE = 'line-height:100%';
|
||||
const COPY_PARAGRAPH_STYLE = 'line-height:100%;margin:0';
|
||||
|
||||
/**
|
||||
* Add single-line spacing to the block elements of a copied HTML fragment. Appending the
|
||||
* declarations lets them win over any inline line-height or margin already on the element.
|
||||
*/
|
||||
export function applySingleLineSpacing(html: string): string {
|
||||
return html.replace(
|
||||
new RegExp(`<(${COPY_BLOCK_TAGS})\\b([^>]*)>`, 'gi'),
|
||||
(_match, tag: string, attributes: string) => {
|
||||
const blockStyle = tag.toLowerCase() === 'blockquote' ? COPY_BLOCK_STYLE : COPY_PARAGRAPH_STYLE;
|
||||
if (!/\bstyle\s*=/i.test(attributes)) {
|
||||
return `<${tag}${attributes} style="${blockStyle}">`;
|
||||
}
|
||||
const styled = attributes.replace(
|
||||
/\bstyle\s*=\s*(["'])(.*?)\1/i,
|
||||
(_styleMatch, quote: string, value: string) => {
|
||||
const existing = value.trim().replace(/;?\s*$/, '');
|
||||
return `style=${quote}${existing ? `${existing};` : ''}${blockStyle}${quote}`;
|
||||
},
|
||||
);
|
||||
return `<${tag}${styled}>`;
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
classifyClipboardType,
|
||||
collectClipboardPayload,
|
||||
isEmptyPayload,
|
||||
needsNativeClipboard,
|
||||
pastedFileName,
|
||||
plainTextFromUriList,
|
||||
withNativeClipboard
|
||||
} from './clipboard-paste.ts';
|
||||
|
||||
const item = entries => ({
|
||||
types: Object.keys(entries),
|
||||
getType: async type => {
|
||||
const value = entries[type];
|
||||
return value instanceof Blob ? value : new Blob([value], { type });
|
||||
}
|
||||
});
|
||||
const png = new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' });
|
||||
|
||||
test('classifies text formats as text, attachments as files and metadata as ignored', () => {
|
||||
assert.equal(classifyClipboardType('text/plain'), 'plain');
|
||||
assert.equal(classifyClipboardType('text/plain;charset=utf-8'), 'plain');
|
||||
assert.equal(classifyClipboardType('TEXT/HTML'), 'html');
|
||||
for (const type of ['text/uri-list', 'text/rtf', 'text/x-moz-url', 'text/csv']) {
|
||||
assert.equal(classifyClipboardType(type), 'string', type);
|
||||
}
|
||||
for (const type of ['image/png', 'image/jpeg', 'image/svg+xml', 'application/pdf']) {
|
||||
assert.equal(classifyClipboardType(type), 'file', type);
|
||||
}
|
||||
for (const type of ['web application/x-custom', 'chromium/x-web-custom-data', 'application/x-moz-nativeimage', 'application/octet-stream', '']) {
|
||||
assert.equal(classifyClipboardType(type), 'ignore', type);
|
||||
}
|
||||
});
|
||||
|
||||
test('a copied link stays text and never becomes a uri-list attachment', async () => {
|
||||
const payload = await collectClipboardPayload([item({ 'text/uri-list': 'https://example.com/a\r\n' })]);
|
||||
assert.equal(payload.files.length, 0);
|
||||
assert.equal(payload.text, 'https://example.com/a');
|
||||
assert.deepEqual(payload.strings, [['text/uri-list', 'https://example.com/a\r\n']]);
|
||||
});
|
||||
|
||||
test('text/plain wins over the uri-list fallback', async () => {
|
||||
const payload = await collectClipboardPayload([item({ 'text/plain': 'Example', 'text/uri-list': 'https://example.com' })]);
|
||||
assert.equal(payload.text, 'Example');
|
||||
assert.equal(payload.files.length, 0);
|
||||
});
|
||||
|
||||
test('uri-list comments and blank lines are skipped', () => {
|
||||
assert.equal(plainTextFromUriList('# copied from browser\n\n https://a.example \nhttps://b.example'), 'https://a.example');
|
||||
assert.equal(plainTextFromUriList('# only a comment\n'), '');
|
||||
});
|
||||
|
||||
test('images and PDFs become named files alongside the text and HTML', async () => {
|
||||
const pdf = new Blob(['%PDF-1.7'], { type: 'application/pdf' });
|
||||
const payload = await collectClipboardPayload([
|
||||
item({ 'text/html': '<img src="https://example.com/cat.png">', 'image/png': png }),
|
||||
item({ 'application/pdf': pdf })
|
||||
]);
|
||||
assert.equal(payload.html, '<img src="https://example.com/cat.png">');
|
||||
assert.deepEqual(payload.files.map(file => [file.name, file.type]), [
|
||||
['pasted-image.png', 'image/png'],
|
||||
['pasted-file-2.pdf', 'application/pdf']
|
||||
]);
|
||||
assert.equal(isEmptyPayload(payload), false);
|
||||
});
|
||||
|
||||
test('metadata-only clipboards are empty and are never read', async () => {
|
||||
const read = [];
|
||||
const payload = await collectClipboardPayload([{
|
||||
types: ['chromium/x-web-custom-data', 'web application/x-custom'],
|
||||
getType: async type => { read.push(type); return new Blob(['x']); }
|
||||
}]);
|
||||
assert.deepEqual(read, []);
|
||||
assert.equal(isEmptyPayload(payload), true);
|
||||
});
|
||||
|
||||
test('pasted file names use friendly extensions', () => {
|
||||
assert.equal(pastedFileName('image/jpeg', 0), 'pasted-image.jpg');
|
||||
assert.equal(pastedFileName('image/svg+xml', 1), 'pasted-image-2.svg');
|
||||
assert.equal(pastedFileName('application/pdf', 0), 'pasted-file.pdf');
|
||||
});
|
||||
|
||||
test('formatting from other apps survives when the web clipboard only offers plain text (P6)', async () => {
|
||||
// WebKitGTK: navigator.clipboard.read() gives just text/plain for a web page copied in a browser.
|
||||
const web = await collectClipboardPayload([item({ 'text/plain': 'Bold link' })]);
|
||||
assert.equal(needsNativeClipboard(web), true);
|
||||
const merged = withNativeClipboard(web, { text: 'Bold link (native)', html: '<b>Bold</b> <a href="https://x.example">link</a>' });
|
||||
assert.equal(merged.html, '<b>Bold</b> <a href="https://x.example">link</a>');
|
||||
assert.equal(merged.text, 'Bold link', 'web text is kept when present');
|
||||
});
|
||||
|
||||
test('a failed web clipboard read falls back to native text and HTML entirely', () => {
|
||||
assert.equal(needsNativeClipboard(null), true);
|
||||
assert.deepEqual(withNativeClipboard(null, { text: 'plain', html: null }), { text: 'plain', html: '', strings: [], files: [] });
|
||||
assert.equal(isEmptyPayload(withNativeClipboard(null, {})), true, 'nothing textual: the native image read comes next');
|
||||
});
|
||||
|
||||
test('the native clipboard is not consulted when the web clipboard already has HTML or files', async () => {
|
||||
assert.equal(needsNativeClipboard(await collectClipboardPayload([item({ 'text/html': '<b>x</b>' })])), false);
|
||||
assert.equal(needsNativeClipboard(await collectClipboardPayload([item({ 'image/png': png })])), false);
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Turns what the async clipboard API (`navigator.clipboard.read()`) returns into the data a keyboard
|
||||
* paste would carry, so the editor's context-menu Paste can replay it as a real paste event.
|
||||
*
|
||||
* The clipboard holds many representations of one copy: plain text, HTML, URI lists, bitmaps, and
|
||||
* browser/OS bookkeeping formats. Only actual attachments may become files. Text formats such as
|
||||
* `text/uri-list` stay text, and unknown metadata is dropped. Turning them into files would insert
|
||||
* junk attachments like `pasted-0.uri-list`.
|
||||
*/
|
||||
|
||||
/** How one clipboard MIME type is pasted. */
|
||||
export type ClipboardTypeRole = 'plain' | 'html' | 'string' | 'file' | 'ignore';
|
||||
|
||||
/** Attachment types a keyboard paste would deliver as files (see `insertFile` in Editor.svelte). */
|
||||
const FILE_TYPES = /^(?:image\/[\w.+-]+|application\/pdf)$/;
|
||||
|
||||
/** Strips parameters (`text/plain;charset=utf-8`) and case. */
|
||||
export function normalizeClipboardType(type: string): string {
|
||||
return type.split(';')[0].trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function classifyClipboardType(type: string): ClipboardTypeRole {
|
||||
const mime = normalizeClipboardType(type);
|
||||
if (mime === 'text/plain') return 'plain';
|
||||
if (mime === 'text/html') return 'html';
|
||||
// Other text formats (uri-list, rtf, x-moz-url, ...) are string data on the paste event, never files.
|
||||
if (/^text\/[\w.+-]+$/.test(mime)) return 'string';
|
||||
if (FILE_TYPES.test(mime)) return 'file';
|
||||
// `web ...` custom formats, chromium/..., application/x-..., and anything else unrecognized.
|
||||
return 'ignore';
|
||||
}
|
||||
|
||||
/** First URI of an RFC 2483 `text/uri-list`. Lines starting with `#` are comments. */
|
||||
export function plainTextFromUriList(list: string): string {
|
||||
for (const line of list.split(/\r?\n/)) {
|
||||
const uri = line.trim();
|
||||
if (uri && !uri.startsWith('#')) return uri;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
const EXTENSIONS: Record<string, string> = { 'image/jpeg': 'jpg', 'image/svg+xml': 'svg', 'application/pdf': 'pdf' };
|
||||
|
||||
/** File name for a pasted attachment, matching the `pasted-image.png` name of the native image fallback. */
|
||||
export function pastedFileName(type: string, index: number): string {
|
||||
const mime = normalizeClipboardType(type);
|
||||
const extension = EXTENSIONS[mime] ?? (mime.split('/')[1]?.replace(/[^\w]/g, '') || 'bin');
|
||||
const base = mime.startsWith('image/') ? 'pasted-image' : 'pasted-file';
|
||||
return `${base}${index > 0 ? `-${index + 1}` : ''}.${extension}`;
|
||||
}
|
||||
|
||||
export interface ClipboardItemLike {
|
||||
readonly types: readonly string[];
|
||||
getType(type: string): Promise<Blob>;
|
||||
}
|
||||
|
||||
export interface ClipboardPastePayload {
|
||||
text: string;
|
||||
html: string;
|
||||
/** Other text formats, keyed by normalized MIME type. */
|
||||
strings: [type: string, value: string][];
|
||||
files: File[];
|
||||
}
|
||||
|
||||
/** Web clipboard data still missing formats a keyboard paste would carry, so the native clipboard is needed. */
|
||||
export function needsNativeClipboard(payload: ClipboardPastePayload | null): boolean {
|
||||
return !payload || (!payload.html && payload.files.length === 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill in what the web clipboard didn't provide from the native clipboard. WebKitGTK often returns
|
||||
* nothing, or only `text/plain`, for content copied from other applications; Ctrl+V would still
|
||||
* have received the HTML (formatting, links), so a paste without it is not the same paste.
|
||||
*/
|
||||
export function withNativeClipboard(
|
||||
payload: ClipboardPastePayload | null,
|
||||
native: { text?: string | null; html?: string | null },
|
||||
): ClipboardPastePayload {
|
||||
return {
|
||||
text: payload?.text || native.text || '',
|
||||
html: payload?.html || native.html || '',
|
||||
strings: payload?.strings ?? [],
|
||||
files: payload?.files ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function isEmptyPayload(payload: ClipboardPastePayload): boolean {
|
||||
return !payload.text && !payload.html && payload.files.length === 0;
|
||||
}
|
||||
|
||||
/** Reads every clipboard item into paste data, classifying each representation. */
|
||||
export async function collectClipboardPayload(items: readonly ClipboardItemLike[]): Promise<ClipboardPastePayload> {
|
||||
const payload: ClipboardPastePayload = { text: '', html: '', strings: [], files: [] };
|
||||
for (const item of items) {
|
||||
for (const type of item.types) {
|
||||
const role = classifyClipboardType(type);
|
||||
if (role === 'ignore') continue;
|
||||
const blob = await item.getType(type);
|
||||
if (role === 'file') {
|
||||
const mime = normalizeClipboardType(type);
|
||||
payload.files.push(new File([blob], pastedFileName(mime, payload.files.length), { type: mime }));
|
||||
continue;
|
||||
}
|
||||
const value = await blob.text();
|
||||
if (!value) continue;
|
||||
if (role === 'plain') payload.text ||= value;
|
||||
else if (role === 'html') payload.html ||= value;
|
||||
else payload.strings.push([normalizeClipboardType(type), value]);
|
||||
}
|
||||
}
|
||||
// Some apps offer a copied link only as a URI list. Paste the link as text instead of nothing.
|
||||
if (!payload.text) {
|
||||
const uriList = payload.strings.find(([type]) => type === 'text/uri-list');
|
||||
if (uriList) payload.text = plainTextFromUriList(uriList[1]);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
@@ -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 }]);
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { buildGraphTopology, getGraphNeighborhood } from './graph-topology.ts';
|
||||
|
||||
const edge = (sourceIdx, targetIdx) => ({ sourceIdx, targetIdx });
|
||||
|
||||
function scannedNeighborhood(nodeIdx, edges) {
|
||||
const nodeSet = new Set();
|
||||
const edgeSet = new Set();
|
||||
if (nodeIdx < 0) return { nodeSet, edgeSet };
|
||||
nodeSet.add(nodeIdx);
|
||||
edges.forEach((e, i) => {
|
||||
if (e.sourceIdx === nodeIdx || e.targetIdx === nodeIdx) {
|
||||
edgeSet.add(i);
|
||||
nodeSet.add(e.sourceIdx);
|
||||
nodeSet.add(e.targetIdx);
|
||||
}
|
||||
});
|
||||
return { nodeSet, edgeSet };
|
||||
}
|
||||
|
||||
test('topology retains duplicate edges and counts self-edges twice in degree but once in adjacency', () => {
|
||||
const edges = [edge(0, 1), edge(0, 1), edge(1, 0), edge(0, 0), edge(2, 2)];
|
||||
const topology = buildGraphTopology(4, edges);
|
||||
assert.deepEqual(topology.incidentEdges, [[0, 1, 2, 3], [0, 1, 2], [4], []]);
|
||||
assert.deepEqual(topology.nodeDegree, [5, 3, 2, 0]);
|
||||
assert.deepEqual(topology.connectedSet, new Set([0, 1, 2]));
|
||||
assert.deepEqual(getGraphNeighborhood(0, edges, topology.incidentEdges), {
|
||||
nodeSet: new Set([0, 1]),
|
||||
edgeSet: new Set([0, 1, 2, 3]),
|
||||
});
|
||||
});
|
||||
|
||||
test('changing active nodes produces only direct neighbors without changing prior sets', () => {
|
||||
const edges = [edge(0, 1), edge(2, 1), edge(2, 3), edge(3, 4)];
|
||||
const { incidentEdges } = buildGraphTopology(6, edges);
|
||||
const first = getGraphNeighborhood(0, edges, incidentEdges);
|
||||
const second = getGraphNeighborhood(2, edges, incidentEdges);
|
||||
assert.deepEqual(first, { nodeSet: new Set([0, 1]), edgeSet: new Set([0]) });
|
||||
assert.deepEqual(second, { nodeSet: new Set([2, 1, 3]), edgeSet: new Set([1, 2]) });
|
||||
assert.deepEqual(getGraphNeighborhood(5, edges, incidentEdges), {
|
||||
nodeSet: new Set([5]), edgeSet: new Set(),
|
||||
});
|
||||
assert.deepEqual(getGraphNeighborhood(-1, edges, incidentEdges), {
|
||||
nodeSet: new Set(), edgeSet: new Set(),
|
||||
});
|
||||
});
|
||||
|
||||
test('rebuilding topology uses the replacement edges for the same active node', () => {
|
||||
const beforeEdges = [edge(0, 1)];
|
||||
const afterEdges = [edge(2, 0), edge(0, 0)];
|
||||
const before = buildGraphTopology(3, beforeEdges);
|
||||
const after = buildGraphTopology(3, afterEdges);
|
||||
assert.deepEqual(getGraphNeighborhood(0, beforeEdges, before.incidentEdges), {
|
||||
nodeSet: new Set([0, 1]), edgeSet: new Set([0]),
|
||||
});
|
||||
assert.deepEqual(getGraphNeighborhood(0, afterEdges, after.incidentEdges), {
|
||||
nodeSet: new Set([0, 2]), edgeSet: new Set([0, 1]),
|
||||
});
|
||||
});
|
||||
|
||||
test('indexed neighborhoods match full scans for directed, duplicate and self edges', () => {
|
||||
const edges = Array.from({ length: 150 }, (_, i) => edge(i % 13, (i * 7 + 3) % 13));
|
||||
edges.push(edge(0, 0), edge(0, 1), edge(0, 1));
|
||||
const { incidentEdges } = buildGraphTopology(14, edges);
|
||||
for (let nodeIdx = -1; nodeIdx < 14; nodeIdx++) {
|
||||
assert.deepEqual(getGraphNeighborhood(nodeIdx, edges, incidentEdges), scannedNeighborhood(nodeIdx, edges));
|
||||
}
|
||||
});
|
||||
|
||||
test('construction reads each endpoint once and neighborhood work visits only incident edges', () => {
|
||||
let endpointReads = 0;
|
||||
const pairs = [[0, 1], [0, 0], [2, 0], ...Array.from({ length: 1000 }, () => [2, 3])];
|
||||
const edges = pairs.map(([source, target]) => ({
|
||||
get sourceIdx() { endpointReads++; return source; },
|
||||
get targetIdx() { endpointReads++; return target; },
|
||||
}));
|
||||
const { incidentEdges } = buildGraphTopology(5, edges);
|
||||
assert.equal(endpointReads, edges.length * 2);
|
||||
endpointReads = 0;
|
||||
assert.deepEqual(getGraphNeighborhood(0, edges, incidentEdges), {
|
||||
nodeSet: new Set([0, 1, 2]), edgeSet: new Set([0, 1, 2]),
|
||||
});
|
||||
assert.equal(endpointReads, 6);
|
||||
endpointReads = 0;
|
||||
getGraphNeighborhood(4, edges, incidentEdges);
|
||||
getGraphNeighborhood(-1, edges, incidentEdges);
|
||||
assert.equal(endpointReads, 0);
|
||||
});
|
||||
|
||||
test('an empty graph has no degree, adjacency or neighborhood entries', () => {
|
||||
const topology = buildGraphTopology(0, []);
|
||||
assert.deepEqual(topology, { incidentEdges: [], nodeDegree: [], connectedSet: new Set() });
|
||||
assert.deepEqual(getGraphNeighborhood(-1, [], topology.incidentEdges), {
|
||||
nodeSet: new Set(), edgeSet: new Set(),
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
interface GraphTopologyEdge {
|
||||
sourceIdx: number;
|
||||
targetIdx: number;
|
||||
}
|
||||
|
||||
export function buildGraphTopology(nodeCount: number, edges: readonly GraphTopologyEdge[]) {
|
||||
const incidentEdges: number[][] = Array.from({ length: nodeCount }, () => []);
|
||||
const nodeDegree = new Array<number>(nodeCount).fill(0);
|
||||
const connectedSet = new Set<number>();
|
||||
for (let i = 0; i < edges.length; i++) {
|
||||
const { sourceIdx, targetIdx } = edges[i];
|
||||
connectedSet.add(sourceIdx);
|
||||
connectedSet.add(targetIdx);
|
||||
nodeDegree[sourceIdx]++;
|
||||
nodeDegree[targetIdx]++;
|
||||
incidentEdges[sourceIdx].push(i);
|
||||
// A self-edge contributes twice to degree, but only once to the neighborhood.
|
||||
if (targetIdx !== sourceIdx) incidentEdges[targetIdx].push(i);
|
||||
}
|
||||
return { incidentEdges, nodeDegree, connectedSet };
|
||||
}
|
||||
|
||||
export function getGraphNeighborhood(
|
||||
nodeIdx: number,
|
||||
edges: readonly GraphTopologyEdge[],
|
||||
incidentEdges: readonly (readonly number[])[],
|
||||
) {
|
||||
const nodeSet = new Set<number>();
|
||||
const edgeSet = new Set<number>();
|
||||
const incident = incidentEdges[nodeIdx];
|
||||
if (!incident) return { nodeSet, edgeSet };
|
||||
nodeSet.add(nodeIdx);
|
||||
for (const i of incident) {
|
||||
const edge = edges[i];
|
||||
edgeSet.add(i);
|
||||
nodeSet.add(edge.sourceIdx);
|
||||
nodeSet.add(edge.targetIdx);
|
||||
}
|
||||
return { nodeSet, edgeSet };
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { comparableBody, compareHistory, splitSnapshot } from './history-comparison.ts';
|
||||
|
||||
function rowsOf(comparison) {
|
||||
return comparison.chunks.flatMap((chunk) => chunk.rows);
|
||||
}
|
||||
|
||||
async function compare(current, snapshot) {
|
||||
const comparison = await compareHistory(current, snapshot);
|
||||
const rows = rowsOf(comparison);
|
||||
const normalize = (body) => body.replace(/\r\n/g, '\n');
|
||||
const restoreText = (excludedKind) => rows
|
||||
.filter((row) => row.kind !== excludedKind)
|
||||
.map((row) => row.text + (row.newline ? '\n' : ''))
|
||||
.join('');
|
||||
|
||||
assert.equal(restoreText('added'), normalize(current), 'all current content is retained');
|
||||
assert.equal(restoreText('removed'), normalize(snapshot), 'all snapshot content is retained');
|
||||
assert.equal(comparison.added, rows.filter((row) => row.kind === 'added').length);
|
||||
assert.equal(comparison.removed, rows.filter((row) => row.kind === 'removed').length);
|
||||
|
||||
let currentLine = 1;
|
||||
let snapshotLine = 1;
|
||||
for (const row of rows) {
|
||||
assert.equal(row.currentLine, row.kind === 'added' ? null : currentLine++);
|
||||
assert.equal(row.snapshotLine, row.kind === 'removed' ? null : snapshotLine++);
|
||||
assert.equal(typeof row.newline, 'boolean');
|
||||
assert.equal(row.text.includes('\n'), false);
|
||||
}
|
||||
for (let index = 0; index < comparison.chunks.length; index++) {
|
||||
const chunk = comparison.chunks[index];
|
||||
assert.ok(chunk.rows.length > 0, 'empty chunks are not displayed');
|
||||
assert.notEqual(chunk.kind, comparison.chunks[index - 1]?.kind, 'adjacent chunks are merged');
|
||||
if (chunk.kind === 'unchanged') {
|
||||
assert.ok(chunk.rows.every((row) => row.kind === 'same'));
|
||||
}
|
||||
}
|
||||
return comparison;
|
||||
}
|
||||
|
||||
function lines(count) {
|
||||
return Array.from({ length: count }, (_, index) => `line ${index + 1}`);
|
||||
}
|
||||
|
||||
function document(lines) {
|
||||
return lines.join('\n') + '\n';
|
||||
}
|
||||
|
||||
test('restoring a snapshot adds snapshot-only lines and removes current-only lines', async () => {
|
||||
const comparison = await compare('keep\nlive\n', 'keep\narchived\nextra\n');
|
||||
assert.equal(comparison.added, 2);
|
||||
assert.equal(comparison.removed, 1);
|
||||
assert.deepEqual(rowsOf(comparison).map((row) => [row.kind, row.text]), [
|
||||
['same', 'keep'],
|
||||
['removed', 'live'],
|
||||
['added', 'archived'],
|
||||
['added', 'extra'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('insertion keeps both line-number columns aligned with their own documents', async () => {
|
||||
const comparison = await compare('first\nlast', 'first\ninserted\nlast');
|
||||
assert.deepEqual(rowsOf(comparison), [
|
||||
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
|
||||
{ kind: 'added', text: 'inserted', currentLine: null, snapshotLine: 2, newline: true },
|
||||
{ kind: 'same', text: 'last', currentLine: 2, snapshotLine: 3, newline: false },
|
||||
]);
|
||||
});
|
||||
|
||||
test('deletion leaves snapshot line numbers unchanged by removed rows', async () => {
|
||||
const comparison = await compare('first\ndeleted\nlast', 'first\nlast');
|
||||
assert.deepEqual(rowsOf(comparison), [
|
||||
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
|
||||
{ kind: 'removed', text: 'deleted', currentLine: 2, snapshotLine: null, newline: true },
|
||||
{ kind: 'same', text: 'last', currentLine: 3, snapshotLine: 2, newline: false },
|
||||
]);
|
||||
});
|
||||
|
||||
test('replacement presents the current line before its snapshot replacement', async () => {
|
||||
const comparison = await compare('first\nlive\nlast\n', 'first\narchived\nlast\n');
|
||||
assert.deepEqual(rowsOf(comparison), [
|
||||
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
|
||||
{ kind: 'removed', text: 'live', currentLine: 2, snapshotLine: null, newline: true },
|
||||
{ kind: 'added', text: 'archived', currentLine: null, snapshotLine: 2, newline: true },
|
||||
{ kind: 'same', text: 'last', currentLine: 3, snapshotLine: 3, newline: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test('empty bodies and blank lines remain distinct without phantom trailing rows', async () => {
|
||||
const cases = [
|
||||
['', '', 0, 0],
|
||||
['', '\n', 1, 0],
|
||||
['\n', '', 0, 1],
|
||||
['', '\n\n', 2, 0],
|
||||
['\n', '\n', 0, 0],
|
||||
['\n\n', '\n', 0, 1],
|
||||
['', 'text', 1, 0],
|
||||
['text', '', 0, 1],
|
||||
];
|
||||
for (const [current, snapshot, added, removed] of cases) {
|
||||
const comparison = await compare(current, snapshot);
|
||||
assert.equal(comparison.added, added);
|
||||
assert.equal(comparison.removed, removed);
|
||||
}
|
||||
assert.deepEqual((await compare('', '')).chunks, []);
|
||||
assert.deepEqual(rowsOf(await compare('', '\n')), [
|
||||
{ kind: 'added', text: '', currentLine: null, snapshotLine: 1, newline: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test('adding a final newline is visible even when the line text is identical', async () => {
|
||||
const comparison = await compare('last', 'last\n');
|
||||
assert.equal(comparison.added, 1);
|
||||
assert.equal(comparison.removed, 1);
|
||||
assert.deepEqual(rowsOf(comparison), [
|
||||
{ kind: 'removed', text: 'last', currentLine: 1, snapshotLine: null, newline: false },
|
||||
{ kind: 'added', text: 'last', currentLine: null, snapshotLine: 1, newline: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test('removing a final newline retains the visible missing-newline flag', async () => {
|
||||
const comparison = await compare('last\n', 'last');
|
||||
assert.deepEqual(rowsOf(comparison).map((row) => [row.kind, row.text, row.newline]), [
|
||||
['removed', 'last', true],
|
||||
['added', 'last', false],
|
||||
]);
|
||||
});
|
||||
|
||||
test('CRLF-only differences compare equal, including blank lines and the final newline', async () => {
|
||||
const comparison = await compare('first\r\n\r\nlast\r\n', 'first\n\nlast\n');
|
||||
assert.equal(comparison.added, 0);
|
||||
assert.equal(comparison.removed, 0);
|
||||
assert.deepEqual(rowsOf(comparison).map((row) => [row.text, row.newline]), [
|
||||
['first', true], ['', true], ['last', true],
|
||||
]);
|
||||
const withoutFinalNewline = await compare('last\r\n', 'last');
|
||||
assert.equal(withoutFinalNewline.added, 1);
|
||||
assert.equal(withoutFinalNewline.removed, 1);
|
||||
});
|
||||
|
||||
test('whitespace and standalone carriage returns are not ignored', async () => {
|
||||
const whitespace = await compare('same \n\t\nlast', 'same\n \nlast');
|
||||
assert.equal(whitespace.added, 2);
|
||||
assert.equal(whitespace.removed, 2);
|
||||
const carriageReturn = await compare('first\rlast', 'firstlast');
|
||||
assert.equal(carriageReturn.added, 1);
|
||||
assert.equal(carriageReturn.removed, 1);
|
||||
assert.equal(rowsOf(carriageReturn)[0].text, 'first\rlast');
|
||||
});
|
||||
|
||||
test('snapshot splitting retains raw BOM/CRLF metadata and untouched body bytes', () => {
|
||||
const metadata = '\uFEFF---\r\ntitle: Snapshot\r\ndescription: "inline --- stays here"\r\n---\r\n';
|
||||
const body = '# Body\r\n\r\n---\r\ntrailing spaces ';
|
||||
assert.deepEqual(splitSnapshot(metadata + body), { metadata, body });
|
||||
});
|
||||
|
||||
test('frontmatter closes only at a complete delimiter line, not inline YAML values', () => {
|
||||
const metadata = '---\ntitle: "before --- after"\nother: ---\n---\n';
|
||||
const body = 'body\n---\nremaining body\n';
|
||||
assert.deepEqual(splitSnapshot(metadata + body), { metadata, body });
|
||||
assert.deepEqual(splitSnapshot('---\n---'), { metadata: '---\n---', body: '' });
|
||||
assert.deepEqual(splitSnapshot('---\ntitle: archived\n---'), {
|
||||
metadata: '---\ntitle: archived\n---', body: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('incomplete, nonleading and non-line delimiters remain entirely in the body', () => {
|
||||
const bodies = [
|
||||
'',
|
||||
'---',
|
||||
'---\ntitle: "inline --- is not a closing line"\nbody',
|
||||
'---\ntitle: archived\n--- suffix\nbody',
|
||||
'---\ntitle: archived\r---\nbody',
|
||||
'---\ntitle: archived\n---\r',
|
||||
'intro\n---\ntitle: archived\n---\nbody',
|
||||
' ---\ntitle: archived\n---\nbody',
|
||||
'\uFEFFbody\r\n',
|
||||
];
|
||||
for (const body of bodies) {
|
||||
assert.deepEqual(splitSnapshot(body), { body, metadata: '' });
|
||||
}
|
||||
});
|
||||
|
||||
test('metadata changes do not become body changes when consumers compare split bodies', async () => {
|
||||
const current = splitSnapshot('---\ntitle: Live\ntags: [live]\n---\nsame body\n');
|
||||
const snapshot = splitSnapshot('---\ntitle: Archived\ntags: [old]\n---\nsame body\n');
|
||||
const comparison = await compare(current.body, snapshot.body);
|
||||
assert.notEqual(current.metadata, snapshot.metadata);
|
||||
assert.equal(comparison.added, 0);
|
||||
assert.equal(comparison.removed, 0);
|
||||
});
|
||||
|
||||
test('long edge runs retain all hidden rows with exactly three visible context lines', async () => {
|
||||
const current = lines(25);
|
||||
const snapshot = [...current];
|
||||
snapshot[12] = 'archived line 13';
|
||||
const comparison = await compare(document(current), document(snapshot));
|
||||
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
|
||||
['unchanged', 9], ['lines', 8], ['unchanged', 9],
|
||||
]);
|
||||
assert.deepEqual(comparison.chunks[1].rows.map((row) => row.text), [
|
||||
'line 10', 'line 11', 'line 12', 'line 13', 'archived line 13',
|
||||
'line 14', 'line 15', 'line 16',
|
||||
]);
|
||||
assert.deepEqual(comparison.chunks[0].rows.map((row) => row.currentLine), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
assert.deepEqual(comparison.chunks[2].rows.map((row) => row.snapshotLine), [17, 18, 19, 20, 21, 22, 23, 24, 25]);
|
||||
});
|
||||
|
||||
test('long middle runs preserve three context rows on each side for expansion', async () => {
|
||||
const current = lines(16);
|
||||
const snapshot = [...current];
|
||||
snapshot[0] = 'archived first';
|
||||
snapshot[15] = 'archived last';
|
||||
const comparison = await compare(document(current), document(snapshot));
|
||||
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
|
||||
['lines', 5], ['unchanged', 8], ['lines', 5],
|
||||
]);
|
||||
assert.deepEqual(comparison.chunks[0].rows.filter((row) => row.kind === 'same').map((row) => row.text), [
|
||||
'line 2', 'line 3', 'line 4',
|
||||
]);
|
||||
assert.deepEqual(comparison.chunks[1].rows.map((row) => row.text), current.slice(4, 12));
|
||||
assert.deepEqual(comparison.chunks[2].rows.filter((row) => row.kind === 'same').map((row) => row.text), [
|
||||
'line 13', 'line 14', 'line 15',
|
||||
]);
|
||||
});
|
||||
|
||||
test('overlapping context is not duplicated and the seventh middle line can collapse', async () => {
|
||||
for (const unchangedCount of [6, 7]) {
|
||||
const current = ['live first', ...lines(unchangedCount), 'live last'];
|
||||
const snapshot = ['archived first', ...lines(unchangedCount), 'archived last'];
|
||||
const comparison = await compare(document(current), document(snapshot));
|
||||
const hidden = comparison.chunks.filter((chunk) => chunk.kind === 'unchanged');
|
||||
assert.equal(hidden.length, unchangedCount === 6 ? 0 : 1);
|
||||
if (hidden.length) assert.deepEqual(hidden[0].rows.map((row) => row.text), ['line 4']);
|
||||
assert.equal(rowsOf(comparison).filter((row) => row.kind === 'same').length, unchangedCount);
|
||||
}
|
||||
});
|
||||
|
||||
test('identical notes have zero additions/removals and retain long unchanged content', async () => {
|
||||
const short = await compare('same\nbody', 'same\nbody');
|
||||
assert.equal(short.added, 0);
|
||||
assert.equal(short.removed, 0);
|
||||
assert.deepEqual(short.chunks.map((chunk) => chunk.kind), ['lines']);
|
||||
|
||||
const body = document(lines(3000));
|
||||
const long = await compare(body, body);
|
||||
assert.equal(long.added, 0);
|
||||
assert.equal(long.removed, 0);
|
||||
assert.deepEqual(long.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [['unchanged', 3000]]);
|
||||
});
|
||||
|
||||
test('large notes preserve hidden content as well as an appended snapshot line', async () => {
|
||||
const current = document(lines(3000));
|
||||
const comparison = await compare(current, current + 'appended\n');
|
||||
assert.equal(comparison.added, 1);
|
||||
assert.equal(comparison.removed, 0);
|
||||
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
|
||||
['unchanged', 2997], ['lines', 4],
|
||||
]);
|
||||
});
|
||||
|
||||
test('comparable bodies ignore only leading and trailing blank lines', () => {
|
||||
assert.equal(comparableBody(''), '');
|
||||
assert.equal(comparableBody('\n\n'), '');
|
||||
assert.equal(comparableBody('body'), 'body\n');
|
||||
assert.equal(comparableBody('\n\n# T\nbody\n\n'), '# T\nbody\n');
|
||||
assert.equal(comparableBody('\r\n# T\r\nbody\r\n'), '# T\r\nbody\n');
|
||||
assert.equal(comparableBody('a\n\n\nb'), 'a\n\n\nb\n');
|
||||
assert.equal(comparableBody(comparableBody('x\n')), 'x\n');
|
||||
});
|
||||
|
||||
test('a stripped current body matches a snapshot that keeps its file whitespace', async () => {
|
||||
// The app hands the review the note body without edge newlines; the stored snapshot keeps them.
|
||||
const current = '# T\nbody';
|
||||
for (const raw of [
|
||||
'---\ntitle: T\n---\n# T\nbody\n',
|
||||
'---\ntitle: T\n---\n\n# T\nbody\n',
|
||||
'---\r\ntitle: T\r\n---\r\n\r\n# T\r\nbody\r\n',
|
||||
]) {
|
||||
const comparison = await compareHistory(comparableBody(current), comparableBody(splitSnapshot(raw).body));
|
||||
assert.equal(comparison.added, 0, JSON.stringify(raw));
|
||||
assert.equal(comparison.removed, 0, JSON.stringify(raw));
|
||||
}
|
||||
const changed = await compareHistory(
|
||||
comparableBody(current),
|
||||
comparableBody(splitSnapshot('---\ntitle: T\n---\n# T\nedited\n').body),
|
||||
);
|
||||
assert.deepEqual([changed.added, changed.removed], [1, 1]);
|
||||
assert.deepEqual(
|
||||
rowsOf(changed).filter((row) => row.kind !== 'same').map((row) => [row.kind, row.text]),
|
||||
[['removed', 'body'], ['added', 'edited']],
|
||||
);
|
||||
});
|
||||
|
||||
const numbered = (count, prefix) => Array.from({ length: count }, (_, index) => `${prefix} ${index}`).join('\n') + '\n';
|
||||
|
||||
test('a heavily rewritten note is compared quickly and still reports every change', async () => {
|
||||
const started = performance.now();
|
||||
const comparison = await compare(numbered(1000, 'old line'), numbered(1000, 'new text'));
|
||||
assert.ok(performance.now() - started < 1500, 'the comparison must not wait on timers per edit');
|
||||
assert.equal(comparison.added, 1000);
|
||||
assert.equal(comparison.removed, 1000);
|
||||
});
|
||||
|
||||
test('beyond the diff limit, shared start and end lines stay unchanged and the middle is replaced', async () => {
|
||||
const head = numbered(100, 'same start');
|
||||
const tail = numbered(100, 'same end');
|
||||
const current = head + numbered(2500, 'old middle') + tail;
|
||||
const snapshot = head + numbered(1800, 'new middle') + tail;
|
||||
const started = performance.now();
|
||||
const comparison = await compare(current, snapshot);
|
||||
assert.ok(performance.now() - started < 1500);
|
||||
assert.equal(comparison.removed, 2500);
|
||||
assert.equal(comparison.added, 1800);
|
||||
assert.equal(rowsOf(comparison).filter((row) => row.kind === 'same').length, 200);
|
||||
assert.equal(rowsOf(comparison)[0].text, 'same start 0');
|
||||
assert.equal(rowsOf(comparison).at(-1).text, 'same end 99');
|
||||
});
|
||||
|
||||
test('the coarse fallback handles CRLF, missing final newlines and empty sides', async () => {
|
||||
const big = numbered(2000, 'a').replace(/\n/g, '\r\n');
|
||||
const other = numbered(2000, 'b');
|
||||
const crlf = await compare(big, other);
|
||||
assert.equal(crlf.added + crlf.removed, 4000);
|
||||
const noFinalNewline = await compare(numbered(1500, 'a').slice(0, -1), numbered(1500, 'b').slice(0, -1));
|
||||
assert.equal(noFinalNewline.added, 1500);
|
||||
assert.equal(rowsOf(noFinalNewline).at(-1).newline, false);
|
||||
const empty = await compare('', numbered(2000, 'b'));
|
||||
assert.deepEqual([empty.added, empty.removed], [2000, 0]);
|
||||
const emptied = await compare(numbered(2000, 'b'), '');
|
||||
assert.deepEqual([emptied.added, emptied.removed], [0, 2000]);
|
||||
});
|
||||
|
||||
test('differences under the limit still use the minimal line diff', async () => {
|
||||
const current = numbered(5000, 'line');
|
||||
const snapshot = current.replace('line 10\n', 'edited 10\n').replace('line 4000\n', 'edited 4000\n');
|
||||
const comparison = await compare(current, snapshot);
|
||||
assert.deepEqual([comparison.added, comparison.removed], [2, 2]);
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { diffLines, type Change } from 'diff';
|
||||
|
||||
export interface HistoryRow {
|
||||
kind: 'same' | 'added' | 'removed';
|
||||
text: string;
|
||||
currentLine: number | null;
|
||||
snapshotLine: number | null;
|
||||
/** Whether this line has a terminating LF; CRLF is normalized for comparison. */
|
||||
newline: boolean;
|
||||
}
|
||||
|
||||
export interface HistoryChunk {
|
||||
kind: 'lines' | 'unchanged';
|
||||
rows: HistoryRow[];
|
||||
}
|
||||
|
||||
export interface HistoryComparison {
|
||||
added: number;
|
||||
removed: number;
|
||||
chunks: HistoryChunk[];
|
||||
}
|
||||
|
||||
/** Separate only a complete leading frontmatter block, keeping both slices verbatim. */
|
||||
export function splitSnapshot(raw: string): { body: string; metadata: string } {
|
||||
const opening = /^(?:\uFEFF)?---\r?\n/.exec(raw);
|
||||
if (!opening) return { body: raw, metadata: '' };
|
||||
|
||||
const closingDelimiter = /\n---(?:\r?\n|$)/g;
|
||||
closingDelimiter.lastIndex = opening[0].length - 1;
|
||||
const closing = closingDelimiter.exec(raw);
|
||||
if (!closing) return { body: raw, metadata: '' };
|
||||
|
||||
const bodyStart = closing.index + closing[0].length;
|
||||
return { body: raw.slice(bodyStart), metadata: raw.slice(0, bodyStart) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Make two note bodies comparable. The note body the app loads has its leading and trailing
|
||||
* blank lines removed, while a stored snapshot keeps the file's exact text, so differences in
|
||||
* those lines are not changes the editor can show or restore.
|
||||
*/
|
||||
export function comparableBody(body: string): string {
|
||||
const trimmed = body.replace(/^(?:\r?\n)+/, '').replace(/(?:\r?\n)+$/, '');
|
||||
return trimmed === '' ? '' : trimmed + '\n';
|
||||
}
|
||||
|
||||
/** Diff cost grows with the square of the edit distance; beyond this, a coarse diff is shown instead. */
|
||||
const MAX_EDIT_LENGTH = 1000;
|
||||
|
||||
/** Always-correct fallback: shared leading and trailing lines stay unchanged, the middle is replaced. */
|
||||
function coarseChanges(current: string, snapshot: string): Change[] {
|
||||
const lines = (text: string) => text.replace(/\r\n/g, '\n').match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
||||
const before = lines(current);
|
||||
const after = lines(snapshot);
|
||||
let start = 0;
|
||||
while (start < before.length && start < after.length && before[start] === after[start]) start++;
|
||||
let end = 0;
|
||||
while (end < before.length - start && end < after.length - start
|
||||
&& before[before.length - 1 - end] === after[after.length - 1 - end]) end++;
|
||||
const part = (items: string[], kind: 'same' | 'added' | 'removed'): Change[] => items.length
|
||||
? [{ value: items.join(''), count: items.length, added: kind === 'added', removed: kind === 'removed' }]
|
||||
: [];
|
||||
return [
|
||||
...part(before.slice(0, start), 'same'),
|
||||
...part(before.slice(start, before.length - end), 'removed'),
|
||||
...part(after.slice(start, after.length - end), 'added'),
|
||||
...part(before.slice(before.length - end), 'same'),
|
||||
];
|
||||
}
|
||||
|
||||
/** Added/removed rows describe restoring the snapshot over the current editor body. */
|
||||
export async function compareHistory(
|
||||
currentBody: string,
|
||||
snapshotBody: string,
|
||||
): Promise<HistoryComparison> {
|
||||
// jsdiff's callback mode waits on a timer for every step, which takes seconds on large changes.
|
||||
const changes = diffLines(currentBody, snapshotBody, { stripTrailingCr: true, maxEditLength: MAX_EDIT_LENGTH })
|
||||
?? coarseChanges(currentBody, snapshotBody);
|
||||
|
||||
const chunks: HistoryChunk[] = [];
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
let currentLine = 1;
|
||||
let snapshotLine = 1;
|
||||
const contextLines = 3;
|
||||
|
||||
for (let changeIndex = 0; changeIndex < changes.length; changeIndex++) {
|
||||
const change = changes[changeIndex];
|
||||
const kind: HistoryRow['kind'] = change.added ? 'added' : change.removed ? 'removed' : 'same';
|
||||
const leadingContext = changeIndex > 0 ? contextLines : 0;
|
||||
const trailingContext = changeIndex < changes.length - 1 ? contextLines : 0;
|
||||
const collapse = kind === 'same' && change.count > (
|
||||
changes.length === 1 ? contextLines * 2 : leadingContext + trailingContext
|
||||
);
|
||||
|
||||
let offset = 0;
|
||||
let rowIndex = 0;
|
||||
while (offset < change.value.length) {
|
||||
const newlineIndex = change.value.indexOf('\n', offset);
|
||||
const newline = newlineIndex !== -1;
|
||||
const end = newline ? newlineIndex : change.value.length;
|
||||
const chunkKind: HistoryChunk['kind'] = collapse
|
||||
&& rowIndex >= leadingContext
|
||||
&& rowIndex < change.count - trailingContext
|
||||
? 'unchanged'
|
||||
: 'lines';
|
||||
let chunk = chunks[chunks.length - 1];
|
||||
if (!chunk || chunk.kind !== chunkKind) {
|
||||
chunk = { kind: chunkKind, rows: [] };
|
||||
chunks.push(chunk);
|
||||
}
|
||||
chunk.rows.push({
|
||||
kind,
|
||||
text: change.value.slice(offset, end),
|
||||
currentLine: kind === 'added' ? null : currentLine++,
|
||||
snapshotLine: kind === 'removed' ? null : snapshotLine++,
|
||||
newline,
|
||||
});
|
||||
if (kind === 'added') added++;
|
||||
if (kind === 'removed') removed++;
|
||||
offset = newline ? end + 1 : end;
|
||||
rowIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
return { added, removed, chunks };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
const { htmlHasFormatting, looksLikeMarkdown } = await import(new URL('./markdown-paste.ts', import.meta.url));
|
||||
|
||||
test('Markdown block and inline syntax is recognized', () => {
|
||||
for (const text of [
|
||||
'# Title\n\nText', 'Intro\n\n- one\n- two', '1. first\n2. second', '> quoted', '```js\ncode\n```',
|
||||
'| a | b |\n| --- | --- |', 'Some **bold** text', 'see `code` here', '[label](https://x.com)', '',
|
||||
'[[Note]] link', 'an *emphasis* word', '- [ ] task', '---',
|
||||
]) assert.equal(looksLikeMarkdown(text), true, text);
|
||||
});
|
||||
|
||||
test('plain text stays plain', () => {
|
||||
for (const text of [
|
||||
'', 'Just a sentence.', 'Two\nlines of text', 'https://example.com/page', '2 * 3 * 4 = 24', 'price: $5 - $10',
|
||||
'snake_case_name and another_one', 'a # not a heading', '-1 degrees', 'C:\\Users\\me\\file.txt',
|
||||
]) assert.equal(looksLikeMarkdown(text), false, text);
|
||||
});
|
||||
|
||||
test('styled text from a code editor is not formatting', () => {
|
||||
assert.equal(htmlHasFormatting('<meta charset="utf-8"><div style="color: #ccc;font-family: monospace;white-space: pre;"><div><span style="color: #569cd6;"># Title</span></div></div>'), false);
|
||||
assert.equal(htmlHasFormatting('<p>Text with <strong>bold</strong></p>'), true);
|
||||
assert.equal(htmlHasFormatting('<ul><li>item</li></ul>'), true);
|
||||
assert.equal(htmlHasFormatting('<a href="x">x</a>'), true);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Pasting Markdown into the rich editor. Plain text that uses Markdown syntax is rendered the way a
|
||||
* note is; anything else keeps the normal paste. Clipboard HTML that is only styled text (a code
|
||||
* editor or terminal copies its colors as HTML) does not count as formatting.
|
||||
*/
|
||||
|
||||
const BLOCK_SYNTAX = /^(?: {0,3}#{1,6}[ \t]+\S| {0,3}>|[ \t]*(?:[-*+]|\d+[.)])[ \t]+\S| {0,3}(?:```|~~~)|[ \t]*\|.*\|[ \t]*$| {0,3}(?:-{3,}|\*{3,}|_{3,})[ \t]*$|:::img-grid\b)/m;
|
||||
const INLINE_SYNTAX = /\*\*[^*\n]+\*\*|__[^_\n]+__|~~[^~\n]+~~|==[^=\n]+==|`[^`\n]+`|!?\[[^\]\n]*\]\([^)\s]+(?:\s+"[^"\n]*")?\)|\[\[[^\]\n]+\]\]|(?:^|[\s(])\*[^*\s][^*\n]*\*(?=[\s).,;:!?]|$)/m;
|
||||
|
||||
/** Whether pasted plain text is written in Markdown rather than meant literally. */
|
||||
export function looksLikeMarkdown(text: string): boolean {
|
||||
if (!text.trim()) return false;
|
||||
// A lone address is a link paste, handled on its own.
|
||||
if (/^\s*[a-z][a-z0-9+.-]*:\/\/\S+\s*$/i.test(text)) return false;
|
||||
return BLOCK_SYNTAX.test(text) || INLINE_SYNTAX.test(text);
|
||||
}
|
||||
|
||||
/** Whether clipboard HTML carries structure of its own (headings, lists, links, emphasis...). */
|
||||
export function htmlHasFormatting(html: string): boolean {
|
||||
return /<(?:h[1-6]|ul|ol|li|table|blockquote|pre|code|a|img|strong|b|em|i|u|s|del|mark|hr)\b/i.test(html);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user