Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
//! Capture — a fixture scenario rendered the way the event loop would, settled on one frame.
use super::color::hex;
use super::fail;
use luxe_tui::app::App;
use luxe_tui::fixture::{seeded_app, FixtureScenario};
use luxe_tui::view;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;
use ratatui::Terminal;
use std::time::Duration;
/// Frames a clock-pinned scenario is stepped before capture, matching `ui_fixture` so a still is
/// the same picture in both tools.
const REVEAL_FRAMES: u32 = 28;
/// A scenario rendered through the production view path, and the theme's text color.
///
/// The ink is what a cell the app left at the terminal default is drawn in, which a palette needs
/// as a real value: one theme may paint a cell another leaves alone.
///
/// `overlay` opens a state over the scenario, by the names `ui_fixture`'s `LUXE_FIXTURE_OVERLAY`
/// takes, so the interactive fixture and the still draw the same picture: `github`,
/// `github-detail`, `github-conversation`, `github-draft`, `github-issue`, `github-pulls`,
/// `github-search`, `github-merged`, `pr`, `pr-merge`, a login state, or `mention-<tab>`.
pub(super) fn render(
theme: &str,
scenario: FixtureScenario,
overlay: Option<&str>,
cols: u16,
rows: u16,
) -> (Buffer, String) {
let mut app = seeded_app(theme, scenario).unwrap_or_else(|error: String| fail(&error));
let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("in-memory terminal");
app.update(luxe_tui::app::Msg::TerminalResized { width: cols, height: rows });
if let Some(overlay) = overlay {
if let Some(login) = luxe_tui::fixture::LoginFixture::parse(overlay) {
luxe_tui::fixture::seed_login_wizard(&mut app, login);
} else if let Some(tab) = overlay.strip_prefix("mention-") {
luxe_tui::fixture::seed_mention_picker(&mut app, tab);
} else if overlay.starts_with("pr") || overlay.starts_with("github") {
luxe_tui::fixture::seed_github(&mut app, overlay);
} else {
fail(&format!("unknown overlay {overlay}"));
}
}
step_reveal(&mut terminal, &mut app);
terminal.draw(|frame| view::render(frame, &mut app)).expect("render");
let ink = app.theme_styles.text.fg.and_then(hex).unwrap_or_else(|| "#ffffff".into());
(terminal.backend().buffer().clone(), ink)
}
/// Runs a mid-animation scenario forward the way the event loop does, so the captured frame is the
/// same one every time rather than wherever the clock happened to land.
fn step_reveal(terminal: &mut Terminal<TestBackend>, app: &mut App) {
let Some(base) = app.status.frame_clock else { return };
for step in 1..=REVEAL_FRAMES {
app.status.frame_clock = Some(base + Duration::from_millis(12) * step);
terminal.draw(|frame| view::render(frame, app)).expect("render");
}
}

View File

@@ -0,0 +1,92 @@
//! Color — a ratatui color as hex, through the ANSI and indexed palettes, and text attributes.
use ratatui::style::{Color, Modifier};
/// A ratatui color as `#rrggbb`, or `None` when the terminal would have chosen it.
pub(super) fn hex(color: Color) -> Option<String> {
let (red, green, blue) = match color {
Color::Rgb(red, green, blue) => (red, green, blue),
Color::Indexed(index) => indexed_rgb(index),
Color::Reset => return None,
// The sixteen named colors belong to the terminal's palette. Luxe's own themes are pure
// RGB, so this is only reached by a user theme; xterm's defaults are the least surprising
// stand-in available.
named => indexed_rgb(named_index(named)?),
};
Some(format!("#{red:02x}{green:02x}{blue:02x}"))
}
fn named_index(color: Color) -> Option<u8> {
Some(match color {
Color::Black => 0,
Color::Red => 1,
Color::Green => 2,
Color::Yellow => 3,
Color::Blue => 4,
Color::Magenta => 5,
Color::Cyan => 6,
Color::Gray => 7,
Color::DarkGray => 8,
Color::LightRed => 9,
Color::LightGreen => 10,
Color::LightYellow => 11,
Color::LightBlue => 12,
Color::LightMagenta => 13,
Color::LightCyan => 14,
Color::White => 15,
_ => return None,
})
}
/// The RGB an xterm-256 index stands for: sixteen system colors, a 6×6×6 cube, then a gray ramp.
fn indexed_rgb(index: u8) -> (u8, u8, u8) {
const SYSTEM: [(u8, u8, u8); 16] = [
(0, 0, 0),
(205, 49, 49),
(13, 188, 121),
(229, 229, 16),
(36, 114, 200),
(188, 63, 188),
(17, 168, 205),
(229, 229, 229),
(102, 102, 102),
(241, 76, 76),
(35, 209, 139),
(245, 245, 67),
(59, 142, 234),
(214, 112, 214),
(41, 184, 219),
(255, 255, 255),
];
if index < 16 {
return SYSTEM[index as usize];
}
if index >= 232 {
let level = 8 + (index - 232) * 10;
return (level, level, level);
}
const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
let index = index - 16;
(LEVELS[(index / 36) as usize], LEVELS[(index % 36 / 6) as usize], LEVELS[(index % 6) as usize])
}
/// Ratatui modifiers as SVG text attributes.
pub(super) fn attributes(modifier: Modifier) -> String {
let mut out = String::new();
if modifier.contains(Modifier::BOLD) {
out.push_str(" font-weight=\"700\"");
}
if modifier.contains(Modifier::ITALIC) {
out.push_str(" font-style=\"italic\"");
}
if modifier.contains(Modifier::DIM) {
out.push_str(" opacity=\"0.6\"");
}
match (modifier.contains(Modifier::UNDERLINED), modifier.contains(Modifier::CROSSED_OUT)) {
(true, true) => out.push_str(" text-decoration=\"underline line-through\""),
(true, false) => out.push_str(" text-decoration=\"underline\""),
(false, true) => out.push_str(" text-decoration=\"line-through\""),
(false, false) => {}
}
out
}

View File

@@ -0,0 +1,209 @@
//! Glyph geometry — block, box and triangle glyphs drawn as exact cell fractions, not typeset.
use super::color::hex;
use super::{CELL_H, CELL_W, HAIRLINE};
use ratatui::buffer::Buffer;
use std::fmt::Write as _;
/// Every cell whose glyph is drawn rather than typeset.
pub(super) fn geometry(buffer: &Buffer) -> String {
let mut out = String::new();
for row in 0..buffer.area.height {
for column in 0..buffer.area.width {
let cell = &buffer[(column, row)];
let Some(glyph) = cell.symbol().chars().next() else { continue };
let Some(fill) = hex(cell.fg) else { continue };
if let Some(drawn) = draw(glyph, column, row, &fill) {
let _ = writeln!(out, " {drawn}");
}
}
}
out
}
/// Whether this glyph is drawn as geometry rather than typeset.
pub(super) fn is_drawn(glyph: char) -> bool {
block(glyph).is_some() || arms(glyph).is_some() || triangle_points(glyph).is_some()
}
/// The SVG element for a drawn glyph, or `None` when the font should handle it.
pub(super) fn draw(glyph: char, column: u16, row: u16, fill: &str) -> Option<String> {
let (x, y) = (f64::from(column) * CELL_W, f64::from(row) * CELL_H);
if let Some(parts) = block(glyph) {
return Some(block_element(&parts, x, y, fill));
}
if let Some(points) = triangle_points(glyph) {
return Some(triangle(&points, x, y, fill));
}
arms(glyph).map(|(arms, rounded)| box_line(arms, rounded, x, y, fill))
}
/// A block glyph as `(fractional rects, opacity)`, in cell-relative units.
///
/// Rects are `(x, y, w, h)` with the cell as the unit square. The shade blocks have no geometry of
/// their own — they are the full cell at a fraction of its ink, which is what they mean.
type Block = (Vec<(f64, f64, f64, f64)>, f64);
pub(super) fn block(glyph: char) -> Option<Block> {
let full = vec![(0.0, 0.0, 1.0, 1.0)];
let eighth = |n: f64| n / 8.0;
Some(match glyph {
'\u{2588}' => (full, 1.0),
// Shades: the same cell, thinned.
'\u{2591}' => (full, 0.25),
'\u{2592}' => (full, 0.5),
'\u{2593}' => (full, 0.75),
// Halves.
'\u{2580}' => (vec![(0.0, 0.0, 1.0, 0.5)], 1.0),
'\u{2584}' => (vec![(0.0, 0.5, 1.0, 0.5)], 1.0),
'\u{258c}' => (vec![(0.0, 0.0, 0.5, 1.0)], 1.0),
'\u{2590}' => (vec![(0.5, 0.0, 0.5, 1.0)], 1.0),
// Lower eighths, one through seven.
'\u{2581}'..='\u{2587}' => {
let height = eighth(f64::from(glyph as u32 - 0x2580));
(vec![(0.0, 1.0 - height, 1.0, height)], 1.0)
}
// Left eighths run the other way: U+2589 is seven eighths, U+258F is one.
'\u{2589}'..='\u{258f}' => {
let width = eighth(f64::from(0x2590 - glyph as u32));
(vec![(0.0, 0.0, width, 1.0)], 1.0)
}
'\u{2594}' => (vec![(0.0, 0.0, 1.0, eighth(1.0))], 1.0),
'\u{2595}' => (vec![(1.0 - eighth(1.0), 0.0, eighth(1.0), 1.0)], 1.0),
// Quadrants, as a bitmask of the four sub-cells.
'\u{2596}'..='\u{259f}' => {
let mask = QUADRANTS[glyph as usize - 0x2596];
let mut rects = Vec::new();
for (bit, (qx, qy)) in
[(0.0, 0.0), (0.5, 0.0), (0.0, 0.5), (0.5, 0.5)].into_iter().enumerate()
{
if mask & (1 << bit) != 0 {
rects.push((qx, qy, 0.5, 0.5));
}
}
(rects, 1.0)
}
_ => return None,
})
}
/// Quadrant fills for `U+2596..=U+259F`, as `upper-left | upper-right | lower-left | lower-right`.
const QUADRANTS: [u8; 10] = [
0b0100, // ▖ lower left
0b1000, // ▗ lower right
0b0001, // ▘ upper left
0b1101, // ▙
0b1001, // ▚
0b0111, // ▛
0b1011, // ▜
0b0010, // ▝ upper right
0b0110, // ▞
0b1110, // ▟
];
fn block_element(block: &Block, x: f64, y: f64, fill: &str) -> String {
let (parts, opacity) = block;
let body: String = parts
.iter()
.map(|(rx, ry, rw, rh)| {
format!(
"M{:.2} {:.2}h{:.2}v{:.2}h-{:.2}z",
x + rx * CELL_W,
y + ry * CELL_H,
rw * CELL_W,
rh * CELL_H,
rw * CELL_W
)
})
.collect::<Vec<_>>()
.join("");
let alpha = if *opacity < 1.0 { format!(" fill-opacity=\"{opacity}\"") } else { String::new() };
format!("<path fill=\"{fill}\"{alpha} d=\"{body}\"/>")
}
/// Which cell edges a box-drawing glyph reaches, and whether its corner is rounded.
///
/// `(up, right, down, left)`. Only the light set: it is what Luxe draws with, and a heavy or double
/// rule would need its own stroke width rather than a flag here.
type Arms = (bool, bool, bool, bool);
fn arms(glyph: char) -> Option<(Arms, bool)> {
let sharp = |arms: Arms| Some((arms, false));
match glyph {
'\u{2500}' => sharp((false, true, false, true)),
'\u{2502}' => sharp((true, false, true, false)),
'\u{250c}' => sharp((false, true, true, false)),
'\u{2510}' => sharp((false, false, true, true)),
'\u{2514}' => sharp((true, true, false, false)),
'\u{2518}' => sharp((true, false, false, true)),
'\u{251c}' => sharp((true, true, true, false)),
'\u{2524}' => sharp((true, false, true, true)),
'\u{252c}' => sharp((false, true, true, true)),
'\u{2534}' => sharp((true, true, false, true)),
'\u{253c}' => sharp((true, true, true, true)),
'\u{256d}' => Some(((false, true, true, false), true)),
'\u{256e}' => Some(((false, false, true, true), true)),
'\u{256f}' => Some(((true, false, false, true), true)),
'\u{2570}' => Some(((true, true, false, false), true)),
_ => None,
}
}
/// A box-drawing glyph as a stroked path.
///
/// A rounded corner is one quadratic curve between the two edge midpoints, with the cell's center
/// as its control point — which is exactly the quarter-round the glyph means, with no radius to
/// pick.
fn box_line((up, right, down, left): Arms, rounded: bool, x: f64, y: f64, fill: &str) -> String {
let (cx, cy) = (x + CELL_W / 2.0, y + CELL_H / 2.0);
let (x1, y1) = (x + CELL_W, y + CELL_H);
let mut path = String::new();
if rounded {
let (from_x, from_y) = if up { (cx, y) } else { (cx, y1) };
let (to_x, to_y) = if left { (x, cy) } else { (x1, cy) };
let _ = write!(path, "M{from_x:.2} {from_y:.2}Q{cx:.2} {cy:.2} {to_x:.2} {to_y:.2}");
} else {
for (present, (ex, ey)) in
[(up, (cx, y)), (right, (x1, cy)), (down, (cx, y1)), (left, (x, cy))]
{
if present {
let _ = write!(path, "M{cx:.2} {cy:.2}L{ex:.2} {ey:.2}");
}
}
}
format!("<path fill=\"none\" stroke=\"{fill}\" stroke-width=\"{HAIRLINE:.2}\" d=\"{path}\"/>")
}
/// The half-cell a Powerline Extra triangle inks, in cell-relative units.
fn triangle_points(glyph: char) -> Option<[(f64, f64); 3]> {
Some(match glyph {
'\u{e0b8}' => [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)], // lower left
'\u{e0ba}' => [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)], // lower right
'\u{e0bc}' => [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], // upper left
'\u{e0be}' => [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)], // upper right
_ => return None,
})
}
fn triangle(points: &[(f64, f64); 3], x: f64, y: f64, fill: &str) -> String {
let path: Vec<String> = points
.iter()
.enumerate()
.map(|(index, (px, py))| {
let verb = if index == 0 { 'M' } else { 'L' };
format!("{verb}{:.2} {:.2}", x + px * CELL_W, y + py * CELL_H)
})
.collect();
format!("<path fill=\"{fill}\" d=\"{}z\"/>", path.join(""))
}
pub(super) fn rect(column: u16, row: u16, cells: u16, lines: u16, fill: &str) -> String {
format!(
"<rect x=\"{:.0}\" y=\"{:.0}\" width=\"{:.0}\" height=\"{:.0}\" fill=\"{fill}\"/>",
f64::from(column) * CELL_W,
f64::from(row) * CELL_H,
f64::from(cells) * CELL_W,
f64::from(lines) * CELL_H
)
}

