Files
luxe/crates/luxe-tui/examples/theme_css.rs
Evan Whittaker d2129a886f Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md
- luxe remote puts the sessions on your computer in reach of your own phone or tablet over
  Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a
  paired device and your own Tailscale login.
- luxe join lets another program on the same machine join a running session over the RPC protocol.
- An AGENTS.md in a subfolder reaches the model the first time it works there.
- Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing.
- A session is open in one Luxe at a time, web_search shares results across its phrasings, and a
  grep glob starting with ! excludes.

The CHANGELOG has the full list.
2026-10-20 02:40:13 -05:00

237 lines
9.3 KiB
Rust

//! theme_css — the built-in themes as CSS custom properties.
//!
//! The website and the terminal have to be the same colors, and the only way that stays true is if
//! neither one owns them: `luxe-core`'s theme JSON is the source, and this writes the web's copy
//! from it. Editing a hex in the site's stylesheet is then a mistake the next regeneration undoes,
//! which is the point.
//!
//! Emits `:root` (the `luxe` theme, the only one the site is set in) and the wordmark ramp steps
//! the vector logotype reads — computed by asking the wordmark itself, so the mark on the page and
//! the mark in the terminal cannot describe different metal.
//!
//! `--json` instead emits every built-in theme's exported tokens as one object, which is what the
//! themes page previews. The site cannot read the theme files itself: `colors` entries may alias
//! `vars` entries, and that resolution is `ThemeRegistry`'s — a second implementation of it in
//! TypeScript would be a rule with two copies.
//!
//! ```sh
//! cargo run -p luxe-tui --example theme_css > web/src/assets/generated/tokens.css
//! cargo run -p luxe-tui --example theme_css -- --json > web/src/assets/generated/themes.json
//! ```
use luxe_core::theme::css::{css_name, custom_properties};
use luxe_core::theme::{ColorValue, ThemeRegistry};
use luxe_tui::widgets::Wordmark;
use std::collections::HashMap;
use std::fmt::Write as _;
/// The theme the site is drawn in.
const DARK: &str = "luxe";
/// Tokens worth exposing to the web, in the order they make sense to read.
///
/// Deliberately not every token: the site has no diff gutters or thinking levels, and shipping
/// forty properties it never uses would make the real ones harder to find.
const EXPORTED: &[&str] = &[
"background",
"userMsgBg",
"selectedBg",
"text",
"muted",
"dim",
"border",
"borderMuted",
"accent",
"accentSecondary",
"info",
"success",
"warning",
"error",
];
fn main() {
let registry = ThemeRegistry::new();
if std::env::args().any(|arg| arg == "--json") {
print!("{}", catalog(&registry));
return;
}
let dark = registry.resolve(DARK).expect("the luxe theme is a built-in");
print!("{}", stylesheet(&dark));
}
/// Every built-in theme's exported tokens, as JSON, in the registry's order.
///
/// Hand-rolled rather than via `serde_json`: the shape is a map of maps of hex strings, and this
/// example has no other reason to pull a dependency in.
fn catalog(registry: &ThemeRegistry) -> String {
let mut out = String::from("{\n");
let names = registry.names();
for (index, name) in names.iter().enumerate() {
let Some(theme) = registry.resolve(name) else { continue };
let _ = write!(out, " \"{name}\": {{");
let mut first = true;
for token in EXPORTED {
if let Some(hex) = hex(theme.get(*token)) {
let separator = if first { "" } else { "," };
let _ = write!(out, "{separator}\n \"{}\": \"{hex}\"", css_name(token));
first = false;
}
}
let comma = if index + 1 == names.len() { "" } else { "," };
let _ = write!(out, "\n }}{comma}\n");
}
out.push_str("}\n");
out
}
/// The whole generated stylesheet.
fn stylesheet(dark: &HashMap<String, ColorValue>) -> String {
let mut out = String::new();
out.push_str(
"/* Generated by `cargo run -p luxe-tui --example theme_css`. Do not edit.\n \
Source: crates/luxe-core/src/themes/luxe.json */\n\n",
);
out.push_str(":root {\n color-scheme: dark;\n");
out.push_str(&block(dark, true));
// The canvas a baked-in capture sits on. A recording is the terminal's own background in every
// cell Luxe paints, so a plate in any other color turns the painted cells into rectangles; with
// one theme on the page these are the page's own colors, named for what they are for.
let _ = writeln!(
out,
" --luxe-capture-bg: {};\n --luxe-capture-fg: {};",
hex(dark.get("background")).unwrap_or_else(|| "#12100e".into()),
hex(dark.get("text")).unwrap_or_else(|| "#e4dfd6".into()),
);
out.push_str("}\n");
out
}
/// One theme's custom properties, wordmark ramp included.
fn block(theme: &HashMap<String, ColorValue>, dark: bool) -> String {
let mut out = custom_properties(theme, EXPORTED.iter().copied());
// The wordmark's steps, taken from the renderer rather than a table copied out of it — a second
// copy of a rule is a rule that drifts. A still is the frame at `STILL_TICK`, which is exactly
// what a page with no animation should show.
let (Some(accent), Some(canvas)) = (rgb(theme.get("accent")), rgb(theme.get("background")))
else {
return out;
};
let size = Wordmark::Full;
for group in 0..size.group_count() {
let shade = size.group_shade(group, luxe_tui::widgets::STILL_TICK);
let _ = writeln!(
out,
" --luxe-wordmark-{}: {};",
group + 1,
to_hex(blend(accent, canvas, shade))
);
}
// The two ends of the drift's swing. The website animates between them in CSS, so they are taken
// from the same constant the terminal swings through rather than restated as a percentage there.
let _ = writeln!(out, " --luxe-wordmark-lit: {};", to_hex(accent));
let _ = writeln!(
out,
" --luxe-wordmark-dim: {};",
to_hex(blend(accent, canvas, luxe_tui::widgets::DRIFT_DEPTH))
);
// How hard the shine may push, which is not the same on both themes: a light theme's letters
// are saturated mid-tones on near-white and wash out long before a dark theme's do.
let peak = if dark { luxe_tui::widgets::PEAK_DARK } else { luxe_tui::widgets::PEAK_LIGHT };
let _ = writeln!(out, " --luxe-wordmark-shine: {peak};");
let _ = writeln!(out, " --luxe-tile-ink: {};", to_hex(canvas));
out
}
/// `base` pulled `amount` of the way toward `target`, matching the renderer's own blend.
fn blend(base: (u8, u8, u8), target: (u8, u8, u8), amount: f32) -> (u8, u8, u8) {
let mix = |from: u8, to: u8| {
(f32::from(from) + (f32::from(to) - f32::from(from)) * amount).round() as u8
};
(mix(base.0, target.0), mix(base.1, target.1), mix(base.2, target.2))
}
fn rgb(value: Option<&ColorValue>) -> Option<(u8, u8, u8)> {
match value? {
ColorValue::Rgb(red, green, blue) => Some((*red, *green, *blue)),
_ => None,
}
}
fn hex(value: Option<&ColorValue>) -> Option<String> {
value.and_then(luxe_core::theme::css::hex)
}
fn to_hex((red, green, blue): (u8, u8, u8)) -> String {
format!("#{red:02x}{green:02x}{blue:02x}")
}
#[cfg(test)]
mod tests {
use super::*;
fn luxe() -> HashMap<String, ColorValue> {
ThemeRegistry::new().resolve(DARK).expect("luxe")
}
/// Every exported token reaches the stylesheet. A token that resolves to an ANSI index or the
/// terminal default has no hex to give, which is fine in a terminal and useless on a page — so
/// Luxe's own theme must not contain one.
#[test]
fn every_exported_token_has_a_color() {
let dark = luxe();
for token in EXPORTED {
assert!(hex(dark.get(*token)).is_some(), "{token} did not resolve to an RGB color");
}
let css = stylesheet(&dark);
assert!(!css.contains("data-theme"), "one theme, no switch");
assert!(css.contains("--luxe-capture-bg:"), "the capture canvas is still named");
}
/// The generated ramp is the one the TUI paints — structurally, because both come out of
/// `Wordmark::group_shade`. This checks the wiring rather than the arithmetic: that every step
/// reaches the stylesheet, they run the right way, and the last is the accent untouched.
#[test]
fn the_wordmark_ramp_matches_the_terminals() {
let dark = luxe();
let css = block(&dark, true);
let accent = hex(dark.get("accent")).expect("an accent");
let steps = Wordmark::Full.group_count();
assert!(
css.contains(&format!("--luxe-wordmark-{steps}: {accent};")),
"the last step is the accent, exactly"
);
for step in 1..=steps {
assert!(css.contains(&format!("--luxe-wordmark-{step}:")), "step {step} is missing");
}
// Dark theme: the ramp climbs out of the canvas, so the first step is the darkest.
let luminance = |step: usize| {
let hex = css
.split(&format!("--luxe-wordmark-{step}: #"))
.nth(1)
.and_then(|rest| rest.get(..6))
.expect("a hex triple");
u32::from_str_radix(hex, 16).expect("hex")
};
let ladder: Vec<u32> = (1..=steps).map(luminance).collect();
assert!(
ladder.windows(2).all(|pair| pair[1] > pair[0]),
"the ramp runs dim to bright on a dark canvas: {ladder:?}"
);
}
/// The document has the one theme and says it is generated, so nobody edits it by hand.
#[test]
fn the_stylesheet_carries_its_theme_and_its_own_warning() {
let css = stylesheet(&luxe());
assert!(css.starts_with("/* Generated by"));
assert!(css.contains("Do not edit"));
assert!(css.contains(":root {"));
assert!(css.contains("color-scheme: dark;"));
assert_eq!(css.matches("--luxe-accent:").count(), 1, "one definition of the accent");
}
}