Compare commits

..
Author SHA1 Message Date
Yuri Karamian db92dabba5 chore: bump version to 1.3.3 2026-06-28 13:31:49 +02:00
Yuri Karamian 2469a971ca WebDAV sync: make config per-vault so switching vaults no longer cross-contaminates remotes; migrate existing global config to the active vault 2026-06-27 11:33:07 +02:00
Yuri Karamian a43bf05bf0 WebDAV sync: make config per-vault so switching vaults no longer cross-contaminates remotes; migrate existing global config
to the active vault
2026-06-27 01:08:02 +02:00
blake ffd9ebad7e The outline side panel now persists when a user clicks in the editor. (#176)
WIP

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/176
2026-06-27 00:00:16 +02:00
mf d2100c8500 Create notes from empty list double-click (#175)
Double-clicking empty space in the notes list now creates a new note. The notebook sidebar double-click shortcut is scoped to the notebook section so adjacent panes do not trigger notebook creation.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/175
2026-06-26 23:59:54 +02:00
Yuri Karamian 7e63d721bc Fix 'Open in New Window' cursor jumping to the top when pausing (ignore the file-watcher echo of the window's own save) 2026-06-25 16:08:25 +02:00
Yuri Karamian 2c774c51c6 Notebook reorder: make path math separator-agnostic so manual sort works on Windows (backslash paths) 2026-06-25 15:10:20 +02:00
Yuri Karamian 8eba4527af Notebook reorder: commit drop on any release event and skip pointer capture on mouse, so it works in WebView2 (Windows) 2026-06-25 14:55:59 +02:00
Yuri Karamian 181b3eb6c2 Notebook reorder: track drag on window pointer events so it works in WebView2 (Windows) 2026-06-25 14:47:06 +02:00
Yuri Karamian 879d2f42c6 Notebook reorder via pointer-event drag handle (fixes Windows/Android); click body selects, chevron expands 2026-06-25 13:31:49 +02:00
Yuri Karamian 85ea26b57a Notebook reorder: use pointer events via a drag handle so manual sort works on Windows and Android 2026-06-25 13:29:24 +02:00
Yuri Karamian 800c81e598 Add ! menu on task lines for setting priority and due date 2026-06-25 12:57:51 +02:00
Yuri Karamian 30c3523722 Parallelize vault-stats and tasks scanning for faster Info/Tasks loads on Android 2026-06-25 12:37:32 +02:00
Yuri Karamian 761bf5b42e Android: add an Info button to the top bar that opens the About panel 2026-06-25 12:37:12 +02:00
Yuri Karamian b10a7b1bfc Fix typing stutter in large notes by debouncing per-keystroke document scans 2026-06-25 12:09:06 +02:00
blake 313d86df23 Show all existing tags when tag input is empty (#165)
WIP: Previously suggestions only appeared after typing; now all unused tags can be shown immediately when the tag menu opens.
Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/165
2026-06-25 11:45:53 +02:00
Yuri Karamian 95627cbb5c Fix ordered list markers and empty-callout placeholder on WebKitGTK 2026-06-25 11:43:08 +02:00
Yuri Karamian b9ea14f330 README: document the macOS damaged-app fix (xattr) 2026-06-25 11:42:53 +02:00
Yuri Karamian 812d025a9d Fix ordered list markers showing only the last digit on WebKitGTK 2026-06-25 00:33:58 +02:00
Yuri Karamian 11cc2daa4b Parallelize notebook and note scanning for faster loads on Android 2026-06-24 23:28:28 +02:00
Blake Boone 5c36f2aa71 Added collapsable info panel that tracks word/character count, snapshots, last modified, etc. (#164)
WIP

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/164
2026-06-24 22:54:52 +02:00
Yuri Karamian 987b1b9ed7 Add opt-in date grouping for the All Notes list 2026-06-24 22:38:23 +02:00
Yuri Karamian 3ef0e14581 Add callouts (> [!type]) with fold, titles, type picker, and custom types 2026-06-24 21:57:13 +02:00
mf f98b3415bc feat(editor): resizable outline panel (#161)
Add a drag handle to resize the outline panel and persist its width in
vault state (outline_width). Outline text now scales with the editor
font size.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/161
2026-06-24 21:01:43 +02:00
mf 16805c96aa Delete active note on shortcut (#156)
Press `ctrl+shift+del` to move the active note to the trash.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/156
2026-06-24 21:00:33 +02:00
Yuri Karamian 9f2e0ba8b6 README: add macOS Apple Silicon (aarch64) download link 2026-06-24 20:05:56 +02:00
blake 7b3609afbb Added custom themes, import/export option with json (#159)
Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/159
2026-06-23 20:19:23 +02:00
Yuri Karamian 84ff75f223 Fix #157: don't flag notebook folder icons as orphaned attachments 2026-06-23 14:03:29 +02:00
Yuri Karamian 56dc0eefd7 Fix #63 desktop/mobile layout; hide Updates tab on Android; dim inline task tokens in the editor 2026-06-23 13:52:26 +02:00
Yuri Karamian eeea16531a Fix #63: decide layout from compile-time platform, not the webview user-agent 2026-06-23 13:12:36 +02:00
Yuri Karamian ac5ab2a27a Release v1.3.2 2026-06-22 23:06:19 +02:00
Yuri Karamian fef4ece2c0 Make editor + menus match the toolbar per platform (dedupe desktop, complete mobile) 2026-06-22 14:25:44 +02:00
Yuri Karamian 613451f4d8 Show search + info/settings icons in the collapsed sidebar rail 2026-06-22 13:45:01 +02:00
Yuri Karamian 04dee78b27 Add command-palette entries to reach hidden sidebar views (#153) 2026-06-22 13:28:24 +02:00
Yuri Karamian 69330bf23c Add command-palette entries to reach hidden sidebar views (#153) 2026-06-22 13:20:15 +02:00
Yuri Karamian 4843bcacd5 Reveal hidden notes list when selecting a sidebar view (#145) 2026-06-22 12:59:04 +02:00
Yuri Karamian 3d28665e1e Add settings to hide unused sidebar items (#153) 2026-06-22 12:52:07 +02:00
Yuri Karamian 209585a0b4 Preserve create date for notes without frontmatter dates (#139) 2026-06-22 12:50:50 +02:00
mf 84eab75ec8 Do not render Notes in Notebook sidebar (#152)
Keeps the notebook tree focused on notebooks and leaves note browsing to the note list.

![image](/attachments/a1e50fba-26b7-4dcd-9d44-9938783c6bc5)

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/152
2026-06-22 11:57:08 +02:00
Yuri Karamian ce17b38509 Add custom note sorting (#149) 2026-06-21 21:44:56 +02:00
Yuri Karamian 85c1e1e7d3 Add customizable keyboard shortcuts (#148) 2026-06-21 13:56:55 +02:00
mf ebf38e2281 Add notes list toggle shortcut (#145)
Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/145
2026-06-21 12:50:31 +02:00
mf 32ec62419d Focus sub-notebook input from context menu (#150)
Focus the sub-notebook name field after choosing New Sub-notebook from a notebook context menu.

Validation: pnpm build
Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/150
2026-06-21 12:49:41 +02:00
mf e46fda91a4 Add custom note sorting 2026-06-21 10:46:22 +03:30
mf 62d5388176 Add customizable keyboard shortcuts
Drive app shortcuts from a central keybindings store (defaults +
localStorage overrides). In the Info panel's Shortcuts tab: click a
shortcut to rebind, right-click to reset, Esc to cancel; combos
already in use are rejected.
2026-06-21 10:37:58 +03:30
Yuri Karamian db2bef892a Add Indent/Outdent buttons to mobile editor toolbar 2026-06-20 23:29:24 +02:00
Yuri Karamian 1c46935cc5 Add Note Width setting to cap editor content width (#137) 2026-06-20 15:01:01 +02:00
Yuri Karamian f0f19125d5 Pin Notebooks header while scrolling, add divider above it (#126) 2026-06-20 14:45:11 +02:00
Yuri Karamian 828f83d2e3 Preserve cursor position when toggling markdown source editor (#125) 2026-06-20 14:35:22 +02:00
Yuri Karamian 002fdb763e WebDAV: source manifest etag from PROPFIND, not PUT response (#147) 2026-06-20 14:14:43 +02:00
Yuri Karamian d3ff1fb931 Parse markdown links with angle brackets and titles (#146) 2026-06-20 13:01:18 +02:00
Yuri Karamian 7951472ae3 Fix reserved $ prefix in variable name 2026-06-19 14:36:10 +02:00
Yuri Karamian 5cffe8846b Fix table menu overflow and conditional reset button 2026-06-19 14:34:28 +02:00
Yuri Karamian 806e975e31 Fix table context menu going below screen 2026-06-19 14:30:32 +02:00
Yuri Karamian e4232269f6 Fix table styling not detected for HTML serialization 2026-06-19 14:29:00 +02:00
Yuri Karamian ab759a006d Fix table content loss in markdown serialization 2026-06-19 14:26:00 +02:00
Yuri Karamian ca7f25003c Tables serialize as markdown by default, HTML only when styled 2026-06-19 14:24:25 +02:00
Yuri Karamian 08ab0b90f2 Fix Enter key in language search truncating code block 2026-06-19 14:15:07 +02:00
Yuri Karamian e275f5c0bb Add PowerShell syntax highlighting 2026-06-19 14:05:04 +02:00
Yuri Karamian 683a01627e add highlight.js 2026-06-19 14:01:04 +02:00
Yuri Karamian 3c11a7f63e Add search filter to code block language selector 2026-06-19 14:00:39 +02:00
Yuri Karamian 90a96552d3 Always show code block controls at low opacity 2026-06-19 14:00:38 +02:00
Yuri Karamian a710603b0a Unify code block copy button and language selector styling 2026-06-19 14:00:38 +02:00
mf 80a6fdca69 Move single list items with Alt Shift arrows (#143)
Adds Alt+Shift+Up/Down for moving only the current list or task item while preserving the existing Alt+Up/Down block movement.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/143
2026-06-19 12:14:34 +02:00
mf 1dc78ca916 Add F2 rename shortcut (#142)
Adds F2 as a keyboard shortcut for focused note and notebook rows, reusing the existing inline rename flow.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/142
2026-06-19 12:14:20 +02:00
Yuri Karamian 3118af1e41 Merge branch 'fix/blob-images-source-mode' 2026-06-19 12:12:36 +02:00
Yuri Karamian a669d96aed Fix images not rendering after comment in source mode (#87) 2026-06-19 12:09:30 +02:00
Yuri Karamian a0b1fa0481 Fix images not rendering after comment in source mode (#87) 2026-06-19 12:03:49 +02:00
Yuri Karamian 2e8c048a3e Fix images not rendering after <- Client-side Create New Pull Zone button for allowed --> comment in source mode (#87) 2026-06-19 12:01:13 +02:00
Yuri Karamian d2ddc7f0de Fix editor not rendering on every other source mode switch 2026-06-19 11:54:13 +02:00
Yuri Karamian 3b88b20c61 Fix editor not rendering on every other source mode switch 2026-06-19 11:49:18 +02:00
Yuri Karamian f8371aaa57 Fix editor not rendering on every other source mode switch 2026-06-19 11:47:11 +02:00
Yuri Karamian c5a45131a5 Fix editor not rendering on every other source mode switch 2026-06-19 11:40:57 +02:00
Yuri Karamian 1681fade3b Fix editor not rendering on every other source mode switch 2026-06-19 11:38:40 +02:00
Yuri Karamian 4f324ad682 Fix pasted images disappearing when switching to source mode (#87) 2026-06-19 11:31:49 +02:00
Yuri Karamian c1a9871703 Fix pasted images disappearing when switching to source mode (#87) 2026-06-19 11:30:07 +02:00
Yuri Karamian 83390f5ed2 Fix images not rendering when switching back from source mode 2026-06-19 11:27:38 +02:00
Yuri Karamian 5bf6d8063e Fix images not rendering when switching back from source mode 2026-06-19 11:25:45 +02:00
Yuri Karamian a1913558b9 Fix pasted images disappearing when switching to source mode (#87) 2026-06-19 11:18:06 +02:00
Yuri Karamian 93e96829f4 Add setting to toggle link arrows (#128) 2026-06-19 11:06:49 +02:00
Yuri Karamian 11673bd8c4 Fix Android crash when swiping back with modal open (#90) 2026-06-19 10:47:39 +02:00
lokthare 4f4e2854a6 Update flake.nix / fix cargoHash (#136)
I wanted to try HelixNotes, I pulled the main branch but it failed to build with `nix build`.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/136
2026-06-19 09:54:58 +02:00
Yuri Karamian 856ac94a76 Centralize darkThemes list, fix dark themes reverting to light on restart 2026-06-18 13:50:33 +02:00
MF 28263de53d Improve notebook path creation (#135)
Backspace on an empty sub-notebook field returns to top-level creation, and top-level names like Parent/Child now create nested notebooks in one action. Validated with pnpm build.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/135
2026-06-18 13:40:41 +02:00
blake b6e855ce3e Accent colors now change automatically when a user selects a theme. Also added a One Dark theme. (#130)
WIP

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/130
2026-06-18 13:27:03 +02:00
MF 51148efe2e Focus notebook name after sidebar double-click (#134)
Double-clicking empty sidebar space now opens the new-notebook field and focuses it, matching the + button flow.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/134
2026-06-18 13:24:15 +02:00
Yuri Karamian 32e056dc24 Fix heading submenu clipped in context menu, flip on narrow screens (#113) 2026-06-18 13:20:35 +02:00
Yuri Karamian c14ad6387d Fix heading submenu clipped in context menu (#113) 2026-06-18 13:16:43 +02:00
36 changed files with 4301 additions and 597 deletions
+15 -7
View File
@@ -1,7 +1,7 @@
# HelixNotes
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](https://codeberg.org/ArkHost/HelixNotes/src/branch/main/LICENSE)
[![Latest Release](https://img.shields.io/badge/release-v1.3.1-green)](https://codeberg.org/ArkHost/HelixNotes/releases)
[![Latest Release](https://img.shields.io/badge/release-v1.3.2-green)](https://codeberg.org/ArkHost/HelixNotes/releases)
[![Website](https://img.shields.io/badge/web-helixnotes.com-purple)](https://helixnotes.com)
[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20Windows%20%7C%20macOS%20%7C%20Android-lightgrey)]()
@@ -10,7 +10,7 @@ A local markdown note-taking app built with Tauri, SvelteKit, and Rust.
Your notes are stored as standard Markdown files on your local filesystem.
No cloud, no lock-in.
## Download (v1.3.1)
## Download (v1.3.2)
### Linux
@@ -92,23 +92,31 @@ sudo eopkg it helixnotes
#### AppImage (Arch, Fedora 43+, openSUSE Tumbleweed)
[Download AppImage](https://download.helixnotes.com/releases/v1.3.1/HelixNotes_1.3.1_amd64.AppImage)
[Download AppImage](https://download.helixnotes.com/releases/v1.3.2/HelixNotes_1.3.2_amd64.AppImage)
#### .deb (manual)
[Download .deb](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.1/HelixNotes_1.3.1_amd64.deb) (Ubuntu 22.04+)
[Download .deb](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_amd64.deb) (Ubuntu 22.04+)
### Windows
[Download Installer](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.1/HelixNotes_1.3.1_x64-setup.exe) (Windows 10/11)
[Download Installer](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_x64-setup.exe) (Windows 10/11)
### macOS
[Download .dmg](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.1/HelixNotes_1.3.1_x64.dmg) (Intel, runs on Apple Silicon via Rosetta)
[Download .dmg (Apple Silicon)](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_aarch64.dmg) (M-series Macs)
[Download .dmg (Intel)](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_x64.dmg) (older Macs, or Apple Silicon via Rosetta)
> **"HelixNotes is damaged and can't be opened"?** The app isn't damaged. The macOS build isn't notarized by Apple yet, so Gatekeeper blocks it on Apple Silicon. Run this once in Terminal, then open it normally (you'll need to redo it after each update):
>
> ```bash
> xattr -cr /Applications/HelixNotes.app
> ```
### Android
[Download APK](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.1/HelixNotes_1.3.1_android.apk)
[Download APK](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_android.apk)
---
+1 -1
View File
@@ -22,7 +22,7 @@
inherit pname version;
src = ./.;
cargoHash = "sha256-QF4HMYBjrxCBiq6PcsNy+kEOq/j+3zDzlcT5dy7MtQk=";
cargoHash = "sha256-3ihGgdU/1WFa3aOeEi5AcwTFIyGQgxT7Ad0uVuFYB+4=";
pnpmDeps = pkgs.fetchPnpmDeps {
inherit pname version;
+2 -1
View File
@@ -2,7 +2,7 @@
"name": "helixnotes",
"private": true,
"license": "AGPL-3.0-or-later",
"version": "1.3.1",
"version": "1.3.3",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -59,6 +59,7 @@
"@tiptap/starter-kit": "^3.19.0",
"@types/katex": "^0.16.8",
"@types/markdown-it": "^14.1.2",
"highlight.js": "^11.11.1",
"katex": "^0.16.28",
"lowlight": "^3.3.0",
"markdown-it": "^14.1.0",
+3
View File
@@ -95,6 +95,9 @@ importers:
'@types/markdown-it':
specifier: ^14.1.2
version: 14.1.2
highlight.js:
specifier: ^11.11.1
version: 11.11.1
katex:
specifier: ^0.16.28
version: 0.16.28
+1 -1
View File
@@ -1850,7 +1850,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "helixnotes"
version = "1.3.1"
version = "1.3.3"
dependencies = [
"arboard",
"chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "helixnotes"
version = "1.3.1"
version = "1.3.3"
description = "Local markdown note-taking app"
authors = ["HelixNotes"]
license = "AGPL-3.0-or-later"
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" ry="112" fill="#626ED4"/>
<line x1="128" y1="128" x2="384" y2="384" stroke="#ffffff" stroke-width="8" stroke-opacity="0.5" stroke-linecap="round"/>
<line x1="384" y1="128" x2="128" y2="384" stroke="#ffffff" stroke-width="8" stroke-opacity="0.5" stroke-linecap="round"/>
<circle cx="128" cy="128" r="36" fill="#ffffff"/>
<circle cx="384" cy="128" r="36" fill="#ffffff"/>
<circle cx="128" cy="384" r="36" fill="#ffffff"/>
<circle cx="384" cy="384" r="36" fill="#ffffff"/>
</svg>

After

Width:  |  Height:  |  Size: 633 B

+21
View File
@@ -0,0 +1,21 @@
{
"themes": [
{
"colors": {
"bg_active": "#373a52",
"bg_editor": "#1a1b26",
"bg_hover": "#2f3145",
"bg_primary": "#1a1b26",
"bg_secondary": "#1f2029",
"bg_tertiary": "#2a2b3d",
"border_color": "#2f3145",
"text_primary": "#c8cde4",
"text_secondary": "#6b7094"
},
"id": "custom-1782146306429",
"is_dark": true,
"name": "My theme"
}
],
"version": 1
}
+223 -94
View File
@@ -43,6 +43,7 @@ pub fn open_vault(app: AppHandle, state: State<'_, AppState>, path: String) -> R
config.vaults.push(VaultConfig {
path: path.clone(),
name,
..Default::default()
});
}
config.active_vault = Some(path);
@@ -90,6 +91,58 @@ pub fn set_accent_color(state: State<'_, AppState>, color: String) -> Result<(),
Ok(())
}
#[tauri::command]
pub fn save_custom_theme(state: State<'_, AppState>, theme: crate::types::CustomTheme) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
if let Some(pos) = config.custom_themes.iter().position(|t| t.id == theme.id) {
config.custom_themes[pos] = theme;
} else {
config.custom_themes.push(theme);
}
save_app_config(&config)?;
Ok(())
}
#[tauri::command]
pub fn delete_custom_theme(state: State<'_, AppState>, id: String) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
config.custom_themes.retain(|t| t.id != id);
if config.theme == id {
config.theme = "system".to_string();
}
save_app_config(&config)?;
Ok(())
}
#[tauri::command]
pub fn export_custom_theme(state: State<'_, AppState>, id: String, path: String) -> Result<(), String> {
let config = state.config.lock().map_err(|e| e.to_string())?;
let theme = config.custom_themes.iter().find(|t| t.id == id)
.ok_or_else(|| "Theme not found".to_string())?;
let export = serde_json::json!({ "version": 1, "themes": [theme] });
let data = serde_json::to_string_pretty(&export).map_err(|e| e.to_string())?;
std::fs::write(&path, data).map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub fn import_custom_themes(state: State<'_, AppState>, path: String) -> Result<Vec<crate::types::CustomTheme>, String> {
let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
let parsed: serde_json::Value = serde_json::from_str(&data).map_err(|e| e.to_string())?;
let themes: Vec<crate::types::CustomTheme> = serde_json::from_value(parsed["themes"].clone())
.map_err(|e| format!("Invalid theme file: {}", e))?;
let mut config = state.config.lock().map_err(|e| e.to_string())?;
for theme in &themes {
if let Some(pos) = config.custom_themes.iter().position(|t| t.id == theme.id) {
config.custom_themes[pos] = theme.clone();
} else {
config.custom_themes.push(theme.clone());
}
}
save_app_config(&config)?;
Ok(themes)
}
#[tauri::command]
pub fn set_font_size(state: State<'_, AppState>, size: u32) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
@@ -122,6 +175,14 @@ pub fn set_ui_scale(state: State<'_, AppState>, scale: f64) -> Result<(), String
Ok(())
}
#[tauri::command]
pub fn set_content_width(state: State<'_, AppState>, width: Option<u32>) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
config.content_width = width;
save_app_config(&config)?;
Ok(())
}
// ── Notebooks ──
#[tauri::command]
@@ -604,6 +665,7 @@ fn extract_title_fast(raw: &str) -> Option<String> {
#[tauri::command]
pub fn get_tasks(state: State<'_, AppState>) -> Result<Vec<crate::types::TaskItem>, String> {
use rayon::prelude::*;
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
let vault = std::path::Path::new(vault_path);
@@ -613,57 +675,57 @@ pub fn get_tasks(state: State<'_, AppState>) -> Result<Vec<crate::types::TaskIte
let due_re = regex::Regex::new(r"\bdue:(\d{4}-\d{2}-\d{2})\b").unwrap();
let prio_re = regex::Regex::new(r"(?i)(?:^|\s)!(high|medium|med|low)\b").unwrap();
let mut tasks = Vec::new();
for entry in walkdir::WalkDir::new(vault)
let paths: Vec<std::path::PathBuf> = walkdir::WalkDir::new(vault)
.into_iter()
.filter_entry(|e| !operations::is_hidden(e.path()) && !e.path().starts_with(&hn_dir))
.filter_map(|e| e.ok())
{
let path = entry.path();
if !path.is_file() {
continue;
}
if path.extension().and_then(|e| e.to_str()) != Some("md") {
continue;
}
let raw = match std::fs::read_to_string(path) {
Ok(r) => r,
Err(_) => continue,
};
let filename = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let (meta, body) = crate::vault::frontmatter::parse_note(&raw, &filename);
let note_path = path.to_string_lossy().to_string();
.filter(|e| {
e.file_type().is_file() && e.path().extension().and_then(|x| x.to_str()) == Some("md")
})
.map(|e| e.into_path())
.collect();
for (i, line) in body.lines().enumerate() {
let caps = match task_re.captures(line) {
Some(c) => c,
None => continue,
// Read and parse each note in parallel; on Android every read_to_string is a FUSE round-trip.
let tasks: Vec<crate::types::TaskItem> = paths
.par_iter()
.flat_map(|path| {
let mut out: Vec<crate::types::TaskItem> = Vec::new();
let raw = match std::fs::read_to_string(path) {
Ok(r) => r,
Err(_) => return out,
};
let completed = !caps[1].trim().is_empty(); // 'x'/'X' completed, ' ' open
let content = caps[2].to_string();
let due = due_re.captures(&content).map(|c| c[1].to_string());
let priority = prio_re.captures(&content).map(|c| {
let p = c[1].to_lowercase();
if p == "medium" { "med".to_string() } else { p }
});
// Strip metadata tokens for the display text, then collapse whitespace.
let mut text = due_re.replace_all(&content, "").to_string();
text = prio_re.replace_all(&text, " ").to_string();
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
tasks.push(crate::types::TaskItem {
note_path: note_path.clone(),
note_title: meta.title.clone(),
line: i,
raw_line: line.to_string(),
text,
completed,
due,
priority,
});
}
}
let filename = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let (meta, body) = crate::vault::frontmatter::parse_note(&raw, &filename);
let note_path = path.to_string_lossy().to_string();
for (i, line) in body.lines().enumerate() {
let caps = match task_re.captures(line) {
Some(c) => c,
None => continue,
};
let completed = !caps[1].trim().is_empty();
let content = caps[2].to_string();
let due = due_re.captures(&content).map(|c| c[1].to_string());
let priority = prio_re.captures(&content).map(|c| {
let p = c[1].to_lowercase();
if p == "medium" { "med".to_string() } else { p }
});
let mut text = due_re.replace_all(&content, "").to_string();
text = prio_re.replace_all(&text, " ").to_string();
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
out.push(crate::types::TaskItem {
note_path: note_path.clone(),
note_title: meta.title.clone(),
line: i,
raw_line: line.to_string(),
text,
completed,
due,
priority,
});
}
out
})
.collect();
Ok(tasks)
}
@@ -1087,17 +1149,28 @@ pub fn set_general_settings(
title_mode: String,
hide_title_in_body: bool,
show_line_numbers: bool,
show_link_arrows: bool,
default_view_mode: bool,
show_tray_icon: bool,
close_to_tray: bool,
enable_wiki_links: bool,
show_note_dates: bool,
restore_last_session: bool,
show_all_notes: bool,
show_quick_access: bool,
show_tasks: bool,
show_daily_notes: bool,
show_trash: bool,
) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
config.compact_notes = compact_notes;
config.show_note_dates = show_note_dates;
config.restore_last_session = restore_last_session;
config.show_all_notes = show_all_notes;
config.show_quick_access = show_quick_access;
config.show_tasks = show_tasks;
config.show_daily_notes = show_daily_notes;
config.show_trash = show_trash;
config.time_format = time_format;
config.week_start = week_start;
config.daily_title_format = daily_title_format;
@@ -1108,6 +1181,7 @@ pub fn set_general_settings(
config.title_mode = title_mode;
config.hide_title_in_body = hide_title_in_body;
config.show_line_numbers = show_line_numbers;
config.show_link_arrows = show_link_arrows;
config.default_view_mode = default_view_mode;
config.show_tray_icon = show_tray_icon;
config.close_to_tray = close_to_tray;
@@ -1151,41 +1225,38 @@ pub fn reorder_quick_access(state: State<'_, AppState>, paths: Vec<String>) -> R
#[tauri::command]
pub fn get_vault_stats(state: State<'_, AppState>) -> Result<VaultStats, String> {
use rayon::prelude::*;
let config = state.config.lock().map_err(|e| e.to_string())?;
let vault_path = config.active_vault.as_ref().ok_or("No active vault")?;
let mut total_notes: u64 = 0;
let mut total_attachments: u64 = 0;
let mut notes_size: u64 = 0;
let mut attachments_size: u64 = 0;
for entry in walkdir::WalkDir::new(vault_path)
let paths: Vec<std::path::PathBuf> = walkdir::WalkDir::new(vault_path)
.into_iter()
.filter_map(|e| e.ok())
{
let path = entry.path();
if !path.is_file() {
continue;
}
let path_str = path.to_string_lossy();
// Include .helixnotes/attachments, skip everything else in .helixnotes
if path_str.contains("/.helixnotes/") && !path_str.contains("/.helixnotes/attachments/") {
continue;
}
// Skip trash
if path_str.contains("/.trash/") {
continue;
}
let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext == "md" {
total_notes += 1;
notes_size += size;
} else {
total_attachments += 1;
attachments_size += size;
}
}
.filter(|e| e.file_type().is_file())
.map(|e| e.into_path())
.filter(|p| {
// attachments under .helixnotes count; nothing else in .helixnotes or .trash does
let s = p.to_string_lossy();
!(s.contains("/.helixnotes/") && !s.contains("/.helixnotes/attachments/"))
&& !s.contains("/.trash/")
})
.collect();
// Stat files in parallel; each metadata() is a FUSE round-trip on Android.
let (total_notes, total_attachments, notes_size, attachments_size) = paths
.par_iter()
.map(|path| {
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
if path.extension().and_then(|e| e.to_str()) == Some("md") {
(1u64, 0u64, size, 0u64)
} else {
(0u64, 1u64, 0u64, size)
}
})
.reduce(
|| (0u64, 0u64, 0u64, 0u64),
|a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3),
);
Ok(VaultStats {
total_notes,
@@ -1668,9 +1739,9 @@ pub struct OrphanAttachment {
// Conservatively find files in .helixnotes/attachments not referenced by ANY note. Scans every
// .md in the vault (including .helixnotes/trash, so a restorable trashed note keeps its files)
// and matches each filename against both the raw note text and a percent-decoded copy (so a
// URL-encoded path like `my%20file.png` still counts as a reference). When in doubt a file is
// KEPT: a leftover orphan is harmless, a wrong deletion is not.
// plus notebook_icons.json, and matches each filename against both the raw text and a
// percent-decoded copy (so a URL-encoded path like `my%20file.png` still counts as a reference).
// When in doubt a file is KEPT: a leftover orphan is harmless, a wrong deletion is not.
fn scan_orphaned_attachments(vault: &str) -> Result<Vec<(String, u64)>, String> {
let attachments_dir = operations::helixnotes_dir(vault).join("attachments");
if !attachments_dir.is_dir() {
@@ -1699,6 +1770,12 @@ fn scan_orphaned_attachments(vault: &str) -> Result<Vec<(String, u64)>, String>
}
}
}
// Folder icons live in attachments but are referenced here, not in notes. (#157)
let icons_path = operations::helixnotes_dir(vault).join("notebook_icons.json");
if let Ok(content) = std::fs::read_to_string(&icons_path) {
haystack.push_str(&content);
haystack.push('\n');
}
let decoded = percent_decode(&haystack);
let orphans = files
.into_iter()
@@ -2124,19 +2201,29 @@ pub fn test_ai_connection(app: AppHandle) -> Result<(), String> {
// ── Sync (WebDAV) ──
fn active_vault_config(config: &AppConfig) -> Result<&VaultConfig, String> {
let active = config.active_vault.as_deref().ok_or("No active vault")?;
config
.vaults
.iter()
.find(|v| v.path == active)
.ok_or_else(|| "Active vault not found in config".to_string())
}
fn sync_config_from(config: &AppConfig) -> Result<crate::sync::WebdavConfig, String> {
if config.sync_provider.as_deref() != Some("webdav") {
let v = active_vault_config(config)?;
if v.sync_provider.as_deref() != Some("webdav") {
return Err("Sync is not configured".to_string());
}
let url = config
let url = v
.webdav_url
.clone()
.filter(|u| !u.trim().is_empty())
.ok_or("WebDAV URL is not set")?;
Ok(crate::sync::WebdavConfig {
url,
username: config.webdav_username.clone().unwrap_or_default(),
password: config.webdav_password.clone().unwrap_or_default(),
username: v.webdav_username.clone().unwrap_or_default(),
password: v.webdav_password.clone().unwrap_or_default(),
})
}
@@ -2152,13 +2239,19 @@ pub fn set_sync_settings(
sync_interval_minutes: u32,
) -> Result<(), String> {
let mut config = state.config.lock().map_err(|e| e.to_string())?;
config.sync_provider = provider.filter(|p| !p.is_empty());
config.webdav_url = url.filter(|u| !u.trim().is_empty());
config.webdav_username = username.filter(|u| !u.is_empty());
config.webdav_password = password.filter(|p| !p.is_empty());
config.sync_on_open = sync_on_open;
config.sync_on_change = sync_on_change;
config.sync_interval_minutes = sync_interval_minutes;
let active = config.active_vault.clone().ok_or("No active vault")?;
let v = config
.vaults
.iter_mut()
.find(|v| v.path == active)
.ok_or_else(|| "Active vault not found in config".to_string())?;
v.sync_provider = provider.filter(|p| !p.is_empty());
v.webdav_url = url.filter(|u| !u.trim().is_empty());
v.webdav_username = username.filter(|u| !u.is_empty());
v.webdav_password = password.filter(|p| !p.is_empty());
v.sync_on_open = sync_on_open;
v.sync_on_change = sync_on_change;
v.sync_interval_minutes = sync_interval_minutes;
save_app_config(&config)?;
Ok(())
}
@@ -2222,13 +2315,15 @@ pub fn sync_now(app: AppHandle) -> Result<(), String> {
};
std::thread::spawn(move || {
use tauri::Emitter;
let result = crate::sync::run_sync(app.clone(), vault, cfg);
let result = crate::sync::run_sync(app.clone(), vault.clone(), cfg);
app.state::<AppState>().syncing.store(false, Ordering::SeqCst);
match result {
Ok(summary) => {
let ts = chrono::Utc::now().to_rfc3339();
if let Ok(mut config) = app.state::<AppState>().config.lock() {
config.last_sync_time = Some(ts.clone());
if let Some(v) = config.vaults.iter_mut().find(|v| v.path == vault) {
v.last_sync_time = Some(ts.clone());
}
let _ = save_app_config(&config);
}
let _ = app.emit(
@@ -2348,11 +2443,45 @@ fn app_config_path() -> Result<std::path::PathBuf, String> {
}
pub fn load_app_config() -> AppConfig {
app_config_path()
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())
.unwrap_or_default()
.unwrap_or_default();
if migrate_global_sync_to_vault(&mut config) {
let _ = save_app_config(&config);
}
config
}
// 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.
fn migrate_global_sync_to_vault(config: &mut AppConfig) -> bool {
if config.sync_provider.is_none() && config.webdav_url.is_none() {
return false;
}
let Some(active) = config.active_vault.clone() 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 Some(v) = config.vaults.iter_mut().find(|v| v.path == active) else { return false; };
if v.sync_provider.is_some() || v.webdav_url.is_some() {
return false; // already migrated / has its own config
}
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
}
fn save_app_config(config: &AppConfig) -> Result<(), String> {
+19
View File
@@ -38,7 +38,21 @@ pub fn run() {
let close_to_tray = config.close_to_tray && show_tray;
let app_state = AppState::new(config);
// Inject the compile-time platform so the frontend never sniffs the (sometimes
// mobile-looking) WebKitGTK user-agent. (#63)
let platform_init = format!(
"window.__HELIX_PLATFORM__={{mobile:{},android:{},ios:{}}};",
cfg!(mobile),
cfg!(target_os = "android"),
cfg!(target_os = "ios"),
);
let mut builder = tauri::Builder::default()
.plugin(
tauri::plugin::Builder::<tauri::Wry>::new("helix-platform")
.js_init_script(platform_init)
.build(),
)
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_opener::init())
@@ -102,10 +116,15 @@ pub fn run() {
commands::get_app_config,
commands::set_theme,
commands::set_accent_color,
commands::save_custom_theme,
commands::delete_custom_theme,
commands::export_custom_theme,
commands::import_custom_themes,
commands::set_font_size,
commands::set_font_family,
commands::set_line_height,
commands::set_ui_scale,
commands::set_content_width,
commands::get_notebooks,
commands::count_root_notes,
commands::create_notebook,
+26 -11
View File
@@ -339,14 +339,29 @@ impl WebdavClient {
Ok(())
}
fn put_with_dirs(
/// Read a file's authoritative remote etag via a Depth-0 PROPFIND. The PUT-response
/// etag is unreliable across WebDAV servers (some omit it, some differ in format from
/// the getetag PROPFIND returns), so we always source the manifest etag from PROPFIND
/// to keep it consistent with future listings. (issue #147)
fn etag_for(&self, relpath: &str) -> String {
self.propfind(relpath, "0")
.ok()
.and_then(|es| es.into_iter().find(|e| !e.is_dir).map(|e| e.etag))
.unwrap_or_default()
}
/// PUT a file (creating parent collections first), then read back its authoritative
/// etag via PROPFIND. Returns the PROPFIND etag (empty if the server exposes no
/// getetag), NOT the PUT-response etag, which is unreliable across servers. (issue #147)
fn upload(
&self,
relpath: &str,
bytes: &[u8],
created: &mut HashSet<String>,
) -> Result<Option<String>, String> {
) -> Result<String, String> {
self.ensure_dirs(relpath, created)?;
self.put(relpath, bytes)
self.put(relpath, bytes)?; // PUT-response etag intentionally discarded
Ok(self.etag_for(relpath))
}
}
@@ -511,12 +526,12 @@ fn apply_changes(
);
} else if local_changed && !remote_changed {
let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?;
let etag = client.put_with_dirs(key, &bytes, &mut created)?;
let etag = client.upload(key, &bytes, &mut created)?;
new_m.files.insert(
key.clone(),
ManifestEntry {
local_hash: lf.hash.clone(),
remote_etag: etag.unwrap_or_else(|| re.clone()),
remote_etag: etag,
},
);
sum.uploaded += 1;
@@ -556,12 +571,12 @@ fn apply_changes(
);
let ckey = conflict_relpath(key, &stamp);
write_local(vault_path, &ckey, &lbytes)?;
let cetag = client.put_with_dirs(&ckey, &lbytes, &mut created)?;
let cetag = client.upload(&ckey, &lbytes, &mut created)?;
new_m.files.insert(
ckey,
ManifestEntry {
local_hash: sha256_hex(&lbytes),
remote_etag: cetag.unwrap_or_default(),
remote_etag: cetag,
},
);
sum.conflicts += 1;
@@ -572,12 +587,12 @@ fn apply_changes(
None => {
// new local -> upload
let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?;
let etag = client.put_with_dirs(key, &bytes, &mut created)?;
let etag = client.upload(key, &bytes, &mut created)?;
new_m.files.insert(
key.clone(),
ManifestEntry {
local_hash: lf.hash.clone(),
remote_etag: etag.unwrap_or_default(),
remote_etag: etag,
},
);
sum.uploaded += 1;
@@ -586,12 +601,12 @@ fn apply_changes(
if me.local_hash != lf.hash {
// remote deleted but local edited -> resurrect (upload)
let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?;
let etag = client.put_with_dirs(key, &bytes, &mut created)?;
let etag = client.upload(key, &bytes, &mut created)?;
new_m.files.insert(
key.clone(),
ManifestEntry {
local_hash: lf.hash.clone(),
remote_etag: etag.unwrap_or_default(),
remote_etag: etag,
},
);
sum.uploaded += 1;
+77 -2
View File
@@ -50,10 +50,48 @@ pub struct NoteContent {
pub raw: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VaultConfig {
pub path: String,
pub name: String,
// Per-vault WebDAV sync (was previously global on AppConfig; those fields are kept deprecated for migration).
#[serde(default)]
pub sync_provider: Option<String>,
#[serde(default)]
pub webdav_url: Option<String>,
#[serde(default)]
pub webdav_username: Option<String>,
#[serde(default)]
pub webdav_password: Option<String>,
#[serde(default)]
pub sync_on_open: bool,
#[serde(default)]
pub sync_on_change: bool,
#[serde(default)]
pub sync_interval_minutes: u32,
#[serde(default)]
pub last_sync_time: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomThemeColors {
pub bg_primary: String,
pub bg_secondary: String,
pub bg_tertiary: String,
pub bg_hover: String,
pub bg_active: String,
pub bg_editor: String,
pub text_primary: String,
pub text_secondary: String,
pub border_color: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomTheme {
pub id: String,
pub name: String,
pub is_dark: bool,
pub colors: CustomThemeColors,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -72,6 +110,8 @@ pub struct AppConfig {
#[serde(default)]
pub ui_scale: Option<f64>,
#[serde(default)]
pub content_width: Option<u32>,
#[serde(default)]
pub compact_notes: bool,
#[serde(default = "default_true")]
pub show_note_dates: bool,
@@ -95,6 +135,18 @@ pub struct AppConfig {
pub hide_title_in_body: bool,
#[serde(default)]
pub show_line_numbers: bool,
#[serde(default = "default_true")]
pub show_link_arrows: bool,
#[serde(default = "default_true")]
pub show_all_notes: bool,
#[serde(default = "default_true")]
pub show_quick_access: bool,
#[serde(default = "default_true")]
pub show_tasks: bool,
#[serde(default = "default_true")]
pub show_daily_notes: bool,
#[serde(default = "default_true")]
pub show_trash: bool,
#[serde(default)]
pub backup_enabled: bool,
#[serde(default = "default_backup_frequency")]
@@ -137,7 +189,7 @@ pub struct AppConfig {
pub enable_wiki_links: bool,
#[serde(default)]
pub restore_last_session: bool,
// WebDAV sync (opt-in; all off by default). Endpoint is fully user-configured.
// DEPRECATED: WebDAV sync moved to per-vault VaultConfig. Kept for one release to migrate old configs.
#[serde(default)]
pub sync_provider: Option<String>,
#[serde(default)]
@@ -154,12 +206,18 @@ pub struct AppConfig {
pub sync_interval_minutes: u32,
#[serde(default)]
pub last_sync_time: Option<String>,
#[serde(default)]
pub custom_themes: Vec<CustomTheme>,
}
fn default_true() -> bool {
true
}
fn default_outline_width() -> f64 {
220.0
}
fn default_pdf_height() -> u32 {
600
}
@@ -203,6 +261,7 @@ impl Default for AppConfig {
font_family: None,
line_height: None,
ui_scale: None,
content_width: None,
compact_notes: false,
show_note_dates: true,
time_format: "relative".to_string(),
@@ -215,6 +274,12 @@ impl Default for AppConfig {
title_mode: "input".to_string(),
hide_title_in_body: false,
show_line_numbers: false,
show_link_arrows: true,
show_all_notes: true,
show_quick_access: true,
show_tasks: true,
show_daily_notes: true,
show_trash: true,
backup_enabled: false,
backup_frequency: "24h".to_string(),
backup_max_count: 10,
@@ -244,6 +309,7 @@ impl Default for AppConfig {
sync_on_change: false,
sync_interval_minutes: 0,
last_sync_time: None,
custom_themes: Vec::new(),
}
}
}
@@ -253,14 +319,20 @@ pub struct VaultState {
pub last_open_note: Option<String>,
pub sidebar_width: f64,
pub notelist_width: f64,
#[serde(default = "default_outline_width")]
pub outline_width: f64,
pub sidebar_collapsed: bool,
#[serde(default)]
pub notelist_collapsed: bool,
#[serde(default)]
pub collapsed_notebooks: Vec<String>,
#[serde(default)]
pub notebook_sort_mode: String,
#[serde(default)]
pub notebook_order: std::collections::HashMap<String, i32>,
#[serde(default)]
pub note_order: std::collections::HashMap<String, i32>,
#[serde(default)]
pub sort_mode: String,
#[serde(default)]
pub last_view_mode: String,
@@ -284,10 +356,13 @@ impl Default for VaultState {
last_open_note: None,
sidebar_width: 220.0,
notelist_width: 280.0,
outline_width: default_outline_width(),
sidebar_collapsed: false,
notelist_collapsed: false,
collapsed_notebooks: Vec::new(),
notebook_sort_mode: String::new(),
notebook_order: std::collections::HashMap::new(),
note_order: std::collections::HashMap::new(),
sort_mode: String::new(),
last_view_mode: String::new(),
last_notebook: None,
+87 -80
View File
@@ -52,11 +52,10 @@ pub fn scan_notebooks(vault_path: &str) -> Result<Vec<NotebookEntry>, String> {
}
fn scan_dir_recursive(dir: &Path, vault_root: &str) -> Vec<NotebookEntry> {
let mut entries = Vec::new();
let root = Path::new(vault_root);
let Ok(read_dir) = fs::read_dir(dir) else {
return entries;
return Vec::new();
};
// Collect subdirs (root level only lists directories, note counts come from scan_dir_with_count)
@@ -76,29 +75,29 @@ fn scan_dir_recursive(dir: &Path, vault_root: &str) -> Vec<NotebookEntry> {
.cmp(&b.file_name().to_string_lossy().to_lowercase())
});
// Store note_count for the parent directory (used when this is the top-level call)
// Each directory pushes its own entry with its own note_count
for dir_entry in dirs {
let path = dir_entry.path();
let name = dir_entry.file_name().to_string_lossy().to_string();
let relative = path
.strip_prefix(root)
.unwrap_or(&path)
.to_string_lossy()
.to_string();
let (children, child_note_count) = scan_dir_with_count(&path, vault_root);
entries.push(NotebookEntry {
name,
path: path.to_string_lossy().to_string(),
relative_path: relative,
children,
note_count: child_note_count,
});
}
entries
// Scan sibling notebooks in parallel: each subtree is independent, so
// overlapping the per-directory read_dir calls hides FUSE latency on Android.
// par_iter().collect() preserves the (already-sorted) order.
let paths: Vec<PathBuf> = dirs.iter().map(|e| e.path()).collect();
paths
.par_iter()
.map(|path| {
let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let relative = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
let (children, child_note_count) = scan_dir_with_count(path, vault_root);
NotebookEntry {
name,
path: path.to_string_lossy().to_string(),
relative_path: relative,
children,
note_count: child_note_count,
}
})
.collect()
}
/// Combined scan: returns (children, note_count) in a single read_dir pass.
@@ -130,26 +129,26 @@ fn scan_dir_with_count(dir: &Path, vault_root: &str) -> (Vec<NotebookEntry>, usi
.cmp(&b.file_name().to_string_lossy().to_lowercase())
});
let mut entries = Vec::new();
for dir_entry in subdirs {
let path = dir_entry.path();
let name = dir_entry.file_name().to_string_lossy().to_string();
let relative = path
.strip_prefix(root)
.unwrap_or(&path)
.to_string_lossy()
.to_string();
let (children, child_note_count) = scan_dir_with_count(&path, vault_root);
entries.push(NotebookEntry {
name,
path: path.to_string_lossy().to_string(),
relative_path: relative,
children,
note_count: child_note_count,
});
}
let paths: Vec<PathBuf> = subdirs.iter().map(|e| e.path()).collect();
let entries: Vec<NotebookEntry> = paths
.par_iter()
.map(|path| {
let name = path.file_name().unwrap_or_default().to_string_lossy().to_string();
let relative = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
let (children, child_note_count) = scan_dir_with_count(path, vault_root);
NotebookEntry {
name,
path: path.to_string_lossy().to_string(),
relative_path: relative,
children,
note_count: child_note_count,
}
})
.collect();
(entries, note_count)
}
@@ -197,47 +196,36 @@ pub fn scan_notes(vault_path: &str, notebook_path: Option<&str>) -> Result<Vec<N
// On mobile, use metadata-only scan (no file reads) for fast listing on sandboxed FS
#[cfg(mobile)]
{
let mut notes = Vec::new();
// Log what read_dir sees
if let Ok(rd) = fs::read_dir(root) {
let items: Vec<_> = rd.filter_map(|e| e.ok()).collect();
log::info!("scan_notes: read_dir found {} entries in {:?}", items.len(), root);
for (i, entry) in items.iter().enumerate().take(5) {
let ft = entry.file_type().map(|ft| if ft.is_file() { "file" } else if ft.is_dir() { "dir" } else { "other" }).unwrap_or("err");
log::info!(" [{}] {:?} type={}", i, entry.file_name(), ft);
}
} else {
log::info!("scan_notes: read_dir FAILED for {:?}", root);
}
if notebook_path.is_some() {
if let Ok(rd) = fs::read_dir(root) {
for entry in rd.filter_map(|e| e.ok()) {
let is_file = entry.file_type().map(|ft| ft.is_file()).unwrap_or(false);
if is_file && entry.path().extension().and_then(|x| x.to_str()) == Some("md") {
if let Ok(note) = read_note_entry_metadata_only(&entry.path(), vault_root) {
notes.push(note);
}
}
}
// Collect candidate .md paths first, then read their metadata in parallel.
// Overlapping the per-file reads hides FUSE latency on Android (matches the
// desktop path below). The previous version also did an extra read_dir purely
// for debug logging, which doubled the directory I/O on the sandboxed FS.
let paths: Vec<PathBuf> = if notebook_path.is_some() {
match fs::read_dir(root) {
Ok(rd) => rd
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("md"))
.collect(),
Err(_) => Vec::new(),
}
} else {
let hn_dir = helixnotes_dir(vault_path);
for entry in WalkDir::new(root)
WalkDir::new(root)
.into_iter()
// filter_entry skips descending into hidden dirs (unlike filter)
.filter_entry(|e| !is_hidden(e.path()) && !e.path().starts_with(&hn_dir))
.filter_map(|e| e.ok())
.filter(|e| {
e.file_type().is_file()
&& e.path().extension().and_then(|x| x.to_str()) == Some("md")
})
{
if let Ok(note) = read_note_entry_metadata_only(entry.path(), vault_root) {
notes.push(note);
}
}
}
.map(|e| e.path().to_path_buf())
.filter(|p| p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("md"))
.collect()
};
let mut notes: Vec<NoteEntry> = paths
.par_iter()
.filter_map(|path| read_note_entry_metadata_only(path, vault_root).ok())
.collect();
log::info!("scan_notes: mobile scan found {} notes", notes.len());
notes.sort_by(|a, b| b.meta.modified.cmp(&a.meta.modified));
return Ok(notes);
@@ -386,7 +374,26 @@ pub fn read_note(path: &str) -> Result<NoteContent, String> {
.to_string_lossy()
.to_string();
let (meta, content) = frontmatter::parse_note(&raw, &filename);
let (mut meta, content) = frontmatter::parse_note(&raw, &filename);
// Fall back to filesystem times when the frontmatter has no created/modified, matching the
// note-list scan (read_note_entry_from_str). Without this, a missing `created:` defaults to
// Utc::now() here and then gets written to disk on the next save (e.g. a title change),
// resetting the create date of imported/frontmatter-less notes. (issue #139)
let has_created = raw.contains("\ncreated:") || raw.starts_with("created:");
let has_modified = raw.contains("\nmodified:") || raw.starts_with("modified:");
if let Ok(fs_meta) = fs::metadata(p) {
if !has_modified {
if let Ok(modified) = fs_meta.modified() {
meta.modified = modified.into();
}
}
if !has_created {
if let Ok(created) = fs_meta.created() {
meta.created = created.into();
}
}
}
Ok(NoteContent {
path: path.to_string(),
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "HelixNotes",
"version": "1.3.1",
"version": "1.3.3",
"identifier": "com.helixnotes.app",
"build": {
"frontendDist": "../build",
+54
View File
@@ -173,6 +173,21 @@
--danger-hover: #d43d3d;
--success: #40c057;
--warning: #fab005;
/* Obsidian-style callout accent hues (RGB triplets; mixed with the background via opacity, so one set works on every theme) */
--callout-note: 68, 138, 255;
--callout-abstract: 0, 191, 188;
--callout-info: 0, 184, 212;
--callout-todo: 0, 184, 212;
--callout-tip: 0, 191, 188;
--callout-success: 8, 185, 78;
--callout-question: 236, 191, 0;
--callout-warning: 236, 117, 0;
--callout-failure: 233, 49, 71;
--callout-danger: 233, 49, 71;
--callout-bug: 233, 49, 71;
--callout-example: 120, 82, 238;
--callout-quote: 158, 158, 158;
--callout-custom: 124, 134, 156;
--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);
@@ -204,6 +219,20 @@
--danger-hover: #eba0ac;
--success: #a6e3a1;
--warning: #f9e2af;
--callout-note: 100, 160, 255;
--callout-abstract: 60, 209, 205;
--callout-info: 60, 200, 224;
--callout-todo: 60, 200, 224;
--callout-tip: 60, 209, 205;
--callout-success: 80, 205, 120;
--callout-question: 240, 205, 80;
--callout-warning: 245, 150, 60;
--callout-failure: 240, 95, 115;
--callout-danger: 240, 95, 115;
--callout-bug: 240, 95, 115;
--callout-example: 165, 135, 245;
--callout-quote: 150, 150, 162;
--callout-custom: 150, 160, 182;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.3);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.4);
@@ -961,6 +990,31 @@
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.8);
}
:root[data-theme="one-dark"] {
--bg-primary: #282c34;
--bg-secondary: #21252b;
--bg-tertiary: #2c313a;
--bg-hover: #3e4451;
--bg-active: #4b5263;
--bg-editor: #282c34;
--text-primary: #abb2bf;
--text-secondary: #828997;
--text-tertiary: #5c6370;
--text-accent: #61afef;
--border-color: #3e4451;
--border-light: #2c313a;
--accent: #61afef;
--accent-hover: #4d9fdf;
--accent-light: color-mix(in srgb, #61afef 12%, transparent);
--danger: #e06c75;
--danger-hover: #cc5560;
--success: #98c379;
--warning: #e5c07b;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.5);
}
*,
*::before,
*::after {
+33
View File
@@ -1,6 +1,7 @@
import { invoke } from "@tauri-apps/api/core";
import type {
AppConfig,
CustomTheme,
NoteContent,
NoteEntry,
NoteMeta,
@@ -36,6 +37,22 @@ export async function setAccentColor(color: string): Promise<void> {
return invoke("set_accent_color", { color });
}
export async function saveCustomTheme(theme: CustomTheme): Promise<void> {
return invoke("save_custom_theme", { theme });
}
export async function deleteCustomTheme(id: string): Promise<void> {
return invoke("delete_custom_theme", { id });
}
export async function exportCustomTheme(id: string, path: string): Promise<void> {
return invoke("export_custom_theme", { id, path });
}
export async function importCustomThemes(path: string): Promise<CustomTheme[]> {
return invoke("import_custom_themes", { path });
}
export async function setFontSize(size: number): Promise<void> {
return invoke("set_font_size", { size });
}
@@ -52,6 +69,10 @@ export async function setUiScale(scale: number): Promise<void> {
return invoke("set_ui_scale", { scale });
}
export async function setContentWidth(width: number | null): Promise<void> {
return invoke("set_content_width", { width });
}
export async function getNotebooks(): Promise<NotebookEntry[]> {
return invoke("get_notebooks");
}
@@ -228,12 +249,18 @@ export async function setGeneralSettings(
titleMode: string,
hideTitleInBody: boolean,
showLineNumbers: boolean,
showLinkArrows: boolean,
defaultViewMode: boolean,
showTrayIcon: boolean,
closeToTray: boolean,
enableWikiLinks: boolean,
showNoteDates: boolean,
restoreLastSession: boolean,
showAllNotes: boolean,
showQuickAccess: boolean,
showTasks: boolean,
showDailyNotes: boolean,
showTrash: boolean,
): Promise<void> {
return invoke("set_general_settings", {
compactNotes,
@@ -247,12 +274,18 @@ export async function setGeneralSettings(
titleMode,
hideTitleInBody,
showLineNumbers,
showLinkArrows,
defaultViewMode,
showTrayIcon,
closeToTray,
enableWikiLinks,
showNoteDates,
restoreLastSession,
showAllNotes,
showQuickAccess,
showTasks,
showDailyNotes,
showTrash,
});
}
+197 -95
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { onMount, onDestroy, tick } from 'svelte';
import { listen } from '@tauri-apps/api/event';
import Sidebar from './Sidebar.svelte';
import NoteList from './NoteList.svelte';
@@ -14,7 +14,9 @@
import {
sidebarWidth,
notelistWidth,
outlineWidth,
sidebarCollapsed,
notelistCollapsed,
collapsedNotebooks,
showSearch,
showCommandPalette,
@@ -37,6 +39,7 @@
rootNoteCount,
viewMode,
sortMode,
groupNotesByDate,
tasksLayout,
tasksHideCompleted,
tasksOnlyFlagged,
@@ -48,15 +51,18 @@
viewerNote,
notebookSortMode,
notebookOrder,
noteOrder,
syncState,
platformIsMobile
platformIsMobile,
activeVaultConfig,
} from '$lib/stores/app';
import { keybindings, matchAction } from '$lib/keybindings';
const appWindow = getCurrentWindow();
const isMac = navigator.platform.startsWith('Mac');
const isMobile = $derived($platformIsMobile);
const isAndroid = /android/i.test(navigator.userAgent);
import { loadVaultState, saveVaultState, readNote, createDailyNote, createBackup, getPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api';
import { darkThemes, isAndroid } from '$lib/platform';
import { debounce } from '$lib/utils/debounce';
import { openNoteWindow } from '$lib/utils/window';
import { get } from 'svelte/store';
@@ -116,16 +122,16 @@
}
function syncConfigured(): boolean {
return get(appConfig)?.sync_provider === 'webdav';
return activeVaultConfig(get(appConfig))?.sync_provider === 'webdav';
}
// Auto-sync on a timer (only when configured and an interval is set).
async function checkScheduledSync() {
const config = get(appConfig);
if (config?.sync_provider !== 'webdav') return;
const mins = config.sync_interval_minutes ?? 0;
const vc = activeVaultConfig(get(appConfig));
if (vc?.sync_provider !== 'webdav') return;
const mins = vc.sync_interval_minutes ?? 0;
if (!mins || get(syncState).running) return;
const last = config.last_sync_time ? new Date(config.last_sync_time).getTime() : 0;
const last = vc.last_sync_time ? new Date(vc.last_sync_time).getTime() : 0;
if (Date.now() - last >= mins * 60 * 1000) {
try { await syncNow(); } catch (_) {}
}
@@ -198,11 +204,15 @@
last_open_note: $activeNotePath,
sidebar_width: $sidebarWidth,
notelist_width: $notelistWidth,
outline_width: $outlineWidth,
sidebar_collapsed: $sidebarCollapsed,
notelist_collapsed: $notelistCollapsed,
collapsed_notebooks: $collapsedNotebooks,
notebook_sort_mode: $notebookSortMode,
notebook_order: $notebookOrder,
note_order: $noteOrder,
sort_mode: $sortMode,
group_notes_by_date: $groupNotesByDate,
last_view_mode: $viewMode,
last_notebook: $activeNotebook?.relative_path ?? null,
last_tag: $activeTag,
@@ -226,6 +236,19 @@
persistState();
}
function revealNoteList() {
$notelistCollapsed = false;
tick().then(() => noteList?.refresh());
}
function toggleNoteList() {
const nextCollapsed = !$notelistCollapsed;
$notelistCollapsed = nextCollapsed;
if (!nextCollapsed) {
tick().then(() => noteList?.refresh());
}
}
// Tasks view: the editor pane shows a placeholder until a task is opened from the list.
let taskNoteOpened = $state(false);
@@ -239,7 +262,14 @@
function handleViewChanged() {
taskNoteOpened = false;
noteList?.refresh();
// Picking a notebook/tag/Tasks/etc. in the sidebar is a request to browse that view's
// notes - so if the notes list was hidden, bring it back rather than navigating blindly
// into a panel the user can't see. revealNoteList() re-mounts the list and refreshes it.
if ($notelistCollapsed) {
revealNoteList();
} else {
noteList?.refresh();
}
if (isMobile) $mobileView = 'notelist';
}
@@ -360,6 +390,16 @@
navFromPopstate = false;
return;
}
// If a modal is open, close it instead of navigating
if ($showSettings || $showInfo || $showSearch || $showCommandPalette) {
$showSettings = false;
$showInfo = false;
$showSearch = false;
$showCommandPalette = false;
// Re-push the current state so the next back still works
history.pushState({ mobileView: $mobileView, depth: historyDepth }, '');
return;
}
const state = e.state;
const targetDepth = state?.depth ?? 0;
historyDepth = targetDepth;
@@ -383,88 +423,83 @@
function handleKeydown(e: KeyboardEvent) {
const mod = e.ctrlKey || e.metaKey;
const code = e.code;
if (e.altKey && e.key === 'ArrowLeft') {
e.preventDefault();
navigateHistory(-1);
return;
}
if (e.altKey && e.key === 'ArrowRight') {
e.preventDefault();
navigateHistory(1);
return;
}
if (mod && !e.shiftKey && code === 'KeyN') {
e.preventDefault();
createAndFocusNote();
return;
}
if (mod && e.shiftKey && code === 'KeyN') {
e.preventDefault();
const isDark = $theme === 'dark' || ($theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
const next = isDark ? 'light' : 'dark';
$theme = next;
setTheme(next);
return;
}
if (mod && e.shiftKey && code === 'KeyF') {
e.preventDefault();
$showSearch = true;
return;
}
if (mod && !e.shiftKey && code === 'KeyF') {
e.preventDefault();
if ($activeNotePath) {
editor?.openNoteSearch();
} else {
$showSearch = true;
}
return;
}
if (mod && !e.shiftKey && code === 'KeyP') {
e.preventDefault();
$showCommandPalette = true;
return;
}
if (mod && !e.shiftKey && code === 'KeyS') {
e.preventDefault();
editor?.forceSave();
return;
}
// Mod+K (insert link) is an editor formatting action and is not user-customizable.
if (mod && code === 'KeyK' && !e.shiftKey && $activeNotePath && !$sourceMode) {
e.preventDefault();
editor?.addLinkFromToolbar();
}
if (mod && e.shiftKey && code === 'KeyM') {
// Ctrl/Cmd+Shift+Delete: move the open note to the trash.
if (mod && e.shiftKey && code === 'Delete' && $activeNotePath) {
e.preventDefault();
$sourceMode = !$sourceMode;
noteList?.trashActiveNote();
return;
}
if (mod && e.shiftKey && code === 'KeyW') {
const action = matchAction(e, $keybindings);
if (action) {
e.preventDefault();
if ($activeNotePath && $activeNote) {
openNoteWindow($activeNotePath, $activeNote.meta.title);
switch (action) {
case 'nav-back':
navigateHistory(-1);
return;
case 'nav-forward':
navigateHistory(1);
return;
case 'new-note':
createAndFocusNote();
return;
case 'toggle-theme': {
const isDark = $theme === 'dark' || ($theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
const next = isDark ? 'light' : 'dark';
$theme = next;
setTheme(next);
return;
}
case 'search-vault':
$showSearch = true;
return;
case 'find-in-note':
if ($activeNotePath) {
editor?.openNoteSearch();
} else {
$showSearch = true;
}
return;
case 'quick-open':
$showCommandPalette = true;
return;
case 'save':
editor?.forceSave();
return;
case 'toggle-source':
$sourceMode = !$sourceMode;
return;
case 'open-new-window':
if ($activeNotePath && $activeNote) {
openNoteWindow($activeNotePath, $activeNote.meta.title);
}
return;
case 'toggle-sidebar':
$sidebarCollapsed = !$sidebarCollapsed;
return;
case 'toggle-notelist':
toggleNoteList();
return;
case 'toggle-focus':
$focusMode = !$focusMode;
return;
case 'toggle-readonly':
if ($viewerNote) return; // viewer mode is always read-only
$readOnly = !$readOnly;
return;
case 'fullscreen':
appWindow.isFullscreen().then(fs => appWindow.setFullscreen(!fs));
return;
}
}
if (mod && e.key === '\\') {
e.preventDefault();
$sidebarCollapsed = !$sidebarCollapsed;
return;
}
if (mod && e.shiftKey && code === 'KeyE') {
e.preventDefault();
$focusMode = !$focusMode;
return;
}
if (mod && e.shiftKey && code === 'KeyR') {
e.preventDefault();
if ($viewerNote) return; // viewer mode is always read-only
$readOnly = !$readOnly;
return;
}
if (e.key === 'F11') {
e.preventDefault();
appWindow.isFullscreen().then(fs => appWindow.setFullscreen(!fs));
return;
}
if (e.key === 'Escape') {
if ($showSettings) $showSettings = false;
else if ($showInfo) $showInfo = false;
@@ -475,8 +510,7 @@
}
function applyTheme(t: string) {
const darkThemes = ['dark', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'dark-coffee', 'crimson'];
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'];
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 root = document.documentElement;
root.classList.remove('dark');
root.removeAttribute('data-theme');
@@ -502,14 +536,27 @@
persistState();
});
$effect(() => {
$sidebarCollapsed;
$notelistCollapsed;
$outlineWidth;
persistState();
});
$effect(() => {
$notebookSortMode;
$notebookOrder;
persistState();
});
$effect(() => {
$noteOrder;
persistState();
});
$effect(() => {
$sortMode;
$groupNotesByDate;
$tasksLayout;
$tasksHideCompleted;
$tasksOnlyFlagged;
@@ -533,11 +580,15 @@
const state = await loadVaultState();
$sidebarWidth = state.sidebar_width;
$notelistWidth = state.notelist_width;
if (typeof state.outline_width === 'number') $outlineWidth = state.outline_width;
$sidebarCollapsed = state.sidebar_collapsed;
$notelistCollapsed = state.notelist_collapsed ?? false;
$collapsedNotebooks = state.collapsed_notebooks ?? [];
$notebookSortMode = state.notebook_sort_mode === 'manual' ? 'manual' : 'alphabetical';
$notebookOrder = state.notebook_order ?? {};
if (state.sort_mode === 'created' || state.sort_mode === 'title' || state.sort_mode === 'modified') $sortMode = state.sort_mode;
$noteOrder = state.note_order ?? {};
if (state.sort_mode === 'created' || state.sort_mode === 'title' || state.sort_mode === 'modified' || state.sort_mode === 'custom') $sortMode = state.sort_mode;
if (typeof state.group_notes_by_date === 'boolean') $groupNotesByDate = state.group_notes_by_date;
if (state.tasks_layout === 'calendar' || state.tasks_layout === 'list') $tasksLayout = state.tasks_layout;
if (typeof state.tasks_hide_completed === 'boolean') $tasksHideCompleted = state.tasks_hide_completed;
if (typeof state.tasks_only_flagged === 'boolean') $tasksOnlyFlagged = state.tasks_only_flagged;
@@ -661,12 +712,13 @@
unlistenSync.push(await listen('sync-done', (event: any) => {
syncState.set({ running: false, error: null });
const cur = get(appConfig);
if (cur && event.payload?.last_sync_time) appConfig.set({ ...cur, last_sync_time: event.payload.last_sync_time });
const ts = event.payload?.last_sync_time;
if (cur && ts) appConfig.set({ ...cur, vaults: cur.vaults.map((v) => v.path === cur.active_vault ? { ...v, last_sync_time: ts } : v) });
}));
unlistenSync.push(await listen('sync-error', (event: any) => syncState.set({ running: false, error: event.payload?.error ?? 'Sync failed' })));
// Sync when the vault opens (if enabled)
if (syncConfigured() && get(appConfig)?.sync_on_open) {
if (syncConfigured() && activeVaultConfig(get(appConfig))?.sync_on_open) {
try { await syncNow(); } catch (_) {}
}
@@ -676,8 +728,8 @@
// Auto-sync on note change: a save flips editorDirty true -> false. Debounce a sync.
unsubDirty = editorDirty.subscribe((d) => {
const config = get(appConfig);
if (prevDirty && !d && config?.sync_provider === 'webdav' && config?.sync_on_change) {
const vc = activeVaultConfig(get(appConfig));
if (prevDirty && !d && vc?.sync_provider === 'webdav' && vc?.sync_on_change) {
if (onChangeSyncTimer) clearTimeout(onChangeSyncTimer);
onChangeSyncTimer = setTimeout(() => { if (!get(syncState).running) syncNow().catch(() => {}); }, 15000);
}
@@ -793,7 +845,7 @@
</svg>
</button>
{/if}
{#if $appConfig?.sync_provider === 'webdav'}
{#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')}>
<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"/>
@@ -820,6 +872,13 @@
<line x1="3" y1="10" x2="21" y2="10" />
</svg>
</button>
<button class="mobile-header-btn" onclick={() => ($showInfo = true)} title="Info">
<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" />
<line x1="12" y1="16" x2="12" y2="12" />
<line x1="12" y1="8" x2="12.01" y2="8" />
</svg>
</button>
<button class="mobile-header-btn" onclick={() => ($showSettings = true)} title="Settings">
<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="3" />
@@ -895,11 +954,24 @@
<ResizeHandle onResize={handleSidebarResize} />
{/if}
<div class="notelist-panel" style="width: {$notelistWidth}px">
<NoteList bind:this={noteList} onNoteSelected={handleNoteSelected} onBeforeNoteSwitch={() => editor?.flushSave()} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={() => { editor?.focusTitle(); sidebar?.refresh(); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} />
</div>
{#if !$notelistCollapsed}
<div class="notelist-panel" style="width: {$notelistWidth}px">
<NoteList bind:this={noteList} onNoteSelected={handleNoteSelected} onBeforeNoteSwitch={() => editor?.flushSave()} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={() => { editor?.focusTitle(); sidebar?.refresh(); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} />
</div>
<ResizeHandle onResize={handleNotelistResize} />
<ResizeHandle onResize={handleNotelistResize} />
{:else}
<div class="notelist-restore-panel">
<button class="notelist-restore-btn" onclick={revealNoteList} title={`Show notes list (${isMac ? '⌘' : 'Ctrl'}+Shift+\\)`} aria-label="Show notes list">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="20" y2="6" />
<line x1="8" y1="12" x2="20" y2="12" />
<line x1="8" y1="18" x2="20" y2="18" />
<polyline points="5 8 3 12 5 16" />
</svg>
</button>
</div>
{/if}
{/if}
<div class="editor-panel">
@@ -918,7 +990,7 @@
{/if}
<SearchPanel />
<CommandPalette />
<CommandPalette onNavigate={handleViewChanged} />
<SettingsPanel />
<InfoPanel />
@@ -949,6 +1021,36 @@
overflow: hidden;
}
.notelist-restore-panel {
flex-shrink: 0;
width: 36px;
height: 100%;
padding-top: 8px;
display: flex;
justify-content: center;
background: var(--bg-primary);
border-right: 1px solid var(--border-color);
}
.notelist-restore-btn {
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: none;
border-radius: 4px;
background: transparent;
color: var(--text-tertiary);
cursor: pointer;
}
.notelist-restore-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.editor-panel {
flex: 1;
height: 100%;
+40 -3
View File
@@ -1,6 +1,19 @@
<script lang="ts">
import { showCommandPalette, showSearch, theme, sourceMode } from '$lib/stores/app';
import { showCommandPalette, showSearch, theme, sourceMode, viewMode, activeNotebook, activeTag } from '$lib/stores/app';
import { setTheme, reindex } from '$lib/api';
import { darkThemes } from '$lib/platform';
// onNavigate runs the parent's view-change handler (refreshes the note list and reveals it
// if it was hidden), so opening a view here behaves exactly like clicking it in the sidebar.
let { onNavigate = () => {} }: { onNavigate?: () => void } = $props();
function openView(mode: 'all' | 'quickaccess' | 'tasks' | 'daily' | 'trash') {
$viewMode = mode;
$activeNotebook = null;
$activeTag = null;
$showCommandPalette = false;
onNavigate();
}
interface Command {
id: string;
@@ -25,6 +38,31 @@
$showSearch = true;
}
},
{
id: 'open-all-notes',
label: 'Open All Notes',
action: () => openView('all')
},
{
id: 'open-quick-access',
label: 'Open Quick Access',
action: () => openView('quickaccess')
},
{
id: 'open-tasks',
label: 'Open Tasks',
action: () => openView('tasks')
},
{
id: 'open-daily',
label: 'Open Daily Notes',
action: () => openView('daily')
},
{
id: 'open-trash',
label: 'Open Trash (restore deleted notes)',
action: () => openView('trash')
},
{
id: 'theme-light',
label: 'Switch to Light Theme',
@@ -142,8 +180,7 @@
}
function applyTheme(t: string) {
const darkThemes = ['dark', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'dark-coffee', 'crimson'];
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'];
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 root = document.documentElement;
root.classList.remove('dark');
root.removeAttribute('data-theme');
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -2,14 +2,13 @@
import { onDestroy } from 'svelte';
import { getGraphData } from '$lib/api';
import { activeNotePath, appConfig } from '$lib/stores/app';
import { isMobile } from '$lib/platform';
let { onclose, onnavigate }: {
onclose: () => void;
onnavigate: (path: string, title: string) => void;
} = $props();
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
let canvas = $state<HTMLCanvasElement>(null!);
let loading = $state(true);
let searchQuery = $state('');
+151 -21
View File
@@ -5,9 +5,84 @@
import { openUrl } from '$lib/api';
import { getVersion } from '@tauri-apps/api/app';
import type { VaultStats } from '$lib/types';
import {
ACTIONS,
keybindings,
setBinding,
resetBinding,
bindingFromEvent,
bindingToKeys,
bindingsEqual,
type ActionDef,
} from '$lib/keybindings';
import { isMobile } from '$lib/platform';
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
// Customizable shortcuts, grouped for display.
const actionGroups: { title: string; actions: ActionDef[] }[] = [
{ title: 'General', actions: ACTIONS.filter((a) => a.group === 'General') },
{ title: 'Interface', actions: ACTIONS.filter((a) => a.group === 'Interface') },
{ title: 'Navigation', actions: ACTIONS.filter((a) => a.group === 'Navigation') },
];
// id of the action currently listening for a new key combo, or null.
let capturingId = $state<string | null>(null);
// id of an action whose row should briefly flash a "already in use" warning.
let conflictId = $state<string | null>(null);
let conflictTimer: ReturnType<typeof setTimeout> | null = null;
function startCapture(id: string) {
conflictId = null;
capturingId = id;
}
function stopCapture() {
capturingId = null;
}
function flashConflict(id: string) {
conflictId = id;
if (conflictTimer) clearTimeout(conflictTimer);
conflictTimer = setTimeout(() => { conflictId = null; }, 1600);
}
function captureKeydown(e: KeyboardEvent) {
if (!capturingId) return;
// Capture phase + stopImmediatePropagation keeps the combo from also
// triggering the app-level shortcut handler on window.
e.preventDefault();
e.stopImmediatePropagation();
if (e.key === 'Escape') { stopCapture(); return; }
const binding = bindingFromEvent(e);
if (!binding) return; // modifier-only press; keep listening
// Reject combos already bound to a different action.
const map = $keybindings;
const target = capturingId;
const clash = Object.keys(map).find((other) => other !== target && bindingsEqual(map[other], binding));
if (clash) {
flashConflict(target);
stopCapture();
return;
}
setBinding(target, binding);
stopCapture();
}
$effect(() => {
if (!capturingId) return;
window.addEventListener('keydown', captureKeydown, true);
return () => window.removeEventListener('keydown', captureKeydown, true);
});
function resetKey(e: MouseEvent, id: string) {
e.preventDefault();
resetBinding(id);
if (capturingId === id) stopCapture();
}
let stats = $state<VaultStats | null>(null);
let activeTab = $state<'about' | 'shortcuts'>(isMobile ? 'about' : 'shortcuts');
@@ -21,7 +96,7 @@
function close() {
$showInfo = false;
activeTab = 'shortcuts';
activeTab = isMobile ? 'about' : 'shortcuts';
}
function openLink(url: string) {
@@ -158,27 +233,39 @@
</div>
{:else}
<div class="shortcuts-section">
<h4 class="shortcuts-group-title">General</h4>
<div class="shortcut-row"><span class="shortcut-desc">New note</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>N</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Save</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>S</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Quick open</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>P</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Find in note</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Search vault</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Open note in new window</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>W</kbd></span></div>
<h4 class="shortcuts-group-title">Interface</h4>
<div class="shortcut-row"><span class="shortcut-desc">Toggle sidebar</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>\</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Toggle dark / light theme</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>N</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Toggle focus mode</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>E</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Toggle read-only</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Toggle source / WYSIWYG</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>M</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Toggle fullscreen</span><span class="shortcut-keys"><kbd>F11</kbd></span></div>
{#if !isMobile}
<p class="shortcuts-hint">Click a shortcut to rebind it, right-click to reset.</p>
{/if}
{#each actionGroups as group}
<h4 class="shortcuts-group-title">{group.title}</h4>
{#each group.actions as action}
<div class="shortcut-row">
<span class="shortcut-desc">{action.label}</span>
{#if isMobile}
<span class="shortcut-keys">{#each bindingToKeys($keybindings[action.id]) as key, i}{#if i > 0}+{/if}<kbd>{key}</kbd>{/each}</span>
{:else}
<button
class="shortcut-key-btn"
class:capturing={capturingId === action.id}
class:conflict={conflictId === action.id}
title="Click to rebind · right-click to reset"
onclick={() => startCapture(action.id)}
oncontextmenu={(e) => resetKey(e, action.id)}
>
{#if capturingId === action.id}
<span class="capture-prompt">Press keys…</span>
{:else if conflictId === action.id}
<span class="conflict-msg">Already in use</span>
{:else}
<span class="shortcut-keys">{#each bindingToKeys($keybindings[action.id]) as key, i}{#if i > 0}+{/if}<kbd>{key}</kbd>{/each}</span>
{/if}
</button>
{/if}
</div>
{/each}
{/each}
<div class="shortcut-row"><span class="shortcut-desc">Close panel / exit focus</span><span class="shortcut-keys"><kbd>Esc</kbd></span></div>
<h4 class="shortcuts-group-title">Navigation</h4>
<div class="shortcut-row"><span class="shortcut-desc">Go back</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd></kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Go forward</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd></kbd></span></div>
<h4 class="shortcuts-group-title">Formatting</h4>
<div class="shortcut-row"><span class="shortcut-desc">Bold</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>B</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Italic</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>I</kbd></span></div>
@@ -189,6 +276,7 @@
<div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>{modKey}</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Move line up / down</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd>↑↓</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Move list item up / down</span><span class="shortcut-keys"><kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>↑↓</kbd></span></div>
<h4 class="shortcuts-group-title">Editor Commands</h4>
<div class="shortcut-row"><span class="shortcut-desc">Slash commands</span><span class="shortcut-keys"><kbd>/</kbd></span></div>
@@ -501,6 +589,48 @@
color: var(--text-tertiary);
}
.shortcuts-hint {
font-size: 12px;
color: var(--text-tertiary);
margin: 0 0 4px;
}
.shortcut-key-btn {
background: none;
border: 1px solid transparent;
border-radius: 6px;
padding: 2px 4px;
margin: -2px -4px;
cursor: pointer;
display: flex;
align-items: center;
flex-shrink: 0;
font: inherit;
}
.shortcut-key-btn:hover {
background: var(--bg-hover);
}
.shortcut-key-btn.capturing {
border-color: var(--accent);
background: var(--accent-light);
}
.shortcut-key-btn.conflict {
border-color: var(--danger, #e11d48);
}
.capture-prompt {
font-size: 12px;
color: var(--accent);
}
.conflict-msg {
font-size: 12px;
color: var(--danger, #e11d48);
}
.shortcut-keys kbd,
.shortcut-desc kbd {
display: inline-block;
+200 -13
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { tick } from 'svelte';
import {
notes,
sortedNotes,
@@ -8,9 +9,12 @@
activeNotebook,
activeTag,
sortMode,
groupNotesByDate,
editorDirty,
quickAccessPaths,
appConfig,
notelistCollapsed,
noteOrder,
notebooks,
tags,
mobileView
@@ -34,12 +38,13 @@
getAllTags,
createDailyNote
} from '$lib/api';
import { formatRelativeTime, formatDate } from '$lib/utils/time';
import { formatRelativeTime, formatDate, dateBucketLabel } from '$lib/utils/time';
import { openNoteWindow } from '$lib/utils/window';
import { revealItemInDir } from '@tauri-apps/plugin-opener';
import type { NoteEntry, TrashNotebookEntry, SortMode, TaskItem } from '$lib/types';
import TasksView from './TasksView.svelte';
import TagSuggestInput from './TagSuggestInput.svelte';
import { isMobile, isAndroid } from '$lib/platform';
let { onNoteSelected = (_path: string, _content: string) => {}, onNoteMoved = () => {}, onBeforeNoteSwitch = () => {}, onNoteCreated = () => {}, onToggleTask = async (_t: TaskItem) => {}, onSetTaskPriority = async (_t: TaskItem, _p: string | null) => {}, onSetTaskDue = async (_t: TaskItem, _d: string | null) => {} }: {
onNoteSelected?: (path: string, content: string) => void;
@@ -52,8 +57,6 @@
} = $props();
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
const isAndroid = /android/i.test(navigator.userAgent);
let multiSelectMode = $state(false);
let trashNotebooks = $state<TrashNotebookEntry[]>([]);
let trashBusy = $state<string | null>(null);
@@ -143,6 +146,7 @@
let sortMenu = $state<{ x: number; y: number } | null>(null);
let editingNote = $state<string | null>(null);
let editValue = $state('');
let renameInput: HTMLInputElement | null = $state(null);
let movePickerNote = $state<NoteEntry | null>(null);
let tagEditNote = $state<NoteEntry | null>(null);
let tagEditTags = $state<string[]>([]);
@@ -203,6 +207,29 @@
let qaDragFrom = $state<number | null>(null);
let qaDragOver = $state<number | null>(null);
let qaDragHalf = $state<'top' | 'bottom'>('bottom');
let noteDragFrom = $state<number | null>(null);
let noteDragOver = $state<number | null>(null);
let noteDragHalf = $state<'top' | 'bottom'>('bottom');
const customOrderViews = new Set(['all', 'notebook', 'tag']);
let canCustomReorder = $derived($sortMode === 'custom' && customOrderViews.has($viewMode));
// Relative-date grouping (All Notes + date sorts only). Pinned notes form their own leading group.
let groupingActive = $derived($groupNotesByDate && $viewMode === 'all' && ($sortMode === 'created' || $sortMode === 'modified'));
let noteGroups = $derived.by(() => {
if (!groupingActive) return [] as { label: string; notes: NoteEntry[] }[];
const pinned: NoteEntry[] = [];
const rest: NoteEntry[] = [];
for (const n of $sortedNotes) (n.meta.pinned ? pinned : rest).push(n);
const groups: { label: string; notes: NoteEntry[] }[] = [];
if (pinned.length) groups.push({ label: 'Pinned', notes: pinned });
let cur: { label: string; notes: NoteEntry[] } | null = null;
for (const n of rest) {
const label = dateBucketLabel($sortMode === 'created' ? n.meta.created : n.meta.modified);
if (!cur || cur.label !== label) { cur = { label, notes: [] }; groups.push(cur); }
cur.notes.push(n);
}
return groups;
});
// Virtual scroll
let listContainer = $state<HTMLDivElement>(null!);
@@ -412,6 +439,7 @@
}
try {
const entry = await createNote(nbRelative, 'Untitled');
if ($sortMode === 'custom') appendManualNoteOrder(entry.path);
noteCache.clear();
await refresh();
await selectNote(entry);
@@ -421,6 +449,14 @@
}
}
function handleListDoubleClick(e: MouseEvent) {
const target = e.target as HTMLElement | null;
if (target?.closest('button, input, .note-item, .context-menu, .sort-menu, .batch-move-picker, .cal')) return;
e.stopPropagation();
if ($viewMode === 'tasks' || $viewMode === 'trash') return;
handleCreateNote();
}
async function handleRename(note: NoteEntry) {
if (!editValue.trim() || editValue.trim() === note.meta.title) {
editingNote = null;
@@ -429,6 +465,7 @@
try {
const newTitle = editValue.trim();
const newPath = await renameNote(note.path, newTitle);
renameManualNoteOrderPath(note.path, newPath);
noteCache.clear();
editingNote = null;
// Update local store immediately (avoid full vault re-scan)
@@ -450,6 +487,7 @@
contextMenu = null;
try {
await deleteNote(note.path);
removeManualNoteOrderPath(note.path);
noteCache.clear();
// Remove from local store immediately (avoid full vault re-scan)
$notes = $notes.filter(n => n.path !== note.path);
@@ -462,6 +500,13 @@
}
}
// Move the currently open note to the trash (keyboard shortcut from the editor).
export async function trashActiveNote() {
if ($viewMode === 'trash' || !$activeNotePath) return;
const note = $notes.find(n => n.path === $activeNotePath);
if (note) await handleDelete(note);
}
async function handleRestore(note: NoteEntry) {
contextMenu = null;
try {
@@ -477,6 +522,7 @@
contextMenu = null;
try {
await permanentDelete(note.path);
removeManualNoteOrderPath(note.path);
noteCache.clear();
$notes = $notes.filter(n => n.path !== note.path);
if ($activeNotePath === note.path) {
@@ -670,11 +716,60 @@
}
}
function persistManualNoteOrder(orderedNotes: NoteEntry[]) {
// Merge into (not replace) the order map so reordering notes in one view does
// not wipe the saved custom order of other notebooks / tags / the all-notes view.
const updates = Object.fromEntries(orderedNotes.map((note, index) => [note.path, index]));
$noteOrder = { ...$noteOrder, ...updates };
}
function appendManualNoteOrder(path: string) {
const nextIndex = Math.max(-1, ...Object.values($noteOrder)) + 1;
$noteOrder = { ...$noteOrder, [path]: nextIndex };
}
function renameManualNoteOrderPath(oldPath: string, newPath: string) {
if (!Object.hasOwn($noteOrder, oldPath)) return;
const { [oldPath]: index, ...rest } = $noteOrder;
$noteOrder = { ...rest, [newPath]: index };
}
function removeManualNoteOrderPath(path: string) {
if (!Object.hasOwn($noteOrder, path)) return;
const { [path]: _, ...rest } = $noteOrder;
$noteOrder = rest;
}
function resetNoteDrag() {
noteDragFrom = null;
noteDragOver = null;
}
function handleCustomNoteDrop(targetIndex: number) {
if (noteDragFrom === null || !canCustomReorder) {
resetNoteDrag();
return;
}
let insertAt = noteDragHalf === 'bottom' ? targetIndex + 1 : targetIndex;
if (noteDragFrom === insertAt || noteDragFrom + 1 === insertAt) {
resetNoteDrag();
return;
}
const arr = [...$sortedNotes];
const [moved] = arr.splice(noteDragFrom, 1);
if (insertAt > noteDragFrom) insertAt--;
arr.splice(insertAt, 0, moved);
$notes = arr;
persistManualNoteOrder(arr);
resetNoteDrag();
}
async function handleMoveNote(note: NoteEntry, destPath: string) {
contextMenu = null;
movePickerNote = null;
try {
const newPath = await moveNote(note.path, destPath);
renameManualNoteOrderPath(note.path, newPath);
noteCache.clear();
$notes = $notes.filter(n => n.path !== note.path);
if ($activeNotePath === note.path) {
@@ -701,10 +796,13 @@
contextMenu = { x, y, note };
}
function startRename(note: NoteEntry) {
async function startRename(note: NoteEntry) {
contextMenu = null;
editingNote = note.path;
editValue = note.meta.title;
await tick();
renameInput?.focus();
renameInput?.select();
}
function getNotebookPath(note: NoteEntry): string {
@@ -773,6 +871,7 @@
async function handleBatchDelete() {
const toDelete = new Set(selectedPaths);
noteCache.clear();
for (const path of toDelete) removeManualNoteOrderPath(path);
$notes = $notes.filter(n => !toDelete.has(n.path));
if ($activeNotePath && toDelete.has($activeNotePath)) {
$activeNote = null;
@@ -808,6 +907,7 @@
async function handleBatchPermanentDelete() {
const toDelete = new Set(selectedPaths);
noteCache.clear();
for (const path of toDelete) removeManualNoteOrderPath(path);
$notes = $notes.filter(n => !toDelete.has(n.path));
if ($activeNotePath && toDelete.has($activeNotePath)) {
$activeNote = null;
@@ -833,6 +933,9 @@
}
function setSortMode(mode: SortMode) {
if (mode === 'custom' && Object.keys($noteOrder).length === 0) {
persistManualNoteOrder($sortedNotes);
}
$sortMode = mode;
sortMenu = null;
}
@@ -856,6 +959,16 @@
<div class="list-header">
<span class="list-title">{viewTitle}</span>
<div class="list-actions">
{#if !isMobile}
<button class="icon-btn" onclick={() => ($notelistCollapsed = true)} title={`Hide notes list (${modKey}+Shift+\\)`} aria-label="Hide notes list">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="4" y1="6" x2="16" y2="6" />
<line x1="4" y1="12" x2="16" y2="12" />
<line x1="4" y1="18" x2="16" y2="18" />
<polyline points="19 8 21 12 19 16" />
</svg>
</button>
{/if}
{#if $viewMode !== 'tasks'}
{#if isAndroid}
<button class="icon-btn" class:active-toggle={multiSelectMode} onclick={() => { multiSelectMode = !multiSelectMode; if (!multiSelectMode) clearSelection(); }} title="Multi-select">
@@ -869,6 +982,13 @@
<line x1="4" y1="6" x2="11" y2="6" /><line x1="4" y1="12" x2="15" y2="12" /><line x1="4" y1="18" x2="20" y2="18" />
</svg>
</button>
{#if $viewMode === 'all' && ($sortMode === 'created' || $sortMode === 'modified')}
<button class="icon-btn" class:active-toggle={$groupNotesByDate} onclick={() => { $groupNotesByDate = !$groupNotesByDate; }} title="Group by date">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6" /><line x1="8" y1="12" x2="21" y2="12" /><line x1="8" y1="18" x2="21" y2="18" /><line x1="3" y1="6" x2="3.01" y2="6" /><line x1="3" y1="12" x2="3.01" y2="12" /><line x1="3" y1="18" x2="3.01" y2="18" />
</svg>
</button>
{/if}
{#if $viewMode !== 'trash'}
<button class={isMobile ? 'mobile-create-btn' : 'icon-btn'} onclick={handleCreateNote} title={`New note (${modKey}+N)`}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width={isMobile ? '3' : '2'} stroke-linecap="round" stroke-linejoin="round">
@@ -967,7 +1087,8 @@
</div>
{/if}
<div class="list-content" bind:this={listContainer} onscroll={onListScroll}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="list-content" bind:this={listContainer} onscroll={onListScroll} ondblclick={handleListDoubleClick}>
{#if $viewMode === 'tasks'}
<TasksView onOpenTask={openTask} onToggleTask={onToggleTask} onSetTaskPriority={onSetTaskPriority} onSetTaskDue={onSetTaskDue} />
{/if}
@@ -1047,14 +1168,13 @@
{/each}
{/if}
<div style="height: {topPad}px"></div>
{#each visibleNotes as note, i (note.path)}
{@const noteIndex = startIndex + i}
{#snippet noteRow(note: NoteEntry, noteIndex: number)}
{#if editingNote === note.path}
<div class="note-item active">
<input
type="text"
class="rename-input"
bind:this={renameInput}
bind:value={editValue}
onkeydown={(e) => {
if (e.key === 'Enter') handleRename(note);
@@ -1072,7 +1192,15 @@
class:compact={compact}
class:qa-drag-above={$viewMode === 'quickaccess' && qaDragOver === noteIndex && qaDragFrom !== null && qaDragHalf === 'top'}
class:qa-drag-below={$viewMode === 'quickaccess' && qaDragOver === noteIndex && qaDragFrom !== null && qaDragHalf === 'bottom'}
class:note-drag-above={canCustomReorder && noteDragOver === noteIndex && noteDragFrom !== null && noteDragHalf === 'top'}
class:note-drag-below={canCustomReorder && noteDragOver === noteIndex && noteDragFrom !== null && noteDragHalf === 'bottom'}
onclick={(e) => handleNoteClick(e, note)}
onkeydown={(e) => {
if (e.key === 'F2') {
e.preventDefault();
startRename(note);
}
}}
ontouchstart={(e) => { if (isMobile && !isAndroid) handleTouchStart(e, note); }}
ontouchmove={(e) => { if (isMobile && !isAndroid) handleTouchMove(e); }}
ontouchend={() => { if (isMobile && !isAndroid) handleTouchEnd(); }}
@@ -1099,6 +1227,12 @@
e.dataTransfer!.effectAllowed = 'move';
return;
}
if (canCustomReorder) {
noteDragFrom = noteIndex;
e.dataTransfer!.setData('text/plain', note.path);
e.dataTransfer!.effectAllowed = 'move';
return;
}
if (selectedPaths.size > 1 && selectedPaths.has(note.path)) {
e.dataTransfer!.setData('text/plain', [...selectedPaths].join('\n'));
} else {
@@ -1113,18 +1247,28 @@
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
qaDragHalf = e.clientY < rect.top + rect.height / 2 ? 'top' : 'bottom';
qaDragOver = noteIndex;
} else if (canCustomReorder && noteDragFrom !== null) {
e.preventDefault();
e.dataTransfer!.dropEffect = 'move';
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
noteDragHalf = e.clientY < rect.top + rect.height / 2 ? 'top' : 'bottom';
noteDragOver = noteIndex;
}
}}
ondragleave={() => {
if (qaDragOver === noteIndex) qaDragOver = null;
if (noteDragOver === noteIndex) noteDragOver = null;
}}
ondrop={(e) => {
if ($viewMode === 'quickaccess' && qaDragFrom !== null) {
e.preventDefault();
handleQaDrop(noteIndex);
} else if (canCustomReorder && noteDragFrom !== null) {
e.preventDefault();
handleCustomNoteDrop(noteIndex);
}
}}
ondragend={() => { qaDragFrom = null; qaDragOver = null; }}
ondragend={() => { qaDragFrom = null; qaDragOver = null; resetNoteDrag(); }}
>
{#if compact}
<div class="note-compact-row" title={getNotebookPath(note) ? `${getNotebookPath(note)}/${note.meta.title}` : note.meta.title}>
@@ -1178,8 +1322,22 @@
{/if}
</button>
{/if}
{/each}
<div style="height: {bottomPad}px"></div>
{/snippet}
{#if groupingActive}
{#each noteGroups as group (group.label)}
<div class="note-list-section">{group.label}</div>
{#each group.notes as note (note.path)}
{@render noteRow(note, -1)}
{/each}
{/each}
{:else}
<div style="height: {topPad}px"></div>
{#each visibleNotes as note, i (note.path)}
{@render noteRow(note, startIndex + i)}
{/each}
<div style="height: {bottomPad}px"></div>
{/if}
</div>
</div>
@@ -1403,6 +1561,18 @@
Title
{#if $sortMode === 'title'}<span class="sort-check">&#10003;</span>{/if}
</button>
<button class:active={$sortMode === 'custom'} onclick={() => setSortMode('custom')}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="8" y1="6" x2="21" y2="6" />
<line x1="8" y1="12" x2="21" y2="12" />
<line x1="8" y1="18" x2="21" y2="18" />
<circle cx="4" cy="6" r="1" />
<circle cx="4" cy="12" r="1" />
<circle cx="4" cy="18" r="1" />
</svg>
Custom
{#if $sortMode === 'custom'}<span class="sort-check">&#10003;</span>{/if}
</button>
</div>
{/if}
@@ -1477,6 +1647,21 @@
background: var(--text-secondary);
}
.note-list-section {
padding: 14px 12px 4px;
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--accent);
border-bottom: 1px solid var(--border-light);
margin-bottom: 2px;
user-select: none;
}
.note-list-section:first-child {
padding-top: 6px;
}
.note-item {
display: block;
width: 100%;
@@ -1925,11 +2110,13 @@
font-size: 14px;
}
.note-item.qa-drag-above {
.note-item.qa-drag-above,
.note-item.note-drag-above {
border-top: 2px solid var(--accent);
}
.note-item.qa-drag-below {
.note-item.qa-drag-below,
.note-item.note-drag-below {
border-bottom: 2px solid var(--accent);
}
+12 -9
View File
@@ -12,10 +12,13 @@
theme
} from '$lib/stores/app';
import { readNote } from '$lib/api';
import { keybindings, matchAction } from '$lib/keybindings';
import type { FileEvent } from '$lib/types';
let { notePath }: { notePath: string } = $props();
import { darkThemes } from '$lib/platform';
const appWindow = getCurrentWindow();
const isMac = navigator.platform.startsWith('Mac');
let editor = $state<Editor>(null!);
@@ -35,8 +38,7 @@
$effect(() => {
const t = $theme || 'system';
const darkThemes = ['dark', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'dark-coffee', 'crimson'];
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'];
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 root = document.documentElement;
root.classList.remove('dark');
root.removeAttribute('data-theme');
@@ -72,13 +74,11 @@
}
function handleKeydown(e: KeyboardEvent) {
const mod = e.ctrlKey || e.metaKey;
if (mod && !e.shiftKey && e.code === 'KeyS') {
const action = matchAction(e, $keybindings);
if (action === 'save') {
e.preventDefault();
editor?.forceSave();
return;
}
if (mod && e.shiftKey && e.code === 'KeyM') {
} else if (action === 'toggle-source') {
e.preventDefault();
$sourceMode = !$sourceMode;
}
@@ -103,8 +103,11 @@
if (!$editorDirty) {
try {
const content = await readNote(notePath);
$activeNote = content;
editor?.loadNote(notePath, content.content);
// Ignore the file-watcher echo of our own save; only reload genuine external edits.
if (content.content.trim() !== (editor?.getCurrentBody() ?? '').trim()) {
$activeNote = content;
editor?.loadNote(notePath, content.content);
}
} catch (_) {}
}
}
+1 -2
View File
@@ -3,6 +3,7 @@
import { searchNotes, readNote } from '$lib/api';
import { debounce } from '$lib/utils/debounce';
import type { SearchResult } from '$lib/types';
import { isMobile } from '$lib/platform';
let query = $state('');
let results = $state<SearchResult[]>([]);
@@ -83,8 +84,6 @@
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
async function openResult(result: SearchResult) {
try {
const content = await readNote(result.path);
File diff suppressed because it is too large Load Diff
+284 -56
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { tick } from 'svelte';
import {
notebooks,
notes,
@@ -20,26 +21,47 @@
notebookSortMode,
notebookOrder
} from '$lib/stores/app';
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, moveNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, getNotes, countRootNotes } from '$lib/api';
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, moveNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, countRootNotes } from '$lib/api';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { readFile } from '@tauri-apps/plugin-fs';
import { convertFileSrc } from '@tauri-apps/api/core';
import type { NotebookEntry } from '$lib/types';
import { isMobile } from '$lib/platform';
let { onViewChanged = () => {} }: {
onViewChanged?: () => void;
} = $props();
const modKey = navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl';
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
// Whether any top nav item (All Notes, Quick Access, Tasks, Daily Notes, Trash) is visible.
// When all are hidden we drop the empty <nav> and its divider so the tree sits flush.
const anyNavItem = $derived(
$appConfig?.show_all_notes !== false ||
$appConfig?.show_quick_access !== false ||
$appConfig?.show_tasks !== false ||
$appConfig?.show_daily_notes !== false ||
$appConfig?.show_trash !== false
);
let editingNotebook = $state<string | null>(null);
let editValue = $state('');
let renameInput: HTMLInputElement | null = $state(null);
let newNotebookName = $state('');
let showNewNotebook = $state(false);
let newNotebookInput: HTMLInputElement | null = $state(null);
let dropTargetPath = $state<string | null>(null);
let dropPosition = $state<'above' | 'into' | 'below' | null>(null);
let draggedNotebookPath = $state<string | null>(null);
let nbPointer: { src: string } | null = null;
// Notebook paths arrive from Rust with native separators (backslashes on Windows), so path math must be separator-agnostic.
const norm = (p: string) => (p ?? '').replace(/\\/g, '/');
const lastSep = (p: string) => Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
const parentOf = (p: string) => { const i = lastSep(p); return i < 0 ? '' : p.slice(0, i); };
const baseOf = (p: string) => p.slice(lastSep(p) + 1);
const joinPath = (parent: string, name: string) => parent + (parent.includes('\\') ? '\\' : '/') + name;
const isDescendant = (child: string, anc: string) => child.startsWith(anc + '/') || child.startsWith(anc + '\\');
// Apply manual ordering recursively when in 'manual' sort mode.
// In 'alphabetical' mode the Rust scanner already sorts, so we pass through unchanged.
@@ -59,19 +81,19 @@
let trashContextMenu = $state<{ x: number; y: number } | null>(null);
let tagsCollapsed = $state(true);
let deleteConfirm = $state<NotebookEntry | null>(null);
function toggleCollapse(path: string, e: MouseEvent) {
function toggleCollapse(nb: NotebookEntry, e: Event) {
e.stopPropagation();
if ($collapsedNotebooks.includes(path)) {
$collapsedNotebooks = $collapsedNotebooks.filter(p => p !== path);
if ($collapsedNotebooks.includes(nb.path)) {
$collapsedNotebooks = $collapsedNotebooks.filter(p => p !== nb.path);
} else {
$collapsedNotebooks = [...$collapsedNotebooks, path];
$collapsedNotebooks = [...$collapsedNotebooks, nb.path];
}
}
// Collapse-all / expand-all: toggles every notebook that has children.
function collectParentPaths(tree: NotebookEntry[]): string[] {
const out: string[] = [];
for (const nb of tree) {
if (nb.children && nb.children.length > 0) {
if (nb.children.length > 0) {
out.push(nb.path);
out.push(...collectParentPaths(nb.children));
}
@@ -133,8 +155,8 @@
onViewChanged();
}
function selectNotebook(nb: NotebookEntry) {
// Deselect if clicking the already-active notebook
async function selectNotebook(nb: NotebookEntry) {
// Deselect if clicking the already-active notebook; expand/collapse is the chevron's job
if ($viewMode === 'notebook' && $activeNotebook?.path === nb.path) {
selectAllNotes();
return;
@@ -182,11 +204,52 @@
let newNotebookParent = $state<NotebookEntry | null>(null);
function getNotebookNameSegments(name: string): string[] | null {
const segments = name.split('/').map((segment) => segment.trim());
if (segments.some((segment) => !segment || segment === '.' || segment === '..' || segment.includes('\\'))) {
return null;
}
return segments;
}
async function focusNewNotebookInput() {
await tick();
newNotebookInput?.focus();
}
async function toggleNewNotebookInput() {
if (showNewNotebook) {
showNewNotebook = false;
newNotebookName = '';
newNotebookParent = null;
return;
}
// Unfiled Notes is the root pseudo-notebook (empty relative_path); treat it as root.
newNotebookParent = ($viewMode === 'notebook' && $activeNotebook?.relative_path) ? $activeNotebook : null;
showNewNotebook = true;
await focusNewNotebookInput();
}
async function startNewNotebookFromSidebar(e: MouseEvent) {
const target = e.target as HTMLElement | null;
if (target?.closest('button, input, .context-menu, .delete-confirm-overlay')) return;
newNotebookParent = ($viewMode === 'notebook' && $activeNotebook?.relative_path) ? $activeNotebook : null;
newNotebookName = '';
showNewNotebook = true;
await focusNewNotebookInput();
}
async function handleCreateNotebook() {
if (!newNotebookName.trim()) return;
try {
const trimmedName = newNotebookName.trim();
const parentRel = newNotebookParent?.relative_path ?? null;
await createNotebook(parentRel, newNotebookName.trim());
const name = parentRel ? trimmedName : getNotebookNameSegments(trimmedName)?.join('/');
if (!name) return;
await createNotebook(parentRel, name);
newNotebookName = '';
showNewNotebook = false;
newNotebookParent = null;
@@ -196,7 +259,24 @@
}
}
function startNewSubNotebook(nb: NotebookEntry) {
function handleNewNotebookKeydown(e: KeyboardEvent) {
if (e.key === 'Enter') {
handleCreateNotebook();
return;
}
if (e.key === 'Escape') {
showNewNotebook = false;
newNotebookName = '';
newNotebookParent = null;
return;
}
if (e.key === 'Backspace' && newNotebookParent && newNotebookName.length === 0) {
e.preventDefault();
newNotebookParent = null;
}
}
async function startNewSubNotebook(nb: NotebookEntry) {
contextMenu = null;
newNotebookParent = nb;
newNotebookName = '';
@@ -205,6 +285,7 @@
if ($collapsedNotebooks.includes(nb.path)) {
$collapsedNotebooks = $collapsedNotebooks.filter(p => p !== nb.path);
}
await focusNewNotebookInput();
}
async function handleRename(nb: NotebookEntry) {
@@ -271,30 +352,34 @@
async function handleNotebookDrop(e: DragEvent, destPath: string) {
e.preventDefault();
dropTargetPath = null;
const srcPath = e.dataTransfer?.getData('text/plain');
if (!srcPath) return;
if (srcPath) await nestNotebook(srcPath, destPath);
}
async function nestNotebook(srcPath: string, destPath: string) {
dropTargetPath = null;
dropPosition = null;
draggedNotebookPath = null;
// Don't move onto self or descendant
if (destPath === srcPath || destPath.startsWith(srcPath + '/')) return;
if (destPath === srcPath || isDescendant(destPath, srcPath)) return;
// Don't move if already in that parent
const parentDir = srcPath.substring(0, srcPath.lastIndexOf('/'));
const parentDir = parentOf(srcPath);
if (parentDir === destPath) return;
try {
const oldName = srcPath.split('/').pop() || '';
const newBasePath = destPath + '/' + oldName;
const oldName = baseOf(srcPath);
const newBasePath = joinPath(destPath, oldName);
await moveNotebook(srcPath, destPath);
// Update collapsedNotebooks paths
$collapsedNotebooks = $collapsedNotebooks.map(p => {
if (p === srcPath) return newBasePath;
if (p.startsWith(srcPath + '/')) return newBasePath + p.slice(srcPath.length);
if (isDescendant(p, srcPath)) return newBasePath + p.slice(srcPath.length);
return p;
});
// Update active notebook/note if inside the moved notebook
if ($activeNotebook?.path === srcPath || $activeNotebook?.path.startsWith(srcPath + '/')) {
if ($activeNotebook?.path === srcPath || isDescendant($activeNotebook?.path ?? '', srcPath)) {
selectAllNotes();
}
if ($activeNotePath && $activeNotePath.startsWith(srcPath + '/')) {
if ($activeNotePath && isDescendant($activeNotePath, srcPath)) {
const newNotePath = newBasePath + $activeNotePath.slice(srcPath.length);
$activeNotePath = newNotePath;
$activeNote = await readNote(newNotePath);
@@ -306,10 +391,74 @@
}
}
function nbStopDragListeners() {
window.removeEventListener('pointermove', nbPointerMove);
window.removeEventListener('pointerup', nbDragEnd);
window.removeEventListener('pointercancel', nbDragEnd);
window.removeEventListener('mouseup', nbDragEnd);
}
function nbHandleDown(e: PointerEvent, nb: NotebookEntry) {
if (e.pointerType === 'mouse' && e.button !== 0) return;
e.stopPropagation();
e.preventDefault();
nbStopDragListeners();
nbPointer = { src: nb.path };
draggedNotebookPath = nb.path;
// Capture helps touch hold the gesture; on Windows mouse it makes WebView2 swallow the release, so skip it there.
if (e.pointerType === 'touch') {
try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); } catch {}
}
window.addEventListener('pointermove', nbPointerMove, { passive: false });
window.addEventListener('pointerup', nbDragEnd);
window.addEventListener('pointercancel', nbDragEnd);
window.addEventListener('mouseup', nbDragEnd);
}
function nbPointerMove(e: PointerEvent) {
if (!nbPointer) return;
e.preventDefault();
const el = document.elementFromPoint(e.clientX, e.clientY) as HTMLElement | null;
if (el?.closest('[data-nb-root]')) { dropTargetPath = '__root__'; dropPosition = null; return; }
const row = el?.closest('[data-nb-path]') as HTMLElement | null;
const path = row?.getAttribute('data-nb-path');
if (!path) { dropTargetPath = null; dropPosition = null; return; }
const src = nbPointer.src;
if (path === src || path.startsWith(src + '/')) { dropTargetPath = null; dropPosition = null; return; }
const rect = row!.getBoundingClientRect();
const relY = (e.clientY - rect.top) / rect.height;
const pos: 'above' | 'into' | 'below' = relY < 0.3 ? 'above' : relY > 0.7 ? 'below' : 'into';
if (pos === 'into' && src.substring(0, src.lastIndexOf('/')) === path) { dropTargetPath = null; dropPosition = null; return; }
dropTargetPath = path;
dropPosition = pos;
}
function nbDragEnd() {
if (!nbPointer) return;
nbStopDragListeners();
const src = nbPointer.src;
const target = dropTargetPath;
const pos = dropPosition;
nbPointer = null;
draggedNotebookPath = null;
dropTargetPath = null;
dropPosition = null;
if (!target) return;
if (target === '__root__') {
const vaultRoot = $appConfig?.active_vault;
if (vaultRoot) nestNotebook(src, vaultRoot);
} else if (pos === 'above' || pos === 'below') {
handleNotebookReorder(src, target, pos);
} else if (pos === 'into') {
nestNotebook(src, target);
}
}
function findSiblingsOfPath(tree: NotebookEntry[], parentPath: string, vaultRoot: string): NotebookEntry[] {
if (parentPath === vaultRoot) return tree;
const target = norm(parentPath);
if (target === norm(vaultRoot)) return tree;
for (const nb of tree) {
if (nb.path === parentPath) return nb.children;
if (norm(nb.path) === target) return nb.children;
if (nb.children.length > 0) {
const found = findSiblingsOfPath(nb.children, parentPath, vaultRoot);
if (found.length > 0) return found;
@@ -323,41 +472,39 @@
dropPosition = null;
draggedNotebookPath = null;
if (srcPath === targetPath) return;
if (targetPath.startsWith(srcPath + '/')) return; // can't move into descendant
if (isDescendant(targetPath, srcPath)) return; // can't move into descendant
const vaultRoot = $appConfig?.active_vault;
if (!vaultRoot) return;
const srcParent = srcPath.substring(0, srcPath.lastIndexOf('/'));
const targetParent = targetPath.substring(0, targetPath.lastIndexOf('/'));
const srcParent = parentOf(srcPath);
const targetParent = parentOf(targetPath);
let actualSrcPath = srcPath;
try {
// Step 1: if different parents, move src into target's parent first
if (srcParent !== targetParent) {
const oldName = srcPath.split('/').pop() || '';
const newPath = targetParent === vaultRoot
? vaultRoot + '/' + oldName
: targetParent + '/' + oldName;
const oldName = baseOf(srcPath);
const newPath = joinPath(targetParent, oldName);
await moveNotebook(srcPath, targetParent);
// Migrate paths in collapsedNotebooks
$collapsedNotebooks = $collapsedNotebooks.map(p => {
if (p === srcPath) return newPath;
if (p.startsWith(srcPath + '/')) return newPath + p.slice(srcPath.length);
if (isDescendant(p, srcPath)) return newPath + p.slice(srcPath.length);
return p;
});
// Migrate paths in notebookOrder
const migrated: Record<string, number> = {};
for (const [p, v] of Object.entries($notebookOrder)) {
if (p === srcPath) migrated[newPath] = v;
else if (p.startsWith(srcPath + '/')) migrated[newPath + p.slice(srcPath.length)] = v;
else if (isDescendant(p, srcPath)) migrated[newPath + p.slice(srcPath.length)] = v;
else migrated[p] = v;
}
$notebookOrder = migrated;
// Update active notebook/note
if ($activeNotebook?.path === srcPath || $activeNotebook?.path.startsWith(srcPath + '/')) {
if ($activeNotebook?.path === srcPath || isDescendant($activeNotebook?.path ?? '', srcPath)) {
selectAllNotes();
}
if ($activeNotePath && $activeNotePath.startsWith(srcPath + '/')) {
if ($activeNotePath && isDescendant($activeNotePath, srcPath)) {
const newNotePath = newPath + $activeNotePath.slice(srcPath.length);
$activeNotePath = newNotePath;
$activeNote = await readNote(newNotePath);
@@ -394,10 +541,13 @@
}
}
function startRename(nb: NotebookEntry) {
async function startRename(nb: NotebookEntry) {
contextMenu = null;
editingNotebook = nb.path;
editValue = nb.name;
await tick();
renameInput?.focus();
renameInput?.select();
}
async function handleSetIcon(nb: NotebookEntry) {
@@ -486,7 +636,7 @@
<svelte:window onclick={handleWindowClick} />
<aside class="sidebar" class:collapsed={$sidebarCollapsed} class:mobile={isMobile}>
<aside class="sidebar" class:collapsed={$sidebarCollapsed} class:mobile={isMobile} class:nav-empty={!anyNavItem}>
{#if !isMobile}
<div class="sidebar-header">
<button class="collapse-btn" onclick={() => ($sidebarCollapsed = !$sidebarCollapsed)} title="Toggle sidebar">
@@ -498,19 +648,19 @@
{/if}
</svg>
</button>
{#if !$sidebarCollapsed}
<button class="icon-btn" onclick={() => ($showSearch = true)} title={`Search (${modKey}+F)`}>
<svg width="16" height="16" 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>
{/if}
</div>
{/if}
{#if !$sidebarCollapsed}
{#if anyNavItem}
<nav class="sidebar-nav">
{#if $appConfig?.show_all_notes !== false}
<button
class="nav-item"
class:active={$viewMode === 'all'}
@@ -522,7 +672,9 @@
</svg>
<span>All Notes</span>
</button>
{/if}
{#if $appConfig?.show_quick_access !== false}
<button
class="nav-item"
class:active={$viewMode === 'quickaccess'}
@@ -533,7 +685,9 @@
</svg>
<span>Quick Access</span>
</button>
{/if}
{#if $appConfig?.show_tasks !== false}
<button
class="nav-item"
class:active={$viewMode === 'tasks'}
@@ -545,7 +699,9 @@
</svg>
<span>Tasks</span>
</button>
{/if}
{#if $appConfig?.show_daily_notes !== false}
<button
class="nav-item"
class:active={$viewMode === 'daily'}
@@ -559,7 +715,9 @@
</svg>
<span>Daily Notes</span>
</button>
{/if}
{#if $appConfig?.show_trash !== false}
<button
class="nav-item"
class:active={$viewMode === 'trash'}
@@ -571,13 +729,17 @@
</svg>
<span>Trash</span>
</button>
{/if}
</nav>
{/if}
<div class="section">
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="section" ondblclick={startNewNotebookFromSidebar}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="section-header"
class:drop-target={dropTargetPath === '__root__'}
data-nb-root
ondragover={(e) => {
if (draggedNotebookPath) {
e.preventDefault();
@@ -606,15 +768,7 @@
</svg>
</button>
{/if}
<button class="icon-btn-sm" onclick={() => {
if (showNewNotebook) {
showNewNotebook = false; newNotebookName = ''; newNotebookParent = null;
} else {
// Unfiled Notes is the root pseudo-notebook (empty relative_path); treat it as root.
newNotebookParent = ($viewMode === 'notebook' && $activeNotebook?.relative_path) ? $activeNotebook : null;
showNewNotebook = true;
}
}} title={$viewMode === 'notebook' && $activeNotebook?.relative_path ? `New notebook inside ${$activeNotebook.name}` : 'New notebook'}>
<button class="icon-btn-sm" onclick={toggleNewNotebookInput} title={$viewMode === 'notebook' && $activeNotebook?.relative_path ? `New notebook inside ${$activeNotebook.name}` : 'New notebook'}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
@@ -630,13 +784,11 @@
</button>
{/if}
<input
bind:this={newNotebookInput}
type="text"
bind:value={newNotebookName}
placeholder={newNotebookParent ? 'Sub-notebook name...' : 'Notebook name...'}
onkeydown={(e) => {
if (e.key === 'Enter') handleCreateNotebook();
if (e.key === 'Escape') { showNewNotebook = false; newNotebookName = ''; newNotebookParent = null; }
}}
onkeydown={handleNewNotebookKeydown}
/>
</div>
{/if}
@@ -708,6 +860,7 @@
{/if}
</div>
{/if}
{/if}
<div class="sidebar-footer">
<button class="icon-btn" onclick={() => ($showInfo = true)} title="Info">
@@ -727,7 +880,6 @@
</div>
</div>
{/if}
</aside>
{#if contextMenu}
@@ -794,6 +946,7 @@
<input
type="text"
class="rename-input"
bind:this={renameInput}
bind:value={editValue}
onkeydown={(e) => {
if (e.key === 'Enter') handleRename(nb);
@@ -810,11 +963,15 @@
class:drop-above={dropTargetPath === nb.path && dropPosition === 'above'}
class:drop-below={dropTargetPath === nb.path && dropPosition === 'below'}
style="padding-left: {8 + depth * 16}px"
draggable="true"
data-nb-path={nb.path}
onclick={() => selectNotebook(nb)}
onkeydown={(e) => {
if (e.key === 'F2') {
e.preventDefault();
startRename(nb);
}
}}
oncontextmenu={(e) => onContextMenu(e, nb)}
ondragstart={(e) => { draggedNotebookPath = nb.path; e.dataTransfer!.setData('text/plain', nb.path); e.dataTransfer!.effectAllowed = 'move'; }}
ondragend={() => { draggedNotebookPath = null; dropPosition = null; }}
ondragover={(e) => {
e.preventDefault();
if (draggedNotebookPath) {
@@ -863,7 +1020,7 @@
>
{#if hasChildren}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span class="chevron" class:collapsed={isCollapsed} onclick={(e) => toggleCollapse(nb.path, e)} onkeydown={(e) => { if (e.key === 'Enter') toggleCollapse(nb.path, e); }}>
<span class="chevron" class:collapsed={isCollapsed} onclick={(e) => toggleCollapse(nb, e)} onkeydown={(e) => { if (e.key === 'Enter') toggleCollapse(nb, e); }}>
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
@@ -879,6 +1036,17 @@
</svg>
{/if}
<span class="notebook-name">{nb.name} <span class="notebook-count">{nb.note_count}</span></span>
{#if $notebookSortMode === 'manual'}
<!-- svelte-ignore a11y_no_static_element_interactions a11y_click_events_have_key_events -->
<span
class="nb-drag-handle"
title="Drag to reorder"
onpointerdown={(e) => nbHandleDown(e, nb)}
onclick={(e) => e.stopPropagation()}
>
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="5" r="1.6"/><circle cx="15" cy="5" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="19" r="1.6"/><circle cx="15" cy="19" r="1.6"/></svg>
</span>
{/if}
</button>
{/if}
{#if hasChildren && !isCollapsed}
@@ -906,6 +1074,29 @@
max-width: 44px;
}
/* Collapsed rail: stack the toolbar icons vertically - search under the expand chevron at
the top, info + settings pinned to the bottom. */
.sidebar.collapsed .sidebar-header {
flex-direction: column;
justify-content: flex-start;
gap: 4px;
padding: 8px 4px;
border-bottom: none;
}
.sidebar.collapsed .sidebar-footer {
flex-direction: column;
align-items: center;
gap: 4px;
margin-top: auto;
padding: 8px 4px;
border-top: none;
}
.sidebar.collapsed .sidebar-footer-right {
flex-direction: column;
}
.sidebar-header {
display: flex;
align-items: center;
@@ -949,6 +1140,22 @@
flex: 1;
overflow-y: auto;
padding: 4px 0;
border-top: 1px solid var(--border-light);
}
/* With the top nav hidden, the header's border-bottom is the only divider needed -
drop the section's border-top so there's no doubled line under the header. */
.sidebar.nav-empty .section {
border-top: none;
}
/* Pin the Notebooks header so its collapse/expand-all button stays reachable while the tree
scrolls; the section's border-top draws the divider above it, matching the Tags section. (issue #126) */
.section > .section-header {
position: sticky;
top: 0;
z-index: 1;
background: var(--bg-secondary);
}
.tags-section {
@@ -1169,6 +1376,27 @@
margin-left: 2px;
}
.nb-drag-handle {
display: flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
padding: 2px;
margin-left: 2px;
color: var(--text-tertiary);
opacity: 0.45;
cursor: grab;
touch-action: none;
}
.nb-drag-handle:hover {
opacity: 1;
}
.nb-drag-handle:active {
cursor: grabbing;
}
.tag-list {
padding: 0 4px;
}
+1 -2
View File
@@ -16,11 +16,10 @@
// Existing tags that match what's typed, prefix matches first, already-applied ones excluded.
const suggestions = $derived.by(() => {
const q = query.trim().toLowerCase();
if (!q) return [];
const taken = new Set(existing);
const names = $tags
.map(([name]) => name)
.filter((name) => !taken.has(name) && name.toLowerCase().includes(q));
.filter((name) => !taken.has(name) && (!q || name.toLowerCase().includes(q)));
names.sort((a, b) => {
const ap = a.toLowerCase().startsWith(q) ? 0 : 1;
const bp = b.toLowerCase().startsWith(q) ? 0 : 1;
+2 -2
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import { getCurrentWindow } from '@tauri-apps/api/window';
import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, syncState } from '$lib/stores/app';
import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, activeVaultConfig, syncState } from '$lib/stores/app';
import { syncNow } from '$lib/api';
let { onNewNote = () => {}, onDailyNote = () => {} }: {
@@ -112,7 +112,7 @@
<line x1="3" y1="10" x2="21" y2="10" />
</svg>
</button>
{#if $appConfig?.sync_provider === 'webdav'}
{#if activeVaultConfig($appConfig)?.sync_provider === 'webdav'}
<button class="switch-vault-btn" class:active={$syncState.running} onclick={() => { if (!$syncState.running) syncNow().catch(() => {}); }} disabled={$syncState.running} title={$syncState.error ? `Sync error: ${$syncState.error}` : ($syncState.running ? 'Syncing vault...' : 'Sync vault now')}>
<svg width="14" height="14" 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"/>
+171
View File
@@ -0,0 +1,171 @@
// Obsidian-compatible callouts.
//
// Callouts are written as blockquotes whose first line is `[!type]`:
//
// > [!warning] Optional title
// > Body markdown...
//
// A trailing `+` / `-` on the type makes the callout foldable
// (`+` = expanded, `-` = collapsed). Types are case-insensitive and have
// aliases. Callouts round-trip to this exact syntax so notes stay portable
// (no lock-in) and stay compatible with Obsidian.
// alias (lowercase) -> canonical group used for icon + colour
const ALIASES: Record<string, string> = {
note: 'note',
abstract: 'abstract', summary: 'abstract', tldr: 'abstract',
info: 'info',
todo: 'todo',
tip: 'tip', hint: 'tip', important: 'tip',
success: 'success', check: 'success', done: 'success',
question: 'question', help: 'question', faq: 'question',
warning: 'warning', caution: 'warning', attention: 'warning',
failure: 'failure', fail: 'failure', missing: 'failure',
danger: 'danger', error: 'danger',
bug: 'bug',
example: 'example',
quote: 'quote', cite: 'quote',
};
/**
* Resolve a (possibly aliased / cased) type to its canonical styling group.
* Unknown / user-defined types resolve to 'custom' (neutral accent + tag icon)
* so a `[!decision]` reads as intentional rather than masquerading as a note.
*/
export function calloutGroup(type: string): string {
return ALIASES[(type || '').trim().toLowerCase()] || 'custom';
}
/** Default header label shown when no custom title is set (matches Obsidian). */
export function calloutLabel(type: string): string {
const t = (type || 'note').trim();
return t ? t.charAt(0).toUpperCase() + t.slice(1) : 'Note';
}
// Inner SVG markup per canonical group (24x24, stroke = currentColor).
const ICONS: Record<string, string> = {
note: '<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
abstract: '<rect x="8" y="2" width="8" height="4" rx="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M9 12h6"/><path d="M9 16h6"/>',
info: '<circle cx="12" cy="12" r="10"/><line x1="12" y1="11" x2="12" y2="16"/><line x1="12" y1="8" x2="12.01" y2="8"/>',
todo: '<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>',
tip: '<path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.07-2.14-.22-4.05 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.15.43-2.29 1-3a2.5 2.5 0 0 0 2.5 2.5Z"/>',
success: '<polyline points="20 6 9 17 4 12"/>',
question: '<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
warning: '<path d="m21.73 18-8-14a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
failure: '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>',
danger: '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
bug: '<rect x="8" y="6" width="8" height="14" rx="4"/><path d="m19 8-3 2"/><path d="m5 8 3 2"/><path d="m19 16-3-2"/><path d="m5 16 3-2"/><path d="M21 13h-5"/><path d="M3 13h5"/><path d="m15 4-1.5 2.5"/><path d="m9 4 1.5 2.5"/>',
example: '<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>',
quote: '<path d="M3 21c3 0 7-1 7-8V5c0-1.25-.76-2.02-2-2H4c-1.25 0-2 .75-2 1.97V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 0-1 1.03V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.76-2.02-2-2h-4c-1.25 0-2 .75-2 1.97V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/>',
custom: '<path d="M20.59 13.41 13.42 20.58a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>',
};
/** Full SVG icon string for a callout type, at the given pixel size. */
export function calloutIcon(type: string, size = 18): string {
const inner = ICONS[calloutGroup(type)] || ICONS.note;
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${inner}</svg>`;
}
/** Ordered list of types offered in the type picker. */
export const CALLOUT_MENU: { type: string; label: string }[] = [
{ type: 'note', label: 'Note' },
{ type: 'abstract', label: 'Abstract' },
{ type: 'info', label: 'Info' },
{ type: 'todo', label: 'Todo' },
{ type: 'tip', label: 'Tip' },
{ type: 'success', label: 'Success' },
{ type: 'question', label: 'Question' },
{ type: 'warning', label: 'Warning' },
{ type: 'failure', label: 'Failure' },
{ type: 'danger', label: 'Danger' },
{ type: 'bug', label: 'Bug' },
{ type: 'example', label: 'Example' },
{ type: 'quote', label: 'Quote' },
];
// First line of a callout: [!type], optional +/- fold marker, optional title.
const CALLOUT_RE = /^\s*\[!([\w-]+)\]([-+]?)[ \t]*(.*)$/;
const BLOCK_SELECTOR =
'p,ul,ol,blockquote,pre,h1,h2,h3,h4,h5,h6,table,hr,div[data-callout],div[data-secret-block],div[data-math-block],div[data-pdf-src],div[data-page-break]';
/**
* Convert callout blockquotes produced by markdown-it into
* `<div data-callout=...>` blocks that the Callout node parses. Operates in
* place on a detached container element. Processes depth-first so nested
* callouts (`> > [!todo]`) are converted before their parents.
*/
export function transformCalloutBlockquotes(root: Element): void {
const walk = (el: Element) => {
for (const child of Array.from(el.children)) walk(child);
if (el.tagName === 'BLOCKQUOTE') convertBlockquote(el);
};
walk(root);
}
function convertBlockquote(bq: Element): void {
const first = bq.firstElementChild;
if (!first || first.tagName !== 'P') return;
// markdown-it merges the title line and any immediately-following body lines
// into one paragraph (separated by "\n"). Split off the first line.
const innerHtml = (first as HTMLElement).innerHTML;
const nlIdx = innerHtml.indexOf('\n');
const firstLineHtml = nlIdx === -1 ? innerHtml : innerHtml.slice(0, nlIdx);
const restHtml = nlIdx === -1 ? '' : innerHtml.slice(nlIdx + 1);
const probe = document.createElement('div');
probe.innerHTML = firstLineHtml;
const m = (probe.textContent || '').match(CALLOUT_RE);
if (!m) return;
const type = m[1].toLowerCase();
const foldChar = m[2];
const title = (m[3] || '').trim();
const foldable = foldChar === '+' || foldChar === '-';
const folded = foldChar === '-';
const div = document.createElement('div');
div.setAttribute('data-callout', type);
div.setAttribute('data-callout-foldable', foldable ? 'true' : 'false');
div.setAttribute('data-callout-folded', folded ? 'true' : 'false');
if (title) div.setAttribute('data-callout-title', title);
if (restHtml.trim()) {
(first as HTMLElement).innerHTML = restHtml;
div.appendChild(first);
} else {
first.remove();
}
while (bq.firstChild) div.appendChild(bq.firstChild);
// content is `block+`; guarantee at least one block.
if (!div.querySelector(BLOCK_SELECTOR)) div.appendChild(document.createElement('p'));
bq.replaceWith(div);
}
/**
* Serialize a Callout ProseMirror node back to `> [!type] ...` markdown.
* `serializeChild` serializes a child block (the editor's own serializer),
* which makes nesting fall out automatically (each `>` line gains another `>`).
*/
export function serializeCallout(node: any, serializeChild: (child: any) => string): string {
const type = node.attrs.type || 'note';
const foldable = !!node.attrs.foldable;
const folded = !!node.attrs.folded;
const title = (node.attrs.title || '').trim();
const suffix = foldable ? (folded ? '-' : '+') : '';
const header = `[!${type}]${suffix}${title ? ' ' + title : ''}`;
const parts: string[] = [];
node.forEach((child: any) => parts.push(serializeChild(child).replace(/\n+$/, '')));
while (parts.length && parts[parts.length - 1] === '') parts.pop();
const out = [`> ${header}`];
const inner = parts.join('\n');
if (inner.length) {
for (const line of inner.split('\n')) out.push(line.length ? `> ${line}` : '>');
}
return out.join('\n') + '\n';
}
+164
View File
@@ -0,0 +1,164 @@
import { writable } from "svelte/store";
// A single key combination. `mod` means Ctrl on Windows/Linux and Cmd on macOS.
// `code` is a KeyboardEvent.code value (layout-independent), e.g. "KeyN",
// "Backslash", "ArrowLeft", "F11".
export interface Binding {
mod?: boolean;
shift?: boolean;
alt?: boolean;
code: string;
}
export interface ActionDef {
id: string;
label: string;
group: "General" | "Interface" | "Navigation";
default: Binding;
}
// Every customizable action and its factory-default binding. These mirror the
// handlers in AppLayout.handleKeydown and the rows in InfoPanel's Shortcuts tab.
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" } },
{ 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" } },
{ id: "toggle-sidebar", label: "Toggle sidebar", group: "Interface", default: { mod: true, code: "Backslash" } },
{ id: "toggle-notelist", label: "Toggle notes list", group: "Interface", default: { mod: true, shift: true, code: "Backslash" } },
{ id: "toggle-theme", label: "Toggle dark / light theme", group: "Interface", default: { mod: true, shift: true, code: "KeyN" } },
{ id: "toggle-focus", label: "Toggle focus mode", group: "Interface", default: { mod: true, shift: true, code: "KeyE" } },
{ id: "toggle-readonly", label: "Toggle read-only", group: "Interface", default: { mod: true, shift: true, code: "KeyR" } },
{ id: "toggle-source", label: "Toggle source / WYSIWYG", group: "Interface", default: { mod: true, shift: true, code: "KeyM" } },
{ id: "fullscreen", label: "Toggle fullscreen", group: "Interface", default: { code: "F11" } },
{ id: "nav-back", label: "Go back", group: "Navigation", default: { alt: true, code: "ArrowLeft" } },
{ id: "nav-forward", label: "Go forward", group: "Navigation", default: { alt: true, code: "ArrowRight" } },
];
export const DEFAULT_BINDINGS: Record<string, Binding> = Object.fromEntries(
ACTIONS.map((a) => [a.id, a.default]),
);
const STORAGE_KEY = "helix-keybindings";
function loadBindings(): Record<string, Binding> {
const merged: Record<string, Binding> = { ...DEFAULT_BINDINGS };
try {
const raw = typeof localStorage !== "undefined" && localStorage.getItem(STORAGE_KEY);
if (raw) {
const stored = JSON.parse(raw) as Record<string, Binding>;
for (const id of Object.keys(merged)) {
if (stored[id]) merged[id] = stored[id];
}
}
} catch {
// Corrupt storage - fall back to defaults.
}
return merged;
}
export const keybindings = writable<Record<string, Binding>>(loadBindings());
keybindings.subscribe((map) => {
try {
if (typeof localStorage !== "undefined") {
localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
}
} catch {
// Ignore quota / unavailable storage.
}
});
export function setBinding(id: string, binding: Binding) {
keybindings.update((m) => ({ ...m, [id]: binding }));
}
export function resetBinding(id: string) {
keybindings.update((m) => ({ ...m, [id]: DEFAULT_BINDINGS[id] }));
}
// True when the keyboard event matches the given binding exactly. Modifier
// state must match precisely so e.g. Mod+Shift+F never also triggers Mod+F.
export function matchBinding(e: KeyboardEvent, b: Binding | undefined): boolean {
if (!b) return false;
const mod = e.ctrlKey || e.metaKey;
return (
!!b.mod === mod &&
!!b.shift === e.shiftKey &&
!!b.alt === e.altKey &&
e.code === b.code
);
}
// Returns the id of the first action whose binding matches the event, or null.
export function matchAction(e: KeyboardEvent, map: Record<string, Binding>): string | null {
for (const id of Object.keys(map)) {
if (matchBinding(e, map[id])) return id;
}
return null;
}
// Build a Binding from a captured keydown event. Returns null for events that
// are only modifier keys (no real key pressed yet).
const MODIFIER_CODES = new Set([
"ControlLeft", "ControlRight", "MetaLeft", "MetaRight",
"ShiftLeft", "ShiftRight", "AltLeft", "AltRight",
]);
export function bindingFromEvent(e: KeyboardEvent): Binding | null {
if (MODIFIER_CODES.has(e.code) || !e.code) return null;
return {
mod: e.ctrlKey || e.metaKey,
shift: e.shiftKey,
alt: e.altKey,
code: e.code,
};
}
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: "[",
BracketRight: "]",
Comma: ",",
Period: ".",
Slash: "/",
Semicolon: ";",
Quote: "'",
Backquote: "`",
Minus: "-",
Equal: "=",
Space: "Space",
Enter: "Enter",
Tab: "Tab",
ArrowLeft: "←",
ArrowRight: "→",
ArrowUp: "↑",
ArrowDown: "↓",
};
function codeToLabel(code: string): string {
if (code.startsWith("Key")) return code.slice(3);
if (code.startsWith("Digit")) return code.slice(5);
if (code.startsWith("Numpad")) return code.slice(6);
return CODE_LABELS[code] ?? code;
}
// Ordered list of key labels for rendering, e.g. ["Ctrl", "Shift", "N"].
export function bindingToKeys(b: Binding): string[] {
const keys: string[] = [];
if (b.mod) keys.push(isMac ? "⌘" : "Ctrl");
if (b.alt) keys.push(isMac ? "⌥" : "Alt");
if (b.shift) keys.push(isMac ? "⇧" : "Shift");
keys.push(codeToLabel(b.code));
return keys;
}
+48 -5
View File
@@ -1,7 +1,50 @@
// Centralized platform detection. iOS WebViews report iPhone/iPad/iPod in the user
// agent (not the literal "ios"), so they must be matched explicitly.
// Platform is the compile-time build target, injected by the backend into
// window.__HELIX_PLATFORM__ before app scripts run (see src-tauri/src/lib.rs). The UA is only a
// fallback when that global is absent (SSR/prerender, plain-browser dev): some desktop WebKitGTK
// builds report a mobile-looking user-agent. (#63)
type HelixPlatform = { mobile: boolean; android: boolean; ios: boolean };
const injected: HelixPlatform | undefined =
typeof window !== 'undefined'
? (window as unknown as { __HELIX_PLATFORM__?: HelixPlatform }).__HELIX_PLATFORM__
: undefined;
const ua = typeof navigator !== 'undefined' ? navigator.userAgent : '';
export const isAndroid = /android/i.test(ua);
export const isIOS = /iphone|ipad|ipod/i.test(ua);
export const isMobile = isAndroid || isIOS;
export const isAndroid = injected ? injected.android : /android/i.test(ua);
export const isIOS = injected ? injected.ios : /iphone|ipad|ipod/i.test(ua);
export const isMobile = injected ? injected.mobile : isAndroid || isIOS;
// Themes that use the dark color scheme. Used by applyTheme() to toggle the
// `dark` class on the root element. Keep this in sync when adding new themes.
export const darkThemes = [
'dark',
'solarized-dark',
'catppuccin',
'nord',
'tokyo-night',
'github-dark',
'dracula',
'blueberry',
'forest-green',
'gruvbox',
'midnight-tide',
'cherry-blossom',
'synthwave',
'ember',
'moonlit',
'dark-coffee',
'crimson',
'material-dark',
'monokai',
'rose-pine',
'everforest',
'horizon',
'cyberpunk',
'black',
'one-dark',
];
export function isDarkTheme(theme: string): boolean {
return darkThemes.includes(theme) || (theme === 'system' && typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches);
}
+42 -7
View File
@@ -1,9 +1,12 @@
import { writable, derived, get } from "svelte/store";
import { isMobile } from "$lib/platform";
import type {
AppConfig,
CustomTheme,
NoteEntry,
NoteContent,
NotebookEntry,
VaultConfig,
VaultState,
ViewMode,
SortMode,
@@ -11,18 +14,28 @@ import type {
// App state
export const appConfig = writable<AppConfig | null>(null);
// The active vault's config entry (where per-vault WebDAV sync settings live).
export function activeVaultConfig(c: AppConfig | null): VaultConfig | null {
if (!c?.active_vault) return null;
return c.vaults.find((v) => v.path === c.active_vault) ?? null;
}
export const vaultReady = writable(false);
// UI state
export const viewMode = writable<ViewMode>("all");
export const sortMode = writable<SortMode>("modified");
// Group the notes list under relative-date headers (All Notes, date sorts only). Persisted per vault.
export const groupNotesByDate = writable<boolean>(false);
export const tasksLayout = writable<"list" | "calendar">("list");
export const tasksHideCompleted = writable<boolean>(true);
export const tasksOnlyFlagged = writable<boolean>(false);
export const tasksSort = writable<"due" | "priority" | "note">("due");
export const sidebarCollapsed = writable(false);
export const notelistCollapsed = writable(false);
export const sidebarWidth = writable(220);
export const notelistWidth = writable(280);
export const outlineWidth = writable(220);
export const searchQuery = writable("");
export const showCommandPalette = writable(false);
export const showSearch = writable(false);
@@ -39,6 +52,7 @@ export const notebookSortMode = writable<"alphabetical" | "manual">(
);
// Map from notebook absolute path → ordinal position (lower = earlier). Only consulted when notebookSortMode === 'manual'.
export const notebookOrder = writable<Record<string, number>>({});
export const noteOrder = writable<Record<string, number>>({});
// Data
export const notebooks = writable<NotebookEntry[]>([]);
@@ -70,6 +84,7 @@ export const readOnly = writable(false);
// Theme
export const theme = writable<string>("system");
export const customThemes = derived(appConfig, ($c): CustomTheme[] => $c?.custom_themes ?? []);
// Sync (WebDAV) - global status so the top-bar button reflects any sync,
// whoever triggered it (manual button, settings, interval, on-change).
@@ -85,11 +100,8 @@ export const updateAvailable = writable<{
} | null>(null);
export const updateObj = writable<any>(null);
export const installType = writable<string>("native");
// True only on the Android/iOS build. Defaults to a user-agent guess for the first paint, then
// gets the authoritative compile-time value from the backend at startup (see +layout). (#63)
export const platformIsMobile = writable<boolean>(
typeof navigator !== "undefined" && /android|iphone|ipad|ipod/i.test(navigator.userAgent),
);
// True only on the Android/iOS build. Reconfirmed from the backend at startup (see +layout). (#63)
export const platformIsMobile = writable<boolean>(isMobile);
export const androidApkUrl = writable<string | null>(null);
// Install types that handle their own updates (in-app auto-updater, or a
@@ -176,16 +188,30 @@ export const canGoForward = derived(navHistory, $h => $h.index < $h.stack.length
// Derived
export const sortedNotes = derived(
[notes, sortMode, viewMode],
([$notes, $sortMode, $viewMode]) => {
[notes, sortMode, viewMode, noteOrder],
([$notes, $sortMode, $viewMode, $noteOrder]) => {
// Quick Access preserves stored order
if ($viewMode === "quickaccess") return $notes;
const customSortable =
$viewMode === "all" || $viewMode === "notebook" || $viewMode === "tag";
const pinned = $notes.filter((n) => n.meta.pinned);
const unpinned = $notes.filter((n) => !n.meta.pinned);
const sortFn = (a: NoteEntry, b: NoteEntry) => {
switch ($sortMode) {
case "custom": {
if (!customSortable) {
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
const oa = $noteOrder[a.path] ?? Number.MAX_SAFE_INTEGER;
const ob = $noteOrder[b.path] ?? Number.MAX_SAFE_INTEGER;
if (oa !== ob) return oa - ob;
return a.meta.title.localeCompare(b.meta.title);
}
case "title":
return a.meta.title.localeCompare(b.meta.title);
case "created":
@@ -211,28 +237,37 @@ export const vaultState = derived(
activeNotePath,
sidebarWidth,
notelistWidth,
outlineWidth,
sidebarCollapsed,
notelistCollapsed,
collapsedNotebooks,
notebookSortMode,
notebookOrder,
noteOrder,
],
([
$activeNotePath,
$sidebarWidth,
$notelistWidth,
$outlineWidth,
$sidebarCollapsed,
$notelistCollapsed,
$collapsedNotebooks,
$notebookSortMode,
$notebookOrder,
$noteOrder,
]) => {
return {
last_open_note: $activeNotePath,
sidebar_width: $sidebarWidth,
notelist_width: $notelistWidth,
outline_width: $outlineWidth,
sidebar_collapsed: $sidebarCollapsed,
notelist_collapsed: $notelistCollapsed,
collapsed_notebooks: $collapsedNotebooks,
notebook_sort_mode: $notebookSortMode,
notebook_order: $notebookOrder,
note_order: $noteOrder,
} satisfies VaultState;
},
);
+41 -1
View File
@@ -44,6 +44,34 @@ export interface NoteContent {
export interface VaultConfig {
path: string;
name: string;
// Per-vault WebDAV sync (moved off the global AppConfig).
sync_provider?: string | null;
webdav_url?: string | null;
webdav_username?: string | null;
webdav_password?: string | null;
sync_on_open?: boolean;
sync_on_change?: boolean;
sync_interval_minutes?: number;
last_sync_time?: string | null;
}
export interface CustomThemeColors {
bg_primary: string;
bg_secondary: string;
bg_tertiary: string;
bg_hover: string;
bg_active: string;
bg_editor: string;
text_primary: string;
text_secondary: string;
border_color: string;
}
export interface CustomTheme {
id: string;
name: string;
is_dark: boolean;
colors: CustomThemeColors;
}
export interface AppConfig {
@@ -55,6 +83,7 @@ export interface AppConfig {
font_family: string | null;
line_height: number | null;
ui_scale: number | null;
content_width: number | null;
compact_notes: boolean;
show_note_dates: boolean;
time_format: string;
@@ -67,6 +96,12 @@ export interface AppConfig {
title_mode: string;
hide_title_in_body: boolean;
show_line_numbers: boolean;
show_link_arrows: boolean;
show_all_notes: boolean;
show_quick_access: boolean;
show_tasks: boolean;
show_daily_notes: boolean;
show_trash: boolean;
backup_enabled: boolean;
backup_frequency: string;
backup_max_count: number;
@@ -96,17 +131,22 @@ export interface AppConfig {
sync_on_change: boolean;
sync_interval_minutes: number;
last_sync_time: string | null;
custom_themes: CustomTheme[];
}
export interface VaultState {
last_open_note: string | null;
sidebar_width: number;
notelist_width: number;
outline_width?: number;
sidebar_collapsed: boolean;
notelist_collapsed: boolean;
collapsed_notebooks: string[];
notebook_sort_mode?: string;
notebook_order?: Record<string, number>;
note_order?: Record<string, number>;
sort_mode?: string;
group_notes_by_date?: boolean;
last_view_mode?: string;
last_notebook?: string | null;
last_tag?: string | null;
@@ -164,7 +204,7 @@ export interface NoteTitleEntry {
path: string;
}
export type SortMode = "modified" | "title" | "created";
export type SortMode = "modified" | "title" | "created" | "custom";
export type ViewMode =
| "all"
| "notebook"
+17
View File
@@ -24,3 +24,20 @@ export function formatDate(dateStr: string): string {
minute: '2-digit'
});
}
// Relative-date bucket label for grouping the notes list:
// Today / Yesterday / Previous 7 Days / Previous 30 Days / "June" (this year) / "June 2025".
// Buckets are contiguous, so a list already sorted by date groups by consecutive label.
export function dateBucketLabel(dateStr: string, now: Date = new Date()): string {
const d = new Date(dateStr);
const dayMs = 86400000;
const startOfDay = (x: Date) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
const today = startOfDay(now);
const day = startOfDay(d);
if (day >= today) return 'Today';
if (day >= today - dayMs) return 'Yesterday';
if (day >= today - 7 * dayMs) return 'Previous 7 Days';
if (day >= today - 30 * dayMs) return 'Previous 30 Days';
if (d.getFullYear() === now.getFullYear()) return d.toLocaleDateString(undefined, { month: 'long' });
return d.toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
}
+45 -12
View File
@@ -1,27 +1,62 @@
<script lang="ts">
import { onMount } from 'svelte';
import '../app.css';
import { theme, appConfig, activeNote, activeNotePath, installType, platformIsMobile, checkForUpdate, checkForUpdateMobile, isManagedInstall } from '$lib/stores/app';
import { theme, appConfig, activeNote, activeNotePath, installType, platformIsMobile, checkForUpdate, checkForUpdateMobile, isManagedInstall, customThemes } from '$lib/stores/app';
import { openFile, openUrl, readNote, getInstallType, isMobilePlatform } from '$lib/api';
import { get } from 'svelte/store';
import { darkThemes, isMobile, isAndroid } from '$lib/platform';
import type { CustomTheme } from '$lib/types';
import ResizeHandles from '$lib/components/ResizeHandles.svelte';
let { children } = $props();
const isMobile = /android|iphone|ipad|ipod/i.test(navigator.userAgent);
// Reactively apply theme class to <html> whenever $theme changes
// Reactively apply theme class to <html> whenever $theme or custom themes change
$effect(() => {
applyTheme($theme);
applyTheme($theme, $customThemes);
});
function applyTheme(t: string) {
const darkThemes = ['dark', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'dark-coffee', 'crimson', 'material-dark', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black'];
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'];
// Apply link arrow visibility from config
$effect(() => {
if ($appConfig) {
document.documentElement.classList.toggle('no-link-arrows', !$appConfig.show_link_arrows);
}
});
const CUSTOM_THEME_VARS = [
'--bg-primary', '--bg-secondary', '--bg-tertiary',
'--bg-hover', '--bg-active', '--bg-editor',
'--text-primary', '--text-secondary', '--border-color',
];
function applyCustomThemeVars(root: HTMLElement, ct: CustomTheme) {
root.style.setProperty('--bg-primary', ct.colors.bg_primary);
root.style.setProperty('--bg-secondary', ct.colors.bg_secondary);
root.style.setProperty('--bg-tertiary', ct.colors.bg_tertiary);
root.style.setProperty('--bg-hover', ct.colors.bg_hover);
root.style.setProperty('--bg-active', ct.colors.bg_active);
root.style.setProperty('--bg-editor', ct.colors.bg_editor);
root.style.setProperty('--text-primary', ct.colors.text_primary);
root.style.setProperty('--text-secondary', ct.colors.text_secondary);
root.style.setProperty('--border-color', ct.colors.border_color);
}
function clearCustomThemeVars(root: HTMLElement) {
for (const v of CUSTOM_THEME_VARS) root.style.removeProperty(v);
}
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 root = document.documentElement;
root.classList.remove('dark');
root.removeAttribute('data-theme');
if (namedThemes.includes(t)) {
clearCustomThemeVars(root);
if (t.startsWith('custom-')) {
const ct = themes.find(c => c.id === t);
if (ct) {
applyCustomThemeVars(root, ct);
if (ct.is_dark) root.classList.add('dark');
}
} else if (namedThemes.includes(t)) {
root.setAttribute('data-theme', t);
if (darkThemes.includes(t)) root.classList.add('dark');
} else if (t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
@@ -39,8 +74,6 @@
return resolved.join('/');
}
const isAndroid = /android/i.test(navigator.userAgent);
function openLocalFile(path: string) {
if (isAndroid) {
const bridge = (window as any).Android;
@@ -92,7 +125,7 @@
isMobilePlatform().then((m) => platformIsMobile.set(m)).catch(() => {});
if (isMobile) {
installType.set('android');
checkForUpdateMobile();
// Android updates come from the F-droid repo / Obtainium, so no in-app update check.
} else {
getInstallType().then(t => {
installType.set(t);
+5 -2
View File
@@ -2,6 +2,7 @@
import { onDestroy, onMount } from 'svelte';
import { appConfig, vaultReady, theme } from '$lib/stores/app';
import { getAppConfig, openVault, setFontSize } from '$lib/api';
import { darkThemes } from '$lib/platform';
import { getCurrentWebview } from '@tauri-apps/api/webview';
import VaultPicker from '$lib/components/VaultPicker.svelte';
import AppLayout from '$lib/components/AppLayout.svelte';
@@ -120,8 +121,7 @@
// Apply theme immediately to prevent flash
const themeValue = config.theme || 'system';
const root = document.documentElement;
const darkThemes = ['dark', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'dark-coffee', 'crimson'];
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'];
const namedThemes = ['solarized-light', 'solarized-dark', 'catppuccin', 'nord', 'tokyo-night', 'github-light', 'github-dark', 'dracula', 'blueberry', 'forest-green', 'gruvbox', 'midnight-tide', 'cherry-blossom', 'synthwave', 'ember', 'moonlit', 'light-coffee', 'dark-coffee', 'cotton-candy', 'crimson', 'cloud', 'peach', 'material-dark', 'material-light', 'monokai', 'rose-pine', 'everforest', 'horizon', 'cyberpunk', 'black', 'one-dark'];
root.classList.remove('dark');
root.removeAttribute('data-theme');
if (namedThemes.includes(themeValue)) {
@@ -138,6 +138,9 @@
if (config.line_height) {
document.documentElement.style.setProperty('--editor-line-height', String(config.line_height));
}
if (config.content_width) {
document.documentElement.style.setProperty('--editor-content-width', `${config.content_width}px`);
}
if (config.font_family) {
const fontStacks: Record<string, string> = {
system: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',