diff --git a/docs/development.md b/docs/development.md index 4af5192..02d586b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -68,6 +68,8 @@ Windows is the primary platform. macOS and Linux builds are experimental. | `backgrounds.rs` | Background image folders for themes and plugins | | `spelling.rs` | Spelling suggestions from the operating system (Windows) | | `settings.rs`, `theme.rs` | The Settings window and theme export | +| `preferences.rs` | The settings file of the user. It reads, writes, and migrates the file, and replaces a damaged file. | +| `tab_transfer.rs` | Tab transfer between windows. The offers stay in memory. | | `completion.rs` | A local proxy to a completion model server | The interface calls Rust commands through Tauri `invoke`. Most calls go through the wrappers in `src/lib/workspace/api.ts`. @@ -79,7 +81,8 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | --- | --- | | `layout/` | The app shell (`Workbench.svelte`), the file tree, tabs, panes, Settings, and dialogs | | `editor/` | The Writer view (`LiveWriter.svelte`), the source editor (`EditorHost.svelte`), tables, links, images, and editor menus | -| `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, and templates | +| `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, templates, and tab transfer (`tabTransfer.ts`) | +| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) | | `plugins/` | The plugin runtime, the SDK types (`sdk.ts`), and Settings → Plug-ins | | `browser/` | The interface of the built-in browser | | `completion/`, `git/` | Contracts and services that plugins use | @@ -107,6 +110,38 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | Documents | Ordinary files in the workspace folder | | Workspace state: tab order, pins, bookmarks, templates, Project Management boards | `.runestone/` in the workspace | | Installed plugins and their settings | The app data folder. See [plugin storage](plugin-host.md#storage-and-recovery). | +| Preferences: general settings, appearance, custom themes, display language | `settings.json` in the app config folder | +| Window layout and the open tabs of each workspace | The WebView storage (`localStorage`) of the app. RuneStone can lose these values without harm. | + +#### The settings file + +`src-tauri/src/preferences.rs` keeps the preferences in `settings.json` in the Tauri `app_config_dir()`. +On Windows, this is `%APPDATA%\com.runestone.app\`, the same folder as the app data. +On macOS, it is `~/Library/Application Support//`. On Linux, it is `~/.config//`. + +```json +{ + "schema": 1, + "revision": 12, + "general": { "autosaveEnabled": true, "autosaveSeconds": 5, "showInternalFolder": false }, + "appearance": { "theme": "default", "mode": "dark" }, + "customThemes": [], + "customThemesLegacy": [], + "language": "en" +} +``` + +| Rule | Detail | +| --- | --- | +| Sections | `general`, `appearance`, `customThemes`, `customThemesLegacy` (the original version 1 themes), and `language`. The host does not interpret their values. The frontend normalizes each section. | +| Size | At most 8 MiB in total. The appearance can hold an image data URL of up to 3,000,000 characters. | +| Writes | `settings_write` replaces one section. The host writes a complete temporary file and renames it. Then it sends `settings-changed` to all windows with the section, the revision, and the value. | +| Damaged file | The host moves the file to `settings.corrupt-.json` and writes a new file with the defaults. The first window that reads the settings shows a message one time. | +| First start | When no file exists, the window reads the old `localStorage` keys and normalizes their values. The keys are `runestone.settings`, `runestone.appearance`, `runestone.custom-themes`, `runestone.custom-themes.legacy`, and `runestone.language`. `settings_migrate` writes the values only when no file exists. RuneStone keeps the old keys for one release, but does not use them. | +| Browser preview | Without the desktop host (`pnpm dev`), the preferences stay in `localStorage` under the old keys. | + +Each window loads all sections one time before its first render (`src/routes/+layout.ts`). +After that, `src/lib/settings/store.ts` reads the sections from memory and tells subscribers about changes. ## Product boundaries @@ -186,6 +221,10 @@ A test states what it needs near its top. The runner skips the test, with the re | `PLAYWRIGHT_MODULE` | A different Playwright package | To write a smoke test, start from an existing test in the same area. The harness in `tests/smoke/_harness/index.mjs` starts the browser, mocks the Tauri commands, and gives an in-memory workspace. + +The harness also has default handlers for the settings file and for tab transfers. All pages of one browser context share them. +To seed preferences, set the old `localStorage` keys before the first load. The app then migrates them. +To read or change a section later, use `window.__TEST__.settings(section)` and `window.__TEST__.writeSettings(section, value)`. A failed test saves `failure.png` in its output folder and prints the page console errors and warnings. You can also run one test file directly while `pnpm dev` runs, for example `node tests/smoke/tabs/order.smoke.mjs`. diff --git a/docs/plugin-host.md b/docs/plugin-host.md index f9f7190..7401526 100644 --- a/docs/plugin-host.md +++ b/docs/plugin-host.md @@ -21,6 +21,9 @@ The native plugin service is in `src-tauri/src/plugins.rs`. Its root is the Taur plugin-removals// packages during confirmed removal ``` +The preferences of the app are not plugin data. They are in `settings.json` in the Tauri `app_config_dir()`. +On Windows and macOS, this is the same folder as `app_data_dir()`. See [the settings file](development.md#the-settings-file). + **Settings → Plug-ins → Open plugins folder** opens `plugins/`. The service writes `plugin-state.json` to a temporary file, then renames it. It reads at most 4 MiB from that file. After each change, the service sends the `plugins-changed` event to all windows. A settings write sends `plugin-settings-changed` with the plugin ID. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index ac55adb..7a4af12 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -17,6 +17,13 @@ fn main() { "spelling_menu_select", "spelling_menu_uninstall", "settings_open_window", + "settings_read", + "settings_write", + "settings_migrate", + "tab_transfer_offer", + "tab_transfer_take", + "tab_transfer_finish", + "tab_transfer_cancel", "completion_request", "completion_cancel", "browser_request", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index ff79961..b9c691d 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -15,6 +15,13 @@ "allow-spelling-menu-select", "allow-spelling-menu-uninstall", "allow-settings-open-window", + "allow-settings-read", + "allow-settings-write", + "allow-settings-migrate", + "allow-tab-transfer-offer", + "allow-tab-transfer-take", + "allow-tab-transfer-finish", + "allow-tab-transfer-cancel", "allow-completion-request", "allow-completion-cancel", "allow-browser-request", diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json index 20132df..d7b478b 100644 --- a/src-tauri/capabilities/settings.json +++ b/src-tauri/capabilities/settings.json @@ -8,6 +8,9 @@ ], "permissions": [ "allow-theme-export", + "allow-settings-read", + "allow-settings-write", + "allow-settings-migrate", "core:default", "core:window:allow-close", "core:window:allow-minimize", diff --git a/src-tauri/permissions/autogenerated/settings_migrate.toml b/src-tauri/permissions/autogenerated/settings_migrate.toml new file mode 100644 index 0000000..cd25c89 --- /dev/null +++ b/src-tauri/permissions/autogenerated/settings_migrate.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-settings-migrate" +description = "Enables the settings_migrate command without any pre-configured scope." +commands.allow = ["settings_migrate"] + +[[permission]] +identifier = "deny-settings-migrate" +description = "Denies the settings_migrate command without any pre-configured scope." +commands.deny = ["settings_migrate"] diff --git a/src-tauri/permissions/autogenerated/settings_read.toml b/src-tauri/permissions/autogenerated/settings_read.toml new file mode 100644 index 0000000..4fafea0 --- /dev/null +++ b/src-tauri/permissions/autogenerated/settings_read.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-settings-read" +description = "Enables the settings_read command without any pre-configured scope." +commands.allow = ["settings_read"] + +[[permission]] +identifier = "deny-settings-read" +description = "Denies the settings_read command without any pre-configured scope." +commands.deny = ["settings_read"] diff --git a/src-tauri/permissions/autogenerated/settings_write.toml b/src-tauri/permissions/autogenerated/settings_write.toml new file mode 100644 index 0000000..68e2bdd --- /dev/null +++ b/src-tauri/permissions/autogenerated/settings_write.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-settings-write" +description = "Enables the settings_write command without any pre-configured scope." +commands.allow = ["settings_write"] + +[[permission]] +identifier = "deny-settings-write" +description = "Denies the settings_write command without any pre-configured scope." +commands.deny = ["settings_write"] diff --git a/src-tauri/permissions/autogenerated/tab_transfer_cancel.toml b/src-tauri/permissions/autogenerated/tab_transfer_cancel.toml new file mode 100644 index 0000000..b01e07b --- /dev/null +++ b/src-tauri/permissions/autogenerated/tab_transfer_cancel.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-tab-transfer-cancel" +description = "Enables the tab_transfer_cancel command without any pre-configured scope." +commands.allow = ["tab_transfer_cancel"] + +[[permission]] +identifier = "deny-tab-transfer-cancel" +description = "Denies the tab_transfer_cancel command without any pre-configured scope." +commands.deny = ["tab_transfer_cancel"] diff --git a/src-tauri/permissions/autogenerated/tab_transfer_finish.toml b/src-tauri/permissions/autogenerated/tab_transfer_finish.toml new file mode 100644 index 0000000..428e606 --- /dev/null +++ b/src-tauri/permissions/autogenerated/tab_transfer_finish.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-tab-transfer-finish" +description = "Enables the tab_transfer_finish command without any pre-configured scope." +commands.allow = ["tab_transfer_finish"] + +[[permission]] +identifier = "deny-tab-transfer-finish" +description = "Denies the tab_transfer_finish command without any pre-configured scope." +commands.deny = ["tab_transfer_finish"] diff --git a/src-tauri/permissions/autogenerated/tab_transfer_offer.toml b/src-tauri/permissions/autogenerated/tab_transfer_offer.toml new file mode 100644 index 0000000..5f5d6f6 --- /dev/null +++ b/src-tauri/permissions/autogenerated/tab_transfer_offer.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-tab-transfer-offer" +description = "Enables the tab_transfer_offer command without any pre-configured scope." +commands.allow = ["tab_transfer_offer"] + +[[permission]] +identifier = "deny-tab-transfer-offer" +description = "Denies the tab_transfer_offer command without any pre-configured scope." +commands.deny = ["tab_transfer_offer"] diff --git a/src-tauri/permissions/autogenerated/tab_transfer_take.toml b/src-tauri/permissions/autogenerated/tab_transfer_take.toml new file mode 100644 index 0000000..eedb359 --- /dev/null +++ b/src-tauri/permissions/autogenerated/tab_transfer_take.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-tab-transfer-take" +description = "Enables the tab_transfer_take command without any pre-configured scope." +commands.allow = ["tab_transfer_take"] + +[[permission]] +identifier = "deny-tab-transfer-take" +description = "Denies the tab_transfer_take command without any pre-configured scope." +commands.deny = ["tab_transfer_take"] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 242d41a..b7c2bfe 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -9,6 +9,8 @@ mod browser; mod git; mod completion; mod settings; +mod preferences; +mod tab_transfer; mod spelling; mod theme; mod backgrounds; @@ -28,6 +30,8 @@ pub fn run() { .manage(browser::BrowserState::default()) .manage(completion::CompletionState::default()) .manage(settings::SettingsState::default()) + .manage(preferences::PreferencesState::default()) + .manage(tab_transfer::TabTransferState::default()) .invoke_handler(tauri::generate_handler![ backgrounds::backgrounds_choose_folder, backgrounds::backgrounds_default_folder, @@ -41,6 +45,13 @@ pub fn run() { spelling::spelling_menu_select, spelling::spelling_menu_uninstall, settings::settings_open_window, + preferences::settings_read, + preferences::settings_write, + preferences::settings_migrate, + tab_transfer::tab_transfer_offer, + tab_transfer::tab_transfer_take, + tab_transfer::tab_transfer_finish, + tab_transfer::tab_transfer_cancel, completion::completion_request, completion::completion_cancel, browser::browser_request, @@ -110,6 +121,7 @@ pub fn run() { // with short locks only. A cleanup thread stops processes and erases files. settings::close_owned_window(app, label); spelling::close_window(app, label); + app.state::().release_window(label); app.state::().close_window(label); let browser_tabs = app.state::().release_window(label); let staging = app.state::().try_release_window(label); diff --git a/src-tauri/src/preferences.rs b/src-tauri/src/preferences.rs new file mode 100644 index 0000000..9d83446 --- /dev/null +++ b/src-tauri/src/preferences.rs @@ -0,0 +1,403 @@ +//! User preferences in one file: `/settings.json`. +//! +//! The file holds a `schema` number, a `revision` number, and one value for each section. +//! The host does not interpret the section values. The frontend normalizes them. +//! Every write replaces the complete file atomically and sends `settings-changed` to all windows. +//! Plugin settings stay in the app data folder (see `plugins.rs`). + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::Serialize; +use serde_json::{Map, Value}; +use tauri::{AppHandle, Emitter, Manager}; + +use crate::error::{Error, Result}; +use crate::fsutil; + +pub const FILE_NAME: &str = "settings.json"; +pub const SCHEMA: u64 = 1; +/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion. +pub const SECTIONS: [&str; 5] = ["general", "appearance", "customThemes", "customThemesLegacy", "language"]; +/// The appearance section can hold an image data URL of up to 3,000,000 characters. +pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024; +pub const CHANGED_EVENT: &str = "settings-changed"; + +/// All sections, as the frontend reads them at startup. +#[derive(Serialize, Clone, Debug, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Snapshot { + /// False when no settings file exists yet. The frontend then migrates its old values. + pub exists: bool, + pub revision: u64, + pub sections: Map, + /// A message for the user, sent once after the host replaced a damaged file. + #[serde(skip_serializing_if = "Option::is_none")] + pub notice: Option, +} + +/// The payload of `settings-changed`. +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct Change { + pub section: String, + pub revision: u64, + pub value: Value, +} + +struct Loaded { + document: Map, + exists: bool, + notice: Option, +} + +/// The settings file and its in-memory copy. One lock serializes all reads and writes. +pub struct Store { + path: PathBuf, + loaded: Option, +} + +fn empty_document() -> Map { + let mut document = Map::new(); + document.insert("schema".into(), SCHEMA.into()); + document.insert("revision".into(), 0.into()); + document +} + +fn revision(document: &Map) -> u64 { + document.get("revision").and_then(Value::as_u64).unwrap_or(0) +} + +fn check_section(section: &str) -> Result<()> { + if SECTIONS.contains(§ion) { Ok(()) } else { Err(Error::new(format!("Unknown settings section: {section}"))) } +} + +/// Parse the file. `None` means that the file is damaged. +fn parse(bytes: &[u8]) -> Option> { + if bytes.len() > MAX_FILE_BYTES { return None; } + let Value::Object(document) = serde_json::from_slice(bytes).ok()? else { return None }; + let schema = document.get("schema").and_then(Value::as_u64)?; + if schema == 0 { return None; } + if document.get("revision").is_some_and(|value| value.as_u64().is_none()) { return None; } + Some(document) +} + +fn encode(document: &Map) -> Result> { + let mut bytes = serde_json::to_vec_pretty(document)?; + bytes.push(b'\n'); + if bytes.len() > MAX_FILE_BYTES { + return Err(Error::new("The settings are larger than 8 MiB. Remove the background image data or some custom themes, then try again.")); + } + Ok(bytes) +} + +fn temp_path(path: &Path) -> Result { + let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?; + Ok(parent.join(format!(".settings-{}.tmp", uuid::Uuid::new_v4()))) +} + +/// Move a damaged file aside to `settings.corrupt-.json`, with a counter if that name exists. +fn keep_damaged_copy(path: &Path) -> Result { + let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(); + let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?; + for attempt in 0..100u32 { + let name = if attempt == 0 { format!("settings.corrupt-{seconds}.json") } else { format!("settings.corrupt-{seconds}-{attempt}.json") }; + let copy = parent.join(name); + match fsutil::rename_no_replace(path, ©) { + Ok(()) => return Ok(copy), + Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => continue, + Err(reason) => return Err(reason.into()), + } + } + Err(Error::new("Could not keep a copy of the damaged settings file.")) +} + +impl Store { + pub fn new(path: PathBuf) -> Self { + Self { path, loaded: None } + } + + fn load(&mut self) -> Result<&mut Loaded> { + if self.loaded.is_none() { + self.loaded = Some(self.read_file()?); + } + Ok(self.loaded.as_mut().expect("loaded above")) + } + + fn read_file(&self) -> Result { + let bytes = match fsutil::open_entry(&self.path) { + Ok(file) => fsutil::read_to_limit(file, MAX_FILE_BYTES as u64)?, + Err(reason) if reason.kind() == io::ErrorKind::NotFound => { + return Ok(Loaded { document: empty_document(), exists: false, notice: None }); + } + Err(reason) => return Err(Error::new(format!("Could not read the settings file {}: {reason}", self.path.display()))), + }; + if let Some(document) = bytes.as_deref().and_then(parse) { + return Ok(Loaded { document, exists: true, notice: None }); + } + // Keep the damaged file for the user, then start again from the defaults. + let copy = keep_damaged_copy(&self.path)?; + let document = empty_document(); + fsutil::create_file(&self.path, &temp_path(&self.path)?, &encode(&document)?)?; + let notice = format!( + "RuneStone could not read your settings file, so the default settings apply. A copy of the damaged file is at {}.", + copy.display() + ); + Ok(Loaded { document, exists: true, notice: Some(notice) }) + } + + /// All known sections. The notice of a replaced file goes to the first reader only. + pub fn read(&mut self) -> Result { + let loaded = self.load()?; + let sections = SECTIONS.iter() + .filter_map(|name| loaded.document.get(*name).map(|value| ((*name).to_owned(), value.clone()))) + .collect(); + Ok(Snapshot { exists: loaded.exists, revision: revision(&loaded.document), sections, notice: loaded.notice.take() }) + } + + /// Replace one section. `null` removes it. Unknown top-level keys stay in the file. + pub fn write(&mut self, section: &str, value: Value) -> Result { + check_section(section)?; + let path = self.path.clone(); + let loaded = self.load()?; + let mut document = loaded.document.clone(); + let next = revision(&document) + 1; + if value.is_null() { document.remove(section); } else { document.insert(section.into(), value.clone()); } + document.insert("revision".into(), next.into()); + if document.get("schema").and_then(Value::as_u64).is_none_or(|schema| schema < SCHEMA) { + document.insert("schema".into(), SCHEMA.into()); + } + let bytes = encode(&document)?; + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } + fsutil::replace_file(&path, &temp_path(&path)?, &bytes) + .map_err(|reason| Error::new(format!("Could not save the settings file {}: {reason}", path.display())))?; + loaded.document = document; + loaded.exists = true; + Ok(Change { section: section.into(), revision: next, value }) + } + + /// Write the first file from the migrated values. When a file exists, keep it and return it unchanged. + pub fn migrate(&mut self, sections: Map) -> Result { + for name in sections.keys() { check_section(name)?; } + let path = self.path.clone(); + if self.load()?.exists { return self.read(); } + let mut document = empty_document(); + document.insert("revision".into(), 1.into()); + for (name, value) in sections { + if !value.is_null() { document.insert(name, value); } + } + let bytes = encode(&document)?; + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } + match fsutil::create_file(&path, &temp_path(&path)?, &bytes) { + Ok(()) => { + let loaded = self.load()?; + loaded.document = document; + loaded.exists = true; + } + // Another process wrote the file first. Use its values. + Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => self.loaded = None, + Err(reason) => return Err(Error::new(format!("Could not create the settings file {}: {reason}", path.display()))), + } + self.read() + } +} + +#[derive(Default)] +pub struct PreferencesState(Mutex>); + +fn settings_path(app: &AppHandle) -> Result { + Ok(app.path().app_config_dir().map_err(|reason| Error::new(format!("app config dir: {reason}")))?.join(FILE_NAME)) +} + +/// Run `task` with the store on a blocking thread, because it reads and writes files. +async fn with_store(app: &AppHandle, task: impl FnOnce(&mut Store) -> Result + Send + 'static) -> Result { + let app = app.clone(); + tauri::async_runtime::spawn_blocking(move || { + let state = app.state::(); + let mut guard = state.0.lock()?; + if guard.is_none() { *guard = Some(Store::new(settings_path(&app)?)); } + task(guard.as_mut().expect("set above")) + }).await? +} + +#[tauri::command] +pub async fn settings_read(app: AppHandle) -> Result { + with_store(&app, Store::read).await +} + +#[tauri::command] +pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result { + let change = with_store(&app, move |store| store.write(§ion, value)).await?; + // Every window shows the same preferences, so the change goes to all of them. + let _ = app.emit(CHANGED_EVENT, &change); + Ok(change) +} + +#[tauri::command] +pub async fn settings_migrate(app: AppHandle, sections: Map) -> Result { + with_store(&app, move |store| store.migrate(sections)).await +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::fs; + + fn fixture(name: &str) -> (PathBuf, PathBuf) { + let dir = std::env::temp_dir().join(format!("rs-preferences-{name}-{}", uuid::Uuid::new_v4())); + fs::create_dir(&dir).unwrap(); + let path = dir.join(FILE_NAME); + (dir, path) + } + + fn on_disk(path: &Path) -> Value { + serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + } + + fn files(dir: &Path) -> Vec { + let mut names: Vec<_> = fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + } + + #[test] + fn a_missing_file_reads_as_empty_and_does_not_exist() { + let (dir, path) = fixture("missing"); + let snapshot = Store::new(path.clone()).read().unwrap(); + assert_eq!(snapshot, Snapshot { exists: false, revision: 0, sections: Map::new(), notice: None }); + assert!(!path.exists()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn writes_replace_one_section_and_increase_the_revision() { + let (dir, path) = fixture("write"); + let mut store = Store::new(path.clone()); + let first = store.write("general", json!({ "autosaveSeconds": 7 })).unwrap(); + assert_eq!(first, Change { section: "general".into(), revision: 1, value: json!({ "autosaveSeconds": 7 }) }); + let second = store.write("language", json!("fr")).unwrap(); + assert_eq!(second.revision, 2); + assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 2, "general": { "autosaveSeconds": 7 }, "language": "fr" })); + // A new store reads the same values from the file. + let snapshot = Store::new(path.clone()).read().unwrap(); + assert!(snapshot.exists); + assert_eq!(snapshot.revision, 2); + assert_eq!(Value::Object(snapshot.sections), json!({ "general": { "autosaveSeconds": 7 }, "language": "fr" })); + store.write("language", Value::Null).unwrap(); + assert!(on_disk(&path).get("language").is_none()); + assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain"); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn writes_reject_unknown_sections_and_values_above_the_limit() { + let (dir, path) = fixture("limits"); + let mut store = Store::new(path.clone()); + assert!(store.write("plugins", json!({})).is_err()); + assert!(store.write("../general", json!({})).is_err()); + // A data URL of 3,000,000 characters fits. + let image = format!("data:image/png;base64,{}", "A".repeat(3_000_000)); + store.write("appearance", json!({ "newTabBackground": { "image": image } })).unwrap(); + let before = fs::read(&path).unwrap(); + let error = store.write("customThemes", json!(["x".repeat(MAX_FILE_BYTES)])).unwrap_err(); + assert!(error.to_string().contains("8 MiB"), "{error}"); + assert_eq!(fs::read(&path).unwrap(), before, "A refused write leaves the file unchanged"); + assert_eq!(store.read().unwrap().revision, 1); + assert_eq!(files(&dir), vec![FILE_NAME.to_owned()]); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn writes_keep_unknown_top_level_keys() { + let (dir, path) = fixture("unknown"); + fs::write(&path, r#"{ "schema": 1, "revision": 4, "future": { "a": 1 }, "general": {} }"#).unwrap(); + let mut store = Store::new(path.clone()); + assert_eq!(store.read().unwrap().sections.keys().collect::>(), vec!["general"]); + assert_eq!(store.write("language", json!("ja")).unwrap().revision, 5); + assert_eq!(on_disk(&path)["future"], json!({ "a": 1 })); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_damaged_file_is_kept_aside_and_reported_once() { + for (name, contents) in [("syntax", "{ broken".as_bytes()), ("array", b"[1, 2]"), ("schema", br#"{ "revision": 1 }"#), ("revision", br#"{ "schema": 1, "revision": "x" }"#)] { + let (dir, path) = fixture(name); + fs::write(&path, contents).unwrap(); + let mut store = Store::new(path.clone()); + let snapshot = store.read().unwrap(); + assert!(snapshot.exists, "{name}: no migration after a damaged file"); + assert_eq!(snapshot.revision, 0); + assert!(snapshot.sections.is_empty()); + let notice = snapshot.notice.expect("The first read reports the damaged file"); + let copies: Vec<_> = files(&dir).into_iter().filter(|file| file.starts_with("settings.corrupt-")).collect(); + assert_eq!(copies.len(), 1, "{name}"); + assert!(notice.contains(&copies[0]), "{notice}"); + assert_eq!(fs::read(dir.join(&copies[0])).unwrap(), contents, "{name}: the copy keeps the damaged bytes"); + assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 0 })); + assert_eq!(store.read().unwrap().notice, None, "Report the damaged file once"); + assert_eq!(Store::new(path.clone()).read().unwrap().notice, None, "The new file is valid"); + fs::remove_dir_all(dir).unwrap(); + } + } + + #[test] + fn a_file_above_the_limit_counts_as_damaged() { + let (dir, path) = fixture("large"); + fs::write(&path, vec![b' '; MAX_FILE_BYTES + 1]).unwrap(); + assert!(Store::new(path.clone()).read().unwrap().notice.is_some()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn migration_writes_the_first_file_only() { + let (dir, path) = fixture("migrate"); + let mut store = Store::new(path.clone()); + let sections = json!({ "general": { "autosaveEnabled": false }, "language": "fr", "customThemes": [] }); + let Value::Object(sections) = sections else { unreachable!() }; + let snapshot = store.migrate(sections.clone()).unwrap(); + assert!(snapshot.exists); + assert_eq!(snapshot.revision, 1); + assert_eq!(snapshot.sections, sections); + assert_eq!(on_disk(&path)["language"], json!("fr")); + // A second migration, for example from a second window, keeps the existing file. + store.write("language", json!("ja")).unwrap(); + let mut other = Store::new(path.clone()); + let again = other.migrate(Map::from_iter([("language".to_owned(), json!("en"))])).unwrap(); + assert_eq!(again.sections["language"], json!("ja")); + assert_eq!(on_disk(&path)["language"], json!("ja")); + let Value::Object(unknown) = json!({ "plugins": {} }) else { unreachable!() }; + assert!(Store::new(dir.join("other.json")).migrate(unknown).is_err()); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn migration_uses_a_file_that_another_writer_created_first() { + let (dir, path) = fixture("race"); + let mut store = Store::new(path.clone()); + assert!(!store.read().unwrap().exists); + fs::write(&path, r#"{ "schema": 1, "revision": 3, "language": "ja" }"#).unwrap(); + let snapshot = store.migrate(Map::from_iter([("language".to_owned(), json!("fr"))])).unwrap(); + assert_eq!(snapshot.revision, 3); + assert_eq!(snapshot.sections["language"], json!("ja")); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn writes_create_a_missing_config_folder() { + let (dir, _) = fixture("folder"); + let path = dir.join("nested").join(FILE_NAME); + Store::new(path.clone()).write("language", json!("fr")).unwrap(); + assert_eq!(on_disk(&path)["language"], json!("fr")); + fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn the_change_event_carries_the_section_revision_and_value() { + let change = Change { section: "language".into(), revision: 9, value: json!("fr") }; + assert_eq!(serde_json::to_value(&change).unwrap(), json!({ "section": "language", "revision": 9, "value": "fr" })); + let snapshot = Snapshot { exists: true, revision: 2, sections: Map::new(), notice: None }; + assert_eq!(serde_json::to_value(&snapshot).unwrap(), json!({ "exists": true, "revision": 2, "sections": {} })); + } +} diff --git a/src-tauri/src/tab_transfer.rs b/src-tauri/src/tab_transfer.rs new file mode 100644 index 0000000..bb9398d --- /dev/null +++ b/src-tauri/src/tab_transfer.rs @@ -0,0 +1,265 @@ +//! Tab transfer between windows of one workspace. +//! +//! An offer holds a tab's state, including unsaved text, in memory only. It never goes to disk. +//! 1. The source window offers the tab and puts the offer ID in the drag data or the new window URL. +//! 2. The receiving window takes the offer. A take checks the workspace root and the expiry. +//! 3. The receiving window finishes the offer. If it accepted the tab, the host sends +//! `tab-transfer-accepted` to the source window only, and the source closes its tab. +//! A refused offer becomes available again. The source tab stays open until it receives the event. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use tauri::{AppHandle, Emitter, State, Window}; + +use crate::error::{Error, Result}; + +/// An offer expires after this time if no window took it. +pub const EXPIRY: Duration = Duration::from_secs(120); +/// A taken offer that the receiver never finished is removed after this time. +const TAKEN_EXPIRY: Duration = Duration::from_secs(240); +/// A text buffer holds the text and its saved copy, and an image tab holds a data URL. +pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; +const MAX_OFFERS: usize = 32; +pub const ACCEPTED_EVENT: &str = "tab-transfer-accepted"; + +pub const EXPIRED: &str = "This tab transfer expired. Drag the tab again."; +pub const OTHER_WORKSPACE: &str = "Move tabs only between windows of the same workspace."; + +struct Offer { + source: String, + root: String, + payload: String, + created: Instant, + taker: Option, +} + +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct Accepted { + pub id: String, +} + +#[derive(Default)] +pub struct TabTransferState(Mutex>); + +fn check_id(id: &str) -> Result<()> { + uuid::Uuid::parse_str(id).map(|_| ()).map_err(|_| Error::new("Invalid tab transfer.")) +} + +fn prune(offers: &mut HashMap, now: Instant) { + offers.retain(|_, offer| { + let age = now.saturating_duration_since(offer.created); + if offer.taker.is_some() { age < TAKEN_EXPIRY } else { age < EXPIRY } + }); +} + +impl TabTransferState { + /// Keep a tab offer from `source`. The source window creates the ID, because a drag needs its data at once. + pub fn offer(&self, id: &str, source: &str, root: &str, payload: String, now: Instant) -> Result<()> { + check_id(id)?; + if payload.len() > MAX_PAYLOAD_BYTES { + return Err(Error::new("This tab is too large to move to another window. Save it, then open the file in the other window.")); + } + serde_json::from_str::(&payload).map_err(|_| Error::new("Invalid tab transfer."))?; + let mut offers = self.0.lock()?; + prune(&mut offers, now); + if offers.contains_key(id) { return Err(Error::new("Invalid tab transfer.")); } + if offers.len() >= MAX_OFFERS { + // Remove the oldest open offer. Its source tab stays open. + if let Some(oldest) = offers.iter().filter(|(_, offer)| offer.taker.is_none()) + .min_by_key(|(_, offer)| offer.created).map(|(key, _)| key.clone()) { + offers.remove(&oldest); + } else { + return Err(Error::new("Too many tab transfers are in progress. Try again.")); + } + } + offers.insert(id.into(), Offer { source: source.into(), root: root.into(), payload, created: now, taker: None }); + Ok(()) + } + + /// Give the offer to `taker` once. A different workspace leaves the offer for another window. + pub fn take(&self, id: &str, taker: &str, root: &str, now: Instant) -> Result { + check_id(id)?; + let mut offers = self.0.lock()?; + prune(&mut offers, now); + let offer = offers.get_mut(id).filter(|offer| offer.taker.is_none()).ok_or_else(|| Error::new(EXPIRED))?; + if offer.root != root { return Err(Error::new(OTHER_WORKSPACE)); } + offer.taker = Some(taker.into()); + Ok(offer.payload.clone()) + } + + /// End the take of `taker`. Return the source window to acknowledge when the taker accepted the tab. + /// A refused offer stays available for another window until it expires. + pub fn finish(&self, id: &str, taker: &str, accepted: bool) -> Result> { + check_id(id)?; + let mut offers = self.0.lock()?; + let Some(offer) = offers.get_mut(id).filter(|offer| offer.taker.as_deref() == Some(taker)) else { + return Err(Error::new(EXPIRED)); + }; + if !accepted { + offer.taker = None; + return Ok(None); + } + Ok(offers.remove(id).map(|offer| offer.source)) + } + + /// Withdraw an open offer of `source`. A taken offer stays until its receiver finishes it. + pub fn cancel(&self, id: &str, source: &str) -> Result<()> { + check_id(id)?; + let mut offers = self.0.lock()?; + if offers.get(id).is_some_and(|offer| offer.source == source && offer.taker.is_none()) { + offers.remove(id); + } + Ok(()) + } + + /// Remove the offers of a closed window, and release the offers that it took. + pub fn release_window(&self, label: &str) { + let Ok(mut offers) = self.0.lock() else { return }; + offers.retain(|_, offer| offer.source != label); + for offer in offers.values_mut() { + if offer.taker.as_deref() == Some(label) { offer.taker = None; } + } + } +} + +#[tauri::command] +pub async fn tab_transfer_offer(window: Window, state: State<'_, TabTransferState>, id: String, root: String, payload: String) -> Result { + state.offer(&id, window.label(), &root, payload, Instant::now())?; + Ok(id) +} + +#[tauri::command] +pub async fn tab_transfer_take(window: Window, state: State<'_, TabTransferState>, id: String, root: String) -> Result { + state.take(&id, window.label(), &root, Instant::now()) +} + +#[tauri::command] +pub async fn tab_transfer_finish(app: AppHandle, window: Window, state: State<'_, TabTransferState>, id: String, accepted: bool) -> Result<()> { + if let Some(source) = state.finish(&id, window.label(), accepted)? { + // Only the source window closes its tab. + app.emit_to(source.as_str(), ACCEPTED_EVENT, Accepted { id })?; + } + Ok(()) +} + +#[tauri::command] +pub async fn tab_transfer_cancel(window: Window, state: State<'_, TabTransferState>, id: String) -> Result<()> { + state.cancel(&id, window.label()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ID: &str = "00000000-0000-4000-8000-000000000001"; + const ROOT: &str = "C:\\workspace"; + + fn offered(now: Instant) -> TabTransferState { + let state = TabTransferState::default(); + state.offer(ID, "main", ROOT, r#"{"buffer":{"contents":"unsaved"}}"#.into(), now).unwrap(); + state + } + + #[test] + fn an_offer_is_taken_once() { + let now = Instant::now(); + let state = offered(now); + assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap(), r#"{"buffer":{"contents":"unsaved"}}"#); + assert_eq!(state.take(ID, "workspace-3", ROOT, now).unwrap_err().to_string(), EXPIRED); + assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main")); + assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); + assert_eq!(state.finish(ID, "workspace-2", true).unwrap_err().to_string(), EXPIRED); + } + + #[test] + fn an_offer_expires_after_two_minutes() { + let now = Instant::now(); + let state = offered(now); + assert!(state.take(ID, "workspace-2", ROOT, now + EXPIRY - Duration::from_secs(1)).is_ok()); + assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None); + assert_eq!(state.take(ID, "workspace-2", ROOT, now + EXPIRY).unwrap_err().to_string(), EXPIRED); + // A taken offer survives the expiry until its receiver finishes it. + let state = offered(now); + state.take(ID, "workspace-2", ROOT, now).unwrap(); + state.offer("00000000-0000-4000-8000-000000000002", "main", ROOT, "{}".into(), now + EXPIRY).unwrap(); + assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main")); + } + + #[test] + fn a_different_workspace_cannot_take_the_offer_and_leaves_it_open() { + let now = Instant::now(); + let state = offered(now); + assert_eq!(state.take(ID, "workspace-2", "C:\\other", now).unwrap_err().to_string(), OTHER_WORKSPACE); + assert!(state.take(ID, "workspace-3", ROOT, now).is_ok()); + } + + #[test] + fn only_the_taker_finishes_and_only_acceptance_acknowledges_the_source() { + let now = Instant::now(); + let state = offered(now); + state.take(ID, "workspace-2", ROOT, now).unwrap(); + assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED); + // A refusal sends nothing, and another window can take the offer. + assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None); + state.take(ID, "workspace-3", ROOT, now).unwrap(); + // The acknowledgement goes to the source window, not to the taker. + assert_eq!(state.finish(ID, "workspace-3", true).unwrap().as_deref(), Some("main")); + } + + #[test] + fn offers_check_the_id_the_size_and_json() { + let now = Instant::now(); + let state = TabTransferState::default(); + assert!(state.offer("not-a-uuid", "main", ROOT, "{}".into(), now).is_err()); + assert!(state.offer(ID, "main", ROOT, "{".into(), now).is_err()); + let large = format!("\"{}\"", "x".repeat(MAX_PAYLOAD_BYTES)); + assert!(state.offer(ID, "main", ROOT, large, now).unwrap_err().to_string().contains("too large")); + state.offer(ID, "main", ROOT, "{}".into(), now).unwrap(); + assert!(state.offer(ID, "main", ROOT, "{}".into(), now).is_err(), "An ID is used once"); + assert!(state.take("../x", "workspace-2", ROOT, now).is_err()); + } + + #[test] + fn the_oldest_open_offer_makes_room_for_a_new_one() { + let now = Instant::now(); + let state = TabTransferState::default(); + let ids: Vec = (0..=MAX_OFFERS).map(|index| format!("00000000-0000-4000-8000-{index:012}")).collect(); + for (index, id) in ids.iter().enumerate() { + state.offer(id, "main", ROOT, "{}".into(), now + Duration::from_millis(index as u64)).unwrap(); + } + assert_eq!(state.take(&ids[0], "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); + assert!(state.take(&ids[MAX_OFFERS], "workspace-2", ROOT, now).is_ok()); + } + + #[test] + fn the_source_cancels_only_its_open_offers() { + let now = Instant::now(); + let state = offered(now); + state.cancel(ID, "workspace-2").unwrap(); + assert!(state.take(ID, "workspace-2", ROOT, now).is_ok()); + state.cancel(ID, "main").unwrap(); + assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"), "A taken offer stays until it finishes"); + let state = offered(now); + state.cancel(ID, "main").unwrap(); + assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); + } + + #[test] + fn closing_a_window_removes_its_offers_and_releases_its_takes() { + let now = Instant::now(); + let state = offered(now); + state.take(ID, "workspace-2", ROOT, now).unwrap(); + state.release_window("workspace-2"); + assert!(state.take(ID, "workspace-3", ROOT, now).is_ok()); + state.release_window("main"); + assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED); + } + + #[test] + fn the_acknowledgement_names_the_offer() { + assert_eq!(serde_json::to_value(Accepted { id: ID.into() }).unwrap(), serde_json::json!({ "id": ID })); + } +} diff --git a/src/lib/i18n/index.ts b/src/lib/i18n/index.ts index c676c25..8edb31c 100644 --- a/src/lib/i18n/index.ts +++ b/src/lib/i18n/index.ts @@ -1,6 +1,8 @@ import { derived, get, writable } from 'svelte/store'; import { catalogs, type Locale } from './messages.ts'; +import { onSettingsChange, readSection, writeSection } from '../settings/store.ts'; export { type Locale } from './messages.ts'; +/** The old localStorage key. The language section of the settings file replaces it. */ export const LANGUAGE_KEY = 'runestone.language'; export const LANGUAGES: { id: Locale; name: string }[] = [ { id: 'en', name: 'English' }, { id: 'fr', name: 'Français' }, @@ -22,19 +24,19 @@ function applyLocale(language: Locale) { locale.set(language); if (typeof document !== 'undefined') document.documentElement.lang = language; } -export function setLocale(language: Locale) { +/** Save and apply a language. Throws at once if browser storage refuses it. The promise reports a failed save. */ +export function setLocale(language: Locale): Promise { const valid = normalizeLocale(language); - localStorage.setItem(LANGUAGE_KEY, valid); + const saved = writeSection('language', valid); applyLocale(valid); + return saved; } +/** Apply the saved language now and after each change in any window. Returns a function that stops it. */ export function syncLocale() { const read = () => { - try { applyLocale(normalizeLocale(localStorage.getItem(LANGUAGE_KEY))); } + try { applyLocale(normalizeLocale(readSection('language'))); } catch { applyLocale('en'); } }; - const sync = (event: StorageEvent) => { if (event.key === LANGUAGE_KEY || event.key === null) read(); }; read(); - window.addEventListener('storage', sync); - window.addEventListener('focus', read); - return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); }; + return onSettingsChange('language', read); } diff --git a/src/lib/layout/SettingsDialog.svelte b/src/lib/layout/SettingsDialog.svelte index 4255c1a..5e41f47 100644 --- a/src/lib/layout/SettingsDialog.svelte +++ b/src/lib/layout/SettingsDialog.svelte @@ -21,7 +21,7 @@ standalone?: boolean; windowError?: string; windowControls?: Snippet; - onSave: (value: AppSettings) => void; + onSave: (value: AppSettings) => void | Promise; onClose: () => void; } = $props(); let closeLanguage = () => {}; @@ -32,7 +32,10 @@ const bounds = anchor.getBoundingClientRect(); closeLanguage = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t("Language"), parent: dialog, items: LANGUAGES.map(item => ({ label: item.name, radio: true, checked: $locale === item.id, - run: () => { try { setLocale(item.id); error = ""; message = $t("Changes saved."); } catch { error = $t("Could not save language settings."); } } })) }).close; + run: () => { + const failed = () => { error = $t("Could not save language settings."); message = ""; }; + try { setLocale(item.id).catch(failed); error = ""; message = $t("Changes saved."); } catch { failed(); } + } })) }).close; } type Section = string; const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = $derived([ @@ -66,8 +69,9 @@ function apply(value: AppSettings) { error = ""; - try { onSave(value); message = $t("Changes saved."); } - catch { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; } + const failed = () => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; }; + try { Promise.resolve(onSave(value)).catch(failed); message = $t("Changes saved."); } + catch { failed(); } } function changeInterval() { diff --git a/src/lib/layout/SettingsWindow.svelte b/src/lib/layout/SettingsWindow.svelte index 7516992..25656b0 100644 --- a/src/lib/layout/SettingsWindow.svelte +++ b/src/lib/layout/SettingsWindow.svelte @@ -4,27 +4,25 @@ import { getCurrentWindow } from "@tauri-apps/api/window"; import SettingsDialog from "./SettingsDialog.svelte"; import WindowControls from "$lib/ui/WindowControls.svelte"; - import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; + import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store"; + import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; let settings = $state({ ...DEFAULT_SETTINGS }); let error = $state(""); function read() { - try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); } + try { settings = readSettings(); } catch { error = "Could not read your settings. Default settings apply until you save new settings."; } } onMount(() => { read(); - const sync = (event: StorageEvent) => { - if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) read(); - }; - window.addEventListener("storage", sync); - window.addEventListener("focus", read); - return () => { window.removeEventListener("storage", sync); window.removeEventListener("focus", read); }; + error = takeSettingsNotice() ?? error; + return onSettingsChange("general", read); }); function save(next: AppSettings) { - saveSettings(localStorage, next); + const saved = saveSettings(next); settings = { ...next }; error = ""; + return saved; } async function close() { if (!isTauri()) { window.location.assign("/"); return; } diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index 088d242..f7dd9a7 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -33,7 +33,9 @@ import WorkspacePicker from "./WorkspacePicker.svelte"; import SettingsDialog from "./SettingsDialog.svelte"; import BrowserSlot from "$lib/plugins/BrowserSlot.svelte"; - import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; + import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; + import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store"; + import { TAB_TRANSFER_ID, cancelTabTransfer, finishTabTransfer, offerTabTransfer, onTabTransferAccepted, parseTabTransfer, takeTabTransfer } from "$lib/workspace/tabTransfer"; import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout"; import FileTree from "./FileTree.svelte"; import EditorPane from "./EditorPane.svelte"; @@ -302,33 +304,52 @@ try { return (view && pluginTabDragData(view)) || JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); } catch (reason) { error = String(reason); return; } } + /** + * Take a tab from another window of this workspace. Both entry points use this one check: + * a new window opened with `?tabTransfer=` (`startup`), and a drop on the tab ribbon (`index`). + * The source tab closes only after this window accepts the tab. + */ + async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) { + if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer."); + const current = documents; + if (!workspace || !current || (switching && !startup)) throw new Error("Move tabs only between windows of the same workspace."); + const payload = await takeTabTransfer(id, workspace.root); + let accepted = false; + try { + const transfer = parseTabTransfer(payload); + let path = ""; + if ("buffer" in transfer) { + if (!current.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open."); + path = transfer.buffer.relPath; + if (!startup) selectTab(path); + } else { + // A new window starts its plugins after the workspace opens. Wait for them there. + const deadline = Date.now() + (startup ? 15000 : 0); + while (!await restorePluginTab(transfer.plugin as Parameters[0])) { + if (Date.now() >= deadline) throw new Error("Enable this tab's plugin before moving it to this window."); + await new Promise(resolve => setTimeout(resolve, 100)); + } + if (index !== undefined) { + if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab."); + path = `plugin:${$pluginView.key}`; + } + } + setReading(transfer.reading); + accepted = true; + if (index !== undefined) { + await tick(); + moveWorkingTab(path, index); + } + } finally { + // Without this acknowledgement, the source tab stays open. + await finishTabTransfer(id, accepted).catch(reason => console.warn("Could not finish the tab transfer.", reason)); + } + } async function receiveTab(data: string, index: number) { try { const payload = JSON.parse(data); if (typeof payload?.tabTransfer === "string") { - if (!/^[0-9a-f-]{36}$/i.test(payload.tabTransfer)) throw new Error("Invalid tab transfer."); - const key = `runestone.tab-transfer.${payload.tabTransfer}`; - const raw = localStorage.getItem(key); - if (!raw) throw new Error("This tab transfer expired. Drag the tab again."); - const transfer = JSON.parse(raw); - if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace."); - if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000) throw new Error("Invalid tab transfer."); - let path: string; - if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string" - && typeof transfer.buffer.saved === "string") { - if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open."); - path = transfer.buffer.relPath; - selectTab(path); - } else if (transfer.plugin) { - if (!await restorePluginTab(transfer.plugin)) throw new Error("Enable this tab's plugin before moving it to this window."); - if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab."); - path = `plugin:${$pluginView.key}`; - } else throw new Error("Invalid tab transfer."); - setReading(transfer.reading === true); - await tick(); - moveWorkingTab(path, index); - localStorage.setItem(key + ".accepted", "true"); - localStorage.removeItem(key); + await acceptTabTransfer(payload.tabTransfer, { index }); error = null; return; } @@ -432,6 +453,7 @@ const active = workingTabs.find(tab => tab.relPath === activeTabPath); const activeDocument = active && ("buffer" in active ? active.buffer.relPath : active.plugin.document?.path); const session: DocumentSession = { version: 1, documents, activePath: activeDocument ?? activePath }; + // The open tabs stay in localStorage on purpose: per-machine view state that is harmless to lose. try { localStorage.setItem(documentSessionKey(workspace.root), JSON.stringify(session)); } catch (reason) { console.warn("Could not save document tabs.", reason); } } @@ -480,29 +502,8 @@ status = workspace.root; refreshToken += 1; const token = new URLSearchParams(location.search).get("tabTransfer"); - if (token && /^[0-9a-f-]{36}$/i.test(token)) { - const key = `runestone.tab-transfer.${token}`; - const raw = localStorage.getItem(key); - if (raw) { - const transfer = JSON.parse(raw); - if (transfer.root === workspace.root && transfer.created > Date.now() - 120000 - && (transfer.buffer || transfer.plugin)) { - if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") { - if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window."); - } - else if (transfer.plugin) { - const deadline = Date.now() + 15000; - while (!await restorePluginTab(transfer.plugin)) { - if (Date.now() > deadline) throw new Error("Enable the plugin before moving this tab."); - await new Promise(resolve => setTimeout(resolve, 100)); - } - } else throw new Error("Invalid tab transfer."); - setReading(transfer.reading === true); - localStorage.setItem(key + ".accepted", "true"); - localStorage.removeItem(key); - } - } - } else await restoreDocumentTabs(); + if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true }); + else await restoreDocumentTabs(); } } catch (err) { error = String(err); } finally { switching = false; workbenchReady = true; } @@ -555,33 +556,44 @@ let transfer: ReturnType | undefined; try { transfer = prepareTabTransfer(tab, keepSource, true); + await transfer.offered; await workspaceOpenWindow(workspace.root, transfer.token); } catch (reason) { transfer?.finish(); error = String(reason); } } + // The offers of this window that wait for another window, by offer ID. + const pendingTransfers = new Map void>(); + onMount(() => { + if (!desktop) return; + const stop = onTabTransferAccepted(id => pendingTransfers.get(id)?.()); + return () => { void stop.then(unlisten => unlisten()); }; + }); function prepareTabTransfer(tab: EditorTab, keepSource = false, reportTimeout = false) { const current = documents; const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined); const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin)); - const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`; - let timer: ReturnType; - const finish = () => { - window.removeEventListener("storage", accepted); + const token = crypto.randomUUID(); + let timer: ReturnType | undefined; + let done = false; + const finish = (withdraw = true) => { + if (done) return; + done = true; + pendingTransfers.delete(token); clearTimeout(timer); - localStorage.removeItem(key); - localStorage.removeItem(key + ".accepted"); + if (withdraw) void cancelTabTransfer(token).catch(() => {}); }; - const accepted = (event: StorageEvent) => { - if (event.key !== key + ".accepted" || event.newValue !== "true") return; + // Close the source tab only if it did not change during the transfer. + pendingTransfers.set(token, () => { if (!keepSource && "buffer" in tab) { if (documents === current && bufferSnapshot(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath); } else if (!keepSource && "plugin" in tab && JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key); - finish(); - }; + finish(false); + }); try { - localStorage.setItem(key, JSON.stringify({ root: workspace!.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading })); - window.addEventListener("storage", accepted); + const offered = offerTabTransfer(token, workspace!.root, { ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }); + // A drag cannot wait for the offer. Report a failed drag offer here. `detachTab` reports its own. + offered.catch(reason => { finish(false); if (!reportTimeout) error = String(reason); }); timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000); - return { token, finish }; + return { token, finish, offered }; } catch (reason) { finish(); throw reason; } } function pinWorkingTab(path: string) { @@ -1127,12 +1139,14 @@ } function updateSettings(next: AppSettings) { - saveSettings(localStorage, next); + const saved = saveSettings(next); settings = { ...next }; + return saved; } onMount(() => { try { + // The layout stays in localStorage on purpose: per-machine view state that is harmless to lose. const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY)); ({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout); if (transferredWindow) { leftOpen = false; rightOpen = false; } @@ -1147,16 +1161,14 @@ }); onMount(() => { - try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); } + try { settings = readSettings(); } catch { error = "Could not read your settings. Default settings apply until you save new settings."; } + error = takeSettingsNotice() ?? error; settingsReady = true; - const syncSettings = (event: StorageEvent) => { - if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) settings = parseSettings(event.newValue); - }; - window.addEventListener("storage", syncSettings); + const stopSettings = onSettingsChange("general", () => { settings = readSettings(); }); window.addEventListener("keydown", onPreferencesKeydown, true); return () => { - window.removeEventListener("storage", syncSettings); + stopSettings(); window.removeEventListener("keydown", onPreferencesKeydown, true); }; }); diff --git a/src/lib/settings/migration.ts b/src/lib/settings/migration.ts new file mode 100644 index 0000000..46f2995 --- /dev/null +++ b/src/lib/settings/migration.ts @@ -0,0 +1,47 @@ +// The first desktop settings file comes from the old localStorage values. +// RuneStone leaves the old values in localStorage for one release, without further use. +import { LEGACY_KEYS, type SettingsSection, type SettingsSections } from './store.ts'; +import { parseSettings } from '../workspace/settings.ts'; +import { normalizeLocale } from '../i18n/index.ts'; +import { parseCustomTheme, type CustomTheme } from '../theme/customThemes.ts'; +import { normalizeAppearance } from '../theme/appearance.ts'; + +function parse(raw: string | null): unknown { + if (raw === null) return undefined; + try { return JSON.parse(raw); } catch { return undefined; } +} + +/** + * Read and normalize the old values. A missing key gives no section, so its defaults apply. + * Version 1 custom themes become version 2 themes with the palette of the saved appearance mode. + * Their original versions go to `customThemesLegacy`, together with an existing backup. + */ +export function migrateLegacyPreferences(read: (key: string) => string | null): SettingsSections { + const raw = (section: SettingsSection) => { try { return read(LEGACY_KEYS[section]); } catch { return null; } }; + const result: SettingsSections = {}; + const general = raw('general'); + if (general !== null) result.general = parseSettings(general); + const language = raw('language'); + if (language !== null) result.language = normalizeLocale(language); + + const appearanceRaw = raw('appearance'); + const appearance = parse(appearanceRaw) as { mode?: unknown } | null | undefined; + const legacyMode = appearance?.mode === 'light' ? 'light' : 'dark'; + const stored = parse(raw('customThemes')); + const backup = parse(raw('customThemesLegacy')); + const originals: unknown[] = Array.isArray(backup) ? [...backup] : []; + let themes: CustomTheme[] = []; + if (Array.isArray(stored)) { + themes = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } }); + for (const value of stored.filter(value => value?.schema === 1)) { + if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value); + } + result.customThemes = themes; + } + if (originals.length) result.customThemesLegacy = originals; + if (appearanceRaw !== null) { + const value = appearance && typeof appearance === 'object' && !Array.isArray(appearance) ? appearance : null; + result.appearance = normalizeAppearance(value, themes); + } + return result; +} diff --git a/src/lib/settings/store.ts b/src/lib/settings/store.ts new file mode 100644 index 0000000..f1bc205 --- /dev/null +++ b/src/lib/settings/store.ts @@ -0,0 +1,182 @@ +// User preferences. The desktop host keeps them in `/settings.json` (src-tauri/src/preferences.rs). +// Each window loads all sections once at startup, then reads them from memory. +// A write goes to the host, and the host sends `settings-changed` to all windows. +// +// Without the desktop host (`pnpm dev` in a browser), the sections stay in localStorage under their old keys. +// +// These values stay in localStorage on purpose, because they are per-machine view state that is harmless to lose: +// `runestone.workbenchLayout` (src/lib/workspace/workbenchLayout.ts) and the open tabs of each workspace +// (`documentSessionKey` in src/lib/workspace/documentSession.ts). +import { invoke, isTauri } from '@tauri-apps/api/core'; +import { listen } from '@tauri-apps/api/event'; + +export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language'] as const; +export type SettingsSection = typeof SETTINGS_SECTIONS[number]; +export type SettingsSections = Partial>; + +/** The old localStorage key of each section: the browser preview storage, and the source of the first desktop file. */ +export const LEGACY_KEYS: Readonly> = { + general: 'runestone.settings', + appearance: 'runestone.appearance', + customThemes: 'runestone.custom-themes', + customThemesLegacy: 'runestone.custom-themes.legacy', + language: 'runestone.language', +}; + +/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */ +export type Migration = (read: (key: string) => string | null) => SettingsSections; + +type Snapshot = { exists: boolean; revision: number; sections: SettingsSections; notice?: string }; +type Change = { section: SettingsSection; revision: number; value: unknown }; +type Waiter = { resolve: () => void; reject: (reason: unknown) => void }; + +const cache: SettingsSections = {}; +const revisions = new Map(); +const subscribers = new Map void>>(); +const queued = new Map(); +const writing = new Set(); +// The newest change from another window that arrived during a local write of the same section. +const deferred = new Map(); +let started: Promise | undefined; +let notice: string | null = null; + +function desktop() { return isTauri(); } + +// The language section was a plain string in localStorage. The other sections were JSON. +function decode(section: SettingsSection, raw: string | null): unknown { + if (raw === null) return undefined; + if (section === 'language') return raw; + try { return JSON.parse(raw); } catch { return undefined; } +} +function encode(section: SettingsSection, value: unknown): string { + return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value); +} + +function notify(section: SettingsSection) { + for (const callback of [...subscribers.get(section) ?? []]) { + try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); } + } +} + +function receive(change: Change) { + if (!(SETTINGS_SECTIONS as readonly string[]).includes(change.section)) return; + // During a local write of this section, apply the newest change only after the write ends. + // Otherwise an older event can show an old value for a moment. + if (writing.has(change.section) || queued.has(change.section)) { + if ((deferred.get(change.section)?.revision ?? -1) < change.revision) deferred.set(change.section, change); + return; + } + if ((revisions.get(change.section) ?? -1) >= change.revision) return; + revisions.set(change.section, change.revision); + cache[change.section] = change.value ?? undefined; + notify(change.section); +} + +function applySnapshot(snapshot: Snapshot) { + for (const section of SETTINGS_SECTIONS) { + if ((revisions.get(section) ?? -1) >= snapshot.revision) continue; + revisions.set(section, snapshot.revision); + cache[section] = snapshot.sections[section]; + } +} + +async function start(migrate: Migration) { + if (!desktop()) { + // The browser preview: other tabs report their changes through storage events. + window.addEventListener('storage', event => { + if (event.key === null) { SETTINGS_SECTIONS.forEach(notify); return; } + const section = SETTINGS_SECTIONS.find(item => LEGACY_KEYS[item] === event.key); + if (section) notify(section); + }); + return; + } + // Listen before the read, so that no change between the read and the listener goes missing. + await listen('settings-changed', event => receive(event.payload)); + let snapshot: Snapshot; + try { snapshot = await invoke('settings_read'); } + catch (reason) { + notice = `RuneStone could not read your settings, so the default settings apply: ${String(reason)}`; + return; + } + if (!snapshot.exists) { + const sections = migrate(key => { try { return localStorage.getItem(key); } catch { return null; } }); + try { snapshot = await invoke('settings_migrate', { sections }); } + catch (reason) { + // Use the old values in this window, and keep them in localStorage for the next start. + snapshot = { exists: false, revision: 0, sections }; + notice = `RuneStone could not save your settings file: ${String(reason)}`; + } + } + applySnapshot(snapshot); + notice ??= snapshot.notice ?? null; +} + +/** Load all sections once. Later calls return the same promise. */ +export function initSettings(migrate: Migration): Promise { + return started ??= start(migrate); +} + +/** A message for the user about the settings file, at most once for each window. */ +export function takeSettingsNotice(): string | null { + const value = notice; + notice = null; + return value; +} + +/** The stored value of a section, or undefined. Normalize it before use. */ +export function readSection(section: SettingsSection): unknown { + if (desktop()) return cache[section]; + try { return decode(section, localStorage.getItem(LEGACY_KEYS[section])); } + catch { return undefined; } +} + +async function flush(section: SettingsSection) { + writing.add(section); + try { + for (let entry = queued.get(section); entry; entry = queued.get(section)) { + queued.delete(section); + try { + const change = await invoke('settings_write', { section, value: entry.value ?? null }); + revisions.set(section, Math.max(revisions.get(section) ?? -1, change.revision)); + entry.waiters.forEach(waiter => waiter.resolve()); + } catch (reason) { entry.waiters.forEach(waiter => waiter.reject(reason)); } + } + } finally { + writing.delete(section); + const late = deferred.get(section); + deferred.delete(section); + // A write of another window that the host saved after this window's last write wins. + if (late) receive(late); + } +} + +/** + * Replace a section. This window reads the new value at once, and its subscribers run at once. + * Without the desktop host, a refused browser storage write throws before anything changes. + * On the desktop, the promise rejects when the host cannot save the file. Quick writes of one section + * merge, so the host saves only the last value. + */ +export function writeSection(section: SettingsSection, value: unknown): Promise { + if (!desktop()) { + localStorage.setItem(LEGACY_KEYS[section], encode(section, value)); + notify(section); + return Promise.resolve(); + } + cache[section] = value; + notify(section); + return new Promise((resolve, reject) => { + const entry = queued.get(section) ?? { value, waiters: [] }; + entry.value = value; + entry.waiters.push({ resolve, reject }); + queued.set(section, entry); + if (!writing.has(section)) void flush(section); + }); +} + +/** Run `callback` after each change of `section` in this window or another window. Returns a function that stops it. */ +export function onSettingsChange(section: SettingsSection, callback: () => void): () => void { + const list = subscribers.get(section) ?? new Set(); + list.add(callback); + subscribers.set(section, list); + return () => { list.delete(callback); }; +} diff --git a/src/lib/theme/AppearanceSettings.svelte b/src/lib/theme/AppearanceSettings.svelte index de7cf59..72242c1 100644 --- a/src/lib/theme/AppearanceSettings.svelte +++ b/src/lib/theme/AppearanceSettings.svelte @@ -7,7 +7,8 @@ import Icon from '$lib/ui/Icon.svelte'; import { showActionMenu } from '$lib/ui/managedActionMenu'; import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages'; - import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance'; + import { onSettingsChange } from '$lib/settings/store'; + import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance'; let appearance = $state({ ...DEFAULT_APPEARANCE }); let error = $state(''); let status = $state(''); @@ -43,12 +44,16 @@ run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close; } onMount(() => { - const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = $t('Could not read appearance settings.'); } }; - read(); window.addEventListener('storage', read); window.addEventListener('focus', read); - return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); }; + const read = () => { try { installed = customThemes(); appearance = readAppearance(); } catch { error = $t('Could not read appearance settings.'); } }; + read(); + const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)]; + return () => stops.forEach(stop => stop()); }); function change(next: Appearance) { - try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; } + try { + saveAppearance(next).catch(() => { error = $t('Could not save appearance settings.'); }); + appearance = normalizeAppearance(next); error = ''; return true; + } catch { error = $t('Could not save appearance settings.'); return false; } } function changeOverlay(input: HTMLInputElement) { @@ -68,7 +73,7 @@ try { if (file.size > 65536) throw new Error($t('Choose a theme smaller than 64 KiB.')); const theme = parseCustomTheme(JSON.parse(await file.text()), appearance.mode); - installTheme(theme); installed = customThemes(); + installTheme(theme).catch(reason => { error = String(reason); }); installed = customThemes(); change({ ...appearance, theme: `custom:${theme.id}` }); } catch (reason) { error = String(reason); } finally { themeInput.value = ''; } @@ -121,7 +126,7 @@ {#if appearance.theme.startsWith('custom:')} { - try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); } + try { removeTheme(appearance.theme.slice(7)).catch(() => { error = 'Could not remove this theme.'; }); installed = customThemes(); change({ ...appearance, theme: 'default' }); } catch { error = 'Could not remove this theme.'; } }} />{/if} diff --git a/src/lib/theme/ThemeSync.svelte b/src/lib/theme/ThemeSync.svelte index 2ae5ee0..f451903 100644 --- a/src/lib/theme/ThemeSync.svelte +++ b/src/lib/theme/ThemeSync.svelte @@ -1,27 +1,24 @@ - - - diff --git a/src/lib/theme/appearance.ts b/src/lib/theme/appearance.ts index 6c62ff6..a3cebcd 100644 --- a/src/lib/theme/appearance.ts +++ b/src/lib/theme/appearance.ts @@ -1,6 +1,8 @@ import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts'; import { readBackgroundImage } from './backgroundImages.ts'; import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts'; +import { readSection, writeSection } from '../settings/store.ts'; +/** The old localStorage key. The appearance section of the settings file replaces it. */ export const APPEARANCE_KEY = 'runestone.appearance'; export const THEMES = ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent'] as const; export const BUILTIN_THEMES = [ @@ -18,10 +20,11 @@ export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', ' export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const; export type Appearance = { transparency?: { enabled: boolean; amount: number }; theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } }; export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' }; -export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance { +/** `themes` is the list of custom themes. By default, it is the saved list. */ +export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null, themes?: CustomTheme[]): Appearance { const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme; const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default'; - const selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined; + const selectedCustom = theme.startsWith('custom:') ? (themes ?? customThemes(value?.mode === 'light' ? 'light' : 'dark')).find(item => `custom:${item.id}` === theme) : undefined; const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') }; if (value?.transparency && typeof value.transparency === 'object') { const source = value.transparency as { enabled?: unknown; amount?: unknown }; @@ -43,6 +46,11 @@ export function parseAppearance(raw: string | null): Appearance { try { return normalizeAppearance(JSON.parse(raw || 'null')); } catch { return { ...DEFAULT_APPEARANCE }; } } +/** The saved appearance, normalized. */ +export function readAppearance(): Appearance { + const value = readSection('appearance'); + return normalizeAppearance(value && typeof value === 'object' && !Array.isArray(value) ? value : null); +} const keys = ['bg', 'bg-elevated', 'bg-active', 'border', 'text-dim', 'text', 'text-strong', 'accent', 'selection'] as const; const palettes = { default: { @@ -203,9 +211,11 @@ export function applyAppearance(value: Appearance, root = document.documentEleme } window.dispatchEvent(new CustomEvent('runestone-theme-changed')); } -export function saveAppearance(value: Appearance) { +/** Save and apply an appearance. Throws at once if browser storage refuses it. The promise reports a failed save. */ +export function saveAppearance(value: Appearance): Promise { const appearance = normalizeAppearance(value); - localStorage.setItem(APPEARANCE_KEY, JSON.stringify(appearance)); + const saved = writeSection('appearance', appearance); applyAppearance(appearance); + return saved; } diff --git a/src/lib/theme/customThemes.ts b/src/lib/theme/customThemes.ts index 4342d49..1f0ab75 100644 --- a/src/lib/theme/customThemes.ts +++ b/src/lib/theme/customThemes.ts @@ -1,3 +1,6 @@ +import { readSection, writeSection } from '../settings/store.ts'; + +/** The old localStorage key. The customThemes section of the settings file replaces it. */ export const CUSTOM_THEMES_KEY = "runestone.custom-themes"; export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const; export type ThemeColors = Partial>; @@ -38,48 +41,24 @@ export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) }; } -const pendingLegacy = new Map(); - +/** The saved custom themes. Version 1 themes use the palette of `legacyMode`, by default the saved appearance mode. */ export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] { try { - const raw = localStorage.getItem(CUSTOM_THEMES_KEY) || "[]"; - const pending = pendingLegacy.get(raw); - if (pending) return pending.map(theme => ({ ...theme, colors: { ...theme.colors } })); - const stored = JSON.parse(raw); + const stored = readSection('customThemes'); if (!Array.isArray(stored)) return []; - if (!legacyMode) { - try { legacyMode = JSON.parse(localStorage.getItem('runestone.appearance') || 'null')?.mode === 'light' ? 'light' : 'dark'; } - catch { legacyMode = 'dark'; } - } - const parsed = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } }); - if (stored.some(value => value?.schema === 1)) { - // Retain both original palettes before converting the saved selection to one palette. - try { - const backupKey = `${CUSTOM_THEMES_KEY}.legacy`; - const backup = JSON.parse(localStorage.getItem(backupKey) || '[]'); - if (!Array.isArray(backup)) throw new Error('Invalid legacy backup'); - const originals = backup; - for (const value of stored.filter(value => value?.schema === 1)) { - if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value); - } - localStorage.setItem(backupKey, JSON.stringify(originals)); - localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(stored.map(value => { - try { return parseCustomTheme(value, legacyMode); } catch { return value; } - }))); - } catch { - // Storage failures must not hide readable themes or change their chosen palette. - pendingLegacy.set(raw, parsed); - } - } - return parsed; + if (!legacyMode) legacyMode = (readSection('appearance') as { mode?: unknown } | undefined)?.mode === 'light' ? 'light' : 'dark'; + const mode = legacyMode; + return stored.flatMap(value => { try { return [parseCustomTheme(value, mode)]; } catch { return []; } }); } catch { return []; } } -export function installTheme(theme: CustomTheme): void { +/** Throws at once if browser storage refuses the change. The promise reports a failed save. */ +export function installTheme(theme: CustomTheme): Promise { const list = customThemes().filter(item => item.id !== theme.id); - localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify([...list, parseCustomTheme(theme)])); + return writeSection('customThemes', [...list, parseCustomTheme(theme)]); } -export function removeTheme(id: string): void { - localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(customThemes().filter(item => item.id !== id))); +/** Throws at once if browser storage refuses the change. The promise reports a failed save. */ +export function removeTheme(id: string): Promise { + return writeSection('customThemes', customThemes().filter(item => item.id !== id)); } diff --git a/src/lib/workspace/settings.ts b/src/lib/workspace/settings.ts index ba437f2..ab5c741 100644 --- a/src/lib/workspace/settings.ts +++ b/src/lib/workspace/settings.ts @@ -1,3 +1,6 @@ +import { readSection, writeSection } from "../settings/store.ts"; + +/** The old localStorage key. The general section of the settings file replaces it. */ export const SETTINGS_KEY = "runestone.settings"; export const MIN_AUTOSAVE_SECONDS = 1; export const MAX_AUTOSAVE_SECONDS = 300; @@ -19,20 +22,28 @@ export function validAutosaveSeconds(value: unknown): value is number { && value >= MIN_AUTOSAVE_SECONDS && value <= MAX_AUTOSAVE_SECONDS; } -export function parseSettings(raw: string | null): AppSettings { - try { - const value = JSON.parse(raw ?? "null"); - return { - autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled, - autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds, - showInternalFolder: value?.showInternalFolder === true, - }; - } catch { return { ...DEFAULT_SETTINGS }; } +export function normalizeSettings(input: unknown): AppSettings { + const value = input && typeof input === "object" ? input as Record : null; + return { + autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled, + autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds, + showInternalFolder: value?.showInternalFolder === true, + }; } -export function saveSettings(storage: Pick, settings: AppSettings): void { +export function parseSettings(raw: string | null): AppSettings { + try { return normalizeSettings(JSON.parse(raw ?? "null")); } + catch { return { ...DEFAULT_SETTINGS }; } +} + +export function readSettings(): AppSettings { + return normalizeSettings(readSection("general")); +} + +/** Check and save the settings. Throws at once for invalid values. The promise reports a failed save. */ +export function saveSettings(settings: AppSettings): Promise { if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") { throw new Error("Choose a whole number from 1 to 300 seconds."); } - storage.setItem(SETTINGS_KEY, JSON.stringify(settings)); + return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true }); } diff --git a/src/lib/workspace/tabTransfer.ts b/src/lib/workspace/tabTransfer.ts new file mode 100644 index 0000000..70aa937 --- /dev/null +++ b/src/lib/workspace/tabTransfer.ts @@ -0,0 +1,55 @@ +// Tab transfer between windows of one workspace. The host keeps each offer in memory (src-tauri/src/tab_transfer.rs). +// The source window offers a tab and closes it only after `tab-transfer-accepted`. +// The receiving window takes the offer, opens the tab, and then finishes the offer. +import { invoke } from "@tauri-apps/api/core"; +import { listen, type UnlistenFn } from "@tauri-apps/api/event"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import type { OpenBuffer } from "./types"; + +export const TAB_TRANSFER_ID = /^[0-9a-f-]{36}$/i; + +export type TabTransfer = { reading: boolean } & ({ buffer: OpenBuffer } | { plugin: unknown }); + +/** The state that the source window sends. */ +export type TabTransferOffer = { reading: boolean } & ({ buffer: OpenBuffer } | { plugin: unknown }); + +/** Check the state of a taken offer. The new window and the tab ribbon use this one check. */ +export function parseTabTransfer(payload: string): TabTransfer { + let value: unknown; + try { value = JSON.parse(payload); } catch { throw new Error("Invalid tab transfer."); } + const transfer = value && typeof value === "object" ? value as Record : {}; + const reading = transfer.reading === true; + const buffer = transfer.buffer as Record | undefined; + if (buffer && typeof buffer === "object" && typeof buffer.relPath === "string" + && typeof buffer.contents === "string" && typeof buffer.saved === "string") { + return { buffer: buffer as unknown as OpenBuffer, reading }; + } + if (transfer.plugin && typeof transfer.plugin === "object") return { plugin: transfer.plugin, reading }; + throw new Error("Invalid tab transfer."); +} + +/** Offer a tab with the ID `id`. The window creates the ID, because a drag needs it at once. */ +export function offerTabTransfer(id: string, root: string, offer: TabTransferOffer): Promise { + return invoke("tab_transfer_offer", { id, root, payload: JSON.stringify(offer) }); +} + +/** Take an offer once. Fails when the offer expired or belongs to another workspace. */ +export async function takeTabTransfer(id: string, root: string): Promise { + if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer."); + return invoke("tab_transfer_take", { id, root }); +} + +/** End a take. `accepted` tells the source window to close its tab. A refused offer stays open for another window. */ +export function finishTabTransfer(id: string, accepted: boolean): Promise { + return invoke("tab_transfer_finish", { id, accepted }); +} + +/** Withdraw an offer that no window took. */ +export function cancelTabTransfer(id: string): Promise { + return invoke("tab_transfer_cancel", { id }); +} + +/** Run `handler` when another window accepts a tab of this window. */ +export function onTabTransferAccepted(handler: (id: string) => void): Promise { + return listen<{ id: string }>("tab-transfer-accepted", event => handler(event.payload.id), { target: getCurrentWindow().label }); +} diff --git a/src/routes/+layout.ts b/src/routes/+layout.ts index 9d24899..8421129 100644 --- a/src/routes/+layout.ts +++ b/src/routes/+layout.ts @@ -2,4 +2,13 @@ // so we use adapter-static with a fallback to index.html to put the site in SPA mode // See: https://svelte.dev/docs/kit/single-page-apps // See: https://v2.tauri.app/start/frontend/sveltekit/ for more info +import { initSettings } from "$lib/settings/store"; +import { migrateLegacyPreferences } from "$lib/settings/migration"; + export const ssr = false; + +// Each window loads the user preferences before its first render, so later reads need no wait. +export async function load() { + await initSettings(migrateLegacyPreferences); + return {}; +} diff --git a/tests/native/tabTransferAndThemeExport.native.mjs b/tests/native/tabTransferAndThemeExport.native.mjs index 0b30068..4b7183c 100644 --- a/tests/native/tabTransferAndThemeExport.native.mjs +++ b/tests/native/tabTransferAndThemeExport.native.mjs @@ -15,11 +15,17 @@ try { const identity=await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir()); assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/); const pending=context.waitForEvent('page'); + // The source window offers the tab through the host and waits for the acknowledgement that the host sends to it alone. const token=await page.evaluate(async()=>{ const {invoke}=await import('/node_modules/@tauri-apps/api/core.js'); + const {listen}=await import('/node_modules/@tauri-apps/api/event.js'); + const {getCurrentWindow}=await import('/node_modules/@tauri-apps/api/window.js'); const root=await invoke('workspace_last_path'); const token=crypto.randomUUID(), id=crypto.randomUUID(); - localStorage.setItem('runestone.tab-transfer.'+token,JSON.stringify({root,created:Date.now(),reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}})); + window.__nativeTransferAccepted=false; + await listen('tab-transfer-accepted',event=>{ if(event.payload.id===token) window.__nativeTransferAccepted=true; },{target:getCurrentWindow().label}); + const payload=JSON.stringify({reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}}); + await invoke('tab_transfer_offer',{id:token,root,payload}); await invoke('workspace_open_window',{path:root,transfer:token}); return token; }); @@ -28,7 +34,7 @@ try { assert.ok(transferred.url().includes('?tabTransfer='+token)); assert.ok(!transferred.url().includes('index.html')); assert.equal(await transferred.getByText('404',{exact:true}).count(),0); - await page.waitForFunction(token=>localStorage.getItem('runestone.tab-transfer.'+token+'.accepted') === 'true',token); + await page.waitForFunction(()=>window.__nativeTransferAccepted===true); console.log('PASS: native empty-tab transfer loads the splash screen and acknowledges its saved tab state.'); await transferred.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()); transferred=undefined; settings=context.pages().find(page => page.url().includes('settingsWindow=true')); diff --git a/tests/native/treeRename.native.mjs b/tests/native/treeRename.native.mjs index 58a573b..825bf61 100644 --- a/tests/native/treeRename.native.mjs +++ b/tests/native/treeRename.native.mjs @@ -88,7 +88,8 @@ try { const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'); const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]); await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage }); - await page.waitForFunction(() => !!JSON.parse(localStorage.getItem('runestone.appearance'))?.newTabBackground?.imageId); + // The appearance is in the settings file of the host. + await page.waitForFunction(() => window.__TAURI_INTERNALS__.invoke('settings_read').then(file => !!file.sections.appearance?.newTabBackground?.imageId)); await page.goto(`${origin}/`); // The image is on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549). await page.locator('.empty').waitFor(); diff --git a/tests/smoke/_harness/index.mjs b/tests/smoke/_harness/index.mjs index d79de53..35c16dc 100644 --- a/tests/smoke/_harness/index.mjs +++ b/tests/smoke/_harness/index.mjs @@ -59,8 +59,14 @@ export function settle(page) { * * `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`. * It cannot use variables from the test file. Pass data through `state`, which must be JSON. - * `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options) }`. + * `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`. * A command without a handler throws "Unhandled IPC", or returns null when `strict` is false. + * + * Default handlers serve the settings file (`settings_*`) and tab transfers (`tab_transfer_*`). `commands` can replace them. + * All pages of one browser context share their state: the settings file and the offers are in localStorage under + * test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page. + * Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load. + * `test.settings(section)` reads a section of the file. `test.writeSettings(section, value)` acts as a write from another window. */ export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) { const options = JSON.stringify({ label, state, strict }); @@ -142,7 +148,80 @@ function installMock(options, commands) { return Object.assign(handlers, { files: store, folders: dirs, root, name }); }; - const test = { state: options.state, calls: [], emit, label: options.label, workspace }; + // The settings file and the tab transfer offers of the desktop host (src-tauri/src/preferences.rs, tab_transfer.rs). + // `crypto.randomUUID` needs a secure context, which `about:blank` is not. + const pageId = `${Date.now()}-${Math.random().toString(16).slice(2)}`; + const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("runestone-smoke-host") : { postMessage() {} }; + channel.addEventListener?.("message", ({ data }) => { if (!data.target || data.target === pageId) emit(data.event, data.payload); }); + // `target` is a page ID. Without it, every page of the context receives the event, this page too. + const broadcast = (event, payload, target) => { + if (!target || target === pageId) emit(event, payload); + if (target !== pageId) channel.postMessage({ event, payload, target }); + }; + const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers"; + const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language"]; + const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } }; + const settingsFile = () => readJson(SETTINGS_FILE, null); + const snapshot = () => { + const file = settingsFile(); + return { exists: !!file, revision: file?.revision ?? 0, sections: Object.fromEntries(SECTIONS.filter(name => file && name in file).map(name => [name, file[name]])) }; + }; + const writeSettings = (section, value) => { + if (!SECTIONS.includes(section)) throw `Unknown settings section: ${section}`; + const file = settingsFile() ?? { schema: 1, revision: 0 }; + file.revision += 1; + if (value === null || value === undefined) delete file[section]; else file[section] = value; + localStorage.setItem(SETTINGS_FILE, JSON.stringify(file)); + const change = { section, revision: file.revision, value: value ?? null }; + broadcast("settings-changed", change); + return change; + }; + const offers = () => { + const list = readJson(TRANSFERS, {}); + for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id]; + return list; + }; + const saveOffers = list => localStorage.setItem(TRANSFERS, JSON.stringify(list)); + const expired = "This tab transfer expired. Drag the tab again."; + const defaults = { + settings_read: () => snapshot(), + settings_migrate: ({ sections }) => { + if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections })); + return snapshot(); + }, + settings_write: ({ section, value }) => writeSettings(section, value), + tab_transfer_offer: ({ id, root, payload }) => { + const list = offers(); + if (list[id]) throw "Invalid tab transfer."; + list[id] = { source: pageId, root, payload, created: Date.now(), taker: null }; + saveOffers(list); + return id; + }, + tab_transfer_take: ({ id, root }) => { + const list = offers(), offer = list[id]; + if (!offer || offer.taker) throw expired; + if (offer.root !== root) throw "Move tabs only between windows of the same workspace."; + offer.taker = pageId; + saveOffers(list); + return offer.payload; + }, + tab_transfer_finish: ({ id, accepted }) => { + const list = offers(), offer = list[id]; + if (!offer || offer.taker !== pageId) throw expired; + if (accepted) delete list[id]; else offer.taker = null; + saveOffers(list); + if (accepted) broadcast("tab-transfer-accepted", { id }, offer.source); + return null; + }, + tab_transfer_cancel: ({ id }) => { + const list = offers(); + if (list[id]?.source === pageId && !list[id].taker) { delete list[id]; saveOffers(list); } + return null; + }, + }; + + const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings }; + // Look up the test's handlers first. A test can return a Proxy, so do not copy its keys. const table = commands ? commands(test) || {} : {}; window.isTauri = true; window.__TEST__ = test; @@ -164,7 +243,7 @@ function installMock(options, commands) { } if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return null; } if (command === "plugin:event|emit" || command === "plugin:event|emit_to") { emit(args.event, args.payload); return null; } - const handler = table[command]; + const handler = typeof table[command] === "function" ? table[command] : defaults[command]; if (typeof handler === "function") { const result = await handler(args, test); return result === undefined ? null : result; diff --git a/tests/smoke/appearance/backgroundImages.smoke.mjs b/tests/smoke/appearance/backgroundImages.smoke.mjs index 3a8ceb5..5831a04 100644 --- a/tests/smoke/appearance/backgroundImages.smoke.mjs +++ b/tests/smoke/appearance/backgroundImages.smoke.mjs @@ -31,7 +31,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => { const imageInput = () => settings.getByLabel('Background image file', { exact: true }); const background = () => main.locator('.workarea-background').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); const decoded = (page, url) => page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url); - const savedImageId = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId); + const savedImageId = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.imageId); const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })); await main.goto(smokeUrl); await main.locator('.empty').waitFor(); @@ -59,7 +59,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => { await imageInput().setInputFiles(largeFile); await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url); url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes'); - assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage'); + assert.ok(await settings.evaluate(() => JSON.stringify(window.__TEST__.settings('appearance')).length < 500), 'Image bytes stay outside the settings file'); await main.reload(); await main.locator('.empty').waitFor(); await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:')); url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload'); diff --git a/tests/smoke/appearance/backgroundLayout.smoke.mjs b/tests/smoke/appearance/backgroundLayout.smoke.mjs index 123d032..21d305a 100644 --- a/tests/smoke/appearance/backgroundLayout.smoke.mjs +++ b/tests/smoke/appearance/backgroundLayout.smoke.mjs @@ -52,7 +52,7 @@ await runSmoke('appearance/backgroundLayout', async ({ browser }) => { for (const mode of ['light', 'dark']) { await settings.evaluate(async mode => { const appearance = await import('/src/lib/theme/appearance.ts'); - appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode }); + appearance.saveAppearance({ ...appearance.readAppearance(), mode }); window.dispatchEvent(new Event('focus')); }, mode); await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode); diff --git a/tests/smoke/appearance/backgroundOverlay.smoke.mjs b/tests/smoke/appearance/backgroundOverlay.smoke.mjs index df2e348..6bbcd91 100644 --- a/tests/smoke/appearance/backgroundOverlay.smoke.mjs +++ b/tests/smoke/appearance/backgroundOverlay.smoke.mjs @@ -21,7 +21,7 @@ await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => { }); const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' }); const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true }); - const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay); + const saved = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.overlay); await input.fill('-37'); assert.equal(await slider.inputValue(), '-37'); assert.equal(await saved(), -0.37); @@ -42,7 +42,7 @@ await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => { for (const mode of ['light', 'dark']) { await settings.evaluate(async mode => { const appearance = await import('/src/lib/theme/appearance.ts'); - appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode }); + appearance.saveAppearance({ ...appearance.readAppearance(), mode }); window.dispatchEvent(new Event('focus')); }, mode); for (const width of [1100, 360]) { diff --git a/tests/smoke/appearance/characterThemes.smoke.mjs b/tests/smoke/appearance/characterThemes.smoke.mjs index 9ccde46..bfe40ee 100644 --- a/tests/smoke/appearance/characterThemes.smoke.mjs +++ b/tests/smoke/appearance/characterThemes.smoke.mjs @@ -196,15 +196,15 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => { console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`); } for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) { - await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous); + await settings.evaluate(theme => window.__TEST__.writeSettings('appearance', { theme, mode: 'dark' }), previous); await openSettings(); assert.equal((await picker('Color theme').textContent()).trim(), label); assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme); await choose('Color theme', label); - assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme); + assert.equal(await settings.evaluate(() => window.__TEST__.settings('appearance').theme), theme); } for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) { - await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode }); + await settings.evaluate(({ theme, mode }) => window.__TEST__.writeSettings('appearance', { theme, mode }), { theme: removed, mode }); await settings.setViewportSize({ width: 1100, height: 780 }); await openSettings(); await waitForAppearance('default', mode); diff --git a/tests/smoke/appearance/colorThemeMenu.smoke.mjs b/tests/smoke/appearance/colorThemeMenu.smoke.mjs index 2250efe..c219778 100644 --- a/tests/smoke/appearance/colorThemeMenu.smoke.mjs +++ b/tests/smoke/appearance/colorThemeMenu.smoke.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs"; await runSmoke("appearance/colorThemeMenu", async ({ browser }) => { - // The settings window changes the main window through shared localStorage, so both pages need one context. + // The settings window changes the main window through the mock settings file, so both pages need one context. const context = await browser.newContext({ viewport: { width: 1200, height: 850 } }); await mockTauri(context, { commands: test => ({ diff --git a/tests/smoke/appearance/newTabBackground.smoke.mjs b/tests/smoke/appearance/newTabBackground.smoke.mjs index 892e63a..952012d 100644 --- a/tests/smoke/appearance/newTabBackground.smoke.mjs +++ b/tests/smoke/appearance/newTabBackground.smoke.mjs @@ -6,7 +6,7 @@ import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/ const name = "appearance/newTabBackground"; await runSmoke(name, async ({ browser }) => { const output = await outputDir(name); - // The settings window changes the main window through shared localStorage and IndexedDB, so both pages need one context. + // The settings window changes the main window through the mock settings file and shared IndexedDB, so both pages need one context. const context = await browser.newContext({ viewport: { width: 1200, height: 850 } }); await mockTauri(context, { commands: test => ({ @@ -35,15 +35,15 @@ await runSmoke(name, async ({ browser }) => { await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer); for (const mode of ["light", "dark"]) { await settings.evaluate(async mode => { - const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import("/src/lib/theme/appearance.ts"); - saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: "default", mode }); + const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts"); + saveAppearance({ ...readAppearance(), theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, mode); await settings.setViewportSize({ width: 650, height: 760 }); await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) }); } assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).isDisabled(), true); - await page.waitForFunction(() => !JSON.parse(localStorage.getItem("runestone.appearance")).newTabBackground); + await page.waitForFunction(() => !window.__TEST__.settings("appearance").newTabBackground); assert.deepEqual([...page.errors, ...settings.errors], []); console.log("PASS: background image applies, survives a reload, and is removed; Reset background is disabled"); }); diff --git a/tests/smoke/appearance/palettes.smoke.mjs b/tests/smoke/appearance/palettes.smoke.mjs index a2b1eb8..3f39bee 100644 --- a/tests/smoke/appearance/palettes.smoke.mjs +++ b/tests/smoke/appearance/palettes.smoke.mjs @@ -99,7 +99,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => { assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor"); await expectAppearance(theme, mode); await waitForSyntax(); - assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode }); + assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme, mode }); await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}.png`) }); await main.screenshot({ path: path.join(output, `appearance-editor-${theme}-${mode}.png`) }); if (theme === "sakura") { @@ -140,11 +140,11 @@ await runSmoke("appearance/palettes", async ({ browser }) => { ["terminal", "dark", "default", "dark"], ["sakura", "dark", "sakura", "light"], ]) { - await settings.evaluate(value => localStorage.setItem("runestone.appearance", JSON.stringify(value)), { theme, mode: savedMode }); + await settings.evaluate(value => window.__TEST__.writeSettings("appearance", value), { theme, mode: savedMode }); await settings.reload(); await settings.getByRole("button", { name: "Appearance", exact: true }).click(); await expectAppearance(expectedTheme, mode); - assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme: expectedTheme, mode }); + assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme: expectedTheme, mode }); console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`); } for (const [theme, mode] of [["default", "dark"], ["claude", "light"], ["claude", "dark"], ["sakura", "light"]]) { diff --git a/tests/smoke/appearance/themeVariants.smoke.mjs b/tests/smoke/appearance/themeVariants.smoke.mjs index 61b9d53..41416b9 100644 --- a/tests/smoke/appearance/themeVariants.smoke.mjs +++ b/tests/smoke/appearance/themeVariants.smoke.mjs @@ -27,7 +27,7 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => { }, { theme, mode }); const slider = page.locator('#surface-transparency'); await slider.fill('100'); - assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount), 100); + assert.equal(await page.evaluate(() => window.__TEST__.settings('appearance').transparency.amount), 100); await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(), '0'); await page.keyboard.press('End'); assert.equal(await slider.inputValue(), '100'); await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-focus.png`) }); diff --git a/tests/smoke/links/linkMenus.smoke.mjs b/tests/smoke/links/linkMenus.smoke.mjs index 001c830..af95da8 100644 --- a/tests/smoke/links/linkMenus.smoke.mjs +++ b/tests/smoke/links/linkMenus.smoke.mjs @@ -160,7 +160,7 @@ await runSmoke("links/linkMenus", async ({ page }) => { } await writerMenu('Workspace note'); await item('Open in new window').click(); await page.waitForFunction(() => window.__TEST__.windows.length === 1); - await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); }); + await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; window.__TEST__.emit('tab-transfer-accepted',{id:transfer}); }); assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab'); await page.locator('[data-tree-rel="a.md"]').click(); await writerMenu('Workspace note'); await item('Bookmark').click(); diff --git a/tests/smoke/settings/displayLanguage.smoke.mjs b/tests/smoke/settings/displayLanguage.smoke.mjs index 3b9c52a..63a86aa 100644 --- a/tests/smoke/settings/displayLanguage.smoke.mjs +++ b/tests/smoke/settings/displayLanguage.smoke.mjs @@ -35,7 +35,7 @@ await runSmoke('settings/displayLanguage', async ({ browser }) => { await main.getByRole('button', { name: files, exact: true }).waitFor(); assert.equal(await settings.locator('html').getAttribute('lang'), language); assert.equal(await main.locator('html').getAttribute('lang'), language); - assert.equal(await settings.evaluate(() => localStorage.getItem('runestone.language')), language); + assert.equal(await settings.evaluate(() => window.__TEST__.settings('language')), language); await settings.reload(); await settings.getByRole('heading', { name: heading, exact: true }).waitFor(); // Arrow keys and Escape retain shared menu focus behavior. diff --git a/tests/smoke/settings/general.smoke.mjs b/tests/smoke/settings/general.smoke.mjs index 0c795cf..aaa8d17 100644 --- a/tests/smoke/settings/general.smoke.mjs +++ b/tests/smoke/settings/general.smoke.mjs @@ -63,7 +63,7 @@ await runSmoke("settings/general", async ({ browser }) => { assert.equal(await interval.inputValue(), "2", "Interval survives reload"); await changeSeconds(0); await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor(); - assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2); + assert.equal(await page.evaluate(() => window.__TEST__.settings("general").autosaveSeconds), 2); await changeSeconds(2); await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins"); await settings.getByText("No plugins installed.", { exact: true }).waitFor(); @@ -113,7 +113,7 @@ await runSmoke("settings/general", async ({ browser }) => { assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3"); assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false); await other.getByRole("button", { name: "Restore defaults" }).click(); - await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled); + await page.waitForFunction(() => window.__TEST__.settings("general").autosaveEnabled); await showSettings(); await enabled.waitFor(); assert(await enabled.isChecked(), "Other windows receive changes"); diff --git a/tests/smoke/tabs/windowTransfer.smoke.mjs b/tests/smoke/tabs/windowTransfer.smoke.mjs index 41d9b96..0fc6300 100644 --- a/tests/smoke/tabs/windowTransfer.smoke.mjs +++ b/tests/smoke/tabs/windowTransfer.smoke.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs"; await runSmoke("tabs/windowTransfer", async ({ browser }) => { - // The transfer passes through localStorage, so the source and target windows need one context. + // The mock host shares its transfer offers in one context, so the source and target windows need one context. const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); await mockTauri(context, { commands: test => ({ diff --git a/tests/smoke/tree/folderActions.smoke.mjs b/tests/smoke/tree/folderActions.smoke.mjs index 0361093..0be4dbe 100644 --- a/tests/smoke/tree/folderActions.smoke.mjs +++ b/tests/smoke/tree/folderActions.smoke.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs"; await runSmoke("tree/folderActions", async ({ browser }) => { - // The settings window shares localStorage with the main window, so both pages need one context. + // The settings window shares the mock settings file with the main window, so both pages need one context. const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); await mockTauri(context, { commands: test => { diff --git a/tests/smoke/tree/renameUndo.smoke.mjs b/tests/smoke/tree/renameUndo.smoke.mjs index 9bdaa29..e90c205 100644 --- a/tests/smoke/tree/renameUndo.smoke.mjs +++ b/tests/smoke/tree/renameUndo.smoke.mjs @@ -148,7 +148,7 @@ await runSmoke('tree/renameUndo', async ({ browser }) => { const saved = await page.evaluate(token => { const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' }); localStorage.setItem('runestone.workbenchLayout', layout); - localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } })); + void window.__TAURI_INTERNALS__.invoke('tab_transfer_offer', { id: token, root: 'C:\\host-todo-test', payload: JSON.stringify({ buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }) }); return layout; }, token); const detached = await openPage(context, { timeout: 30000 }); diff --git a/tests/unit/i18n.spec.ts b/tests/unit/i18n.spec.ts index 5253be6..1feb21a 100644 --- a/tests/unit/i18n.spec.ts +++ b/tests/unit/i18n.spec.ts @@ -3,6 +3,7 @@ import { test } from 'node:test'; import { catalogs, messageRows } from '../../src/lib/i18n/messages.ts'; import { get } from 'svelte/store'; import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../../src/lib/i18n/index.ts'; +import { initSettings } from '../../src/lib/settings/store.ts'; test('Every catalog entry has all translations and preserves its placeholders', () => { const seen = new Set(); for (const [english, ...translations] of messageRows) { @@ -22,7 +23,7 @@ test('Locale parsing rejects unsupported values and interpolation preserves user assert.equal(translate('fr', 'Missing source text'), 'Missing source text'); assert.equal(translate('ja', 'Close {name}', { name: '' }), 'を閉じる'); }); -test('Language saves before reactive changes and syncs across windows', () => { +test('Language saves before reactive changes and syncs across windows', async () => { const stored = new Map(); const events = new Map(); const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document; @@ -30,8 +31,10 @@ test('Language saves before reactive changes and syncs across windows', () => { globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage; globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis; globalThis.document = { documentElement: { lang: '' } } as unknown as Document; + // Without the desktop host, the settings store keeps the language in localStorage and listens for storage events. + await initSettings(() => ({})); const stop = syncLocale(); - setLocale('fr'); + await setLocale('fr'); assert.equal(stored.get(LANGUAGE_KEY), 'fr'); assert.equal(get(t)('Settings'), 'Paramètres'); assert.equal(document.documentElement.lang, 'fr'); @@ -40,7 +43,9 @@ test('Language saves before reactive changes and syncs across windows', () => { globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); }; assert.throws(() => setLocale('ja')); assert.equal(get(locale), 'zh-CN'); - stop(); assert.equal(events.size, 0); + stop(); + stored.set(LANGUAGE_KEY, 'ja'); events.get('storage')!({ key: LANGUAGE_KEY }); + assert.equal(get(locale), 'zh-CN', 'A stopped sync ignores later changes'); } finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); } }); diff --git a/tests/unit/layout/settings.spec.ts b/tests/unit/layout/settings.spec.ts index 723bdc4..c69dca0 100644 --- a/tests/unit/layout/settings.spec.ts +++ b/tests/unit/layout/settings.spec.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../../../src/lib/workspace/settings.ts"; +import { DEFAULT_SETTINGS, SETTINGS_KEY, normalizeSettings, parseSettings, readSettings, saveSettings } from "../../../src/lib/workspace/settings.ts"; test("missing or damaged preferences keep safe defaults", () => { for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) { @@ -12,21 +12,38 @@ test("missing or damaged preferences keep safe defaults", () => { assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false }); }); +function withStorage(storage: Pick, body: () => void) { + const prior = globalThis.localStorage; + try { globalThis.localStorage = storage as Storage; body(); } + finally { globalThis.localStorage = prior; } +} + test("preferences persist and load at both interval limits", () => { const store = new Map(); - for (const autosaveSeconds of [1, 23, 300]) { - const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false }; - saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings); - assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings); - } + withStorage({ getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }, () => { + for (const autosaveSeconds of [1, 23, 300]) { + const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false }; + void saveSettings(settings); + assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings); + assert.deepEqual(readSettings(), settings); + } + }); }); test("invalid changes never reach storage and storage failures reach the caller", () => { let writes = 0; - const storage = { setItem: () => { writes++; } }; - for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) { - assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false })); - } + withStorage({ getItem: () => null, setItem: () => { writes++; } }, () => { + for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) { + assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false })); + } + }); assert.equal(writes, 0); - assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/); + withStorage({ getItem: () => null, setItem: () => { throw new Error("Storage unavailable"); } }, () => { + assert.throws(() => saveSettings({ ...DEFAULT_SETTINGS }), /Storage unavailable/); + }); +}); + +test("stored values of any type normalize to safe settings", () => { + for (const value of [undefined, null, 42, "text", [], { autosaveSeconds: 0 }]) assert.deepEqual(normalizeSettings(value), DEFAULT_SETTINGS); + assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }); }); diff --git a/tests/unit/settings/migration.spec.ts b/tests/unit/settings/migration.spec.ts new file mode 100644 index 0000000..28dd616 --- /dev/null +++ b/tests/unit/settings/migration.spec.ts @@ -0,0 +1,69 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { migrateLegacyPreferences } from '../../../src/lib/settings/migration.ts'; +import { LEGACY_KEYS } from '../../../src/lib/settings/store.ts'; + +const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' }; +const reader = (values: Record) => (key: string) => Object.hasOwn(values, key) ? values[key] : null; + +test('Migration reads the four old keys and the theme backup, and normalizes each value', () => { + const custom = { schema: 2, id: 'night', name: 'Night', colors: { ...palette, bg: '#000000' } }; + const sections = migrateLegacyPreferences(reader({ + 'runestone.settings': JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 900, extra: true }), + 'runestone.appearance': JSON.stringify({ theme: 'custom:night', mode: 'light', transparency: { amount: 140 } }), + 'runestone.custom-themes': JSON.stringify([custom, { schema: 2, id: '../bad' }]), + 'runestone.custom-themes.legacy': JSON.stringify([{ schema: 1, id: 'kept' }]), + 'runestone.language': 'fr', + })); + assert.deepEqual(sections, { + general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false }, + language: 'fr', + customThemes: [custom], + customThemesLegacy: [{ schema: 1, id: 'kept' }], + // The mode comes from the migrated custom theme, not from a store that is still empty. + appearance: { theme: 'custom:night', mode: 'dark', transparency: { enabled: true, amount: 100 } }, + }); +}); + +test('Migration of version 1 themes keeps the saved palette and adds the originals to the backup once', () => { + const legacy = { schema: 1, id: 'old', name: 'Old', light: { ...palette, bg: '#fff' }, dark: palette }; + const sections = migrateLegacyPreferences(reader({ + 'runestone.appearance': JSON.stringify({ theme: 'custom:old', mode: 'light' }), + 'runestone.custom-themes': JSON.stringify([legacy]), + 'runestone.custom-themes.legacy': JSON.stringify([legacy]), + })); + assert.deepEqual(sections.customThemes, [{ schema: 2, id: 'old', name: 'Old', colors: legacy.light }]); + assert.deepEqual(sections.customThemesLegacy, [legacy]); + assert.deepEqual(sections.appearance, { theme: 'custom:old', mode: 'light' }); +}); + +test('Missing keys give no sections, so the defaults apply', () => { + assert.deepEqual(migrateLegacyPreferences(() => null), {}); + assert.deepEqual(migrateLegacyPreferences(() => { throw new Error('Storage unavailable'); }), {}); +}); + +test('Damaged old values become defaults and unknown languages become English', () => { + const sections = migrateLegacyPreferences(reader({ + 'runestone.settings': '{broken', + 'runestone.appearance': '[1, 2]', + 'runestone.custom-themes': '{"not":"a list"}', + 'runestone.language': 'de', + })); + assert.deepEqual(sections, { + general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false }, + language: 'en', + appearance: { theme: 'default', mode: 'dark' }, + }); +}); + +test('Migration keeps renamed theme IDs and a background image data URL', () => { + const image = 'data:image/png;base64,' + 'A'.repeat(40); + const sections = migrateLegacyPreferences(reader({ + 'runestone.appearance': JSON.stringify({ theme: 'holo', mode: 'dark', newTabBackground: { image, overlay: 0.4 } }), + })); + assert.deepEqual(sections.appearance, { theme: 'harvest-moon', mode: 'dark', newTabBackground: { image, overlay: 0.4, position: 'center', size: 'cover' } }); +}); + +test('Every section has one old key', () => { + assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.language', 'runestone.settings']); +}); diff --git a/tests/unit/settings/store.spec.ts b/tests/unit/settings/store.spec.ts new file mode 100644 index 0000000..6afd823 --- /dev/null +++ b/tests/unit/settings/store.spec.ts @@ -0,0 +1,118 @@ +// The settings store with a mock desktop host. Each test file runs in its own process, +// so the mock is installed before the first import of the store. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +type Handler = (args: Record) => unknown; +const calls: { command: string; args: Record }[] = []; +const callbacks = new Map void>(); +const listeners = new Map(); +const handlers = new Map(); +let sequence = 0; +const host = globalThis as unknown as Record; +host.isTauri = true; +host.window = globalThis; +host.__TAURI_INTERNALS__ = { + transformCallback: (callback: (event: unknown) => void) => { callbacks.set(++sequence, callback); return sequence; }, + invoke: async (command: string, args: Record = {}) => { + calls.push({ command, args }); + if (command === 'plugin:event|listen') { + listeners.set(args.event as string, [...listeners.get(args.event as string) ?? [], args.handler as number]); + return args.handler; + } + const handler = handlers.get(command); + if (!handler) throw new Error(`Unhandled IPC: ${command}`); + return handler(args); + }, +}; +function emit(event: string, payload: unknown) { + for (const id of listeners.get(event) ?? []) callbacks.get(id)?.({ event, id, payload }); +} +const legacy = new Map(); +host.localStorage = { getItem: (key: string) => legacy.get(key) ?? null, setItem: (key: string, value: string) => legacy.set(key, value) }; + +const store = await import('../../../src/lib/settings/store.ts'); +const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts'); + +let file: Record | null = null; +let revision = 0; +// While `gate` is set, the host holds each write until the gate opens. +let gate: Promise | undefined; +function closeGate() { + let open!: () => void; + gate = new Promise(resolve => { open = resolve; }); + return () => { gate = undefined; open(); }; +} +handlers.set('settings_read', () => ({ exists: file !== null, revision, sections: { ...file } })); +handlers.set('settings_migrate', args => { + if (file === null) { file = { ...(args.sections as Record) }; revision = 1; } + return { exists: true, revision, sections: { ...file }, notice: 'Notice once' }; +}); +handlers.set('settings_write', async args => { + if (gate) await gate; + const section = args.section as string; + file![section] = args.value; + revision += 1; + return { section, revision, value: args.value }; +}); + +test('The first start migrates the old localStorage values, and later reads come from memory', async () => { + legacy.set('runestone.language', 'ja'); + legacy.set('runestone.settings', JSON.stringify({ autosaveSeconds: 12 })); + await store.initSettings(migrateLegacyPreferences); + await store.initSettings(() => { throw new Error('Migrates once'); }); + assert.deepEqual(calls.filter(call => !call.command.startsWith('plugin:')).map(call => call.command), ['settings_read', 'settings_migrate']); + assert.equal(calls[0].command, 'plugin:event|listen', 'The listener starts before the read'); + assert.equal(store.readSection('language'), 'ja'); + assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false }); + assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place'); + assert.equal(store.takeSettingsNotice(), 'Notice once'); + assert.equal(store.takeSettingsNotice(), null); +}); + +test('A write shows at once, merges quick writes, and runs subscribers', async () => { + let changes = 0; + const stop = store.onSettingsChange('language', () => { changes++; }); + const open = closeGate(); + const first = store.writeSection('language', 'fr'); + const second = store.writeSection('language', 'zh-CN'); + const third = store.writeSection('language', 'en'); + assert.equal(store.readSection('language'), 'en'); + assert.equal(changes, 3); + open(); + await Promise.all([first, second, third]); + const writes = calls.filter(call => call.command === 'settings_write').map(call => call.args.value); + assert.deepEqual(writes, ['fr', 'en'], 'The writes during the first one merge into the last value'); + assert.equal(file!.language, 'en'); + stop(); +}); + +test('Changes from other windows apply in revision order, and old changes do not', () => { + let changes = 0; + const stop = store.onSettingsChange('appearance', () => { changes++; }); + emit('settings-changed', { section: 'appearance', revision: 50, value: { theme: 'claude', mode: 'light' } }); + assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' }); + emit('settings-changed', { section: 'appearance', revision: 40, value: { theme: 'sakura', mode: 'light' } }); + assert.deepEqual(store.readSection('appearance'), { theme: 'claude', mode: 'light' }); + emit('settings-changed', { section: 'unknown', revision: 60, value: 1 }); + assert.equal(changes, 1); + stop(); + emit('settings-changed', { section: 'appearance', revision: 70, value: null }); + assert.equal(store.readSection('appearance'), undefined, 'null removes the section'); + assert.equal(changes, 1, 'A stopped subscriber does not run'); +}); + +test('A change from another window during a local write applies after the write when it is newer', async () => { + const open = closeGate(); + const pending = store.writeSection('general', { autosaveSeconds: 30 }); + emit('settings-changed', { section: 'general', revision: 1000, value: { autosaveSeconds: 60 } }); + assert.deepEqual(store.readSection('general'), { autosaveSeconds: 30 }, 'No old value appears during the write'); + open(); + await pending; + assert.deepEqual(store.readSection('general'), { autosaveSeconds: 60 }, 'The host saved the other window last'); +}); + +test('A failed write reaches the caller', async () => { + handlers.set('settings_write', () => { throw 'Disk full'; }); + await assert.rejects(store.writeSection('customThemes', []), /Disk full/); +}); diff --git a/tests/unit/theme/customThemes.spec.ts b/tests/unit/theme/customThemes.spec.ts index 6ed32bd..97d9b58 100644 --- a/tests/unit/theme/customThemes.spec.ts +++ b/tests/unit/theme/customThemes.spec.ts @@ -81,8 +81,16 @@ test('Opaque mode retains background ownership and the amount for re-enabling', test('Saved legacy light themes migrate once and preserve both original palettes', async () => { const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts'); + const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts'); + const { LEGACY_KEYS } = await import('../../../src/lib/settings/store.ts'); const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } }; - const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]); + const old = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]); + const sections = migrateLegacyPreferences(key => old.get(key) ?? null); + assert.equal((sections.customThemes as { schema: number }[])[0].schema, 2); + assert.deepEqual(sections.customThemesLegacy, [legacy]); + assert.deepEqual(sections.appearance, { theme: 'custom:saved-light', mode: 'light' }); + // The browser preview store reads the sections from their old keys. + const stored = new Map(Object.entries(sections).map(([section, value]) => [LEGACY_KEYS[section as keyof typeof LEGACY_KEYS], JSON.stringify(value)])); const previous = globalThis.localStorage; try { globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage; @@ -90,22 +98,18 @@ test('Saved legacy light themes migrate once and preserve both original palettes assert.deepEqual(themeModes('custom:saved-light'), ['light']); assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light'); assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff'); - assert.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2); - assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy); - assert.deepEqual(customThemes('dark')[0].colors, legacy.light); + assert.deepEqual(customThemes('dark')[0].colors, legacy.light, 'The converted theme keeps its palette in both modes'); } finally { globalThis.localStorage = previous; } }); -test('Legacy migration storage failure leaves the original palette available', async () => { +test('Reading custom themes never writes, and an unconverted version 1 theme uses the requested palette', async () => { const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts'); const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette }; - const raw = JSON.stringify([legacy]); const previous = globalThis.localStorage; - let original = raw; try { - globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage; + globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? JSON.stringify([legacy]) : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage; assert.deepEqual(customThemes('light')[0].colors, legacy.light); - assert.equal(original, raw); - assert.deepEqual(customThemes('dark')[0].colors, legacy.light); + assert.deepEqual(customThemes('dark')[0].colors, palette); + assert.deepEqual(customThemes()[0].colors, palette, 'Without a saved appearance, the dark palette applies'); } finally { globalThis.localStorage = previous; } }); diff --git a/tests/unit/workspace/tabTransfer.spec.ts b/tests/unit/workspace/tabTransfer.spec.ts new file mode 100644 index 0000000..041fc0d --- /dev/null +++ b/tests/unit/workspace/tabTransfer.spec.ts @@ -0,0 +1,26 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { TAB_TRANSFER_ID, parseTabTransfer } from '../../../src/lib/workspace/tabTransfer.ts'; + +const buffer = { id: 'one', relPath: 'a.md', name: 'a.md', kind: 'text', contents: 'Unsaved', saved: 'Saved' }; + +test('A buffer transfer needs a path, its text, and its saved text', () => { + assert.deepEqual(parseTabTransfer(JSON.stringify({ buffer, reading: true })), { buffer, reading: true }); + assert.equal(parseTabTransfer(JSON.stringify({ buffer })).reading, false); + for (const field of ['relPath', 'contents', 'saved'] as const) { + assert.throws(() => parseTabTransfer(JSON.stringify({ buffer: { ...buffer, [field]: 1 } })), /Invalid tab transfer/); + } +}); + +test('A plugin transfer needs a state object, and other payloads are invalid', () => { + const plugin = { owner: 'test.plugin', id: 'board' }; + assert.deepEqual(parseTabTransfer(JSON.stringify({ plugin, reading: false })), { plugin, reading: false }); + for (const payload of ['{', 'null', '[]', '{}', '{"plugin":"text"}', '{"buffer":null}']) { + assert.throws(() => parseTabTransfer(payload), /Invalid tab transfer/, payload); + } +}); + +test('Transfer IDs are UUIDs', () => { + assert.ok(TAB_TRANSFER_ID.test(crypto.randomUUID())); + for (const id of ['', '../x', 'runestone.tab-transfer.1']) assert.ok(!TAB_TRANSFER_ID.test(id), id); +});