Skip to main content

max / makeover

83.4 KB · 2332 lines History Blame Raw
1 //! Shared theme loading + intent resolution for TOML-based theme files.
2 //!
3 //! Used by GoingsOn, Balanced Breakfast (Tauri apps), audiofiles (egui), and the
4 //! MNW web server. Themes are authored by **intent** ("human design"): colors are
5 //! declared by role (surface / content / action / status / line / category), not
6 //! by hue. This crate is the single place that resolves an authored theme into a
7 //! full set of intent tokens — including the derived interactive states
8 //! (hover/active/selection/row-stripe/contrast) that each app used to recompute
9 //! itself — and emits them as CSS variables or RGB tuples.
10 //!
11 //! Theme file shape:
12 //! ```text
13 //! [meta]
14 //! name = "Nord"
15 //! variant = "dark" # or "light"
16 //!
17 //! [surface] # container backgrounds by role/elevation
18 //! page = "#2e3440"; raised = "#3b4252"; sunken = "#434c5e"; overlay = "#3b4252"
19 //!
20 //! [content] # text/ink by emphasis
21 //! primary = "#d8dee9"; secondary = "#e5e9f0"; muted = "#616e88"
22 //!
23 //! [action] # interactive / brand color
24 //! primary = "#81a1c1"
25 //!
26 //! [status] # state semantics
27 //! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
28 //!
29 //! [line]
30 //! border = "#4c566a"
31 //!
32 //! [category] # distinct decorative colors for tags/badges/charts
33 //! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
34 //! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
35 //! ```
36
37 // Color-space math: single-letter channel names (r/g/b/l/m/s) and the published
38 // high-precision OKLab/sRGB matrix constants are the domain vocabulary here.
39 #![allow(clippy::many_single_char_names, clippy::unreadable_literal)]
40
41 use serde::Serialize;
42 use std::collections::{BTreeMap, HashMap};
43 use std::path::{Path, PathBuf};
44
45 /// The color sections an authored theme may declare.
46 pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];
47
48 /// Theme metadata parsed from the `[meta]` section.
49 #[derive(Debug, Clone, Serialize)]
50 #[serde(rename_all = "camelCase")]
51 pub struct ThemeMeta {
52 pub id: String,
53 pub name: String,
54 pub variant: String,
55 pub is_custom: bool,
56 }
57
58 /// A loaded theme: metadata plus the authored colors, flattened to dotted keys
59 /// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
60 #[derive(Debug, Serialize)]
61 #[serde(rename_all = "camelCase")]
62 pub struct ThemeColors {
63 pub meta: ThemeMeta,
64 pub colors: HashMap<String, String>,
65 }
66
67 // ============================================================================
68 // Color math — perceptual (OKLab) derivations + WCAG contrast.
69 //
70 // Interactive states (hover/active/selection/surfaces) are derived in OKLab so
71 // equal steps look equal across every theme's hues (Ottosson 2020; the modern
72 // CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
73 // luminance threshold, so the choice actually meets AA where achievable.
74 // This is the single source of truth shared by every product.
75 // ============================================================================
76
77 /// An sRGB color. Hex round-trips losslessly.
78 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
79 pub struct Rgb {
80 pub r: u8,
81 pub g: u8,
82 pub b: u8,
83 }
84
85 impl Rgb {
86 /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
87 pub fn from_hex(s: &str) -> Option<Rgb> {
88 let h = s.strip_prefix('#')?;
89 let (r, g, b) = match h.len() {
90 6 => (
91 u8::from_str_radix(&h[0..2], 16).ok()?,
92 u8::from_str_radix(&h[2..4], 16).ok()?,
93 u8::from_str_radix(&h[4..6], 16).ok()?,
94 ),
95 3 => {
96 let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
97 (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
98 }
99 _ => return None,
100 };
101 Some(Rgb { r, g, b })
102 }
103
104 /// Lowercase `#rrggbb`.
105 pub fn to_hex(self) -> String {
106 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
107 }
108
109 pub fn tuple(self) -> (u8, u8, u8) {
110 (self.r, self.g, self.b)
111 }
112 }
113
114 /// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
115 #[derive(Clone, Copy, Debug)]
116 pub struct Oklab {
117 pub l: f32,
118 pub a: f32,
119 pub b: f32,
120 }
121
122 fn srgb_to_linear(c: u8) -> f32 {
123 let c = c as f32 / 255.0;
124 if c <= 0.04045 {
125 c / 12.92
126 } else {
127 ((c + 0.055) / 1.055).powf(2.4)
128 }
129 }
130
131 fn linear_to_srgb(c: f32) -> u8 {
132 let c = c.clamp(0.0, 1.0);
133 let v = if c <= 0.0031308 {
134 c * 12.92
135 } else {
136 1.055 * c.powf(1.0 / 2.4) - 0.055
137 };
138 (v * 255.0).round().clamp(0.0, 255.0) as u8
139 }
140
141 impl Rgb {
142 /// Convert to OKLab (Ottosson's sRGB matrices).
143 ///
144 /// The matrix coefficients are quoted at their published precision so they
145 /// can be diffed against the reference. `f32` rounds them at compile time;
146 /// truncating the literals would only make them harder to check.
147 #[allow(clippy::excessive_precision)]
148 pub fn to_oklab(self) -> Oklab {
149 let (r, g, b) = (
150 srgb_to_linear(self.r),
151 srgb_to_linear(self.g),
152 srgb_to_linear(self.b),
153 );
154 let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
155 let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
156 let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
157 let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
158 Oklab {
159 l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
160 a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
161 b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
162 }
163 }
164
165 /// Convert from OKLab back to the nearest in-gamut sRGB.
166 ///
167 /// Published precision, as in [`Rgb::to_oklab`].
168 #[allow(clippy::excessive_precision)]
169 pub fn from_oklab(c: Oklab) -> Rgb {
170 let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
171 let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
172 let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
173 let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
174 Rgb {
175 r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
176 g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
177 b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
178 }
179 }
180 }
181
182 /// WCAG 2.x relative luminance of an sRGB color.
183 fn rel_luminance(c: Rgb) -> f32 {
184 0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
185 }
186
187 /// WCAG 2.x contrast ratio between two colors, in [1, 21].
188 pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
189 let (la, lb) = (rel_luminance(a), rel_luminance(b));
190 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
191 (hi + 0.05) / (lo + 0.05)
192 }
193
194 /// Pick black or white for legible text on `bg`, by the higher WCAG contrast
195 /// ratio (so the choice meets AA wherever the background allows it).
196 pub fn readable_on(bg: Rgb) -> Rgb {
197 let white = Rgb {
198 r: 255,
199 g: 255,
200 b: 255,
201 };
202 let black = Rgb { r: 0, g: 0, b: 0 };
203 if wcag_contrast(white, bg) >= wcag_contrast(black, bg) {
204 white
205 } else {
206 black
207 }
208 }
209
210 /// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
211 pub fn lighten(c: Rgb, delta: f32) -> Rgb {
212 let mut lab = c.to_oklab();
213 lab.l = (lab.l + delta).clamp(0.0, 1.0);
214 Rgb::from_oklab(lab)
215 }
216
217 /// Shift OKLab lightness down by `delta` (perceptually uniform).
218 pub fn darken(c: Rgb, delta: f32) -> Rgb {
219 lighten(c, -delta)
220 }
221
222 /// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
223 pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
224 let (x, y) = (a.to_oklab(), b.to_oklab());
225 Rgb::from_oklab(Oklab {
226 l: x.l + (y.l - x.l) * t,
227 a: x.a + (y.a - x.a) * t,
228 b: x.b + (y.b - x.b) * t,
229 })
230 }
231
232 // ============================================================================
233 // Low-color terminals
234 // ============================================================================
235
236 /// The 16 colors an ANSI terminal addresses by index, in the PC/VGA
237 /// arrangement the Linux console and most emulators start from.
238 ///
239 /// 0-7 are the normal colors and 8-15 the bright ones. Index 7 is a light gray
240 /// rather than white, which is the entry a themed surface usually lands on, and
241 /// index 15 is the true white.
242 ///
243 /// Emulators let the user repaint all sixteen, so this is the standard
244 /// arrangement rather than a promise about any one terminal. The Linux console
245 /// keeps it, which is the case that matters: a console app cannot fall back to
246 /// 24-bit color there.
247 pub const ANSI_16: [Rgb; 16] = [
248 Rgb {
249 r: 0x00,
250 g: 0x00,
251 b: 0x00,
252 },
253 Rgb {
254 r: 0xaa,
255 g: 0x00,
256 b: 0x00,
257 },
258 Rgb {
259 r: 0x00,
260 g: 0xaa,
261 b: 0x00,
262 },
263 Rgb {
264 r: 0xaa,
265 g: 0x55,
266 b: 0x00,
267 },
268 Rgb {
269 r: 0x00,
270 g: 0x00,
271 b: 0xaa,
272 },
273 Rgb {
274 r: 0xaa,
275 g: 0x00,
276 b: 0xaa,
277 },
278 Rgb {
279 r: 0x00,
280 g: 0xaa,
281 b: 0xaa,
282 },
283 Rgb {
284 r: 0xaa,
285 g: 0xaa,
286 b: 0xaa,
287 },
288 Rgb {
289 r: 0x55,
290 g: 0x55,
291 b: 0x55,
292 },
293 Rgb {
294 r: 0xff,
295 g: 0x55,
296 b: 0x55,
297 },
298 Rgb {
299 r: 0x55,
300 g: 0xff,
301 b: 0x55,
302 },
303 Rgb {
304 r: 0xff,
305 g: 0xff,
306 b: 0x55,
307 },
308 Rgb {
309 r: 0x55,
310 g: 0x55,
311 b: 0xff,
312 },
313 Rgb {
314 r: 0xff,
315 g: 0x55,
316 b: 0xff,
317 },
318 Rgb {
319 r: 0x55,
320 g: 0xff,
321 b: 0xff,
322 },
323 Rgb {
324 r: 0xff,
325 g: 0xff,
326 b: 0xff,
327 },
328 ];
329
330 /// The 256 colors an xterm-compatible terminal addresses by index, so that
331 /// entry `i` is what the terminal paints for `38;5;i`.
332 ///
333 /// Three regions, and they are not equally trustworthy. 0-15 are the [`ANSI_16`]
334 /// system colors, which every emulator lets the user repaint. 16-231 are a
335 /// 6x6x6 RGB cube and 232-255 a 24-step gray ramp, and those 240 are fixed.
336 ///
337 /// So a color whose whole job is to be told apart from another should quantize
338 /// against [`ANSI_240`] rather than against this table: a match landing in the
339 /// low sixteen is a match against a color the user may have moved.
340 pub const ANSI_256: [Rgb; 256] = build_ansi_256();
341
342 /// The fixed region of [`ANSI_256`]: the 6x6x6 cube and the gray ramp, without
343 /// the sixteen repaintable system colors.
344 ///
345 /// Quantizing against this returns an index into *this* slice; add
346 /// [`ANSI_240_OFFSET`] to get the index the terminal wants.
347 pub const ANSI_240: &[Rgb] = ANSI_256.split_at(16).1;
348
349 /// What to add to an [`ANSI_240`] index to get an [`ANSI_256`] one.
350 pub const ANSI_240_OFFSET: usize = 16;
351
352 const fn build_ansi_256() -> [Rgb; 256] {
353 let mut table = [Rgb { r: 0, g: 0, b: 0 }; 256];
354
355 let mut i = 0;
356 while i < 16 {
357 table[i] = ANSI_16[i];
358 i += 1;
359 }
360
361 // The cube's six levels are not evenly spaced. The step from black to the
362 // first is more than twice any later one, which is xterm's arrangement
363 // rather than a choice available here, and it is why the darkest tones a
364 // theme can reach on 256 colors come from the gray ramp instead.
365 const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
366 let mut r = 0;
367 while r < 6 {
368 let mut g = 0;
369 while g < 6 {
370 let mut b = 0;
371 while b < 6 {
372 table[16 + 36 * r + 6 * g + b] = Rgb {
373 r: LEVELS[r],
374 g: LEVELS[g],
375 b: LEVELS[b],
376 };
377 b += 1;
378 }
379 g += 1;
380 }
381 r += 1;
382 }
383
384 // 8 to 238 in steps of 10. Neither end is black or white; both of those are
385 // in the cube, so the ramp is 24 steps of gray between them rather than 24
386 // steps of the whole range.
387 let mut k = 0;
388 while k < 24 {
389 let v = 8 + 10 * k as u8;
390 table[232 + k as usize] = Rgb { r: v, g: v, b: v };
391 k += 1;
392 }
393
394 table
395 }
396
397 /// The contrast ratio two colors must clear to read as separate areas.
398 ///
399 /// WCAG 2.x asks 3:1 of user interface components and graphics, which is what
400 /// a border, a rule, or a focus ring is. Text wants more, and a caller drawing
401 /// text can ask for more by checking [`wcag_contrast`] itself.
402 pub const DISTINCT: f32 = 3.0;
403
404 /// Perceptual distance between two colors, for choosing the closest of a set.
405 fn oklab_distance(a: Rgb, b: Rgb) -> f32 {
406 let (x, y) = (a.to_oklab(), b.to_oklab());
407 ((x.l - y.l).powi(2) + (x.a - y.a).powi(2) + (x.b - y.b).powi(2)).sqrt()
408 }
409
410 /// Index of the entry in `palette` that looks most like `c`.
411 ///
412 /// OKLab distance rather than distance in sRGB, for the same reason [`mix`]
413 /// interpolates there: sRGB's numbers are not spaced the way seeing is, so a
414 /// nearest match computed in it picks visibly wrong entries in the mid tones.
415 ///
416 /// # Panics
417 ///
418 /// If `palette` is empty.
419 pub fn quantize(c: Rgb, palette: &[Rgb]) -> usize {
420 assert!(!palette.is_empty(), "a palette needs at least one color");
421 let mut best = 0;
422 let mut best_distance = f32::INFINITY;
423 for (index, entry) in palette.iter().enumerate() {
424 let distance = oklab_distance(c, *entry);
425 if distance < best_distance {
426 best = index;
427 best_distance = distance;
428 }
429 }
430 best
431 }
432
433 /// Index of the entry in `palette` closest to `fg` that still reads against
434 /// `bg`.
435 ///
436 /// [`quantize`] answers about one color at a time, and two colors that differ
437 /// can quantize to the same entry: a themed page and a border drawn on it are
438 /// often a few steps apart in a 24-bit theme and land together on a 16-color
439 /// terminal, leaving one flat area where there was a frame. Alloy's console
440 /// showed exactly this, and it is not a contrived pairing: a light page and the
441 /// mid-tone border derived from it both land on index 7.
442 ///
443 /// So the background is quantized first, because what the border must be
444 /// distinguished from is the entry the terminal will actually paint, not the
445 /// color the theme asked for. Then the nearest entry to `fg` clearing
446 /// [`DISTINCT`] against it wins. When nothing clears it, the entry that gets
447 /// furthest does: at that point the palette cannot honor the design, and the
448 /// most legible approximation beats the closest invisible one.
449 ///
450 /// Only for colors whose whole job is to be told apart from their background.
451 /// Applied to every token it would push a deliberately quiet one until it
452 /// shouted.
453 ///
454 /// # Panics
455 ///
456 /// If `palette` is empty.
457 pub fn quantize_against(fg: Rgb, bg: Rgb, palette: &[Rgb]) -> usize {
458 assert!(!palette.is_empty(), "a palette needs at least one color");
459 let shown = palette[quantize(bg, palette)];
460
461 let mut order: Vec<usize> = (0..palette.len()).collect();
462 order.sort_by(|a, b| {
463 oklab_distance(fg, palette[*a]).total_cmp(&oklab_distance(fg, palette[*b]))
464 });
465
466 order
467 .iter()
468 .copied()
469 .find(|index| wcag_contrast(palette[*index], shown) >= DISTINCT)
470 .unwrap_or_else(|| {
471 order
472 .iter()
473 .copied()
474 .max_by(|a, b| {
475 wcag_contrast(palette[*a], shown).total_cmp(&wcag_contrast(palette[*b], shown))
476 })
477 .expect("the palette is not empty")
478 })
479 }
480
481 // ============================================================================
482 // Intent resolution
483 // ============================================================================
484
485 /// Authored base intents: (TOML dotted source key, canonical token key).
486 /// These are read straight from the theme; the token key is the CSS-var stem
487 /// (`--{token}`) and the `rgb()` lookup key.
488 pub const BASE_INTENTS: &[(&str, &str)] = &[
489 ("surface.page", "surface-page"),
490 ("surface.raised", "surface-raised"),
491 ("surface.sunken", "surface-sunken"),
492 ("surface.overlay", "surface-overlay"),
493 ("content.primary", "content"),
494 ("content.secondary", "content-secondary"),
495 ("content.muted", "content-muted"),
496 ("action.primary", "action"),
497 ("status.danger", "danger"),
498 ("status.success", "success"),
499 ("status.warning", "warning"),
500 ("status.info", "info"),
501 ("line.border", "border"),
502 ("category.one", "category-one"),
503 ("category.two", "category-two"),
504 ("category.three", "category-three"),
505 ("category.four", "category-four"),
506 ("category.five", "category-five"),
507 ("category.six", "category-six"),
508 ];
509
510 /// A fully resolved intent layer: every token key → concrete `#rrggbb`.
511 /// Includes both authored base intents and the computed derived intents.
512 #[derive(Debug, Clone, Serialize)]
513 #[serde(rename_all = "camelCase")]
514 pub struct SemanticTokens {
515 pub meta: ThemeMeta,
516 /// token-key → resolved hex. Stable, deterministic ordering.
517 pub intents: BTreeMap<String, String>,
518 }
519
520 impl SemanticTokens {
521 /// Resolved hex for a token key, if present.
522 pub fn hex(&self, key: &str) -> Option<&str> {
523 self.intents.get(key).map(String::as_str)
524 }
525
526 /// Resolved RGB tuple for a token key (for egui / native consumers).
527 pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
528 self.intents
529 .get(key)
530 .and_then(|h| Rgb::from_hex(h))
531 .map(Rgb::tuple)
532 }
533 }
534
535 /// Resolve an authored theme into the full intent token set.
536 ///
537 /// 1. Copy each present base intent from the authored colors.
538 /// 2. Compute the derived interactive states from the base intents, using the
539 /// same math the apps used to apply individually (so output is identical).
540 ///
541 /// Each derived token is emitted only when its source intents exist, mirroring
542 /// the skip-missing behavior of the rest of the crate.
543 pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
544 let mut intents: BTreeMap<String, String> = BTreeMap::new();
545
546 // 1. Base intents (authored). Copy only values that parse as a hex color and
547 // re-emit them in canonical `#rrggbb` form, so an authored value can never
548 // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
549 // raw into a `<style>` block by the web server). A malformed value is skipped,
550 // mirroring the skip-missing behavior for absent intents.
551 for (src, token) in BASE_INTENTS {
552 if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
553 intents.insert((*token).to_string(), rgb.to_hex());
554 }
555 }
556
557 // Helper: parse an already-resolved token to Rgb.
558 let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));
559
560 // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
561 // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
562 let mut derived: Vec<(String, Rgb)> = Vec::new();
563 if let Some(action) = get(&intents, "action") {
564 derived.push(("action-hover".into(), lighten(action, 0.05)));
565 derived.push(("content-on-action".into(), readable_on(action)));
566 derived.push(("focus-ring".into(), action));
567 }
568 if let Some(page) = get(&intents, "surface-page") {
569 // Modal scrim: a near-black tone carrying a faint hint of the theme's
570 // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
571 // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
572 // it is inserted directly rather than through the hex loop below.
573 let mut o = page.to_oklab();
574 o.l = 0.08;
575 let s = Rgb::from_oklab(o);
576 intents.insert(
577 "overlay".into(),
578 format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b),
579 );
580 }
581 if let Some(raised) = get(&intents, "surface-raised") {
582 // The two edges of a bevel: a raised control is lit from the top left,
583 // so its top and left edges take `bevel-light` and its bottom and right
584 // edges `bevel-dark`. Inverting the pair gives a pressed state and an
585 // inset well, which is what makes the idiom cheap for a consumer.
586 //
587 // Derived here rather than composed per-app because the two webviews
588 // could do it in `color-mix()` and audiofiles, which is egui, could not.
589 // Geometry (thickness, radius, which side gets which) stays app-side.
590 //
591 // The deltas are asymmetric because the eye is: an equal step down reads
592 // as a smaller change than the same step up, so the shadow is cut deeper
593 // than the highlight is raised.
594 //
595 // A face already at the top of the ramp cannot hold a highlight — the
596 // lightening clamps and the control bevels on two sides without ever
597 // resolving as lit. That is a property of the theme, not of this
598 // derivation; `bevel_edges_are_distinct_from_their_face` names the
599 // shipped themes it currently bites.
600 derived.push(("bevel-light".into(), lighten(raised, 0.14)));
601 derived.push(("bevel-dark".into(), darken(raised, 0.18)));
602
603 // An inset well: the content surface inside a raised container, so a
604 // list reads as content in a container rather than as bands on a panel.
605 // `surface-sunken` cannot serve, because a theme is free to author it
606 // darker than raised (goingson does) and a well has to go the other way.
607 //
608 // Which way is "the other way" depends on the theme, and this is the one
609 // derivation here that inverts. A well is lighter than its face on a
610 // light theme and darker on a dark one, where the bevel pair sidesteps
611 // the question by emitting both directions at once.
612 //
613 // Read the direction off `content` rather than off `Variant`. A theme
614 // whose text is dark is a theme whose surfaces are light, whatever its
615 // `variant` field claims, so this resolves correctly even when that
616 // field is wrong and it keeps the branch on measured color rather than
617 // on metadata.
618 //
619 // Deltas are asymmetric for the same reason the bevel's are, and smaller
620 // than the bevel's because a well is an area rather than an edge. The
621 // step up is the specimen's, measured: #D9DDF4 to #F3F5FD is 0.069.
622 //
623 // A face at the top of its ramp cannot hold a lighter well, the same
624 // clamp `bevel-light` hits; `well_is_visible_against_its_face` names the
625 // shipped themes where it bites.
626 if let Some(content) = get(&intents, "content") {
627 let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
628 let well = if content_is_darker {
629 lighten(raised, 0.07)
630 } else {
631 darken(raised, 0.09)
632 };
633 derived.push(("surface-well".into(), well));
634 }
635 }
636 if let Some(sunken) = get(&intents, "surface-sunken") {
637 derived.push(("hover-surface".into(), sunken));
638 }
639 if let Some(border) = get(&intents, "border") {
640 derived.push(("border-strong".into(), darken(border, 0.05)));
641 }
642
643 for (token, rgb) in derived {
644 intents.insert(token, rgb.to_hex());
645 }
646
647 SemanticTokens {
648 meta: theme.meta.clone(),
649 intents,
650 }
651 }
652
653 /// Emit the resolved intent layer as CSS declarations (no selector), one
654 /// ` --token: #hex;` line each, in deterministic (BTreeMap) order.
655 pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
656 let mut out = String::new();
657 for (token, hex) in &tokens.intents {
658 out.push_str(" --");
659 out.push_str(token);
660 out.push_str(": ");
661 out.push_str(hex);
662 out.push_str(";\n");
663 }
664 out
665 }
666
667 /// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
668 /// CSS mapping every web surface injects.
669 pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
670 format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
671 }
672
673 // ============================================================================
674 // Loading / parsing
675 // ============================================================================
676
677 /// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
678 pub fn validate_theme_id(id: &str) -> Result<(), String> {
679 if !id
680 .chars()
681 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
682 {
683 return Err(format!("Invalid theme ID: {id}"));
684 }
685 Ok(())
686 }
687
688 /// Parse the `[meta]` section into `ThemeMeta`.
689 ///
690 /// Falls back to the file ID as the name and `"dark"` as the variant.
691 pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
692 let meta = table.get("meta").and_then(|m| m.as_table());
693 let name = meta
694 .and_then(|m| m.get("name"))
695 .and_then(|v| v.as_str())
696 .unwrap_or(id)
697 .to_string();
698 let variant = meta
699 .and_then(|m| m.get("variant"))
700 .and_then(|v| v.as_str())
701 .unwrap_or("dark")
702 .to_string();
703
704 ThemeMeta {
705 id: id.to_string(),
706 name,
707 variant,
708 is_custom,
709 }
710 }
711
712 // ============================================================================
713 // Choosing a theme.
714 //
715 // The file half of this crate was always shared; the *selection* half was not,
716 // and four apps re-rolled it four ways. GoingsOn stores a "system" sentinel in
717 // localStorage, Balanced Breakfast treats an absent value as follow-the-system
718 // and hardcodes two theme ids as its light/dark pair, audiofiles keeps the id
719 // in a synced SQLite table, and the Alloy console parses COLORFGBG. They also
720 // disagreed about what a variant string means: this crate defaults a missing
721 // one to "dark" while alloy_tui parsed an unrecognized one as light.
722 //
723 // What cannot be shared is the store — localStorage, a synced config table and
724 // a TOML file are genuinely different places. What can be shared, and is here,
725 // is the *meaning*: one vocabulary for variants, one encoding for "what did the
726 // user choose", and one rule for turning that into an id that exists.
727 // ============================================================================
728
729 /// A theme's kind, as declared by `meta.variant`.
730 ///
731 /// Three, not two: one shipped theme is `high-contrast`, and an app that
732 /// matched on light-or-dark alone would quietly file it under the wrong one.
733 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
734 #[serde(rename_all = "kebab-case")]
735 pub enum Variant {
736 Light,
737 Dark,
738 HighContrast,
739 }
740
741 impl Variant {
742 /// The spelling used in a theme file and in [`ThemeMeta::variant`].
743 #[must_use]
744 pub const fn as_str(self) -> &'static str {
745 match self {
746 Variant::Light => "light",
747 Variant::Dark => "dark",
748 Variant::HighContrast => "high-contrast",
749 }
750 }
751
752 /// Read a variant string, or `None` if it names none of them.
753 #[must_use]
754 pub fn parse(raw: &str) -> Option<Self> {
755 match raw {
756 "light" => Some(Variant::Light),
757 "dark" => Some(Variant::Dark),
758 "high-contrast" => Some(Variant::HighContrast),
759 _ => None,
760 }
761 }
762 }
763
764 impl std::fmt::Display for Variant {
765 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
766 f.write_str(self.as_str())
767 }
768 }
769
770 /// Anything unrecognized reads as dark, which is what [`parse_meta`] already
771 /// does with a missing one. Consumers that guessed light for an unknown string
772 /// were disagreeing with the crate that produced it.
773 impl From<&str> for Variant {
774 fn from(raw: &str) -> Self {
775 Variant::parse(raw).unwrap_or(Variant::Dark)
776 }
777 }
778
779 impl ThemeMeta {
780 /// This theme's variant as a value rather than a string.
781 #[must_use]
782 pub fn kind(&self) -> Variant {
783 Variant::from(self.variant.as_str())
784 }
785 }
786
787 /// The spelling of "follow whatever the system is doing", in every store.
788 pub const FOLLOW: &str = "system";
789
790 /// What the user chose, as opposed to what is being rendered.
791 ///
792 /// The distinction is the whole point: `Follow` is a standing instruction that
793 /// resolves differently as the ambient mode changes, and a `Fixed` id is an
794 /// answer that does not. An app that stored only the rendered id could not tell
795 /// the two apart the next time the system flipped to dark.
796 #[derive(Debug, Clone, PartialEq, Eq, Default)]
797 pub enum ThemeSelection {
798 /// Track the ambient light/dark mode.
799 #[default]
800 Follow,
801 /// Always this theme.
802 Fixed(String),
803 }
804
805 impl ThemeSelection {
806 /// Read a stored selection. An empty or absent value is [`Follow`], which
807 /// is what an app with nothing saved yet should do.
808 ///
809 /// [`Follow`]: ThemeSelection::Follow
810 #[must_use]
811 pub fn parse(raw: Option<&str>) -> Self {
812 match raw.map(str::trim) {
813 None | Some("" | FOLLOW) => ThemeSelection::Follow,
814 Some(id) => ThemeSelection::Fixed(id.to_string()),
815 }
816 }
817
818 /// The string to persist, whatever the store is.
819 #[must_use]
820 pub fn as_str(&self) -> &str {
821 match self {
822 ThemeSelection::Follow => FOLLOW,
823 ThemeSelection::Fixed(id) => id,
824 }
825 }
826
827 /// Turn a selection into a theme id that exists.
828 ///
829 /// `ambient` is the light/dark mode the app learned however it can: a
830 /// `prefers-color-scheme` media query, an OS appearance API, `COLORFGBG`
831 /// from a terminal. `available` is what [`list_themes_from_dirs`] found.
832 ///
833 /// A `Fixed` id that is no longer on disk falls through to the same path as
834 /// `Follow` rather than being returned anyway. Themes are deletable in
835 /// three of the four apps, and handing back an id that will fail to load
836 /// only moves the error somewhere less helpful.
837 ///
838 /// The fallback chain is: the app's own default for the ambient mode if it
839 /// is installed, then any installed theme of that variant, then the app's
840 /// default regardless. The last step means this always returns something,
841 /// and an app with no theme directory at all gets the id it ships with and
842 /// the load error it would have had anyway.
843 #[must_use]
844 pub fn resolve(
845 &self,
846 ambient: Variant,
847 defaults: &ThemeDefaults,
848 available: &[ThemeMeta],
849 ) -> String {
850 let installed = |id: &str| available.iter().any(|meta| meta.id == id);
851
852 if let ThemeSelection::Fixed(id) = self
853 && installed(id)
854 {
855 return id.clone();
856 }
857
858 let preferred = defaults.for_variant(ambient);
859 if installed(preferred) {
860 return preferred.to_string();
861 }
862 available
863 .iter()
864 .find(|meta| meta.kind() == ambient)
865 .map_or_else(|| preferred.to_string(), |meta| meta.id.clone())
866 }
867 }
868
869 impl std::fmt::Display for ThemeSelection {
870 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
871 f.write_str(self.as_str())
872 }
873 }
874
875 /// The themes an app falls back to, one per ambient mode.
876 ///
877 /// App-specific on purpose: which theme is "the app's own" is the app's
878 /// identity, not this crate's business. What is shared is everything around it.
879 #[derive(Debug, Clone)]
880 pub struct ThemeDefaults {
881 light: String,
882 dark: String,
883 high_contrast: Option<String>,
884 }
885
886 impl ThemeDefaults {
887 pub fn new(light: impl Into<String>, dark: impl Into<String>) -> Self {
888 Self {
889 light: light.into(),
890 dark: dark.into(),
891 high_contrast: None,
892 }
893 }
894
895 /// Name a theme for a high-contrast ambient mode. Without one, that mode
896 /// falls back to the dark default, which is the safer of the two to read.
897 #[must_use]
898 pub fn high_contrast(mut self, id: impl Into<String>) -> Self {
899 self.high_contrast = Some(id.into());
900 self
901 }
902
903 #[must_use]
904 pub fn for_variant(&self, variant: Variant) -> &str {
905 match variant {
906 Variant::Light => &self.light,
907 Variant::Dark => &self.dark,
908 Variant::HighContrast => self.high_contrast.as_ref().unwrap_or(&self.dark),
909 }
910 }
911 }
912
913 // ============================================================================
914 // Where themes are looked for.
915 //
916 // Four apps built this vector by hand, two of them byte-for-byte identically,
917 // and one of them built it backwards: the Alloy console pushed the user's own
918 // directory first, under a comment saying "highest precedence first", when both
919 // consumers of the vector resolve *last* wins. A user's custom theme lost to
920 // the packaged one of the same id.
921 //
922 // Hence a builder that names the tiers rather than a function taking a vector.
923 // The precedence is stated once, here, and a caller cannot express it backwards
924 // because the order is not theirs to choose.
925 // ============================================================================
926
927 /// Builds the search path [`load_theme`] and [`list_themes_from_dirs`] take.
928 ///
929 /// Tiers are added in whatever order is convenient and always end up in
930 /// precedence order: the user's own themes win, then whatever the system
931 /// ships, then whatever the app bundles.
932 ///
933 /// A directory that does not exist is dropped rather than carried, so callers
934 /// can offer every tier they might have without checking each one.
935 #[derive(Debug, Default, Clone)]
936 pub struct ThemeDirs {
937 bundled: Vec<PathBuf>,
938 system: Vec<PathBuf>,
939 custom: Option<PathBuf>,
940 }
941
942 impl ThemeDirs {
943 #[must_use]
944 pub fn new() -> Self {
945 Self::default()
946 }
947
948 /// Themes the app ships with. Lowest precedence.
949 ///
950 /// Takes more than one because a Tauri app has two: the bundled resource
951 /// directory in production, and the tree `build.rs` materialized for a
952 /// `cargo run` that has no resource directory at all.
953 #[must_use]
954 pub fn bundled(mut self, dir: Option<PathBuf>) -> Self {
955 self.bundled.extend(dir);
956 self
957 }
958
959 /// Themes the machine ships, from an image or a package. Overrides bundled.
960 #[must_use]
961 pub fn system(mut self, dir: Option<PathBuf>) -> Self {
962 self.system.extend(dir);
963 self
964 }
965
966 /// The user's own themes. Highest precedence, and the only tier flagged
967 /// custom, which is what makes them exportable and deletable.
968 #[must_use]
969 pub fn custom(mut self, dir: Option<PathBuf>) -> Self {
970 self.custom = dir;
971 self
972 }
973
974 /// The search path, lowest precedence first.
975 #[must_use]
976 pub fn build(self) -> Vec<(PathBuf, bool)> {
977 let mut dirs = Vec::new();
978 for dir in self.bundled.into_iter().chain(self.system) {
979 if dir.is_dir() {
980 dirs.push((dir, false));
981 }
982 }
983 if let Some(dir) = self.custom
984 && dir.is_dir()
985 {
986 dirs.push((dir, true));
987 }
988 dirs
989 }
990 }
991
992 /// Extract the intent color sections into a flat `HashMap` with dotted keys
993 /// like `"surface.page"`, `"status.danger"`, `"category.one"`.
994 pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
995 let mut colors = HashMap::new();
996 for section in COLOR_SECTIONS {
997 if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
998 for (key, val) in sect {
999 if let Some(color) = val.as_str() {
1000 colors.insert(format!("{section}.{key}"), color.to_string());
1001 }
1002 }
1003 }
1004 }
1005 colors
1006 }
1007
1008 /// Scan directories for `.toml` theme files and return metadata for each.
1009 ///
1010 /// Directories are checked in order; later entries override earlier ones by ID.
1011 /// Each entry in `dirs` is `(path, is_custom)`.
1012 pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
1013 let mut seen: HashMap<String, ThemeMeta> = HashMap::new();
1014
1015 for (dir, is_custom) in dirs {
1016 let Ok(entries) = std::fs::read_dir(dir) else {
1017 continue;
1018 };
1019
1020 for entry in entries {
1021 let Ok(entry) = entry else {
1022 continue;
1023 };
1024 let path = entry.path();
1025 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1026 continue;
1027 }
1028
1029 let id = path
1030 .file_stem()
1031 .and_then(|s| s.to_str())
1032 .unwrap_or_default()
1033 .to_string();
1034
1035 let Ok(content) = std::fs::read_to_string(&path) else {
1036 continue;
1037 };
1038 let table: toml::Table = match content.parse() {
1039 Ok(t) => t,
1040 Err(_) => continue,
1041 };
1042
1043 seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
1044 }
1045 }
1046
1047 let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
1048 themes.sort_by(|a, b| a.name.cmp(&b.name));
1049 themes
1050 }
1051
1052 /// Find a theme file by ID in the given directories.
1053 ///
1054 /// Checks directories in reverse order so the highest-priority directory wins.
1055 /// Returns `(path, is_custom)` or `None` if not found.
1056 pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
1057 let filename = format!("{id}.toml");
1058
1059 for (dir, is_custom) in dirs.iter().rev() {
1060 let path = dir.join(&filename);
1061 if path.is_file() {
1062 return Some((path, *is_custom));
1063 }
1064 }
1065
1066 None
1067 }
1068
1069 /// Parse a complete theme (metadata + colors) from raw TOML content, with no
1070 /// filesystem access. For callers that embed themes at compile time.
1071 pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
1072 validate_theme_id(id)?;
1073 let table: toml::Table = content
1074 .parse()
1075 .map_err(|e| format!("Failed to parse theme '{id}': {e}"))?;
1076 let meta = parse_meta(id, &table, is_custom);
1077 let colors = extract_colors(&table);
1078 Ok(ThemeColors { meta, colors })
1079 }
1080
1081 /// Load a complete theme (metadata + colors) by ID from the given directories.
1082 pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
1083 validate_theme_id(id)?;
1084
1085 let (path, is_custom) =
1086 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1087
1088 let content = std::fs::read_to_string(&path)
1089 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1090
1091 let table: toml::Table = content
1092 .parse()
1093 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1094
1095 let meta = parse_meta(id, &table, is_custom);
1096 let colors = extract_colors(&table);
1097
1098 Ok(ThemeColors { meta, colors })
1099 }
1100
1101 /// Load a theme and resolve it to the full intent token set in one step.
1102 pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
1103 Ok(resolve(&load_theme(dirs, id)?))
1104 }
1105
1106 /// Import a theme TOML file into the custom themes directory.
1107 ///
1108 /// Validates that the file is parseable TOML with at least one intent color
1109 /// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
1110 pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
1111 let content = std::fs::read_to_string(source_path)
1112 .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;
1113
1114 let table: toml::Table = content.parse().map_err(|e| format!("Invalid TOML: {e}"))?;
1115
1116 let has_colors = COLOR_SECTIONS
1117 .iter()
1118 .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
1119 if !has_colors {
1120 return Err(format!(
1121 "Theme file must have at least one color section ({})",
1122 COLOR_SECTIONS.join(", ")
1123 ));
1124 }
1125
1126 let id = source_path
1127 .file_stem()
1128 .and_then(|s| s.to_str())
1129 .ok_or("Invalid file name")?
1130 .to_string();
1131 validate_theme_id(&id)?;
1132
1133 std::fs::create_dir_all(custom_dir)
1134 .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;
1135
1136 let dest = custom_dir.join(format!("{id}.toml"));
1137 std::fs::copy(source_path, &dest).map_err(|e| format!("Failed to copy theme: {e}"))?;
1138
1139 Ok(parse_meta(&id, &table, true))
1140 }
1141
1142 /// Delete a custom theme by ID.
1143 ///
1144 /// Only operates on `custom_dir` — bundled themes are not deletable through
1145 /// this entry point.
1146 pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
1147 validate_theme_id(id)?;
1148
1149 let path = custom_dir.join(format!("{id}.toml"));
1150 if !path.is_file() {
1151 return Err(format!("Custom theme '{id}' not found"));
1152 }
1153
1154 std::fs::remove_file(&path).map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
1155 }
1156
1157 /// A four-color preview for theme thumbnails: the representative swatch from
1158 /// each of the principal roles.
1159 #[derive(Debug, Clone, Serialize)]
1160 #[serde(rename_all = "camelCase")]
1161 pub struct ThemePreview {
1162 pub meta: ThemeMeta,
1163 /// Page background (`surface.page`).
1164 pub background: Option<String>,
1165 /// Body text (`content.primary`).
1166 pub foreground: Option<String>,
1167 /// Brand/interactive color (`action.primary`).
1168 pub accent: Option<String>,
1169 /// Divider/outline color (`line.border`).
1170 pub border: Option<String>,
1171 }
1172
1173 fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
1174 table
1175 .get(section)
1176 .and_then(|s| s.as_table())
1177 .and_then(|s| s.get(key))
1178 .and_then(|v| v.as_str())
1179 .map(std::string::ToString::to_string)
1180 }
1181
1182 /// Load just the preview swatches for a theme — for UI thumbnails.
1183 pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
1184 validate_theme_id(id)?;
1185
1186 let (path, is_custom) =
1187 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1188
1189 let content = std::fs::read_to_string(&path)
1190 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
1191
1192 let table: toml::Table = content
1193 .parse()
1194 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
1195
1196 Ok(ThemePreview {
1197 meta: parse_meta(id, &table, is_custom),
1198 background: color_at(&table, "surface", "page"),
1199 foreground: color_at(&table, "content", "primary"),
1200 accent: color_at(&table, "action", "primary"),
1201 border: color_at(&table, "line", "border"),
1202 })
1203 }
1204
1205 /// Export a theme to a user-chosen path.
1206 pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
1207 validate_theme_id(id)?;
1208
1209 let (source, _) = find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
1210
1211 std::fs::copy(&source, dest_path).map_err(|e| format!("Failed to export theme: {e}"))?;
1212
1213 Ok(())
1214 }
1215
1216 /// The themes this crate ships, embedded at compile time.
1217 ///
1218 /// `include_dir` is an implementation detail: the public API hands back plain
1219 /// `(id, toml_source)` pairs, so how the data is embedded can change without
1220 /// a breaking release.
1221 static EMBEDDED: include_dir::Dir<'static> =
1222 include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");
1223
1224 /// The themes this crate ships, as `(id, toml_source)` pairs.
1225 ///
1226 /// This is the path-free way to reach the bundled set, for consumers that
1227 /// cannot rely on a directory existing at runtime: a crate pulled from
1228 /// crates.io lives in a registry checkout whose location is not knowable at
1229 /// compile time, so `include_dir!` and asset-bundling globs in the depending
1230 /// crate have nothing stable to point at. Embedding here and re-exporting the
1231 /// contents gives them one source of truth without a path.
1232 ///
1233 /// Ordering follows the embedded directory and is not guaranteed; collect and
1234 /// sort by id where a stable order matters (a theme picker, say).
1235 pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
1236 EMBEDDED.files().filter_map(|file| {
1237 let path = file.path();
1238 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
1239 return None;
1240 }
1241 let id = path.file_stem()?.to_str()?;
1242 Some((id, file.contents_utf8()?))
1243 })
1244 }
1245
1246 /// The theme directory this crate ships, for use as a build-from-source
1247 /// fallback.
1248 ///
1249 /// Resolves against `makeover`'s own manifest directory, fixed at compile
1250 /// time, so it works from a path dependency and from a cargo git checkout
1251 /// alike. Installed systems should put their packaged theme directory ahead
1252 /// of this in the search path; this is the entry that keeps `cargo run` in a
1253 /// fresh clone from coming up with no themes at all.
1254 ///
1255 /// Returns `None` when the directory is absent — a cargo cache that has been
1256 /// cleaned, or a vendored copy that dropped the data — so callers degrade to
1257 /// their remaining search path rather than failing.
1258 pub fn bundled_themes_dir() -> Option<PathBuf> {
1259 let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
1260 if themes.is_dir() { Some(themes) } else { None }
1261 }
1262
1263 #[cfg(test)]
1264 mod tests {
1265 use super::*;
1266 use std::fs;
1267
1268 // ---- id validation ----
1269
1270 #[test]
1271 fn validate_theme_id_alphanumeric() {
1272 assert!(validate_theme_id("darkmode").is_ok());
1273 assert!(validate_theme_id("Theme123").is_ok());
1274 }
1275
1276 #[test]
1277 fn validate_theme_id_hyphens_underscores() {
1278 assert!(validate_theme_id("dark-mode").is_ok());
1279 assert!(validate_theme_id("my_theme_v2").is_ok());
1280 }
1281
1282 #[test]
1283 fn validate_theme_id_rejects_path_traversal() {
1284 assert!(validate_theme_id("../etc/passwd").is_err());
1285 assert!(validate_theme_id("foo/bar").is_err());
1286 assert!(validate_theme_id("theme.toml").is_err());
1287 }
1288
1289 // ---- low-color terminals ----
1290
1291 #[test]
1292 fn the_ansi_palette_is_sixteen_distinct_colors() {
1293 let mut seen: Vec<(u8, u8, u8)> = ANSI_16.iter().map(|c| c.tuple()).collect();
1294 seen.sort_unstable();
1295 seen.dedup();
1296 assert_eq!(seen.len(), 16);
1297 }
1298
1299 #[test]
1300 fn quantize_picks_the_obvious_entry() {
1301 let black = Rgb { r: 0, g: 0, b: 0 };
1302 let white = Rgb {
1303 r: 255,
1304 g: 255,
1305 b: 255,
1306 };
1307 assert_eq!(quantize(black, &ANSI_16), 0);
1308 assert_eq!(quantize(white, &ANSI_16), 15);
1309 }
1310
1311 // Nearest-entry quantization is per-color, so two colors a theme keeps
1312 // apart can arrive as one. These two are both closest to the palette's
1313 // light gray, and a border drawn in one on a page painted the other is not
1314 // drawn at all.
1315 #[test]
1316 fn two_colors_can_quantize_to_one_entry() {
1317 let page = Rgb::from_hex("#a8a8a8").unwrap();
1318 let border = Rgb::from_hex("#b4b4b4").unwrap();
1319
1320 assert_eq!(quantize(page, &ANSI_16), quantize(border, &ANSI_16));
1321 assert!(quantize_against(border, page, &ANSI_16) != quantize(page, &ANSI_16));
1322 }
1323
1324 #[test]
1325 fn quantize_against_keeps_the_border_off_the_page() {
1326 let page = Rgb::from_hex("#e4ded6").unwrap();
1327 let border = Rgb::from_hex("#7f786d").unwrap();
1328
1329 let shown_page = ANSI_16[quantize(page, &ANSI_16)];
1330 let shown_border = ANSI_16[quantize_against(border, page, &ANSI_16)];
1331
1332 assert!(
1333 wcag_contrast(shown_border, shown_page) >= DISTINCT,
1334 "border {} on page {} is {:.2}:1",
1335 shown_border.to_hex(),
1336 shown_page.to_hex(),
1337 wcag_contrast(shown_border, shown_page)
1338 );
1339 }
1340
1341 // A color that already reads against its background is left where it is,
1342 // so this can be applied without redesigning what already worked.
1343 #[test]
1344 fn quantize_against_leaves_a_readable_color_alone() {
1345 let page = Rgb::from_hex("#e4ded6").unwrap();
1346 let text = Rgb::from_hex("#1a1816").unwrap();
1347
1348 assert_eq!(
1349 quantize_against(text, page, &ANSI_16),
1350 quantize(text, &ANSI_16)
1351 );
1352 }
1353
1354 // With nothing in the palette to satisfy the request, the most legible
1355 // entry is the answer. Returning the nearest one would return the
1356 // background itself, which is the failure this function exists to avoid.
1357 #[test]
1358 fn an_impossible_palette_gets_the_most_legible_entry() {
1359 let page = Rgb::from_hex("#ffffff").unwrap();
1360 let border = Rgb::from_hex("#fefefe").unwrap();
1361 let palette = [
1362 Rgb::from_hex("#ffffff").unwrap(),
1363 Rgb::from_hex("#fdfdfd").unwrap(),
1364 ];
1365
1366 let chosen = palette[quantize_against(border, page, &palette)];
1367 assert_eq!(chosen.to_hex(), "#fdfdfd");
1368 }
1369
1370 // ---- meta ----
1371
1372 #[test]
1373 fn parse_meta_with_name_and_variant() {
1374 let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
1375 .parse()
1376 .unwrap();
1377 let meta = parse_meta("nord", &table, false);
1378 assert_eq!(meta.id, "nord");
1379 assert_eq!(meta.name, "Nord");
1380 assert_eq!(meta.variant, "light");
1381 assert!(!meta.is_custom);
1382 }
1383
1384 #[test]
1385 fn parse_meta_defaults_to_id_and_dark() {
1386 let table: toml::Table = "".parse().unwrap();
1387 let meta = parse_meta("fallback", &table, true);
1388 assert_eq!(meta.name, "fallback");
1389 assert_eq!(meta.variant, "dark");
1390 assert!(meta.is_custom);
1391 }
1392
1393 // ---- color math (formulas must match the apps they came from) ----
1394
1395 #[test]
1396 fn rgb_hex_roundtrip() {
1397 assert_eq!(
1398 Rgb::from_hex("#6196FF").unwrap(),
1399 Rgb {
1400 r: 0x61,
1401 g: 0x96,
1402 b: 0xff
1403 }
1404 );
1405 assert_eq!(
1406 Rgb::from_hex("#abc").unwrap(),
1407 Rgb {
1408 r: 0xaa,
1409 g: 0xbb,
1410 b: 0xcc
1411 }
1412 );
1413 assert_eq!(
1414 Rgb {
1415 r: 0x61,
1416 g: 0x96,
1417 b: 0xff
1418 }
1419 .to_hex(),
1420 "#6196ff"
1421 );
1422 assert!(Rgb::from_hex("not-a-color").is_none());
1423 }
1424
1425 #[test]
1426 fn oklab_roundtrips_within_tolerance() {
1427 for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
1428 let c = Rgb::from_hex(hex).unwrap();
1429 let back = Rgb::from_oklab(c.to_oklab());
1430 // Gamut round-trip is near-exact (±1 per channel from rounding).
1431 assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
1432 assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
1433 assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
1434 }
1435 }
1436
1437 #[test]
1438 fn wcag_contrast_known_pairs() {
1439 let white = Rgb {
1440 r: 255,
1441 g: 255,
1442 b: 255,
1443 };
1444 let black = Rgb { r: 0, g: 0, b: 0 };
1445 assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
1446 assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
1447 }
1448
1449 #[test]
1450 fn readable_on_picks_by_wcag() {
1451 assert_eq!(
1452 readable_on(Rgb {
1453 r: 255,
1454 g: 255,
1455 b: 255
1456 }),
1457 Rgb { r: 0, g: 0, b: 0 }
1458 );
1459 assert_eq!(
1460 readable_on(Rgb { r: 0, g: 0, b: 0 }),
1461 Rgb {
1462 r: 255,
1463 g: 255,
1464 b: 255
1465 }
1466 );
1467 // A light blue action -> black text reads better.
1468 let action = Rgb::from_hex("#6196ff").unwrap();
1469 assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
1470 }
1471
1472 #[test]
1473 fn lighten_darken_move_oklab_lightness() {
1474 let c = Rgb::from_hex("#6196ff").unwrap();
1475 let l0 = c.to_oklab().l;
1476 assert!(lighten(c, 0.05).to_oklab().l > l0);
1477 assert!(darken(c, 0.05).to_oklab().l < l0);
1478 }
1479
1480 #[test]
1481 fn mix_endpoints_and_midpoint() {
1482 let a = Rgb::from_hex("#000000").unwrap();
1483 let b = Rgb::from_hex("#6196ff").unwrap();
1484 assert_eq!(mix(a, b, 0.0), a);
1485 assert_eq!(mix(a, b, 1.0), b);
1486 // Midpoint sits between the endpoints in OKLab lightness.
1487 let mid = mix(a, b, 0.5).to_oklab().l;
1488 assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
1489 }
1490
1491 // ---- extract + resolve ----
1492
1493 fn nord_toml() -> &'static str {
1494 r##"
1495 [meta]
1496 name = "Nord"
1497 variant = "dark"
1498
1499 [surface]
1500 page = "#2e3440"
1501 raised = "#3b4252"
1502 sunken = "#434c5e"
1503 overlay = "#3b4252"
1504
1505 [content]
1506 primary = "#d8dee9"
1507 secondary = "#e5e9f0"
1508 muted = "#616e88"
1509
1510 [action]
1511 primary = "#81a1c1"
1512
1513 [status]
1514 danger = "#bf616a"
1515 success = "#a3be8c"
1516 warning = "#ebcb8b"
1517 info = "#88c0d0"
1518
1519 [line]
1520 border = "#4c566a"
1521
1522 [category]
1523 one = "#bf616a"
1524 two = "#a3be8c"
1525 three = "#81a1c1"
1526 four = "#ebcb8b"
1527 five = "#b48ead"
1528 six = "#88c0d0"
1529 "##
1530 }
1531
1532 #[test]
1533 fn extract_colors_reads_intent_sections() {
1534 let table: toml::Table = nord_toml().parse().unwrap();
1535 let colors = extract_colors(&table);
1536 assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
1537 assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
1538 assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
1539 assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
1540 assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
1541 assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
1542 assert_eq!(colors.len(), 19);
1543 }
1544
1545 #[test]
1546 fn resolve_base_intents_passthrough() {
1547 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1548 let t = resolve(&theme);
1549 assert_eq!(t.hex("surface-page"), Some("#2e3440"));
1550 assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
1551 assert_eq!(t.hex("content-muted"), Some("#616e88"));
1552 assert_eq!(t.hex("action"), Some("#81a1c1"));
1553 assert_eq!(t.hex("danger"), Some("#bf616a"));
1554 assert_eq!(t.hex("border"), Some("#4c566a"));
1555 assert_eq!(t.hex("category-five"), Some("#b48ead"));
1556 }
1557
1558 #[test]
1559 fn resolve_derived_intents() {
1560 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1561 let t = resolve(&theme);
1562 let action = Rgb::from_hex("#81a1c1").unwrap();
1563 let page = Rgb::from_hex("#2e3440").unwrap();
1564 let _ = page;
1565 assert_eq!(
1566 t.hex("action-hover").unwrap(),
1567 lighten(action, 0.05).to_hex()
1568 );
1569 assert_eq!(
1570 t.hex("content-on-action").unwrap(),
1571 readable_on(action).to_hex()
1572 );
1573 assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
1574 assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
1575 // Pruned by the usage audit (0 consumers): action-active, the *-surface
1576 // tints, selection, row-stripe. Apps that need them derive inline via
1577 // the shared mix().
1578 assert!(t.hex("action-active").is_none());
1579 assert!(t.hex("danger-surface").is_none());
1580 assert!(t.hex("selection").is_none());
1581 assert!(t.hex("row-stripe").is_none());
1582 }
1583
1584 #[test]
1585 fn resolve_bevel_intents() {
1586 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1587 let t = resolve(&theme);
1588 let raised = Rgb::from_hex("#3b4252").unwrap();
1589 assert_eq!(
1590 t.hex("bevel-light").unwrap(),
1591 lighten(raised, 0.14).to_hex()
1592 );
1593 assert_eq!(t.hex("bevel-dark").unwrap(), darken(raised, 0.18).to_hex());
1594 }
1595
1596 // A bevel is two edges around one face, so both edges have to be visibly off
1597 // that face or the control never resolves as lit. The lightening clamps at
1598 // the top of the ramp, which means a theme authoring a white raised surface
1599 // gets a highlight identical to the surface it is meant to sit on.
1600 //
1601 // The list is asserted rather than merely reported so that changing a theme
1602 // has to come here and say so. Shrinking it is the fix; growing it is a
1603 // regression in the theme, not in this derivation.
1604 #[test]
1605 fn bevel_edges_are_distinct_from_their_face() {
1606 const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];
1607
1608 let mut degenerate: Vec<String> = Vec::new();
1609 for (id, source) in embedded_themes() {
1610 let theme = parse_theme_str(id, source, false).unwrap();
1611 let t = resolve(&theme);
1612 let Some(raised) = t.hex("surface-raised") else {
1613 continue;
1614 };
1615 let light = t.hex("bevel-light").expect("raised implies bevel-light");
1616 let dark = t.hex("bevel-dark").expect("raised implies bevel-dark");
1617 if light == raised || dark == raised {
1618 degenerate.push(id.to_string());
1619 }
1620 }
1621 degenerate.sort();
1622
1623 assert_eq!(
1624 degenerate, CANNOT_BEVEL,
1625 "themes whose raised surface cannot hold both bevel edges"
1626 );
1627 }
1628
1629 // The well inverts by theme, so assert both directions explicitly rather
1630 // than only the one the light themes happen to take.
1631 #[test]
1632 fn resolve_well_intent_follows_the_content_direction() {
1633 // nord is dark: light text on a dark raised surface, so the well goes
1634 // down and away from the text.
1635 let dark = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
1636 let dark_raised = Rgb::from_hex("#3b4252").unwrap();
1637 assert_eq!(
1638 dark.hex("surface-well").unwrap(),
1639 darken(dark_raised, 0.09).to_hex()
1640 );
1641
1642 // The shipped light themes take the other branch.
1643 let goingson = embedded_themes()
1644 .into_iter()
1645 .find(|(id, _)| *id == "goingson")
1646 .expect("goingson is embedded")
1647 .1;
1648 let light = resolve(&parse_theme_str("goingson", goingson, false).unwrap());
1649 let light_raised = light
1650 .hex("surface-raised")
1651 .and_then(Rgb::from_hex)
1652 .expect("goingson authors a raised surface");
1653 assert_eq!(
1654 light.hex("surface-well").unwrap(),
1655 lighten(light_raised, 0.07).to_hex()
1656 );
1657 }
1658
1659 // A well is a fill, not an edge, so the only thing that makes it read is
1660 // being a different color from the surface it is cut into.
1661 //
1662 // Same shape and the same asserted-list discipline as
1663 // `bevel_edges_are_distinct_from_their_face`, and it bites the same two
1664 // themes for the same reason: a raised surface already at the top of the
1665 // ramp has nothing lighter to go to.
1666 #[test]
1667 fn well_is_distinct_from_its_face() {
1668 const CANNOT_WELL: &[&str] = &["neobrute", "oxocarbon-light"];
1669
1670 let mut degenerate: Vec<String> = Vec::new();
1671 for (id, source) in embedded_themes() {
1672 let theme = parse_theme_str(id, source, false).unwrap();
1673 let t = resolve(&theme);
1674 let Some(raised) = t.hex("surface-raised") else {
1675 continue;
1676 };
1677 let well = t.hex("surface-well").expect("raised implies surface-well");
1678 if well == raised {
1679 degenerate.push(id.to_string());
1680 }
1681 }
1682 degenerate.sort();
1683
1684 assert_eq!(
1685 degenerate, CANNOT_WELL,
1686 "themes whose raised surface cannot hold a well"
1687 );
1688 }
1689
1690 // Distinct is not the same as visible. A face near the top of the ramp
1691 // clamps partway rather than exactly, which yields a well that differs from
1692 // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
1693 // authors raised at L=0.987 and gets 0.009 of the 0.07 it asked for.
1694 //
1695 // Worth a separate test from the one above because the fix differs: an
1696 // exactly-degenerate theme needs its raised surface off the ramp end, while
1697 // these need it merely lowered. Both fixes are the theme's, not this
1698 // derivation's, which is why the list is asserted rather than warned about.
1699 #[test]
1700 fn well_is_visible_against_its_face() {
1701 // Below this, the well and its face are the same surface to a reader.
1702 const MIN_DELTA_L: f32 = 0.02;
1703 const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] =
1704 &["neobrute", "oxocarbon-light", "rosepine-dawn"];
1705
1706 let mut invisible: Vec<String> = Vec::new();
1707 for (id, source) in embedded_themes() {
1708 let theme = parse_theme_str(id, source, false).unwrap();
1709 let t = resolve(&theme);
1710 let (Some(raised), Some(well)) = (
1711 t.hex("surface-raised").and_then(Rgb::from_hex),
1712 t.hex("surface-well").and_then(Rgb::from_hex),
1713 ) else {
1714 continue;
1715 };
1716 if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_DELTA_L {
1717 invisible.push(id.to_string());
1718 }
1719 }
1720 invisible.sort();
1721
1722 assert_eq!(
1723 invisible, CANNOT_HOLD_A_VISIBLE_WELL,
1724 "themes whose well is too close to its face to read as one"
1725 );
1726 }
1727
1728 // What the bevel pair does on a sixteen-color terminal, measured across the
1729 // shipped set rather than assumed. Two results, both load-bearing for a
1730 // consumer that has to render one there.
1731 //
1732 // Exactly one edge survives, never both. A raised face quantizes onto one of
1733 // the palette's three grays, and the palette is too coarse to hold anything
1734 // between that entry and its neighbour, so whichever edge is pushed toward
1735 // the end of the ramp the face already sits on lands back on the face. Light
1736 // themes and most dark ones keep the shadow and lose the highlight; a face
1737 // that quantizes to black keeps the highlight and loses the shadow.
1738 //
1739 // So a low-color consumer draws the single edge it can render, on the side
1740 // the palette left it, rather than a bevel that resolves on two sides.
1741 //
1742 // And `quantize_against` is the wrong function for this pair, though it is
1743 // the right one for a border. It answers "nearest entry that clears DISTINCT
1744 // against the background", which has no notion of direction, so both edges
1745 // are pushed onto the same contrasting entry and the bevel inverts on one
1746 // side. Plain `quantize` keeps them apart and in the right order.
1747 #[test]
1748 fn a_sixteen_color_terminal_gets_one_bevel_edge_and_not_two() {
1749 for (id, source) in embedded_themes() {
1750 let theme = parse_theme_str(id, source, false).unwrap();
1751 let t = resolve(&theme);
1752 let (Some(face), Some(light), Some(dark)) = (
1753 t.hex("surface-raised").and_then(Rgb::from_hex),
1754 t.hex("bevel-light").and_then(Rgb::from_hex),
1755 t.hex("bevel-dark").and_then(Rgb::from_hex),
1756 ) else {
1757 continue;
1758 };
1759
1760 let face_index = quantize(face, &ANSI_16);
1761 let light_survives = quantize(light, &ANSI_16) != face_index;
1762 let dark_survives = quantize(dark, &ANSI_16) != face_index;
1763 assert!(
1764 light_survives != dark_survives,
1765 "{id}: expected exactly one bevel edge to survive 16 colors, \
1766 highlight {light_survives} shadow {dark_survives}"
1767 );
1768
1769 // Direction-blind, so it collapses the pair it is asked to separate.
1770 assert_eq!(
1771 quantize_against(light, face, &ANSI_16),
1772 quantize_against(dark, face, &ANSI_16),
1773 "{id}: quantize_against is expected to be unusable for a bevel pair"
1774 );
1775 }
1776 }
1777
1778 // 256 colors is where the bevel starts working. At 16 every shipped theme
1779 // loses an edge; here all but the five whose raised surface sits at the very
1780 // top of the ramp keep both, and those five fail for the reason they fail in
1781 // truecolor rather than for a palette reason.
1782 //
1783 // Three of them cannot bevel at any depth, so they are the
1784 // `bevel_edges_are_distinct_from_their_face` set. The other two are new here:
1785 // they hold a highlight in 24-bit, but not one wide enough to survive
1786 // rounding onto the cube.
1787 #[test]
1788 fn two_hundred_fifty_six_colors_keep_both_bevel_edges() {
1789 const LOSES_AN_EDGE: &[&str] = &[
1790 "gruvbox-light",
1791 "neobrute",
1792 "oxocarbon-light",
1793 "rosepine-dawn",
1794 ];
1795
1796 let mut lost: Vec<String> = Vec::new();
1797 for (id, source) in embedded_themes() {
1798 let theme = parse_theme_str(id, source, false).unwrap();
1799 let t = resolve(&theme);
1800 let (Some(face), Some(light), Some(dark)) = (
1801 t.hex("surface-raised").and_then(Rgb::from_hex),
1802 t.hex("bevel-light").and_then(Rgb::from_hex),
1803 t.hex("bevel-dark").and_then(Rgb::from_hex),
1804 ) else {
1805 continue;
1806 };
1807
1808 // Against the fixed region, which is what a consumer should use: a
1809 // match in the low sixteen is a match against a repaintable color.
1810 let f = quantize(face, ANSI_240);
1811 let l = quantize(light, ANSI_240);
1812 let d = quantize(dark, ANSI_240);
1813 if l == f || d == f || l == d {
1814 lost.push(id.to_string());
1815 }
1816 }
1817 lost.sort();
1818
1819 assert_eq!(
1820 lost, LOSES_AN_EDGE,
1821 "themes that cannot hold a two-tone bevel on a 256-color terminal"
1822 );
1823 }
1824
1825 #[test]
1826 fn the_256_table_has_its_three_regions() {
1827 // Index is the escape-sequence index, so the low sixteen must match.
1828 assert_eq!(ANSI_256[..16], ANSI_16);
1829 // The cube's corners, at both ends and one interior level.
1830 assert_eq!(ANSI_256[16].tuple(), (0, 0, 0));
1831 assert_eq!(ANSI_256[231].tuple(), (255, 255, 255));
1832 assert_eq!(ANSI_256[16 + 36 * 2 + 6 * 3 + 4].tuple(), (135, 175, 215));
1833 // The gray ramp runs 8 to 238 and contains neither black nor white.
1834 assert_eq!(ANSI_256[232].tuple(), (8, 8, 8));
1835 assert_eq!(ANSI_256[255].tuple(), (238, 238, 238));
1836 // The fixed region is the table minus the repaintable colors.
1837 assert_eq!(ANSI_240.len(), 240);
1838 assert_eq!(ANSI_240[0], ANSI_256[ANSI_240_OFFSET]);
1839 }
1840
1841 #[test]
1842 fn resolve_overlay_is_dark_translucent_scrim() {
1843 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1844 let t = resolve(&theme);
1845 let overlay = t.hex("overlay").unwrap();
1846 assert!(
1847 overlay.starts_with("rgba("),
1848 "overlay is translucent: {overlay}"
1849 );
1850 assert!(overlay.ends_with(", 0.5)"));
1851 // The scrim tone is anchored very dark regardless of theme.
1852 let inner = overlay
1853 .trim_start_matches("rgba(")
1854 .trim_end_matches(", 0.5)");
1855 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
1856 let scrim = Rgb {
1857 r: parts[0],
1858 g: parts[1],
1859 b: parts[2],
1860 };
1861 assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
1862 }
1863
1864 #[test]
1865 fn resolve_drops_non_hex_base_intent() {
1866 // A base intent that isn't a hex color must never reach the resolved
1867 // token set (it would otherwise be inlined verbatim into a <style>
1868 // block). Skipped like a missing intent; valid siblings survive.
1869 let theme = parse_theme_str(
1870 "x",
1871 "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
1872 false,
1873 )
1874 .unwrap();
1875 let t = resolve(&theme);
1876 assert!(
1877 t.hex("surface-page").is_none(),
1878 "non-hex base intent leaked"
1879 );
1880 assert_eq!(t.hex("content").unwrap(), "#111111");
1881 // The injected markup appears in no resolved value.
1882 assert!(!t.intents.values().any(|v| v.contains('<')));
1883 }
1884
1885 #[test]
1886 fn resolve_skips_derived_when_source_missing() {
1887 // No [action] => no action-derived tokens.
1888 let theme = parse_theme_str(
1889 "x",
1890 "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
1891 false,
1892 )
1893 .unwrap();
1894 let t = resolve(&theme);
1895 assert!(t.hex("action").is_none());
1896 assert!(t.hex("action-hover").is_none());
1897 assert!(t.hex("selection").is_none());
1898 assert_eq!(
1899 t.hex("border-strong").unwrap(),
1900 darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
1901 );
1902 }
1903
1904 #[test]
1905 fn rgb_accessor_for_native_consumers() {
1906 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1907 let t = resolve(&theme);
1908 assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
1909 assert_eq!(t.rgb("nonexistent"), None);
1910 }
1911
1912 // ---- css emit ----
1913
1914 #[test]
1915 fn intent_css_vars_wraps_root_and_includes_tokens() {
1916 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
1917 let css = intent_css_vars(&resolve(&theme));
1918 assert!(css.starts_with(":root {\n"));
1919 assert!(css.contains(" --surface-page: #2e3440;\n"));
1920 assert!(css.contains(" --danger: #bf616a;\n"));
1921 assert!(css.contains(" --action-hover: "));
1922 assert!(css.trim_end().ends_with('}'));
1923 }
1924
1925 // ---- loading / fs ----
1926
1927 #[test]
1928 fn load_and_resolve_round_trip() {
1929 let dir = tempfile::tempdir().unwrap();
1930 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
1931 let dirs = vec![(dir.path().to_path_buf(), false)];
1932 let t = load_semantic(&dirs, "nord").unwrap();
1933 assert_eq!(t.meta.name, "Nord");
1934 assert_eq!(t.hex("action"), Some("#81a1c1"));
1935 }
1936
1937 #[test]
1938 fn load_theme_rejects_invalid_id() {
1939 assert!(load_theme(&[], "../evil").is_err());
1940 }
1941
1942 fn meta(id: &str, variant: &str) -> ThemeMeta {
1943 ThemeMeta {
1944 id: id.to_string(),
1945 name: id.to_string(),
1946 variant: variant.to_string(),
1947 is_custom: false,
1948 }
1949 }
1950
1951 fn defaults() -> ThemeDefaults {
1952 ThemeDefaults::new("flatwhite", "nord")
1953 }
1954
1955 // The three the shipped themes actually declare.
1956 #[test]
1957 fn every_shipped_variant_parses() {
1958 assert_eq!(Variant::parse("light"), Some(Variant::Light));
1959 assert_eq!(Variant::parse("dark"), Some(Variant::Dark));
1960 assert_eq!(Variant::parse("high-contrast"), Some(Variant::HighContrast));
1961 assert_eq!(Variant::parse("sepia"), None);
1962 }
1963
1964 // parse_meta already defaults a *missing* variant to dark, so an
1965 // unrecognized one reading as light would have the crate disagreeing with
1966 // itself. alloy_tui did exactly that before this existed.
1967 #[test]
1968 fn an_unrecognized_variant_reads_the_way_a_missing_one_does() {
1969 assert_eq!(Variant::from("sepia"), Variant::Dark);
1970 assert_eq!(Variant::from(""), Variant::Dark);
1971
1972 let missing: toml::Table = "[meta]\nname = \"X\"\n".parse().unwrap();
1973 assert_eq!(parse_meta("x", &missing, false).kind(), Variant::Dark);
1974 }
1975
1976 #[test]
1977 fn a_selection_round_trips_through_any_store() {
1978 for (stored, expect) in [
1979 (Some("system"), ThemeSelection::Follow),
1980 (None, ThemeSelection::Follow),
1981 (Some(""), ThemeSelection::Follow),
1982 (Some(" "), ThemeSelection::Follow),
1983 (Some("nord"), ThemeSelection::Fixed("nord".into())),
1984 ] {
1985 let parsed = ThemeSelection::parse(stored);
1986 assert_eq!(parsed, expect, "{stored:?}");
1987 assert_eq!(
1988 ThemeSelection::parse(Some(parsed.as_str())),
1989 expect,
1990 "what is written reads back as what was meant",
1991 );
1992 }
1993 }
1994
1995 // Nothing saved is follow-the-system, which is what Balanced Breakfast
1996 // expressed as an absent value and GoingsOn as a sentinel. Both are now the
1997 // same thing.
1998 #[test]
1999 fn nothing_chosen_yet_is_follow() {
2000 assert_eq!(ThemeSelection::default(), ThemeSelection::Follow);
2001 }
2002
2003 #[test]
2004 fn a_fixed_selection_wins_when_its_theme_is_installed() {
2005 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2006 let fixed = ThemeSelection::Fixed("nord".into());
2007 assert_eq!(
2008 fixed.resolve(Variant::Light, &defaults(), &available),
2009 "nord",
2010 "a chosen theme is not overridden by the ambient mode",
2011 );
2012 }
2013
2014 // Themes are deletable in three of the four apps. Handing back an id that
2015 // will fail to load only moves the error somewhere less helpful.
2016 #[test]
2017 fn a_fixed_selection_whose_theme_is_gone_falls_back() {
2018 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2019 let fixed = ThemeSelection::Fixed("deleted".into());
2020 assert_eq!(
2021 fixed.resolve(Variant::Light, &defaults(), &available),
2022 "flatwhite",
2023 );
2024 }
2025
2026 #[test]
2027 fn follow_picks_the_apps_default_for_the_ambient_mode() {
2028 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
2029 let follow = ThemeSelection::Follow;
2030 assert_eq!(
2031 follow.resolve(Variant::Dark, &defaults(), &available),
2032 "nord",
2033 );
2034 assert_eq!(
2035 follow.resolve(Variant::Light, &defaults(), &available),
2036 "flatwhite",
2037 );
2038 }
2039
2040 // The behaviour Balanced Breakfast could not have: following the system
2041 // into a theme the user installed, when the app's own default is absent.
2042 #[test]
2043 fn follow_uses_any_installed_theme_of_the_right_variant() {
2044 let available = [meta("solarized-light", "light"), meta("mine", "dark")];
2045 assert_eq!(
2046 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &available),
2047 "mine",
2048 "the app's `nord` is not installed, but a dark theme is",
2049 );
2050 }
2051
2052 // Always returns something: an app with no theme directory gets the id it
2053 // ships with, and the load error it would have had anyway.
2054 #[test]
2055 fn an_empty_catalog_still_names_the_apps_default() {
2056 assert_eq!(
2057 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &[]),
2058 "nord",
2059 );
2060 }
2061
2062 #[test]
2063 fn high_contrast_falls_back_to_dark_unless_named() {
2064 let plain = defaults();
2065 assert_eq!(plain.for_variant(Variant::HighContrast), "nord");
2066
2067 let named = defaults().high_contrast("sharp");
2068 assert_eq!(named.for_variant(Variant::HighContrast), "sharp");
2069 }
2070
2071 // The bug this builder exists to prevent: the Alloy console pushed the
2072 // user's directory first under a comment reading "highest precedence
2073 // first", when both consumers of this vector resolve last-wins. A custom
2074 // theme lost to the packaged one of the same id.
2075 #[test]
2076 fn the_users_own_themes_outrank_everything() {
2077 let root = tempfile::tempdir().unwrap();
2078 let make = |name: &str| {
2079 let dir = root.path().join(name);
2080 std::fs::create_dir_all(&dir).unwrap();
2081 dir
2082 };
2083 let (bundled, system, custom) = (make("bundled"), make("system"), make("custom"));
2084
2085 let dirs = ThemeDirs::new()
2086 .custom(Some(custom.clone()))
2087 .bundled(Some(bundled.clone()))
2088 .system(Some(system.clone()))
2089 .build();
2090
2091 assert_eq!(
2092 dirs,
2093 vec![(bundled, false), (system, false), (custom.clone(), true)],
2094 "lowest precedence first, whatever order the tiers were added in",
2095 );
2096 assert!(dirs.last().unwrap().1, "only the user's tier is custom");
2097
2098 // And the ordering means what the consumers think it means.
2099 for dir in dirs.iter().map(|(dir, _)| dir) {
2100 std::fs::write(dir.join("shared.toml"), "[meta]\nname = \"x\"\n").unwrap();
2101 }
2102 assert_eq!(
2103 find_theme_path(&dirs, "shared").unwrap().0,
2104 custom.join("shared.toml"),
2105 "the user's copy is the one that loads",
2106 );
2107 }
2108
2109 #[test]
2110 fn a_directory_that_does_not_exist_is_dropped() {
2111 let root = tempfile::tempdir().unwrap();
2112 let real = root.path().join("real");
2113 std::fs::create_dir_all(&real).unwrap();
2114
2115 let dirs = ThemeDirs::new()
2116 .bundled(Some(root.path().join("nope")))
2117 .system(None)
2118 .custom(Some(real.clone()))
2119 .build();
2120
2121 assert_eq!(dirs, vec![(real, true)]);
2122 }
2123
2124 // A Tauri app has two bundled tiers: the resource dir in production and the
2125 // tree build.rs materialized for a dev run with no resource dir.
2126 #[test]
2127 fn more_than_one_bundled_tier_is_allowed() {
2128 let root = tempfile::tempdir().unwrap();
2129 let (first, second) = (root.path().join("a"), root.path().join("b"));
2130 std::fs::create_dir_all(&first).unwrap();
2131 std::fs::create_dir_all(&second).unwrap();
2132
2133 let dirs = ThemeDirs::new()
2134 .bundled(Some(first.clone()))
2135 .bundled(Some(second.clone()))
2136 .build();
2137 assert_eq!(dirs, vec![(first, false), (second, false)]);
2138 }
2139
2140 #[test]
2141 fn list_themes_from_dirs_finds_toml_files() {
2142 let dir = tempfile::tempdir().unwrap();
2143 fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
2144 fs::write(dir.path().join("x.txt"), "ignored").unwrap();
2145 let dirs = vec![(dir.path().to_path_buf(), false)];
2146 let themes = list_themes_from_dirs(&dirs);
2147 assert_eq!(themes.len(), 1);
2148 assert_eq!(themes[0].id, "t");
2149 }
2150
2151 #[test]
2152 fn find_theme_path_reverse_priority() {
2153 let d1 = tempfile::tempdir().unwrap();
2154 let d2 = tempfile::tempdir().unwrap();
2155 fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
2156 fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
2157 let dirs = vec![
2158 (d1.path().to_path_buf(), false),
2159 (d2.path().to_path_buf(), true),
2160 ];
2161 let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
2162 assert!(is_custom);
2163 assert_eq!(path, d2.path().join("s.toml"));
2164 }
2165
2166 #[test]
2167 fn import_theme_valid_and_rejects_empty() {
2168 let src_dir = tempfile::tempdir().unwrap();
2169 let custom_dir = tempfile::tempdir().unwrap();
2170
2171 let good = src_dir.path().join("my-theme.toml");
2172 fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
2173 let meta = import_theme(&good, custom_dir.path()).unwrap();
2174 assert_eq!(meta.id, "my-theme");
2175 assert!(custom_dir.path().join("my-theme.toml").exists());
2176
2177 let empty = src_dir.path().join("empty.toml");
2178 fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
2179 assert!(import_theme(&empty, custom_dir.path()).is_err());
2180 }
2181
2182 #[test]
2183 fn import_theme_rejects_invalid_toml() {
2184 let src_dir = tempfile::tempdir().unwrap();
2185 let custom_dir = tempfile::tempdir().unwrap();
2186 let src = src_dir.path().join("bad.toml");
2187 fs::write(&src, "this is not [valid toml [[[").unwrap();
2188 assert!(import_theme(&src, custom_dir.path()).is_err());
2189 }
2190
2191 #[test]
2192 fn delete_theme_removes_and_guards() {
2193 let custom = tempfile::tempdir().unwrap();
2194 let path = custom.path().join("doomed.toml");
2195 fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
2196 delete_theme(custom.path(), "doomed").unwrap();
2197 assert!(!path.exists());
2198 assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
2199 assert!(delete_theme(custom.path(), "ghost").is_err());
2200 }
2201
2202 #[test]
2203 fn export_theme_copies_file() {
2204 let src_dir = tempfile::tempdir().unwrap();
2205 let dest_dir = tempfile::tempdir().unwrap();
2206 let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
2207 fs::write(src_dir.path().join("e.toml"), content).unwrap();
2208 let dirs = vec![(src_dir.path().to_path_buf(), false)];
2209 let dest = dest_dir.path().join("out.toml");
2210 export_theme(&dirs, "e", &dest).unwrap();
2211 assert_eq!(fs::read_to_string(&dest).unwrap(), content);
2212 assert!(export_theme(&dirs, "missing", &dest).is_err());
2213 }
2214
2215 #[test]
2216 fn load_theme_preview_returns_role_swatches() {
2217 let dir = tempfile::tempdir().unwrap();
2218 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
2219 let dirs = vec![(dir.path().to_path_buf(), false)];
2220 let p = load_theme_preview(&dirs, "nord").unwrap();
2221 assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
2222 assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
2223 assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
2224 assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
2225 }
2226
2227 #[test]
2228 fn bundled_themes_dir_resolves_to_shipped_themes() {
2229 // The crate ships its themes, so this must resolve in-tree and the
2230 // Akari defaults the console falls back to must be present.
2231 let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
2232 assert!(dir.join("akari-dawn.toml").is_file());
2233 assert!(dir.join("akari-night.toml").is_file());
2234 }
2235
2236 #[test]
2237 fn every_theme_is_accounted_for_in_third_party_notices() {
2238 // Attribution is a redistribution obligation, not a nicety: adding a
2239 // theme without a notice entry silently ships someone's work
2240 // uncredited. Fail here instead.
2241 let notices = std::fs::read_to_string(
2242 Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
2243 )
2244 .expect("THIRD-PARTY-NOTICES.md must exist");
2245 let missing: Vec<&str> = embedded_themes()
2246 .map(|(id, _)| id)
2247 .filter(|id| !notices.contains(*id))
2248 .collect();
2249 assert!(
2250 missing.is_empty(),
2251 "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
2252 );
2253 }
2254
2255 #[test]
2256 fn adapted_themes_carry_inline_attribution() {
2257 // Each adapted file must name its upstream in-file, so the credit
2258 // survives someone copying a single .toml out of the crate.
2259 const ORIGINALS: [&str; 5] = [
2260 "makenotwork",
2261 "goingson",
2262 "audiofiles",
2263 "high-contrast",
2264 "neobrute",
2265 ];
2266 for (id, source) in embedded_themes() {
2267 if ORIGINALS.contains(&id) {
2268 continue;
2269 }
2270 assert!(
2271 source.contains("adapted from"),
2272 "adapted theme `{id}` is missing its inline attribution header"
2273 );
2274 }
2275 }
2276
2277 #[test]
2278 fn embedded_themes_match_the_directory() {
2279 // The embedded copy and themes/ are two views of one source. If they
2280 // ever disagree, path-based and path-free consumers render different
2281 // theme sets, which is exactly the drift shipping the data was meant
2282 // to prevent.
2283 let dir = bundled_themes_dir().unwrap();
2284 let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
2285 .unwrap()
2286 .filter_map(|e| {
2287 let path = e.ok()?.path();
2288 if path.extension()? != "toml" {
2289 return None;
2290 }
2291 Some(path.file_stem()?.to_str()?.to_string())
2292 })
2293 .collect();
2294 let mut embedded: Vec<String> = embedded_themes().map(|(id, _)| id.to_string()).collect();
2295 on_disk.sort();
2296 embedded.sort();
2297 assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
2298 }
2299
2300 #[test]
2301 fn every_embedded_theme_parses() {
2302 // Guards the path-free consumers (MNW server, the Tauri build steps)
2303 // the same way every_shipped_theme_loads guards the path-based ones.
2304 let mut count = 0;
2305 for (id, source) in embedded_themes() {
2306 parse_theme_str(id, source, false)
2307 .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
2308 count += 1;
2309 }
2310 assert!(count >= 30, "expected the full theme set, got {count}");
2311 }
2312
2313 #[test]
2314 fn every_shipped_theme_loads() {
2315 // Guards the data, not just the loader: a malformed or truncated
2316 // .toml in themes/ is a shipping bug, and it should fail here rather
2317 // than at a user's first launch.
2318 let dir = bundled_themes_dir().unwrap();
2319 let dirs = vec![(dir.clone(), false)];
2320 let themes = list_themes_from_dirs(&dirs);
2321 assert!(
2322 themes.len() >= 30,
2323 "expected the full theme set, got {}",
2324 themes.len()
2325 );
2326 for meta in &themes {
2327 load_theme(&dirs, &meta.id)
2328 .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
2329 }
2330 }
2331 }
2332