View File

@@ -0,0 +1,73 @@
//! Grid input — a terminal grid handed in on stdin, read into the buffer the exporter draws.
use super::fail;
use ratatui::buffer::Buffer;
use ratatui::style::{Color, Modifier};
/// One cell of a grid handed in on stdin.
#[derive(serde::Deserialize)]
struct GridCell {
/// The character. Empty for the second half of a wide glyph.
c: String,
/// `#rrggbb`, or absent for the terminal's default.
#[serde(default)]
fg: Option<String>,
#[serde(default)]
bg: Option<String>,
#[serde(default)]
bold: bool,
}
#[derive(serde::Deserialize)]
struct Grid {
width: u16,
height: u16,
/// Row-major, `width * height` of them.
cells: Vec<GridCell>,
}
/// Reads a grid from stdin into the buffer the exporter already knows how to draw.
pub(super) fn buffer_from_grid() -> Buffer {
let grid: Grid = serde_json::from_reader(std::io::stdin().lock())
.unwrap_or_else(|error| fail(&format!("could not read the grid: {error}")));
let expected = usize::from(grid.width) * usize::from(grid.height);
if grid.cells.len() != expected {
fail(&format!(
"grid says {}x{} but carries {} cells",
grid.width,
grid.height,
grid.cells.len()
));
}
let area = ratatui::layout::Rect::new(0, 0, grid.width, grid.height);
let mut buffer = Buffer::empty(area);
for (index, cell) in grid.cells.iter().enumerate() {
let (x, y) = (index % usize::from(grid.width), index / usize::from(grid.width));
let target = &mut buffer[(x as u16, y as u16)];
// A wide glyph's trailing cell carries no character of its own; leaving it as a space keeps
// the columns after it where the emulator put them.
target.set_symbol(if cell.c.is_empty() { " " } else { &cell.c });
if let Some(color) = cell.fg.as_deref().and_then(parse_hex) {
target.set_fg(color);
}
if let Some(color) = cell.bg.as_deref().and_then(parse_hex) {
target.set_bg(color);
}
if cell.bold {
target.set_style(ratatui::style::Style::default().add_modifier(Modifier::BOLD));
}
}
buffer
}
/// `#rrggbb` to a ratatui color.
pub(super) fn parse_hex(value: &str) -> Option<Color> {
let digits = value.strip_prefix('#')?;
// ASCII first, so the channel slices below always land on character boundaries
if digits.len() != 6 || !digits.is_ascii() {
return None;
}
let channel = |at: usize| u8::from_str_radix(&digits[at..at + 2], 16).ok();
Some(Color::Rgb(channel(0)?, channel(2)?, channel(4)?))
}

View File

