Skip to main content

max / makeover

167.1 KB · 4337 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] # the ink. Its emphasis steps are derived, not authored:
21 //! primary = "#d8dee9" # `content-secondary` and `content-muted` are tonal
22 //! # steps of this toward `surface.page`. See `Emphasis`.
23 //!
24 //! [action] # interactive / brand color
25 //! primary = "#81a1c1"
26 //!
27 //! [status] # state semantics
28 //! danger = "#bf616a"; success = "#a3be8c"; warning = "#ebcb8b"; info = "#88c0d0"
29 //!
30 //! [line]
31 //! border = "#4c566a"
32 //!
33 //! [category] # distinct decorative colors for tags/badges/charts
34 //! one = "#bf616a"; two = "#a3be8c"; three = "#81a1c1"
35 //! four = "#ebcb8b"; five = "#b48ead"; six = "#88c0d0"
36 //! ```
37
38 // Color-space math: single-letter channel names (r/g/b/l/m/s) and the published
39 // high-precision OKLab/sRGB matrix constants are the domain vocabulary here.
40 #![allow(clippy::many_single_char_names, clippy::unreadable_literal)]
41
42 use serde::Serialize;
43 use std::collections::{BTreeMap, HashMap};
44 use std::path::{Path, PathBuf};
45
46 /// The color sections an authored theme may declare.
47 pub const COLOR_SECTIONS: &[&str] = &["surface", "content", "action", "status", "line", "category"];
48
49 /// Theme metadata parsed from the `[meta]` section.
50 #[derive(Debug, Clone, Serialize)]
51 #[serde(rename_all = "camelCase")]
52 pub struct ThemeMeta {
53 pub id: String,
54 pub name: String,
55 pub variant: String,
56 pub is_custom: bool,
57 }
58
59 /// A loaded theme: metadata plus the authored colors, flattened to dotted keys
60 /// (e.g. `"surface.page"`, `"status.danger"`, `"category.one"`).
61 #[derive(Debug, Serialize)]
62 #[serde(rename_all = "camelCase")]
63 pub struct ThemeColors {
64 pub meta: ThemeMeta,
65 pub colors: HashMap<String, String>,
66 }
67
68 // ============================================================================
69 // Color math — perceptual (OKLab) derivations + WCAG contrast.
70 //
71 // Interactive states (hover/active/selection/surfaces) are derived in OKLab so
72 // equal steps look equal across every theme's hues (Ottosson 2020; the modern
73 // CIELAB). Text-on-color is picked by the WCAG 2.x contrast ratio, not a naive
74 // luminance threshold, so the choice actually meets AA where achievable.
75 // This is the single source of truth shared by every product.
76 // ============================================================================
77
78 /// An sRGB color. Hex round-trips losslessly.
79 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
80 pub struct Rgb {
81 pub r: u8,
82 pub g: u8,
83 pub b: u8,
84 }
85
86 impl Rgb {
87 /// Parse `#rgb` or `#rrggbb` (case-insensitive). Returns `None` otherwise.
88 pub fn from_hex(s: &str) -> Option<Rgb> {
89 let h = s.strip_prefix('#')?;
90 let (r, g, b) = match h.len() {
91 6 => (
92 u8::from_str_radix(&h[0..2], 16).ok()?,
93 u8::from_str_radix(&h[2..4], 16).ok()?,
94 u8::from_str_radix(&h[4..6], 16).ok()?,
95 ),
96 3 => {
97 let d = |c: &str| u8::from_str_radix(c, 16).ok().map(|v| v * 17);
98 (d(&h[0..1])?, d(&h[1..2])?, d(&h[2..3])?)
99 }
100 _ => return None,
101 };
102 Some(Rgb { r, g, b })
103 }
104
105 /// Lowercase `#rrggbb`.
106 pub fn to_hex(self) -> String {
107 format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
108 }
109
110 pub fn tuple(self) -> (u8, u8, u8) {
111 (self.r, self.g, self.b)
112 }
113 }
114
115 /// A color in OKLab (perceptually uniform): `l` lightness in [0,1], `a`/`b` opponent axes.
116 #[derive(Clone, Copy, Debug)]
117 pub struct Oklab {
118 pub l: f32,
119 pub a: f32,
120 pub b: f32,
121 }
122
123 fn srgb_to_linear(c: u8) -> f32 {
124 let c = c as f32 / 255.0;
125 if c <= 0.04045 {
126 c / 12.92
127 } else {
128 ((c + 0.055) / 1.055).powf(2.4)
129 }
130 }
131
132 fn linear_to_srgb(c: f32) -> u8 {
133 let c = c.clamp(0.0, 1.0);
134 let v = if c <= 0.0031308 {
135 c * 12.92
136 } else {
137 1.055 * c.powf(1.0 / 2.4) - 0.055
138 };
139 (v * 255.0).round().clamp(0.0, 255.0) as u8
140 }
141
142 impl Rgb {
143 /// Convert to OKLab (Ottosson's sRGB matrices).
144 ///
145 /// The matrix coefficients are quoted at their published precision so they
146 /// can be diffed against the reference. `f32` rounds them at compile time;
147 /// truncating the literals would only make them harder to check.
148 #[allow(clippy::excessive_precision)]
149 pub fn to_oklab(self) -> Oklab {
150 let (r, g, b) = (
151 srgb_to_linear(self.r),
152 srgb_to_linear(self.g),
153 srgb_to_linear(self.b),
154 );
155 let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
156 let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
157 let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
158 let (l_, m_, s_) = (l.cbrt(), m.cbrt(), s.cbrt());
159 Oklab {
160 l: 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
161 a: 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
162 b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
163 }
164 }
165
166 /// Convert from OKLab back to the nearest in-gamut sRGB.
167 ///
168 /// Published precision, as in [`Rgb::to_oklab`].
169 #[allow(clippy::excessive_precision)]
170 pub fn from_oklab(c: Oklab) -> Rgb {
171 let l_ = c.l + 0.3963377774 * c.a + 0.2158037573 * c.b;
172 let m_ = c.l - 0.1055613458 * c.a - 0.0638541728 * c.b;
173 let s_ = c.l - 0.0894841775 * c.a - 1.2914855480 * c.b;
174 let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
175 Rgb {
176 r: linear_to_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
177 g: linear_to_srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
178 b: linear_to_srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
179 }
180 }
181 }
182
183 /// WCAG 2.x relative luminance of an sRGB color.
184 fn rel_luminance(c: Rgb) -> f32 {
185 0.2126 * srgb_to_linear(c.r) + 0.7152 * srgb_to_linear(c.g) + 0.0722 * srgb_to_linear(c.b)
186 }
187
188 /// WCAG 2.x contrast ratio between two colors, in [1, 21].
189 pub fn wcag_contrast(a: Rgb, b: Rgb) -> f32 {
190 let (la, lb) = (rel_luminance(a), rel_luminance(b));
191 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
192 (hi + 0.05) / (lo + 0.05)
193 }
194
195 /// Pick black or white for legible text on `bg`, by the higher WCAG contrast
196 /// ratio (so the choice meets AA wherever the background allows it).
197 pub fn readable_on(bg: Rgb) -> Rgb {
198 let white = Rgb {
199 r: 255,
200 g: 255,
201 b: 255,
202 };
203 let black = Rgb { r: 0, g: 0, b: 0 };
204 if wcag_contrast(white, bg) >= wcag_contrast(black, bg) {
205 white
206 } else {
207 black
208 }
209 }
210
211 /// Shift OKLab lightness by `delta` (perceptually uniform). Positive lightens.
212 pub fn lighten(c: Rgb, delta: f32) -> Rgb {
213 let mut lab = c.to_oklab();
214 lab.l = (lab.l + delta).clamp(0.0, 1.0);
215 Rgb::from_oklab(lab)
216 }
217
218 /// Shift OKLab lightness down by `delta` (perceptually uniform).
219 pub fn darken(c: Rgb, delta: f32) -> Rgb {
220 lighten(c, -delta)
221 }
222
223 /// Interpolate between `a` and `b` by `t` in [0,1] in OKLab (perceptual blend).
224 pub fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb {
225 let (x, y) = (a.to_oklab(), b.to_oklab());
226 Rgb::from_oklab(Oklab {
227 l: x.l + (y.l - x.l) * t,
228 a: x.a + (y.a - x.a) * t,
229 b: x.b + (y.b - x.b) * t,
230 })
231 }
232
233 // ============================================================================
234 // Tonal steps
235 // ============================================================================
236
237 /// How far a tonal step sits from the token it is a step of.
238 ///
239 /// The named ratios. [`tonal`] is the same operation with the number written
240 /// out, and this is the small set of steps the vocabulary has agreed on, so a
241 /// consumer asking for "the muted form of this" names it rather than picking a
242 /// number and disagreeing with the next consumer to pick one.
243 ///
244 /// The rule these encode, stated as the three-tone convention:
245 ///
246 /// | step | what it means |
247 /// |------|---------------|
248 /// | [`Full`](Self::Full) | active, emphasised, the thing itself |
249 /// | [`Secondary`](Self::Secondary) | inactive but usable: a control that still answers |
250 /// | [`Muted`](Self::Muted) | inert: disabled, or not a control at all |
251 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252 pub enum Emphasis {
253 /// The token unchanged.
254 Full,
255 /// One step back. Still legible as content, not competing with `Full`.
256 Secondary,
257 /// Two steps back. Present, and saying it is not the point.
258 Muted,
259 }
260
261 impl Emphasis {
262 /// The fraction of the way to the ground this step travels.
263 ///
264 /// Both numbers are the shipped corpus' own, not invented: across the 31
265 /// bundled themes, hand-authored `content.secondary` sat at a median 0.115
266 /// of the way from `content.primary` to `surface.page`, and `content.muted`
267 /// at 0.424. So the derivation reproduces what theme authors converged on
268 /// by eye, and the themes that move are the ones that were off the cluster.
269 #[must_use]
270 pub const fn ratio(self) -> f32 {
271 match self {
272 Self::Full => 0.0,
273 Self::Secondary => 0.12,
274 Self::Muted => 0.42,
275 }
276 }
277
278 /// The suffix a derived token takes, or `None` for the token itself.
279 ///
280 /// `content` + [`Muted`](Self::Muted) is `content-muted`, which is the
281 /// naming every consumer already spells by hand. Grouping a family this way
282 /// is what makes `danger-muted` or `action-secondary` nameable without a
283 /// second table saying what they mean.
284 #[must_use]
285 pub const fn suffix(self) -> Option<&'static str> {
286 match self {
287 Self::Full => None,
288 Self::Secondary => Some("-secondary"),
289 Self::Muted => Some("-muted"),
290 }
291 }
292
293 /// The derived token key for `token` at this step.
294 #[must_use]
295 pub fn token(self, token: &str) -> String {
296 match self.suffix() {
297 Some(suffix) => format!("{token}{suffix}"),
298 None => token.to_string(),
299 }
300 }
301 }
302
303 /// The contrast a tonal step must clear against the token it is a step of.
304 ///
305 /// A ratio says how far to travel, not how far that lands, and the two are the
306 /// same thing only when the base has room to travel in. Across the bundled
307 /// themes a derived `content.secondary` sits between 1.21 and 1.44 of its ink;
308 /// the exceptions were the two themes whose ink is `#000000`, where OKLab L is
309 /// 0, 12 percent of nothing is nothing, and the sRGB transfer curve compresses
310 /// what is left into a 3/255 move. So the floor is the bottom of the band the
311 /// healthy themes already reach, and a theme inside it does not move.
312 ///
313 /// Deliberately below [`DISTINCT`]: that is the 3:1 two *areas* need to read as
314 /// separate, and an emphasis step is one voice quieter rather than a second
315 /// region. Asking 3:1 of it would flatten every theme's ramp into three widely
316 /// spaced greys.
317 pub const STEP_FLOOR: f32 = 1.21;
318
319 /// A tonal step of `base`, `ratio` of the way toward the `ground` it is read
320 /// against.
321 ///
322 /// The numerical form of [`Emphasis`], for a consumer that wants a step the
323 /// named set does not have. `ratio` is clamped to [0,1]: past 1 the step is no
324 /// longer a step of `base` but a colour beyond the ground, which is a different
325 /// operation wearing this one's name.
326 ///
327 /// # Toward the ground, not toward grey
328 ///
329 /// A tonal step is a *reduction in contrast against what it is read on*, so it
330 /// interpolates toward the surface rather than desaturating or lightening. That
331 /// is why it takes two colours: lightening is wrong on a light theme and
332 /// darkening is wrong on a dark one, and mixing toward the ground is correct on
333 /// both without asking which theme this is. It is also why the ground is a
334 /// parameter rather than assumed — text in a well is read against the well.
335 ///
336 /// # It composes
337 ///
338 /// Two steps toward the same ground are one step toward that ground, since
339 /// OKLab interpolation is linear: `tonal(tonal(c, g, a), g, b)` is
340 /// `tonal(c, g, a + b - a*b)`. So a family can be derived recursively — the
341 /// muted form of a secondary is a well-defined colour and not a compounding
342 /// error — and re-deriving a token that was already derived is stable rather
343 /// than a slow slide into the background.
344 #[must_use]
345 pub fn tonal(base: Rgb, ground: Rgb, ratio: f32) -> Rgb {
346 mix(base, ground, ratio.clamp(0.0, 1.0))
347 }
348
349 /// A named tonal step of `base` against the `ground` it is read on.
350 ///
351 /// [`tonal`] with [`Emphasis::ratio`], and the form to reach for: the two
352 /// spellings of "muted" a pair of consumers pick independently are the drift
353 /// this replaces.
354 #[must_use]
355 pub fn emphasized(base: Rgb, ground: Rgb, emphasis: Emphasis) -> Rgb {
356 tonal(base, ground, emphasis.ratio())
357 }
358
359 // ============================================================================
360 // Low-color terminals
361 // ============================================================================
362
363 /// The 16 colors an ANSI terminal addresses by index, in the PC/VGA
364 /// arrangement the Linux console and most emulators start from.
365 ///
366 /// 0-7 are the normal colors and 8-15 the bright ones. Index 7 is a light gray
367 /// rather than white, which is the entry a themed surface usually lands on, and
368 /// index 15 is the true white.
369 ///
370 /// Emulators let the user repaint all sixteen, so this is the standard
371 /// arrangement rather than a promise about any one terminal. The Linux console
372 /// keeps it, which is the case that matters: a console app cannot fall back to
373 /// 24-bit color there.
374 pub const ANSI_16: [Rgb; 16] = [
375 Rgb {
376 r: 0x00,
377 g: 0x00,
378 b: 0x00,
379 },
380 Rgb {
381 r: 0xaa,
382 g: 0x00,
383 b: 0x00,
384 },
385 Rgb {
386 r: 0x00,
387 g: 0xaa,
388 b: 0x00,
389 },
390 Rgb {
391 r: 0xaa,
392 g: 0x55,
393 b: 0x00,
394 },
395 Rgb {
396 r: 0x00,
397 g: 0x00,
398 b: 0xaa,
399 },
400 Rgb {
401 r: 0xaa,
402 g: 0x00,
403 b: 0xaa,
404 },
405 Rgb {
406 r: 0x00,
407 g: 0xaa,
408 b: 0xaa,
409 },
410 Rgb {
411 r: 0xaa,
412 g: 0xaa,
413 b: 0xaa,
414 },
415 Rgb {
416 r: 0x55,
417 g: 0x55,
418 b: 0x55,
419 },
420 Rgb {
421 r: 0xff,
422 g: 0x55,
423 b: 0x55,
424 },
425 Rgb {
426 r: 0x55,
427 g: 0xff,
428 b: 0x55,
429 },
430 Rgb {
431 r: 0xff,
432 g: 0xff,
433 b: 0x55,
434 },
435 Rgb {
436 r: 0x55,
437 g: 0x55,
438 b: 0xff,
439 },
440 Rgb {
441 r: 0xff,
442 g: 0x55,
443 b: 0xff,
444 },
445 Rgb {
446 r: 0x55,
447 g: 0xff,
448 b: 0xff,
449 },
450 Rgb {
451 r: 0xff,
452 g: 0xff,
453 b: 0xff,
454 },
455 ];
456
457 /// The 256 colors an xterm-compatible terminal addresses by index, so that
458 /// entry `i` is what the terminal paints for `38;5;i`.
459 ///
460 /// Three regions, and they are not equally trustworthy. 0-15 are the [`ANSI_16`]
461 /// system colors, which every emulator lets the user repaint. 16-231 are a
462 /// 6x6x6 RGB cube and 232-255 a 24-step gray ramp, and those 240 are fixed.
463 ///
464 /// So a color whose whole job is to be told apart from another should quantize
465 /// against [`ANSI_240`] rather than against this table: a match landing in the
466 /// low sixteen is a match against a color the user may have moved.
467 pub const ANSI_256: [Rgb; 256] = build_ansi_256();
468
469 /// The fixed region of [`ANSI_256`]: the 6x6x6 cube and the gray ramp, without
470 /// the sixteen repaintable system colors.
471 ///
472 /// Quantizing against this returns an index into *this* slice; add
473 /// [`ANSI_240_OFFSET`] to get the index the terminal wants.
474 pub const ANSI_240: &[Rgb] = ANSI_256.split_at(16).1;
475
476 /// What to add to an [`ANSI_240`] index to get an [`ANSI_256`] one.
477 pub const ANSI_240_OFFSET: usize = 16;
478
479 /// The twelve chromatic ANSI slots, as the intents that paint them.
480 ///
481 /// Indexed 1-6 and 9-14. The hues do not depend on whether the theme is light
482 /// or dark, since red is the theme's danger tone either way, which is exactly
483 /// why the four achromatic slots are not in this table.
484 ///
485 /// Lifted from Alloy's `skelgen` on 2026-07-31, which had folded three
486 /// disagreeing hand-maintained copies into one and is the reason the
487 /// arrangement is trusted. It moved here so a program that paints its own
488 /// palette at runtime, rather than reading a generated config, resolves the
489 /// same slots. Slot 14 was the one the copies disagreed on and is
490 /// `category.six`, which both the Linux console table and the retired
491 /// `vtrgb.py` had.
492 const CHROMATIC: [(usize, &str); 12] = [
493 (1, "status.danger"),
494 (2, "status.success"),
495 (3, "status.warning"),
496 (4, "status.info"),
497 (5, "category.five"),
498 (6, "category.six"),
499 (9, "action.primary"), // bright red, the theme's warm accent
500 (10, "status.success"),
501 (11, "status.warning"),
502 (12, "status.info"),
503 (13, "category.five"),
504 (14, "category.six"),
505 ];
506
507 /// The four achromatic slots, 0, 7, 8 and 15, which invert with the theme.
508 ///
509 /// These are the slots a naive table gets wrong. ANSI 0 is "black" and 7 is
510 /// "white", but what a terminal wants there is *the darkest tone* and *the
511 /// lightest tone*, and which intent that is flips with the theme's polarity. A
512 /// light theme's darkest tone is its ink; a dark theme's is its deepest
513 /// surface. Pinning slot 0 to `content.primary` reads correctly on a light
514 /// theme and hands a dark one a pale cream as "black".
515 ///
516 /// Slot 7 is a surface and not a text tone, because it is what a program with
517 /// no way to name anything else draws its container on: a greeter's login card
518 /// is a light card on the darker field slot 0 paints.
519 ///
520 /// Anything that is not `dark`, including `high-contrast`, follows the light
521 /// anchors.
522 fn achromatic_slot(index: usize, variant: &str) -> Option<&'static str> {
523 let dark = variant == "dark";
524 Some(match (index, dark) {
525 (0, false) => "content.primary", // darkest text tone
526 (0, true) => "surface.sunken", // darkest surface
527 (7, false) => "surface.raised", // the login card
528 (7, true) => "content.secondary", // a readable light tone
529 (8, _) => "content.muted", // muted chrome, either way
530 (15, false) => "surface.overlay", // lightest surface
531 (15, true) => "content.primary", // lightest text tone
532 _ => return None,
533 })
534 }
535
536 /// The authored intent painting ANSI slot `index` under a theme of `variant`,
537 /// as a dotted key into [`ThemeColors::colors`].
538 ///
539 /// `None` for an index outside 0-15. Every slot in range resolves, so a caller
540 /// that has the intent can fill all sixteen.
541 ///
542 /// This is what makes a bare console, a terminal emulator and a generated
543 /// config agree on what red means. They disagreed for as long as each kept its
544 /// own table.
545 #[must_use]
546 pub fn ansi_intent(index: usize, variant: &str) -> Option<&'static str> {
547 achromatic_slot(index, variant).or_else(|| {
548 CHROMATIC
549 .iter()
550 .find(|(slot, _)| *slot == index)
551 .map(|(_, intent)| *intent)
552 })
553 }
554
555 const fn build_ansi_256() -> [Rgb; 256] {
556 let mut table = [Rgb { r: 0, g: 0, b: 0 }; 256];
557
558 let mut i = 0;
559 while i < 16 {
560 table[i] = ANSI_16[i];
561 i += 1;
562 }
563
564 // The cube's six levels are not evenly spaced. The step from black to the
565 // first is more than twice any later one, which is xterm's arrangement
566 // rather than a choice available here, and it is why the darkest tones a
567 // theme can reach on 256 colors come from the gray ramp instead.
568 const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
569 let mut r = 0;
570 while r < 6 {
571 let mut g = 0;
572 while g < 6 {
573 let mut b = 0;
574 while b < 6 {
575 table[16 + 36 * r + 6 * g + b] = Rgb {
576 r: LEVELS[r],
577 g: LEVELS[g],
578 b: LEVELS[b],
579 };
580 b += 1;
581 }
582 g += 1;
583 }
584 r += 1;
585 }
586
587 // 8 to 238 in steps of 10. Neither end is black or white; both of those are
588 // in the cube, so the ramp is 24 steps of gray between them rather than 24
589 // steps of the whole range.
590 let mut k = 0;
591 while k < 24 {
592 let v = 8 + 10 * k as u8;
593 table[232 + k as usize] = Rgb { r: v, g: v, b: v };
594 k += 1;
595 }
596
597 table
598 }
599
600 /// The contrast ratio two colors must clear to read as separate areas.
601 ///
602 /// WCAG 2.x asks 3:1 of user interface components and graphics, which is what
603 /// a border, a rule, or a focus ring is. Text wants more, and a caller drawing
604 /// text can ask for more by checking [`wcag_contrast`] itself.
605 pub const DISTINCT: f32 = 3.0;
606
607 /// Perceptual distance between two colors, for choosing the closest of a set.
608 fn oklab_distance(a: Rgb, b: Rgb) -> f32 {
609 let (x, y) = (a.to_oklab(), b.to_oklab());
610 ((x.l - y.l).powi(2) + (x.a - y.a).powi(2) + (x.b - y.b).powi(2)).sqrt()
611 }
612
613 /// Index of the entry in `palette` that looks most like `c`.
614 ///
615 /// OKLab distance rather than distance in sRGB, for the same reason [`mix`]
616 /// interpolates there: sRGB's numbers are not spaced the way seeing is, so a
617 /// nearest match computed in it picks visibly wrong entries in the mid tones.
618 ///
619 /// # Panics
620 ///
621 /// If `palette` is empty.
622 pub fn quantize(c: Rgb, palette: &[Rgb]) -> usize {
623 assert!(!palette.is_empty(), "a palette needs at least one color");
624 let mut best = 0;
625 let mut best_distance = f32::INFINITY;
626 for (index, entry) in palette.iter().enumerate() {
627 let distance = oklab_distance(c, *entry);
628 if distance < best_distance {
629 best = index;
630 best_distance = distance;
631 }
632 }
633 best
634 }
635
636 /// Index of the entry in `palette` closest to `fg` that still reads against
637 /// `bg`.
638 ///
639 /// [`quantize`] answers about one color at a time, and two colors that differ
640 /// can quantize to the same entry: a themed page and a border drawn on it are
641 /// often a few steps apart in a 24-bit theme and land together on a 16-color
642 /// terminal, leaving one flat area where there was a frame. Alloy's console
643 /// showed exactly this, and it is not a contrived pairing: a light page and the
644 /// mid-tone border derived from it both land on index 7.
645 ///
646 /// So the background is quantized first, because what the border must be
647 /// distinguished from is the entry the terminal will actually paint, not the
648 /// color the theme asked for. Then the nearest entry to `fg` clearing
649 /// [`DISTINCT`] against it wins. When nothing clears it, the entry that gets
650 /// furthest does: at that point the palette cannot honor the design, and the
651 /// most legible approximation beats the closest invisible one.
652 ///
653 /// Only for colors whose whole job is to be told apart from their background.
654 /// Applied to every token it would push a deliberately quiet one until it
655 /// shouted.
656 ///
657 /// # Panics
658 ///
659 /// If `palette` is empty.
660 pub fn quantize_against(fg: Rgb, bg: Rgb, palette: &[Rgb]) -> usize {
661 assert!(!palette.is_empty(), "a palette needs at least one color");
662 let shown = palette[quantize(bg, palette)];
663
664 let mut order: Vec<usize> = (0..palette.len()).collect();
665 order.sort_by(|a, b| {
666 oklab_distance(fg, palette[*a]).total_cmp(&oklab_distance(fg, palette[*b]))
667 });
668
669 order
670 .iter()
671 .copied()
672 .find(|index| wcag_contrast(palette[*index], shown) >= DISTINCT)
673 .unwrap_or_else(|| {
674 order
675 .iter()
676 .copied()
677 .max_by(|a, b| {
678 wcag_contrast(palette[*a], shown).total_cmp(&wcag_contrast(palette[*b], shown))
679 })
680 .expect("the palette is not empty")
681 })
682 }
683
684 // ============================================================================
685 // Intent resolution
686 // ============================================================================
687
688 /// Base intents: (TOML dotted source key, canonical token key). The token key
689 /// is the CSS-var stem (`--{token}`) and the `rgb()` lookup key.
690 ///
691 /// Read straight from the loaded theme, which is not quite the same as read
692 /// from the file: `content.secondary` and `content.muted` are tonal steps of
693 /// `content.primary` and are filled in at load by [`derive_tonal_steps`], so
694 /// they arrive here already computed and take this path like any other.
695 pub const BASE_INTENTS: &[(&str, &str)] = &[
696 ("surface.page", "surface-page"),
697 ("surface.raised", "surface-raised"),
698 ("surface.sunken", "surface-sunken"),
699 ("surface.overlay", "surface-overlay"),
700 ("content.primary", "content"),
701 ("content.secondary", "content-secondary"),
702 ("content.muted", "content-muted"),
703 ("action.primary", "action"),
704 ("status.danger", "danger"),
705 ("status.success", "success"),
706 ("status.warning", "warning"),
707 ("status.info", "info"),
708 ("line.border", "border"),
709 ("category.one", "category-one"),
710 ("category.two", "category-two"),
711 ("category.three", "category-three"),
712 ("category.four", "category-four"),
713 ("category.five", "category-five"),
714 ("category.six", "category-six"),
715 ];
716
717 /// A fully resolved intent layer: every token key → concrete `#rrggbb`.
718 /// Includes both authored base intents and the computed derived intents.
719 #[derive(Debug, Clone, Serialize)]
720 #[serde(rename_all = "camelCase")]
721 pub struct SemanticTokens {
722 pub meta: ThemeMeta,
723 /// token-key → resolved hex. Stable, deterministic ordering.
724 pub intents: BTreeMap<String, String>,
725 }
726
727 impl SemanticTokens {
728 /// Resolved hex for a token key, if present.
729 pub fn hex(&self, key: &str) -> Option<&str> {
730 self.intents.get(key).map(String::as_str)
731 }
732
733 /// Resolved RGB tuple for a token key (for egui / native consumers).
734 ///
735 /// `None` for a translucent token. Two intents are emitted as `rgba(...)`
736 /// rather than hex, `overlay` and `elevation`, and dropping the alpha would
737 /// hand a native consumer an opaque near-black where it asked for a scrim.
738 /// Those want [`rgba`](Self::rgba).
739 pub fn rgb(&self, key: &str) -> Option<(u8, u8, u8)> {
740 self.intents
741 .get(key)
742 .and_then(|h| Rgb::from_hex(h))
743 .map(Rgb::tuple)
744 }
745
746 /// Resolved RGBA tuple for a token key, alpha as 0-255.
747 ///
748 /// Reads both spellings, so a caller that does not care whether an intent
749 /// happens to be translucent can use this for everything: an opaque token
750 /// comes back at 255.
751 ///
752 /// It exists because a CSS consumer can take `rgba(...)` as a string
753 /// straight out of [`hex`](Self::hex) and a native one cannot. Without it
754 /// the two translucent intents are reachable from a stylesheet and from
755 /// nowhere else, which is the coupling deriving in the crate was meant to
756 /// avoid.
757 pub fn rgba(&self, key: &str) -> Option<(u8, u8, u8, u8)> {
758 let value = self.intents.get(key)?;
759 if let Some(rgb) = Rgb::from_hex(value) {
760 let (r, g, b) = rgb.tuple();
761 return Some((r, g, b, 255));
762 }
763 let inner = value.strip_prefix("rgba(")?.strip_suffix(')')?;
764 let mut parts = inner.split(',').map(str::trim);
765 let r = parts.next()?.parse().ok()?;
766 let g = parts.next()?.parse().ok()?;
767 let b = parts.next()?.parse().ok()?;
768 let alpha: f32 = parts.next()?.parse().ok()?;
769 if parts.next().is_some() || !(0.0..=1.0).contains(&alpha) {
770 return None;
771 }
772 Some((r, g, b, (alpha * 255.0).round() as u8))
773 }
774 }
775
776 /// Resolve an authored theme into the full intent token set.
777 ///
778 /// 1. Copy each present base intent from the authored colors.
779 /// 2. Compute the derived interactive states from the base intents, using the
780 /// same math the apps used to apply individually (so output is identical).
781 ///
782 /// Each derived token is emitted only when its source intents exist, mirroring
783 /// the skip-missing behavior of the rest of the crate.
784 pub fn resolve(theme: &ThemeColors) -> SemanticTokens {
785 let mut intents: BTreeMap<String, String> = BTreeMap::new();
786
787 // 1. Base intents (authored). Copy only values that parse as a hex color and
788 // re-emit them in canonical `#rrggbb` form, so an authored value can never
789 // carry arbitrary bytes into the emitted CSS (the resolved tokens are inlined
790 // raw into a `<style>` block by the web server). A malformed value is skipped,
791 // mirroring the skip-missing behavior for absent intents.
792 for (src, token) in BASE_INTENTS {
793 if let Some(rgb) = theme.colors.get(*src).and_then(|v| Rgb::from_hex(v)) {
794 intents.insert((*token).to_string(), rgb.to_hex());
795 }
796 }
797
798 // Helper: parse an already-resolved token to Rgb.
799 let get = |m: &BTreeMap<String, String>, k: &str| m.get(k).and_then(|h| Rgb::from_hex(h));
800
801 // 2. Derived intents — perceptual (OKLab) steps + WCAG-picked text.
802 // Lightness deltas are in OKLab L units; mix ratios interpolate in OKLab.
803 let mut derived: Vec<(String, Rgb)> = Vec::new();
804 if let Some(action) = get(&intents, "action") {
805 derived.push(("action-hover".into(), lighten(action, 0.05)));
806 derived.push(("content-on-action".into(), readable_on(action)));
807 // The focus ring is the action colour itself, not a tint of it: a ring
808 // is a statement that the keyboard is here, and a faded one reads as a
809 // disabled control rather than an emphatic one.
810 //
811 // One ring, not one per primitive. Where the ring sits is a depth
812 // question and not a per-component choice: a well takes it inside its
813 // own edge and a raised surface takes it outside. That is one decision
814 // with two renderings rather than one decision per component, which is
815 // how the three apps ended up with three rings. This token is the one
816 // shared artifact; which thing wears it, and how it is drawn, is each
817 // renderer's own (see `makeover_layout`'s crate header, "reach, focus
818 // and the focus ring").
819 derived.push(("focus-ring".into(), action));
820 }
821 if let Some(page) = get(&intents, "surface-page") {
822 // Modal scrim: a near-black tone carrying a faint hint of the theme's
823 // hue, at 50% alpha. Anchored very dark (OKLab L=0.08) so it dims the
824 // page on light *and* dark themes. Emitted as rgba (not a flat hex), so
825 // it is inserted directly rather than through the hex loop below.
826 let mut o = page.to_oklab();
827 o.l = 0.08;
828 let s = Rgb::from_oklab(o);
829 intents.insert(
830 "overlay".into(),
831 format!("rgba({}, {}, {}, 0.5)", s.r, s.g, s.b),
832 );
833
834 // What a surface that FLOATS OVER the page is cast onto it with.
835 //
836 // The one intent here about a surface's relationship to the page rather
837 // than about the surface itself, which is why it is derived from `page`
838 // and not from `surface-raised`. A shadow is not the thing, it is the
839 // absence of light on what is behind the thing.
840 //
841 // SCOPE, and it is the whole point of this intent existing rather than
842 // a general "shadow": a surface that overlays the page takes this, a
843 // surface IN the page takes a bevel. Menus, toasts, popovers and
844 // dropdowns overlay. A card, a plate and a framed image do not, and
845 // reaching for this on one of those is how a pre-Platinum look survives
846 // a conversion wearing a token's name. `.raised` is the answer there.
847 //
848 // Same anchor as the scrim above and for the same reason: a tone read
849 // off the theme's hue but pinned very dark, so it reads as absence of
850 // light on a light theme and on a dark one alike. A shadow tinted to a
851 // dark theme's own lightness would not be a shadow.
852 //
853 // The alpha is the only number here that is a look decision rather than
854 // a derivation. 0.18 sits between the two literal scales it replaces:
855 // the MNW server's --shadow-2 (0.10) reads as nothing under a menu, and
856 // its --shadow-3 (0.15) was measured invisible at plate size. Geometry
857 // stays with the consumer, the way bevel thickness does.
858 intents.insert(
859 "elevation".into(),
860 format!("rgba({}, {}, {}, 0.18)", s.r, s.g, s.b),
861 );
862 }
863 if let Some(raised) = get(&intents, "surface-raised") {
864 // The two edges of a bevel: a raised control is lit from the top left,
865 // so its top and left edges take `bevel-light` and its bottom and right
866 // edges `bevel-dark`. Inverting the pair gives a pressed state and an
867 // inset well, which is what makes the idiom cheap for a consumer.
868 //
869 // Derived here rather than composed per-app because the two webviews
870 // could do it in `color-mix()` and audiofiles, which is egui, could not.
871 // Geometry (thickness, radius, which side gets which) stays app-side.
872 //
873 // The deltas are asymmetric because the eye is: an equal step down reads
874 // as a smaller change than the same step up, so the shadow is cut deeper
875 // than the highlight is raised.
876 //
877 // A face already at the top of the ramp cannot hold a highlight — the
878 // lightening clamps and the control bevels on two sides without ever
879 // resolving as lit. That is a property of the theme, not of this
880 // derivation; `bevel_edges_are_distinct_from_their_face` names the
881 // shipped themes it currently bites.
882 derived.push(("bevel-light".into(), lighten(raised, 0.14)));
883 derived.push(("bevel-dark".into(), darken(raised, 0.18)));
884
885 // An inset well: the content surface inside a raised container, so a
886 // list reads as content in a container rather than as bands on a panel.
887 // `surface-sunken` cannot serve, because a theme is free to author it
888 // darker than raised (goingson does) and a well has to go the other way.
889 //
890 // Which way is "the other way" depends on the theme, and this is the one
891 // derivation here that inverts. A well is lighter than its face on a
892 // light theme and darker on a dark one, where the bevel pair sidesteps
893 // the question by emitting both directions at once.
894 //
895 // Read the direction off `content` rather than off `Variant`. A theme
896 // whose text is dark is a theme whose surfaces are light, whatever its
897 // `variant` field claims, so this resolves correctly even when that
898 // field is wrong and it keeps the branch on measured color rather than
899 // on metadata.
900 //
901 // Deltas are asymmetric for the same reason the bevel's are, and smaller
902 // than the bevel's because a well is an area rather than an edge. The
903 // step up is the specimen's, measured: #D9DDF4 to #F3F5FD is 0.069.
904 //
905 // A face at the top of its ramp cannot hold a lighter well, the same
906 // clamp `bevel-light` hits; `well_is_visible_against_its_face` names the
907 // shipped themes where it bites.
908 if let Some(content) = get(&intents, "content") {
909 let content_is_darker = content.to_oklab().l < raised.to_oklab().l;
910 let well = if content_is_darker {
911 lighten(raised, 0.07)
912 } else {
913 darken(raised, 0.09)
914 };
915 derived.push(("surface-well".into(), well));
916 }
917 }
918 if let Some(sunken) = get(&intents, "surface-sunken") {
919 derived.push(("hover-surface".into(), sunken));
920 }
921 if let Some(border) = get(&intents, "border") {
922 derived.push(("border-strong".into(), darken(border, 0.05)));
923 }
924
925 for (token, rgb) in derived {
926 intents.insert(token, rgb.to_hex());
927 }
928
929 SemanticTokens {
930 meta: theme.meta.clone(),
931 intents,
932 }
933 }
934
935 /// Emit the resolved intent layer as CSS declarations (no selector), one
936 /// ` --token: #hex;` line each, in deterministic (BTreeMap) order.
937 pub fn intent_css_declarations(tokens: &SemanticTokens) -> String {
938 let mut out = String::new();
939 for (token, hex) in &tokens.intents {
940 out.push_str(" --");
941 out.push_str(token);
942 out.push_str(": ");
943 out.push_str(hex);
944 out.push_str(";\n");
945 }
946 out
947 }
948
949 /// Emit the resolved intent layer as a `:root { … }` block — the single TOML →
950 /// CSS mapping every web surface injects.
951 pub fn intent_css_vars(tokens: &SemanticTokens) -> String {
952 format!(":root {{\n{}}}\n", intent_css_declarations(tokens))
953 }
954
955 // ============================================================================
956 // Every theme in one sheet, keyed by a root attribute.
957 //
958 // The block above serves one theme: a consumer resolves the chosen id, renders
959 // `:root`, and links the result. Changing the pin then means rendering a new
960 // sheet and getting the document to re-link it, which an htmx navigation does
961 // not do -- so a pinned change landed at the next launch and the screen had to
962 // apologise for it in a hint.
963 //
964 // The fix is to stop encoding the choice in *which* sheet is linked. One sheet
965 // carries every theme, each behind `:root[data-theme="<id>"]`, and choosing is
966 // setting an attribute. No reload, no second request, and the picker can
967 // preview a theme by writing the attribute and undo by writing the old one.
968 //
969 // It is a separate emitter rather than a wider `intent_css_vars` because the
970 // bundle is not free: 31 themes of custom properties, against the one block a
971 // server-rendered page injects per response. MNW ships a single theme and must
972 // keep paying for a single theme, so this is opt-in by being its own call.
973 // ============================================================================
974
975 /// The root attribute [`all_themes_css`] keys its blocks on.
976 ///
977 /// Stated here so a consumer's frontend and its stylesheet cannot disagree
978 /// about the spelling; a picker writes this attribute on `document
979 /// .documentElement` and nothing else has to change.
980 pub const THEME_ATTRIBUTE: &str = "data-theme";
981
982 /// Emit one theme's intent layer keyed by [`THEME_ATTRIBUTE`], as
983 /// `:root[data-theme="<id>"] { … }`.
984 ///
985 /// The attribute selector outranks the bare `:root` of [`intent_css_vars`],
986 /// including one inside a media query, so a sheet may carry an
987 /// ambient-following default and let a pin override it without `!important`
988 /// and without ordering games.
989 pub fn keyed_intent_css_vars(id: &str, tokens: &SemanticTokens) -> String {
990 format!(
991 ":root[{THEME_ATTRIBUTE}=\"{id}\"] {{\n{}}}\n",
992 intent_css_declarations(tokens)
993 )
994 }
995
996 /// Every theme in `dirs` as one stylesheet: an ambient-following default, then
997 /// a keyed block per theme.
998 ///
999 /// The sheet a consumer links once and never re-links. Setting
1000 /// [`THEME_ATTRIBUTE`] on the root element pins a theme; removing it, or
1001 /// setting it to anything that names no theme (`"system"`, say), falls back to
1002 /// the default blocks, which follow the OS through `prefers-color-scheme` and
1003 /// `prefers-contrast`. Those are the same three ambient modes
1004 /// [`ThemeSelection::resolve`] answers, so a sheet and a Rust-side resolution
1005 /// of the same selection agree.
1006 ///
1007 /// `defaults` names the app's own fallbacks. A high-contrast default is only
1008 /// emitted when [`ThemeDefaults::high_contrast`] named one: falling back to the
1009 /// dark theme is right for a resolution and wrong for a media query, where it
1010 /// would answer `prefers-contrast: more` with a theme that is not one.
1011 ///
1012 /// Themes that fail to load are skipped rather than failing the sheet: a
1013 /// consumer's custom directory is user-writable, and one unparseable file
1014 /// there should cost that file's block and nothing else.
1015 ///
1016 /// Blocks are ordered by id so the output is byte-stable, which is what lets a
1017 /// caller cache it or compare two builds.
1018 pub fn all_themes_css(dirs: &[(PathBuf, bool)], defaults: &ThemeDefaults) -> String {
1019 let available = list_themes_from_dirs(dirs);
1020 let mut out = String::new();
1021
1022 let mut default_block = |variant: Variant, query: Option<&str>| {
1023 let id = ThemeSelection::Follow.resolve(variant, defaults, &available);
1024 let Ok(tokens) = load_semantic(dirs, &id) else {
1025 return;
1026 };
1027 match query {
1028 None => out.push_str(&intent_css_vars(&tokens)),
1029 Some(query) => {
1030 out.push_str("\n@media (");
1031 out.push_str(query);
1032 out.push_str(") {\n");
1033 out.push_str(&intent_css_vars(&tokens));
1034 out.push_str("}\n");
1035 }
1036 }
1037 };
1038
1039 default_block(Variant::Light, None);
1040 default_block(Variant::Dark, Some("prefers-color-scheme: dark"));
1041 if defaults.names_high_contrast() {
1042 default_block(Variant::HighContrast, Some("prefers-contrast: more"));
1043 }
1044
1045 let mut ids: Vec<&str> = available.iter().map(|meta| meta.id.as_str()).collect();
1046 ids.sort_unstable();
1047 for id in ids {
1048 if let Ok(tokens) = load_semantic(dirs, id) {
1049 out.push('\n');
1050 out.push_str(&keyed_intent_css_vars(id, &tokens));
1051 }
1052 }
1053
1054 out
1055 }
1056
1057 // ============================================================================
1058 // Typography — layer 1 of the house font model.
1059 //
1060 // Wiki `typography-standard`. The model is three layers: an app override, the
1061 // house default, then a system generic, and this is the middle one. Two needs,
1062 // two names, and no others in the suite:
1063 //
1064 // --font-mono Quasi Mono -> monospace
1065 // --font-sans Quasi Body -> sans-serif
1066 //
1067 // Both are cut by `quasi-type` from the Atkinson Hyperlegible superfamily plus
1068 // the house glyph set. This crate does not cut them and cannot: quasi-type is
1069 // `publish = false` and makeover is on crates.io, so the cut lives in each
1070 // consumer's own build script (`quasi_type::cut`, taken as a git dependency,
1071 // the way `shop-font` does it). What lives here is the vocabulary, which is
1072 // the half that was scattered.
1073 //
1074 // Font is not a theme's business and none of this is themeable. A theme
1075 // declares colour by role; nothing in a theme file names a face, and the two
1076 // tokens below are the same in every theme. That is why they are constants
1077 // rather than another section of `SemanticTokens`, and why they belong in a
1078 // stylesheet generated once at build time rather than in the block that gets
1079 // re-injected on a theme switch.
1080 //
1081 // The brand/display tier is out of scope, per product and by decision: Young
1082 // Serif on MNW, Reglo in GoingsOn, Departure Mono on Alloy, audiofiles' logo
1083 // face. No renderer emits them and no described screen resolves a token to
1084 // one, so they keep their own `font-family` until the app-override layer
1085 // lands and gives them a place to be declared.
1086 // ============================================================================
1087
1088 /// The mono slot: code, data, identifiers, cell grids, anything monospaced.
1089 pub const FONT_MONO: &str = "\"Quasi Mono\", monospace";
1090
1091 /// The body / UI slot. Everything that is not the mono slot or brand tier.
1092 pub const FONT_SANS: &str = "\"Quasi Body\", sans-serif";
1093
1094 /// The family name inside [`FONT_MONO`], on its own, for a consumer that needs
1095 /// the name rather than the stack. A test asserts the two agree.
1096 pub const HOUSE_MONO_FAMILY: &str = "Quasi Mono";
1097
1098 /// The family name inside [`FONT_SANS`]. See [`HOUSE_MONO_FAMILY`].
1099 pub const HOUSE_SANS_FAMILY: &str = "Quasi Body";
1100
1101 /// The weight range both house faces carry.
1102 ///
1103 /// They are variable, `wght` 200-800, and a declaration that omits the range
1104 /// makes every weight resolve to the file's default instance — which is
1105 /// ExtraLight, because a cut keeps its base's default.
1106 pub const HOUSE_WEIGHT_RANGE: &str = "200 800";
1107
1108 /// Filename a consumer writes the cut mono face to, under its own font URL.
1109 ///
1110 /// `quasi-type` writes `QuasiMono[wght].woff2`, naming the variable axis the
1111 /// way a font tool expects. Those brackets have to be percent-encoded to
1112 /// survive a URL and are a bug waiting to be written, so the web copy takes a
1113 /// plain name and the two places that have to agree — the build script that
1114 /// writes the file and the `@font-face` that fetches it — agree through this
1115 /// constant rather than by both spelling it out.
1116 pub const WEBFONT_MONO_FILE: &str = "QuasiMono.woff2";
1117
1118 /// Filename a consumer writes the cut body face to. See [`WEBFONT_MONO_FILE`].
1119 pub const WEBFONT_SANS_FILE: &str = "QuasiBody.woff2";
1120
1121 /// The house font tokens as CSS declarations (no selector), for a caller that
1122 /// is composing its own block.
1123 pub fn typography_css_declarations() -> String {
1124 format!(" --font-mono: {FONT_MONO};\n --font-sans: {FONT_SANS};\n")
1125 }
1126
1127 /// The house font tokens as a `:root { … }` block.
1128 ///
1129 /// Inlined by surfaces that cannot link a stylesheet — the MNW embeds are the
1130 /// live case — and written to a file by everything else, through
1131 /// `makeover_build::typography_css`.
1132 pub fn typography_css_vars() -> String {
1133 format!(":root {{\n{}}}\n", typography_css_declarations())
1134 }
1135
1136 /// The `@font-face` rules for both slots, fetching from `base_url`.
1137 ///
1138 /// `base_url` is the directory the consumer serves its fonts from, without a
1139 /// trailing slash: `/static/fonts` on the MNW server, `fonts` for a Tauri
1140 /// frontend loading relative to its index.
1141 ///
1142 /// # `font-weight: 200 800`, which is the part that bites
1143 ///
1144 /// Both faces are variable over `wght` 200-800 in one file, and the mono
1145 /// face's **default instance is ExtraLight** — that is upstream Atkinson's
1146 /// default and the cut keeps the axis rather than pinning a master, so a
1147 /// consumer that loads the file and takes what it opens at draws its whole UI
1148 /// at 200. Declaring the range here is what makes the browser resolve `normal`
1149 /// to 400 and `bold` to 700 instead. shop hit the same trap from the other
1150 /// side and names `wght` 400 explicitly in its shaper; this is the web's
1151 /// version of that fix, stated once for every consumer.
1152 ///
1153 /// `font-display: swap` on both: the faces are 31KB and 50KB, they are cached
1154 /// hard after the first paint, and a flash of the fallback beats invisible
1155 /// text either way.
1156 pub fn font_face_css(base_url: &str) -> String {
1157 // Rendered from the same `FontFace` a product override uses, rather than
1158 // written out here a second time. It used to be a format string, which is
1159 // why the house tier could be emitted and not read.
1160 let base = base_url.trim_end_matches('/');
1161 FontSlot::ALL
1162 .iter()
1163 .filter_map(|slot| slot.house_face())
1164 .map(|face| face.css(base))
1165 .collect()
1166 }
1167
1168 // ============================================================================
1169 // Typography — layer 0, the app override.
1170 //
1171 // Wiki `typography-standard`, GO makeover `174ab3c1`. Layer 1 above is what
1172 // every product shares; this is the one declaration a product is allowed to
1173 // make for itself:
1174 //
1175 // layer 0 app override per product, optional MNW display -> Young Serif
1176 // layer 1 house default the quasi-* slot font quasi-mono -> Quasi Mono
1177 // layer 2 system generic one hop, no further monospace / sans-serif
1178 //
1179 // The brand tier was already exempt by decision (`cdf8ac09`), and the exemption
1180 // was enforced by those faces simply not being in the vocabulary — so each
1181 // product reached its own face through a hardcoded `font-family` and an
1182 // `@font-face` block it maintained by hand, which is the exact shape the
1183 // unification is deleting everywhere else. This turns the carve-out into a
1184 // mechanism: the per-product face is declared once, in the build script that
1185 // already writes the typography layer, and is readable as an override rather
1186 // than as a stylesheet nobody unified.
1187 //
1188 // It permits overriding `mono` and `sans` too. No product wants that today,
1189 // and a layer that only allows overriding the slot nobody describes is not a
1190 // layer, it is the exemption restated.
1191 //
1192 // **One declaration per product per slot.** [`Typography::with_override`]
1193 // panics on a second override of the same slot rather than letting the last
1194 // one win: a product with two answers for a slot has the vocabulary wrong, and
1195 // that is the thing to fix.
1196 //
1197 // # What a renderer does when it cannot honour one
1198 //
1199 // Declare once, renderers honour what they can. Today only the webview surface
1200 // has a face to honour at all — neither `makeover-tui` nor `makeover-immediate`
1201 // emits a `font-family` from anywhere, because the terminal owns the face in
1202 // one and the app loads its own font stack in the other. So an override is
1203 // honoured by the generated stylesheet and ignored, silently and correctly, by
1204 // the other two. That last clause was too strong and 2.10.0 corrected it: egui
1205 // can reach a face perfectly well, it just needs the file rather than a stack.
1206 // audiofiles honours its override with no stylesheet anywhere in the path. A renderer that gains font control later reads
1207 // [`Typography::resolve`] rather than the CSS, which is why the resolution is
1208 // a method on the data and not a string-building detail. Loading a file needs
1209 // one thing more than the stack — the family name and the source to load it
1210 // from — so [`Typography::faces`] is the same data read the other way, and
1211 // between them an egui or TUI surface can honour an override without a
1212 // stylesheet anywhere in the path. audiofiles is the first to do it.
1213 // ============================================================================
1214
1215 /// A slot in the house font vocabulary — the unit an override replaces.
1216 ///
1217 /// Three, and the third is deliberately empty by default: `display` is the
1218 /// brand tier, it has no house answer, and a product that does not override it
1219 /// leaves the token undefined so whatever the consumer wrote as a fallback
1220 /// renders. The MNW embeds rely on exactly that.
1221 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1222 pub enum FontSlot {
1223 /// Code, data, identifiers, cell grids. [`FONT_MONO`] by default.
1224 Mono,
1225 /// Body and UI text: everything that is not mono or brand. [`FONT_SANS`].
1226 Sans,
1227 /// The brand / display tier. No house default, per `cdf8ac09`.
1228 Display,
1229 }
1230
1231 impl FontSlot {
1232 /// Every slot, in the order they are emitted.
1233 pub const ALL: [FontSlot; 3] = [FontSlot::Mono, FontSlot::Sans, FontSlot::Display];
1234
1235 /// The custom property this slot is read through.
1236 pub fn token(self) -> &'static str {
1237 match self {
1238 FontSlot::Mono => "--font-mono",
1239 FontSlot::Sans => "--font-sans",
1240 FontSlot::Display => "--font-display",
1241 }
1242 }
1243
1244 /// The house stack, or `None` for the brand tier.
1245 pub fn house_default(self) -> Option<&'static str> {
1246 match self {
1247 FontSlot::Mono => Some(FONT_MONO),
1248 FontSlot::Sans => Some(FONT_SANS),
1249 FontSlot::Display => None,
1250 }
1251 }
1252
1253 /// The house face behind that stack, or `None` for the brand tier.
1254 ///
1255 /// The counterpart of [`house_default`](Self::house_default), and the same
1256 /// split as [`Typography::resolve`] against [`Typography::faces`]: one
1257 /// names the family that wins, the other names the file behind it. The
1258 /// house tier was a format string until this existed, so it could be
1259 /// emitted and not read — which made [`Typography::faces`] answer for the
1260 /// brand tier and stay silent about the other two.
1261 ///
1262 /// The sources are the **web** copies. A native loader wants a `ttf` and
1263 /// cuts its own through `quasi-type`, whose `cut_native` writes the file
1264 /// and hands back the family, style and default weight to register it
1265 /// under; there is no house `ttf` named here, and there should not be. This
1266 /// crate is on crates.io and `quasi-type` is `publish = false`, so naming a
1267 /// native file here would assert a path the web build does not write and
1268 /// save the consumer nothing, since it still has to run the pipeline.
1269 ///
1270 /// One hazard travels with that arrangement and is not solved: a native
1271 /// consumer takes `quasi-type` as a git dep and pins a rev, so a stale pin
1272 /// ships an older glyph set silently. Advance it deliberately.
1273 pub fn house_face(self) -> Option<FontFace> {
1274 let (family, file) = match self {
1275 FontSlot::Mono => (HOUSE_MONO_FAMILY, WEBFONT_MONO_FILE),
1276 FontSlot::Sans => (HOUSE_SANS_FAMILY, WEBFONT_SANS_FILE),
1277 FontSlot::Display => return None,
1278 };
1279 Some(
1280 FontFace::new(family, [file])
1281 .with_weight(HOUSE_WEIGHT_RANGE)
1282 .with_style("normal"),
1283 )
1284 }
1285 }
1286
1287 /// One `@font-face` an override brings with it.
1288 ///
1289 /// A product overriding a slot usually has to ship the face too, and the two
1290 /// halves have to agree on a family name. Declaring them together is what
1291 /// makes that agreement structural rather than a string typed twice.
1292 #[derive(Debug, Clone)]
1293 pub struct FontFace {
1294 family: String,
1295 sources: Vec<String>,
1296 weight: Option<String>,
1297 style: Option<String>,
1298 }
1299
1300 impl FontFace {
1301 /// A face named `family`, fetched from `sources`.
1302 ///
1303 /// Each source is either a bare filename, resolved against the
1304 /// [`Typography`] base URL, or an absolute one (`/…` or `https://…`) taken
1305 /// as written. The `format()` hint is inferred from the extension —
1306 /// `woff2`, `woff`, `ttf`, `otf` — and omitted for anything else rather
1307 /// than guessed, since a wrong hint is worse than none.
1308 pub fn new<S: Into<String>>(
1309 family: impl Into<String>,
1310 sources: impl IntoIterator<Item = S>,
1311 ) -> Self {
1312 Self {
1313 family: family.into(),
1314 sources: sources.into_iter().map(Into::into).collect(),
1315 weight: None,
1316 style: None,
1317 }
1318 }
1319
1320 /// `font-weight`, as CSS writes it: `"700"`, or `"200 800"` for a variable
1321 /// axis. Omitted when unset, which means `normal`.
1322 ///
1323 /// A variable face MUST name its range here for the same reason the house
1324 /// faces do: a `@font-face` with no range makes the browser resolve every
1325 /// weight to the file's default instance.
1326 #[must_use]
1327 pub fn with_weight(mut self, weight: impl Into<String>) -> Self {
1328 self.weight = Some(weight.into());
1329 self
1330 }
1331
1332 /// `font-style`. Omitted when unset, which means `normal`.
1333 #[must_use]
1334 pub fn with_style(mut self, style: impl Into<String>) -> Self {
1335 self.style = Some(style.into());
1336 self
1337 }
1338
1339 /// The declared `font-weight`, or `None` when the face never named one.
1340 ///
1341 /// A renderer loading a variable face directly has to name a weight — the
1342 /// file's own default instance is whatever the base shipped, which for the
1343 /// house faces is ExtraLight — so this is the half of the declaration that
1344 /// stops the load from being a guess.
1345 pub fn weight(&self) -> Option<&str> {
1346 self.weight.as_deref()
1347 }
1348
1349 /// The declared `font-style`, or `None`, which means `normal`.
1350 pub fn style(&self) -> Option<&str> {
1351 self.style.as_deref()
1352 }
1353
1354 /// The family name, as the stack has to spell it.
1355 ///
1356 /// For a renderer that loads faces rather than emitting CSS this is the
1357 /// name it registers the file under, and reading it here is what keeps
1358 /// that name from being typed a second time.
1359 pub fn family(&self) -> &str {
1360 &self.family
1361 }
1362
1363 /// The sources, unresolved — bare filenames as they were declared, not
1364 /// joined to any base URL. A renderer loading from disk or from an
1365 /// `include_bytes!` wants the filename; only the CSS wants the URL.
1366 pub fn sources(&self) -> &[String] {
1367 &self.sources
1368 }
1369
1370 fn css(&self, base: &str) -> String {
1371 use std::fmt::Write as _;
1372
1373 let src = self
1374 .sources
1375 .iter()
1376 .map(|s| {
1377 let url = if s.starts_with('/') || s.contains("://") {
1378 s.clone()
1379 } else {
1380 format!("{base}/{s}")
1381 };
1382 match font_format(s) {
1383 Some(fmt) => format!("url(\"{url}\") format(\"{fmt}\")"),
1384 None => format!("url(\"{url}\")"),
1385 }
1386 })
1387 .collect::<Vec<_>>()
1388 .join(",\n ");
1389
1390 let mut out = format!(
1391 "@font-face {{\n font-family: \"{}\";\n src: {src};\n",
1392 self.family
1393 );
1394 if let Some(w) = &self.weight {
1395 let _ = writeln!(out, " font-weight: {w};");
1396 }
1397 if let Some(s) = &self.style {
1398 let _ = writeln!(out, " font-style: {s};");
1399 }
1400 out.push_str(" font-display: swap;\n}\n\n");
1401 out
1402 }
1403 }
1404
1405 /// The `format()` hint for a source, by extension. `None` when unrecognised.
1406 fn font_format(source: &str) -> Option<&'static str> {
1407 match source.rsplit('.').next()?.to_ascii_lowercase().as_str() {
1408 "woff2" => Some("woff2"),
1409 "woff" => Some("woff"),
1410 "ttf" => Some("truetype"),
1411 "otf" => Some("opentype"),
1412 _ => None,
1413 }
1414 }
1415
1416 /// One product's answer for one slot: the stack, and any faces it ships.
1417 #[derive(Debug, Clone)]
1418 pub struct FontOverride {
1419 slot: FontSlot,
1420 stack: String,
1421 faces: Vec<FontFace>,
1422 }
1423
1424 impl FontOverride {
1425 /// Point `slot` at `stack`.
1426 ///
1427 /// `stack` is the CSS value the token takes, written the way the house
1428 /// stacks are: the family, then one hop to a system generic. Layer 2 is
1429 /// still one hop and no further — an override is a different answer to the
1430 /// slot, not a licence to write the fallback chain the standard deleted.
1431 pub fn new(slot: FontSlot, stack: impl Into<String>) -> Self {
1432 Self {
1433 slot,
1434 stack: stack.into(),
1435 faces: Vec::new(),
1436 }
1437 }
1438
1439 /// Ship a face with the override.
1440 #[must_use]
1441 pub fn with_face(mut self, face: FontFace) -> Self {
1442 self.faces.push(face);
1443 self
1444 }
1445
1446 /// The slot this answers.
1447 pub fn slot(&self) -> FontSlot {
1448 self.slot
1449 }
1450
1451 /// The stack it resolves to.
1452 pub fn stack(&self) -> &str {
1453 &self.stack
1454 }
1455
1456 /// The faces it ships, in declaration order.
1457 pub fn faces(&self) -> &[FontFace] {
1458 &self.faces
1459 }
1460 }
1461
1462 /// The whole typography layer for one product: the house defaults, plus
1463 /// whatever it overrides.
1464 ///
1465 /// This is what a build script composes and what
1466 /// `makeover_build::typography_css_from` writes. [`typography_css_vars`] and
1467 /// [`font_face_css`] are the no-override case of it and stay for callers that
1468 /// have nothing to declare.
1469 #[derive(Debug, Clone)]
1470 pub struct Typography {
1471 base_url: String,
1472 overrides: Vec<FontOverride>,
1473 }
1474
1475 impl Typography {
1476 /// The house layer alone, fetching faces from `base_url` — the directory
1477 /// the consumer serves fonts from, with or without a trailing slash.
1478 pub fn house(base_url: impl Into<String>) -> Self {
1479 Self {
1480 base_url: base_url.into(),
1481 overrides: Vec::new(),
1482 }
1483 }
1484
1485 /// Add one product override.
1486 ///
1487 /// # Panics
1488 ///
1489 /// If the slot is already overridden. One declaration per product per
1490 /// slot: a second is not a merge to resolve, it is two answers to a
1491 /// question that has one, and the vocabulary is what wants fixing.
1492 #[must_use]
1493 pub fn with_override(mut self, ov: FontOverride) -> Self {
1494 assert!(
1495 !self.overrides.iter().any(|o| o.slot == ov.slot),
1496 "{} is overridden twice; one declaration per product per slot",
1497 ov.slot.token()
1498 );
1499 self.overrides.push(ov);
1500 self
1501 }
1502
1503 /// What `slot` resolves to under this layer, or `None` for a brand slot
1504 /// nobody overrode.
1505 ///
1506 /// The resolution, for a renderer that has a face to choose rather than a
1507 /// stylesheet to emit.
1508 pub fn resolve(&self, slot: FontSlot) -> Option<&str> {
1509 self.overrides
1510 .iter()
1511 .find(|o| o.slot == slot)
1512 .map(|o| o.stack.as_str())
1513 .or_else(|| slot.house_default())
1514 }
1515
1516 /// The faces a product ships for `slot`, in declaration order, or an
1517 /// empty slice for a slot it did not override.
1518 ///
1519 /// The other half of [`resolve`](Self::resolve), for a renderer that has
1520 /// to load a file rather than name a stack: `resolve` says which family
1521 /// wins, this says where the bytes come from, what to call them, and at
1522 /// what weight. The
1523 /// house faces are not here — they belong to the slot rather than to any
1524 /// one product, and [`FontSlot::house_face`] is where they answer.
1525 pub fn faces(&self, slot: FontSlot) -> &[FontFace] {
1526 self.overrides
1527 .iter()
1528 .find(|o| o.slot == slot)
1529 .map_or(&[], |o| o.faces())
1530 }
1531
1532 /// The `@font-face` rules: the two house faces, then each override's.
1533 pub fn font_face_css(&self) -> String {
1534 let base = self.base_url.trim_end_matches('/');
1535 let mut out = font_face_css(base);
1536 for ov in &self.overrides {
1537 for face in &ov.faces {
1538 out.push_str(&face.css(base));
1539 }
1540 }
1541 out
1542 }
1543
1544 /// The resolved tokens as CSS declarations, no selector.
1545 pub fn css_declarations(&self) -> String {
1546 use std::fmt::Write as _;
1547
1548 let mut out = String::new();
1549 for slot in FontSlot::ALL {
1550 if let Some(stack) = self.resolve(slot) {
1551 let _ = writeln!(out, " {}: {stack};", slot.token());
1552 }
1553 }
1554 out
1555 }
1556
1557 /// The resolved tokens as a `:root { … }` block.
1558 pub fn css_vars(&self) -> String {
1559 format!(":root {{\n{}}}\n", self.css_declarations())
1560 }
1561
1562 /// Faces then tokens, in the order a stylesheet wants them.
1563 pub fn css(&self) -> String {
1564 format!("{}{}", self.font_face_css(), self.css_vars())
1565 }
1566 }
1567
1568 // ============================================================================
1569 // Loading / parsing
1570 // ============================================================================
1571
1572 /// Validate a theme ID contains only safe characters (alphanumeric, hyphens, underscores).
1573 pub fn validate_theme_id(id: &str) -> Result<(), String> {
1574 if !id
1575 .chars()
1576 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
1577 {
1578 return Err(format!("Invalid theme ID: {id}"));
1579 }
1580 Ok(())
1581 }
1582
1583 /// Parse the `[meta]` section into `ThemeMeta`.
1584 ///
1585 /// Falls back to the file ID as the name and `"dark"` as the variant.
1586 pub fn parse_meta(id: &str, table: &toml::Table, is_custom: bool) -> ThemeMeta {
1587 let meta = table.get("meta").and_then(|m| m.as_table());
1588 let name = meta
1589 .and_then(|m| m.get("name"))
1590 .and_then(|v| v.as_str())
1591 .unwrap_or(id)
1592 .to_string();
1593 let variant = meta
1594 .and_then(|m| m.get("variant"))
1595 .and_then(|v| v.as_str())
1596 .unwrap_or("dark")
1597 .to_string();
1598
1599 ThemeMeta {
1600 id: id.to_string(),
1601 name,
1602 variant,
1603 is_custom,
1604 }
1605 }
1606
1607 // ============================================================================
1608 // Choosing a theme.
1609 //
1610 // The file half of this crate was always shared; the *selection* half was not,
1611 // and four apps re-rolled it four ways. GoingsOn stores a "system" sentinel in
1612 // localStorage, Balanced Breakfast treats an absent value as follow-the-system
1613 // and hardcodes two theme ids as its light/dark pair, audiofiles keeps the id
1614 // in a synced SQLite table, and the Alloy console parses COLORFGBG. They also
1615 // disagreed about what a variant string means: this crate defaults a missing
1616 // one to "dark" while alloy_tui parsed an unrecognized one as light.
1617 //
1618 // What cannot be shared is the store — localStorage, a synced config table and
1619 // a TOML file are genuinely different places. What can be shared, and is here,
1620 // is the *meaning*: one vocabulary for variants, one encoding for "what did the
1621 // user choose", and one rule for turning that into an id that exists.
1622 // ============================================================================
1623
1624 /// A theme's kind, as declared by `meta.variant`.
1625 ///
1626 /// Three, not two: one shipped theme is `high-contrast`, and an app that
1627 /// matched on light-or-dark alone would quietly file it under the wrong one.
1628 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1629 #[serde(rename_all = "kebab-case")]
1630 pub enum Variant {
1631 Light,
1632 Dark,
1633 HighContrast,
1634 }
1635
1636 impl Variant {
1637 /// The spelling used in a theme file and in [`ThemeMeta::variant`].
1638 #[must_use]
1639 pub const fn as_str(self) -> &'static str {
1640 match self {
1641 Variant::Light => "light",
1642 Variant::Dark => "dark",
1643 Variant::HighContrast => "high-contrast",
1644 }
1645 }
1646
1647 /// Read a variant string, or `None` if it names none of them.
1648 #[must_use]
1649 pub fn parse(raw: &str) -> Option<Self> {
1650 match raw {
1651 "light" => Some(Variant::Light),
1652 "dark" => Some(Variant::Dark),
1653 "high-contrast" => Some(Variant::HighContrast),
1654 _ => None,
1655 }
1656 }
1657 }
1658
1659 impl std::fmt::Display for Variant {
1660 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1661 f.write_str(self.as_str())
1662 }
1663 }
1664
1665 /// Anything unrecognized reads as dark, which is what [`parse_meta`] already
1666 /// does with a missing one. Consumers that guessed light for an unknown string
1667 /// were disagreeing with the crate that produced it.
1668 impl From<&str> for Variant {
1669 fn from(raw: &str) -> Self {
1670 Variant::parse(raw).unwrap_or(Variant::Dark)
1671 }
1672 }
1673
1674 impl ThemeMeta {
1675 /// This theme's variant as a value rather than a string.
1676 #[must_use]
1677 pub fn kind(&self) -> Variant {
1678 Variant::from(self.variant.as_str())
1679 }
1680 }
1681
1682 /// The spelling of "follow whatever the system is doing", in every store.
1683 pub const FOLLOW: &str = "system";
1684
1685 /// What the user chose, as opposed to what is being rendered.
1686 ///
1687 /// The distinction is the whole point: `Follow` is a standing instruction that
1688 /// resolves differently as the ambient mode changes, and a `Fixed` id is an
1689 /// answer that does not. An app that stored only the rendered id could not tell
1690 /// the two apart the next time the system flipped to dark.
1691 #[derive(Debug, Clone, PartialEq, Eq, Default)]
1692 pub enum ThemeSelection {
1693 /// Track the ambient light/dark mode.
1694 #[default]
1695 Follow,
1696 /// Always this theme.
1697 Fixed(String),
1698 }
1699
1700 impl ThemeSelection {
1701 /// Read a stored selection. An empty or absent value is [`Follow`], which
1702 /// is what an app with nothing saved yet should do.
1703 ///
1704 /// [`Follow`]: ThemeSelection::Follow
1705 #[must_use]
1706 pub fn parse(raw: Option<&str>) -> Self {
1707 match raw.map(str::trim) {
1708 None | Some("" | FOLLOW) => ThemeSelection::Follow,
1709 Some(id) => ThemeSelection::Fixed(id.to_string()),
1710 }
1711 }
1712
1713 /// The string to persist, whatever the store is.
1714 #[must_use]
1715 pub fn as_str(&self) -> &str {
1716 match self {
1717 ThemeSelection::Follow => FOLLOW,
1718 ThemeSelection::Fixed(id) => id,
1719 }
1720 }
1721
1722 /// Turn a selection into a theme id that exists.
1723 ///
1724 /// `ambient` is the light/dark mode the app learned however it can: a
1725 /// `prefers-color-scheme` media query, an OS appearance API, `COLORFGBG`
1726 /// from a terminal. `available` is what [`list_themes_from_dirs`] found.
1727 ///
1728 /// A `Fixed` id that is no longer on disk falls through to the same path as
1729 /// `Follow` rather than being returned anyway. Themes are deletable in
1730 /// three of the four apps, and handing back an id that will fail to load
1731 /// only moves the error somewhere less helpful.
1732 ///
1733 /// The fallback chain is: the app's own default for the ambient mode if it
1734 /// is installed, then any installed theme of that variant, then the app's
1735 /// default regardless. The last step means this always returns something,
1736 /// and an app with no theme directory at all gets the id it ships with and
1737 /// the load error it would have had anyway.
1738 #[must_use]
1739 pub fn resolve(
1740 &self,
1741 ambient: Variant,
1742 defaults: &ThemeDefaults,
1743 available: &[ThemeMeta],
1744 ) -> String {
1745 let installed = |id: &str| available.iter().any(|meta| meta.id == id);
1746
1747 if let ThemeSelection::Fixed(id) = self
1748 && installed(id)
1749 {
1750 return id.clone();
1751 }
1752
1753 let preferred = defaults.for_variant(ambient);
1754 if installed(preferred) {
1755 return preferred.to_string();
1756 }
1757 available
1758 .iter()
1759 .find(|meta| meta.kind() == ambient)
1760 .map_or_else(|| preferred.to_string(), |meta| meta.id.clone())
1761 }
1762 }
1763
1764 impl std::fmt::Display for ThemeSelection {
1765 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1766 f.write_str(self.as_str())
1767 }
1768 }
1769
1770 /// The themes an app falls back to, one per ambient mode.
1771 ///
1772 /// App-specific on purpose: which theme is "the app's own" is the app's
1773 /// identity, not this crate's business. What is shared is everything around it.
1774 #[derive(Debug, Clone)]
1775 pub struct ThemeDefaults {
1776 light: String,
1777 dark: String,
1778 high_contrast: Option<String>,
1779 }
1780
1781 impl ThemeDefaults {
1782 pub fn new(light: impl Into<String>, dark: impl Into<String>) -> Self {
1783 Self {
1784 light: light.into(),
1785 dark: dark.into(),
1786 high_contrast: None,
1787 }
1788 }
1789
1790 /// Name a theme for a high-contrast ambient mode. Without one, that mode
1791 /// falls back to the dark default, which is the safer of the two to read.
1792 #[must_use]
1793 pub fn high_contrast(mut self, id: impl Into<String>) -> Self {
1794 self.high_contrast = Some(id.into());
1795 self
1796 }
1797
1798 /// Whether a high-contrast default was named.
1799 ///
1800 /// [`for_variant`] answers for every mode by falling back to the dark
1801 /// theme, which is right for resolving a selection and wrong for emitting
1802 /// a `prefers-contrast: more` block: that block would then answer the
1803 /// preference with a theme that does not honour it. A caller that renders
1804 /// per ambient mode asks this first.
1805 ///
1806 /// [`for_variant`]: ThemeDefaults::for_variant
1807 #[must_use]
1808 pub const fn names_high_contrast(&self) -> bool {
1809 self.high_contrast.is_some()
1810 }
1811
1812 #[must_use]
1813 pub fn for_variant(&self, variant: Variant) -> &str {
1814 match variant {
1815 Variant::Light => &self.light,
1816 Variant::Dark => &self.dark,
1817 Variant::HighContrast => self.high_contrast.as_ref().unwrap_or(&self.dark),
1818 }
1819 }
1820 }
1821
1822 // ============================================================================
1823 // Where themes are looked for.
1824 //
1825 // Four apps built this vector by hand, two of them byte-for-byte identically,
1826 // and one of them built it backwards: the Alloy console pushed the user's own
1827 // directory first, under a comment saying "highest precedence first", when both
1828 // consumers of the vector resolve *last* wins. A user's custom theme lost to
1829 // the packaged one of the same id.
1830 //
1831 // Hence a builder that names the tiers rather than a function taking a vector.
1832 // The precedence is stated once, here, and a caller cannot express it backwards
1833 // because the order is not theirs to choose.
1834 // ============================================================================
1835
1836 /// Builds the search path [`load_theme`] and [`list_themes_from_dirs`] take.
1837 ///
1838 /// Tiers are added in whatever order is convenient and always end up in
1839 /// precedence order: the user's own themes win, then whatever the system
1840 /// ships, then whatever the app bundles.
1841 ///
1842 /// A directory that does not exist is dropped rather than carried, so callers
1843 /// can offer every tier they might have without checking each one.
1844 #[derive(Debug, Default, Clone)]
1845 pub struct ThemeDirs {
1846 bundled: Vec<PathBuf>,
1847 system: Vec<PathBuf>,
1848 custom: Option<PathBuf>,
1849 }
1850
1851 impl ThemeDirs {
1852 #[must_use]
1853 pub fn new() -> Self {
1854 Self::default()
1855 }
1856
1857 /// Themes the app ships with. Lowest precedence.
1858 ///
1859 /// Takes more than one because a Tauri app has two: the bundled resource
1860 /// directory in production, and the tree `build.rs` materialized for a
1861 /// `cargo run` that has no resource directory at all.
1862 #[must_use]
1863 pub fn bundled(mut self, dir: Option<PathBuf>) -> Self {
1864 self.bundled.extend(dir);
1865 self
1866 }
1867
1868 /// Themes the machine ships, from an image or a package. Overrides bundled.
1869 #[must_use]
1870 pub fn system(mut self, dir: Option<PathBuf>) -> Self {
1871 self.system.extend(dir);
1872 self
1873 }
1874
1875 /// The user's own themes. Highest precedence, and the only tier flagged
1876 /// custom, which is what makes them exportable and deletable.
1877 #[must_use]
1878 pub fn custom(mut self, dir: Option<PathBuf>) -> Self {
1879 self.custom = dir;
1880 self
1881 }
1882
1883 /// The search path, lowest precedence first.
1884 #[must_use]
1885 pub fn build(self) -> Vec<(PathBuf, bool)> {
1886 let mut dirs = Vec::new();
1887 for dir in self.bundled.into_iter().chain(self.system) {
1888 if dir.is_dir() {
1889 dirs.push((dir, false));
1890 }
1891 }
1892 if let Some(dir) = self.custom
1893 && dir.is_dir()
1894 {
1895 dirs.push((dir, true));
1896 }
1897 dirs
1898 }
1899 }
1900
1901 /// Extract the intent color sections into a flat `HashMap` with dotted keys
1902 /// like `"surface.page"`, `"status.danger"`, `"category.one"`.
1903 ///
1904 /// The tonal steps of `content.primary` are filled in here rather than read, by
1905 /// [`derive_tonal_steps`]. Anything a theme authored under those keys is
1906 /// replaced.
1907 pub fn extract_colors(table: &toml::Table) -> HashMap<String, String> {
1908 let mut colors = HashMap::new();
1909 for section in COLOR_SECTIONS {
1910 if let Some(sect) = table.get(*section).and_then(|s| s.as_table()) {
1911 for (key, val) in sect {
1912 if let Some(color) = val.as_str() {
1913 colors.insert(format!("{section}.{key}"), color.to_string());
1914 }
1915 }
1916 }
1917 }
1918 derive_tonal_steps(&mut colors);
1919 colors
1920 }
1921
1922 /// Fill in the tonal steps of `content.primary`, overwriting whatever the theme
1923 /// authored under those keys.
1924 ///
1925 /// # Why they are not authored
1926 ///
1927 /// `content.secondary` and `content.muted` are not independent colours. They are
1928 /// the ink, one step and two steps back, and a theme that names them separately
1929 /// is stating three times something it stated once — which is how three of the
1930 /// bundled themes came to author a `secondary` *lighter* than their own
1931 /// `primary` (nord, solarized-dark) or identical to it (dracula), inverting the
1932 /// emphasis ramp the whole vocabulary rests on. Deriving them makes
1933 /// `content` > `content-secondary` > `content-muted` true by construction in
1934 /// every theme, including one a user writes.
1935 ///
1936 /// Applied at load rather than in [`resolve`] so that there is one answer: the
1937 /// resolved token layer, the ANSI table ([`ansi_intent`] reads authored keys),
1938 /// and every consumer holding a [`ThemeColors`] all see the same value. A
1939 /// derivation visible from only one of those is how a terminal and a webview
1940 /// come to disagree about what muted means.
1941 ///
1942 /// Both keys need `content.primary` and `surface.page` to exist and parse. When
1943 /// either is missing the step is skipped and anything authored is left where it
1944 /// is, mirroring the skip-missing behaviour of the rest of the crate — a
1945 /// half-written theme keeps whatever it has rather than losing it.
1946 ///
1947 /// # The ratio is a starting point, not the answer
1948 ///
1949 /// Each step is pushed further toward the page until it clears [`STEP_FLOOR`]
1950 /// against the ink, so what the theme gets is a step that can be seen rather
1951 /// than a step of the agreed size. The two are the same number in every bundled
1952 /// theme but the two with a pure-black ink, where the ratio has no range to
1953 /// travel in and the nominal step lands 3/255 from where it started.
1954 pub fn derive_tonal_steps<S: std::hash::BuildHasher>(colors: &mut HashMap<String, String, S>) {
1955 let ink = colors.get("content.primary").and_then(|v| Rgb::from_hex(v));
1956 let page = colors.get("surface.page").and_then(|v| Rgb::from_hex(v));
1957 let (Some(ink), Some(page)) = (ink, page) else {
1958 return;
1959 };
1960 // Each step starts no nearer than the one before it landed, so pushing
1961 // secondary out cannot carry it past muted and invert the ramp.
1962 let mut reached = 0.0;
1963 for (key, step) in [
1964 ("content.secondary", Emphasis::Secondary),
1965 ("content.muted", Emphasis::Muted),
1966 ] {
1967 let (color, ratio) = step_clearing_floor(ink, page, step.ratio().max(reached));
1968 reached = ratio;
1969 colors.insert(key.to_string(), color.to_hex());
1970 }
1971 }
1972
1973 /// The step `from` of the way from `ink` to `page`, pushed toward `page` until
1974 /// it clears [`STEP_FLOOR`] against the ink it is a step of. Returns the colour
1975 /// and the ratio it was found at.
1976 ///
1977 /// A forward scan rather than a solve, because it wants the *first* ratio that
1978 /// clears: contrast against the base rises with the distance travelled, but it
1979 /// rises through sRGB's transfer curve and OKLab's chroma path, and a bisection
1980 /// would trust a monotonicity nothing here guarantees.
1981 ///
1982 /// Travel stops at the ground. A theme whose ink and page are the same colour
1983 /// has no step to take, and the ground is the honest answer — nothing past it
1984 /// is a step of the ink any more.
1985 fn step_clearing_floor(ink: Rgb, page: Rgb, from: f32) -> (Rgb, f32) {
1986 // Finer than 8-bit sRGB can resolve on the shortest ramp in the corpus, so
1987 // the scan never steps over the first colour that clears.
1988 const PROBE: f32 = 0.005;
1989 let mut ratio = from.clamp(0.0, 1.0);
1990 loop {
1991 let color = tonal(ink, page, ratio);
1992 if wcag_contrast(color, ink) >= STEP_FLOOR || ratio >= 1.0 {
1993 return (color, ratio);
1994 }
1995 ratio = (ratio + PROBE).min(1.0);
1996 }
1997 }
1998
1999 /// Scan directories for `.toml` theme files and return metadata for each.
2000 ///
2001 /// Directories are checked in order; later entries override earlier ones by ID.
2002 /// Each entry in `dirs` is `(path, is_custom)`.
2003 pub fn list_themes_from_dirs(dirs: &[(PathBuf, bool)]) -> Vec<ThemeMeta> {
2004 let mut seen: HashMap<String, ThemeMeta> = HashMap::new();
2005
2006 for (dir, is_custom) in dirs {
2007 let Ok(entries) = std::fs::read_dir(dir) else {
2008 continue;
2009 };
2010
2011 for entry in entries {
2012 let Ok(entry) = entry else {
2013 continue;
2014 };
2015 let path = entry.path();
2016 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
2017 continue;
2018 }
2019
2020 let id = path
2021 .file_stem()
2022 .and_then(|s| s.to_str())
2023 .unwrap_or_default()
2024 .to_string();
2025
2026 let Ok(content) = std::fs::read_to_string(&path) else {
2027 continue;
2028 };
2029 let table: toml::Table = match content.parse() {
2030 Ok(t) => t,
2031 Err(_) => continue,
2032 };
2033
2034 seen.insert(id.clone(), parse_meta(&id, &table, *is_custom));
2035 }
2036 }
2037
2038 let mut themes: Vec<ThemeMeta> = seen.into_values().collect();
2039 themes.sort_by(|a, b| a.name.cmp(&b.name));
2040 themes
2041 }
2042
2043 /// How legible a theme's muted text is, measured rather than declared.
2044 ///
2045 /// The worst WCAG contrast ratio of `content.muted` against the two panel
2046 /// grounds a reader actually meets it on, `surface.page` and `surface.sunken`,
2047 /// bucketed at the two thresholds WCAG 2.x draws. Worst rather than average,
2048 /// because a theme that is legible on one panel and not the other is a theme
2049 /// with an illegible panel.
2050 ///
2051 /// It is measured here rather than authored in the theme file for the reason
2052 /// the whole crate exists: a curated palette keeps its identity and the reader
2053 /// still gets told what it costs them. An author cannot mis-declare it, and a
2054 /// theme edited on disk re-measures on the next scan.
2055 ///
2056 /// Ordered worst-first, so `sort` puts the most legible theme last and
2057 /// [`theme_options`] reverses it into what a picker wants at the top.
2058 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
2059 #[serde(rename_all = "kebab-case")]
2060 pub enum ContrastTier {
2061 /// Muted text below the 3:1 floor WCAG sets for large text and UI parts.
2062 Low,
2063 /// Muted text meets 3:1 but not the 4.5:1 bar for normal text.
2064 Standard,
2065 /// Muted text meets WCAG AA on every panel ground, 4.5:1 or better.
2066 High,
2067 }
2068
2069 impl ContrastTier {
2070 /// The machine spelling, for a data attribute or a stored value.
2071 #[must_use]
2072 pub const fn as_str(self) -> &'static str {
2073 match self {
2074 ContrastTier::Low => "low",
2075 ContrastTier::Standard => "standard",
2076 ContrastTier::High => "high",
2077 }
2078 }
2079
2080 /// Measure a loaded theme.
2081 ///
2082 /// A theme missing either ground or the muted content colour reads as
2083 /// [`Standard`](Self::Standard): the measurement did not happen, and
2084 /// claiming `Low` would badge a theme for the scan's failure rather than
2085 /// its own.
2086 #[must_use]
2087 pub fn of(theme: &ThemeColors) -> Self {
2088 let colour = |key: &str| theme.colors.get(key).and_then(|v| Rgb::from_hex(v));
2089 let (Some(muted), Some(page), Some(sunken)) = (
2090 colour("content.muted"),
2091 colour("surface.page"),
2092 colour("surface.sunken"),
2093 ) else {
2094 return ContrastTier::Standard;
2095 };
2096
2097 let worst = wcag_contrast(muted, page).min(wcag_contrast(muted, sunken));
2098 if worst >= 4.5 {
2099 ContrastTier::High
2100 } else if worst >= 3.0 {
2101 ContrastTier::Standard
2102 } else {
2103 ContrastTier::Low
2104 }
2105 }
2106 }
2107
2108 /// One theme, as a picker offers it.
2109 ///
2110 /// [`ThemeMeta`] plus the two facts a picker needs and a scan is what supplies:
2111 /// the variant as a value rather than a string, and the measured contrast tier.
2112 /// Owned, because it outlives the directory scan that produced it and is held
2113 /// by an app across the frames or requests that draw the control.
2114 ///
2115 /// It carries no `is_custom`. A picker that sorted the user's own themes apart
2116 /// from the shipped ones would be answering a different question, and
2117 /// [`ThemeMeta`] is still there for a screen that wants it.
2118 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2119 #[serde(rename_all = "camelCase")]
2120 pub struct ThemeOption {
2121 /// The id stored, and the value the picker submits.
2122 pub id: String,
2123 /// What the picker reads.
2124 pub name: String,
2125 /// Which group it belongs to.
2126 pub variant: Variant,
2127 /// How legible its muted text measured.
2128 pub contrast: ContrastTier,
2129 }
2130
2131 /// Every installed theme, in the order a picker should offer them.
2132 ///
2133 /// This is the half of a theme picker that is not the control: which themes
2134 /// exist, which group each is in, how legible each one is, and what order that
2135 /// puts them in. Three apps derived it three ways and two of them lost it
2136 /// entirely when their pickers were described, which is what makes it the
2137 /// crate's job rather than each app's.
2138 ///
2139 /// # The order
2140 ///
2141 /// By variant in [`Variant`]'s own order — light, dark, high contrast — then
2142 /// by measured contrast **best first**, then by name. The middle key is the one
2143 /// no app can supply without redoing the work this crate has already done: the
2144 /// tier comes off the resolved colours, and an app sorting a `Vec<ThemeMeta>`
2145 /// has only the names.
2146 ///
2147 /// Grouping is left implicit in the order rather than returned as groups. A
2148 /// renderer that draws headings walks the run of one variant; one that cannot
2149 /// draw headings still gets the useful order. Handing back
2150 /// `Vec<(Variant, Vec<ThemeOption>)>` would force the second renderer to
2151 /// flatten what the first wanted, and neither shape is more true.
2152 ///
2153 /// # What it costs
2154 ///
2155 /// Every theme file is parsed twice: once by [`list_themes_from_dirs`] for its
2156 /// metadata, once here for the colours the tier is measured from. Measured
2157 /// rather than assumed to be cheap: a picker is drawn on a settings screen, the
2158 /// shipped set is around twenty files, and the alternative is caching a
2159 /// derived value that a theme edited on disk would then be wrong about.
2160 /// A theme whose colours will not load keeps its metadata and reads as
2161 /// [`ContrastTier::Standard`], on the same footing as one missing a ground.
2162 ///
2163 /// A host whose themes are not all on disk builds its own [`ThemeOption`]s and
2164 /// calls [`order_theme_options`], which is this function's second half.
2165 #[must_use]
2166 pub fn theme_options(dirs: &[(PathBuf, bool)]) -> Vec<ThemeOption> {
2167 let mut options: Vec<ThemeOption> = list_themes_from_dirs(dirs)
2168 .into_iter()
2169 .map(|meta| {
2170 let contrast = load_theme(dirs, &meta.id)
2171 .map_or(ContrastTier::Standard, |theme| ContrastTier::of(&theme));
2172 ThemeOption {
2173 variant: meta.kind(),
2174 contrast,
2175 id: meta.id,
2176 name: meta.name,
2177 }
2178 })
2179 .collect();
2180
2181 order_theme_options(&mut options);
2182 options
2183 }
2184
2185 /// Put an already-collected set into the order a picker offers them in.
2186 ///
2187 /// [`theme_options`]' second half, reachable on its own because not every host
2188 /// resolves its themes by scanning a directory. audiofiles embeds its shipped
2189 /// set at compile time and reads only its custom themes off disk, so a
2190 /// directory scan cannot see most of what it offers, and the alternative to
2191 /// this being public was that app re-deriving the sort — which is exactly the
2192 /// three-apps-three-orders state the picker was described to end.
2193 ///
2194 /// The order is by variant in [`Variant`]'s own order, then by measured
2195 /// contrast **best first**, then by name.
2196 pub fn order_theme_options(options: &mut [ThemeOption]) {
2197 options.sort_by(|a, b| {
2198 variant_order(a.variant)
2199 .cmp(&variant_order(b.variant))
2200 .then(b.contrast.cmp(&a.contrast))
2201 .then_with(|| a.name.cmp(&b.name))
2202 });
2203 }
2204
2205 /// Where a variant sits in a picker, light first.
2206 ///
2207 /// Not `Variant as usize`: the declaration order of an enum is not a promise
2208 /// about how it reads, and a member inserted for a fourth variant would
2209 /// silently reorder every picker in the tree.
2210 const fn variant_order(variant: Variant) -> u8 {
2211 match variant {
2212 Variant::Light => 0,
2213 Variant::Dark => 1,
2214 Variant::HighContrast => 2,
2215 }
2216 }
2217
2218 /// Find a theme file by ID in the given directories.
2219 ///
2220 /// Checks directories in reverse order so the highest-priority directory wins.
2221 /// Returns `(path, is_custom)` or `None` if not found.
2222 pub fn find_theme_path(dirs: &[(PathBuf, bool)], id: &str) -> Option<(PathBuf, bool)> {
2223 let filename = format!("{id}.toml");
2224
2225 for (dir, is_custom) in dirs.iter().rev() {
2226 let path = dir.join(&filename);
2227 if path.is_file() {
2228 return Some((path, *is_custom));
2229 }
2230 }
2231
2232 None
2233 }
2234
2235 /// Parse a complete theme (metadata + colors) from raw TOML content, with no
2236 /// filesystem access. For callers that embed themes at compile time.
2237 pub fn parse_theme_str(id: &str, content: &str, is_custom: bool) -> Result<ThemeColors, String> {
2238 validate_theme_id(id)?;
2239 let table: toml::Table = content
2240 .parse()
2241 .map_err(|e| format!("Failed to parse theme '{id}': {e}"))?;
2242 let meta = parse_meta(id, &table, is_custom);
2243 let colors = extract_colors(&table);
2244 Ok(ThemeColors { meta, colors })
2245 }
2246
2247 /// Load a complete theme (metadata + colors) by ID from the given directories.
2248 pub fn load_theme(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemeColors, String> {
2249 validate_theme_id(id)?;
2250
2251 let (path, is_custom) =
2252 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
2253
2254 let content = std::fs::read_to_string(&path)
2255 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
2256
2257 let table: toml::Table = content
2258 .parse()
2259 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
2260
2261 let meta = parse_meta(id, &table, is_custom);
2262 let colors = extract_colors(&table);
2263
2264 Ok(ThemeColors { meta, colors })
2265 }
2266
2267 /// Load a theme and resolve it to the full intent token set in one step.
2268 pub fn load_semantic(dirs: &[(PathBuf, bool)], id: &str) -> Result<SemanticTokens, String> {
2269 Ok(resolve(&load_theme(dirs, id)?))
2270 }
2271
2272 /// Import a theme TOML file into the custom themes directory.
2273 ///
2274 /// Validates that the file is parseable TOML with at least one intent color
2275 /// section, then copies it to `custom_dir/{id}.toml`. Returns the theme metadata.
2276 pub fn import_theme(source_path: &Path, custom_dir: &Path) -> Result<ThemeMeta, String> {
2277 let content = std::fs::read_to_string(source_path)
2278 .map_err(|e| format!("Failed to read {}: {}", source_path.display(), e))?;
2279
2280 let table: toml::Table = content.parse().map_err(|e| format!("Invalid TOML: {e}"))?;
2281
2282 let has_colors = COLOR_SECTIONS
2283 .iter()
2284 .any(|s| table.get(*s).and_then(|v| v.as_table()).is_some());
2285 if !has_colors {
2286 return Err(format!(
2287 "Theme file must have at least one color section ({})",
2288 COLOR_SECTIONS.join(", ")
2289 ));
2290 }
2291
2292 let id = source_path
2293 .file_stem()
2294 .and_then(|s| s.to_str())
2295 .ok_or("Invalid file name")?
2296 .to_string();
2297 validate_theme_id(&id)?;
2298
2299 std::fs::create_dir_all(custom_dir)
2300 .map_err(|e| format!("Failed to create {}: {}", custom_dir.display(), e))?;
2301
2302 let dest = custom_dir.join(format!("{id}.toml"));
2303 std::fs::copy(source_path, &dest).map_err(|e| format!("Failed to copy theme: {e}"))?;
2304
2305 Ok(parse_meta(&id, &table, true))
2306 }
2307
2308 /// Delete a custom theme by ID.
2309 ///
2310 /// Only operates on `custom_dir` — bundled themes are not deletable through
2311 /// this entry point.
2312 pub fn delete_theme(custom_dir: &Path, id: &str) -> Result<(), String> {
2313 validate_theme_id(id)?;
2314
2315 let path = custom_dir.join(format!("{id}.toml"));
2316 if !path.is_file() {
2317 return Err(format!("Custom theme '{id}' not found"));
2318 }
2319
2320 std::fs::remove_file(&path).map_err(|e| format!("Failed to delete {}: {}", path.display(), e))
2321 }
2322
2323 /// A four-color preview for theme thumbnails: the representative swatch from
2324 /// each of the principal roles.
2325 #[derive(Debug, Clone, Serialize)]
2326 #[serde(rename_all = "camelCase")]
2327 pub struct ThemePreview {
2328 pub meta: ThemeMeta,
2329 /// Page background (`surface.page`).
2330 pub background: Option<String>,
2331 /// Body text (`content.primary`).
2332 pub foreground: Option<String>,
2333 /// Brand/interactive color (`action.primary`).
2334 pub accent: Option<String>,
2335 /// Divider/outline color (`line.border`).
2336 pub border: Option<String>,
2337 }
2338
2339 fn color_at(table: &toml::Table, section: &str, key: &str) -> Option<String> {
2340 table
2341 .get(section)
2342 .and_then(|s| s.as_table())
2343 .and_then(|s| s.get(key))
2344 .and_then(|v| v.as_str())
2345 .map(std::string::ToString::to_string)
2346 }
2347
2348 /// Load just the preview swatches for a theme — for UI thumbnails.
2349 pub fn load_theme_preview(dirs: &[(PathBuf, bool)], id: &str) -> Result<ThemePreview, String> {
2350 validate_theme_id(id)?;
2351
2352 let (path, is_custom) =
2353 find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
2354
2355 let content = std::fs::read_to_string(&path)
2356 .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
2357
2358 let table: toml::Table = content
2359 .parse()
2360 .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
2361
2362 Ok(ThemePreview {
2363 meta: parse_meta(id, &table, is_custom),
2364 background: color_at(&table, "surface", "page"),
2365 foreground: color_at(&table, "content", "primary"),
2366 accent: color_at(&table, "action", "primary"),
2367 border: color_at(&table, "line", "border"),
2368 })
2369 }
2370
2371 /// Export a theme to a user-chosen path.
2372 pub fn export_theme(dirs: &[(PathBuf, bool)], id: &str, dest_path: &Path) -> Result<(), String> {
2373 validate_theme_id(id)?;
2374
2375 let (source, _) = find_theme_path(dirs, id).ok_or_else(|| format!("Theme '{id}' not found"))?;
2376
2377 std::fs::copy(&source, dest_path).map_err(|e| format!("Failed to export theme: {e}"))?;
2378
2379 Ok(())
2380 }
2381
2382 /// The themes this crate ships, embedded at compile time.
2383 ///
2384 /// `include_dir` is an implementation detail: the public API hands back plain
2385 /// `(id, toml_source)` pairs, so how the data is embedded can change without
2386 /// a breaking release.
2387 static EMBEDDED: include_dir::Dir<'static> =
2388 include_dir::include_dir!("$CARGO_MANIFEST_DIR/themes");
2389
2390 /// The themes this crate ships, as `(id, toml_source)` pairs.
2391 ///
2392 /// This is the path-free way to reach the bundled set, for consumers that
2393 /// cannot rely on a directory existing at runtime: a crate pulled from
2394 /// crates.io lives in a registry checkout whose location is not knowable at
2395 /// compile time, so `include_dir!` and asset-bundling globs in the depending
2396 /// crate have nothing stable to point at. Embedding here and re-exporting the
2397 /// contents gives them one source of truth without a path.
2398 ///
2399 /// Ordering follows the embedded directory and is not guaranteed; collect and
2400 /// sort by id where a stable order matters (a theme picker, say).
2401 pub fn embedded_themes() -> impl Iterator<Item = (&'static str, &'static str)> {
2402 EMBEDDED.files().filter_map(|file| {
2403 let path = file.path();
2404 if path.extension().and_then(|e| e.to_str()) != Some("toml") {
2405 return None;
2406 }
2407 let id = path.file_stem()?.to_str()?;
2408 Some((id, file.contents_utf8()?))
2409 })
2410 }
2411
2412 /// The theme directory this crate ships, for use as a build-from-source
2413 /// fallback.
2414 ///
2415 /// Resolves against `makeover`'s own manifest directory, fixed at compile
2416 /// time, so it works from a path dependency and from a cargo git checkout
2417 /// alike. Installed systems should put their packaged theme directory ahead
2418 /// of this in the search path; this is the entry that keeps `cargo run` in a
2419 /// fresh clone from coming up with no themes at all.
2420 ///
2421 /// Returns `None` when the directory is absent — a cargo cache that has been
2422 /// cleaned, or a vendored copy that dropped the data — so callers degrade to
2423 /// their remaining search path rather than failing.
2424 pub fn bundled_themes_dir() -> Option<PathBuf> {
2425 let themes = Path::new(env!("CARGO_MANIFEST_DIR")).join("themes");
2426 if themes.is_dir() { Some(themes) } else { None }
2427 }
2428
2429 #[cfg(test)]
2430 mod tests {
2431 use super::*;
2432 use std::fs;
2433
2434 // ---- id validation ----
2435
2436 #[test]
2437 fn validate_theme_id_alphanumeric() {
2438 assert!(validate_theme_id("darkmode").is_ok());
2439 assert!(validate_theme_id("Theme123").is_ok());
2440 }
2441
2442 #[test]
2443 fn validate_theme_id_hyphens_underscores() {
2444 assert!(validate_theme_id("dark-mode").is_ok());
2445 assert!(validate_theme_id("my_theme_v2").is_ok());
2446 }
2447
2448 #[test]
2449 fn validate_theme_id_rejects_path_traversal() {
2450 assert!(validate_theme_id("../etc/passwd").is_err());
2451 assert!(validate_theme_id("foo/bar").is_err());
2452 assert!(validate_theme_id("theme.toml").is_err());
2453 }
2454
2455 // ---- low-color terminals ----
2456
2457 #[test]
2458 fn the_ansi_palette_is_sixteen_distinct_colors() {
2459 let mut seen: Vec<(u8, u8, u8)> = ANSI_16.iter().map(|c| c.tuple()).collect();
2460 seen.sort_unstable();
2461 seen.dedup();
2462 assert_eq!(seen.len(), 16);
2463 }
2464
2465 // ---- the intent-to-slot table ----
2466
2467 // Sixteen slots, every one of them answered. A caller filling a terminal
2468 // palette has no fallback for a hole: the slot would keep whatever the
2469 // emulator started with, and one raw ANSI colour in a themed table is more
2470 // obviously wrong than all sixteen would be.
2471 #[test]
2472 fn every_ansi_slot_names_an_intent_on_either_polarity() {
2473 for variant in ["light", "dark", "high-contrast"] {
2474 for index in 0..16 {
2475 assert!(
2476 ansi_intent(index, variant).is_some(),
2477 "slot {index} unanswered on {variant}"
2478 );
2479 }
2480 assert_eq!(ansi_intent(16, variant), None);
2481 }
2482 }
2483
2484 // The property the four achromatic slots exist to hold: 0 is the darkest
2485 // tone the theme offers and 15 the lightest, in either polarity. A table
2486 // that pins slot 0 to `content.primary` passes this on a light theme and
2487 // inverts on a dark one, which is the bug the polarity split fixes.
2488 #[test]
2489 fn ansi_zero_is_darker_than_ansi_fifteen_on_either_polarity() {
2490 for id in ["akari-dawn", "akari-night"] {
2491 let theme = bundled(id);
2492 let slot = |i: usize| -> Rgb {
2493 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
2494 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
2495 };
2496 assert!(
2497 rel_luminance(slot(0)) < rel_luminance(slot(15)),
2498 "{id}: ANSI 0 {} should be darker than ANSI 15 {}",
2499 slot(0).to_hex(),
2500 slot(15).to_hex(),
2501 );
2502 }
2503 }
2504
2505 // The pair a greeter draws with: its container on 7, its text on 0. If
2506 // those collapse the login screen is one flat block, and slot 7 being a
2507 // surface rather than a text tone is what keeps them apart.
2508 #[test]
2509 fn the_container_slot_and_the_text_slot_stay_legible() {
2510 for id in ["akari-dawn", "akari-night"] {
2511 let theme = bundled(id);
2512 let slot = |i: usize| -> Rgb {
2513 let key = ansi_intent(i, &theme.meta.variant).expect("in range");
2514 Rgb::from_hex(theme.colors.get(key).expect("theme carries it")).expect("valid hex")
2515 };
2516 let contrast = wcag_contrast(slot(0), slot(7));
2517 assert!(contrast >= 4.5, "{id}: ANSI 0 on ANSI 7 is {contrast:.2}:1");
2518 }
2519 }
2520
2521 // The hues do not move with polarity. Red is the theme's danger tone on a
2522 // light theme and on a dark one, which is why only four slots are in the
2523 // polarity table at all.
2524 #[test]
2525 fn the_chromatic_slots_do_not_vary_with_polarity() {
2526 for index in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14] {
2527 assert_eq!(
2528 ansi_intent(index, "light"),
2529 ansi_intent(index, "dark"),
2530 "slot {index} moved with polarity"
2531 );
2532 }
2533 }
2534
2535 fn bundled(id: &str) -> ThemeColors {
2536 let dir = bundled_themes_dir().expect("makeover ships its themes");
2537 load_theme(&[(dir, false)], id).expect("the akari pair ships")
2538 }
2539
2540 #[test]
2541 fn quantize_picks_the_obvious_entry() {
2542 let black = Rgb { r: 0, g: 0, b: 0 };
2543 let white = Rgb {
2544 r: 255,
2545 g: 255,
2546 b: 255,
2547 };
2548 assert_eq!(quantize(black, &ANSI_16), 0);
2549 assert_eq!(quantize(white, &ANSI_16), 15);
2550 }
2551
2552 // Nearest-entry quantization is per-color, so two colors a theme keeps
2553 // apart can arrive as one. These two are both closest to the palette's
2554 // light gray, and a border drawn in one on a page painted the other is not
2555 // drawn at all.
2556 #[test]
2557 fn two_colors_can_quantize_to_one_entry() {
2558 let page = Rgb::from_hex("#a8a8a8").unwrap();
2559 let border = Rgb::from_hex("#b4b4b4").unwrap();
2560
2561 assert_eq!(quantize(page, &ANSI_16), quantize(border, &ANSI_16));
2562 assert_ne!(
2563 quantize_against(border, page, &ANSI_16),
2564 quantize(page, &ANSI_16)
2565 );
2566 }
2567
2568 #[test]
2569 fn quantize_against_keeps_the_border_off_the_page() {
2570 let page = Rgb::from_hex("#e4ded6").unwrap();
2571 let border = Rgb::from_hex("#7f786d").unwrap();
2572
2573 let shown_page = ANSI_16[quantize(page, &ANSI_16)];
2574 let shown_border = ANSI_16[quantize_against(border, page, &ANSI_16)];
2575
2576 assert!(
2577 wcag_contrast(shown_border, shown_page) >= DISTINCT,
2578 "border {} on page {} is {:.2}:1",
2579 shown_border.to_hex(),
2580 shown_page.to_hex(),
2581 wcag_contrast(shown_border, shown_page)
2582 );
2583 }
2584
2585 // A color that already reads against its background is left where it is,
2586 // so this can be applied without redesigning what already worked.
2587 #[test]
2588 fn quantize_against_leaves_a_readable_color_alone() {
2589 let page = Rgb::from_hex("#e4ded6").unwrap();
2590 let text = Rgb::from_hex("#1a1816").unwrap();
2591
2592 assert_eq!(
2593 quantize_against(text, page, &ANSI_16),
2594 quantize(text, &ANSI_16)
2595 );
2596 }
2597
2598 // With nothing in the palette to satisfy the request, the most legible
2599 // entry is the answer. Returning the nearest one would return the
2600 // background itself, which is the failure this function exists to avoid.
2601 #[test]
2602 fn an_impossible_palette_gets_the_most_legible_entry() {
2603 let page = Rgb::from_hex("#ffffff").unwrap();
2604 let border = Rgb::from_hex("#fefefe").unwrap();
2605 let palette = [
2606 Rgb::from_hex("#ffffff").unwrap(),
2607 Rgb::from_hex("#fdfdfd").unwrap(),
2608 ];
2609
2610 let chosen = palette[quantize_against(border, page, &palette)];
2611 assert_eq!(chosen.to_hex(), "#fdfdfd");
2612 }
2613
2614 // ---- meta ----
2615
2616 #[test]
2617 fn parse_meta_with_name_and_variant() {
2618 let table: toml::Table = "[meta]\nname = \"Nord\"\nvariant = \"light\"\n"
2619 .parse()
2620 .unwrap();
2621 let meta = parse_meta("nord", &table, false);
2622 assert_eq!(meta.id, "nord");
2623 assert_eq!(meta.name, "Nord");
2624 assert_eq!(meta.variant, "light");
2625 assert!(!meta.is_custom);
2626 }
2627
2628 #[test]
2629 fn parse_meta_defaults_to_id_and_dark() {
2630 let table: toml::Table = "".parse().unwrap();
2631 let meta = parse_meta("fallback", &table, true);
2632 assert_eq!(meta.name, "fallback");
2633 assert_eq!(meta.variant, "dark");
2634 assert!(meta.is_custom);
2635 }
2636
2637 // ---- color math (formulas must match the apps they came from) ----
2638
2639 #[test]
2640 fn rgb_hex_roundtrip() {
2641 assert_eq!(
2642 Rgb::from_hex("#6196FF").unwrap(),
2643 Rgb {
2644 r: 0x61,
2645 g: 0x96,
2646 b: 0xff
2647 }
2648 );
2649 assert_eq!(
2650 Rgb::from_hex("#abc").unwrap(),
2651 Rgb {
2652 r: 0xaa,
2653 g: 0xbb,
2654 b: 0xcc
2655 }
2656 );
2657 assert_eq!(
2658 Rgb {
2659 r: 0x61,
2660 g: 0x96,
2661 b: 0xff
2662 }
2663 .to_hex(),
2664 "#6196ff"
2665 );
2666 assert!(Rgb::from_hex("not-a-color").is_none());
2667 }
2668
2669 #[test]
2670 fn oklab_roundtrips_within_tolerance() {
2671 for hex in ["#6196ff", "#2e3440", "#ffffff", "#000000", "#c0392b"] {
2672 let c = Rgb::from_hex(hex).unwrap();
2673 let back = Rgb::from_oklab(c.to_oklab());
2674 // Gamut round-trip is near-exact (±1 per channel from rounding).
2675 assert!((c.r as i16 - back.r as i16).abs() <= 1, "{hex} r");
2676 assert!((c.g as i16 - back.g as i16).abs() <= 1, "{hex} g");
2677 assert!((c.b as i16 - back.b as i16).abs() <= 1, "{hex} b");
2678 }
2679 }
2680
2681 #[test]
2682 fn wcag_contrast_known_pairs() {
2683 let white = Rgb {
2684 r: 255,
2685 g: 255,
2686 b: 255,
2687 };
2688 let black = Rgb { r: 0, g: 0, b: 0 };
2689 assert!((wcag_contrast(white, black) - 21.0).abs() < 0.01);
2690 assert!((wcag_contrast(white, white) - 1.0).abs() < 0.01);
2691 }
2692
2693 #[test]
2694 fn readable_on_picks_by_wcag() {
2695 assert_eq!(
2696 readable_on(Rgb {
2697 r: 255,
2698 g: 255,
2699 b: 255
2700 }),
2701 Rgb { r: 0, g: 0, b: 0 }
2702 );
2703 assert_eq!(
2704 readable_on(Rgb { r: 0, g: 0, b: 0 }),
2705 Rgb {
2706 r: 255,
2707 g: 255,
2708 b: 255
2709 }
2710 );
2711 // A light blue action -> black text reads better.
2712 let action = Rgb::from_hex("#6196ff").unwrap();
2713 assert_eq!(readable_on(action), Rgb { r: 0, g: 0, b: 0 });
2714 }
2715
2716 #[test]
2717 fn lighten_darken_move_oklab_lightness() {
2718 let c = Rgb::from_hex("#6196ff").unwrap();
2719 let l0 = c.to_oklab().l;
2720 assert!(lighten(c, 0.05).to_oklab().l > l0);
2721 assert!(darken(c, 0.05).to_oklab().l < l0);
2722 }
2723
2724 #[test]
2725 fn mix_endpoints_and_midpoint() {
2726 let a = Rgb::from_hex("#000000").unwrap();
2727 let b = Rgb::from_hex("#6196ff").unwrap();
2728 assert_eq!(mix(a, b, 0.0), a);
2729 assert_eq!(mix(a, b, 1.0), b);
2730 // Midpoint sits between the endpoints in OKLab lightness.
2731 let mid = mix(a, b, 0.5).to_oklab().l;
2732 assert!(mid > a.to_oklab().l && mid < b.to_oklab().l);
2733 }
2734
2735 // ---- extract + resolve ----
2736
2737 fn nord_toml() -> &'static str {
2738 r##"
2739 [meta]
2740 name = "Nord"
2741 variant = "dark"
2742
2743 [surface]
2744 page = "#2e3440"
2745 raised = "#3b4252"
2746 sunken = "#434c5e"
2747 overlay = "#3b4252"
2748
2749 [content]
2750 primary = "#d8dee9"
2751 secondary = "#e5e9f0"
2752 muted = "#616e88"
2753
2754 [action]
2755 primary = "#81a1c1"
2756
2757 [status]
2758 danger = "#bf616a"
2759 success = "#a3be8c"
2760 warning = "#ebcb8b"
2761 info = "#88c0d0"
2762
2763 [line]
2764 border = "#4c566a"
2765
2766 [category]
2767 one = "#bf616a"
2768 two = "#a3be8c"
2769 three = "#81a1c1"
2770 four = "#ebcb8b"
2771 five = "#b48ead"
2772 six = "#88c0d0"
2773 "##
2774 }
2775
2776 #[test]
2777 fn extract_colors_reads_intent_sections() {
2778 let table: toml::Table = nord_toml().parse().unwrap();
2779 let colors = extract_colors(&table);
2780 assert_eq!(colors.get("surface.page").unwrap(), "#2e3440");
2781 assert_eq!(colors.get("content.primary").unwrap(), "#d8dee9");
2782 assert_eq!(colors.get("action.primary").unwrap(), "#81a1c1");
2783 assert_eq!(colors.get("status.danger").unwrap(), "#bf616a");
2784 assert_eq!(colors.get("line.border").unwrap(), "#4c566a");
2785 assert_eq!(colors.get("category.five").unwrap(), "#b48ead");
2786 assert_eq!(colors.len(), 19);
2787 }
2788
2789 #[test]
2790 fn resolve_base_intents_passthrough() {
2791 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2792 let t = resolve(&theme);
2793 assert_eq!(t.hex("surface-page"), Some("#2e3440"));
2794 assert_eq!(t.hex("content"), Some("#d8dee9")); // content.primary -> content
2795 // Not a passthrough: a tonal step of the ink, whatever the file said.
2796 assert_eq!(
2797 t.hex("content-muted").unwrap(),
2798 emphasized(
2799 Rgb::from_hex("#d8dee9").unwrap(),
2800 Rgb::from_hex("#2e3440").unwrap(),
2801 Emphasis::Muted
2802 )
2803 .to_hex()
2804 );
2805 assert_eq!(t.hex("action"), Some("#81a1c1"));
2806 assert_eq!(t.hex("danger"), Some("#bf616a"));
2807 assert_eq!(t.hex("border"), Some("#4c566a"));
2808 assert_eq!(t.hex("category-five"), Some("#b48ead"));
2809 }
2810
2811 #[test]
2812 fn a_tonal_step_lands_between_its_base_and_its_ground() {
2813 let ink = Rgb::from_hex("#d8dee9").unwrap();
2814 let page = Rgb::from_hex("#2e3440").unwrap();
2815 for step in [Emphasis::Full, Emphasis::Secondary, Emphasis::Muted] {
2816 let out = emphasized(ink, page, step).to_oklab().l;
2817 assert!(
2818 out <= ink.to_oklab().l && out >= page.to_oklab().l,
2819 "{step:?} left the interval between the ink and the page"
2820 );
2821 }
2822 assert_eq!(emphasized(ink, page, Emphasis::Full).to_hex(), ink.to_hex());
2823 }
2824
2825 #[test]
2826 fn tonal_steps_compose_rather_than_compound() {
2827 // Two steps toward one ground are one step toward it, which is what
2828 // makes deriving a family recursively well-defined. Within a rounding
2829 // step, since each hop lands back in 8-bit sRGB.
2830 let ink = Rgb::from_hex("#d8dee9").unwrap();
2831 let page = Rgb::from_hex("#2e3440").unwrap();
2832 let (a, b) = (0.12f32, 0.42f32);
2833 let twice = tonal(tonal(ink, page, a), page, b);
2834 let once = tonal(ink, page, a + b - a * b);
2835 let (x, y) = (twice.tuple(), once.tuple());
2836 for (l, r) in [(x.0, y.0), (x.1, y.1), (x.2, y.2)] {
2837 assert!(l.abs_diff(r) <= 1, "{twice:?} is not {once:?}");
2838 }
2839 }
2840
2841 #[test]
2842 fn a_ratio_outside_the_interval_is_clamped_rather_than_extrapolated() {
2843 let ink = Rgb::from_hex("#d8dee9").unwrap();
2844 let page = Rgb::from_hex("#2e3440").unwrap();
2845 assert_eq!(tonal(ink, page, -1.0).to_hex(), ink.to_hex());
2846 assert_eq!(tonal(ink, page, 2.0).to_hex(), page.to_hex());
2847 }
2848
2849 #[test]
2850 fn a_derived_token_key_is_the_family_plus_the_step() {
2851 assert_eq!(Emphasis::Muted.token("content"), "content-muted");
2852 assert_eq!(Emphasis::Secondary.token("content"), "content-secondary");
2853 assert_eq!(Emphasis::Full.token("content"), "content");
2854 // The point of the suffix being a property of the step: any family can
2855 // be grouped the same way without a second table saying what it means.
2856 assert_eq!(Emphasis::Muted.token("danger"), "danger-muted");
2857 }
2858
2859 #[test]
2860 fn every_shipped_theme_ramps_one_way() {
2861 // The property authoring the steps separately could not hold: three
2862 // themes had shipped a secondary lighter than their own primary, so a
2863 // renderer reading the emphasis order got the reverse of it.
2864 for (id, toml) in embedded_themes() {
2865 let theme = parse_theme_str(id, toml, false).unwrap();
2866 let t = resolve(&theme);
2867 let page = Rgb::from_hex(t.hex("surface-page").unwrap()).unwrap();
2868 let steps = ["content", "content-secondary", "content-muted"]
2869 .map(|k| wcag_contrast(Rgb::from_hex(t.hex(k).unwrap()).unwrap(), page));
2870 assert!(
2871 steps[0] > steps[1] && steps[1] > steps[2],
2872 "{id}: emphasis does not fall monotonically: {steps:?}"
2873 );
2874 }
2875 }
2876
2877 #[test]
2878 fn every_shipped_theme_takes_a_visible_first_step() {
2879 // The property that was missing when 2.6.0 derived these, and the
2880 // reason a pure-black ink shipped a secondary 3/255 away from it: the
2881 // ramp falling monotonically says nothing about how far it falls, and
2882 // a step nobody can see is not a step.
2883 for (id, toml) in embedded_themes() {
2884 let theme = parse_theme_str(id, toml, false).unwrap();
2885 let t = resolve(&theme);
2886 let ink = Rgb::from_hex(t.hex("content").unwrap()).unwrap();
2887 let secondary = Rgb::from_hex(t.hex("content-secondary").unwrap()).unwrap();
2888 let step = wcag_contrast(ink, secondary);
2889 assert!(
2890 step >= STEP_FLOOR,
2891 "{id}: secondary is {step:.2} from its ink, under the {STEP_FLOOR} floor"
2892 );
2893 }
2894 }
2895
2896 #[test]
2897 fn an_authored_emphasis_step_does_not_survive_loading() {
2898 // `nord_toml` still authors both, because a user's theme file might and
2899 // the answer has to be the same one.
2900 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2901 assert_ne!(theme.colors.get("content.muted").unwrap(), "#616e88");
2902 assert_ne!(theme.colors.get("content.secondary").unwrap(), "#e5e9f0");
2903 }
2904
2905 #[test]
2906 fn a_theme_with_no_page_keeps_what_it_authored() {
2907 // Skip-missing: there is nothing to read the step against, so the step
2908 // is not taken and a half-written theme does not lose a colour.
2909 let mut colors = HashMap::new();
2910 colors.insert("content.primary".to_string(), "#d8dee9".to_string());
2911 colors.insert("content.muted".to_string(), "#616e88".to_string());
2912 derive_tonal_steps(&mut colors);
2913 assert_eq!(colors.get("content.muted").unwrap(), "#616e88");
2914 }
2915
2916 #[test]
2917 fn resolve_derived_intents() {
2918 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2919 let t = resolve(&theme);
2920 let action = Rgb::from_hex("#81a1c1").unwrap();
2921 let page = Rgb::from_hex("#2e3440").unwrap();
2922 let _ = page;
2923 assert_eq!(
2924 t.hex("action-hover").unwrap(),
2925 lighten(action, 0.05).to_hex()
2926 );
2927 assert_eq!(
2928 t.hex("content-on-action").unwrap(),
2929 readable_on(action).to_hex()
2930 );
2931 assert_eq!(t.hex("focus-ring"), Some("#81a1c1"));
2932 assert_eq!(t.hex("hover-surface"), Some("#434c5e")); // = surface.sunken
2933 // Pruned by the usage audit (0 consumers): action-active, the *-surface
2934 // tints, selection, row-stripe. Apps that need them derive inline via
2935 // the shared mix().
2936 assert!(t.hex("action-active").is_none());
2937 assert!(t.hex("danger-surface").is_none());
2938 assert!(t.hex("selection").is_none());
2939 assert!(t.hex("row-stripe").is_none());
2940 }
2941
2942 #[test]
2943 fn resolve_bevel_intents() {
2944 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
2945 let t = resolve(&theme);
2946 let raised = Rgb::from_hex("#3b4252").unwrap();
2947 assert_eq!(
2948 t.hex("bevel-light").unwrap(),
2949 lighten(raised, 0.14).to_hex()
2950 );
2951 assert_eq!(t.hex("bevel-dark").unwrap(), darken(raised, 0.18).to_hex());
2952 }
2953
2954 // A bevel is two edges around one face, so both edges have to be visibly off
2955 // that face or the control never resolves as lit. The lightening clamps at
2956 // the top of the ramp, which means a theme authoring a white raised surface
2957 // gets a highlight identical to the surface it is meant to sit on.
2958 //
2959 // The list is asserted rather than merely reported so that changing a theme
2960 // has to come here and say so. Shrinking it is the fix; growing it is a
2961 // regression in the theme, not in this derivation.
2962 #[test]
2963 fn bevel_edges_are_distinct_from_their_face() {
2964 const CANNOT_BEVEL: &[&str] = &["neobrute", "oxocarbon-light"];
2965
2966 let mut degenerate: Vec<String> = Vec::new();
2967 for (id, source) in embedded_themes() {
2968 let theme = parse_theme_str(id, source, false).unwrap();
2969 let t = resolve(&theme);
2970 let Some(raised) = t.hex("surface-raised") else {
2971 continue;
2972 };
2973 let light = t.hex("bevel-light").expect("raised implies bevel-light");
2974 let dark = t.hex("bevel-dark").expect("raised implies bevel-dark");
2975 if light == raised || dark == raised {
2976 degenerate.push(id.to_string());
2977 }
2978 }
2979 degenerate.sort();
2980
2981 assert_eq!(
2982 degenerate, CANNOT_BEVEL,
2983 "themes whose raised surface cannot hold both bevel edges"
2984 );
2985 }
2986
2987 // The well inverts by theme, so assert both directions explicitly rather
2988 // than only the one the light themes happen to take.
2989 #[test]
2990 fn resolve_well_intent_follows_the_content_direction() {
2991 // nord is dark: light text on a dark raised surface, so the well goes
2992 // down and away from the text.
2993 let dark = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
2994 let dark_raised = Rgb::from_hex("#3b4252").unwrap();
2995 assert_eq!(
2996 dark.hex("surface-well").unwrap(),
2997 darken(dark_raised, 0.09).to_hex()
2998 );
2999
3000 // The shipped light themes take the other branch.
3001 let goingson = embedded_themes()
3002 .into_iter()
3003 .find(|(id, _)| *id == "goingson")
3004 .expect("goingson is embedded")
3005 .1;
3006 let light = resolve(&parse_theme_str("goingson", goingson, false).unwrap());
3007 let light_raised = light
3008 .hex("surface-raised")
3009 .and_then(Rgb::from_hex)
3010 .expect("goingson authors a raised surface");
3011 assert_eq!(
3012 light.hex("surface-well").unwrap(),
3013 lighten(light_raised, 0.07).to_hex()
3014 );
3015 }
3016
3017 // A well is a fill, not an edge, so the only thing that makes it read is
3018 // being a different color from the surface it is cut into.
3019 //
3020 // Same shape and the same asserted-list discipline as
3021 // `bevel_edges_are_distinct_from_their_face`, and it bites the same two
3022 // themes for the same reason: a raised surface already at the top of the
3023 // ramp has nothing lighter to go to.
3024 #[test]
3025 fn well_is_distinct_from_its_face() {
3026 const CANNOT_WELL: &[&str] = &["neobrute", "oxocarbon-light"];
3027
3028 let mut degenerate: Vec<String> = Vec::new();
3029 for (id, source) in embedded_themes() {
3030 let theme = parse_theme_str(id, source, false).unwrap();
3031 let t = resolve(&theme);
3032 let Some(raised) = t.hex("surface-raised") else {
3033 continue;
3034 };
3035 let well = t.hex("surface-well").expect("raised implies surface-well");
3036 if well == raised {
3037 degenerate.push(id.to_string());
3038 }
3039 }
3040 degenerate.sort();
3041
3042 assert_eq!(
3043 degenerate, CANNOT_WELL,
3044 "themes whose raised surface cannot hold a well"
3045 );
3046 }
3047
3048 // Distinct is not the same as visible. A face near the top of the ramp
3049 // clamps partway rather than exactly, which yields a well that differs from
3050 // its face by a hex digit and by nothing the eye can find. `rosepine-dawn`
3051 // authors raised at L=0.987 and gets 0.009 of the 0.07 it asked for.
3052 //
3053 // Worth a separate test from the one above because the fix differs: an
3054 // exactly-degenerate theme needs its raised surface off the ramp end, while
3055 // these need it merely lowered. Both fixes are the theme's, not this
3056 // derivation's, which is why the list is asserted rather than warned about.
3057 #[test]
3058 fn well_is_visible_against_its_face() {
3059 // Below this, the well and its face are the same surface to a reader.
3060 const MIN_DELTA_L: f32 = 0.02;
3061 const CANNOT_HOLD_A_VISIBLE_WELL: &[&str] =
3062 &["neobrute", "oxocarbon-light", "rosepine-dawn"];
3063
3064 let mut invisible: Vec<String> = Vec::new();
3065 for (id, source) in embedded_themes() {
3066 let theme = parse_theme_str(id, source, false).unwrap();
3067 let t = resolve(&theme);
3068 let (Some(raised), Some(well)) = (
3069 t.hex("surface-raised").and_then(Rgb::from_hex),
3070 t.hex("surface-well").and_then(Rgb::from_hex),
3071 ) else {
3072 continue;
3073 };
3074 if (well.to_oklab().l - raised.to_oklab().l).abs() < MIN_DELTA_L {
3075 invisible.push(id.to_string());
3076 }
3077 }
3078 invisible.sort();
3079
3080 assert_eq!(
3081 invisible, CANNOT_HOLD_A_VISIBLE_WELL,
3082 "themes whose well is too close to its face to read as one"
3083 );
3084 }
3085
3086 // The three tests above each measure a derived color against the face it was
3087 // derived from, so a theme can pass all of them and still have nothing lift
3088 // off anything: the face itself sits on the page, and that relationship is
3089 // the one a bevel needs in order to read as an object rather than as a
3090 // rectangle with decorated edges. makenot.work passed all three and could
3091 // not hold a bevel, which is what this covers.
3092 //
3093 // The threshold is picked against the ramps already ruled on rather than
3094 // against a round number. makenot.work shipped at 0.024 and was invisible,
3095 // was tried at 0.036 and rejected as marginal on badges and chips, and was
3096 // accepted at 0.058; goingson and audiofiles sit at 0.119 and 0.065. Every
3097 // ramp judged inadequate is below 0.036 and every one judged adequate is
3098 // above 0.058, so the line goes in the gap between them. Note the unit: this
3099 // is oklab L on 0 to 1, not the CIE L* on 0 to 100 that the theme files quote
3100 // in their comments, and the two are not interchangeable.
3101 //
3102 // Most of the list is imported palettes, which were authored for syntax
3103 // highlighting and owe our depth model nothing. Failing here says a theme
3104 // cannot hold a bevel, not that it is wrong. Shrinking the list is the fix;
3105 // growing it is a regression in the theme, not in this derivation.
3106 //
3107 // tokyonight left the list on 2026-08-15, and it is the only entry that could
3108 // leave without a judgment call about someone else's palette. Its page and
3109 // raised were the identical hex, so it had no ramp at all rather than a
3110 // shallow one, and the fix is upstream's own `bg_highlight` (#292e42, 0.079
3111 // above the page) rather than a color we picked. The other nineteen are
3112 // shallow ramps in published palettes, which is a different claim, and they
3113 // stay deferred until every app is migrated and eyeballed.
3114 #[test]
3115 fn raised_is_distinct_from_page() {
3116 // Below this, a raised surface and the page under it are one surface to
3117 // a reader, whichever direction the theme ramps in.
3118 const MIN_DELTA_L: f32 = 0.05;
3119 const CANNOT_LIFT_OFF_THE_PAGE: &[&str] = &[
3120 "akari-dawn",
3121 "akari-night",
3122 "ayu-light",
3123 "ayu-mirage",
3124 "catppuccin-latte",
3125 "catppuccin-mocha",
3126 "dawnfox",
3127 "dracula",
3128 "everforest",
3129 "flatwhite",
3130 "gruvbox-light",
3131 "neobrute",
3132 "one-dark",
3133 "oxocarbon-dark",
3134 "oxocarbon-light",
3135 "poimandres",
3136 "rosepine",
3137 "rosepine-dawn",
3138 "solarized-dark",
3139 ];
3140
3141 let mut flat: Vec<String> = Vec::new();
3142 for (id, source) in embedded_themes() {
3143 let theme = parse_theme_str(id, source, false).unwrap();
3144 let t = resolve(&theme);
3145 let (Some(page), Some(raised)) = (
3146 t.hex("surface-page").and_then(Rgb::from_hex),
3147 t.hex("surface-raised").and_then(Rgb::from_hex),
3148 ) else {
3149 continue;
3150 };
3151 if (raised.to_oklab().l - page.to_oklab().l).abs() < MIN_DELTA_L {
3152 flat.push(id.to_string());
3153 }
3154 }
3155 flat.sort();
3156
3157 assert_eq!(
3158 flat, CANNOT_LIFT_OFF_THE_PAGE,
3159 "themes whose raised surface is too close to the page to lift off it"
3160 );
3161 }
3162
3163 // What the bevel pair does on a sixteen-color terminal, measured across the
3164 // shipped set rather than assumed. Two results, both load-bearing for a
3165 // consumer that has to render one there.
3166 //
3167 // Exactly one edge survives, never both. A raised face quantizes onto one of
3168 // the palette's three grays, and the palette is too coarse to hold anything
3169 // between that entry and its neighbour, so whichever edge is pushed toward
3170 // the end of the ramp the face already sits on lands back on the face. Light
3171 // themes and most dark ones keep the shadow and lose the highlight; a face
3172 // that quantizes to black keeps the highlight and loses the shadow.
3173 //
3174 // So a low-color consumer draws the single edge it can render, on the side
3175 // the palette left it, rather than a bevel that resolves on two sides.
3176 //
3177 // And `quantize_against` is the wrong function for this pair, though it is
3178 // the right one for a border. It answers "nearest entry that clears DISTINCT
3179 // against the background", which has no notion of direction, so both edges
3180 // are pushed onto the same contrasting entry and the bevel inverts on one
3181 // side. Plain `quantize` keeps them apart and in the right order.
3182 #[test]
3183 fn a_sixteen_color_terminal_gets_one_bevel_edge_and_not_two() {
3184 for (id, source) in embedded_themes() {
3185 let theme = parse_theme_str(id, source, false).unwrap();
3186 let t = resolve(&theme);
3187 let (Some(face), Some(light), Some(dark)) = (
3188 t.hex("surface-raised").and_then(Rgb::from_hex),
3189 t.hex("bevel-light").and_then(Rgb::from_hex),
3190 t.hex("bevel-dark").and_then(Rgb::from_hex),
3191 ) else {
3192 continue;
3193 };
3194
3195 let face_index = quantize(face, &ANSI_16);
3196 let light_survives = quantize(light, &ANSI_16) != face_index;
3197 let dark_survives = quantize(dark, &ANSI_16) != face_index;
3198 assert!(
3199 light_survives != dark_survives,
3200 "{id}: expected exactly one bevel edge to survive 16 colors, \
3201 highlight {light_survives} shadow {dark_survives}"
3202 );
3203
3204 // Direction-blind, so it collapses the pair it is asked to separate.
3205 assert_eq!(
3206 quantize_against(light, face, &ANSI_16),
3207 quantize_against(dark, face, &ANSI_16),
3208 "{id}: quantize_against is expected to be unusable for a bevel pair"
3209 );
3210 }
3211 }
3212
3213 // 256 colors is where the bevel starts working. At 16 every shipped theme
3214 // loses an edge; here all but the five whose raised surface sits at the very
3215 // top of the ramp keep both, and those five fail for the reason they fail in
3216 // truecolor rather than for a palette reason.
3217 //
3218 // Three of them cannot bevel at any depth, so they are the
3219 // `bevel_edges_are_distinct_from_their_face` set. The other two are new here:
3220 // they hold a highlight in 24-bit, but not one wide enough to survive
3221 // rounding onto the cube.
3222 #[test]
3223 fn two_hundred_fifty_six_colors_keep_both_bevel_edges() {
3224 const LOSES_AN_EDGE: &[&str] = &[
3225 "gruvbox-light",
3226 "neobrute",
3227 "oxocarbon-light",
3228 "rosepine-dawn",
3229 ];
3230
3231 let mut lost: Vec<String> = Vec::new();
3232 for (id, source) in embedded_themes() {
3233 let theme = parse_theme_str(id, source, false).unwrap();
3234 let t = resolve(&theme);
3235 let (Some(face), Some(light), Some(dark)) = (
3236 t.hex("surface-raised").and_then(Rgb::from_hex),
3237 t.hex("bevel-light").and_then(Rgb::from_hex),
3238 t.hex("bevel-dark").and_then(Rgb::from_hex),
3239 ) else {
3240 continue;
3241 };
3242
3243 // Against the fixed region, which is what a consumer should use: a
3244 // match in the low sixteen is a match against a repaintable color.
3245 let f = quantize(face, ANSI_240);
3246 let l = quantize(light, ANSI_240);
3247 let d = quantize(dark, ANSI_240);
3248 if l == f || d == f || l == d {
3249 lost.push(id.to_string());
3250 }
3251 }
3252 lost.sort();
3253
3254 assert_eq!(
3255 lost, LOSES_AN_EDGE,
3256 "themes that cannot hold a two-tone bevel on a 256-color terminal"
3257 );
3258 }
3259
3260 #[test]
3261 fn the_256_table_has_its_three_regions() {
3262 // Index is the escape-sequence index, so the low sixteen must match.
3263 assert_eq!(ANSI_256[..16], ANSI_16);
3264 // The cube's corners, at both ends and one interior level.
3265 assert_eq!(ANSI_256[16].tuple(), (0, 0, 0));
3266 assert_eq!(ANSI_256[231].tuple(), (255, 255, 255));
3267 assert_eq!(ANSI_256[16 + 36 * 2 + 6 * 3 + 4].tuple(), (135, 175, 215));
3268 // The gray ramp runs 8 to 238 and contains neither black nor white.
3269 assert_eq!(ANSI_256[232].tuple(), (8, 8, 8));
3270 assert_eq!(ANSI_256[255].tuple(), (238, 238, 238));
3271 // The fixed region is the table minus the repaintable colors.
3272 assert_eq!(ANSI_240.len(), 240);
3273 assert_eq!(ANSI_240[0], ANSI_256[ANSI_240_OFFSET]);
3274 }
3275
3276 #[test]
3277 fn resolve_overlay_is_dark_translucent_scrim() {
3278 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
3279 let t = resolve(&theme);
3280 let overlay = t.hex("overlay").unwrap();
3281 assert!(
3282 overlay.starts_with("rgba("),
3283 "overlay is translucent: {overlay}"
3284 );
3285 assert!(overlay.ends_with(", 0.5)"));
3286 // The scrim tone is anchored very dark regardless of theme.
3287 let inner = overlay
3288 .trim_start_matches("rgba(")
3289 .trim_end_matches(", 0.5)");
3290 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
3291 let scrim = Rgb {
3292 r: parts[0],
3293 g: parts[1],
3294 b: parts[2],
3295 };
3296 assert!(scrim.to_oklab().l < 0.2, "scrim must be near-black");
3297 }
3298
3299 /// Every shipped theme derives it, on both polarities, and it is always a
3300 /// near-black translucent tone. A shadow tinted to a dark theme's own
3301 /// lightness would not read as one.
3302 #[test]
3303 fn elevation_is_a_near_black_cast_on_every_theme() {
3304 for (id, source) in embedded_themes() {
3305 let theme = parse_theme_str(id, source, false).unwrap();
3306 let t = resolve(&theme);
3307 let Some(elevation) = t.hex("elevation") else {
3308 panic!("{id} derives no elevation");
3309 };
3310 assert!(
3311 elevation.starts_with("rgba(") && elevation.ends_with(", 0.18)"),
3312 "{id}: elevation is translucent: {elevation}"
3313 );
3314 let inner = elevation
3315 .trim_start_matches("rgba(")
3316 .trim_end_matches(", 0.18)");
3317 let parts: Vec<u8> = inner.split(", ").map(|p| p.parse().unwrap()).collect();
3318 let cast = Rgb {
3319 r: parts[0],
3320 g: parts[1],
3321 b: parts[2],
3322 };
3323 assert!(
3324 cast.to_oklab().l < 0.2,
3325 "{id}: a cast shadow must be near-black, got {elevation}"
3326 );
3327 }
3328 }
3329
3330 /// The scrim and the cast share an anchor and differ only in weight. Stated
3331 /// as a test because the two are easy to drift apart, and a scrim that
3332 /// stopped matching the shadow under the thing it dims would show.
3333 #[test]
3334 fn elevation_and_the_scrim_are_the_same_tone() {
3335 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
3336 let t = resolve(&theme);
3337 let scrim = t.hex("overlay").unwrap();
3338 let cast = t.hex("elevation").unwrap();
3339 assert_eq!(
3340 scrim.trim_end_matches(", 0.5)"),
3341 cast.trim_end_matches(", 0.18)"),
3342 );
3343 }
3344
3345 /// The accessor that makes a translucent intent reachable from something
3346 /// that is not a stylesheet. Both spellings, and an opaque token answers
3347 /// 255 so a caller need not know which kind it asked for.
3348 #[test]
3349 fn rgba_reads_both_spellings() {
3350 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
3351 let t = resolve(&theme);
3352
3353 let (_, _, _, opaque) = t.rgba("surface-page").expect("page is a hex token");
3354 assert_eq!(opaque, 255);
3355
3356 let (r, g, b, alpha) = t.rgba("elevation").expect("elevation is translucent");
3357 assert_eq!(alpha, 46, "0.18 of 255");
3358 assert_eq!(t.rgb("elevation"), None, "rgb declines to drop the alpha");
3359
3360 let (sr, sg, sb, scrim) = t.rgba("overlay").expect("overlay is translucent");
3361 assert_eq!((sr, sg, sb), (r, g, b), "one tone, two weights");
3362 assert_eq!(scrim, 128);
3363 }
3364
3365 #[test]
3366 fn resolve_drops_non_hex_base_intent() {
3367 // A base intent that isn't a hex color must never reach the resolved
3368 // token set (it would otherwise be inlined verbatim into a <style>
3369 // block). Skipped like a missing intent; valid siblings survive.
3370 let theme = parse_theme_str(
3371 "x",
3372 "[surface]\npage = \"</style><script>alert(1)</script>\"\n[content]\nprimary = \"#111111\"\n",
3373 false,
3374 )
3375 .unwrap();
3376 let t = resolve(&theme);
3377 assert!(
3378 t.hex("surface-page").is_none(),
3379 "non-hex base intent leaked"
3380 );
3381 assert_eq!(t.hex("content").unwrap(), "#111111");
3382 // The injected markup appears in no resolved value.
3383 assert!(!t.intents.values().any(|v| v.contains('<')));
3384 }
3385
3386 #[test]
3387 fn resolve_skips_derived_when_source_missing() {
3388 // No [action] => no action-derived tokens.
3389 let theme = parse_theme_str(
3390 "x",
3391 "[surface]\npage = \"#000000\"\n[line]\nborder = \"#222222\"\n",
3392 false,
3393 )
3394 .unwrap();
3395 let t = resolve(&theme);
3396 assert!(t.hex("action").is_none());
3397 assert!(t.hex("action-hover").is_none());
3398 assert!(t.hex("selection").is_none());
3399 assert_eq!(
3400 t.hex("border-strong").unwrap(),
3401 darken(Rgb::from_hex("#222222").unwrap(), 0.05).to_hex()
3402 );
3403 }
3404
3405 #[test]
3406 fn rgb_accessor_for_native_consumers() {
3407 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
3408 let t = resolve(&theme);
3409 assert_eq!(t.rgb("action"), Some((0x81, 0xa1, 0xc1)));
3410 assert_eq!(t.rgb("nonexistent"), None);
3411 }
3412
3413 // ---- css emit ----
3414
3415 #[test]
3416 fn intent_css_vars_wraps_root_and_includes_tokens() {
3417 let theme = parse_theme_str("nord", nord_toml(), false).unwrap();
3418 let css = intent_css_vars(&resolve(&theme));
3419 assert!(css.starts_with(":root {\n"));
3420 assert!(css.contains(" --surface-page: #2e3440;\n"));
3421 assert!(css.contains(" --danger: #bf616a;\n"));
3422 assert!(css.contains(" --action-hover: "));
3423 assert!(css.trim_end().ends_with('}'));
3424 }
3425
3426 // ---- every theme in one sheet ----
3427
3428 /// The shipped themes, as the search path a consumer hands the emitter.
3429 fn shipped() -> Vec<(PathBuf, bool)> {
3430 vec![(
3431 bundled_themes_dir().expect("makeover ships its themes"),
3432 false,
3433 )]
3434 }
3435
3436 #[test]
3437 fn a_keyed_block_carries_the_same_declarations_as_a_root_one() {
3438 let tokens = resolve(&parse_theme_str("nord", nord_toml(), false).unwrap());
3439 let keyed = keyed_intent_css_vars("nord", &tokens);
3440 assert!(
3441 keyed.starts_with(":root[data-theme=\"nord\"] {\n"),
3442 "{keyed}"
3443 );
3444 assert_eq!(
3445 keyed.replace(":root[data-theme=\"nord\"]", ":root"),
3446 intent_css_vars(&tokens),
3447 "the two emitters differ only in the selector"
3448 );
3449 }
3450
3451 #[test]
3452 fn every_installed_theme_gets_a_block_and_they_are_in_id_order() {
3453 let dirs = shipped();
3454 let css = all_themes_css(&dirs, &ThemeDefaults::new("goingson", "catppuccin-mocha"));
3455
3456 let keys: Vec<&str> = css
3457 .match_indices(":root[data-theme=\"")
3458 .map(|(at, prefix)| {
3459 let rest = &css[at + prefix.len()..];
3460 &rest[..rest.find('"').unwrap()]
3461 })
3462 .collect();
3463
3464 let mut expected: Vec<String> = list_themes_from_dirs(&dirs)
3465 .into_iter()
3466 .map(|meta| meta.id)
3467 .collect();
3468 expected.sort();
3469 assert_eq!(keys, expected, "one block per theme, ordered by id");
3470 assert!(
3471 keys.len() > 20,
3472 "the shipped set is the whole picker: {keys:?}"
3473 );
3474 }
3475
3476 /// The property the whole sheet exists for: a pin is an attribute, and it
3477 /// beats the ambient default without `!important` or ordering games.
3478 #[test]
3479 fn the_default_follows_the_system_and_a_pin_outranks_it() {
3480 let css = all_themes_css(
3481 &shipped(),
3482 &ThemeDefaults::new("goingson", "catppuccin-mocha"),
3483 );
3484
3485 assert!(css.starts_with(":root {\n"), "the light default is first");
3486 assert!(css.contains("@media (prefers-color-scheme: dark) {\n:root {\n"));
3487
3488 // Specificity, not order: (0,1,0) for the default against (0,2,0) for
3489 // a keyed block. Asserted as the fact that the keyed blocks follow the
3490 // defaults, which is the ordering that would matter if they tied.
3491 let dark = css.find("prefers-color-scheme").unwrap();
3492 let first_key = css.find(":root[data-theme=").unwrap();
3493 assert!(dark < first_key, "defaults, then the keyed blocks");
3494 }
3495
3496 /// `for_variant` answers every mode by falling back to dark, so emitting a
3497 /// `prefers-contrast` block unconditionally would answer the preference
3498 /// with a theme that does not honour it.
3499 #[test]
3500 fn a_high_contrast_block_appears_only_when_one_was_named() {
3501 let dirs = shipped();
3502 let plain = ThemeDefaults::new("goingson", "catppuccin-mocha");
3503 assert!(!all_themes_css(&dirs, &plain).contains("prefers-contrast"));
3504
3505 let named = plain.clone().high_contrast("high-contrast");
3506 let css = all_themes_css(&dirs, &named);
3507 assert!(
3508 css.contains("@media (prefers-contrast: more) {\n:root {\n"),
3509 "{css}"
3510 );
3511 }
3512
3513 /// A consumer's custom directory is user-writable, so one bad file there
3514 /// costs its own block and nothing else.
3515 #[test]
3516 fn an_unloadable_theme_is_skipped_rather_than_failing_the_sheet() {
3517 let custom = tempfile::tempdir().unwrap();
3518 fs::write(custom.path().join("broken.toml"), "this is not = = toml").unwrap();
3519 fs::write(
3520 custom.path().join("mine.toml"),
3521 "[meta]\nname = \"Mine\"\nvariant = \"dark\"\n[surface]\npage = \"#101010\"\n",
3522 )
3523 .unwrap();
3524
3525 let mut dirs = shipped();
3526 dirs.push((custom.path().to_path_buf(), true));
3527 let css = all_themes_css(&dirs, &ThemeDefaults::new("goingson", "catppuccin-mocha"));
3528
3529 assert!(
3530 css.contains(":root[data-theme=\"mine\"] {"),
3531 "a custom theme is switchable too"
3532 );
3533 assert!(!css.contains("data-theme=\"broken\""), "{css}");
3534 assert!(
3535 css.contains(":root[data-theme=\"nord\"] {"),
3536 "the rest of the sheet survives"
3537 );
3538 }
3539
3540 // ---- typography ----
3541
3542 #[test]
3543 fn the_font_tokens_are_two_names_and_each_ends_at_a_system_generic() {
3544 let css = typography_css_vars();
3545 assert!(css.starts_with(":root {\n"));
3546 assert!(css.contains(" --font-mono: \"Quasi Mono\", monospace;\n"));
3547 assert!(css.contains(" --font-sans: \"Quasi Body\", sans-serif;\n"));
3548
3549 // Layer 2 is one hop and no further. A third entry in either stack is
3550 // the shape the standard exists to delete: a chain nobody can predict
3551 // the metrics of, which is what `--font-sans: -apple-system,
3552 // BlinkMacSystemFont, 'Segoe UI', Roboto, ...` was in three apps.
3553 for stack in [FONT_MONO, FONT_SANS] {
3554 assert_eq!(stack.split(',').count(), 2, "{stack} is not one hop");
3555 }
3556
3557 // Two tokens, and no others. `--font-body`, `--font-heading` and
3558 // `--font-display` are gone or out of scope; a token appearing here
3559 // is a fifth answer to a question that has two.
3560 assert_eq!(css.matches("--font-").count(), 2);
3561 }
3562
3563 #[test]
3564 fn every_font_face_names_the_weight_range_because_the_mono_opens_at_200() {
3565 let css = font_face_css("/static/fonts");
3566
3567 assert_eq!(css.matches("@font-face").count(), 2);
3568 assert!(css.contains("src: url(\"/static/fonts/QuasiMono.woff2\") format(\"woff2\");"));
3569 assert!(css.contains("src: url(\"/static/fonts/QuasiBody.woff2\") format(\"woff2\");"));
3570
3571 // The trap. Atkinson Hyperlegible Mono's default instance is
3572 // ExtraLight and the cut keeps the axis, so a `@font-face` that omits
3573 // the range draws the whole UI at 200.
3574 assert_eq!(css.matches("font-weight: 200 800;").count(), 2);
3575
3576 // The families have to be exactly what the tokens ask for, or the
3577 // stack falls through to the generic and the face is dead weight.
3578 for family in [FONT_MONO, FONT_SANS] {
3579 let quoted = family.split(',').next().unwrap();
3580 assert!(css.contains(&format!("font-family: {quoted};")));
3581 }
3582 }
3583
3584 #[test]
3585 fn a_trailing_slash_on_the_base_url_does_not_double_it() {
3586 assert_eq!(font_face_css("fonts/"), font_face_css("fonts"));
3587 assert!(font_face_css("fonts").contains("url(\"fonts/QuasiMono.woff2\")"));
3588 }
3589
3590 // ---- typography, layer 0 ----
3591
3592 /// The live case: MNW's Young Serif, which reached the page through a
3593 /// hand-maintained `@font-face` and a `--font-heading` nothing else knew
3594 /// about.
3595 fn young_serif() -> FontOverride {
3596 FontOverride::new(FontSlot::Display, "\"Young Serif\", serif")
3597 .with_face(FontFace::new("Young Serif", ["ysrf.woff2", "ysrf.ttf"]))
3598 }
3599
3600 #[test]
3601 fn the_house_layer_alone_is_exactly_what_the_free_functions_emit() {
3602 let t = Typography::house("/static/fonts");
3603 assert_eq!(t.font_face_css(), font_face_css("/static/fonts"));
3604 assert_eq!(t.css_vars(), typography_css_vars());
3605 }
3606
3607 #[test]
3608 fn an_unoverridden_display_slot_defines_no_token_at_all() {
3609 // Not "defined empty": undefined, so the consumer's own fallback in
3610 // `var(--font-display, …)` renders. The MNW embeds depend on it.
3611 let t = Typography::house("fonts");
3612 assert!(!t.css_vars().contains("--font-display"));
3613 assert_eq!(t.resolve(FontSlot::Display), None);
3614 assert_eq!(t.css_vars().matches("--font-").count(), 2);
3615 }
3616
3617 #[test]
3618 fn an_override_adds_its_token_and_its_face_without_touching_the_house_two() {
3619 let t = Typography::house("/static/fonts").with_override(young_serif());
3620
3621 assert!(
3622 t.css_vars()
3623 .contains(" --font-display: \"Young Serif\", serif;\n")
3624 );
3625 assert!(
3626 t.css_vars()
3627 .contains(" --font-mono: \"Quasi Mono\", monospace;\n")
3628 );
3629 assert!(
3630 t.css_vars()
3631 .contains(" --font-sans: \"Quasi Body\", sans-serif;\n")
3632 );
3633 assert_eq!(t.resolve(FontSlot::Display), Some("\"Young Serif\", serif"));
3634
3635 let faces = t.font_face_css();
3636 assert_eq!(faces.matches("@font-face").count(), 3);
3637 assert!(faces.contains("font-family: \"Young Serif\";"));
3638 assert!(faces.contains("url(\"/static/fonts/ysrf.woff2\") format(\"woff2\")"));
3639 assert!(faces.contains("url(\"/static/fonts/ysrf.ttf\") format(\"truetype\")"));
3640
3641 // The house faces still come first, so a product face never shadows a
3642 // slot it did not claim.
3643 assert!(faces.find("Quasi Mono").unwrap() < faces.find("Young Serif").unwrap());
3644 }
3645
3646 #[test]
3647 fn overriding_mono_or_sans_replaces_the_house_stack_rather_than_adding_to_it() {
3648 // Nobody wants this today. A layer that only permits overriding the
3649 // slot nobody describes is the exemption restated, not a layer.
3650 let t = Typography::house("fonts").with_override(FontOverride::new(
3651 FontSlot::Mono,
3652 "\"Departure Mono\", monospace",
3653 ));
3654
3655 assert!(
3656 t.css_vars()
3657 .contains(" --font-mono: \"Departure Mono\", monospace;\n")
3658 );
3659 assert!(!t.css_vars().contains("Quasi Mono"));
3660 assert_eq!(t.css_vars().matches("--font-").count(), 2);
3661 }
3662
3663 #[test]
3664 #[should_panic(expected = "--font-display is overridden twice")]
3665 fn a_second_override_of_one_slot_is_a_vocabulary_bug_and_says_so() {
3666 let _ = Typography::house("fonts")
3667 .with_override(young_serif())
3668 .with_override(FontOverride::new(FontSlot::Display, "\"Reglo\", serif"));
3669 }
3670
3671 #[test]
3672 fn an_absolute_source_is_taken_as_written_and_a_relative_one_joins_the_base() {
3673 let t = Typography::house("/static/fonts").with_override(
3674 FontOverride::new(FontSlot::Display, "\"Reglo\", serif").with_face(
3675 FontFace::new(
3676 "Reglo",
3677 ["Reglo-Bold.woff2", "https://cdn.example/reglo.woff2"],
3678 )
3679 .with_weight("700"),
3680 ),
3681 );
3682 let faces = t.font_face_css();
3683 assert!(faces.contains("url(\"/static/fonts/Reglo-Bold.woff2\")"));
3684 assert!(faces.contains("url(\"https://cdn.example/reglo.woff2\")"));
3685 assert!(faces.contains(" font-weight: 700;\n"));
3686 }
3687
3688 #[test]
3689 fn the_house_tier_renders_byte_for_byte_what_the_format_string_wrote() {
3690 // The house faces became `FontFace` values so they could be read as
3691 // well as emitted. Nothing about the sheet was meant to move, and this
3692 // is the whole of that claim: the literal the format string produced.
3693 let expected = concat!(
3694 "@font-face {\n",
3695 " font-family: \"Quasi Mono\";\n",
3696 " src: url(\"/static/fonts/QuasiMono.woff2\") format(\"woff2\");\n",
3697 " font-weight: 200 800;\n",
3698 " font-style: normal;\n",
3699 " font-display: swap;\n",
3700 "}\n\n",
3701 "@font-face {\n",
3702 " font-family: \"Quasi Body\";\n",
3703 " src: url(\"/static/fonts/QuasiBody.woff2\") format(\"woff2\");\n",
3704 " font-weight: 200 800;\n",
3705 " font-style: normal;\n",
3706 " font-display: swap;\n",
3707 "}\n\n",
3708 );
3709 assert_eq!(font_face_css("/static/fonts"), expected);
3710 }
3711
3712 #[test]
3713 fn a_house_slot_names_the_same_family_in_its_stack_and_in_its_face() {
3714 // The family is spelled once as a bare name and once inside a CSS
3715 // stack, because a stack cannot be built from a const at compile time.
3716 // A face whose family is not the one the stack names loads and is
3717 // never asked for.
3718 for (slot, family) in [
3719 (FontSlot::Mono, HOUSE_MONO_FAMILY),
3720 (FontSlot::Sans, HOUSE_SANS_FAMILY),
3721 ] {
3722 let face = slot.house_face().expect("a house slot has a house face");
3723 assert_eq!(face.family(), family);
3724 assert!(
3725 slot.house_default()
3726 .unwrap()
3727 .starts_with(&format!("\"{family}\""))
3728 );
3729 }
3730 }
3731
3732 #[test]
3733 fn the_brand_tier_has_no_house_face_the_way_it_has_no_house_stack() {
3734 assert!(FontSlot::Display.house_face().is_none());
3735 assert!(FontSlot::Display.house_default().is_none());
3736 }
3737
3738 #[test]
3739 fn a_face_loading_renderer_reads_the_family_and_the_source_off_the_layer() {
3740 // The egui case, which has no stylesheet in the path at all: the
3741 // renderer registers the file under a name, and the name has to be
3742 // the one the stack spells or the two halves drift.
3743 let t = Typography::house("fonts").with_override(
3744 FontOverride::new(FontSlot::Display, "\"RecursiveMono\", monospace").with_face(
3745 FontFace::new("RecursiveMono", ["RecursiveMonoLnrSt-Bold.ttf"]).with_weight("700"),
3746 ),
3747 );
3748
3749 let [face] = t.faces(FontSlot::Display) else {
3750 panic!("the display slot ships exactly one face");
3751 };
3752 assert_eq!(face.family(), "RecursiveMono");
3753 assert_eq!(face.sources(), ["RecursiveMonoLnrSt-Bold.ttf"]);
3754 assert!(
3755 t.resolve(FontSlot::Display)
3756 .unwrap()
3757 .contains(face.family())
3758 );
3759 }
3760
3761 #[test]
3762 fn a_weight_and_style_are_readable_now_that_the_builders_are_not_using_the_names() {
3763 let bold = FontFace::new("Reglo", ["Reglo-Bold.woff2"]).with_weight("700");
3764 assert_eq!(bold.weight(), Some("700"));
3765 assert_eq!(
3766 bold.style(),
3767 None,
3768 "unset means normal, not a stated normal"
3769 );
3770
3771 let italic = FontFace::new("Odd", ["odd.woff2"]).with_style("italic");
3772 assert_eq!(italic.weight(), None);
3773 assert_eq!(italic.style(), Some("italic"));
3774 }
3775
3776 #[test]
3777 fn the_house_faces_state_the_variable_range_a_direct_loader_has_to_name() {
3778 // The trap this closes: a variable face's own default instance is
3779 // whatever the base shipped, which for these is ExtraLight. A loader
3780 // that does not name a weight gets that and nothing says so.
3781 for slot in [FontSlot::Mono, FontSlot::Sans] {
3782 let face = slot.house_face().unwrap();
3783 assert_eq!(face.weight(), Some(HOUSE_WEIGHT_RANGE));
3784 assert_eq!(face.style(), Some("normal"));
3785 }
3786 }
3787
3788 #[test]
3789 fn a_source_is_read_back_unresolved_because_only_the_css_wants_a_url() {
3790 let t = Typography::house("/static/fonts").with_override(young_serif());
3791 assert_eq!(
3792 t.faces(FontSlot::Display)[0].sources(),
3793 ["ysrf.woff2", "ysrf.ttf"]
3794 );
3795 // The same face, joined to the base, in the sheet.
3796 assert!(
3797 t.font_face_css()
3798 .contains("url(\"/static/fonts/ysrf.woff2\")")
3799 );
3800 }
3801
3802 #[test]
3803 fn a_slot_nobody_overrode_ships_no_faces_including_the_house_two() {
3804 let t = Typography::house("fonts").with_override(young_serif());
3805 assert!(t.faces(FontSlot::Mono).is_empty());
3806 assert!(t.faces(FontSlot::Sans).is_empty());
3807 assert_eq!(t.faces(FontSlot::Display).len(), 1);
3808 }
3809
3810 #[test]
3811 fn an_unrecognised_extension_gets_no_format_hint_rather_than_a_guessed_one() {
3812 let t = Typography::house("fonts").with_override(
3813 FontOverride::new(FontSlot::Display, "\"Odd\", serif")
3814 .with_face(FontFace::new("Odd", ["odd.eot"])),
3815 );
3816 assert!(t.font_face_css().contains("url(\"fonts/odd.eot\");"));
3817 assert!(!t.font_face_css().contains("format(\"eot\")"));
3818 }
3819
3820 #[test]
3821 fn css_puts_the_faces_before_the_tokens_that_name_them() {
3822 let t = Typography::house("fonts").with_override(young_serif());
3823 let css = t.css();
3824 assert!(css.starts_with("@font-face"));
3825 assert!(css.find("@font-face").unwrap() < css.find(":root").unwrap());
3826 }
3827
3828 // ---- loading / fs ----
3829
3830 #[test]
3831 fn load_and_resolve_round_trip() {
3832 let dir = tempfile::tempdir().unwrap();
3833 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
3834 let dirs = vec![(dir.path().to_path_buf(), false)];
3835 let t = load_semantic(&dirs, "nord").unwrap();
3836 assert_eq!(t.meta.name, "Nord");
3837 assert_eq!(t.hex("action"), Some("#81a1c1"));
3838 }
3839
3840 #[test]
3841 fn load_theme_rejects_invalid_id() {
3842 assert!(load_theme(&[], "../evil").is_err());
3843 }
3844
3845 fn meta(id: &str, variant: &str) -> ThemeMeta {
3846 ThemeMeta {
3847 id: id.to_string(),
3848 name: id.to_string(),
3849 variant: variant.to_string(),
3850 is_custom: false,
3851 }
3852 }
3853
3854 fn defaults() -> ThemeDefaults {
3855 ThemeDefaults::new("flatwhite", "nord")
3856 }
3857
3858 // The three the shipped themes actually declare.
3859 #[test]
3860 fn every_shipped_variant_parses() {
3861 assert_eq!(Variant::parse("light"), Some(Variant::Light));
3862 assert_eq!(Variant::parse("dark"), Some(Variant::Dark));
3863 assert_eq!(Variant::parse("high-contrast"), Some(Variant::HighContrast));
3864 assert_eq!(Variant::parse("sepia"), None);
3865 }
3866
3867 // parse_meta already defaults a *missing* variant to dark, so an
3868 // unrecognized one reading as light would have the crate disagreeing with
3869 // itself. alloy_tui did exactly that before this existed.
3870 #[test]
3871 fn an_unrecognized_variant_reads_the_way_a_missing_one_does() {
3872 assert_eq!(Variant::from("sepia"), Variant::Dark);
3873 assert_eq!(Variant::from(""), Variant::Dark);
3874
3875 let missing: toml::Table = "[meta]\nname = \"X\"\n".parse().unwrap();
3876 assert_eq!(parse_meta("x", &missing, false).kind(), Variant::Dark);
3877 }
3878
3879 #[test]
3880 fn a_selection_round_trips_through_any_store() {
3881 for (stored, expect) in [
3882 (Some("system"), ThemeSelection::Follow),
3883 (None, ThemeSelection::Follow),
3884 (Some(""), ThemeSelection::Follow),
3885 (Some(" "), ThemeSelection::Follow),
3886 (Some("nord"), ThemeSelection::Fixed("nord".into())),
3887 ] {
3888 let parsed = ThemeSelection::parse(stored);
3889 assert_eq!(parsed, expect, "{stored:?}");
3890 assert_eq!(
3891 ThemeSelection::parse(Some(parsed.as_str())),
3892 expect,
3893 "what is written reads back as what was meant",
3894 );
3895 }
3896 }
3897
3898 // Nothing saved is follow-the-system, which is what Balanced Breakfast
3899 // expressed as an absent value and GoingsOn as a sentinel. Both are now the
3900 // same thing.
3901 #[test]
3902 fn nothing_chosen_yet_is_follow() {
3903 assert_eq!(ThemeSelection::default(), ThemeSelection::Follow);
3904 }
3905
3906 #[test]
3907 fn a_fixed_selection_wins_when_its_theme_is_installed() {
3908 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
3909 let fixed = ThemeSelection::Fixed("nord".into());
3910 assert_eq!(
3911 fixed.resolve(Variant::Light, &defaults(), &available),
3912 "nord",
3913 "a chosen theme is not overridden by the ambient mode",
3914 );
3915 }
3916
3917 // Themes are deletable in three of the four apps. Handing back an id that
3918 // will fail to load only moves the error somewhere less helpful.
3919 #[test]
3920 fn a_fixed_selection_whose_theme_is_gone_falls_back() {
3921 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
3922 let fixed = ThemeSelection::Fixed("deleted".into());
3923 assert_eq!(
3924 fixed.resolve(Variant::Light, &defaults(), &available),
3925 "flatwhite",
3926 );
3927 }
3928
3929 #[test]
3930 fn follow_picks_the_apps_default_for_the_ambient_mode() {
3931 let available = [meta("nord", "dark"), meta("flatwhite", "light")];
3932 let follow = ThemeSelection::Follow;
3933 assert_eq!(
3934 follow.resolve(Variant::Dark, &defaults(), &available),
3935 "nord",
3936 );
3937 assert_eq!(
3938 follow.resolve(Variant::Light, &defaults(), &available),
3939 "flatwhite",
3940 );
3941 }
3942
3943 // The behaviour Balanced Breakfast could not have: following the system
3944 // into a theme the user installed, when the app's own default is absent.
3945 #[test]
3946 fn follow_uses_any_installed_theme_of_the_right_variant() {
3947 let available = [meta("solarized-light", "light"), meta("mine", "dark")];
3948 assert_eq!(
3949 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &available),
3950 "mine",
3951 "the app's `nord` is not installed, but a dark theme is",
3952 );
3953 }
3954
3955 // Always returns something: an app with no theme directory gets the id it
3956 // ships with, and the load error it would have had anyway.
3957 #[test]
3958 fn an_empty_catalog_still_names_the_apps_default() {
3959 assert_eq!(
3960 ThemeSelection::Follow.resolve(Variant::Dark, &defaults(), &[]),
3961 "nord",
3962 );
3963 }
3964
3965 #[test]
3966 fn high_contrast_falls_back_to_dark_unless_named() {
3967 let plain = defaults();
3968 assert_eq!(plain.for_variant(Variant::HighContrast), "nord");
3969
3970 let named = defaults().high_contrast("sharp");
3971 assert_eq!(named.for_variant(Variant::HighContrast), "sharp");
3972 }
3973
3974 // The bug this builder exists to prevent: the Alloy console pushed the
3975 // user's directory first under a comment reading "highest precedence
3976 // first", when both consumers of this vector resolve last-wins. A custom
3977 // theme lost to the packaged one of the same id.
3978 #[test]
3979 fn the_users_own_themes_outrank_everything() {
3980 let root = tempfile::tempdir().unwrap();
3981 let make = |name: &str| {
3982 let dir = root.path().join(name);
3983 std::fs::create_dir_all(&dir).unwrap();
3984 dir
3985 };
3986 let (bundled, system, custom) = (make("bundled"), make("system"), make("custom"));
3987
3988 let dirs = ThemeDirs::new()
3989 .custom(Some(custom.clone()))
3990 .bundled(Some(bundled.clone()))
3991 .system(Some(system.clone()))
3992 .build();
3993
3994 assert_eq!(
3995 dirs,
3996 vec![(bundled, false), (system, false), (custom.clone(), true)],
3997 "lowest precedence first, whatever order the tiers were added in",
3998 );
3999 assert!(dirs.last().unwrap().1, "only the user's tier is custom");
4000
4001 // And the ordering means what the consumers think it means.
4002 for dir in dirs.iter().map(|(dir, _)| dir) {
4003 std::fs::write(dir.join("shared.toml"), "[meta]\nname = \"x\"\n").unwrap();
4004 }
4005 assert_eq!(
4006 find_theme_path(&dirs, "shared").unwrap().0,
4007 custom.join("shared.toml"),
4008 "the user's copy is the one that loads",
4009 );
4010 }
4011
4012 #[test]
4013 fn a_directory_that_does_not_exist_is_dropped() {
4014 let root = tempfile::tempdir().unwrap();
4015 let real = root.path().join("real");
4016 std::fs::create_dir_all(&real).unwrap();
4017
4018 let dirs = ThemeDirs::new()
4019 .bundled(Some(root.path().join("nope")))
4020 .system(None)
4021 .custom(Some(real.clone()))
4022 .build();
4023
4024 assert_eq!(dirs, vec![(real, true)]);
4025 }
4026
4027 // A Tauri app has two bundled tiers: the resource dir in production and the
4028 // tree build.rs materialized for a dev run with no resource dir.
4029 #[test]
4030 fn more_than_one_bundled_tier_is_allowed() {
4031 let root = tempfile::tempdir().unwrap();
4032 let (first, second) = (root.path().join("a"), root.path().join("b"));
4033 std::fs::create_dir_all(&first).unwrap();
4034 std::fs::create_dir_all(&second).unwrap();
4035
4036 let dirs = ThemeDirs::new()
4037 .bundled(Some(first.clone()))
4038 .bundled(Some(second.clone()))
4039 .build();
4040 assert_eq!(dirs, vec![(first, false), (second, false)]);
4041 }
4042
4043 #[test]
4044 fn list_themes_from_dirs_finds_toml_files() {
4045 let dir = tempfile::tempdir().unwrap();
4046 fs::write(dir.path().join("t.toml"), "[meta]\nname = \"T\"\n").unwrap();
4047 fs::write(dir.path().join("x.txt"), "ignored").unwrap();
4048 let dirs = vec![(dir.path().to_path_buf(), false)];
4049 let themes = list_themes_from_dirs(&dirs);
4050 assert_eq!(themes.len(), 1);
4051 assert_eq!(themes[0].id, "t");
4052 }
4053
4054 #[test]
4055 fn find_theme_path_reverse_priority() {
4056 let d1 = tempfile::tempdir().unwrap();
4057 let d2 = tempfile::tempdir().unwrap();
4058 fs::write(d1.path().join("s.toml"), "[meta]\n").unwrap();
4059 fs::write(d2.path().join("s.toml"), "[meta]\n").unwrap();
4060 let dirs = vec![
4061 (d1.path().to_path_buf(), false),
4062 (d2.path().to_path_buf(), true),
4063 ];
4064 let (path, is_custom) = find_theme_path(&dirs, "s").unwrap();
4065 assert!(is_custom);
4066 assert_eq!(path, d2.path().join("s.toml"));
4067 }
4068
4069 #[test]
4070 fn import_theme_valid_and_rejects_empty() {
4071 let src_dir = tempfile::tempdir().unwrap();
4072 let custom_dir = tempfile::tempdir().unwrap();
4073
4074 let good = src_dir.path().join("my-theme.toml");
4075 fs::write(&good, "[surface]\npage = \"#1a1b26\"\n").unwrap();
4076 let meta = import_theme(&good, custom_dir.path()).unwrap();
4077 assert_eq!(meta.id, "my-theme");
4078 assert!(custom_dir.path().join("my-theme.toml").exists());
4079
4080 let empty = src_dir.path().join("empty.toml");
4081 fs::write(&empty, "[meta]\nname = \"E\"\n").unwrap();
4082 assert!(import_theme(&empty, custom_dir.path()).is_err());
4083 }
4084
4085 #[test]
4086 fn import_theme_rejects_invalid_toml() {
4087 let src_dir = tempfile::tempdir().unwrap();
4088 let custom_dir = tempfile::tempdir().unwrap();
4089 let src = src_dir.path().join("bad.toml");
4090 fs::write(&src, "this is not [valid toml [[[").unwrap();
4091 assert!(import_theme(&src, custom_dir.path()).is_err());
4092 }
4093
4094 #[test]
4095 fn delete_theme_removes_and_guards() {
4096 let custom = tempfile::tempdir().unwrap();
4097 let path = custom.path().join("doomed.toml");
4098 fs::write(&path, "[surface]\npage = \"#000\"\n").unwrap();
4099 delete_theme(custom.path(), "doomed").unwrap();
4100 assert!(!path.exists());
4101 assert!(delete_theme(custom.path(), "../etc/passwd").is_err());
4102 assert!(delete_theme(custom.path(), "ghost").is_err());
4103 }
4104
4105 #[test]
4106 fn export_theme_copies_file() {
4107 let src_dir = tempfile::tempdir().unwrap();
4108 let dest_dir = tempfile::tempdir().unwrap();
4109 let content = "[meta]\nname = \"E\"\n[surface]\npage = \"#ffffff\"\n";
4110 fs::write(src_dir.path().join("e.toml"), content).unwrap();
4111 let dirs = vec![(src_dir.path().to_path_buf(), false)];
4112 let dest = dest_dir.path().join("out.toml");
4113 export_theme(&dirs, "e", &dest).unwrap();
4114 assert_eq!(fs::read_to_string(&dest).unwrap(), content);
4115 assert!(export_theme(&dirs, "missing", &dest).is_err());
4116 }
4117
4118 #[test]
4119 fn load_theme_preview_returns_role_swatches() {
4120 let dir = tempfile::tempdir().unwrap();
4121 fs::write(dir.path().join("nord.toml"), nord_toml()).unwrap();
4122 let dirs = vec![(dir.path().to_path_buf(), false)];
4123 let p = load_theme_preview(&dirs, "nord").unwrap();
4124 assert_eq!(p.background.as_deref(), Some("#2e3440")); // surface.page
4125 assert_eq!(p.foreground.as_deref(), Some("#d8dee9")); // content.primary
4126 assert_eq!(p.accent.as_deref(), Some("#81a1c1")); // action.primary
4127 assert_eq!(p.border.as_deref(), Some("#4c566a")); // line.border
4128 }
4129
4130 #[test]
4131 fn bundled_themes_dir_resolves_to_shipped_themes() {
4132 // The crate ships its themes, so this must resolve in-tree and the
4133 // Akari defaults the console falls back to must be present.
4134 let dir = bundled_themes_dir().expect("makeover ships a themes/ directory");
4135 assert!(dir.join("akari-dawn.toml").is_file());
4136 assert!(dir.join("akari-night.toml").is_file());
4137 }
4138
4139 #[test]
4140 fn every_theme_is_accounted_for_in_third_party_notices() {
4141 // Attribution is a redistribution obligation, not a nicety: adding a
4142 // theme without a notice entry silently ships someone's work
4143 // uncredited. Fail here instead.
4144 let notices = std::fs::read_to_string(
4145 Path::new(env!("CARGO_MANIFEST_DIR")).join("THIRD-PARTY-NOTICES.md"),
4146 )
4147 .expect("THIRD-PARTY-NOTICES.md must exist");
4148 let missing: Vec<&str> = embedded_themes()
4149 .map(|(id, _)| id)
4150 .filter(|id| !notices.contains(*id))
4151 .collect();
4152 assert!(
4153 missing.is_empty(),
4154 "themes missing from THIRD-PARTY-NOTICES.md: {missing:?}"
4155 );
4156 }
4157
4158 #[test]
4159 fn adapted_themes_carry_inline_attribution() {
4160 // Each adapted file must name its upstream in-file, so the credit
4161 // survives someone copying a single .toml out of the crate.
4162 const ORIGINALS: [&str; 5] = [
4163 "makenotwork",
4164 "goingson",
4165 "audiofiles",
4166 "high-contrast",
4167 "neobrute",
4168 ];
4169 for (id, source) in embedded_themes() {
4170 if ORIGINALS.contains(&id) {
4171 continue;
4172 }
4173 assert!(
4174 source.contains("adapted from"),
4175 "adapted theme `{id}` is missing its inline attribution header"
4176 );
4177 }
4178 }
4179
4180 #[test]
4181 fn embedded_themes_match_the_directory() {
4182 // The embedded copy and themes/ are two views of one source. If they
4183 // ever disagree, path-based and path-free consumers render different
4184 // theme sets, which is exactly the drift shipping the data was meant
4185 // to prevent.
4186 let dir = bundled_themes_dir().unwrap();
4187 let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
4188 .unwrap()
4189 .filter_map(|e| {
4190 let path = e.ok()?.path();
4191 if path.extension()? != "toml" {
4192 return None;
4193 }
4194 Some(path.file_stem()?.to_str()?.to_string())
4195 })
4196 .collect();
4197 let mut embedded: Vec<String> = embedded_themes().map(|(id, _)| id.to_string()).collect();
4198 on_disk.sort();
4199 embedded.sort();
4200 assert_eq!(embedded, on_disk, "embedded theme set drifted from themes/");
4201 }
4202
4203 #[test]
4204 fn every_embedded_theme_parses() {
4205 // Guards the path-free consumers (MNW server, the Tauri build steps)
4206 // the same way every_shipped_theme_loads guards the path-based ones.
4207 let mut count = 0;
4208 for (id, source) in embedded_themes() {
4209 parse_theme_str(id, source, false)
4210 .unwrap_or_else(|e| panic!("embedded theme `{id}` failed to parse: {e}"));
4211 count += 1;
4212 }
4213 assert!(count >= 30, "expected the full theme set, got {count}");
4214 }
4215
4216 #[test]
4217 fn every_shipped_theme_loads() {
4218 // Guards the data, not just the loader: a malformed or truncated
4219 // .toml in themes/ is a shipping bug, and it should fail here rather
4220 // than at a user's first launch.
4221 let dir = bundled_themes_dir().unwrap();
4222 let dirs = vec![(dir.clone(), false)];
4223 let themes = list_themes_from_dirs(&dirs);
4224 assert!(
4225 themes.len() >= 30,
4226 "expected the full theme set, got {}",
4227 themes.len()
4228 );
4229 for meta in &themes {
4230 load_theme(&dirs, &meta.id)
4231 .unwrap_or_else(|e| panic!("shipped theme `{}` failed to load: {e}", meta.id));
4232 }
4233 }
4234
4235 #[test]
4236 fn theme_options_groups_by_variant_light_first() {
4237 let dirs = vec![(bundled_themes_dir().unwrap(), false)];
4238 let options = theme_options(&dirs);
4239 assert!(!options.is_empty(), "the shipped set is not empty");
4240
4241 let order: Vec<u8> = options.iter().map(|o| variant_order(o.variant)).collect();
4242 let mut sorted = order.clone();
4243 sorted.sort_unstable();
4244 assert_eq!(
4245 order, sorted,
4246 "every variant should occupy one run, light first"
4247 );
4248 }
4249
4250 #[test]
4251 fn theme_options_puts_the_most_legible_theme_first_in_its_group() {
4252 let dirs = vec![(bundled_themes_dir().unwrap(), false)];
4253 let options = theme_options(&dirs);
4254
4255 for pair in options.windows(2) {
4256 let (a, b) = (&pair[0], &pair[1]);
4257 if a.variant != b.variant {
4258 continue;
4259 }
4260 assert!(
4261 a.contrast >= b.contrast,
4262 "within {}, {} ({:?}) should not follow {} ({:?})",
4263 a.variant,
4264 b.id,
4265 b.contrast,
4266 a.id,
4267 a.contrast
4268 );
4269 if a.contrast == b.contrast {
4270 assert!(
4271 a.name <= b.name,
4272 "ties break by name: {} then {}",
4273 a.name,
4274 b.name
4275 );
4276 }
4277 }
4278 }
4279
4280 #[test]
4281 fn theme_options_carries_every_theme_the_scan_found() {
4282 let dirs = vec![(bundled_themes_dir().unwrap(), false)];
4283 let mut scanned: Vec<String> = list_themes_from_dirs(&dirs)
4284 .into_iter()
4285 .map(|meta| meta.id)
4286 .collect();
4287 let mut offered: Vec<String> = theme_options(&dirs).into_iter().map(|o| o.id).collect();
4288 scanned.sort();
4289 offered.sort();
4290 assert_eq!(scanned, offered, "ordering must not drop a theme");
4291 }
4292
4293 #[test]
4294 fn a_theme_that_cannot_be_measured_reads_as_standard() {
4295 // Not Low: a missing ground is the scan failing, and badging the theme
4296 // for that would tell the reader something untrue about the theme.
4297 let theme = ThemeColors {
4298 meta: ThemeMeta {
4299 id: "unmeasurable".to_string(),
4300 name: "Unmeasurable".to_string(),
4301 variant: "dark".to_string(),
4302 is_custom: false,
4303 },
4304 colors: HashMap::new(),
4305 };
4306 assert_eq!(ContrastTier::of(&theme), ContrastTier::Standard);
4307 }
4308
4309 #[test]
4310 fn the_house_themes_measure_high() {
4311 // The two we author. Measured 2026-08-28: goingson 6.18/7.01 and
4312 // audiofiles 6.80/4.78 against page and sunken. A change that drops
4313 // either below AA is a regression in a theme we control, which is
4314 // exactly what this crate now knows how to see.
4315 //
4316 // `high-contrast` is deliberately not in this list. It measures
4317 // 4.89/3.53 and therefore reads as Standard: its muted text misses AA
4318 // on its own sunken panel. That is a finding about the theme file, not
4319 // about the measurement, and it is filed rather than asserted away.
4320 let dirs = vec![(bundled_themes_dir().unwrap(), false)];
4321 for id in ["goingson", "audiofiles"] {
4322 let theme = load_theme(&dirs, id).expect("shipped");
4323 assert_eq!(
4324 ContrastTier::of(&theme),
4325 ContrastTier::High,
4326 "{id} is one of ours and should meet AA on both grounds"
4327 );
4328 }
4329 }
4330
4331 #[test]
4332 fn contrast_tiers_order_worst_first() {
4333 assert!(ContrastTier::Low < ContrastTier::Standard);
4334 assert!(ContrastTier::Standard < ContrastTier::High);
4335 }
4336 }
4337