T1: four more themes, theme picker, theme file import, editor font settings
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 <data_dir>/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 <noreply@anthropic.com>
This commit is contained in:
parent
872b5cb258
commit
086bc8a925
26 changed files with 2881 additions and 100 deletions
|
|
@ -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-<name>`) 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<Theme> {
|
||||
|
|
@ -287,18 +570,281 @@ pub fn token_map(theme: &Theme) -> BTreeMap<String, String> {
|
|||
|
||||
/// 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-<name>` → value.
|
||||
pub tokens: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
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<String, String>,
|
||||
}
|
||||
|
||||
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<Item = &'static str> {
|
||||
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::<Vec<_>>()
|
||||
.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<UserTheme, String> {
|
||||
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<String> = 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<bool>,
|
||||
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 {
|
|||
/// `<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();
|
||||
init_script_for_css(&css_for_setting(setting))
|
||||
}
|
||||
|
||||
/// JavaScript that installs `css` as the `<style id="lt-theme">` element,
|
||||
/// as [`init_script`] does; for an imported theme, which only the engine
|
||||
/// knows.
|
||||
pub fn init_script_for_css(css: &str) -> String {
|
||||
let css = serde_json::Value::String(css.to_string()).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);}}}})();"
|
||||
)
|
||||
|
|
@ -349,7 +902,108 @@ mod tests {
|
|||
#[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));
|
||||
for theme in BUILTIN {
|
||||
assert_eq!(names(&DARK), names(theme), "{}", theme.id);
|
||||
assert!(valid_id(theme.id), "{}", theme.id);
|
||||
assert!(
|
||||
theme.tokens.iter().all(|(_, v)| is_hex_colour(v)),
|
||||
"{}",
|
||||
theme.id
|
||||
);
|
||||
}
|
||||
let mut ids: Vec<_> = BUILTIN.iter().map(|t| t.id).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), BUILTIN.len());
|
||||
assert_eq!(BUILTIN.iter().filter(|t| t.dark).count(), 3);
|
||||
}
|
||||
|
||||
/// A valid theme file built from a built-in theme's colours.
|
||||
fn file_from(theme: &Theme, id: &str) -> serde_json::Value {
|
||||
let tokens: serde_json::Map<_, _> = theme
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|(n, v)| ((*n).to_string(), serde_json::Value::from(*v)))
|
||||
.collect();
|
||||
serde_json::json!({
|
||||
"lutraTheme": 1,
|
||||
"id": id,
|
||||
"name": " My Dusk ",
|
||||
"dark": theme.dark,
|
||||
"description": "test",
|
||||
"tokens": tokens,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_a_theme_file() {
|
||||
let mut file = file_from(&RIVER, "my-dusk");
|
||||
file["tokens"]["--lt-bg"] = file["tokens"]["bg"].take();
|
||||
file["tokens"].as_object_mut().unwrap().remove("bg");
|
||||
file["tokens"]["accent"] = "#ABCDEF".into();
|
||||
let theme = parse_file(&file.to_string()).unwrap();
|
||||
assert_eq!(theme.id, "my-dusk");
|
||||
assert_eq!(theme.name, "My Dusk");
|
||||
assert!(theme.dark);
|
||||
assert_eq!(theme.tokens["bg"], "#1a2125");
|
||||
assert_eq!(theme.tokens["accent"], "#abcdef");
|
||||
let resolved = theme.resolved();
|
||||
assert_eq!(resolved.tokens.len(), token_map(&RIVER).len());
|
||||
assert_eq!(resolved.tokens["--lt-font-size-editor"], "14px");
|
||||
let again = parse_file(&theme.to_file().to_string()).unwrap();
|
||||
assert_eq!(again, theme);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_broken_theme_files() {
|
||||
let good = file_from(&PAPER, "fine");
|
||||
let broken = |edit: &dyn Fn(&mut serde_json::Value)| {
|
||||
let mut file = good.clone();
|
||||
edit(&mut file);
|
||||
parse_file(&file.to_string()).unwrap_err()
|
||||
};
|
||||
assert!(parse_file("{nope").unwrap_err().contains("not valid JSON"));
|
||||
assert!(parse_file("[]").unwrap_err().contains("JSON object"));
|
||||
assert!(broken(&|f| f["lutraTheme"] = 2.into()).contains("lutraTheme"));
|
||||
assert!(broken(&|f| f["Dark"] = true.into()).contains("unknown key \"Dark\""));
|
||||
assert!(broken(&|f| f["id"] = "Bad Id".into()).contains("not allowed"));
|
||||
assert!(broken(&|f| f["id"] = "lutra-river".into()).contains("built-in"));
|
||||
assert!(broken(&|f| f["id"] = SYSTEM.into()).contains("built-in"));
|
||||
assert!(broken(&|f| f["name"] = " ".into()).contains("name"));
|
||||
assert!(broken(&|f| f["dark"] = "yes".into()).contains("dark"));
|
||||
assert!(broken(&|f| f["tokens"]["bg"] = "red".into()).contains("\"bg\" must be a colour"));
|
||||
assert!(broken(&|f| f["tokens"]["--lt-bg"] = "#000000".into()).contains("twice"));
|
||||
assert!(
|
||||
broken(&|f| f["tokens"]["sparkle"] = "#000000".into())
|
||||
.contains("unknown tokens: sparkle")
|
||||
);
|
||||
let missing = broken(&|f| f["tokens"] = serde_json::json!({}));
|
||||
assert!(
|
||||
missing.starts_with("59 tokens are missing: bg, editor-bg"),
|
||||
"{missing}"
|
||||
);
|
||||
assert!(missing.ends_with("and 51 more"), "{missing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_imported_themes() {
|
||||
let mine = parse_file(&file_from(&REED, "mine").to_string()).unwrap();
|
||||
let imported = [mine.clone()];
|
||||
assert_eq!(resolve_with("mine", Some(true), &imported), mine.resolved());
|
||||
assert_eq!(
|
||||
resolve_with("lutra-paper", None, &imported),
|
||||
PAPER.resolved()
|
||||
);
|
||||
assert_eq!(resolve_with("gone", None, &imported), DARK.resolved());
|
||||
assert_eq!(
|
||||
resolve_with(SYSTEM, Some(false), &imported),
|
||||
LIGHT.resolved()
|
||||
);
|
||||
assert!(css_of(&mine.resolved()).contains(
|
||||
" --lt-bg: #e9e7d8;
|
||||
"
|
||||
));
|
||||
assert!(init_script_for_css("a").contains("var css=\"a\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -434,6 +1088,9 @@ mod tests {
|
|||
assert_eq!(resolve(SYSTEM, Some(true)), DARK);
|
||||
assert_eq!(resolve(SYSTEM, None), DARK);
|
||||
assert_eq!(resolve("nope", Some(false)), DARK);
|
||||
assert_eq!(resolve("lutra-river", Some(false)), RIVER);
|
||||
assert_eq!(by_id("lutra-plum-night"), Some(PLUM_NIGHT));
|
||||
assert_eq!(by_id("lutra-reed"), Some(REED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue