diff --git a/README.md b/README.md index 30ebf0a..e1e7a35 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ SFTP · SCP · FTP/FTPS · WebDAV · S3 · Azure · Google Cloud Storage — on ### 🗂️ Classic commander, modern feel Two panels, session tabs, bookmarks, drag & drop and full keyboard control with the **original Norton Commander layout** and function key bar — or Total Commander's. -Light and dark theme, English and German. +Light and dark theme, ten skins, English and German. @@ -107,6 +107,17 @@ through any SSH session. Host-key verification, TLS checks, an encrypted credential vault (XChaCha20-Poly1305, optional Argon2id master password), throttled and CSRF-protected web logins. + + + + + +### 🎨 Skins +Ten built-in skins — from the standard look to *Retro Blue*, *Nord*, *Solarized*, *Catppuccin*, +*Gruvbox*, *Dracula* and *High Contrast* — that color everything, terminal and editor included. +Adjust accent, row height, fonts and corners, or **create your own** in the skin editor or as a +small JSON file: [Skins](docs/src/guide/skins.md) · [Creating skins](docs/src/guide/creating-skins.md). + @@ -120,6 +131,8 @@ optional Argon2id master password), throttled and CSRF-protected web logins. | ![Remote Explorer](docs/src/images/remote-explorer.png) | ![Synchronization checklist](docs/src/images/sync-checklist.png) | | **Nearby instances on the LAN** | **Share this instance** | | ![Nearby](docs/src/images/nearby.png) | ![Share this instance](docs/src/images/share.png) | +| **Skins** | **Skin editor** | +| ![Skins in Preferences](docs/src/images/skins-gallery.png) | ![Skin editor](docs/src/images/skin-editor.png) | ## 🚀 Quick start @@ -176,6 +189,7 @@ The full documentation lives in [`docs/`](docs/) and can be built as a website w | **Deployment** | [Editor](docs/src/guide/editor.md) · [Remote Explorer](docs/src/guide/remote-explorer.md) | **Development** | | [Headless server](docs/src/deployment/headless-server.md) | [Terminal and SSH tunnels](docs/src/guide/terminal-and-tunnels.md) | [Architecture](docs/src/development/architecture.md) | | [Security](docs/src/deployment/security.md) | [LAN discovery](docs/src/guide/lan-discovery.md) · [Web mode](docs/src/guide/web-mode.md) | [Testing](docs/src/development/testing.md) · [Releasing](docs/src/development/releasing.md) | +| | [Skins](docs/src/guide/skins.md) · [Creating skins](docs/src/guide/creating-skins.md) | [Skin tokens](docs/src/reference/skin-tokens.md) | ## 🛠️ Building diff --git a/crates/rc-api/src/dispatch.rs b/crates/rc-api/src/dispatch.rs index c127e4d..ce771f4 100644 --- a/crates/rc-api/src/dispatch.rs +++ b/crates/rc-api/src/dispatch.rs @@ -18,6 +18,7 @@ use rc_core::{Error, Protocol}; use crate::handlers::{compare, discovery, edit, explorer, format, fs, jobs, misc, sessions, terminal}; use crate::server::ServerStatus; use crate::settings::Settings; +use crate::skins; use crate::state::{AppState, Bookmark, CustomCommand, Origin}; /// Error returned to the UI. @@ -540,6 +541,25 @@ pub async fn dispatch(state: &Arc, origin: &Origin, method: &str, para } "commands.run" => ok(misc::command_run(st, origin, parse(params)?).await?), + // ---------------------------------------------------------- skins + "skins.list" => ok(skins::list(&skins::skins_dir(&st.config_dir))), + "skins.save" => { + #[derive(Deserialize)] + struct P { + skin: Value, + } + let p: P = parse(params)?; + let saved = skins::save(&skins::skins_dir(&st.config_dir), p.skin)?; + st.events.emit("skins.changed", json!({ "id": saved.skin["id"] })); + ok(saved) + } + "skins.delete" => { + let p: Id = parse(params)?; + skins::delete(&skins::skins_dir(&st.config_dir), &p.id)?; + st.events.emit("skins.changed", json!({ "id": p.id })); + ok(Value::Null) + } + // ---------------------------------------------------------- external editing "edit.external" => { desktop_only(origin)?; diff --git a/crates/rc-api/src/lib.rs b/crates/rc-api/src/lib.rs index 9a99c66..16ed00c 100644 --- a/crates/rc-api/src/lib.rs +++ b/crates/rc-api/src/lib.rs @@ -13,6 +13,7 @@ pub mod persist; pub mod prompts; pub mod server; pub mod settings; +pub mod skins; pub mod state; pub use dispatch::{dispatch, RpcError}; diff --git a/crates/rc-api/src/settings.rs b/crates/rc-api/src/settings.rs index 287b162..5507655 100644 --- a/crates/rc-api/src/settings.rs +++ b/crates/rc-api/src/settings.rs @@ -89,11 +89,52 @@ impl Default for TerminalSettings { } } +/// Look of the user interface: a skin plus the user's own adjustments on top of it. +/// `None` = what the skin says. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct AppearanceSettings { + /// Id of a built-in skin or of a file in `/skins/`. Unknown ids fall back + /// to "default". + pub skin: String, + /// Accent color (CSS color), for both the light and the dark variant. + pub accent: Option, + /// File list density: "compact", "normal" or "comfortable". + pub density: Option, + /// Font size of the file lists in pixels. + pub list_font_size: Option, + /// Corner radius of controls in pixels. + pub radius: Option, + /// Alternating row backgrounds in the file lists. + pub stripes: Option, + /// Font of the user interface (CSS font-family). + pub font_ui: Option, + /// Monospaced font (paths, editor, permissions). + pub font_mono: Option, +} + +impl Default for AppearanceSettings { + fn default() -> Self { + AppearanceSettings { + skin: "default".into(), + accent: None, + density: None, + list_font_size: None, + radius: None, + stripes: None, + font_ui: None, + font_mono: None, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct Settings { pub language: String, + /// "system", "light" or "dark": which variant of the skin to show. pub theme: String, + pub appearance: AppearanceSettings, pub show_hidden: bool, pub confirm_delete: bool, pub confirm_overwrite: bool, @@ -123,6 +164,7 @@ impl Default for Settings { Settings { language: "auto".into(), theme: "system".into(), + appearance: AppearanceSettings::default(), show_hidden: false, confirm_delete: true, confirm_overwrite: true, @@ -162,4 +204,20 @@ mod tests { assert_eq!(v["keymap"], "total"); assert_eq!(v["showKeyBar"], false); } + + #[test] + fn appearance_defaults_to_the_default_skin() { + let s: Settings = serde_json::from_str(r#"{ "theme": "dark" }"#).unwrap(); + assert_eq!(s.appearance.skin, "default"); + assert!(s.appearance.accent.is_none()); + + let s: Settings = + serde_json::from_str(r##"{ "appearance": { "skin": "nord", "accent": "#ff8800", "stripes": true } }"##) + .unwrap(); + assert_eq!(s.appearance.skin, "nord"); + assert_eq!(s.appearance.accent.as_deref(), Some("#ff8800")); + let v = serde_json::to_value(&s).unwrap(); + assert_eq!(v["appearance"]["stripes"], true); + assert_eq!(v["appearance"]["listFontSize"], serde_json::Value::Null); + } } diff --git a/crates/rc-api/src/skins.rs b/crates/rc-api/src/skins.rs new file mode 100644 index 0000000..4ebbf6d --- /dev/null +++ b/crates/rc-api/src/skins.rs @@ -0,0 +1,224 @@ +//! User skins: one JSON file per skin in `/skins/`. +//! +//! The skin format (colors, fonts, shapes) is interpreted by the user interface, which +//! validates every value before it applies it (see `ui/src/lib/skins/`). The backend only +//! stores the files: it checks that a skin is a JSON object with a usable `id` and `name`, +//! keeps them small, and makes sure an id can never name a file outside the skins folder. +//! +//! Files may also be dropped into the folder by hand. Their `id` decides which skin they +//! are; a file without one uses its file name (`ocean.json` → `ocean`). + +use std::path::{Path, PathBuf}; + +use serde::Serialize; +use serde_json::Value; + +use rc_core::store::save_json; +use rc_core::{Error, Result}; + +/// Larger files are not skins (and would slow down every start of the UI). +pub const MAX_SKIN_BYTES: u64 = 256 * 1024; +/// At most this many skins are loaded. +pub const MAX_SKINS: usize = 200; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SkinFile { + /// File name inside the skins folder. + pub file: String, + /// The skin as stored (`id` is always set). + pub skin: Value, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SkinFileError { + pub file: String, + pub message: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SkinList { + /// The skins folder (native path), for "open folder" and the documentation. + pub dir: String, + pub skins: Vec, + /// Files that could not be loaded. + pub errors: Vec, +} + +pub fn skins_dir(config_dir: &Path) -> PathBuf { + config_dir.join("skins") +} + +/// `a-z`, `0-9`, `-` and `_`, starting with a letter or digit, at most 64 characters. +pub fn valid_id(id: &str) -> bool { + let b = id.as_bytes(); + !b.is_empty() + && b.len() <= 64 + && (b[0].is_ascii_lowercase() || b[0].is_ascii_digit()) + && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-' || *c == b'_') +} + +fn read_skin(path: &Path) -> std::result::Result { + let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; + if meta.len() > MAX_SKIN_BYTES { + return Err(format!("larger than {} KiB", MAX_SKIN_BYTES / 1024)); + } + let data = std::fs::read(path).map_err(|e| e.to_string())?; + let mut v: Value = serde_json::from_slice(&data).map_err(|e| format!("invalid JSON: {e}"))?; + let obj = v.as_object_mut().ok_or("not a JSON object")?; + let id = match obj.get("id") { + Some(Value::String(id)) => id.clone(), + None => path.file_stem().and_then(|s| s.to_str()).unwrap_or_default().to_ascii_lowercase(), + Some(_) => return Err("\"id\" is not a string".into()), + }; + if !valid_id(&id) { + return Err(format!("invalid id {id:?} (use a-z, 0-9, - and _)")); + } + obj.insert("id".into(), Value::String(id)); + Ok(v) +} + +/// All skins in `dir`, sorted by file name. A missing folder is an empty list. +pub fn list(dir: &Path) -> SkinList { + let mut out = SkinList { dir: dir.display().to_string(), skins: Vec::new(), errors: Vec::new() }; + let Ok(rd) = std::fs::read_dir(dir) else { + return out; + }; + let mut files: Vec = rd + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_file() && p.extension().is_some_and(|x| x.eq_ignore_ascii_case("json"))) + .collect(); + files.sort(); + for path in files { + let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if out.skins.len() >= MAX_SKINS { + out.errors.push(SkinFileError { file, message: format!("more than {MAX_SKINS} skins") }); + continue; + } + match read_skin(&path) { + Ok(skin) => { + let id = skin["id"].as_str().unwrap_or_default(); + if let Some(first) = out.skins.iter().find(|s| s.skin["id"] == id) { + let message = format!("id {id:?} is already used by {}", first.file); + out.errors.push(SkinFileError { file, message }); + } else { + out.skins.push(SkinFile { file, skin }); + } + } + Err(message) => out.errors.push(SkinFileError { file, message }), + } + } + out +} + +/// Store a skin (create or replace). A skin that came from a hand-named file is written +/// back to that file. +pub fn save(dir: &Path, mut skin: Value) -> Result { + let obj = skin.as_object_mut().ok_or_else(|| Error::InvalidInput("a skin must be a JSON object".into()))?; + let id = obj.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); + if !valid_id(&id) { + return Err(Error::InvalidInput(format!("invalid skin id {id:?} (use a-z, 0-9, - and _)"))); + } + let name_ok = obj.get("name").and_then(Value::as_str).is_some_and(|n| !n.trim().is_empty()); + if !name_ok { + return Err(Error::InvalidInput("a skin needs a name".into())); + } + let size = serde_json::to_vec_pretty(&skin)?.len() as u64; + if size > MAX_SKIN_BYTES { + return Err(Error::InvalidInput(format!("skin is larger than {} KiB", MAX_SKIN_BYTES / 1024))); + } + let existing = list(dir).skins.into_iter().find(|s| s.skin["id"] == id.as_str()); + let file = existing.map(|s| s.file).unwrap_or_else(|| format!("{id}.json")); + save_json(&dir.join(&file), &skin)?; + Ok(SkinFile { file, skin }) +} + +/// Remove the file(s) of a skin. Unknown ids are not an error. +pub fn delete(dir: &Path, id: &str) -> Result<()> { + if !valid_id(id) { + return Err(Error::InvalidInput(format!("invalid skin id {id:?}"))); + } + for s in list(dir).skins.into_iter().filter(|s| s.skin["id"] == id) { + let path = dir.join(&s.file); + std::fs::remove_file(&path).map_err(|e| Error::io_at(e, &path.display().to_string()))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn ids_cannot_leave_the_folder() { + for bad in ["", "../x", "a/b", "a\\b", "A", "-x", ".hidden", "x.json", &"x".repeat(65)] { + assert!(!valid_id(bad), "{bad:?} accepted"); + } + for good in ["default", "nord-2", "my_skin", "9lives"] { + assert!(valid_id(good), "{good:?} rejected"); + } + } + + #[test] + fn save_list_delete() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("skins"); + assert!(list(&dir).skins.is_empty()); + + let saved = save(&dir, json!({ "id": "ocean", "name": "Ocean", "dark": { "accent": "#0af" } })).unwrap(); + assert_eq!(saved.file, "ocean.json"); + let l = list(&dir); + assert_eq!(l.skins.len(), 1); + assert_eq!(l.skins[0].skin["dark"]["accent"], "#0af"); + + // replaced, not duplicated + save(&dir, json!({ "id": "ocean", "name": "Ocean 2" })).unwrap(); + let l = list(&dir); + assert_eq!(l.skins.len(), 1); + assert_eq!(l.skins[0].skin["name"], "Ocean 2"); + + delete(&dir, "ocean").unwrap(); + assert!(list(&dir).skins.is_empty()); + delete(&dir, "ocean").unwrap(); + } + + #[test] + fn rejects_invalid_skins() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + assert!(save(dir, json!([1, 2])).is_err()); + assert!(save(dir, json!({ "id": "../evil", "name": "x" })).is_err()); + assert!(save(dir, json!({ "id": "ok" })).is_err()); + assert!(save(dir, json!({ "id": "ok", "name": " " })).is_err()); + let huge = "x".repeat(MAX_SKIN_BYTES as usize); + assert!(save(dir, json!({ "id": "big", "name": "Big", "description": huge })).is_err()); + assert!(std::fs::read_dir(dir).unwrap().next().is_none(), "nothing may be written"); + } + + #[test] + fn hand_written_files() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + std::fs::write(dir.join("My Theme.json"), r#"{ "id": "mine", "name": "Mine" }"#).unwrap(); + std::fs::write(dir.join("sunset.json"), r#"{ "name": "Sunset" }"#).unwrap(); + std::fs::write(dir.join("broken.json"), "{ nope").unwrap(); + std::fs::write(dir.join("twice.json"), r#"{ "id": "mine", "name": "Again" }"#).unwrap(); + std::fs::write(dir.join("notes.txt"), "ignored").unwrap(); + + let l = list(dir); + let ids: Vec<_> = l.skins.iter().map(|s| s.skin["id"].as_str().unwrap().to_string()).collect(); + assert_eq!(ids, ["mine", "sunset"]); + let bad: Vec<_> = l.errors.iter().map(|e| e.file.as_str()).collect(); + assert_eq!(bad, ["broken.json", "twice.json"]); + + // saving keeps the user's file name + let s = save(dir, json!({ "id": "mine", "name": "Mine 2" })).unwrap(); + assert_eq!(s.file, "My Theme.json"); + delete(dir, "mine").unwrap(); + assert!(!dir.join("My Theme.json").exists()); + } +} diff --git a/crates/rc-api/tests/dispatch.rs b/crates/rc-api/tests/dispatch.rs index 042ee67..82c6958 100644 --- a/crates/rc-api/tests/dispatch.rs +++ b/crates/rc-api/tests/dispatch.rs @@ -411,3 +411,39 @@ async fn interrupted_jobs_and_sessions_survive_a_restart() { assert_eq!(sessions[0]["id"], "gone"); st.shutdown().await; } + +#[tokio::test(flavor = "multi_thread")] +async fn skins_and_appearance() { + let (_dir, st) = state().await; + + let settings = call(&st, "settings.get", Value::Null).await; + assert_eq!(settings["appearance"]["skin"], "default"); + assert_eq!(settings["appearance"]["accent"], Value::Null); + + let list = call(&st, "skins.list", Value::Null).await; + assert_eq!(list["skins"], json!([])); + assert!(list["dir"].as_str().unwrap().ends_with("skins")); + + let mut events = st.events.subscribe(); + let skin = json!({ "id": "ocean", "name": "Ocean", "dark": { "accent": "#00aaff" } }); + let saved = call(&st, "skins.save", json!({ "skin": skin })).await; + assert_eq!(saved["file"], "ocean.json"); + let ev = events.recv().await.unwrap(); + assert_eq!(ev.name, "skins.changed"); + + let list = call(&st, "skins.list", Value::Null).await; + assert_eq!(list["skins"][0]["skin"]["dark"]["accent"], "#00aaff"); + + let bad = dispatch(&st, &Origin::Desktop, "skins.save", json!({ "skin": { "id": "../x", "name": "x" } })).await; + assert_eq!(bad.unwrap_err().code, "invalid_input"); + + let mut settings = settings; + settings["appearance"]["skin"] = json!("ocean"); + settings["appearance"]["density"] = json!("compact"); + let saved = call(&st, "settings.set", json!({ "settings": settings })).await; + assert_eq!(saved["appearance"]["skin"], "ocean"); + assert_eq!(saved["appearance"]["density"], "compact"); + + call(&st, "skins.delete", json!({ "id": "ocean" })).await; + assert_eq!(call(&st, "skins.list", Value::Null).await["skins"], json!([])); +} diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 4a4169d..27ccb53 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -22,6 +22,8 @@ - [Terminal and SSH tunnels](guide/terminal-and-tunnels.md) - [LAN discovery and sharing](guide/lan-discovery.md) - [Web mode](guide/web-mode.md) +- [Skins and appearance](guide/skins.md) + - [Creating skins](guide/creating-skins.md) # Reference @@ -30,6 +32,7 @@ - [Scripting](reference/scripting.md) - [File masks](reference/file-masks.md) - [Configuration files](reference/configuration.md) +- [Skin tokens](reference/skin-tokens.md) # Deployment diff --git a/docs/src/development/architecture.md b/docs/src/development/architecture.md index 9fbf48b..ccfbc92 100644 --- a/docs/src/development/architecture.md +++ b/docs/src/development/architecture.md @@ -77,6 +77,10 @@ pin it. - `ui/src/components/` — panels, dock, sidebar, editor (CodeMirror 6), terminal (xterm.js) and dialogs. - `ui/src/i18n/` — English and German strings. +- `ui/src/lib/skins/` and `ui/src/skins/` — the skin engine (tokens, validation, + derivation, applying CSS custom properties) and the built-in skins as JSON files; user + skins are stored by the backend in `/skins/` (`crates/rc-api/src/skins.rs`). + See [Creating skins](../guide/creating-skins.md). The same build (`ui/dist`) is bundled into the desktop app and embedded into `rc-server`. diff --git a/docs/src/development/testing.md b/docs/src/development/testing.md index 11a947d..7e589ad 100644 --- a/docs/src/development/testing.md +++ b/docs/src/development/testing.md @@ -28,14 +28,16 @@ service. ```bash npm --prefix ui run typecheck -npm --prefix ui run test:unit # language detection, JSON checks, formatters +npm --prefix ui run test:unit # language detection, JSON checks, formatters, skins +node ui/scripts/skins.mjs check # built-in skins: validity and contrast report npm --prefix ui test # unit tests + Playwright smoke test ``` The smoke test (`ui/tests/smoke.mjs`) builds the UI if needed, starts `vite preview` and drives the app against the demo backend (`?mock=1`): navigation, copying, the Site Manager and host-key prompt, synchronization, conflicts, properties, Nearby, the Remote -Explorer, terminal, editor, fingerprints, drag and drop, web login and the mobile layout. +Explorer, terminal, editor, skins and the skin editor, fingerprints, drag and drop, web +login and the mobile layout. Its screenshots end up in `ui/tests/screenshots/`. ```bash diff --git a/docs/src/guide/creating-skins.md b/docs/src/guide/creating-skins.md new file mode 100644 index 0000000..95b9d0f --- /dev/null +++ b/docs/src/guide/creating-skins.md @@ -0,0 +1,395 @@ +# Creating skins + +A skin is a small JSON file. You can build one without writing any JSON in the +[skin editor](skins.md#the-skin-editor), or write the file yourself in any text editor — +this page explains the format, walks through a complete skin step by step and collects +recipes for common looks. The full list of colors is in the +[token reference](../reference/skin-tokens.md). + +## Your first skin in two minutes + +1. Open *Preferences* (Ctrl+,) → **Appearance** and note the **skins folder** (on Linux + `~/.config/rust-commander/skins/`; the desktop app has an **Open folder** button). +2. Create the file `sunset.json` in that folder: + + ```json + { + "id": "sunset", + "name": "Sunset", + "light": { "accent": "#e8590c" }, + "dark": { "accent": "#ff922b" } + } + ``` + +3. Switch back to Rust Commander: *Sunset* appears under **Your skins** and in + *View* → **Skin**. Select it. + +One color was enough for a consistent result: buttons, links, the frame of the active +panel, the file cursor, marked files, focus rings, progress bars, symbolic links and the +editor cursor all follow the new accent, in hover and selection shades computed from it. +Everything else comes from the standard skin. + +## How a skin works + +### The file + +| Key | Required | Meaning | +|---|---|---| +| `id` | yes | Unique id: `a-z`, `0-9`, `-` and `_`, at most 64 characters. Use it as the file name too (`sunset.json`). The ids of the built-in skins are reserved. | +| `name` | yes | Name in the gallery and the *Skin* menu. | +| `description`, `author`, `version`, `license` | no | Shown in the gallery (as a tooltip) and kept when the skin is shared. | +| `extends` | no | Id of the skin this one builds on. Default: `default` (the standard *Rust Commander* skin). | +| `style` | no | Fonts, corner radii, row height, list font size, striped rows — for both variants. | +| `light`, `dark` | no | The colors of the light and the dark variant: `"token": "value"` pairs. | +| `$schema` | no | Lets editors such as VS Code complete and check the file (see [Tools](#tools)). | + +Unknown keys and invalid values are ignored — the rest of the skin still works. They are +reported when you import the skin, and a warning icon on the skin's card in +Preferences → Appearance lists them. + +### Variants: light and dark + +Rust Commander shows the **light** or the **dark** variant of a skin, depending on the +*Theme* setting (*System*, *Light*, *Dark*). A skin may have both, or only one: + +- `light` and `dark` → follows the *Theme* setting. +- only `dark` (or only `light`) → always that variant, whatever the *Theme* says. *Retro + Blue* and *Dracula* work this way. +- neither (a skin that only changes `style`) → has the variants of the skin it extends. + +An empty object, `"light": {}`, is enough to declare a variant that inherits all its colors. + +### Inheritance: `extends` + +A skin starts from the skin it extends and changes only what it sets. That chain always ends +at `default`, which defines every token, so a skin never has holes: + +```json +{ + "id": "nord-rose", + "name": "Nord Rosé", + "extends": "nord", + "dark": { "accent": "#d8a0b8" } +} +``` + +*Nord Rosé* is *Nord* in every detail — palette, fonts, radius, terminal, light/dark +behavior (*Nord* has both; this skin declares only `dark`, so it is always dark) — except +for the accent. You can extend user skins as well as built-in ones. + +### Derived colors + +Many tokens are computed from others when a skin does not set them itself. The main ones: + +| You set | Rust Commander derives | +|---|---| +| `accent` | `accent-hover`, `accent-fg` (black or white, whichever is readable), `accent-weak`, `accent-weak-2`, `accent-border`, `sel-bg`, `sel-fg`, `cursor-bg`, `hover`, `fi-link`, `term-selection`, `editor-selection`, `editor-cursor`, `editor-active-line`, `syn-link`, `syn-heading` | +| `text` | `text-2`, `muted`, `faint` (mixed towards `surface`), `term-fg`, `editor-fg`, `syn-variable` | +| `surface`, `bg` | `surface-2`, `surface-3`, `input-bg`, `border`, `border-soft`, `border-strong`, `scroll`, `row-alt`, `term-bg`, `editor-bg`, `editor-gutter-bg` | +| the **palette** (`red`, `orange`, `yellow`, `green`, `teal`, `cyan`, `blue`, `purple`, `pink`) | the status colors (`ok`, `warn`, `err` and their backgrounds), the file icon colors, the colored terminal colors (red … cyan, normal and bright) and the syntax highlighting | + +Derivation only touches tokens that depend on what you changed: a skin that sets only +`accent` keeps the default surfaces, borders and text colors. +Whatever you set explicitly always wins — set `sel-fg` and the derived value is not used. +The [token reference](../reference/skin-tokens.md) shows for every token what it is derived +from. + +In practice this means a good skin needs surprisingly few values: the nine palette hues, +`bg`, `chrome`, `surface`, `text` and `accent` per variant give a complete, consistent look. +Everything after that is fine-tuning. + +### Color values + +Any of these notations works: + +| Notation | Example | +|---|---| +| Hex | `#0af`, `#00aaff`, `#00aaff80` (with alpha) | +| RGB | `rgb(0, 170, 255)`, `rgba(0, 170, 255, 0.5)`, `rgb(0 170 255 / 50%)` | +| HSL | `hsl(200, 100%, 50%)`, `hsla(200, 100%, 50%, 0.5)` | +| Keywords | `black`, `white`, `transparent` | + +Translucent colors are welcome for tints that sit on top of other colors (`sel-bg`, +`accent-weak`, `backdrop`, `editor-selection` in dark skins). Other color names (`red`, +`navy` …), `var()` and `url()` are not accepted. + +The tokens `shadow` and `shadow-lg` take a CSS `box-shadow` — lengths and colors, several +separated by commas — or `none` for a flat look: + +```json +"shadow": "none", +"shadow-lg": "0 0 0 1px #55ffff, 8px 8px 0 rgba(0, 0, 0, 0.65)" +``` + +### Style + +```json +"style": { + "fontUi": "'Inter', system-ui, sans-serif", + "fontMono": "'JetBrains Mono', monospace", + "radius": 4, + "panelRadius": 6, + "density": "compact", + "listFontSize": 13, + "stripes": true +} +``` + +| Key | Meaning | Range | Default | +|---|---|---|---| +| `fontUi` | Font of the user interface (CSS font-family list) | | system font | +| `fontMono` | Font of paths, permissions and the editor | | system monospace | +| `radius` | Corner radius of buttons, inputs, menu items | 0–16 px | 6 | +| `panelRadius` | Corner radius of panels, menus, dialogs | 0–24 px | 9 | +| `density` | Row height of the file lists | `compact`, `normal`, `comfortable` | `normal` | +| `listFontSize` | Font size of the file lists | 10–20 px | 13 | +| `stripes` | Alternating row backgrounds (color: `row-alt`) | `true` / `false` | `false` | + +Fonts are not downloaded: list fonts that are installed, with a generic family +(`sans-serif`, `monospace`) last. The user's own [adjustments](skins.md#adjustments) +(accent, row height, fonts …) override what the skin says here. + +## Tutorial: the *Ocean* skin + +Let's build a complete skin with a light and a dark variant: deep blue water, sandy +highlights. Create `ocean.json` in the skins folder and keep Rust Commander open next to +your editor — every time you save and switch back to the window, the skin reloads. + +### 1. Name and palette + +Start with the metadata and the palette. The nine hues drive file icons, status colors, +the terminal and the syntax highlighting, so choose them first. Light variants need darker, +more saturated hues (they sit on light backgrounds), dark variants lighter ones: + +```json +{ + "$schema": "https://raw.githubusercontent.com/bobnautic/rustcommander/main/ui/src/skins/skin.schema.json", + "id": "ocean", + "name": "Ocean", + "description": "Deep blue water, sandy highlights.", + "author": "Your Name", + "version": "1.0.0", + "light": { + "red": "#c92a2a", "orange": "#d9480f", "yellow": "#b07d05", "green": "#2b8a3e", "teal": "#0c8599", + "cyan": "#1098ad", "blue": "#1971c2", "purple": "#7048e8", "pink": "#c2255c" + }, + "dark": { + "red": "#ff8787", "orange": "#ffa94d", "yellow": "#ffd43b", "green": "#69db7c", "teal": "#38d9a9", + "cyan": "#3bc9db", "blue": "#74c0fc", "purple": "#b197fc", "pink": "#f783ac" + } +} +``` + +Select *Ocean* now: the folder icons are yellow-gold, scripts green, archives orange, and +the terminal (`ls`) uses the new colors — the surfaces are still the default ones. + +### 2. Surfaces and text + +Three surfaces define the depth of the window: `bg` (behind everything), `chrome` (menu +bar, tabs, status bar) and `surface` (panels and dialogs). In light skins the panels are the +brightest layer; in dark skins they are slightly *lighter* than the background. Add `text`: + +```json +"light": { + …palette…, + "bg": "#e3eef5", "chrome": "#edf4f8", "surface": "#fbfdfe", + "text": "#0b2233" +}, +"dark": { + …palette…, + "bg": "#06141f", "chrome": "#0a1b28", "surface": "#0e2333", + "text": "#e3f2fb" +} +``` + +Headers, hover backgrounds, input fields, all borders, secondary text, hints and the +editor and terminal backgrounds are derived from these — tinted blue now, like the rest. + +### 3. The accent + +```json +"light": { …, "accent": "#0b7285" }, +"dark": { …, "accent": "#3bc9db" } +``` + +The accent colors the active panel, the cursor bar, marked files and buttons. For a sandy +touch in the dark variant, give marked files their own color and make the terminal a little +deeper than the panels: + +```json +"dark": { …, "sel-fg": "#ffd43b", "term-bg": "#041019" } +``` + +### 4. Shape + +Rounder corners and striped lists fit the soft look: + +```json +"style": { "radius": 8, "panelRadius": 12, "stripes": true } +``` + +### 5. Check it + +- Switch *Theme* between *Light* and *Dark* (toolbar button) and look at both variants. +- Mark a few files (Insert), move the cursor, open a dialog (F5) and a menu. +- Open a terminal (Ctrl+J → *Terminal*) and run `ls`; open a source file in the editor (F4). +- Open the skin in the skin editor (*Your skins* → pencil icon): the **contrast check** under + the preview lists everything that is hard to read. + +The complete file: + +```json +{ + "$schema": "https://raw.githubusercontent.com/bobnautic/rustcommander/main/ui/src/skins/skin.schema.json", + "id": "ocean", + "name": "Ocean", + "description": "Deep blue water, sandy highlights.", + "author": "Your Name", + "version": "1.0.0", + "style": { "radius": 8, "panelRadius": 12, "stripes": true }, + "light": { + "red": "#c92a2a", "orange": "#d9480f", "yellow": "#b07d05", "green": "#2b8a3e", "teal": "#0c8599", + "cyan": "#1098ad", "blue": "#1971c2", "purple": "#7048e8", "pink": "#c2255c", + "bg": "#e3eef5", "chrome": "#edf4f8", "surface": "#fbfdfe", + "text": "#0b2233", + "accent": "#0b7285" + }, + "dark": { + "red": "#ff8787", "orange": "#ffa94d", "yellow": "#ffd43b", "green": "#69db7c", "teal": "#38d9a9", + "cyan": "#3bc9db", "blue": "#74c0fc", "purple": "#b197fc", "pink": "#f783ac", + "bg": "#06141f", "chrome": "#0a1b28", "surface": "#0e2333", + "text": "#e3f2fb", + "accent": "#3bc9db", + "sel-fg": "#ffd43b", + "term-bg": "#041019" + } +} +``` + +About thirty values for a skin that colors all 117 tokens in two variants. + +## Recipes + +**Just another accent for a built-in skin** + +```json +{ "id": "gruvbox-aqua", "name": "Gruvbox Aqua", "extends": "gruvbox", + "light": { "accent": "#427b58" }, "dark": { "accent": "#8ec07c" } } +``` + +**Flat and square** + +```json +"style": { "radius": 0, "panelRadius": 0 }, +"light": { "shadow": "none", "shadow-lg": "0 0 0 1px #000000" } +``` + +**A classic cursor bar** — a solid bar with its own text color, like the DOS-era file +managers (*Retro Blue*): + +```json +"dark": { "cursor-bg": "#00a8a8", "cursor-fg": "#000000" } +``` + +**Colored folder names** — folders in their own color (optional token, unset by default): + +```json +"dark": { "dir-fg": "#ffffff" } +``` + +**A colored menu bar and function keys** + +```json +"dark": { + "menubar-bg": "#00a8a8", "menubar-fg": "#000000", + "key-bg": "#00a8a8", "key-fg": "#000000", "key-num": "#ffffff" +} +``` + +**Your terminal color scheme** — the 16 ANSI colors plus background, text, cursor and +selection (`term-black` … `term-bright-white`, see the +[reference](../reference/skin-tokens.md#terminal)): + +```json +"dark": { "term-bg": "#000000", "term-fg": "#aaaaaa", "term-red": "#aa0000", "term-bright-red": "#ff5555" } +``` + +**Syntax colors** — `syn-keyword`, `syn-string`, `syn-comment`, `syn-function`, `syn-type` … +(see the [reference](../reference/skin-tokens.md#syntax-highlighting)). Without them the +editor uses the palette: keywords purple, strings green, numbers orange, functions blue. + +**Big lists for a presentation or a TV** + +```json +"style": { "listFontSize": 17, "density": "comfortable" } +``` + +## Tools + +- **Completion and checking in your editor.** With the `$schema` line at the top of the file, + VS Code, JetBrains IDEs and other editors that support JSON Schema complete token names, + show their descriptions and flag invalid values. Exported skins contain the line already. +- **Live reload.** Rust Commander re-reads the skins folder whenever its window gets the + focus again (and with **Reload skins** in Preferences → Appearance). Save in your editor, + switch back, look. +- **The skin editor** writes the same files: open a skin you wrote by hand, adjust colors with + the color picker and save — or copy the result from its **JSON** tab. +- **Contrast.** Aim for at least 4.5 : 1 for text on its background (WCAG AA), 3 : 1 for + hints, icons and button labels. The skin editor checks the important combinations. With a + checkout of the source code (and `npm --prefix ui ci`) you can check files from the + command line: + + ```bash + node ui/scripts/skins.mjs check ~/.config/rust-commander/skins/ocean.json + ``` + +## Sharing skins + +A skin is a single file: share the file from the skins folder, or **Export** it from its card +in Preferences → Appearance. Others add it with **Import…** or by putting it into their +skins folder. If the id already exists, Rust Commander asks before replacing; a file that +uses the id of a built-in skin is imported as `-custom`. + +### Contributing a built-in skin + +Built-in skins live in [`ui/src/skins/`](https://github.com/bobnautic/rustcommander/tree/main/ui/src/skins) +in exactly this format. To propose one: + +1. Add `.json` there (with `"$schema": "./skin.schema.json"`, an `author` and a + `license`; palettes of other projects need a compatible license and a credit in + `author`). Give it both variants if the design allows it. +2. Add the id to `ORDER` in `ui/src/skins/index.ts`. +3. Run, in `ui/`: + + ```bash + node scripts/skins.mjs format + node scripts/skins.mjs check + npm test + ``` + + `check` must report *contrast ok* for every variant; the unit tests verify the same. +4. Regenerate the screenshots with `ONLY=skins,skins-overview npm run screenshots:docs` and + add the skin to the table in [Skins and appearance](skins.md). + +If you add a token to `ui/src/lib/skins/tokens.ts`, also give it a value in `default.json` +and run `node scripts/skins.mjs schema` and `node scripts/skins.mjs docs`. + +## What skins can and cannot do + +Skins change colors, shadows, fonts, corner radii, row height and striped rows — in the +whole app, including the terminal and the editor. They cannot change the layout, replace +icons, add CSS or load anything from the network: every value is checked to be a color, a +shadow made of lengths and colors, a number in range or a font list, before it is applied. +A skin from the internet therefore cannot hide or fake parts of the interface, track you or +run code — at worst it looks bad, and *View* → *Skin* → **Rust Commander** brings the +standard look back. + +## Reference + +- [Skin tokens](../reference/skin-tokens.md) — every token with its purpose, what it is + derived from and its default values. +- [`skin.schema.json`](https://github.com/bobnautic/rustcommander/blob/main/ui/src/skins/skin.schema.json) + — the JSON Schema of skin files. +- The [built-in skins](https://github.com/bobnautic/rustcommander/tree/main/ui/src/skins) + as examples — *Retro Blue* uses nearly every optional token, *Ember* shows how far the + palette and a handful of colors go. diff --git a/docs/src/guide/interface.md b/docs/src/guide/interface.md index e474215..7c4064d 100644 --- a/docs/src/guide/interface.md +++ b/docs/src/guide/interface.md @@ -48,11 +48,13 @@ app you can also drop files from your operating system's file manager. bookmark list, the "directory hotlist"). Bookmarks can apply to the local file system, to a single site or to every session (for example `/var/log/nginx`). -## Themes and languages +## Skins, themes and languages The theme follows your system by default; *View* → **Theme** or the toolbar button -switches between system, light and dark. The interface is available in English and German -(*View* → **Language** or **Preferences**, Ctrl+,). +switches between system, light and dark. *View* → **Skin** changes the whole look — ten +skins are built in (from the standard look to *Retro Blue*, *Nord* or *High Contrast*), and +you can adjust them or create your own: see [Skins and appearance](skins.md). The interface is +available in English and German (*View* → **Language** or **Preferences**, Ctrl+,). On narrow screens — for example the [web mode](web-mode.md) on a phone — the layout shows one panel at a time with a switcher. diff --git a/docs/src/guide/skins.md b/docs/src/guide/skins.md new file mode 100644 index 0000000..b94d9ed --- /dev/null +++ b/docs/src/guide/skins.md @@ -0,0 +1,122 @@ +# Skins and appearance + +A **skin** decides how Rust Commander looks: the colors of every surface, the file icons, +the terminal and the editor's syntax highlighting, plus fonts, corner radius and row height. +Ten skins come with the app, you can adjust any of them to your taste, and you can create +your own — in the built-in skin editor or as a small JSON file +(see [Creating skins](creating-skins.md)). + +![The built-in skins](../images/skins-overview.jpg) + +## Choosing a skin + +*View* → **Skin** lists all skins; a click switches immediately. For a visual overview open +*View* → *Skin* → **Appearance…** (or **Preferences**, Ctrl+, → **Appearance**): + +![Preferences → Appearance](../images/skins-gallery.png) + +- **Theme** picks the variant: *System* follows the light/dark setting of your operating + system (or browser), *Light* and *Dark* force one. The toolbar button cycles through the + three. +- **Built in** and **Your skins** show a live miniature of every skin in the current variant. + Clicking one previews it in the whole window; **Save** keeps it, **Cancel** goes back. +- A sun or moon icon on a card marks a skin that has only a light or only a dark variant + (*Retro Blue* and *Dracula* are always dark). + +The skin is stored in `settings.json` with the other preferences. In [web mode](web-mode.md) +the server stores it, so every browser that opens the instance shows the same skin. + +### The built-in skins + +| Skin | Variants | Character | +|---|---|---| +| **Rust Commander** | light + dark | The standard look: calm grays with a blue accent. | +| **Ember** | light + dark | Warm stone grays and a rust-orange accent, slightly rounder. | +| **Graphite** | light + dark | Monochrome and flat: no shadows, small corners, compact striped lists. | +| **Retro Blue** | dark | The classic two-panel look of the DOS days: blue panels, cyan text, a cyan cursor bar, yellow marked files, square corners and a monospaced font. | +| **High Contrast** | light + dark | Black and white, solid borders, strong selection colors and larger list text. | +| **Nord** | light + dark | Arctic, north-bluish colors (palette by Arctic Ice Studio). | +| **Solarized** | light + dark | Ethan Schoonover's low-glare palette. | +| **Catppuccin** | light + dark | Soothing pastels: *Latte* when light, *Mocha* when dark. | +| **Gruvbox** | light + dark | Retro groove: earthy, warm colors with an orange accent. | +| **Dracula** | dark | Vivid purple, pink and green on a dark background. | + +Every built-in skin colors the terminal and the editor as well, and is checked for readable +contrast (text on panels, marked files, the cursor row, buttons, terminal text). + +## Adjustments + +Below the gallery, **Adjustments** change the look *on top of* whatever skin is selected — +switch skins and your adjustments stay: + +| Adjustment | Effect | +|---|---| +| **Accent color** | Buttons, links, the active panel, the cursor and selection colors. Hover and selection shades are derived from it automatically. | +| **Row height** | *Compact*, *Normal* or *Comfortable* rows in the file lists. | +| **List font size** | Font size of the file lists (11–18 px); the row height follows. | +| **Corner radius** | From square (0 px) to round; panels and dialogs scale along. | +| **Striped rows** | Alternating row backgrounds in the file lists. | +| **Interface font** / **Monospaced font** | Any font installed on your computer, as a CSS font list, e.g. `Inter, sans-serif` or `'JetBrains Mono', monospace`. | + +*From skin* (or an empty field) means the skin decides; **Reset adjustments** clears them all. + +## Your own skins + +There are three ways to get a skin of your own: + +1. **Customize a built-in skin.** Hover over its card and click the copy icon + (**Customize (copy)**). The skin editor opens with a new skin that is *based on* the + built-in one — change only what you want, everything else is inherited. +2. **New skin** (above *Your skins*) does the same for the selected skin. +3. **Import…** a skin file someone shared (`*.json`), or drop skin files into the + [skins folder](#the-skins-folder). + +User skins appear under **Your skins**. Hover over a card to **edit**, **export** (download +the file to share it) or **delete** it. + +### The skin editor + +![Skin editor](../images/skin-editor.png) + +- **Name**, **Id** (also the file name), **Author** and **Description**; **Based on** chooses + the skin it inherits from. +- **Variants**: whether the skin has its own light and/or dark colors. **Editing** switches + between them. +- **Colors** lists every token by group (surfaces, text, accent, selection, status, palette, + file icons, menu and key bar, terminal, syntax, editor). Click a swatch to pick a color or + type any CSS color (`#0af`, `rgba(0, 170, 255, 0.3)`, `hsl(200 100% 50%)`). Empty fields + show the inherited value in gray; the reset button removes your value again. + *Only set here* shows just what your skin changes. +- **Shape & fonts**: fonts, corner radii, row height, list font size, striped rows. +- **JSON** shows the skin file; you can edit it there or copy it. +- The **preview** on the right shows panels, marked files, the cursor, the editor, the + terminal and controls in the skin; **Preview in the whole window** applies it to the + entire app while you edit. +- The **contrast check** below the preview warns when text would be hard to read. + +**Save** stores the skin in the skins folder, **Save and use** also selects it. + +### The skins folder + +User skins are plain JSON files in the `skins` folder of the +[configuration directory](../reference/configuration.md#configuration-directory), for example +`~/.config/rust-commander/skins/` on Linux. Preferences → Appearance shows the exact path; in +the desktop app **Open folder** opens it. + +- Every `*.json` file there is loaded. Files that cannot be used are listed under + *Skin files with problems* with the reason. +- Changes to the files show up as soon as you switch back to the Rust Commander window (or + click **Reload skins**) — handy while [writing a skin](creating-skins.md) in your favorite + editor. +- The ids of built-in skins are reserved; a user skin cannot replace *Nord* itself, but it can + be based on it. + +## Troubleshooting + +- **A skin does not appear.** Check *Skin files with problems* in Preferences → Appearance. + The file must be valid JSON with an `id` (a–z, 0–9, `-`, `_`) and a `name`. +- **A color is ignored.** Values that are not colors (or for shadows: not a box-shadow) are + skipped; the skin editor and **Import** report them. See the + [token reference](../reference/skin-tokens.md) for the names. +- **Everything looks wrong after an experiment.** *View* → *Skin* → **Rust Commander** and + **Reset adjustments** bring back the standard look. diff --git a/docs/src/images/skin-editor.png b/docs/src/images/skin-editor.png new file mode 100644 index 0000000..94afbcf Binary files /dev/null and b/docs/src/images/skin-editor.png differ diff --git a/docs/src/images/skins-gallery.png b/docs/src/images/skins-gallery.png new file mode 100644 index 0000000..a614c8a Binary files /dev/null and b/docs/src/images/skins-gallery.png differ diff --git a/docs/src/images/skins-overview.jpg b/docs/src/images/skins-overview.jpg new file mode 100644 index 0000000..ea03367 Binary files /dev/null and b/docs/src/images/skins-overview.jpg differ diff --git a/docs/src/introduction.md b/docs/src/introduction.md index 1a4d1a3..1d121bc 100644 --- a/docs/src/introduction.md +++ b/docs/src/introduction.md @@ -15,7 +15,7 @@ can be opened straight from the app. | Area | Highlights | |---|---| | Protocols | SFTP, SCP, FTP, FTPS (explicit and implicit), WebDAV(S), Amazon S3 and S3-compatible storage (MinIO, Wasabi, R2, Ceph …), Azure Blob Storage, Google Cloud Storage, and other Rust Commander instances | -| Interface | Commander layout with two panels, session tabs, bookmarks, synchronized browsing, directory comparison, full keyboard control with the Norton Commander (default) or Total Commander keyboard layout and a function key bar, light and dark theme, English and German | +| Interface | Commander layout with two panels, session tabs, bookmarks, synchronized browsing, directory comparison, full keyboard control with the Norton Commander (default) or Total Commander keyboard layout and a function key bar, light and dark theme, ten built-in [skins](guide/skins.md) plus your own, English and German | | Transfers | Background queue with pause/resume/cancel/retry, resumable transfers, overwrite rules, **fingerprint comparison before copying**, preserved timestamps and permissions, file masks, speed limit, parallel transfers, server-to-server copies | | Synchronization | One-way or two-way comparison by size, time or checksum, mirror mode, a **checklist** before anything runs, and "keep remote folder up to date" | | Editor | Built-in editor for local and remote files with language detection, **linting**, **formatting**, change markers and a diff view | diff --git a/docs/src/reference/configuration.md b/docs/src/reference/configuration.md index fbf61de..4b6b21c 100644 --- a/docs/src/reference/configuration.md +++ b/docs/src/reference/configuration.md @@ -21,6 +21,7 @@ containers (`/config`). | `known_hosts.json` | Trusted SSH host keys and TLS certificates | | `bookmarks.json` | Bookmarks | | `commands.json` | Custom commands | +| `skins/*.json` | Your [skins](../guide/skins.md#the-skins-folder), one file per skin | | `vault.json` | Master password settings (when a master password has been set) | | `vault.key` | Vault key when no master password is set (readable only by the user) | | `server.json` | Web login password (Argon2 hash) | @@ -50,7 +51,8 @@ system's temporary folder. | Tab | Settings | |---|---| -| General | Language, theme, [keyboard layout](keyboard-shortcuts.md) (Norton Commander, Total Commander, Rust Commander) and function key bar, hidden files, size format, what double-click / Enter does on a file (edit, open with the default application, copy to the other panel), confirmations before deleting and overwriting, moving deleted local files to the trash, whether the copy/move dialog is shown | +| General | Language, [keyboard layout](keyboard-shortcuts.md) (Norton Commander, Total Commander, Rust Commander) and function key bar, hidden files, size format, what double-click / Enter does on a file (edit, open with the default application, copy to the other panel), confirmations before deleting and overwriting, moving deleted local files to the trash, whether the copy/move dialog is shown | +| Appearance | Theme (system, light, dark), [skin](../guide/skins.md) and adjustments (accent color, row height, list font size, corner radius, striped rows, fonts), the skins folder | | Transfer | Default transfer settings, number of parallel jobs, reconnecting the sessions and continuing the jobs of the last run | | Editor | Show problems, format when saving, line width for formatting, tab width, word wrap | | Terminal | Font family, font size, scrollback lines | diff --git a/docs/src/reference/skin-tokens.md b/docs/src/reference/skin-tokens.md new file mode 100644 index 0000000..659a221 --- /dev/null +++ b/docs/src/reference/skin-tokens.md @@ -0,0 +1,200 @@ +# Skin tokens + + + +Every color a skin can set. Each token is a CSS custom property (`--name`) and goes into the +`light` and/or `dark` object of a skin file — see [Creating skins](../guide/creating-skins.md). + +A token a skin leaves out comes from its base skin. When the skin sets a token that another one +is **derived from**, the derived token is computed from the new value instead (unless the skin sets +it too). *Optional* tokens have no value until a skin sets one. + +## Surfaces + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `bg` | Window background: around the panels and behind the active session tab. | — | `#eef0f3` | `#111316` | +| `chrome` | Menu bar, session tabs, sidebar, status bar and function key bar. | — | `#f5f6f8` | `#17191d` | +| `surface` | Panels, dialogs, menus and cards. | — | `#ffffff` | `#1c1f24` | +| `surface-2` | Panel headers, column headers and panel status lines. | `surface`, `bg`, `text` | `#f7f8fa` | `#22262c` | +| `surface-3` | Hover and pressed backgrounds, segmented controls, progress tracks. | `surface`, `bg`, `text` | `#eceef2` | `#2a2f36` | +| `input-bg` | Text fields and drop-down lists. | `surface`, `bg` | `#ffffff` | `#16191d` | +| `hover` | Row under the mouse pointer. | `surface-2`, `accent` | `#f1f4f9` | `#242a32` | +| `border` | Borders of panels, dialogs and tables. | `surface`, `text` | `#e0e3e8` | `#2e333a` | +| `border-soft` | Subtle separators. | `border`, `surface` | `#eef0f3` | `#262a30` | +| `border-strong` | Borders of buttons and inputs. | `border`, `text` | `#cdd2d9` | `#3b414a` | +| `scroll` | Scrollbar thumbs. | `border-strong` | `#c9ced6` | `#3a4048` | +| `backdrop` | Shade behind modal dialogs (use a translucent color). | — | `rgba(17, 24, 39, 0.36)` | `rgba(0, 0, 0, 0.5)` | +| `shadow` | Shadow of panels and cards: a CSS box-shadow, or "none" for a flat look. | — | `0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 3px rgba(16, 24, 40, 0.08)` | `0 1px 2px rgba(0, 0, 0, 0.3)` | +| `shadow-lg` | Shadow of menus, dialogs and notifications: a CSS box-shadow or "none". | — | `0 18px 50px rgba(16, 24, 40, 0.22), 0 4px 12px rgba(16, 24, 40, 0.1)` | `0 20px 60px rgba(0, 0, 0, 0.55), 0 4px 14px rgba(0, 0, 0, 0.35)` | + +## Text + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `text` | Main text color. | — | `#1b2028` | `#e5e8ec` | +| `text-2` | Secondary text: other columns, labels, inactive tabs. | `text`, `surface` | `#464e5a` | `#b6bdc7` | +| `muted` | Hints, placeholders, status texts. | `text`, `surface` | `#6f7782` | `#8a929d` | +| `faint` | Very low-emphasis text and decorations (separators, line numbers). | `text`, `surface` | `#a3aab4` | `#5d6570` | + +## Accent + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `accent` | Buttons, links, focus rings, the active panel, highlighted menu items, progress bars. | — | `#2563d9` | `#4c8df6` | +| `accent-hover` | Primary buttons under the mouse pointer. | `accent` | `#1d55c2` | `#6aa0f8` | +| `accent-fg` | Text on accent-colored backgrounds. | `accent` | `#ffffff` | `#ffffff` | +| `accent-weak` | Light accent tint (active rows, drop zones). | `accent`, `surface` | `#eaf1fe` | `rgba(76, 141, 246, 0.13)` | +| `accent-weak-2` | Stronger accent tint (focus glow, active toggle buttons). | `accent`, `surface` | `#d6e4fd` | `rgba(76, 141, 246, 0.24)` | +| `accent-border` | Border of the active panel. | `accent` | `rgba(37, 99, 217, 0.45)` | `rgba(76, 141, 246, 0.55)` | +| `brand` | The Rust Commander logo color. | — | `#e2672f` | `#e2672f` | + +## Selection and cursor + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `sel-bg` | Background of marked (selected) files. | `accent`, `surface` | `#e3ecfd` | `rgba(76, 141, 246, 0.17)` | +| `sel-fg` | Text of marked files. | `accent`, `text` | `#1446ad` | `#8ab6ff` | +| `cursor-bg` | The file cursor in the active panel. | `accent`, `surface` | `#cfdffc` | `rgba(76, 141, 246, 0.32)` | +| `cursor-fg` | Text on the file cursor. Optional: without it the text keeps its color. | *optional* | — | — | +| `row-alt` | Every other row of the file lists when striped rows are on. | `surface`, `text` | `#f8f9fa` | `#202328` | +| `dir-fg` | Names of folders in the file lists. Optional: without it folders look like files. | *optional* | — | — | + +## Status + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `ok` | Success: finished jobs, identical files, connected. | `green` | `#1d8348` | `#43b96f` | +| `ok-weak` | Background of success messages. | `ok`, `surface` | `#e7f6ed` | `rgba(67, 185, 111, 0.12)` | +| `ok-border` | Border of success messages. | `ok`, `surface` | `#a7dcbb` | `rgba(67, 185, 111, 0.4)` | +| `warn` | Warnings: different files, attention. | `yellow` | `#a8670b` | `#e3a742` | +| `warn-weak` | Background of warnings. | `warn`, `surface` | `#fdf3e2` | `rgba(227, 167, 66, 0.13)` | +| `err` | Errors and destructive actions. | `red` | `#cc2f35` | `#f0595e` | +| `err-weak` | Background of error messages. | `err`, `surface` | `#fdecec` | `rgba(240, 89, 94, 0.13)` | +| `err-border` | Border of error messages. | `err`, `surface` | `#f3b5b7` | `rgba(240, 89, 94, 0.45)` | + +## Palette + +Nine hues that file icons, status colors, the terminal and the syntax highlighting are derived from. Setting just the palette gives a skin consistent colors everywhere. + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `red` | Palette hue "red". File icons, status, terminal and syntax colors are derived from the palette. | — | `#cc2f35` | `#f0595e` | +| `orange` | Palette hue "orange". File icons, status, terminal and syntax colors are derived from the palette. | — | `#c96a1e` | `#f08a55` | +| `yellow` | Palette hue "yellow". File icons, status, terminal and syntax colors are derived from the palette. | — | `#c18a0e` | `#e3b341` | +| `green` | Palette hue "green". File icons, status, terminal and syntax colors are derived from the palette. | — | `#1d8348` | `#43b96f` | +| `teal` | Palette hue "teal". File icons, status, terminal and syntax colors are derived from the palette. | — | `#0f978a` | `#3cc7b6` | +| `cyan` | Palette hue "cyan". File icons, status, terminal and syntax colors are derived from the palette. | — | `#0b86a0` | `#3db8d0` | +| `blue` | Palette hue "blue". File icons, status, terminal and syntax colors are derived from the palette. | — | `#2563d9` | `#6aa0f8` | +| `purple` | Palette hue "purple". File icons, status, terminal and syntax colors are derived from the palette. | — | `#8e44c9` | `#c08cf0` | +| `pink` | Palette hue "pink". File icons, status, terminal and syntax colors are derived from the palette. | — | `#c93b8f` | `#f07ab9` | + +## File icons + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `fi-file` | Files without a known type. | `muted` | `#8a929d` | `#8a929d` | +| `fi-dir` | Folder icons (outline). | `yellow` | `#d39c12` | `#e3b341` | +| `fi-dir-fill` | Folder icons (fill). | `fi-dir`, `surface` | `#fbdc8e` | `rgba(227, 179, 65, 0.32)` | +| `fi-image` | Images. | `purple` | `#8e44c9` | `#c08cf0` | +| `fi-video` | Videos. | `pink` | `#c93b8f` | `#f07ab9` | +| `fi-audio` | Audio files. | `teal` | `#0f978a` | `#3cc7b6` | +| `fi-archive` | Archives (zip, tar, …). | `orange` | `#a85d1b` | `#d68a46` | +| `fi-code` | Source code. | `blue` | `#2563d9` | `#6aa0f8` | +| `fi-script` | Scripts (sh, py, …). | `green` | `#1d8a5a` | `#4cc38a` | +| `fi-config` | Configuration files (json, yaml, toml, …). | `cyan` | `#0b86a0` | `#3db8d0` | +| `fi-text` | Text files. | `muted` | `#67707c` | `#98a1ad` | +| `fi-document` | Documents (pdf, doc, …). | `red` | `#cc2f35` | `#f0757a` | +| `fi-spreadsheet` | Spreadsheets. | `green` | `#1d8348` | `#4cc38a` | +| `fi-presentation` | Presentations. | `orange` | `#e2672f` | `#f08a55` | +| `fi-key` | Keys and certificates. | `yellow` | `#b07a10` | `#e0b04a` | +| `fi-executable` | Programs. | `blue`, `purple` | `#5262c9` | `#8d9bf0` | +| `fi-font` | Fonts. | `purple` | `#7454e6` | `#a58cff` | +| `fi-database` | Databases. | `blue`, `cyan` | `#0a74ad` | `#49a8e0` | +| `fi-disk` | Disk images. | `muted` | `#6b7380` | `#98a1ad` | +| `fi-link` | Symbolic links. | `accent` | `#2563d9` | `#6aa0f8` | + +## Menu bar and function key bar + +All optional: they let a skin color the menu bar and the function keys differently from the rest of the chrome (the classic cyan bars of *Retro Blue*). + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `menubar-bg` | Background of the menu bar. Optional: default is "chrome". | *optional* | — | — | +| `menubar-fg` | Menu titles and toolbar icons. Optional. | *optional* | — | — | +| `key-bg` | Background of the function key labels (F1–F10). Optional: default is "surface-3". | *optional* | — | — | +| `key-fg` | Text of the function key labels. Optional: default is "text-2". | *optional* | — | — | +| `key-num` | Numbers of the function keys. Optional: default is "muted". | *optional* | — | — | + +## Terminal + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `term-bg` | Terminal background. | `bg`, `surface` | `#fbfbfc` | `#121417` | +| `term-fg` | Terminal text. | `text` | `#1f2328` | `#d6dae0` | +| `term-cursor` | Terminal cursor. | `term-fg` | `#1f2328` | `#e6e9ee` | +| `term-selection` | Selected text in the terminal. | `accent` | `#b6d1fb` | `#33476b` | +| `term-black` | ANSI black. | `text`, `faint`, `bg` | `#24292f` | `#484f58` | +| `term-red` | ANSI red. | `red` | `#cf222e` | `#ff7b72` | +| `term-green` | ANSI green. | `green` | `#116329` | `#3fb950` | +| `term-yellow` | ANSI yellow. | `yellow` | `#7d4e00` | `#d29922` | +| `term-blue` | ANSI blue. | `blue` | `#0969da` | `#58a6ff` | +| `term-magenta` | ANSI magenta. | `purple` | `#8250df` | `#bc8cff` | +| `term-cyan` | ANSI cyan. | `cyan` | `#1b7c83` | `#39c5cf` | +| `term-white` | ANSI white. | `muted`, `text-2` | `#6e7781` | `#b1bac4` | +| `term-bright-black` | ANSI bright black (often used for gray text). | `text`, `surface`, `muted` | `#57606a` | `#6e7681` | +| `term-bright-red` | ANSI bright red. | `red` | `#a40e26` | `#ffa198` | +| `term-bright-green` | ANSI bright green. | `green` | `#1a7f37` | `#56d364` | +| `term-bright-yellow` | ANSI bright yellow. | `yellow` | `#633c01` | `#e3b341` | +| `term-bright-blue` | ANSI bright blue. | `blue` | `#218bff` | `#79c0ff` | +| `term-bright-magenta` | ANSI bright magenta. | `purple` | `#a475f9` | `#d2a8ff` | +| `term-bright-cyan` | ANSI bright cyan. | `cyan` | `#3192aa` | `#56d4dd` | +| `term-bright-white` | ANSI bright white. | `text`, `faint` | `#8c959f` | `#ffffff` | + +## Syntax highlighting + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `syn-keyword` | Keywords (if, fn, return). | `purple` | `#cf222e` | `#c678dd` | +| `syn-string` | Strings. | `green` | `#0a3069` | `#98c379` | +| `syn-number` | Numbers. | `orange` | `#0550ae` | `#d19a66` | +| `syn-constant` | Constants, booleans, null. | `orange` | `#0550ae` | `#d19a66` | +| `syn-comment` | Comments. | `muted` | `#6e7781` | `#7d8799` | +| `syn-function` | Function and method names. | `blue` | `#8250df` | `#61afef` | +| `syn-type` | Types, classes, namespaces. | `yellow` | `#953800` | `#e5c07b` | +| `syn-property` | Properties and keys. | `red` | `#0550ae` | `#e06c75` | +| `syn-variable` | Variables. | `text` | `#1f2328` | `#d6dae0` | +| `syn-operator` | Operators. | `cyan` | `#cf222e` | `#56b6c2` | +| `syn-tag` | HTML/XML tags. | `red` | `#116329` | `#e06c75` | +| `syn-attribute` | HTML/XML attributes. | `orange` | `#0550ae` | `#d19a66` | +| `syn-heading` | Markdown headings. | `accent` | `#0550ae` | `#e06c75` | +| `syn-link` | Links and URLs. | `accent` | `#0a3069` | `#56b6c2` | +| `syn-invalid` | Invalid code. | `err` | `#cf222e` | `#ff6b6b` | +| `syn-meta` | Annotations, preprocessor, front matter. | `muted` | `#6e7781` | `#7d8799` | +| `syn-regexp` | Regular expressions and escapes. | `teal` | `#116329` | `#56b6c2` | + +## Editor + +| Token | Used for | Derived from | Default light | Default dark | +|---|---|---|---|---| +| `editor-bg` | Editor background. | `surface` | `#ffffff` | `#1c1f24` | +| `editor-fg` | Editor text. | `text` | `#1b2028` | `#e5e8ec` | +| `editor-gutter-bg` | Line number gutter background. | `surface`, `surface-2` | `#f7f8fa` | `#1c1f24` | +| `editor-gutter-fg` | Line numbers. | `faint` | `#a3aab4` | `#5d6570` | +| `editor-active-line` | Line with the cursor. | `accent` | `rgba(37, 99, 217, 0.05)` | `rgba(76, 141, 246, 0.06)` | +| `editor-selection` | Selected text. | `accent`, `surface` | `#d3e1fa` | `rgba(76, 141, 246, 0.3)` | +| `editor-cursor` | Text cursor. | `accent` | `#1b2028` | `#e5e8ec` | + +## Style + +Not colors: the `style` object of a skin applies to both variants. + +| Key | Values | Default | +|---|---|---| +| `fontUi` | CSS font-family list of the user interface | the system font | +| `fontMono` | CSS font-family list for paths, permissions, code | the system monospace font | +| `radius` | corner radius of buttons and inputs, 0–16 px | `6` | +| `panelRadius` | corner radius of panels, menus and dialogs, 0–24 px | `9` | +| `density` | row height of the file lists: `"compact"`, `"normal"`, `"comfortable"` | `"normal"` | +| `listFontSize` | font size of the file lists, 10–20 px | `13` | +| `stripes` | `true` for alternating row backgrounds (`row-alt`) | `false` | diff --git a/ui/package-lock.json b/ui/package-lock.json index 093dd86..f99f346 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -18,6 +18,7 @@ "@codemirror/state": "^6.5.2", "@codemirror/view": "^6.38.6", "@lezer/common": "^1.5.5", + "@lezer/highlight": "^1.2.5", "@tauri-apps/api": "^2.9.0", "@tauri-apps/plugin-dialog": "^2.4.2", "@uiw/react-codemirror": "^4.25.2", diff --git a/ui/package.json b/ui/package.json index cb6a358..c927d70 100644 --- a/ui/package.json +++ b/ui/package.json @@ -25,6 +25,7 @@ "@codemirror/state": "^6.5.2", "@codemirror/view": "^6.38.6", "@lezer/common": "^1.5.5", + "@lezer/highlight": "^1.2.5", "@tauri-apps/api": "^2.9.0", "@tauri-apps/plugin-dialog": "^2.4.2", "@uiw/react-codemirror": "^4.25.2", diff --git a/ui/public/theme-init.js b/ui/public/theme-init.js index 49e5ccf..d8240ae 100644 --- a/ui/public/theme-init.js +++ b/ui/public/theme-init.js @@ -1,11 +1,23 @@ -// Apply the last used theme before the bundle loads to avoid a flash. +// Apply the last used theme and skin before the bundle loads to avoid a flash. // Kept as a file (not inline) so a strict Content-Security-Policy allows it. +// `rc.look` is written by src/lib/skins/apply.ts: the resolved skin for a light and a dark +// system setting (CSS custom properties + root classes). (function () { + var root = document.documentElement; try { var t = localStorage.getItem('rc.theme') || 'system'; var dark = t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches); - document.documentElement.dataset.theme = dark ? 'dark' : 'light'; + var look = JSON.parse(localStorage.getItem('rc.look') || 'null'); + var v = look && look[dark ? 'dark' : 'light']; + if (v && v.vars) { + for (var k in v.vars) { + if (k.indexOf('--') === 0 && typeof v.vars[k] === 'string') root.style.setProperty(k, v.vars[k]); + } + for (var i = 0; v.classes && i < v.classes.length; i++) root.classList.add(String(v.classes[i])); + dark = v.scheme === 'dark'; + } + root.dataset.theme = dark ? 'dark' : 'light'; } catch (e) { - document.documentElement.dataset.theme = 'light'; + root.dataset.theme = 'light'; } })(); diff --git a/ui/scripts/skins.mjs b/ui/scripts/skins.mjs new file mode 100644 index 0000000..79537a3 --- /dev/null +++ b/ui/scripts/skins.mjs @@ -0,0 +1,184 @@ +#!/usr/bin/env node +// Maintenance for the built-in skins in src/skins/: +// +// node scripts/skins.mjs check validate every skin, print warnings and a contrast report +// node scripts/skins.mjs format sort the tokens of every skin like the token list +// node scripts/skins.mjs schema regenerate src/skins/skin.schema.json from the token list +// node scripts/skins.mjs docs regenerate docs/src/reference/skin-tokens.md from the token list +// node scripts/skins.mjs check path/to/my-skin.json … check other skin files +// +// Loads the TypeScript sources through Vite, like tests/unit.mjs. +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createServer } from 'vite'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const skinsDir = join(root, 'src', 'skins'); +const [cmd = 'check', ...files] = process.argv.slice(2); + +const vite = await createServer({ root, logLevel: 'error', server: { middlewareMode: true, hmr: false }, appType: 'custom', optimizeDeps: { noDiscovery: true } }); +const { TOKENS, GROUPS } = await vite.ssrLoadModule('/src/lib/skins/tokens.ts'); +const engine = await vite.ssrLoadModule('/src/lib/skins/engine.ts'); + +const builtinFiles = () => + readdirSync(skinsDir) + .filter((f) => f.endsWith('.json') && f !== 'skin.schema.json') + .map((f) => join(skinsDir, f)); +const read = (f) => JSON.parse(readFileSync(f, 'utf8')); + +let failed = 0; + +if (cmd === 'format') { + for (const f of builtinFiles()) { + const skin = read(f); + for (const v of ['light', 'dark']) { + if (!skin[v]) continue; + const sorted = {}; + for (const t of TOKENS) if (t.name in skin[v]) sorted[t.name] = skin[v][t.name]; + for (const k of Object.keys(skin[v])) if (!(k in sorted)) sorted[k] = skin[v][k]; + skin[v] = sorted; + } + writeFileSync(f, JSON.stringify(skin, null, 2) + '\n'); + console.log(`formatted ${basename(f)}`); + } +} else if (cmd === 'schema') { + const tokenProps = (kindFilter) => { + const props = {}; + for (const t of TOKENS) { + props[t.name] = { + description: `${t.doc} (group: ${t.group})`, + ...(t.kind === 'color' ? { $ref: '#/$defs/color' } : { $ref: '#/$defs/shadow' }), + }; + } + return props; + }; + const schema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + $id: 'https://raw.githubusercontent.com/bobnautic/rustcommander/main/ui/src/skins/skin.schema.json', + title: 'Rust Commander skin', + description: 'A skin for Rust Commander. See docs/src/guide/creating-skins.md. This file is generated by `node scripts/skins.mjs schema`.', + type: 'object', + required: ['id', 'name'], + additionalProperties: false, + properties: { + $schema: { type: 'string' }, + id: { type: 'string', pattern: engine.ID_RE.source, description: 'Unique id: a-z, 0-9, - and _ (also the file name).' }, + name: { type: 'string', minLength: 1, maxLength: 80, description: 'Name shown in the skin gallery.' }, + description: { type: 'string', maxLength: 500 }, + author: { type: 'string', maxLength: 500 }, + version: { type: 'string', maxLength: 500 }, + license: { type: 'string', maxLength: 500 }, + extends: { type: 'string', pattern: engine.ID_RE.source, description: 'Id of the skin this one builds on (default: "default").' }, + style: { + type: 'object', + additionalProperties: false, + properties: { + fontUi: { type: 'string', description: 'CSS font-family of the user interface.' }, + fontMono: { type: 'string', description: 'CSS font-family of monospaced text.' }, + radius: { type: 'integer', minimum: engine.STYLE_LIMITS.radius[0], maximum: engine.STYLE_LIMITS.radius[1], description: 'Corner radius of buttons and inputs (px).' }, + panelRadius: { type: 'integer', minimum: engine.STYLE_LIMITS.panelRadius[0], maximum: engine.STYLE_LIMITS.panelRadius[1], description: 'Corner radius of panels, menus and dialogs (px).' }, + density: { enum: engine.DENSITIES, description: 'Row height of the file lists.' }, + listFontSize: { type: 'integer', minimum: engine.STYLE_LIMITS.listFontSize[0], maximum: engine.STYLE_LIMITS.listFontSize[1], description: 'Font size of the file lists (px).' }, + stripes: { type: 'boolean', description: 'Alternating row backgrounds in the file lists.' }, + }, + }, + light: { $ref: '#/$defs/variant', description: 'Token values of the light variant.' }, + dark: { $ref: '#/$defs/variant', description: 'Token values of the dark variant.' }, + }, + $defs: { + color: { + type: 'string', + description: 'A CSS color: #rgb, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl(), hsla(), black, white or transparent.', + pattern: '^\\s*(#[0-9a-fA-F]{3,8}|(rgb|rgba|hsl|hsla)\\([^()]*\\)|black|white|transparent)\\s*$', + }, + shadow: { type: 'string', description: 'A CSS box-shadow (lengths and colors) or "none".' }, + variant: { type: 'object', additionalProperties: false, properties: tokenProps() }, + }, + }; + writeFileSync(join(skinsDir, 'skin.schema.json'), JSON.stringify(schema, null, 2) + '\n'); + console.log(`wrote skin.schema.json (${TOKENS.length} tokens in ${GROUPS.length} groups)`); +} else if (cmd === 'docs') { + const titles = { base: 'Surfaces', text: 'Text', accent: 'Accent', selection: 'Selection and cursor', status: 'Status', palette: 'Palette', files: 'File icons', chrome: 'Menu bar and function key bar', terminal: 'Terminal', syntax: 'Syntax highlighting', editor: 'Editor' }; + const def = read(join(skinsDir, 'default.json')); + const lines = [ + '# Skin tokens', + '', + '', + '', + 'Every color a skin can set. Each token is a CSS custom property (`--name`) and goes into the', + '`light` and/or `dark` object of a skin file — see [Creating skins](../guide/creating-skins.md).', + '', + 'A token a skin leaves out comes from its base skin. When the skin sets a token that another one', + 'is **derived from**, the derived token is computed from the new value instead (unless the skin sets', + 'it too). *Optional* tokens have no value until a skin sets one.', + '', + ]; + for (const g of GROUPS) { + lines.push(`## ${titles[g]}`, ''); + if (g === 'palette') lines.push('Nine hues that file icons, status colors, the terminal and the syntax highlighting are derived from. Setting just the palette gives a skin consistent colors everywhere.', ''); + if (g === 'chrome') lines.push('All optional: they let a skin color the menu bar and the function keys differently from the rest of the chrome (the classic cyan bars of *Retro Blue*).', ''); + lines.push('| Token | Used for | Derived from | Default light | Default dark |', '|---|---|---|---|---|'); + for (const t of TOKENS.filter((x) => x.group === g)) { + const from = t.optional ? '*optional*' : (t.from ?? []).map((f) => `\`${f}\``).join(', ') || '—'; + const val = (v) => (v === undefined ? '—' : `\`${v}\``); + lines.push(`| \`${t.name}\` | ${t.doc.replace(/\|/g, '\\|')} | ${from} | ${val(def.light[t.name])} | ${val(def.dark[t.name])} |`); + } + lines.push(''); + } + lines.push( + '## Style', + '', + 'Not colors: the `style` object of a skin applies to both variants.', + '', + '| Key | Values | Default |', + '|---|---|---|', + `| \`fontUi\` | CSS font-family list of the user interface | the system font |`, + `| \`fontMono\` | CSS font-family list for paths, permissions, code | the system monospace font |`, + `| \`radius\` | corner radius of buttons and inputs, ${engine.STYLE_LIMITS.radius.join('–')} px | \`6\` |`, + `| \`panelRadius\` | corner radius of panels, menus and dialogs, ${engine.STYLE_LIMITS.panelRadius.join('–')} px | \`9\` |`, + `| \`density\` | row height of the file lists: ${engine.DENSITIES.map((d) => `\`"${d}"\``).join(', ')} | \`"normal"\` |`, + `| \`listFontSize\` | font size of the file lists, ${engine.STYLE_LIMITS.listFontSize.join('–')} px | \`13\` |`, + '| `stripes` | `true` for alternating row backgrounds (`row-alt`) | `false` |', + '', + ); + const target = join(root, '..', 'docs', 'src', 'reference', 'skin-tokens.md'); + writeFileSync(target, lines.join('\n')); + console.log(`wrote ${target}`); +} else if (cmd === 'check') { + const paths = files.length ? files.map((f) => resolve(f)) : builtinFiles(); + const byId = new Map(); + for (const f of builtinFiles()) { + const v = engine.validateSkin(read(f)); + if (v.skin) byId.set(v.skin.id, v.skin); + } + const lookup = (id) => byId.get(id); + for (const f of paths) { + const v = engine.validateSkin(read(f)); + if (!v.skin) { + failed++; + console.log(`✘ ${basename(f)}: ${v.errors.join('; ')}`); + continue; + } + if (v.skin.id !== basename(f, '.json') && !files.length) console.log(` ! ${basename(f)}: file name should be ${v.skin.id}.json`); + byId.set(v.skin.id, v.skin); + const variants = engine.variantsOf(v.skin, lookup); + console.log(`${v.warnings.length ? '!' : '✔'} ${v.skin.name} (${v.skin.id}) – ${variants.join(' + ')}`); + for (const w of v.warnings) console.log(` warning: ${w}`); + for (const scheme of variants) { + const r = engine.resolveSkin(v.skin, lookup, scheme); + const low = engine + .contrastReport(r) + .filter((c) => !c.ok) + .map((c) => `${c.what} ${c.ratio.toFixed(2)} < ${c.min}`); + console.log(` ${scheme}: ${low.length ? 'low contrast: ' + low.join(', ') : 'contrast ok'}`); + if (low.length && !files.length) failed++; + } + } +} else { + console.log(`unknown command ${cmd}`); + failed++; +} + +await vite.close(); +process.exit(failed ? 1 : 0); diff --git a/ui/src/actions/boot.ts b/ui/src/actions/boot.ts index 91395ac..970a532 100644 --- a/ui/src/actions/boot.ts +++ b/ui/src/actions/boot.ts @@ -12,6 +12,7 @@ import { adoptTerminals, onTerminalData, onTerminalExit } from '../store/termina import { toast } from '../store/toasts'; import { openDialog } from '../store/dialogs'; import { onJobForUndo } from './undo'; +import { reloadSkins } from '../store/skins'; let subscribed = false; @@ -77,6 +78,7 @@ export function subscribeEvents() { explorerFsChanged(session, path); }); on('log', (e) => appendLog(e)); + on('skins.changed', () => void reloadSkins()); on('resync', () => void loadState(false)); onReconnected(() => { void loadState(false); @@ -105,6 +107,7 @@ export async function loadState(initial: boolean) { if (info.status === 'rejected') throw info.reason; useApp.setState({ info: info.value }); if (settings.status === 'fulfilled') applySettings(settings.value); + void reloadSkins(); if (vault.status === 'fulfilled') useApp.setState({ vault: vault.value }); if (jobs.status === 'fulfilled') setJobs(jobs.value); if (prompts.status === 'fulfilled') { diff --git a/ui/src/api/mock.ts b/ui/src/api/mock.ts index 2360b3e..ccac8f6 100644 --- a/ui/src/api/mock.ts +++ b/ui/src/api/mock.ts @@ -435,6 +435,7 @@ function defaultSettings(): T.Settings { return { language: 'auto', theme: 'system', + appearance: { skin: 'default', accent: null, density: null, listFontSize: null, radius: null, stripes: null, fontUi: null, fontMono: null }, showHidden: false, confirmDelete: true, confirmOverwrite: true, @@ -609,6 +610,19 @@ export function createMockBackend(emit: Emit, opts: MockOptions): MockBackend { { id: 'bm4', name: 'nginx logs', scope: '*', path: '/var/log/nginx' }, ]; + /** User skins (the skins folder); one example so the gallery shows how they look. */ + const userSkins: Record = { + lagoon: { + id: 'lagoon', + name: 'Lagoon', + author: 'demo', + description: 'A user skin: the default look with a teal accent and striped rows.', + style: { stripes: true, radius: 8 }, + light: { accent: '#0e8a8a' }, + dark: { accent: '#3cc7c0', bg: '#0d1517', chrome: '#111c1f', surface: '#152226' }, + }, + }; + let commands: T.CustomCommand[] = [ { id: 'cmd1', name: 'Disk usage', command: 'du -sh !&', perFile: false, target: 'session', showOutput: true, refresh: false }, { id: 'cmd2', name: 'Tail (last 50 lines)', command: 'tail -n 50 "!"', perFile: true, target: 'session', showOutput: true, refresh: false }, @@ -2287,6 +2301,26 @@ export function createMockBackend(emit: Emit, opts: MockOptions): MockBackend { return null; }, + 'skins.list': () => ({ + dir: '/home/demo/.config/rust-commander/skins', + skins: Object.entries(userSkins).map(([id, skin]) => ({ file: `${id}.json`, skin: deepClone(skin) })), + errors: [], + }), + 'skins.save': (p) => { + const skin = deepClone(p.skin) as Dict; + const id = String(skin?.id ?? ''); + if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(id)) fail('invalid_input', `invalid skin id "${id}"`); + if (!String(skin.name ?? '').trim()) fail('invalid_input', 'a skin needs a name'); + userSkins[id] = skin; + emit('skins.changed', { id }); + return { file: `${id}.json`, skin: deepClone(skin) }; + }, + 'skins.delete': (p) => { + delete userSkins[String(p.id)]; + emit('skins.changed', { id: String(p.id) }); + return null; + }, + 'commands.list': () => deepClone(commands), 'commands.save': (p) => { const c = { ...(p.command as T.CustomCommand) }; diff --git a/ui/src/api/types.ts b/ui/src/api/types.ts index 7758c11..8618bce 100644 --- a/ui/src/api/types.ts +++ b/ui/src/api/types.ts @@ -416,9 +416,27 @@ export interface ServerStatus { error?: string | null; } +/** The look: a skin plus the user's adjustments (`null` = what the skin says). */ +export interface AppearanceSettings { + /** Built-in skin id or a user skin (file in `/skins/`). */ + skin: string; + accent?: string | null; + density?: 'compact' | 'normal' | 'comfortable' | null; + listFontSize?: number | null; + radius?: number | null; + stripes?: boolean | null; + fontUi?: string | null; + fontMono?: string | null; +} + +/** A skin file in the skins folder (content checked by lib/skins/engine.ts). */ +export interface SkinFile { file: string; skin: unknown } + export interface Settings { language: 'auto' | 'en' | 'de'; + /** Which variant of the skin: follow the system, or always light / dark. */ theme: 'system' | 'light' | 'dark'; + appearance: AppearanceSettings; showHidden: boolean; confirmDelete: boolean; confirmOverwrite: boolean; @@ -486,6 +504,12 @@ export interface RpcMethods { 'settings.get': [Empty, Settings]; 'settings.set': [{ settings: Settings }, Settings]; + /** User skins: the JSON files in `/skins/` (`dir`), and files that could not be read. */ + 'skins.list': [Empty, { dir: string; skins: SkinFile[]; errors: { file: string; message: string }[] }]; + /** Create or replace a user skin (by its `id`). */ + 'skins.save': [{ skin: unknown }, SkinFile]; + 'skins.delete': [{ id: string }, null]; + 'vault.status': [Empty, VaultStatus]; 'vault.unlock': [{ password: string }, VaultStatus]; 'vault.lock': [Empty, VaultStatus]; @@ -671,6 +695,8 @@ export interface RpcEvents { /** A directory changed because of an operation; panels showing it should refresh. */ 'fs.changed': { session: string; path: string }; 'log': LogEntry; + /** A user skin was saved or deleted (possibly by another client). */ + 'skins.changed': { id: string }; /** Events were dropped because this client fell behind: reload the state. */ 'resync': null; } diff --git a/ui/src/components/DialogHost.tsx b/ui/src/components/DialogHost.tsx index 8f07828..91b0cfd 100644 --- a/ui/src/components/DialogHost.tsx +++ b/ui/src/components/DialogHost.tsx @@ -37,6 +37,7 @@ const registry: Registry = { diff: lazy(() => import('./dialogs/DiffDialog')), fingerprint: lazy(() => import('./dialogs/FingerprintDialog')), openFile: lazy(() => import('./dialogs/OpenFileDialog')), + skinEditor: lazy(() => import('./dialogs/SkinEditor')), }; export function DialogHost() { diff --git a/ui/src/components/MenuBar.tsx b/ui/src/components/MenuBar.tsx index c2b83be..0a670d5 100644 --- a/ui/src/components/MenuBar.tsx +++ b/ui/src/components/MenuBar.tsx @@ -4,11 +4,12 @@ import { GitCompareArrows, Hash, Info, Keyboard, Link2, ListChecks, Lock, LogOut, Menu as MenuIcon, Monitor, Moon, MoveRight, Network, PanelBottom, PanelLeft, Pencil, Plus, RefreshCw, Search, Settings, Share2, SquareTerminal, Sun, SunMoon, Trash2, Unplug, Upload, Command, Archive, ArrowDownUp, Radar, ClipboardCopy, FolderOpen, Route, Repeat, FolderTree, Fingerprint, GitCompare, FileSearch, - Undo2, + Undo2, Palette, } from 'lucide-react'; import { call, mode, webLogout } from '../api/client'; import { useT, type TFn } from '../i18n'; -import { cycleTheme, saveSettings, setLayout, setTheme, toggleDock, toggleHidden, toggleSidebar, useApp } from '../store/app'; +import { cycleTheme, saveSettings, setLayout, setSkin, setTheme, toggleDock, toggleHidden, toggleSidebar, useApp } from '../store/app'; +import { allSkins } from '../store/skins'; import { openDialog, openSingleton } from '../store/dialogs'; import { getPanel, navigate, other, patchPanel, refresh, selectAll, selectNone, invertSelection, setSort, usePanels, type SortKey } from '../store/panels'; import * as ops from '../actions/fileOps'; @@ -173,6 +174,21 @@ export function buildMenus(t: TFn): { id: string; label: string; items: () => Me { label: t('theme.dark'), icon: Moon, checked: theme === 'dark', onClick: () => setTheme('dark') }, ], }, + { + label: t('view.skin'), + icon: Palette, + testId: 'menu-skin', + submenu: [ + ...allSkins().map((e): MenuItem => ({ + label: e.skin.name, + checked: (st.settings?.appearance?.skin || 'default') === e.skin.id, + testId: `menu-skin-${e.skin.id}`, + onClick: () => setSkin(e.skin.id), + })), + { separator: true }, + { label: t('view.appearance'), icon: Palette, onClick: () => openSingleton('preferences', { tab: 'appearance' }), testId: 'menu-appearance' }, + ], + }, { label: t('keymap.title'), icon: Keyboard, diff --git a/ui/src/components/SkinPreview.tsx b/ui/src/components/SkinPreview.tsx new file mode 100644 index 0000000..a6e174e --- /dev/null +++ b/ui/src/components/SkinPreview.tsx @@ -0,0 +1,160 @@ +// A miniature Rust Commander drawn with a skin's tokens: the gallery thumbnails and the +// skin editor's preview. The tokens are set as CSS custom properties on the preview's root, +// so everything inside uses the skin without touching the rest of the page. +import type { CSSProperties } from 'react'; +import { Archive, FileCode2, FileText, Folder, Image, ScrollText, Terminal } from 'lucide-react'; +import type { Resolved } from '../lib/skins/engine'; +import { cx } from './ui'; + +interface Row { + name: string; + cat: 'dir' | 'code' | 'image' | 'archive' | 'text' | 'document' | 'script'; + size?: string; + cursor?: boolean; + selected?: boolean; +} + +const ICONS = { dir: Folder, code: FileCode2, image: Image, archive: Archive, text: FileText, document: FileText, script: ScrollText }; + +const LEFT: Row[] = [ + { name: '..', cat: 'dir' }, + { name: 'Documents', cat: 'dir' }, + { name: 'projects', cat: 'dir', cursor: true }, + { name: 'backup.tar.gz', cat: 'archive', size: '1.2 GB' }, + { name: 'main.rs', cat: 'code', size: '8.4 KB' }, + { name: 'photo.jpg', cat: 'image', size: '2.1 MB', selected: true }, + { name: 'notes.md', cat: 'text', size: '3 KB' }, + { name: 'report.pdf', cat: 'document', size: '640 KB' }, +]; +const RIGHT: Row[] = [ + { name: '..', cat: 'dir' }, + { name: 'www', cat: 'dir' }, + { name: 'index.html', cat: 'code', size: '12 KB' }, + { name: 'logo.png', cat: 'image', size: '48 KB', selected: true }, + { name: 'deploy.sh', cat: 'script', size: '1 KB' }, + { name: 'style.css', cat: 'code', size: '9 KB' }, + { name: 'access.log', cat: 'text', size: '5 MB' }, + { name: 'site.tar', cat: 'archive', size: '30 MB' }, +]; +const KEYS = ['Help', 'Menu', 'View', 'Edit', 'Copy', 'Move', 'Mkdir', 'Delete']; + +export function skinStyle(r: Resolved): CSSProperties { + return { ...(r.vars as CSSProperties), colorScheme: r.scheme }; +} + +function Panel({ rows, path, active, stripes }: { rows: Row[]; path: string; active: boolean; stripes: boolean }) { + return ( +
+
+ {active ? 'local' : 'web-01'} +
+
{path}
+
+ {rows.map((r, i) => { + const Icon = ICONS[r.cat]; + return ( +
+ + + + {r.name} + {r.size ?? ''} +
+ ); + })} +
+
{active ? '1 of 7 marked · 2.1 MB' : '1 of 7 marked'}
+
+ ); +} + +function Code() { + return ( +
+      1{'// copy only what changed'}{'\n'}
+      2fn sync(src: &Path) -> Result{'<'}u64{'> {'}{'\n'}
+      3{'    '}let limit = 4096;{'\n'}
+      4{'    '}println!("done: {'{'}limit{'}'}");{'\n'}
+      5{'    '}return true;{'\n'}
+      6{'}'}
+    
+ ); +} + +function Term() { + return ( +
+      demo@web-01:~$ ls{'\n'}
+      app  logs  site.tar  deploy.sh{'\n'}
+      warning: disk 81% full{'\n'}
+      demo@web-01:~$  
+    
+ ); +} + +/** `size="card"`: thumbnail for the gallery; `"full"`: with editor, terminal and controls. */ +export function SkinPreview({ resolved, size = 'full', className }: { resolved: Resolved; size?: 'card' | 'full'; className?: string }) { + const stripes = resolved.style.stripes; + const keys = size === 'card' ? KEYS.slice(0, 6) : KEYS; + return ( + + ); +} diff --git a/ui/src/components/dialogs/Appearance.tsx b/ui/src/components/dialogs/Appearance.tsx new file mode 100644 index 0000000..6773d79 --- /dev/null +++ b/ui/src/components/dialogs/Appearance.tsx @@ -0,0 +1,303 @@ +// Preferences → Appearance: light/dark, the skin gallery, the user's adjustments, and the +// skins folder. Changes are previewed live; the Preferences dialog saves them. +import { useEffect, useMemo, type KeyboardEvent } from 'react'; +import { BookOpen, Check, Copy, Download, FileUp, FolderOpen, Moon, Pencil, Plus, RefreshCw, RotateCcw, Sun, Trash2, TriangleAlert } from 'lucide-react'; +import type { AppearanceSettings, Settings } from '../../api/types'; +import { call } from '../../api/client'; +import { tr, useT } from '../../i18n'; +import { DENSITIES, DEFAULT_SKIN_ID, normalizeSkinId, validateSkin, type Density, type Skin } from '../../lib/skins/engine'; +import { downloadSkin, GUIDE_URL, pickTextFile } from '../../lib/skins/files'; +import { normalizeColor, toHex6 } from '../../lib/skins/color'; +import { BUILTIN_IDS, BUILTIN_SKINS } from '../../skins'; +import { useApp } from '../../store/app'; +import { confirmDialog, openDialog } from '../../store/dialogs'; +import { deleteUserSkin, lookupSkin, reloadSkins, resolveLook, saveUserSkin, skinVariants, useSkins, type SkinEntry } from '../../store/skins'; +import { toast } from '../../store/toasts'; +import { Badge, Button, Field, IconButton, Segmented, Select, TextInput, cx } from '../ui'; +import { SkinPreview } from '../SkinPreview'; + +const ACCENTS = ['#2563d9', '#0e8a8a', '#2f8f46', '#c27c0e', '#e2672f', '#d03e47', '#c2417f', '#7c4dd6']; + +export function openGuide() { + if (useApp.getState().info?.mode === 'desktop') void call('app.open', { target: GUIDE_URL }).catch((e) => toast.error(e)); + else window.open(GUIDE_URL, '_blank', 'noopener,noreferrer'); +} + +/** Imports a skin file chosen by the user; returns its id. */ +export async function importSkin(): Promise { + const text = await pickTextFile(); + if (text === null) return null; + let raw: unknown; + try { + raw = JSON.parse(text); + } catch (e) { + toast.error(tr('skins.invalid'), String(e)); + return null; + } + const v = validateSkin(raw); + if (!v.skin) { + toast.error(tr('skins.invalid'), v.errors.join('\n')); + return null; + } + const skin = v.skin; + if (BUILTIN_IDS.has(skin.id)) skin.id = normalizeSkinId(`${skin.id}-custom`); + if (useSkins.getState().user.some((e) => e.skin.id === skin.id)) { + const ok = await confirmDialog({ title: tr('skins.replaceTitle'), message: tr('skins.replaceText', { id: skin.id }), okLabel: tr('common.replace') }); + if (!ok) return null; + } + try { + await saveUserSkin(skin); + } catch (e) { + toast.error(e); + return null; + } + if (v.warnings.length) toast.warning(tr('skins.imported', { name: skin.name }), tr('skins.importIgnored', { n: v.warnings.length, first: v.warnings[0] })); + else toast.success(tr('skins.imported', { name: skin.name })); + return skin.id; +} + +/** A copy of `base` to customize: it extends the base and starts without changes. */ +export function newSkinFrom(baseId: string): Skin { + const base = lookupSkin(baseId) ?? lookupSkin(DEFAULT_SKIN_ID)!; + const taken = (id: string) => BUILTIN_IDS.has(id) || useSkins.getState().user.some((e) => e.skin.id === id); + let id = normalizeSkinId(`${base.id}-custom`); + for (let i = 2; taken(id); i++) id = normalizeSkinId(`${base.id}-custom-${i}`); + const variants = skinVariants(base); + return { + id, + name: tr('skins.copyName', { name: base.name }), + extends: base.id, + ...(variants.includes('light') ? { light: {} } : {}), + ...(variants.includes('dark') ? { dark: {} } : {}), + }; +} + +function SkinCard({ entry, selected, theme, onSelect, onUse }: { entry: SkinEntry; selected: boolean; theme: Settings['theme']; onSelect: () => void; onUse: (id: string) => void }) { + const t = useT(); + const { skin, builtin } = entry; + const user = useSkins((s) => s.user); + const resolved = useMemo(() => resolveLook({ theme, appearance: { skin: skin.id } }), [skin, theme, user]); // eslint-disable-line react-hooks/exhaustive-deps + const variants = skinVariants(skin); + const onKey = (e: KeyboardEvent) => { + if (e.target !== e.currentTarget) return; + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + onSelect(); + } + }; + const edit = () => openDialog('skinEditor', builtin ? { skin: newSkinFrom(skin.id), onSaved: (id, use) => use && onUse(id) } : { skin, onSaved: (id, use) => use && onUse(id) }); + const remove = async () => { + if (!(await confirmDialog({ title: t('skins.deleteTitle'), message: t('skins.deleteText', { name: skin.name }), okLabel: t('skins.delete'), danger: true }))) return; + try { + await deleteUserSkin(skin.id); + if (selected) onUse(DEFAULT_SKIN_ID); + toast.success(t('skins.deleted'), skin.name); + } catch (e) { + toast.error(e); + } + }; + return ( +
+
+ +
+ {selected && ( + + + + )} +
e.stopPropagation()}> + + downloadSkin(skin)} /> + {!builtin && void remove()} />} +
+
+
+
{skin.name}
+
{skin.author && !builtin ? t('skins.by', { author: skin.author }) : (skin.description ?? '')}
+
+ {variants.length === 1 && ( + + {variants[0] === 'dark' ? : } + + )} + {entry.warnings.length > 0 && ( + + + + )} +
+
+ ); +} + +function AccentPicker({ value, onChange }: { value: string | null | undefined; onChange: (v: string | null) => void }) { + const t = useT(); + const cur = value ? normalizeColor(value) : null; + return ( +
+
+ ); +} + +export function AppearancePane({ draft, onChange }: { draft: Settings; onChange: (patch: Partial) => void }) { + const t = useT(); + const user = useSkins((s) => s.user); + const problems = useSkins((s) => s.problems); + const dir = useSkins((s) => s.dir); + const desktop = useApp((s) => s.info?.mode === 'desktop'); + const app: AppearanceSettings = draft.appearance ?? { skin: DEFAULT_SKIN_ID }; + const setApp = (patch: Partial) => onChange({ appearance: { ...app, ...patch } }); + const current = app.skin || DEFAULT_SKIN_ID; + + useEffect(() => { + void reloadSkins(); + }, []); + + const card = (entry: SkinEntry) => ( + setApp({ skin: entry.skin.id })} onUse={(id) => setApp({ skin: id })} /> + ); + const adjusted = !!(app.accent || app.density || app.listFontSize || app.radius !== null && app.radius !== undefined || app.stripes !== null && app.stripes !== undefined || app.fontUi || app.fontMono); + const opt = (v: string, parse: (s: string) => T): T | null => (v === '' ? null : parse(v)); + + return ( +
+ + onChange({ theme: v })} + options={[ + { value: 'system', label: t('theme.system') }, + { value: 'light', label: t('theme.light'), icon: Sun }, + { value: 'dark', label: t('theme.dark'), icon: Moon }, + ]} + /> + + +
{t('skins.builtin')}
+
+ {BUILTIN_SKINS.map((skin) => card({ skin, builtin: true, warnings: [] }))} +
+ +
+ {t('skins.user')} +
+ + +
+ {user.length ?
{user.map(card)}
:

{t('skins.userEmpty')}

} + {problems.length > 0 && ( +
+
+ {t('skins.problems')} +
+ {problems.map((p) => ( +
+ {p.file} – {p.message} +
+ ))} +
+ )} +
+
+
{t('skins.folder')}
+ {dir &&
{dir}
} +
{t('skins.folderHint')}
+
+
+ {desktop && dir && ( + + )} + + +
+
+ +
+ {t('skins.adjust')} + {adjusted && {lookupSkin(current)?.name}} +
+

