Skip to main content

max / makeover-tui

28.0 KB · 679 lines History Blame Raw
1 //! A loaded makeover theme, resolved into the colours ratatui draws with.
2 //!
3 //! Behind the `theme` feature, because it is the one thing here that needs
4 //! `makeover` itself. The rest of this crate takes [`Color`]s it is handed and
5 //! never asks where they came from, which keeps a consumer that only wants
6 //! [`frame`](crate::frame) off the theme loader and its embedded theme files.
7 //!
8 //! # Why this lives here rather than in each consumer
9 //!
10 //! Reading makeover's intents into ratatui `Color`s is the same work every
11 //! terminal consumer does, and doing it twice is how two of them end up
12 //! disagreeing about which intent a surface reads from. The mapping is
13 //! mechanical, the failure mode is silent, and there is exactly one right
14 //! answer, so it belongs with the renderer.
15 //!
16 //! # What is deliberately absent
17 //!
18 //! Tokens a consumer derives for itself. `alloy_tui` mixes a `border-subtle`
19 //! and its own focus-ring `border-strong` out of the authored border, holding
20 //! the latter to WCAG AA-UI against the page because Alloy spends it as the
21 //! entire focus cue. makeover emits a `border-strong` too, and it is a flat 5%
22 //! darkening: a firmer divider, not a focus ring. Those are different tokens
23 //! wearing one name, and on Akari Dawn they land at 1.63:1 and 3.27:1. This
24 //! struct carries makeover's, and a consumer that needs its own keeps deriving
25 //! it. Adopting one for the other would take a focus ring to half its floor.
26
27 use makeover::{Rgb, ThemeColors};
28 use ratatui::style::Color;
29
30 /// A theme's polarity, as its author declared it.
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
32 pub enum Mode {
33 Light,
34 Dark,
35 HighContrast,
36 }
37
38 /// A makeover theme's intents, resolved to ratatui colours.
39 ///
40 /// `#[non_exhaustive]`: this gains a field whenever makeover gains an intent,
41 /// and without the attribute every one of those would be a major here. Nothing
42 /// should be building one field-by-field anyway, since [`Theme::from_theme`] is
43 /// the only way to get one and a partial theme is an error rather than a
44 /// default.
45 #[derive(Debug, Clone, Copy)]
46 #[non_exhaustive]
47 pub struct Theme {
48 pub mode: Mode,
49
50 pub surface_page: Color,
51 pub surface_raised: Color,
52 pub surface_sunken: Color,
53 pub surface_overlay: Color,
54
55 /// makeover's inset content surface: the surface inside a raised container,
56 /// so a list reads as content in a container rather than as bands on a
57 /// panel.
58 ///
59 /// Not [`surface_sunken`](Theme::surface_sunken). A theme is free to author
60 /// sunken *darker* than raised while a well always inverts away from the
61 /// text, so substituting one for the other lands a well on the wrong side of
62 /// its face on exactly the themes where it matters.
63 ///
64 /// `None` where makeover derived nothing, which is a theme authoring no
65 /// raised surface or no content colour. Left missing rather than guessed,
66 /// the same way [`Palette::fill`](crate::Palette::fill) answers a missing
67 /// well with structure instead of a substitute colour.
68 pub surface_well: Option<Color>,
69
70 pub content_primary: Color,
71 pub content_secondary: Color,
72 pub content_muted: Color,
73
74 pub action_primary: Color,
75
76 pub status_danger: Color,
77 pub status_success: Color,
78 pub status_warning: Color,
79 pub status_info: Color,
80
81 /// The authored border colour.
82 pub line_border: Color,
83 /// makeover's derived firmer divider: the authored border, 5% darker.
84 ///
85 /// A divider, not a focus ring. See the module header before spending it as
86 /// one.
87 pub border_strong: Color,
88
89 /// The foreground for text sitting on [`action_primary`](Theme::action_primary).
90 ///
91 /// DERIVED, not authored. Every consumer measured did selection with
92 /// `REVERSED`, because there was no on-accent foreground to pair with an
93 /// accent background, and four ports were each about to invent one.
94 ///
95 /// Chosen between [`surface_page`](Theme::surface_page) and
96 /// [`content_primary`](Theme::content_primary) by contrast against the
97 /// accent, rather than mixed: both are colours the theme authored, so a
98 /// selected row stays inside the theme's own palette instead of landing on
99 /// a colour that appears nowhere in the file. That is
100 /// [`Quantize::against`]'s reasoning applied a step earlier — a colour on a
101 /// colour, answered by measuring rather than by taste.
102 ///
103 /// A candidate for promotion to an authored theme key if a theme ever needs
104 /// to tune it. That direction works and the reverse does not: an authored
105 /// key can fall back to this derivation and break no theme on disk, while a
106 /// key this crate started requiring would break every theme that has one.
107 pub selection_on: Color,
108 /// The colour of a focus ring.
109 ///
110 /// DERIVED, not authored, and deliberately not
111 /// [`border_strong`](Theme::border_strong). That is a divider at 5%
112 /// darkening — see the module header — and spending it here takes a focus
113 /// ring to half its floor. The cue comes off
114 /// [`action_primary`](Theme::action_primary) instead, held to AA-UI against
115 /// the page, which is what `alloy_tui` already derives for itself rather
116 /// than adopting makeover's border for a job it does not do.
117 ///
118 /// Promotable to an authored key on the same terms as
119 /// [`selection_on`](Theme::selection_on).
120 pub focus_ring: Color,
121
122 /// The lit and shadowed edges of a raised surface.
123 ///
124 /// A control is lit from the top left, so its top and left edges take
125 /// `bevel_light` and its bottom and right edges `bevel_dark`; swapping the
126 /// two recesses it, which is what a pressed state and a text well are. The
127 /// light source does not flip with polarity, or the rule stops transferring
128 /// between widgets, which is the whole reason to have one.
129 pub bevel_light: Color,
130 pub bevel_dark: Color,
131
132 pub category: [Color; 6],
133 }
134
135 /// Why a theme could not be resolved.
136 ///
137 /// Both variants name the key, because "the theme is bad" is not something a
138 /// user can act on and "the theme is missing `content.muted`" is.
139 #[derive(Debug, Clone)]
140 pub enum ThemeError {
141 MissingKey(&'static str),
142 InvalidHex { key: &'static str, value: String },
143 }
144
145 impl std::fmt::Display for ThemeError {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 match self {
148 Self::MissingKey(k) => write!(f, "theme missing required key `{k}`"),
149 Self::InvalidHex { key, value } => {
150 write!(f, "theme key `{key}` has invalid hex value `{value}`")
151 }
152 }
153 }
154 }
155
156 impl std::error::Error for ThemeError {}
157
158 impl Theme {
159 /// Resolve a loaded [`ThemeColors`] into the colours ratatui draws with.
160 ///
161 /// Every intent this struct names is required, apart from
162 /// [`surface_well`](Theme::surface_well), which makeover derives only when
163 /// the theme gave it enough to derive from. A malformed or partial theme is
164 /// rejected rather than papered over with defaults: rendering in colours
165 /// that appear nowhere in the theme file is worse than refusing to render.
166 pub fn from_theme(theme: &ThemeColors) -> Result<Self, ThemeError> {
167 let authored = |key: &'static str| -> Result<Rgb, ThemeError> {
168 let hex = theme.colors.get(key).ok_or(ThemeError::MissingKey(key))?;
169 Rgb::from_hex(hex).ok_or_else(|| ThemeError::InvalidHex {
170 key,
171 value: hex.clone(),
172 })
173 };
174
175 // The bevel pair, the well and the firm border are makeover's derived
176 // intents, so a console, a webview and an egui app light a raised
177 // surface the same way. Read through `resolve` rather than recomputed
178 // here, which is the point of them living in that crate.
179 let resolved = makeover::resolve(theme);
180 let derived = |key: &'static str| -> Result<Rgb, ThemeError> {
181 let hex = resolved.hex(key).ok_or(ThemeError::MissingKey(key))?;
182 Rgb::from_hex(hex).ok_or_else(|| ThemeError::InvalidHex {
183 key,
184 value: hex.to_string(),
185 })
186 };
187
188 // The two derived cues. Both are computed here rather than in
189 // `makeover::resolve`, because neither is a colour a webview or an egui
190 // app needs: CSS has `:focus-visible` with its own accent handling, and
191 // a browser paints a selection itself. This is the terminal's problem,
192 // so it is answered where the terminal is drawn.
193 let accent = authored("action.primary")?;
194 let page = authored("surface.page")?;
195 let selection_on = on_accent(accent, page, authored("content.primary")?);
196
197 let mode = match theme.meta.variant.as_str() {
198 "dark" => Mode::Dark,
199 "high-contrast" => Mode::HighContrast,
200 _ => Mode::Light,
201 };
202
203 Ok(Self {
204 mode,
205
206 surface_page: rgb(authored("surface.page")?),
207 surface_raised: rgb(authored("surface.raised")?),
208 surface_sunken: rgb(authored("surface.sunken")?),
209 surface_overlay: rgb(authored("surface.overlay")?),
210 surface_well: resolved
211 .hex("surface-well")
212 .and_then(Rgb::from_hex)
213 .map(rgb),
214
215 content_primary: rgb(authored("content.primary")?),
216 content_secondary: rgb(authored("content.secondary")?),
217 content_muted: rgb(authored("content.muted")?),
218
219 action_primary: rgb(accent),
220 selection_on: rgb(selection_on),
221 focus_ring: rgb(focus_ring(accent, page)),
222
223 status_danger: rgb(authored("status.danger")?),
224 status_success: rgb(authored("status.success")?),
225 status_warning: rgb(authored("status.warning")?),
226 status_info: rgb(authored("status.info")?),
227
228 line_border: rgb(authored("line.border")?),
229 border_strong: rgb(derived("border-strong")?),
230
231 bevel_light: rgb(derived("bevel-light")?),
232 bevel_dark: rgb(derived("bevel-dark")?),
233
234 category: [
235 rgb(authored("category.one")?),
236 rgb(authored("category.two")?),
237 rgb(authored("category.three")?),
238 rgb(authored("category.four")?),
239 rgb(authored("category.five")?),
240 rgb(authored("category.six")?),
241 ],
242 })
243 }
244
245 /// This theme as the terminal can actually draw it.
246 ///
247 /// At [`TrueColor`](crate::Fidelity::TrueColor) the theme is returned
248 /// untouched. Otherwise every colour becomes a palette index, which is the
249 /// point: left as 24-bit, the terminal approximates them itself, and its
250 /// approximation collapses tones the theme keeps apart. Alloy's console lost
251 /// its frame that way, drawing a border in a colour the Linux console could
252 /// not tell from the page behind it.
253 ///
254 /// Anything that has to be seen against the page is quantised against it
255 /// rather than on its own, so a border stays a border and text stays
256 /// readable. The surfaces themselves are quantised plainly: they are what
257 /// the others are measured against.
258 ///
259 /// The bevel edges are quantised plainly too, for a different reason. They
260 /// are measured against the raised surface they surround rather than against
261 /// the page, and running them through [`Quantize::against`] would push both
262 /// onto the same entry and invert the bevel on one side. At
263 /// [`Ansi16`](crate::Fidelity::Ansi16) the palette cannot hold the pair at
264 /// all and one edge lands back on its face, which is a property of sixteen
265 /// colours rather than something this can fix. A caller drawing there does
266 /// not have to handle it: [`Theme::palette`] carries the fidelity through,
267 /// and [`frame`](crate::frame) answers it with glyphs instead of tones.
268 ///
269 /// A consumer holding tokens of its own quantises them alongside this, with
270 /// the same [`Quantize`], rather than after the fact.
271 #[must_use]
272 pub fn for_terminal(self, fidelity: crate::Fidelity) -> Self {
273 let Some(q) = Quantize::for_fidelity(fidelity) else {
274 return self;
275 };
276
277 let plain = |c: Color| q.plain(c);
278 let on_page = |c: Color| q.against(c, self.surface_page);
279
280 Self {
281 mode: self.mode,
282
283 surface_page: plain(self.surface_page),
284 surface_raised: plain(self.surface_raised),
285 surface_sunken: plain(self.surface_sunken),
286 surface_overlay: plain(self.surface_overlay),
287 // Plainly, like the other surfaces and for the same reason as the
288 // bevel pair: a well is measured against the raised face it is cut
289 // into, not against the page, so quantising it against the page
290 // would push it toward contrast it is not supposed to have.
291 surface_well: self.surface_well.map(plain),
292
293 content_primary: on_page(self.content_primary),
294 content_secondary: on_page(self.content_secondary),
295 content_muted: on_page(self.content_muted),
296
297 action_primary: on_page(self.action_primary),
298 // Against the accent, not against the page: this is the one colour
299 // here whose whole job is to be legible on the accent behind it.
300 // Quantising it against the page would answer the wrong question
301 // and hand a selected row unreadable text at Ansi16.
302 selection_on: q.against(self.selection_on, self.action_primary),
303 focus_ring: on_page(self.focus_ring),
304
305 status_danger: on_page(self.status_danger),
306 status_success: on_page(self.status_success),
307 status_warning: on_page(self.status_warning),
308 status_info: on_page(self.status_info),
309
310 line_border: on_page(self.line_border),
311 border_strong: on_page(self.border_strong),
312
313 bevel_light: plain(self.bevel_light),
314 bevel_dark: plain(self.bevel_dark),
315
316 category: self.category.map(on_page),
317 }
318 }
319
320 /// The depth-painting palette this theme implies, at `fidelity`.
321 ///
322 /// The bridge between the two halves of this crate: [`Theme`] is what a
323 /// theme file says, [`Palette`](crate::Palette) is the subset
324 /// [`frame`](crate::frame) and [`paint_bevel`](crate::paint_bevel) need. A
325 /// consumer holding a `Theme` should not be assembling that by hand and
326 /// picking the wrong surface for the well.
327 #[must_use]
328 pub const fn palette(&self, fidelity: crate::Fidelity) -> crate::Palette {
329 crate::Palette {
330 page: self.surface_page,
331 raised: self.surface_raised,
332 overlay: self.surface_overlay,
333 well: self.surface_well,
334 bevel_light: self.bevel_light,
335 bevel_dark: self.bevel_dark,
336 fidelity,
337 }
338 }
339 }
340
341 fn rgb(c: Rgb) -> Color {
342 Color::Rgb(c.r, c.g, c.b)
343 }
344
345 /// The AA floor for text against what it sits on.
346 const TEXT_FLOOR: f32 = 4.5;
347
348 /// The AA-UI floor a non-text cue has to clear against what it sits on.
349 ///
350 /// 3:1 rather than 4.5:1 because a ring is a graphical object and not text.
351 /// The same number `alloy_tui` holds its own derived ring to.
352 const UI_FLOOR: f32 = 3.0;
353
354 /// The better of the theme's two candidates for text on the accent, or black or
355 /// white where neither is legible.
356 ///
357 /// Preferring an authored colour is the point: a selected row should stay inside
358 /// the palette the theme wrote rather than land on a colour appearing nowhere in
359 /// the file. But an unreadable selection is worse than an off-palette one, and
360 /// the two candidates can both fail — ayu-light's page and content both land
361 /// under 2.5:1 on its accent. So the walk is: page or content by contrast,
362 /// and `readable_on` only when the winner misses the AA text floor.
363 ///
364 /// Measured across every bundled theme when this was written: 29 of 31 clear
365 /// the floor from the theme's own colours, one clears it at 3.99 and 3.36 (the
366 /// app themes), and ayu-light is the one that needs the backstop.
367 fn on_accent(accent: Rgb, page: Rgb, content: Rgb) -> Rgb {
368 let best = if makeover::wcag_contrast(page, accent) >= makeover::wcag_contrast(content, accent)
369 {
370 page
371 } else {
372 content
373 };
374 if makeover::wcag_contrast(best, accent) >= TEXT_FLOOR {
375 best
376 } else {
377 makeover::readable_on(accent)
378 }
379 }
380
381 /// A ring colour off the accent, pushed away from the page until it is visible.
382 ///
383 /// The accent itself is the answer on most themes, and the walk only runs where
384 /// it is not: a theme whose accent sits close to its page has a real focus
385 /// problem, and returning the accent unchanged there would be a ring nobody can
386 /// see. Which way to push is decided by the page rather than by the theme's
387 /// declared variant, because a light theme may carry a dark panel and the
388 /// question is always "away from *this* surface".
389 ///
390 /// Steps in 5% and stops at the floor rather than going as far as it can, so
391 /// the ring stays recognisably the accent on the themes that need the help.
392 fn focus_ring(accent: Rgb, page: Rgb) -> Rgb {
393 if makeover::wcag_contrast(accent, page) >= UI_FLOOR {
394 return accent;
395 }
396
397 // Whether the page is dark, by the same relative-luminance rule the
398 // contrast ratio is built on: white against it beats black against it.
399 let page_is_dark = makeover::wcag_contrast(
400 Rgb {
401 r: 255,
402 g: 255,
403 b: 255,
404 },
405 page,
406 ) > makeover::wcag_contrast(Rgb { r: 0, g: 0, b: 0 }, page);
407
408 let mut candidate = accent;
409 for _ in 0..20 {
410 candidate = if page_is_dark {
411 makeover::lighten(candidate, 0.05)
412 } else {
413 makeover::darken(candidate, 0.05)
414 };
415 if makeover::wcag_contrast(candidate, page) >= UI_FLOOR {
416 return candidate;
417 }
418 }
419 candidate
420 }
421
422 /// The palette a [`Fidelity`](crate::Fidelity) quantises into, and the rules for
423 /// landing a colour in it.
424 ///
425 /// Public because a consumer carrying tokens of its own has to quantise them the
426 /// same way this crate quantises the ones it knows about. `alloy_tui` derives a
427 /// decorative divider and a focus ring from the authored border; those are its
428 /// tokens, but "a colour that must stay legible against the page is quantised
429 /// against the page" is not its rule to reinvent.
430 #[derive(Debug, Clone, Copy)]
431 pub struct Quantize {
432 palette: &'static [Rgb],
433 offset: usize,
434 }
435
436 impl Quantize {
437 /// The quantiser for `fidelity`, or `None` at
438 /// [`TrueColor`](crate::Fidelity::TrueColor), where nothing is quantised.
439 ///
440 /// 256 resolves to makeover's fixed region rather than the whole table: the
441 /// low sixteen are repaintable in every emulator, so a match landing there
442 /// is a match against a colour the user may have moved out from under it.
443 #[must_use]
444 pub const fn for_fidelity(fidelity: crate::Fidelity) -> Option<Self> {
445 match fidelity {
446 crate::Fidelity::TrueColor => None,
447 crate::Fidelity::Ansi256 => Some(Self {
448 palette: makeover::ANSI_240,
449 offset: makeover::ANSI_240_OFFSET,
450 }),
451 crate::Fidelity::Ansi16 => Some(Self {
452 palette: &makeover::ANSI_16,
453 offset: 0,
454 }),
455 }
456 }
457
458 /// The palette entry for `c`, as an index the terminal will not reinterpret.
459 ///
460 /// For a colour measured against the surface it sits on rather than against
461 /// the page: the surfaces themselves, and the bevel pair.
462 #[must_use]
463 pub fn plain(&self, c: Color) -> Color {
464 match c {
465 Color::Rgb(r, g, b) => Color::Indexed(
466 (makeover::quantize(Rgb { r, g, b }, self.palette) + self.offset) as u8,
467 ),
468 other => other,
469 }
470 }
471
472 /// As [`plain`](Self::plain), but guaranteed to stay legible against `on`.
473 ///
474 /// Only for a colour whose job is to be told apart from a known background.
475 /// It answers "nearest entry that still contrasts with `on`" and has no
476 /// notion of which side of `on` the answer should fall, so a pair of colours
477 /// that must also stay apart from *each other* is the one thing it must not
478 /// be used for: both get pushed onto the same contrasting entry. That is why
479 /// the bevel edges go through [`plain`](Self::plain).
480 #[must_use]
481 pub fn against(&self, c: Color, on: Color) -> Color {
482 match (c, on) {
483 (Color::Rgb(r, g, b), Color::Rgb(br, bg, bb)) => Color::Indexed(
484 (makeover::quantize_against(
485 Rgb { r, g, b },
486 Rgb {
487 r: br,
488 g: bg,
489 b: bb,
490 },
491 self.palette,
492 ) + self.offset) as u8,
493 ),
494 _ => self.plain(c),
495 }
496 }
497 }
498
499 #[cfg(test)]
500 mod tests {
501 use super::*;
502
503 fn bundled(id: &str) -> ThemeColors {
504 let dir = makeover::bundled_themes_dir().expect("makeover ships themes");
505 makeover::load_theme(&[(dir, false)], id).expect("bundled theme loads")
506 }
507
508 #[test]
509 fn every_bundled_theme_resolves() {
510 // The point of rejecting a partial theme is that it never happens to a
511 // theme we ship. If one of these stops resolving, that is a real gap in
512 // the theme file, not a reason to soften the error.
513 let dir = makeover::bundled_themes_dir().expect("makeover ships themes");
514 let metas = makeover::list_themes_from_dirs(&[(dir, false)]);
515 assert!(
516 !metas.is_empty(),
517 "makeover shipped no themes to test against"
518 );
519 for meta in &metas {
520 let colors = bundled(&meta.id);
521 assert!(
522 Theme::from_theme(&colors).is_ok(),
523 "bundled theme `{}` failed to resolve",
524 meta.id
525 );
526 }
527 }
528
529 fn to_rgb(c: Color) -> Rgb {
530 match c {
531 Color::Rgb(r, g, b) => Rgb { r, g, b },
532 other => panic!("expected a resolved colour, got {other:?}"),
533 }
534 }
535
536 #[test]
537 fn the_two_derived_cues_are_legible_in_every_bundled_theme() {
538 // The test that would have caught `border_strong` being spent as a
539 // focus ring: it lands at 1.63:1 on Akari Dawn, and nothing asked.
540 // Every theme rather than one, because a derivation that works on the
541 // theme it was written against says nothing about the other thirty.
542 let dir = makeover::bundled_themes_dir().expect("makeover ships themes");
543 for meta in makeover::list_themes_from_dirs(&[(dir, false)]) {
544 let theme = Theme::from_theme(&bundled(&meta.id)).expect("resolves");
545
546 // Text on the accent, so the text floor.
547 let selection =
548 makeover::wcag_contrast(to_rgb(theme.selection_on), to_rgb(theme.action_primary));
549 assert!(
550 selection >= TEXT_FLOOR,
551 "{}: selection_on is {selection:.2} on the accent",
552 meta.id
553 );
554
555 // A ring is a graphical object, so the AA-UI floor.
556 let ring =
557 makeover::wcag_contrast(to_rgb(theme.focus_ring), to_rgb(theme.surface_page));
558 assert!(
559 ring >= UI_FLOOR,
560 "{}: focus_ring is {ring:.2} on the page",
561 meta.id
562 );
563
564 // And the ring is not the divider wearing the ring's name, which
565 // is the whole reason it is derived rather than adopted.
566 assert_ne!(theme.focus_ring, theme.border_strong, "{}", meta.id);
567 }
568 }
569
570 #[test]
571 fn the_derived_cues_are_quantised_for_the_surface_each_sits_on() {
572 // A colour that has to be told apart from a known background is
573 // quantised against that background, and the two cues do not share one.
574 // Left plain, both collapse toward whatever the palette has nearest.
575 let theme = Theme::from_theme(&bundled("goingson")).expect("resolves");
576 let ansi16 = theme.for_terminal(crate::Fidelity::Ansi16);
577 let q = Quantize::for_fidelity(crate::Fidelity::Ansi16).expect("Ansi16 quantises");
578
579 assert_eq!(
580 ansi16.selection_on,
581 q.against(theme.selection_on, theme.action_primary)
582 );
583 assert_eq!(
584 ansi16.focus_ring,
585 q.against(theme.focus_ring, theme.surface_page)
586 );
587 }
588
589 #[test]
590 fn a_missing_intent_names_the_key_it_wanted() {
591 let mut colors = bundled("goingson");
592 colors.colors.remove("content.muted");
593 match Theme::from_theme(&colors) {
594 Err(ThemeError::MissingKey(k)) => assert_eq!(k, "content.muted"),
595 other => panic!("expected MissingKey(content.muted), got {other:?}"),
596 }
597 }
598
599 #[test]
600 fn an_unparseable_hex_names_the_key_and_the_value() {
601 let mut colors = bundled("goingson");
602 colors
603 .colors
604 .insert("content.muted".into(), "not-a-colour".into());
605 match Theme::from_theme(&colors) {
606 Err(ThemeError::InvalidHex { key, value }) => {
607 assert_eq!(key, "content.muted");
608 assert_eq!(value, "not-a-colour");
609 }
610 other => panic!("expected InvalidHex, got {other:?}"),
611 }
612 }
613
614 #[test]
615 fn a_capable_terminal_gets_the_theme_as_authored() {
616 let theme = Theme::from_theme(&bundled("goingson")).expect("resolves");
617 let same = theme.for_terminal(crate::Fidelity::TrueColor);
618 assert_eq!(same.surface_page, theme.surface_page);
619 assert_eq!(same.content_primary, theme.content_primary);
620 assert!(matches!(same.surface_page, Color::Rgb(..)));
621 }
622
623 #[test]
624 fn a_limited_terminal_gets_indices_rather_than_rgb() {
625 let theme = Theme::from_theme(&bundled("goingson")).expect("resolves");
626 for fidelity in [crate::Fidelity::Ansi16, crate::Fidelity::Ansi256] {
627 let q = theme.for_terminal(fidelity);
628 assert!(
629 matches!(q.surface_page, Color::Indexed(_)),
630 "{fidelity:?} left a surface as rgb"
631 );
632 assert!(
633 matches!(q.content_primary, Color::Indexed(_)),
634 "{fidelity:?} left content as rgb"
635 );
636 }
637 }
638
639 #[test]
640 fn the_256_indices_land_outside_the_repaintable_low_sixteen() {
641 // The reason Quantize::for_fidelity resolves 256 to makeover's fixed
642 // region: an index below 16 is one the user's emulator may have moved.
643 let theme = Theme::from_theme(&bundled("goingson")).expect("resolves");
644 let q = theme.for_terminal(crate::Fidelity::Ansi256);
645 for (name, c) in [
646 ("surface_page", q.surface_page),
647 ("content_primary", q.content_primary),
648 ("bevel_light", q.bevel_light),
649 ("bevel_dark", q.bevel_dark),
650 ] {
651 match c {
652 Color::Indexed(i) => assert!(i >= 16, "{name} landed on repaintable index {i}"),
653 other => panic!("{name} was not quantised: {other:?}"),
654 }
655 }
656 }
657
658 #[test]
659 fn the_bevel_pair_stays_two_tones_at_256() {
660 // Quantised plainly rather than against the page, precisely so they do
661 // not collapse onto one entry and invert the bevel on one side.
662 let theme = Theme::from_theme(&bundled("goingson")).expect("resolves");
663 let q = theme.for_terminal(crate::Fidelity::Ansi256);
664 assert_ne!(q.bevel_light, q.bevel_dark);
665 }
666
667 #[test]
668 fn the_palette_takes_the_well_and_not_the_sunken_surface() {
669 // The substitution this crate deleted from the description, asserted
670 // absent here too: a theme authoring sunken darker than raised would
671 // land the well on the wrong side of its face.
672 let colors = bundled("goingson");
673 let theme = Theme::from_theme(&colors).expect("resolves");
674 let palette = theme.palette(crate::Fidelity::TrueColor);
675 assert_eq!(palette.well, theme.surface_well);
676 assert_ne!(palette.well, Some(theme.surface_sunken));
677 }
678 }
679