feat: add live preview and quick vault switching

This commit is contained in:
Yuri Karamian committed 2026-11-15 01:21:05 +04:00
1 parent 622cb1f397
commit 3c44458598
58 files changed
+2518 -171

No files matched your search

+2
View File
@@ -12,6 +12,8 @@ bun.lockb
.wrangler
/.svelte-kit
/build
/test-results/
/playwright-report/
# Nix
/result
+2
View File
@@ -163,6 +163,8 @@ All releases: [gitlab.com/ArkHost/HelixNotes/-/releases](https://gitlab.com/ArkH
- Manual notebook sorting (drag to reorder above, into, or below)
- External `.md` viewer mode with import-to-vault flow
- PDF preview, Obsidian import, "Show in File Manager"
- [Editable Live preview](docs/live-preview.md) alongside rich text and Markdown source, with one compact editor-mode selector and a three-button new-note preference (1.3.8, unreleased)
- [Quick vault switching](docs/vault-switching.md) from the title bar, with saved-vault paths, Add vault and Manage Vaults (1.3.8, unreleased)
- AI writing tools (Ollama / OpenAI-compatible / Anthropic / OpenAI)
- [Provider model discovery and opt-in image input](docs/ai-models-and-images.md) (1.3.8, unreleased)
- **Optional WebDAV sync** to your own server (Nextcloud, ownCloud, a NAS): manual or automatic, with keep-both conflict copies
+46
View File
@@ -0,0 +1,46 @@
# Live Preview
Unreleased work for 1.3.8. Application versions remain 1.3.7 until release preparation.
## Choose an editor mode
Use the existing source-code icon and its dropdown to choose **Rich text**, **Live preview** or **Markdown source**. The desktop editor, detached windows and tablet toolbar use the same compact selector. On phones, the three choices are in the note's **More** menu. They are also available in the command palette.
Edit/View remains a separate control. Choosing Live preview does not make a read-only note editable.
Live preview is an editable Markdown surface, not a split screen or a read-only rendered page. It shares its CodeMirror document with Markdown source. Switching between those two modes preserves the document, selection, undo/redo history and viewport anchor without converting HTML, marking the note dirty or triggering a save. Switching to or from Rich text still uses the existing editor-conversion path.
The current presentation is remembered for the window/session, not stored in the vault or synchronized. The existing source/rich-text shortcut returns to whichever Markdown presentation you last chose.
In **Settings → Editor → New note editor**, three joined buttons choose **Rich text**, **Live preview** or **Markdown source** for new empty notes. Fresh profiles default to Rich text; an existing “Open new notes in source mode” preference keeps Source selected. The preference is saved on this device. It does not change the current editor, existing notes, or the separate Edit/View preference. A failed save keeps the previous button selected and shows an error. The setting’s title and description occupy their own full-width row above the buttons.
## Editing
- Headings, bold, italic, strikethrough and inline code are styled inline.
- Syntax on the caret's line, or lines touched by a selection, remains visible for direct editing. A fenced code block reveals its fences while the selection is inside it.
- Inline Markdown links show their labels. Ctrl/Cmd-click opens a rendered link; Ctrl/Cmd-Enter opens the link under the caret.
- Bullet lists, blockquotes, horizontal rules and fenced code blocks have preview styling. Code contents stay literal source, not executable content.
- Task checkboxes are clickable away from the active line. Toggling changes only the checkbox character in Markdown and is undoable. Checkboxes are disabled in View mode.
- Inline Markdown images render through the existing asset/image-proxy resolver. Select an image to reveal and select its Markdown. Broken images retain a selectable source control.
- Copy and Find/Replace work against the Markdown document, not a generated HTML copy. Search selections reveal the syntax they touch.
- Live preview wraps lines and hides line numbers. Markdown source restores the existing line-number setting.
There is no separate preview buffer to save. Typing and checkbox edits use the existing source editor's save, conflict and history handling. Moving the caret, rendering an image, changing language or changing presentation does not edit the note.
## Initial scope
This is an initial Obsidian-style editing mode, not complete Obsidian compatibility. Tables, raw HTML, math, Mermaid diagrams, wiki links and reference-style links remain editable as source rather than receiving a second, potentially lossy interpretation. Very long paragraphs also stay source to bound rendering work. Imported HTML tables and other unsupported constructs are not rewritten by the preview.
Raw HTML is never inserted into preview DOM. Preview URLs reject executable schemes. Local files and remote images use the same scoped asset and image-proxy paths as the existing editor; previewing a remote image may contact its server, just as in rich text.
## Verification
```sh
pnpm verify
pnpm exec playwright install chromium # once, if a compatible browser is not installed
pnpm test:browser
```
The checked-in browser fixture uses the production SourceEditor, SourceController and mode selector. It exercises rendering, source/live switching, selection and copying, task edits, undo/redo, read-only guards, links, images, localization, narrow layouts, viewport preservation, large-note virtualization and unsafe-content fallback. It does not mock a successful preview operation or need a native vault.
Before release, also test the complete rebuilt app: rich-text transitions, saves/restarts, external changes and conflicts, AI actions, attachment insertion, detached windows, mobile touch selection and real IME input. The isolated browser fixture does not prove native-webview or end-to-end vault behaviour.
+36
View File
@@ -0,0 +1,36 @@
# Quick vault switching
Unreleased work for 1.3.8. Application versions remain 1.3.7.
The desktop title bar shows the current vault name beside the app name. Open its dropdown to switch directly to another saved vault. Each row shows its name and folder path, with a checkmark on the current vault. Paths distinguish vaults with identical names; long names truncate in the title bar but remain readable in the menu.
- **Add vault…** opens the desktop folder chooser. Choose an existing notes folder, or create a folder using the system dialog where available. Opening it registers the vault.
- **Manage Vaults** opens the existing management screen, where vaults can be removed from the saved list. The quick menu does not contain removal actions.
- Choosing the current vault is a no-op: it does not save, reload or discard its draft.
The mobile home and note headers expose the same dropdown. Mobile **Add vault…** opens the existing platform-specific picker, retaining Android storage permissions and iOS local-folder/Files choices.
## Switching safely
A switch saves the current note and persists its vault layout before opening the destination. The old editor is frozen until activation succeeds and the new vault's layout replaces it. Native activation returns the committed configuration in the same response; there is no second config read that could fail after changing the native vault.
A save failure or an operation already using the editor blocks the switch. An unavailable destination leaves the previous vault and its text available. Only one switch can run at a time. Failed operations release the editing gate so they can be retried.
Saved-vault opens require an existing, registered folder and its initialized HelixNotes metadata. Missing folders and empty mount-point placeholders are not silently initialized as replacement vaults. Reconnect the storage or explicitly choose the folder again through Add/Manage. New folder initialization remains an explicit Add action.
The native operation checks the expected source vault's path and bookmark identity. iOS Files vaults restore by bookmark, allowing their provider path to change. Layouts are keyed by path and bookmark, and delayed sync events are scoped to that identity. Detached note windows keep their original vault; switching the main window does not move them or delete their files.
## Keyboard and appearance
- Enter/Space or Arrow Down opens the menu.
- Arrow Up/Down, Home/End and type-ahead move between choices.
- Escape or Tab closes the menu and returns focus to its trigger.
- Clicking outside dismisses it when no transition is running.
The menu follows app theme tokens, scrolls within the viewport and supports narrow screens. Its controls are excluded from title-bar dragging and double-click maximize handling.
## Verification
Run `pnpm verify` and `pnpm test:browser`. Unit tests cover transition ordering, cancellation, overlapping requests, failures, stale origins, preference preservation, atomic IPC responses and bookmark identity. Rust tests cover saved-folder validation and non-mutating rejection of missing folders, missing metadata, invalid paths and bookmark-only vaults. Browser tests use the production title bar, dropdown, source editor and coordinator with mocked native/save boundaries.
Before release, test rebuilt desktop/mobile apps with real file choosers, unavailable/removable storage, detached windows, background sync and iOS security-scoped folders. Browser mocks do not verify those platform boundaries.
+3
View File
@@ -14,6 +14,7 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test": "node --test tests/*.test.mjs src/lib/utils/*.test.mjs",
"test:rust": "cargo test --manifest-path src-tauri/Cargo.toml",
"test:browser": "playwright test --config tests/browser/playwright.config.ts --workers=2",
"lint:rust": "cargo fmt --manifest-path src-tauri/Cargo.toml --check && cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings",
"verify": "pnpm check && pnpm test && pnpm test:rust && pnpm lint:rust && pnpm build",
"tauri": "tauri",
@@ -21,6 +22,7 @@
"tauri:build": "tauri build"
},
"devDependencies": {
"@playwright/test": "1.58.2",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.70.2",
@@ -42,6 +44,7 @@
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.4",
"@lezer/markdown": "^1.7.2",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-fs": "^2.4.5",
+41
View File
@@ -29,6 +29,9 @@ importers:
'@lezer/highlight':
specifier: ^1.2.4
version: 1.2.4
'@lezer/markdown':
specifier: ^1.7.2
version: 1.7.2
'@tauri-apps/api':
specifier: ^2.10.1
version: 2.10.1
@@ -147,6 +150,9 @@ importers:
specifier: ^11.16.1
version: 11.16.1
devDependencies:
'@playwright/test':
specifier: 1.58.2
version: 1.58.2
'@sveltejs/adapter-auto':
specifier: ^7.0.0
version: 7.0.0(@sveltejs/kit@2.70.2(@sveltejs/vite-plugin-svelte@6.2.4(svelte@5.56.9)(vite@7.3.6(@types/node@26.2.0)(jiti@2.7.0)(lightningcss@1.32.0)))(svelte@5.56.9)(typescript@5.9.3)(vite@7.3.6(@types/node@26.2.0)(jiti@2.7.0)(lightningcss@1.32.0)))
@@ -453,6 +459,11 @@ packages:
os: [linux]
libc: [glibc]
'@playwright/test@1.58.2':
resolution: {integrity: sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==}
engines: {node: '>=18'}
hasBin: true
'@polka/url@1.0.0-next.29':
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
@@ -1438,6 +1449,11 @@ packages:
picomatch:
optional: true
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -1649,6 +1665,16 @@ packages:
resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
engines: {node: '>=12'}
playwright-core@1.58.2:
resolution: {integrity: sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==}
engines: {node: '>=18'}
hasBin: true
playwright@1.58.2:
resolution: {integrity: sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==}
engines: {node: '>=18'}
hasBin: true
points-on-curve@0.2.0:
resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==}
@@ -2118,6 +2144,10 @@ snapshots:
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
optional: true
'@playwright/test@1.58.2':
dependencies:
playwright: 1.58.2
'@polka/url@1.0.0-next.29': {}
'@remirror/core-constants@3.0.0': {}
@@ -3035,6 +3065,9 @@ snapshots:
optionalDependencies:
picomatch: 4.0.5
fsevents@2.3.2:
optional: true
fsevents@2.3.3:
optional: true
@@ -3213,6 +3246,14 @@ snapshots:
picomatch@4.0.5: {}
playwright-core@1.58.2: {}
playwright@1.58.2:
dependencies:
playwright-core: 1.58.2
optionalDependencies:
fsevents: 2.3.2
points-on-curve@0.2.0: {}
points-on-path@0.2.1:
+131 -39
View File
@@ -111,26 +111,57 @@ fn announce_rewritten_links<R: Runtime>(
// ── Vault Management ──
#[cfg(target_os = "ios")]
use tauri_plugin_ios_vault_access::{FolderSelection, IosVaultAccessExt};
#[cfg(test)]
mod vault_switch_tests;
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExternalVaultResult {
pub bookmark_id: String,
pub path: String,
pub name: String,
#[cfg(target_os = "ios")]
use tauri_plugin_ios_vault_access::IosVaultAccessExt;
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct VaultIdentity {
path: String,
bookmark_id: Option<String>,
}
#[cfg(target_os = "ios")]
impl From<FolderSelection> for ExternalVaultResult {
fn from(selection: FolderSelection) -> Self {
Self {
bookmark_id: selection.bookmark_id,
path: selection.path,
name: selection.name,
fn validate_vault_origin(
config: &AppConfig,
expected: Option<&VaultIdentity>,
) -> Result<(), String> {
if let Some(expected) = expected {
if config.active_vault.as_deref() != Some(expected.path.as_str())
|| config.active_bookmark_id != expected.bookmark_id
{
return Err("The active vault changed. Reopen the vault menu before switching.".into());
}
}
Ok(())
}
fn validate_vault_path(path: &str) -> Result<(), String> {
if !Path::new(path).is_absolute() {
return Err("Choose an absolute vault folder path.".into());
}
Ok(())
}
fn validate_saved_vault(config: &AppConfig, path: &str) -> Result<(), String> {
if !config
.vaults
.iter()
.any(|vault| vault.bookmark_id.is_none() && vault.path == path)
{
return Err("This vault is no longer in the saved list. Reopen the vault menu.".into());
}
if !Path::new(path).is_dir() {
return Err("This vault folder is unavailable. Reconnect its storage or choose it again; it was not recreated.".into());
}
// An unmounted drive can leave an empty mount-point directory behind. Saved
// vaults were already initialized; do not silently initialize that placeholder.
if !Path::new(path).join(".helixnotes/config.json").is_file() {
return Err("This saved vault's metadata is unavailable. Reconnect its storage or explicitly choose the folder again.".into());
}
Ok(())
}
fn open_vault_path(
@@ -138,7 +169,8 @@ fn open_vault_path(
state: &State<'_, AppState>,
path: String,
external: Option<(String, String)>,
) -> Result<std::sync::Arc<SearchIndex>, String> {
) -> Result<(std::sync::Arc<SearchIndex>, AppConfig), String> {
validate_vault_path(&path)?;
operations::ensure_vault_structure(&path)?;
// Stage the search index and watcher before replacing the active runtime.
@@ -196,14 +228,17 @@ fn open_vault_path(
return Err(error);
}
let old_search = search_slot.replace(search.clone());
*config = next;
*config = next.clone();
drop(config);
drop(search_slot);
// Index disposal and watcher shutdown must not hold global state slots.
state.retain_vault_watchers()?;
// Once configuration is committed, cleanup failures must not report activation
// failure and strand the frontend on the previous vault.
if let Err(error) = state.retain_vault_watchers() {
log::error!("Could not clean up vault watchers after activation: {error}");
}
drop(old_search);
Ok(search)
Ok((search, next))
}
#[tauri::command]
@@ -211,17 +246,29 @@ pub async fn open_vault(
app: AppHandle,
state: State<'_, AppState>,
path: String,
) -> Result<(), String> {
require_existing: Option<bool>,
expected: Option<VaultIdentity>,
) -> Result<AppConfig, String> {
let _transition = state.vault_transition.lock().await;
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
let search = open_vault_path(app.clone(), &state, path.clone(), None)?;
validate_vault_path(&path)?;
{
let config = state.config.lock().map_err(|error| error.to_string())?;
validate_vault_origin(&config, expected.as_ref())?;
if require_existing.unwrap_or(false) {
validate_saved_vault(&config, &path)?;
}
}
let (search, config) = open_vault_path(app.clone(), &state, path.clone(), None)?;
#[cfg(target_os = "ios")]
app.ios_vault_access().release_active()?;
if let Err(error) = app.ios_vault_access().release_active() {
log::error!("Could not release previous vault scope after activation: {error}");
}
if let Err(error) = search.queue_vault_refresh(&path) {
log::error!("Failed to queue opened vault search refresh: {error}");
}
Ok(())
Ok(config)
})
.await
.map_err(|error| error.to_string())?
@@ -231,7 +278,7 @@ pub async fn open_vault(
pub async fn choose_external_vault(
app: AppHandle,
state: State<'_, AppState>,
) -> Result<Option<ExternalVaultResult>, String> {
) -> Result<Option<AppConfig>, String> {
let _transition = state.vault_transition.lock().await;
#[cfg(target_os = "ios")]
{
@@ -244,7 +291,7 @@ pub async fn choose_external_vault(
if selection.cancelled {
return Ok(None);
}
let result = ExternalVaultResult::from(selection);
let result = selection;
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
let bookmark_was_registered = state
@@ -254,13 +301,13 @@ pub async fn choose_external_vault(
.vaults
.iter()
.any(|vault| vault.bookmark_id.as_deref() == Some(result.bookmark_id.as_str()));
let search = match open_vault_path(
let (search, config) = match open_vault_path(
app.clone(),
&state,
result.path.clone(),
Some((result.bookmark_id.clone(), result.name.clone())),
) {
Ok(search) => search,
Ok(opened) => opened,
Err(error) => {
let rollback = if bookmark_was_registered {
app.ios_vault_access().rollback_staged()
@@ -275,11 +322,13 @@ pub async fn choose_external_vault(
});
}
};
app.ios_vault_access().commit_staged()?;
if let Err(error) = app.ios_vault_access().commit_staged() {
log::error!("Could not finalize vault scope after activation: {error}");
}
if let Err(error) = search.queue_vault_refresh(&result.path) {
log::error!("Failed to queue opened vault search refresh: {error}");
}
Ok(Some(result))
Ok(Some(config))
})
.await
.map_err(|error| error.to_string())?
@@ -296,8 +345,20 @@ pub async fn restore_external_vault(
app: AppHandle,
state: State<'_, AppState>,
bookmark_id: String,
) -> Result<ExternalVaultResult, String> {
expected: Option<VaultIdentity>,
) -> Result<AppConfig, String> {
let _transition = state.vault_transition.lock().await;
{
let config = state.config.lock().map_err(|error| error.to_string())?;
validate_vault_origin(&config, expected.as_ref())?;
if !config
.vaults
.iter()
.any(|vault| vault.bookmark_id.as_deref() == Some(bookmark_id.as_str()))
{
return Err("This vault is no longer in the saved list. Reopen the vault menu.".into());
}
}
#[cfg(target_os = "ios")]
{
let resolver_app = app.clone();
@@ -306,16 +367,16 @@ pub async fn restore_external_vault(
})
.await
.map_err(|error| error.to_string())??;
let result = ExternalVaultResult::from(selection);
let result = selection;
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<AppState>();
let search = match open_vault_path(
let (search, config) = match open_vault_path(
app.clone(),
&state,
result.path.clone(),
Some((result.bookmark_id.clone(), result.name.clone())),
) {
Ok(search) => search,
Ok(opened) => opened,
Err(error) => {
return Err(match app.ios_vault_access().rollback_staged() {
Ok(()) => error,
@@ -325,11 +386,13 @@ pub async fn restore_external_vault(
});
}
};
app.ios_vault_access().commit_staged()?;
if let Err(error) = app.ios_vault_access().commit_staged() {
log::error!("Could not finalize vault scope after activation: {error}");
}
if let Err(error) = search.queue_vault_refresh(&result.path) {
log::error!("Failed to queue opened vault search refresh: {error}");
}
Ok(result)
Ok(config)
})
.await
.map_err(|error| error.to_string())?
@@ -2519,6 +2582,31 @@ pub async fn import_tag_icon(
// ── General Settings ──
#[cfg(test)]
mod editor_mode_tests;
fn persist_new_note_editor_mode(
config: &mut AppConfig,
mode: NewNoteEditorMode,
path: &Path,
) -> Result<(), String> {
let mut next = config.clone();
next.new_note_editor_mode = Some(mode);
next.new_notes_in_source_mode = mode != NewNoteEditorMode::Rich;
save_app_config_to(&next, path)?;
*config = next;
Ok(())
}
#[tauri::command]
pub fn set_new_note_editor_mode(
state: State<'_, AppState>,
mode: NewNoteEditorMode,
) -> Result<(), String> {
let mut config = state.config.lock().map_err(|error| error.to_string())?;
persist_new_note_editor_mode(&mut config, mode, &app_config_path()?)
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub fn set_general_settings(
@@ -2573,7 +2661,11 @@ pub fn set_general_settings(
config.show_line_numbers = show_line_numbers;
config.show_link_arrows = show_link_arrows;
config.default_view_mode = default_view_mode;
config.new_notes_in_source_mode = new_notes_in_source_mode;
config.new_notes_in_source_mode = config
.new_note_editor_mode
.map_or(new_notes_in_source_mode, |mode| {
mode != NewNoteEditorMode::Rich
});
config.show_tray_icon = show_tray_icon;
config.close_to_tray = close_to_tray;
config.enable_wiki_links = enable_wiki_links;
@@ -4406,7 +4498,7 @@ pub fn sync_now(app: AppHandle) -> Result<(), String> {
};
std::thread::spawn(move || {
use tauri::Emitter;
let result = crate::sync::run_sync(app.clone(), vault.clone(), cfg);
let result = crate::sync::run_sync(app.clone(), vault.clone(), bookmark_id.clone(), cfg);
app.state::<AppState>()
.syncing
.store(false, Ordering::SeqCst);
@@ -4429,7 +4521,7 @@ pub fn sync_now(app: AppHandle) -> Result<(), String> {
Err(e) => {
let _ = app.emit(
"sync-error",
serde_json::json!({ "vault_path": vault, "success": false, "error": e }),
serde_json::json!({ "vault_path": vault, "bookmark_id": bookmark_id, "success": false, "error": e }),
);
}
}
@@ -0,0 +1,59 @@
use super::*;
#[test]
fn new_note_preferences_round_trip_without_changing_other_settings() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("config.json");
let mut config = AppConfig {
theme: "custom".into(),
active_vault: Some("/notes/Work".into()),
..Default::default()
};
for mode in [
NewNoteEditorMode::Rich,
NewNoteEditorMode::Live,
NewNoteEditorMode::Source,
] {
persist_new_note_editor_mode(&mut config, mode, &path).unwrap();
let saved: AppConfig = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(saved.new_note_editor_mode, Some(mode));
assert_eq!(
saved.new_notes_in_source_mode,
mode != NewNoteEditorMode::Rich
);
assert_eq!(saved.theme, "custom");
assert_eq!(saved.active_vault.as_deref(), Some("/notes/Work"));
}
}
#[test]
fn failed_preference_save_retains_the_previous_in_memory_value() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("config.json");
std::fs::create_dir(&path).unwrap();
let mut config = AppConfig::default();
let before = serde_json::to_value(&config).unwrap();
assert!(persist_new_note_editor_mode(&mut config, NewNoteEditorMode::Live, &path).is_err());
assert_eq!(serde_json::to_value(&config).unwrap(), before);
assert!(path.is_dir());
}
#[test]
fn missing_or_invalid_new_fields_preserve_legacy_source_preferences() {
for legacy in [false, true] {
let mut value = serde_json::to_value(AppConfig::default()).unwrap();
value
.as_object_mut()
.unwrap()
.remove("new_note_editor_mode");
value["new_notes_in_source_mode"] = serde_json::json!(legacy);
let restored: AppConfig = serde_json::from_value(value.clone()).unwrap();
assert_eq!(restored.new_note_editor_mode, None);
assert_eq!(restored.new_notes_in_source_mode, legacy);
value["new_note_editor_mode"] = serde_json::json!("invalid-mode");
let restored: AppConfig = serde_json::from_value(value).unwrap();
assert_eq!(restored.new_note_editor_mode, None);
assert_eq!(restored.new_notes_in_source_mode, legacy);
}
assert!(serde_json::from_str::<NewNoteEditorMode>("\"invalid-mode\"").is_err());
}
@@ -0,0 +1,123 @@
use super::*;
fn config_for(path: &str, bookmark: Option<&str>) -> AppConfig {
AppConfig {
active_vault: Some(path.into()),
active_bookmark_id: bookmark.map(String::from),
vaults: vec![VaultConfig {
path: path.into(),
name: "Work".into(),
bookmark_id: bookmark.map(String::from),
..Default::default()
}],
..Default::default()
}
}
#[test]
fn expected_origin_checks_both_path_and_bookmark_without_touching_config() {
let config = config_for("/vault/Work", Some("bookmark-a"));
let before = serde_json::to_value(&config).unwrap();
for expected in [
VaultIdentity {
path: "/other/Work".into(),
bookmark_id: Some("bookmark-a".into()),
},
VaultIdentity {
path: "/vault/Work".into(),
bookmark_id: Some("bookmark-b".into()),
},
VaultIdentity {
path: "/vault/Work".into(),
bookmark_id: None,
},
] {
assert!(validate_vault_origin(&config, Some(&expected))
.unwrap_err()
.contains("active vault changed"));
}
assert!(validate_vault_origin(
&config,
Some(&VaultIdentity {
path: "/vault/Work".into(),
bookmark_id: Some("bookmark-a".into())
})
)
.is_ok());
assert!(validate_vault_origin(&config, None).is_ok());
assert_eq!(serde_json::to_value(&config).unwrap(), before);
}
#[test]
fn activation_rejects_empty_and_relative_paths_before_initializing_them() {
for path in ["", "relative/Work", "../outside"] {
assert!(validate_vault_path(path).is_err());
}
let root = tempfile::tempdir().unwrap();
assert!(validate_vault_path(root.path().to_str().unwrap()).is_ok());
}
#[test]
fn saved_local_vault_requires_a_registered_directory() {
let root = tempfile::tempdir().unwrap();
let path = root.path().to_str().unwrap();
operations::ensure_vault_structure(path).unwrap();
let metadata = std::fs::read(root.path().join(".helixnotes/config.json")).unwrap();
assert!(validate_saved_vault(&config_for(path, None), path).is_ok());
assert_eq!(
std::fs::read(root.path().join(".helixnotes/config.json")).unwrap(),
metadata
);
assert!(validate_saved_vault(&AppConfig::default(), path)
.unwrap_err()
.contains("saved list"));
let unrelated = tempfile::tempdir().unwrap();
assert!(
validate_saved_vault(&AppConfig::default(), unrelated.path().to_str().unwrap()).is_err()
);
assert!(!unrelated.path().join(".helixnotes").exists());
}
#[test]
fn an_empty_mount_point_is_not_initialized_as_a_replacement_vault() {
let root = tempfile::tempdir().unwrap();
let path = root.path().to_str().unwrap();
assert!(validate_saved_vault(&config_for(path, None), path)
.unwrap_err()
.contains("metadata"));
assert!(!root.path().join(".helixnotes").exists());
}
#[test]
fn missing_saved_folders_are_not_recreated_or_removed_from_the_list() {
let root = tempfile::tempdir().unwrap();
let missing = root.path().join("disconnected-drive/Work");
let path = missing.to_str().unwrap();
let config = config_for(path, None);
assert!(validate_saved_vault(&config, path)
.unwrap_err()
.contains("unavailable"));
assert!(!missing.exists());
assert!(!missing.parent().unwrap().exists());
assert_eq!(config.vaults.len(), 1);
assert_eq!(config.active_vault.as_deref(), Some(path));
}
#[test]
fn bookmark_vaults_must_be_resolved_by_bookmark_not_opened_as_local_paths() {
let root = tempfile::tempdir().unwrap();
let path = root.path().to_str().unwrap();
let config = config_for(path, Some("security-scoped-bookmark"));
assert!(validate_saved_vault(&config, path).is_err());
assert!(!root.path().join(".helixnotes").exists());
}
#[test]
fn a_saved_path_that_is_now_a_file_is_rejected_unchanged() {
let root = tempfile::tempdir().unwrap();
let file = root.path().join("Work");
std::fs::write(&file, "not a directory").unwrap();
let path = file.to_str().unwrap();
assert!(validate_saved_vault(&config_for(path, None), path).is_err());
assert_eq!(std::fs::read_to_string(file).unwrap(), "not a directory");
}
+1
View File
@@ -229,6 +229,7 @@ pub fn run() {
commands::set_tag_style,
commands::import_tag_icon,
commands::set_general_settings,
commands::set_new_note_editor_mode,
commands::get_quick_access,
commands::add_quick_access,
commands::remove_quick_access,
+3 -2
View File
@@ -1138,6 +1138,7 @@ pub fn test_connection(cfg: WebdavConfig) -> Result<String, String> {
pub fn run_sync(
app: tauri::AppHandle,
vault: String,
bookmark_id: Option<String>,
cfg: WebdavConfig,
) -> Result<SyncSummary, String> {
use std::sync::atomic::Ordering;
@@ -1151,7 +1152,7 @@ pub fn run_sync(
let _ = app.emit(
"sync-progress",
serde_json::json!({ "vault_path": vault, "status": "listing" }),
serde_json::json!({ "vault_path": vault, "bookmark_id": bookmark_id, "status": "listing" }),
);
let remote: HashMap<String, RemoteFile> = client
.list()?
@@ -1182,7 +1183,7 @@ pub fn run_sync(
let _ = app.emit(
"sync-progress",
serde_json::json!({ "vault_path": vault, "status": "syncing" }),
serde_json::json!({ "vault_path": vault, "bookmark_id": bookmark_id, "status": "syncing" }),
);
let mut changes = HashMap::new();
// Mute the watcher across local writes; its deferred batch also preserves
+12
View File
@@ -143,6 +143,14 @@ pub enum StartupView {
All,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NewNoteEditorMode {
Rich,
Live,
Source,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolbarLayout {
pub main: Vec<String>,
@@ -288,6 +296,9 @@ pub struct AppConfig {
pub default_view_mode: bool,
#[serde(default)]
pub new_notes_in_source_mode: bool,
/// None migrates the legacy boolean without changing existing Source preferences.
#[serde(default, deserialize_with = "lenient_option")]
pub new_note_editor_mode: Option<NewNoteEditorMode>,
#[serde(default)]
pub show_tray_icon: bool,
#[serde(default)]
@@ -426,6 +437,7 @@ impl Default for AppConfig {
ai_writing_style: None,
default_view_mode: false,
new_notes_in_source_mode: false,
new_note_editor_mode: None,
show_tray_icon: false,
close_to_tray: false,
enable_wiki_links: true,
+13 -6
View File
@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/core";
import type { Language } from './i18n/core';
import type { EditorMode } from './editor/mode';
import type { ExternalNoteReference } from "./editor/externalNote";
import type {
AppConfig,
@@ -19,22 +20,24 @@ import type {
BackupEntry,
VersionEntry,
TaskItem,
ExternalVaultResult,
VaultIdentity,
StartupView,
ToolbarLayout,
PendingOpenFile,
} from "./types";
export async function openVault(path: string): Promise<void> {
return invoke("open_vault", { path });
// Activation returns the committed configuration in the same IPC response. A second
// config read must not fail after the native vault has already changed.
export async function openVault(path: string, options: { existing?: boolean; expected?: VaultIdentity } = {}): Promise<AppConfig> {
return invoke("open_vault", { path, requireExisting: options.existing ?? false, expected: options.expected ?? null });
}
export async function chooseExternalVault(): Promise<ExternalVaultResult | null> {
export async function chooseExternalVault(): Promise<AppConfig | null> {
return invoke("choose_external_vault");
}
export async function restoreExternalVault(bookmarkId: string): Promise<ExternalVaultResult> {
return invoke("restore_external_vault", { bookmarkId });
export async function restoreExternalVault(bookmarkId: string, expected?: VaultIdentity): Promise<AppConfig> {
return invoke("restore_external_vault", { bookmarkId, expected: expected ?? null });
}
export async function removeVault(path: string, bookmarkId?: string | null): Promise<void> {
@@ -371,6 +374,10 @@ export async function importTagIcon(
return invoke("import_tag_icon", { vaultPath, tag, name, data });
}
export async function setNewNoteEditorMode(mode: EditorMode): Promise<void> {
return invoke('set_new_note_editor_mode', { mode });
}
export async function setGeneralSettings(
compactNotes: boolean,
timeFormat: string,
+103 -22
View File
@@ -7,11 +7,16 @@
import Sidebar from './Sidebar.svelte';
import NoteList from './NoteList.svelte';
import Editor from './Editor.svelte';
import EditorModePicker from './EditorModePicker.svelte';
import { editorMode, selectEditorMode, type EditorMode } from '$lib/editor/mode';
import SearchPanel from './SearchPanel.svelte';
import CommandPalette from './CommandPalette.svelte';
import SettingsPanel from './SettingsPanel.svelte';
import InfoPanel from './InfoPanel.svelte';
import TitleBar from './TitleBar.svelte';
import VaultSwitcher from './VaultSwitcher.svelte';
import { createVaultSwitch, activeVaultIdentity, mergeVaultActivation, vaultEventMatches } from '$lib/utils/vault-switch';
import { open as openFolderDialog } from '@tauri-apps/plugin-dialog';
import ResizeHandle from './ResizeHandle.svelte';
import TagLabel from './TagLabel.svelte';
import { getCurrentWindow } from '@tauri-apps/api/window';
@@ -38,6 +43,7 @@
sourceMode,
mobileView,
appConfig,
vaultReady,
quickAccessPaths,
tags,
notes,
@@ -82,7 +88,7 @@
tabletNavHidden = hidden;
localStorage.setItem('helix-tablet-nav-hidden', hidden ? '1' : '0');
}
import { loadVaultState, saveVaultState, readNote, deleteNote, createDailyNote, createBackup, getPendingOpenFile, ackPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api';
import { openVault, restoreExternalVault, loadVaultState, saveVaultState, readNote, deleteNote, createDailyNote, createBackup, getPendingOpenFile, ackPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api';
import { darkThemes, isAndroid } from '$lib/platform';
import { openNoteWindow } from '$lib/utils/window';
import { normalizeStartupView, resolveStartupTarget } from '$lib/utils/startup-view';
@@ -109,6 +115,7 @@
let outlineOpen = $state(false);
let outlinePanelId = $state('');
let mobileNoteMenuOpen = $state(false);
let vaultSwitchBusy = $state(false);
let mobileNoteMenuWrapper = $state<HTMLDivElement>();
let mobileNoteMenuTrigger = $state<HTMLButtonElement>();
let mobileNoteMenu = $state<HTMLDivElement>();
@@ -183,7 +190,9 @@
let unlistenVaultRestored: (() => void) | null = null;
let fileRefreshTimer: ReturnType<typeof setTimeout> | null = null;
const ownerVault = get(appConfig)?.active_vault ?? null;
activateVaultData(ownerVault);
const ownerBookmark = get(appConfig)?.active_bookmark_id ?? null;
// A fresh layout also reloads clean notes after returning from vault management.
activateVaultData(ownerVault, ownerBookmark, true);
let stateReady = false;
let restoringNote = false;
let disposed = false;
@@ -203,7 +212,8 @@
let fileRefreshRequest = 0;
function ownerIsCurrent() {
return !disposed && (get(appConfig)?.active_vault ?? null) === ownerVault;
const current = get(appConfig);
return !disposed && (current?.active_vault ?? null) === ownerVault && (current?.active_bookmark_id ?? null) === ownerBookmark;
}
function beginNavigation() {
@@ -445,10 +455,10 @@
function drainPendingOpenFiles() {
if (pendingOpenDrain) { pendingOpenNotification = true; return; }
if (!stateReady || !ownerIsCurrent()) return;
if (vaultSwitchBusy || !stateReady || !ownerIsCurrent()) return;
pendingOpenDrain = (async () => {
try {
while (ownerIsCurrent()) {
while (ownerIsCurrent() && !vaultSwitchBusy) {
const pending = await getPendingOpenFile();
if (!pending || !ownerIsCurrent()) break;
if (!(await handleOpenFile(pending.path))) break;
@@ -530,6 +540,7 @@
}
async function prepareVaultSwitch(): Promise<boolean> {
if (vaultSwitchBusy) return false;
const token = beginNavigation();
if (editor && !(await editor.flushSave())) return false;
if (!navigationIsCurrent(token)) return false;
@@ -537,6 +548,61 @@
return navigationIsCurrent(token);
}
const vaultSwitch = createVaultSwitch({
current: () => activeVaultIdentity(get(appConfig)),
busy: value => {
if (!disposed) {
vaultSwitchBusy = value;
if (value) { beginNavigation(); activeRefreshRequest++; }
else {
queueMicrotask(drainPendingOpenFiles);
const path = get(activeNotePath);
if (path && ownerIsCurrent()) void refreshActiveNote(path);
}
}
},
acquire: async () => {
if (!editor && get(editorDirty)) return null;
const token = beginNavigation();
const release = editor ? await editor.beginPathMutation() : () => {};
if (!release) return null;
if (!navigationIsCurrent(token)) { release(); return null; }
await persistVaultState();
if (!navigationIsCurrent(token)) { release(); return null; }
return release;
},
open: (target, expected) => target.bookmarkId
? restoreExternalVault(target.bookmarkId, expected)
: openVault(target.path, { existing: target.existing, expected }),
commit: async config => {
if (disposed) return;
$showSettings = false;
$showSearch = false;
$showCommandPalette = false;
$focusMode = false;
appConfig.update(current => mergeVaultActivation(current, config));
// The root keys AppLayout by path AND bookmark. Keep the old editor frozen
// until teardown, so its destroy hook cannot save into the new vault.
await tick();
},
manage: async () => {
if (disposed) return;
$showSettings = false;
$vaultReady = false;
await tick();
},
});
function addVault() {
// Keep mobile storage permissions, local-folder naming and iOS Files access
// in the existing platform-specific picker rather than inventing a second flow.
if (isMobile) return vaultSwitch.manage();
return vaultSwitch.add(async () => {
const selected = await openFolderDialog({ directory: true, multiple: false, title: $ui('ui.choose_notes_folder') });
return typeof selected === 'string' ? { path: selected, bookmarkId: null, existing: false } : null;
});
}
function handleSidebarResize(delta: number) {
$sidebarWidth = Math.max(160, Math.min(400, $sidebarWidth + delta));
persistState();
@@ -837,6 +903,7 @@
}
function handleMouseDown(e: MouseEvent) {
if (vaultSwitchBusy) { e.preventDefault(); return; }
if (e.button === 3) { e.preventDefault(); navigateHistory(-1); }
if (e.button === 4) { e.preventDefault(); navigateHistory(1); }
}
@@ -850,6 +917,7 @@
}
function handleKeydown(e: KeyboardEvent) {
if (vaultSwitchBusy) { e.preventDefault(); return; }
const mod = e.ctrlKey || e.metaKey;
const code = e.code;
@@ -998,12 +1066,12 @@
let activeRefreshRequest = 0;
async function refreshActiveNote(path: string, restored = false) {
if (path !== $activeNotePath || !$activeNote || !ownerIsCurrent()) return;
if (vaultSwitchBusy || path !== $activeNotePath || !$activeNote || !ownerIsCurrent()) return;
const request = ++activeRefreshRequest;
const openingNote = $activeNote;
try {
const content = await readNote(ownerVault!, path);
if (!ownerIsCurrent() || request !== activeRefreshRequest || $activeNotePath !== path) return;
if (vaultSwitchBusy || !ownerIsCurrent() || request !== activeRefreshRequest || $activeNotePath !== path) return;
if ($editorDirty) {
if (restored && content.raw !== editor?.getAcceptedRaw()) editor?.flagExternalConflict();
return;
@@ -1182,12 +1250,12 @@
backupInterval = setInterval(checkScheduledBackup, 5 * 60 * 1000);
// ── WebDAV sync: global status + auto-sync triggers ──
unlistenSync.push(await listen<{ vault_path: string }>('sync-progress', ({ payload }) => {
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: true, error: null, result: null });
unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null }>('sync-progress', ({ payload }) => {
if (ownerIsCurrent() && vaultEventMatches(payload, { path: ownerVault!, bookmarkId: ownerBookmark })) syncState.set({ running: true, error: null, result: null });
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null; success: boolean; summary?: SyncSummary; last_sync_time?: string | null }>('sync-done', ({ payload }) => {
if (!ownerIsCurrent() || payload.vault_path !== ownerVault) return;
if (!ownerIsCurrent() || !vaultEventMatches(payload, { path: ownerVault!, bookmarkId: ownerBookmark })) return;
syncState.set({ running: false, error: null,
result: payload.success ? { vault: payload.vault_path, summary: payload.summary ?? {} } : null });
if (!payload.success || !payload.last_sync_time) return;
@@ -1199,8 +1267,8 @@
});
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
unlistenSync.push(await listen<{ vault_path: string; error?: string }>('sync-error', ({ payload }) => {
if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: false, error: payload.error ?? 'Sync failed', result: null });
unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null; error?: string }>('sync-error', ({ payload }) => {
if (ownerIsCurrent() && vaultEventMatches(payload, { path: ownerVault!, bookmarkId: ownerBookmark })) syncState.set({ running: false, error: payload.error ?? 'Sync failed', result: null });
}));
if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; }
@@ -1252,6 +1320,8 @@
<svelte:window onkeydown={handleKeydown} onmousedown={isMobile ? undefined : handleMouseDown} />
<div class="vault-transition-shell" aria-busy={vaultSwitchBusy}>
<div class="vault-transition-content" inert={vaultSwitchBusy}>
{#if isMobile}
<!-- ═══ MOBILE LAYOUT ═══ -->
<div class="mobile-shell">
@@ -1285,19 +1355,22 @@
</div>
{/if}
{#if tabletNavShown || (!tabletLayout && $mobileView !== 'editor')}
<span class="mobile-header-title">
<div class="mobile-header-title">
{#if $mobileView === 'sidebar'}
HelixNotes
<VaultSwitcher vaults={$appConfig?.vaults ?? []} active={activeVaultIdentity($appConfig)} busy={vaultSwitchBusy} onselect={vaultSwitch.switchTo} onadd={addVault} onmanage={vaultSwitch.manage} />
{:else}
{#if $viewMode === 'notebook'}{$activeNotebook?.name ?? 'Notebook'}{:else if $viewMode === 'tag' && $activeTag}<TagLabel name={$activeTag} size={16} />{:else if $viewMode === 'quickaccess'}{$ui("ui.quick_access")}{:else if $viewMode === 'daily'}{$ui("ui.daily_notes")}{:else if $viewMode === 'tasks'}{$ui("ui.tasks")}{:else if $viewMode === 'trash'}{$ui("ui.trash")}{:else}{$ui("ui.all_notes")}{/if}
{/if}
</span>
</div>
{#if $globalUpdateAvailable && $mobileView === 'sidebar'}
<button class="mobile-update-badge" onclick={() => { $settingsTab = 'updates'; $showSettings = true; }}>
v{$globalUpdateAvailable.version}
</button>
{/if}
{/if}
{#if $mobileView === 'editor'}
<div class="mobile-vault-switcher"><VaultSwitcher vaults={$appConfig?.vaults ?? []} active={activeVaultIdentity($appConfig)} busy={vaultSwitchBusy} onselect={vaultSwitch.switchTo} onadd={addVault} onmanage={vaultSwitch.manage} /></div>
{/if}
<div class="mobile-header-actions">
{#if $mobileView === 'editor' || (tabletLayout && $activeNotePath)}
<button class="mobile-header-btn" class:active={$readOnly} disabled={isTrashedNote($activeNotePath, ownerVault)} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? $ui("ui.edit") : $ui("ui.view")} aria-label={$readOnly ? $ui("ui.edit") : $ui("ui.view")}>
@@ -1375,12 +1448,13 @@
{#if inMenu}<span>{$syncState.running ? $ui("ui.syncing") : $syncState.error ? $ui("ui.sync_error_retry") : $ui("ui.sync_now")}</span>{/if}
</button>
{/if}
<button class={inMenu ? 'mobile-note-menu-item' : 'mobile-header-btn'} type="button" role={inMenu ? 'menuitem' : undefined} class:active={$sourceMode} onclick={() => ($sourceMode = !$sourceMode)} title={$sourceMode ? $ui("ui.rich_editor") : $ui("ui.source_mode")}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
</svg>
{#if inMenu}<span>{$sourceMode ? $ui("ui.rich_editor") : $ui("ui.source_mode")}</span>{/if}
</button>
{#if inMenu}
{#each ['rich', 'live', 'source'] as mode}
<button class="mobile-note-menu-item" type="button" role="menuitemradio" aria-checked={$editorMode === mode} class:active={$editorMode === mode} onclick={() => selectEditorMode(mode as EditorMode)}>
<span>{$ui(mode === 'rich' ? 'editorMode.rich' : mode === 'live' ? 'editorMode.live' : 'editorMode.source')}</span>
</button>
{/each}
{:else}<EditorModePicker id="tablet-editor-mode" />{/if}
{/snippet}
{#if tabletLayout}
{@render secondaryNoteActions(false)}
@@ -1486,7 +1560,7 @@
</div>
</div>
{:else}
<TitleBar onNewNote={createAndFocusNote} onDailyNote={handleDailyNote} onSelectNote={selectNoteFromSwitcher} onBeforeVaultSwitch={prepareVaultSwitch} />
<TitleBar onNewNote={createAndFocusNote} onDailyNote={handleDailyNote} onSelectNote={selectNoteFromSwitcher} onSwitchVault={vaultSwitch.switchTo} onAddVault={addVault} onManageVaults={vaultSwitch.manage} switching={vaultSwitchBusy} />
{/if}
<div class="app-layout">
{#if !$focusMode}
@@ -1536,9 +1610,15 @@
<SearchPanel onSelectNote={selectNoteFromSearch} />
<CommandPalette onNavigate={handleViewChanged} />
<SettingsPanel onBeforeVaultSwitch={prepareVaultSwitch} />
</div>
{#if vaultSwitchBusy}<div class="vault-transition-status" role="status">{$ui('vaultSwitcher.switching')}</div>{/if}
</div>
<InfoPanel />
<style>
.vault-transition-shell, .vault-transition-content { width: 100%; height: 100%; min-height: 0; }
.vault-transition-shell { position: relative; }
.vault-transition-status { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 2300; max-width: calc(100vw - 32px); padding: 8px 14px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); color: var(--text-primary); font-size: 13px; pointer-events: none; }
/* ═══ DESKTOP STYLES ═══ */
.app-shell {
display: flex;
@@ -1737,6 +1817,7 @@
flex-shrink: 0;
}
.mobile-vault-switcher { min-width: 0; max-width: 160px; flex-shrink: 1; }
.mobile-header-actions {
display: flex;
align-items: center;
+5 -9
View File
@@ -1,7 +1,8 @@
<script lang="ts">
import { t as ui, label as uiLabel } from '$lib/i18n';
import { showCommandPalette, showSearch, theme, sourceMode, viewMode, activeNotebook, activeTag } from '$lib/stores/app';
import { showCommandPalette, showSearch, theme, viewMode, activeNotebook, activeTag } from '$lib/stores/app';
import { setTheme, reindex } from '$lib/api';
import { selectEditorMode } from '$lib/editor/mode';
import { darkThemes } from '$lib/platform';
// onNavigate runs the parent's view-change handler (refreshes the note list and reveals it
@@ -133,14 +134,9 @@
label: 'Switch to Dracula Theme',
action: () => { $theme = 'dracula'; setTheme('dracula'); applyTheme('dracula'); $showCommandPalette = false; }
},
{
id: 'toggle-source',
label: 'Toggle Source/WYSIWYG Mode',
action: () => {
$sourceMode = !$sourceMode;
$showCommandPalette = false;
}
},
{ id: 'editor-rich', label: 'Rich text', action: () => { selectEditorMode('rich'); $showCommandPalette = false; } },
{ id: 'editor-live', label: 'Live preview', action: () => { selectEditorMode('live'); $showCommandPalette = false; } },
{ id: 'editor-source', label: 'Markdown source', action: () => { selectEditorMode('source'); $showCommandPalette = false; } },
{
id: 'reindex',
label: 'Rebuild Search Index',
+29 -17
View File
@@ -37,7 +37,7 @@
import { readFile } from '@tauri-apps/plugin-fs';
import { openFile, openUrl, copyFileTo, copyImageToClipboard as copyImageToClipboardCmd, writeBytesTo, copyPngToClipboard, copyTextToClipboard } from '$lib/api';
import { save as saveDialog } from '@tauri-apps/plugin-dialog';
import { activeNote, activeNotePath, appConfig, editorDirty, sourceMode, focusMode, readOnly, quickAccessPaths, notes, navHistory, canGoBack, canGoForward, viewerNote, viewMode, notebooks, outlineWidth } from '$lib/stores/app';
import { activeNote, activeNotePath, appConfig, editorDirty, sourceMode, livePreviewMode, focusMode, readOnly, quickAccessPaths, notes, navHistory, canGoBack, canGoForward, viewerNote, viewMode, notebooks, outlineWidth } from '$lib/stores/app';
import { saveNote, importNote, createNote, saveImage, saveAttachment, readClipboardImage, readClipboardContents, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api';
import type { NoteContent, VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types';
import { listen } from '@tauri-apps/api/event';
@@ -56,6 +56,8 @@
import { defaultGridCols, expandImageRange, reorderTarget, serializeImgGrid } from '$lib/editor/imageGrid';
import { calloutGroup, calloutIcon, calloutLabel, CALLOUT_MENU, transformCalloutBlockquotes, serializeCallout } from '$lib/editor/callouts';
import SourceEditor from './SourceEditor.svelte';
import EditorModePicker from './EditorModePicker.svelte';
import { newNoteEditorMode, selectEditorMode } from '$lib/editor/mode';
import { SourceController } from '$lib/editor/source/controller';
import { findDocumentMatches, findSourceMatches, closestSearchMatch, type NoteSearchMatch, replaceableMatches } from '$lib/editor/search';
import { keybindings, bindingToKeys } from '$lib/keybindings';
@@ -195,6 +197,7 @@
scheduleOutlineActive();
}
}, { paste: handleFilePaste, drop: handleFileDrop, scroll: scheduleOutlineActive });
const sourceAssetContext = $derived(`${$activeNotePath ?? ''}|${currentNoteAssetRoot() ?? ''}`);
let loadedPath = '';
type NoteScrollPosition = { rich: number; source: number };
const MAX_NOTE_SCROLL_POSITIONS = 200;
@@ -4027,7 +4030,10 @@
externalOperationBusy = true;
source.configure(true, !isMobile && ($appConfig?.show_line_numbers ?? false));
editor?.setEditable(false);
let released = false;
return () => {
if (released || editorDisposed) return;
released = true;
externalOperationBusy = false;
source.configure($readOnly || !!$viewerNote, !isMobile && ($appConfig?.show_line_numbers ?? false));
editor?.setEditable(!$readOnly && !$viewerNote);
@@ -4118,12 +4124,10 @@
isLoadingNote = true;
isLargeDoc = content.length > LARGE_DOC_CHARS;
// Viewer mode (external file) always forces read-only. New notes stay editable and
// can opt into source mode without changing how existing notes choose their mode.
// use the saved editor preference without changing existing notes' presentation.
const isViewer = !!get(viewerNote);
const isNewNote = $activeNote?.meta.title === 'Untitled' && !content.replace(/^---[\s\S]*?---\s*/, '').trim();
if (isNewNote && ($appConfig?.new_notes_in_source_mode ?? false)) {
$sourceMode = true;
}
if (isNewNote && !isViewer) selectEditorMode(newNoteEditorMode($appConfig));
lastSourceMode = $sourceMode;
const shouldBeReadOnly = isViewer || isTrashedNote(path, $appConfig?.active_vault)
? true : (isNewNote ? false : ($appConfig?.default_view_mode ?? false));
@@ -7077,6 +7081,23 @@
return path.endsWith('.md') ? path : null;
}
function openPreviewLink(href: string) {
if (href.startsWith('#')) {
let target = href.slice(1);
try { target = decodeURIComponent(target); } catch { return; }
const slug = (text: string) => text.toLocaleLowerCase().replace(/\s+/g, '-');
const heading = sourceHeadings(source.state).find(item => slug(item.text) === slug(target));
if (heading) { source.select(heading.pos, heading.pos, true); source.focus(); }
return;
}
const notePath = resolveNoteHref(href);
if (notePath) { navigateToWikiLink(notePath, ''); return; }
if (/^(https?:|mailto:)/i.test(href)) void openUrl(href).catch(console.error);
else if (!/^[a-z][\w+.-]*:/i.test(href) || /^[a-z]:[\\/]/i.test(href)) {
void openFile(resolveHrefToAbsPath(href)).catch(console.error);
}
}
function linkMenuOpen() {
if (!linkContextMenu) return;
const href = linkContextMenu.href;
@@ -8220,16 +8241,7 @@
</svg>
</button>
{/if}
<button
class="icon-btn"
class:active={$sourceMode}
onclick={() => ($sourceMode = !$sourceMode)}
title={$ui("ui.toggle_markdown_editor")}
>
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M5.854 4.854a.5.5 0 10-.708-.708l-3.5 3.5a.5.5 0 000 .708l3.5 3.5a.5.5 0 00.708-.708L2.707 8l3.147-3.146zm4.292 0a.5.5 0 01.708-.708l3.5 3.5a.5.5 0 010 .708l-3.5 3.5a.5.5 0 01-.708-.708L13.293 8l-3.147-3.146z" />
</svg>
</button>
<EditorModePicker id={`${componentId}-editor-mode`} disabled={externalOperationBusy} />
</div>
{/if}
</div>
@@ -8356,12 +8368,12 @@
<div class="editor-body-row" class:reviewing-history={showHistory}>
<div class="editor-body" class:source-body={$sourceMode} class:history-hidden={showHistory} onscroll={scheduleOutlineActive}>
{#if isMobile}
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} visible={$sourceMode} mobile />
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} visible={$sourceMode} preview={$livePreviewMode} resolveImage={resolveImageSrc} openLink={openPreviewLink} context={sourceAssetContext} mobile />
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="tiptap-wrapper" class:large-doc={isLargeDoc} style={$sourceMode ? 'display:none' : ''} spellcheck="false" bind:this={editorElement} onerrorcapture={retryFailedImage} onclick={(e) => { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }}></div>
{:else}
{#if $sourceMode}
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} numbers={$appConfig?.show_line_numbers ?? false} />
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} numbers={$appConfig?.show_line_numbers ?? false} preview={$livePreviewMode} resolveImage={resolveImageSrc} openLink={openPreviewLink} context={sourceAssetContext} />
{:else}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="tiptap-wrapper" class:large-doc={isLargeDoc} spellcheck="false" bind:this={editorElement} onerrorcapture={retryFailedImage} onclick={(e) => { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }} oncontextmenu={handleEditorContextMenu}></div>
@@ -0,0 +1,55 @@
<script lang="ts">
import { onDestroy, tick } from 'svelte';
import { t } from '$lib/i18n';
import type { EditorMode } from '$lib/editor/mode';
let { value, onchange, disabled = false }: { value: EditorMode; onchange: (mode: EditorMode) => Promise<void>; disabled?: boolean } = $props();
const group = $props.id();
let root: HTMLDivElement;
let pending = $state(false), error = $state('');
let disposed = false;
onDestroy(() => { disposed = true; });
const options = $derived([
{ value: 'rich' as const, label: $t('editorMode.rich') },
{ value: 'live' as const, label: $t('editorMode.live') },
{ value: 'source' as const, label: $t('editorMode.source') },
]);
async function choose(next: EditorMode) {
// Radio DOM changes immediately; keep the saved value selected until persistence succeeds.
for (const input of root.querySelectorAll<HTMLInputElement>('input')) input.checked = input.value === value;
if (pending || disabled || next === value) return;
const restore = root.contains(document.activeElement);
pending = true; error = '';
try { await onchange(next); }
catch (cause) { if (!disposed) error = String(cause); }
finally { if (!disposed) pending = false; }
await tick();
if (!disposed && restore && document.activeElement === document.body) root.querySelector<HTMLInputElement>('input:checked')?.focus();
}
</script>
<div class="editor-mode-preference" bind:this={root} aria-busy={pending}>
<fieldset role="radiogroup" aria-label={$t('editorMode.newNotes')} disabled={disabled || pending}>
{#each options as option}
<label>
<input type="radio" name={group} value={option.value} checked={value === option.value} onchange={() => choose(option.value)} />
<span>{option.label}</span>
</label>
{/each}
</fieldset>
{#if pending}<p role="status">{$t('ui.saving')}</p>{/if}
{#if error}<p role="alert">{$t('editorMode.saveFailed', { error })}</p>{/if}
</div>
<style>
.editor-mode-preference { min-width: 0; width: min(100%, 360px); }
fieldset { display: flex; padding: 0; margin: 0; min-width: 0; border: 1px solid var(--border-color); border-radius: 7px; overflow: hidden; }
label { position: relative; flex: 1; min-width: 0; display: flex; }
label + label { border-inline-start: 1px solid var(--border-color); }
input { position: absolute; width: 1px; height: 1px; opacity: 0; }
span { display: flex; align-items: center; justify-content: center; box-sizing: border-box; width: 100%; min-height: 38px; padding: 7px 10px; background: var(--bg-secondary); color: var(--text-secondary); font-size: 12px; line-height: 1.35; text-align: center; overflow-wrap: anywhere; cursor: pointer; }
input:checked + span { background: var(--accent-light, var(--bg-hover)); color: var(--accent); font-weight: 600; }
input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: -2px; }
input:disabled + span { opacity: .6; cursor: wait; }
p { margin: 8px 0 0; font-size: 12px; line-height: 1.4; color: var(--text-secondary); overflow-wrap: anywhere; }
@media (pointer: coarse) { span { min-height: 44px; } }
</style>
@@ -0,0 +1,13 @@
<script lang="ts">
import { t } from '$lib/i18n';
import { editorMode, selectEditorMode, type EditorMode } from '$lib/editor/mode';
import ThemedSelect from './ThemedSelect.svelte';
let { id, disabled = false }: { id: string; disabled?: boolean } = $props();
const options = $derived([
{ value: 'rich', label: $t('editorMode.rich') },
{ value: 'live', label: $t('editorMode.live') },
{ value: 'source', label: $t('editorMode.source') },
]);
</script>
<ThemedSelect {id} label={$t('editorMode.label')} {options} value={$editorMode} {disabled} compact onchange={value => selectEditorMode(value as EditorMode)} />
@@ -0,0 +1,21 @@
<script lang="ts">
import { t } from '$lib/i18n';
import type { EditorMode } from '$lib/editor/mode';
import EditorModeButtons from './EditorModeButtons.svelte';
let { value, onchange }: { value: EditorMode; onchange: (mode: EditorMode) => Promise<void> } = $props();
</script>
<div class="new-note-editor-setting">
<div class="preference-copy">
<span class="preference-name">{$t('editorMode.newNotes')}</span>
<span class="preference-description">{$t('editorMode.newNotesHelp')}</span>
</div>
<EditorModeButtons {value} {onchange} />
</div>
<style>
.new-note-editor-setting { display: flex; flex-direction: column; align-items: stretch; gap: 12px; width: 100%; min-width: 0; box-sizing: border-box; padding: 16px 0 10px; margin-top: 12px; border-top: 1px solid var(--border-light, var(--border-color)); }
.preference-copy { display: flex; flex-direction: column; gap: 3px; width: 100%; min-width: 0; }
.preference-name { color: var(--text-primary); font-size: 13px; font-weight: 500; }
.preference-description { color: var(--text-tertiary, var(--text-secondary)); font-size: 11px; line-height: 1.4; }
</style>
+2 -5
View File
@@ -5,6 +5,7 @@
import { getCurrentWebview } from '@tauri-apps/api/webview';
import { getCurrentWindow } from '@tauri-apps/api/window';
import Editor from './Editor.svelte';
import EditorModePicker from './EditorModePicker.svelte';
import {
appConfig,
activeNote,
@@ -266,11 +267,7 @@
{/if}
</div>
<div class="titlebar-actions">
<button class="nw-btn" class:active={$sourceMode} onclick={() => ($sourceMode = !$sourceMode)} title={$ui("ui.toggle_source_mode")}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
</svg>
</button>
<EditorModePicker id="detached-editor-mode" />
<button class="nw-btn" class:active={$readOnly} onclick={() => ($readOnly = !$readOnly)} title={$readOnly ? $ui("ui.switch_to_edit_mode") : $ui("ui.switch_to_view_mode")}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
{#if $readOnly}
+11 -13
View File
@@ -5,6 +5,9 @@
import { setLanguage } from '$lib/api';
import ThemedSelect from './ThemedSelect.svelte';
import DailyNoteTemplate from './DailyNoteTemplate.svelte';
import NewNoteEditorSetting from './NewNoteEditorSetting.svelte';
import { newNoteEditorMode, type EditorMode } from '$lib/editor/mode';
import { setNewNoteEditorMode } from '$lib/api';
import AiModelPicker from './AiModelPicker.svelte';
import { showSettings, syncState, theme, resolvedTheme, appConfig, platformIsMobile, activeVaultConfig, updateAvailable as globalUpdateAvailable, updateObj as globalUpdateObj, installType, settingsTab, vaultReady, androidApkUrl, checkForUpdateMobile, notebookSortMode, isManagedInstall, customThemes } from '$lib/stores/app';
import { setTheme, setSystemThemes, setAccentColor, setFontSize, setScrollToChangeFontSize, setFontFamily, setLineHeight, setUiScale, setContentWidth, setGeneralSettings, importObsidian, createBackup, listBackups, restoreBackup, deleteBackup, setBackupSettings, setAiSettings, testAiConnection, setSyncSettings, testSyncConnection, syncNow, saveCustomTheme, deleteCustomTheme, exportCustomTheme, importCustomThemes, getVaultStats, findOrphanedAttachments, trashOrphanedAttachments } from '$lib/api';
@@ -976,7 +979,11 @@
let showLineNumbers = $state($appConfig?.show_line_numbers ?? false);
let showLinkArrows = $state($appConfig?.show_link_arrows ?? true);
let defaultViewMode = $state($appConfig?.default_view_mode ?? false);
let newNotesInSourceMode = $state($appConfig?.new_notes_in_source_mode ?? false);
const newNoteMode = $derived(newNoteEditorMode($appConfig));
async function saveNewNoteMode(mode: EditorMode) {
await setNewNoteEditorMode(mode);
appConfig.update(config => config ? { ...config, new_note_editor_mode: mode, new_notes_in_source_mode: mode !== 'rich' } : config);
}
let showTrayIcon = $state($appConfig?.show_tray_icon ?? false);
let closeToTray = $state($appConfig?.close_to_tray ?? false);
let enableWikiLinks = $state($appConfig?.enable_wiki_links ?? true);
@@ -1050,7 +1057,7 @@
$appConfig.show_line_numbers = showLineNumbers;
$appConfig.show_link_arrows = showLinkArrows;
$appConfig.default_view_mode = defaultViewMode;
$appConfig.new_notes_in_source_mode = newNotesInSourceMode;
$appConfig.new_notes_in_source_mode = newNoteMode !== 'rich';
$appConfig.show_tray_icon = showTrayIcon;
$appConfig.close_to_tray = closeToTray;
$appConfig.enable_wiki_links = enableWikiLinks;
@@ -1060,7 +1067,7 @@
$appConfig.show_daily_notes = showDailyNotes;
$appConfig.show_trash = showTrash;
}
setGeneralSettings(compactNotes, timeFormat, weekStart, dailyTitleFormat, gpuAcceleration, autostart, pdfPreview, pdfHeight, titleMode, hideTitleInBody, showLineNumbers, showLinkArrows, defaultViewMode, newNotesInSourceMode, showTrayIcon, closeToTray, enableWikiLinks, showNoteDates, showNoteSwitcher, startupView, restoreLastSession, showAllNotes, showQuickAccess, showTasks, showDailyNotes, showTrash)
setGeneralSettings(compactNotes, timeFormat, weekStart, dailyTitleFormat, gpuAcceleration, autostart, pdfPreview, pdfHeight, titleMode, hideTitleInBody, showLineNumbers, showLinkArrows, defaultViewMode, newNoteMode !== 'rich', showTrayIcon, closeToTray, enableWikiLinks, showNoteDates, showNoteSwitcher, startupView, restoreLastSession, showAllNotes, showQuickAccess, showTasks, showDailyNotes, showTrash)
.catch((e) => console.error('Failed to save general settings:', e));
}
@@ -1272,7 +1279,6 @@
pdfPreview = $appConfig.pdf_preview ?? false;
pdfHeight = $appConfig.pdf_height ?? 600;
titleMode = $appConfig.title_mode ?? 'input';
newNotesInSourceMode = $appConfig.new_notes_in_source_mode ?? false;
showAllNotes = $appConfig.show_all_notes ?? true;
showQuickAccess = $appConfig.show_quick_access ?? true;
showTasks = $appConfig.show_tasks ?? true;
@@ -1705,15 +1711,7 @@
<span class="toggle-knob"></span>
</button>
</label>
<label class="setting-toggle" style="margin-top: 12px;">
<span class="setting-label">
<span class="setting-name">{$ui("ui.open_new_notes_in_source_mode")}</span>
<span class="setting-desc">{$ui("ui.start_empty_notes_in_the_plain_text_markdown_editor_instead_of_e41488")}</span>
</span>
<button class="toggle-switch" class:on={newNotesInSourceMode} role="switch" aria-checked={newNotesInSourceMode} aria-label={$ui("ui.open_new_notes_in_source_mode")} onclick={() => { newNotesInSourceMode = !newNotesInSourceMode; saveGeneralSettings(); }}>
<span class="toggle-knob"></span>
</button>
</label>
<NewNoteEditorSetting value={newNoteMode} onchange={saveNewNoteMode} />
</div>
+22 -5
View File
@@ -1,14 +1,18 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, untrack } from 'svelte';
import { t as ui } from '$lib/i18n';
import type { SourceController } from '$lib/editor/source/controller';
let { controller, readonly = false, numbers = false, visible = true, mobile = false }: {
let { controller, readonly = false, numbers = false, visible = true, mobile = false, preview = false, resolveImage, openLink, context = '' }: {
controller: SourceController;
readonly?: boolean;
numbers?: boolean;
visible?: boolean;
mobile?: boolean;
preview?: boolean;
resolveImage?: (href: string) => string;
openLink?: (href: string) => void;
context?: string;
} = $props();
let host: HTMLDivElement;
onMount(() => {
@@ -23,12 +27,25 @@
detach();
};
});
$effect(() => { controller.configure(readonly, numbers); });
$effect(() => { controller.setLabels($ui('source.placeholder'), $ui('source.label')); });
$effect(() => {
const settings = { readonly, numbers };
untrack(() => controller.configure(settings.readonly, settings.numbers));
});
$effect(() => {
const placeholder = $ui('source.placeholder'), label = $ui(preview ? 'editorMode.live' : 'source.label');
untrack(() => controller.setLabels(placeholder, label));
});
$effect(() => {
const enabled = preview && visible;
const options = { resolveImage, openLink, context,
checkboxLabel: $ui('livePreview.toggleTask'), imageLabel: $ui('livePreview.editImage') };
// Renderer callbacks must not subscribe this effect to unrelated note/config stores.
untrack(() => controller.setLivePreview(enabled, options));
});
$effect(() => { if (visible) controller.view?.requestMeasure(); });
</script>
<div class="source-editor" class:mobile class:with-line-numbers={numbers} style:display={visible ? undefined : 'none'} bind:this={host}></div>
<div class="source-editor" class:mobile class:live-preview={preview} class:with-line-numbers={numbers && !preview} style:display={visible ? undefined : 'none'} bind:this={host}></div>
<style>
.source-editor {
+21 -8
View File
@@ -2,12 +2,14 @@
import { tick } from 'svelte';
import { findTypeaheadIndex, moveSelectIndex, typeaheadQuery, TYPEAHEAD_TIMEOUT, type SelectOption } from '$lib/utils/select-navigation';
let { id, label, options, value, disabled = false, onchange }: {
let { id, label, options, value, disabled = false, compact = false, onchange }: {
id: string;
label: string;
options: readonly SelectOption[];
value: string;
disabled?: boolean;
/** Icon-only editor-mode trigger, using the same accessible listbox. */
compact?: boolean;
onchange: (value: string) => void | Promise<void>;
} = $props();
@@ -99,7 +101,7 @@
const topEdge = (viewport?.offsetTop ?? 0) + 8;
const rightEdge = leftEdge + (viewport?.width ?? window.innerWidth) - 16;
const bottomEdge = topEdge + (viewport?.height ?? window.innerHeight) - 16;
const width = Math.min(rect.width, rightEdge - leftEdge);
const width = Math.min(compact ? 240 : rect.width, rightEdge - leftEdge);
const below = bottomEdge - rect.bottom - 4;
const above = rect.top - topEdge - 4;
const upward = below < Math.min(240, menu.scrollHeight) && above > below;
@@ -128,7 +130,10 @@
};
const blur = () => dismiss();
const scroll = (event: Event) => {
if (!(event.target instanceof Node) || !menu?.contains(event.target)) dismiss();
// Only scrolling an ancestor can move the trigger. Unrelated CodeMirror
// scroll restoration must not close a menu that the user just opened.
const target = event.target;
if (target instanceof Node && target.contains(trigger) && !menu?.contains(target)) dismiss();
};
document.addEventListener('pointerdown', outside, true);
document.addEventListener('scroll', scroll, true);
@@ -158,14 +163,16 @@
});
</script>
<div class="themed-select" bind:this={root} onfocusout={(event) => {
<div class="themed-select" class:compact bind:this={root} onfocusout={(event) => {
if (!root.contains(event.relatedTarget as Node | null)) dismiss();
}}>
<button {id} type="button" class="select-trigger" class:open {disabled} bind:this={trigger}
role="combobox" aria-label={label} aria-haspopup="listbox" aria-expanded={open}
<button {id} type="button" class="select-trigger" class:open class:chosen={compact && value !== 'rich'} {disabled} bind:this={trigger}
role="combobox" aria-label={compact ? `${label}: ${selected?.label ?? value}` : label} title={compact ? `${label}: ${selected?.label ?? value}` : undefined} aria-haspopup="listbox" aria-expanded={open}
aria-controls={open ? listId : undefined} aria-activedescendant={open ? optionId(active) : undefined}
onclick={() => { if (open) dismiss(); else show(); }} onkeydown={handleKeydown}>
<span lang={selected?.lang}>{selected?.label ?? value}</span>
{#if compact}
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="m5.5 4-4 4 4 4 1-1-3-3 3-3Zm5 0-1 1 3 3-3 3 1 1 4-4Z"/></svg>
{:else}<span lang={selected?.lang}>{selected?.label ?? value}</span>{/if}
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
</button>
{#if open}
@@ -185,6 +192,11 @@
<style>
.themed-select { width: 100%; max-width: 320px; margin-top: 10px; }
.themed-select.compact { width: auto; max-width: none; margin: 0; flex-shrink: 0; }
.compact .select-trigger { min-height: 30px; width: 38px; padding: 5px 4px; gap: 2px; border-color: transparent; background: transparent; color: var(--text-secondary); }
.compact .select-trigger.chosen { color: var(--accent); }
.compact .select-trigger svg:last-child { width: 10px; }
.compact .select-trigger:hover, .compact .select-trigger.open { color: var(--text-primary); background: var(--bg-hover); }
.select-trigger {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
width: 100%; min-height: 40px; padding: 8px 12px;
@@ -197,7 +209,7 @@
.select-trigger:hover:not(:disabled) { background: var(--bg-hover); }
.select-trigger:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.select-trigger.open { border-color: var(--accent); }
.select-trigger.open svg { transform: rotate(180deg); }
.select-trigger.open svg:last-child { transform: rotate(180deg); }
.select-trigger:disabled { opacity: 0.6; cursor: wait; }
.select-menu {
position: fixed; z-index: 2100; box-sizing: border-box; overflow-y: auto; overscroll-behavior: contain;
@@ -214,4 +226,5 @@
.select-option span { min-width: 0; overflow-wrap: anywhere; }
.select-option svg { flex-shrink: 0; color: var(--accent); }
.select-option.active { background: var(--accent-light); color: var(--text-primary); }
@media (pointer: coarse) { .compact .select-trigger { min-height: 40px; width: 44px; } }
</style>
+21 -11
View File
@@ -1,21 +1,30 @@
<script lang="ts">
import { t as ui } from '$lib/i18n';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { vaultReady, focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, activeNotePath, activeVaultConfig, syncState } from '$lib/stores/app';
import { focusMode, readOnly, updateAvailable, showSettings, settingsTab, appConfig, activeNotePath, activeVaultConfig, syncState } from '$lib/stores/app';
import { syncNow } from '$lib/api';
import NoteSwitcher from './NoteSwitcher.svelte';
import VaultSwitcher from './VaultSwitcher.svelte';
import { activeVaultIdentity, type VaultSwitchResult } from '$lib/utils/vault-switch';
import type { VaultConfig } from '$lib/types';
import { isTrashedNote } from '$lib/utils/paths';
let {
onNewNote = () => {},
onDailyNote = () => {},
onSelectNote,
onBeforeVaultSwitch
onSwitchVault,
onAddVault,
onManageVaults,
switching = false
}: {
onNewNote?: () => void;
onDailyNote?: () => void;
onSelectNote?: (path: string) => Promise<boolean>;
onBeforeVaultSwitch: () => Promise<boolean>;
onSwitchVault: (vault: VaultConfig) => Promise<VaultSwitchResult>;
onAddVault: () => Promise<VaultSwitchResult>;
onManageVaults: () => Promise<VaultSwitchResult>;
switching?: boolean;
} = $props();
const appWindow = getCurrentWindow();
@@ -40,7 +49,7 @@
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const target = e.target as HTMLElement;
if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions') || target.closest('.titlebar-note-switcher')) return;
if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions') || target.closest('.titlebar-note-switcher') || target.closest('.titlebar-vault-switcher')) return;
// Don't start dragging near window edges - let Tauri handle resize
if (!maximized) {
@@ -91,19 +100,15 @@
</button>
{/if}
</div>
<div class="titlebar-vault-switcher">
<VaultSwitcher vaults={$appConfig?.vaults ?? []} active={activeVaultIdentity($appConfig)} busy={switching} onselect={onSwitchVault} onadd={onAddVault} onmanage={onManageVaults} />
</div>
{#if $appConfig?.show_note_switcher}
<div class="titlebar-note-switcher">
<NoteSwitcher {onSelectNote} />
</div>
{/if}
<div class="titlebar-actions">
<button class="switch-vault-btn" onclick={async () => { if (await onBeforeVaultSwitch()) $vaultReady = false; }} title={$ui("ui.manage_vaults")} aria-label={$ui("ui.manage_vaults")}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="18" height="16" rx="2" />
<circle cx="12" cy="11" r="3.5" />
<path d="M12 7.5V6M12 16v-1.5M7 19v2M17 19v2" />
</svg>
</button>
<button class="switch-vault-btn" onclick={() => ($focusMode = true)} title={$ui("ui.focus_mode")}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"/>
@@ -192,6 +197,7 @@
pointer-events: none;
}
.titlebar-vault-switcher { min-width: 0; max-width: 200px; margin-left: 10px; -webkit-app-region: no-drag; }
.titlebar-note-switcher {
display: flex;
align-items: center;
@@ -315,6 +321,10 @@
color: white;
}
@media (max-width: 720px) {
.titlebar-title { display: none; }
.titlebar-vault-switcher { max-width: 130px; }
}
/* macOS: add left padding for native traffic light buttons */
.titlebar.macos .titlebar-brand {
padding-left: 78px;
+5 -8
View File
@@ -103,7 +103,7 @@
}
}
async function openSelectedVault(path: string) {
async function openSelectedVault(path: string, existing = false) {
loading = true;
error = '';
try {
@@ -113,9 +113,7 @@
bridge?.prepareVaultDir?.(path);
} catch { /* Rust will retry mkdir itself */ }
}
await openVault(path);
const config = await getAppConfig();
$appConfig = config;
$appConfig = await openVault(path, { existing });
$vaultReady = true;
} catch (e) {
const msg = String(e);
@@ -135,7 +133,7 @@
try {
const selected = await chooseExternalVault();
if (!selected) return;
$appConfig = await getAppConfig();
$appConfig = selected;
$vaultReady = true;
} catch (e) {
error = String(e);
@@ -147,15 +145,14 @@
async function openRecentVault(vault: VaultConfig) {
if (loading) return;
if (!isIOS || !vault.bookmark_id) {
await openSelectedVault(vault.path);
await openSelectedVault(vault.path, true);
return;
}
loading = true;
error = '';
try {
await restoreExternalVault(vault.bookmark_id);
$appConfig = await getAppConfig();
$appConfig = await restoreExternalVault(vault.bookmark_id);
$vaultReady = true;
} catch (e) {
error = String(e);
+175
View File
@@ -0,0 +1,175 @@
<script lang="ts">
import { onDestroy, tick } from 'svelte';
import { t } from '$lib/i18n';
import type { VaultConfig, VaultIdentity } from '$lib/types';
import { sameVault, vaultIdentity, vaultIdentityKey, vaultDisplayName, type VaultSwitchResult } from '$lib/utils/vault-switch';
import { findTypeaheadIndex, typeaheadQuery, TYPEAHEAD_TIMEOUT } from '$lib/utils/select-navigation';
let { vaults, active, busy = false, onselect, onadd, onmanage }: {
vaults: readonly VaultConfig[];
active: VaultIdentity | null;
busy?: boolean;
onselect: (vault: VaultConfig) => Promise<VaultSwitchResult>;
onadd: () => Promise<VaultSwitchResult>;
onmanage: () => Promise<VaultSwitchResult>;
} = $props();
const componentId = $props.id();
const menuId = `${componentId}-vault-menu`;
const current = $derived(vaults.find(vault => sameVault(vaultIdentity(vault), active)));
const name = $derived(current ? vaultDisplayName(current) : active?.path.replace(/\\/g, '/').replace(/\/+$/, '').split('/').at(-1) || $t('ui.vault'));
let root: HTMLDivElement;
let trigger: HTMLButtonElement;
let menu = $state<HTMLDivElement>();
let open = $state(false);
let pending = $state(false);
let error = $state<{ key: 'vaultSwitcher.failed' | 'vaultSwitcher.blocked' | 'vaultSwitcher.stale'; detail?: string } | null>(null);
let position = $state('visibility: hidden;');
let disposed = false;
let query = '', lastTyped = 0;
onDestroy(() => { disposed = true; });
const buttons = () => Array.from(menu?.querySelectorAll<HTMLButtonElement>('button:not(:disabled)') ?? []);
async function show(index = vaults.findIndex(vault => sameVault(vaultIdentity(vault), active))) {
if (pending || busy) return;
open = true; error = null; query = ''; position = 'visibility: hidden;';
await tick();
if (disposed || !open) return;
const items = buttons(); items[Math.max(0, Math.min(items.length - 1, index))]?.focus({ preventScroll: true });
}
function dismiss(restoreFocus = false) {
if (pending || busy) return;
open = false; query = '';
if (restoreFocus) trigger?.focus({ preventScroll: true });
}
async function run(action: () => Promise<VaultSwitchResult>) {
if (pending || busy) return;
pending = true; error = null;
let result: VaultSwitchResult | undefined;
try {
result = await action();
if (disposed) return;
if (result === 'blocked') error = { key: 'vaultSwitcher.blocked' };
if (result === 'stale') error = { key: 'vaultSwitcher.stale' };
} catch (cause) { if (!disposed) error = { key: 'vaultSwitcher.failed', detail: String(cause) }; }
finally { if (!disposed) pending = false; }
await tick();
if (disposed) return;
if (result === 'done' || result === 'cancelled') dismiss(true);
else buttons()[0]?.focus({ preventScroll: true });
}
function onMenuKeydown(event: KeyboardEvent) {
event.stopPropagation();
if (event.key === 'Escape' || event.key === 'Tab') {
event.preventDefault(); event.stopPropagation(); dismiss(true); return;
}
if (pending || busy || event.isComposing || event.ctrlKey || event.metaKey || event.altKey) return;
const items = buttons();
if (!items.length) return;
const index = items.indexOf(document.activeElement as HTMLButtonElement);
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
event.preventDefault(); event.stopPropagation();
const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1
: event.key === 'ArrowDown' ? (index + 1) % items.length : (index - 1 + items.length) % items.length;
items[next].focus(); return;
}
if (event.key.length === 1 && event.key !== ' ') {
event.preventDefault(); event.stopPropagation();
const now = performance.now(); query = typeaheadQuery(query, event.key, now - lastTyped); lastTyped = now;
const options = items.map((item, i) => ({ value: String(i), label: item.dataset.name ?? item.textContent ?? '' }));
const next = findTypeaheadIndex(options, query, Math.max(0, index));
if (next >= 0) items[next].focus();
}
}
function placeMenu() {
if (!menu || !trigger) return;
const rect = trigger.getBoundingClientRect(), viewport = window.visualViewport;
const leftEdge = (viewport?.offsetLeft ?? 0) + 8, topEdge = (viewport?.offsetTop ?? 0) + 8;
const width = Math.max(0, (viewport?.width ?? window.innerWidth) - 16);
const bottom = topEdge + (viewport?.height ?? window.innerHeight) - 16;
const popupWidth = Math.min(360, width);
const below = bottom - rect.bottom - 4, above = rect.top - topEdge - 4;
const upward = below < Math.min(240, menu.scrollHeight) && above > below;
const height = Math.max(36, Math.min(480, upward ? above : below));
const top = upward ? rect.top - 4 - Math.min(menu.scrollHeight + 2, height) : rect.bottom + 4;
position = `left: ${Math.max(leftEdge, Math.min(rect.left, leftEdge + width - popupWidth))}px; top: ${Math.max(topEdge, top)}px; width: ${popupWidth}px; max-height: ${height}px;`;
}
function portal(node: HTMLDivElement) {
document.body.appendChild(node); menu = node;
return { destroy() { node.remove(); menu = undefined; } };
}
$effect(() => {
if (!open || !menu) return;
placeMenu();
const outside = (event: PointerEvent) => {
const target = event.target as Node;
if (!root.contains(target) && !menu?.contains(target)) dismiss();
};
const scroll = (event: Event) => {
const target = event.target;
if (target instanceof Node && target.contains(trigger) && !menu?.contains(target)) dismiss();
};
const blur = () => dismiss();
document.addEventListener('pointerdown', outside, true); document.addEventListener('scroll', scroll, true);
window.addEventListener('resize', placeMenu); window.addEventListener('blur', blur);
window.visualViewport?.addEventListener('resize', placeMenu); window.visualViewport?.addEventListener('scroll', placeMenu);
const observer = new ResizeObserver(placeMenu); observer.observe(trigger); observer.observe(menu);
return () => {
document.removeEventListener('pointerdown', outside, true); document.removeEventListener('scroll', scroll, true);
window.removeEventListener('resize', placeMenu); window.removeEventListener('blur', blur);
window.visualViewport?.removeEventListener('resize', placeMenu); window.visualViewport?.removeEventListener('scroll', placeMenu);
observer.disconnect();
};
});
</script>
<div class="vault-switcher" bind:this={root}>
<button type="button" class="vault-trigger" class:open disabled={busy || pending} bind:this={trigger}
aria-label={`${$t('vaultSwitcher.label')}: ${name}`} title={active?.path ?? name} aria-haspopup="menu" aria-expanded={open} aria-controls={open ? menuId : undefined}
onclick={() => open ? dismiss(true) : show()} onkeydown={event => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); event.stopPropagation(); void show(event.key === 'ArrowUp' ? vaults.length + 1 : undefined); }
if (event.key === 'Escape') { event.stopPropagation(); dismiss(true); }
}}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><rect x="3" y="3" width="18" height="16" rx="2"/><circle cx="12" cy="11" r="3.5"/><path d="M7 19v2m10-2v2"/></svg>
<span>{name}</span>
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
</button>
{#if open}
<div class="vault-menu" id={menuId} role="menu" aria-label={$t('vaultSwitcher.label')} aria-busy={busy || pending} tabindex="-1" style={position} use:portal onkeydown={onMenuKeydown}>
{#each vaults as vault (vaultIdentityKey(vaultIdentity(vault)))}
<button type="button" class="vault-option" role="menuitemradio" aria-checked={sameVault(vaultIdentity(vault), active)} tabindex="-1" disabled={busy || pending}
data-name={vaultDisplayName(vault)} title={vault.path} onclick={() => run(() => onselect(vault))}>
<span class="vault-check" aria-hidden="true">{#if sameVault(vaultIdentity(vault), active)}✓{/if}</span>
<span class="vault-description"><span class="vault-name">{vaultDisplayName(vault)}</span><span class="vault-path">{vault.path}</span></span>
</button>
{:else}<p class="vault-empty">{$t('vaultSwitcher.empty')}</p>{/each}
<div class="vault-separator" role="separator"></div>
<button type="button" class="vault-option vault-action" role="menuitem" tabindex="-1" disabled={busy || pending} onclick={() => run(onadd)}><span aria-hidden="true">+</span><span>{$t('vaultSwitcher.add')}</span></button>
<button type="button" class="vault-option vault-action" role="menuitem" tabindex="-1" disabled={busy || pending} onclick={() => run(onmanage)}><span aria-hidden="true">⋯</span><span>{$t('ui.manage_vaults')}</span></button>
{#if busy || pending}<p class="vault-message" role="status">{$t('vaultSwitcher.switching')}</p>{/if}
{#if error}<p class="vault-error" role="alert">{$t(error.key, { error: error.detail ?? '' })}</p>{/if}
</div>
{/if}
</div>
<style>
.vault-switcher { min-width: 0; max-width: 100%; -webkit-app-region: no-drag; }
.vault-trigger { display: flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%; min-height: 26px; padding: 3px 7px; border: 1px solid transparent; border-radius: 6px; background: transparent; color: var(--text-primary); font: inherit; font-size: 12px; cursor: pointer; -webkit-app-region: no-drag; }
.vault-trigger span { min-width: 0; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.vault-trigger svg { flex-shrink: 0; }
.vault-trigger:hover, .vault-trigger.open { background: var(--bg-hover); border-color: var(--border-color); }
.vault-trigger:disabled { cursor: wait; opacity: .6; }
.vault-trigger:focus-visible, .vault-option:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.vault-menu { position: fixed; z-index: 2200; box-sizing: border-box; overflow-y: auto; overscroll-behavior: contain; padding: 5px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); color: var(--text-primary); box-shadow: var(--shadow-lg, 0 8px 28px #0003); -webkit-app-region: no-drag; }
.vault-option { display: flex; align-items: center; gap: 8px; box-sizing: border-box; width: 100%; padding: 8px; border: 0; border-radius: 5px; background: transparent; color: inherit; text-align: start; font: inherit; font-size: 13px; cursor: pointer; }
.vault-option:hover, .vault-option:focus { background: var(--bg-hover); }
.vault-option:disabled { cursor: wait; opacity: .6; }
.vault-check { flex: 0 0 16px; color: var(--accent); }
.vault-description { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 3px; }
.vault-name { font-weight: 500; overflow-wrap: anywhere; }
.vault-path { font-size: 11px; line-height: 1.4; color: var(--text-secondary); overflow-wrap: anywhere; }
.vault-action > span:first-child { width: 16px; flex-shrink: 0; text-align: center; }
.vault-separator { height: 1px; background: var(--border-color); margin: 5px 3px; }
.vault-message, .vault-empty { margin: 8px; color: var(--text-secondary); font-size: 12px; }
.vault-error { margin: 8px; color: var(--text-primary); font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
@media (pointer: coarse) { .vault-trigger { min-height: 40px; } .vault-option { min-height: 44px; } }
</style>
+21
View File
@@ -0,0 +1,21 @@
import { derived, writable } from 'svelte/store';
export type EditorMode = 'rich' | 'live' | 'source';
// Source and Live Preview use one source controller; this flag only changes its presentation.
// Preferences are per window/session, matching the existing source-mode behaviour.
export const sourceMode = writable(false);
export const livePreviewMode = writable(false);
export const editorMode = derived([sourceMode, livePreviewMode], ([$source, $live]): EditorMode =>
$source ? ($live ? 'live' : 'source') : 'rich');
export function newNoteEditorMode(config: { new_note_editor_mode?: unknown; new_notes_in_source_mode?: unknown } | null | undefined): EditorMode {
const mode = config?.new_note_editor_mode;
return mode === 'rich' || mode === 'live' || mode === 'source' ? mode
: config?.new_notes_in_source_mode === true ? 'source' : 'rich';
}
export function selectEditorMode(mode: EditorMode): void {
if (mode !== 'rich' && mode !== 'live' && mode !== 'source') return;
if (mode !== 'rich') livePreviewMode.set(mode === 'live');
sourceMode.set(mode !== 'rich');
}
+23 -4
View File
@@ -3,6 +3,8 @@ import { Decoration, EditorView, drawSelection, keymap, lineNumbers, placeholder
import { defaultKeymap, history, historyKeymap, indentWithTab, redo, undo } from '@codemirror/commands';
import { HighlightStyle, indentUnit, syntaxHighlighting } from '@codemirror/language';
import { markdown } from '@codemirror/lang-markdown';
import { sourceMarkdownExtensions } from './syntax.ts';
import { livePreview, type LivePreviewOptions } from './live-preview.ts';
import { tags } from '@lezer/highlight';
import { getSelectionPair } from '../selectionPairs.ts';
import type { NoteSearchMatch } from '../search';
@@ -67,6 +69,9 @@ const sourceSyntax = HighlightStyle.define([
export class SourceController {
private configuration = new Compartment();
private presentation = new Compartment();
private preview = false;
private previewOptions: LivePreviewOptions = {};
private readOnly = false;
private numbers = false;
private placeholderText = 'Start writing...';
@@ -83,7 +88,7 @@ export class SourceController {
} = {}) {
this.onChange = onChange;
this.extensions = [
markdown(), history(), drawSelection(), sourceSearchDecoration, sourceTheme,
markdown({ extensions: sourceMarkdownExtensions }), history(), drawSelection(), sourceSearchDecoration, sourceTheme,
syntaxHighlighting(sourceSyntax), indentUnit.of('\t'), EditorState.tabSize.of(4),
keymap.of([{ key: 'Shift-Enter', run: sourceHardBreak }, indentWithTab, ...historyKeymap, ...defaultKeymap]),
EditorView.domEventHandlers({
@@ -98,7 +103,7 @@ export class SourceController {
drop: (event, view) => !view.state.readOnly && (events.drop?.(event) ?? false),
scroll: () => { events.scroll?.(); return false; },
}),
this.configuration.of(this.settings()),
this.configuration.of(this.settings()), this.presentation.of([]),
];
this.state = EditorState.create({ extensions: this.extensions });
}
@@ -107,7 +112,20 @@ export class SourceController {
return [EditorState.readOnly.of(this.readOnly), EditorView.editable.of(!this.readOnly),
placeholder(this.placeholderText),
EditorView.contentAttributes.of({ 'aria-label': this.accessibleLabel, tabindex: '0', spellcheck: 'false', autocapitalize: 'off' }),
this.numbers ? lineNumbers() : EditorView.lineWrapping];
this.numbers && !this.preview ? lineNumbers() : EditorView.lineWrapping];
}
/** Reconfigure presentation only: keep the Text, selection, undo branches and save revision. */
setLivePreview(enabled: boolean, options: LivePreviewOptions = {}): void {
if (enabled === this.preview && Object.keys({ ...this.previewOptions, ...options }).every(key =>
this.previewOptions[key as keyof LivePreviewOptions] === options[key as keyof LivePreviewOptions])) return;
this.preview = enabled;
this.previewOptions = options;
this.dispatch({ effects: [
this.configuration.reconfigure(this.settings()),
this.presentation.reconfigure(enabled ? livePreview(options) : []),
...(this.view ? [this.view.scrollSnapshot()] : []),
] });
}
setLabels(placeholderText: string, accessibleLabel: string): void {
@@ -157,7 +175,8 @@ export class SourceController {
load(content: string): void {
this.state = EditorState.create({ doc: content, extensions: this.extensions });
// A fresh state starts with the original compartment; retain live settings.
this.state = this.state.update({ effects: this.configuration.reconfigure(this.settings()) }).state;
this.state = this.state.update({ effects: [this.configuration.reconfigure(this.settings()),
this.presentation.reconfigure(this.preview ? livePreview(this.previewOptions) : [])] }).state;
this.view?.setState(this.state);
}
+295
View File
@@ -0,0 +1,295 @@
import { EditorSelection, EditorState, type Extension, type Range } from '@codemirror/state';
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from '@codemirror/view';
import { syntaxTree } from '@codemirror/language';
import MarkdownIt from 'markdown-it';
export interface LivePreviewOptions {
resolveImage?: (href: string) => string;
openLink?: (href: string) => void;
checkboxLabel?: string;
imageLabel?: string;
/** Re-resolve assets after note/vault changes, even if the Markdown is identical. */
context?: string;
}
export type PreviewSpan = {
from: number; to: number;
kind: 'line' | 'mark' | 'hide' | 'image' | 'checkbox' | 'bullet';
className?: string; href?: string; label?: string; checked?: boolean;
};
const markdown = new MarkdownIt({ html: false });
/** Never interpret raw HTML or arbitrary URI schemes as preview content. */
export function previewDestination(raw: string): string | null {
const href = markdown.utils.unescapeAll(raw.replace(/^<([\s\S]*)>$/, '$1'));
if (!href || /[\u0000-\u001f\u007f]/.test(href)) return null;
if (/^[a-z]:[\\/]/i.test(href)) return href;
if (/^[a-z][\w+.-]*:/i.test(href) && !/^(https?:|mailto:|asset:|imgproxy:|blob:)/i.test(href)
&& !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/=]+$/i.test(href)) return null;
return href;
}
/** Presentation only. Every coordinate still addresses the original Markdown document. */
export function previewSpans(state: EditorState, visible: readonly { from: number; to: number }[] = [{ from: 0, to: state.doc.length }], composing = false): PreviewSpan[] {
const spans: PreviewSpan[] = [];
const seen = new Set<string>();
const selected = state.selection.ranges.map(range => ({
from: state.doc.lineAt(range.from).from,
to: state.doc.lineAt(range.to).to,
}));
const active = (from: number, to: number) => (!state.readOnly || composing) && selected.some(range => from <= range.to && to >= range.from);
const shown = (from: number, to: number) => visible.some(range => from <= range.to && to >= range.from);
const add = (span: PreviewSpan) => {
if (!shown(span.from, span.to)) return;
const key = `${span.kind}:${span.from}:${span.to}:${span.className ?? ''}`;
if (!seen.has(key)) { seen.add(key); spans.push(span); }
};
const hide = (from: number, to: number) => { if (to > from) add({ from, to, kind: 'hide' }); };
const lines = (from: number, to: number, className: string) => {
for (const range of visible) {
let line = state.doc.lineAt(Math.max(from, range.from));
const end = Math.min(to, range.to);
while (line.from <= end) {
add({ from: line.from, to: line.from, kind: 'line', className });
if (line.to >= state.doc.length) break;
line = state.doc.lineAt(line.to + 1);
}
}
};
for (const range of visible) {
let line = state.doc.lineAt(range.from);
while (line.from <= range.to) {
if (!active(line.from, line.to)) add({ from: line.from, to: line.from, kind: 'line', className: 'lp-rendered' });
if (line.to >= state.doc.length) break;
line = state.doc.lineAt(line.to + 1);
}
}
for (const range of visible) syntaxTree(state).iterate({ from: range.from, to: range.to, enter(ref) {
const node = ref.node;
const { from, to, name } = node;
// Complex constructs remain literal source, not unsafe HTML or a lossy rendering.
if (name === 'HTMLBlock' || name === 'HTMLTag' || name === 'Table' || name === 'LinkReference'
|| name === 'SourceMathBlock' || name === 'SourceMathInline') return false;
if (name === 'Paragraph') {
// Bound work for very long paragraphs; CodeMirror parses visible syntax incrementally.
if (to - from > 30_000) return false;
}
if (name === 'FencedCode' || name === 'CodeBlock') {
lines(from, to, 'lp-code-block');
if (name === 'FencedCode' && !active(from, to)) {
for (const mark of node.getChildren('CodeMark')) {
const line = state.doc.lineAt(mark.from);
hide(mark.from, line.to);
}
}
return false;
}
const heading = /^(?:ATX|Setext)Heading([1-6])$/.exec(name);
if (heading) {
const underline = name.startsWith('Setext') ? node.getChild('HeaderMark') : null;
lines(from, underline ? state.doc.lineAt(underline.from).from - 1 : to, `lp-heading lp-h${heading[1]}`);
if (!active(from, to)) for (const mark of node.getChildren('HeaderMark')) {
let end = mark.to;
while (state.sliceDoc(end, end + 1) === ' ') end++;
hide(mark.from, end);
}
}
if (name === 'StrongEmphasis' || name === 'Emphasis' || name === 'Strikethrough' || name === 'InlineCode') {
const className = ({ StrongEmphasis: 'lp-strong', Emphasis: 'lp-emphasis', Strikethrough: 'lp-strike', InlineCode: 'lp-inline-code' })[name]!;
add({ from, to, kind: 'mark', className });
if (!active(from, to)) for (const mark of node.getChildren(name === 'InlineCode' ? 'CodeMark' : name === 'Strikethrough' ? 'StrikethroughMark' : 'EmphasisMark')) hide(mark.from, mark.to);
if (name === 'InlineCode') return false;
}
if (name === 'Blockquote') lines(from, to, 'lp-quote');
if (name === 'QuoteMark' && !active(from, to)) {
hide(from, to + (state.sliceDoc(to, to + 1) === ' ' ? 1 : 0));
}
if (name === 'HorizontalRule' && !active(from, to)) {
lines(from, to, 'lp-rule'); hide(from, to); return false;
}
if (name === 'ListMark' || name === 'TaskMarker') {
const line = state.doc.lineAt(from);
if (active(line.from, line.to)) return;
if (name === 'TaskMarker') {
const checked = /[xX]/.test(state.sliceDoc(from, to));
add({ from, to, kind: 'checkbox', checked });
if (checked && node.parent && node.parent.to > to) add({ from: to, to: node.parent.to, kind: 'mark', className: 'lp-task-done' });
} else if (node.parent?.parent?.name === 'BulletList') {
const tail = state.sliceDoc(to, Math.min(line.to, to + 8));
if (/^\s+\[[ xX]\]/.test(tail)) hide(from, to + 1);
else add({ from, to, kind: 'bullet' });
}
}
if (name === 'Link' || name === 'Image') {
if (to - from > 30_000) return false;
const url = node.getChild('URL');
if (!url) return false; // Wiki/reference links remain editable literal text.
const href = previewDestination(state.sliceDoc(url.from, url.to));
if (!href) return false;
const marks = node.getChildren('LinkMark');
const close = marks.find(mark => state.sliceDoc(mark.from, mark.to) === ']');
if (!close || active(from, to)) return false;
if (name === 'Image') {
if (state.doc.lineAt(from).number !== state.doc.lineAt(to).number || /^mailto:/i.test(href)) return false;
add({ from, to, kind: 'image', href, label: state.sliceDoc(from + 2, close.from) });
return false;
}
if (close.from <= from + 1) return false; // Empty labels must remain selectable source, not zero-length marks.
hide(from, from + 1); hide(close.from, to);
add({ from: from + 1, to: close.from, kind: 'mark', className: 'lp-link', href });
}
} });
return spans;
}
class Bullet extends WidgetType {
toDOM() { const span = document.createElement('span'); span.className = 'lp-bullet'; span.textContent = '•'; span.setAttribute('aria-hidden', 'true'); return span; }
}
class Checkbox extends WidgetType {
readonly from: number;
readonly checked: boolean;
readonly readonly: boolean;
readonly label: string;
constructor(from: number, checked: boolean, readonly: boolean, label: string) {
super(); this.from = from; this.checked = checked; this.readonly = readonly; this.label = label;
}
eq(other: Checkbox) { return this.from === other.from && this.checked === other.checked && this.readonly === other.readonly && this.label === other.label; }
toDOM(view: EditorView) {
const input = document.createElement('input');
input.type = 'checkbox'; input.className = 'lp-checkbox'; input.checked = this.checked; input.disabled = this.readonly;
input.dataset.sourceFrom = String(this.from);
input.setAttribute('aria-label', this.label);
input.onmousedown = event => event.preventDefault();
input.onchange = () => {
const from = Number(input.dataset.sourceFrom);
const raw = view.state.sliceDoc(from, from + 3);
if (view.state.readOnly || !/^\[[ xX]\]$/.test(raw)) { input.checked = /[xX]/.test(raw); return; }
view.dispatch({ changes: { from: from + 1, to: from + 2, insert: raw[1] === ' ' ? 'x' : ' ' }, userEvent: 'input' });
};
return input;
}
updateDOM(dom: HTMLElement) {
if (!(dom instanceof HTMLInputElement)) return false;
dom.dataset.sourceFrom = String(this.from); dom.checked = this.checked; dom.disabled = this.readonly;
dom.setAttribute('aria-label', this.label);
return true;
}
ignoreEvent() { return true; }
}
class PreviewImage extends WidgetType {
readonly from: number;
readonly to: number;
readonly src: string;
readonly alt: string;
readonly label: string;
constructor(from: number, to: number, src: string, alt: string, label: string) {
super(); this.from = from; this.to = to; this.src = src; this.alt = alt; this.label = label;
}
eq(other: PreviewImage) { return this.from === other.from && this.to === other.to && this.src === other.src && this.alt === other.alt && this.label === other.label; }
get estimatedHeight() { return 160; }
toDOM(view: EditorView) {
const button = document.createElement('button');
button.type = 'button'; button.className = 'lp-image'; button.setAttribute('aria-label', this.label);
button.dataset.sourceFrom = String(this.from); button.dataset.sourceTo = String(this.to); button.dataset.previewSrc = this.src;
const image = document.createElement('img');
image.alt = this.alt; image.loading = 'lazy'; image.decoding = 'async'; image.referrerPolicy = 'no-referrer';
image.crossOrigin = 'anonymous';
const fallback = document.createElement('span'); fallback.className = 'lp-image-fallback'; fallback.textContent = this.alt || this.label;
image.onload = () => { fallback.hidden = true; if (button.isConnected) view.requestMeasure(); };
image.onerror = () => { image.hidden = true; fallback.hidden = false; if (button.isConnected) view.requestMeasure(); };
button.onmousedown = event => event.preventDefault();
button.onclick = () => { view.dispatch({ selection: EditorSelection.single(Number(button.dataset.sourceFrom), Number(button.dataset.sourceTo)), scrollIntoView: true }); view.focus(); };
button.append(image, fallback); image.src = this.src;
return button;
}
updateDOM(dom: HTMLElement) {
if (!(dom instanceof HTMLButtonElement) || dom.dataset.previewSrc !== this.src) return false;
// Keep already loaded images stable while typing before them, but refresh source coordinates.
dom.dataset.sourceFrom = String(this.from); dom.dataset.sourceTo = String(this.to);
dom.setAttribute('aria-label', this.label);
const image = dom.querySelector('img'); if (image) image.alt = this.alt;
const fallback = dom.querySelector('.lp-image-fallback'); if (fallback) fallback.textContent = this.alt || this.label;
return true;
}
destroy(dom: HTMLElement) { const image = dom.querySelector('img'); if (image) { image.onload = null; image.onerror = null; } }
ignoreEvent() { return true; }
}
export function livePreview(options: LivePreviewOptions = {}): Extension {
const plugin = ViewPlugin.fromClass(class {
decorations: DecorationSet = Decoration.none;
atomic: DecorationSet = Decoration.none;
constructor(view: EditorView) { this.build(view); }
update(update: ViewUpdate) {
if (update.docChanged || update.selectionSet || update.viewportChanged || update.transactions.some(tr => tr.reconfigured)
|| syntaxTree(update.state) !== syntaxTree(update.startState)) this.build(update.view);
}
build(view: EditorView) {
const ranges: Range<Decoration>[] = [];
for (const span of previewSpans(view.state, view.visibleRanges, view.composing)) {
let decoration: Decoration;
if (span.kind === 'line') decoration = Decoration.line({ attributes: { class: span.className! } });
else if (span.kind === 'mark') decoration = Decoration.mark({ class: span.className!, attributes: span.href ? { 'data-preview-href': span.href, title: span.href } : undefined });
else {
let widget: WidgetType | undefined;
if (span.kind === 'bullet') widget = new Bullet();
if (span.kind === 'checkbox') widget = new Checkbox(span.from, !!span.checked, view.state.readOnly, options.checkboxLabel ?? 'Toggle task');
if (span.kind === 'image') {
let src: string;
try { src = options.resolveImage?.(span.href!) ?? span.href!; } catch { continue; }
widget = new PreviewImage(span.from, span.to, src, span.label!, options.imageLabel ?? 'Edit image source');
}
decoration = Decoration.replace({ widget, liveAtomic: true });
}
ranges.push(decoration.range(span.from, span.to));
}
this.decorations = Decoration.set(ranges, true);
this.atomic = this.decorations.update({ filter: (_from, _to, decoration) => !!decoration.spec.liveAtomic });
}
}, { decorations: value => value.decorations, provide: plugin => EditorView.atomicRanges.of(view => view.plugin(plugin)?.atomic ?? Decoration.none) });
return [plugin, EditorView.domEventHandlers({
mousedown(event) {
// Handle before CM moves the caret and reveals (removes) the decorated link.
const link = (event.target as Element).closest?.('[data-preview-href]');
if (!link || !(event.ctrlKey || event.metaKey) || !options.openLink) return false;
event.preventDefault(); options.openLink(link.getAttribute('data-preview-href')!); return true;
},
keydown(event, view) {
if (event.key !== 'Enter' || !(event.ctrlKey || event.metaKey) || !options.openLink || event.isComposing) return false;
let node = syntaxTree(view.state).resolveInner(view.state.selection.main.head, -1);
while (node.parent && node.name !== 'Link') node = node.parent;
const url = node.name === 'Link' ? node.getChild('URL') : null;
const href = url ? previewDestination(view.state.sliceDoc(url.from, url.to)) : null;
if (!href) return false;
event.preventDefault(); options.openLink(href); return true;
},
}), EditorView.theme({
'&': { fontFamily: 'var(--editor-font-family, sans-serif)' },
'.cm-scroller': { fontFamily: 'var(--editor-font-family, sans-serif)' },
'.cm-line': { lineHeight: 'var(--editor-line-height, 1.6)' },
'.lp-rendered span': { color: 'inherit' },
'.lp-rendered .lp-link, .lp-rendered .lp-link span': { color: 'var(--accent)' },
'.lp-rendered .lp-task-done, .lp-rendered .lp-task-done span': { color: 'var(--text-secondary)', textDecoration: 'line-through' },
'.lp-heading': { fontWeight: '700', paddingTop: '0.45em', paddingBottom: '0.2em', lineHeight: '1.35' },
'.lp-heading span': { color: 'var(--text-primary)' },
'.lp-h1': { fontSize: '1.9em' }, '.lp-h2': { fontSize: '1.55em' }, '.lp-h3': { fontSize: '1.3em' },
'.lp-h4': { fontSize: '1.15em' }, '.lp-h5, .lp-h6': { fontSize: '1em' },
'.cm-line .lp-strong': { fontWeight: '700', color: 'var(--text-primary)' },
'.cm-line .lp-emphasis': { fontStyle: 'italic', color: 'var(--text-primary)' },
'.lp-strike': { textDecoration: 'line-through' },
'.lp-inline-code': { fontFamily: 'var(--font-mono, monospace)', background: 'var(--bg-secondary)', borderRadius: '3px', padding: '1px 3px' },
'.lp-code-block': { fontFamily: 'var(--font-mono, monospace)', background: 'var(--bg-secondary)' },
'.lp-quote': { borderLeft: '3px solid var(--accent)', paddingLeft: '12px', color: 'var(--text-secondary)' },
'.lp-rule': { borderBottom: '1px solid var(--border-color)' },
'.lp-link': { color: 'var(--accent)', textDecoration: 'underline', cursor: 'text' },
'.lp-bullet': { color: 'var(--accent)', fontWeight: '700' },
'.lp-checkbox': { cursor: 'pointer', verticalAlign: 'middle', accentColor: 'var(--accent)', width: '16px', height: '16px', margin: '0 5px 0 0' },
'.lp-image': { display: 'inline-block', border: '0', padding: '0', background: 'transparent', color: 'var(--text-secondary)', cursor: 'pointer', maxWidth: '100%', verticalAlign: 'middle' },
'.lp-image img': { maxWidth: '100%', maxHeight: '360px', objectFit: 'contain', borderRadius: '4px' },
'.lp-image:focus-visible': { outline: '2px solid var(--accent)' },
'.lp-image-fallback': { fontSize: '0.9em', padding: '8px', border: '1px dashed var(--border-color)' },
'@media (pointer: coarse)': { '.lp-checkbox': { width: '24px', height: '24px' } },
})];
}
+40
View File
@@ -0,0 +1,40 @@
import { GFM, type MarkdownConfig } from '@lezer/markdown';
// Recognize math as opaque source. Without these nodes CommonMark can mistake
// headings, images or emphasis inside $$ blocks for ordinary preview content.
const mathAsSource: MarkdownConfig = {
defineNodes: [{ name: 'SourceMathBlock', block: true }, 'SourceMathInline'],
parseBlock: [{
name: 'SourceMathBlock', before: 'FencedCode',
parse(context, line) {
const text = line.text.slice(line.pos);
if (text.trim() !== '$$') return false;
const from = context.lineStart + line.pos;
let to = context.lineStart + line.text.length;
while (context.nextLine()) {
to = context.lineStart + line.text.length;
if (line.text.slice(line.pos).trim() === '$$') { context.nextLine(); break; }
}
context.addElement(context.elt('SourceMathBlock', from, to));
return true;
},
}],
parseInline: [{
name: 'SourceMathInline', before: 'Emphasis',
parse(context, next, from) {
if (next !== 36 || context.char(from - 1) === 36 || /[\s$]/.test(context.slice(from + 1, from + 2))) return -1;
for (let to = from + 1; to < Math.min(context.end, from + 30_000); to++) {
const char = context.char(to);
if (char === 10) return -1;
if (char === 92) { to++; continue; }
if (char === 36) {
if (to === from + 1 || /\s/.test(context.slice(to - 1, to)) || context.char(to + 1) === 36 || /\d/.test(context.slice(to + 1, to + 2))) return -1;
return context.addElement(context.elt('SourceMathInline', from, to + 1));
}
}
return -1;
},
}],
};
export const sourceMarkdownExtensions = [GFM, mathAsSource];
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Keine geeigneten lokalen Bilder in dieser Notiz.",
"ai.vision.privacy": "{count, plural, one {# ausgewähltes Bild wird} other {# ausgewählte Bilder werden}} mit dieser Anfrage an {provider} gesendet. Bilder können Tokenverbrauch und Kosten erhöhen.",
"ai.vision.describe": "Ausgewählte Bilder beschreiben",
"ai.mediaMismatch": "Die KI hat Medienplatzhalter entfernt oder dupliziert. Das Ergebnis wurde nicht angewendet. Erneut versuchen oder den Text manuell kopieren."
"ai.mediaMismatch": "Die KI hat Medienplatzhalter entfernt oder dupliziert. Das Ergebnis wurde nicht angewendet. Erneut versuchen oder den Text manuell kopieren.",
"editorMode.label": "Editormodus",
"editorMode.rich": "Formatierter Text",
"editorMode.live": "Live-Vorschau",
"editorMode.source": "Markdown-Quelltext",
"livePreview.toggleTask": "Aufgabenstatus umschalten",
"livePreview.editImage": "Bildquelltext bearbeiten",
"vaultSwitcher.label": "Tresor wechseln",
"vaultSwitcher.add": "Tresor hinzufügen…",
"vaultSwitcher.empty": "Keine gespeicherten Tresore",
"vaultSwitcher.switching": "Tresor wird gewechselt…",
"vaultSwitcher.failed": "Tresor konnte nicht geöffnet werden: {error}",
"vaultSwitcher.blocked": "Die aktuelle Notiz konnte nicht gespeichert werden oder ist beschäftigt. Beheben Sie den Speicherfehler oder warten Sie auf das Ende des Vorgangs und versuchen Sie es erneut.",
"vaultSwitcher.stale": "Der aktive Tresor hat sich geändert. Öffnen Sie dieses Menü erneut und versuchen Sie es noch einmal.",
"editorMode.newNotes": "Editor für neue Notizen",
"editorMode.newNotesHelp": "Wählen Sie den Editor für neue leere Notizen. Bestehende Notizen bleiben unverändert.",
"editorMode.saveFailed": "Editor-Einstellung konnte nicht gespeichert werden: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "No eligible local images in this note.",
"ai.vision.privacy": "{count, plural, one {# checked image will be sent} other {# checked images will be sent}} to {provider} with this request. Images can increase token usage and cost.",
"ai.vision.describe": "Describe selected images",
"ai.mediaMismatch": "The AI removed or duplicated media placeholders. The result was not applied. Retry or copy the text manually."
"ai.mediaMismatch": "The AI removed or duplicated media placeholders. The result was not applied. Retry or copy the text manually.",
"editorMode.label": "Editor mode",
"editorMode.rich": "Rich text",
"editorMode.live": "Live preview",
"editorMode.source": "Markdown source",
"livePreview.toggleTask": "Toggle task",
"livePreview.editImage": "Edit image source",
"vaultSwitcher.label": "Switch vault",
"vaultSwitcher.add": "Add vault…",
"vaultSwitcher.empty": "No saved vaults",
"vaultSwitcher.switching": "Switching vault…",
"vaultSwitcher.failed": "Could not open the vault: {error}",
"vaultSwitcher.blocked": "The current note could not be saved or is busy. Resolve the save error or wait for the operation to finish, then try again.",
"vaultSwitcher.stale": "The active vault changed. Reopen this menu and try again.",
"editorMode.newNotes": "New note editor",
"editorMode.newNotesHelp": "Choose the editor for new empty notes. This does not change existing notes.",
"editorMode.saveFailed": "Could not save the editor preference: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "No hay imágenes locales compatibles en esta nota.",
"ai.vision.privacy": "{count, plural, one {Se enviará # imagen seleccionada} other {Se enviarán # imágenes seleccionadas}} a {provider} con esta solicitud. Las imágenes pueden aumentar el consumo de tokens y el coste.",
"ai.vision.describe": "Describir imágenes seleccionadas",
"ai.mediaMismatch": "La IA eliminó o duplicó marcadores de archivos. El resultado no se aplicó. Reintenta o copia el texto manualmente."
"ai.mediaMismatch": "La IA eliminó o duplicó marcadores de archivos. El resultado no se aplicó. Reintenta o copia el texto manualmente.",
"editorMode.label": "Modo del editor",
"editorMode.rich": "Texto enriquecido",
"editorMode.live": "Vista previa en vivo",
"editorMode.source": "Código Markdown",
"livePreview.toggleTask": "Cambiar el estado de la tarea",
"livePreview.editImage": "Editar el código de la imagen",
"vaultSwitcher.label": "Cambiar de bóveda",
"vaultSwitcher.add": "Añadir bóveda…",
"vaultSwitcher.empty": "No hay bóvedas guardadas",
"vaultSwitcher.switching": "Cambiando de bóveda…",
"vaultSwitcher.failed": "No se pudo abrir la bóveda: {error}",
"vaultSwitcher.blocked": "No se pudo guardar la nota actual o está ocupada. Resuelve el error de guardado o espera a que termine la operación e inténtalo de nuevo.",
"vaultSwitcher.stale": "La bóveda activa ha cambiado. Vuelve a abrir este menú e inténtalo de nuevo.",
"editorMode.newNotes": "Editor de notas nuevas",
"editorMode.newNotesHelp": "Elige el editor para las notas nuevas vacías. Las notas existentes no cambian.",
"editorMode.saveFailed": "No se pudo guardar la preferencia del editor: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Aucune image locale compatible dans cette note.",
"ai.vision.privacy": "{count, plural, one {# image sélectionnée sera envoyée} other {# images sélectionnées seront envoyées}} à {provider} avec cette requête. Les images peuvent augmenter la consommation de jetons et le coût.",
"ai.vision.describe": "Décrire les images sélectionnées",
"ai.mediaMismatch": "L''IA a supprimé ou dupliqué des marqueurs de médias. Le résultat n''a pas été appliqué. Réessayez ou copiez le texte manuellement."
"ai.mediaMismatch": "L''IA a supprimé ou dupliqué des marqueurs de médias. Le résultat n''a pas été appliqué. Réessayez ou copiez le texte manuellement.",
"editorMode.label": "Mode de l’éditeur",
"editorMode.rich": "Texte enrichi",
"editorMode.live": "Aperçu en direct",
"editorMode.source": "Source Markdown",
"livePreview.toggleTask": "Changer l’état de la tâche",
"livePreview.editImage": "Modifier la source de l’image",
"vaultSwitcher.label": "Changer de coffre",
"vaultSwitcher.add": "Ajouter un coffre…",
"vaultSwitcher.empty": "Aucun coffre enregistré",
"vaultSwitcher.switching": "Changement de coffre…",
"vaultSwitcher.failed": "Impossible d’ouvrir le coffre : {error}",
"vaultSwitcher.blocked": "La note actuelle n’a pas pu être enregistrée ou est occupée. Corrigez l’erreur d’enregistrement ou attendez la fin de l’opération, puis réessayez.",
"vaultSwitcher.stale": "Le coffre actif a changé. Rouvrez ce menu et réessayez.",
"editorMode.newNotes": "Éditeur des nouvelles notes",
"editorMode.newNotesHelp": "Choisissez l’éditeur des nouvelles notes vides. Les notes existantes restent inchangées.",
"editorMode.saveFailed": "Impossible d’enregistrer la préférence de l’éditeur : {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Nessuna immagine locale compatibile in questa nota.",
"ai.vision.privacy": "{count, plural, one {# immagine selezionata verrà inviata} other {# immagini selezionate verranno inviate}} a {provider} con questa richiesta. Le immagini possono aumentare il consumo di token e il costo.",
"ai.vision.describe": "Descrivi immagini selezionate",
"ai.mediaMismatch": "L''IA ha rimosso o duplicato segnaposto multimediali. Il risultato non è stato applicato. Riprova o copia il testo manualmente."
"ai.mediaMismatch": "L''IA ha rimosso o duplicato segnaposto multimediali. Il risultato non è stato applicato. Riprova o copia il testo manualmente.",
"editorMode.label": "Modalità editor",
"editorMode.rich": "Testo formattato",
"editorMode.live": "Anteprima dal vivo",
"editorMode.source": "Sorgente Markdown",
"livePreview.toggleTask": "Cambia lo stato dell’attività",
"livePreview.editImage": "Modifica il sorgente dell’immagine",
"vaultSwitcher.label": "Cambia archivio",
"vaultSwitcher.add": "Aggiungi archivio…",
"vaultSwitcher.empty": "Nessun archivio salvato",
"vaultSwitcher.switching": "Cambio archivio…",
"vaultSwitcher.failed": "Impossibile aprire l’archivio: {error}",
"vaultSwitcher.blocked": "La nota attuale non è stata salvata o è occupata. Risolvi l’errore di salvataggio o attendi la fine dell’operazione e riprova.",
"vaultSwitcher.stale": "L’archivio attivo è cambiato. Riapri questo menu e riprova.",
"editorMode.newNotes": "Editor delle nuove note",
"editorMode.newNotesHelp": "Scegli l’editor per le nuove note vuote. Le note esistenti non cambiano.",
"editorMode.saveFailed": "Impossibile salvare la preferenza dell’editor: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Geen geschikte lokale afbeeldingen in deze notitie.",
"ai.vision.privacy": "{count, plural, one {# aangevinkte afbeelding wordt} other {# aangevinkte afbeeldingen worden}} met dit verzoek naar {provider} gestuurd. Afbeeldingen kunnen het tokengebruik en de kosten verhogen.",
"ai.vision.describe": "Gekozen afbeeldingen beschrijven",
"ai.mediaMismatch": "De AI heeft mediamarkeringen verwijderd of herhaald. Het resultaat is niet toegepast. Probeer opnieuw of kopieer de tekst handmatig."
"ai.mediaMismatch": "De AI heeft mediamarkeringen verwijderd of herhaald. Het resultaat is niet toegepast. Probeer opnieuw of kopieer de tekst handmatig.",
"editorMode.label": "Editormodus",
"editorMode.rich": "Opgemaakte tekst",
"editorMode.live": "Livevoorbeeld",
"editorMode.source": "Markdown-bron",
"livePreview.toggleTask": "Taak afvinken of herstellen",
"livePreview.editImage": "Afbeeldingsbron bewerken",
"vaultSwitcher.label": "Kluis wisselen",
"vaultSwitcher.add": "Kluis toevoegen…",
"vaultSwitcher.empty": "Geen opgeslagen kluizen",
"vaultSwitcher.switching": "Kluis wisselen…",
"vaultSwitcher.failed": "Kan de kluis niet openen: {error}",
"vaultSwitcher.blocked": "De huidige notitie kon niet worden opgeslagen of is bezig. Los de opslagfout op of wacht tot de bewerking klaar is en probeer het opnieuw.",
"vaultSwitcher.stale": "De actieve kluis is gewijzigd. Open dit menu opnieuw en probeer het nogmaals.",
"editorMode.newNotes": "Editor voor nieuwe notities",
"editorMode.newNotesHelp": "Kies de editor voor nieuwe lege notities. Bestaande notities veranderen niet.",
"editorMode.saveFailed": "Kan de editorvoorkeur niet opslaan: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Não há imagens locais compatíveis nesta nota.",
"ai.vision.privacy": "{count, plural, =0 {# imagens selecionadas serão enviadas} one {# imagem selecionada será enviada} other {# imagens selecionadas serão enviadas}} ao {provider} com esta solicitação. As imagens podem aumentar o consumo de tokens e o custo.",
"ai.vision.describe": "Descrever imagens selecionadas",
"ai.mediaMismatch": "A IA removeu ou duplicou marcadores de anexos. O resultado não foi aplicado. Tente novamente ou copie o texto manualmente."
"ai.mediaMismatch": "A IA removeu ou duplicou marcadores de anexos. O resultado não foi aplicado. Tente novamente ou copie o texto manualmente.",
"editorMode.label": "Modo do editor",
"editorMode.rich": "Texto formatado",
"editorMode.live": "Prévia em tempo real",
"editorMode.source": "Código Markdown",
"livePreview.toggleTask": "Alternar o estado da tarefa",
"livePreview.editImage": "Editar o código da imagem",
"vaultSwitcher.label": "Trocar de cofre",
"vaultSwitcher.add": "Adicionar cofre…",
"vaultSwitcher.empty": "Nenhum cofre salvo",
"vaultSwitcher.switching": "Trocando de cofre…",
"vaultSwitcher.failed": "Não foi possível abrir o cofre: {error}",
"vaultSwitcher.blocked": "A nota atual não pôde ser salva ou está ocupada. Resolva o erro ao salvar ou aguarde o fim da operação e tente novamente.",
"vaultSwitcher.stale": "O cofre ativo mudou. Reabra este menu e tente novamente.",
"editorMode.newNotes": "Editor de novas notas",
"editorMode.newNotesHelp": "Escolha o editor para novas notas vazias. As notas existentes não serão alteradas.",
"editorMode.saveFailed": "Não foi possível salvar a preferência do editor: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "Não há imagens locais compatíveis nesta nota.",
"ai.vision.privacy": "{count, plural, one {# imagem selecionada será enviada} other {# imagens selecionadas serão enviadas}} para {provider} com este pedido. As imagens podem aumentar o consumo de tokens e o custo.",
"ai.vision.describe": "Descrever imagens selecionadas",
"ai.mediaMismatch": "A IA removeu ou duplicou marcadores de anexos. O resultado não foi aplicado. Tente novamente ou copie o texto manualmente."
"ai.mediaMismatch": "A IA removeu ou duplicou marcadores de anexos. O resultado não foi aplicado. Tente novamente ou copie o texto manualmente.",
"editorMode.label": "Modo do editor",
"editorMode.rich": "Texto formatado",
"editorMode.live": "Pré-visualização em tempo real",
"editorMode.source": "Código Markdown",
"livePreview.toggleTask": "Alternar o estado da tarefa",
"livePreview.editImage": "Editar o código da imagem",
"vaultSwitcher.label": "Mudar de cofre",
"vaultSwitcher.add": "Adicionar cofre…",
"vaultSwitcher.empty": "Nenhum cofre guardado",
"vaultSwitcher.switching": "A mudar de cofre…",
"vaultSwitcher.failed": "Não foi possível abrir o cofre: {error}",
"vaultSwitcher.blocked": "A nota atual não pôde ser guardada ou está ocupada. Resolva o erro de gravação ou aguarde o fim da operação e tente novamente.",
"vaultSwitcher.stale": "O cofre ativo mudou. Reabra este menu e tente novamente.",
"editorMode.newNotes": "Editor de novas notas",
"editorMode.newNotesHelp": "Escolha o editor para novas notas vazias. As notas existentes não são alteradas.",
"editorMode.saveFailed": "Não foi possível guardar a preferência do editor: {error}"
}
+17 -1
View File
@@ -1176,5 +1176,21 @@
"ai.vision.none": "В заметке нет подходящих локальных изображений.",
"ai.vision.privacy": "{count, plural, one {# выбранное изображение будет отправлено} few {# выбранных изображения будут отправлены} many {# выбранных изображений будут отправлены} other {# выбранного изображения будут отправлены}} провайдеру {provider} с этим запросом. Изображения могут увеличить расход токенов и стоимость.",
"ai.vision.describe": "Описать выбранные изображения",
"ai.mediaMismatch": "ИИ удалил или повторил маркеры вложений. Результат не применён. Повторите запрос или скопируйте текст вручную."
"ai.mediaMismatch": "ИИ удалил или повторил маркеры вложений. Результат не применён. Повторите запрос или скопируйте текст вручную.",
"editorMode.label": "Режим редактора",
"editorMode.rich": "Форматированный текст",
"editorMode.live": "Живой предпросмотр",
"editorMode.source": "Исходный текст Markdown",
"livePreview.toggleTask": "Переключить выполнение задачи",
"livePreview.editImage": "Изменить исходный код изображения",
"vaultSwitcher.label": "Сменить хранилище",
"vaultSwitcher.add": "Добавить хранилище…",
"vaultSwitcher.empty": "Нет сохранённых хранилищ",
"vaultSwitcher.switching": "Смена хранилища…",
"vaultSwitcher.failed": "Не удалось открыть хранилище: {error}",
"vaultSwitcher.blocked": "Текущая заметка не сохранена или занята. Устраните ошибку сохранения или дождитесь завершения операции и повторите попытку.",
"vaultSwitcher.stale": "Активное хранилище изменилось. Откройте меню заново и повторите попытку.",
"editorMode.newNotes": "Редактор новых заметок",
"editorMode.newNotesHelp": "Выберите редактор для новых пустых заметок. Существующие заметки не изменятся.",
"editorMode.saveFailed": "Не удалось сохранить настройку редактора: {error}"
}
+7 -5
View File
@@ -84,7 +84,7 @@ export const mobileView = writable<"sidebar" | "notelist" | "editor">(
// Editor state
export const editorDirty = writable(false);
export const sourceMode = writable(false);
export { sourceMode, livePreviewMode, editorMode, selectEditorMode } from '../editor/mode.ts';
export const focusMode = writable(false);
export const readOnly = writable(false);
@@ -249,12 +249,14 @@ export const navHistory = createNavHistory();
export const canGoBack = derived(navHistory, $h => $h.index > 0);
export const canGoForward = derived(navHistory, $h => $h.index < $h.stack.length - 1);
let dataVaultPath: string | null = null;
let dataVaultIdentity = '';
/** Never expose the previous vault's editable note while a new vault loads. */
export function activateVaultData(vaultPath: string | null): void {
if (dataVaultPath === vaultPath) return;
dataVaultPath = vaultPath;
export function activateVaultData(vaultPath: string | null, bookmarkId: string | null = null, fresh = false): void {
const identity = JSON.stringify([vaultPath, bookmarkId]);
if (!fresh && dataVaultIdentity === identity) return;
dataVaultIdentity = identity;
syncState.set({ running: false, error: null, result: null });
activeNote.set(null);
activeNotePath.set(null);
activeNotebook.set(null);
+3 -3
View File
@@ -75,10 +75,9 @@ export interface PendingOpenFile {
path: string;
}
export interface ExternalVaultResult {
bookmarkId: string;
export interface VaultIdentity {
path: string;
name: string;
bookmarkId: string | null;
}
export interface CustomThemeColors {
@@ -164,6 +163,7 @@ export interface AppConfig {
ai_writing_style: string | null;
default_view_mode: boolean;
new_notes_in_source_mode: boolean;
new_note_editor_mode?: 'rich' | 'live' | 'source' | null;
show_tray_icon: boolean;
close_to_tray: boolean;
enable_wiki_links: boolean;
+88
View File
@@ -0,0 +1,88 @@
import type { AppConfig, VaultConfig, VaultIdentity } from '../types.ts';
export type VaultTarget = VaultIdentity & { existing: boolean };
export type VaultSwitchResult = 'done' | 'cancelled' | 'blocked' | 'stale' | 'busy';
export type VaultRelease = () => void;
export function vaultIdentity(vault: VaultConfig): VaultIdentity {
return { path: vault.path, bookmarkId: vault.bookmark_id ?? null };
}
export function activeVaultIdentity(config: Pick<AppConfig, 'active_vault' | 'active_bookmark_id'> | null): VaultIdentity | null {
return config?.active_vault ? { path: config.active_vault, bookmarkId: config.active_bookmark_id ?? null } : null;
}
export function vaultIdentityKey(vault: VaultIdentity | null): string {
return JSON.stringify(vault ? [vault.path, vault.bookmarkId] : null);
}
export function sameVault(a: VaultIdentity | null, b: VaultIdentity | null): boolean {
if (!a || !b) return a === b;
return a.bookmarkId || b.bookmarkId ? !!a.bookmarkId && a.bookmarkId === b.bookmarkId : a.path === b.path;
}
export function vaultEventMatches(event: { vault_path: string; bookmark_id?: string | null }, active: VaultIdentity | null): boolean {
const normalize = (path: string) => path.replace(/\\/g, '/').replace(/\/+$/, '');
return !!active && typeof event.vault_path === 'string' && normalize(event.vault_path) === normalize(active.path) && (event.bookmark_id ?? null) === active.bookmarkId;
}
export function vaultDisplayName(vault: Pick<VaultConfig, 'name' | 'path'>): string {
return vault.name.trim() || vault.path.replace(/\\/g, '/').replace(/\/+$/, '').split('/').at(-1) || vault.path;
}
/** Preserve live device preferences when publishing the native activation snapshot. */
export function mergeVaultActivation(current: AppConfig | null, activated: AppConfig): AppConfig {
if (!current) return activated;
return { ...current, active_vault: activated.active_vault, active_bookmark_id: activated.active_bookmark_id,
vaults: activated.vaults.map(vault => {
const previous = current.vaults.find(item => sameVault(vaultIdentity(item), vaultIdentity(vault)));
const latest = (a: string | null | undefined, b: string | null | undefined) =>
a && (!b || Date.parse(a) > Date.parse(b)) ? a : b;
return previous ? { ...vault,
last_sync_time: latest(previous.last_sync_time, vault.last_sync_time),
last_backup_time: latest(previous.last_backup_time, vault.last_backup_time) } : vault;
}) };
}
export interface VaultSwitchHooks {
current: () => VaultIdentity | null;
/** Save and freeze editing until the returned release function is called. */
acquire: () => Promise<VaultRelease | null>;
open: (target: VaultTarget, expected: VaultIdentity) => Promise<AppConfig>;
commit: (config: AppConfig) => Promise<void>;
manage: () => Promise<void>;
busy: (value: boolean) => void;
}
/** One transition at a time. Never clear the old document before native activation succeeds. */
export function createVaultSwitch(hooks: VaultSwitchHooks) {
let busy = false;
async function run(choose: (() => Promise<VaultTarget | null>) | null): Promise<VaultSwitchResult> {
if (busy) return 'busy';
const origin = hooks.current();
if (!origin) return 'stale';
const originKey = vaultIdentityKey(origin);
let release: VaultRelease | null = null;
busy = true;
hooks.busy(true);
try {
const target = choose ? await choose() : null;
if (choose && !target) return 'cancelled';
if (vaultIdentityKey(hooks.current()) !== originKey) return 'stale';
if (target && sameVault(origin, target)) return 'done';
release = await hooks.acquire();
if (!release) return 'blocked';
if (vaultIdentityKey(hooks.current()) !== originKey) return 'stale';
if (target) {
const config = await hooks.open(target, origin);
if (!sameVault(activeVaultIdentity(config), target) || !Array.isArray(config.vaults)) {
throw new Error('The vault activation response was invalid.');
}
await hooks.commit(config);
} else await hooks.manage();
return 'done';
} finally {
try { release?.(); } finally { busy = false; hooks.busy(false); }
}
}
return {
switchTo: (vault: VaultConfig) => run(async () => ({ ...vaultIdentity(vault), existing: true })),
add: (choose: () => Promise<VaultTarget | null>) => run(choose),
manage: () => run(null),
};
}
+5 -4
View File
@@ -277,10 +277,9 @@
// Note windows don't re-open the vault (already open in main process)
if (!noteWindowPath) {
if (isIOS && activeVault?.bookmark_id) {
await restoreExternalVault(activeVault.bookmark_id);
$appConfig = await getAppConfig();
$appConfig = await restoreExternalVault(activeVault.bookmark_id);
} else {
await openVault(config.active_vault);
$appConfig = await openVault(config.active_vault, { existing: true });
}
}
$vaultReady = true;
@@ -324,7 +323,9 @@
{:else if noteWindowPath}
<NoteWindow notePath={noteWindowPath} vaultPath={noteWindowVault} />
{:else if $vaultReady}
<AppLayout />
{#key JSON.stringify([$appConfig?.active_vault ?? null, $appConfig?.active_bookmark_id ?? null])}
<AppLayout />
{/key}
{:else}
<VaultPicker initialError={startupVaultError} />
{/if}
@@ -0,0 +1,35 @@
<script lang="ts">
import { get } from 'svelte/store';
import { untrack } from 'svelte';
import { applyLanguage } from '../../src/lib/i18n';
import NewNoteEditorSetting from '../../src/lib/components/NewNoteEditorSetting.svelte';
import { newNoteEditorMode, selectEditorMode, editorMode, type EditorMode } from '../../src/lib/editor/mode';
import { setNewNoteEditorMode } from '../../src/lib/api';
let config = $state<{new_note_editor_mode?: EditorMode | null;new_notes_in_source_mode:boolean}>({new_notes_in_source_mode:false});
let persisted=untrack(()=>JSON.stringify(config)), fail=false, hold=false;
selectEditorMode('live');
let release: (()=>void)|null=null;
const calls: unknown[]=[];
(window as any).__TAURI_INTERNALS__.invoke=async(command:string,args:any)=>{
if(command!=='set_new_note_editor_mode')throw Error(`Unexpected command: ${command}`);
calls.push({command,args});
if(hold)await new Promise<void>(resolve=>{release=resolve;});
if(fail)throw Error('Disk full');
persisted=JSON.stringify({new_note_editor_mode:args.mode,new_notes_in_source_mode:args.mode!=='rich'});
};
async function save(mode:EditorMode){await setNewNoteEditorMode(mode);config=JSON.parse(persisted);}
Object.assign(window,{preferenceFixture:{
fail:(value:boolean)=>{fail=value;}, hold:()=>{hold=true;}, release:()=>release?.(),
legacy:(source:boolean)=>{config={new_notes_in_source_mode:source};persisted=JSON.stringify(config);},
restart:()=>{config=JSON.parse(persisted);}, language:applyLanguage,
snapshot:()=>({config:JSON.parse(JSON.stringify(config)),mode:newNoteEditorMode(config),currentEditor:get(editorMode),calls:[...calls]}),
}});
</script>
<section>
<NewNoteEditorSetting value={newNoteEditorMode(config)} onchange={save}/>
</section>
<style>
:global(:root){--bg-primary:#fff;--bg-secondary:#f3f5f7;--bg-hover:#e7edf0;--text-primary:#20252b;--text-secondary:#626e79;--accent:#276e68;--accent-light:#dfefeb;--border-color:#ced6dc;}
:global(body){margin:0;font-family:sans-serif;background:var(--bg-primary);color:var(--text-primary);}
section{padding:24px;max-width:420px;}
</style>
+56
View File
@@ -0,0 +1,56 @@
<script lang="ts">
import SourceEditor from '../../src/lib/components/SourceEditor.svelte';
import EditorModePicker from '../../src/lib/components/EditorModePicker.svelte';
import { SourceController } from '../../src/lib/editor/source/controller';
import { sourceMode, livePreviewMode, selectEditorMode } from '../../src/lib/editor/mode';
import { applyLanguage } from '../../src/lib/i18n';
const initial = 'Edit here\n\n# Heading\n\n**bold** and *italic* and ~~gone~~ and `code`\n\n[Example](https://example.org)\n\n- [ ] First task\n- [x] Second task\n\n![sample](sample.png)\n\n```js\nconst value = "**literal**";\n```\n\n> Quoted text\n\nLast line';
let edits = 0;
let readonly = $state(false);
let context = $state('first');
let dark = $state(false);
$effect(() => { document.documentElement.dataset.previewDark = String(dark); });
const opened: string[] = [];
const controller = new SourceController((_changes, edited) => { if (edited) edits++; });
controller.load(initial);
selectEditorMode('live');
const canvas = document.createElement('canvas'); canvas.width = 480; canvas.height = 180;
const drawing = canvas.getContext('2d')!;
drawing.fillStyle = '#d6e8e3'; drawing.fillRect(0, 0, 480, 180);
drawing.fillStyle = '#264e47'; drawing.font = '24px sans-serif'; drawing.fillText('Local image preview', 30, 80);
drawing.font = '16px sans-serif'; drawing.fillText('Select to edit its Markdown', 30, 116);
const image = canvas.toDataURL();
const resolveImage = () => image;
const openLink = (href: string) => { opened.push(href); };
Object.assign(window, { previewFixture: {
initial,
snapshot: () => ({ text: controller.state.doc.toString(), anchor: controller.state.selection.main.anchor, head: controller.state.selection.main.head, edits, opened: [...opened], view: !!controller.view }),
select: (from: number, to = from) => { controller.select(from, to); controller.focus(); },
mode: selectEditorMode,
insert: (text: string) => controller.replace(text, controller.state.selection.main.from, controller.state.selection.main.to),
undo: () => controller.undo(), redo: () => controller.redo(),
readOnly: (value: boolean) => { readonly = value; },
language: applyLanguage,
context: (value: string) => { context = value; },
dark: () => { dark = !dark; },
load: (text: string) => { controller.load(text); },
reveal: (from: number) => { controller.select(from, from, true); },
top: () => controller.view?.lineBlockAtHeight(controller.view.scrollDOM.scrollTop).from,
} });
</script>
<main>
<header><span>Live Preview regression fixture</span><EditorModePicker id="fixture-mode" /></header>
<section>
<SourceEditor {controller} {readonly} visible={$sourceMode} preview={$livePreviewMode} {resolveImage} {openLink} {context} numbers />
</section>
</main>
<style>
:global(body) { margin: 0; font-family: sans-serif; }
:global(:root) { --text-primary: #20242a; --text-secondary: #69737d; --bg-primary: #fff; --bg-secondary: #f3f5f6; --bg-hover: #e8edf0; --accent: #26706e; --border-color: #c9d0d4; --editor-font-size: 16px; --editor-font-family: sans-serif; --editor-line-height: 1.7; --editor-scroll-past-end: 30vh; --success: #237448; }
main { height: 100vh; background: var(--bg-primary); color: var(--text-primary); display: flex; flex-direction: column; }
:global(:root[data-preview-dark='true']) { --text-primary: #e5eaf0; --text-secondary: #9aa8b5; --bg-primary: #182027; --bg-secondary: #222d36; --bg-hover: #303d48; --border-color: #3c4b58; --accent: #79c7b6; }
header { display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; border-bottom: 1px solid var(--border-color); }
section { flex: 1; min-height: 0; padding: 18px; }
</style>
+42
View File
@@ -0,0 +1,42 @@
<script lang="ts">
import { onDestroy, untrack } from 'svelte';
import TitleBar from '../../src/lib/components/TitleBar.svelte';
import VaultSwitcher from '../../src/lib/components/VaultSwitcher.svelte';
import SourceEditor from '../../src/lib/components/SourceEditor.svelte';
import { SourceController } from '../../src/lib/editor/source/controller';
import { appConfig, editorDirty } from '../../src/lib/stores/app';
import { activeVaultIdentity, type VaultSwitchResult } from '../../src/lib/utils/vault-switch';
import type { VaultConfig } from '../../src/lib/types';
let { owner, initial, save, onselect, onadd, onmanage, busy, mobile, destroyed }: {
owner: string; initial: string; save: (text: string) => Promise<boolean>;
onselect: (vault: VaultConfig) => Promise<VaultSwitchResult>; onadd: () => Promise<VaultSwitchResult>; onmanage: () => Promise<VaultSwitchResult>;
busy: boolean; mobile: boolean; destroyed: (locked: boolean, owner: string) => void;
} = $props();
let locked = $state(false), disposed = false, dirty = false;
const controller = new SourceController((_mapping, edited) => { if (edited) { dirty = true; editorDirty.set(true); } });
controller.load(untrack(() => initial)); editorDirty.set(false);
export function edit(text: string) { controller.replace(text, controller.state.doc.length); controller.focus(); }
export function snapshot() { return { text: controller.state.doc.toString(), dirty, locked, readonly: controller.state.readOnly }; }
export async function acquire() {
if (disposed || locked || !(await save(controller.state.doc.toString()))) return null;
dirty = false; editorDirty.set(false); locked = true; controller.configure(true, false);
let released = false;
return () => { if (disposed || released) return; released = true; locked = false; controller.configure(false, false); };
}
onDestroy(() => { disposed = true; destroyed(locked, owner); });
</script>
<div class="frame" inert={busy}>
{#if mobile}
<header><VaultSwitcher vaults={$appConfig?.vaults ?? []} active={activeVaultIdentity($appConfig)} {busy} {onselect} {onadd} {onmanage} /></header>
{:else}
<TitleBar onSwitchVault={onselect} onAddVault={onadd} onManageVaults={onmanage} switching={busy} />
{/if}
<section><SourceEditor {controller} readonly={locked} {mobile} /></section>
</div>
<style>
.frame { height: 100vh; display: flex; flex-direction: column; }
header { height: 44px; padding: 0 12px; display: flex; align-items: center; background: var(--bg-secondary); border-bottom: 1px solid var(--border-color); }
section { padding: 24px; flex: 1; min-height: 0; }
</style>
+92
View File
@@ -0,0 +1,92 @@
<script lang="ts">
import { tick } from 'svelte';
import { get } from 'svelte/store';
import VaultSwitchFrame from './VaultSwitchFrame.svelte';
import { appConfig } from '../../src/lib/stores/app';
import { applyLanguage } from '../../src/lib/i18n';
import { openVault, restoreExternalVault } from '../../src/lib/api';
import { open as pickFolder } from '@tauri-apps/plugin-dialog';
import { createVaultSwitch, activeVaultIdentity, mergeVaultActivation, vaultIdentityKey } from '../../src/lib/utils/vault-switch';
import type { AppConfig, VaultConfig } from '../../src/lib/types';
const a = { path: '/notes/Work', name: 'Work' }, b = { path: '/archive/Work', name: 'Work' };
const vaults = [a, b, { path: '/home/user/Notes/Personal', name: 'Personal' }, { path: '/long/very-long-vault-folder/with-a-distinct-location', name: 'A very long vault name that must truncate in the title bar' }];
appConfig.set({ active_vault: a.path, active_bookmark_id: null, vaults, show_note_switcher: false, theme: 'light', language: 'en' } as AppConfig);
const saved = new Map(vaults.map(vault => [vault.path, `# ${vault.name}\n\nSaved note in ${vault.path}`]));
let frame = $state<VaultSwitchFrame>();
let busy = $state(false), managing = $state(false), mobile = $state(false), dark = $state(false);
let failSave = false, failOpen = false, holdOpen = false, folder: string | null = null;
let resolveOpen: (() => void) | null = null;
const calls: {command: string; args?: any}[] = [];
const destroyed: { locked: boolean; owner: string }[] = [];
let saves = 0;
$effect(() => { document.documentElement.dataset.vaultDark = String(dark); });
(window as any).__TAURI_INTERNALS__.invoke = async (command: string, args: any) => {
calls.push({ command, args });
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return 1;
if (command.startsWith('plugin:event|') || command.startsWith('plugin:window|')) return;
if (command === 'plugin:dialog|open') return folder;
if (command === 'open_vault' || command === 'restore_external_vault') {
if (holdOpen) await new Promise<void>(resolve => { resolveOpen = resolve; });
if (failOpen) throw 'Folder unavailable';
const current = get(appConfig)!;
if (JSON.stringify(args.expected) !== JSON.stringify(activeVaultIdentity(current))) throw 'Stale origin';
let rows = [...current.vaults];
let path: string = args.path;
let bookmarkId: string | null = null;
if (command === 'restore_external_vault') {
bookmarkId = args.bookmarkId; path = `/resolved/${bookmarkId}`;
rows = rows.map(vault => vault.bookmark_id === bookmarkId ? { ...vault, path } : vault);
} else if (!rows.some(vault => vault.path === path)) {
if (args.requireExisting) throw 'Vault no longer registered';
rows.push({ path, name: path.split('/').at(-1) || path });
}
return { ...current, active_vault: path, active_bookmark_id: bookmarkId, vaults: rows };
}
throw new Error(`Unexpected native call: ${command}`);
};
const switcher = createVaultSwitch({
current: () => activeVaultIdentity(get(appConfig)), busy: value => { busy = value; },
acquire: async () => frame ? frame.acquire() : null,
open: (target, expected) => target.bookmarkId ? restoreExternalVault(target.bookmarkId, expected) : openVault(target.path, { existing: target.existing, expected }),
commit: async config => { appConfig.update(current => mergeVaultActivation(current, config)); await tick(); },
manage: async () => { managing = true; await tick(); },
});
async function save(text: string) {
saves++; if (failSave) return false;
saved.set(get(appConfig)!.active_vault!, text); return true;
}
const add = () => switcher.add(async () => {
const path = await pickFolder({ directory: true, multiple: false });
return typeof path === 'string' ? { path, bookmarkId: null, existing: false } : null;
});
Object.assign(window, { vaultFixture: {
snapshot: () => ({ active: activeVaultIdentity(get(appConfig)), editor: frame?.snapshot(), busy, managing, saves, calls: [...calls], destroyed: [...destroyed] }),
edit: (text: string) => frame?.edit(text),
failSave: (value: boolean) => { failSave = value; }, failOpen: (value: boolean) => { failOpen = value; },
hold: (value: boolean) => { holdOpen = value; }, release: () => resolveOpen?.(),
folder: (value: string | null) => { folder = value; }, switchToB: () => switcher.switchTo(b),
mobile: () => { mobile = true; }, dark: () => { dark = !dark; }, language: applyLanguage,
back: () => { managing = false; },
bookmarks: () => { appConfig.update(config => ({ ...config!, vaults: [...config!.vaults, { path: '/provider/A', name: 'Files A', bookmark_id: 'book-a' }, { path: '/provider/B', name: 'Files B', bookmark_id: 'book-b' }] })); },
} });
</script>
<main>
{#if managing}<h1>Vault management fixture</h1>
{:else}
{#key vaultIdentityKey(activeVaultIdentity($appConfig))}
<VaultSwitchFrame bind:this={frame} owner={$appConfig!.active_vault!} initial={saved.get($appConfig!.active_vault!) ?? 'New vault'} {save}
onselect={switcher.switchTo} onadd={add} onmanage={switcher.manage} {busy} {mobile} destroyed={(locked, owner) => destroyed.push({ locked, owner })} />
{/key}
{/if}
</main>
<style>
:global(:root) { --bg-primary: #fff; --bg-secondary: #f3f5f7; --bg-hover: #e7edf0; --bg-tertiary: #e8edf0; --text-primary: #20252b; --text-secondary: #626e79; --text-tertiary: #79838d; --accent: #276e68; --accent-hover: #1f5e59; --border-color: #ced6dc; --editor-font-size: 16px; --editor-line-height: 1.6; }
:global(:root[data-vault-dark='true']) { --bg-primary: #182027; --bg-secondary: #222d36; --bg-hover: #303d48; --bg-tertiary: #303d48; --text-primary: #e5eaf0; --text-secondary: #a1acb8; --text-tertiary: #8b99a6; --accent: #79c7b6; --border-color: #3c4b58; }
:global(body) { margin: 0; font-family: sans-serif; color: var(--text-primary); background: var(--bg-primary); }
main { height: 100vh; }
</style>
+44
View File
@@ -0,0 +1,44 @@
import { test, expect } from '@playwright/test';
let errors:string[];
test.beforeEach(async({page})=>{errors=[];page.on('pageerror',error=>errors.push(error.message));await page.goto('/?fixture=preference');await expect(page.getByRole('radiogroup')).toBeVisible();});
test.afterEach(()=>{expect(errors).toEqual([]);});
test('Rich text is selected by default and all three choices persist without changing the current editor',async({page})=>{
await expect(page.getByRole('radio',{name:'Rich text',exact:true})).toBeChecked();
for(const [label,mode] of [['Live preview','live'],['Markdown source','source'],['Rich text','rich']]){
await page.getByRole('radio',{name:label,exact:true}).check();
await expect(page.getByRole('radio',{name:label,exact:true})).toBeChecked();
await page.evaluate(()=>(window as any).preferenceFixture.restart());
await expect(page.getByRole('radio',{name:label,exact:true})).toBeChecked();
const state=await page.evaluate(()=>(window as any).preferenceFixture.snapshot());
expect(state.mode).toBe(mode);expect(state.currentEditor).toBe('live');
}
});
test('legacy Source preference migrates and failed saves keep the previously saved button selected',async({page})=>{
await page.evaluate(()=>(window as any).preferenceFixture.legacy(true));
await expect(page.getByRole('radio',{name:'Markdown source',exact:true})).toBeChecked();
await page.evaluate(()=>(window as any).preferenceFixture.fail(true));
await page.getByRole('radio',{name:'Live preview',exact:true}).click();
await expect(page.getByRole('alert')).toContainText('Disk full');
await expect(page.getByRole('radio',{name:'Markdown source',exact:true})).toBeChecked();
await page.evaluate(()=>(window as any).preferenceFixture.fail(false));
await page.getByRole('radio',{name:'Rich text',exact:true}).check();
await expect(page.getByRole('radio',{name:'Rich text',exact:true})).toBeChecked();
});
test('native radio keyboard navigation saves the next mode and the group fits longer translations on phones',async({page},testInfo)=>{
await page.getByRole('radio',{name:'Rich text',exact:true}).focus();
await page.keyboard.press('ArrowRight');
await expect(page.getByRole('radio',{name:'Live preview',exact:true})).toBeChecked();
await expect(page.getByRole('radio',{name:'Live preview',exact:true})).toBeFocused();
await page.setViewportSize({width:360,height:640});
await page.evaluate(()=>(window as any).preferenceFixture.language('pt-PT'));
const bounds=await page.getByRole('radiogroup').boundingBox();expect(bounds!.x+bounds!.width).toBeLessThanOrEqual(360);
const copy=await page.locator('.preference-copy').boundingBox();
expect(copy!.width).toBeGreaterThanOrEqual(bounds!.width);
expect(copy!.y+copy!.height).toBeLessThan(bounds!.y);
expect((await page.locator('.preference-name').boundingBox())!.height).toBeLessThan(40);
expect((await page.locator('.preference-description').boundingBox())!.height).toBeLessThan(100);
await page.screenshot({path:testInfo.outputPath('editor-mode-buttons-phone.png'),fullPage:true});
});
+2
View File
@@ -0,0 +1,2 @@
<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Live Preview regression fixture</title></head><body><div id="app"></div><script type="module" src="/main.ts"></script></body></html>
+130
View File
@@ -0,0 +1,130 @@
import { test, expect } from '@playwright/test';
const snapshot = (page: import('@playwright/test').Page) => page.evaluate(() => (window as any).previewFixture.snapshot());
async function choose(page: import('@playwright/test').Page, name: string) {
await page.getByRole('combobox', { name: /Editor mode/ }).click();
await page.getByRole('option', { name, exact: true }).click();
}
let errors: string[];
test.beforeEach(async ({ page }) => {
errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto('/');
await expect(page.locator('.cm-editor')).toBeVisible();
});
test.afterEach(() => { expect(errors).toEqual([]); });
test('renders inline, reveals selected syntax, and preserves the source for copying', async ({ page, context }, testInfo) => {
await expect(page.locator('.lp-h1')).toHaveText('Heading');
await expect(page.locator('.lp-strong')).toHaveText('bold');
await expect(page.locator('.lp-strike')).toHaveText('gone');
await expect(page.locator('.lp-image img')).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('live-preview-desktop.png'), fullPage: true });
const before = await snapshot(page);
await page.evaluate(() => { const f = (window as any).previewFixture; f.select(f.initial.indexOf('**bold**'), f.initial.indexOf('[Example]') - 2); });
await expect(page.locator('.lp-strong')).toHaveText('**bold**');
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.keyboard.press('ControlOrMeta+c');
const copied = await page.evaluate(() => navigator.clipboard.readText());
expect(copied).toBe(before.text.slice(before.text.indexOf('**bold**'), before.text.indexOf('[Example]') - 2));
expect((await snapshot(page)).edits).toBe(0);
await page.evaluate(() => (window as any).previewFixture.select(0));
await page.locator('.lp-link').click({ modifiers: ['ControlOrMeta'] });
expect((await snapshot(page)).opened).toEqual(['https://example.org']);
});
test('source/live switching keeps the same editor, selection, unsaved text and undo/redo', async ({ page }) => {
await page.evaluate(() => {
(window as any).originalEditor = document.querySelector('.cm-content');
const f = (window as any).previewFixture; f.select(9); f.insert(' draft');
});
const before = await snapshot(page);
await choose(page, 'Markdown source');
await expect(page.locator('.lp-image')).toHaveCount(0);
await expect(page.locator('.cm-gutters')).toBeVisible();
await choose(page, 'Live preview');
await expect(page.locator('.lp-image')).toHaveCount(1);
expect(await page.evaluate(() => document.querySelector('.cm-content') === (window as any).originalEditor)).toBe(true);
expect(await snapshot(page)).toEqual(before);
await page.evaluate(() => (window as any).previewFixture.undo());
expect((await snapshot(page)).text).toBe(await page.evaluate(() => (window as any).previewFixture.initial));
await page.evaluate(() => (window as any).previewFixture.redo());
expect((await snapshot(page)).text).toBe(before.text);
});
test('task clicks change one Markdown character, are undoable, and cannot write in View mode', async ({ page }) => {
const initial = (await snapshot(page)).text;
await page.evaluate(() => { const f = (window as any).previewFixture; f.select(0); f.insert('Prefix\n\n'); });
await page.getByRole('checkbox', { name: 'Toggle task' }).first().click();
expect((await snapshot(page)).text).toBe('Prefix\n\n' + initial.replace('- [ ] First task', '- [x] First task'));
expect((await snapshot(page)).edits).toBe(2);
await page.evaluate(() => (window as any).previewFixture.undo());
expect((await snapshot(page)).text).toBe('Prefix\n\n' + initial);
await page.evaluate(() => (window as any).previewFixture.undo());
expect((await snapshot(page)).text).toBe(initial);
await page.evaluate(() => (window as any).previewFixture.readOnly(true));
await expect(page.getByRole('checkbox').first()).toBeDisabled();
const before = await snapshot(page);
await page.locator('.cm-content').click();
await page.keyboard.type('must not write');
expect((await snapshot(page)).text).toBe(before.text);
});
test('image editing and language/context changes preserve source, selection and undo', async ({ page }) => {
await page.evaluate(() => {
(window as any).originalImage = document.querySelector('.lp-image img');
const f = (window as any).previewFixture; f.select(0); f.insert('Prefix\n\n');
});
await expect.poll(() => page.evaluate(() => document.querySelector('.lp-image img') === (window as any).originalImage)).toBe(true);
const initial = (await snapshot(page)).text;
await page.getByRole('button', { name: 'Edit image source' }).click();
await expect(page.locator('.lp-image')).toHaveCount(0);
const selected = await snapshot(page);
expect(initial.slice(selected.anchor, selected.head)).toBe('![sample](sample.png)');
await page.evaluate(() => { const f = (window as any).previewFixture; f.language('ru'); f.context('other-vault'); });
await expect(page.getByRole('combobox', { name: /Режим редактора/ })).toBeVisible();
expect(await snapshot(page)).toEqual(selected);
await page.evaluate(() => (window as any).previewFixture.select(0));
await expect(page.locator('.lp-image')).toHaveCount(1);
expect((await snapshot(page)).text).toBe(initial);
});
test('mode switches retain the viewport anchor away from the start of a long note', async ({ page }) => {
await page.evaluate(() => { const f = (window as any).previewFixture; const text = 'Caret\n\n' + '## Heading\n\nParagraph **text**\n\n'.repeat(300); f.load(text); f.reveal(text.indexOf('## Heading', 3500)); });
await expect.poll(() => page.evaluate(() => (window as any).previewFixture.top())).toBeGreaterThan(1000);
const top = await page.evaluate(() => (window as any).previewFixture.top());
const before = await snapshot(page);
await choose(page, 'Markdown source');
await choose(page, 'Live preview');
expect(Math.abs((await page.evaluate(() => (window as any).previewFixture.top())) - top)).toBeLessThan(150);
expect(await snapshot(page)).toEqual(before);
});
test('unsafe links and raw HTML stay source and cannot create executable preview DOM', async ({ page }) => {
await page.evaluate(() => (window as any).previewFixture.load('Caret\n\n<img src=x onerror="window.previewInjected=true">\n\n![bad](javascript:alert)\n\n[bad](data:text/html,secret)\n\n$$\n# literal math heading\n\n![private](secret.png)\n\nx*y*z\n$$'));
await expect(page.locator('.lp-image')).toHaveCount(0);
await expect(page.locator('.cm-content img')).toHaveCount(0);
await expect(page.locator('.lp-link')).toHaveCount(0);
await expect(page.locator('.lp-h1')).toHaveCount(0);
expect(await page.evaluate(() => (window as any).previewInjected)).toBeUndefined();
expect((await snapshot(page)).edits).toBe(0);
});
test('keyboard menu works at phone width and large notes remain virtualized', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 360, height: 640 });
await page.evaluate(() => (window as any).previewFixture.dark());
const picker = page.getByRole('combobox', { name: /Editor mode/ });
await picker.focus(); await page.keyboard.press('Enter');
await page.locator('.cm-scroller').evaluate(element=>element.dispatchEvent(new Event('scroll')));
await expect(page.getByRole('listbox')).toBeVisible();
const bounds = await page.getByRole('listbox').boundingBox();
expect(bounds!.x).toBeGreaterThanOrEqual(0);
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(360);
await page.keyboard.press('Escape');
await expect(page.getByRole('listbox')).toHaveCount(0);
await page.screenshot({ path: testInfo.outputPath('live-preview-phone.png'), fullPage: true });
await page.evaluate(() => (window as any).previewFixture.load('Caret\n\n' + '## Heading\n\n**text**\n\n'.repeat(5000)));
await expect(page.locator('.lp-h2').first()).toBeVisible();
expect(await page.locator('.cm-line').count()).toBeLessThan(200);
expect((await snapshot(page)).edits).toBe(0);
});
+18
View File
@@ -0,0 +1,18 @@
import { mount } from 'svelte';
import LivePreviewHarness from './LivePreviewHarness.svelte';
const fixture = new URLSearchParams(location.search).get('fixture');
if (fixture === 'vault' || fixture === 'preference') {
Object.assign(window, {
__TAURI_INTERNALS__: { metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {}, invoke: async () => undefined },
__TAURI_EVENT_PLUGIN_INTERNALS__: { unregisterListener: () => {} },
});
if (fixture === 'vault') {
const { default: VaultSwitchHarness } = await import('./VaultSwitchHarness.svelte');
mount(VaultSwitchHarness, { target: document.getElementById('app')! });
} else {
const { default: EditorPreferenceHarness } = await import('./EditorPreferenceHarness.svelte');
mount(EditorPreferenceHarness, { target: document.getElementById('app')! });
}
} else mount(LivePreviewHarness, { target: document.getElementById('app')! });
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from '@playwright/test';
import { fileURLToPath } from 'node:url';
export default defineConfig({
testDir: '.',
testMatch: '*.spec.ts',
fullyParallel: true,
use: { baseURL: 'http://127.0.0.1:5187', headless: true, trace: 'retain-on-failure' },
webServer: {
command: 'pnpm exec vite --config tests/browser/vite.config.ts',
cwd: fileURLToPath(new URL('../..', import.meta.url)),
url: 'http://127.0.0.1:5187',
reuseExistingServer: !process.env.CI,
},
});
+155
View File
@@ -0,0 +1,155 @@
import { test, expect, type Page } from '@playwright/test';
const snapshot = (page: Page) => page.evaluate(() => (window as any).vaultFixture.snapshot());
const nativeOpens = (state: any) => state.calls.filter((call: any) => ['open_vault','restore_external_vault'].includes(call.command));
async function menu(page: Page) { await page.getByRole('button', { name: /Switch vault:/ }).click(); }
const vaultRow = (page: Page, path: string) => page.getByRole('menuitemradio').filter({ hasText: path });
let errors: string[];
test.beforeEach(async ({ page }) => {
errors=[]; page.on('pageerror', error=>errors.push(error.message));
await page.goto('/?fixture=vault');
await expect(page.locator('.cm-editor')).toBeVisible();
});
test.afterEach(() => { expect(errors).toEqual([]); });
test('duplicate names show paths and saved-vault selection publishes one atomic native response', async ({ page }, testInfo) => {
await page.evaluate(() => (window as any).vaultFixture.edit(' unsaved draft'));
await menu(page);
await expect(vaultRow(page,'/notes/Work')).toHaveAttribute('aria-checked','true');
await expect(vaultRow(page,'/archive/Work')).toHaveAttribute('aria-checked','false');
await page.screenshot({path:testInfo.outputPath('vault-switcher-desktop.png'),fullPage:true});
await vaultRow(page,'/archive/Work').click();
await expect.poll(async()=> (await snapshot(page)).active.path).toBe('/archive/Work');
const state=await snapshot(page);
expect(state.destroyed).toEqual([{locked:true,owner:'/notes/Work'}]);
expect(state.editor.text).not.toContain('unsaved draft');
expect(nativeOpens(state)).toHaveLength(1);
expect(nativeOpens(state)[0].args).toEqual({path:'/archive/Work',requireExisting:true,expected:{path:'/notes/Work',bookmarkId:null}});
expect(state.calls.some((call:any)=>call.command==='get_app_config')).toBe(false);
await menu(page); await expect(vaultRow(page,'/archive/Work')).toHaveAttribute('aria-checked','true');
await page.evaluate(()=>(window as any).vaultFixture.edit(' keep this draft'));
const dirty=await snapshot(page);
await vaultRow(page,'/archive/Work').click();
expect((await snapshot(page)).editor.text).toBe(dirty.editor.text);
expect((await snapshot(page)).editor.dirty).toBe(true);
expect((await snapshot(page)).saves).toBe(dirty.saves);
});
test('save failure keeps the draft and editor and never starts native activation', async ({ page }) => {
await page.evaluate(() => { const f=(window as any).vaultFixture; f.edit(' 日本語 😀'); f.failSave(true); (window as any).oldEditor=document.querySelector('.cm-content'); });
const before=await snapshot(page);
await menu(page); await vaultRow(page,'/archive/Work').click();
await expect(page.getByRole('alert')).toContainText('could not be saved');
const after=await snapshot(page);
expect(after.active).toEqual(before.active); expect(after.editor.text).toBe(before.editor.text);
expect(after.editor.dirty).toBe(true); expect(after.editor.readonly).toBe(false);
expect(nativeOpens(after)).toHaveLength(0); expect(after.destroyed).toEqual([]);
expect(await page.evaluate(()=>document.querySelector('.cm-content')===(window as any).oldEditor)).toBe(true);
});
test('unavailable destinations retain the current vault and allow retry without losing text', async ({ page }) => {
await page.evaluate(() => { const f=(window as any).vaultFixture; f.edit(' safe text'); f.failOpen(true); });
const text=(await snapshot(page)).editor.text;
await menu(page); await vaultRow(page,'/archive/Work').click();
await expect(page.getByRole('alert')).toContainText('Folder unavailable');
const failed=await snapshot(page);
expect(failed.active.path).toBe('/notes/Work'); expect(failed.editor.text).toBe(text);
expect(failed.editor.readonly).toBe(false); expect(failed.destroyed).toEqual([]);
await page.evaluate(()=>(window as any).vaultFixture.failOpen(false));
await vaultRow(page,'/archive/Work').click();
await expect.poll(async()=> (await snapshot(page)).active.path).toBe('/archive/Work');
await menu(page); await vaultRow(page,'/notes/Work').click();
await expect.poll(async()=> (await snapshot(page)).editor.text).toBe(text);
});
test('pending switches freeze interaction and reject overlapping requests', async ({ page }) => {
await page.evaluate(()=>(window as any).vaultFixture.hold(true));
await menu(page); await vaultRow(page,'/archive/Work').click();
await expect.poll(async()=>nativeOpens(await snapshot(page)).length).toBe(1);
await expect(page.getByRole('menuitemradio').first()).toBeDisabled();
expect((await snapshot(page)).editor.readonly).toBe(true);
expect(await page.evaluate(()=>(window as any).vaultFixture.switchToB())).toBe('busy');
const before=(await snapshot(page)).editor.text;
await page.keyboard.type('must not enter the frozen editor');
expect((await snapshot(page)).editor.text).toBe(before);
await page.evaluate(()=>(window as any).vaultFixture.release());
await expect.poll(async()=> (await snapshot(page)).active.path).toBe('/archive/Work');
expect(nativeOpens(await snapshot(page))).toHaveLength(1);
});
test('Add cancellation does not save, while choosing a folder registers it and switches', async ({ page }) => {
await page.evaluate(()=>(window as any).vaultFixture.edit(' draft before folder picker'));
const before=await snapshot(page);
await menu(page); await page.getByRole('menuitem',{name:'Add vault…'}).click();
await expect(page.getByRole('menu')).toHaveCount(0);
const cancelled=await snapshot(page);
expect(cancelled.active).toEqual(before.active); expect(cancelled.editor.text).toBe(before.editor.text);
expect(cancelled.saves).toBe(0); expect(nativeOpens(cancelled)).toHaveLength(0);
await page.evaluate(()=>(window as any).vaultFixture.folder('/notes/New vault'));
await menu(page); await page.getByRole('menuitem',{name:'Add vault…'}).click();
await expect(page.getByRole('button',{name:'Switch vault: New vault'})).toBeVisible();
const opened=await snapshot(page);
expect(nativeOpens(opened)[0].args.requireExisting).toBe(false);
expect(opened.destroyed).toEqual([{locked:true,owner:'/notes/Work'}]);
});
test('Manage uses the save gate without activating another vault', async ({ page }) => {
await page.evaluate(()=>(window as any).vaultFixture.edit(' saved before managing'));
const before=(await snapshot(page)).editor.text;
await menu(page); await page.getByRole('menuitem',{name:'Manage Vaults'}).click();
await expect(page.getByRole('heading',{name:'Vault management fixture'})).toBeVisible();
expect(nativeOpens(await snapshot(page))).toHaveLength(0);
await page.evaluate(()=>(window as any).vaultFixture.back());
await expect(page.locator('.cm-editor')).toBeVisible();
expect((await snapshot(page)).editor.text).toBe(before);
});
test('keyboard navigation, type-ahead and dismissal do not drag or maximize the window', async ({ page }) => {
const trigger=page.getByRole('button',{name:'Switch vault: Work'});
await trigger.focus(); await page.keyboard.press('ArrowDown');
await page.locator('.cm-scroller').evaluate(element=>element.dispatchEvent(new Event('scroll')));
await expect(page.getByRole('menu')).toBeVisible();
await expect(vaultRow(page,'/notes/Work')).toBeFocused();
await page.keyboard.press('End'); await expect(page.getByRole('menuitem',{name:'Manage Vaults'})).toBeFocused();
await page.keyboard.press('Home'); await page.keyboard.press('p');
await expect(vaultRow(page,'/home/user/Notes/Personal')).toBeFocused();
await page.keyboard.press('Escape'); await expect(page.getByRole('menu')).toHaveCount(0); await expect(trigger).toBeFocused();
await trigger.click(); await page.locator('section').click({position:{x:10,y:10}});
await expect(page.getByRole('menu')).toHaveCount(0);
expect((await snapshot(page)).calls.filter((call:any)=>/start_dragging|toggle_maximize/.test(call.command))).toHaveLength(0);
});
test('narrow dark layouts, long names and language changes retain readable menu paths', async ({ page },testInfo) => {
await page.evaluate(()=>(window as any).vaultFixture.mobile());
await page.setViewportSize({width:360,height:640});
await page.evaluate(()=>(window as any).vaultFixture.dark());
await menu(page);
const bounds=await page.getByRole('menu').boundingBox();
expect(bounds!.x).toBeGreaterThanOrEqual(0); expect(bounds!.x+bounds!.width).toBeLessThanOrEqual(360);
await expect(vaultRow(page,'/long/very-long-vault-folder/with-a-distinct-location')).toBeVisible();
const before=(await snapshot(page)).editor.text;
await page.evaluate(()=>(window as any).vaultFixture.language('ru'));
await expect(page.getByRole('menuitem',{name:'Добавить хранилище…'})).toBeVisible();
expect((await snapshot(page)).editor.text).toBe(before);
expect(await page.evaluate(()=>document.documentElement.scrollWidth)).toBeLessThanOrEqual(360);
await page.screenshot({path:testInfo.outputPath('vault-switcher-phone-dark.png'),fullPage:true});
});
test('a long current name fits the real title bar at a narrow desktop width', async ({ page }) => {
await menu(page);
await vaultRow(page,'/long/very-long-vault-folder/with-a-distinct-location').click();
await page.setViewportSize({width:640,height:640});
await expect(page.getByRole('button',{name:/Switch vault: A very long vault name/})).toBeVisible();
const right=await page.getByRole('button',{name:'Close',exact:true}).boundingBox();
expect(right!.x+right!.width).toBeLessThanOrEqual(640);
expect(await page.locator('.titlebar').evaluate(element=>element.scrollWidth)).toBeLessThanOrEqual(640);
});
test('security-scoped vaults restore by bookmark and accept a refreshed provider path', async ({ page }) => {
await page.evaluate(()=>(window as any).vaultFixture.bookmarks());
await menu(page); await page.getByRole('menuitemradio').filter({hasText:'Files B'}).click();
await expect.poll(async()=> (await snapshot(page)).active).toEqual({path:'/resolved/book-b',bookmarkId:'book-b'});
const state=await snapshot(page);
expect(nativeOpens(state)[0]).toEqual({command:'restore_external_vault',args:{bookmarkId:'book-b',expected:{path:'/notes/Work',bookmarkId:null}}});
await expect(page.getByRole('button',{name:'Switch vault: Files B'})).toBeVisible();
});
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { fileURLToPath } from 'node:url';
export default defineConfig({
root: fileURLToPath(new URL('.', import.meta.url)),
plugins: [svelte({ configFile: false })],
resolve: { alias: { $lib: fileURLToPath(new URL('../../src/lib', import.meta.url)) } },
server: { port: 5187, strictPort: true, host: '127.0.0.1', fs: { allow: [fileURLToPath(new URL('../..', import.meta.url))] } },
});
+38
View File
@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { get } from 'svelte/store';
import { newNoteEditorMode, selectEditorMode, editorMode } from '../src/lib/editor/mode.ts';
import { setNewNoteEditorMode } from '../src/lib/api.ts';
test('fresh profiles default to Rich text and legacy Source preferences are retained',()=>{
for(const config of [null,undefined,{}, {new_notes_in_source_mode:false}]) assert.equal(newNoteEditorMode(config),'rich');
assert.equal(newNoteEditorMode({new_notes_in_source_mode:true}),'source');
for(const mode of ['rich','live','source']) assert.equal(newNoteEditorMode({new_note_editor_mode:mode,new_notes_in_source_mode:true}),mode);
assert.equal(newNoteEditorMode({new_note_editor_mode:'invalid',new_notes_in_source_mode:true}),'source');
});
test('new-note preferences only choose a mode when explicitly applied to a new note',()=>{
selectEditorMode('live');
const config={new_note_editor_mode:'rich'};
assert.equal(newNoteEditorMode(config),'rich'); assert.equal(get(editorMode),'live');
selectEditorMode(newNoteEditorMode(config)); assert.equal(get(editorMode),'rich');
});
test('preference writes use a dedicated partial command and propagate failure',async()=>{
const before=globalThis.window, calls=[];
globalThis.window={__TAURI_INTERNALS__:{invoke:async(command,args)=>{calls.push({command,args});throw Error('disk full');}}};
try {
await assert.rejects(setNewNoteEditorMode('live'),/disk full/);
assert.deepEqual(calls,[{command:'set_new_note_editor_mode',args:{mode:'live'}}]);
} finally {if(before===undefined)delete globalThis.window;else globalThis.window=before;}
});
test('Settings has connected mode buttons and keeps the separate View-mode toggle',async()=>{
const settings=await readFile(new URL('../src/lib/components/SettingsPanel.svelte',import.meta.url),'utf8');
assert.match(settings,/<NewNoteEditorSetting value=\{newNoteMode\} onchange=\{saveNewNoteMode\}/);
assert.doesNotMatch(settings,/class:on=\{newNotesInSourceMode\}/);
assert.match(settings,/class:on=\{defaultViewMode\} role="switch"/);
const editor=await readFile(new URL('../src/lib/components/Editor.svelte',import.meta.url),'utf8');
assert.match(editor,/if \(isNewNote && !isViewer\) selectEditorMode\(newNoteEditorMode\(\$appConfig\)\)/);
});
+1 -1
View File
@@ -220,7 +220,7 @@ test('the language selector renders its popup in the app rather than delegating
assert.doesNotMatch(source, /<select[^>]+id="interface-language"/);
const select = await readFile(new URL('../src/lib/components/ThemedSelect.svelte', import.meta.url), 'utf8');
for (const selector of ['select-trigger', 'select-menu', 'select-option']) {
const rule = select.match(new RegExp(`\\.${selector}\\s*\\{([^}]+)\\}`))[1];
const rule = select.match(new RegExp(`\\n\\t\\.${selector}\\s*\\{([^}]+)\\}`))[1];
assert.match(rule, /background:\s*var\(--bg-secondary\)/, selector);
assert.match(rule, /color:\s*var\(--text-primary\)/, selector);
}
+133
View File
@@ -0,0 +1,133 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { EditorSelection, EditorState, StateEffect } from '@codemirror/state';
import { ensureSyntaxTree } from '@codemirror/language';
import { get } from 'svelte/store';
import { SourceController } from '../src/lib/editor/source/controller.ts';
import { previewDestination, previewSpans } from '../src/lib/editor/source/live-preview.ts';
import { editorMode, sourceMode, livePreviewMode, selectEditorMode } from '../src/lib/editor/mode.ts';
function fixture(text) {
const controller = new SourceController();
controller.load(text + '\n\nCaret');
controller.select(controller.state.doc.length);
return controller;
}
const hidden = state => previewSpans(state).filter(span => span.kind === 'hide').map(span => state.sliceDoc(span.from, span.to));
test('preview decorates headings, emphasis, code, lists, links and images without changing Markdown', () => {
const raw = '# Heading\n\n**bold** *italic* ~~gone~~ `code` [link](https://example.com)\n\n- [ ] task\n- [X] done\n- bullet\n\n![alt](image.png "title")';
const c = fixture(raw), doc = c.state.doc;
const spans = previewSpans(c.state);
for (const name of ['lp-heading lp-h1', 'lp-strong', 'lp-emphasis', 'lp-strike', 'lp-inline-code', 'lp-link']) assert.ok(spans.some(span => span.className === name), name);
assert.deepEqual(spans.filter(span => span.kind === 'checkbox').map(span => span.checked), [false, true]);
assert.equal(spans.find(span => span.kind === 'image').href, 'image.png');
assert.equal(spans.find(span => span.kind === 'image').label, 'alt');
assert.equal(spans.filter(span => span.kind === 'bullet').length, 1);
assert.equal(c.state.doc, doc);
assert.ok(hidden(c.state).includes('**'));
});
test('all selected lines reveal syntax, including backwards and multiple Unicode selections', () => {
const c = fixture('**日本語😀**\n\n*second*\n\n~~third~~');
c.dispatch({ effects: StateEffect.appendConfig.of(EditorState.allowMultipleSelections.of(true)) });
c.dispatch({ selection: EditorSelection.create([EditorSelection.range(10, 2), EditorSelection.range(15, 17)]) });
const hide = hidden(c.state);
assert.ok(!hide.includes('**'));
assert.ok(!hide.includes('*'));
assert.ok(hide.includes('~~'));
assert.deepEqual(previewSpans(c.state, undefined, true).filter(span => span.kind === 'hide').map(span => c.state.sliceDoc(span.from, span.to)), hide);
});
test('fenced literal Markdown is not interpreted and fences reveal together while editing the block', () => {
const c = fixture('```md\n**not bold**\n![not an image](x.png)\n```');
assert.ok(!previewSpans(c.state).some(span => ['image', 'checkbox'].includes(span.kind) || span.className === 'lp-strong'));
assert.deepEqual(hidden(c.state), ['```md', '```']);
c.select(12);
assert.deepEqual(hidden(c.state), []);
});
test('raw HTML, tables, math and unresolved wiki/reference links remain literal source', () => {
const c = fixture('<div>**raw** <img src="https://bad.invalid/x"></div>\n\n$$\nx*y*z\n$$\n\n| A | B |\n|---|---|\n| **raw** | cell |\n\n[[Wiki]]\n\n[ref][label]\n\n[label]: example.png');
assert.deepEqual(previewSpans(c.state).filter(span => span.kind !== 'line'), []);
});
test('math blocks suppress headings and images across blank lines without suppressing the following Markdown', () => {
const c = fixture('$$\n# Literal math heading\n\n![not an image](secret.png)\n\n**not bold**\n$$\n\n# Real heading\n\nText $x*y*z$ and **real bold**');
const spans = previewSpans(c.state);
assert.equal(spans.filter(span => span.className?.includes('lp-h1')).length, 1);
assert.ok(!spans.some(span => span.kind === 'image'));
assert.deepEqual(spans.filter(span => span.className === 'lp-strong').map(span => c.state.sliceDoc(span.from, span.to)), ['**real bold**']);
assert.ok(!spans.some(span => span.className === 'lp-emphasis'));
});
test('unsafe destinations never become images or clickable links', () => {
for (const value of ['javascript:alert(1)', 'data:text/html,script', 'data:image/svg+xml;base64,PHN2Zz4=', 'vbscript:x', 'file:///etc/passwd', 'java&#x73;cript:x', 'https://example.org/\u0000']) assert.equal(previewDestination(value), null, value);
for (const value of ['photo%20one.png', '../images/pic.png', 'https://example.org/pic.png', 'C:\\Vault\\pic.png', '#heading', 'mailto:me@example.org']) assert.equal(previewDestination(value), value);
const c = fixture('![bad](javascript:alert)\n\n[bad](data:text/html,x)');
assert.ok(!previewSpans(c.state).some(span => span.kind === 'image' || span.href));
});
test('empty link labels remain source instead of creating invalid zero-length decorations', () => {
const c = fixture('[](https://example.org)\n\n![](sample.png)');
const spans = previewSpans(c.state);
assert.ok(spans.every(span => span.kind !== 'mark' || span.to > span.from));
assert.ok(!spans.some(span => span.className === 'lp-link'));
assert.equal(spans.find(span => span.kind === 'image').label, '');
});
test('source/live switching retains the exact Text, selection, dirty count and both undo branches', () => {
let edits = 0;
const c = new SourceController((_, edited) => { if (edited) edits++; });
c.load('# Original\n\nUnicode 日本語😀');
c.replace(' draft', c.state.doc.length);
c.select(14, 20);
const doc = c.state.doc, selection = c.state.selection;
for (let i = 0; i < 4; i++) {
c.setLivePreview(true, { context: '/vault/Note.md' });
c.setLabels('Write', 'Live preview');
c.setLivePreview(false);
assert.equal(c.state.doc, doc);
assert.equal(c.state.selection, selection);
}
assert.equal(edits, 1);
assert.equal(c.undo(), true);
assert.equal(c.state.doc.toString(), '# Original\n\nUnicode 日本語😀');
c.setLivePreview(true);
assert.equal(c.redo(), true);
assert.equal(c.state.doc.toString(), doc.toString());
c.load('Other note');
assert.equal(c.undo(), false);
});
test('preview read-only mode renders selected syntax without enabling writes', () => {
const c = fixture('# Heading\n\n- [ ] Task');
c.select(0);
assert.ok(!hidden(c.state).includes('# '));
c.configure(true, true);
c.setLivePreview(true);
assert.ok(hidden(c.state).includes('# '));
assert.equal(c.state.readOnly, true);
c.setLivePreview(false);
assert.equal(c.state.readOnly, true);
});
test('viewport decoration work is bounded and does not scan offscreen code-block lines', () => {
const c = fixture('```md\n' + 'plain\n'.repeat(10000) + '```');
ensureSyntaxTree(c.state, c.state.doc.length, 500);
const from = 3000, to = 3300;
const spans = previewSpans(c.state, [{ from, to }]);
assert.ok(spans.length < 120, `${spans.length} decorations`);
assert.ok(spans.every(span => span.from >= c.state.doc.lineAt(from).from && span.to <= to));
});
test('mode selection preserves existing defaults and legacy toggles remember the last Markdown presentation', () => {
selectEditorMode('rich'); livePreviewMode.set(false);
assert.equal(get(editorMode), 'rich');
selectEditorMode('live'); assert.equal(get(sourceMode), true); assert.equal(get(editorMode), 'live');
sourceMode.set(false); assert.equal(get(editorMode), 'rich');
sourceMode.set(true); assert.equal(get(editorMode), 'live');
selectEditorMode('source'); assert.equal(get(editorMode), 'source');
selectEditorMode('invalid'); assert.equal(get(editorMode), 'source');
selectEditorMode('rich'); livePreviewMode.set(false);
});
+157
View File
@@ -0,0 +1,157 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
import { activeVaultIdentity, createVaultSwitch, mergeVaultActivation, sameVault, vaultEventMatches, vaultDisplayName, vaultIdentity, vaultIdentityKey } from '../src/lib/utils/vault-switch.ts';
import { openVault, restoreExternalVault } from '../src/lib/api.ts';
const a = { path: '/notes/Work', name: 'Work' }, b = { path: '/archive/Work', name: 'Work' };
const config = vault => ({ active_vault: vault.path, active_bookmark_id: vault.bookmark_id ?? null, vaults: [a,b], language: 'en', theme: 'dark' });
const deferred = () => { let resolve, reject; const promise = new Promise((yes,no) => { resolve=yes; reject=no; }); return {promise,resolve,reject}; };
function fixture(overrides = {}) {
let current = config(a), draft = 'Unsaved 日本語 😀', frozen = false;
const calls = [];
const hooks = {
current: () => activeVaultIdentity(current),
busy: value => calls.push(['busy', value]),
acquire: async () => { calls.push(['save', draft]); frozen = true; return () => { calls.push(['release']); frozen = false; }; },
open: async (target, expected) => { calls.push(['open',target,expected]); assert.equal(frozen,true); return config(target); },
commit: async next => { calls.push(['commit']); assert.equal(frozen,true); current = next; },
manage: async () => { calls.push(['manage']); assert.equal(frozen,true); },
...overrides,
};
return { switcher: createVaultSwitch(hooks), hooks, calls, get current(){ return current; }, set current(value){ current=value; }, get draft(){ return draft; }, get frozen(){ return frozen; } };
}
test('switch saves and freezes before opening, then commits before releasing', async () => {
const f = fixture();
assert.equal(await f.switcher.switchTo(b), 'done');
assert.deepEqual(f.calls.map(call=>call[0]), ['busy','save','open','commit','release','busy']);
assert.deepEqual(f.calls[2][2], {path:a.path,bookmarkId:null});
assert.equal(f.current.active_vault,b.path); assert.equal(f.frozen,false);
});
test('failed save blocks native activation without discarding the draft', async () => {
const f = fixture({acquire:async()=>null});
assert.equal(await f.switcher.switchTo(b),'blocked');
assert.equal(f.current.active_vault,a.path); assert.equal(f.draft,'Unsaved 日本語 😀');
assert.deepEqual(f.calls,[['busy',true],['busy',false]]);
});
test('failed native activation keeps old configuration and draft, releases editing, and allows retry', async () => {
let fail = true;
const f = fixture({open:async()=>{if(fail)throw Error('disk unavailable');return config(b);}});
await assert.rejects(f.switcher.switchTo(b), /disk unavailable/);
assert.equal(f.current.active_vault,a.path); assert.equal(f.draft,'Unsaved 日本語 😀'); assert.equal(f.frozen,false);
fail=false; assert.equal(await f.switcher.switchTo(b),'done');
});
test('only one switch can wait for native activation at a time', async () => {
const wait = deferred(), entered = deferred();
const f = fixture({open:async()=>{entered.resolve();return wait.promise;}});
const first = f.switcher.switchTo(b); await entered.promise;
assert.equal(await f.switcher.switchTo(a),'busy'); assert.equal(await f.switcher.manage(),'busy');
assert.equal(f.current.active_vault,a.path); assert.equal(f.frozen,true);
wait.resolve(config(b)); assert.equal(await first,'done'); assert.equal(f.frozen,false);
});
test('choosing the active vault is a no-op even if its note is dirty', async () => {
const f=fixture(); assert.equal(await f.switcher.switchTo(a),'done');
assert.deepEqual(f.calls.map(call=>call[0]),['busy','busy']); assert.equal(f.draft,'Unsaved 日本語 😀');
});
test('cancelling Add does not save or activate anything', async () => {
const f=fixture(); assert.equal(await f.switcher.add(async()=>null),'cancelled');
assert.deepEqual(f.calls,[['busy',true],['busy',false]]); assert.equal(f.current.active_vault,a.path);
});
test('Add marks its selected folder as explicit initialization, not a saved-vault switch', async () => {
const f=fixture(); const next={path:'/new/folder',bookmarkId:null,existing:false};
assert.equal(await f.switcher.add(async()=>next),'done');
assert.deepEqual(f.calls.find(call=>call[0]==='open')[1],next);
});
test('origin changes during a picker or save invalidate the transition', async () => {
const f=fixture();
assert.equal(await f.switcher.add(async()=>{f.current=config(b);return {path:'/new',bookmarkId:null,existing:false};}),'stale');
assert.ok(!f.calls.some(call=>call[0]==='save'));
let releases=0;
const g=fixture({acquire:async()=>{g.current=config(b);return ()=>releases++;}});
assert.equal(await g.switcher.switchTo(b),'stale'); assert.equal(releases,1);
assert.ok(!g.calls.some(call=>call[0]==='open'));
});
test('the editor stays frozen until asynchronous UI teardown completes', async () => {
const entered=deferred(), teardown=deferred();
const f=fixture({commit:async()=>{entered.resolve();await teardown.promise;}});
const pending=f.switcher.switchTo(b); await entered.promise;
assert.equal(f.frozen,true); assert.ok(!f.calls.some(call=>call[0]==='release'));
teardown.resolve(); await pending; assert.equal(f.frozen,false);
});
test('Manage uses the same save gate but does not open a vault', async () => {
const f=fixture(); assert.equal(await f.switcher.manage(),'done');
assert.deepEqual(f.calls.map(call=>call[0]),['busy','save','manage','release','busy']);
const g=fixture({acquire:async()=>null}); assert.equal(await g.switcher.manage(),'blocked');
assert.ok(!g.calls.some(call=>call[0]==='manage'));
});
test('picker and save exceptions leave the transition retryable', async () => {
const f=fixture(); await assert.rejects(f.switcher.add(async()=>{throw Error('picker error');}), /picker error/);
assert.equal(await f.switcher.switchTo(b),'done');
const g=fixture({acquire:async()=>{throw Error('save error');}});
await assert.rejects(g.switcher.switchTo(b), /save error/);
assert.deepEqual(g.calls,[['busy',true],['busy',false]]);
});
test('vault identity distinguishes duplicate names, paths, bookmarks and delimiter characters', () => {
assert.equal(sameVault(vaultIdentity(a),vaultIdentity(b)),false);
assert.equal(sameVault({path:'/old',bookmarkId:'book'},{path:'/resolved',bookmarkId:'book'}),true);
assert.equal(sameVault({path:'/same',bookmarkId:'one'},{path:'/same',bookmarkId:'two'}),false);
assert.equal(sameVault({path:'/same',bookmarkId:null},{path:'/same',bookmarkId:'book'}),false);
assert.notEqual(vaultIdentityKey({path:'a|b',bookmarkId:'c'}),vaultIdentityKey({path:'a',bookmarkId:'b|c'}));
assert.equal(vaultDisplayName({path:'C:\\Notes\\Work\\',name:''}),'Work');
assert.equal(vaultDisplayName({path:'/',name:''}),'/');
});
test('late sync events cannot mark a different path or bookmark as running or complete', () => {
const active={path:'/vault/Work',bookmarkId:'book-b'};
assert.equal(vaultEventMatches({vault_path:'/vault/Work',bookmark_id:'book-a'},active),false);
assert.equal(vaultEventMatches({vault_path:'/vault/Work'},active),false);
assert.equal(vaultEventMatches({vault_path:'/other/Work',bookmark_id:'book-b'},active),false);
assert.equal(vaultEventMatches({vault_path:'/vault/Work/',bookmark_id:'book-b'},active),true);
assert.equal(vaultEventMatches({vault_path:'C:\\Vault\\Work'}, {path:'C:/Vault/Work',bookmarkId:null}),true);
assert.equal(vaultEventMatches({},active),false);
});
test('activation publication preserves live language/theme preferences and newer per-vault timestamps', () => {
const old={...config(a),language:'ru',theme:'custom',vaults:[{...a,last_sync_time:'2026-11-14T12:00:00Z'},b]};
const next={...config(b),vaults:[{...a,last_sync_time:'2026-11-13T12:00:00Z'},b,{path:'/new',name:'New'}]};
const merged=mergeVaultActivation(old,next);
assert.equal(merged.active_vault,b.path); assert.equal(merged.language,'ru'); assert.equal(merged.theme,'custom');
assert.equal(merged.vaults[0].last_sync_time,old.vaults[0].last_sync_time);
assert.equal(merged.vaults.length,3); assert.equal(old.vaults.length,2);
});
test('activation API uses one atomic response and passes expected identity and existing-folder intent', async () => {
const before=globalThis.window, calls=[], snapshot=config(b), expected={path:a.path,bookmarkId:null};
globalThis.window={__TAURI_INTERNALS__:{invoke:async(command,args)=>{calls.push({command,args});return snapshot;}}};
try {
assert.equal(await openVault(b.path,{existing:true,expected}),snapshot);
assert.equal(await restoreExternalVault('bookmark',expected),snapshot);
assert.deepEqual(calls,[
{command:'open_vault',args:{path:b.path,requireExisting:true,expected}},
{command:'restore_external_vault',args:{bookmarkId:'bookmark',expected}},
]);
} finally { if(before===undefined)delete globalThis.window;else globalThis.window=before; }
});
test('application integration keys vault layouts, freezes interaction, and guards disposed editor releases', async () => {
const page=await readFile(new URL('../src/routes/+page.svelte',import.meta.url),'utf8');
assert.match(page,/\{#key JSON\.stringify\(\[\$appConfig\?\.active_vault \?\? null, \$appConfig\?\.active_bookmark_id \?\? null\]\)\}/);
const layout=await readFile(new URL('../src/lib/components/AppLayout.svelte',import.meta.url),'utf8');
assert.match(layout,/inert=\{vaultSwitchBusy\}/);
assert.match(layout,/await editor\.beginPathMutation\(\)/);
assert.match(layout,/if \(vaultSwitchBusy\) \{ e\.preventDefault\(\); return; \}/);
const editor=await readFile(new URL('../src/lib/components/Editor.svelte',import.meta.url),'utf8');
assert.match(editor,/if \(released \|\| editorDisposed\) return;/);
});