Skip to main content

webizen_studio/
theme_engine.rs

1use std::collections::{BTreeSet, HashMap};
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
6pub struct ThemeDefinition {
7    pub id: String,
8    #[serde(default)]
9    pub stylesheet_href: Option<String>,
10    #[serde(default)]
11    pub class_name: Option<String>,
12    #[serde(default)]
13    pub tokens: HashMap<String, String>,
14}
15
16#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
17pub struct ThemeBinding {
18    #[serde(default)]
19    pub theme_id: Option<String>,
20    #[serde(default)]
21    pub stylesheet_href: Option<String>,
22    #[serde(default)]
23    pub class_name: Option<String>,
24    #[serde(default)]
25    pub tokens: HashMap<String, String>,
26    /// Presentation morphology bias P0–P6 (Presentation Binding).
27    #[serde(default)]
28    pub presentation_level: Option<u8>,
29    /// Spatial grammar hint: list | board | globe | room | strata | hyperspace
30    #[serde(default)]
31    pub spatial_grammar: Option<String>,
32    /// When false, UI should disable/discourage Spatialize (Sanctuary).
33    #[serde(default)]
34    pub spatialize_allowed: Option<bool>,
35}
36
37#[derive(Clone, Debug, Default, PartialEq)]
38pub struct ResolvedTheme {
39    pub theme_key: Option<String>,
40    pub class_name: Option<String>,
41    pub stylesheets: Vec<String>,
42    pub tokens: HashMap<String, String>,
43    pub presentation_level: u8,
44    pub spatial_grammar: String,
45    pub spatialize_allowed: bool,
46}
47
48/// Canonical QPrime preset IDs (theme picker foreground).
49pub const QPRIME_PRESET_IDS: &[&str] =
50    &["fiduciary-dark", "commons-light", "sanctuary", "infosphere"];
51
52/// Legacy extras — available but not primary in the picker.
53pub const LEGACY_PRESET_IDS: &[&str] = &["human-warmth", "twilight-blue", "midnight-slate"];
54
55/// `true` when qprime-preset.
56pub fn is_qprime_preset(id: &str) -> bool {
57    QPRIME_PRESET_IDS.contains(&id)
58}
59
60/// Theme label.
61pub fn theme_label(id: &str) -> String {
62    id.split('-')
63        .map(|w| {
64            let mut c = w.chars();
65            c.next()
66                .map(|ch| ch.to_uppercase().collect::<String>() + c.as_str())
67                .unwrap_or_default()
68        })
69        .collect::<Vec<_>>()
70        .join(" ")
71}
72
73/// WCAG relative contrast for opaque `#RRGGBB` colours.
74pub fn contrast_ratio(foreground: &str, background: &str) -> Option<f64> {
75    fn luminance(value: &str) -> Option<f64> {
76        let hex = value.strip_prefix('#')?;
77        if hex.len() != 6 {
78            return None;
79        }
80        let channel = |offset: usize| -> Option<f64> {
81            let raw = u8::from_str_radix(&hex[offset..offset + 2], 16).ok()? as f64 / 255.0;
82            Some(if raw <= 0.04045 {
83                raw / 12.92
84            } else {
85                ((raw + 0.055) / 1.055).powf(2.4)
86            })
87        };
88        Some(0.2126 * channel(0)? + 0.7152 * channel(2)? + 0.0722 * channel(4)?)
89    }
90    let foreground = luminance(foreground)?;
91    let background = luminance(background)?;
92    let (light, dark) = if foreground >= background {
93        (foreground, background)
94    } else {
95        (background, foreground)
96    };
97    Some((light + 0.05) / (dark + 0.05))
98}
99
100/// Split catalog into QPrime presets (ordered) and everything else.
101pub fn theme_picker_sections(
102    catalog: &[ThemeDefinition],
103) -> (Vec<ThemeDefinition>, Vec<ThemeDefinition>) {
104    let mut qprime = Vec::new();
105    for id in QPRIME_PRESET_IDS {
106        if let Some(t) = catalog.iter().find(|t| t.id == *id) {
107            qprime.push(t.clone());
108        }
109    }
110    let legacy_ids: std::collections::BTreeSet<&str> = LEGACY_PRESET_IDS.iter().copied().collect();
111    let extras: Vec<ThemeDefinition> = catalog
112        .iter()
113        .filter(|t| !is_qprime_preset(&t.id) && !legacy_ids.contains(t.id.as_str()))
114        .cloned()
115        .collect();
116    let mut legacy: Vec<ThemeDefinition> = catalog
117        .iter()
118        .filter(|t| legacy_ids.contains(t.id.as_str()))
119        .cloned()
120        .collect();
121    legacy.sort_by(|a, b| a.id.cmp(&b.id));
122    let mut other = legacy;
123    other.extend(extras);
124    (qprime, other)
125}
126
127/// Built-in theme catalog.
128pub fn builtin_theme_catalog() -> Vec<ThemeDefinition> {
129    vec![
130        ThemeDefinition {
131            id: "human-warmth".to_string(),
132            class_name: Some("theme-human-warmth".to_string()),
133            stylesheet_href: None,
134            tokens: HashMap::from([
135                ("bg".to_string(), "#fbf9f6".to_string()),
136                ("surface".to_string(), "rgba(255, 255, 255, 0.72)".to_string()),
137                ("border".to_string(), "rgba(220, 210, 200, 0.55)".to_string()),
138                ("text".to_string(), "#2d2824".to_string()),
139                ("text-muted".to_string(), "#6f655d".to_string()),
140                ("accent".to_string(), "#a7432c".to_string()),
141                ("accent-glow".to_string(), "rgba(224, 122, 95, 0.18)".to_string()),
142                ("bg-gradient".to_string(), "radial-gradient(ellipse at 20% 15%, rgba(240,175,145,0.38) 0%, transparent 55%), radial-gradient(ellipse at 80% 75%, rgba(230,195,155,0.28) 0%, transparent 50%), linear-gradient(160deg, #fdf6f0 0%, #f5e8da 100%)".to_string()),
143            ]),
144        },
145        ThemeDefinition {
146            id: "twilight-blue".to_string(),
147            class_name: Some("theme-twilight-blue".to_string()),
148            stylesheet_href: None,
149            tokens: HashMap::from([
150                ("bg".to_string(), "#1e212b".to_string()),
151                ("surface".to_string(), "rgba(39, 43, 56, 0.6)".to_string()),
152                ("border".to_string(), "rgba(74, 85, 104, 0.4)".to_string()),
153                ("text".to_string(), "#f0f4f8".to_string()),
154                ("text-muted".to_string(), "#a0aec0".to_string()),
155                ("accent".to_string(), "#4fd1c5".to_string()),
156                ("accent-glow".to_string(), "rgba(79, 209, 197, 0.22)".to_string()),
157                ("bg-gradient".to_string(), "radial-gradient(ellipse at 20% 15%, rgba(79,209,197,0.18) 0%, transparent 50%), radial-gradient(ellipse at 80% 80%, rgba(59,130,246,0.12) 0%, transparent 50%), linear-gradient(160deg, #1a1e2a 0%, #20263a 100%)".to_string()),
158            ]),
159        },
160        ThemeDefinition {
161            id: "midnight-slate".to_string(),
162            class_name: Some("theme-midnight-slate".to_string()),
163            stylesheet_href: None,
164            tokens: HashMap::from([
165                ("bg".to_string(), "#0f111a".to_string()),
166                ("surface".to_string(), "rgba(23, 26, 38, 0.65)".to_string()),
167                ("border".to_string(), "rgba(45, 51, 74, 0.5)".to_string()),
168                ("text".to_string(), "#e2e8f0".to_string()),
169                ("text-muted".to_string(), "#94a3b8".to_string()),
170                ("accent".to_string(), "#818cf8".to_string()),
171                ("accent-glow".to_string(), "rgba(129, 140, 248, 0.18)".to_string()),
172                ("bg-gradient".to_string(), "radial-gradient(ellipse at 25% 20%, rgba(129,140,248,0.14) 0%, transparent 50%), radial-gradient(ellipse at 75% 80%, rgba(99,102,241,0.10) 0%, transparent 50%), linear-gradient(160deg, #0d0f18 0%, #121420 100%)".to_string()),
173            ]),
174        },
175        ThemeDefinition {
176            id: "fiduciary-dark".to_string(),
177            class_name: Some("theme-fiduciary-dark".to_string()),
178            stylesheet_href: None,
179            tokens: HashMap::from([
180                ("bg".to_string(), "#070b14".to_string()),
181                ("surface".to_string(), "rgba(15, 23, 38, 0.78)".to_string()),
182                ("border".to_string(), "rgba(148, 163, 184, 0.18)".to_string()),
183                ("text".to_string(), "#f1f5f9".to_string()),
184                ("text-muted".to_string(), "#9aa9bd".to_string()),
185                ("accent".to_string(), "#7dd3fc".to_string()),
186                ("accent-glow".to_string(), "rgba(56, 189, 248, 0.16)".to_string()),
187                ("bg-gradient".to_string(), "radial-gradient(ellipse at 14% 8%, rgba(56,189,248,0.11) 0%, transparent 42%), radial-gradient(ellipse at 88% 92%, rgba(129,140,248,0.10) 0%, transparent 46%), linear-gradient(155deg, #050812 0%, #0a1020 52%, #070b14 100%)".to_string()),
188                ("presentation-level".to_string(), "1".to_string()),
189                ("spatial-grammar".to_string(), "list".to_string()),
190                ("spatialize-allowed".to_string(), "true".to_string()),
191                ("motion-duration".to_string(), "120ms".to_string()),
192            ]),
193        },
194        ThemeDefinition {
195            id: "commons-light".to_string(),
196            class_name: Some("theme-commons-light".to_string()),
197            stylesheet_href: None,
198            tokens: HashMap::from([
199                ("bg".to_string(), "#faf9f6".to_string()), // Soft cream
200                ("surface".to_string(), "rgba(255, 255, 255, 0.75)".to_string()),
201                ("border".to_string(), "rgba(163, 177, 161, 0.4)".to_string()), // Sage-tinted border
202                ("text".to_string(), "#2d3748".to_string()),
203                ("text-muted".to_string(), "#596579".to_string()),
204                ("accent".to_string(), "#4a5568".to_string()), // Accessible slate/sage
205                ("accent-glow".to_string(), "rgba(74, 85, 104, 0.15)".to_string()),
206                ("bg-gradient".to_string(), "radial-gradient(ellipse at 20% 20%, rgba(163,177,161,0.15) 0%, transparent 50%), linear-gradient(160deg, #ffffff 0%, #f4f5f0 100%)".to_string()),
207            ]),
208        },
209        ThemeDefinition {
210            id: "sanctuary".to_string(),
211            class_name: Some("theme-sanctuary".to_string()),
212            stylesheet_href: None,
213            tokens: HashMap::from([
214                ("bg".to_string(), "#fefeff".to_string()),
215                ("surface".to_string(), "rgba(244, 246, 248, 0.95)".to_string()), // High clarity, opaque glass
216                ("border".to_string(), "rgba(200, 205, 212, 0.8)".to_string()),
217                ("text".to_string(), "#1a202c".to_string()), // High contrast text
218                ("text-muted".to_string(), "#4a5568".to_string()),
219                ("accent".to_string(), "#2b6cb0".to_string()), // Calm, trustworthy blue
220                ("accent-glow".to_string(), "rgba(43, 108, 176, 0.1)".to_string()),
221                ("bg-gradient".to_string(), "none".to_string()), // Muted, gentle
222                ("motion-duration".to_string(), "0ms".to_string()),
223                ("motion-ease".to_string(), "linear".to_string()),
224                ("presentation-level".to_string(), "0".to_string()),
225                ("spatial-grammar".to_string(), "list".to_string()),
226                ("spatialize-allowed".to_string(), "false".to_string()),
227            ]),
228        },
229        ThemeDefinition {
230            id: "infosphere".to_string(),
231            class_name: Some("theme-infosphere".to_string()),
232            stylesheet_href: None,
233            tokens: HashMap::from([
234                ("bg".to_string(), "#050510".to_string()), // Deep space
235                ("surface".to_string(), "rgba(18, 15, 38, 0.6)".to_string()),
236                ("border".to_string(), "rgba(78, 65, 128, 0.5)".to_string()),
237                ("text".to_string(), "#e0def4".to_string()),
238                ("text-muted".to_string(), "#908caa".to_string()),
239                ("accent".to_string(), "#eb6f92".to_string()), // Soft rose / neural
240                ("accent-glow".to_string(), "rgba(235, 111, 146, 0.25)".to_string()),
241                ("bg-gradient".to_string(), "radial-gradient(circle at 50% 50%, rgba(235,111,146,0.1) 0%, transparent 40%), radial-gradient(circle at 10% 80%, rgba(156,207,216,0.1) 0%, transparent 30%), linear-gradient(180deg, #020208 0%, #050510 100%)".to_string()),
242                ("presentation-level".to_string(), "3".to_string()),
243                ("spatial-grammar".to_string(), "strata".to_string()),
244                ("spatialize-allowed".to_string(), "true".to_string()),
245                ("motion-duration".to_string(), "180ms".to_string()),
246            ]),
247        },
248    ]
249}
250
251/// Resolves theme.
252pub fn resolve_theme(binding: Option<&ThemeBinding>, catalog: &[ThemeDefinition]) -> ResolvedTheme {
253    let Some(binding) = binding else {
254        return ResolvedTheme {
255            presentation_level: 1,
256            spatial_grammar: "list".into(),
257            spatialize_allowed: true,
258            ..Default::default()
259        };
260    };
261
262    let mut resolved = ResolvedTheme {
263        presentation_level: 1,
264        spatial_grammar: "list".into(),
265        spatialize_allowed: true,
266        ..Default::default()
267    };
268
269    if let Some(theme_id) = binding.theme_id.as_ref() {
270        resolved.theme_key = Some(theme_id.clone());
271
272        if let Some(definition) = catalog.iter().find(|theme| theme.id == *theme_id) {
273            resolved.class_name = definition.class_name.clone();
274            push_stylesheet(
275                &mut resolved.stylesheets,
276                definition.stylesheet_href.clone(),
277            );
278            resolved.tokens.extend(definition.tokens.clone());
279        }
280    }
281
282    if let Some(class_name) = binding.class_name.clone() {
283        resolved.class_name = Some(class_name);
284    }
285
286    push_stylesheet(&mut resolved.stylesheets, binding.stylesheet_href.clone());
287    resolved.tokens.extend(binding.tokens.clone());
288
289    // Presentation Binding fields (binding overrides theme tokens)
290    if let Some(level) = binding.presentation_level {
291        resolved.presentation_level = level.min(6);
292        resolved
293            .tokens
294            .insert("presentation-level".into(), level.to_string());
295    } else if let Some(s) = resolved.tokens.get("presentation-level") {
296        if let Ok(n) = s.parse::<u8>() {
297            resolved.presentation_level = n.min(6);
298        }
299    }
300    if let Some(g) = binding.spatial_grammar.as_ref() {
301        resolved.spatial_grammar = g.clone();
302        resolved.tokens.insert("spatial-grammar".into(), g.clone());
303    } else if let Some(g) = resolved.tokens.get("spatial-grammar") {
304        resolved.spatial_grammar = g.clone();
305    }
306    if let Some(ok) = binding.spatialize_allowed {
307        resolved.spatialize_allowed = ok;
308        resolved.tokens.insert(
309            "spatialize-allowed".into(),
310            if ok { "true" } else { "false" }.into(),
311        );
312    } else if let Some(s) = resolved.tokens.get("spatialize-allowed") {
313        resolved.spatialize_allowed = s != "false" && s != "0";
314    }
315    // Sanctuary hard policy: motion 0 already in tokens; force no spatialize
316    if resolved.theme_key.as_deref() == Some("sanctuary") {
317        resolved.spatialize_allowed = false;
318        resolved.presentation_level = resolved.presentation_level.min(1);
319        resolved
320            .tokens
321            .insert("spatialize-allowed".into(), "false".into());
322        resolved
323            .tokens
324            .insert("motion-duration".into(), "0ms".into());
325    }
326
327    resolved
328}
329
330/// Whether Spatialize should be offered in UI for this resolved pack.
331pub fn spatialize_allowed(theme: &ResolvedTheme) -> bool {
332    theme.spatialize_allowed
333}
334
335/// Default presentation level P0–P6 from pack.
336pub fn presentation_level(theme: &ResolvedTheme) -> u8 {
337    theme.presentation_level.min(6)
338}
339
340/// Motion, elevation, typography, and focus tokens shared by every QPrime scope.
341pub fn qprime_system_token_pairs() -> [(&'static str, &'static str); 12] {
342    [
343        ("elevation-0", "none"),
344        ("elevation-1", "0 12px 26px rgba(0, 0, 0, 0.18)"),
345        ("elevation-2", "0 22px 50px rgba(0, 0, 0, 0.28)"),
346        ("elevation-3", "0 28px 80px rgba(0, 0, 0, 0.38)"),
347        ("motion-duration", "220ms"),
348        ("motion-ease", "cubic-bezier(0.22, 1, 0.36, 1)"),
349        ("type-scale", "1"),
350        ("type-scale-sm", "0.875"),
351        ("type-scale-lg", "1.125"),
352        (
353            "focus-ring",
354            "0 0 0 3px var(--qualia-accent-glow, rgba(245, 158, 11, 0.35))",
355        ),
356        ("focus-ring-color", "var(--qualia-accent, #f59e0b)"),
357        ("focus-ring-offset", "2px"),
358    ]
359}
360
361/// Shoelace design tokens bridged from Qualia accent/surface tokens.
362pub fn shoelace_bridge_css(selector: &str, theme: &ResolvedTheme) -> String {
363    let accent = theme
364        .tokens
365        .get("accent")
366        .map(String::as_str)
367        .unwrap_or("#f59e0b");
368    let surface = theme
369        .tokens
370        .get("surface")
371        .map(String::as_str)
372        .unwrap_or("rgba(20, 28, 48, 0.7)");
373    let text = theme
374        .tokens
375        .get("text")
376        .map(String::as_str)
377        .unwrap_or("#f8f9fb");
378    format!(
379        "{selector} {{
380  --sl-color-primary-600: {accent};
381  --sl-color-primary-500: {accent};
382  --sl-color-primary-400: {accent};
383  --sl-color-neutral-0: {surface};
384  --sl-color-neutral-50: {surface};
385  --sl-color-neutral-900: {text};
386  --sl-focus-ring: var(--qualia-focus-ring);
387  --sl-transition-fast: var(--qualia-motion-duration);
388  --sl-transition-medium: var(--qualia-motion-duration);
389}}
390"
391    )
392}
393
394/// Renders scope-tokens.
395pub fn render_scope_tokens(selector: &str, theme: &ResolvedTheme) -> Option<String> {
396    let mut css = format!("{selector} {{\n");
397    for (token, value) in qprime_system_token_pairs() {
398        css.push_str("  --qualia-");
399        css.push_str(token);
400        css.push_str(": ");
401        css.push_str(value);
402        css.push_str(";\n");
403    }
404    let mut pairs: Vec<_> = theme.tokens.iter().collect();
405    pairs.sort_by(|left, right| left.0.cmp(right.0));
406    for (token, value) in pairs {
407        css.push_str("  --qualia-");
408        css.push_str(token);
409        css.push_str(": ");
410        css.push_str(value);
411        css.push_str(";\n");
412    }
413    css.push_str("}\n");
414    css.push_str(&shoelace_bridge_css(selector, theme));
415    Some(css)
416}
417
418/// Collects stylesheets.
419pub fn collect_stylesheets(themes: &[&ResolvedTheme]) -> Vec<String> {
420    let mut hrefs = BTreeSet::new();
421    for theme in themes {
422        for href in theme.stylesheets.iter() {
423            if !href.trim().is_empty() {
424                hrefs.insert(href.clone());
425            }
426        }
427    }
428    hrefs.into_iter().collect()
429}
430
431/// Joins theme classes.
432pub fn join_theme_classes(base_class: &str, theme: &ResolvedTheme) -> String {
433    match theme.class_name.as_deref() {
434        Some(class_name) if !class_name.trim().is_empty() => {
435            format!("{base_class} {class_name}")
436        }
437        _ => base_class.to_string(),
438    }
439}
440
441/// Motion timeline honoring sanctuary preset and resolved theme class.
442pub fn theme_motion_timeline(theme: &ResolvedTheme, dt: f64) -> crate::render::motion::Timeline {
443    let class = theme.class_name.as_deref();
444    crate::render::motion::timeline_from_theme(0.0, dt, class)
445}
446
447/// Spring scale bump when a pane is selected (native + wasm shared helper).
448pub fn theme_selection_pulse(
449    spring: &mut crate::render::motion::Spring,
450    selected: bool,
451    theme: &ResolvedTheme,
452) -> f64 {
453    crate::render::motion_loop::step_selection_spring(
454        spring,
455        selected,
456        theme.class_name.as_deref(),
457        0.016,
458    )
459}
460
461/// Human-readable provenance for inspector chips (Phase 2B).
462pub fn theme_binding_provenance(binding: &ThemeBinding) -> &'static str {
463    if !binding.tokens.is_empty()
464        || binding
465            .stylesheet_href
466            .as_ref()
467            .is_some_and(|h| !h.trim().is_empty())
468        || binding
469            .class_name
470            .as_ref()
471            .is_some_and(|c| !c.trim().is_empty())
472    {
473        "Locally overridden"
474    } else if binding.theme_id.is_some() {
475        "Inherited from preset"
476    } else {
477        "Workspace default"
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    #[test]
486    fn shoelace_bridge_maps_accent() {
487        let theme = resolve_theme(
488            Some(&ThemeBinding {
489                theme_id: Some("fiduciary-dark".to_string()),
490                ..Default::default()
491            }),
492            &builtin_theme_catalog(),
493        );
494        let css = shoelace_bridge_css(":root", &theme);
495        assert!(css.contains("--sl-color-primary-600: #7dd3fc"));
496    }
497
498    #[test]
499    fn theme_picker_lists_qprime_first() {
500        let (qprime, _) = theme_picker_sections(&builtin_theme_catalog());
501        assert_eq!(qprime.len(), 4);
502        assert_eq!(qprime[0].id, "fiduciary-dark");
503    }
504
505    #[test]
506    fn sanctuary_zero_motion_override() {
507        let theme = builtin_theme_catalog()
508            .into_iter()
509            .find(|t| t.id == "sanctuary")
510            .expect("sanctuary preset");
511        assert_eq!(
512            theme.tokens.get("motion-duration").map(String::as_str),
513            Some("0ms")
514        );
515    }
516
517    #[test]
518    fn theme_motion_timeline_honors_sanctuary() {
519        let theme = resolve_theme(
520            Some(&ThemeBinding {
521                theme_id: Some("sanctuary".to_string()),
522                ..Default::default()
523            }),
524            &builtin_theme_catalog(),
525        );
526        let timeline = theme_motion_timeline(&theme, 0.016);
527        assert!(timeline.reduced_motion);
528    }
529
530    #[test]
531    fn presentation_binding_sanctuary_disables_spatialize() {
532        let theme = resolve_theme(
533            Some(&ThemeBinding {
534                theme_id: Some("sanctuary".to_string()),
535                ..Default::default()
536            }),
537            &builtin_theme_catalog(),
538        );
539        assert!(!spatialize_allowed(&theme));
540        assert!(presentation_level(&theme) <= 1);
541        assert_eq!(
542            theme.tokens.get("motion-duration").map(String::as_str),
543            Some("0ms")
544        );
545    }
546
547    #[test]
548    fn presentation_binding_infosphere_biases_spatial() {
549        let theme = resolve_theme(
550            Some(&ThemeBinding {
551                theme_id: Some("infosphere".to_string()),
552                ..Default::default()
553            }),
554            &builtin_theme_catalog(),
555        );
556        assert!(spatialize_allowed(&theme));
557        assert!(presentation_level(&theme) >= 3);
558        assert_eq!(theme.spatial_grammar, "strata");
559    }
560
561    #[test]
562    fn presentation_binding_override_on_binding() {
563        let theme = resolve_theme(
564            Some(&ThemeBinding {
565                theme_id: Some("fiduciary-dark".to_string()),
566                presentation_level: Some(2),
567                spatial_grammar: Some("board".into()),
568                spatialize_allowed: Some(false),
569                ..Default::default()
570            }),
571            &builtin_theme_catalog(),
572        );
573        assert_eq!(presentation_level(&theme), 2);
574        assert_eq!(theme.spatial_grammar, "board");
575        assert!(!spatialize_allowed(&theme));
576    }
577
578    #[test]
579    fn builtin_theme_text_and_muted_text_meet_wcag_aa() {
580        for theme in builtin_theme_catalog() {
581            let background = theme.tokens.get("bg").expect("theme background");
582            for token in ["text", "text-muted"] {
583                let foreground = theme.tokens.get(token).expect("theme text token");
584                let ratio = contrast_ratio(foreground, background)
585                    .unwrap_or_else(|| panic!("opaque colours required for {} {token}", theme.id));
586                assert!(
587                    ratio >= 4.5,
588                    "{} {token} contrast {ratio:.2}:1 is below WCAG AA",
589                    theme.id
590                );
591            }
592        }
593    }
594}
595
596fn push_stylesheet(stylesheets: &mut Vec<String>, href: Option<String>) {
597    if let Some(href) = href {
598        if !href.trim().is_empty() && !stylesheets.iter().any(|existing| existing == &href) {
599            stylesheets.push(href);
600        }
601    }
602}