{t('skins.adjustHint')}

+
+ + setApp({ accent: v })} /> + + + + + + + + + + + + + + + setApp({ fontUi: e.target.value || null })} placeholder={t('skins.fromSkin')} /> + + + setApp({ fontMono: e.target.value || null })} placeholder={t('skins.fromSkin')} className="mono" /> + +
+
+ +
+
+ ); +} diff --git a/ui/src/components/dialogs/PreferencesDialog.tsx b/ui/src/components/dialogs/PreferencesDialog.tsx index c6c1e41..ac33276 100644 --- a/ui/src/components/dialogs/PreferencesDialog.tsx +++ b/ui/src/components/dialogs/PreferencesDialog.tsx @@ -1,5 +1,5 @@ -import { useEffect, useState } from 'react'; -import { ArrowLeftRight, Code2, Globe, KeyRound, Lock, Radar, Settings, Shield, SquareTerminal, Trash2, Search } from 'lucide-react'; +import { useEffect, useLayoutEffect, useState } from 'react'; +import { ArrowLeftRight, Code2, Globe, KeyRound, Lock, Palette, Radar, Settings, Shield, SquareTerminal, Trash2, Search } from 'lucide-react'; import type { FormatterInfo, KnownHost, Settings as SettingsT } from '../../api/types'; import { call } from '../../api/client'; import { tr, useT } from '../../i18n'; @@ -13,8 +13,10 @@ import { attempt, toast } from '../../store/toasts'; import { Badge, Button, Checkbox, Dialog, DialogButtons, Field, IconButton, NumberInput, Segmented, Select, Spinner, Tabs, TextInput, type TabDef } from '../ui'; import { TransferOptionsForm } from './common'; import { KEYMAP_IDS } from '../../lib/keymaps'; +import { endPreview, previewLook } from '../../store/skins'; +import { AppearancePane } from './Appearance'; -type Tab = 'general' | 'transfer' | 'discovery' | 'server' | 'editor' | 'terminal' | 'security'; +type Tab = 'general' | 'appearance' | 'transfer' | 'discovery' | 'server' | 'editor' | 'terminal' | 'security'; /** Built-in formatters plus the ones found on the host. */ function InstalledFormatters() { @@ -173,6 +175,20 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps if (!draft && settings) setDraft(structuredClone(settings)); }, [settings, draft]); + // live preview of the look while the dialog is open + const lookKey = draft ? JSON.stringify([draft.theme, draft.appearance]) : ''; + const savedKey = settings ? JSON.stringify([settings.theme, settings.appearance]) : ''; + useEffect(() => { + if (!draft) return; + if (lookKey === savedKey) endPreview('prefs'); + else previewLook('prefs', { theme: draft.theme, appearance: draft.appearance }); + }, [lookKey, savedKey]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => () => endPreview('prefs'), []); + // opened on a specific tab (View → Skin → Appearance…): focus that tab, not the first one + useLayoutEffect(() => { + if (props.tab) document.querySelector('.prefs-tabs .tab.on')?.focus({ preventScroll: true }); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + if (!draft) return null; const set = (k: K, v: SettingsT[K]) => setDraft({ ...draft, [k]: v }); const sub = (k: K, patch: Partial) => setDraft({ ...draft, [k]: { ...draft[k], ...patch } }); @@ -181,6 +197,7 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps const submit = async () => { setBusy(true); save('skipCopyDialog', skipCopy); + endPreview('prefs', false); const r = await saveSettings(draft); setBusy(false); if (r) { @@ -191,6 +208,7 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps const tabs: TabDef[] = [ { id: 'general', label: t('prefs.general'), icon: Settings }, + { id: 'appearance', label: t('prefs.appearance'), icon: Palette }, { id: 'transfer', label: t('prefs.transfer'), icon: ArrowLeftRight }, { id: 'discovery', label: t('prefs.discovery'), icon: Radar }, { id: 'server', label: t('prefs.server'), icon: Globe }, @@ -200,7 +218,7 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps ]; return ( - void submit()} width={820} height={600} bodyClassName="prefs-body" footer={}> + void submit()} width={900} height={640} bodyClassName="prefs-body" footer={}>
{tab === 'general' && ( @@ -213,9 +231,6 @@ export default function PreferencesDialog({ props, close }: { props: DialogProps - - set('theme', v)} options={[{ value: 'system', label: t('theme.system') }, { value: 'light', label: t('theme.light') }, { value: 'dark', label: t('theme.dark') }]} /> - onChange(withPreviousAlpha(e.target.value, effective))} aria-label={def.name} /> + + ) : ( + + )} +
+ {def.name} + {def.doc} +
+ { + const v = e.target.value; + setText(v); + if (!v.trim()) onChange(null); + else if (sanitizeValue(def, v) !== null) onChange(v.trim()); + }} + onBlur={() => !invalid && setText(value ?? '')} + aria-label={`${def.name} value`} + data-no-enter + /> + onChange(null)} disabled={value === undefined} className="tok-reset" /> +
+ ); +} + +function StyleSelect({ value, options, onChange, format }: { value: T | undefined; options: T[]; onChange: (v: T | undefined) => void; format?: (v: T) => string }) { + const t = useT(); + return ( + + ); +} + +const range = (lo: number, hi: number, step = 1) => Array.from({ length: Math.floor((hi - lo) / step) + 1 }, (_, i) => lo + i * step); + +export default function SkinEditor({ props, close }: { props: DialogPropsMap['skinEditor']; close: () => void }) { + const t = useT(); + const user = useSkins((s) => s.user); + const theme = useApp((s) => s.settings?.theme ?? 'system'); + const [initial] = useState(() => structuredClone(props.skin ?? { id: 'my-skin', name: 'My skin', light: {}, dark: {} })); + const [isNew] = useState(() => !user.some((e) => e.skin.id === initial.id)); + const [skin, setSkin] = useState(initial); + const [idTouched, setIdTouched] = useState(!isNew); + const [view, setView] = useState('colors'); + const [filter, setFilter] = useState(''); + const [onlySet, setOnlySet] = useState(false); + const [live, setLive] = useState(false); + const [json, setJson] = useState(''); + const [busy, setBusy] = useState(false); + const [openGroups, setOpenGroups] = useState>(() => new Set(['base', 'text', 'accent'])); + + // the draft as it would be saved: values checked and normalized + const clean = useMemo(() => validateSkin(skin).skin ?? { ...skin, id: normalizeSkinId(skin.id || 'skin'), name: skin.name || '?' }, [skin]); + const variants = useMemo(() => skinVariants(clean), [clean, user]); // eslint-disable-line react-hooks/exhaustive-deps + const [scheme, setScheme] = useState(() => { + const v = skinVariants(initial); + const want = requestedScheme(theme); + return v.includes(want) ? want : v[0]; + }); + useEffect(() => { + if (!variants.includes(scheme)) setScheme(variants[0]); + }, [variants, scheme]); + + const resolved = useMemo(() => resolveLook({ theme: scheme, appearance: { skin: clean.id } }, scheme, clean), [clean, scheme, user]); // eslint-disable-line react-hooks/exhaustive-deps + const contrast = useMemo(() => contrastReport(resolved).filter((c) => !c.ok), [resolved]); + + useEffect(() => { + if (live) previewLook('skin-editor', { theme: scheme, appearance: { skin: clean.id } }, clean); + else endPreview('skin-editor'); + }, [live, clean, scheme]); + useEffect(() => () => endPreview('skin-editor'), []); + + const own = (scheme === 'light' ? skin.light : skin.dark) ?? {}; + const effectiveOwn = (scheme === 'light' ? clean.light : clean.dark) ?? {}; + const setToken = (name: string, value: string | null) => + setSkin((s) => { + const v = { ...(s[scheme] ?? {}) }; + if (value === null) delete v[name]; + else v[name] = value; + return { ...s, [scheme]: v }; + }); + const setStyle = (k: K, v: SkinStyle[K] | undefined) => + setSkin((s) => { + const style = { ...(s.style ?? {}) }; + if (v === undefined || v === '') delete style[k]; + else style[k] = v; + return { ...s, style }; + }); + const toggleVariant = (v: Scheme, on: boolean) => + setSkin((s) => { + const next = { ...s }; + if (on) next[v] = s[v] ?? {}; + else delete next[v]; + return next; + }); + + const bases = allSkins().filter((e) => e.skin.id !== skin.id); + const idError = !ID_RE.test(skin.id) ? t('skinEditor.idHint') : BUILTIN_IDS.has(skin.id) ? t('skins.reservedId', { id: skin.id }) : null; + const dirty = JSON.stringify(compactSkin(clean)) !== JSON.stringify(compactSkin(validateSkin(initial).skin ?? initial)); + + const q = filter.trim().toLowerCase(); + const visible = (d: TokenDef) => (!q || d.name.includes(q) || d.doc.toLowerCase().includes(q)) && (!onlySet || own[d.name] !== undefined); + + const tryClose = async () => { + if (dirty && !(await confirmDialog({ title: t('skinEditor.title'), message: t('skinEditor.unsaved'), okLabel: t('common.ok') }))) return; + close(); + }; + + const save = async (use: boolean) => { + if (idError) return toast.warning(idError); + if (!skin.name.trim()) return toast.warning(t('skins.invalid'), '"name"'); + const exists = user.some((e) => e.skin.id === clean.id); + if (exists && (isNew || clean.id !== initial.id)) { + if (!(await confirmDialog({ title: t('skins.replaceTitle'), message: t('skins.replaceText', { id: clean.id }), okLabel: t('common.replace') }))) return; + } + setBusy(true); + try { + await saveUserSkin(compactSkin(clean)); + toast.success(t('skins.saved', { name: clean.name })); + if (props.onSaved) props.onSaved(clean.id, use); + else if (use) applySkinSetting(clean.id); + endPreview('skin-editor', false); + close(); + } catch (e) { + toast.error(e); + } finally { + setBusy(false); + } + }; + + const applyJson = () => { + let raw: unknown; + try { + raw = JSON.parse(json); + } catch (e) { + return toast.error(t('skins.invalid'), String(e)); + } + const v = validateSkin(raw); + if (!v.skin) return toast.error(t('skins.invalid'), v.errors.join('\n')); + if (v.warnings.length) toast.warning(t('skins.importIgnored', { n: v.warnings.length, first: v.warnings[0] })); + setSkin(v.skin); + setIdTouched(true); + }; + + const tabs: TabDef[] = [ + { id: 'colors', label: t('skinEditor.colors') }, + { id: 'style', label: t('skinEditor.style') }, + { id: 'json', label: t('skinEditor.json') }, + ]; + + return ( + void tryClose()} + onSubmit={() => void save(false)} + width={1120} + height={720} + className="skin-editor-dlg" + bodyClassName="skin-editor" + footer={ + <> +
+ + +
+
+ + + +
+ + } + > +
+
+ + { + const name = e.target.value; + setSkin((s) => ({ ...s, name, ...(idTouched ? {} : { id: normalizeSkinId(slugify(name)) }) })); + }} + data-testid="skin-name" + data-autofocus + /> + + {idError} : undefined}> + { + setIdTouched(true); + setSkin((s) => ({ ...s, id: e.target.value.toLowerCase() })); + }} + data-testid="skin-id" + /> + + + + + + setSkin((s) => ({ ...s, author: e.target.value || undefined }))} /> + + + setSkin((s) => ({ ...s, description: e.target.value || undefined }))} /> + +
+
+ {t('skinEditor.variants')} + toggleVariant('light', v)} /> + toggleVariant('dark', v)} /> +
+ {t('skinEditor.editing')} + ({ value: v, label: v === 'light' ? t('skinEditor.hasLight') : t('skinEditor.hasDark'), icon: v === 'light' ? Sun : Moon }))} + /> +
+ { + if (v === 'json') setJson(skinToJson(clean)); + setView(v); + }} + className="se-tabs" + /> +
+ {view === 'colors' && ( +
+
+
+ + setFilter(e.target.value)} placeholder={t('skinEditor.filter')} data-no-enter /> +
+ +
+ {GROUPS.map((g) => { + const defs = TOKENS.filter((d) => d.group === g && visible(d)); + if (!defs.length) return null; + const count = TOKENS.filter((d) => d.group === g && own[d.name] !== undefined).length; + const hint = g === 'palette' || g === 'accent' ? t(`skinEditor.hint.${g}` as TKey) : null; + return ( + + setOpenGroups((s) => { + const n = new Set(s); + if (n.has(g)) n.delete(g); + else n.add(g); + return n; + }) + } + extra={count ? `${count} ${t('skinEditor.set')}` : undefined} + > + {hint &&

{hint}

} +
+ {defs.map((d) => ( + setToken(d.name, v)} /> + ))} +
+
+ ); + })} +
+ )} + {view === 'style' && ( +
+ + setStyle('fontUi', e.target.value)} placeholder={resolved.style.fontUi} /> + + + setStyle('fontMono', e.target.value)} placeholder={resolved.style.fontMono} /> + + + setStyle('radius', v)} format={(n) => `${n} px`} /> + + + setStyle('panelRadius', v)} format={(n) => `${n} px`} /> + + + value={skin.style?.density} options={DENSITIES} onChange={(v) => setStyle('density', v)} format={(d) => t(`skins.density.${d}`)} /> + + + setStyle('listFontSize', v)} format={(n) => `${n} px`} /> + + + setStyle('stripes', v)} format={(b) => (b ? t('common.on') : t('common.off'))} /> + +
+ )} + {view === 'json' && ( +
+

{t('skinEditor.jsonHint')}

+