From 086bc8a92514dac071c8cff683c524b0570b93f8 Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 2 Nov 2026 19:47:58 +0100 Subject: [PATCH] T1: four more themes, theme picker, theme file import, editor font settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plum Night, River, Paper and Reed (designed by Amy, approved by Daniel) join the brand pair. theme.list/current/select/import, a picker with live preview (view.selectTheme) and "Import Theme…" (view.importTheme); imported themes are validated and stored in /themes. Editor font family and line height settings apply live. Docs: docs/themes.md. Gate: fmt, clippy and the rest pass up to cargo test, where only the unrelated lutra-terminal PTY test a_full_buffer_stops_the_shell timed out under load; to be re-run. Co-Authored-By: Claude Opus 5.5 --- apps/lutra-desktop/src/main.rs | 41 +- crates/control/tests/events.rs | 2 + crates/engine/src/cmd/mod.rs | 3 + crates/engine/src/cmd/settings.rs | 32 +- crates/engine/src/cmd/theme.rs | 342 +++++++++++- crates/engine/src/engine.rs | 1 + crates/engine/src/settings.rs | 102 +++- crates/engine/src/state.rs | 3 + crates/engine/src/theme.rs | 673 +++++++++++++++++++++++- crates/engine/tests/settings.rs | 18 +- crates/engine/tests/theme.rs | 158 +++++- docs/gaps.md | 5 +- docs/themes.md | 158 ++++++ docs/ui-parity.md | 6 +- ui/src/App.vue | 5 +- ui/src/commands/modals.ts | 7 +- ui/src/commands/uiCommands.ts | 2 + ui/src/components/editor/extensions.ts | 2 +- ui/src/components/theme/ThemePicker.vue | 285 ++++++++++ ui/src/components/theme/themes.ts | 232 ++++++++ ui/src/i18n/en.json | 23 + ui/src/stores/settings.ts | 92 +++- ui/tests/settings/fontSettings.test.ts | 178 +++++++ ui/tests/theme/ThemePicker.test.ts | 279 ++++++++++ ui/tests/theme/contrast.test.ts | 42 +- ui/tests/theme/themes.json | 290 ++++++++++ 26 files changed, 2881 insertions(+), 100 deletions(-) create mode 100644 docs/themes.md create mode 100644 ui/src/components/theme/ThemePicker.vue create mode 100644 ui/src/components/theme/themes.ts create mode 100644 ui/tests/settings/fontSettings.test.ts create mode 100644 ui/tests/theme/ThemePicker.test.ts diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index 1512adc..ccc3129 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -110,16 +110,22 @@ fn run(args: &args::Args) -> Result<(), String> { let setup_host = setup_slot.get().ok_or("the host is not ready")?; setup_host.attach(app.handle().clone()); let setting = stored_theme(setup_host); + let current = current_theme(setup_host); + let css = match ¤t { + Some(resolved) if setting != theme::SYSTEM => theme::css_of(resolved), + _ => theme::css_for_setting(&setting), + }; let mut window = WebviewWindowBuilder::new(app, MAIN_WINDOW, WebviewUrl::default()) .title(WINDOW_TITLE) .inner_size(1200.0, 800.0) .min_inner_size(640.0, 400.0) .focused(focus_on_start) - .initialization_script(theme::init_script(&setting)); + .initialization_script(theme::init_script_for_css(&css)); if let Some(dir) = &webview_dir { window = window.data_directory(dir.clone()); } - if let Some(color) = token_color(&theme::resolve(&setting, None), "bg") { + let first = current.unwrap_or_else(|| theme::resolve(&setting, None).resolved()); + if let Some(color) = token_color(&first, "bg") { window = window.background_color(color); } let window = window.build()?; @@ -281,6 +287,23 @@ fn stored_theme(host: &Host) -> String { .unwrap_or_else(|| theme::SYSTEM.to_string()) } +/// The theme the engine resolves now (`theme.current`), imported themes +/// included; `None` if the answer cannot be read. +fn current_theme(host: &Host) -> Option { + let value = host.run("theme.current", Value::Null).ok()?; + let tokens = value + .get("tokens")? + .as_object()? + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))) + .collect(); + Some(theme::ResolvedTheme { + id: value.get("id")?.as_str()?.to_string(), + dark: value.get("dark")?.as_bool()?, + tokens, + }) +} + /// In "system" mode, sets the window background to the theme the OS /// prefers; the page itself follows the OS through the init script's /// `prefers-color-scheme` query. Failures are ignored: the background only @@ -290,15 +313,15 @@ fn follow_system_background(window: &tauri::WebviewWindow) { return; }; let resolved = theme::resolve(theme::SYSTEM, Some(os == tauri::Theme::Dark)); - if let Some(color) = token_color(&resolved, "bg") { + if let Some(color) = token_color(&resolved.resolved(), "bg") { let _ = window.set_background_color(Some(color)); } } /// Reads a `#rrggbb` theme token as an opaque colour for the window /// background, so that no white frame shows before the page paints. -fn token_color(theme: &theme::Theme, name: &str) -> Option { - let (_, value) = theme.tokens.iter().find(|(n, _)| *n == name)?; +fn token_color(theme: &theme::ResolvedTheme, name: &str) -> Option { + let value = theme.tokens.get(&format!("--lt-{name}"))?; let hex = value.strip_prefix('#')?; let byte = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok(); Some(Color(byte(0)?, byte(2)?, byte(4)?, 255)) @@ -378,10 +401,14 @@ mod tests { #[test] fn reads_theme_colours() { assert_eq!( - token_color(&theme::DARK, "bg"), + token_color(&theme::DARK.resolved(), "bg"), Some(Color(0x1e, 0x1b, 0x1e, 255)) ); - assert_eq!(token_color(&theme::DARK, "missing"), None); + assert_eq!( + token_color(&theme::RIVER.resolved(), "bg"), + Some(Color(0x1a, 0x21, 0x25, 255)) + ); + assert_eq!(token_color(&theme::DARK.resolved(), "missing"), None); } #[test] diff --git a/crates/control/tests/events.rs b/crates/control/tests/events.rs index 811445d..9bc8afc 100644 --- a/crates/control/tests/events.rs +++ b/crates/control/tests/events.rs @@ -197,6 +197,8 @@ fn settings_changes_stream_and_persist() { json!({ "appearance.theme": "system", "editor.fontSize": 14, + "editor.fontFamily": "", + "editor.lineHeight": 150, "ui.language": "en", "php.executable": "", "phpactor.path": "", diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 2a2663d..916e2d3 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -55,6 +55,9 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { registry.register(Box::new(settings::Set))?; registry.register(Box::new(settings::Reset))?; registry.register(Box::new(theme::List))?; + registry.register(Box::new(theme::Current))?; + registry.register(Box::new(theme::Select))?; + registry.register(Box::new(theme::Import))?; registry.register(Box::new(theme::SystemPreference))?; registry.register(Box::new(ui::RegisterCommands))?; registry.register(Box::new(search::Find))?; diff --git a/crates/engine/src/cmd/settings.rs b/crates/engine/src/cmd/settings.rs index 520e5c5..e1482e5 100644 --- a/crates/engine/src/cmd/settings.rs +++ b/crates/engine/src/cmd/settings.rs @@ -19,12 +19,24 @@ impl Command for List { label: "List Settings", menu_path: None, default_shortcut: None, - params: "none; returns [{ key, type: enum|int|bool|string, default, enumValues?, min?, max?, labelKey, descriptionKey, section }]", + params: "none; returns [{ key, type: enum|int|bool|string, default, enumValues?, valueNames?, min?, max?, labelKey, descriptionKey, section }]; valueNames holds display names of enum values without a catalog key (imported themes)", } } - fn run(&self, _state: &mut State, _params: Value) -> Result { - let list: Vec<_> = DEFS.iter().map(settings::Def::info).collect(); + fn run(&self, state: &mut State, _params: Value) -> Result { + let mut list: Vec<_> = DEFS.iter().map(settings::Def::info).collect(); + if let Some(info) = list.iter_mut().find(|i| i.key == theme::SETTING) { + let (ids, names) = theme::choices(state); + info.enum_values = Some(ids); + if !names.is_empty() { + info.value_names = Some( + names + .into_iter() + .filter_map(|(k, v)| Some((k, v.as_str()?.to_string()))) + .collect(), + ); + } + } let value = serde_json::to_value(list).map_err(|e| EngineError::Internal(e.to_string()))?; Ok(Outcome::value(value)) } @@ -97,6 +109,16 @@ impl Command for Set { fn run(&self, state: &mut State, params: Value) -> Result { let id = self.spec().id; let p: SetParams = parse(id, params)?; + if p.key == theme::SETTING + && let Some(name) = p.value.as_str() + && !theme::known(state, name) + { + let (ids, _) = theme::choices(state); + return Err(EngineError::invalid_params( + id, + format!("unknown theme: {name}; known: {}", ids.join(", ")), + )); + } let before = theme::resolved(state); let changed = state .settings @@ -138,7 +160,7 @@ impl Command for Reset { } /// Maps a settings error to the command error. -fn set_error(command: &str, error: SetError) -> EngineError { +pub(crate) fn set_error(command: &str, error: SetError) -> EngineError { match error { SetError::Invalid(message) => EngineError::invalid_params(command, message), SetError::Save(message) => { @@ -153,7 +175,7 @@ fn finish( state: &mut State, key: &str, changed: bool, - before: crate::theme::Theme, + before: crate::theme::ResolvedTheme, ) -> Result { if changed { state.emit(Event::SettingsChanged { diff --git a/crates/engine/src/cmd/theme.rs b/crates/engine/src/cmd/theme.rs index fb09f38..b06d3a7 100644 --- a/crates/engine/src/cmd/theme.rs +++ b/crates/engine/src/cmd/theme.rs @@ -1,45 +1,190 @@ -//! Theme commands: `theme.list` and `theme.systemPreference`. Switching -//! themes goes through `settings.set appearance.theme`; whenever the -//! resolved theme changes, `themeChanged` carries its tokens. +//! Theme commands: `theme.list`, `theme.current`, `theme.select`, +//! `theme.import` and `theme.systemPreference`. The selected theme is the +//! setting `appearance.theme`; whenever the resolved theme changes, +//! `themeChanged` carries its tokens. Imported themes live as normalised +//! theme files in `/themes/.json` and are loaded at start +//! ([`load_imported`]). + +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; use serde::Deserialize; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use crate::cmd::params::parse; -use crate::theme::{self, BUILTIN, Theme}; -use crate::{Command, CommandSpec, EngineError, Event, Outcome, State}; +use crate::theme::{self, BUILTIN, ResolvedTheme, UserTheme}; +use crate::{Command, CommandSpec, EngineError, Event, NotificationLevel, Outcome, State}; /// The setting that selects the theme. pub const SETTING: &str = "appearance.theme"; +/// Directory of imported themes inside the data directory. +pub const DIR_NAME: &str = "themes"; + +/// Most imported themes loaded at start; further files are ignored. +pub const MAX_IMPORTED: usize = 200; + /// The theme the current settings and OS preference resolve to. -pub fn resolved(state: &State) -> Theme { +pub fn resolved(state: &State) -> ResolvedTheme { let setting = state.settings.get(SETTING); let id = setting .as_ref() .and_then(Value::as_str) .unwrap_or(theme::SYSTEM); - theme::resolve(id, state.system_dark) + theme::resolve_with(id, state.system_dark, &state.themes) +} + +/// Whether `id` names a theme Lutra can apply: [`theme::SYSTEM`], a +/// built-in theme or an imported one. +pub fn known(state: &State, id: &str) -> bool { + theme::reserved_id(id) || state.themes.iter().any(|t| t.id == id) +} + +/// Every theme id in picker order (built-in, imported by name, then +/// `system`) and the names of the imported ones, for `settings.list`. +pub fn choices(state: &State) -> (Vec, Map) { + let mut ids: Vec = BUILTIN.iter().map(|t| t.id.to_string()).collect(); + let mut names = Map::new(); + for t in sorted_imports(state) { + ids.push(t.id.clone()); + names.insert(t.id.clone(), Value::from(t.name.clone())); + } + ids.push(theme::SYSTEM.to_string()); + (ids, names) +} + +/// The imported themes sorted by name, then id. +fn sorted_imports(state: &State) -> Vec<&UserTheme> { + let mut list: Vec<_> = state.themes.iter().collect(); + list.sort_by(|a, b| { + a.name + .to_lowercase() + .cmp(&b.name.to_lowercase()) + .then_with(|| a.id.cmp(&b.id)) + }); + list } /// The `themeChanged` event for a theme. -pub fn changed_event(theme: &Theme) -> Event { +pub fn changed_event(theme: &ResolvedTheme) -> Event { Event::ThemeChanged { - id: theme.id.to_string(), + id: theme.id.clone(), dark: theme.dark, - tokens: theme::token_map(theme), + tokens: theme.tokens.clone(), } } /// Emits `themeChanged` if the resolved theme is no longer `before`. -pub fn emit_if_changed(state: &mut State, before: Theme) { +pub fn emit_if_changed(state: &mut State, before: ResolvedTheme) { let now = resolved(state); if now != before { state.emit(changed_event(&now)); } } -/// `theme.list`: the built-in themes. +/// A resolved theme as a command result: `{ id, dark, tokens }`. +fn theme_value(theme: &ResolvedTheme) -> Value { + json!({ "id": theme.id, "dark": theme.dark, "tokens": theme.tokens }) +} + +/// The directory of imported themes, or `None` without persistence. +fn themes_dir(state: &State) -> Option { + state.config.as_ref().map(|c| c.data_dir.join(DIR_NAME)) +} + +/// Reads a theme file with the size cap of [`theme::MAX_FILE_SIZE`]. +/// +/// # Errors +/// An English sentence for the user: the file cannot be read, is too +/// large or is not a valid theme file. +fn read_theme_file(path: &Path) -> Result { + let file = fs::File::open(path).map_err(|e| format!("cannot read it: {e}"))?; + let mut text = String::new(); + file.take(theme::MAX_FILE_SIZE + 1) + .read_to_string(&mut text) + .map_err(|e| format!("cannot read it as UTF-8 text: {e}"))?; + if text.len() as u64 > theme::MAX_FILE_SIZE { + return Err(format!( + "it is larger than {} KiB", + theme::MAX_FILE_SIZE / 1024 + )); + } + theme::parse_file(&text) +} + +/// Loads the imported themes from `/themes/*.json` into the +/// state. A missing directory means none. A file that is not a valid +/// theme file, or whose id another file already took, is skipped with a +/// warning notification naming it and the reason, so a broken file never +/// blocks startup. At most [`MAX_IMPORTED`] files are read. +pub fn load_imported(state: &mut State) { + let Some(dir) = themes_dir(state) else { + return; + }; + let Ok(entries) = fs::read_dir(&dir) else { + return; + }; + let mut paths: Vec = entries + .filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|ext| ext == "json")) + .collect(); + paths.sort(); + for path in paths.into_iter().take(MAX_IMPORTED) { + match read_theme_file(&path) { + Ok(theme) if !state.themes.iter().any(|t| t.id == theme.id) => { + state.themes.push(theme); + } + Ok(theme) => broken_file(state, &path, &format!("the id {} is taken", theme.id)), + Err(reason) => broken_file(state, &path, &reason), + } + } +} + +/// Warns that an imported theme file was skipped. +fn broken_file(state: &mut State, path: &Path, reason: &str) { + let file = path.display().to_string(); + let mut params = Map::new(); + params.insert("file".into(), Value::from(file.clone())); + params.insert("reason".into(), Value::from(reason)); + state.notify( + NotificationLevel::Warning, + Some("theme.notification.skipped"), + Some(format!("Skipped the theme file {file}: {reason}")), + Some(params), + ); +} + +/// Sets `appearance.theme` to a known theme and emits `settingsChanged` +/// and, if the resolved theme changed, `themeChanged`. +/// +/// # Errors +/// `invalid_params` for an unknown id; `failed` if the settings cannot be +/// saved. +pub fn select(state: &mut State, command: &str, id: &str) -> Result<(), EngineError> { + if !known(state, id) { + let (ids, _) = choices(state); + return Err(EngineError::invalid_params( + command, + format!("unknown theme: {id}; known: {}", ids.join(", ")), + )); + } + let before = resolved(state); + let changed = state + .settings + .set(SETTING, Value::from(id)) + .map_err(|e| super::settings::set_error(command, e))?; + if changed { + state.emit(Event::SettingsChanged { + keys: vec![SETTING.to_string()], + }); + emit_if_changed(state, before); + } + Ok(()) +} + +/// `theme.list`: the built-in and imported themes. pub struct List; impl Command for List { @@ -49,16 +194,156 @@ impl Command for List { label: "List Themes", menu_path: None, default_shortcut: None, - params: "none; returns [{ id, label, dark }], label is a message-catalog key", + params: "none; returns [{ id, label, name, dark, builtin, tokens }]: label is a message-catalog key (null for an imported theme), name is the imported theme's display name (null for a built-in one), tokens as in themeChanged", } } - fn run(&self, _state: &mut State, _params: Value) -> Result { - let list: Vec<_> = BUILTIN - .iter() - .map(|t| json!({ "id": t.id, "label": t.label_key, "dark": t.dark })) - .collect(); - Ok(Outcome::value(Value::Array(list))) + fn run(&self, state: &mut State, _params: Value) -> Result { + let builtin = BUILTIN.iter().map(|t| { + json!({ + "id": t.id, + "label": t.label_key, + "name": Value::Null, + "dark": t.dark, + "builtin": true, + "tokens": theme::token_map(t), + }) + }); + let imported = sorted_imports(state).into_iter().map(|t| { + json!({ + "id": t.id, + "label": Value::Null, + "name": t.name, + "dark": t.dark, + "builtin": false, + "tokens": t.resolved().tokens, + }) + }); + Ok(Outcome::value(Value::Array( + builtin.chain(imported).collect(), + ))) + } +} + +/// `theme.current`: the theme in use. +pub struct Current; + +impl Command for Current { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "theme.current", + label: "Current Theme", + menu_path: None, + default_shortcut: None, + params: "none; returns the resolved theme { id, dark, tokens }", + } + } + + fn run(&self, state: &mut State, _params: Value) -> Result { + Ok(Outcome::value(theme_value(&resolved(state)))) + } +} + +/// Params of `theme.select`. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SelectParams { + /// Theme id or `system`. + id: String, +} + +/// `theme.select`: switches the theme, live. +pub struct Select; + +impl Command for Select { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "theme.select", + label: "Select Theme", + menu_path: None, + default_shortcut: None, + params: "{ id }: a theme id from theme.list or \"system\"; returns the resolved theme { id, dark, tokens }; emits settingsChanged and themeChanged", + } + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let id = self.spec().id; + let p: SelectParams = parse(id, params)?; + select(state, id, &p.id)?; + Ok(Outcome::value(theme_value(&resolved(state)))) + } +} + +/// Params of `theme.import`. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ImportParams { + /// Path of the theme file. + path: PathBuf, + /// Whether to switch to the theme; true when absent. + select: Option, +} + +/// `theme.import`: reads a theme file, keeps it in the data directory and, +/// by default, switches to it. Importing an id again replaces that theme. +pub struct Import; + +impl Command for Import { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "theme.import", + label: "Import Theme", + menu_path: None, + default_shortcut: None, + params: "{ path, select?: bool = true }; returns { id, name, dark, replaced }; failed with the reason for an unreadable or invalid file (format: docs/themes.md); emits settingsChanged for appearance.theme", + } + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let id = self.spec().id; + let p: ImportParams = parse(id, params)?; + let imported = read_theme_file(&p.path).map_err(|reason| { + EngineError::Failed(format!( + "cannot import the theme {}: {reason}", + p.path.display() + )) + })?; + if let Some(dir) = themes_dir(state) { + let text = serde_json::to_string_pretty(&imported.to_file()) + .map_err(|e| EngineError::Internal(e.to_string()))?; + fs::create_dir_all(&dir) + .and_then(|()| fs::write(dir.join(format!("{}.json", imported.id)), text)) + .map_err(|e| { + EngineError::Failed(format!("cannot store the theme in {}: {e}", dir.display())) + })?; + } + let before = resolved(state); + let replaced = match state.themes.iter_mut().find(|t| t.id == imported.id) { + Some(slot) => { + *slot = imported.clone(); + true + } + None => { + state.themes.push(imported.clone()); + false + } + }; + if p.select.unwrap_or(true) { + state + .settings + .set(SETTING, Value::from(imported.id.clone())) + .map_err(|e| super::settings::set_error(id, e))?; + } + state.emit(Event::SettingsChanged { + keys: vec![SETTING.to_string()], + }); + emit_if_changed(state, before); + Ok(Outcome::value(json!({ + "id": imported.id, + "name": imported.name, + "dark": imported.dark, + "replaced": replaced, + }))) } } @@ -90,18 +375,17 @@ impl Command for SystemPreference { let before = resolved(state); state.system_dark = Some(p.dark); emit_if_changed(state, before); - let now = resolved(state); - let value = serde_json::to_value(changed_event(&now)) - .map_err(|e| EngineError::Internal(e.to_string()))?; - let Value::Object(mut fields) = value else { - return Err(EngineError::Internal("theme is not an object".into())); - }; - fields.remove("kind"); - Ok(Outcome::value(Value::Object(fields))) + Ok(Outcome::value(theme_value(&resolved(state)))) } } /// The ids of the commands this module registers, checked against the /// registry by the engine's listing test. Add a new command's id here. #[cfg(test)] -pub(crate) const COMMAND_IDS: &[&str] = &["theme.list", "theme.systemPreference"]; +pub(crate) const COMMAND_IDS: &[&str] = &[ + "theme.list", + "theme.current", + "theme.select", + "theme.import", + "theme.systemPreference", +]; diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index b09b9f7..36f44d3 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -47,6 +47,7 @@ impl Engine { let (settings, problem) = Settings::load(&config.config_dir); engine.state.settings = settings; engine.state.config = Some(config); + cmd::theme::load_imported(&mut engine.state); if let Some(problem) = problem { engine.state.notify( NotificationLevel::Warning, diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 5f4ff5c..9588ede 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -48,6 +48,19 @@ pub enum Kind { /// Longest accepted value in bytes. max_len: usize, }, + /// A theme id or `system`: any well-formed id + /// ([`crate::theme::valid_id`]), so an imported theme's id survives a + /// restart. `settings.set` also requires the theme to exist; listed as + /// an enum of the built-in ids and `system`, which `settings.list` + /// extends with the imported ones. + Theme, + /// A font family list for CSS, such as `"Fira Code", monospace`: at + /// most `max_len` bytes without control characters or `;{}<>\`, so it + /// cannot leave the `font-family` value. Empty means the theme's font. + FontFamily { + /// Longest accepted value in bytes. + max_len: usize, + }, } /// Checks a path setting's text: at most `max_len` bytes, no control @@ -162,22 +175,57 @@ impl Def { } None => Err(format!("{} must be a path string, got {value}", self.key)), }, + Kind::Theme => match value.as_str() { + Some(s) if crate::theme::valid_id(s) => Ok(()), + _ => Err(format!( + "{} must be a theme id (lowercase letters, digits and dashes) or system, got {value}", + self.key + )), + }, + Kind::FontFamily { max_len } => match value.as_str() { + Some(s) + if s.len() <= max_len + && !s.chars().any(|c| c.is_control() || ";{}<>\\".contains(c)) => + { + Ok(()) + } + _ => Err(format!( + "{} must be a font family list of at most {max_len} bytes without control characters or ; {{ }} < > \\", + self.key + )), + }, } } /// The description for `settings.list`. pub fn info(&self) -> SettingInfo { let (kind, enum_values, min, max) = match self.kind { - Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None), + Kind::Enum(values) => ( + "enum", + Some(values.iter().map(|v| (*v).to_string()).collect()), + None, + None, + ), Kind::Int { min, max } => ("int", None, Some(min), Some(max)), Kind::Bool => ("bool", None, None, None), - Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None), + Kind::Str { .. } | Kind::Path { .. } | Kind::FontFamily { .. } => { + ("string", None, None, None) + } + Kind::Theme => { + let mut ids: Vec<_> = crate::theme::BUILTIN + .iter() + .map(|t| t.id.to_string()) + .collect(); + ids.push(crate::theme::SYSTEM.to_string()); + ("enum", Some(ids), None, None) + } }; SettingInfo { key: self.key, kind, default: self.default.to_value(), enum_values, + value_names: None, min, max, path: matches!(self.kind, Kind::Path { .. }), @@ -201,7 +249,11 @@ pub struct SettingInfo { pub default: Value, /// Accepted values of an enum. #[serde(skip_serializing_if = "Option::is_none")] - pub enum_values: Option>, + pub enum_values: Option>, + /// Display names of enum values that have no catalog key, such as + /// imported themes, by value. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_names: Option>, /// Smallest value of an int. #[serde(skip_serializing_if = "Option::is_none")] pub min: Option, @@ -224,7 +276,7 @@ pub struct SettingInfo { pub const DEFS: &[Def] = &[ Def { key: "appearance.theme", - kind: Kind::Enum(&["lutra-dark", "lutra-light", "system"]), + kind: Kind::Theme, default: DefaultValue::Str("system"), label_key: "settings.appearance.theme.label", description_key: "settings.appearance.theme.description", @@ -238,6 +290,22 @@ pub const DEFS: &[Def] = &[ description_key: "settings.editor.fontSize.description", section: "editor", }, + Def { + key: "editor.fontFamily", + kind: Kind::FontFamily { max_len: 256 }, + default: DefaultValue::Str(""), + label_key: "settings.editor.fontFamily.label", + description_key: "settings.editor.fontFamily.description", + section: "editor", + }, + Def { + key: "editor.lineHeight", + kind: Kind::Int { min: 100, max: 300 }, + default: DefaultValue::Int(150), + label_key: "settings.editor.lineHeight.label", + description_key: "settings.editor.lineHeight.description", + section: "editor", + }, Def { key: "ui.language", kind: Kind::Enum(&["en"]), @@ -687,9 +755,31 @@ mod tests { )); } assert!(matches!( - s.set("appearance.theme", json!("dark")), + s.set("appearance.theme", json!("Dark Mode")), Err(SetError::Invalid(_)) )); + assert_eq!(s.set("appearance.theme", json!("my-import")), Ok(true)); + assert_eq!(s.get("editor.fontFamily"), Some(json!(""))); + assert_eq!(s.get("editor.lineHeight"), Some(json!(150))); + assert_eq!( + s.set("editor.fontFamily", json!("\"Fira Code\", monospace")), + Ok(true) + ); + for bad in ["a; color: red", "x{", "", "a\\b", "tab\there"] { + assert!( + matches!( + s.set("editor.fontFamily", json!(bad)), + Err(SetError::Invalid(_)) + ), + "{bad}" + ); + } + for bad in [json!(99), json!(301), json!(1.5)] { + assert!(matches!( + s.set("editor.lineHeight", bad), + Err(SetError::Invalid(_)) + )); + } assert!(matches!(s.set("x.y", json!(1)), Err(SetError::Invalid(_)))); assert_eq!(s.get("editor.fontSize"), Some(json!(16))); assert_eq!(s.reset("editor.fontSize"), Ok(true)); @@ -812,7 +902,7 @@ mod tests { "key": "appearance.theme", "type": "enum", "default": "system", - "enumValues": ["lutra-dark", "lutra-light", "system"], + "enumValues": ["lutra-dark", "lutra-light", "lutra-plum-night", "lutra-river", "lutra-paper", "lutra-reed", "system"], "labelKey": "settings.appearance.theme.label", "descriptionKey": "settings.appearance.theme.description", "section": "appearance", diff --git a/crates/engine/src/state.rs b/crates/engine/src/state.rs index e7eb628..61715c3 100644 --- a/crates/engine/src/state.rs +++ b/crates/engine/src/state.rs @@ -25,6 +25,9 @@ pub struct State { /// Whether the OS prefers a dark theme, as the frontend reported it with /// `theme.systemPreference`; `None` until then. pub system_dark: Option, + /// Themes imported from theme files (`theme.import`), loaded from + /// `/themes` at start. + pub themes: Vec, /// Where the engine stores its files; `None` for an engine without /// persistence ([`crate::Engine::new`]). pub config: Option, diff --git a/crates/engine/src/theme.rs b/crates/engine/src/theme.rs index a5f7192..36b5504 100644 --- a/crates/engine/src/theme.rs +++ b/crates/engine/src/theme.rs @@ -8,9 +8,15 @@ //! meet WCAG AA in both themes; `ui/tests/theme` checks it against the snapshot `ui/tests/theme/themes.json`, which the test //! `ui_snapshot_is_current` keeps in step with this file. //! +//! Besides the brand pair (`lutra-dark`, `lutra-light`) Lutra ships four +//! more themes from the same palette family (C9): Plum Night and River +//! (dark), Paper and Reed (light). Users can import their own as theme +//! files ([`parse_file`], format in `docs/themes.md`); the engine keeps +//! them as [`UserTheme`]s and [`resolve_with`] finds them. +//! //! The setting `appearance.theme` holds a theme id or [`SYSTEM`]. "System" //! follows the OS: the frontend reports the OS preference and -//! [`resolve`] picks the theme. +//! [`resolve`] picks the theme (always the brand pair). use std::collections::BTreeMap; @@ -30,7 +36,10 @@ pub struct Theme { /// The `appearance.theme` value that follows the OS preference. pub const SYSTEM: &str = "system"; -/// Tokens shared by every theme (fonts and sizes). +/// Tokens shared by every theme (fonts, sizes and the editor's line +/// height). The editor settings `editor.fontFamily`, `editor.fontSize` and +/// `editor.lineHeight` override `font-mono`, `font-size-editor` and +/// `line-height-editor` in the frontend. const COMMON: &[(&str, &str)] = &[ ( "font-ui", @@ -43,6 +52,7 @@ const COMMON: &[(&str, &str)] = &[ ("font-size-ui", "13px"), ("font-size-small", "12px"), ("font-size-editor", "14px"), + ("line-height-editor", "1.5"), ]; /// Syntax token names (`--lt-syntax-`) every theme defines. The @@ -249,8 +259,281 @@ pub const LIGHT: Theme = Theme { ], }; -/// Every built-in theme. -pub const BUILTIN: &[Theme] = &[DARK, LIGHT]; +/// Plum Night (dark): Deep, warm plum surfaces with a soft cream-gold accent. The banner after sunset: cosy for long evening sessions. +pub const PLUM_NIGHT: Theme = Theme { + id: "lutra-plum-night", + label_key: "theme.lutraPlumNight", + dark: true, + tokens: &[ + ("bg", "#241a22"), + ("editor-bg", "#1c1419"), + ("fg", "#f0e6dc"), + ("fg-muted", "#a8969f"), + ("border", "#3d2c38"), + ("accent", "#e6c27f"), + ("error", "#f48a78"), + ("statusbar-bg", "#2a1e27"), + ("statusbar-fg", "#c4b3bb"), + ("editor-selection-bg", "#56334a"), + ("editor-active-line-bg", "#291e27"), + ("editor-cursor", "#e6c27f"), + ("editor-gutter-bg", "#1c1419"), + ("editor-gutter-fg", "#a8969f"), + ("editor-match-bg", "#43303a"), + ("tab-active-bg", "#1c1419"), + ("tab-modified", "#e6c27f"), + ("notice-bg", "#3e2836"), + ("syntax-keyword", "#ec92bd"), + ("syntax-string", "#b6c98a"), + ("syntax-number", "#efa985"), + ("syntax-comment", "#9c8a94"), + ("syntax-variable", "#e3cdbb"), + ("syntax-function", "#ebca7d"), + ("syntax-type", "#8cc0cc"), + ("syntax-constant", "#c5a8ec"), + ("syntax-tag", "#e8907a"), + ("syntax-attribute", "#d4b98a"), + ("syntax-operator", "#c4b3bb"), + ("diag-error", "#f48a78"), + ("diag-warning", "#e8b85a"), + ("diag-info", "#9db4ea"), + ("diag-hint", "#a8969f"), + ("vcs-added", "#a6c784"), + ("vcs-modified", "#9db4ea"), + ("vcs-deleted", "#dc9890"), + ("vcs-untracked", "#e8aa6c"), + ("vcs-ignored", "#9e8e97"), + ("vcs-conflicted", "#f6788e"), + ("terminal-bg", "#1c1419"), + ("terminal-fg", "#f0e6dc"), + ("terminal-cursor", "#e6c27f"), + ("terminal-selection-bg", "#56334a"), + ("terminal-ansi-black", "#33262f"), + ("terminal-ansi-red", "#f28474"), + ("terminal-ansi-green", "#b6c98a"), + ("terminal-ansi-yellow", "#ebca7d"), + ("terminal-ansi-blue", "#98aee6"), + ("terminal-ansi-magenta", "#ec92bd"), + ("terminal-ansi-cyan", "#8cc0cc"), + ("terminal-ansi-white", "#d9cdc6"), + ("terminal-ansi-bright-black", "#a8969f"), + ("terminal-ansi-bright-red", "#f8a596"), + ("terminal-ansi-bright-green", "#cbdca6"), + ("terminal-ansi-bright-yellow", "#f4dc9a"), + ("terminal-ansi-bright-blue", "#b8c6f2"), + ("terminal-ansi-bright-magenta", "#f4b0cf"), + ("terminal-ansi-bright-cyan", "#acd6de"), + ("terminal-ansi-bright-white", "#faf3ea"), + ], +}; + +/// River (dark): Cool slate and river teal, with raspberry keywords as the family link. Calm and crisp, like the water an otter dives into. +pub const RIVER: Theme = Theme { + id: "lutra-river", + label_key: "theme.lutraRiver", + dark: true, + tokens: &[ + ("bg", "#1a2125"), + ("editor-bg", "#151b1e"), + ("fg", "#e2e8e6"), + ("fg-muted", "#8e9ca3"), + ("border", "#2c373d"), + ("accent", "#6fc6b8"), + ("error", "#f08a7a"), + ("statusbar-bg", "#1e272b"), + ("statusbar-fg", "#adbbc0"), + ("editor-selection-bg", "#28434a"), + ("editor-active-line-bg", "#1b2327"), + ("editor-cursor", "#6fc6b8"), + ("editor-gutter-bg", "#151b1e"), + ("editor-gutter-fg", "#8e9ca3"), + ("editor-match-bg", "#24393b"), + ("tab-active-bg", "#151b1e"), + ("tab-modified", "#6fc6b8"), + ("notice-bg", "#223a3c"), + ("syntax-keyword", "#e392b6"), + ("syntax-string", "#9fcb94"), + ("syntax-number", "#e8ae86"), + ("syntax-comment", "#87959c"), + ("syntax-variable", "#d2dcd9"), + ("syntax-function", "#e4cb7c"), + ("syntax-type", "#74c3d1"), + ("syntax-constant", "#b4aaea"), + ("syntax-tag", "#e6957c"), + ("syntax-attribute", "#c9bd86"), + ("syntax-operator", "#adbbc0"), + ("diag-error", "#f08a7a"), + ("diag-warning", "#e2b65c"), + ("diag-info", "#8fb6ec"), + ("diag-hint", "#8e9ca3"), + ("vcs-added", "#93c98a"), + ("vcs-modified", "#8fb6ec"), + ("vcs-deleted", "#d69a92"), + ("vcs-untracked", "#e3aa6a"), + ("vcs-ignored", "#86939a"), + ("vcs-conflicted", "#f27a90"), + ("terminal-bg", "#151b1e"), + ("terminal-fg", "#e2e8e6"), + ("terminal-cursor", "#6fc6b8"), + ("terminal-selection-bg", "#28434a"), + ("terminal-ansi-black", "#263035"), + ("terminal-ansi-red", "#ee8172"), + ("terminal-ansi-green", "#9fcb94"), + ("terminal-ansi-yellow", "#e4cb7c"), + ("terminal-ansi-blue", "#8cb0e8"), + ("terminal-ansi-magenta", "#e392b6"), + ("terminal-ansi-cyan", "#74c3d1"), + ("terminal-ansi-white", "#c6d0cd"), + ("terminal-ansi-bright-black", "#8e9ca3"), + ("terminal-ansi-bright-red", "#f6a597"), + ("terminal-ansi-bright-green", "#bfdeb2"), + ("terminal-ansi-bright-yellow", "#f0dc9c"), + ("terminal-ansi-bright-blue", "#afc6f2"), + ("terminal-ansi-bright-magenta", "#f0b0cd"), + ("terminal-ansi-bright-cyan", "#a6dbe3"), + ("terminal-ansi-bright-white", "#f3f6f5"), + ], +}; + +/// Paper (light): High-key, almost white paper with deep plum ink as the accent. Bright and airy for daylight; the quietest of the family. +pub const PAPER: Theme = Theme { + id: "lutra-paper", + label_key: "theme.lutraPaper", + dark: false, + tokens: &[ + ("bg", "#f6f5f1"), + ("editor-bg", "#fefdfb"), + ("fg", "#221d20"), + ("fg-muted", "#625b5f"), + ("border", "#e2dfd7"), + ("accent", "#83224b"), + ("error", "#ad3524"), + ("statusbar-bg", "#eeece6"), + ("statusbar-fg", "#4f474b"), + ("editor-selection-bg", "#efd9e3"), + ("editor-active-line-bg", "#f7f5f0"), + ("editor-cursor", "#83224b"), + ("editor-gutter-bg", "#fefdfb"), + ("editor-gutter-fg", "#625b5f"), + ("editor-match-bg", "#f4e3ea"), + ("tab-active-bg", "#fefdfb"), + ("tab-modified", "#83224b"), + ("notice-bg", "#f3e2e8"), + ("syntax-keyword", "#8e2856"), + ("syntax-string", "#46661f"), + ("syntax-number", "#984216"), + ("syntax-comment", "#686064"), + ("syntax-variable", "#5c3f4e"), + ("syntax-function", "#745306"), + ("syntax-type", "#1f6476"), + ("syntax-constant", "#5a44a0"), + ("syntax-tag", "#a23f27"), + ("syntax-attribute", "#645a17"), + ("syntax-operator", "#4f474b"), + ("diag-error", "#ad3524"), + ("diag-warning", "#7f5000"), + ("diag-info", "#2d58a6"), + ("diag-hint", "#625b5f"), + ("vcs-added", "#38701f"), + ("vcs-modified", "#2d58a6"), + ("vcs-deleted", "#9e4236"), + ("vcs-untracked", "#8c520a"), + ("vcs-ignored", "#6d6569"), + ("vcs-conflicted", "#a81c40"), + ("terminal-bg", "#fefdfb"), + ("terminal-fg", "#221d20"), + ("terminal-cursor", "#83224b"), + ("terminal-selection-bg", "#efd9e3"), + ("terminal-ansi-black", "#221d20"), + ("terminal-ansi-red", "#ad3524"), + ("terminal-ansi-green", "#46661f"), + ("terminal-ansi-yellow", "#745306"), + ("terminal-ansi-blue", "#2c52a2"), + ("terminal-ansi-magenta", "#8e2856"), + ("terminal-ansi-cyan", "#1f6476"), + ("terminal-ansi-white", "#e2dfd7"), + ("terminal-ansi-bright-black", "#625b5f"), + ("terminal-ansi-bright-red", "#8a2717"), + ("terminal-ansi-bright-green", "#365015"), + ("terminal-ansi-bright-yellow", "#5a4003"), + ("terminal-ansi-bright-blue", "#213c7c"), + ("terminal-ansi-bright-magenta", "#6a1a40"), + ("terminal-ansi-bright-cyan", "#174e5c"), + ("terminal-ansi-bright-white", "#f6f5f1"), + ], +}; + +/// Reed (light): Soft sand and sage surfaces with a muted pine accent. The riverbank in the afternoon: gentle on the eyes, still clearly Lutra. +pub const REED: Theme = Theme { + id: "lutra-reed", + label_key: "theme.lutraReed", + dark: false, + tokens: &[ + ("bg", "#e9e7d8"), + ("editor-bg", "#f3f2e8"), + ("fg", "#25261f"), + ("fg-muted", "#5b5a4f"), + ("border", "#d2cfbb"), + ("accent", "#3c6447"), + ("error", "#a63424"), + ("statusbar-bg", "#e1dfce"), + ("statusbar-fg", "#4a4a40"), + ("editor-selection-bg", "#d7e0cc"), + ("editor-active-line-bg", "#eceadd"), + ("editor-cursor", "#3c6447"), + ("editor-gutter-bg", "#f3f2e8"), + ("editor-gutter-fg", "#5b5a4f"), + ("editor-match-bg", "#e2e6d2"), + ("tab-active-bg", "#f3f2e8"), + ("tab-modified", "#3c6447"), + ("notice-bg", "#dde3cf"), + ("syntax-keyword", "#8c2a5a"), + ("syntax-string", "#3d6020"), + ("syntax-number", "#913f17"), + ("syntax-comment", "#625f55"), + ("syntax-variable", "#6c4433"), + ("syntax-function", "#6e5006"), + ("syntax-type", "#1d5f6e"), + ("syntax-constant", "#57439a"), + ("syntax-tag", "#9a3c26"), + ("syntax-attribute", "#5f5718"), + ("syntax-operator", "#4a4a40"), + ("diag-error", "#a63424"), + ("diag-warning", "#784c00"), + ("diag-info", "#2b549c"), + ("diag-hint", "#5b5a4f"), + ("vcs-added", "#356a1e"), + ("vcs-modified", "#2b549c"), + ("vcs-deleted", "#973f33"), + ("vcs-untracked", "#844d0a"), + ("vcs-ignored", "#615e54"), + ("vcs-conflicted", "#a11c3e"), + ("terminal-bg", "#f3f2e8"), + ("terminal-fg", "#25261f"), + ("terminal-cursor", "#3c6447"), + ("terminal-selection-bg", "#d7e0cc"), + ("terminal-ansi-black", "#25261f"), + ("terminal-ansi-red", "#a63424"), + ("terminal-ansi-green", "#3d6020"), + ("terminal-ansi-yellow", "#6e5006"), + ("terminal-ansi-blue", "#2a4f98"), + ("terminal-ansi-magenta", "#8c2a5a"), + ("terminal-ansi-cyan", "#1d5f6e"), + ("terminal-ansi-white", "#d2cfbb"), + ("terminal-ansi-bright-black", "#5b5a4f"), + ("terminal-ansi-bright-red", "#842617"), + ("terminal-ansi-bright-green", "#304b14"), + ("terminal-ansi-bright-yellow", "#553d03"), + ("terminal-ansi-bright-blue", "#203a76"), + ("terminal-ansi-bright-magenta", "#6a1c42"), + ("terminal-ansi-bright-cyan", "#164a56"), + ("terminal-ansi-bright-white", "#e9e7d8"), + ], +}; + +/// Every built-in theme, in picker order: the brand pair first, then the +/// themes of C9 (dark before light). +pub const BUILTIN: &[Theme] = &[DARK, LIGHT, PLUM_NIGHT, RIVER, PAPER, REED]; /// Looks a built-in theme up by id. pub fn by_id(id: &str) -> Option { @@ -287,18 +570,281 @@ pub fn token_map(theme: &Theme) -> BTreeMap { /// Renders a theme as a `:root { … }` rule of CSS custom properties. pub fn css_variables(theme: &Theme) -> String { + css_of(&theme.resolved()) +} + +/// Renders a resolved theme as a `:root { … }` rule of CSS custom +/// properties, `color-scheme` first. +pub fn css_of(theme: &ResolvedTheme) -> String { let mut css = String::from(":root {\n"); css.push_str(&format!( " color-scheme: {};\n", if theme.dark { "dark" } else { "light" } )); - for (name, value) in COMMON.iter().chain(theme.tokens) { - css.push_str(&format!(" --lt-{name}: {value};\n")); + for (name, value) in &theme.tokens { + css.push_str(&format!(" {name}: {value};\n")); } css.push('}'); css } +/// A theme ready to apply, built-in or imported: what `themeChanged` +/// carries. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedTheme { + /// Theme id. + pub id: String, + /// Whether the theme is dark. + pub dark: bool, + /// Every token, shared ones included, as `--lt-` → value. + pub tokens: BTreeMap, +} + +impl Theme { + /// The theme with its shared tokens, ready to apply. + pub fn resolved(&self) -> ResolvedTheme { + ResolvedTheme { + id: self.id.to_string(), + dark: self.dark, + tokens: token_map(self), + } + } +} + +/// The `lutraTheme` value of the current theme file format +/// (`docs/themes.md`). +pub const FILE_FORMAT: u64 = 1; + +/// Largest theme file that is read. +pub const MAX_FILE_SIZE: u64 = 256 * 1024; + +/// Longest theme id and display name, in bytes. +pub const MAX_ID_LEN: usize = 64; + +/// A theme imported from a theme file. Its colour tokens are exactly the +/// colour tokens of the built-in themes; fonts and sizes stay shared. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UserTheme { + /// Id, unique among built-in and imported themes. + pub id: String, + /// Display name, shown as typed. + pub name: String, + /// Whether the theme is dark. + pub dark: bool, + /// Colour tokens without the `--lt-` prefix → `#rrggbb`. + pub tokens: BTreeMap, +} + +impl UserTheme { + /// The theme with the shared tokens, ready to apply. + pub fn resolved(&self) -> ResolvedTheme { + let tokens = COMMON + .iter() + .map(|(name, value)| (format!("--lt-{name}"), (*value).to_string())) + .chain( + self.tokens + .iter() + .map(|(name, value)| (format!("--lt-{name}"), value.clone())), + ) + .collect(); + ResolvedTheme { + id: self.id.clone(), + dark: self.dark, + tokens, + } + } + + /// The theme as a theme file, in the normalised form Lutra stores. + pub fn to_file(&self) -> serde_json::Value { + serde_json::json!({ + "lutraTheme": FILE_FORMAT, + "id": self.id, + "name": self.name, + "dark": self.dark, + "tokens": self.tokens, + }) + } +} + +/// The colour token names every theme defines, in the order of [`DARK`]. +pub fn colour_tokens() -> impl Iterator { + DARK.tokens.iter().map(|(name, _)| *name) +} + +/// Whether `id` is a well-formed theme id: 1 to [`MAX_ID_LEN`] bytes of +/// lowercase ASCII letters, digits and `-`, starting with a letter. +pub fn valid_id(id: &str) -> bool { + id.len() <= MAX_ID_LEN + && id.chars().next().is_some_and(|c| c.is_ascii_lowercase()) + && id + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// Whether `id` is taken by a built-in theme or is [`SYSTEM`]. +pub fn reserved_id(id: &str) -> bool { + id == SYSTEM || by_id(id).is_some() +} + +/// Whether `value` is a `#rrggbb` colour. +fn is_hex_colour(value: &str) -> bool { + value.len() == 7 + && value.starts_with('#') + && value.chars().skip(1).all(|c| c.is_ascii_hexdigit()) +} + +/// Most token names listed in one error message. +const MAX_LISTED: usize = 8; + +/// Joins names for an error message, at most [`MAX_LISTED`] of them. +fn listing(names: &[String]) -> String { + let shown = names + .iter() + .take(MAX_LISTED) + .cloned() + .collect::>() + .join(", "); + match names.len().checked_sub(MAX_LISTED) { + Some(more) if more > 0 => format!("{shown} and {more} more"), + _ => shown, + } +} + +/// Reads a theme file (`docs/themes.md`). +/// +/// The file is untrusted. It must be a JSON object with `lutraTheme` +/// ([`FILE_FORMAT`]), `id` (see [`valid_id`], not a built-in id), `name` +/// (1 to [`MAX_ID_LEN`] bytes, no control characters), `dark` and +/// `tokens`: every colour token of the built-in themes, named with or +/// without the `--lt-` prefix, as `#rrggbb`. `description` and `author` +/// strings are allowed and ignored; any other key is refused, so a typo +/// does not pass unnoticed. Colours are stored in lowercase. +/// +/// # Errors +/// One English sentence saying what is wrong, for the user. +pub fn parse_file(text: &str) -> Result { + let value: serde_json::Value = + serde_json::from_str(text).map_err(|e| format!("the file is not valid JSON: {e}"))?; + let serde_json::Value::Object(fields) = value else { + return Err("the file must contain a JSON object".into()); + }; + for key in fields.keys() { + if ![ + "lutraTheme", + "id", + "name", + "dark", + "tokens", + "description", + "author", + ] + .contains(&key.as_str()) + { + return Err(format!("unknown key \"{key}\"")); + } + } + if fields.get("lutraTheme").and_then(serde_json::Value::as_u64) != Some(FILE_FORMAT) { + return Err(format!( + "this is not a Lutra theme file: it needs \"lutraTheme\": {FILE_FORMAT}" + )); + } + for key in ["description", "author"] { + if fields.get(key).is_some_and(|v| !v.is_string()) { + return Err(format!("\"{key}\" must be a string")); + } + } + let id = fields + .get("id") + .and_then(serde_json::Value::as_str) + .ok_or("\"id\" is missing or not a string")?; + if !valid_id(id) { + return Err(format!( + "the id \"{id}\" is not allowed: use up to {MAX_ID_LEN} lowercase letters, digits and dashes, starting with a letter" + )); + } + if reserved_id(id) { + return Err(format!( + "the id \"{id}\" belongs to a built-in theme; choose another one" + )); + } + let name = fields + .get("name") + .and_then(serde_json::Value::as_str) + .map(str::trim) + .ok_or("\"name\" is missing or not a string")?; + if name.is_empty() || name.len() > MAX_ID_LEN || name.chars().any(char::is_control) { + return Err(format!( + "\"name\" must be 1 to {MAX_ID_LEN} characters without control characters" + )); + } + let dark = fields + .get("dark") + .and_then(serde_json::Value::as_bool) + .ok_or("\"dark\" is missing or not true/false")?; + let Some(serde_json::Value::Object(raw)) = fields.get("tokens") else { + return Err("\"tokens\" is missing or not an object".into()); + }; + let mut tokens = BTreeMap::new(); + let mut unknown = Vec::new(); + for (key, value) in raw { + let name = key.strip_prefix("--lt-").unwrap_or(key); + if !colour_tokens().any(|known| known == name) { + unknown.push(key.clone()); + continue; + } + let Some(colour) = value.as_str().filter(|v| is_hex_colour(v)) else { + return Err(format!( + "the token \"{name}\" must be a colour like \"#1e1b1e\", got {value}" + )); + }; + if tokens + .insert(name.to_string(), colour.to_ascii_lowercase()) + .is_some() + { + return Err(format!("the token \"{name}\" is given twice")); + } + } + if !unknown.is_empty() { + return Err(format!("unknown tokens: {}", listing(&unknown))); + } + let missing: Vec = colour_tokens() + .filter(|name| !tokens.contains_key(*name)) + .map(str::to_string) + .collect(); + if !missing.is_empty() { + return Err(format!( + "{} tokens are missing: {}", + missing.len(), + listing(&missing) + )); + } + Ok(UserTheme { + id: id.to_string(), + name: name.to_string(), + dark, + tokens, + }) +} + +/// The theme for an `appearance.theme` value, imported themes included. +/// +/// # Parameters +/// - `setting`: a theme id or [`SYSTEM`]. +/// - `system_dark`: the OS preference, as for [`resolve`]. +/// - `imported`: the imported themes. +/// +/// Returns [`DARK`] for an id that is neither built in nor imported. +pub fn resolve_with( + setting: &str, + system_dark: Option, + imported: &[UserTheme], +) -> ResolvedTheme { + match imported.iter().find(|t| t.id == setting) { + Some(theme) => theme.resolved(), + None => resolve(setting, system_dark).resolved(), + } +} + /// The CSS for an `appearance.theme` value: the theme's variables, or for /// [`SYSTEM`] the dark theme with the light one inside a /// `prefers-color-scheme: light` media query, so the first frame follows the @@ -318,7 +864,14 @@ pub fn css_for_setting(setting: &str) -> String { /// ` diff --git a/ui/src/components/theme/themes.ts b/ui/src/components/theme/themes.ts new file mode 100644 index 0000000..8919009 --- /dev/null +++ b/ui/src/components/theme/themes.ts @@ -0,0 +1,232 @@ +/** + * The theme picker and theme import (C9 T1). + * + * - **Picker:** "Select Theme…" (`view.selectTheme`) lists the built-in + * and imported themes from `theme.list`, plus "Same as system". Moving + * the selection previews the theme live (its tokens go onto `:root` + * through `applyTheme`); Enter or a click switches to it with + * `theme.select`; Escape puts the theme in use back. An exclusive modal + * (`commands/modals.ts`). + * - **Import:** "Import Theme…" (`view.importTheme`) asks for a theme file + * (format: `docs/themes.md`) and runs `theme.import`, which stores the + * theme in Lutra's data directory and switches to it. A broken file + * gives an error toast with the engine's reason. + */ +import { defineStore } from "pinia"; +import { computed, ref } from "vue"; +import { hasMessage, t } from "../../i18n"; +import { pickFile, run } from "../../ipc"; +import { useNotificationsStore } from "../../stores/notifications"; +import { applyTheme, toResolvedTheme, type ResolvedTheme } from "../../theme"; + +/** The `appearance.theme` value that follows the OS. */ +export const SYSTEM = "system"; + +/** Most themes read from `theme.list`. */ +export const MAX_THEMES = 500; + +/** A theme as the picker lists it. */ +export interface ThemeInfo { + /** Theme id, or {@link SYSTEM}. */ + id: string; + /** Display name: catalog text for built-in themes, the file's name for imported ones. */ + name: string; + /** Whether the theme is dark; null for {@link SYSTEM}. */ + dark: boolean | null; + /** Whether Lutra ships it. */ + builtin: boolean; + /** Its tokens for the preview; null for {@link SYSTEM}. */ + theme: ResolvedTheme | null; +} + +/** + * Reads one `theme.list` entry from untrusted data. + * + * @param raw - the entry. + * @returns the theme, or null if it is malformed. + */ +export function toThemeInfo(raw: unknown): ThemeInfo | null { + const theme = toResolvedTheme(raw); + if (!theme) { + return null; + } + const { label, name, builtin } = raw as Record; + const shown = + typeof label === "string" && hasMessage(label) + ? t(label) + : typeof name === "string" && name.trim() !== "" + ? name.trim() + : theme.id; + return { id: theme.id, name: shown, dark: theme.dark, builtin: builtin === true, theme }; +} + +/** + * Reads the `theme.list` result and appends "Same as system". + * + * @param raw - the result. + * @returns the themes, or null if the result is not a list. + */ +export function toThemeList(raw: unknown): ThemeInfo[] | null { + if (!Array.isArray(raw)) { + return null; + } + const themes = (raw as unknown[]) + .slice(0, MAX_THEMES) + .map(toThemeInfo) + .filter((info): info is ThemeInfo => info !== null); + themes.push({ + id: SYSTEM, + name: t("settings.appearance.theme.value.system"), + dark: null, + builtin: true, + theme: null, + }); + return themes; +} + +/** Store of the theme picker. */ +export const useThemesStore = defineStore("themes", () => { + const notifications = useNotificationsStore(); + /** Themes in picker order; empty while closed. */ + const items = ref([]); + /** Index of the selected row. */ + const selected = ref(0); + /** Whether the picker is shown. */ + const open = ref(false); + /** Id of the theme setting when the picker opened. */ + const initialId = ref(null); + /** The theme on screen when the picker opened, to restore on Escape. */ + let initialTheme: ResolvedTheme | null = null; + + /** The selected theme, or null. */ + const current = computed(() => items.value[selected.value] ?? null); + + /** + * Shows a theme's tokens without switching to it. "Same as system" shows + * the theme in use when the picker opened. + * + * @param info - the theme. + */ + function preview(info: ThemeInfo | null): void { + const theme = info?.theme ?? initialTheme; + if (theme) { + applyTheme(theme); + } + } + + /** Opens the picker with the current theme selected. A failed load raises an error toast. */ + async function show(): Promise { + const [listed, setting, now] = await Promise.all([ + run("theme.list"), + run("settings.get", { keys: ["appearance.theme"] }), + run("theme.current"), + ]); + if (!listed.ok) { + notifications.notifyError("theme.list", listed.error); + return; + } + const list = toThemeList(listed.value); + if (!list) { + return; + } + const values = setting.ok ? (setting.value as { values?: Record } | null)?.values : undefined; + const id = typeof values?.["appearance.theme"] === "string" ? values["appearance.theme"] : null; + initialId.value = id; + initialTheme = now.ok ? toResolvedTheme(now.value) : null; + items.value = list; + selected.value = Math.max(0, list.findIndex((info) => info.id === id)); + open.value = true; + } + + /** + * Moves the selection and previews the theme there. + * + * @param delta - rows to move; clamped to the list. + */ + function move(delta: number): void { + const count = items.value.length; + if (count === 0) { + return; + } + selected.value = Math.min(count - 1, Math.max(0, selected.value + delta)); + preview(current.value); + } + + /** + * Selects a row by index and previews it. + * + * @param index - the row. + */ + function hover(index: number): void { + if (index >= 0 && index < items.value.length && index !== selected.value) { + selected.value = index; + preview(current.value); + } + } + + /** Closes the picker and puts the theme in use back. */ + function cancel(): void { + if (!open.value) { + return; + } + open.value = false; + if (initialTheme) { + applyTheme(initialTheme); + } + } + + /** + * Switches to a theme with `theme.select` and closes the picker. A + * failure puts the previous theme back and raises an error toast. + * + * @param index - the row; the selected one when absent. + */ + async function choose(index?: number): Promise { + const info = items.value[index ?? selected.value]; + if (!open.value || !info) { + return; + } + open.value = false; + const result = await run("theme.select", { id: info.id }); + if (!result.ok) { + if (initialTheme) { + applyTheme(initialTheme); + } + notifications.notifyError("theme.select", result.error); + return; + } + const theme = toResolvedTheme(result.value); + if (theme) { + applyTheme(theme); + } + } + + /** + * Asks for a theme file and imports it with `theme.import`. Cancelling + * the file dialog does nothing; success shows an info toast with the + * theme's name; a broken file shows the engine's reason. + */ + async function importFile(): Promise { + const picked = await pickFile(t("theme.import.title")); + if (!picked.ok) { + notifications.notifyError("theme.import", picked.error); + return; + } + if (picked.value === null) { + return; + } + const result = await run("theme.import", { path: picked.value }); + if (!result.ok) { + notifications.notifyError("theme.import", result.error); + return; + } + const name = (result.value as { name?: unknown } | null)?.name; + notifications.notify({ + level: "info", + messageKey: "theme.import.done", + params: { name: typeof name === "string" ? name : picked.value }, + }); + } + + return { items, selected, open, initialId, current, show, move, hover, cancel, choose, importFile }; +}); diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index c3bf973..035623c 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -49,6 +49,8 @@ "command.vcs.showStashes": "Stashes…", "command.vcs.stash": "Stash Changes…", "command.vcs.toggleBlame": "Annotate with Git Blame", + "command.view.importTheme": "Import Theme…", + "command.view.selectTheme": "Select Theme…", "command.view.toggleProjectTree": "Show or Hide Project", "command.view.toggleStructure": "Show or Hide Structure", "common.cancel": "Cancel", @@ -359,6 +361,10 @@ "settings.appearance.theme.label": "Theme", "settings.appearance.theme.value.lutraDark": "Lutra Dark", "settings.appearance.theme.value.lutraLight": "Lutra Light", + "settings.appearance.theme.value.lutraPaper": "Paper", + "settings.appearance.theme.value.lutraPlumNight": "Plum Night", + "settings.appearance.theme.value.lutraReed": "Reed", + "settings.appearance.theme.value.lutraRiver": "River", "settings.appearance.theme.value.system": "Same as system", "settings.dialog.browse": "Browse…", "settings.dialog.browseLabel": "Choose a file for {name}", @@ -380,10 +386,14 @@ "settings.editor.completion.autoPopup.label": "Show completions while typing", "settings.editor.completion.delayMs.description": "How long Lutra waits after you stop typing before it asks for completions. 0 asks at once.", "settings.editor.completion.delayMs.label": "Completion popup delay (ms)", + "settings.editor.fontFamily.description": "Font family of the editor, the terminal and other code text, as a CSS list such as \"JetBrains Mono\", monospace. Empty uses Lutra's default monospace fonts.", + "settings.editor.fontFamily.label": "Editor font", "settings.editor.fontSize.description": "Size of the text in the editor, in pixels.", "settings.editor.fontSize.label": "Editor font size", "settings.editor.hover.delayMs.description": "How long the pointer has to rest on a name before its documentation shows.", "settings.editor.hover.delayMs.label": "Documentation tooltip delay (ms)", + "settings.editor.lineHeight.description": "Height of each editor line relative to the font size. 150 means one and a half times the font size.", + "settings.editor.lineHeight.label": "Editor line height (%)", "settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.int": "Enter a whole number", "settings.error.intRange": "Enter a whole number from {min} to {max}", @@ -436,8 +446,21 @@ "terminal.tab.numbered": "Local ({n})", "terminal.tabs.label": "Terminals", "terminal.toolWindow.title": "Terminal", + "theme.import.done": "Imported the theme {name}.", + "theme.import.title": "Import Theme", "theme.lutraDark": "Lutra Dark", "theme.lutraLight": "Lutra Light", + "theme.lutraPaper": "Paper", + "theme.lutraPlumNight": "Plum Night", + "theme.lutraReed": "Reed", + "theme.lutraRiver": "River", + "theme.notification.skipped": "Skipped the theme file {file}: {reason}", + "theme.picker.current": "current", + "theme.picker.dark": "Dark", + "theme.picker.followsSystem": "Follows the light or dark preference of your operating system", + "theme.picker.imported": "{mode}, imported", + "theme.picker.light": "Light", + "theme.picker.title": "Select Theme", "vcs.branchItem.detached": "Detached HEAD at {hash}. Click for branches.", "vcs.branchItem.label": "Git branch {branch}. Click for branches.", "vcs.branches.create": "Create", diff --git a/ui/src/stores/settings.ts b/ui/src/stores/settings.ts index a7951bd..7161729 100644 --- a/ui/src/stores/settings.ts +++ b/ui/src/stores/settings.ts @@ -8,9 +8,13 @@ * ones. * - **Errors:** a refused change keeps the error per key until the value * changes or another change succeeds; the dialog shows it inline. - * - **Effects:** `editor.fontSize` drives `--lt-font-size-editor` (above - * the theme's value, see `setTokenOverride`). `appearance.theme` needs - * nothing here: the engine answers with `themeChanged`. + * - **Effects:** the editor font settings drive theme tokens above the + * theme's value (see `setTokenOverride`), live: `editor.fontSize` → + * `--lt-font-size-editor`, `editor.fontFamily` → `--lt-font-mono` (with + * {@link MONO_FALLBACK} behind it), `editor.lineHeight` → + * `--lt-line-height-editor`. `appearance.theme` needs nothing here: the + * engine answers with `themeChanged`; a change of it reloads the list, + * since an import adds a value (C9 T1). * - **Text:** labels, descriptions, section names and enum value names are * catalog keys (`settings..label`, `settings..description`, * `settings.section.`, `settings..value.`); the engine @@ -38,6 +42,8 @@ export interface SettingDef { default: SettingValue; /** Accepted values of an enum; empty otherwise. */ enumValues: string[]; + /** Display names of enum values without a catalog key (imported themes), by value. */ + valueNames: Record; /** Smallest value of an int, or null. */ min: number | null; /** Largest value of an int, or null. */ @@ -68,6 +74,54 @@ export const FONT_SIZE_KEY = "editor.fontSize"; /** Theme token the editor font size drives. */ export const FONT_SIZE_TOKEN = "--lt-font-size-editor"; +/** Key of the editor font family setting. */ +export const FONT_FAMILY_KEY = "editor.fontFamily"; + +/** Theme token the editor font family drives. */ +export const FONT_FAMILY_TOKEN = "--lt-font-mono"; + +/** Fonts behind a chosen family, as `font-mono` in `crates/engine/src/theme.rs`. */ +export const MONO_FALLBACK = 'ui-monospace, "Cascadia Code", Menlo, Consolas, monospace'; + +/** Key of the editor line height setting, in percent of the font size. */ +export const LINE_HEIGHT_KEY = "editor.lineHeight"; + +/** Theme token the editor line height drives. */ +export const LINE_HEIGHT_TOKEN = "--lt-line-height-editor"; + +/** Key of the theme setting. */ +export const THEME_KEY = "appearance.theme"; + +/** + * The token value of an editor font setting, or null for the theme's. + * + * @param key - the setting. + * @param value - its value; unchecked. + * @returns the CSS value, or null when the value is the default or unusable. + */ +export function fontTokenValue(key: string, value: SettingValue | undefined): string | null { + if (key === FONT_SIZE_KEY) { + return typeof value === "number" && Number.isInteger(value) && value > 0 ? `${String(value)}px` : null; + } + if (key === LINE_HEIGHT_KEY) { + return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 300 + ? String(value / 100) + : null; + } + if (key === FONT_FAMILY_KEY) { + const family = typeof value === "string" ? value.trim() : ""; + return family === "" || /[;{}<>\\]/.test(family) ? null : `${family}, ${MONO_FALLBACK}`; + } + return null; +} + +/** Each editor font setting and the token it drives. */ +const FONT_TOKENS: Readonly> = { + [FONT_SIZE_KEY]: FONT_SIZE_TOKEN, + [FONT_FAMILY_KEY]: FONT_FAMILY_TOKEN, + [LINE_HEIGHT_KEY]: LINE_HEIGHT_TOKEN, +}; + /** Most settings read from `settings.list`; the rest are dropped. */ export const MAX_SETTINGS = 1000; @@ -94,7 +148,7 @@ function toSettingDef(raw: unknown): SettingDef | null { return null; } const entry = raw as Record; - const { key, type, labelKey, descriptionKey, section, enumValues, min, max } = entry; + const { key, type, labelKey, descriptionKey, section, enumValues, valueNames, min, max } = entry; if ( typeof key !== "string" || typeof labelKey !== "string" || @@ -110,11 +164,20 @@ function toSettingDef(raw: unknown): SettingDef | null { if (type === "enum" && values.length === 0) { return null; } + const names: Record = {}; + if (typeof valueNames === "object" && valueNames !== null) { + for (const [value, name] of Object.entries(valueNames as Record)) { + if (typeof name === "string" && values.includes(value)) { + names[value] = clip(name); + } + } + } return { key, type, default: toScalar(entry.default), enumValues: values, + valueNames: names, min: typeof min === "number" && Number.isFinite(min) ? min : null, max: typeof max === "number" && Number.isFinite(max) ? max : null, labelKey, @@ -179,14 +242,15 @@ export function sectionLabel(id: string): string { /** * The name of an enum value: `settings..value.` with the value - * in camel case (`lutra-dark` → `lutraDark`), or the value itself. + * in camel case (`lutra-dark` → `lutraDark`), else the name the engine + * sent (an imported theme), else the value itself. * * @param def - the setting. * @param value - one of its values. */ export function valueLabel(def: SettingDef, value: string): string { const name = value.replace(/[-_.\s]+([A-Za-z0-9])/g, (_m, c: string) => c.toUpperCase()); - return textOr(`settings.${def.key}.value.${name}`, value); + return textOr(`settings.${def.key}.value.${name}`, def.valueNames[value] ?? value); } /** @@ -259,19 +323,15 @@ export const useSettingsStore = defineStore("settings", () => { /** * Applies what a value change means outside the dialog: the editor font - * size token. + * tokens. * * @param key - the changed key. */ function applyEffect(key: string): void { - if (key !== FONT_SIZE_KEY) { - return; + const token = FONT_TOKENS[key]; + if (token !== undefined) { + setTokenOverride(token, fontTokenValue(key, values[key])); } - const size = values[key]; - setTokenOverride( - FONT_SIZE_TOKEN, - typeof size === "number" && Number.isInteger(size) && size > 0 ? `${String(size)}px` : null, - ); } /** @@ -408,6 +468,10 @@ export const useSettingsStore = defineStore("settings", () => { for (const key of keys) { Reflect.deleteProperty(errors, key); } + if (keys.includes(THEME_KEY)) { + void load(); + return; + } void fetchValues(keys); } diff --git a/ui/tests/settings/fontSettings.test.ts b/ui/tests/settings/fontSettings.test.ts new file mode 100644 index 0000000..50a3d12 --- /dev/null +++ b/ui/tests/settings/fontSettings.test.ts @@ -0,0 +1,178 @@ +/** + * Tests of the editor font settings and imported theme names in the + * settings store (C9 T1): `editor.fontFamily`, `editor.fontSize` and + * `editor.lineHeight` drive their tokens live and survive a theme switch; + * imported themes show by name; a change of `appearance.theme` reloads the + * list so a newly imported theme appears. The engine is a fake behind the + * mocked Tauri `invoke` and `listen`. + */ +import { flushPromises } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +const listen = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("@tauri-apps/api/event", () => ({ listen })); + +import { + FONT_FAMILY_TOKEN, + FONT_SIZE_TOKEN, + LINE_HEIGHT_TOKEN, + MONO_FALLBACK, + fontTokenValue, + toSettingDefs, + useSettingsStore, + valueLabel, + type SettingDef, +} from "../../src/stores/settings"; +import { applyTheme, setTokenOverride } from "../../src/theme"; + +/** The theme setting as `settings.list` describes it, with or without an import. */ +function themeDef(imported: boolean): Record { + return { + key: "appearance.theme", + type: "enum", + default: "system", + enumValues: ["lutra-dark", "lutra-river", ...(imported ? ["dusk"] : []), "system"], + ...(imported ? { valueNames: { dusk: "My Dusk", ghost: "Not listed", "lutra-river": 5 } } : {}), + labelKey: "settings.appearance.theme.label", + descriptionKey: "settings.appearance.theme.description", + section: "appearance", + }; +} + +/** Whether the fake engine already imported `dusk`. */ +let imported: boolean; +/** The fake engine's values. */ +let values: Record; +/** Every `engine_execute` command, in order. */ +let commands: string[]; +/** The engine event callbacks. */ +let listeners: ((payload: unknown) => void)[]; + +const root = document.documentElement; + +beforeEach(() => { + setActivePinia(createPinia()); + imported = false; + values = { + "appearance.theme": "lutra-dark", + "editor.fontSize": 14, + "editor.fontFamily": "", + "editor.lineHeight": 150, + }; + commands = []; + listeners = []; + root.removeAttribute("style"); + listen.mockReset(); + listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { + listeners.push((payload) => { + callback({ payload }); + }); + return Promise.resolve(() => undefined); + }); + invoke.mockReset(); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd !== "engine_execute" || !args) { + return Promise.resolve(null); + } + commands.push(args.command); + switch (args.command) { + case "settings.list": + return Promise.resolve([themeDef(imported)]); + case "settings.get": { + const keys = Array.isArray(args.params.keys) ? (args.params.keys as string[]) : Object.keys(values); + return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) }); + } + default: + return Promise.resolve(null); + } + }); +}); + +afterEach(() => { + useSettingsStore().stop(); + for (const token of [FONT_SIZE_TOKEN, FONT_FAMILY_TOKEN, LINE_HEIGHT_TOKEN]) { + setTokenOverride(token, null); + } +}); + +/** + * Sends an engine event to every subscriber. + * + * @param payload - the event. + */ +async function emit(payload: unknown): Promise { + for (const listener of listeners) { + listener(payload); + } + await flushPromises(); +} + +describe("fontTokenValue", () => { + it("turns each font setting into its token value", () => { + expect(fontTokenValue("editor.fontSize", 16)).toBe("16px"); + expect(fontTokenValue("editor.fontSize", 0)).toBeNull(); + expect(fontTokenValue("editor.fontSize", "16")).toBeNull(); + expect(fontTokenValue("editor.lineHeight", 150)).toBe("1.5"); + expect(fontTokenValue("editor.lineHeight", 120)).toBe("1.2"); + expect(fontTokenValue("editor.lineHeight", 99)).toBeNull(); + expect(fontTokenValue("editor.lineHeight", 1.5)).toBeNull(); + expect(fontTokenValue("editor.fontFamily", "")).toBeNull(); + expect(fontTokenValue("editor.fontFamily", " ")).toBeNull(); + expect(fontTokenValue("editor.fontFamily", ' "Fira Code" ')).toBe(`"Fira Code", ${MONO_FALLBACK}`); + expect(fontTokenValue("editor.fontFamily", "x; color: red")).toBeNull(); + expect(fontTokenValue("editor.fontFamily", "a}b")).toBeNull(); + expect(fontTokenValue("editor.other", 3)).toBeNull(); + }); +}); + +describe("editor font settings", () => { + it("apply on load and live on settingsChanged, above any theme", async () => { + await useSettingsStore().start(); + expect(root.style.getPropertyValue(FONT_SIZE_TOKEN)).toBe("14px"); + expect(root.style.getPropertyValue(LINE_HEIGHT_TOKEN)).toBe("1.5"); + expect(root.style.getPropertyValue(FONT_FAMILY_TOKEN)).toBe(""); + + values["editor.fontFamily"] = "Iosevka"; + values["editor.lineHeight"] = 180; + await emit({ kind: "settingsChanged", keys: ["editor.fontFamily", "editor.lineHeight"] }); + expect(root.style.getPropertyValue(FONT_FAMILY_TOKEN)).toBe(`Iosevka, ${MONO_FALLBACK}`); + expect(root.style.getPropertyValue(LINE_HEIGHT_TOKEN)).toBe("1.8"); + + applyTheme({ + id: "lutra-river", + dark: true, + tokens: { [FONT_FAMILY_TOKEN]: "monospace", [LINE_HEIGHT_TOKEN]: "1.5", "--lt-bg": "#1a2125" }, + }); + expect(root.style.getPropertyValue(FONT_FAMILY_TOKEN)).toBe(`Iosevka, ${MONO_FALLBACK}`); + expect(root.style.getPropertyValue(LINE_HEIGHT_TOKEN)).toBe("1.8"); + + values["editor.fontFamily"] = ""; + await emit({ kind: "settingsChanged", keys: ["editor.fontFamily"] }); + expect(root.style.getPropertyValue(FONT_FAMILY_TOKEN)).toBe("monospace"); + }); +}); + +describe("imported themes in the settings", () => { + it("show by the name the engine sends", () => { + const [def] = toSettingDefs([themeDef(true)]) as SettingDef[]; + expect(def?.valueNames).toEqual({ dusk: "My Dusk" }); + expect(valueLabel(def as SettingDef, "dusk")).toBe("My Dusk"); + expect(valueLabel(def as SettingDef, "lutra-river")).toBe("River"); + expect(valueLabel(def as SettingDef, "unknown-id")).toBe("unknown-id"); + }); + + it("appear after an import, since a theme change reloads the list", async () => { + const store = useSettingsStore(); + await store.start(); + expect(store.defs[0]?.enumValues).not.toContain("dusk"); + imported = true; + values["appearance.theme"] = "dusk"; + await emit({ kind: "settingsChanged", keys: ["appearance.theme"] }); + expect(store.defs[0]?.enumValues).toContain("dusk"); + expect(store.values["appearance.theme"]).toBe("dusk"); + expect(commands.filter((c) => c === "settings.list")).toHaveLength(2); + }); +}); diff --git a/ui/tests/theme/ThemePicker.test.ts b/ui/tests/theme/ThemePicker.test.ts new file mode 100644 index 0000000..5439fd3 --- /dev/null +++ b/ui/tests/theme/ThemePicker.test.ts @@ -0,0 +1,279 @@ +/** + * Tests of the theme picker and theme import (C9 T1): "Select Theme…" + * lists the six built-in themes, imported ones and "Same as system" with + * the current one selected; moving previews the tokens live; Escape puts + * the theme back; Enter switches through `theme.select`; "Import Theme…" + * runs `theme.import` with the picked file and reports success or the + * engine's reason. The engine is a fake behind the mocked Tauri `invoke` + * and `listen`, answering from the `themes.json` snapshot. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import themes from "./themes.json"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); +vi.mock("@tauri-apps/api/event", () => ({ listen: () => Promise.resolve(() => undefined) })); + +import { useCommandsStore } from "../../src/commands/store"; +import { useModalsStore } from "../../src/commands/modals"; +import ThemePicker from "../../src/components/theme/ThemePicker.vue"; +import { SYSTEM, toThemeInfo, toThemeList, useThemesStore } from "../../src/components/theme/themes"; +import { useNotificationsStore } from "../../src/stores/notifications"; + +/** An imported theme as `theme.list` lists it. */ +const IMPORTED = { + id: "dusk", + label: null, + name: "My Dusk", + dark: true, + builtin: false, + tokens: { ...(themes[3]?.tokens ?? {}), "--lt-bg": "#102030" }, +}; + +/** The fake engine's `appearance.theme`. */ +let setting: string; +/** Every `engine_execute` call, in order. */ +let calls: { command: string; params: Record }[]; +/** What `pick_file` returns. */ +let picked: string | null; +/** Commands that fail, with their message. */ +let failing: Map; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components, unmounted after each test. */ +let mounted: VueWrapper[]; + +const root = document.documentElement; + +/** + * A theme of the fake engine by id. + * + * @param id - the theme id. + */ +function themeOf(id: string): { id: string; dark: boolean; tokens: Record } { + if (id === IMPORTED.id) { + return IMPORTED; + } + const found = themes.find((t) => t.id === id) ?? themes[0]; + if (!found) { + throw new Error("no themes"); + } + return found; +} + +/** + * The fake engine's answer to a command. + * + * @param command - the command id. + * @param params - its params. + */ +function answer(command: string, params: Record): unknown { + switch (command) { + case "theme.list": + return [ + ...themes.map((t) => ({ id: t.id, label: t.labelKey, name: null, dark: t.dark, builtin: true, tokens: t.tokens })), + IMPORTED, + ]; + case "settings.get": + return { values: { "appearance.theme": setting } }; + case "theme.current": + return themeOf(setting === SYSTEM ? "lutra-dark" : setting); + case "theme.select": + setting = params.id as string; + return themeOf(setting === SYSTEM ? "lutra-dark" : setting); + case "theme.import": + return { id: "dusk", name: "My Dusk", dark: true, replaced: false }; + default: + return null; + } +} + +/** Mounts the picker and starts the command store. */ +async function mountPicker(): Promise { + const wrapper = mount(ThemePicker, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useCommandsStore(pinia).start(); + await flushPromises(); + return wrapper; +} + +/** + * Presses a key on the picker's list. + * + * @param wrapper - the picker. + * @param key - the key. + */ +async function press(wrapper: VueWrapper, key: string): Promise { + await wrapper.find("[data-test=theme-picker-list]").trigger("keydown", { key }); + await flushPromises(); +} + +/** + * The ids of the listed themes. + * + * @param wrapper - the picker. + */ +function ids(wrapper: VueWrapper): string[] { + return wrapper.findAll("[data-test=theme-picker-row]").map((row) => row.attributes("data-id") ?? ""); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + setting = "lutra-river"; + calls = []; + picked = null; + failing = new Map(); + mounted = []; + root.removeAttribute("style"); + invoke.mockReset(); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([]); + } + if (cmd === "pick_file") { + return Promise.resolve(picked); + } + if (cmd === "engine_execute" && args) { + calls.push({ command: args.command, params: args.params }); + const message = failing.get(args.command); + if (message !== undefined) { + return Promise.reject(Object.assign(new Error(message), { code: "failed", message })); + } + return Promise.resolve(answer(args.command, args.params)); + } + return Promise.resolve(null); + }); +}); + +afterEach(() => { + useCommandsStore(pinia).stop(); + for (const wrapper of mounted) { + wrapper.unmount(); + } +}); + +describe("theme list helpers", () => { + it("reads theme.list defensively and names themes", () => { + expect(toThemeList("nope")).toBeNull(); + const list = toThemeList([null, { id: 1 }, ...themes.map((t) => ({ ...t, label: t.labelKey })), IMPORTED]); + expect(list?.map((t) => t.name)).toEqual([ + "Lutra Dark", + "Lutra Light", + "Plum Night", + "River", + "Paper", + "Reed", + "My Dusk", + "Same as system", + ]); + expect(list?.at(-1)).toMatchObject({ id: SYSTEM, dark: null, theme: null }); + expect(toThemeInfo({ id: "x", dark: false, name: " " })?.name).toBe("x"); + }); +}); + +describe("theme picker", () => { + it("opens from view.selectTheme with every theme and the current one selected", async () => { + const wrapper = await mountPicker(); + await useCommandsStore(pinia).execute("view.selectTheme"); + await flushPromises(); + expect(ids(wrapper)).toEqual([ + "lutra-dark", + "lutra-light", + "lutra-plum-night", + "lutra-river", + "lutra-paper", + "lutra-reed", + "dusk", + SYSTEM, + ]); + const selected = wrapper.find(".theme-picker__row--selected"); + expect(selected.attributes("data-id")).toBe("lutra-river"); + expect(selected.text()).toContain("River"); + expect(selected.text()).toContain("current"); + expect(wrapper.find('[data-id="dusk"]').text()).toContain("Dark, imported"); + expect(useModalsStore(pinia).current).toBe("themes"); + expect(document.activeElement?.getAttribute("data-test")).toBe("theme-picker-list"); + }); + + it("previews while moving and puts the theme back on Escape", async () => { + const wrapper = await mountPicker(); + await useThemesStore(pinia).show(); + await flushPromises(); + await press(wrapper, "ArrowDown"); + expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-paper").tokens["--lt-bg"]); + expect(root.style.colorScheme).toBe("light"); + await press(wrapper, "End"); + expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]); + await press(wrapper, "ArrowUp"); + expect(root.style.getPropertyValue("--lt-bg")).toBe("#102030"); + await press(wrapper, "Escape"); + expect(wrapper.find("[data-test=theme-picker]").exists()).toBe(false); + expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]); + expect(calls.some((c) => c.command === "theme.select")).toBe(false); + expect(useModalsStore(pinia).current).toBeNull(); + }); + + it("switches with Enter and with a click", async () => { + const wrapper = await mountPicker(); + await useThemesStore(pinia).show(); + await flushPromises(); + await press(wrapper, "Home"); + await press(wrapper, "ArrowDown"); + await press(wrapper, "ArrowDown"); + await press(wrapper, "Enter"); + expect(calls.filter((c) => c.command === "theme.select").map((c) => c.params)).toEqual([{ id: "lutra-plum-night" }]); + expect(wrapper.find("[data-test=theme-picker]").exists()).toBe(false); + expect(root.dataset.theme).toBe("lutra-plum-night"); + + await useThemesStore(pinia).show(); + await flushPromises(); + await wrapper.find('[data-id="lutra-reed"]').trigger("click"); + await flushPromises(); + expect(setting).toBe("lutra-reed"); + expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-reed").tokens["--lt-bg"]); + }); + + it("puts the theme back and raises a toast when switching fails", async () => { + const wrapper = await mountPicker(); + failing.set("theme.select", "settings cannot be saved"); + await useThemesStore(pinia).show(); + await flushPromises(); + await press(wrapper, "ArrowDown"); + await press(wrapper, "Enter"); + expect(root.style.getPropertyValue("--lt-bg")).toBe(themeOf("lutra-river").tokens["--lt-bg"]); + expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("settings cannot be saved"); + }); +}); + +describe("theme import", () => { + it("imports the picked file and confirms it", async () => { + await mountPicker(); + picked = "C:/themes/dusk.json"; + await useCommandsStore(pinia).execute("view.importTheme"); + await flushPromises(); + expect(calls.find((c) => c.command === "theme.import")?.params).toEqual({ path: "C:/themes/dusk.json" }); + expect(useNotificationsStore(pinia).toasts.at(-1)).toMatchObject({ level: "info", text: "Imported the theme My Dusk." }); + }); + + it("does nothing when the file dialog is cancelled", async () => { + await mountPicker(); + await useThemesStore(pinia).importFile(); + await flushPromises(); + expect(calls.filter((c) => c.command.startsWith("theme."))).toEqual([]); + expect(useNotificationsStore(pinia).toasts).toEqual([]); + }); + + it("shows the reason of a broken file", async () => { + await mountPicker(); + picked = "C:/themes/bad.json"; + failing.set("theme.import", 'cannot import the theme C:/themes/bad.json: 59 tokens are missing: bg, editor-bg'); + await useThemesStore(pinia).importFile(); + await flushPromises(); + const toast = useNotificationsStore(pinia).toasts.at(-1); + expect(toast?.level).toBe("error"); + expect(toast?.text).toContain("59 tokens are missing"); + }); +}); diff --git a/ui/tests/theme/contrast.test.ts b/ui/tests/theme/contrast.test.ts index a226212..1dba8a6 100644 --- a/ui/tests/theme/contrast.test.ts +++ b/ui/tests/theme/contrast.test.ts @@ -106,21 +106,24 @@ const KIND_PAIRS: [string, string, number][] = [...new Set(Object.values(KIND_CO /** ANSI colour names, as in `TERMINAL_TOKENS` in `theme.rs`. */ const ANSI = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"] as const; -/** ANSI tokens that may blend into the background, per theme id. */ -const TERMINAL_EXEMPT: Record = { - "lutra-dark": ["terminal-ansi-black"], - "lutra-light": ["terminal-ansi-white", "terminal-ansi-bright-white"], -}; +/** + * ANSI tokens that may blend into the background: black in dark themes, + * white and bright white in light ones. + */ +const TERMINAL_EXEMPT = { + dark: ["terminal-ansi-black"], + light: ["terminal-ansi-white", "terminal-ansi-bright-white"], +} as const; /** * The terminal's pairs for one theme: text and selection, the cursor, and * every ANSI colour (normal and bright) that is not exempt. * - * @param id - the theme id. + * @param dark - whether the theme is dark. * @returns foreground token, background token and minimum ratio. */ -function terminalPairs(id: string): [string, string, number][] { - const exempt = TERMINAL_EXEMPT[id] ?? []; +function terminalPairs(dark: boolean): [string, string, number][] { + const exempt: readonly string[] = TERMINAL_EXEMPT[dark ? "dark" : "light"]; const ansi = ANSI.flatMap((name) => [`terminal-ansi-${name}`, `terminal-ansi-bright-${name}`]).filter( (name) => !exempt.includes(name), ); @@ -162,6 +165,27 @@ export function contrast(a: string, b: string): number { return (hi + 0.05) / (lo + 0.05); } +describe("built-in themes", () => { + it("are the brand pair and the four C9 themes, two of each kind added", () => { + expect(themes.map((theme) => theme.id)).toEqual([ + "lutra-dark", + "lutra-light", + "lutra-plum-night", + "lutra-river", + "lutra-paper", + "lutra-reed", + ]); + expect(themes.filter((theme) => theme.dark)).toHaveLength(3); + }); + + it("all define the same tokens", () => { + const names = (tokens: Record): string[] => Object.keys(tokens).sort(); + for (const theme of themes) { + expect(names(theme.tokens)).toEqual(names(themes[0]?.tokens ?? {})); + } + }); +}); + describe("contrast helper", () => { it("matches the WCAG extremes", () => { expect(contrast("#000000", "#ffffff")).toBeCloseTo(21, 5); @@ -203,7 +227,7 @@ describe.each(themes)("theme $id", (theme) => { expect(defined).toHaveLength(ANSI.length * 2); }); - it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...TAB_STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => { + it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...TAB_STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.dark)])("%s on %s reaches %d:1", (fg, bg, min) => { expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min); }); }); diff --git a/ui/tests/theme/themes.json b/ui/tests/theme/themes.json index b189c68..86763c3 100644 --- a/ui/tests/theme/themes.json +++ b/ui/tests/theme/themes.json @@ -26,6 +26,7 @@ "--lt-font-size-small": "12px", "--lt-font-size-ui": "13px", "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", "--lt-notice-bg": "#382632", "--lt-statusbar-bg": "#231f23", "--lt-statusbar-fg": "#bdb3b8", @@ -97,6 +98,7 @@ "--lt-font-size-small": "12px", "--lt-font-size-ui": "13px", "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", "--lt-notice-bg": "#eedcdc", "--lt-statusbar-bg": "#ebe5d5", "--lt-statusbar-fg": "#554c50", @@ -140,5 +142,293 @@ "--lt-vcs-modified": "#2f5aa8", "--lt-vcs-untracked": "#93560c" } + }, + { + "dark": true, + "id": "lutra-plum-night", + "labelKey": "theme.lutraPlumNight", + "tokens": { + "--lt-accent": "#e6c27f", + "--lt-bg": "#241a22", + "--lt-border": "#3d2c38", + "--lt-diag-error": "#f48a78", + "--lt-diag-hint": "#a8969f", + "--lt-diag-info": "#9db4ea", + "--lt-diag-warning": "#e8b85a", + "--lt-editor-active-line-bg": "#291e27", + "--lt-editor-bg": "#1c1419", + "--lt-editor-cursor": "#e6c27f", + "--lt-editor-gutter-bg": "#1c1419", + "--lt-editor-gutter-fg": "#a8969f", + "--lt-editor-match-bg": "#43303a", + "--lt-editor-selection-bg": "#56334a", + "--lt-error": "#f48a78", + "--lt-fg": "#f0e6dc", + "--lt-fg-muted": "#a8969f", + "--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace", + "--lt-font-size-editor": "14px", + "--lt-font-size-small": "12px", + "--lt-font-size-ui": "13px", + "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", + "--lt-notice-bg": "#3e2836", + "--lt-statusbar-bg": "#2a1e27", + "--lt-statusbar-fg": "#c4b3bb", + "--lt-syntax-attribute": "#d4b98a", + "--lt-syntax-comment": "#9c8a94", + "--lt-syntax-constant": "#c5a8ec", + "--lt-syntax-function": "#ebca7d", + "--lt-syntax-keyword": "#ec92bd", + "--lt-syntax-number": "#efa985", + "--lt-syntax-operator": "#c4b3bb", + "--lt-syntax-string": "#b6c98a", + "--lt-syntax-tag": "#e8907a", + "--lt-syntax-type": "#8cc0cc", + "--lt-syntax-variable": "#e3cdbb", + "--lt-tab-active-bg": "#1c1419", + "--lt-tab-modified": "#e6c27f", + "--lt-terminal-ansi-black": "#33262f", + "--lt-terminal-ansi-blue": "#98aee6", + "--lt-terminal-ansi-bright-black": "#a8969f", + "--lt-terminal-ansi-bright-blue": "#b8c6f2", + "--lt-terminal-ansi-bright-cyan": "#acd6de", + "--lt-terminal-ansi-bright-green": "#cbdca6", + "--lt-terminal-ansi-bright-magenta": "#f4b0cf", + "--lt-terminal-ansi-bright-red": "#f8a596", + "--lt-terminal-ansi-bright-white": "#faf3ea", + "--lt-terminal-ansi-bright-yellow": "#f4dc9a", + "--lt-terminal-ansi-cyan": "#8cc0cc", + "--lt-terminal-ansi-green": "#b6c98a", + "--lt-terminal-ansi-magenta": "#ec92bd", + "--lt-terminal-ansi-red": "#f28474", + "--lt-terminal-ansi-white": "#d9cdc6", + "--lt-terminal-ansi-yellow": "#ebca7d", + "--lt-terminal-bg": "#1c1419", + "--lt-terminal-cursor": "#e6c27f", + "--lt-terminal-fg": "#f0e6dc", + "--lt-terminal-selection-bg": "#56334a", + "--lt-vcs-added": "#a6c784", + "--lt-vcs-conflicted": "#f6788e", + "--lt-vcs-deleted": "#dc9890", + "--lt-vcs-ignored": "#9e8e97", + "--lt-vcs-modified": "#9db4ea", + "--lt-vcs-untracked": "#e8aa6c" + } + }, + { + "dark": true, + "id": "lutra-river", + "labelKey": "theme.lutraRiver", + "tokens": { + "--lt-accent": "#6fc6b8", + "--lt-bg": "#1a2125", + "--lt-border": "#2c373d", + "--lt-diag-error": "#f08a7a", + "--lt-diag-hint": "#8e9ca3", + "--lt-diag-info": "#8fb6ec", + "--lt-diag-warning": "#e2b65c", + "--lt-editor-active-line-bg": "#1b2327", + "--lt-editor-bg": "#151b1e", + "--lt-editor-cursor": "#6fc6b8", + "--lt-editor-gutter-bg": "#151b1e", + "--lt-editor-gutter-fg": "#8e9ca3", + "--lt-editor-match-bg": "#24393b", + "--lt-editor-selection-bg": "#28434a", + "--lt-error": "#f08a7a", + "--lt-fg": "#e2e8e6", + "--lt-fg-muted": "#8e9ca3", + "--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace", + "--lt-font-size-editor": "14px", + "--lt-font-size-small": "12px", + "--lt-font-size-ui": "13px", + "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", + "--lt-notice-bg": "#223a3c", + "--lt-statusbar-bg": "#1e272b", + "--lt-statusbar-fg": "#adbbc0", + "--lt-syntax-attribute": "#c9bd86", + "--lt-syntax-comment": "#87959c", + "--lt-syntax-constant": "#b4aaea", + "--lt-syntax-function": "#e4cb7c", + "--lt-syntax-keyword": "#e392b6", + "--lt-syntax-number": "#e8ae86", + "--lt-syntax-operator": "#adbbc0", + "--lt-syntax-string": "#9fcb94", + "--lt-syntax-tag": "#e6957c", + "--lt-syntax-type": "#74c3d1", + "--lt-syntax-variable": "#d2dcd9", + "--lt-tab-active-bg": "#151b1e", + "--lt-tab-modified": "#6fc6b8", + "--lt-terminal-ansi-black": "#263035", + "--lt-terminal-ansi-blue": "#8cb0e8", + "--lt-terminal-ansi-bright-black": "#8e9ca3", + "--lt-terminal-ansi-bright-blue": "#afc6f2", + "--lt-terminal-ansi-bright-cyan": "#a6dbe3", + "--lt-terminal-ansi-bright-green": "#bfdeb2", + "--lt-terminal-ansi-bright-magenta": "#f0b0cd", + "--lt-terminal-ansi-bright-red": "#f6a597", + "--lt-terminal-ansi-bright-white": "#f3f6f5", + "--lt-terminal-ansi-bright-yellow": "#f0dc9c", + "--lt-terminal-ansi-cyan": "#74c3d1", + "--lt-terminal-ansi-green": "#9fcb94", + "--lt-terminal-ansi-magenta": "#e392b6", + "--lt-terminal-ansi-red": "#ee8172", + "--lt-terminal-ansi-white": "#c6d0cd", + "--lt-terminal-ansi-yellow": "#e4cb7c", + "--lt-terminal-bg": "#151b1e", + "--lt-terminal-cursor": "#6fc6b8", + "--lt-terminal-fg": "#e2e8e6", + "--lt-terminal-selection-bg": "#28434a", + "--lt-vcs-added": "#93c98a", + "--lt-vcs-conflicted": "#f27a90", + "--lt-vcs-deleted": "#d69a92", + "--lt-vcs-ignored": "#86939a", + "--lt-vcs-modified": "#8fb6ec", + "--lt-vcs-untracked": "#e3aa6a" + } + }, + { + "dark": false, + "id": "lutra-paper", + "labelKey": "theme.lutraPaper", + "tokens": { + "--lt-accent": "#83224b", + "--lt-bg": "#f6f5f1", + "--lt-border": "#e2dfd7", + "--lt-diag-error": "#ad3524", + "--lt-diag-hint": "#625b5f", + "--lt-diag-info": "#2d58a6", + "--lt-diag-warning": "#7f5000", + "--lt-editor-active-line-bg": "#f7f5f0", + "--lt-editor-bg": "#fefdfb", + "--lt-editor-cursor": "#83224b", + "--lt-editor-gutter-bg": "#fefdfb", + "--lt-editor-gutter-fg": "#625b5f", + "--lt-editor-match-bg": "#f4e3ea", + "--lt-editor-selection-bg": "#efd9e3", + "--lt-error": "#ad3524", + "--lt-fg": "#221d20", + "--lt-fg-muted": "#625b5f", + "--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace", + "--lt-font-size-editor": "14px", + "--lt-font-size-small": "12px", + "--lt-font-size-ui": "13px", + "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", + "--lt-notice-bg": "#f3e2e8", + "--lt-statusbar-bg": "#eeece6", + "--lt-statusbar-fg": "#4f474b", + "--lt-syntax-attribute": "#645a17", + "--lt-syntax-comment": "#686064", + "--lt-syntax-constant": "#5a44a0", + "--lt-syntax-function": "#745306", + "--lt-syntax-keyword": "#8e2856", + "--lt-syntax-number": "#984216", + "--lt-syntax-operator": "#4f474b", + "--lt-syntax-string": "#46661f", + "--lt-syntax-tag": "#a23f27", + "--lt-syntax-type": "#1f6476", + "--lt-syntax-variable": "#5c3f4e", + "--lt-tab-active-bg": "#fefdfb", + "--lt-tab-modified": "#83224b", + "--lt-terminal-ansi-black": "#221d20", + "--lt-terminal-ansi-blue": "#2c52a2", + "--lt-terminal-ansi-bright-black": "#625b5f", + "--lt-terminal-ansi-bright-blue": "#213c7c", + "--lt-terminal-ansi-bright-cyan": "#174e5c", + "--lt-terminal-ansi-bright-green": "#365015", + "--lt-terminal-ansi-bright-magenta": "#6a1a40", + "--lt-terminal-ansi-bright-red": "#8a2717", + "--lt-terminal-ansi-bright-white": "#f6f5f1", + "--lt-terminal-ansi-bright-yellow": "#5a4003", + "--lt-terminal-ansi-cyan": "#1f6476", + "--lt-terminal-ansi-green": "#46661f", + "--lt-terminal-ansi-magenta": "#8e2856", + "--lt-terminal-ansi-red": "#ad3524", + "--lt-terminal-ansi-white": "#e2dfd7", + "--lt-terminal-ansi-yellow": "#745306", + "--lt-terminal-bg": "#fefdfb", + "--lt-terminal-cursor": "#83224b", + "--lt-terminal-fg": "#221d20", + "--lt-terminal-selection-bg": "#efd9e3", + "--lt-vcs-added": "#38701f", + "--lt-vcs-conflicted": "#a81c40", + "--lt-vcs-deleted": "#9e4236", + "--lt-vcs-ignored": "#6d6569", + "--lt-vcs-modified": "#2d58a6", + "--lt-vcs-untracked": "#8c520a" + } + }, + { + "dark": false, + "id": "lutra-reed", + "labelKey": "theme.lutraReed", + "tokens": { + "--lt-accent": "#3c6447", + "--lt-bg": "#e9e7d8", + "--lt-border": "#d2cfbb", + "--lt-diag-error": "#a63424", + "--lt-diag-hint": "#5b5a4f", + "--lt-diag-info": "#2b549c", + "--lt-diag-warning": "#784c00", + "--lt-editor-active-line-bg": "#eceadd", + "--lt-editor-bg": "#f3f2e8", + "--lt-editor-cursor": "#3c6447", + "--lt-editor-gutter-bg": "#f3f2e8", + "--lt-editor-gutter-fg": "#5b5a4f", + "--lt-editor-match-bg": "#e2e6d2", + "--lt-editor-selection-bg": "#d7e0cc", + "--lt-error": "#a63424", + "--lt-fg": "#25261f", + "--lt-fg-muted": "#5b5a4f", + "--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace", + "--lt-font-size-editor": "14px", + "--lt-font-size-small": "12px", + "--lt-font-size-ui": "13px", + "--lt-font-ui": "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", + "--lt-line-height-editor": "1.5", + "--lt-notice-bg": "#dde3cf", + "--lt-statusbar-bg": "#e1dfce", + "--lt-statusbar-fg": "#4a4a40", + "--lt-syntax-attribute": "#5f5718", + "--lt-syntax-comment": "#625f55", + "--lt-syntax-constant": "#57439a", + "--lt-syntax-function": "#6e5006", + "--lt-syntax-keyword": "#8c2a5a", + "--lt-syntax-number": "#913f17", + "--lt-syntax-operator": "#4a4a40", + "--lt-syntax-string": "#3d6020", + "--lt-syntax-tag": "#9a3c26", + "--lt-syntax-type": "#1d5f6e", + "--lt-syntax-variable": "#6c4433", + "--lt-tab-active-bg": "#f3f2e8", + "--lt-tab-modified": "#3c6447", + "--lt-terminal-ansi-black": "#25261f", + "--lt-terminal-ansi-blue": "#2a4f98", + "--lt-terminal-ansi-bright-black": "#5b5a4f", + "--lt-terminal-ansi-bright-blue": "#203a76", + "--lt-terminal-ansi-bright-cyan": "#164a56", + "--lt-terminal-ansi-bright-green": "#304b14", + "--lt-terminal-ansi-bright-magenta": "#6a1c42", + "--lt-terminal-ansi-bright-red": "#842617", + "--lt-terminal-ansi-bright-white": "#e9e7d8", + "--lt-terminal-ansi-bright-yellow": "#553d03", + "--lt-terminal-ansi-cyan": "#1d5f6e", + "--lt-terminal-ansi-green": "#3d6020", + "--lt-terminal-ansi-magenta": "#8c2a5a", + "--lt-terminal-ansi-red": "#a63424", + "--lt-terminal-ansi-white": "#d2cfbb", + "--lt-terminal-ansi-yellow": "#6e5006", + "--lt-terminal-bg": "#f3f2e8", + "--lt-terminal-cursor": "#3c6447", + "--lt-terminal-fg": "#25261f", + "--lt-terminal-selection-bg": "#d7e0cc", + "--lt-vcs-added": "#356a1e", + "--lt-vcs-conflicted": "#a11c3e", + "--lt-vcs-deleted": "#973f33", + "--lt-vcs-ignored": "#615e54", + "--lt-vcs-modified": "#2b549c", + "--lt-vcs-untracked": "#844d0a" + } } ]