1use chrono::{DateTime, Utc};
23use rustango::sql::Auto;
24use rustango::Model;
25use serde::{Deserialize, Serialize};
26
27#[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 #[rustango(max_length = 100)]
54 pub name: String,
55
56 #[rustango(max_length = 64, unique)]
60 pub slug: String,
61
62 pub is_admin_default: bool,
65
66 pub is_default: bool,
69
70 #[rustango(max_length = 16)]
73 pub default_mode: String,
74
75 #[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 #[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 #[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 #[rustango(max_length = 255)]
119 pub font_heading: String,
120 #[rustango(max_length = 255)]
121 pub font_body: String,
122 #[rustango(max_length = 500)]
125 pub font_url: String,
126
127 #[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#[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 #[rustango(max_length = 64)]
174 pub slug: String,
175
176 #[rustango(max_length = 100)]
178 pub name: String,
179
180 #[rustango(max_length = 255)]
183 pub color_value: String,
184
185 #[rustango(max_length = 255)]
188 pub color_value_dark: String,
189
190 pub sort_order: i32,
192}
193
194#[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 out.push_str(":root {\n");
222 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 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 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 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 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 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 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
390struct 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,
411 Dark,
415}
416
417fn 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 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 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 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 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 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
557fn 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 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
591fn mix_or_same(hex: &str, t: f32) -> String {
596 mix_with_neutral(hex, t).unwrap_or_else(|| hex.to_string())
597}
598
599fn 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
619fn 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
643fn 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('&', "&")
655 .replace('"', """)
656 .replace('<', "<")
657 .replace('>', ">")
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 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
695const 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
712pub(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
726fn 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
736fn 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
747fn 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 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); 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 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 #[test]
893 fn emit_css_bridges_md3_namespace() {
894 let css = emit_css(&fixture_theme(), &[]);
895 assert!(
897 css.contains("--color-bg: #ffffff"),
898 "legacy --color-bg missing"
899 );
900 assert!(css.contains("--color-link: #6366f1"));
901 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 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 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 #[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 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 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 #[test]
963 fn emit_css_dark_block_uses_dark_columns() {
964 let css = emit_css(&fixture_theme(), &[]);
965 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 #[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}