@@ -0,0 +1,149 @@
//! fixture_svg — a production render, exported as vector.
//!
//! The site needs pictures of Luxe, and a screenshot is the worst way to get one: it is a raster at
//! somebody's DPI, its text cannot be selected or searched, it weighs ten times what it should, and
//! it puts a terminal and a font in the pipeline where neither belongs. The render is already a
//! grid of glyphs and colors, so it can be drawn directly.
//!
//! A scenario from [`luxe_tui::fixture`] renders through the **production view path** into a
//! `TestBackend` buffer, and each cell becomes geometry or text:
//!
//! - **Block Elements** (full, halves, eighths, quadrants, shades) become rectangles. These are
//! defined as exact cell fractions, which is precisely what a font renderer approximates and a
//! rectangle does not.
//! - **Box drawing** (light lines and rounded corners) becomes stroked paths, for the same reason
//! plus one more: a fallback font leaves gaps between border segments, and a panel drawn with
//! gaps in it is worse than no panel.
//! - **Powerline Extra triangles** become triangles — the range terminals disagree about most.
//! - **Everything else** stays real text, one `<text>` per row, so a reader can select a command
//! out of the picture and run it.
//!
//! Every text row carries `textLength`, so the grid holds under whatever monospace font the reader
//! actually has rather than only under ours.
//!
//! ```sh
//! cargo run -p luxe-tui --example fixture_svg -- --theme luxe --scenario chat-tools > shot.svg
//! cargo run -p luxe-tui --example fixture_svg -- --census # what is still drawn as text
//! ```
mod capture;
mod color;
mod geometry;
mod grid;
mod palette;
mod svg;
use capture::render;
use grid::buffer_from_grid;
use luxe_tui::fixture::FixtureScenario;
use palette::palette_svg;
use svg::{svg, text_census};
/// Cell size in user units, at the 1:2.2 aspect a terminal draws — the same grid the wordmark's
/// vector twin uses, so a logotype exported here lines up with the standalone one.
const CELL_W: f64 = 10.0;
const CELL_H: f64 = 22.0;
/// The face's advance width, as a fraction of its type size.
///
/// This has to be the *real* figure for the first font in the stack below, because every row is
/// stretched to `cols × CELL_W` by `textLength`: guess low and every glyph is squeezed, guess high
/// and they are pulled apart, in both cases silently and across every capture at once. JetBrains
/// Mono advances 0.6em. `scripts/site-smoke.mjs` measures what the website's own face actually
/// advances and fails on the difference.
const ADVANCE: f64 = 0.6;
/// Type size that fills the cell at [`ADVANCE`]. `textLength` corrects the rest.
const FONT_SIZE: f64 = CELL_W / ADVANCE;
/// The face's ascender, as a fraction of its type size.
///
/// JetBrains Mono's line box is 1.02em up and 0.30em down, 1.32em in all, which at [`FONT_SIZE`]
/// is exactly [`CELL_H`] — so the baseline sits where a terminal drawing this face puts it.
const ASCENT: f64 = 1.02;
/// Baseline as a fraction of cell height.
const BASELINE: f64 = ASCENT * FONT_SIZE / CELL_H;
/// Stroke width of a light box-drawing line.
const HAIRLINE: f64 = CELL_W / 8.0;
fn main() {
let mut theme = "luxe".to_string();
let mut scenario = "chat-tools".to_string();
let (mut cols, mut rows) = (150_u16, 40_u16);
let mut census = false;
let mut grid = false;
let mut palette: Option<Vec<String>> = None;
let mut palette_json: Option<String> = None;
let mut overlay: Option<String> = None;
let mut args = std::env::args().skip(1);
while let Some(flag) = args.next() {
let mut value = || args.next().unwrap_or_else(|| fail(&format!("{flag} needs a value")));
match flag.as_str() {
"--theme" => theme = value(),
"--scenario" => scenario = value(),
"--cols" => cols = value().parse().unwrap_or_else(|_| fail("--cols wants a number")),
"--rows" => rows = value().parse().unwrap_or_else(|_| fail("--rows wants a number")),
"--census" => census = true,
"--grid" => grid = true,
"--palette" => {
palette = Some(value().split(',').map(str::trim).map(str::to_owned).collect());
}
"--palette-json" => palette_json = Some(value()),
"--overlay" => overlay = Some(value()),
"--help" | "-h" => {
println!("{USAGE}");
return;
}
other => fail(&format!("unknown flag {other}\n\n{USAGE}")),
}
}
// The braille sweep, as the live app draws it wherever a font can: the site's webfonts carry all
// ten frames, and a still of a running card in the four-corner fallback reads as broken
luxe_tui::glyphs::set_braille(true);
// A screen somebody else emulated, drawn by the same hand as a fixture.
//
// `scripts/cast-still.py` replays a recording with a real terminal emulator and sends the
// resulting grid here rather than writing its own SVG. Box-drawing and block characters are
// *geometry* in this exporter, not glyphs — which is the only way a vertical rule tiles down a
// column instead of breaking into dashes at every row boundary — and a second implementation
// of that in another language would drift from this one within a release.
if grid {
print!("{}", svg(&buffer_from_grid()));
return;
}
let scenario: FixtureScenario = scenario.parse().unwrap_or_else(|error: String| fail(&error));
if let Some(themes) = palette {
let Some(json) = palette_json else { fail("--palette needs --palette-json FILE") };
let (document, values) = palette_svg(&themes, scenario, cols, rows);
let written = serde_json::to_string_pretty(&values).expect("a palette is plain strings");
std::fs::write(&json, written + "\n")
.unwrap_or_else(|error| fail(&format!("could not write {json}: {error}")));
print!("{document}");
return;
}
let buffer = render(&theme, scenario, overlay.as_deref(), cols, rows).0;
if census {
for (glyph, count) in text_census(&buffer) {
println!("U+{:04X} {glyph} {count}", glyph as u32);
}
return;
}
print!("{}", svg(&buffer));
}
const USAGE: &str = "usage: fixture_svg [--theme ID] [--scenario NAME] [--cols N] [--rows N] \
[--overlay STATE] [--census] [--grid] [--palette ID,ID,... --palette-json FILE]";
fn fail(message: &str) -> ! {
eprintln!("{message}");
std::process::exit(2)
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,122 @@
//! Palette pictures — one scenario drawn once for every theme, its colors as CSS variables.
use super::capture::render;
use super::color::hex;
use super::fail;
use super::svg::{canvas_color, svg};
use luxe_tui::fixture::FixtureScenario;
use ratatui::buffer::Buffer;
use ratatui::style::Color;
use std::collections::BTreeMap;
use std::fmt::Write as _;
/// The first byte of a placeholder color. Only placeholders are ever in the buffer that gets
/// drawn, so nothing real can be mistaken for one.
const SENTINEL: u8 = 0x0f;
/// The scenario drawn once for every theme in `themes`: each color a `var(--pN, first)`, plus what
/// every `N` is in every theme.
///
/// Twelve themes lay the same cells out identically, so what differs between their pictures is
/// only which color goes where. Each cell's colors are keyed on what they are across *all* the
/// themes at once, and the key becomes a placeholder color in one buffer that the ordinary
/// exporter then draws. That is also what keeps the background runs right: two neighbors merge into
/// one rectangle only when they match in every theme, where merging per theme and comparing the
/// results would have given different shapes to the same picture.
pub(super) fn palette_svg(
themes: &[String],
scenario: FixtureScenario,
cols: u16,
rows: u16,
) -> (String, BTreeMap<String, BTreeMap<String, String>>) {
if themes.is_empty() {
fail("--palette wants at least one theme");
}
let drawn: Vec<(Buffer, String)> =
themes.iter().map(|theme| render(theme, scenario, None, cols, rows)).collect();
let (first, _) = &drawn[0];
for (theme, (buffer, _)) in themes.iter().zip(&drawn).skip(1) {
let same = first.content().iter().zip(buffer.content()).all(|(left, right)| {
left.symbol() == right.symbol() && left.modifier == right.modifier
});
if !same {
fail(&format!("{theme} lays {scenario:?} out differently, so no one picture fits it"));
}
}
let canvases: Vec<String> = drawn.iter().map(|(buffer, _)| canvas_color(buffer)).collect();
// One key per distinct "this color in every theme", numbered in the order the cells meet them
let mut keys: BTreeMap<Vec<String>, u16> = BTreeMap::new();
let mut order: Vec<Vec<String>> = Vec::new();
let mut key_of = |key: Vec<String>| -> u16 {
if let Some(index) = keys.get(&key) {
return *index;
}
let index = u16::try_from(order.len()).unwrap_or_else(|_| fail("too many colors"));
keys.insert(key.clone(), index);
order.push(key);
index
};
let placeholder = |index: u16| {
let [high, low] = index.to_be_bytes();
Color::Rgb(SENTINEL, high, low)
};
let mut merged = first.clone();
for (position, cell) in merged.content.iter_mut().enumerate() {
let fg: Vec<String> = drawn
.iter()
.map(|(buffer, ink)| hex(buffer.content[position].fg).unwrap_or_else(|| ink.clone()))
.collect();
let bg: Vec<String> = drawn
.iter()
.zip(&canvases)
.map(|((buffer, _), canvas)| {
hex(buffer.content[position].bg).unwrap_or_else(|| canvas.clone())
})
.collect();
cell.set_fg(placeholder(key_of(fg)));
cell.set_bg(placeholder(key_of(bg)));
}
let first_values: Vec<&str> = order.iter().map(|key| key[0].as_str()).collect();
let document = with_variables(&svg(&merged), &first_values);
let mut values = BTreeMap::new();
for (column, theme) in themes.iter().enumerate() {
let table =
order.iter().enumerate().map(|(index, key)| (format!("p{index}"), key[column].clone()));
values.insert(theme.clone(), table.collect());
}
(document, values)
}
/// Every placeholder in an attribute swapped for `var(--pN, #first)`.
///
/// Only attribute values are touched (`="#0f…"`), because a picture of a terminal can have a hex
/// color in its *text*, and that one is somebody's code.
pub(super) fn with_variables(document: &str, first: &[&str]) -> String {
let marker = format!("=\"#{SENTINEL:02x}");
let mut out = String::with_capacity(document.len() + document.len() / 4);
let mut rest = document;
while let Some(at) = rest.find(&marker) {
let (before, tail) = rest.split_at(at);
out.push_str(before);
let digits = &tail[marker.len()..];
let index = digits
.get(..4)
.filter(|_| digits.as_bytes().get(4) == Some(&b'"'))
.and_then(|hex| usize::from_str_radix(hex, 16).ok());
match index {
Some(index) => {
let fallback = first.get(index).copied().unwrap_or("#000000");
let _ = write!(out, "=\"var(--p{index}, {fallback})\"");
rest = &digits[5..];
}
None => {
out.push_str(&marker);
rest = digits;
}
}
}
out.push_str(rest);
out
}

View File

@@ -0,0 +1,156 @@
//! The SVG document — its backgrounds, the drawn glyphs, and one selectable text row per line.
use super::color::{attributes, hex};
use super::geometry::{geometry, is_drawn, rect};
use super::{BASELINE, CELL_H, CELL_W, FONT_SIZE};
use ratatui::buffer::Buffer;
use std::collections::BTreeMap;
use std::fmt::Write as _;
/// The whole document.
pub(super) fn svg(buffer: &Buffer) -> String {
let (cols, rows) = (buffer.area.width, buffer.area.height);
let (width, height) = (f64::from(cols) * CELL_W, f64::from(rows) * CELL_H);
let canvas = canvas_color(buffer);
let mut out = String::new();
let _ = writeln!(
out,
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {width:.0} {height:.0}\" \
width=\"{width:.0}\" height=\"{height:.0}\" font-family=\"'JetBrainsMono Nerd Font Mono', \
'AdwaitaMono Nerd Font Mono', 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, \
Consolas, monospace\" \
font-size=\"{FONT_SIZE:.2}\">"
);
let _ =
writeln!(out, " <rect width=\"{width:.0}\" height=\"{height:.0}\" fill=\"{canvas}\"/>");
out.push_str(" <g shape-rendering=\"crispEdges\">\n");
out.push_str(&backgrounds(buffer, &canvas));
out.push_str(&geometry(buffer));
out.push_str(" </g>\n");
out.push_str(&text(buffer));
out.push_str("</svg>\n");
out
}
/// The color behind everything, taken from the cell the app paints most of.
///
/// Reading it off the render rather than the theme keeps the export honest about surfaces that
/// bring their own canvas, and gives `Color::Reset` something real to resolve to.
pub(super) fn canvas_color(buffer: &Buffer) -> String {
let mut tally: BTreeMap<String, usize> = BTreeMap::new();
for cell in buffer.content() {
if let Some(hex) = hex(cell.bg) {
*tally.entry(hex).or_default() += 1;
}
}
tally.into_iter().max_by_key(|(_, count)| *count).map(|(hex, _)| hex).unwrap_or_else(|| {
// Nothing painted a background, so the terminal's own shows through. Dark is the safer
// guess: it is what a terminal defaults to, and light text on it stays readable.
"#000000".to_string()
})
}
/// Merged background rectangles, skipping whatever already matches the canvas.
fn backgrounds(buffer: &Buffer, canvas: &str) -> String {
let mut out = String::new();
for row in 0..buffer.area.height {
let mut run: Option<(u16, u16, String)> = None;
let flush = |run: &mut Option<(u16, u16, String)>, out: &mut String| {
if let Some((start, end, fill)) = run.take() {
let _ = writeln!(out, " {}", rect(start, row, end - start + 1, 1, &fill));
}
};
for column in 0..buffer.area.width {
let fill = hex(buffer[(column, row)].bg).filter(|fill| fill != canvas);
match (&mut run, fill) {
(Some((_, end, current)), Some(fill)) if *current == fill && *end + 1 == column => {
*end = column;
}
(_, Some(fill)) => {
flush(&mut run, &mut out);
run = Some((column, column, fill));
}
(_, None) => flush(&mut run, &mut out),
}
}
flush(&mut run, &mut out);
}
out
}
/// One `<text>` per row, so selecting a line of the picture yields the line.
pub(super) fn text(buffer: &Buffer) -> String {
let width = f64::from(buffer.area.width) * CELL_W;
let mut out = String::new();
for row in 0..buffer.area.height {
let mut spans = String::new();
let mut pending = String::new();
let mut pending_style: Option<(String, String)> = None;
for column in 0..buffer.area.width {
let cell = &buffer[(column, row)];
let symbol = cell.symbol();
let glyph = symbol.chars().next().unwrap_or(' ');
// A drawn glyph leaves a space behind so the columns after it still line up, and so the
// row does not paint the same mark twice. The whole symbol otherwise: an accent or a
// joined emoji is several scalars in one cell, and an empty cell still takes a column.
let typeset = if is_drawn(glyph) || symbol.is_empty() { " " } else { symbol };
let style = (hex(cell.fg).unwrap_or_default(), attributes(cell.modifier));
if pending_style.as_ref() != Some(&style) {
flush_span(&mut spans, &mut pending, &pending_style);
pending_style = Some(style);
}
pending.push_str(typeset);
}
flush_span(&mut spans, &mut pending, &pending_style);
if spans.trim().is_empty() {
continue;
}
let baseline = (f64::from(row) + BASELINE) * CELL_H;
let _ = writeln!(
out,
" <text x=\"0\" y=\"{baseline:.1}\" textLength=\"{width:.0}\" \
lengthAdjust=\"spacingAndGlyphs\" xml:space=\"preserve\">{spans}</text>"
);
}
out
}
fn flush_span(spans: &mut String, pending: &mut String, style: &Option<(String, String)>) {
if pending.is_empty() {
return;
}
let text = std::mem::take(pending);
// A run of pure whitespace still has to occupy its columns, but needs no fill or attributes.
if text.trim().is_empty() {
let _ = write!(spans, "<tspan>{}</tspan>", escape(&text));
return;
}
let (fill, attrs) = style.clone().unwrap_or_default();
let fill = if fill.is_empty() { String::new() } else { format!(" fill=\"{fill}\"") };
let _ = write!(spans, "<tspan{fill}{attrs}>{}</tspan>", escape(&text));
}
/// Glyphs still reaching the font, most common first — the input to deciding what to draw next.
pub(super) fn text_census(buffer: &Buffer) -> Vec<(char, usize)> {
let mut tally: BTreeMap<char, usize> = BTreeMap::new();
for cell in buffer.content() {
let glyph = cell.symbol().chars().next().unwrap_or(' ');
if glyph != ' ' && !glyph.is_ascii() && !is_drawn(glyph) {
*tally.entry(glyph).or_default() += 1;
}
}
let mut census: Vec<(char, usize)> = tally.into_iter().collect();
census.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
census
}
fn escape(text: &str) -> String {
text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}

View File

@@ -0,0 +1,180 @@
use super::geometry::{block, is_drawn};
use super::grid::parse_hex;
use super::palette::with_variables;
use super::svg::text;
use super::*;
use luxe_tui::fixture::FixtureScenario;
use ratatui::buffer::Buffer;
use ratatui::style::Color;
fn shot() -> Buffer {
render("luxe", FixtureScenario::ChatTools, None, 120, 30).0
}
/// One palette picture stands in for every theme: no placeholder survives into the document,
/// the fallbacks are the first theme's own colors, and every theme gets a value for every
/// variable the picture uses.
#[test]
fn a_palette_picture_names_every_color_it_draws() {
let themes = ["luxe".to_string(), "nord".to_string()];
let (document, values) = palette_svg(&themes, FixtureScenario::ChatTools, 120, 30);
assert!(!document.contains("=\"#0f"), "a placeholder leaked into the picture");
assert!(document.contains("fill=\"var(--p0, #"), "{}", &document[..400]);
let used = document.matches("var(--p").count();
assert!(used > 20, "the picture is drawn in variables: {used}");
let (luxe, nord) = (&values["luxe"], &values["nord"]);
assert_eq!(luxe.len(), nord.len());
assert!(luxe.iter().any(|(key, value)| nord[key] != *value), "the themes differ");
for (key, value) in luxe {
assert!(document.contains(&format!("var(--{key}, {value})")), "{key} unused");
}
}
/// Only attributes are rewritten: a hex color in the terminal's *text* is somebody's code.
#[test]
fn a_placeholder_in_the_text_is_left_alone() {
let document = "<rect fill=\"#0f0001\"/><text>#0f0001</text>";
let out = with_variables(document, &["#aaaaaa", "#bbbbbb"]);
assert_eq!(out, "<rect fill=\"var(--p1, #bbbbbb)\"/><text>#0f0001</text>");
}
/// The export is a real render, not a blank grid — the cheapest way to catch a fixture that
/// stopped seeding itself.
#[test]
fn the_export_carries_the_render() {
let svg = svg(&shot());
assert!(svg.starts_with("<svg xmlns="));
assert!(svg.trim_end().ends_with("</svg>"));
assert!(svg.contains("<text "), "no typeset rows reached the document");
assert!(svg.matches("<text ").count() > 5, "suspiciously few rows");
}
/// Text stays text. The whole reason not to ship a PNG is that a reader can select a command
/// out of the picture, so a run of real characters has to survive the trip.
#[test]
fn commands_in_the_render_are_still_selectable_text() {
let svg = svg(&shot());
assert!(svg.contains("cargo test"), "a command the fixture renders went missing");
assert!(svg.contains("xml:space=\"preserve\""), "leading columns would collapse");
assert!(svg.contains("lengthAdjust=\"spacingAndGlyphs\""), "the grid needs pinning");
}
/// Every glyph defined as an exact cell fraction is drawn rather than typeset. These are the
/// ones a font approximates, which is what makes a terminal picture look wrong.
#[test]
fn cell_fraction_glyphs_are_drawn_not_typeset() {
for glyph in [
'\u{2588}', '\u{2580}', '\u{2584}', '\u{258c}', '\u{2590}', '\u{2581}', '\u{2587}',
'\u{258f}', '\u{2589}', '\u{2594}', '\u{2595}', '\u{2596}', '\u{259f}', '\u{2591}',
'\u{2593}',
] {
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
}
for glyph in ['\u{2500}', '\u{2502}', '\u{250c}', '\u{253c}', '\u{256d}', '\u{2570}'] {
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
}
for glyph in ['\u{e0b8}', '\u{e0ba}', '\u{e0bc}', '\u{e0be}'] {
assert!(is_drawn(glyph), "U+{:04X} should be geometry", glyph as u32);
}
// Letters and the geometric shapes Luxe uses as marks stay text: any font has them, and
// they carry meaning that should remain selectable.
for glyph in ['a', '\u{276f}', '\u{25cf}', '\u{25c6}'] {
assert!(!is_drawn(glyph), "U+{:04X} should be typeset", glyph as u32);
}
}
/// A drawn glyph leaves a space in its row, so the columns after it still land on the grid and
/// the mark is not painted twice.
#[test]
fn a_drawn_glyph_holds_its_column_in_the_text_layer() {
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 3, 1));
buffer[(0, 0)].set_symbol("\u{2588}");
buffer[(1, 0)].set_symbol("A");
buffer[(2, 0)].set_symbol("B");
let text = text(&buffer);
assert!(text.contains("AB"), "typeset glyphs survive: {text}");
assert!(!text.contains('\u{2588}'), "the block is drawn, not typeset: {text}");
assert!(text.contains(' '), "the block still occupies its column: {text}");
}
/// Quadrant masks are transcribed correctly. Getting one wrong is invisible in review and
/// obvious on the page, so it is checked against the halves they must add up to.
#[test]
fn quadrant_masks_agree_with_the_halves_they_compose() {
let area = |glyph: char| {
block(glyph).expect("a block").0.iter().map(|(_, _, w, h)| w * h).sum::<f64>()
};
assert_eq!(area('\u{2596}'), 0.25, "one quadrant");
assert_eq!(area('\u{259f}'), 0.75, "three quadrants");
// ▘ upper-left plus ▗ lower-right is the same ink as ▚.
assert_eq!(area('\u{2598}') + area('\u{2597}'), area('\u{259a}'));
// Every eighth block covers the fraction it is named for.
assert!((area('\u{2581}') - 0.125).abs() < f64::EPSILON, "one lower eighth");
assert!((area('\u{2587}') - 0.875).abs() < f64::EPSILON, "seven lower eighths");
assert!((area('\u{258f}') - 0.125).abs() < f64::EPSILON, "one left eighth");
assert!((area('\u{2589}') - 0.875).abs() < f64::EPSILON, "seven left eighths");
}
/// Markup that would break a parser is escaped. A diff of HTML is an ordinary thing to render.
#[test]
fn markup_in_the_render_is_escaped() {
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 5, 1));
for (index, glyph) in "<a&b".chars().enumerate() {
buffer[(index as u16, 0)].set_symbol(&glyph.to_string());
}
let text = text(&buffer);
assert!(text.contains("&lt;a&amp;b"), "unescaped markup would break the document: {text}");
}
/// A cell's whole symbol is typeset, and a wide glyph's trailing cell keeps its column, so the
/// marker after each lands where the terminal put it.
///
/// The break this catches: the text layer kept only a cell's first scalar, so a decomposed
/// accent lost its mark and a joined emoji lost everything after its first person.
#[test]
fn a_cell_keeps_its_whole_symbol_in_the_text_layer() {
let mut buffer = Buffer::empty(ratatui::layout::Rect::new(0, 0, 8, 1));
for (column, symbol) in
["e\u{301}", "X", "\u{1f469}\u{200d}\u{1f4bb}", " ", "Y", "\u{4e2d}", "", "Z"]
.into_iter()
.enumerate()
{
buffer[(column as u16, 0)].set_symbol(symbol);
}
let text = text(&buffer);
assert!(
text.contains("e\u{301}X\u{1f469}\u{200d}\u{1f4bb} Y\u{4e2d} Z"),
"every scalar of every cell, one column each: {text}"
);
}
/// A color that is not ASCII hex is refused, not sliced.
///
/// The break this catches: six bytes passed the length check and the channel slices cut a
/// multi-byte character in half, which panics on a grid handed in on stdin.
#[test]
fn non_ascii_grid_colors_are_rejected_without_panicking() {
// six bytes each, with a channel boundary inside a three-byte character
assert_eq!(parse_hex("#a\u{20ac}bc"), None);
assert_eq!(parse_hex("#\u{e9}\u{20ac}a"), None);
assert_eq!(parse_hex("#0a0B0c"), Some(Color::Rgb(0x0a, 0x0b, 0x0c)));
}
/// Each quadrant sits where its name says, not merely with the right amount of ink.
#[test]
fn quadrants_sit_in_their_own_corners() {
let rects = |glyph: char| block(glyph).expect("a block").0;
let (upper_left, upper_right) = ((0.0, 0.0, 0.5, 0.5), (0.5, 0.0, 0.5, 0.5));
let (lower_left, lower_right) = ((0.0, 0.5, 0.5, 0.5), (0.5, 0.5, 0.5, 0.5));
assert_eq!(rects('\u{2598}'), vec![upper_left]);
assert_eq!(rects('\u{259d}'), vec![upper_right]);
assert_eq!(rects('\u{2596}'), vec![lower_left]);
assert_eq!(rects('\u{2597}'), vec![lower_right]);
assert_eq!(rects('\u{259a}'), vec![upper_left, lower_right]);
assert_eq!(rects('\u{259e}'), vec![upper_right, lower_left]);
assert_eq!(rects('\u{2599}'), vec![upper_left, lower_left, lower_right]);
assert_eq!(rects('\u{259b}'), vec![upper_left, upper_right, lower_left]);
assert_eq!(rects('\u{259c}'), vec![upper_left, upper_right, lower_right]);
assert_eq!(rects('\u{259f}'), vec![upper_right, lower_left, lower_right]);
}

