M1.10: light theme, live theme switching, editor tokens
- theme::LIGHT next to DARK with the 10 new tokens (editor selection, active line, cursor, gutter, match, font size, tab active/modified, notice); light fg-muted, accent and error darkened for WCAG AA - theme.list, theme.systemPreference, themeChanged event when the resolved theme changes (settings.set/reset appearance.theme, or the OS preference in system mode) - desktop init script and window background from the stored setting; system mode uses a prefers-color-scheme media query for the first frame - ui/src/theme.ts applies tokens to :root and color-scheme live; editor, tabs and notice drop their var() fallbacks - Vitest WCAG AA contrast check against a Rust-maintained snapshot, DOM tests, headless control-channel test - docs: architecture Themes, parity rows, ui-parity, gaps, roadmaps Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1ab448de4d
commit
cde6e119c6
29 changed files with 1192 additions and 72 deletions
|
|
@ -6,6 +6,7 @@ mod file;
|
|||
mod params;
|
||||
mod project;
|
||||
mod settings;
|
||||
pub mod theme;
|
||||
|
||||
use crate::{EngineError, Registry};
|
||||
|
||||
|
|
@ -30,5 +31,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(settings::Get))?;
|
||||
registry.register(Box::new(settings::Set))?;
|
||||
registry.register(Box::new(settings::Reset))?;
|
||||
registry.register(Box::new(theme::List))?;
|
||||
registry.register(Box::new(theme::SystemPreference))?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use serde::Deserialize;
|
|||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::cmd::params::parse;
|
||||
use crate::cmd::theme;
|
||||
use crate::settings::{self, DEFS, SetError};
|
||||
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
|
||||
|
||||
|
|
@ -96,11 +97,12 @@ impl Command for Set {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let id = self.spec().id;
|
||||
let p: SetParams = parse(id, params)?;
|
||||
let before = theme::resolved(state);
|
||||
let changed = state
|
||||
.settings
|
||||
.set(&p.key, p.value)
|
||||
.map_err(|e| set_error(id, e))?;
|
||||
finish(state, &p.key, changed)
|
||||
finish(state, &p.key, changed, before)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -129,8 +131,9 @@ impl Command for Reset {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let id = self.spec().id;
|
||||
let p: ResetParams = parse(id, params)?;
|
||||
let before = theme::resolved(state);
|
||||
let changed = state.settings.reset(&p.key).map_err(|e| set_error(id, e))?;
|
||||
finish(state, &p.key, changed)
|
||||
finish(state, &p.key, changed, before)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -144,12 +147,19 @@ fn set_error(command: &str, error: SetError) -> EngineError {
|
|||
}
|
||||
}
|
||||
|
||||
/// Emits `settingsChanged` if the value changed and returns `{ value }`.
|
||||
fn finish(state: &mut State, key: &str, changed: bool) -> Result<Outcome, EngineError> {
|
||||
/// Emits `settingsChanged` if the value changed, then `themeChanged` if the
|
||||
/// resolved theme is no longer `before`, and returns `{ value }`.
|
||||
fn finish(
|
||||
state: &mut State,
|
||||
key: &str,
|
||||
changed: bool,
|
||||
before: crate::theme::Theme,
|
||||
) -> Result<Outcome, EngineError> {
|
||||
if changed {
|
||||
state.emit(Event::SettingsChanged {
|
||||
keys: vec![key.to_string()],
|
||||
});
|
||||
theme::emit_if_changed(state, before);
|
||||
}
|
||||
let value = state
|
||||
.settings
|
||||
|
|
|
|||
102
crates/engine/src/cmd/theme.rs
Normal file
102
crates/engine/src/cmd/theme.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
//! Theme commands: `theme.list` and `theme.systemPreference`. Switching
|
||||
//! themes goes through `settings.set appearance.theme`; whenever the
|
||||
//! resolved theme changes, `themeChanged` carries its tokens.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::params::parse;
|
||||
use crate::theme::{self, BUILTIN, Theme};
|
||||
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
|
||||
|
||||
/// The setting that selects the theme.
|
||||
pub const SETTING: &str = "appearance.theme";
|
||||
|
||||
/// The theme the current settings and OS preference resolve to.
|
||||
pub fn resolved(state: &State) -> Theme {
|
||||
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)
|
||||
}
|
||||
|
||||
/// The `themeChanged` event for a theme.
|
||||
pub fn changed_event(theme: &Theme) -> Event {
|
||||
Event::ThemeChanged {
|
||||
id: theme.id.to_string(),
|
||||
dark: theme.dark,
|
||||
tokens: theme::token_map(theme),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits `themeChanged` if the resolved theme is no longer `before`.
|
||||
pub fn emit_if_changed(state: &mut State, before: Theme) {
|
||||
let now = resolved(state);
|
||||
if now != before {
|
||||
state.emit(changed_event(&now));
|
||||
}
|
||||
}
|
||||
|
||||
/// `theme.list`: the built-in themes.
|
||||
pub struct List;
|
||||
|
||||
impl Command for List {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "theme.list",
|
||||
label: "List Themes",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns [{ id, label, dark }], label is a message-catalog key",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
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)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `theme.systemPreference`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PreferenceParams {
|
||||
/// Whether the OS prefers a dark theme.
|
||||
dark: bool,
|
||||
}
|
||||
|
||||
/// `theme.systemPreference`: the frontend reports the OS colour preference;
|
||||
/// in "system" mode a change of it switches the theme.
|
||||
pub struct SystemPreference;
|
||||
|
||||
impl Command for SystemPreference {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "theme.systemPreference",
|
||||
label: "Report System Theme",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ dark: bool }; returns the resolved theme { id, dark, tokens }; emits themeChanged when it changes",
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let p: PreferenceParams = parse(self.spec().id, params)?;
|
||||
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)))
|
||||
}
|
||||
}
|
||||
|
|
@ -288,6 +288,8 @@ mod tests {
|
|||
"settings.reset",
|
||||
"settings.set",
|
||||
"test.disabled",
|
||||
"theme.list",
|
||||
"theme.systemPreference",
|
||||
]
|
||||
);
|
||||
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@
|
|||
//! Serialised as `{"kind": "<camelCase variant>", ...fields in camelCase}`.
|
||||
//! Paths are project-relative with `/` separators, the root is `""`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
|
|
@ -83,6 +85,17 @@ pub enum Event {
|
|||
/// The changed keys.
|
||||
keys: Vec<String>,
|
||||
},
|
||||
/// The resolved theme changed, through `appearance.theme` or, in
|
||||
/// "system" mode, the OS preference. The frontend writes the tokens onto
|
||||
/// `:root` and sets `color-scheme`.
|
||||
ThemeChanged {
|
||||
/// Theme id, e.g. `lutra-light`.
|
||||
id: String,
|
||||
/// Whether the theme is dark.
|
||||
dark: bool,
|
||||
/// Every token as `--lt-<name>` → CSS value.
|
||||
tokens: BTreeMap<String, String>,
|
||||
},
|
||||
/// A message for the user, shown as a toast.
|
||||
Notification {
|
||||
/// Unique id of this notification, for dismissing it.
|
||||
|
|
@ -166,4 +179,17 @@ mod tests {
|
|||
json!({"kind": "settingsChanged", "keys": ["editor.fontSize"]})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_changed_shape() {
|
||||
let e = Event::ThemeChanged {
|
||||
id: "lutra-light".into(),
|
||||
dark: false,
|
||||
tokens: [("--lt-bg".to_string(), "#f4f1ec".to_string())].into(),
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(e).unwrap(),
|
||||
json!({"kind": "themeChanged", "id": "lutra-light", "dark": false, "tokens": {"--lt-bg": "#f4f1ec"}})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@ pub struct State {
|
|||
pub buffers: Buffers,
|
||||
/// Settings, saved to the config directory when the engine has one.
|
||||
pub settings: Settings,
|
||||
/// Whether the OS prefers a dark theme, as the frontend reported it with
|
||||
/// `theme.systemPreference`; `None` until then.
|
||||
pub system_dark: Option<bool>,
|
||||
/// Where the engine stores its files; `None` for an engine without
|
||||
/// persistence ([`crate::Engine::new`]).
|
||||
pub config: Option<EngineConfig>,
|
||||
|
|
|
|||
|
|
@ -2,21 +2,33 @@
|
|||
//!
|
||||
//! Themes are defined here in Rust and rendered as CSS custom properties
|
||||
//! (`--lt-<token>`). Frontend components use only `var(--lt-…)`. The palettes
|
||||
//! are Lutra's own: warm otter browns with a copper accent.
|
||||
//! are Lutra's own: warm otter browns with a copper accent. Text and
|
||||
//! background pairs 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.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// A named set of token values.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Theme {
|
||||
/// Stable id used in settings, e.g. `lutra-dark`.
|
||||
pub id: &'static str,
|
||||
/// Display name.
|
||||
pub name: &'static str,
|
||||
/// Message-catalog key of the display name.
|
||||
pub label_key: &'static str,
|
||||
/// Whether the theme is dark, for the window chrome and `color-scheme`.
|
||||
pub dark: bool,
|
||||
/// Token names (without the `--lt-` prefix) and CSS values.
|
||||
pub tokens: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
/// The `appearance.theme` value that follows the OS preference.
|
||||
pub const SYSTEM: &str = "system";
|
||||
|
||||
/// Tokens shared by every theme (fonts and sizes).
|
||||
const COMMON: &[(&str, &str)] = &[
|
||||
(
|
||||
|
|
@ -29,12 +41,13 @@ const COMMON: &[(&str, &str)] = &[
|
|||
),
|
||||
("font-size-ui", "13px"),
|
||||
("font-size-small", "12px"),
|
||||
("font-size-editor", "14px"),
|
||||
];
|
||||
|
||||
/// The default dark theme.
|
||||
pub const DARK: Theme = Theme {
|
||||
id: "lutra-dark",
|
||||
name: "Lutra Dark",
|
||||
label_key: "theme.lutraDark",
|
||||
dark: true,
|
||||
tokens: &[
|
||||
("bg", "#1f1d1b"),
|
||||
|
|
@ -46,24 +59,42 @@ pub const DARK: Theme = Theme {
|
|||
("error", "#ef7b6c"),
|
||||
("statusbar-bg", "#24211f"),
|
||||
("statusbar-fg", "#b8afa6"),
|
||||
("editor-selection-bg", "#513f2c"),
|
||||
("editor-active-line-bg", "#232221"),
|
||||
("editor-cursor", "#d39a5c"),
|
||||
("editor-gutter-bg", "#191817"),
|
||||
("editor-gutter-fg", "#9a928a"),
|
||||
("editor-match-bg", "#3a2f23"),
|
||||
("tab-active-bg", "#191817"),
|
||||
("tab-modified", "#d39a5c"),
|
||||
("notice-bg", "#3a3025"),
|
||||
],
|
||||
};
|
||||
|
||||
/// The light theme.
|
||||
pub const LIGHT: Theme = Theme {
|
||||
id: "lutra-light",
|
||||
name: "Lutra Light",
|
||||
label_key: "theme.lutraLight",
|
||||
dark: false,
|
||||
tokens: &[
|
||||
("bg", "#f4f1ec"),
|
||||
("editor-bg", "#fbfaf8"),
|
||||
("fg", "#2a2622"),
|
||||
("fg-muted", "#7a7168"),
|
||||
("fg-muted", "#6b625a"),
|
||||
("border", "#ddd6cd"),
|
||||
("accent", "#a8662a"),
|
||||
("error", "#c2412f"),
|
||||
("accent", "#965a22"),
|
||||
("error", "#b23a29"),
|
||||
("statusbar-bg", "#ece7e0"),
|
||||
("statusbar-fg", "#5a5149"),
|
||||
("editor-selection-bg", "#e5d7c9"),
|
||||
("editor-active-line-bg", "#f1efed"),
|
||||
("editor-cursor", "#965a22"),
|
||||
("editor-gutter-bg", "#fbfaf8"),
|
||||
("editor-gutter-fg", "#6b625a"),
|
||||
("editor-match-bg", "#ece2d8"),
|
||||
("tab-active-bg", "#fbfaf8"),
|
||||
("tab-modified", "#965a22"),
|
||||
("notice-bg", "#e9dfd4"),
|
||||
],
|
||||
};
|
||||
|
||||
|
|
@ -75,6 +106,34 @@ pub fn by_id(id: &str) -> Option<Theme> {
|
|||
BUILTIN.iter().copied().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// The theme for an `appearance.theme` value.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `setting`: a theme id or [`SYSTEM`].
|
||||
/// - `system_dark`: the OS preference; `None` while the frontend has not
|
||||
/// reported it, which counts as dark.
|
||||
///
|
||||
/// Returns [`DARK`] for an unknown id.
|
||||
pub fn resolve(setting: &str, system_dark: Option<bool>) -> Theme {
|
||||
if setting == SYSTEM {
|
||||
return if system_dark.unwrap_or(true) {
|
||||
DARK
|
||||
} else {
|
||||
LIGHT
|
||||
};
|
||||
}
|
||||
by_id(setting).unwrap_or(DARK)
|
||||
}
|
||||
|
||||
/// Every token of a theme, shared ones included, as `--lt-<name>` → value.
|
||||
pub fn token_map(theme: &Theme) -> BTreeMap<String, String> {
|
||||
COMMON
|
||||
.iter()
|
||||
.chain(theme.tokens)
|
||||
.map(|(name, value)| (format!("--lt-{name}"), (*value).to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Renders a theme as a `:root { … }` rule of CSS custom properties.
|
||||
pub fn css_variables(theme: &Theme) -> String {
|
||||
let mut css = String::from(":root {\n");
|
||||
|
|
@ -89,11 +148,26 @@ pub fn css_variables(theme: &Theme) -> String {
|
|||
css
|
||||
}
|
||||
|
||||
/// JavaScript that installs the theme's CSS as a `<style id="lt-theme">`
|
||||
/// element as soon as the document has a `<head>`, for use as a webview
|
||||
/// initialization script.
|
||||
pub fn init_script(theme: &Theme) -> String {
|
||||
let css = serde_json::Value::String(css_variables(theme)).to_string();
|
||||
/// 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
|
||||
/// OS before the frontend has started.
|
||||
pub fn css_for_setting(setting: &str) -> String {
|
||||
if setting == SYSTEM {
|
||||
return format!(
|
||||
"{}\n@media (prefers-color-scheme: light) {{\n{}\n}}",
|
||||
css_variables(&DARK),
|
||||
css_variables(&LIGHT)
|
||||
);
|
||||
}
|
||||
css_variables(&resolve(setting, None))
|
||||
}
|
||||
|
||||
/// JavaScript that installs the CSS for an `appearance.theme` value as a
|
||||
/// `<style id="lt-theme">` element as soon as the document has a `<head>`,
|
||||
/// for use as a webview initialization script.
|
||||
pub fn init_script(setting: &str) -> String {
|
||||
let css = serde_json::Value::String(css_for_setting(setting)).to_string();
|
||||
format!(
|
||||
"(function(){{var css={css};function apply(){{var s=document.getElementById('lt-theme');if(!s){{s=document.createElement('style');s.id='lt-theme';document.head.appendChild(s);}}s.textContent=css;}}if(document.head){{apply();}}else{{document.addEventListener('DOMContentLoaded',apply);}}}})();"
|
||||
)
|
||||
|
|
@ -103,12 +177,65 @@ pub fn init_script(theme: &Theme) -> String {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The snapshot of every theme that the frontend's contrast test reads.
|
||||
fn ui_snapshot() -> String {
|
||||
let themes: Vec<_> = BUILTIN
|
||||
.iter()
|
||||
.map(|t| {
|
||||
serde_json::json!({
|
||||
"id": t.id,
|
||||
"labelKey": t.label_key,
|
||||
"dark": t.dark,
|
||||
"tokens": token_map(t),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut text = serde_json::to_string_pretty(&themes).unwrap();
|
||||
text.push('\n');
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn themes_define_the_same_tokens() {
|
||||
let names = |t: &Theme| t.tokens.iter().map(|(n, _)| *n).collect::<Vec<_>>();
|
||||
assert_eq!(names(&DARK), names(&LIGHT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn themes_define_the_editor_tokens() {
|
||||
for theme in BUILTIN {
|
||||
let tokens = token_map(theme);
|
||||
for name in [
|
||||
"editor-selection-bg",
|
||||
"editor-active-line-bg",
|
||||
"editor-cursor",
|
||||
"editor-gutter-bg",
|
||||
"editor-gutter-fg",
|
||||
"editor-match-bg",
|
||||
"font-size-editor",
|
||||
"tab-active-bg",
|
||||
"tab-modified",
|
||||
"notice-bg",
|
||||
] {
|
||||
assert!(
|
||||
tokens.contains_key(&format!("--lt-{name}")),
|
||||
"{} lacks {name}",
|
||||
theme.id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_settings() {
|
||||
assert_eq!(resolve("lutra-light", Some(true)), LIGHT);
|
||||
assert_eq!(resolve("lutra-dark", Some(false)), DARK);
|
||||
assert_eq!(resolve(SYSTEM, Some(false)), LIGHT);
|
||||
assert_eq!(resolve(SYSTEM, Some(true)), DARK);
|
||||
assert_eq!(resolve(SYSTEM, None), DARK);
|
||||
assert_eq!(resolve("nope", Some(false)), DARK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_css_variables() {
|
||||
let css = css_variables(&DARK);
|
||||
|
|
@ -118,12 +245,43 @@ mod tests {
|
|||
assert!(css.contains("color-scheme: dark;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_follows_the_setting() {
|
||||
assert_eq!(css_for_setting("lutra-light"), css_variables(&LIGHT));
|
||||
assert_eq!(css_for_setting("lutra-dark"), css_variables(&DARK));
|
||||
let system = css_for_setting(SYSTEM);
|
||||
assert!(system.starts_with(&css_variables(&DARK)));
|
||||
assert!(system.contains("@media (prefers-color-scheme: light) {\n:root {"));
|
||||
assert!(system.contains("color-scheme: light;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_script_embeds_escaped_css() {
|
||||
let js = init_script(&LIGHT);
|
||||
let js = init_script("lutra-light");
|
||||
assert!(js.contains("\\\"Segoe UI\\\""));
|
||||
assert!(js.contains("lt-theme"));
|
||||
assert!(js.contains("--lt-bg: #f4f1ec;"));
|
||||
assert_eq!(by_id("lutra-light"), Some(LIGHT));
|
||||
assert_eq!(by_id("nope"), None);
|
||||
}
|
||||
|
||||
/// Set `LUTRA_UPDATE_SNAPSHOTS=1` to rewrite the snapshot after changing
|
||||
/// a token.
|
||||
#[test]
|
||||
fn ui_snapshot_is_current() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../ui/tests/theme/themes.json");
|
||||
let expected = ui_snapshot();
|
||||
if std::env::var_os("LUTRA_UPDATE_SNAPSHOTS").is_some() {
|
||||
std::fs::write(&path, &expected).unwrap();
|
||||
}
|
||||
let actual = std::fs::read_to_string(&path)
|
||||
.unwrap_or_default()
|
||||
.replace("\r\n", "\n");
|
||||
assert!(
|
||||
actual == expected,
|
||||
"{} is out of date; run with LUTRA_UPDATE_SNAPSHOTS=1",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -72,10 +72,10 @@ fn get_set_reset_and_events() {
|
|||
.unwrap();
|
||||
assert_eq!(out.value, json!({"value": "lutra-light"}));
|
||||
assert_eq!(
|
||||
out.events,
|
||||
vec![Event::SettingsChanged {
|
||||
out.events.first(),
|
||||
Some(&Event::SettingsChanged {
|
||||
keys: vec!["appearance.theme".into()]
|
||||
}]
|
||||
})
|
||||
);
|
||||
let same = e
|
||||
.execute(
|
||||
|
|
@ -94,7 +94,7 @@ fn get_set_reset_and_events() {
|
|||
.execute("settings.reset", json!({"key": "appearance.theme"}))
|
||||
.unwrap();
|
||||
assert_eq!(reset.value, json!({"value": "system"}));
|
||||
assert_eq!(reset.events.len(), 1);
|
||||
assert_eq!(reset.events.len(), 2);
|
||||
let again = e
|
||||
.execute("settings.reset", json!({"key": "appearance.theme"}))
|
||||
.unwrap();
|
||||
|
|
|
|||
154
crates/engine/tests/theme.rs
Normal file
154
crates/engine/tests/theme.rs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
//! Theme commands and `themeChanged`: switching through `settings.set`, the
|
||||
//! "system" mode following the reported OS preference, and the stored theme
|
||||
//! surviving a restart.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::panic,
|
||||
clippy::indexing_slicing
|
||||
)]
|
||||
|
||||
use lutra_engine::{Engine, EngineConfig, Event, theme};
|
||||
use serde_json::{Value, json};
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn themes(events: &[Event]) -> Vec<(String, bool)> {
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::ThemeChanged { id, dark, .. } => Some((id.clone(), *dark)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn set_theme(engine: &mut Engine, value: &str) -> Vec<(String, bool)> {
|
||||
let outcome = engine
|
||||
.execute(
|
||||
"settings.set",
|
||||
json!({"key": "appearance.theme", "value": value}),
|
||||
)
|
||||
.unwrap();
|
||||
themes(&outcome.events)
|
||||
}
|
||||
|
||||
fn report(engine: &mut Engine, dark: bool) -> (Value, Vec<(String, bool)>) {
|
||||
let outcome = engine
|
||||
.execute("theme.systemPreference", json!({"dark": dark}))
|
||||
.unwrap();
|
||||
let events = themes(&outcome.events);
|
||||
(outcome.value, events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_names_the_builtin_themes_by_catalog_key() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
assert_eq!(
|
||||
list,
|
||||
json!([
|
||||
{"id": "lutra-dark", "label": "theme.lutraDark", "dark": true},
|
||||
{"id": "lutra-light", "label": "theme.lutraLight", "dark": false},
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_the_setting_emits_the_new_tokens() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let outcome = e
|
||||
.execute(
|
||||
"settings.set",
|
||||
json!({"key": "appearance.theme", "value": "lutra-light"}),
|
||||
)
|
||||
.unwrap();
|
||||
let Some(Event::ThemeChanged { id, dark, tokens }) = outcome
|
||||
.events
|
||||
.iter()
|
||||
.find(|e| matches!(e, Event::ThemeChanged { .. }))
|
||||
else {
|
||||
panic!("no themeChanged in {:?}", outcome.events);
|
||||
};
|
||||
assert_eq!(id, "lutra-light");
|
||||
assert!(!dark);
|
||||
assert_eq!(tokens, &theme::token_map(&theme::LIGHT));
|
||||
assert_eq!(tokens["--lt-bg"], "#f4f1ec");
|
||||
assert_eq!(tokens["--lt-font-size-editor"], "14px");
|
||||
assert!(matches!(
|
||||
outcome.events.first(),
|
||||
Some(Event::SettingsChanged { .. })
|
||||
));
|
||||
|
||||
assert_eq!(set_theme(&mut e, "lutra-light"), []);
|
||||
assert_eq!(
|
||||
set_theme(&mut e, "lutra-dark"),
|
||||
[("lutra-dark".into(), true)]
|
||||
);
|
||||
let reset = e
|
||||
.execute("settings.reset", json!({"key": "appearance.theme"}))
|
||||
.unwrap();
|
||||
assert_eq!(themes(&reset.events), []);
|
||||
let other = e
|
||||
.execute(
|
||||
"settings.set",
|
||||
json!({"key": "editor.fontSize", "value": 18}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(themes(&other.events), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_mode_follows_the_reported_preference() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let (value, events) = report(&mut e, true);
|
||||
assert_eq!(events, []);
|
||||
assert_eq!(value["id"], "lutra-dark");
|
||||
assert_eq!(value["dark"], true);
|
||||
assert_eq!(value["tokens"]["--lt-bg"], "#1f1d1b");
|
||||
assert!(value.get("kind").is_none());
|
||||
|
||||
let (value, events) = report(&mut e, false);
|
||||
assert_eq!(events, [("lutra-light".into(), false)]);
|
||||
assert_eq!(value["id"], "lutra-light");
|
||||
assert_eq!(report(&mut e, false).1, []);
|
||||
|
||||
assert_eq!(
|
||||
set_theme(&mut e, "lutra-dark"),
|
||||
[("lutra-dark".into(), true)]
|
||||
);
|
||||
let (value, events) = report(&mut e, true);
|
||||
assert_eq!(events, []);
|
||||
assert_eq!(report(&mut e, false).1, []);
|
||||
assert_eq!(value["id"], "lutra-dark");
|
||||
|
||||
assert_eq!(set_theme(&mut e, "system"), [("lutra-light".into(), false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_preference_params() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
for params in [
|
||||
json!({}),
|
||||
json!({"dark": "yes"}),
|
||||
json!({"dark": true, "x": 1}),
|
||||
] {
|
||||
let err = e.execute("theme.systemPreference", params).unwrap_err();
|
||||
assert_eq!(err.code(), "invalid_params");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stored_theme_survives_a_restart() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let config = EngineConfig {
|
||||
config_dir: dir.path().join("config"),
|
||||
data_dir: dir.path().join("data"),
|
||||
};
|
||||
let mut e = Engine::with_config(config.clone()).unwrap();
|
||||
set_theme(&mut e, "lutra-light");
|
||||
drop(e);
|
||||
let mut e = Engine::with_config(config).unwrap();
|
||||
let (value, _) = report(&mut e, true);
|
||||
assert_eq!(value["id"], "lutra-light");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue