Skip to main content

rustango_cms/
theme.rs

1//! Visual themes — design tokens stored as data, rendered as CSS
2//! variables:
3//! a [`Theme`] holds surface / semantic colors + typography + radii +
4//! shadows; [`BrandColor`] rows attach N named brand colors per theme,
5//! each emitting its own slug-keyed CSS variable triplet (raw / rgb /
6//! contrast) plus an auto-derived 50→950 shade scale.
7//!
8//! The theme is rendered into a `<style>` block by [`emit_css`] —
9//! consumers (admin chrome, public page render) drop the block into
10//! `<head>` and reference `var(--color-bg)`, `var(--color-primary)`
11//! etc. anywhere downstream.
12//!
13//! The admin chrome reads Material Design 3 token names
14//! (`--md-sys-color-surface`, `--md-sys-color-primary`, …), not the
15//! legacy `--color-*` names this module historically emitted. So every
16//! block now emits BOTH namespaces: the legacy `--color-*` for any
17//! host crate / public template still reading them, plus the MD3
18//! bridge so picking a different admin theme actually shifts the
19//! chrome palette. Container / on-* variants the schema doesn't carry
20//! directly are derived via `mix_with_neutral` + `wcag_foreground`.
21
22use chrono::{DateTime, Utc};
23use rustango::sql::Auto;
24use rustango::Model;
25use serde::{Deserialize, Serialize};
26
27/// A named design-token bundle. Editors create one per visual style
28/// they want to ship: "Teal", "Forest", "Aurora Violet".
29///
30/// One theme can be marked `is_admin_default` (drives the admin
31/// chrome) and one `is_default` (the fallback for public pages with
32/// no explicit theme). They can be the same row or different.
33///
34/// The `_dark` columns are optional — when blank, the light value
35/// shows through for dark mode too. The renderer emits both variants
36/// behind `[data-theme="light"]` / `[data-theme="dark"]` blocks.
37#[derive(Model, Debug, Clone, Serialize, Deserialize)]
38#[rustango(
39    table = "cms_theme",
40    app = "cms",
41    display = "name",
42    admin(
43        list_display = "name, slug, is_admin_default, is_default, default_mode",
44        ordering = "name",
45        list_filter = "is_default, is_admin_default",
46    )
47)]
48pub struct Theme {
49    #[rustango(primary_key)]
50    pub id: Auto<i64>,
51
52    /// Human display name — "Teal", "Forest", etc.
53    #[rustango(max_length = 100)]
54    pub name: String,
55
56    /// URL-safe identifier — emitted into the body class as
57    /// `theme-<slug>` so per-theme template overrides work
58    /// (`.theme-forest .hero { … }`).
59    #[rustango(max_length = 64, unique)]
60    pub slug: String,
61
62    /// When true, this theme drives the CMS admin UI chrome. Exactly
63    /// one row at a time; the picker enforces it.
64    pub is_admin_default: bool,
65
66    /// When true, this is the fallback theme for public pages with
67    /// no explicit `page.theme_id`. Exactly one row at a time.
68    pub is_default: bool,
69
70    /// Default mode for visitors with no saved preference. Valid
71    /// values: `light`, `dark`, `system`.
72    #[rustango(max_length = 16)]
73    pub default_mode: String,
74
75    // -------- Surface colors (light) --------
76    #[rustango(max_length = 32)]
77    pub color_bg: String,
78    #[rustango(max_length = 32)]
79    pub color_surface: String,
80    #[rustango(max_length = 32)]
81    pub color_text_primary: String,
82    #[rustango(max_length = 32)]
83    pub color_text_secondary: String,
84    #[rustango(max_length = 32)]
85    pub color_text_muted: String,
86    #[rustango(max_length = 32)]
87    pub color_border: String,
88
89    // -------- Surface colors (dark) --------
90    #[rustango(max_length = 32)]
91    pub color_bg_dark: String,
92    #[rustango(max_length = 32)]
93    pub color_surface_dark: String,
94    #[rustango(max_length = 32)]
95    pub color_text_primary_dark: String,
96    #[rustango(max_length = 32)]
97    pub color_text_secondary_dark: String,
98    #[rustango(max_length = 32)]
99    pub color_text_muted_dark: String,
100    #[rustango(max_length = 32)]
101    pub color_border_dark: String,
102
103    // -------- Semantic colors (light only — dark inherits) --------
104    #[rustango(max_length = 32)]
105    pub color_success: String,
106    #[rustango(max_length = 32)]
107    pub color_warning: String,
108    #[rustango(max_length = 32)]
109    pub color_error: String,
110    #[rustango(max_length = 32)]
111    pub color_info: String,
112    #[rustango(max_length = 32)]
113    pub color_link: String,
114    #[rustango(max_length = 32)]
115    pub color_focus_ring: String,
116
117    // -------- Typography --------
118    #[rustango(max_length = 255)]
119    pub font_heading: String,
120    #[rustango(max_length = 255)]
121    pub font_body: String,
122    /// Optional URL to an external font CSS (e.g. Google Fonts) the
123    /// renderer should `<link>` before the variables block.
124    #[rustango(max_length = 500)]
125    pub font_url: String,
126
127    // -------- Radii + shadows --------
128    #[rustango(max_length = 16)]
129    pub radius_sm: String,
130    #[rustango(max_length = 16)]
131    pub radius_md: String,
132    #[rustango(max_length = 16)]
133    pub radius_lg: String,
134    #[rustango(max_length = 255)]
135    pub shadow_sm: String,
136    #[rustango(max_length = 255)]
137    pub shadow_md: String,
138    #[rustango(max_length = 255)]
139    pub shadow_lg: String,
140
141    #[rustango(auto_now_add)]
142    pub created_at: Auto<DateTime<Utc>>,
143    #[rustango(auto_now)]
144    pub updated_at: Auto<DateTime<Utc>>,
145}
146
147/// A named brand color attached to a [`Theme`]. Each one emits:
148///
149/// - `--color-<slug>` — the raw value as authored.
150/// - `--color-<slug>-rgb` — RGB triplet (only when the value is a
151///   solid color, not a gradient). Powers Tailwind opacity.
152/// - `--color-<slug>-contrast` — auto-computed via WCAG luminance.
153/// - `--color-<slug>-50` … `--color-<slug>-950` — Tailwind-aligned
154///   shade scale auto-derived from the base.
155#[derive(Model, Debug, Clone, Serialize, Deserialize)]
156#[rustango(
157    table = "cms_brand_color",
158    app = "cms",
159    display = "name",
160    admin(
161        list_display = "theme_id, name, slug, sort_order, color_value",
162        ordering = "theme_id, sort_order",
163    )
164)]
165pub struct BrandColor {
166    #[rustango(primary_key)]
167    pub id: Auto<i64>,
168
169    #[rustango(fk = "cms_theme", on = "id", index)]
170    pub theme_id: i64,
171
172    /// URL-safe identifier — becomes the `--color-<slug>` variable.
173    #[rustango(max_length = 64)]
174    pub slug: String,
175
176    /// Display name for the admin picker. "Primary", "Aurora", etc.
177    #[rustango(max_length = 100)]
178    pub name: String,
179
180    /// Light-mode value. Solid color (`#rrggbb` / `rgb()` / `hsl()`)
181    /// or a gradient.
182    #[rustango(max_length = 255)]
183    pub color_value: String,
184
185    /// Optional dark-mode override. Empty = fall back to
186    /// `color_value`.
187    #[rustango(max_length = 255)]
188    pub color_value_dark: String,
189
190    /// Ordering for the admin picker.
191    pub sort_order: i32,
192}
193
194// =====================================================================
195// CSS emission
196// =====================================================================
197
198/// Render a `Theme` (plus its `BrandColor` rows) as a `<style>` block
199/// ready to drop into `<head>`. Emits:
200///
201/// - `:root { … }` — surface, semantic, typography, radii, shadow
202///   tokens in their light-mode values.
203/// - `[data-theme="dark"] { … }` — overrides for dark mode.
204/// - One block per brand color with raw / rgb / contrast / 50-950.
205///
206/// The returned string is plain HTML; the caller is responsible for
207/// rendering it into the `<head>` (e.g. via Tera or a context var).
208#[must_use]
209pub fn emit_css(theme: &Theme, brand_colors: &[BrandColor]) -> String {
210    let mut out = String::with_capacity(8192);
211    out.push_str("<style data-rcms-theme=\"");
212    out.push_str(&html_escape_attr(&theme.slug));
213    out.push_str("\">\n");
214
215    // -------- :root (light defaults) --------
216    // Specificity matters: cms.css's dark block uses `:root[data-theme="dark"]`
217    // (0,2,0), so emit_css's dark/system blocks must do the same to win the
218    // cascade — see below. The light block stays `:root` because the cms.css
219    // light defaults sit on `:root` too and we want this to override them by
220    // source order (theme CSS loads AFTER cms.css in `_base.html`).
221    out.push_str(":root {\n");
222    // Legacy `--color-*` namespace — kept for back-compat with any host
223    // crate / public template still reading them.
224    push_var(&mut out, "color-bg", &theme.color_bg);
225    push_var(&mut out, "color-surface", &theme.color_surface);
226    push_var(&mut out, "color-text-primary", &theme.color_text_primary);
227    push_var(
228        &mut out,
229        "color-text-secondary",
230        &theme.color_text_secondary,
231    );
232    push_var(&mut out, "color-text-muted", &theme.color_text_muted);
233    push_var(&mut out, "color-border", &theme.color_border);
234    push_var(&mut out, "color-success", &theme.color_success);
235    push_var(&mut out, "color-warning", &theme.color_warning);
236    push_var(&mut out, "color-error", &theme.color_error);
237    push_var(&mut out, "color-info", &theme.color_info);
238    push_var(&mut out, "color-link", &theme.color_link);
239    push_var(&mut out, "color-focus-ring", &theme.color_focus_ring);
240    push_var(&mut out, "font-heading", &theme.font_heading);
241    push_var(&mut out, "font-body", &theme.font_body);
242    push_var(&mut out, "radius-sm", &theme.radius_sm);
243    push_var(&mut out, "radius-md", &theme.radius_md);
244    push_var(&mut out, "radius-lg", &theme.radius_lg);
245    push_var(&mut out, "shadow-sm", &theme.shadow_sm);
246    push_var(&mut out, "shadow-md", &theme.shadow_md);
247    push_var(&mut out, "shadow-lg", &theme.shadow_lg);
248    // #274 — MD3 bridge: write the same palette into the
249    // `--md-sys-color-*` namespace the chrome actually reads.
250    emit_md3_bridge(
251        &mut out,
252        "  ",
253        Md3Bridge {
254            bg: &theme.color_bg,
255            surface: &theme.color_surface,
256            text_primary: &theme.color_text_primary,
257            text_secondary: &theme.color_text_secondary,
258            text_muted: &theme.color_text_muted,
259            border: &theme.color_border,
260            link: &theme.color_link,
261            success: &theme.color_success,
262            warning: &theme.color_warning,
263            error: &theme.color_error,
264            mode: BridgeMode::Light,
265        },
266    );
267    // Brand colors — light variants here.
268    for bc in brand_colors {
269        emit_brand_color_block(&mut out, &bc.slug, &bc.color_value);
270    }
271    out.push_str("}\n");
272
273    // -------- :root[data-theme="dark"] --------
274    // `:root[…]` matches cms.css's specificity (0,2,0) so our overrides win
275    // by source order. Using bare `[data-theme="dark"]` (0,1,0) loses to
276    // cms.css's defaults and the theme switch becomes invisible.
277    out.push_str(":root[data-theme=\"dark\"] {\n");
278    push_var(&mut out, "color-bg", &theme.color_bg_dark);
279    push_var(&mut out, "color-surface", &theme.color_surface_dark);
280    push_var(
281        &mut out,
282        "color-text-primary",
283        &theme.color_text_primary_dark,
284    );
285    push_var(
286        &mut out,
287        "color-text-secondary",
288        &theme.color_text_secondary_dark,
289    );
290    push_var(&mut out, "color-text-muted", &theme.color_text_muted_dark);
291    push_var(&mut out, "color-border", &theme.color_border_dark);
292    emit_md3_bridge(
293        &mut out,
294        "  ",
295        Md3Bridge {
296            bg: pick_with_fallback(&theme.color_bg_dark, &theme.color_bg),
297            surface: pick_with_fallback(&theme.color_surface_dark, &theme.color_surface),
298            text_primary: pick_with_fallback(
299                &theme.color_text_primary_dark,
300                &theme.color_text_primary,
301            ),
302            text_secondary: pick_with_fallback(
303                &theme.color_text_secondary_dark,
304                &theme.color_text_secondary,
305            ),
306            text_muted: pick_with_fallback(&theme.color_text_muted_dark, &theme.color_text_muted),
307            border: pick_with_fallback(&theme.color_border_dark, &theme.color_border),
308            // Semantics + link reuse the light value — schema doesn't carry
309            // dark overrides for these. The bridge derives container tints
310            // appropriately for the dark surface inside `emit_md3_bridge`.
311            link: &theme.color_link,
312            success: &theme.color_success,
313            warning: &theme.color_warning,
314            error: &theme.color_error,
315            mode: BridgeMode::Dark,
316        },
317    );
318    // Brand colors with explicit dark overrides.
319    for bc in brand_colors {
320        let dark_value = if bc.color_value_dark.is_empty() {
321            &bc.color_value
322        } else {
323            &bc.color_value_dark
324        };
325        emit_brand_color_block(&mut out, &bc.slug, dark_value);
326    }
327    out.push_str("}\n");
328
329    // -------- @media (prefers-color-scheme: dark) for "system" --------
330    // Must match cms.css's own OS-dark selector EXACTLY: `:root:not(
331    // [data-theme="light"])`. "System" mode is represented by the ABSENCE of
332    // `data-theme` (the admin's no-flash script removes the attribute), so
333    // keying on `[data-theme="system"]` never matched — the theme's dark
334    // palette (incl. the accent) was silently dropped in System mode and the
335    // chrome fell back to cms.css's built-in dark defaults (the violet accent).
336    out.push_str("@media (prefers-color-scheme: dark) {\n");
337    out.push_str("  :root:not([data-theme=\"light\"]) {\n");
338    push_var_indented(&mut out, "color-bg", &theme.color_bg_dark);
339    push_var_indented(&mut out, "color-surface", &theme.color_surface_dark);
340    push_var_indented(
341        &mut out,
342        "color-text-primary",
343        &theme.color_text_primary_dark,
344    );
345    push_var_indented(
346        &mut out,
347        "color-text-secondary",
348        &theme.color_text_secondary_dark,
349    );
350    push_var_indented(&mut out, "color-text-muted", &theme.color_text_muted_dark);
351    push_var_indented(&mut out, "color-border", &theme.color_border_dark);
352    emit_md3_bridge(
353        &mut out,
354        "    ",
355        Md3Bridge {
356            bg: pick_with_fallback(&theme.color_bg_dark, &theme.color_bg),
357            surface: pick_with_fallback(&theme.color_surface_dark, &theme.color_surface),
358            text_primary: pick_with_fallback(
359                &theme.color_text_primary_dark,
360                &theme.color_text_primary,
361            ),
362            text_secondary: pick_with_fallback(
363                &theme.color_text_secondary_dark,
364                &theme.color_text_secondary,
365            ),
366            text_muted: pick_with_fallback(&theme.color_text_muted_dark, &theme.color_text_muted),
367            border: pick_with_fallback(&theme.color_border_dark, &theme.color_border),
368            link: &theme.color_link,
369            success: &theme.color_success,
370            warning: &theme.color_warning,
371            error: &theme.color_error,
372            mode: BridgeMode::Dark,
373        },
374    );
375    for bc in brand_colors {
376        let dark_value = if bc.color_value_dark.is_empty() {
377            &bc.color_value
378        } else {
379            &bc.color_value_dark
380        };
381        emit_brand_color_block_indented(&mut out, &bc.slug, dark_value);
382    }
383    out.push_str("  }\n");
384    out.push_str("}\n");
385
386    out.push_str("</style>\n");
387    out
388}
389
390/// Inputs for the MD3 bridge. Wraps the resolved (light- or dark-variant)
391/// colors so [`emit_md3_bridge`] doesn't grow a 12-arg signature.
392struct Md3Bridge<'a> {
393    bg: &'a str,
394    surface: &'a str,
395    text_primary: &'a str,
396    text_secondary: &'a str,
397    text_muted: &'a str,
398    border: &'a str,
399    link: &'a str,
400    success: &'a str,
401    warning: &'a str,
402    error: &'a str,
403    mode: BridgeMode,
404}
405
406#[derive(Clone, Copy)]
407enum BridgeMode {
408    /// Light surfaces — containers step DARKER than `surface`; primary
409    /// containers tint LIGHTER toward white.
410    Light,
411    /// Dark surfaces — containers step LIGHTER than `surface`; primary
412    /// containers tint DARKER toward black so they sit visually below
413    /// the base primary against a dark page.
414    Dark,
415}
416
417/// Map the theme's `color_*` columns onto the Material 3 token names
418/// the admin chrome reads (`--md-sys-color-*`). Variants the schema
419/// doesn't carry directly — surface container tiers, primary
420/// container / fixed, on-* contrast pairs — are derived via mixing +
421/// WCAG luminance so the resolved palette covers every name listed in
422/// the `:root` block of `src/admin/static/cms.css`.
423fn emit_md3_bridge(buf: &mut String, indent: &str, b: Md3Bridge<'_>) {
424    let push = |buf: &mut String, name: &str, value: &str| push_var_at(buf, indent, name, value);
425
426    // ---- Surfaces ----
427    // Container tier steps; signs depend on mode (see [`BridgeMode`]).
428    let (cstep_low, cstep, cstep_high, cstep_highest, cstep_dim, cstep_bright) = match b.mode {
429        BridgeMode::Light => (0.03_f32, 0.06, 0.10, 0.14, 0.05, -0.05),
430        BridgeMode::Dark => (-0.05_f32, -0.10, -0.15, -0.20, 0.05, -0.10),
431    };
432    push(buf, "md-sys-color-surface", b.bg);
433    push(
434        buf,
435        "md-sys-color-surface-dim",
436        &mix_or_same(b.bg, cstep_dim),
437    );
438    push(
439        buf,
440        "md-sys-color-surface-bright",
441        &mix_or_same(b.bg, cstep_bright),
442    );
443    push(buf, "md-sys-color-surface-container-lowest", b.surface);
444    push(
445        buf,
446        "md-sys-color-surface-container-low",
447        &mix_or_same(b.surface, cstep_low),
448    );
449    push(
450        buf,
451        "md-sys-color-surface-container",
452        &mix_or_same(b.surface, cstep),
453    );
454    push(
455        buf,
456        "md-sys-color-surface-container-high",
457        &mix_or_same(b.surface, cstep_high),
458    );
459    push(
460        buf,
461        "md-sys-color-surface-container-highest",
462        &mix_or_same(b.surface, cstep_highest),
463    );
464    push(buf, "md-sys-color-surface-variant", b.border);
465    push(buf, "md-sys-color-on-surface", b.text_primary);
466    push(buf, "md-sys-color-on-surface-variant", b.text_secondary);
467    push(buf, "md-sys-color-outline", b.text_muted);
468    push(buf, "md-sys-color-outline-variant", b.border);
469    push(buf, "md-sys-color-inverse-surface", b.text_primary);
470    push(buf, "md-sys-color-inverse-on-surface", b.surface);
471
472    // ---- Primary (driven by color_link — the most visible accent) ----
473    // Container/fixed derivations tinted appropriately per mode.
474    let (p_container_t, p_fixed_t, p_fixed_dim_t, p_on_fixed_variant_t) = match b.mode {
475        BridgeMode::Light => (-0.35_f32, -0.78, -0.55, 0.35),
476        BridgeMode::Dark => (0.30_f32, -0.55, -0.30, 0.55),
477    };
478    let primary_container = mix_or_same(b.link, p_container_t);
479    let primary_fixed = mix_or_same(b.link, p_fixed_t);
480    let primary_fixed_dim = mix_or_same(b.link, p_fixed_dim_t);
481    let on_primary_fixed_variant = mix_or_same(b.link, p_on_fixed_variant_t);
482    push(buf, "md-sys-color-primary", b.link);
483    push(buf, "md-sys-color-on-primary", wcag_foreground(b.link));
484    push(buf, "md-sys-color-primary-container", &primary_container);
485    push(
486        buf,
487        "md-sys-color-on-primary-container",
488        wcag_foreground(&primary_container),
489    );
490    push(buf, "md-sys-color-primary-fixed", &primary_fixed);
491    push(buf, "md-sys-color-primary-fixed-dim", &primary_fixed_dim);
492    push(buf, "md-sys-color-on-primary-fixed", b.link);
493    push(
494        buf,
495        "md-sys-color-on-primary-fixed-variant",
496        &on_primary_fixed_variant,
497    );
498    push(buf, "md-sys-color-surface-tint", b.link);
499    push(buf, "md-sys-color-inverse-primary", &primary_fixed_dim);
500
501    // ---- Secondary (driven by text_muted — neutral chip accent) ----
502    let secondary_container = mix_or_same(
503        b.text_muted,
504        match b.mode {
505            BridgeMode::Light => -0.55,
506            BridgeMode::Dark => 0.35,
507        },
508    );
509    push(buf, "md-sys-color-secondary", b.text_muted);
510    push(
511        buf,
512        "md-sys-color-on-secondary",
513        wcag_foreground(b.text_muted),
514    );
515    push(
516        buf,
517        "md-sys-color-secondary-container",
518        &secondary_container,
519    );
520    push(
521        buf,
522        "md-sys-color-on-secondary-container",
523        wcag_foreground(&secondary_container),
524    );
525
526    // ---- Tertiary (driven by link too — themes only carry one accent) ----
527    let tertiary_container = mix_or_same(
528        b.link,
529        match b.mode {
530            BridgeMode::Light => -0.25,
531            BridgeMode::Dark => 0.20,
532        },
533    );
534    let tertiary_fixed_t = match b.mode {
535        BridgeMode::Light => -0.65,
536        BridgeMode::Dark => -0.40,
537    };
538    let tertiary_fixed = mix_or_same(b.link, tertiary_fixed_t);
539    let tertiary_fixed_dim = mix_or_same(b.link, tertiary_fixed_t - 0.20);
540    push(buf, "md-sys-color-tertiary", b.link);
541    push(buf, "md-sys-color-on-tertiary", wcag_foreground(b.link));
542    push(buf, "md-sys-color-tertiary-container", &tertiary_container);
543    push(
544        buf,
545        "md-sys-color-on-tertiary-container",
546        wcag_foreground(&tertiary_container),
547    );
548    push(buf, "md-sys-color-tertiary-fixed", &tertiary_fixed);
549    push(buf, "md-sys-color-tertiary-fixed-dim", &tertiary_fixed_dim);
550
551    // ---- Semantic colors ----
552    emit_semantic_pair(buf, indent, "success", b.success, b.mode);
553    emit_semantic_pair(buf, indent, "warning", b.warning, b.mode);
554    emit_semantic_pair(buf, indent, "error", b.error, b.mode);
555}
556
557/// Emit the four-tuple of `--md-sys-color-<name>` / `-on-<name>` /
558/// `-<name>-container` / `-on-<name>-container` for a single semantic
559/// hue (success / warning / error). Container tinted away from the
560/// base in the surface direction; foreground picked via WCAG luminance.
561fn emit_semantic_pair(buf: &mut String, indent: &str, name: &str, value: &str, mode: BridgeMode) {
562    if value.is_empty() {
563        return;
564    }
565    let container_t = match mode {
566        BridgeMode::Light => -0.55_f32,
567        BridgeMode::Dark => 0.40,
568    };
569    let on_container_t = match mode {
570        BridgeMode::Light => 0.40_f32,
571        BridgeMode::Dark => -0.55,
572    };
573    // The base hue is authored for light surfaces; on dark it must
574    // lighten or text/border uses (field errors, tree badges) fall
575    // below readable contrast (MD3 itself ships #ba1a1a → #ffb4ab).
576    let base = match mode {
577        BridgeMode::Light => value.to_string(),
578        BridgeMode::Dark => mix_or_same(value, -0.60),
579    };
580    let container = mix_or_same(value, container_t);
581    let on_container = mix_or_same(value, on_container_t);
582    let write = |buf: &mut String, var: &str, val: &str| {
583        push_var_at(buf, indent, &format!("md-sys-color-{var}"), val);
584    };
585    write(buf, name, &base);
586    write(buf, &format!("on-{name}"), wcag_foreground(&base));
587    write(buf, &format!("{name}-container"), &container);
588    write(buf, &format!("on-{name}-container"), &on_container);
589}
590
591/// Mix `hex` toward white/black by `t` and return the result — or fall
592/// back to the original string when the input isn't 6-digit hex (named
593/// colors, gradients, `rgb(…)`). The caller usually wants to emit
594/// SOMETHING even on a non-hex value rather than swallowing the var.
595fn mix_or_same(hex: &str, t: f32) -> String {
596    mix_with_neutral(hex, t).unwrap_or_else(|| hex.to_string())
597}
598
599/// Pick `primary` if non-empty, else `fallback`. Used to resolve the
600/// dark-mode value for surface columns where the `_dark` companion may
601/// be blank (the schema lets editors skip them — light value carries
602/// through). Returning &str keeps the call sites borrow-clean.
603fn pick_with_fallback<'a>(primary: &'a str, fallback: &'a str) -> &'a str {
604    if primary.is_empty() {
605        fallback
606    } else {
607        primary
608    }
609}
610
611fn push_var(buf: &mut String, name: &str, value: &str) {
612    push_var_at(buf, "  ", name, value);
613}
614
615fn push_var_indented(buf: &mut String, name: &str, value: &str) {
616    push_var_at(buf, "    ", name, value);
617}
618
619/// Append `--name: value;` — or nothing, when either half could end the
620/// declaration, the rule or the `<style>` element. Theme and brand
621/// colour rows are editable by any user with change permission on those
622/// models, and this output reaches every public page and the admin chrome
623/// with `| safe`, so a value is data and must stay inside its declaration.
624fn push_var_at(buf: &mut String, indent: &str, name: &str, value: &str) {
625    if value.is_empty() || !is_css_ident(name) || !is_inert_css_value(value) {
626        return;
627    }
628    buf.push_str(indent);
629    buf.push_str("--");
630    buf.push_str(name);
631    buf.push_str(": ");
632    buf.push_str(value);
633    buf.push_str(";\n");
634}
635
636fn is_css_ident(name: &str) -> bool {
637    !name.is_empty()
638        && name
639            .bytes()
640            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
641}
642
643/// A custom-property value that cannot escape its declaration: no `;` `{`
644/// `}` to end it, no `<` to close the `<style>` element, no `\` escapes,
645/// no comment opener and no control characters.
646fn is_inert_css_value(value: &str) -> bool {
647    !value.contains("/*")
648        && !value
649            .chars()
650            .any(|c| matches!(c, ';' | '{' | '}' | '<' | '>' | '\\') || c.is_control())
651}
652
653fn html_escape_attr(s: &str) -> String {
654    s.replace('&', "&amp;")
655        .replace('"', "&quot;")
656        .replace('<', "&lt;")
657        .replace('>', "&gt;")
658}
659
660fn emit_brand_color_block(buf: &mut String, slug: &str, value: &str) {
661    push_var(buf, &format!("color-{slug}"), value);
662    if let Some(rgb) = hex_to_rgb_triplet(value) {
663        push_var(buf, &format!("color-{slug}-rgb"), &rgb);
664        push_var(
665            buf,
666            &format!("color-{slug}-contrast"),
667            wcag_foreground(value),
668        );
669        // 50 → 950 shade scale.
670        for (suffix, t) in SHADE_LEVELS {
671            if let Some(shade) = mix_with_neutral(value, *t) {
672                push_var(buf, &format!("color-{slug}-{suffix}"), &shade);
673            }
674        }
675    }
676}
677
678fn emit_brand_color_block_indented(buf: &mut String, slug: &str, value: &str) {
679    push_var_indented(buf, &format!("color-{slug}"), value);
680    if let Some(rgb) = hex_to_rgb_triplet(value) {
681        push_var_indented(buf, &format!("color-{slug}-rgb"), &rgb);
682        push_var_indented(
683            buf,
684            &format!("color-{slug}-contrast"),
685            wcag_foreground(value),
686        );
687        for (suffix, t) in SHADE_LEVELS {
688            if let Some(shade) = mix_with_neutral(value, *t) {
689                push_var_indented(buf, &format!("color-{slug}-{suffix}"), &shade);
690            }
691        }
692    }
693}
694
695// Tailwind-aligned scale. Negative t mixes toward white, positive
696// toward black. Tuned to roughly land where Tailwind 50/100/.../950
697// sit relative to the 500 base.
698const SHADE_LEVELS: &[(&str, f32)] = &[
699    ("50", -0.92),
700    ("100", -0.82),
701    ("200", -0.62),
702    ("300", -0.40),
703    ("400", -0.20),
704    ("500", 0.0),
705    ("600", 0.14),
706    ("700", 0.30),
707    ("800", 0.48),
708    ("900", 0.66),
709    ("950", 0.82),
710];
711
712/// Parse `rrggbb` (an optional leading `#` is dropped) into bytes.
713///
714/// Checks the digits before slicing: `len()` counts bytes, so a 6-byte
715/// non-ASCII string (`"aé€"`) would otherwise pass a length check and
716/// panic on a char boundary.
717pub(crate) fn parse_rgb6(hex: &str) -> Option<(u8, u8, u8)> {
718    let s = hex.trim_start_matches('#');
719    if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
720        return None;
721    }
722    let byte = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
723    Some((byte(0)?, byte(2)?, byte(4)?))
724}
725
726/// Parse `#rrggbb` (with or without `#`, case-insensitive) into a
727/// space-separated `"r g b"` triplet suitable for
728/// `rgb(var(--…-rgb) / 50%)` Tailwind syntax. Returns `None` for
729/// anything that isn't a 6-digit hex (gradients, named colors, etc.)
730/// — those get no `-rgb` companion and no shade scale.
731fn hex_to_rgb_triplet(hex: &str) -> Option<String> {
732    let (r, g, b) = parse_rgb6(hex.trim())?;
733    Some(format!("{r} {g} {b}"))
734}
735
736/// Mix `hex` with white (t<0) or black (t>0) by ratio `|t|`. Returns
737/// the result as `#rrggbb`. Used to synthesize a 50→950 shade scale
738/// from a single base color.
739fn mix_with_neutral(hex: &str, t: f32) -> Option<String> {
740    let (r, g, b) = parse_rgb6(hex.trim())?;
741    let (r, g, b) = (r as f32, g as f32, b as f32);
742    let (target, ratio) = if t < 0.0 { (255.0, -t) } else { (0.0, t) };
743    let mix = |c: f32| (c + (target - c) * ratio).clamp(0.0, 255.0) as u8;
744    Some(format!("#{:02x}{:02x}{:02x}", mix(r), mix(g), mix(b)))
745}
746
747/// WCAG-style luminance check; returns `#000` for light backgrounds,
748/// `#fff` for dark ones. Good enough for body text on a brand color.
749fn wcag_foreground(hex: &str) -> &'static str {
750    let Some((r, g, b)) = parse_rgb6(hex.trim()) else {
751        return "#fff";
752    };
753    let lum = 0.2126 * (r as f32) + 0.7152 * (g as f32) + 0.0722 * (b as f32);
754    if lum > 140.0 {
755        "#0a0a0a"
756    } else {
757        "#ffffff"
758    }
759}
760
761#[cfg(test)]
762pub(crate) mod tests {
763    use super::*;
764
765    #[test]
766    fn hostile_theme_values_never_leave_their_declaration() {
767        let mut theme = fixture_theme();
768        theme.slug = "x\"><script>alert(1)</script>".into();
769        theme.color_link = "red}</style><svg onload=alert(1)>".into();
770        theme.font_body = "a; } body { display: none".into();
771        theme.color_bg = "#fff /* swallow the rest".into();
772        theme.color_surface = "\"Inter\", 'Helvetica Neue', sans-serif".into();
773        let brand = BrandColor {
774            id: Auto::Unset,
775            theme_id: 1,
776            slug: "x:root{}".into(),
777            name: "Hostile".into(),
778            color_value: "#123456".into(),
779            color_value_dark: String::new(),
780            sort_order: 0,
781        };
782        let css = emit_css(&theme, &[brand]);
783        assert!(!css.contains("</style><") && !css.contains("<svg") && !css.contains("<script"));
784        assert!(!css.contains("display: none") && !css.contains("swallow"));
785        assert!(!css.contains("x:root"), "a hostile brand slug is not a property name");
786        assert!(css.contains("--color-surface: \"Inter\", 'Helvetica Neue', sans-serif;"));
787        assert_eq!(css.matches("<style").count(), 1);
788        assert_eq!(css.matches("</style>").count(), 1);
789    }
790
791    #[test]
792    fn six_byte_non_ascii_colours_are_rejected_not_panicked_on() {
793        // 1 + 2 + 3 bytes: passes a byte-length check, index 2 is mid-char.
794        let bad = "a\u{e9}\u{20ac}";
795        assert_eq!(parse_rgb6(bad), None);
796        assert_eq!(hex_to_rgb_triplet(bad), None);
797        assert_eq!(mix_with_neutral(bad, 0.5), None);
798        assert_eq!(wcag_foreground(bad), "#fff");
799        assert_eq!(parse_rgb6("#3B82f6"), Some((59, 130, 246)));
800        assert_eq!(parse_rgb6("+1+2+3"), None, "from_str_radix alone accepts a sign");
801    }
802
803    #[test]
804    fn hex_to_rgb_parses_six_digit() {
805        assert_eq!(hex_to_rgb_triplet("#3b82f6"), Some("59 130 246".to_owned()));
806        assert_eq!(hex_to_rgb_triplet("3b82f6"), Some("59 130 246".to_owned()));
807    }
808
809    #[test]
810    fn hex_to_rgb_rejects_non_hex() {
811        assert_eq!(hex_to_rgb_triplet("linear-gradient(...)"), None);
812        assert_eq!(hex_to_rgb_triplet("#fff"), None); // 3-digit not supported yet
813        assert_eq!(hex_to_rgb_triplet("rgb(0,0,0)"), None);
814    }
815
816    #[test]
817    fn mix_toward_white_brightens() {
818        let lighter = mix_with_neutral("#2E7D32", -0.5).unwrap();
819        let original_r = 0x2e;
820        let lighter_r =
821            u8::from_str_radix(lighter.trim_start_matches('#').get(0..2).unwrap(), 16).unwrap();
822        assert!(lighter_r > original_r);
823    }
824
825    #[test]
826    fn mix_toward_black_darkens() {
827        let darker = mix_with_neutral("#2E7D32", 0.5).unwrap();
828        let original_g = 0x7d;
829        let darker_g =
830            u8::from_str_radix(darker.trim_start_matches('#').get(2..4).unwrap(), 16).unwrap();
831        assert!(darker_g < original_g);
832    }
833
834    #[test]
835    fn foreground_picks_white_on_dark() {
836        assert_eq!(wcag_foreground("#1B5E20"), "#ffffff");
837    }
838
839    #[test]
840    fn foreground_picks_black_on_light() {
841        assert_eq!(wcag_foreground("#fafdf6"), "#0a0a0a");
842    }
843
844    /// Build a minimal theme suitable for snapshotting the emitter
845    /// without depending on a `Default` impl on the rustango `Auto<…>`
846    /// columns. Only the columns `emit_css` reads matter.
847    pub(crate) fn fixture_theme() -> Theme {
848        Theme {
849            id: Auto::default(),
850            name: "Fixture".into(),
851            slug: "fixture".into(),
852            is_admin_default: false,
853            is_default: false,
854            default_mode: "light".into(),
855            color_bg: "#ffffff".into(),
856            color_surface: "#fafafa".into(),
857            color_text_primary: "#111111".into(),
858            color_text_secondary: "#444444".into(),
859            color_text_muted: "#777777".into(),
860            color_border: "#dddddd".into(),
861            color_bg_dark: "#0a0a0a".into(),
862            color_surface_dark: "#141414".into(),
863            color_text_primary_dark: "#f5f5f5".into(),
864            color_text_secondary_dark: "#bbbbbb".into(),
865            color_text_muted_dark: "#888888".into(),
866            color_border_dark: "#222222".into(),
867            color_success: "#22a06b".into(),
868            color_warning: "#d97706".into(),
869            color_error: "#ba1a1a".into(),
870            color_info: "#3b82f6".into(),
871            color_link: "#6366f1".into(),
872            color_focus_ring: "#6366f1".into(),
873            font_heading: "system-ui".into(),
874            font_body: "system-ui".into(),
875            font_url: String::new(),
876            radius_sm: "2px".into(),
877            radius_md: "4px".into(),
878            radius_lg: "8px".into(),
879            shadow_sm: "0 1px 2px #0001".into(),
880            shadow_md: "0 4px 12px #0001".into(),
881            shadow_lg: "0 12px 28px #0001".into(),
882            created_at: Auto::default(),
883            updated_at: Auto::default(),
884        }
885    }
886
887    /// Every MD3 token the chrome reads from `cms.css` must be
888    /// covered by `emit_css` so picking a theme actually swings the
889    /// palette. Cross-check the bridge against the full list of
890    /// `--md-sys-color-*` consumers; missing one means switching that
891    /// hue is silently a no-op.
892    #[test]
893    fn emit_css_bridges_md3_namespace() {
894        let css = emit_css(&fixture_theme(), &[]);
895        // Sanity: legacy namespace still present (back-compat).
896        assert!(
897            css.contains("--color-bg: #ffffff"),
898            "legacy --color-bg missing"
899        );
900        assert!(css.contains("--color-link: #6366f1"));
901        // Surface family — picked-theme bg/surface drive every tier.
902        assert!(css.contains("--md-sys-color-surface: #ffffff"));
903        assert!(css.contains("--md-sys-color-surface-container-lowest: #fafafa"));
904        assert!(css.contains("--md-sys-color-surface-container-low:"));
905        assert!(css.contains("--md-sys-color-surface-container:"));
906        assert!(css.contains("--md-sys-color-surface-container-high:"));
907        assert!(css.contains("--md-sys-color-surface-container-highest:"));
908        assert!(css.contains("--md-sys-color-on-surface: #111111"));
909        assert!(css.contains("--md-sys-color-on-surface-variant: #444444"));
910        assert!(css.contains("--md-sys-color-outline: #777777"));
911        assert!(css.contains("--md-sys-color-outline-variant: #dddddd"));
912        // Accent — link drives MD3 primary so theme switch shifts the
913        // pickup color across buttons / sidebar active / focus rings.
914        assert!(css.contains("--md-sys-color-primary: #6366f1"));
915        assert!(css.contains("--md-sys-color-primary-container:"));
916        assert!(css.contains("--md-sys-color-primary-fixed:"));
917        assert!(css.contains("--md-sys-color-on-primary:"));
918        // Semantic family.
919        assert!(css.contains("--md-sys-color-success: #22a06b"));
920        assert!(css.contains("--md-sys-color-on-success:"));
921        assert!(css.contains("--md-sys-color-success-container:"));
922        assert!(css.contains("--md-sys-color-warning: #d97706"));
923        assert!(css.contains("--md-sys-color-error: #ba1a1a"));
924        assert!(css.contains("--md-sys-color-error-container:"));
925    }
926
927    /// The dark + system blocks have to match cms.css's
928    /// specificity (`:root[data-theme="dark"]`, 0,2,0). A bare
929    /// `[data-theme="dark"]` selector loses the cascade against
930    /// cms.css's built-in dark block and the theme switch becomes
931    /// silently invisible in dark mode.
932    #[test]
933    fn emit_css_uses_root_qualified_selectors_for_dark_and_system() {
934        let css = emit_css(&fixture_theme(), &[]);
935        assert!(
936            css.contains(":root[data-theme=\"dark\"] {"),
937            "dark block must be :root-qualified to match cms.css specificity"
938        );
939        // "System" is the ABSENCE of `data-theme` — the admin's no-flash
940        // script removes the attribute — so the OS-dark block keys on
941        // `:root:not([data-theme="light"])`, matching cms.css's own selector.
942        // It used to key on `[data-theme="system"]`, which never matched and
943        // silently dropped the tenant's dark palette in System mode; this
944        // assertion tracked that superseded selector.
945        assert!(
946            css.contains(":root:not([data-theme=\"light\"]) {"),
947            "system block (inside @media) must be :root-qualified and match cms.css's OS-dark selector"
948        );
949        // And no LOSING-specificity bare attribute selectors left over.
950        assert!(
951            !css.contains("\n[data-theme=\"dark\"] {"),
952            "stray bare [data-theme=\"dark\"] would lose cascade"
953        );
954        assert!(
955            !css.contains("[data-theme=\"system\"]"),
956            "`system` is the absence of data-theme, so no selector should name it"
957        );
958    }
959
960    /// Dark surfaces resolve from `_dark` columns so the bridge picks
961    /// up the inverted palette there too.
962    #[test]
963    fn emit_css_dark_block_uses_dark_columns() {
964        let css = emit_css(&fixture_theme(), &[]);
965        // Slice down to the dark block to keep the assertion local.
966        let dark = css
967            .split(":root[data-theme=\"dark\"] {")
968            .nth(1)
969            .unwrap()
970            .split("}\n")
971            .next()
972            .unwrap();
973        assert!(dark.contains("--md-sys-color-surface: #0a0a0a"));
974        assert!(dark.contains("--md-sys-color-surface-container-lowest: #141414"));
975        assert!(dark.contains("--md-sys-color-on-surface: #f5f5f5"));
976    }
977
978    /// Semantic base hues are authored for light surfaces; the dark
979    /// blocks must lighten them or error/success/warning text and
980    /// borders (field validation, block-tree badges) go unreadable
981    /// against dark backgrounds.
982    #[test]
983    fn emit_css_dark_block_lightens_semantic_bases() {
984        let css = emit_css(&fixture_theme(), &[]);
985        let dark = css
986            .split(":root[data-theme=\"dark\"] {")
987            .nth(1)
988            .unwrap()
989            .split("}\n")
990            .next()
991            .unwrap();
992        assert!(
993            !dark.contains("--md-sys-color-error: #ba1a1a"),
994            "dark block must not reuse the light error hue verbatim"
995        );
996        let err_line = dark
997            .lines()
998            .find(|l| l.contains("--md-sys-color-error:"))
999            .expect("dark block emits an error base");
1000        let hex = err_line
1001            .split(':')
1002            .nth(1)
1003            .unwrap()
1004            .trim()
1005            .trim_end_matches(';');
1006        let r = u8::from_str_radix(&hex[1..3], 16).unwrap();
1007        assert!(
1008            r > 0xba,
1009            "dark error base should be lighter than the light hue, got {hex}"
1010        );
1011    }
1012}