View File

@@ -0,0 +1,52 @@
//! Visual demo for the permission-ask prompt (dev-only; not shipped).
//!
//! Renders the yellow permission picker above a mock composer so the styling/layout can be
//! eyeballed or screenshotted. Run: `cargo run -p luxe-tui --example permission_prompt_demo`.
use std::cell::RefCell;
use std::io;
use crossterm::{execute, terminal};
use ratatui::{backend::CrosstermBackend, layout::Rect, widgets::Paragraph, Terminal};
use luxe_core::permission::PermissionRequestId;
use luxe_tui::mouse::HitRegions;
use luxe_tui::permission_prompt::{render_permission_prompt, PermissionPromptState};
use luxe_tui::theme::styles::ThemeStyles;
fn main() -> io::Result<()> {
let registry = luxe_core::theme::ThemeRegistry::new();
let resolved = registry.resolve("dark").expect("dark theme");
let theme = ThemeStyles::from_resolved(&resolved, "dark");
let state = PermissionPromptState::new(
PermissionRequestId::new(),
"bash".to_string(),
"Run: rm -rf /etc".to_string(),
vec!["bash rm *".to_string()],
);
let hit = RefCell::new(HitRegions::default());
terminal::enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, terminal::EnterAlternateScreen)?;
let mut term = Terminal::new(CrosstermBackend::new(stdout))?;
term.draw(|f| {
let size = f.area();
f.render_widget(ratatui::widgets::Block::default().style(theme.background), size);
// Mock composer (rounded) at the bottom, matching the real chat layout's inset.
let composer = Rect::new(1, size.height.saturating_sub(4), size.width.saturating_sub(2), 3);
f.render_widget(
Paragraph::new(" ask luxe to do something…")
.style(theme.muted)
.block(luxe_tui::widgets::panel_block().border_style(theme.border_accent)),
composer,
);
let region = Rect::new(composer.x, 1, composer.width, composer.y.saturating_sub(1));
render_permission_prompt(f, region, composer.y, &state, &theme, &hit);
})?;
// Hold the frame so a screenshot can capture it, then restore the terminal.
std::thread::sleep(std::time::Duration::from_secs(6));
terminal::disable_raw_mode()?;
execute!(term.backend_mut(), terminal::LeaveAlternateScreen)?;
Ok(())
}

View File

@@ -0,0 +1,266 @@
//! What one frame costs, on every surface that draws one.
//!
//! Two numbers per surface: the wall clock, and the **allocation count**. The second is the one
//! that travels — it is identical on any machine, so a claim made here can be checked in review,
//! and a frame whose allocations scale with the transcript is a frame that re-derives it.
//!
//! Run: `cargo run -p luxe-tui --release --example render_perf`
use luxe_core::config::Config;
use luxe_core::keymap::KeyMap;
use luxe_tui::app::{App, ConvoBlock, Msg};
use luxe_tui::fixture::{seeded_app, FixtureScenario};
use luxe_tui::view::render;
use ratatui::{backend::TestBackend, Terminal};
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
// === Allocation counting ===
static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
static ALLOCATED_BYTES: AtomicUsize = AtomicUsize::new(0);
/// Passes everything through to the system allocator and counts what went by.
struct Counting;
// SAFETY: every method forwards to `System` with its caller's own arguments, so it upholds exactly
// the contract `System` does; the counting beside it never allocates and cannot panic.
#[allow(unsafe_code)]
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
ALLOCATED_BYTES.fetch_add(layout.size(), Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
ALLOCATED_BYTES.fetch_add(new_size.saturating_sub(layout.size()), Ordering::Relaxed);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
fn counters() -> (usize, usize) {
(ALLOCATIONS.load(Ordering::Relaxed), ALLOCATED_BYTES.load(Ordering::Relaxed))
}
// === Fixtures ===
const WIDTH: u16 = 140;
const HEIGHT: u16 = 44;
fn prose(index: usize) -> String {
format!(
"Paragraph {index}: the streaming path re-lays out the whole transcript every frame, which \
means markdown parsing, syntax highlighting and wrapping all happen again. This is a \
realistic length for a model answer with `inline code`, **bold**, and _emphasis_ mixed \
in, spanning several wrapped rows at a typical terminal width.\n\nA second paragraph so \
the block is not trivially short, with a list:\n\n- first item\n- second item\n- third \
item\n"
)
}
fn code(index: usize) -> String {
format!(
"Here is a snippet:\n\n```rust\nfn thing_{index}(input: &str) -> usize {{\n let mut \
total = 0usize;\n for (index, ch) in input.char_indices() {{\n if \
ch.is_alphanumeric() {{\n total += index;\n }}\n }}\n total\n}}\n\
```\n\nAnd some trailing prose after the fence.\n"
)
}
fn chat_app(turns: usize, with_code: bool) -> App {
let (tx, _rx) = tokio::sync::mpsc::channel(64);
let mut app = App::new_fixture(tx, KeyMap::defaults(), Config::default());
app.headless = true;
app.update(Msg::TerminalResized { width: WIDTH, height: HEIGHT });
for index in 0..turns {
app.push_convo(ConvoBlock::User {
text: format!("question {index}"),
attached: Vec::new(),
chips: Vec::new(),
});
app.push_convo(ConvoBlock::Thinking {
text: format!(
"Reasoning {index}: consider the options, weigh them, then pick one. This is the \
sort of length a reasoning block reaches before the answer starts streaming."
),
expanded: true,
});
if with_code && index % 3 == 0 {
app.push_convo(ConvoBlock::Assistant(code(index)));
} else {
app.push_convo(ConvoBlock::Assistant(prose(index)));
}
}
app
}
// === Measurement ===
struct Reading {
mean_ms: f64,
p50_ms: f64,
p95_ms: f64,
max_ms: f64,
allocations: usize,
kib: f64,
}
/// Draws `frames` steady-state frames and reports what one of them cost.
///
/// The first draw is thrown away: it warms the syntax set, the highlight memo and any layout cache,
/// and pricing a cold start as if it were a repaint is how a cache gets called useless.
fn measure(app: &mut App, width: u16, height: u16, frames: usize) -> Reading {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).expect("a test terminal");
for _ in 0..2 {
terminal.draw(|frame| render(frame, app)).expect("a warm-up frame");
}
let (allocations_before, bytes_before) = counters();
let mut samples = Vec::with_capacity(frames);
for _ in 0..frames {
let start = Instant::now();
terminal.draw(|frame| render(frame, app)).expect("a frame");
samples.push(start.elapsed().as_secs_f64() * 1000.0);
}
let (allocations_after, bytes_after) = counters();
samples.sort_by(|left, right| left.partial_cmp(right).expect("no NaN timings"));
Reading {
mean_ms: samples.iter().sum::<f64>() / samples.len() as f64,
p50_ms: samples[samples.len() / 2],
p95_ms: samples[(samples.len() * 95 / 100).min(samples.len() - 1)],
max_ms: samples[samples.len() - 1],
allocations: (allocations_after - allocations_before) / frames,
kib: (bytes_after - bytes_before) as f64 / frames as f64 / 1024.0,
}
}
fn report(label: &str, reading: &Reading) {
println!(
"{label:<38} mean {:7.3} ms p50 {:7.3} p95 {:7.3} max {:7.3} allocs {:8} {:8.0} KiB",
reading.mean_ms,
reading.p50_ms,
reading.p95_ms,
reading.max_ms,
reading.allocations,
reading.kib
);
}
/// One Guided Review frame at `times` the large fixture.
///
/// The other surfaces are bounded by what they draw; a review is bounded by the change under
/// review, and the walkthrough draws one file's diff however large that is. So the question here
/// is not the absolute figure but the *shape*: anything that grows faster than the review does is
/// a scan where a lookup belongs.
fn review_at_scale(times: usize) {
use luxe_core::guided_review::ReviewLoadRequestId;
use luxe_tui::app::ViewMode;
let review = luxe_tui::fixture::fixture_guided_review_scaled(times);
let files = review.files.len();
let hunks: usize = review.files.iter().map(|file| file.hunks.len()).sum();
let Ok(mut app) = seeded_app("luxe", FixtureScenario::GuidedReviewReady) else {
return;
};
app.current_view = ViewMode::GuidedReview;
let request_id = ReviewLoadRequestId::new();
app.active_guided_review_request = Some(request_id.clone());
app.update(Msg::Engine(luxe_core::Event::GuidedReviewLoaded {
request_id,
review: Box::new(review),
}));
app.update(Msg::TerminalResized { width: 170, height: 48 });
let reading = measure(&mut app, 170, 48, 40);
report(&format!("{times}x large review ({files} files, {hunks} hunks)"), &reading);
}
fn scenario(label: &str, which: FixtureScenario, width: u16, height: u16) {
let Ok(mut app) = seeded_app("luxe", which) else {
println!("{label:<38} (fixture unavailable)");
return;
};
app.update(Msg::TerminalResized { width, height });
let reading = measure(&mut app, width, height, 120);
report(label, &reading);
}
fn main() {
println!("=== chat transcript, idle (the keystroke frame) ===");
for turns in [1usize, 5, 20, 50, 150, 400] {
let mut app = chat_app(turns, true);
let reading = measure(&mut app, WIDTH, HEIGHT, if turns > 150 { 40 } else { 200 });
report(&format!("{turns} turns ({} items)", turns * 3), &reading);
}
println!();
println!("=== chat transcript, scrolled off the bottom ===");
for turns in [50usize, 150] {
let mut app = chat_app(turns, true);
app.scroll_state.up_by(40);
let reading = measure(&mut app, WIDTH, HEIGHT, 120);
report(&format!("{turns} turns, scrolled"), &reading);
}
println!();
println!("=== composing into the prompt ===");
for characters in [0usize, 80, 400, 2000] {
let mut app = chat_app(20, true);
for _ in 0..characters {
app.editor.insert_text("x");
}
let reading = measure(&mut app, WIDTH, HEIGHT, 120);
report(&format!("{characters}-character draft"), &reading);
}
println!();
println!("=== other surfaces ===");
scenario("dashboard", FixtureScenario::Dashboard, WIDTH, HEIGHT);
scenario("guided review (standard)", FixtureScenario::GuidedReviewReady, 170, 48);
scenario("guided review (large corpus)", FixtureScenario::GuidedReviewLarge, 170, 48);
scenario("guided review (split)", FixtureScenario::GuidedReviewSplit, 170, 48);
scenario("guided review (no guide)", FixtureScenario::GuidedReviewGuideHidden, 170, 48);
scenario("changes pane (wide)", FixtureScenario::ChangesWide, 170, 48);
scenario("dock (side by side)", FixtureScenario::DockWide, 170, 48);
scenario("dock (overlay)", FixtureScenario::DockOverlay, 120, 40);
scenario("chat + tool cards", FixtureScenario::ChatTools, WIDTH, HEIGHT);
scenario("chat + card bodies", FixtureScenario::ChatCardBodies, WIDTH, HEIGHT);
scenario("chat streaming (mid-reveal)", FixtureScenario::ChatStreaming, WIDTH, HEIGHT);
println!();
println!("=== guided review, against the size of the review ===");
for times in [1usize, 2, 4, 8, 16] {
review_at_scale(times);
}
println!();
println!("=== markdown + highlight isolation ===");
let styles = {
let registry = luxe_core::theme::ThemeRegistry::new();
let resolved = registry.resolve("dark").expect("the dark theme");
luxe_tui::theme::styles::ThemeStyles::from_resolved(&resolved, "dark")
};
for (label, text) in [("prose block", prose(1)), ("code block", code(1))] {
let start = Instant::now();
let (allocations, _) = counters();
for _ in 0..1000 {
std::hint::black_box(luxe_tui::markdown::render_markdown(&text, &styles));
}
let per_call = (counters().0 - allocations) / 1000;
println!(
"render_markdown({label:<11}) x1000: {:?} ({per_call} allocs/call)",
start.elapsed()
);
}
}

View File

@@ -0,0 +1,152 @@
//! shiki_theme — luxe's palette as a syntax theme for the website's code blocks.
//!
//! The docs describe a terminal program; highlighting their code in somebody else's palette is a
//! small lie about what Luxe looks like. This writes a TextMate theme from the same JSON the TUI
//! loads, so the code on the page is colored by the product's own tokens.
//!
//! It is also the palette's hardest test. A theme with six accents can hide a weak one behind a
//! statusline; a syntax theme puts all of them on screen at once, adjacent, in small type.
//!
//! The mapping is the TUI's own, [`luxe_tui::highlight::SCOPES`], so a code block on the page and
//! one in the terminal are colored the same way; why each role takes its token is said there.
//!
//! ```sh
//! cargo run -p luxe-tui --example shiki_theme -- luxe > web/src/assets/generated/shiki-luxe.json
//! ```
use luxe_core::theme::{ColorValue, ThemeRegistry};
use ratatui::style::Modifier;
use std::collections::HashMap;
fn main() {
let name = std::env::args().nth(1).unwrap_or_else(|| "luxe".into());
let registry = ThemeRegistry::new();
let resolved =
registry.resolve(&name).unwrap_or_else(|| panic!("{name} is not a built-in theme"));
println!("{}", theme_json(&name, &resolved));
}
/// The TextMate document Shiki loads.
fn theme_json(name: &str, theme: &HashMap<String, ColorValue>) -> String {
let hex = |token: &str| -> String {
match theme.get(token) {
Some(ColorValue::Rgb(red, green, blue)) => format!("#{red:02x}{green:02x}{blue:02x}"),
// Every token this maps is RGB in Luxe's own themes; anything else would be a theme
// this generator was not written for, and inventing a color would hide that.
_ => panic!("{name}.{token} is not an RGB color"),
}
};
let mut rules = String::new();
for (selectors, role) in luxe_tui::highlight::SCOPES {
let (token, modifier) = role.token();
let list = selectors
.split(',')
.map(|scope| format!("\"{}\"", scope.trim()))
.collect::<Vec<_>>()
.join(", ");
let font = [(Modifier::BOLD, "bold"), (Modifier::ITALIC, "italic")]
.iter()
.filter(|(flag, _)| modifier.contains(*flag))
.map(|(_, word)| *word)
.collect::<Vec<_>>()
.join(" ");
let font = match font.is_empty() {
true => String::new(),
false => format!(", \"fontStyle\": \"{font}\""),
};
rules.push_str(&format!(
" {{ \"scope\": [{list}], \"settings\": {{ \"foreground\": \"{}\"{font} }} }},\n",
hex(token)
));
}
let rules = rules.trim_end().trim_end_matches(',');
format!(
// `settings` rather than `tokenColors`: both are accepted, but the former is the raw
// TextMate shape Shiki's own type is written against, so the config typechecks without a cast.
"{{\n \"name\": \"{name}\",\n \"type\": \"{}\",\n \"colors\": {{\n \
\"editor.background\": \"{}\",\n \"editor.foreground\": \"{}\"\n }},\n \
\"settings\": [\n{rules}\n ]\n}}",
if name.contains("light") { "light" } else { "dark" },
hex("background"),
hex("text"),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn theme(name: &str) -> HashMap<String, ColorValue> {
ThemeRegistry::new().resolve(name).expect("a built-in")
}
/// The document parses, and says which mode it is for — Shiki picks the CSS variable prefix
/// from that, so a light theme labeled dark inverts the whole page.
#[test]
fn the_theme_is_valid_json_of_the_right_mode() {
{
let (name, mode) = ("luxe", "dark");
let parsed: serde_json::Value =
serde_json::from_str(&theme_json(name, &theme(name))).expect("valid json");
assert_eq!(parsed["name"], name);
assert_eq!(parsed["type"], mode);
assert!(parsed["settings"].as_array().is_some_and(|rules| rules.len() > 5));
}
}
/// Every color on a code block clears the same floor the rest of the palette does. Syntax
/// highlighting is the one surface that puts six accents together in small type, so a token
/// that only just passes elsewhere fails here first.
#[test]
fn every_highlight_color_is_readable_on_the_code_background() {
{
let name = "luxe";
let resolved = theme(name);
let parsed: serde_json::Value =
serde_json::from_str(&theme_json(name, &resolved)).expect("valid json");
let background =
parsed["colors"]["editor.background"].as_str().expect("a background").to_string();
for rule in parsed["settings"].as_array().expect("rules") {
let color = rule["settings"]["foreground"].as_str().expect("a color");
let ratio = contrast(color, &background);
assert!(ratio >= 4.5, "{name}: {color} is {ratio:.2}:1 on {background}");
}
}
}
/// `dim` is a rule color, not a text color, and putting it on punctuation is the classic way
/// a syntax theme becomes unreadable.
#[test]
fn the_theme_never_reaches_for_dim() {
{
let name = "luxe";
let resolved = theme(name);
let ColorValue::Rgb(red, green, blue) = resolved["dim"] else { panic!("dim is rgb") };
let dim = format!("#{red:02x}{green:02x}{blue:02x}");
assert!(!theme_json(name, &resolved).contains(&dim), "{name} highlights with dim");
}
}
fn luminance(hex: &str) -> f32 {
let channel = |raw: u8| {
let value = f32::from(raw) / 255.0;
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
};
let byte = |at: usize| u8::from_str_radix(&hex[at..at + 2], 16).expect("hex");
0.2126 * channel(byte(1)) + 0.7152 * channel(byte(3)) + 0.0722 * channel(byte(5))
}
fn contrast(fore: &str, back: &str) -> f32 {
let (a, b) = (luminance(fore), luminance(back));
let (hi, lo) = if a > b { (a, b) } else { (b, a) };
(hi + 0.05) / (lo + 0.05)
}
}

View File

@@ -0,0 +1,123 @@
//! Throwaway perf probe: cost of repainting while text streams in.
//!
//! Measures both halves of a frame: the layout/diff work (ratatui) and the bytes crossterm
//! actually writes to the terminal, for several reveal granularities.
//!
//! Run: `cargo run -p luxe-tui --release --example stream_perf`
use luxe_core::config::Config;
use luxe_core::keymap::KeyMap;
use luxe_tui::app::{App, ConvoBlock, Msg};
use luxe_tui::view::render;
use ratatui::{backend::CrosstermBackend, layout::Rect, Terminal, TerminalOptions, Viewport};
use std::cell::Cell;
use std::io::Write;
use std::rc::Rc;
use std::time::Instant;
/// Sinks bytes and counts them — stands in for the terminal so a frame's real escape-sequence
/// volume is measurable.
#[derive(Clone)]
struct Counter(Rc<Cell<usize>>);
impl Write for Counter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.set(self.0.get() + buf.len());
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
const W: u16 = 140;
const H: u16 = 44;
fn body() -> String {
let mut s = String::new();
for i in 0..12 {
s.push_str(&format!(
"Sentence {i} of a streamed answer, long enough to wrap across the prose canvas more \
than once so the transcript keeps growing downward as it arrives. "
));
}
s
}
fn seed(turns: usize) -> App {
let (tx, _rx) = tokio::sync::mpsc::channel(64);
let mut app = App::new_fixture(tx, KeyMap::defaults(), Config::default());
app.headless = true;
app.update(Msg::TerminalResized { width: W, height: H });
for i in 0..turns {
app.push_convo(ConvoBlock::User {
text: format!("question {i}"),
attached: Vec::new(),
chips: Vec::new(),
});
app.push_convo(ConvoBlock::Assistant(format!(
"Answer {i}. Some prose with `code` and **bold** that wraps over a couple of rows in \
the transcript, plus a second sentence for length."
)));
}
app
}
/// Streams `text` into the app's tail block `chars_per_frame` at a time, drawing each step.
fn run(label: &str, turns: usize, chars_per_frame: usize) {
let mut app = seed(turns);
app.push_convo(ConvoBlock::Assistant(String::new()));
let counter = Counter(Rc::new(Cell::new(0)));
let backend = CrosstermBackend::new(counter.clone());
let mut term = Terminal::with_options(
backend,
TerminalOptions { viewport: Viewport::Fixed(Rect::new(0, 0, W, H)) },
)
.unwrap();
term.draw(|f| render(f, &mut app)).unwrap();
counter.0.set(0);
let text = body();
let chars: Vec<char> = text.chars().collect();
let mut frames = 0usize;
let mut times = Vec::new();
let mut bytes = Vec::new();
for chunk in chars.chunks(chars_per_frame) {
if let Some(ConvoBlock::Assistant(tail)) =
app.convo.last_mut().map(luxe_tui::app::ConversationItem::block_mut)
{
tail.extend(chunk.iter());
}
let before = counter.0.get();
let start = Instant::now();
term.draw(|f| render(f, &mut app)).unwrap();
times.push(start.elapsed().as_secs_f64() * 1000.0);
bytes.push(counter.0.get() - before);
frames += 1;
}
let total_bytes: usize = bytes.iter().sum();
let mean_t = times.iter().sum::<f64>() / frames as f64;
let mut sorted = times.clone();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
let p95 = sorted[(frames * 95 / 100).min(frames - 1)];
let mut bs = bytes.clone();
bs.sort_unstable();
println!(
"{label:<46} frames {frames:4} draw mean {mean_t:6.3} ms p95 {p95:6.3} \
bytes/frame p50 {:5} p95 {:6} max {:6} total {:6} KiB",
bs[frames / 2],
bs[(frames * 95 / 100).min(frames - 1)],
bs[frames - 1],
total_bytes / 1024
);
}
fn main() {
println!("=== streaming {} chars into a transcript ({W}x{H}) ===", body().chars().count());
for turns in [10usize, 60] {
for cpf in [1usize, 2, 4, 8, 16, 80] {
run(&format!("{turns} prior turns, {cpf} chars/frame"), turns, cpf);
}
println!();
}
}

View File

@@ -0,0 +1,264 @@
//! 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::{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}\"", kebab(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 = String::new();
for token in EXPORTED {
if let Some(hex) = hex(theme.get(*token)) {
let _ = writeln!(out, " --luxe-{}: {hex};", kebab(token));
}
}
// 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))
}
/// `accentSecondary` reads as `--luxe-accent-secondary` on the web side.
fn kebab(token: &str) -> String {
let mut out = String::new();
for (index, character) in token.char_indices() {
if character.is_ascii_uppercase() {
if index > 0 {
out.push('-');
}
out.push(character.to_ascii_lowercase());
} else {
out.push(character);
}
}
out
}
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> {
rgb(value).map(to_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:?}"
);
}
/// Token names arrive in the shape a stylesheet expects.
#[test]
fn token_names_become_kebab_case() {
assert_eq!(kebab("accentSecondary"), "accent-secondary");
assert_eq!(kebab("background"), "background");
assert_eq!(kebab("borderMuted"), "border-muted");
}
/// 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");
}
}

View File

@@ -0,0 +1,496 @@
//! ui_fixture — static production-renderer screenshots for UI review.
use anyhow::{bail, Result};
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::{execute, terminal::SetTitle};
use luxe_tui::fixture::{seeded_app, FixtureScenario};
use luxe_tui::main_loop::{route_mouse, RouteAction, ScrollAction};
use luxe_tui::{terminal, view};
use std::env;
use std::io;
use std::time::Duration;
fn main() -> Result<()> {
let (theme, scenario) = parse_args()?;
// The fixture keeps clear of user config on purpose, so the glyph vocabulary gets its own knob:
// `LUXE_FIXTURE_GLYPHS=nerd|nerd-wide|unicode|ascii` captures a surface at one fidelity.
if let Ok(glyphs) = env::var("LUXE_FIXTURE_GLYPHS") {
use luxe_tui::glyphs::{set_tier, GlyphTier};
set_tier(match glyphs.as_str() {
"nerd-wide" | "nerd_wide" => GlyphTier::NerdWide,
"unicode" => GlyphTier::Unicode,
"ascii" => GlyphTier::Ascii,
_ => GlyphTier::Nerd,
});
}
let mut app = seeded_app(&theme, scenario).map_err(anyhow::Error::msg)?;
// `LUXE_FIXTURE_DESKTOP=<name>` paints the frame in an Omarchy theme from this machine, turned
// into Luxe's the way a session following the desktop does, so a theme no built-in matches can
// be judged without applying it
if let Ok(name) = env::var("LUXE_FIXTURE_DESKTOP") {
app.theme_styles = desktop_styles(&name)?;
}
// The same knob for the other thing the terminal decides for us:
// `LUXE_FIXTURE_IMAGES=pixels|blocks|off` captures an image surface at one fidelity.
if let Ok(images) = env::var("LUXE_FIXTURE_IMAGES") {
use luxe_tui::graphics::ImageTier;
app.images.set_tier(match images.as_str() {
"pixels" => ImageTier::Pixels,
"off" => ImageTier::Text,
_ => ImageTier::Blocks,
});
}
let scenario_name = scenario.name();
execute!(io::stdout(), SetTitle(format!("Luxe fixture: {scenario_name}")))?;
let mut terminal = terminal::init()?;
let result = run(&mut terminal, &mut app);
terminal::restore()?;
result
}
fn run(terminal: &mut terminal::Tui, app: &mut luxe_tui::app::App) -> Result<()> {
let size = terminal.size()?;
app.update(luxe_tui::app::Msg::TerminalResized { width: size.width, height: size.height });
// Optional overlay to open at startup for screenshot review (e.g. LUXE_FIXTURE_OVERLAY=palette).
// A subscription's remaining allowance takes the statusline's cost slot; seed it on demand.
if env::var("LUXE_FIXTURE_PLAN").is_ok() {
luxe_tui::fixture::seed_plan_usage(app);
}
// The dock at a width a reader dragged it to, e.g. `LUXE_FIXTURE_DOCK_WIDTH=80`
if let Some(width) = env::var("LUXE_FIXTURE_DOCK_WIDTH").ok().and_then(|w| w.parse().ok()) {
app.panes.set(luxe_tui::workspace_layout::Pane::Dock, Some(width));
}
// The File view on a real file, e.g. `LUXE_FIXTURE_FILE=crates/luxe-tui/src/files.rs`, with
// `LUXE_FIXTURE_PICK=40-52` picking lines in it
if let Ok(path) = env::var("LUXE_FIXTURE_FILE") {
let text = std::fs::read_to_string(&path).unwrap_or_default();
let pick = env::var("LUXE_FIXTURE_PICK").ok().and_then(|pick| {
let (first, last) = pick.split_once('-').unwrap_or((&pick, &pick));
Some((first.parse().ok()?, last.parse().ok()?))
});
luxe_tui::fixture::seed_file_view(app, &path, &text, pick);
}
// Where the keyboard is: `LUXE_FIXTURE_FOCUS=files` for the tree, `=peek:44` for the preview
// with its cursor on line 44
if let Ok(focus) = env::var("LUXE_FIXTURE_FOCUS") {
match focus.split_once(':').unwrap_or((&focus, "")) {
("files", _) => app.update(luxe_tui::app::Msg::FocusFiles),
("peek", line) => luxe_tui::fixture::focus_preview(app, line.parse().ok()),
// `filter:dock` filters the tree over this checkout's files
("filter", query) => {
let cwd = env::current_dir().unwrap_or_default();
let files = luxe_tui::ref_provider::list_files(&cwd);
luxe_tui::fixture::filter_tree(app, &files, query);
}
// `visual:12-16` selects those lines in visual-line mode
("visual", range) => {
let (from, to) = range.split_once('-').unwrap_or((range, range));
if let (Ok(from), Ok(to)) = (from.parse(), to.parse()) {
luxe_tui::fixture::preview_visual(app, from, to);
}
}
_ => {}
}
}
// Todo subjects as long as a real plan writes them, to see the checklist wrap
if env::var("LUXE_FIXTURE_LONG_TODOS").is_ok() {
if let Some(snapshot) = app.workspace.as_mut() {
let lengthen = |subject: &mut String| {
subject.push_str(" across the backend, the frontend and every integration test");
};
snapshot.todos.items.iter_mut().for_each(|item| lengthen(&mut item.subject));
if let Some(current) = snapshot.todos.current.as_mut() {
lengthen(&mut current.subject);
}
}
}
if let Ok(overlay) = env::var("LUXE_FIXTURE_OVERLAY") {
if let Some(login) = luxe_tui::fixture::LoginFixture::parse(&overlay) {
luxe_tui::fixture::seed_login_wizard(app, login);
}
// The `@` picker on each of its tabs, and GitHub when `gh` cannot list anything
if let Some(tab) = overlay.strip_prefix("mention-") {
luxe_tui::fixture::seed_mention_picker(app, tab);
}
// `/github` and `/pr`, each in a state worth a look: `github`, `github-detail`,
// `github-conversation`, `github-draft`, `github-issue`, `github-pulls`, `github-search`,
// `github-merged`, `pr`, `pr-merge`
if overlay.starts_with("pr") || overlay.starts_with("github") {
luxe_tui::fixture::seed_github(app, &overlay);
}
// Keys the review answers to, as a reader would press them: `help` for `?`
if overlay == "help" {
app.update(luxe_tui::app::Msg::Key(KeyEvent::new(
KeyCode::Char('?'),
KeyModifiers::NONE,
)));
}
if overlay == "palette" {
app.update(luxe_tui::app::Msg::Key(KeyEvent::new(
KeyCode::Char('k'),
KeyModifiers::CONTROL,
)));
}
}
// Demo the file list at scale: clone the fixture file into many deeply-nested long paths so
// the rail's one-line truncation + colored counts are visible for screenshot review.
let many_files = env::var("LUXE_FIXTURE_MANYFILES").ok();
if let Some(mode) = many_files.as_deref() {
use luxe_core::guided_review::{FileId, ReviewFileStatus, ReviewItemRef};
if let Some(review) = app.guided_review.as_mut() {
let template = review.files[0].clone();
let specs: &[(&str, u64, u64, ReviewFileStatus)] = &[
("crates/luxe-core/src/keymap/actions.rs", 5, 0, ReviewFileStatus::Modified),
("crates/luxe-core/src/config.rs", 109, 2, ReviewFileStatus::Modified),
("crates/luxe-tui/src/app/commands.rs", 3, 0, ReviewFileStatus::Modified),
("crates/luxe-tui/src/model_picker.rs", 51, 16, ReviewFileStatus::Modified),
("crates/luxe-tui/src/session_picker.rs", 167, 39, ReviewFileStatus::Modified),
(
"crates/luxe-tui/src/view/guided_review/context.rs",
151,
30,
ReviewFileStatus::Modified,
),
(
"crates/luxe-tui/src/view/guided_review/diff_render.rs",
330,
116,
ReviewFileStatus::Modified,
),
("crates/luxe-tui/src/themes/rose-pine.json", 2, 0, ReviewFileStatus::Added),
("docs/design/legacy-review-notes.md", 0, 84, ReviewFileStatus::Deleted),
];
for (path, additions, deletions, status) in specs {
let mut file = template.clone();
file.id = FileId::from_path_lineage(None, Some(std::path::Path::new(path)));
file.new_path = Some(path.into());
file.old_path = Some(path.into());
file.additions = Some(*additions);
file.deletions = Some(*deletions);
file.status = *status;
if let Some(chapter) = review.chapters.first_mut() {
chapter.items.push(ReviewItemRef::File(file.id.clone()));
}
review.files.push(file);
// Keep the review summary consistent with the injected files.
review.stats.files += 1;
review.stats.additions = Some(review.stats.additions.unwrap_or(0) + additions);
review.stats.deletions = Some(review.stats.deletions.unwrap_or(0) + deletions);
}
}
// `LUXE_FIXTURE_MANYFILES=hidden` puts the guide away, so the injected list is read from
// the diff pane's own header instead.
if mode == "hidden" {
app.update(luxe_tui::app::Msg::GuidedReviewToggleGuide);
}
}
// Demo the intra-line marks: replace the first hunk with pairs the fixture's single-token edit
// cannot show — two separate edits in one line, an edit that only moves punctuation, a rewrite
// that must come back unmarked. `LUXE_FIXTURE_INTRALINE=1`.
if env::var("LUXE_FIXTURE_INTRALINE").is_ok() {
use luxe_core::guided_review::{ReviewLine, ReviewLineKind};
let pairs = [
(
"/// Takes a string like '2' and returns it.",
"/// Takes a number like 2 and returns it.",
),
(" pub category: String,", " pub category: NotificationCategory,"),
(
" let label: String = category.to_string();",
" let label = category.display_name();",
),
(" if ready && !stale {", " if ready {"),
(" send(payload, Priority::Low)?;", " dispatch(payload).await?;"),
];
if let Some(hunk) = app
.guided_review
.as_mut()
.and_then(|review| review.files.first_mut().and_then(|file| file.hunks.first_mut()))
{
hunk.lines = pairs
.iter()
.enumerate()
.flat_map(|(index, (removed, added))| {
let number = index as u32 * 2 + 1;
[
ReviewLine {
old_line: Some(number),
new_line: None,
kind: ReviewLineKind::Deletion,
text: (*removed).into(),
},
ReviewLine {
old_line: None,
new_line: Some(number),
kind: ReviewLineKind::Addition,
text: (*added).into(),
},
]
})
.collect();
}
}
// Demo tab-indented source, which is what exposed the expansion defect: `LUXE_FIXTURE_TABS=1`.
if env::var("LUXE_FIXTURE_TABS").is_ok() {
use luxe_core::guided_review::{ReviewLine, ReviewLineKind};
if let Some(hunk) = app
.guided_review
.as_mut()
.and_then(|review| review.files.first_mut().and_then(|file| file.hunks.first_mut()))
{
hunk.lines = (1..=5u32)
.flat_map(|depth| {
let indent = "\t".repeat(depth as usize);
[
ReviewLine {
old_line: Some(depth * 2),
new_line: None,
kind: ReviewLineKind::Deletion,
text: format!("{indent}<div class=\"grid grid-cols-2 gap-4\">"),
},
ReviewLine {
old_line: None,
new_line: Some(depth * 2),
kind: ReviewLineKind::Addition,
text: format!("{indent}<div class=\"form-control\">"),
},
]
})
.collect();
}
}
// Demo the review word-wrap: inject a long addition line and turn wrapping on so it is visible
// for screenshot review (the fixture's own lines are short).
if env::var("LUXE_FIXTURE_WRAP").is_ok() {
if let Some(line) = app.guided_review.as_mut().and_then(|review| {
review.files.first_mut().and_then(|file| file.hunks.first_mut()).and_then(|hunk| {
hunk.lines
.iter_mut()
.find(|line| line.kind == luxe_core::guided_review::ReviewLineKind::Addition)
})
}) {
line.text = "let very_long_identifier = compute_something(alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa);".into();
}
app.update(luxe_tui::app::Msg::Key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE)));
}
// A scenario with a pinned clock is mid-animation on purpose, so run the reveal forward the way
// the event loop does — one frame every 12 ms — and then stop, leaving a frame that is the same
// every time it is captured. Stepping matters: a frame's timestep is capped, so jumping the clock
// would land somewhere else entirely.
if let Some(base) = app.status.frame_clock {
for step in 1..=REVEAL_FRAMES {
app.status.frame_clock = Some(base + Duration::from_millis(12) * step);
draw(terminal, app)?;
}
}
// A named wordmark frame is a still: the shine is a pure function of the tick, so holding the
// tick holds the frame, and the capture is the same every time instead of wherever ~1s of
// ticking happened to land.
let pinned = env::var("LUXE_FIXTURE_BANNER_TICK").is_ok();
// Capture the mouse, so a pointer gesture is reviewable the way a keystroke is. This is the
// only place the production mouse router meets a real terminal without a live engine behind it.
terminal::set_mouse_capture(true)?;
loop {
draw(terminal, app)?;
// Poll on the production tick, and tick the app when nothing arrives, so animated chrome
// (the activity bar, tool-card spinners) runs at the speed it will really run at.
if event::poll(Duration::from_millis(33))? {
match event::read()? {
// Esc closes whatever the app has open before it closes the fixture, or a
// surface that exists to be reviewed can never be reviewed.
Event::Key(key)
if matches!(key.code, KeyCode::Esc | KeyCode::Char('q'))
&& app.overlays.image_viewer.is_none() =>
{
return Ok(());
}
Event::Key(key)
if key.code == KeyCode::Char('b')
&& key.modifiers.contains(KeyModifiers::CONTROL) =>
{
app.update(luxe_tui::app::Msg::GuidedReviewToggleSplit);
}
// Reflow on window resize so responsive layouts (dock, dashboard) can be
// reviewed at any size, not just the size present at launch.
Event::Resize(width, height) => {
app.update(luxe_tui::app::Msg::TerminalResized { width, height });
}
// Forward every other key to the app so overlays (palette via Ctrl+K, pickers,
// in-review actions) can be driven for screenshot review.
Event::Key(key) => {
app.update(luxe_tui::app::Msg::Key(key));
}
// Pointer gestures go through the production router, so drag-to-select,
// multi-click, and click-to-expand can be reviewed here too.
Event::Mouse(mouse) => {
let action = route_mouse(app, &mouse);
apply(app, action);
}
_ => {}
}
} else if !pinned {
app.update(luxe_tui::app::Msg::Tick);
}
}
}
/// Applies what the mouse router asked for. The fixture has no engine, so the outcomes that end a
/// session or reopen a project are unreachable here and ignored.
fn apply(app: &mut luxe_tui::app::App, action: RouteAction) {
match action {
RouteAction::Msg(message) => app.update(*message),
RouteAction::Scroll(ScrollAction::Up(lines)) => app.scroll_state.up_by(lines),
RouteAction::Scroll(ScrollAction::Down(lines)) => app.scroll_state.down_by(lines),
RouteAction::Scroll(ScrollAction::PageUp) => app.scroll_state.page_up(),
RouteAction::Scroll(ScrollAction::PageDown) => app.scroll_state.page_down(),
RouteAction::Scroll(ScrollAction::ToBottom) => app.scroll_state.to_bottom(),
RouteAction::Scroll(ScrollAction::DragTo { row, height }) => {
app.scroll_state.drag_to(row, height);
}
_ => {}
}
}
/// Frames a clock-pinned scenario is stepped before it is captured — about a third of a second,
/// far enough in that the reveal has a settled beginning and a fading tail to look at.
const REVEAL_FRAMES: u32 = 28;
fn parse_args() -> Result<(String, FixtureScenario)> {
let mut args = env::args().skip(1);
let Some(flag) = args.next() else {
bail!(usage());
};
if flag == "--help" || flag == "-h" {
println!("{}", usage());
std::process::exit(0);
}
if flag != "--theme" {
bail!(usage());
}
let Some(theme) = args.next() else {
bail!(usage());
};
let Some(scenario) = args.next() else {
bail!(usage());
};
if args.next().is_some() {
bail!(usage());
}
Ok((theme, scenario.parse().map_err(anyhow::Error::msg)?))
}
fn usage() -> String {
let names: Vec<&str> = FixtureScenario::ALL.iter().map(|scenario| scenario.name()).collect();
format!(
"usage: cargo run -p luxe-tui --example ui_fixture -- --theme <built-in-id> <{}>",
names.join("|")
)
}
/// The styles of the Omarchy theme `name`, installed or the user's own.
fn desktop_styles(name: &str) -> Result<luxe_tui::theme::styles::ThemeStyles> {
let home = luxe_core::user_dirs::home_dir().unwrap_or_default();
let dir = [".config/omarchy/themes", ".local/share/omarchy/themes"]
.iter()
.map(|root| home.join(root).join(name))
.find(|dir| dir.is_dir());
let Some(dir) = dir else { bail!("no Omarchy theme named {name}") };
let desktop = luxe_core::omarchy::DesktopTheme { name: name.to_owned(), dir };
let registry = luxe_core::theme::ThemeRegistry::new().with_desktop(Some(&desktop));
let Some(resolved) = registry.resolve(luxe_core::omarchy::DESKTOP_THEME) else {
bail!("{name} has no colors Luxe can read")
};
Ok(luxe_tui::theme::styles::ThemeStyles::from_resolved(&resolved, name))
}
/// Draws a frame, with the headings in lower case under `LUXE_FIXTURE_HEADINGS=lower`.
///
/// For weighing a look before building it: the frame is drawn as shipped and its headings are
/// rewritten in the buffer, so the comparison is the same frame with one thing changed. A heading
/// is told by how it is drawn, a bold word of three or more capitals standing alone, which is
/// every section badge and pane tab and no code a preview could be showing.
fn draw(terminal: &mut terminal::Tui, app: &mut luxe_tui::app::App) -> io::Result<()> {
if env::var("LUXE_FIXTURE_HEADINGS").as_deref() != Ok("lower") {
return view::draw(terminal, app);
}
terminal::draw_synchronized(terminal, |frame| {
view::render(frame, app);
lower_headings(frame.buffer_mut());
})
}
fn lower_headings(buffer: &mut ratatui::buffer::Buffer) {
use ratatui::style::Modifier;
let area = buffer.area;
for y in area.top()..area.bottom() {
let mut x = area.left();
while x < area.right() {
let heading = |cell: &ratatui::buffer::Cell| {
cell.modifier.contains(Modifier::BOLD)
&& cell.symbol().chars().all(|c| c.is_ascii_uppercase())
&& !cell.symbol().is_empty()
};
let start = x;
while x < area.right() && heading(&buffer[(x, y)]) {
x += 1;
}
let alone = |at: u16| {
at < area.left()
|| at >= area.right()
|| !buffer[(at, y)].symbol().chars().all(char::is_alphanumeric)
|| buffer[(at, y)].symbol().is_empty()
};
if x - start >= 3 && alone(start.wrapping_sub(1)) && alone(x) {
for column in start..x {
let lower = buffer[(column, y)].symbol().to_ascii_lowercase();
buffer[(column, y)].set_symbol(&lower);
}
}
x = x.max(start + 1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usage_describes_stable_fixture_interface() {
assert!(usage().contains("--theme <built-in-id>"));
assert!(usage().contains("chat-tool-error"));
assert!(usage().contains("chat-tool-run"));
assert!(usage().contains("guided-review-wide"));
assert!(usage().contains("guided-review-findings-empty"));
assert!(usage().contains("guided-review-findings"));
assert!(usage().contains("guided-review-needs-verification"));
assert!(usage().contains("guided-review-finish"));
assert!(usage().contains("guided-review-medium"));
assert!(usage().contains("guided-review-narrow"));
assert!(usage().contains("dock-compact"));
// Every name this offers has to open something. The list had drifted: it advertised a
// `guided-review-skim` that no longer exists, so the one place a user looks up a surface
// was naming one they could not reach.
let usage = usage();
let offered = usage
.rsplit_once('<')
.map(|(_, tail)| tail.trim_end_matches('>'))
.expect("the scenario list");
let mut advertised = Vec::new();
for name in offered.split('|') {
let scenario = name.parse::<FixtureScenario>();
assert!(scenario.is_ok(), "usage offers unknown {name:?}");
advertised.push(scenario.unwrap());
}
// And the list checks walk has to be the same one, or a scenario dodges every check by
// being in neither: `FixtureScenario::ALL` is what the fixture's own invariants run over.
for scenario in FixtureScenario::ALL {
assert!(advertised.contains(scenario), "usage never offers {scenario:?}");
}
assert_eq!(advertised.len(), FixtureScenario::ALL.len(), "the two lists have drifted");
}
}

View File

@@ -0,0 +1,321 @@
//! wordmark_svg — the logotype as vector, generated from the art that ships.
//!
//! The web needs the same mark the terminal draws, and the only honest way to get one is to derive
//! it from the same rows rather than trace it: `art.rs` is the single source, and a traced copy is
//! a second drawing that silently disagrees the first time either moves.
//!
//! Each cell becomes geometry — the full block a rectangle, the half blocks the half of the cell
//! they ink — and horizontal runs merge so a row of blocks is one rectangle rather than fourteen.
//! Output is one `<path>` per ink group, so the brass steps the TUI paints have somewhere to land in
//! CSS.
//!
//! ```sh
//! cargo run -p luxe-tui --example wordmark_svg -- wordmark > web/src/assets/wordmark.svg
//! cargo run -p luxe-tui --example wordmark_svg -- mark > web/src/assets/mark.svg
//! cargo run -p luxe-tui --example wordmark_svg -- tile > web/src/assets/tile.svg
//! ```
use luxe_tui::widgets::Wordmark;
use std::env;
/// Cell size in user units, at the 1:2.2 aspect a terminal actually draws — the mark is recognized
/// at those proportions, so an idealised 1:2 grid would ship a subtly different logotype.
const CELL_W: u32 = 10;
const CELL_H: u32 = 22;
fn main() {
let mut args = env::args().skip(1);
let target = args.next().unwrap_or_else(|| "wordmark".into());
let rows = Wordmark::Full.rows();
match target.as_str() {
"wordmark" => print!("{}", svg(rows, 0..Wordmark::Full.group_count())),
"mark" => print!("{}", svg(rows, 0..1)),
"tile" => print!("{}", tile(rows, tile_colors())),
other => {
eprintln!("usage: wordmark_svg [wordmark|mark|tile] (got {other:?})");
std::process::exit(2);
}
}
}
/// Side of the square tile, in user units. 512 exports cleanly to every favicon size.
const TILE: u32 = 512;
/// Air between the letter and the tile's edge. Little of it: a thin letter on a dark tile has to
/// fill the tile to stay a letter at 16px, and more margin left a blur in the tab strip.
const TILE_PAD: u32 = 32;
/// The tile's plate and letter, as colors written into the file: the luxe theme's canvas, and the
/// letter in its accent, the brass the wordmark is lit in.
///
/// Written in rather than left to page variables. A favicon is drawn as an image, where no page CSS
/// reaches, so `var(--luxe-wordmark-4, currentColor)` fell back to black under a near-black letter
/// and the tab showed an empty dark square.
fn tile_colors() -> (String, String) {
let theme = luxe_core::theme::ThemeRegistry::new().resolve("luxe").expect("a built-in theme");
let hex = |token: &str| match theme.get(token) {
Some(luxe_core::theme::ColorValue::Rgb(red, green, blue)) => {
format!("#{red:02x}{green:02x}{blue:02x}")
}
other => panic!("the luxe theme's {token} is a color, not {other:?}"),
};
(hex("background"), hex("accent"))
}
/// The favicon: a square dark tile with the L in brass.
///
/// The wordmark does not survive a 16px tab strip and neither does one bare letter — the L alone is
/// thin, tall and mostly air. What *is* legible at that size is a solid shape, so the mark becomes
/// a plain square, the same flat block the product draws its labels on. The letter is there for
/// anyone looking at it larger than a tab.
fn tile(rows: &[&str], (plate_color, ink): (String, String)) -> String {
let side = TILE;
let plate = format!("M0 0H{side}V{side}H0z");
// Fit the L by height, then center it: it is the taller axis, so height sets the scale.
let letter_w = ink_right(rows, 0..1) * CELL_W;
let letter_h = rows.len() as u32 * CELL_H;
let scale = f64::from(side - TILE_PAD * 2) / f64::from(letter_h);
let offset_x = (f64::from(side) - f64::from(letter_w) * scale) / 2.0;
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {side} {side}\" \
width=\"{side}\" height=\"{side}\" role=\"img\" aria-label=\"Luxe\">\n \
<title>Luxe</title>\n \
<path fill=\"{plate_color}\" d=\"{plate}\"/>\n \
<g transform=\"translate({offset_x:.2} {TILE_PAD}) scale({scale:.4})\">\n \
<path fill=\"{ink}\" d=\"{letter}\"/>\n \
</g>\n</svg>\n",
letter = letter_path(rows, 0)
)
}
/// The SVG for `letters` of the logotype, one path per letter.
fn svg(rows: &[&str], letters: std::ops::Range<usize>) -> String {
let paths: Vec<String> = letters.clone().map(|letter| letter_path(rows, letter)).collect();
// Crop to the ink actually emitted, so the `mark` variant is not the full logotype's box with
// three empty letters of padding on the right.
let left = first_column(letters.start) * CELL_W;
let right = ink_right(rows, letters.clone()) * CELL_W;
let (width, height) = (right - left, rows.len() as u32 * CELL_H);
let mut out = String::new();
// The cell rides along because the drawing is a grid, and the website's highlight is defined in
// that grid the way the terminal's is — one cell right per row of lean. Deriving the cell from
// the box instead means knowing how many rows the art has, which is a second copy of the art.
out.push_str(&format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{left} 0 {width} {height}\" \
width=\"{width}\" height=\"{height}\" data-cell=\"{CELL_W} {CELL_H}\" \
role=\"img\" aria-label=\"Luxe\">\n"
));
out.push_str(" <title>Luxe</title>\n");
for (index, path) in paths.iter().enumerate() {
let step = index + letters.start + 1;
out.push_str(&format!(
" <path fill=\"var(--luxe-wordmark-{step}, currentColor)\" d=\"{path}\"/>\n"
));
}
out.push_str("</svg>\n");
out
}
/// The first column of ink group `group`.
fn first_column(group: usize) -> u32 {
let groups = Wordmark::Full.groups();
groups.iter().position(|owner| *owner == group).unwrap_or(0) as u32
}
/// The columns ink group `group` spans.
fn group_span(group: usize) -> std::ops::Range<usize> {
let groups = Wordmark::Full.groups();
let first = groups.iter().position(|owner| *owner == group).unwrap_or(0);
let last = groups.iter().rposition(|owner| *owner == group).unwrap_or(first);
first..last + 1
}
/// One column past the rightmost inked cell in `letters`.
fn ink_right(rows: &[&str], letters: std::ops::Range<usize>) -> u32 {
let span = group_span(letters.start).start..group_span(letters.end - 1).end;
rows.iter()
.flat_map(|row| {
row.chars()
.enumerate()
.filter(|(column, glyph)| *glyph != ' ' && span.contains(column))
.map(|(column, _)| column as u32 + 1)
})
.max()
.unwrap_or(0)
}
/// Every inked cell of one letter, as a single path's worth of subpaths.
fn letter_path(rows: &[&str], letter: usize) -> String {
let span = group_span(letter);
let mut parts: Vec<String> = Vec::new();
for (row, text) in rows.iter().enumerate() {
let cells: Vec<(usize, char)> =
text.chars().enumerate().filter(|(column, _)| span.contains(column)).collect();
// Merge horizontal runs of full blocks into one rectangle each; a half block breaks the run
// because it inks only part of its cell, and emits its own.
let mut run: Option<(usize, usize)> = None;
let flush = |run: &mut Option<(usize, usize)>, parts: &mut Vec<String>| {
if let Some((start, end)) = run.take() {
parts.push(rect(start as u32, row as u32, (end - start + 1) as u32, 0, 1.0));
}
};
for (column, glyph) in cells {
match glyph {
'\u{2588}' => match run {
Some((start, end)) if end + 1 == column => run = Some((start, column)),
_ => {
flush(&mut run, &mut parts);
run = Some((column, column));
}
},
// The half blocks: the same rectangle at half height, from one edge or the other.
'\u{2580}' | '\u{2584}' => {
flush(&mut run, &mut parts);
let top = u32::from(glyph == '\u{2584}');
parts.push(rect(column as u32, row as u32, 1, top, 0.5));
}
_ => flush(&mut run, &mut parts),
}
}
flush(&mut run, &mut parts);
}
parts.join(" ")
}
/// A run of `cells` cells at `(column, row)`, inked for `share` of the cell's height.
///
/// `half` shifts the rectangle down by half a cell, which is the whole difference between the upper
/// and lower half block. Fractions rather than whole cells because that is what these glyphs *are*:
/// the reason the art needs no font is that a terminal draws them at exact cell fractions, and the
/// vector twin keeps the same promise rather than rounding it.
fn rect(column: u32, row: u32, cells: u32, half: u32, share: f32) -> String {
let x = column * CELL_W;
let y = row * CELL_H + half * CELL_H / 2;
let w = cells * CELL_W;
let h = (f64::from(CELL_H) * f64::from(share)).round() as u32;
format!("M{x} {y}h{w}v{h}h-{w}z")
}
#[cfg(test)]
mod tests {
use super::*;
/// The groups this generator slices by are the art's own, and they tile it without gaps or
/// overlaps — the one way a letter can silently lose half of itself.
#[test]
fn the_groups_tile_the_art() {
let rows = Wordmark::Full.rows();
let width = rows[0].chars().count();
assert!(rows.iter().all(|row| row.chars().count() == width), "ragged art");
let mut covered = 0usize;
let mut previous_end = 0usize;
for group in 0..Wordmark::Full.group_count() {
let span = group_span(group);
assert!(span.start >= previous_end, "group {group} overlaps the one before it");
previous_end = span.end;
covered += span.len();
}
assert!(covered <= width, "the groups claim more columns than the art has");
}
/// Every inked cell reaches the output. A dropped glyph is a hole in the mark, and the art's own
/// guard only checks the art — not that this generator understood all of it.
#[test]
fn every_inked_cell_becomes_geometry() {
let rows = Wordmark::Full.rows();
let inked = rows.iter().flat_map(|row| row.chars()).filter(|glyph| *glyph != ' ').count();
let emitted: usize = (0..Wordmark::Full.group_count())
.map(|letter| {
let path = letter_path(rows, letter);
// Each subpath starts with `M`; a merged run stands for its whole width.
path.split('M').skip(1).map(cells_in_subpath).sum::<usize>()
})
.sum();
assert_eq!(emitted, inked, "the vector twin lost cells the art draws");
}
/// How many cells one subpath accounts for: a merged block run by its width, a half block as
/// one.
fn cells_in_subpath(part: &str) -> usize {
match part.split_once('h') {
Some((_, rest)) => {
let width: u32 = rest
.chars()
.take_while(char::is_ascii_digit)
.collect::<String>()
.parse()
.unwrap_or(CELL_W);
(width / CELL_W) as usize
}
None => 1,
}
}
/// The generated document is well-formed enough to be trusted without opening a browser.
#[test]
fn the_document_is_shaped_like_an_svg() {
let svg = svg(Wordmark::Full.rows(), 0..4);
assert!(svg.starts_with("<svg xmlns="));
assert!(svg.trim_end().ends_with("</svg>"));
assert_eq!(svg.matches("<path").count(), 4, "one path per letter");
assert!(svg.contains("--luxe-wordmark-1"), "letters are themable from CSS");
assert!(svg.contains("aria-label=\"Luxe\""));
assert!(svg.contains("data-cell=\"10 22\""), "the grid the highlight is drawn in");
}
/// The tile is a plain square and keeps the letter inside its own padding, which is what decides
/// whether it survives a 16px tab strip.
#[test]
fn the_tile_is_a_plain_square() {
let rows = Wordmark::Full.rows();
let svg = tile(rows, tile_colors());
assert!(svg.contains(&format!("viewBox=\"0 0 {TILE} {TILE}\"")), "the tile is square");
assert_eq!(svg.matches("<path").count(), 2, "a plate and a letter");
// Colors written in: a favicon is an image, and no page variable reaches it
assert!(!svg.contains("var("), "{svg}");
let (plate_color, ink) = tile_colors();
assert!(
svg.contains(&format!("fill=\"{plate_color}\""))
&& svg.contains(&format!("fill=\"{ink}\""))
);
assert_ne!(plate_color, ink);
// Four corners and the close: no cut, no curve.
let plate =
svg.split("d=\"").nth(1).and_then(|rest| rest.split('"').next()).expect("plate");
let vertices = plate.chars().filter(|glyph| "MHVLz".contains(*glyph)).count();
assert_eq!(vertices, 5, "a square: {plate}");
assert!(!plate.contains('A') && !plate.contains('C'), "square, never rounded: {plate}");
// The letter is scaled to its padding rather than overflowing the plate it sits on.
let scale: f64 = svg
.split("scale(")
.nth(1)
.and_then(|rest| rest.split(')').next())
.and_then(|raw| raw.parse().ok())
.expect("a scale factor");
let drawn = scale * f64::from(rows.len() as u32 * CELL_H);
assert!(
(drawn - f64::from(TILE - TILE_PAD * 2)).abs() < 1.0,
"the letter fills its box exactly: {drawn}"
);
}
/// The single-letter mark crops to its own ink instead of carrying three empty letters of
/// padding.
#[test]
fn the_mark_crops_to_the_letter_it_draws() {
let rows = Wordmark::Full.rows();
let mark = svg(rows, 0..1);
assert_eq!(mark.matches("<path").count(), 1);
let full_width = (rows[0].chars().count() as u32 * CELL_W).to_string();
assert!(!mark.contains(&format!("width=\"{full_width}\"")), "the mark is not the wordmark");
}
}