Skip to main content

renox_core/
theme.rs

1//! Brand themes: colour math and the contrast core.
2//!
3//! This part holds the building blocks the theme derivation uses: sRGB and
4//! OKLCH conversion, hex parsing, the WCAG 2.x contrast ratio, mixing, and a
5//! lightness search that finds the nearest colour passing a check. On top of
6//! it, [`Brand`] and [`Theme`] derive the kit's accent tokens (light and dark)
7//! from one or two brand colours and refuse colours that cannot reach readable
8//! contrast. No I/O.
9
10use std::collections::{BTreeMap, HashMap};
11use std::fmt;
12use std::sync::{Arc, PoisonError, RwLock};
13
14use sha2::{Digest, Sha256};
15
16use self::color::{Oklch, Rgb, nearest_passing};
17
18/// The kit's light page background (`--rx-bg`), one of the colours text is checked on.
19const LIGHT_BG: Rgb = Rgb::new(0xf6, 0xf1, 0xe8);
20/// The kit's light card surface (`--rx-surface`).
21const LIGHT_SURFACE: Rgb = Rgb::new(0xff, 0xfd, 0xf9);
22/// The kit's dark page background.
23const DARK_BG: Rgb = Rgb::new(0x15, 0x14, 0x12);
24/// The kit's dark card surface.
25const DARK_SURFACE: Rgb = Rgb::new(0x1d, 0x1b, 0x18);
26const WHITE: Rgb = Rgb::new(255, 255, 255);
27const NEAR_BLACK: Rgb = Rgb::new(0x1f, 0x24, 0x21);
28/// Contrast for text (WCAG AA).
29const TEXT_RATIO: f64 = 4.5;
30/// Contrast for button labels and chart marks (WCAG AA for large text and graphics).
31const LARGE_RATIO: f64 = 3.0;
32/// How far (OKLCH lightness) a brand colour may move to become a readable
33/// text colour before the brand is refused. Dark mode may lighten further:
34/// a very dark brand colour (black, navy) is a normal choice there.
35const MAX_SHIFT: f64 = 0.3;
36const MAX_SHIFT_DARK: f64 = 0.7;
37
38/// A brand: one colour, an optional second one and an optional display font.
39///
40/// ```
41/// use renox::theme::{Brand, Theme};
42///
43/// let brand = Brand::new("#0F766E").second("#B8532E").display_font("Poppins");
44/// let theme = Theme::from_brand(&brand).unwrap();
45/// assert!(theme.css().contains("--rx-accent"));
46/// ```
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Brand {
49    color: String,
50    second: Option<String>,
51    display_font: Option<String>,
52}
53
54impl Brand {
55    /// A brand with this colour, `#rgb` or `#rrggbb`.
56    pub fn new(color: impl Into<String>) -> Self {
57        Self {
58            color: color.into(),
59            second: None,
60            display_font: None,
61        }
62    }
63
64    /// Sets the second brand colour (`--rx-accent-2`).
65    #[must_use]
66    pub fn second(mut self, color: impl Into<String>) -> Self {
67        self.second = Some(color.into());
68        self
69    }
70
71    /// Sets the display font family (`--rx-font-display`). The name is reduced
72    /// to letters, digits, spaces, `-` and `_`; the font itself is not loaded.
73    #[must_use]
74    pub fn display_font(mut self, family: impl Into<String>) -> Self {
75        self.display_font = Some(family.into());
76        self
77    }
78}
79
80/// What went wrong in [`Theme::from_brand`].
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum ContrastErrorKind {
84    /// The text is not a `#rgb` / `#rrggbb` colour.
85    InvalidColor,
86    /// The colour cannot reach readable contrast.
87    LowContrast,
88}
89
90/// A brand colour that is malformed or cannot reach readable contrast.
91///
92/// For [`ContrastErrorKind::LowContrast`] the `suggestion` is the nearest
93/// colour that [`Theme::from_brand`] accepts, so a settings form can show it.
94///
95/// ```
96/// use renox::theme::{Brand, Theme};
97///
98/// let err = Theme::from_brand(&Brand::new("#FFF59D")).unwrap_err();
99/// assert!(Theme::from_brand(&Brand::new(err.suggestion.as_str())).is_ok());
100/// ```
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct ContrastError {
103    /// What went wrong.
104    pub kind: ContrastErrorKind,
105    /// The colour as given.
106    pub color: String,
107    /// The nearest passing colour as `#rrggbb`; empty for an invalid colour.
108    pub suggestion: String,
109}
110
111impl fmt::Display for ContrastError {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self.kind {
114            ContrastErrorKind::InvalidColor => {
115                write!(f, "`{}` is not a colour like #0f766e", self.color)
116            }
117            ContrastErrorKind::LowContrast => write!(
118                f,
119                "`{}` cannot reach readable contrast; try {}",
120                self.color, self.suggestion
121            ),
122        }
123    }
124}
125
126impl std::error::Error for ContrastError {}
127
128/// The accent tokens of a brand for one colour scheme.
129#[derive(Debug, Clone)]
130struct Scheme {
131    accent: Rgb,
132    hover: Rgb,
133    pressed: Rgb,
134    text: Rgb,
135    on_accent: Rgb,
136    soft: Rgb,
137    focus: String,
138    chart: Rgb,
139    second: Option<(Rgb, Rgb)>,
140}
141
142impl Scheme {
143    /// Derives the tokens for `brand` on `bg`/`surface`; `None` when no text
144    /// colour within [`MAX_SHIFT`] (or [`MAX_SHIFT_DARK`]) reaches [`TEXT_RATIO`].
145    fn derive(brand: Rgb, second: Option<Rgb>, bg: Rgb, surface: Rgb, dark: bool) -> Option<Self> {
146        let shift = if dark { MAX_SHIFT_DARK } else { MAX_SHIFT };
147        let readable = |c: Rgb| c.contrast(bg) >= TEXT_RATIO && c.contrast(surface) >= TEXT_RATIO;
148        let text = nearest_passing(brand, shift, readable)?;
149        let second = match second {
150            Some(c) => Some((c, nearest_passing(c, shift, readable)?)),
151            None => None,
152        };
153        let (white, black) = (brand.contrast(WHITE), brand.contrast(NEAR_BLACK));
154        let on_accent = if white >= TEXT_RATIO || white >= black {
155            WHITE
156        } else {
157            NEAR_BLACK
158        };
159        if brand.contrast(on_accent) < LARGE_RATIO {
160            return None;
161        }
162        // Hover and pressed move so the label keeps (or gains) contrast.
163        let step = |by: f64| {
164            let o = brand.to_oklch();
165            let l = if on_accent == WHITE {
166                o.l - by
167            } else {
168                o.l + by
169            };
170            Oklch { l, ..o }.to_rgb()
171        };
172        let chart =
173            nearest_passing(brand, shift, |c| c.contrast(surface) >= LARGE_RATIO).unwrap_or(brand);
174        let soft = surface.mix(brand, if dark { 0.22 } else { 0.14 });
175        let (focus_base, alpha) = if dark { (text, 0.45) } else { (brand, 0.35) };
176        Some(Self {
177            accent: brand,
178            hover: step(0.03),
179            pressed: step(0.06),
180            text,
181            on_accent,
182            soft,
183            focus: format!(
184                "rgba({}, {}, {}, {alpha})",
185                focus_base.r, focus_base.g, focus_base.b
186            ),
187            chart,
188            second,
189        })
190    }
191
192    fn tokens(&self) -> BTreeMap<&'static str, String> {
193        let mut t = BTreeMap::new();
194        t.insert("--rx-accent", self.accent.to_hex());
195        t.insert("--rx-accent-hover", self.hover.to_hex());
196        t.insert("--rx-accent-pressed", self.pressed.to_hex());
197        t.insert("--rx-accent-text", self.text.to_hex());
198        t.insert("--rx-on-accent", self.on_accent.to_hex());
199        t.insert("--rx-accent-soft", self.soft.to_hex());
200        t.insert("--rx-focus", self.focus.clone());
201        t.insert("--rx-chart-1", self.chart.to_hex());
202        if let Some((c, text)) = self.second {
203            t.insert("--rx-accent-2", c.to_hex());
204            t.insert("--rx-accent-2-text", text.to_hex());
205        }
206        t
207    }
208}
209
210/// The accent tokens derived from a [`Brand`], for light and dark mode.
211///
212/// Build it with [`Theme::from_brand`]; [`Theme::css`] is the stylesheet,
213/// [`Theme::tokens`] and [`Theme::dark_tokens`] the values as data.
214#[derive(Debug, Clone)]
215pub struct Theme {
216    light: BTreeMap<&'static str, String>,
217    dark: BTreeMap<&'static str, String>,
218    css: String,
219    hash: String,
220}
221
222impl Theme {
223    /// Derives the kit's accent tokens from `brand`.
224    ///
225    /// Text colours must reach 4.5:1 on the kit's background and surface in
226    /// both colour schemes, the label on the accent 3:1. The brand colour
227    /// itself is kept; only the text variants move in lightness. When that is
228    /// not enough, the error carries the nearest colour that works.
229    ///
230    /// ```
231    /// use renox::theme::{Brand, Theme};
232    ///
233    /// assert!(Theme::from_brand(&Brand::new("#1E3A5F")).is_ok());
234    /// assert!(Theme::from_brand(&Brand::new("#FFF59D")).is_err());
235    /// ```
236    ///
237    /// # Errors
238    ///
239    /// [`ContrastError`] for a malformed colour or one that cannot reach
240    /// readable contrast.
241    pub fn from_brand(brand: &Brand) -> Result<Self, ContrastError> {
242        let invalid = |c: &str| ContrastError {
243            kind: ContrastErrorKind::InvalidColor,
244            color: c.to_string(),
245            suggestion: String::new(),
246        };
247        let low = |color: &str, suggestion: String| ContrastError {
248            kind: ContrastErrorKind::LowContrast,
249            color: color.to_string(),
250            suggestion,
251        };
252        let main = Rgb::parse_hex(&brand.color).ok_or_else(|| invalid(&brand.color))?;
253        let second = match &brand.second {
254            Some(c) => Some(Rgb::parse_hex(c).ok_or_else(|| invalid(c))?),
255            None => None,
256        };
257        let derive = |main: Rgb, second: Option<Rgb>| {
258            let light = Scheme::derive(main, second, LIGHT_BG, LIGHT_SURFACE, false)?;
259            let dark = Scheme::derive(main, second, DARK_BG, DARK_SURFACE, true)?;
260            Some((light, dark))
261        };
262        // The suggestion is searched over the whole lightness range, and is
263        // checked with the same derivation, so it always passes.
264        if derive(main, None).is_none() {
265            let nearest = nearest_passing(main, 1.0, |c| derive(c, None).is_some());
266            return Err(low(&brand.color, nearest.unwrap_or(main).to_hex()));
267        }
268        if let (Some(c), Some(raw)) = (second, &brand.second)
269            && derive(main, Some(c)).is_none()
270        {
271            let nearest = nearest_passing(c, 1.0, |x| derive(main, Some(x)).is_some());
272            return Err(low(raw, nearest.unwrap_or(c).to_hex()));
273        }
274        let (light, dark) = derive(main, second).expect("checked above");
275        let mut light_tokens = light.tokens();
276        if let Some(font) = brand.display_font.as_deref().and_then(sanitize_family) {
277            light_tokens.insert("--rx-font-display", format!("\"{font}\", var(--rx-font)"));
278        }
279        let dark_tokens = dark.tokens();
280        let css = render_css(&light_tokens, &dark_tokens);
281        let hash = hash_css(&css);
282        Ok(Self {
283            light: light_tokens,
284            dark: dark_tokens,
285            css,
286            hash,
287        })
288    }
289
290    /// The stylesheet: a `:root` block for light mode and the kit's two dark
291    /// selectors (`prefers-color-scheme: dark` and `[data-theme="dark"]`).
292    /// Load it after the kit's CSS.
293    pub fn css(&self) -> &str {
294        &self.css
295    }
296
297    /// A short content hash of [`Theme::css`] (16 hex digits), the key of the
298    /// theme's cacheable stylesheet URL.
299    pub fn hash(&self) -> &str {
300        &self.hash
301    }
302
303    /// The derived tokens for light mode, such as `--rx-accent` => `#0f766e`.
304    pub fn tokens(&self) -> BTreeMap<&'static str, String> {
305        self.light.clone()
306    }
307
308    /// The derived tokens for dark mode.
309    pub fn dark_tokens(&self) -> BTreeMap<&'static str, String> {
310        self.dark.clone()
311    }
312}
313
314/// What a [`App::theme_for`](crate::App::theme_for) chooser gets: the request
315/// a page is rendered for, to pick the brand by host, tenant or setting.
316#[derive(Clone)]
317#[non_exhaustive]
318pub struct ThemeRequest {
319    /// The request's host without the port, e.g. `shop.example.com`
320    /// (empty when the request has none).
321    pub host: String,
322    /// The request's path, e.g. `/products`.
323    pub path: String,
324    /// The request's language, e.g. `en`.
325    pub locale: String,
326    /// The logged-in user, if any.
327    pub user: Option<Arc<crate::auth::User>>,
328    /// The application state, e.g. to read a tenant's brand from the database.
329    pub state: crate::AppState,
330}
331
332/// How a per-request theme chooser is kept.
333pub(crate) type ThemeFn = Arc<
334    dyn Fn(
335            ThemeRequest,
336        ) -> std::pin::Pin<
337            Box<dyn std::future::Future<Output = crate::Result<Option<Theme>>> + Send>,
338        > + Send
339        + Sync,
340>;
341
342pub(crate) fn theme_fn<F, Fut>(choose: F) -> ThemeFn
343where
344    F: Fn(ThemeRequest) -> Fut + Send + Sync + 'static,
345    Fut: std::future::Future<Output = crate::Result<Option<Theme>>> + Send + 'static,
346{
347    Arc::new(move |req| Box::pin(choose(req)))
348}
349
350/// Every theme the app can serve, by content hash, and which one a request
351/// gets.
352///
353/// Filled when the app sets a theme and when a per-request chooser returns
354/// one, so `/_renox/theme/{hash}.css` can answer any hash a page was given.
355/// Cloning shares the map.
356#[derive(Clone, Default)]
357pub(crate) struct ThemeRegistry {
358    themes: Arc<RwLock<HashMap<String, Arc<str>>>>,
359    /// The URL of the app's own theme (`App::theme`).
360    app_url: Option<String>,
361    /// The per-request chooser (`App::theme_for`).
362    chooser: Option<ThemeFn>,
363}
364
365impl ThemeRegistry {
366    /// A registry for an app with `app` as its theme and `chooser` picking
367    /// per request.
368    pub(crate) fn new(app: Option<&Theme>, chooser: Option<ThemeFn>) -> Self {
369        let mut registry = Self {
370            chooser,
371            ..Self::default()
372        };
373        registry.app_url = app.map(|theme| registry.register(theme));
374        registry
375    }
376
377    /// Remembers `theme`'s stylesheet under its hash and returns its URL.
378    /// A theme already known is not copied again.
379    pub(crate) fn register(&self, theme: &Theme) -> String {
380        let known = self
381            .themes
382            .read()
383            .unwrap_or_else(PoisonError::into_inner)
384            .contains_key(theme.hash());
385        if !known {
386            self.themes
387                .write()
388                .unwrap_or_else(PoisonError::into_inner)
389                .entry(theme.hash().to_owned())
390                .or_insert_with(|| theme.css().into());
391        }
392        theme_url(theme.hash())
393    }
394
395    /// The stylesheet registered under `hash`.
396    pub(crate) fn css(&self, hash: &str) -> Option<Arc<str>> {
397        self.themes
398            .read()
399            .unwrap_or_else(PoisonError::into_inner)
400            .get(hash)
401            .cloned()
402    }
403
404    /// The stylesheet URL for a request: the chooser's theme, else the
405    /// app's, else none (the kit's own look). A chooser that fails is logged
406    /// and falls back like one that answers `None`.
407    pub(crate) async fn resolve(&self, req: ThemeRequest) -> Option<String> {
408        if let Some(choose) = &self.chooser {
409            match choose(req).await {
410                Ok(Some(theme)) => return Some(self.register(&theme)),
411                Ok(None) => {}
412                Err(err) => tracing::warn!(error = ?err, "the theme chooser failed"),
413            }
414        }
415        self.app_url.clone()
416    }
417
418    /// Whether a theme can be chosen at all, so a request without one skips
419    /// the work.
420    pub(crate) fn is_set(&self) -> bool {
421        self.app_url.is_some() || self.chooser.is_some()
422    }
423}
424
425/// The URL of the stylesheet for a theme hash.
426pub(crate) fn theme_url(hash: &str) -> String {
427    format!("/_renox/theme/{hash}.css")
428}
429
430fn sanitize_family(name: &str) -> Option<String> {
431    let clean: String = name
432        .chars()
433        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_'))
434        .collect();
435    let clean = clean.trim().to_string();
436    (!clean.is_empty()).then_some(clean)
437}
438
439fn declarations(tokens: &BTreeMap<&'static str, String>) -> String {
440    tokens.iter().map(|(k, v)| format!("{k}:{v};")).collect()
441}
442
443fn render_css(
444    light: &BTreeMap<&'static str, String>,
445    dark: &BTreeMap<&'static str, String>,
446) -> String {
447    let dark = declarations(dark);
448    format!(
449        ":root{{{}}}\n@media (prefers-color-scheme:dark){{:root:not([data-theme=\"light\"]){{{dark}}}}}\n:root[data-theme=\"dark\"]{{{dark}}}\n",
450        declarations(light)
451    )
452}
453
454fn hash_css(css: &str) -> String {
455    Sha256::digest(css.as_bytes())
456        .iter()
457        .take(8)
458        .map(|b| format!("{b:02x}"))
459        .collect()
460}
461
462#[cfg(test)]
463mod theme_tests {
464    use super::*;
465
466    #[test]
467    fn registry_serves_what_it_handed_out() {
468        let registry = ThemeRegistry::default();
469        let theme = Theme::from_brand(&Brand::new("#1E3A5F")).unwrap();
470        let url = registry.register(&theme);
471        assert_eq!(url, format!("/_renox/theme/{}.css", theme.hash()));
472        assert_eq!(registry.register(&theme), url);
473        assert_eq!(&*registry.css(theme.hash()).unwrap(), theme.css());
474        assert!(registry.css("0000000000000000").is_none());
475        // A clone shares the map.
476        assert!(registry.clone().css(theme.hash()).is_some());
477    }
478
479    fn rgb(t: &BTreeMap<&'static str, String>, k: &str) -> Rgb {
480        Rgb::parse_hex(&t[k]).unwrap_or_else(|| panic!("{k} is not a hex colour: {}", t[k]))
481    }
482
483    fn assert_ratios(brand: &str) {
484        let theme = Theme::from_brand(&Brand::new(brand).second("#b8532e")).expect(brand);
485        for (t, bg, surface) in [
486            (theme.tokens(), LIGHT_BG, LIGHT_SURFACE),
487            (theme.dark_tokens(), DARK_BG, DARK_SURFACE),
488        ] {
489            for key in ["--rx-accent-text", "--rx-accent-2-text"] {
490                let c = rgb(&t, key);
491                assert!(c.contrast(bg) >= 4.5, "{brand} {key} on bg");
492                assert!(c.contrast(surface) >= 4.5, "{brand} {key} on surface");
493            }
494            let accent = rgb(&t, "--rx-accent");
495            assert!(
496                rgb(&t, "--rx-on-accent").contrast(accent) >= 3.0,
497                "{brand} label"
498            );
499            for key in [
500                "--rx-accent-hover",
501                "--rx-accent-pressed",
502                "--rx-accent-soft",
503                "--rx-chart-1",
504            ] {
505                assert!(t.contains_key(key), "{key}");
506            }
507            assert!(t["--rx-focus"].starts_with("rgba("));
508        }
509    }
510
511    #[test]
512    fn accepted_colours_meet_the_ratios_in_both_modes() {
513        for c in [
514            "#0b6e66", "#1E3A5F", "#0F766E", "#b8532e", "#7c3aed", "#000", "#333",
515        ] {
516            assert_ratios(c);
517        }
518    }
519
520    #[test]
521    fn the_kit_default_accent_is_kept() {
522        let t = Theme::from_brand(&Brand::new("#0b6e66")).unwrap().tokens();
523        assert_eq!(t["--rx-accent"], "#0b6e66");
524        assert_eq!(t["--rx-on-accent"], "#ffffff");
525        assert_eq!(t["--rx-accent-text"], "#0b6e66");
526    }
527
528    #[test]
529    fn pale_yellow_is_refused_with_a_passing_suggestion() {
530        let err = Theme::from_brand(&Brand::new("#FFF59D")).unwrap_err();
531        assert_eq!(err.kind, ContrastErrorKind::LowContrast);
532        assert!(err.to_string().contains(&err.suggestion));
533        assert_ne!(err.suggestion, "#fff59d");
534        assert_ratios(&err.suggestion);
535    }
536
537    #[test]
538    fn a_failing_second_colour_is_refused_and_named() {
539        let err = Theme::from_brand(&Brand::new("#0f766e").second("#fff59d")).unwrap_err();
540        assert_eq!(err.color, "#fff59d");
541        Theme::from_brand(&Brand::new("#0f766e").second(err.suggestion.as_str())).unwrap();
542    }
543
544    #[test]
545    fn malformed_hex_is_a_distinct_error() {
546        for bad in ["", "red", "#12", "#ggg"] {
547            let err = Theme::from_brand(&Brand::new(bad)).unwrap_err();
548            assert_eq!(err.kind, ContrastErrorKind::InvalidColor, "{bad}");
549            assert!(err.suggestion.is_empty());
550        }
551        let err = Theme::from_brand(&Brand::new("#0f766e").second("nope")).unwrap_err();
552        assert_eq!(err.kind, ContrastErrorKind::InvalidColor);
553    }
554
555    #[test]
556    fn second_colour_and_display_font_are_optional_tokens() {
557        let plain = Theme::from_brand(&Brand::new("#0f766e")).unwrap().tokens();
558        assert!(!plain.contains_key("--rx-accent-2"));
559        assert!(!plain.contains_key("--rx-font-display"));
560        let theme = Theme::from_brand(
561            &Brand::new("#0f766e")
562                .second("#b8532e")
563                .display_font("Poppins\";}body{x:y"),
564        )
565        .unwrap();
566        let t = theme.tokens();
567        assert_eq!(t["--rx-accent-2"], "#b8532e");
568        assert_eq!(t["--rx-font-display"], "\"Poppinsbodyxy\", var(--rx-font)");
569        // The font only goes into light mode (dark inherits it).
570        assert!(!theme.dark_tokens().contains_key("--rx-font-display"));
571    }
572
573    #[test]
574    fn css_has_the_kits_three_selector_blocks() {
575        let css = Theme::from_brand(&Brand::new("#1e3a5f"))
576            .unwrap()
577            .css()
578            .to_string();
579        assert!(css.starts_with(":root{--rx-accent:"));
580        assert!(
581            css.contains("@media (prefers-color-scheme:dark){:root:not([data-theme=\"light\"]){")
582        );
583        assert!(css.contains(":root[data-theme=\"dark\"]{"));
584        // No `:where` on the generated selectors, so the brand is at least as
585        // specific as the kit's `data-rx-theme` blocks and, loaded later, wins.
586        assert!(!css.contains(":where"));
587    }
588
589    #[test]
590    fn hash_follows_the_content() {
591        let a = Theme::from_brand(&Brand::new("#1e3a5f")).unwrap();
592        let b = Theme::from_brand(&Brand::new("#1E3A5F")).unwrap();
593        let c = Theme::from_brand(&Brand::new("#0f766e")).unwrap();
594        assert_eq!(a.hash(), b.hash());
595        assert_ne!(a.hash(), c.hash());
596        assert_eq!(a.hash().len(), 16);
597    }
598}
599
600pub(crate) mod color {
601    //! sRGB, OKLCH and WCAG contrast math.
602
603    /// An 8-bit sRGB colour.
604    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
605    pub(crate) struct Rgb {
606        pub(crate) r: u8,
607        pub(crate) g: u8,
608        pub(crate) b: u8,
609    }
610
611    /// A colour in OKLCH: lightness `l` in 0..=1, chroma `c`, hue `h` in degrees.
612    #[derive(Debug, Clone, Copy, PartialEq)]
613    pub(crate) struct Oklch {
614        pub(crate) l: f64,
615        pub(crate) c: f64,
616        pub(crate) h: f64,
617    }
618
619    impl Rgb {
620        /// Builds a colour from its three channels.
621        pub(crate) const fn new(r: u8, g: u8, b: u8) -> Self {
622            Self { r, g, b }
623        }
624
625        /// Parses `#rgb` or `#rrggbb` (the `#` is optional, case is ignored).
626        pub(crate) fn parse_hex(s: &str) -> Option<Self> {
627            let s = s.trim();
628            let s = s.strip_prefix('#').unwrap_or(s);
629            if !s.chars().all(|c| c.is_ascii_hexdigit()) {
630                return None;
631            }
632            let digit = |i: usize| u8::from_str_radix(&s[i..=i], 16).ok();
633            let pair = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
634            match s.len() {
635                3 => Some(Self::new(digit(0)? * 17, digit(1)? * 17, digit(2)? * 17)),
636                6 => Some(Self::new(pair(0)?, pair(2)?, pair(4)?)),
637                _ => None,
638            }
639        }
640
641        /// The colour as lowercase `#rrggbb`.
642        pub(crate) fn to_hex(self) -> String {
643            format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
644        }
645
646        /// WCAG relative luminance, 0 (black) to 1 (white).
647        pub(crate) fn luminance(self) -> f64 {
648            let lin = |v: u8| srgb_to_linear(f64::from(v) / 255.0);
649            0.2126 * lin(self.r) + 0.7152 * lin(self.g) + 0.0722 * lin(self.b)
650        }
651
652        /// The WCAG contrast ratio against `other`, 1.0 to 21.0.
653        pub(crate) fn contrast(self, other: Rgb) -> f64 {
654            let (a, b) = (self.luminance(), other.luminance());
655            let (hi, lo) = if a >= b { (a, b) } else { (b, a) };
656            (hi + 0.05) / (lo + 0.05)
657        }
658
659        /// This colour in OKLCH.
660        pub(crate) fn to_oklch(self) -> Oklch {
661            let (l, a, b) = self.to_oklab();
662            let c = a.hypot(b);
663            let h = if c < 1e-9 {
664                0.0
665            } else {
666                b.atan2(a).to_degrees().rem_euclid(360.0)
667            };
668            Oklch { l, c, h }
669        }
670
671        fn to_oklab(self) -> (f64, f64, f64) {
672            let r = srgb_to_linear(f64::from(self.r) / 255.0);
673            let g = srgb_to_linear(f64::from(self.g) / 255.0);
674            let b = srgb_to_linear(f64::from(self.b) / 255.0);
675            let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
676            let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
677            let s = (0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b).cbrt();
678            (
679                0.210_454_255_3 * l + 0.793_617_785 * m - 0.004_072_046_8 * s,
680                1.977_998_495_1 * l - 2.428_592_205 * m + 0.450_593_709_9 * s,
681                0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766 * s,
682            )
683        }
684
685        fn from_oklab(l: f64, a: f64, b: f64) -> (f64, f64, f64) {
686            let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
687            let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
688            let s_ = l - 0.089_484_177_5 * a - 1.291_485_548 * b;
689            let (l, m, s) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
690            (
691                4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s,
692                -1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s,
693                -0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701 * s,
694            )
695        }
696
697        /// Mixes `self` with `other` in OKLab; `t` is the share of `other`, 0..=1.
698        pub(crate) fn mix(self, other: Rgb, t: f64) -> Rgb {
699            let t = t.clamp(0.0, 1.0);
700            let (a, b) = (self.to_oklab(), other.to_oklab());
701            let lerp = |x: f64, y: f64| x + (y - x) * t;
702            let (r, g, bl) = Self::from_oklab(lerp(a.0, b.0), lerp(a.1, b.1), lerp(a.2, b.2));
703            from_linear(r, g, bl)
704        }
705    }
706
707    impl Oklch {
708        /// The colour as sRGB. When it is outside the sRGB gamut the chroma is
709        /// reduced (hue and lightness kept) until it fits.
710        pub(crate) fn to_rgb(self) -> Rgb {
711            let l = self.l.clamp(0.0, 1.0);
712            let lin = |c: f64| {
713                let (a, b) = (c * self.h.to_radians().cos(), c * self.h.to_radians().sin());
714                Rgb::from_oklab(l, a, b)
715            };
716            let in_gamut = |(r, g, b): (f64, f64, f64)| {
717                let ok = |v: f64| (-1e-4..=1.0 + 1e-4).contains(&v);
718                ok(r) && ok(g) && ok(b)
719            };
720            let mut c = self.c.max(0.0);
721            if !in_gamut(lin(c)) {
722                let (mut lo, mut hi) = (0.0, c);
723                for _ in 0..24 {
724                    let mid = (lo + hi) / 2.0;
725                    if in_gamut(lin(mid)) {
726                        lo = mid;
727                    } else {
728                        hi = mid;
729                    }
730                }
731                c = lo;
732            }
733            let (r, g, b) = lin(c);
734            from_linear(r, g, b)
735        }
736    }
737
738    fn srgb_to_linear(v: f64) -> f64 {
739        if v <= 0.040_45 {
740            v / 12.92
741        } else {
742            ((v + 0.055) / 1.055).powf(2.4)
743        }
744    }
745
746    fn linear_to_srgb(v: f64) -> f64 {
747        let v = v.clamp(0.0, 1.0);
748        if v <= 0.003_130_8 {
749            v * 12.92
750        } else {
751            1.055 * v.powf(1.0 / 2.4) - 0.055
752        }
753    }
754
755    fn from_linear(r: f64, g: f64, b: f64) -> Rgb {
756        let ch = |v: f64| (linear_to_srgb(v) * 255.0).round() as u8;
757        Rgb::new(ch(r), ch(g), ch(b))
758    }
759
760    /// The colour nearest to `from` in lightness (hue and chroma kept) for which
761    /// `passes` holds, searching at most `max_shift` of OKLCH lightness up or down.
762    /// `from` itself is returned when it already passes. `None` when nothing in
763    /// range passes.
764    pub(crate) fn nearest_passing(
765        from: Rgb,
766        max_shift: f64,
767        passes: impl Fn(Rgb) -> bool,
768    ) -> Option<Rgb> {
769        if passes(from) {
770            return Some(from);
771        }
772        let base = from.to_oklch();
773        let step = 0.002;
774        let mut i = 1.0;
775        while i * step <= max_shift + 1e-12 {
776            let shift = i * step;
777            let at = |l: f64| {
778                (0.0..=1.0)
779                    .contains(&l)
780                    .then(|| Oklch { l, ..base }.to_rgb())
781                    .filter(|c| passes(*c))
782            };
783            // When both directions pass, keep the one closer to the original.
784            match (at(base.l + shift), at(base.l - shift)) {
785                (Some(u), Some(d)) => {
786                    return Some(if dist(from, u) <= dist(from, d) { u } else { d });
787                }
788                (Some(c), None) | (None, Some(c)) => return Some(c),
789                (None, None) => {}
790            }
791            i += 1.0;
792        }
793        None
794    }
795
796    fn dist(a: Rgb, b: Rgb) -> f64 {
797        let d = |x: u8, y: u8| (f64::from(x) - f64::from(y)).powi(2);
798        d(a.r, b.r) + d(a.g, b.g) + d(a.b, b.b)
799    }
800
801    #[cfg(test)]
802    mod tests {
803        use super::*;
804
805        #[test]
806        fn hex_parses_short_long_and_rejects_junk() {
807            assert_eq!(Rgb::parse_hex("#0F766E"), Some(Rgb::new(15, 118, 110)));
808            assert_eq!(Rgb::parse_hex("fa0"), Some(Rgb::new(255, 170, 0)));
809            assert_eq!(Rgb::parse_hex(" #abc "), Some(Rgb::new(170, 187, 204)));
810            for bad in ["", "#", "#12", "#12345", "#1234567", "#ggg", "red", "#é12"] {
811                assert_eq!(Rgb::parse_hex(bad), None, "{bad}");
812            }
813            assert_eq!(Rgb::new(11, 110, 102).to_hex(), "#0b6e66");
814        }
815
816        #[test]
817        fn contrast_matches_wcag_reference_values() {
818            let (black, white) = (Rgb::new(0, 0, 0), Rgb::new(255, 255, 255));
819            assert!((black.contrast(white) - 21.0).abs() < 1e-9);
820            assert!((white.contrast(black) - 21.0).abs() < 1e-9);
821            assert!((white.contrast(white) - 1.0).abs() < 1e-9);
822            // #777 on white is the well-known 4.48:1.
823            let grey = Rgb::parse_hex("#777777").unwrap();
824            assert!((grey.contrast(white) - 4.48).abs() < 0.01);
825        }
826
827        #[test]
828        fn oklch_round_trips_and_matches_reference() {
829            let white = Rgb::new(255, 255, 255).to_oklch();
830            assert!((white.l - 1.0).abs() < 1e-3 && white.c < 1e-3);
831            let red = Rgb::new(255, 0, 0).to_oklch();
832            assert!((red.l - 0.628).abs() < 0.002 && (red.c - 0.258).abs() < 0.002);
833            assert!((red.h - 29.2).abs() < 0.5);
834            for hex in [
835                "#0f766e", "#b8532e", "#1e3a5f", "#fff59d", "#808080", "#000000",
836            ] {
837                let c = Rgb::parse_hex(hex).unwrap();
838                assert_eq!(c.to_oklch().to_rgb(), c, "{hex}");
839            }
840        }
841
842        #[test]
843        fn out_of_gamut_chroma_is_reduced_keeping_lightness() {
844            let wild = Oklch {
845                l: 0.7,
846                c: 0.5,
847                h: 150.0,
848            }
849            .to_rgb();
850            let back = wild.to_oklch();
851            assert!((back.l - 0.7).abs() < 0.02);
852            assert!((back.h - 150.0).abs() < 3.0);
853        }
854
855        #[test]
856        fn mix_endpoints_and_midpoint() {
857            let (a, b) = (Rgb::new(0, 0, 0), Rgb::new(255, 255, 255));
858            assert_eq!(a.mix(b, 0.0), a);
859            assert_eq!(a.mix(b, 1.0), b);
860            let mid = a.mix(b, 0.5);
861            assert!(mid.r > 90 && mid.r < 130 && mid.r == mid.g && mid.g == mid.b);
862        }
863
864        #[test]
865        fn nearest_passing_keeps_a_passing_colour_and_moves_a_failing_one() {
866            let white = Rgb::new(255, 255, 255);
867            let teal = Rgb::parse_hex("#0b6e66").unwrap();
868            assert_eq!(
869                nearest_passing(teal, 0.3, |c| c.contrast(white) >= 4.5),
870                Some(teal)
871            );
872
873            let yellow = Rgb::parse_hex("#fff59d").unwrap();
874            let fixed = nearest_passing(yellow, 0.7, |c| c.contrast(white) >= 4.5).unwrap();
875            assert!(fixed.contrast(white) >= 4.5);
876            // Hue is kept.
877            assert!((fixed.to_oklch().h - yellow.to_oklch().h).abs() < 8.0);
878            // Too small a range finds nothing.
879            assert_eq!(
880                nearest_passing(yellow, 0.1, |c| c.contrast(white) >= 4.5),
881                None
882            );
883        }
884
885        #[test]
886        fn nearest_passing_is_minimal_in_lightness() {
887            let white = Rgb::new(255, 255, 255);
888            let mid = Rgb::parse_hex("#8a8a8a").unwrap();
889            let fixed = nearest_passing(mid, 0.5, |c| c.contrast(white) >= 4.5).unwrap();
890            assert!(fixed.contrast(white) >= 4.5);
891            // A hair closer to the original lightness no longer passes.
892            let (from_l, o) = (mid.to_oklch().l, fixed.to_oklch());
893            let closer = if o.l < from_l { o.l + 0.01 } else { o.l - 0.01 };
894            assert!(Oklch { l: closer, ..o }.to_rgb().contrast(white) < 4.5);
895        }
896    }
897}