Compare commits
4 commits
872b5cb258
...
aa96118602
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa96118602 | ||
|
|
f2a1ef12cd | ||
|
|
d81c943905 | ||
|
|
086bc8a925 |
34 changed files with 2956 additions and 109 deletions
|
|
@ -6,7 +6,7 @@ Every non-code asset in this repository (icons, images, example projects, colour
|
|||
|
||||
Generated-in-code art is original and has no file to list (default colour schemes, file-type badges, the placeholder app icon that `apps/lutra-desktop/build.rs` falls back to when `assets/app-icon/icon.png` is missing).
|
||||
|
||||
**Font files are never committed.** Inter and JetBrains Mono (both SIL OFL 1.1) come from the `@fontsource` npm packages and are listed in `NOTICE`. **Lucide icons** come from the `lucide-vue-next` npm package (ISC) and are listed in `NOTICE`; only icons drawn for Lutra live in `assets/icons/` with the prefix `lt-`.
|
||||
**Font files are never committed.** Fonts come from `@fontsource` npm packages and are listed in `NOTICE`: IBM Plex Mono (SIL OFL 1.1, bundled as the code font for the editor and the terminal, owner decision D28; the only package allowed under OFL-1.1, see `PACKAGE_EXCEPTIONS` in `xtask/src/licences.rs`). The UI uses the system font. **Lucide icons** come from the `lucide-vue-next` npm package (ISC) and are listed in `NOTICE`; only icons drawn for Lutra live in `assets/icons/` with the prefix `lt-`.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
|
|
|||
4
NOTICE
4
NOTICE
|
|
@ -14,7 +14,9 @@ kept up to date when one is added or removed.
|
|||
Bundled components (planned; update when added):
|
||||
* Lucide icons (@lucide/vue, formerly lucide-vue-next) — ISC License, https://lucide.dev
|
||||
* Inter typeface (@fontsource/inter) — SIL Open Font License 1.1
|
||||
* JetBrains Mono typeface (@fontsource/jetbrains-mono) — SIL Open Font License 1.1
|
||||
* IBM Plex Mono typeface (@fontsource/ibm-plex-mono), Lutra's code font for
|
||||
the editor and the terminal — SIL Open Font License 1.1, Copyright
|
||||
IBM Corp.; licence text in the package (bundled since C9 T1, D28)
|
||||
* CodeMirror 6 — MIT License
|
||||
* tree-sitter and tree-sitter-php — MIT License
|
||||
* Tauri — MIT OR Apache-2.0 (the Windows setup is built from an adapted
|
||||
|
|
|
|||
|
|
@ -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<theme::ResolvedTheme> {
|
||||
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<Color> {
|
||||
let (_, value) = theme.tokens.iter().find(|(n, _)| *n == name)?;
|
||||
fn token_color(theme: &theme::ResolvedTheme, name: &str) -> Option<Color> {
|
||||
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]
|
||||
|
|
|
|||
|
|
@ -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": "",
|
||||
|
|
|
|||
|
|
@ -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))?;
|
||||
|
|
|
|||
|
|
@ -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<Outcome, EngineError> {
|
||||
let list: Vec<_> = DEFS.iter().map(settings::Def::info).collect();
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
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<Outcome, EngineError> {
|
||||
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<Outcome, EngineError> {
|
||||
if changed {
|
||||
state.emit(Event::SettingsChanged {
|
||||
|
|
|
|||
|
|
@ -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 `<data_dir>/themes/<id>.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<String>, Map<String, Value>) {
|
||||
let mut ids: Vec<String> = 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<PathBuf> {
|
||||
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<UserTheme, String> {
|
||||
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 `<data_dir>/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<PathBuf> = 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("notification.theme.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<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)))
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
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<Outcome, EngineError> {
|
||||
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<Outcome, EngineError> {
|
||||
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<bool>,
|
||||
}
|
||||
|
||||
/// `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<Outcome, EngineError> {
|
||||
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",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<Vec<&'static str>>,
|
||||
pub enum_values: Option<Vec<String>>,
|
||||
/// 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<std::collections::BTreeMap<String, String>>,
|
||||
/// Smallest value of an int.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub min: Option<i64>,
|
||||
|
|
@ -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{", "</style>", "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",
|
||||
|
|
|
|||
|
|
@ -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<bool>,
|
||||
/// Themes imported from theme files (`theme.import`), loaded from
|
||||
/// `<data_dir>/themes` at start.
|
||||
pub themes: Vec<crate::theme::UserTheme>,
|
||||
/// Where the engine stores its files; `None` for an engine without
|
||||
/// persistence ([`crate::Engine::new`]).
|
||||
pub config: Option<EngineConfig>,
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
@ -38,11 +47,12 @@ const COMMON: &[(&str, &str)] = &[
|
|||
),
|
||||
(
|
||||
"font-mono",
|
||||
"ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace",
|
||||
"\"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-<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]
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
|
|||
[
|
||||
"appearance.theme",
|
||||
"editor.fontSize",
|
||||
"editor.fontFamily",
|
||||
"editor.lineHeight",
|
||||
"ui.language",
|
||||
"php.executable",
|
||||
"phpactor.path",
|
||||
|
|
@ -72,12 +74,14 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
|
|||
}
|
||||
assert_eq!(list[1]["type"], "int");
|
||||
assert_eq!(list[1]["default"], 14);
|
||||
assert_eq!(list[2]["enumValues"], json!(["en"]));
|
||||
assert_eq!(list[3]["type"], "string");
|
||||
assert_eq!(list[3]["default"], "");
|
||||
assert_eq!(list[5]["type"], "bool");
|
||||
assert_eq!(list[5]["default"], true);
|
||||
assert_eq!(list[5]["section"], "php");
|
||||
assert_eq!(list[2]["type"], "string");
|
||||
assert_eq!(list[3]["default"], 150);
|
||||
assert_eq!(list[4]["enumValues"], json!(["en"]));
|
||||
assert_eq!(list[5]["type"], "string");
|
||||
assert_eq!(list[5]["default"], "");
|
||||
assert_eq!(list[7]["type"], "bool");
|
||||
assert_eq!(list[7]["default"], true);
|
||||
assert_eq!(list[7]["section"], "php");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -117,6 +121,8 @@ fn get_set_reset_and_events() {
|
|||
json!({
|
||||
"appearance.theme": "system",
|
||||
"editor.fontSize": 14,
|
||||
"editor.fontFamily": "",
|
||||
"editor.lineHeight": 150,
|
||||
"ui.language": "en",
|
||||
"php.executable": "",
|
||||
"phpactor.path": "",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
//! Theme commands and `themeChanged`: switching through `settings.set`, the
|
||||
//! "system" mode following the reported OS preference, and the stored theme
|
||||
//! surviving a restart.
|
||||
//! "system" mode following the reported OS preference, the stored theme
|
||||
//! surviving a restart, `theme.select`, `theme.current` and importing theme
|
||||
//! files (C9 T1).
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
|
|
@ -45,13 +46,156 @@ fn report(engine: &mut Engine, dark: bool) -> (Value, Vec<(String, bool)>) {
|
|||
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;
|
||||
let rows: Vec<_> = list
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
(
|
||||
t["id"].as_str().unwrap(),
|
||||
t["label"].as_str().unwrap(),
|
||||
t["dark"].as_bool().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
list,
|
||||
json!([
|
||||
{"id": "lutra-dark", "label": "theme.lutraDark", "dark": true},
|
||||
{"id": "lutra-light", "label": "theme.lutraLight", "dark": false},
|
||||
])
|
||||
rows,
|
||||
[
|
||||
("lutra-dark", "theme.lutraDark", true),
|
||||
("lutra-light", "theme.lutraLight", false),
|
||||
("lutra-plum-night", "theme.lutraPlumNight", true),
|
||||
("lutra-river", "theme.lutraRiver", true),
|
||||
("lutra-paper", "theme.lutraPaper", false),
|
||||
("lutra-reed", "theme.lutraReed", false),
|
||||
]
|
||||
);
|
||||
assert_eq!(list[3]["tokens"], json!(theme::token_map(&theme::RIVER)));
|
||||
assert_eq!(list[3]["builtin"], true);
|
||||
assert_eq!(list[3]["name"], Value::Null);
|
||||
}
|
||||
|
||||
/// A valid theme file with the colours of `base`.
|
||||
fn theme_file(base: &theme::Theme, id: &str, name: &str) -> String {
|
||||
let tokens: serde_json::Map<_, _> = base
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|(n, v)| (format!("--lt-{n}"), Value::from(*v)))
|
||||
.collect();
|
||||
json!({"lutraTheme": 1, "id": id, "name": name, "dark": base.dark, "tokens": tokens})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_and_current_switch_live() {
|
||||
let mut e = Engine::new().unwrap();
|
||||
let out = e
|
||||
.execute("theme.select", json!({"id": "lutra-paper"}))
|
||||
.unwrap();
|
||||
assert_eq!(out.value["id"], "lutra-paper");
|
||||
assert_eq!(out.value["tokens"]["--lt-bg"], "#f6f5f1");
|
||||
assert_eq!(themes(&out.events), [("lutra-paper".into(), false)]);
|
||||
assert!(matches!(
|
||||
out.events.first(),
|
||||
Some(Event::SettingsChanged { keys }) if keys == &["appearance.theme"]
|
||||
));
|
||||
let current = e.execute("theme.current", Value::Null).unwrap().value;
|
||||
assert_eq!(current["id"], "lutra-paper");
|
||||
assert_eq!(current["tokens"], json!(theme::token_map(&theme::PAPER)));
|
||||
let again = e
|
||||
.execute("theme.select", json!({"id": "lutra-paper"}))
|
||||
.unwrap();
|
||||
assert!(again.events.is_empty());
|
||||
for bad in [json!({"id": "nope"}), json!({}), json!({"id": "x", "y": 1})] {
|
||||
let err = e.execute("theme.select", bad).unwrap_err();
|
||||
assert_eq!(err.code(), "invalid_params");
|
||||
}
|
||||
let err = e
|
||||
.execute(
|
||||
"settings.set",
|
||||
json!({"key": "appearance.theme", "value": "not-imported"}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("unknown theme"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_themes_are_selected_stored_and_reloaded() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let config = EngineConfig {
|
||||
config_dir: dir.path().join("config"),
|
||||
data_dir: dir.path().join("data"),
|
||||
};
|
||||
let file = dir.path().join("dusk.json");
|
||||
std::fs::write(&file, theme_file(&theme::RIVER, "dusk", "Dusk")).unwrap();
|
||||
let mut e = Engine::with_config(config.clone()).unwrap();
|
||||
let out = e.execute("theme.import", json!({"path": file})).unwrap();
|
||||
assert_eq!(
|
||||
out.value,
|
||||
json!({"id": "dusk", "name": "Dusk", "dark": true, "replaced": false})
|
||||
);
|
||||
assert_eq!(themes(&out.events), [("dusk".into(), true)]);
|
||||
let stored = dir.path().join("data/themes/dusk.json");
|
||||
assert!(stored.is_file());
|
||||
let list = e.execute("settings.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list[0]["enumValues"].as_array().unwrap().len(), 8);
|
||||
assert_eq!(list[0]["enumValues"][6], "dusk");
|
||||
assert_eq!(list[0]["valueNames"], json!({"dusk": "Dusk"}));
|
||||
|
||||
std::fs::write(&file, theme_file(&theme::REED, "dusk", "Dusk 2")).unwrap();
|
||||
let out = e
|
||||
.execute("theme.import", json!({"path": file, "select": false}))
|
||||
.unwrap();
|
||||
assert_eq!(out.value["replaced"], true);
|
||||
assert_eq!(themes(&out.events), [("dusk".into(), false)]);
|
||||
drop(e);
|
||||
|
||||
std::fs::write(dir.path().join("data/themes/broken.json"), "{oops").unwrap();
|
||||
let mut e = Engine::with_config(config).unwrap();
|
||||
let events = e.take_events();
|
||||
assert!(
|
||||
events.iter().any(|ev| matches!(
|
||||
ev,
|
||||
Event::Notification { message: Some(m), .. } if m.contains("broken.json") && m.contains("not valid JSON")
|
||||
)),
|
||||
"{events:?}"
|
||||
);
|
||||
let current = e.execute("theme.current", Value::Null).unwrap().value;
|
||||
assert_eq!(current["id"], "dusk");
|
||||
assert_eq!(current["tokens"]["--lt-bg"], "#e9e7d8");
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list[6]["name"], "Dusk 2");
|
||||
assert_eq!(list[6]["builtin"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_theme_file_is_refused_with_the_reason() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let mut e = Engine::new().unwrap();
|
||||
let missing = e
|
||||
.execute(
|
||||
"theme.import",
|
||||
json!({"path": dir.path().join("none.json")}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(missing.code(), "failed");
|
||||
assert!(missing.to_string().contains("cannot read it"), "{missing}");
|
||||
let file = dir.path().join("bad.json");
|
||||
std::fs::write(&file, r##"{"lutraTheme": 1, "id": "bad", "name": "Bad", "dark": true, "tokens": {"bg": "#000"}}"##).unwrap();
|
||||
let err = e
|
||||
.execute("theme.import", json!({"path": file}))
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("the token \"bg\" must be a colour"),
|
||||
"{err}"
|
||||
);
|
||||
std::fs::write(&file, "x".repeat(300 * 1024)).unwrap();
|
||||
let err = e
|
||||
.execute("theme.import", json!({"path": file}))
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("larger than 256 KiB"), "{err}");
|
||||
let list = e.execute("theme.list", Value::Null).unwrap().value;
|
||||
assert_eq!(list.as_array().unwrap().len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -30,5 +30,10 @@ allow = [
|
|||
crate = "notify"
|
||||
allow = ["CC0-1.0"]
|
||||
|
||||
# OFL-1.1 is approved for one frontend package only: the bundled code font
|
||||
# @fontsource/ibm-plex-mono (owner decision D28, 2026-11-06). It is an npm
|
||||
# package, not a crate, so its exception lives in PACKAGE_EXCEPTIONS in
|
||||
# xtask/src/licences.rs; no crate may use OFL-1.1.
|
||||
|
||||
[licenses.private]
|
||||
ignore = true
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Gaps
|
||||
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-01
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-06
|
||||
|
||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||
|
||||
|
|
@ -8,7 +8,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
|||
|---|---|---|---|
|
||||
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
||||
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~14 h |
|
||||
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h |
|
||||
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b; C9 T1: six built-in themes, picker with live preview, theme file import, editor font family and line height), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h |
|
||||
| G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h |
|
||||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
|
||||
|
|
@ -56,6 +56,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
|||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 |
|
||||
| 2026-11-06 | minor | G3: more themes, theme import, editor font settings (C9 T1) |
|
||||
| 2026-11-01 | patch | G8: chunk staging, unstaging and revert from the gutter and the diff viewer (C8 C3) |
|
||||
| 2026-10-31 | patch | C7 review: stray revision rows moved here; installers (B1, B2) and the alpha checklist (A2) change no gap |
|
||||
| 2026-10-31 | patch | A1: macOS system menus (G3), Retina region for the macOS screenshot fallback |
|
||||
|
|
|
|||
159
docs/themes.md
Normal file
159
docs/themes.md
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
# Themes
|
||||
|
||||
> **Status:** six built-in themes, theme files with import, editor font settings, bundled code font IBM Plex Mono (C9 T1) · **Last updated:** 2026-11-06
|
||||
|
||||
Every colour and font in Lutra comes from theme tokens: CSS custom properties `--lt-<name>` that `crates/engine/src/theme.rs` defines and the UI reads with `var(--lt-…)`. Nothing in the UI hard-codes a colour.
|
||||
|
||||
## Built-in themes
|
||||
|
||||
| Id | Name | Kind | Character |
|
||||
|---|---|---|---|
|
||||
| `lutra-dark` | Lutra Dark | dark | The brand theme (H5): near-neutral, faintly plum surfaces, raspberry accent. |
|
||||
| `lutra-light` | Lutra Light | light | The brand theme (H5): cream-tinted surfaces, raspberry accent. |
|
||||
| `lutra-plum-night` | Plum Night | dark | Deep, warm plum surfaces with a soft cream-gold accent. |
|
||||
| `lutra-river` | River | dark | Cool slate and river teal; raspberry keywords keep the family link. |
|
||||
| `lutra-paper` | Paper | light | Almost white paper with the banner plum as the accent; the quietest theme. |
|
||||
| `lutra-reed` | Reed | light | Soft sand and sage surfaces with a muted pine accent. |
|
||||
|
||||
Amy designed the four C9 themes from the README banner and the brand tokens; Daniel approved them on 2026-11-02. All colours are Lutra's own (no copied editor or IDE scheme). Every text colour reaches WCAG AA (4.5:1) on the backgrounds it is drawn on, and every icon and cursor colour reaches 3:1. `ui/tests/theme/contrast.test.ts` checks this for every built-in theme on each run of the gate.
|
||||
|
||||
## Choosing a theme
|
||||
|
||||
- **Settings ▸ Appearance ▸ Theme** lists every built-in and imported theme and "Same as system".
|
||||
- **View ▸ Select Theme…** (`view.selectTheme`, also in the command palette) opens a picker. Up/Down previews a theme live, Enter keeps it, Escape goes back to the one you had.
|
||||
- **Same as system** follows the light or dark preference of the operating system, using Lutra Dark and Lutra Light.
|
||||
- Agents and scripts: `theme.list`, `theme.current`, `theme.select { id }` (an id from `theme.list`, or `system`), or `settings.set` with `appearance.theme`. Every switch is live: the engine sends `themeChanged` with all tokens.
|
||||
|
||||
## Editor font
|
||||
|
||||
The **Editor** section of the settings has three font settings. They apply live and stay when you switch themes.
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `editor.fontFamily` | empty | A CSS font list such as `"Fira Code", monospace`. Empty uses Lutra's own code font, IBM Plex Mono, which ships with Lutra (regular, bold and italic; comments are set in its italic). The default stack (`"IBM Plex Mono", ui-monospace, "Cascadia Code", Menlo, Consolas, monospace`) also stays behind your choice as a fallback. Any other font must be installed. The characters `; { } < > \` are refused. Applies to the editor and other code text at once, and to terminals opened afterwards (it drives `--lt-font-mono`). |
|
||||
| `editor.fontSize` | 14 | Size in pixels, 8 to 48. |
|
||||
| `editor.lineHeight` | 150 | Line height in percent of the font size, 100 to 300. |
|
||||
|
||||
## Theme files
|
||||
|
||||
A theme file is a UTF-8 JSON file of at most 256 KiB:
|
||||
|
||||
```json
|
||||
{
|
||||
"lutraTheme": 1,
|
||||
"id": "my-river",
|
||||
"name": "My River",
|
||||
"dark": true,
|
||||
"description": "River with a warmer accent",
|
||||
"author": "you",
|
||||
"tokens": {
|
||||
"bg": "#1a2125",
|
||||
"editor-bg": "#151b1e",
|
||||
"fg": "#e2e8e6",
|
||||
"fg-muted": "#8e9ca3",
|
||||
"border": "#2c373d",
|
||||
"accent": "#e8a87c",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Required | Meaning |
|
||||
|---|---|---|
|
||||
| `lutraTheme` | yes | The format version, `1`. |
|
||||
| `id` | yes | 1 to 64 lowercase letters, digits and dashes, starting with a letter. It must not be a built-in id or `system`. Importing a file with the same id again replaces that theme. |
|
||||
| `name` | yes | Display name, 1 to 64 characters, no control characters. |
|
||||
| `dark` | yes | `true` for a dark theme. It sets the window's `color-scheme`, so scroll bars and form controls match. |
|
||||
| `tokens` | yes | Every colour token below, as `"#rrggbb"`. Names may be written with or without the `--lt-` prefix. |
|
||||
| `description`, `author` | no | Free text; Lutra ignores it. |
|
||||
|
||||
Lutra refuses any other key, an unknown or repeated token, a missing token and a colour that is not `#rrggbb`. The error names the problem (for example "59 tokens are missing: bg, editor-bg, … and 51 more"). Fonts and sizes are not part of a theme; they are the settings above.
|
||||
|
||||
### Importing
|
||||
|
||||
**View ▸ Import Theme…** (`view.importTheme`) asks for a file, checks it and switches to the theme. A broken file shows an error with the reason and changes nothing. Lutra stores a checked, normalised copy in its data directory under `themes/<id>.json` and loads it at every start. If a stored file is broken later, Lutra skips it with a warning and starts normally. To remove an imported theme, delete its file there and restart Lutra.
|
||||
|
||||
Agents and scripts: `theme.import { path, select?: true }`. It returns `{ id, name, dark, replaced }` and fails with the reason.
|
||||
|
||||
Lutra does not check the contrast of an imported theme. To check it the way the built-in themes are checked, keep text at 4.5:1 or more against the backgrounds listed below.
|
||||
|
||||
### Colour tokens
|
||||
|
||||
| Tokens | Used for |
|
||||
|---|---|
|
||||
| `bg`, `fg`, `fg-muted`, `border` | Window surface, text, secondary text and lines (tool windows, dialogs, popups). |
|
||||
| `accent`, `error` | Focus rings, active tab and tool-window markers, buttons; error text. |
|
||||
| `statusbar-bg`, `statusbar-fg` | Status bar. |
|
||||
| `editor-bg`, `editor-selection-bg`, `editor-active-line-bg`, `editor-cursor`, `editor-gutter-bg`, `editor-gutter-fg`, `editor-match-bg` | The editor. Selection and active line sit under text, so text must stay readable on them. |
|
||||
| `tab-active-bg`, `tab-modified`, `notice-bg` | The active tab, the unsaved-changes dot, and highlighted rows (current problem, notices). |
|
||||
| `syntax-keyword`, `syntax-string`, `syntax-number`, `syntax-comment`, `syntax-variable`, `syntax-function`, `syntax-type`, `syntax-constant`, `syntax-tag`, `syntax-attribute`, `syntax-operator` | Syntax highlighting; also the colours of completion kind icons and the Structure window. Text on `editor-bg` and `editor-active-line-bg`. |
|
||||
| `diag-error`, `diag-warning`, `diag-info`, `diag-hint` | Underlines, gutter markers and Problems icons; text on `editor-bg`, `editor-active-line-bg` and `bg`. |
|
||||
| `vcs-added`, `vcs-modified`, `vcs-deleted`, `vcs-untracked`, `vcs-ignored`, `vcs-conflicted` | Git status colours of file names in the tree and tabs and of the change markers; text on `bg`, `editor-bg`, `editor-active-line-bg` and `tab-active-bg`. |
|
||||
| `terminal-bg`, `terminal-fg`, `terminal-cursor`, `terminal-selection-bg` | The terminal. |
|
||||
| `terminal-ansi-black` … `terminal-ansi-white`, `terminal-ansi-bright-black` … `terminal-ansi-bright-white` (16) | ANSI colours in the order black, red, green, yellow, blue, magenta, cyan, white. They are text on `terminal-bg`, except the one meant to vanish into it (black in a dark theme, white and bright white in a light one). |
|
||||
|
||||
## For contributors
|
||||
|
||||
- A built-in theme is a `Theme` constant in `crates/engine/src/theme.rs`, listed in `BUILTIN`, with its name in `ui/src/i18n/en.json` (`theme.<camelId>` and `settings.appearance.theme.value.<camelId>`).
|
||||
- Every built-in theme defines exactly the tokens of `DARK` (a Rust test checks it). After changing a token, run the engine tests with `LUTRA_UPDATE_SNAPSHOTS=1` to rewrite `ui/tests/theme/themes.json`. The Vitest contrast test reads that file.
|
||||
- A new token needs a value in every theme, a row above, and a contrast pair in `contrast.test.ts` if text or marks are drawn with it.
|
||||
- The code font IBM Plex Mono comes from `@fontsource/ibm-plex-mono` (Latin and Latin Extended, 400 and 700 with italics, about 118 KB), imported in `ui/src/main.ts`, and leads `font-mono` (`COMMON` in `theme.rs`) and `MONO_FALLBACK` (`ui/src/stores/settings.ts`). Daniel chose it from four candidates Amy compared (D28); OFL-1.1 is allowed for this package only (`PACKAGE_EXCEPTIONS` in `xtask/src/licences.rs`, comment in `deny.toml`). The UI font stays the system font.
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-06 | minor | IBM Plex Mono bundled as the code font, italic comments (D28) |
|
||||
| 2026-11-02 | major | First version: four new built-in themes, theme file format and import, editor font settings (C9 T1) |
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# UI parity checklist
|
||||
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10) · **Last updated:** 2026-11-01
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10), four more themes, theme import and editor font settings (C9 T1) · **Last updated:** 2026-11-02
|
||||
|
||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
|
||||
|
|
@ -24,8 +24,9 @@
|
|||
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
|
||||
- M1.8 (2026-10-16): the global keymap built from the default shortcuts of engine and UI commands; no user keymap and no editor yet.
|
||||
- [ ] Light and dark themes from theme tokens
|
||||
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). M1.9b: theme picker in the settings dialog, editor font size from `editor.fontSize`. Missing: a theme command in the palette, the native title bar following the theme, colour scheme editor, high-contrast theme.
|
||||
- M1.10 (2026-10-16): Lutra Dark and Lutra Light from Rust tokens, switched live through `appearance.theme` (no reload), `system` follows the OS preference, the first frame uses the stored theme; the editor (selection, active line, cursor, gutter, matches), tabs and notices have their own tokens; WCAG AA contrast checked by Vitest for every text pair in both themes. Covered by Vitest DOM and control-channel tests; live check pending (gaming mode). M1.9b: theme picker in the settings dialog, editor font size from `editor.fontSize`. Missing: the native title bar following the theme, colour scheme editor, high-contrast theme (the palette command came with C9 T1).
|
||||
- H5 (2026-10-25): both themes follow the README banner, approved by the owner from before/after screenshots (tree, PHP editor, Problems, terminal, palette, settings; Windows 11, bundled UI, control port 7955): cream-tinted light theme, faintly plum-tinted dark theme, raspberry only as the accent, retuned syntax colours, the terminal on the editor surface. Diagnostics get their own colours (`--lt-diag-*`: error, amber warning, blue info, muted hint) in the underline, gutter dot, tooltip stripe and Problems icon; `--lt-vcs-*` status colours for M4.4; completion kind icons coloured by kind. Every text colour ≥ 4.5:1 and icon colour ≥ 3:1 in both themes (Vitest contrast test).
|
||||
- C9 T1 (2026-11-02): four more built-in themes designed by Amy and approved by the owner: Plum Night and River (dark), Paper and Reed (light), each with the full token set and AA contrast checked by the Vitest contrast test. "Select Theme…" (`view.selectTheme`, View menu, palette) opens a picker that previews live while moving and restores on Escape; `theme.select`, `theme.current` and `theme.list` serve agents. Theme files (JSON, every colour token, validated; `docs/themes.md`) come in through "Import Theme…" (`view.importTheme`) or `theme.import`, are stored in Lutra's data directory and appear in the picker and the settings; a broken file gives the reason, a broken stored file is skipped with a warning. Editor font family and line height settings join the font size, all live. Missing: a colour scheme editor, exporting and removing themes in the UI, per-token font styles, a high-contrast theme. Lutra's own code font, IBM Plex Mono (owner's choice, D28), ships for the editor and the terminal, with italic comments.
|
||||
- [ ] Notifications and background task indicator
|
||||
- M1.12 (2026-10-16): toasts at the bottom right for engine and host notifications (corrupt settings and journal entries at startup, folder that cannot be opened, `unsaved_changes` when switching projects, file watching stopped, failed commands without their own UI): info dismissed after 5 s, warnings and errors stay until closed, close button and Escape, at most 5 visible with "+n more", `role="status"`/`role="alert"`; startup notifications are replayed when the page starts listening. Vitest (19 store and component tests); live check pending (gaming mode). Missing: a notification log / Notifications tool window, actions inside a toast, balloon grouping, "don't show again", background task indicator with progress.
|
||||
- [ ] Structure tool window
|
||||
|
|
@ -51,6 +52,7 @@
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | minor | Four more themes, theme picker, theme file import, editor font family and line height (C9 T1) |
|
||||
| 2026-11-01 | patch | Chunk popup from the gutter and the diff viewer, staged markers, partly staged rows (C8 C3) |
|
||||
| 2026-10-31 | patch | Changes context menu with Add to .gitignore and the merge message prefill (C7 A3) |
|
||||
| 2026-10-28 | minor | Fetch/pull/push with progress, clone and remotes dialogs (M4.10) |
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@
|
|||
"@codemirror/merge": "^6.12.3",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.14",
|
||||
"@fontsource/ibm-plex-mono": "^5.3.0",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@lucide/vue": "^1.57.0",
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
|
|
|
|||
8
ui/pnpm-lock.yaml
generated
8
ui/pnpm-lock.yaml
generated
|
|
@ -47,6 +47,9 @@ importers:
|
|||
'@codemirror/view':
|
||||
specifier: ^6.43.14
|
||||
version: 6.43.14
|
||||
'@fontsource/ibm-plex-mono':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.5
|
||||
version: 1.2.5
|
||||
|
|
@ -284,6 +287,9 @@ packages:
|
|||
'@noble/hashes':
|
||||
optional: true
|
||||
|
||||
'@fontsource/ibm-plex-mono@5.3.0':
|
||||
resolution: {integrity: sha512-eTgnZjZEGk1QtD3ZstF+Vclo2HLAni8YMy34/DxllwZvyz1lR/1RF/xTiAquOBO7MvqBx8D2Ig2WCPMVfdZu7Q==}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
|
||||
engines: {node: '>=18.18.0'}
|
||||
|
|
@ -1620,6 +1626,8 @@ snapshots:
|
|||
|
||||
'@exodus/bytes@1.16.0': {}
|
||||
|
||||
'@fontsource/ibm-plex-mono@5.3.0': {}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
dependencies:
|
||||
'@humanfs/types': 0.15.0
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
* Root component: mounts the main window layout with the editor area; the
|
||||
* slogan shows while no tab is open, and the restore dialog for unsaved
|
||||
* texts from the recovery journal, the toast stack, the command palette,
|
||||
* the go-to popup, the settings dialog and the merge dialog. Loads product information from the engine on
|
||||
* the go-to popup, the settings dialog, the merge dialog and the theme
|
||||
* picker. Loads product information from the engine on
|
||||
* mount, starts showing notifications, following the theme (see
|
||||
* `theme.ts`; a failed theme report raises an error toast) and the global
|
||||
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
|
||||
|
|
@ -22,6 +23,7 @@ import NotificationStack from "./components/notifications/NotificationStack.vue"
|
|||
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
||||
import SettingsDialog from "./components/settings/SettingsDialog.vue";
|
||||
import MergeDialog from "./components/vcs/merge/MergeDialog.vue";
|
||||
import ThemePicker from "./components/theme/ThemePicker.vue";
|
||||
import { useAppStore } from "./stores/app";
|
||||
import { useAutosaveStore } from "./stores/autosave";
|
||||
import { useNotificationsStore } from "./stores/notifications";
|
||||
|
|
@ -73,6 +75,7 @@ onUnmounted(() => {
|
|||
<GotoPopup />
|
||||
<SettingsDialog />
|
||||
<MergeDialog />
|
||||
<ThemePicker />
|
||||
<NavLayer />
|
||||
<NotificationStack />
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -20,8 +20,8 @@
|
|||
* - **Navigation (M3.5):** the definition picker and the inline rename field
|
||||
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
||||
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
||||
* dialog (M4.8) and the stash dialog (M4.9), and the deployment servers
|
||||
* dialog (G17).
|
||||
* dialog (M4.8) and the stash dialog (M4.9), the deployment servers
|
||||
* dialog (G17) and the theme picker (C9 T1).
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, watch } from "vue";
|
||||
|
|
@ -41,7 +41,8 @@ export type ModalId =
|
|||
| "remotes"
|
||||
| "deployment"
|
||||
| "merge"
|
||||
| "stash";
|
||||
| "stash"
|
||||
| "themes";
|
||||
|
||||
/** Store of the open exclusive modal. */
|
||||
export const useModalsStore = defineStore("modals", () => {
|
||||
|
|
|
|||
|
|
@ -66,4 +66,6 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
|
||||
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
|
||||
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
|
||||
{ id: "view.selectTheme", labelKey: "command.view.selectTheme", menuPath: "View/Select Theme…" },
|
||||
{ id: "view.importTheme", labelKey: "command.view.importTheme", menuPath: "View/Import Theme…" },
|
||||
];
|
||||
|
|
|
|||
|
|
@ -22,12 +22,13 @@ import { gitGutterExtensions } from "./gitGutter";
|
|||
/**
|
||||
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
|
||||
* token each, spelled out so the theme tests can check every token name.
|
||||
* Comments are set in italic, the bundled code font's real italic (D28).
|
||||
*/
|
||||
const syntaxColours: Record<`.${typeof SYNTAX_CLASS}${SyntaxToken}`, { color: string }> = {
|
||||
const syntaxColours: Record<`.${typeof SYNTAX_CLASS}${SyntaxToken}`, { color: string; fontStyle?: string }> = {
|
||||
".lt-syntax-keyword": { color: "var(--lt-syntax-keyword)" },
|
||||
".lt-syntax-string": { color: "var(--lt-syntax-string)" },
|
||||
".lt-syntax-number": { color: "var(--lt-syntax-number)" },
|
||||
".lt-syntax-comment": { color: "var(--lt-syntax-comment)" },
|
||||
".lt-syntax-comment": { color: "var(--lt-syntax-comment)", fontStyle: "italic" },
|
||||
".lt-syntax-variable": { color: "var(--lt-syntax-variable)" },
|
||||
".lt-syntax-function": { color: "var(--lt-syntax-function)" },
|
||||
".lt-syntax-type": { color: "var(--lt-syntax-type)" },
|
||||
|
|
@ -50,7 +51,7 @@ export const lutraEditorTheme: Extension = EditorView.theme({
|
|||
},
|
||||
".cm-scroller": {
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
lineHeight: "1.5",
|
||||
lineHeight: "var(--lt-line-height-editor)",
|
||||
},
|
||||
".cm-content": {
|
||||
caretColor: "var(--lt-editor-cursor)",
|
||||
|
|
|
|||
285
ui/src/components/theme/ThemePicker.vue
Normal file
285
ui/src/components/theme/ThemePicker.vue
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The theme picker (C9 T1): "Select Theme…" lists the built-in and imported
|
||||
* themes with a swatch of each (window, editor, accent, keyword and string
|
||||
* colour) and "Same as system". Up/Down, Home and End move the selection
|
||||
* and preview the theme live; Enter or a click switches to it; Escape or a
|
||||
* click outside puts the previous theme back. Also supplies "Import
|
||||
* Theme…". An exclusive modal (`commands/modals.ts`).
|
||||
*/
|
||||
import { Monitor } from "@lucide/vue";
|
||||
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { useModalsStore } from "../../commands/modals";
|
||||
import { useCommandsStore } from "../../commands/store";
|
||||
import { t } from "../../i18n";
|
||||
import { useThemesStore, type ThemeInfo } from "./themes";
|
||||
|
||||
const themes = useThemesStore();
|
||||
const modals = useModalsStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** The list element, which holds the focus. */
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
|
||||
/** Element that had the focus before the picker opened. */
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
|
||||
/** Withdraws the UI commands; set while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
/** Swatch tokens, in the order they are drawn. */
|
||||
const SWATCH = ["--lt-bg", "--lt-editor-bg", "--lt-accent", "--lt-syntax-keyword", "--lt-syntax-string"] as const;
|
||||
|
||||
/**
|
||||
* The swatch colours of a theme.
|
||||
*
|
||||
* @param info - the theme.
|
||||
* @returns CSS colours; empty for "Same as system".
|
||||
*/
|
||||
function swatch(info: ThemeInfo): string[] {
|
||||
const tokens = info.theme?.tokens ?? {};
|
||||
return SWATCH.map((name) => tokens[name] ?? "transparent");
|
||||
}
|
||||
|
||||
/**
|
||||
* The second line of a row: dark or light, and whether it was imported.
|
||||
*
|
||||
* @param info - the theme.
|
||||
*/
|
||||
function kindOf(info: ThemeInfo): string {
|
||||
if (info.dark === null) {
|
||||
return t("theme.picker.followsSystem");
|
||||
}
|
||||
const mode = info.dark ? t("theme.picker.dark") : t("theme.picker.light");
|
||||
return info.builtin ? mode : t("theme.picker.imported", { mode });
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the list.
|
||||
*
|
||||
* @param event - the key press.
|
||||
*/
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
const count = themes.items.length;
|
||||
const moves: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, Home: -count, End: count };
|
||||
const delta = moves[event.key];
|
||||
if (delta !== undefined) {
|
||||
themes.move(delta);
|
||||
scrollSelected();
|
||||
} else if (event.key === "Enter") {
|
||||
void themes.choose();
|
||||
} else if (event.key === "Escape") {
|
||||
themes.cancel();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
/** Keeps the selected row in view. */
|
||||
function scrollSelected(): void {
|
||||
void nextTick(() => {
|
||||
const row = list.value?.querySelector<HTMLElement>(`#lt-theme-${String(themes.selected)}`);
|
||||
if (row && typeof row.scrollIntoView === "function") {
|
||||
row.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
watch(
|
||||
() => themes.open,
|
||||
(open) => {
|
||||
if (open) {
|
||||
const active = document.activeElement;
|
||||
returnFocus = active instanceof HTMLElement ? active : null;
|
||||
modals.opened("themes", () => {
|
||||
themes.cancel();
|
||||
});
|
||||
void nextTick(() => {
|
||||
list.value?.focus();
|
||||
scrollSelected();
|
||||
});
|
||||
} else {
|
||||
modals.closed("themes");
|
||||
returnFocus?.focus();
|
||||
returnFocus = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
withdraw = [
|
||||
commands.provide("view.selectTheme", { run: () => themes.show() }),
|
||||
commands.provide("view.importTheme", { run: () => themes.importFile() }),
|
||||
];
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
for (const stop of withdraw) {
|
||||
stop();
|
||||
}
|
||||
withdraw = [];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="themes.open"
|
||||
class="theme-picker"
|
||||
data-test="theme-picker"
|
||||
@mousedown.self.prevent="themes.cancel()"
|
||||
>
|
||||
<div
|
||||
class="theme-picker__dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('theme.picker.title')"
|
||||
>
|
||||
<p class="theme-picker__title">
|
||||
{{ t("theme.picker.title") }}
|
||||
</p>
|
||||
<ul
|
||||
ref="list"
|
||||
class="theme-picker__list"
|
||||
role="listbox"
|
||||
tabindex="0"
|
||||
:aria-label="t('theme.picker.title')"
|
||||
:aria-activedescendant="`lt-theme-${String(themes.selected)}`"
|
||||
data-test="theme-picker-list"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<li
|
||||
v-for="(item, index) in themes.items"
|
||||
:id="`lt-theme-${String(index)}`"
|
||||
:key="item.id"
|
||||
class="theme-picker__row"
|
||||
:class="{ 'theme-picker__row--selected': index === themes.selected }"
|
||||
role="option"
|
||||
:aria-selected="index === themes.selected"
|
||||
:data-id="item.id"
|
||||
data-test="theme-picker-row"
|
||||
@mousemove="themes.hover(index)"
|
||||
@mousedown.prevent
|
||||
@click="themes.choose(index)"
|
||||
>
|
||||
<span
|
||||
v-if="item.theme"
|
||||
class="theme-picker__swatch"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span
|
||||
v-for="(colour, part) in swatch(item)"
|
||||
:key="part"
|
||||
class="theme-picker__chip"
|
||||
:style="{ background: colour }"
|
||||
/>
|
||||
</span>
|
||||
<Monitor
|
||||
v-else
|
||||
class="theme-picker__icon"
|
||||
:size="14"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="theme-picker__name">{{ item.name }}</span>
|
||||
<span class="theme-picker__kind">{{ kindOf(item) }}</span>
|
||||
<span
|
||||
v-if="item.id === themes.initialId"
|
||||
class="theme-picker__current"
|
||||
>{{ t("theme.picker.current") }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.theme-picker {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 12vh;
|
||||
background: color-mix(in srgb, var(--lt-bg) 40%, transparent);
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.theme-picker__dialog {
|
||||
width: min(480px, 90vw);
|
||||
max-height: 60vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--lt-bg);
|
||||
color: var(--lt-fg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.theme-picker__title {
|
||||
margin: 0;
|
||||
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
|
||||
font-weight: 600;
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
}
|
||||
|
||||
.theme-picker__list {
|
||||
margin: 0;
|
||||
padding: var(--lt-space-s, 4px) 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.theme-picker__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--lt-space-m, 8px);
|
||||
padding: 5px var(--lt-space-m, 8px);
|
||||
white-space: nowrap;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.theme-picker__row--selected {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.theme-picker__swatch {
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.theme-picker__chip {
|
||||
width: 10px;
|
||||
height: 14px;
|
||||
}
|
||||
|
||||
.theme-picker__icon {
|
||||
flex-shrink: 0;
|
||||
width: 52px;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.theme-picker__name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.theme-picker__kind,
|
||||
.theme-picker__current {
|
||||
flex-shrink: 0;
|
||||
color: var(--lt-fg-muted);
|
||||
font-size: var(--lt-font-size-small);
|
||||
}
|
||||
|
||||
.theme-picker__row--selected .theme-picker__kind,
|
||||
.theme-picker__row--selected .theme-picker__current {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
</style>
|
||||
232
ui/src/components/theme/themes.ts
Normal file
232
ui/src/components/theme/themes.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||
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<ThemeInfo[]>([]);
|
||||
/** 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<string | null>(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<void> {
|
||||
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<string, unknown> } | 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<void> {
|
||||
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<void> {
|
||||
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: "notification.theme.imported",
|
||||
params: { name: typeof name === "string" ? name : picked.value },
|
||||
});
|
||||
}
|
||||
|
||||
return { items, selected, open, initialId, current, show, move, hover, cancel, choose, importFile };
|
||||
});
|
||||
|
|
@ -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",
|
||||
|
|
@ -274,6 +276,8 @@
|
|||
"notification.settings.unavailable": "Settings cannot be loaded ({error}). The defaults are used and changes are not saved.",
|
||||
"notification.stack.label": "Notifications",
|
||||
"notification.stack.more": "+{count} more",
|
||||
"notification.theme.imported": "Imported the theme {name}.",
|
||||
"notification.theme.skipped": "Skipped the theme file {file}: {reason}",
|
||||
"notification.toolchain.downloadDone": "Phpactor {version} is ready, downloaded and verified in {seconds} s.",
|
||||
"notification.toolchain.downloadFailed": "Phpactor {version} could not be downloaded: {reason}",
|
||||
"notification.toolchain.downloadStarted": "Downloading Phpactor {version} from GitHub for PHP language features…",
|
||||
|
|
@ -359,6 +363,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 +388,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 +448,19 @@
|
|||
"terminal.tab.numbered": "Local ({n})",
|
||||
"terminal.tabs.label": "Terminals",
|
||||
"terminal.toolWindow.title": "Terminal",
|
||||
"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.picker.current": "current",
|
||||
"theme.picker.dark": "Dark",
|
||||
"theme.picker.followsSystem": "Light or dark, as your 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",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,18 @@
|
|||
/**
|
||||
* Entry point of the Lutra frontend: creates the Vue app with Pinia and
|
||||
* mounts it on `#app`.
|
||||
* mounts it on `#app`. Loads Lutra's bundled code font, IBM Plex Mono
|
||||
* (OFL-1.1, owner decision D28), for the editor and the terminal: regular,
|
||||
* bold and their italics, in the Latin and Latin Extended subsets, so the
|
||||
* app needs no network and comments get a real italic.
|
||||
*/
|
||||
import "@fontsource/ibm-plex-mono/latin-400.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-400-italic.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-700.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-700-italic.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-ext-400.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-ext-400-italic.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-ext-700.css";
|
||||
import "@fontsource/ibm-plex-mono/latin-ext-700-italic.css";
|
||||
import { createPinia } from "pinia";
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
|
|
|
|||
|
|
@ -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.<key>.label`, `settings.<key>.description`,
|
||||
* `settings.section.<id>`, `settings.<key>.value.<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<string, string>;
|
||||
/** 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 = '"IBM Plex Mono", 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<Record<string, string>> = {
|
||||
[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<string, unknown>;
|
||||
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<string, string> = {};
|
||||
if (typeof valueNames === "object" && valueNames !== null) {
|
||||
for (const [value, name] of Object.entries(valueNames as Record<string, unknown>)) {
|
||||
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.<key>.value.<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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -85,10 +85,18 @@ function camel(value: string): string {
|
|||
* - Rust `*_key: "…"` fields: theme labels and the settings' `labelKey`
|
||||
* and `descriptionKey`;
|
||||
* - per settings definition, its section name (`settings.section.<s>`) and
|
||||
* each enum value (`settings.<key>.value.<value>`).
|
||||
* each enum value (`settings.<key>.value.<value>`); a `Kind::Theme`
|
||||
* setting has every built-in theme id of `theme.rs` and `system` as
|
||||
* values (C9 T1).
|
||||
*/
|
||||
const RUNTIME_KEYS = (() => {
|
||||
const keys = new Set<string>();
|
||||
const themeIds = [
|
||||
...[...shippedRust(join(REPO, "crates", "engine", "src", "theme.rs")).matchAll(/\bid:\s*"([a-z0-9-]+)"/g)].map(
|
||||
(m) => m[1] ?? "",
|
||||
),
|
||||
"system",
|
||||
];
|
||||
const add = (text: string, pattern: RegExp): void => {
|
||||
for (const m of text.matchAll(pattern)) {
|
||||
keys.add(m[1] ?? "");
|
||||
|
|
@ -112,6 +120,11 @@ const RUNTIME_KEYS = (() => {
|
|||
for (const value of values.matchAll(/"([^"]+)"/g)) {
|
||||
keys.add(`settings.${key ?? ""}.value.${camel(value[1] ?? "")}`);
|
||||
}
|
||||
if (/Kind::Theme\b/.test(body)) {
|
||||
for (const id of themeIds) {
|
||||
keys.add(`settings.${key ?? ""}.value.${camel(id)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
keys.delete("");
|
||||
|
|
|
|||
178
ui/tests/settings/fontSettings.test.ts
Normal file
178
ui/tests/settings/fontSettings.test.ts
Normal file
|
|
@ -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<string, unknown> {
|
||||
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<string, unknown>;
|
||||
/** 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<string, unknown> }) => {
|
||||
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<void> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
279
ui/tests/theme/ThemePicker.test.ts
Normal file
279
ui/tests/theme/ThemePicker.test.ts
Normal file
|
|
@ -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<string, unknown> }[];
|
||||
/** What `pick_file` returns. */
|
||||
let picked: string | null;
|
||||
/** Commands that fail, with their message. */
|
||||
let failing: Map<string, string>;
|
||||
/** 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<string, string> } {
|
||||
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<string, unknown>): 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<VueWrapper> {
|
||||
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<void> {
|
||||
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<string, unknown> }) => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
|
@ -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<string, readonly string[]> = {
|
||||
"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, string>): 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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,11 +21,12 @@
|
|||
"--lt-error": "#f2836b",
|
||||
"--lt-fg": "#ebe5dc",
|
||||
"--lt-fg-muted": "#9e9499",
|
||||
"--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace",
|
||||
"--lt-font-mono": "\"IBM Plex 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": "#382632",
|
||||
"--lt-statusbar-bg": "#231f23",
|
||||
"--lt-statusbar-fg": "#bdb3b8",
|
||||
|
|
@ -92,11 +93,12 @@
|
|||
"--lt-error": "#b23a29",
|
||||
"--lt-fg": "#2a2427",
|
||||
"--lt-fg-muted": "#675d61",
|
||||
"--lt-font-mono": "ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace",
|
||||
"--lt-font-mono": "\"IBM Plex 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": "#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": "\"IBM Plex 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": "\"IBM Plex 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": "\"IBM Plex 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": "\"IBM Plex 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"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -21,6 +21,12 @@ pub const ALLOWED: &[&str] = &[
|
|||
"Unicode-3.0",
|
||||
];
|
||||
|
||||
/// Package-scoped exceptions: a package and the one extra licence it may
|
||||
/// carry, each approved by the owner. They do not widen [`ALLOWED`] for any
|
||||
/// other package. `@fontsource/ibm-plex-mono` is Lutra's bundled code font
|
||||
/// under the SIL Open Font License 1.1 (owner decision D28, 2026-11-06).
|
||||
pub const PACKAGE_EXCEPTIONS: &[(&str, &str)] = &[("@fontsource/ibm-plex-mono", "OFL-1.1")];
|
||||
|
||||
/// Runs the check on the production dependencies of `ui/`.
|
||||
///
|
||||
/// # Errors
|
||||
|
|
@ -61,6 +67,9 @@ pub fn check_pnpm_report(json: &str) -> TaskResult<Vec<String>> {
|
|||
}
|
||||
for package in packages.as_array().into_iter().flatten() {
|
||||
let name = package.get("name").and_then(Value::as_str).unwrap_or("?");
|
||||
if PACKAGE_EXCEPTIONS.contains(&(name, licence.as_str())) {
|
||||
continue;
|
||||
}
|
||||
problems.push(format!("{name}: {licence}"));
|
||||
}
|
||||
}
|
||||
|
|
@ -102,4 +111,19 @@ mod tests {
|
|||
vec!["bad: GPL-3.0".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_font_exception_covers_only_its_package_and_licence() {
|
||||
let json = r#"{"OFL-1.1":[{"name":"@fontsource/ibm-plex-mono"},{"name":"@fontsource/other"}],"GPL-3.0":[{"name":"@fontsource/ibm-plex-mono"}]}"#;
|
||||
let mut problems = check_pnpm_report(json).unwrap();
|
||||
problems.sort();
|
||||
assert_eq!(
|
||||
problems,
|
||||
vec![
|
||||
"@fontsource/ibm-plex-mono: GPL-3.0".to_string(),
|
||||
"@fontsource/other: OFL-1.1".to_string()
|
||||
]
|
||||
);
|
||||
assert!(!is_allowed("OFL-1.1"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue