//! Theme tokens: the single source of every colour and font in the UI. //! //! Themes are defined here in Rust and rendered as CSS custom properties //! (`--lt-`). Frontend components use only `var(--lt-…)`. The palettes //! are Lutra's own and follow the README banner: calm, near-neutral surfaces //! (cream-tinted in the light theme, faintly plum-tinted in the dark one) //! with the banner's raspberry as the only 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. //! //! 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 (always the brand pair). 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, /// 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, 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", "system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif", ), ( "font-mono", "\"IBM Plex Mono\", ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace", ), ("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 /// editor's highlighter reads only these; each reaches 4.5:1 on the editor /// background (`ui/tests/theme/contrast.test.ts`). The colours are Lutra's /// own, tuned to sit next to the raspberry accent without repeating it /// (only keywords take a muted raspberry). pub const SYNTAX_TOKENS: &[&str] = &[ "keyword", "string", "number", "comment", "variable", "function", "type", "constant", "tag", "attribute", "operator", ]; /// Terminal token names (`--lt-terminal-`) every theme defines: the /// terminal's background, text, cursor and selection, and the 16 ANSI /// colours xterm.js maps escape sequences to. Every ANSI colour that shows /// as text reaches 4.5:1 on `terminal-bg` (`ui/tests/theme/contrast.test.ts`); /// the exceptions are the colour meant to vanish into the background: ANSI /// black in the dark theme, white and bright white in the light one. pub const TERMINAL_TOKENS: &[&str] = &[ "bg", "fg", "cursor", "selection-bg", "ansi-black", "ansi-red", "ansi-green", "ansi-yellow", "ansi-blue", "ansi-magenta", "ansi-cyan", "ansi-white", "ansi-bright-black", "ansi-bright-red", "ansi-bright-green", "ansi-bright-yellow", "ansi-bright-blue", "ansi-bright-magenta", "ansi-bright-cyan", "ansi-bright-white", ]; /// Diagnostic severity token names (`--lt-diag-`) every theme /// defines. They colour the editor's lint underlines, gutter markers and /// tooltip stripes and the Problems window's severity icons; each reaches /// 4.5:1 on the editor background, the active line and the window /// background (`ui/tests/theme/contrast.test.ts`). pub const DIAGNOSTIC_TOKENS: &[&str] = &["error", "warning", "info", "hint"]; /// Version-control status token names (`--lt-vcs-`) every theme /// defines, for file names in the project tree and tabs and for the /// editor's change markers. Each reaches 4.5:1 as text on the editor /// background, the active line and the window background. pub const VCS_TOKENS: &[&str] = &[ "added", "modified", "deleted", "untracked", "ignored", "conflicted", ]; /// The default dark theme. pub const DARK: Theme = Theme { id: "lutra-dark", label_key: "theme.lutraDark", dark: true, tokens: &[ ("bg", "#1e1b1e"), ("editor-bg", "#181618"), ("fg", "#ebe5dc"), ("fg-muted", "#9e9499"), ("border", "#362f35"), ("accent", "#e27ba6"), ("error", "#f2836b"), ("statusbar-bg", "#231f23"), ("statusbar-fg", "#bdb3b8"), ("editor-selection-bg", "#4c2d3d"), ("editor-active-line-bg", "#221f22"), ("editor-cursor", "#e27ba6"), ("editor-gutter-bg", "#181618"), ("editor-gutter-fg", "#9e9499"), ("editor-match-bg", "#3a2632"), ("tab-active-bg", "#181618"), ("tab-modified", "#e27ba6"), ("notice-bg", "#382632"), ("syntax-keyword", "#d98aab"), ("syntax-string", "#a9bd7e"), ("syntax-number", "#e8a87c"), ("syntax-comment", "#978e93"), ("syntax-variable", "#dcc6b2"), ("syntax-function", "#e6c46f"), ("syntax-type", "#7fbac6"), ("syntax-constant", "#b9a5e2"), ("syntax-tag", "#e08b70"), ("syntax-attribute", "#cdb87e"), ("syntax-operator", "#bdb3b8"), ("diag-error", "#f2836b"), ("diag-warning", "#e6b450"), ("diag-info", "#8fb0e8"), ("diag-hint", "#9e9499"), ("vcs-added", "#9cc27a"), ("vcs-modified", "#8fb0e8"), ("vcs-deleted", "#d4908a"), ("vcs-untracked", "#e3a464"), ("vcs-ignored", "#8f878b"), ("vcs-conflicted", "#f26d82"), ("terminal-bg", "#181618"), ("terminal-fg", "#ebe5dc"), ("terminal-cursor", "#e27ba6"), ("terminal-selection-bg", "#4c2d3d"), ("terminal-ansi-black", "#2e2a2e"), ("terminal-ansi-red", "#ef7b6c"), ("terminal-ansi-green", "#a9bd7e"), ("terminal-ansi-yellow", "#e6c46f"), ("terminal-ansi-blue", "#8fa8e0"), ("terminal-ansi-magenta", "#e27ba6"), ("terminal-ansi-cyan", "#7fbac6"), ("terminal-ansi-white", "#d3cbc4"), ("terminal-ansi-bright-black", "#9e9499"), ("terminal-ansi-bright-red", "#f59a8d"), ("terminal-ansi-bright-green", "#c2d69a"), ("terminal-ansi-bright-yellow", "#f2d88e"), ("terminal-ansi-bright-blue", "#aebff0"), ("terminal-ansi-bright-magenta", "#f0a6c6"), ("terminal-ansi-bright-cyan", "#a2d3dc"), ("terminal-ansi-bright-white", "#f7f2ea"), ], }; /// The light theme. pub const LIGHT: Theme = Theme { id: "lutra-light", label_key: "theme.lutraLight", dark: false, tokens: &[ ("bg", "#f3efe3"), ("editor-bg", "#fbf9f3"), ("fg", "#2a2427"), ("fg-muted", "#675d61"), ("border", "#ddd5c4"), ("accent", "#a32c66"), ("error", "#b23a29"), ("statusbar-bg", "#ebe5d5"), ("statusbar-fg", "#554c50"), ("editor-selection-bg", "#ecd6dc"), ("editor-active-line-bg", "#f3f0e8"), ("editor-cursor", "#a32c66"), ("editor-gutter-bg", "#fbf9f3"), ("editor-gutter-fg", "#675d61"), ("editor-match-bg", "#f2e1e3"), ("tab-active-bg", "#fbf9f3"), ("tab-modified", "#a32c66"), ("notice-bg", "#eedcdc"), ("syntax-keyword", "#9a2d61"), ("syntax-string", "#4e6a24"), ("syntax-number", "#9c4519"), ("syntax-comment", "#6b6367"), ("syntax-variable", "#7f4a34"), ("syntax-function", "#7a5808"), ("syntax-type", "#24697a"), ("syntax-constant", "#5e489e"), ("syntax-tag", "#a5432a"), ("syntax-attribute", "#695d1a"), ("syntax-operator", "#554c50"), ("diag-error", "#b23a29"), ("diag-warning", "#865500"), ("diag-info", "#2f5aa8"), ("diag-hint", "#675d61"), ("vcs-added", "#3d7526"), ("vcs-modified", "#2f5aa8"), ("vcs-deleted", "#a3463b"), ("vcs-untracked", "#93560c"), ("vcs-ignored", "#71686c"), ("vcs-conflicted", "#b01f45"), ("terminal-bg", "#fbf9f3"), ("terminal-fg", "#2a2427"), ("terminal-cursor", "#a32c66"), ("terminal-selection-bg", "#ecd6dc"), ("terminal-ansi-black", "#2a2427"), ("terminal-ansi-red", "#b23a29"), ("terminal-ansi-green", "#4e6a24"), ("terminal-ansi-yellow", "#7a5808"), ("terminal-ansi-blue", "#2f55a4"), ("terminal-ansi-magenta", "#a32c66"), ("terminal-ansi-cyan", "#24697a"), ("terminal-ansi-white", "#ddd5c4"), ("terminal-ansi-bright-black", "#675d61"), ("terminal-ansi-bright-red", "#8f2a1c"), ("terminal-ansi-bright-green", "#3b5418"), ("terminal-ansi-bright-yellow", "#5f4404"), ("terminal-ansi-bright-blue", "#233f7f"), ("terminal-ansi-bright-magenta", "#7c1f4d"), ("terminal-ansi-bright-cyan", "#1a5260"), ("terminal-ansi-bright-white", "#f3efe3"), ], }; /// 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 { 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) -> 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-` → value. pub fn token_map(theme: &Theme) -> BTreeMap { 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 { 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 &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 /// 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 /// `