Compare commits

..
Author SHA1 Message Date
Yuri Karamian 458bff3eac docs(flatpak): record live ArkHost repository and update flow 2026-11-10 22:46:07 +04:00
Yuri Karamian 882006feb7 chore(flatpak): pin stable repository package metadata 2026-11-10 19:41:10 +04:00
Yuri Karamian d5dc7147ab feat(flatpak): prepare signed ArkHost repository publishing 2026-11-10 19:40:22 +04:00
Yuri Karamian 59b171af0a chore(flatpak): pin the source for submission preparation 2026-11-10 17:53:25 +04:00
Yuri Karamian d36ac5e9fa chore(flatpak): prepare Flathub identity and store metadata 2026-11-10 16:56:41 +04:00
Yuri Karamian 4787559af5 fix(flatpak): detect external edits with preserved timestamps 2026-11-10 16:39:52 +04:00
Yuri Karamian ceb3a7d647 feat(linux): add sandboxed Flatpak packaging 2026-11-10 15:14:32 +04:00
Yuri Karamian b9074ec550 fix(android): keep font choices within narrow settings 2026-11-10 12:26:12 +04:00
Yuri Karamian c8277bb01c fix(android): wrap settings options on narrow screens 2026-11-10 12:13:22 +04:00
Yuri Karamian 17f1af4294 fix(android): simplify the note toolbar 2026-11-10 12:00:00 +04:00
Yuri Karamian fbabcf5099 fix(android): keep scaled layouts within the screen 2026-11-10 11:09:01 +04:00
Yuri Karamian 338db1e7b0 chore: prepare v1.3.7 release 2026-11-10 10:25:33 +04:00
Yuri Karamian ac4b85fd0f Merge branch 'main' into 'main'
feat: add 12 more folder/tag icons

See merge request ArkHost/HelixNotes!21
2026-11-06 21:56:19 +00:00
Blake Boone 6716fec63a feat: add 12 more folder/tag icons 2026-11-06 21:56:19 +00:00
Yuri Karamian 237bf799e3 fix: toggle selected paragraphs as one code block 2026-11-06 12:33:49 +04:00
Yuri Karamian 77164427f1 fix: keep table horizontal scrolling when notes open read-only
TipTap registers the table node view together with column resizing only when the editor starts editable. Opening a note in View mode therefore left tables without their .tableWrapper, so wide tables could not scroll horizontally until the app was restarted in Edit mode.

Keep the table view plugin installed for read-only editors; its resize handlers still ignore non-editable views.

Add a regression test that the table node view is registered when the initial editor is read-only. (Discord report)
2026-11-05 01:27:11 +04:00
Yuri Karamian 523d1a5511 fix(webdav): use Last-Modified when a server has no strong ETag
Some WebDAV servers return no usable strong ETag for a file. Sync then refused to overwrite an edited note with "server provides no strong ETag".

Request and parse getlastmodified in PROPFIND, and use If-Unmodified-Since as the conditional header for overwrites and deletes when no strong ETag is available. Keep failing safely when neither validator exists.

Refs #291.
2026-11-04 14:38:53 +04:00
Yuri Karamian 6ecde99f25 fix: keep formatting and single spacing when copying
Copied notes now use inline single spacing, so Word and email clients no longer add their own paragraph spacing. Context-menu Copy and Cut now write rich HTML with a plain-text fallback instead of text only, preserving formatting and blank lines.

Add "Copy as Plain Text" to the context menu and a "Single" line-spacing preset in Settings.

Add regression tests for clipboard HTML spacing.
2026-11-04 02:03:28 +04:00
Yuri Karamian a466df85ed fix: stop compose and dead keys from adding stray quotes around accents
Typing é with a compose key (Compose ' e) or a dead key on Linux gave
'é' instead of é, with the first quote curled by Typography. Every
accented letter was affected.

GTK shows the keys typed so far as a preedit in the editor (· then ')
and replaces it at each step. ProseMirror reports that replacement as
a quote typed over a non-empty range. WrapSelectedText only checked
that the range was non-empty, so it treated the preedit as a selection
and wrapped it in quotes. The composition then removed its own preedit
but left the added quotes behind.

Wrap only when the range is exactly the user's selection and no
composition is active. Selecting text and typing ( or " still wraps
it.

Move the logic into wrapSelection() and cover it with tests.
2026-10-30 17:28:54 +04:00
Yuri Karamian 3858f8e455 fix: let Alt+Left/Right move by word while editing (#290)
History navigation is bound to Alt+Left/Right by default, so the global
keydown handler swallowed those keys before the editor could use them.
Skip the history shortcuts while focus is in the rich editor, the source
editor, or a text input, letting the editable surface handle word
movement. History still works via the mouse buttons and outside editors.
2026-10-28 22:49:17 +04:00
Yuri Karamian 64266969f3 fix: Interface Scale on Android, and a larger default on phones (#288)
Phones used the desktop sizes with no way to enlarge the interface: the
Interface Scale setting was hidden on mobile, and setZoom does nothing on
Android. Android now has the setting (100, 115, 125 and 140%) and starts
at 115% until a scale is chosen. It is applied through the viewport
scale, so taps and menu positions keep matching. Presets that would make
the layout narrower than the mobile menus are left out on small phones.
2026-10-28 11:32:06 +04:00
Yuri Karamian a80425e084 Merge branch 'perf/parallel-listing-upstream' into 'main'
perf(sync): list WebDAV folders several at a time

See merge request ArkHost/HelixNotes!17
2026-10-28 07:06:40 +00:00
Chris Benninger 2d554c6a9d perf(sync): list WebDAV folders several at a time 2026-10-28 07:06:39 +00:00
Yuri Karamian 1676f9fbd1 fix: keep the link around an image and the size of HTML images on save
An image inside a link lost the link the first time the note was saved,
and <img width=...> lost its size. Images now keep the link around them
and are written back as HTML when they have a width or height. Only a
single plain image line is joined to the block above, as the parser
reads it, so a linked or sized image keeps the blank line before it.
2026-10-17 22:53:19 +02:00
Yuri Karamian 3c8b320892 fix: Ctrl+A in source mode selects the text, not every note
The note list's window-wide select-all skipped text fields and the rich
editor but not the source editor. It now skips any editable field.
2026-10-17 17:17:13 +02:00
Yuri Karamian b5189cf0e5 feat: paste Markdown text as formatted content in the rich editor
Plain text written in Markdown is rendered the way a note is read and
inserted: one paragraph joins the line at the cursor, several blocks
split it. Styled text from a code editor or terminal counts as plain.
Text without Markdown, pastes inside code, Ctrl+Shift+V and clipboard
HTML with its own formatting paste as before. Pasting ![](url) no longer
stays as text that saves as ![]([url](url)).
2026-10-17 17:17:13 +02:00
Yuri Karamian 3d21a74d24 fix: count words in tables and agree between rich and source mode
The rich editor ran blocks and table cells together, so a table counted
as a few words. Source mode counted table pipes, delimiter rows and list
markers as words. Blocks are now kept apart, a word needs a letter or
digit, both modes count the same, and switching to source mode recounts.
2026-10-17 16:48:30 +02:00
Yuri Karamian 3b59d34fed fix: keep links working when notes are renamed or moved
Renaming through the title field saved the new title before the file was
renamed, so the rename took the new title for the old one and [[Old]]
links were never updated. It now uses the old file name.

A rename now also updates heading and block links, other capitals,
[[Note.md]] and Markdown links to the file. Moving a note, and renaming
or moving a notebook, updates links that contain a folder, keeping each
link's form, and points the moved notes' own relative links from their
new folder. Code is left as written, and a name another note shares is
not rewritten. Open notes with unsaved edits follow the same rules,
checked on both sides against tests/fixtures/renamed-links.json.
2026-10-17 16:48:30 +02:00
Yuri Karamian c7bcb993bb fix: group images on consecutive lines into a grid, and say when there is nothing to group
Images on consecutive lines share one paragraph joined by line breaks,
which counted as text, so the image toolbar's Grid button did nothing.
Line breaks and whitespace between images no longer count. When no other
image sits right above or below, the button is disabled with a hint.
2026-10-14 09:44:02 +02:00
Yuri Karamian 4e2c87434d fix: show images glued to the empty-line marker by older versions
Before 1.3.7 an empty line before an image could be saved as
<!-- -->![](image.png) on one line, which reads as raw HTML and showed
the image as text. That line is now read as the empty line plus the
image, and the next save writes them apart.
2026-10-14 08:53:58 +02:00
Yuri Karamian 76919d6f1c fix: ask again for a web image that failed to load
A failed web image stayed blank until the note was redrawn. It is now
requested again after 1, 3 and 9 seconds, counted per address and reset
when a note opens.
2026-10-14 08:53:58 +02:00
Yuri Karamian 5e49051ecb fix: follow web image redirects to other hosts, checking every hop
The image proxy refused any redirect to a different host, so an image
behind a CDN or a bare-domain to www redirect never loaded. It now
follows up to five redirects itself and resolves, checks and pins each
hop exactly like a direct image address.
2026-10-14 08:53:58 +02:00
Yuri Karamian a6798d31e2 fix: a new ETag for unchanged remote bytes is not a sync conflict
Some WebDAV servers report a new ETag for a file nobody changed. A note
edited locally then became a conflict copy. The downloaded bytes are now
compared with the hash from the last sync; only different bytes count as
a remote change, so the local edit is uploaded with If-Match.
2026-10-14 08:53:58 +02:00
Yuri Karamian 648cf48dcc feat: offer to create the note from the [[ menu when none has that name
The menu gets a 'Create note' row when no note has the typed title. It
inserts the link, creates the note in the open note's notebook and stays
there. Aliases and #heading parts are kept; typing ]] still only links.
2026-10-14 08:53:58 +02:00
Yuri Karamian 3a9cae27c4 fix: keep one wiki-link mark per text so renaming through a link writes [[New]]
Editing a link's text renamed the note and then added a second wikiLink
mark beside the old one, because the mark only excluded normal links.
The note was saved as [[Old|[[New]]]]. The mark now also excludes itself.
2026-10-14 08:53:58 +02:00
Yuri Karamian 31d19a9faf feat: use a vault icon for Manage Vaults 2026-10-14 00:34:06 +02:00
Yuri Karamian d8e6228f13 feat: color the default notebook glyph and fold extra icons behind a More button 2026-10-14 00:34:06 +02:00
Yuri Karamian 48e39a0cbc feat: add colors to notebook icons and 16 more built-in icons 2026-10-14 00:08:24 +02:00
Yuri Karamian 2ddefc51e4 fix: run hourly backups every hour
The scheduler had no case for the 1 hour frequency offered in Settings
and fell back to 24 hours.
2026-10-13 22:42:29 +02:00
Yuri Karamian 557f625947 feat: show the note beside the notebooks and note list on wide tablets
The mobile layout showed one panel at a time at any size. From 900 px
wide (an iPad in landscape) the notebooks or the note list now stay in a
left column with the note next to them, and back returns from the note
list to the notebooks. A header button hides or shows the column, and
the choice is kept on the device. Narrower windows are unchanged.
2026-10-13 15:46:38 +02:00
Yuri Karamian 043d2bd6c4 fix: measure mermaid labels in the editor so the last line is not cut off
Labels were measured under <body> with a smaller line height than the
editor's, so boxes came out too short for their text. They are now
measured inside the diagram's container. PNG copy and save carry the
editor font and line height into the image.
2026-10-13 14:39:10 +02:00
Yuri Karamian 7100ac637c fix: keep graph hover links inside the local graph and visible when zoomed out
Hovering a neighbour of the open note in the local graph highlighted that
neighbour's links to notes the local graph does not show, so lines and
arrowheads ended in empty space. Only links in the local graph are
highlighted now. Link lines and hover arrowheads also keep their on-screen
size below 100% zoom instead of thinning out under a pixel.
2026-10-13 14:19:27 +02:00
Yuri Karamian c0058f43f4 perf: reuse the wiki title index, parsed note dates and skip grammar guessing
Opening a note rebuilt the wiki-link title lookup every time; it is now
built once per titles list and the list is replaced, not mutated, when a
title changes. Re-sorting the note list on each external file change
re-parsed every note's date; parsed dates are now kept per entry. A code
block naming a language without a grammar (mermaid, a typo) ran every
registered grammar on each keystroke; it is now left plain.
2026-10-13 14:19:27 +02:00
Yuri Karamian 6986546f20 fix: find and update aliased wiki links in table cells
In a table cell the alias separator is written \|. The graph did not
find such links and renaming a note did not update them.
2026-10-11 13:37:14 +02:00
Yuri Karamian 578bf9d253 fix: give a sync conflict copy a title that says so
The copy differed from the original only in its file name, and the
note list, search and quick open go by title, so it could not be found.
Its title and leading heading now carry the same suffix.
2026-10-11 13:37:14 +02:00
Yuri Karamian 94b477d072 fix: show the last sync result in Settings however the sync started
The result line was only filled in for a sync started with the button
in Settings, so a sync from the title bar or an automatic one left it
empty or stale.
2026-10-11 13:37:14 +02:00
Yuri Karamian 5b21e1c3a1 fix: fall back when a volume has no exclusive rename
exFAT on macOS and some FUSE mounts reject the exclusive rename, so
trash, move, rename, attachments, version history and backups failed
there. They now check that the target does not exist and then rename.
2026-10-11 09:43:25 +02:00
Yuri Karamian 630e6ea878 fix: check a vault's windows before locking when forgetting it
Asking a window for its address waits for the main thread, which could
be waiting for the settings lock held here, freezing the app.
2026-10-11 09:43:25 +02:00
Yuri Karamian 1289e865ce fix: keep angle-bracket text and comments when a note is saved
Text such as List<String> or <username> was read as an HTML tag and
deleted on the next save, and HTML comments were dropped. Anything in
angle brackets that is not an HTML element now stays text, and
comments are kept and shown. A numbered list that starts at 0 keeps
its numbering.
2026-10-11 09:43:24 +02:00
Yuri Karamian 0f946ca330 feat: replace in note
The find bar gets a second row with Replace and Replace all, opened
from the bar or with Ctrl+H (Cmd+Option+F on macOS, rebindable). It
works in the rich editor and in source mode, and replace all is one
undo step. Replacing the text of a wiki link changes what it shows,
not its target.
2026-10-11 01:39:03 +02:00
Yuri Karamian 39c56f7e13 fix: keep unsaved edits when a linked note is renamed
Renaming a note rewrites the links to it in other notes. A note that
was open with unsaved edits then failed its next save with a conflict,
and the rewritten notes had no copy of their previous state.

The rename now reports the notes it rewrote. Their previous state goes
into version history, and an open editor takes over the new links and
continues from the rewritten file.
2026-10-11 01:39:03 +02:00
Yuri Karamian 8f07a24d62 perf: only serialize the blocks that changed when saving
Saving turned the whole note into Markdown every time. Document nodes
are immutable and an edit replaces only the blocks it touches, so the
Markdown of each top-level block is now kept and reused. A repeated
save of a 1.1 MB note drops from 70 ms to 4 ms. The first save after
opening a note is unchanged.
2026-10-10 22:53:57 +02:00
Yuri Karamian 9b8602e20f fix: keep literal text literal when a note is saved
Text that reads as Markdown (asterisks around words, a line starting with
"1." or "#", an HTML tag or entity written as text) lost its escaping on
save and came back as formatting. It is now written with a backslash, but
only where the parser would otherwise read it differently, so ordinary
notes are written as before. Text that reads as a link or an image is
still left to become one, and a line the note already had unescaped keeps
its previous behavior.
2026-10-10 22:36:58 +02:00
Yuri Karamian 90795bea73 fix: keep a single title heading when a note's title changes
The heading that reads as the old title follows a title change, in the
editor and on disk, and a title heading is only added to a note that has
no top-level heading.
2026-10-10 22:04:38 +02:00
Yuri Karamian 66fe9c8344 fix: rewrite links after a rename in one step and only for the renamed note
Notes that link to a renamed note are replaced in one step instead of with
a truncating write, and an alias is only updated on links that target the
renamed note.
2026-10-10 21:08:19 +02:00
Yuri Karamian 05249a3c81 fix: leave hidden files and empty folders alone when importing
Hidden files and folders are not moved into attachments or deleted, and
folders that were already empty before the import are kept.
2026-10-10 21:08:19 +02:00
Yuri Karamian af35b4dd75 fix: keep version history inside real folders and prune only snapshots
The history folders must be real folders, and only regular files named
like snapshots are listed, read and pruned.
2026-10-10 21:08:19 +02:00
Yuri Karamian b8821dd6fb fix: read frontmatter fields independently and write new frontmatter safely
Known keys are read one by one, so a field of another shape (a scalar tag
list, yes/no, a numeric title or id) no longer discards the note's id,
title and tags. New frontmatter is written through the YAML serializer, so
any title or tag reads back as written.
2026-10-10 21:08:19 +02:00
Yuri Karamian 5185f9a040 feat: open a tag's notes from the tags under a note's title
Clicking a tag there used to open the same tag editor as the header
button. It now shows that tag's notes; editing stays on the header button,
and a note without tags keeps "+ Tags".
2026-10-10 20:24:48 +02:00
Yuri Karamian 7db8d3f9d3 fix: harden backups against empty archives, foreign vaults and sync rollback
A backup folder that contains the vault now produces complete archives and
an archive without content is not restored. Archives from another vault
are labelled. After a restore the sync baseline is reset.
2026-10-10 20:14:37 +02:00
Yuri Karamian 9f9c7e6c07 fix: make configuration saves and loading resilient
The configuration is replaced in one step, an unreadable one is kept aside
instead of being overwritten, missing or damaged entries no longer discard
the rest, and migrated global sync settings are cleared.
2026-10-10 20:14:37 +02:00
76 changed files with 18514 additions and 904 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "packaging/flatpak/shared-modules"]
path = packaging/flatpak/shared-modules
url = https://github.com/flathub/shared-modules.git
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "helixnotes",
"private": true,
"license": "AGPL-3.0-or-later",
"version": "1.3.6",
"version": "1.3.7",
"type": "module",
"packageManager": "pnpm@11.18.0",
"scripts": {
+169
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
{
"only-arches": ["x86_64"]
}
File diff suppressed because it is too large. Load diff
+235
View File
@@ -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()
+1 -1
View File
@@ -1776,7 +1776,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "helixnotes"
version = "1.3.6"
version = "1.3.7"
dependencies = [
"aho-corasick",
"arboard",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "helixnotes"
version = "1.3.6"
version = "1.3.7"
description = "Local markdown note-taking app"
authors = ["HelixNotes"]
license = "AGPL-3.0-or-later"
@@ -33,6 +33,9 @@ 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() {
+115 -5
View File
@@ -54,7 +54,9 @@ fn excluded_path(path: &Path, vault: &Path, backup_dir: &Path, attachments: bool
if path == vault {
return false;
}
if path.starts_with(backup_dir) {
// Only a backup folder inside the vault is skipped. One that contains the vault (its parent,
// the home folder) used to match every path, leaving archives with nothing but the manifest.
if backup_dir.starts_with(vault) && path.starts_with(backup_dir) {
return true;
}
// Old configured backup folders may remain inside the vault after relocation.
@@ -193,9 +195,8 @@ pub fn create_backup(
Ok(())
})();
result?;
// persist_noclobber does not replace an existing backup even on UUID collision.
temporary
.persist_noclobber(&backup_path)
// Never replaces an existing backup, even on UUID collision.
crate::vault::operations::persist_without_replacing(temporary, &backup_path)
.map_err(|e| format!("Failed to publish backup: {}", e.error))?;
let meta = fs::metadata(&backup_path).map_err(|e| e.to_string())?;
Ok(BackupEntry {
@@ -203,6 +204,7 @@ pub fn create_backup(
path: backup_path.to_string_lossy().to_string(),
size: meta.len(),
created: now.to_rfc3339(),
other_vault: false,
})
}
@@ -243,12 +245,15 @@ fn list_owned_backups(
}
let filename = entry.file_name().to_string_lossy().to_string();
if let Some((created, owned)) = archive_name(&filename, &id) {
// Archives from before vault identities carry none, so they cannot be told apart.
let names_a_vault = filename.len() > "helixnotes-backup-0000-00-00T00-00-00.zip".len();
entries.push((
BackupEntry {
filename,
path: path.to_string_lossy().to_string(),
size: meta.len(),
created,
other_vault: names_a_vault && !owned,
},
owned,
));
@@ -262,7 +267,8 @@ fn list_owned_backups(
Ok(entries)
}
/// List backups from every vault; only automatic pruning uses vault identity.
/// List backups from every vault, each marked when it belongs to another one; a vault that was
/// moved or renamed must still be able to restore its earlier archives.
pub fn list_backups(backup_dir: &Path, vault_path: &str) -> Result<Vec<BackupEntry>, String> {
Ok(list_owned_backups(backup_dir, vault_path)?
.into_iter()
@@ -703,6 +709,12 @@ pub fn restore_backup(
));
}
}
// An archive holding only its manifest would replace the vault with nothing.
if seen.keys().all(|entry| entry == Path::new(MANIFEST)) {
return Err(
"This backup contains no notes, so restoring it would empty the vault".to_string(),
);
}
let attachments = if let Some(meta) = manifest {
if meta.version != 1
|| meta.vault.len() != 64
@@ -1094,4 +1106,102 @@ mod tests {
"source content"
);
}
fn archive_names(path: &str) -> Vec<String> {
let mut archive = ZipArchive::new(File::open(path).unwrap()).unwrap();
(0..archive.len())
.map(|index| archive.by_index(index).unwrap().name().to_string())
.collect()
}
#[test]
fn a_backup_folder_that_contains_the_vault_still_archives_the_notes() {
let root = tempdir().unwrap();
let vault = root.path().join("Documents/Notes");
fs::create_dir_all(vault.join("Sub")).unwrap();
fs::write(vault.join("note.md"), "content").unwrap();
fs::write(vault.join("Sub/deep.md"), "deep").unwrap();
// The parent folder, and the folder above that.
for output in [root.path().join("Documents"), root.path().to_path_buf()] {
let entry = create_backup(&vault_string(&vault), &output, false).unwrap();
let names = archive_names(&entry.path);
assert!(names.iter().any(|name| name == "note.md"), "{names:?}");
assert!(names.iter().any(|name| name == "Sub/deep.md"), "{names:?}");
// A second run does not swallow the first archive, which now lies beside the vault.
let again = create_backup(&vault_string(&vault), &output, false).unwrap();
assert!(!archive_names(&again.path)
.iter()
.any(|name| name.ends_with(".zip")));
}
}
#[test]
fn an_archive_without_content_is_not_restored() {
let root = tempdir().unwrap();
let vault = root.path().join("vault");
let output = root.path().join("backups");
fs::create_dir_all(&vault).unwrap();
fs::create_dir_all(&output).unwrap();
fs::write(vault.join("note.md"), "keep me").unwrap();
// What the old exclusion produced: nothing but the manifest.
let empty = output.join(format!(
"helixnotes-backup-2026-01-01T00-00-00-{}-{}.zip",
"a".repeat(64),
Uuid::new_v4()
));
let mut writer = ZipWriter::new(File::create(&empty).unwrap());
writer
.start_file(super::MANIFEST, SimpleFileOptions::default())
.unwrap();
writer
.write_all(
format!(
r#"{{"version":1,"vault":"{}","attachments":false}}"#,
"a".repeat(64)
)
.as_bytes(),
)
.unwrap();
writer.finish().unwrap();
let error =
restore_backup(&vault_string(&vault), &output, &empty.to_string_lossy()).unwrap_err();
assert!(error.contains("contains no notes"), "{error}");
assert_eq!(
fs::read_to_string(vault.join("note.md")).unwrap(),
"keep me"
);
}
#[test]
fn backups_from_another_vault_are_marked() {
let root = tempdir().unwrap();
let output = root.path().join("backups");
let first = root.path().join("first");
let second = root.path().join("second");
fs::create_dir_all(&first).unwrap();
fs::create_dir_all(&second).unwrap();
fs::write(first.join("note.md"), "one").unwrap();
fs::write(second.join("note.md"), "two").unwrap();
let own = create_backup(&vault_string(&first), &output, false).unwrap();
let foreign = create_backup(&vault_string(&second), &output, false).unwrap();
// An archive from before vault identities: it cannot be attributed, so it is not flagged.
fs::copy(
&own.path,
output.join("helixnotes-backup-2020-01-01T00-00-00.zip"),
)
.unwrap();
assert!(!own.other_vault);
let listed = list_backups(&output, &vault_string(&first)).unwrap();
let marked = |path: &str| {
listed
.iter()
.find(|entry| entry.path == path)
.unwrap()
.other_vault
};
assert!(!marked(&own.path));
assert!(marked(&foreign.path));
assert!(listed.iter().filter(|entry| entry.other_vault).count() == 1);
assert_eq!(listed.len(), 3);
}
}
+370 -97
View File
@@ -66,6 +66,48 @@ fn emit_path_move<R: Runtime>(
}
}
#[derive(Clone, serde::Serialize)]
struct LinksRewrittenEvent<'a> {
vault_path: &'a str,
path: &'a str,
old_raw: &'a str,
new_raw: &'a str,
renames: &'a [operations::LinkRename],
}
// A rename also rewrites the notes that link to the renamed one. Keep their previous state in
// version history, and tell open editors so unsaved edits in such a note are not refused as a
// conflict with the disk.
fn announce_rewritten_links<R: Runtime>(
app: &AppHandle<R>,
vault: &str,
links: &operations::LinkRewrite,
max_versions: u32,
) {
for note in &links.notes {
let filename = Path::new(&note.path)
.file_name()
.unwrap_or_default()
.to_string_lossy();
let (meta, _) = crate::vault::frontmatter::parse_note(&note.old_raw, &filename);
if !meta.id.is_empty() {
crate::history::maybe_snapshot(vault, &meta.id, &note.old_raw, max_versions);
}
if let Err(error) = app.emit(
"vault-links-rewritten",
LinksRewrittenEvent {
vault_path: vault,
path: &note.path,
old_raw: &note.old_raw,
new_raw: &note.new_raw,
renames: &links.renames,
},
) {
log::error!("Could not notify note windows about updated links: {error}");
}
}
}
// ── Vault Management ──
#[cfg(target_os = "ios")]
@@ -322,23 +364,36 @@ fn remove_vault_path<R: Runtime>(
bookmark_id: Option<String>,
config_path: &Path,
) -> Result<(), String> {
let find = |config: &AppConfig| {
config
.vaults
.iter()
.find(|vault| match bookmark_id.as_deref() {
Some(bookmark_id) => vault.bookmark_id.as_deref() == Some(bookmark_id),
None => vault.bookmark_id.is_none() && vault.path == path,
})
.cloned()
};
// Asking a window for its address waits for the main thread, and the main thread may be
// waiting for the locks taken below. Check the windows before holding any of them.
#[cfg(desktop)]
{
// Only a bookmarked vault needs the list to learn its path.
let listed = match bookmark_id {
Some(_) => find(&*state.config.lock().map_err(|error| error.to_string())?)
.map(|vault| vault.path),
None => Some(path.clone()),
};
if let Some(vault_path) = listed {
AppState::ensure_no_detached_windows(app, &vault_path)?;
}
}
let mut search_slot = state
.search_index
.lock()
.map_err(|error| error.to_string())?;
let mut config = state.config.lock().map_err(|error| error.to_string())?;
let target = if let Some(bookmark_id) = bookmark_id.as_deref() {
config
.vaults
.iter()
.find(|vault| vault.bookmark_id.as_deref() == Some(bookmark_id))
} else {
config
.vaults
.iter()
.find(|vault| vault.bookmark_id.is_none() && vault.path == path)
}
.map(|vault| {
let target = find(&config).map(|vault| {
let is_active = if let Some(bookmark_id) = vault.bookmark_id.as_deref() {
config.active_bookmark_id.as_deref() == Some(bookmark_id)
} else {
@@ -351,9 +406,6 @@ fn remove_vault_path<R: Runtime>(
let Some((target_path, target_bookmark, is_active)) = target else {
return Ok(());
};
#[cfg(desktop)]
AppState::ensure_no_detached_windows(app, &target_path)?;
let old = config.clone();
let mut next = old.clone();
if let Some(id) = target_bookmark.as_deref() {
@@ -710,9 +762,15 @@ pub async fn rename_notebook<R: Runtime>(
new_name: String,
) -> Result<String, String> {
let search = state.vault_snapshot(&vault_path)?;
let max_versions = state
.config
.lock()
.map_err(|error| error.to_string())?
.max_versions_per_note;
let _write_guard = state.note_save.lock().await;
let renamed = operations::rename_notebook(&vault_path, &path, &new_name)?;
let (renamed, links) = operations::rename_notebook(&vault_path, &path, &new_name)?;
emit_path_move(&app, &vault_path, &path, &renamed, None);
announce_rewritten_links(&app, &vault_path, &links, max_versions);
if let Some(search) = search {
if let Err(error) = search.queue_vault_refresh(&vault_path) {
log::error!("Failed to queue renamed notebook search refresh: {error}");
@@ -730,11 +788,18 @@ pub async fn move_notebook<R: Runtime>(
dest_parent: String,
) -> Result<String, String> {
let search = state.vault_snapshot(&vault_path)?;
let max_versions = state
.config
.lock()
.map_err(|error| error.to_string())?
.max_versions_per_note;
let _write_guard = state.note_save.lock().await;
let vault_path = vault_path.as_str();
let new_full_path = operations::move_notebook(vault_path, &notebook_path, &dest_parent)?;
let (new_full_path, links) =
operations::move_notebook(vault_path, &notebook_path, &dest_parent)?;
emit_path_move(&app, vault_path, &notebook_path, &new_full_path, None);
announce_rewritten_links(&app, vault_path, &links, max_versions);
// Reconcile renamed paths without blocking the move on a full rebuild.
if let Some(search) = search {
@@ -948,9 +1013,15 @@ pub async fn rename_note<R: Runtime>(
new_title: String,
) -> Result<String, String> {
let search = state.vault_snapshot(&vault_path)?;
let max_versions = state
.config
.lock()
.map_err(|error| error.to_string())?
.max_versions_per_note;
let _write_guard = state.note_save.lock().await;
let renamed = operations::rename_note(&path, &new_title, &vault_path)?;
emit_path_move(&app, &vault_path, &path, &renamed.path, Some(&renamed));
announce_rewritten_links(&app, &vault_path, &renamed.links, max_versions);
if let Some(search) = search {
if let Err(error) = search.queue_vault_refresh(&vault_path) {
log::error!("Failed to queue renamed note search refresh: {error}");
@@ -984,14 +1055,23 @@ pub async fn move_note<R: Runtime>(
dest_notebook: String,
) -> Result<String, String> {
let search = state.vault_snapshot(&vault_path)?;
let max_versions = state
.config
.lock()
.map_err(|error| error.to_string())?
.max_versions_per_note;
let _write_guard = state.note_save.lock().await;
let vault_path = vault_path.as_str();
let new_full_path = operations::move_note(vault_path, &note_path, &dest_notebook)?;
let (new_full_path, links) = operations::move_note(vault_path, &note_path, &dest_notebook)?;
emit_path_move(&app, vault_path, &note_path, &new_full_path, None);
announce_rewritten_links(&app, vault_path, &links, max_versions);
index_note_bg(search.clone(), &note_path);
index_note_bg(search, &new_full_path);
index_note_bg(search.clone(), &new_full_path);
for note in &links.notes {
index_note_bg(search.clone(), &note.path);
}
Ok(new_full_path)
}
@@ -1122,6 +1202,8 @@ fn extract_wiki_links(body: &str) -> Vec<String> {
if i + 1 < len {
let link_raw = &body[start..i];
let link = link_raw.split('|').next().unwrap_or(link_raw);
// In a table cell the alias separator is written `\|`.
let link = link.strip_suffix('\\').unwrap_or(link);
let link = link.split('#').next().unwrap_or(link);
let link = link.split('^').next().unwrap_or(link);
links.push(link.trim().to_lowercase());
@@ -1134,6 +1216,19 @@ fn extract_wiki_links(body: &str) -> Vec<String> {
links
}
#[cfg(test)]
mod graph_link_tests {
use super::extract_wiki_links;
#[test]
fn aliased_links_in_a_table_cell_are_found() {
let body =
"| a |\n| --- |\n| [[Home\\|start]] and [[Other]] and [[Deep/Note#part\\|x]] |\n";
assert_eq!(extract_wiki_links(body), ["home", "other", "deep/note"]);
assert_eq!(extract_wiki_links("[[Home|start]]"), ["home"]);
}
}
fn scan_graph_data(vault_path: &str) -> Result<crate::types::GraphData, String> {
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
@@ -3157,49 +3252,7 @@ fn active_vault_path<R: Runtime>(app: &AppHandle<R>) -> Result<PathBuf, String>
.ok_or_else(|| "No active vault".to_string())
}
/// Folders the user already works in: every configured vault and every folder granted through a
/// file dialog or by opening a note from outside a vault. Used to judge network paths by their text.
fn known_roots<R: Runtime>(app: &AppHandle<R>) -> Vec<String> {
let mut roots: Vec<String> = app
.try_state::<AppState>()
.and_then(|state| {
state.config.lock().ok().map(|config| {
config
.vaults
.iter()
.map(|vault| vault.path.clone())
.collect()
})
})
.unwrap_or_default();
for pattern in app.fs_scope().allowed_patterns() {
// Scope entries are glob patterns: `folder`, `folder/*` and `folder/**`, with glob
// characters in the folder name written as one-character classes.
let text = pattern
.as_str()
.replace("[[]", "[")
.replace("[]]", "]")
.replace("[*]", "*")
.replace("[?]", "?");
let folder = text.trim_end_matches(['*', '/', '\\']);
if !folder.is_empty() {
roots.push(folder.to_string());
}
}
roots
}
fn refuse_foreign_network_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
if cfg!(windows) && crate::vault::operations::is_network_path(&path.to_string_lossy()) {
return crate::vault::operations::refuse_foreign_network_path(path, &known_roots(app));
}
Ok(())
}
fn path_is_in_active_vault<R: Runtime>(app: &AppHandle<R>, path: &Path) -> bool {
if refuse_foreign_network_path(app, path).is_err() {
return false;
}
let Ok(vault) = active_vault_path(app)
.and_then(|path| std::fs::canonicalize(path).map_err(|error| error.to_string()))
else {
@@ -3215,7 +3268,6 @@ fn path_is_in_active_vault<R: Runtime>(app: &AppHandle<R>, path: &Path) -> bool
}
fn ensure_scoped_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if app.fs_scope().is_allowed(path) {
Ok(())
} else {
@@ -3224,7 +3276,6 @@ fn ensure_scoped_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(),
}
fn ensure_readable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if path.is_file() && (path_is_in_active_vault(app, path) || app.fs_scope().is_allowed(path)) {
Ok(())
} else {
@@ -3233,7 +3284,6 @@ fn ensure_readable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(
}
fn ensure_writable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if path_is_in_active_vault(app, path) || app.fs_scope().is_allowed(path) {
Ok(())
} else {
@@ -3772,7 +3822,9 @@ pub fn restore_backup(
let result = {
let _writes = state.note_save.blocking_lock();
state.importing.store(true, Ordering::Release);
let result = crate::backup::restore_backup(&vault_path, &backup_dir, &backup_path);
let result = crate::backup::restore_backup(&vault_path, &backup_dir, &backup_path)
// Still under the maintenance lock, so no sync can run in between.
.and_then(|()| crate::sync::forget_baseline(&vault_path));
state.importing.store(false, Ordering::Release);
result
};
@@ -4051,6 +4103,28 @@ mod vault_identity_tests {
config.active_bookmark_id = None;
assert_eq!(active_vault_config(&config).unwrap().name, "Local");
}
#[test]
fn the_folder_request_setting_reaches_the_sync_and_older_configs_get_the_default() {
let mut config = AppConfig {
active_vault: Some("/v".to_string()),
vaults: vec![VaultConfig {
path: "/v".to_string(),
name: "v".to_string(),
sync_provider: Some("webdav".to_string()),
webdav_url: Some("https://x.test/dav".to_string()),
..Default::default()
}],
..Default::default()
};
assert_eq!(sync_config_from(&config).unwrap().listing_parallelism, 0);
config.vaults[0].sync_folder_requests = 3;
assert_eq!(sync_config_from(&config).unwrap().listing_parallelism, 3);
// A vault saved before the setting existed has no such field.
let older: VaultConfig = serde_json::from_str(r#"{"path":"/v","name":"v"}"#).unwrap();
assert_eq!(older.sync_folder_requests, 0);
}
}
fn sync_config_from(config: &AppConfig) -> Result<crate::sync::WebdavConfig, String> {
@@ -4067,6 +4141,7 @@ fn sync_config_from(config: &AppConfig) -> Result<crate::sync::WebdavConfig, Str
url,
username: v.webdav_username.clone().unwrap_or_default(),
password: v.webdav_password.clone().unwrap_or_default(),
listing_parallelism: v.sync_folder_requests as usize,
})
}
@@ -4081,6 +4156,7 @@ pub fn set_sync_settings(
sync_on_open: bool,
sync_on_change: bool,
sync_interval_minutes: u32,
sync_folder_requests: u32,
) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
let active_index = active_vault_index(&config)?;
@@ -4092,6 +4168,8 @@ pub fn set_sync_settings(
v.sync_on_open = sync_on_open;
v.sync_on_change = sync_on_change;
v.sync_interval_minutes = sync_interval_minutes;
v.sync_folder_requests =
crate::sync::effective_listing_parallelism(sync_folder_requests as usize) as u32;
save_app_config(&config)?;
Ok(())
}
@@ -4297,8 +4375,7 @@ fn app_config_path() -> Result<std::path::PathBuf, String> {
pub fn load_app_config() -> AppConfig {
let mut config: AppConfig = app_config_path()
.ok()
.and_then(|p| std::fs::read_to_string(p).ok())
.and_then(|s| serde_json::from_str(&s).ok())
.map(|path| read_app_config(&path))
.unwrap_or_default();
let migrated_sync = migrate_global_sync_to_vault(&mut config);
let migrated_font = adopt_font_size_as_preference(&mut config);
@@ -4308,6 +4385,54 @@ pub fn load_app_config() -> AppConfig {
config
}
/// Reads the configuration, falling back to the defaults when there is none. A file that exists but
/// cannot be parsed is first copied aside: the defaults are saved over it on the next change, and
/// it holds the vault list, sync credentials, API keys and custom themes.
fn read_app_config(path: &Path) -> AppConfig {
let Ok(text) = std::fs::read_to_string(path) else {
return AppConfig::default();
};
match serde_json::from_str(&text) {
Ok(config) => config,
Err(error) => {
if !text.trim().is_empty() {
keep_unreadable_config(path, &text, &error.to_string());
}
AppConfig::default()
}
}
}
fn keep_unreadable_config(path: &Path, text: &str, reason: &str) {
let Some(folder) = path.parent() else { return };
// One copy per distinct content: loading again before anything is saved must not pile them up.
let already_kept = std::fs::read_dir(folder).is_ok_and(|entries| {
entries.flatten().any(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with("config.unreadable-")
&& std::fs::read_to_string(entry.path()).is_ok_and(|kept| kept == text)
})
});
if already_kept {
return;
}
let copy = folder.join(format!(
"config.unreadable-{}.json",
chrono::Utc::now().format("%Y%m%d-%H%M%S")
));
match write_private_file(&copy, text.as_bytes()) {
Ok(()) => eprintln!(
"Configuration could not be read ({reason}); a copy was kept at {}",
copy.display()
),
Err(error) => eprintln!(
"Configuration could not be read ({reason}), and no copy could be kept: {error}"
),
}
}
// One-time migration: the size in use when the preference was introduced becomes the preference,
// so resetting the zoom does not fall back to the built-in default for existing users.
fn adopt_font_size_as_preference(config: &mut AppConfig) -> bool {
@@ -4319,7 +4444,9 @@ fn adopt_font_size_as_preference(config: &mut AppConfig) -> bool {
}
// One-time migration: WebDAV sync moved from global AppConfig to per-vault VaultConfig.
// Copy the old global settings into the active vault's config if it has none yet. Idempotent.
// The old global settings go to the active vault if it has none yet, and are then cleared. Left in
// place, they were copied again at every start into whichever vault was active and had sync
// disabled, undoing "Disabled" and pointing a second vault at the first one's remote folder.
fn migrate_global_sync_to_vault(config: &mut AppConfig) -> bool {
if config.sync_provider.is_none() && config.webdav_url.is_none() {
return false;
@@ -4327,48 +4454,58 @@ fn migrate_global_sync_to_vault(config: &mut AppConfig) -> bool {
let Ok(active_index) = active_vault_index(config) else {
return false;
};
let g_provider = config.sync_provider.clone();
let g_url = config.webdav_url.clone();
let g_user = config.webdav_username.clone();
let g_pass = config.webdav_password.clone();
let g_on_open = config.sync_on_open;
let g_on_change = config.sync_on_change;
let g_interval = config.sync_interval_minutes;
let g_last = config.last_sync_time.clone();
let g_provider = config.sync_provider.take();
let g_url = config.webdav_url.take();
let g_user = config.webdav_username.take();
let g_pass = config.webdav_password.take();
let g_on_open = std::mem::take(&mut config.sync_on_open);
let g_on_change = std::mem::take(&mut config.sync_on_change);
let g_interval = std::mem::take(&mut config.sync_interval_minutes);
let g_last = config.last_sync_time.take();
let v = &mut config.vaults[active_index];
if v.sync_provider.is_some() || v.webdav_url.is_some() {
return false; // already migrated / has its own config
if v.sync_provider.is_none() && v.webdav_url.is_none() {
v.sync_provider = g_provider;
v.webdav_url = g_url;
v.webdav_username = g_user;
v.webdav_password = g_pass;
v.sync_on_open = g_on_open;
v.sync_on_change = g_on_change;
v.sync_interval_minutes = g_interval;
v.last_sync_time = g_last;
}
v.sync_provider = g_provider;
v.webdav_url = g_url;
v.webdav_username = g_user;
v.webdav_password = g_pass;
v.sync_on_open = g_on_open;
v.sync_on_change = g_on_change;
v.sync_interval_minutes = g_interval;
v.last_sync_time = g_last;
true
}
/// Writes an owner-only file by replacing it in one step: the data goes to a temporary file in the
/// same folder, is flushed to disk and then renamed over the target. A crash or a full disk during
/// the write leaves the previous file intact instead of an empty or half-written one.
fn write_private_file(path: &std::path::Path, data: &[u8]) -> Result<(), String> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.create(true).truncate(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|error| error.to_string())?;
let folder = path.parent().ok_or("File has no parent directory")?;
let mut temporary = tempfile::Builder::new()
.prefix(".helixnotes-config-")
.tempfile_in(folder)
.map_err(|error| error.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o600))
temporary
.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o600))
.map_err(|error| error.to_string())?;
}
file.write_all(data).map_err(|error| error.to_string())
temporary
.write_all(data)
.map_err(|error| error.to_string())?;
temporary
.as_file()
.sync_all()
.map_err(|error| error.to_string())?;
temporary
.persist(path)
.map(|_| ())
.map_err(|error| error.error.to_string())
}
#[cfg(all(test, unix))]
@@ -4458,6 +4595,142 @@ pub fn get_install_type() -> String {
}
}
#[cfg(test)]
mod config_resilience_tests {
use super::*;
fn config_from(json: &str) -> (tempfile::TempDir, AppConfig) {
let folder = tempfile::tempdir().unwrap();
let path = folder.path().join("config.json");
std::fs::write(&path, json).unwrap();
let config = read_app_config(&path);
(folder, config)
}
fn kept_copies(folder: &Path) -> Vec<String> {
std::fs::read_dir(folder)
.unwrap()
.flatten()
.map(|entry| entry.file_name().to_string_lossy().to_string())
.filter(|name| name.starts_with("config.unreadable-"))
.collect()
}
#[test]
fn missing_keys_and_damaged_entries_do_not_blank_the_configuration() {
// No `theme`, a custom theme without its colors, a vault without a path, a toolbar of the wrong shape.
let (folder, config) = config_from(
r##"{"vaults":[{"path":"/notes","name":"Notes","webdav_url":"https://dav.example/x"},{"name":"broken"}],
"active_vault":"/notes","font_size":18,"toolbar_layout":"oops",
"custom_themes":[{"id":"a","name":"A","is_dark":true},
{"id":"b","name":"B","is_dark":false,"colors":{"bg_primary":"#fff","bg_secondary":"#fff","bg_tertiary":"#fff","bg_hover":"#fff","bg_active":"#fff","bg_editor":"#fff","text_primary":"#000","text_secondary":"#000","border_color":"#000"}}]}"##,
);
assert_eq!(config.vaults.len(), 1);
assert_eq!(
config.vaults[0].webdav_url.as_deref(),
Some("https://dav.example/x")
);
assert_eq!(config.active_vault.as_deref(), Some("/notes"));
assert_eq!(config.font_size, Some(18));
assert_eq!(config.theme, AppConfig::default().theme);
assert!(config.toolbar_layout.is_none());
assert_eq!(config.custom_themes.len(), 1);
assert_eq!(config.custom_themes[0].id, "b");
assert!(kept_copies(folder.path()).is_empty());
}
#[test]
fn an_unreadable_configuration_is_kept_aside_once() {
let (folder, config) =
config_from(r#"{"vaults":[{"path":"/notes","name":"Notes"}],"active_va"#);
assert!(config.vaults.is_empty());
let copies = kept_copies(folder.path());
assert_eq!(copies.len(), 1);
assert_eq!(
std::fs::read_to_string(folder.path().join(&copies[0])).unwrap(),
r#"{"vaults":[{"path":"/notes","name":"Notes"}],"active_va"#
);
// Loading again before anything is saved keeps no second copy.
read_app_config(&folder.path().join("config.json"));
assert_eq!(kept_copies(folder.path()).len(), 1);
// No file and an empty file are a fresh start, not damage.
assert!(read_app_config(&folder.path().join("absent.json"))
.vaults
.is_empty());
let (empty, _) = config_from("");
assert!(kept_copies(empty.path()).is_empty());
}
#[test]
fn saving_replaces_the_file_in_one_step_and_leaves_nothing_behind() {
let folder = tempfile::tempdir().unwrap();
let path = folder.path().join("config.json");
std::fs::write(&path, "previous").unwrap();
save_app_config_to(&AppConfig::default(), &path).unwrap();
assert!(read_app_config(&path).vaults.is_empty());
let names: Vec<_> = std::fs::read_dir(folder.path())
.unwrap()
.flatten()
.map(|entry| entry.file_name())
.collect();
assert_eq!(names, vec![std::ffi::OsString::from("config.json")]);
}
fn vault(path: &str) -> crate::types::VaultConfig {
serde_json::from_value(serde_json::json!({ "path": path, "name": path })).unwrap()
}
#[test]
fn global_sync_settings_move_to_the_active_vault_once() {
let mut config = AppConfig {
vaults: vec![vault("/a"), vault("/b")],
active_vault: Some("/a".into()),
sync_provider: Some("webdav".into()),
webdav_url: Some("https://dav.example/a".into()),
webdav_username: Some("me".into()),
webdav_password: Some("secret".into()),
sync_on_open: true,
..AppConfig::default()
};
assert!(migrate_global_sync_to_vault(&mut config));
assert_eq!(
config.vaults[0].webdav_url.as_deref(),
Some("https://dav.example/a")
);
assert!(config.vaults[0].sync_on_open);
// The global copy is gone, so nothing is left to hand out again.
assert!(config.sync_provider.is_none() && config.webdav_url.is_none());
assert!(config.webdav_username.is_none() && config.webdav_password.is_none());
assert!(!config.sync_on_open);
// Disabling sync on that vault stays disabled, and another vault inherits nothing.
config.vaults[0].sync_provider = None;
config.vaults[0].webdav_url = None;
config.active_vault = Some("/b".into());
assert!(!migrate_global_sync_to_vault(&mut config));
assert!(config.vaults[0].webdav_url.is_none());
assert!(config.vaults[1].webdav_url.is_none());
}
#[test]
fn a_vault_with_its_own_sync_settings_keeps_them_and_the_global_copy_is_cleared() {
let mut own = vault("/a");
own.webdav_url = Some("https://dav.example/own".into());
let mut config = AppConfig {
vaults: vec![own],
active_vault: Some("/a".into()),
webdav_url: Some("https://dav.example/old".into()),
..AppConfig::default()
};
assert!(migrate_global_sync_to_vault(&mut config));
assert_eq!(
config.vaults[0].webdav_url.as_deref(),
Some("https://dav.example/own")
);
assert!(config.webdav_url.is_none());
}
}
#[cfg(test)]
mod open_file_tests {
use super::opens_with_default_application;
+107 -8
View File
@@ -18,10 +18,44 @@ 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> {
@@ -43,7 +77,7 @@ fn snapshot_path(dir: &Path, raw_content: &str) -> Result<(), String> {
// allowing multiple versions within one second.
let timestamp = instant.format("%Y-%m-%dT%H-%M-%S%.3f");
let path = dir.join(format!("{timestamp}.md"));
match temporary.persist_noclobber(&path) {
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;
@@ -167,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()
@@ -195,6 +229,9 @@ pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<S
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))
}
@@ -204,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
@@ -279,7 +317,8 @@ mod tests {
super::force_snapshot(root, "note", "new", 0).unwrap();
super::maybe_snapshot(root, "note", "too soon", 0);
let versions = list_versions(root, "note").unwrap();
assert_eq!(versions.len(), 3);
// 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"
@@ -289,4 +328,64 @@ mod tests {
"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);
}
}
}
+83 -24
View File
@@ -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());
}
}
+754 -64
View File
File diff suppressed because it is too large. Load diff
+36 -2
View File
@@ -102,6 +102,9 @@ 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)]
@@ -146,8 +149,36 @@ pub struct ToolbarLayout {
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)]
@@ -169,7 +200,7 @@ pub struct AppConfig {
pub preferred_font_size: Option<u32>,
#[serde(default = "default_true")]
pub scroll_to_change_font_size: bool,
#[serde(default)]
#[serde(default, deserialize_with = "lenient_option")]
pub toolbar_layout: Option<ToolbarLayout>,
#[serde(default)]
pub font_family: Option<String>,
@@ -278,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>,
}
@@ -540,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)]
+193 -40
View File
@@ -101,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::<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));
@@ -138,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)
@@ -161,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 {
@@ -277,11 +315,7 @@ pub fn filename_to_title(filename: &str) -> String {
pub fn extract_title(raw: &str) -> Option<String> {
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 {
@@ -575,4 +609,123 @@ mod tests {
"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(&note("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(&note("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(&note("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(&note("tags: work\naliases: [x]"), "File.md");
let saved = merge_frontmatter(&note("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", "&amp"],
),
("- 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"));
}
}
+67 -11
View File
@@ -15,6 +15,9 @@ 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)?;
@@ -204,16 +207,18 @@ pub fn import(vault_path: &str) -> Result<ImportResult, String> {
}
}
cleanup_empty_dirs(vault)?;
cleanup_empty_dirs(vault, &already_empty)?;
Ok(result)
}
fn is_excluded_dir(path: &Path) -> bool {
matches!(
path.file_name().and_then(|name| name.to_str()),
Some(".helixnotes" | ".obsidian" | ".trash" | ".stfolder" | ".claude")
)
/// 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(
@@ -221,9 +226,7 @@ fn vault_entries(
) -> impl Iterator<Item = Result<walkdir::DirEntry, walkdir::Error>> + '_ {
walkdir::WalkDir::new(vault)
.into_iter()
.filter_entry(|entry| {
entry.depth() == 0 || !entry.file_type().is_dir() || !is_excluded_dir(entry.path())
})
.filter_entry(|entry| entry.depth() == 0 || !is_hidden_entry(entry.path()))
}
fn scanned_files(vault: &Path) -> Result<Vec<PathBuf>, String> {
@@ -782,7 +785,20 @@ fn resolve_relative_ref(base: &Path, reference: &str) -> Option<String> {
Some(rel.to_string_lossy().replace('\\', "/"))
}
fn cleanup_empty_dirs(root: &Path) -> Result<(), String> {
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())),
@@ -795,7 +811,7 @@ fn cleanup_empty_dirs(root: &Path) -> Result<(), String> {
dirs.sort_by_key(|path| std::cmp::Reverse(path.components().count()));
for dir in dirs {
if dir == root {
if dir == root || keep.contains(&dir) {
continue;
}
let mut entries =
@@ -908,6 +924,46 @@ mod tests {
}
}
#[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![p](Pictures/photo.png)\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();
+2
View File
@@ -1,6 +1,8 @@
pub mod frontmatter;
pub mod import;
pub mod operations;
#[cfg(target_os = "linux")]
mod portal_watcher;
pub mod watcher;
#[cfg(test)]
+3 -1
View File
@@ -182,7 +182,9 @@ fn imported_document_links_remain_managed_and_stable_after_note_and_notebook_mov
.as_ref(),
);
assert_eq!(fs::read(attachment).unwrap(), b"pdf");
let moved = super::operations::move_note(&vault, &note.path, &vault).unwrap();
let moved = super::operations::move_note(&vault, &note.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(
File diff suppressed because it is too large. Load diff
+353
View File
@@ -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, &current) {
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(&note, "before").unwrap();
let modified = fs::metadata(&note).unwrap().modified().unwrap();
let before = scan(vault.path()).unwrap();
std::thread::sleep(Duration::from_millis(2));
fs::write(&note, "after!").unwrap();
set_modified(&note, modified);
assert_eq!(fs::metadata(&note).unwrap().modified().unwrap(), modified);
assert_modified(&before, vault.path(), &note);
}
#[test]
fn backdated_and_fractional_modification_times_are_detected() {
let vault = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
fs::write(&note, "before").unwrap();
set_modified(&note, UNIX_EPOCH + Duration::new(1000, 100));
let before = scan(vault.path()).unwrap();
fs::write(&note, "after!").unwrap();
set_modified(&note, UNIX_EPOCH + Duration::new(1000, 200));
let metadata = fs::metadata(&note).unwrap();
assert_eq!((metadata.mtime(), metadata.mtime_nsec()), (1000, 200));
assert_modified(&before, vault.path(), &note);
let before = scan(vault.path()).unwrap();
set_modified(&note, UNIX_EPOCH + Duration::from_secs(10));
assert_modified(&before, vault.path(), &note);
}
#[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(&note, "before").unwrap();
let metadata = fs::metadata(&note).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, &note).unwrap();
let replaced = fs::metadata(&note).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(), &note);
}
#[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, &current);
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(&current, &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(&note, "before").unwrap();
fs::write(outside.path().join("Outside.md"), "outside").unwrap();
symlink(&note, &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(&note, 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(&note, "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(&note, 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(&note));
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)
));
}
}
+68 -33
View File
@@ -9,8 +9,11 @@ use tauri::{AppHandle, Emitter, Manager};
use crate::state::AppState;
use crate::types::FileEvent;
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);
@@ -18,35 +21,48 @@ const EVENT_BATCH_INTERVAL: Duration = Duration::from_millis(50);
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),
}
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),
}
}
Recommended {
_watcher: RecommendedWatcher,
},
Poll {
_watcher: PollWatcher,
},
#[cfg(target_os = "linux")]
Portal {
_watcher: PortalWatcher,
},
}
fn collect_changes(event: Event, vault_root: &Path, changes: &mut HashMap<PathBuf, &'static str>) {
@@ -115,21 +131,33 @@ pub(crate) fn changed_entry(path: PathBuf, event_type: &str, vault_root: &Path)
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())?;
std::thread::spawn(move || {
let vault_root = Path::new(&vault_path);
let mut changes = HashMap::new();
@@ -222,25 +250,32 @@ 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)
);
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "HelixNotes",
"version": "1.3.6",
"version": "1.3.7",
"identifier": "com.helixnotes.app",
"build": {
"frontendDist": "../build",
+250
View File
@@ -1074,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 {
+2 -1
View File
@@ -553,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> {
+273 -30
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { onMount, onDestroy, tick, untrack } from 'svelte';
import { MediaQuery } from 'svelte/reactivity';
import { listen } from '@tauri-apps/api/event';
import Sidebar from './Sidebar.svelte';
import NoteList from './NoteList.svelte';
@@ -56,6 +57,7 @@
notebookOrder,
noteOrder,
syncState,
type SyncSummary,
platformIsMobile,
activeVaultConfig,
activateVaultData,
@@ -65,6 +67,19 @@
const appWindow = getCurrentWindow();
const isMac = navigator.platform.startsWith('Mac');
const isMobile = $derived($platformIsMobile);
// A tablet in landscape has room for the editor next to the navigation: the notebooks or the
// note list stay on the left instead of replacing the note. Narrower windows (phones, a tablet
// in portrait or in a split screen) keep one panel at a time.
const wideMobileQuery = new MediaQuery('(min-width: 900px)');
const tabletLayout = $derived(isMobile && wideMobileQuery.current);
// Kept on the device: the vault state is shared with desktops, where collapsing means something else.
let tabletNavHidden = $state(localStorage.getItem('helix-tablet-nav-hidden') === '1');
const tabletNavShown = $derived(tabletLayout && !tabletNavHidden);
function setTabletNavHidden(hidden: boolean) {
tabletNavHidden = hidden;
localStorage.setItem('helix-tablet-nav-hidden', hidden ? '1' : '0');
}
import { loadVaultState, saveVaultState, readNote, deleteNote, createDailyNote, createBackup, getPendingOpenFile, ackPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api';
import { darkThemes, isAndroid } from '$lib/platform';
import { openNoteWindow } from '$lib/utils/window';
@@ -91,6 +106,70 @@
let editor = $state<Editor>();
let outlineOpen = $state(false);
let outlinePanelId = $state('');
let mobileNoteMenuOpen = $state(false);
let mobileNoteMenuWrapper = $state<HTMLDivElement>();
let mobileNoteMenuTrigger = $state<HTMLButtonElement>();
let mobileNoteMenu = $state<HTMLDivElement>();
let mobileBackButton = $state<HTMLButtonElement>();
function closeMobileNoteMenu(restoreTriggerFocus = false) {
const wasOpen = mobileNoteMenuOpen;
mobileNoteMenuOpen = false;
if (wasOpen && restoreTriggerFocus) mobileNoteMenuTrigger?.focus();
}
async function toggleMobileNoteMenu() {
if (mobileNoteMenuOpen) {
closeMobileNoteMenu(true);
return;
}
mobileNoteMenuOpen = true;
await tick();
if (mobileNoteMenuOpen) mobileNoteMenu?.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus();
}
function handleMobileNoteMenuKeydown(event: KeyboardEvent) {
if (event.key === 'Tab') {
closeMobileNoteMenu(true);
return;
}
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
const buttons = Array.from(mobileNoteMenu?.querySelectorAll<HTMLButtonElement>('button:not(:disabled)') ?? []);
if (!buttons.length) return;
event.preventDefault();
const current = buttons.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1
: event.key === 'ArrowDown' ? (current + 1) % buttons.length
: current < 0 ? buttons.length - 1 : (current - 1 + buttons.length) % buttons.length;
buttons[next].focus();
}
$effect(() => {
$activeNotePath;
$mobileView;
tabletLayout;
mobileNoteMenuOpen = false;
});
$effect(() => {
if (!mobileNoteMenuOpen) return;
const handleOutsidePointerDown = (event: PointerEvent) => {
const target = event.target as Node;
if (!mobileNoteMenuWrapper?.contains(target) && !mobileBackButton?.contains(target)) closeMobileNoteMenu();
};
const handleEscape = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
event.preventDefault();
event.stopPropagation();
closeMobileNoteMenu(true);
};
document.addEventListener('pointerdown', handleOutsidePointerDown, true);
document.addEventListener('keydown', handleEscape, true);
return () => {
document.removeEventListener('pointerdown', handleOutsidePointerDown, true);
document.removeEventListener('keydown', handleEscape, true);
};
});
function handleOutlineChange(open: boolean, panelId: string) {
outlineOpen = open;
@@ -220,6 +299,7 @@
function parseFrequencyMs(freq: string): number {
switch (freq) {
case '1h': return 60 * 60 * 1000;
case '6h': return 6 * 60 * 60 * 1000;
case '12h': return 12 * 60 * 60 * 1000;
case '7d': return 7 * 24 * 60 * 60 * 1000;
@@ -562,6 +642,14 @@
});
});
/** A tag clicked under a note's title: browse that tag's notes, like picking it in the sidebar. */
function showTagNotes(tag: string) {
$viewMode = 'tag';
$activeTag = tag;
$activeNotebook = null;
handleViewChanged();
}
function handleViewChanged() {
if (!ownerIsCurrent()) return;
beginNavigation();
@@ -645,12 +733,16 @@
// sidebar=0, notelist=1, editor=2. Each forward nav pushes, back pops.
let historyDepth = 0;
let navFromPopstate = false;
let lastMobileView = get(mobileView);
if (get(platformIsMobile)) {
history.replaceState({ mobileView: 'sidebar', depth: 0 }, '');
$effect(() => {
const view = $mobileView;
// Going to the notebooks or the note list brings a hidden column back.
if (view !== 'editor' && view !== untrack(() => lastMobileView)) untrack(() => setTabletNavHidden(false));
lastMobileView = view;
if (navFromPopstate) {
navFromPopstate = false;
return;
@@ -678,7 +770,8 @@
return;
}
// If a modal is open, close it instead of navigating
if ($showSettings || $showInfo || $showSearch || $showCommandPalette) {
if (mobileNoteMenuOpen || $showSettings || $showInfo || $showSearch || $showCommandPalette) {
closeMobileNoteMenu(true);
$showSettings = false;
$showInfo = false;
$showSearch = false;
@@ -689,7 +782,13 @@
}
const state = e.state;
const targetDepth = state?.depth ?? 0;
const leavingEditor = $mobileView === 'editor';
historyDepth = targetDepth;
if (tabletLayout && leavingEditor && targetDepth === 1) {
// The note list is already showing beside the note, so back goes on to the notebooks.
$mobileView = 'sidebar';
return;
}
navFromPopstate = true;
if (targetDepth === 0) $mobileView = 'sidebar';
else if (targetDepth === 1) $mobileView = 'notelist';
@@ -700,8 +799,12 @@
}
function mobileBack() {
if ($mobileView === 'editor') $mobileView = 'notelist';
else if ($mobileView === 'notelist') $mobileView = 'sidebar';
if (mobileNoteMenuOpen) {
closeMobileNoteMenu(true);
return;
}
if ($mobileView === 'editor' && !tabletLayout) $mobileView = 'notelist';
else $mobileView = 'sidebar';
}
async function trashOpenNote(path: string): Promise<boolean> {
@@ -732,6 +835,14 @@
if (e.button === 4) { e.preventDefault(); navigateHistory(1); }
}
// True when the event is going to a text field or editor. App-wide
// shortcuts must leave those keys alone so editing keeps working - for
// example Alt+Left/Right moves by word in the editor and in inputs.
function isEditableTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
return target.isContentEditable || !!target.closest('input, textarea, .cm-editor');
}
function handleKeydown(e: KeyboardEvent) {
const mod = e.ctrlKey || e.metaKey;
const code = e.code;
@@ -751,6 +862,10 @@
const action = matchAction(e, $keybindings);
if (action) {
// History navigation is bound to Alt+Left/Right by default. While the
// user is editing, those keys belong to the editor (word movement),
// so skip the app shortcut and let the editable surface handle them.
if ((action === 'nav-back' || action === 'nav-forward') && isEditableTarget(e.target)) return;
e.preventDefault();
switch (action) {
case 'nav-back':
@@ -780,6 +895,9 @@
$showSearch = true;
}
return;
case 'replace-in-note':
if ($activeNotePath) editor?.openNoteSearch(true);
return;
case 'quick-open':
$showCommandPalette = true;
return;
@@ -1059,12 +1177,13 @@
// ── WebDAV sync: global status + auto-sync triggers ──
unlistenSync.push(await listen<{ vault_path: string }>('sync-progress', ({ payload }) => {
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: true, error: null });
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: true, error: null, result: null });
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null; success: boolean; last_sync_time?: string | null }>('sync-done', ({ payload }) => {
unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null; success: boolean; summary?: SyncSummary; last_sync_time?: string | null }>('sync-done', ({ payload }) => {
if (!ownerIsCurrent() || payload.vault_path !== ownerVault) return;
syncState.set({ running: false, error: null });
syncState.set({ running: false, error: null,
result: payload.success ? { vault: payload.vault_path, summary: payload.summary ?? {} } : null });
if (!payload.success || !payload.last_sync_time) return;
const current = get(appConfig);
const active = activeVaultConfig(current);
@@ -1075,7 +1194,7 @@
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
unlistenSync.push(await listen<{ vault_path: string; error?: string }>('sync-error', ({ payload }) => {
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: false, error: payload.error ?? 'Sync failed' });
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: false, error: payload.error ?? 'Sync failed', result: null });
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
@@ -1132,8 +1251,18 @@
<div class="mobile-shell">
<!-- Mobile Header -->
<div class="mobile-header">
{#if $mobileView !== 'sidebar'}
<button class="mobile-header-btn" onclick={mobileBack} aria-label="Go back">
{#if tabletLayout}
<button class="mobile-header-btn" class:active={!tabletNavHidden} onclick={() => setTabletNavHidden(!tabletNavHidden)}
title={tabletNavHidden ? 'Show side panel' : 'Hide side panel'} aria-label={tabletNavHidden ? 'Show side panel' : 'Hide side panel'} aria-pressed={!tabletNavHidden}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/>
</svg>
</button>
{/if}
{#if tabletLayout && tabletNavHidden}
<!-- The hidden column has no title or back step to show. -->
{:else if $mobileView !== 'sidebar'}
<button class="mobile-header-btn" bind:this={mobileBackButton} onclick={mobileBack} aria-label="Go back">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M15 18l-6-6 6-6"/>
</svg>
@@ -1149,7 +1278,7 @@
</svg>
</div>
{/if}
{#if $mobileView !== 'editor'}
{#if tabletNavShown || (!tabletLayout && $mobileView !== 'editor')}
<span class="mobile-header-title">
{#if $mobileView === 'sidebar'}
HelixNotes
@@ -1164,8 +1293,8 @@
{/if}
{/if}
<div class="mobile-header-actions">
{#if $mobileView === 'editor'}
<button class="mobile-header-btn" class:active={$readOnly} disabled={isTrashedNote($activeNotePath, ownerVault)} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Edit' : 'View'}>
{#if $mobileView === 'editor' || (tabletLayout && $activeNotePath)}
<button class="mobile-header-btn" class:active={$readOnly} disabled={isTrashedNote($activeNotePath, ownerVault)} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? 'Edit' : 'View'} aria-label={$readOnly ? 'Edit' : 'View'}>
<svg width="18" height="18" 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" />
@@ -1176,17 +1305,19 @@
{/if}
</svg>
</button>
<button class="mobile-header-btn" onclick={() => editor?.openNoteSearch()} title="Find in note">
<button class="mobile-header-btn" onclick={() => editor?.openNoteSearch()} title="Find in note" aria-label="Find in note">
<svg width="18" height="18" 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"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
</svg>
</button>
<button class="mobile-header-btn" class:active={$activeNote?.meta.pinned} onclick={() => { if ($activeNote) { $activeNote.meta.pinned = !$activeNote.meta.pinned; editor?.markEdited(); } }} title="Pin">
{#snippet secondaryNoteActions(inMenu: boolean)}
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitemcheckbox' : undefined} aria-checked={inMenu ? !!$activeNote?.meta.pinned : undefined} class:active={$activeNote?.meta.pinned} onclick={() => { if ($activeNote) { $activeNote.meta.pinned = !$activeNote.meta.pinned; editor?.markEdited(); } }} title="Pin">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 17v5"/><path d="M9 2h6l-1 7h4l-2 4H8l-2-4h4L9 2z"/>
</svg>
{#if inMenu}<span>Pin</span>{/if}
</button>
<button class="mobile-header-btn" class:active={isQuickAccess} onclick={async () => {
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitemcheckbox' : undefined} aria-checked={inMenu ? isQuickAccess : undefined} class:active={isQuickAccess} onclick={async () => {
if (!noteRelativePath) return;
try {
if (isQuickAccess) { await removeQuickAccess(ownerVault!, noteRelativePath); } else { await addQuickAccess(ownerVault!, noteRelativePath); }
@@ -1198,46 +1329,73 @@
<svg width="18" height="18" viewBox="0 0 24 24" fill={isQuickAccess ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
</svg>
{#if inMenu}<span>Quick Access</span>{/if}
</button>
<button class="mobile-header-btn" class:active={outlineOpen} onclick={() => editor?.toggleOutlinePanel()}
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} class:active={outlineOpen} onclick={() => editor?.toggleOutlinePanel()}
title="Outline" aria-label="Outline" aria-expanded={outlineOpen} aria-controls={outlinePanelId || undefined}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="4" y1="6" x2="20" y2="6"/><line x1="8" y1="12" x2="20" y2="12"/><line x1="8" y1="18" x2="20" y2="18"/><circle cx="4" cy="12" r="1" fill="currentColor"/><circle cx="4" cy="18" r="1" fill="currentColor"/>
</svg>
{#if inMenu}<span>Outline</span>{/if}
</button>
<button class="mobile-header-btn" onclick={() => editor?.toggleHistoryPanel()} title="History">
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} onclick={() => editor?.toggleHistoryPanel()} title="History">
<svg width="18" height="18" 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"/><polyline points="12 6 12 12 16 14"/>
</svg>
{#if inMenu}<span>History</span>{/if}
</button>
{#if $appConfig?.enable_wiki_links}
<button class="mobile-header-btn" onclick={() => editor?.toggleGraphView()} title="Graph View">
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} onclick={() => editor?.toggleGraphView()} title="Graph View">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="6" cy="6" r="3"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="18" r="3"/>
<line x1="8.5" y1="7.5" x2="15.5" y2="16.5"/><line x1="15.5" y1="7.5" x2="8.5" y2="16.5"/>
</svg>
{#if inMenu}<span>Graph View</span>{/if}
</button>
{/if}
{#if $appConfig?.ai_provider}
<button class="mobile-header-btn" onclick={() => editor?.triggerAiMenu()} title="AI Actions">
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} onclick={() => editor?.triggerAiMenu()} title="AI Actions">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 8V4l-2-2"/><rect x="4" y="8" width="16" height="12" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M9 13v2"/><path d="M15 13v2"/>
</svg>
{#if inMenu}<span>AI Actions</span>{/if}
</button>
{/if}
{#if activeVaultConfig($appConfig)?.sync_provider === 'webdav'}
<button class="mobile-header-btn" class:active={$syncState.running} onclick={triggerSyncNow} disabled={$syncState.running} title={$syncState.error ? `Sync error: ${$syncState.error}` : ($syncState.running ? 'Syncing...' : 'Sync now')}>
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} class:active={$syncState.running} onclick={triggerSyncNow} disabled={$syncState.running} title={$syncState.error ? `Sync error: ${$syncState.error}` : ($syncState.running ? 'Syncing...' : 'Sync now')}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class:sync-spin={$syncState.running}>
<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0115-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 01-15 6.7L3 16"/>
</svg>
{#if inMenu}<span>{$syncState.running ? 'Syncing...' : $syncState.error ? 'Sync error: retry' : 'Sync now'}</span>{/if}
</button>
{/if}
<button class="mobile-header-btn" class:active={$sourceMode} onclick={() => ($sourceMode = !$sourceMode)} title={$sourceMode ? 'Rich Editor' : 'Source Mode'}>
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} class:active={$sourceMode} onclick={() => ($sourceMode = !$sourceMode)} title={$sourceMode ? 'Rich Editor' : 'Source Mode'}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
</svg>
{#if inMenu}<span>{$sourceMode ? 'Rich Editor' : 'Source Mode'}</span>{/if}
</button>
{:else}
{/snippet}
{#if tabletLayout}
{@render secondaryNoteActions(false)}
{:else}
<div class="mobile-note-menu-wrapper" bind:this={mobileNoteMenuWrapper}>
<button class="mobile-header-btn" class:active={mobileNoteMenuOpen} type="button" bind:this={mobileNoteMenuTrigger}
title="More note actions" aria-label="More note actions" aria-haspopup="menu" aria-expanded={mobileNoteMenuOpen} aria-controls="mobile-note-menu" onclick={toggleMobileNoteMenu}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/>
</svg>
</button>
{#if mobileNoteMenuOpen}
<div class="mobile-note-menu" id="mobile-note-menu" bind:this={mobileNoteMenu} role="menu" aria-label="Note actions" tabindex="-1"
onkeydown={handleMobileNoteMenuKeydown} onclickcapture={() => closeMobileNoteMenu(true)}>
{@render secondaryNoteActions(true)}
</div>
{/if}
</div>
{/if}
{/if}
{#if tabletLayout || $mobileView !== 'editor'}
<button class="mobile-header-btn" onclick={() => ($showSearch = true)} title="Search">
<svg width="18" height="18" 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" />
@@ -1270,15 +1428,15 @@
</div>
<!-- Mobile Content -->
<div class="mobile-content">
<div class="mobile-panel" class:active={$mobileView === 'sidebar'}>
<div class="mobile-content" class:tablet={tabletLayout} class:nav-hidden={tabletLayout && tabletNavHidden}>
<div class="mobile-panel" class:active={$mobileView === 'sidebar' && (!tabletLayout || tabletNavShown)}>
<Sidebar bind:this={sidebar} onViewChanged={handleViewChanged} onBeforeNoteChange={() => editor?.flushSave() ?? Promise.resolve(true)} onBeforePathMutation={() => editor?.beginPathMutation() ?? Promise.resolve(() => {})} onPathsMoved={handlePathsMoved} />
</div>
<div class="mobile-panel" class:active={$mobileView === 'notelist'}>
<div class="mobile-panel" class:active={tabletLayout ? tabletNavShown && $mobileView !== 'sidebar' : $mobileView === 'notelist'}>
<NoteList bind:this={noteList} onNoteSelected={handleNoteSelected} onBeforeNoteSwitch={() => editor?.flushSave() ?? Promise.resolve(true)} onBeforeNoteDuplicate={() => editor?.forceSave() ?? Promise.resolve(true)} onBeforePathMutation={() => editor?.beginPathMutation() ?? Promise.resolve(() => {})} onPathsMoved={handlePathsMoved} onUpdateActiveNote={updateActiveNoteMetadata} onTagsChanged={handleTagsChanged} onRefreshTags={() => { if (!isMobile) void sidebar?.refreshTags(); }} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={(token) => { editor?.focusTitle(token); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} />
</div>
<div class="mobile-panel" class:active={$mobileView === 'editor'}>
<Editor bind:this={editor} onMoveToTrash={trashOpenNote} onOutlineChange={handleOutlineChange} />
<div class="mobile-panel mobile-editor-panel" class:active={$mobileView === 'editor' || tabletLayout}>
<Editor bind:this={editor} onMoveToTrash={trashOpenNote} onOutlineChange={handleOutlineChange} onShowTag={showTagNotes} />
</div>
</div>
@@ -1355,7 +1513,7 @@
{/if}
<div class="editor-panel">
<Editor bind:this={editor} onMoveToTrash={trashOpenNote} />
<Editor bind:this={editor} onMoveToTrash={trashOpenNote} onShowTag={showTagNotes} />
{#if $viewMode === 'tasks' && !taskNoteOpened}
<div class="tasks-editor-placeholder">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
@@ -1531,8 +1689,8 @@
.mobile-header {
display: flex;
align-items: center;
height: 52px;
padding: 0 8px;
min-height: 52px;
padding: 8px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
flex-shrink: 0;
@@ -1576,12 +1734,16 @@
.mobile-header-actions {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
min-width: 0;
gap: 2px;
margin-left: auto;
}
.mobile-header-btn {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: center;
width: 34px;
@@ -1606,6 +1768,70 @@
color: var(--accent);
}
.mobile-note-menu-wrapper {
position: relative;
flex-shrink: 0;
}
.mobile-note-menu {
position: absolute;
top: calc(100% + 8px);
right: 0;
z-index: 1000;
width: min(260px, calc(100vw - 24px));
max-height: calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 72px);
overflow-y: auto;
overscroll-behavior: contain;
padding: 6px;
border: 1px solid var(--border-color);
border-radius: 10px;
background: var(--bg-secondary);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
}
.mobile-note-menu-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
min-height: 42px;
padding: 8px 10px;
border: none;
border-radius: 7px;
background: none;
color: var(--text-primary);
font: inherit;
font-size: 14px;
text-align: left;
cursor: pointer;
}
.mobile-note-menu-item svg {
width: 18px;
height: 18px;
flex-shrink: 0;
}
.mobile-note-menu-item:hover {
background: var(--bg-hover);
}
.mobile-note-menu-item.active {
color: var(--accent);
background: var(--accent-light);
}
.mobile-note-menu-item:disabled {
opacity: 0.5;
cursor: default;
}
.mobile-header-btn:focus-visible,
.mobile-note-menu-item:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.mobile-content {
flex: 1;
overflow: hidden;
@@ -1627,4 +1853,21 @@
pointer-events: auto;
}
.mobile-content.tablet .mobile-panel {
right: auto;
width: 320px;
border-right: 1px solid var(--border-color);
}
.mobile-content.tablet .mobile-editor-panel {
left: 320px;
right: 0;
width: auto;
border-right: none;
}
.mobile-content.tablet.nav-hidden .mobile-editor-panel {
left: 0;
}
</style>
+1 -1
View File
@@ -184,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');
File diff suppressed because it is too large. Load diff
+14 -7
View File
@@ -311,13 +311,16 @@
// Local mode: restrict which nodes/edges are visible
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;
@@ -330,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);
}
@@ -341,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];
@@ -370,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++) {
@@ -392,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++) {
+6 -3
View File
@@ -1209,9 +1209,12 @@
clearSelection();
}
if ((e.ctrlKey || e.metaKey) && e.key === 'a' && $sortedNotes.length > 0) {
// Only select all if focus is not in an input/editor
const tag = (e.target as HTMLElement)?.tagName;
if (tag !== 'INPUT' && tag !== 'TEXTAREA' && !(e.target as HTMLElement)?.closest('.ProseMirror')) {
// Only select all notes when Ctrl+A is not meant for a text field or either editor
// (the source editor is CodeMirror, and a read-only editor is not contenteditable).
const target = e.target as HTMLElement | null;
const tag = target?.tagName;
if (tag !== 'INPUT' && tag !== 'TEXTAREA' && tag !== 'SELECT' && !target?.isContentEditable
&& !target?.closest('.ProseMirror, .cm-editor')) {
e.preventDefault();
selectedPaths = new Set($sortedNotes.map(n => n.path));
}
+80
View File
@@ -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" />
+85 -62
View File
@@ -1,11 +1,12 @@
<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 { 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';
@@ -467,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;
@@ -491,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) {
@@ -511,6 +517,7 @@
sync_on_open: syncOnOpen,
sync_on_change: syncOnChange,
sync_interval_minutes: syncIntervalMinutes,
sync_folder_requests: syncFolderRequests,
} : vault),
};
}
@@ -537,47 +544,37 @@
}
}
async function handleSyncNow() {
// The outcome of the last sync, whether it was started here, from the title bar or automatically.
$effect(() => {
const state = $syncState;
const vault = maintenanceVault;
if (!vault || syncRunning) return;
syncRunning = true;
syncMessage = null;
const unlisteners: Array<() => void> = [];
const cleanup = () => { unlisteners.forEach((u) => u()); };
unlisteners.push(await listen<{ vault_path: string; success: boolean; summary?: { uploaded?: number; downloaded?: number; deleted_local?: number; deleted_remote?: number; conflicts?: number }; last_sync_time?: string }>('sync-done', (event) => {
if (event.payload.vault_path !== vault) return;
if (!$showSettings || maintenanceVault !== vault) { cleanup(); return; }
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;
const timestamp = event.payload.last_sync_time;
const currentVault = activeVaultConfig($appConfig);
if (timestamp && currentVault && $appConfig) {
$appConfig = { ...$appConfig, vaults: $appConfig.vaults.map(item =>
item === currentVault ? { ...item, last_sync_time: timestamp } : item) };
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<{ vault_path: string; error?: string }>('sync-error', (event) => {
if (event.payload.vault_path !== vault) return;
if (!$showSettings || maintenanceVault !== vault) { cleanup(); return; }
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;
}
}
@@ -621,6 +618,16 @@
{ 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.
@@ -672,22 +679,13 @@
];
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 },
@@ -701,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);
@@ -813,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) {
@@ -1146,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);
@@ -1499,7 +1489,9 @@
<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={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>
Manage Vaults
</button>
@@ -2060,7 +2052,7 @@
{/if}
</div>
{#if !isMobile}
{#if !isMobile || isAndroid}
<div class="settings-section">
<h3>Interface Scale</h3>
<div class="font-size-options">
@@ -2074,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}
@@ -2097,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
@@ -2110,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">
@@ -2226,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}>
@@ -2253,6 +2249,9 @@
<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>
@@ -2613,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>
@@ -3862,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;
}
@@ -3872,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;
}
@@ -3880,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;
+147 -13
View File
@@ -38,11 +38,14 @@
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 = () => {}, onBeforeNoteChange = async () => true, onBeforePathMutation = async () => null, onPathsMoved = async (_old: string, _next: string) => {} }: {
onViewChanged?: () => void;
@@ -134,6 +137,13 @@
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);
@@ -633,6 +643,8 @@
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;
@@ -647,22 +659,30 @@
notebookIcons.set(icons);
}
async function handleBuiltinIcon(nb: NotebookEntry, icon: NotebookIconId) {
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 = encodeBuiltinNotebookIcon(icon);
const value = icon || iconPickerColor ? encodeBuiltinNotebookIcon(icon, iconPickerColor) : null;
iconError = '';
try {
await notebookAppearance.run(ownerVault, key, latest,
() => setNotebookIcon(ownerVault, key, value),
() => publishNotebookIcon(key, value));
if (ownerIsCurrent() && latest()) iconPickerNotebook = null;
if (close && ownerIsCurrent() && latest()) iconPickerNotebook = null;
} catch (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);
@@ -1066,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)}
@@ -1078,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!)}>
@@ -1090,7 +1144,7 @@
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>
@@ -1172,7 +1226,7 @@
{@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
@@ -1263,18 +1317,18 @@
{:else}
<span class="chevron-spacer"></span>
{/if}
<span class="notebook-icon-slot" class:notebook-builtin-icon={!!builtinIcon}>
{#if builtinIcon}
<NotebookGlyph icon={builtinIcon} size={18} />
<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" 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"/>
@@ -1928,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;
@@ -1987,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;
+31 -1
View File
@@ -12,6 +12,9 @@
import TagLabel from './TagLabel.svelte';
import {
NOTEBOOK_ICON_OPTIONS,
COMMON_NOTEBOOK_ICON_COUNT,
decodeBuiltinNotebookIcon,
isCommonNotebookIcon,
encodeBuiltinNotebookIcon,
type NotebookIconId
} from '$lib/utils/notebook-icons';
@@ -41,6 +44,9 @@
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));
@@ -154,7 +160,7 @@
</header>
{#if error}<div class="picker-error" role="alert">{error}</div>{/if}
<div class="icon-picker-grid">
{#each NOTEBOOK_ICON_OPTIONS as option (option.id)}
{#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"
@@ -167,6 +173,9 @@
<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>
@@ -344,6 +353,22 @@
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;
@@ -458,6 +483,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;
}
+3 -1
View File
@@ -98,7 +98,9 @@
<div class="titlebar-actions">
<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">
@@ -1,4 +1,5 @@
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';
@@ -35,9 +36,11 @@ export function createCodeBlockHighlightPlugin({
const cached = cache.get(node);
if (cached) return cached;
const language = node.attrs.language || defaultLanguage;
const tree = language && lowlight.registered(language)
? lowlight.highlight(language, node.textContent)
: lowlight.highlightAuto(node.textContent);
// 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) {
@@ -120,6 +123,9 @@ export const CachedCodeBlockLowlight = CodeBlock.extend<CodeBlockOptions & { low
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.
@@ -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;
};
}
+23 -8
View File
@@ -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;
},
+184 -9
View File
@@ -182,6 +182,32 @@ function markdownMark(mark: Mark, text: string): MarkdownMark | null {
}
}
const escapeAttribute = (value: string) => value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
/**
* 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 `![${alt}${sizeSuffix}](${source}${serializeImageTitle(node.attrs.title)})`;
}
function marksForText(node: ProseMirrorNode, linksOnly = false): MarkdownMark[] {
return node.marks
.filter((mark) => !linksOnly || mark.type.name === 'link' || mark.type.name === 'wikiLink')
@@ -200,6 +226,8 @@ function commonMarkCount(active: MarkdownMark[], next: MarkdownMark[]): number {
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(
@@ -271,6 +299,7 @@ export function serializeInlineMarkdown(
transitionMarks(marks);
result += serializeCodeSpan(text);
} else {
if (options.literalText) text = options.literalText(text, index);
if (index === 0) {
text = text.replace(/^[\t\u2003]+/, (whitespace) => '&emsp;'.repeat(whitespace.length));
}
@@ -296,16 +325,18 @@ export function serializeInlineMarkdown(
continue;
}
transitionMarks([]);
if (child.type.name === 'image') {
const source = normalizeAssetSource(child.attrs.src || '');
if (!source) continue;
const alt = child.attrs.alt || '';
const size = child.attrs['data-size'] || child.attrs.size || 'full';
const sizeSuffix = size && size !== 'full' ? `|size=${size}` : '';
if (result) result += '\n';
result += `![${alt}${sizeSuffix}](${source}${serializeImageTitle(child.attrs.title)})`;
} else if (child.type.name === 'mathInline') {
// An image can sit inside a link (`[![logo](logo.png)](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'
@@ -320,6 +351,148 @@ export function serializeInlineMarkdown(
return result;
}
// ---- Keeping plain text plain
// Text in the editor is literal: `*not italic*`, `<b>` or `&amp;` 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;
@@ -329,10 +502,12 @@ export function serializeInlineMarkdownKeepingDollars(
node: ProseMirrorNode,
normalizeAssetSource: AssetSourceNormalizer,
inlineMathPayloads: (markdown: string) => string[],
plainText?: InlinePlainText,
): string {
const escaped = serializeInlineMarkdown(node, normalizeAssetSource);
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 });
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);
+66 -7
View File
@@ -10,8 +10,9 @@ import { IMG_GRID_CLOSER, parseImgGridHeader, splitTrailingCloser } from './imag
interface WikiTitle { path: string; title: string }
export interface MarkdownEnvironment { wikiLinkTitles?: readonly WikiTitle[] }
const wikiIndexKey = Symbol('wiki-index');
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];
@@ -98,7 +99,7 @@ function wikiLink(state: StateInline, silent: boolean): boolean {
const raw = state.src.slice(state.pos + 2, end);
if (!raw || raw.includes(']')) return false;
if (!silent) {
let index: WikiIndex | undefined = state.env[wikiIndexKey];
let index = wikiIndexes.get(notes);
if (!index) {
index = { paths: new Map(), titles: new Map() };
for (const note of notes) {
@@ -109,7 +110,7 @@ function wikiLink(state: StateInline, silent: boolean): boolean {
const previous = index.titles.get(title);
if (!previous || depth < previous.depth) index.titles.set(title, { path: note.path, depth });
}
state.env[wikiIndexKey] = index;
wikiIndexes.set(notes, index);
}
const pipe = raw.indexOf('|');
const reference = (pipe < 0 ? raw : raw.slice(0, pipe)).trim();
@@ -275,14 +276,28 @@ function legacyLink(state: StateInline, silent: boolean): boolean {
return true;
}
function emptyParagraph(state: StateBlock, startLine: number, _endLine: number, silent: boolean): boolean {
const EMPTY_PARAGRAPH_MARKER = '<!-- -->';
function emptyParagraph(state: StateBlock, startLine: number, endLine: number, silent: boolean): boolean {
const from = state.bMarks[startLine] + state.tShift[startLine];
if (state.src.slice(from, state.eMarks[startLine]).trim() !== '<!-- -->') return false;
const line = state.src.slice(from, state.eMarks[startLine]);
// Versions before 1.3.7 glued the marker to a following image (`<!-- -->![](a.png)`), 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];
state.line = 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;
}
@@ -340,6 +355,49 @@ function imageGrid(state: StateBlock, startLine: number, endLine: number, silent
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('&lt;')
? `<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);
@@ -354,7 +412,8 @@ export function createEditorMarkdownParser(): MarkdownIt {
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.before('block', 'helix_wiki_index', state => { delete state.env[wikiIndexKey]; });
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 }[] = [];
+233
View File
@@ -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);
}
+12
View File
@@ -64,6 +64,18 @@ export function findDocumentMatches(doc: ProseMirrorNode, query: string, options
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;
+27
View File
@@ -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;
},
});
+4 -2
View File
@@ -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: "[",
+7
View File
@@ -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 {
+22 -3
View File
@@ -117,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
@@ -264,6 +278,9 @@ export function activateVaultData(vaultPath: string | null): void {
}
// 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]) => {
@@ -277,9 +294,11 @@ export const sortedNotes = derived(
const dateField = $sortMode === "title" || ($sortMode === "custom" && customSortable)
? null
: $sortMode === "created" ? "created" : "modified";
const timestamps = dateField ? new Map<NoteEntry, number>() : null;
const timestamps = dateField ? noteTimestamps[dateField] : null;
if (dateField && timestamps) {
for (const note of $notes) timestamps.set(note, Date.parse(note.meta[dateField]));
for (const note of $notes) {
if (!timestamps.has(note)) timestamps.set(note, Date.parse(note.meta[dateField]));
}
}
const sortFn = (a: NoteEntry, b: NoteEntry) => {
+3
View File
@@ -63,6 +63,7 @@ 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;
}
@@ -251,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 {
+72
View File
@@ -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);
}
}
+35
View File
@@ -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}>`;
},
);
}
+26
View File
@@ -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)', '![](img.png)',
'[[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);
});
+21
View File
@@ -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);
}
+3 -2
View File
@@ -1,6 +1,6 @@
import type { FileEvent, NoteEntry } from '../types';
const normalize = (path: string) => path.replace(/\\/g, '/');
const normalize = (path: string) => path.includes('\\') ? path.replace(/\\/g, '/') : path;
/** A delayed watcher/sync batch must not update a different (even nested) vault. */
export function isCurrentVaultEvent(event: FileEvent, vaultPath: string | null): boolean {
@@ -27,7 +27,8 @@ function belongsToList(note: NoteEntry, key: string, quickAccess: string[]): boo
/** Patch one note without rescanning the vault, including changes to tag membership. */
export function updateNoteList(list: NoteEntry[], note: NoteEntry, key: string, quickAccess: string[]): NoteEntry[] {
if (key === 'trash') return list;
const index = list.findIndex((entry) => normalize(entry.path) === normalize(note.path));
const notePath = normalize(note.path);
const index = list.findIndex((entry) => normalize(entry.path) === notePath);
if (!belongsToList(note, key, quickAccess)) {
return index < 0 ? list : list.filter((_, i) => i !== index);
}
+45
View File
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const { decodeBuiltinNotebookIcon, decodeNotebookIcon, encodeBuiltinNotebookIcon } = await import(
new URL('./notebook-icons.ts', import.meta.url)
);
test('encodes a builtin notebook icon with an optional color', () => {
assert.equal(encodeBuiltinNotebookIcon('star'), 'builtin:star');
assert.equal(encodeBuiltinNotebookIcon('star', null), 'builtin:star');
assert.equal(encodeBuiltinNotebookIcon('star', '#E11D48'), 'builtin:star#e11d48');
assert.equal(encodeBuiltinNotebookIcon('star', 'red'), 'builtin:star');
});
test('decodes notebook icons with and without a color', () => {
assert.deepEqual(decodeNotebookIcon('builtin:star'), { icon: 'star', color: null });
assert.deepEqual(decodeNotebookIcon('builtin:star#e11d48'), { icon: 'star', color: '#e11d48' });
assert.deepEqual(decodeNotebookIcon('builtin:star#nope'), { icon: 'star', color: null });
});
test('colors the default notebook glyph without an icon', () => {
assert.equal(encodeBuiltinNotebookIcon(null, '#E11D48'), 'builtin:#e11d48');
assert.deepEqual(decodeNotebookIcon('builtin:#e11d48'), { icon: null, color: '#e11d48' });
assert.equal(decodeNotebookIcon('builtin:'), null);
assert.equal(decodeNotebookIcon('builtin:#nope'), null);
});
test('ignores custom images and unknown builtin icons', () => {
assert.equal(decodeNotebookIcon(null), null);
assert.equal(decodeNotebookIcon('.helixnotes/attachments/icon#1.png'), null);
assert.equal(decodeNotebookIcon('builtin:unknown#e11d48'), null);
});
test('tag icons stay uncolored builtin ids', () => {
assert.equal(decodeBuiltinNotebookIcon('builtin:star'), 'star');
assert.equal(decodeBuiltinNotebookIcon('builtin:star#e11d48'), null);
});
test('only the first icons are common', async () => {
const { isCommonNotebookIcon } = await import(new URL('./notebook-icons.ts', import.meta.url));
assert.equal(isCommonNotebookIcon(null), true);
assert.equal(isCommonNotebookIcon('code'), true);
assert.equal(isCommonNotebookIcon('flask'), false);
assert.equal(isCommonNotebookIcon('pen'), false);
});
+86 -4
View File
@@ -1,3 +1,5 @@
import { isValidTagColor } from './tag-styles.ts';
export const NOTEBOOK_ICON_OPTIONS = [
{ id: 'book', label: 'Book' },
{ id: 'folder', label: 'Folder' },
@@ -14,11 +16,47 @@ export const NOTEBOOK_ICON_OPTIONS = [
{ id: 'archive', label: 'Archive' },
{ id: 'globe', label: 'Globe' },
{ id: 'plane', label: 'Travel' },
{ id: 'palette', label: 'Creative' }
{ id: 'palette', label: 'Creative' },
{ id: 'music', label: 'Music' },
{ id: 'camera', label: 'Photos' },
{ id: 'film', label: 'Film' },
{ id: 'gamepad', label: 'Games' },
{ id: 'cart', label: 'Shopping' },
{ id: 'money', label: 'Finance' },
{ id: 'health', label: 'Health' },
{ id: 'food', label: 'Food' },
{ id: 'coffee', label: 'Coffee' },
{ id: 'leaf', label: 'Nature' },
{ id: 'users', label: 'People' },
{ id: 'chat', label: 'Chat' },
{ id: 'mail', label: 'Mail' },
{ id: 'lock', label: 'Private' },
{ id: 'wrench', label: 'Tools' },
{ id: 'pen', label: 'Writing' },
{ id: 'tag', label: 'Tag' },
{ id: 'clock', label: 'Clock' },
{ id: 'bell', label: 'Reminders' },
{ id: 'pin', label: 'Location' },
{ id: 'gift', label: 'Gifts' },
{ id: 'trophy', label: 'Goals' },
{ id: 'rocket', label: 'Projects' },
{ id: 'flag', label: 'Flag' },
{ id: 'shield', label: 'Security' },
{ id: 'gear', label: 'Settings' },
{ id: 'search', label: 'Search' },
{ id: 'zap', label: 'Energy' }
] as const;
export type NotebookIconId = (typeof NOTEBOOK_ICON_OPTIONS)[number]['id'];
/** The pickers show this many icons until "More icons" is pressed. */
export const COMMON_NOTEBOOK_ICON_COUNT = 8;
export function isCommonNotebookIcon(icon: NotebookIconId | null | undefined): boolean {
if (!icon) return true;
return NOTEBOOK_ICON_OPTIONS.findIndex((option) => option.id === icon) < COMMON_NOTEBOOK_ICON_COUNT;
}
const BUILTIN_PREFIX = 'builtin:';
const BUILTIN_IDS: Record<NotebookIconId, true> = {
book: true,
@@ -36,15 +74,43 @@ const BUILTIN_IDS: Record<NotebookIconId, true> = {
archive: true,
globe: true,
plane: true,
palette: true
palette: true,
music: true,
camera: true,
film: true,
gamepad: true,
cart: true,
money: true,
health: true,
food: true,
coffee: true,
leaf: true,
users: true,
chat: true,
mail: true,
lock: true,
wrench: true,
pen: true,
tag: true,
clock: true,
bell: true,
pin: true,
gift: true,
trophy: true,
rocket: true,
flag: true,
shield: true,
gear: true,
search: true,
zap: true
};
export function normalizeNotebookIconKey(path: string): string {
return path.replace(/\\/g, '/');
}
export function encodeBuiltinNotebookIcon(icon: NotebookIconId): string {
return `${BUILTIN_PREFIX}${icon}`;
export function encodeBuiltinNotebookIcon(icon: NotebookIconId | null, color?: string | null): string {
return `${BUILTIN_PREFIX}${icon ?? ''}${isValidTagColor(color) ? color.toLowerCase() : ''}`;
}
export function decodeBuiltinNotebookIcon(value: string | null | undefined): NotebookIconId | null {
@@ -52,3 +118,19 @@ export function decodeBuiltinNotebookIcon(value: string | null | undefined): Not
const icon = value.slice(BUILTIN_PREFIX.length);
return Object.hasOwn(BUILTIN_IDS, icon) ? icon as NotebookIconId : null;
}
/**
* Notebook icons keep their color in the stored value: `builtin:star#e11d48`.
* `builtin:#e11d48` colors the default notebook glyph.
*/
export function decodeNotebookIcon(
value: string | null | undefined
): { icon: NotebookIconId | null; color: string | null } | null {
if (!value?.startsWith(BUILTIN_PREFIX)) return null;
const hash = value.indexOf('#');
const icon = decodeBuiltinNotebookIcon(hash < 0 ? value : value.slice(0, hash));
const color = hash < 0 ? null : value.slice(hash);
const valid = isValidTagColor(color) ? color : null;
if (!icon && (!valid || hash !== BUILTIN_PREFIX.length)) return null;
return { icon, color: valid };
}
-48
View File
@@ -1,48 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { isNetworkPath, networkPathWithin, resolveFileReference, resolveVaultFilePath } from './paths.ts';
test('network paths are recognized by their text', () => {
for (const path of ['\\\\host\\share\\r.pdf', '//host/share/r.pdf', '\\\\?\\UNC\\host\\share', '//?/unc/host/share']) {
assert.equal(isNetworkPath(path), true, path);
}
for (const path of ['C:\\Users\\me\\note.md', 'C:/Users/me/note.md', '\\\\?\\C:\\Users\\me', '/home/me/note.md', 'relative/note.md', '']) {
assert.equal(isNetworkPath(path), false, path);
}
});
test('a network path counts as inside a folder only by its own text', () => {
const roots = ['\\\\nas\\notes\\Vault', 'C:/Users/me/Vault', null];
assert.equal(networkPathWithin('//NAS/notes/vault/sub/a.png', roots), true);
assert.equal(networkPathWithin('\\\\?\\UNC\\nas\\notes\\Vault\\a.png', roots), true);
assert.equal(networkPathWithin('//nas/notes/Vault2/a.png', roots), false);
assert.equal(networkPathWithin('//nas/notes/Vault/../../other/a.png', roots), false);
assert.equal(networkPathWithin('//evil/share/a.png', roots), false);
});
test('on Windows a reference to a network path outside the vault resolves to no file', () => {
const vault = 'C:/Users/me/Vault';
const note = 'C:/Users/me/Vault/Folder/note.md';
for (const target of ['//evil/share/r.pdf', '\\\\evil\\share\\r.pdf', '//evil/share/image.png', '%2F%2Fevil/share/x.png']) {
assert.equal(resolveFileReference(target, note, vault, true).path, '', target);
}
// Ordinary references are untouched.
assert.equal(resolveVaultFilePath('image.png', note, vault, true), 'C:/Users/me/Vault/Folder/image.png');
assert.equal(resolveVaultFilePath('.helixnotes/attachments/a.png', note, vault, true), 'C:/Users/me/Vault/.helixnotes/attachments/a.png');
assert.equal(resolveVaultFilePath('C:/Users/me/Pictures/a.png', note, vault, true), 'C:/Users/me/Pictures/a.png');
});
test('a vault or an opened note on a network share keeps working on Windows', () => {
const vault = '\\\\nas\\notes\\Vault';
const note = '\\\\nas\\notes\\Vault\\Folder\\note.md';
assert.equal(resolveVaultFilePath('image.png', note, vault, true), '//nas/notes/Vault/Folder/image.png');
assert.equal(resolveVaultFilePath('//nas/notes/Vault/other.png', note, vault, true), '//nas/notes/Vault/other.png');
assert.equal(resolveVaultFilePath('//nas/notes/Elsewhere/x.png', note, vault, true), '');
// A note opened from outside any vault: its own folder is allowed.
assert.equal(resolveVaultFilePath('pic.png', '\\\\files\\home\\me\\note.md', null, true), '//files/home/me/pic.png');
assert.equal(resolveVaultFilePath('//other/share/pic.png', '\\\\files\\home\\me\\note.md', null, true), '');
});
test('elsewhere a path starting with two slashes stays an ordinary local path', () => {
assert.equal(resolveVaultFilePath('//home/me/pic.png', '/home/me/Vault/note.md', '/home/me/Vault', false), '//home/me/pic.png');
});
+2 -39
View File
@@ -52,41 +52,13 @@ export function noteAssetRoot(notePath: string | null, activeVault: string | nul
return [...vaults].filter(root => isPathInDirectory(notePath, root)).sort((a, b) => b.length - a.length)[0] ?? null;
}
/**
* Whether Windows would resolve this path over the network: `\\host\share`, `//host/share` or the
* verbatim `\\?\UNC\host`. Merely loading or examining such a path makes Windows contact the host
* and offer it the user's login, so a path from note content is judged by its text first.
*/
export function isNetworkPath(path: string): boolean {
const normalized = path.replace(/\\/g, '/');
const verbatim = /^\/\/[?.]\/(.*)$/.exec(normalized);
return verbatim ? /^unc\//i.test(verbatim[1]) : normalized.startsWith('//');
}
function networkPathKey(path: string): string {
return path.replace(/\\/g, '/').replace(/^\/\/[?.]\/unc\//i, '//').replace(/\/+$/, '').toLowerCase();
}
/** Whether a network path lies, by its text alone, inside one of the given folders. */
export function networkPathWithin(path: string, roots: readonly (string | null | undefined)[]): boolean {
const key = networkPathKey(path);
if (key.split('/').includes('..')) return false;
return roots.some((root) => {
if (!root || !isNetworkPath(root)) return false;
const rootKey = networkPathKey(root);
return key === rootKey || key.startsWith(rootKey + '/');
});
}
const windowsHost = typeof navigator !== 'undefined' && /windows nt/i.test(navigator.userAgent);
/** Decode only the URI path, keeping query/fragment data out of filesystem paths. */
export function resolveFileReference(source: string, notePath: string | null, vaultRoot: string | null, windows = windowsHost): { path: string; suffix: string } {
export function resolveFileReference(source: string, notePath: string | null, vaultRoot: string | null): { path: string; suffix: string } {
const boundary = source.search(/[?#]/);
const encoded = boundary < 0 ? source : source.slice(0, boundary);
let path: string;
try { path = decodeURIComponent(encoded); } catch { path = encoded; }
return { path: resolveVaultFilePath(path, notePath, vaultRoot, windows), suffix: boundary < 0 ? '' : source.slice(boundary) };
return { path: resolveVaultFilePath(path, notePath, vaultRoot), suffix: boundary < 0 ? '' : source.slice(boundary) };
}
/** Percent-encode each path segment for a Markdown destination; a Windows drive prefix stays literal. */
@@ -97,21 +69,12 @@ export function encodeMarkdownPath(path: string): string {
.replace(/[!'()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)).join('/');
}
/**
* The local file a reference in a note points at. On Windows a network path outside the vault and
* the note's own folder resolves to '' (no file), so nothing downstream touches it.
*/
export function resolveVaultFilePath(
targetPath: string,
notePath: string | null,
vaultRoot: string | null,
windows = windowsHost,
): string {
const target = normalizeLocalAssetPath(targetPath);
if (windows && isNetworkPath(target)) {
const noteFolder = notePath ? notePath.replace(/\\/g, '/').replace(/\/[^/]*$/, '') : null;
if (!networkPathWithin(target, [vaultRoot, noteFolder])) return '';
}
if (target.startsWith('/') || /^[A-Za-z]:\//.test(target)) return target;
const root = vaultRoot?.replace(/\\/g, '/').replace(/\/$/, '') ?? '';
+22
View File
@@ -0,0 +1,22 @@
import assert from 'node:assert/strict';
import test from 'node:test';
const { countWords, markdownCountText } = await import(new URL('./word-count.ts', import.meta.url));
test('counts words, not punctuation or table borders', () => {
assert.equal(countWords(''), 0);
assert.equal(countWords(' one two\nthree '), 3);
assert.equal(countWords('| a | b |'), 2);
assert.equal(countWords('- > --- |'), 0);
assert.equal(countWords("it's e-mail, 2026 café"), 4);
});
test('a table counts its cell words in source mode', () => {
const md = '| Name | Role |\n| --- | :---: |\n| Ada Lovelace | First programmer |\n';
assert.equal(countWords(markdownCountText(md)), 6);
});
test('Markdown syntax does not count as words', () => {
const md = '---\ntitle: X\n---\n# Title here\n\n- [ ] task one\n- [x] done\n1. first\n - nested **bold** item\n> quoted text\n\n[[Note|shown name]] [link](https://x.com) ![img](a.png) `code`\n';
assert.equal(countWords(markdownCountText(md)), 15);
});
+23
View File
@@ -0,0 +1,23 @@
/** Words are runs of non-space text with at least one letter or digit, so `|`, `-` or `>` don't count. */
export function countWords(text: string): number {
let count = 0;
for (const token of text.split(/\s+/)) {
if (/[\p{L}\p{N}]/u.test(token)) count++;
}
return count;
}
/** The readable text of a Markdown note, for counting words and characters in source mode. */
export function markdownCountText(markdown: string): string {
return markdown
.replace(/^---\n[\s\S]*?\n---\n?/, '')
// Table delimiter rows (`| --- | :---: |`) are layout, not words.
.replace(/^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*$/gm, '')
.replace(/!\[[^\]]*\]\([^)]*\)/g, '')
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
.replace(/\[\[([^\]|]*\|)?([^\]]*)\]\]/g, '$2')
.replace(/^[ \t]*#{1,6}[ \t]+/gm, '')
.replace(/^[ \t]*(?:>[ \t]*)+/gm, '')
.replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+(?:\[[ xX]\][ \t]+)?/gm, '')
.replace(/[*_~`|]+/g, ' ');
}
+1 -7
View File
@@ -55,7 +55,7 @@
}
function applyTheme(t: string, themes: CustomTheme[] = []) {
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');
@@ -93,12 +93,6 @@
const note = get(activeNotePath);
const root = noteAssetRoot(note, config?.active_vault ?? null, config?.vaults.map(vault => vault.path) ?? []);
const absPath = resolveFileReference(href, note, root).path;
if (!absPath) {
// A network path outside the vault is not opened as a file (Windows). Written as
// `//host/page` it is a web address without its scheme.
if (/^\/\/[^/\\?.]/.test(href)) openUrl('https:' + href).catch((err) => console.error('Failed to open URL:', err));
return;
}
// Internal .md note link - navigate within the app
if (absPath.endsWith('.md')) {
window.dispatchEvent(new CustomEvent('helixnotes-open-note', { detail: absPath }));
+5 -10
View File
@@ -4,7 +4,7 @@
import { getAppConfig, openVault, restoreExternalVault, setFontSize } from '$lib/api';
import { darkThemes, isIOS, isMobile } from '$lib/platform';
import { getWheelFontSizeAction } from '$lib/utils/editor-zoom';
import { getCurrentWebview } from '@tauri-apps/api/webview';
import { applyUiScale, defaultUiScale } from '$lib/ui-scale';
import { listen } from '@tauri-apps/api/event';
import { getCurrentWindow } from '@tauri-apps/api/window';
import VaultPicker from '$lib/components/VaultPicker.svelte';
@@ -188,7 +188,7 @@
? (prefersDark ? config.system_dark_theme || 'dark' : config.system_light_theme || 'light')
: rawTheme;
const root = document.documentElement;
const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark'];
const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark', 'matrix', 'amber-crt', 'sepia', 'deep-ocean', 'sandstone', 'lavender', 'graphite', 'nebula', 'wine', 'jade'];
root.classList.remove('dark');
root.removeAttribute('data-theme');
if (namedThemes.includes(themeValue)) {
@@ -259,14 +259,9 @@
}
}
// Apply saved interface scale to every desktop window; no-ops gracefully elsewhere.
if (config.ui_scale && config.ui_scale !== 1) {
try {
await getCurrentWebview().setZoom(config.ui_scale);
} catch (e) {
console.error('Failed to apply interface scale:', e);
}
}
// Apply saved interface scale (or the platform default) to desktop windows and Android.
const uiScale = config.ui_scale ?? defaultUiScale;
if (uiScale !== 1) await applyUiScale(uiScale);
await revealStartupWindow();
removeEditorZoomShortcuts = installEditorZoomShortcuts();
+39
View File
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applySingleLineSpacing } from '../src/lib/utils/clipboard-copy.ts';
const STYLE = 'line-height:100%;margin:0';
test('paragraphs, headings, list items and quotes are copied with single spacing', () => {
assert.equal(
applySingleLineSpacing('<p>One</p><p>Two</p>'),
`<p style="${STYLE}">One</p><p style="${STYLE}">Two</p>`
);
assert.equal(
applySingleLineSpacing('<h1>Title</h1><ul><li>Item</li></ul><blockquote><p>Quote</p></blockquote>'),
`<h1 style="${STYLE}">Title</h1><ul><li style="${STYLE}">Item</li></ul><blockquote style="line-height:100%"><p style="${STYLE}">Quote</p></blockquote>`
);
});
test('existing inline styles are kept and the copy style wins', () => {
assert.equal(
applySingleLineSpacing('<p style="text-align: center; line-height: 1.5">Centered</p>'),
`<p style="text-align: center; line-height: 1.5;${STYLE}">Centered</p>`
);
assert.equal(
applySingleLineSpacing("<p class='lead' style='margin-bottom: 8px'>Lead</p>"),
`<p class='lead' style='margin-bottom: 8px;${STYLE}'>Lead</p>`
);
assert.equal(
applySingleLineSpacing('<p style="">Empty</p>'),
`<p style="${STYLE}">Empty</p>`
);
});
test('non-block markup is untouched', () => {
const html = '<pre><code>&lt;p&gt;not a block&lt;/p&gt;</code></pre><p><strong>bold</strong> <a href="https://example.com">link</a></p><table><tr><td>cell</td></tr></table><path d="M0 0"/>';
assert.equal(
applySingleLineSpacing(html),
`<pre><code>&lt;p&gt;not a block&lt;/p&gt;</code></pre><p style="${STYLE}"><strong>bold</strong> <a href="https://example.com">link</a></p><table><tr><td>cell</td></tr></table><path d="M0 0"/>`
);
});
+6
View File
@@ -148,3 +148,9 @@ test('cache ownership respects highlighter/default-language boundaries and empty
assert.deepEqual(fixture.calls, [{ language: 'javascript', text: 'const x = 1;' }]);
assert.deepEqual(keywordRanges(fixture.plugin, state), expectedKeywords(state.doc));
});
test('a named language without a grammar is left plain instead of guessed', () => {
const { plugin, state, calls } = setup([codeBlock('graph TD; A-->B;', 'mermaid'), codeBlock('const a = 1;', null)], null);
assert.deepEqual(calls, [{ language: 'auto', text: 'const a = 1;' }]);
assert.equal(plugin.getState(state).decorations.find(0, 'graph TD; A-->B;'.length + 2).length, 0);
});
+230
View File
@@ -0,0 +1,230 @@
[
{
"name": "title links, aliases and links to other notes",
"rename": {
"old_ref": "Home",
"new_ref": "Start",
"old_title": "Home",
"new_title": "Start",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "See [[Home]], [[Home|the start page]] and [[Home|Home]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n",
"expected": "See [[Start]], [[Start|the start page]] and [[Start|Start]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n"
},
{
"name": "headings, blocks, other capitals, the .md extension and embeds",
"rename": {
"old_ref": "Home",
"new_ref": "Start",
"old_title": "Home",
"new_title": "Start",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "[[Home#Section]] [[Home^abc123]] [[Home#Section|Home]] [[home]] [[HOME|x]] [[Home.md]] [[Home.md#Part]] ![[Home]] ![[Home#Part|300]] [[Homepage]] [[Home Office]]\n",
"expected": "[[Start#Section]] [[Start^abc123]] [[Start#Section|Start]] [[Start]] [[Start|x]] [[Start.md]] [[Start.md#Part]] ![[Start]] ![[Start#Part|300]] [[Homepage]] [[Home Office]]\n"
},
{
"name": "aliased links in a table cell",
"rename": {
"old_ref": "Home",
"new_ref": "Start",
"old_title": "Home",
"new_title": "Start",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "| [[Home\\|Home]] | [[Home\\|start]] and [[Index\\|Home]] | [[Home#A\\|Home]] |\n",
"expected": "| [[Start\\|Start]] | [[Start\\|start]] and [[Index\\|Home]] | [[Start#A\\|Start]] |\n"
},
{
"name": "links in code stay as written",
"rename": {
"old_ref": "Home",
"new_ref": "Start",
"old_title": "Home",
"new_title": "Start",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "Inline `[[Home]]` and ``a ` [[Home]]`` but [[Home]].\n```\n[[Home]] [x](Home.md)\n```\n~~~~md\n[[Home]]\n~~~\n~~~~\nAfter [[Home]] and `unclosed [[Home]]\n",
"expected": "Inline `[[Home]]` and ``a ` [[Home]]`` but [[Start]].\n```\n[[Home]] [x](Home.md)\n```\n~~~~md\n[[Home]]\n~~~\n~~~~\nAfter [[Start]] and `unclosed [[Start]]\n"
},
{
"name": "Markdown links in the same folder",
"rename": {
"old_ref": "Home",
"new_ref": "Start",
"old_title": "Home",
"new_title": "Start",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "[Home](Home.md) [x](Home.md#Part \"title\") [x](./Home.md) [x](<Home.md>) [x](home.md) ![x](Home.md)\nUntouched: [x](https://example.com/Home.md) [x](Other.md) [x](Home) [x](#Home) [Home](Index.md)\n",
"expected": "[Start](Start.md) [x](Start.md#Part \"title\") [x](./Start.md) [x](<Start.md>) [x](Start.md) ![x](Start.md)\nUntouched: [x](https://example.com/Home.md) [x](Other.md) [x](Home) [x](#Home) [Home](Index.md)\n"
},
{
"name": "a note in a folder, linked from that folder",
"rename": {
"old_ref": "Work/Old Plan",
"new_ref": "Work/New Plan",
"old_title": "Old Plan",
"new_title": "New Plan",
"title_rules": true,
"file_rules": true
},
"note_dir": "Work",
"input": "[a](Old%20Plan.md) [a](<Old Plan.md>) [[Old Plan]] [[Work/Old Plan#Goals|g]] [[Work\\Old Plan]]\n",
"expected": "[a](New%20Plan.md) [a](<New Plan.md>) [[New Plan]] [[Work/New Plan#Goals|g]] [[Work/New Plan]]\n"
},
{
"name": "a note in a folder, linked from another folder",
"rename": {
"old_ref": "Work/Old Plan",
"new_ref": "Work/New Plan",
"old_title": "Old Plan",
"new_title": "New Plan",
"title_rules": true,
"file_rules": true
},
"note_dir": "Other/Deep",
"input": "[a](../../Work/Old%20Plan.md#Goals) [a](Work/Old%20Plan.md) [a](/Work/Old%20Plan.md) [a](Old%20Plan.md) [a](Elsewhere/Old%20Plan.md) [a](../Old%20Plan.md)\n",
"expected": "[a](../../Work/New%20Plan.md#Goals) [a](Work/New%20Plan.md) [a](/Work/New%20Plan.md) [a](New%20Plan.md) [a](Elsewhere/Old%20Plan.md) [a](../Old%20Plan.md)\n"
},
{
"name": "another note has the same name: only path links follow",
"rename": {
"old_ref": "Work/Old Plan",
"new_ref": "Work/New Plan",
"old_title": "Old Plan",
"new_title": "New Plan",
"title_rules": false,
"file_rules": false
},
"note_dir": "Other",
"input": "[[Old Plan]] [[Old Plan|x]] [[Work/Old Plan|Old Plan]] [a](Old%20Plan.md) [a](../Work/Old%20Plan.md)\n",
"expected": "[[Old Plan]] [[Old Plan|x]] [[Work/New Plan|New Plan]] [a](Old%20Plan.md) [a](../Work/New%20Plan.md)\n"
},
{
"name": "new names with characters a link destination has to encode",
"rename": {
"old_ref": "Plan",
"new_ref": "Plan (v2) #1",
"old_title": "Plan",
"new_title": "Plan (v2) #1",
"title_rules": true,
"file_rules": true
},
"note_dir": "",
"input": "[a](Plan.md) [a](<Plan.md>) [[Plan]]\n",
"expected": "[a](Plan%20%28v2%29%20%231.md) [a](<Plan (v2) #1.md>) [[Plan (v2) #1]]\n"
},
{
"name": "a note at the top of the vault whose name another note shares",
"rename": {
"old_ref": "Plan B",
"new_ref": "Plan C",
"old_title": "Plan B",
"new_title": "Plan C",
"title_rules": false,
"file_rules": false
},
"note_dir": "Other",
"input": "[[Plan B]] [[Plan B|x]] [[Plan B#Part]] [a](Plan%20B.md) [b](../Plan%20B.md)\n",
"expected": "[[Plan B]] [[Plan B|x]] [[Plan B#Part]] [a](Plan%20B.md) [b](../Plan%20C.md)\n"
},
{
"name": "a note moved to another folder, linked from its old folder",
"renames": [
{
"old_ref": "Work/Plan",
"new_ref": "Archive/Plan",
"old_title": "Plan",
"new_title": "Plan",
"title_rules": false,
"file_rules": true
}
],
"note_dir": "Work",
"input": "[p](Plan.md) [[Work/Plan]] [[Plan]] [q](./Plan.md#Goals)\n",
"expected": "[p](../Archive/Plan.md) [[Archive/Plan]] [[Plan]] [q](../Archive/Plan.md#Goals)\n"
},
{
"name": "a note moved to another folder, linked from elsewhere",
"renames": [
{
"old_ref": "Work/Plan",
"new_ref": "Archive/Plan",
"old_title": "Plan",
"new_title": "Plan",
"title_rules": false,
"file_rules": true
}
],
"note_dir": "Other",
"input": "[[Work/Plan#Goals|g]] [a](../Work/Plan.md) [b](Plan.md) [r](/Work/Plan.md) [c](<../Work/Plan.md>) [d](Work/Plan.md)\n",
"expected": "[[Archive/Plan#Goals|g]] [a](../Archive/Plan.md) [b](Plan.md) [r](/Archive/Plan.md) [c](<../Archive/Plan.md>) [d](Archive/Plan.md)\n"
},
{
"name": "a renamed notebook moves every note in it",
"renames": [
{
"old_ref": "Work/A",
"new_ref": "Projects/A",
"old_title": "A",
"new_title": "A",
"title_rules": false,
"file_rules": true
},
{
"old_ref": "Work/Sub/B",
"new_ref": "Projects/Sub/B",
"old_title": "B",
"new_title": "B",
"title_rules": false,
"file_rules": true
}
],
"note_dir": "Other",
"input": "[[Work/A]] [[Work/Sub/B|b]] [x](../Work/Sub/B.md) [y](../Work/Other.md) [[A]]\n",
"expected": "[[Projects/A]] [[Projects/Sub/B|b]] [x](../Projects/Sub/B.md) [y](../Work/Other.md) [[A]]\n"
},
{
"name": "a note moved from the top of the vault into a folder",
"renames": [
{
"old_ref": "Plan",
"new_ref": "My Folder/Plan",
"old_title": "Plan",
"new_title": "Plan",
"title_rules": false,
"file_rules": true
}
],
"note_dir": "",
"input": "[[Plan]] [a](Plan.md) [b](<Plan.md>)\n",
"expected": "[[Plan]] [a](My%20Folder/Plan.md) [b](<My Folder/Plan.md>)\n"
},
{
"name": "a note moved to the top of the vault",
"renames": [
{
"old_ref": "Work/Plan",
"new_ref": "Plan",
"old_title": "Plan",
"new_title": "Plan",
"title_rules": false,
"file_rules": true
}
],
"note_dir": "Other",
"input": "[[Work/Plan]] [a](../Work/Plan.md) [b](/Work/Plan.md)\n",
"expected": "[[Plan]] [a](../Plan.md) [b](/Plan.md)\n"
}
]
+8
View File
@@ -75,3 +75,11 @@ test('rescanning edited documents adds and removes occurrences without changing
assert.equal(after.textContent, 'word WORD word');
});
test('replace all takes each stretch of text once when matches overlap', async () => {
const { replaceableMatches } = await import('../src/lib/editor/search.ts');
const overlapping = findSourceMatches('aaaa b aa', 'aa', options);
assert.deepEqual(overlapping.map(({ from }) => from), [0, 1, 2, 7]);
assert.deepEqual(replaceableMatches(overlapping), [{ from: 0, to: 2 }, { from: 2, to: 4 }, { from: 7, to: 9 }]);
assert.deepEqual(replaceableMatches([]), []);
});
+40 -3
View File
@@ -100,7 +100,7 @@ test('wiki lookup preserves path precedence, shallowest title and escaped attrib
assert.doesNotMatch(parser.render('[[Note]]'), /data-wiki-link/);
});
test('wiki lookup reads titles once per render and refreshes after in-place cache changes', () => {
test('wiki lookup reads titles once per titles array and refreshes when the array is replaced', () => {
let reads = 0;
const notes = Array.from({ length: 250 }, (_, index) => ({
path: `folder/Note ${index}.md`, get title() { reads++; return `Note ${index}`; },
@@ -108,9 +108,11 @@ test('wiki lookup reads titles once per render and refreshes after in-place cach
const env = { wikiLinkTitles: notes };
const source = '[[Note 249]] '.repeat(100);
parser.render(source, env);
parser.render(source, env);
assert.equal(reads, notes.length);
notes[249] = { path: 'Moved.md', title: 'Note 249' };
assert.match(parser.render(source, env), /data-path="Moved\.md"/);
const updated = notes.slice();
updated[249] = { path: 'Moved.md', title: 'Note 249' };
assert.match(parser.render(source, { wikiLinkTitles: updated }), /data-path="Moved\.md"/);
});
test('ordinary and legacy links/images remain functional while unsafe schemes remain rejected', () => {
@@ -253,3 +255,38 @@ test('a line with thousands of unclosed link starts is parsed in linear time', (
assert.match(parser.render(noise + '[doc](my file.md) and ![pic](photo one.png "Caption")'), /href="my%20file.md".*src="photo%20one.png"/s);
assert.match(parser.render(noise + '\n[doc](my file.md)'), /href="my%20file.md"/);
});
test('angle-bracket text that is not HTML stays text', () => {
assert.equal(parser.render('returns List<String> or Map<K,V> here'), '<p>returns List&lt;String&gt; or Map&lt;K,V&gt; here</p>\n');
assert.equal(parser.render('Run `x` as <username> then <my-tag a="1">'), '<p data-helix-code="">Run <code style="white-space: pre-wrap">x</code> as &lt;username&gt; then &lt;my-tag a=&quot;1&quot;&gt;</p>\n');
// A placeholder alone on a line would otherwise be an HTML block.
assert.equal(parser.render('<GroupName>\n\nafter'), '<p>&lt;GroupName&gt;</p>\n<p>after</p>\n');
assert.equal(parser.render('<Foo>\ntext \n</Foo>'), '<p>&lt;Foo&gt;<br>text<br>&lt;/Foo&gt;</p>\n');
});
test('real HTML elements are still HTML', () => {
assert.equal(parser.render('a <b>bold</b> and <br> and <kbd>K</kbd>'), '<p>a <b>bold</b> and <br> and <kbd>K</kbd></p>\n');
assert.equal(parser.render('<div class="x">there</div>'), '<div class="x">there</div>');
assert.equal(parser.render('<details><summary>S</summary>\n\nbody\n\n</details>'), '<details><summary>S</summary>\n<p>body</p>\n</details>');
});
test('HTML comments are kept as text, the blank-line marker is not', () => {
assert.equal(parser.render('a <!-- note to self --> b'), '<p>a &lt;!-- note to self --&gt; b</p>\n');
assert.equal(parser.render('before\n\n<!--\nline one\nline two\n-->\n\nafter'), '<p>before</p>\n<p>&lt;!--<br>line one<br>line two<br>--&gt;</p>\n<p>after</p>\n');
assert.equal(parser.render('one\n\n<!-- -->\n\ntwo'), '<p>one</p>\n<p></p>\n<p>two</p>\n');
assert.equal(parser.render('x <!-- --> y'), '<p>x <!-- --> y</p>\n');
});
test('an empty paragraph marker glued to an image by older versions still shows the image', () => {
const html = parser.render('Before\n\n<!-- -->![](a.png)\n![](b.png)\n\nAfter');
assert.match(html, /<p><\/p>/);
assert.equal((html.match(/<img /g) ?? []).length, 2);
assert.doesNotMatch(html, /&lt;!--|!\[\]|<!--/);
assert.match(html, /<p>After<\/p>/);
const indented = parser.render(' <!-- --> ![](a.png)');
assert.equal((indented.match(/<img /g) ?? []).length, 1);
assert.doesNotMatch(indented, /<pre>/);
// Anything else after the marker is still raw HTML, and code keeps the line as written.
assert.match(parser.render('<!-- -->text'), /^<!-- -->text/);
assert.equal(unescape(escapedCode(parser.render('```\n<!-- -->![](a.png)\n```'))), '<!-- -->![](a.png)');
});
+128 -2
View File
@@ -14,7 +14,7 @@ const { code } = await transformWithEsbuild(source, 'markdown.ts', {
format: 'esm',
target: 'esnext'
});
const { joinListItemBlocks, joinMarkdownBlocks, serializeCodeBlock, serializeInlineMarkdown, serializeInlineMarkdownKeepingDollars } = await import(
const { escapeBlockStarts, joinListItemBlocks, joinMarkdownBlocks, literalTextEscapes, serializeCodeBlock, serializeInlineMarkdown, serializeInlineMarkdownKeepingDollars } = await import(
`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`
);
@@ -40,7 +40,12 @@ const schema = new Schema({
doc: { content: 'block+' },
paragraph: { content: 'inline*', group: 'block' },
text: { group: 'inline' },
mathInline: { inline: true, group: 'inline', atom: true, attrs: { tex: { default: '' } } }
mathInline: { inline: true, group: 'inline', atom: true, attrs: { tex: { default: '' } } },
image: {
inline: true,
group: 'inline',
attrs: { src: {}, alt: { default: '' }, title: { default: null }, size: { default: 'full' }, width: { default: null }, height: { default: null } }
}
},
marks: {
link: { attrs: { href: {} } },
@@ -234,6 +239,105 @@ test('drops formatting around a code span that a letter or digit touches', () =>
assert.match(editorMarkdown.renderInline('(**`x`**).'), /<strong><code[^>]*>x<\/code><\/strong>/);
});
// What the editor does when it saves a paragraph: escape only what would read back differently.
const inlinePlainText = (markdown) => (editorMarkdown.parseInline(markdown, {})[0]?.children ?? [])
.map((token) => (token.type === 'text' || token.type === 'code_inline' || token.type === 'helix_wiki' ? token.content : '')).join('');
const readsAsParagraph = (markdown) => {
const tokens = editorMarkdown.parse(markdown, {});
return tokens.length === 3 && tokens[0].type === 'paragraph_open';
};
function saveParagraph(segments) {
const node = paragraph(segments);
const literalText = literalTextEscapes(node, (source) => source, inlinePlainText);
return escapeBlockStarts(serializeInlineMarkdown(node, (source) => source, { literalText }), readsAsParagraph);
}
/** Block types and visible text a saved paragraph has when it is loaded again. */
function reload(markdown) {
const tokens = editorMarkdown.parse(markdown, {});
return {
blocks: tokens.filter((token) => token.nesting === 1).map((token) => token.type.replace('_open', '')).join(','),
text: tokens.filter((token) => token.type === 'inline').flatMap((token) => token.children)
.filter((token) => token.type === 'text' || token.type === 'code_inline').map((token) => token.content).join(''),
formatted: tokens.filter((token) => token.type === 'inline').flatMap((token) => token.children)
.some((token) => /^(em|strong|s|link|html_inline|mark)/.test(token.type)),
};
}
test('text that looks like Markdown is saved so that it stays text', () => {
const cases = [
['*not italic*', '\\*not italic*'],
['a*b*c in a formula', 'a\\*b*c in a formula'],
['__init__ is a method', '\\_\\_init__ is a method'],
['`not code`', '\\`not code`'],
['~~not struck~~', '\\~~not struck~~'],
['<b> shown as text', '\\<b> shown as text'],
['&amp; literal entity', '\\&amp; literal entity'],
['1. not a list', '1\\. not a list'],
['12) not a list', '12\\) not a list'],
['# not a heading', '\\# not a heading'],
['> not a quote', '\\> not a quote'],
['- not a bullet', '\\- not a bullet'],
['+ not a bullet', '\\+ not a bullet'],
['---', '\\---'],
['[x]: http://not.a/definition', '\\[x]: http://not.a/definition'],
['\\\\server\\share and C:\\.', '\\\\\\server\\share and C:\\\\.'],
];
for (const [text, expected] of cases) {
const saved = saveParagraph([{ text, marks: [] }]);
assert.equal(saved, expected, text);
assert.deepEqual(reload(saved), { blocks: 'paragraph', text, formatted: false }, saved);
// Saving what was loaded again changes nothing more.
assert.equal(saveParagraph([{ text: reload(saved).text, marks: [] }]), saved);
}
});
test('text that reads as a link or an image is left to become one', () => {
// Deliberate: images damaged by an old save bug (`<!-- -->![](a b.png)`) load as text and come
// back as images this way. Brackets are never escaped.
for (const text of ['![](.helixnotes/attachments/a b.png)', '[docs](https://example.com)', '[[Other note]]']) {
assert.equal(saveParagraph([{ text, marks: [] }]), text);
}
});
test('a line the note already has unescaped keeps its meaning from before', () => {
// The editor shows a source line such as ` - item` as text; saving it as `- item` lets the
// next load read the list its author wrote. Only text from elsewhere is escaped.
const node = paragraph([{ text: '- item from an indented source line', marks: [] }]);
const line = serializeInlineMarkdown(node, (source) => source);
const source = new Set(['- item from an indented source line']);
assert.equal(escapeBlockStarts(line, readsAsParagraph, (text) => source.has(text.trim())), '- item from an indented source line');
assert.equal(escapeBlockStarts(line, readsAsParagraph, () => false), '\\- item from an indented source line');
// Line by line: one known line does not excuse another.
assert.equal(
escapeBlockStarts('1. typed here\n2. from the source', readsAsParagraph, (text) => text.trim() === '2. from the source'),
'1\\. typed here\n2. from the source'
);
});
test('ordinary text is written exactly as before, without added backslashes', () => {
for (const text of [
'2 * 3 * 4', 'snake_case_name and file_name.md', 'price is [10] and a < b & c', 'R&D, AT&T, x = y, 5^2?',
'a lone * star and a lone ` tick', 'TODO [ ] check', 'version 1.2.3 and #hashtag', 'C:\\Users\\tom\\notes',
'e.g. 1.5x faster - really', 'Q&A: why? because!', 'a_b_c', '100% (approx.) ~ 3', 'email@example.com', '(a) [b] {c}',
]) {
assert.equal(saveParagraph([{ text, marks: [] }]), text);
}
});
test('literal text next to real formatting keeps both', () => {
const codeMark = schema.marks.code.create();
// Asterisks in plain text around bold text must not join the bold markers.
let saved = saveParagraph([{ text: 'a*', marks: [] }, { text: 'b', marks: [bold] }, { text: '*c', marks: [] }]);
assert.equal(reload(saved).text, 'a*b*c');
assert.equal(editorMarkdown.renderInline(saved), 'a*<strong>b</strong>*c');
// Text in a code span is never escaped.
saved = saveParagraph([{ text: 'x ', marks: [] }, { text: 'a*b*c', marks: [codeMark] }, { text: ' and [docs]', marks: [] }]);
assert.equal(saved, 'x `a*b*c` and [docs]');
// A paragraph with formatting and harmless brackets gets no backslashes.
saved = saveParagraph([{ text: 'Note:', marks: [bold] }, { text: ' see [docs] and file_name', marks: [] }]);
assert.equal(saved, '**Note:** see [docs] and file_name');
});
test('preserves formatting on non-code parts of a link', () => {
const codeMark = schema.marks.code.create();
const serialized = serializeInlineMarkdown(paragraph([
@@ -561,3 +665,25 @@ test('joining a very large note takes linear time', () => {
assert.equal(joined.endsWith('Paragraph 29999 with some words in it.\n'), true);
assert.ok(!joined.includes('\n\n\n'));
});
test('an image keeps the link around it, alone or within text', () => {
const linked = (attrs, href = 'https://example.com') =>
schema.nodes.image.create(attrs, null, [schema.marks.link.create({ href })]);
const alone = schema.node('paragraph', null, [linked({ src: 'logo.png' })]);
assert.equal(serializeInlineMarkdown(alone), '[![](logo.png)](https://example.com)');
assert.match(markdown.render(serializeInlineMarkdown(alone)), /<a href="https:\/\/example.com"><img src="logo.png"/);
const within = schema.node('paragraph', null, [
schema.text('See '), linked({ src: 'badge.svg', alt: 'badge' }, 'https://ci.example.com'), schema.text(' here')
]);
assert.equal(serializeInlineMarkdown(within), 'See [![badge](badge.svg)](https://ci.example.com) here');
// Without a link an image still goes on its own line, as before.
const plain = schema.node('paragraph', null, [schema.text('Text '), schema.nodes.image.create({ src: 'a.png', alt: 'alt' })]);
assert.equal(serializeInlineMarkdown(plain), 'Text \n![alt](a.png)');
});
test('an image with a width or height is written as HTML so the size is kept', () => {
const sized = schema.node('paragraph', null, [schema.nodes.image.create({ src: 'd.png', alt: 'Logo "x"', width: '120', height: '40' })]);
const html = serializeInlineMarkdown(sized);
assert.equal(html, '<img src="d.png" alt="Logo &quot;x&quot;" width="120" height="40">');
assert.match(markdown.render(html), /<img src="d.png" alt="Logo &quot;x&quot;" width="120" height="40">/);
});
+63
View File
@@ -0,0 +1,63 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { transformWithEsbuild } from 'vite';
const source = await readFile(new URL('../src/lib/editor/renamedLinks.ts', import.meta.url), 'utf8');
const { code } = await transformWithEsbuild(source, 'renamedLinks.ts', { loader: 'ts', format: 'esm' });
const { renamedLinkChanges } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
const apply = (text, rename) => {
let result = text;
for (const change of renamedLinkChanges(text, rename).reverse()) {
result = result.slice(0, change.from) + change.insert + result.slice(change.to);
}
return result;
};
test('links to a renamed note follow it, as the backend rewrites them', () => {
// Same input and result as the backend test for update_wikilinks_after_rename.
const rename = { old_ref: 'Home', new_ref: 'Start', old_title: 'Home', new_title: 'Start', title_rules: true };
assert.equal(
apply('See [[Home]], [[Home|the start page]] and [[Home|Home]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n', rename),
'See [[Start]], [[Start|the start page]] and [[Start|Start]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n'
);
});
test('path links follow a rename in a folder', () => {
const rename = { old_ref: 'Work/Plan', new_ref: 'Work/Roadmap', old_title: 'Plan', new_title: 'Roadmap', title_rules: true };
assert.equal(
apply('[[Work/Plan]] [[Work/Plan|Plan]] [[Work/Plan|mine]] [[Plan]] [[Other/Plan]]', rename),
'[[Work/Roadmap]] [[Work/Roadmap|Roadmap]] [[Work/Roadmap|mine]] [[Roadmap]] [[Other/Plan]]'
);
});
test('title links stay when another note shares the old title', () => {
const rename = { old_ref: 'Work/Plan', new_ref: 'Work/Roadmap', old_title: 'Plan', new_title: 'Roadmap', title_rules: false };
assert.equal(apply('[[Plan]] [[Plan|x]] [[Work/Plan|Plan]]', rename), '[[Plan]] [[Plan|x]] [[Work/Roadmap|Roadmap]]');
});
test('nothing changes when no link points at the renamed note', () => {
const rename = { old_ref: 'Home', new_ref: 'Start', old_title: 'Home', new_title: 'Start', title_rules: true };
assert.deepEqual(renamedLinkChanges('Home is [[Elsewhere]] and `code`.', rename), []);
});
test('aliased links in a table cell follow a rename', () => {
const rename = { old_ref: 'Home', new_ref: 'Start', old_title: 'Home', new_title: 'Start', title_rules: true };
assert.equal(
apply('| [[Home\\|Home]] | [[Home\\|start]] and [[Index\\|Home]] |', rename),
'| [[Start\\|Start]] | [[Start\\|start]] and [[Index\\|Home]] |'
);
});
// The same cases are checked against the backend rewrite in operations.rs.
const fixtures = JSON.parse(await readFile(new URL('./fixtures/renamed-links.json', import.meta.url), 'utf8'));
for (const fixture of fixtures) {
test(`shared rename case: ${fixture.name}`, () => {
let result = fixture.input;
for (const change of renamedLinkChanges(fixture.input, fixture.renames ?? fixture.rename, fixture.note_dir).reverse()) {
result = result.slice(0, change.from) + change.insert + result.slice(change.to);
}
assert.equal(result, fixture.expected);
});
}
+50
View File
@@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Table } from '@tiptap/extension-table';
import { columnResizingPluginKey, tableEditingKey, tableNodes } from '@tiptap/pm/tables';
import { EditorState } from '@tiptap/pm/state';
import { Schema } from '@tiptap/pm/model';
import { AlwaysResizableTable } from '../src/lib/editor/tableExtension.ts';
test('the table wrapper is registered even when the editor starts read-only', () => {
const options = {
...Table.options,
resizable: true,
};
const plugins = AlwaysResizableTable.config.addProseMirrorPlugins.call({
options,
editor: { isEditable: false },
});
const keys = new Set(plugins.map((plugin) => plugin.key));
assert.ok(keys.has(columnResizingPluginKey.key), 'missing table node view / column resizing plugin');
assert.ok(keys.has(tableEditingKey.key), 'missing table editing plugin');
// The column-resizing plugin registers the table node view when its state starts. That node
// view is what creates .tableWrapper, which owns the horizontal scrollbar.
const resizing = plugins.find((plugin) => plugin.key === columnResizingPluginKey.key);
const nodes = tableNodes({ tableGroup: 'block', cellContent: 'inline*', cellAttributes: {} });
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
text: { group: 'inline' },
paragraph: { content: 'inline*', group: 'block' },
...nodes,
},
});
EditorState.create({ schema, plugins });
assert.equal(typeof resizing.spec.props.nodeViews.table, 'function');
});
test('a non-resizable table still gets table editing', () => {
const options = {
...Table.options,
resizable: false,
};
const plugins = AlwaysResizableTable.config.addProseMirrorPlugins.call({
options,
editor: { isEditable: false },
});
const keys = new Set(plugins.map((plugin) => plugin.key));
assert.equal(keys.has(columnResizingPluginKey.key), false);
assert.ok(keys.has(tableEditingKey.key));
});
+50
View File
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Editor } from '@tiptap/core';
import StarterKit from '@tiptap/starter-kit';
import { createLowlight } from 'lowlight';
import { CachedCodeBlockLowlight } from '../src/lib/editor/extensions/cachedCodeBlockLowlight.ts';
const paragraph = (text = '') => ({ type: 'paragraph', ...(text ? { content: [{ type: 'text', text }] } : {}) });
const code = (text = '') => ({ type: 'codeBlock', attrs: Object.assign(Object.create(null), { language: null }), ...(text ? { content: [{ type: 'text', text }] } : {}) });
function editor(content) {
return new Editor({ extensions: [StarterKit.configure({ codeBlock: false }), CachedCodeBlockLowlight.configure({ lowlight: createLowlight() })], content: { type: 'doc', content } });
}
test('converts selected paragraphs to one code block and back, preserving blank lines', () => {
const initial = [paragraph('First'), paragraph(), paragraph('Second'), paragraph()];
const e = editor(initial);
e.commands.selectAll();
assert.equal(e.commands.toggleCodeBlock(), true);
assert.deepEqual(e.getJSON().content, [code('First\n\nSecond\n')]);
assert.equal(e.commands.toggleCodeBlock(), true);
assert.deepEqual(e.getJSON().content, initial);
e.destroy();
});
test('converts multiple existing code blocks back to paragraphs', () => {
const e = editor([code('First'), code(), code('Second')]);
e.commands.selectAll();
e.commands.toggleCodeBlock();
assert.deepEqual(e.getJSON().content, [paragraph('First'), paragraph(), paragraph('Second')]);
e.destroy();
});
test('preserves hard breaks and leaves unselected blocks alone', () => {
const first = { type: 'paragraph', content: [{ type: 'text', text: 'one' }, { type: 'hardBreak' }, { type: 'text', text: 'two' }] };
const e = editor([first, paragraph('three'), paragraph('outside')]);
const end = e.state.doc.child(0).nodeSize + e.state.doc.child(1).nodeSize - 1;
e.commands.setTextSelection({ from: 1, to: end });
e.commands.toggleCodeBlock();
assert.deepEqual(e.getJSON().content, [code('one\ntwo\nthree'), paragraph('outside')]);
e.destroy();
});
test('single cursor code toggle retains standard behaviour', () => {
const e = editor([paragraph('Hello')]);
e.commands.toggleCodeBlock();
assert.deepEqual(e.getJSON().content, [code('Hello')]);
e.commands.toggleCodeBlock();
assert.deepEqual(e.getJSON().content, [paragraph('Hello')]);
e.destroy();
});
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { createContext, Script } from 'node:vm';
import ts from 'typescript';
const source = await readFile(new URL('../src/lib/ui-scale.ts', import.meta.url), 'utf8');
const script = new Script(ts.transpileModule(source.replace(/^import .*;\n/gm, ''), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText);
function setup(android = true) {
let content = 'width=device-width, initial-scale=1';
let writes = 0;
const listeners = [];
const zooms = [];
const viewport = { width: 411, scale: 1 };
const context = createContext({
exports: {}, isAndroid: android, console,
screen: { width: 411, height: 850 },
window: { visualViewport: viewport, addEventListener: (event, handler) => listeners.push({ event, handler }) },
document: { querySelector: () => ({
getAttribute: () => content,
setAttribute: (_name, value) => { content = value; writes++; }
}) },
getCurrentWebview: () => ({ setZoom: async (scale) => zooms.push(scale) })
});
script.runInContext(context);
return {
apply: context.exports.applyUiScale, viewport, listeners, zooms,
get writes() { return writes; },
get values() { return Object.fromEntries(content.split(',').map((part) => part.trim().split('='))); }
};
}
test('Android scales the layout to the visible phone width, keeping tablet layout out', async () => {
const app = setup();
for (const scale of [1, 1.15, 1.25, 1.4]) {
await app.apply(scale);
const width = Number(app.values.width);
assert.ok(width <= 411 / scale, 'the layout must fit inside the scaled visible area');
assert.ok(width >= 290, 'mobile menus must still fit');
assert.ok(width < 900, 'a phone must not acquire the tablet breakpoint');
assert.equal(Number(app.values['initial-scale']), scale);
}
});
test('Android adapts to rotation and a narrower app window without multiplying the saved scale', async () => {
const app = setup();
await app.apply(1.25);
app.viewport.width = 850 / 1.25;
app.viewport.scale = 1.25;
app.listeners[0].handler();
assert.equal(Number(app.values.width), 680);
app.viewport.width = 360 / 1.25;
app.listeners[0].handler();
assert.equal(Number(app.values.width), 290);
assert.ok(Number(app.values.width) * Number(app.values['initial-scale']) <= 360);
});
test('reapplying a scale does not duplicate resize listeners or rewrite the same viewport', async () => {
const app = setup();
await app.apply(1.15);
await app.apply(1.15);
assert.equal(app.listeners.length, 1);
assert.equal(app.listeners[0].event, 'resize');
assert.equal(app.writes, 1);
app.listeners[0].handler();
assert.equal(app.writes, 1);
});
test('desktop keeps using native WebView zoom without changing the viewport', async () => {
const app = setup(false);
await app.apply(1.5);
assert.deepEqual(app.zooms, [1.5]);
assert.equal(app.writes, 0);
assert.equal(app.listeners.length, 0);
});
+52
View File
@@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, TextSelection } from '@tiptap/pm/state';
import { wrapSelection } from '../src/lib/editor/extensions/wrapSelectedText.ts';
const schema = new Schema({
nodes: {
doc: { content: 'block+' },
paragraph: { group: 'block', content: 'inline*' },
text: { group: 'inline' },
},
marks: { bold: {} },
});
// A document holding one paragraph with `text`; positions inside it start at 1.
function stateWith(text, anchor, head = anchor) {
const doc = schema.node('doc', null, [schema.node('paragraph', null, schema.text(text))]);
return EditorState.create({ doc, selection: TextSelection.create(doc, anchor, head) });
}
test('typing a pair character over the selection wraps it and keeps the text selected', () => {
const state = stateWith('say hello now', 5, 10);
const tr = wrapSelection(state, 5, 10, '(');
assert.ok(tr);
assert.equal(tr.doc.textContent, 'say (hello) now');
assert.equal(tr.selection.from, 6);
assert.equal(tr.selection.to, 11);
assert.equal(tr.doc.textBetween(tr.selection.from, tr.selection.to), 'hello');
});
test('a compose or dead-key preedit being replaced is not a selection and is left alone', () => {
// Compose ' e: GTK shows "·", then replaces it with "'", then commits "é". ProseMirror reports
// the replacement as a quote typed over the preedit range, with the cursor collapsed after it.
const state = stateWith('a·', 3);
assert.equal(wrapSelection(state, 2, 3, "'", true), null);
assert.equal(wrapSelection(state, 2, 3, "'", false), null);
});
test('only a range equal to the selection is wrapped, never a collapsed cursor', () => {
const partial = stateWith('say hello now', 5, 10);
assert.equal(wrapSelection(partial, 5, 8, '"'), null);
assert.equal(wrapSelection(partial, 5, 5, '"'), null);
const cursor = stateWith('say hello now', 5);
assert.equal(wrapSelection(cursor, 5, 10, '"'), null);
});
test('characters without a closing pair pass through', () => {
const state = stateWith('say hello now', 5, 10);
assert.equal(wrapSelection(state, 5, 10, 'x'), null);
assert.equal(wrapSelection(state, 5, 10, 'é'), null);
});