1use crate::Color;
47use std::collections::BTreeMap;
48use std::fmt;
49use std::rc::Rc;
50
51#[derive(Clone, Copy, Debug, PartialEq)]
57pub struct Variant<T> {
58 pub light: T,
59 pub dark: T,
60}
61
62impl<T> Variant<T> {
63 pub fn of(light: T, dark: T) -> Self {
64 Self { light, dark }
65 }
66
67 pub fn get(&self, dark: bool) -> &T {
68 if dark {
69 &self.dark
70 } else {
71 &self.light
72 }
73 }
74}
75
76impl<T: Clone> Variant<T> {
77 pub fn both(value: T) -> Self {
78 Self { light: value.clone(), dark: value }
79 }
80}
81
82impl<T: Copy> Variant<T> {
83 pub fn value(&self, dark: bool) -> T {
84 *self.get(dark)
85 }
86
87 pub fn map<U: Copy>(&self, mut f: impl FnMut(&T) -> U) -> Variant<U> {
88 Variant { light: f(&self.light), dark: f(&self.dark) }
89 }
90}
91
92macro_rules! named_tokens {
101 (
102 $(#[$meta:meta])*
103 pub enum $name:ident { $( $(#[$attr:meta])* $variant:ident => $css:literal ),* $(,)? }
104 ) => {
105 $(#[$meta])*
106 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
107 pub enum $name { $( $(#[$attr])* $variant, )* }
108
109 impl $name {
110 pub const ALL: &'static [Self] = &[$(Self::$variant),*];
112
113 pub fn as_str(self) -> &'static str {
115 match self { $(Self::$variant => $css),* }
116 }
117
118 pub fn from_name(text: &str) -> Option<Self> {
120 Self::ALL.iter().copied().find(|token| token.as_str() == text)
121 }
122 }
123 };
124}
125
126named_tokens! {
127 pub enum ColorToken {
129 Accent => "--color-accent",
130 AccentMuted => "--color-accent-muted",
131 OnAccent => "--color-on-accent",
132 Neutral => "--color-neutral",
134 BackgroundSurface => "--color-background-surface",
135 BackgroundBody => "--color-background-body",
136 BackgroundCard => "--color-background-card",
137 BackgroundPopover => "--color-background-popover",
138 BackgroundMuted => "--color-background-muted",
139 BackgroundInverted => "--color-background-inverted",
140 BackgroundErrorInverted => "--color-background-error-inverted",
141 TextPrimary => "--color-text-primary",
142 TextSecondary => "--color-text-secondary",
143 TextDisabled => "--color-text-disabled",
144 TextAccent => "--color-text-accent",
145 TextBlue => "--color-text-blue",
146 TextGreen => "--color-text-green",
147 TextYellow => "--color-text-yellow",
148 TextRed => "--color-text-red",
149 TextInfo => "--color-text-info",
150 TextSuccess => "--color-text-success",
151 TextWarning => "--color-text-warning",
152 TextError => "--color-text-error",
153 IconPrimary => "--color-icon-primary",
154 IconSecondary => "--color-icon-secondary",
155 IconDisabled => "--color-icon-disabled",
156 IconAccent => "--color-icon-accent",
157 IconInfo => "--color-icon-info",
158 IconSuccess => "--color-icon-success",
159 IconWarning => "--color-icon-warning",
160 IconError => "--color-icon-error",
161 Border => "--color-border",
163 BorderEmphasized => "--color-border-emphasized",
165 BorderInfo => "--color-border-info",
166 BorderSuccess => "--color-border-success",
167 BorderWarning => "--color-border-warning",
168 BorderError => "--color-border-error",
169 Info => "--color-info",
170 InfoMuted => "--color-info-muted",
171 OnInfo => "--color-on-info",
172 OnInfoMuted => "--color-on-info-muted",
173 Success => "--color-success",
174 SuccessMuted => "--color-success-muted",
175 OnSuccess => "--color-on-success",
176 OnSuccessMuted => "--color-on-success-muted",
177 Error => "--color-error",
178 ErrorMuted => "--color-error-muted",
179 OnError => "--color-on-error",
180 OnErrorMuted => "--color-on-error-muted",
181 Warning => "--color-warning",
182 WarningMuted => "--color-warning-muted",
183 OnWarning => "--color-on-warning",
184 OnWarningMuted => "--color-on-warning-muted",
185 Overlay => "--color-overlay",
187 OverlayHover => "--color-overlay-hover",
189 OverlayPressed => "--color-overlay-pressed",
191 Shadow => "--color-shadow",
192 Skeleton => "--color-skeleton",
194 Track => "--color-track",
196 TintHover => "--color-tint-hover",
198 OnDark => "--color-on-dark",
199 OnLight => "--color-on-light",
200 FocusOutline => "--focus-outline-color",
202 DataCategoricalBlue => "--color-data-categorical-blue",
203 DataCategoricalBrown => "--color-data-categorical-brown",
204 DataCategoricalCyan => "--color-data-categorical-cyan",
205 DataCategoricalGreen => "--color-data-categorical-green",
206 DataCategoricalIndigo => "--color-data-categorical-indigo",
207 DataCategoricalOrange => "--color-data-categorical-orange",
208 DataCategoricalPink => "--color-data-categorical-pink",
209 DataCategoricalPurple => "--color-data-categorical-purple",
210 DataCategoricalRed => "--color-data-categorical-red",
211 DataCategoricalTeal => "--color-data-categorical-teal",
212 }
213}
214
215named_tokens! {
216 pub enum LengthToken {
218 RadiusNone => "--radius-none",
220 RadiusInner => "--radius-inner",
222 RadiusElement => "--radius-element",
224 RadiusContainer => "--radius-container",
226 RadiusPage => "--radius-page",
228 RadiusChat => "--radius-chat",
230 RadiusFull => "--radius-full",
232 SizeElementSm => "--size-element-sm",
234 SizeElementMd => "--size-element-md",
236 SizeElementLg => "--size-element-lg",
238 BorderWidth => "--border-width",
240 FocusOutlineWidth => "--focus-outline-width",
242 FocusOutlineOffset => "--focus-outline-offset",
244 }
245}
246
247named_tokens! {
248 pub enum SpacingStep {
251 S0 => "--spacing-0",
252 S0_5 => "--spacing-0-5",
253 S1 => "--spacing-1",
254 S1_5 => "--spacing-1-5",
255 S2 => "--spacing-2",
256 S3 => "--spacing-3",
257 S4 => "--spacing-4",
258 S5 => "--spacing-5",
259 S6 => "--spacing-6",
260 S7 => "--spacing-7",
261 S8 => "--spacing-8",
262 S9 => "--spacing-9",
263 S10 => "--spacing-10",
264 S11 => "--spacing-11",
265 S12 => "--spacing-12",
266 }
267}
268
269named_tokens! {
270 pub enum DurationToken {
272 Fast => "--duration-fast",
273 FastMin => "--duration-fast-min",
274 FastMax => "--duration-fast-max",
275 Medium => "--duration-medium",
276 MediumMin => "--duration-medium-min",
277 MediumMax => "--duration-medium-max",
278 Slow => "--duration-slow",
279 SlowMin => "--duration-slow-min",
280 SlowMax => "--duration-slow-max",
281 }
282}
283
284named_tokens! {
285 pub enum FontSizeToken {
287 FourXs => "--font-size-4xs",
288 ThreeXs => "--font-size-3xs",
289 TwoXs => "--font-size-2xs",
290 Xs => "--font-size-xs",
291 Sm => "--font-size-sm",
292 Base => "--font-size-base",
293 Lg => "--font-size-lg",
294 Xl => "--font-size-xl",
295 TwoXl => "--font-size-2xl",
296 ThreeXl => "--font-size-3xl",
297 FourXl => "--font-size-4xl",
298 FiveXl => "--font-size-5xl",
299 }
300}
301
302impl FontSizeToken {
303 fn step(self) -> i32 {
305 match self {
306 Self::FourXs => -5,
307 Self::ThreeXs => -4,
308 Self::TwoXs => -3,
309 Self::Xs => -2,
310 Self::Sm => -1,
311 Self::Base => 0,
312 Self::Lg => 1,
313 Self::Xl => 2,
314 Self::TwoXl => 3,
315 Self::ThreeXl => 4,
316 Self::FourXl => 5,
317 Self::FiveXl => 6,
318 }
319 }
320}
321
322named_tokens! {
323 pub enum FontWeightToken {
325 Normal => "--font-weight-normal",
326 Medium => "--font-weight-medium",
327 Semibold => "--font-weight-semibold",
328 Bold => "--font-weight-bold",
329 }
330}
331
332named_tokens! {
333 pub enum ShadowToken {
335 Low => "--shadow-low",
336 Med => "--shadow-med",
337 High => "--shadow-high",
338 InsetHover => "--shadow-inset-hover",
339 InsetSelected => "--shadow-inset-selected",
340 InsetSuccess => "--shadow-inset-success",
341 InsetWarning => "--shadow-inset-warning",
342 InsetError => "--shadow-inset-error",
343 }
344}
345
346named_tokens! {
347 pub enum EasingToken {
349 Standard => "--ease-standard",
350 Entrance => "--ease-entrance",
351 Move => "--ease-move",
352 Exit => "--ease-exit",
353 }
354}
355
356named_tokens! {
357 pub enum TextRole {
362 DisplayOne => "--text-display-1",
363 DisplayTwo => "--text-display-2",
364 DisplayThree => "--text-display-3",
365 HeadingOne => "--text-heading-1",
366 HeadingTwo => "--text-heading-2",
367 HeadingThree => "--text-heading-3",
368 HeadingFour => "--text-heading-4",
369 HeadingFive => "--text-heading-5",
370 HeadingSix => "--text-heading-6",
371 Large => "--text-large",
372 Body => "--text-body",
373 Label => "--text-label",
374 Supporting => "--text-supporting",
375 Code => "--text-code",
376 }
377}
378
379impl TextRole {
380 pub fn stem(self) -> &'static str {
382 match self {
383 Self::DisplayOne => "display-1",
384 Self::DisplayTwo => "display-2",
385 Self::DisplayThree => "display-3",
386 Self::HeadingOne => "heading-1",
387 Self::HeadingTwo => "heading-2",
388 Self::HeadingThree => "heading-3",
389 Self::HeadingFour => "heading-4",
390 Self::HeadingFive => "heading-5",
391 Self::HeadingSix => "heading-6",
392 Self::Large => "large",
393 Self::Body => "body",
394 Self::Label => "label",
395 Self::Supporting => "supporting",
396 Self::Code => "code",
397 }
398 }
399
400 pub fn size_name(self) -> String {
401 format!("{}-size", self.as_str())
402 }
403
404 pub fn weight_name(self) -> String {
405 format!("{}-weight", self.as_str())
406 }
407
408 pub fn leading_name(self) -> String {
409 format!("{}-leading", self.as_str())
410 }
411}
412
413named_tokens! {
414 pub enum FontFamilyToken {
417 Body => "--font-family-body",
418 Display => "--font-family-display",
419 Mono => "--font-family-mono",
420 }
421}
422
423#[derive(Clone, Copy, Debug, PartialEq, Eq)]
425enum Kind {
426 Color,
427 Number,
429 Shadow,
430 Easing,
431 FontStack,
433}
434
435fn kind_of(name: &str) -> Option<Kind> {
437 if ColorToken::from_name(name).is_some() {
438 return Some(Kind::Color);
439 }
440 if LengthToken::from_name(name).is_some()
441 || SpacingStep::from_name(name).is_some()
442 || DurationToken::from_name(name).is_some()
443 || FontSizeToken::from_name(name).is_some()
444 || FontWeightToken::from_name(name).is_some()
445 {
446 return Some(Kind::Number);
447 }
448 if ShadowToken::from_name(name).is_some() {
449 return Some(Kind::Shadow);
450 }
451 if EasingToken::from_name(name).is_some() {
452 return Some(Kind::Easing);
453 }
454 if name.starts_with("--font-family-") {
455 return Some(Kind::FontStack);
456 }
457 if let Some(stem) = name.strip_prefix("--text-") {
459 if stem.ends_with("-size") || stem.ends_with("-weight") || stem.ends_with("-leading") {
460 return Some(Kind::Number);
461 }
462 }
463 None
464}
465
466#[derive(Clone, Debug, PartialEq)]
472enum Atom {
473 Color(Color),
474 Num(f32),
476 LightDark(Rc<Atom>, Rc<Atom>),
478 Ref {
480 name: String,
481 fallback: Option<Rc<Atom>>,
482 },
483 Text(Rc<str>),
485}
486
487const REM_PX: f32 = 16.0;
489
490fn parse_atom(text: &str) -> Atom {
492 let text = text.trim();
493 if text.is_empty() {
494 return Atom::Text(Rc::from(""));
495 }
496 let lower = text.to_ascii_lowercase();
497 if let Some(inner) = strip_call(&lower, "light-dark") {
498 if let Some((light, dark)) = split_top(inner, ',') {
499 return Atom::LightDark(Rc::new(parse_atom(light)), Rc::new(parse_atom(dark)));
500 }
501 }
502 if let Some(inner) = strip_call(&lower, "var") {
503 let (name, fallback) = match split_top(inner, ',') {
504 Some((name, fallback)) => (name.trim().to_string(), Some(Rc::new(parse_atom(fallback)))),
505 None => (inner.trim().to_string(), None),
506 };
507 return Atom::Ref { name, fallback };
508 }
509 if let Some(color) = parse_color(&lower) {
510 return Atom::Color(color);
511 }
512 if let Some(value) = parse_number(&lower) {
513 return Atom::Num(value);
514 }
515 Atom::Text(Rc::from(text))
516}
517
518fn parse_color(lower: &str) -> Option<Color> {
520 if let Some(digits) = lower.strip_prefix('#') {
521 return parse_hex(digits);
522 }
523 for name in ["rgba", "rgb"] {
524 if let Some(inner) = strip_call(lower, name) {
525 return parse_rgba(inner);
526 }
527 }
528 match lower {
529 "black" => Some(Color::BLACK),
530 "white" => Some(Color::WHITE),
531 "transparent" => Some(Color::TRANSPARENT),
532 _ => None,
533 }
534}
535
536fn parse_hex(digits: &str) -> Option<Color> {
537 let byte = |s: &str| u8::from_str_radix(s, 16).ok();
538 match digits.len() {
539 3 => {
540 let r = byte(&digits[0..1])?;
541 let g = byte(&digits[1..2])?;
542 let b = byte(&digits[2..3])?;
543 Some(Color::from_rgb8(r * 17, g * 17, b * 17))
544 }
545 6 => Some(Color::from_rgb8(byte(&digits[0..2])?, byte(&digits[2..4])?, byte(&digits[4..6])?)),
546 8 => Some(Color::from_rgba8(
548 byte(&digits[0..2])?,
549 byte(&digits[2..4])?,
550 byte(&digits[4..6])?,
551 byte(&digits[6..8])?,
552 )),
553 _ => None,
554 }
555}
556
557fn parse_rgba(inner: &str) -> Option<Color> {
559 let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
560 if parts.len() != 4 {
561 return None;
562 }
563 let r: f32 = parts[0].parse().ok()?;
564 let g: f32 = parts[1].parse().ok()?;
565 let b: f32 = parts[2].parse().ok()?;
566 let a: f32 = parts[3].parse().ok()?;
567 Some(Color::rgba(r / 255.0, g / 255.0, b / 255.0, a))
568}
569
570fn parse_number(lower: &str) -> Option<f32> {
572 if let Some(px) = lower.strip_suffix("px") {
573 return px.trim().parse::<f32>().ok();
574 }
575 if let Some(rem) = lower.strip_suffix("rem") {
576 return rem.trim().parse::<f32>().ok().map(|v| v * REM_PX);
577 }
578 if let Some(ms) = lower.strip_suffix("ms") {
579 return ms.trim().parse::<f32>().ok().map(|v| v / 1000.0);
580 }
581 if let Some(sec) = lower.strip_suffix('s') {
582 return sec.trim().parse::<f32>().ok();
583 }
584 lower.parse::<f32>().ok()
585}
586
587fn strip_call<'a>(lower: &'a str, name: &str) -> Option<&'a str> {
589 let rest = lower.strip_prefix(name)?.trim_start();
590 let rest = rest.strip_prefix('(')?;
591 rest.strip_suffix(')')
592}
593
594fn split_top(text: &str, sep: char) -> Option<(&str, &str)> {
596 let mut depth = 0usize;
597 for (index, ch) in text.char_indices() {
598 match ch {
599 '(' => depth += 1,
600 ')' => depth = depth.saturating_sub(1),
601 c if c == sep && depth == 0 => return Some((&text[..index], &text[index + 1..])),
602 _ => {}
603 }
604 }
605 None
606}
607
608fn split_top_all(text: &str, sep: char) -> Vec<&str> {
610 let mut out = Vec::new();
611 let mut depth = 0usize;
612 let mut start = 0usize;
613 for (index, ch) in text.char_indices() {
614 match ch {
615 '(' => depth += 1,
616 ')' => depth = depth.saturating_sub(1),
617 c if c == sep && depth == 0 => {
618 out.push(text[start..index].trim());
619 start = index + 1;
620 }
621 _ => {}
622 }
623 }
624 out.push(text[start..].trim());
625 out
626}
627
628fn split_top_space(text: &str) -> Vec<&str> {
630 let mut out = Vec::new();
631 let mut depth = 0usize;
632 let mut start: Option<usize> = None;
633 for (index, ch) in text.char_indices() {
634 if ch == '(' {
635 depth += 1;
636 continue;
637 }
638 if ch == ')' {
639 depth = depth.saturating_sub(1);
640 continue;
641 }
642 if depth != 0 {
643 continue;
644 }
645 if ch.is_whitespace() {
646 if let Some(from) = start.take() {
647 out.push(&text[from..index]);
648 }
649 } else if start.is_none() {
650 start = Some(index);
651 }
652 }
653 if let Some(from) = start {
654 out.push(&text[from..]);
655 }
656 out
657}
658
659#[derive(Clone, Copy, Debug, PartialEq)]
665pub struct ShadowLayer {
666 pub inset: bool,
667 pub offset_x: f32,
668 pub offset_y: f32,
669 pub blur: f32,
670 pub spread: f32,
671 pub color: Color,
672}
673
674#[derive(Clone, Debug, Default, PartialEq)]
676pub struct Shadow {
677 pub layers: Vec<ShadowLayer>,
678}
679
680impl Shadow {
681 pub fn first(&self) -> Option<ShadowLayer> {
683 self.layers.first().copied()
684 }
685
686 pub fn ring(&self) -> Option<ShadowLayer> {
688 self.layers.iter().copied().find(|layer| layer.inset && layer.blur == 0.0)
689 }
690
691 pub fn is_empty(&self) -> bool {
692 self.layers.is_empty()
693 }
694}
695
696fn parse_shadow(text: &str, table: &TokenTable, dark: bool) -> Shadow {
698 let mut layers = Vec::new();
699 for part in split_top_all(text, ',') {
700 if part.is_empty() {
701 continue;
702 }
703 layers.push(parse_shadow_layer(part, table, dark));
704 }
705 Shadow { layers }
706}
707
708fn parse_shadow_layer(text: &str, table: &TokenTable, dark: bool) -> ShadowLayer {
709 let mut inset = false;
710 let mut numbers: Vec<f32> = Vec::new();
711 let mut color_source = String::new();
712 for part in split_top_space(text) {
713 if part.eq_ignore_ascii_case("inset") {
714 inset = true;
715 continue;
716 }
717 if let Some(value) = parse_number(&part.to_ascii_lowercase()) {
718 numbers.push(value);
719 continue;
720 }
721 if !color_source.is_empty() {
722 color_source.push(' ');
723 }
724 color_source.push_str(part);
725 }
726 let color = if color_source.is_empty() {
727 Color::TRANSPARENT
728 } else {
729 table.color_from_source(&color_source, dark).unwrap_or(Color::TRANSPARENT)
730 };
731 ShadowLayer {
732 inset,
733 offset_x: numbers.first().copied().unwrap_or(0.0),
734 offset_y: numbers.get(1).copied().unwrap_or(0.0),
735 blur: numbers.get(2).copied().unwrap_or(0.0),
736 spread: numbers.get(3).copied().unwrap_or(0.0),
737 color,
738 }
739}
740
741pub const BASE_TOKENS: &[(&str, &str)] = &[
747 ("--color-accent", "light-dark(#0064E0, #2694FE)"),
749 ("--color-accent-muted", "light-dark(#0082FB33, #0082FB3F)"),
750 ("--color-on-accent", "light-dark(#FFFFFF, #FFFFFF)"),
751 ("--color-neutral", "light-dark(rgba(5, 54, 89, 0.1), rgba(223, 226, 229, 0.2))"),
752 ("--color-background-surface", "light-dark(#FFFFFF, #1F1F22)"),
754 ("--color-background-body", "light-dark(#F1F4F7, #111112)"),
755 ("--color-background-card", "light-dark(#FFFFFF, #1F1F22)"),
756 ("--color-background-popover", "light-dark(#FFFFFF, #28292C)"),
757 ("--color-background-muted", "light-dark(#0536590C, #1111127F)"),
758 ("--color-background-inverted", "light-dark(#0A1317, #FFFFFF)"),
759 ("--color-background-error-inverted", "light-dark(#AA071E, #E3193B)"),
760 ("--color-text-primary", "light-dark(#0A1317, #DFE2E5)"),
762 ("--color-text-secondary", "light-dark(#4E606F, #AAAFB5)"),
763 ("--color-text-disabled", "light-dark(#A4B0BC, #6F747C)"),
764 ("--color-text-accent", "light-dark(#0064E0, #3E9EFB)"),
765 ("--color-text-blue", "light-dark(#042F97, #AFD7FF)"),
766 ("--color-text-green", "light-dark(#09441F, #A5F690)"),
767 ("--color-text-yellow", "light-dark(#753F07, #FBCE03)"),
768 ("--color-text-red", "light-dark(#7B0210, #FFB2B8)"),
769 ("--color-text-info", "var(--color-text-blue)"),
770 ("--color-text-success", "var(--color-text-green)"),
771 ("--color-text-warning", "var(--color-text-yellow)"),
772 ("--color-text-error", "var(--color-text-red)"),
773 ("--color-icon-primary", "light-dark(#0A1317, #DFE2E5)"),
775 ("--color-icon-secondary", "light-dark(#4E606F, #AAAFB5)"),
776 ("--color-icon-disabled", "light-dark(#A4B0BC, #6F747C)"),
777 ("--color-icon-accent", "light-dark(#0064E0, #2694FE)"),
778 ("--color-icon-info", "var(--color-text-info)"),
779 ("--color-icon-success", "var(--color-text-success)"),
780 ("--color-icon-warning", "var(--color-text-warning)"),
781 ("--color-icon-error", "var(--color-text-error)"),
782 ("--color-border", "light-dark(#05365919, #F2F4F619)"),
784 ("--color-border-emphasized", "light-dark(#CCD3DB, #494D53)"),
785 ("--color-border-info", "var(--color-text-info)"),
786 ("--color-border-success", "var(--color-text-success)"),
787 ("--color-border-warning", "var(--color-text-warning)"),
788 ("--color-border-error", "var(--color-text-error)"),
789 ("--color-info", "light-dark(#0064E0, #0064E0)"),
791 ("--color-info-muted", "light-dark(#0082FB33, #0082FB3F)"),
792 ("--color-on-info", "light-dark(#FFFFFF, #FFFFFF)"),
793 ("--color-on-info-muted", "var(--color-text-blue)"),
794 ("--color-success", "light-dark(#0D8626, #0D8626)"),
795 ("--color-success-muted", "light-dark(#0B991F33, #0B991F3F)"),
796 ("--color-on-success", "light-dark(#FFFFFF, #FFFFFF)"),
797 ("--color-on-success-muted", "var(--color-text-green)"),
798 ("--color-error", "light-dark(#E3193B, #F5394F)"),
799 ("--color-error-muted", "light-dark(#E3193B33, #F5394F3F)"),
800 ("--color-on-error", "light-dark(#FFFFFF, #0A1317)"),
802 ("--color-on-error-muted", "var(--color-text-red)"),
803 ("--color-warning", "light-dark(#E9AF08, #F2C00B)"),
804 ("--color-warning-muted", "light-dark(#E2A40033, #E2A4003F)"),
805 ("--color-on-warning", "light-dark(#0A1317, #0A1317)"),
806 ("--color-on-warning-muted", "var(--color-text-yellow)"),
807 ("--color-overlay", "light-dark(#01122866, #11111299)"),
809 ("--color-overlay-hover", "light-dark(#0536590C, #FFFFFF0C)"),
810 ("--color-overlay-pressed", "light-dark(#05365919, #FFFFFF19)"),
811 ("--color-shadow", "light-dark(rgba(5, 54, 89, 0.1), rgba(0, 0, 0, 0.3))"),
812 ("--color-skeleton", "light-dark(#CCD3DB, #5A5E66)"),
813 ("--color-track", "light-dark(#CCD3DB, #5A5E66)"),
814 ("--color-tint-hover", "light-dark(black, white)"),
815 ("--color-on-dark", "light-dark(#FFFFFF, #FFFFFF)"),
816 ("--color-on-light", "light-dark(#000000, #000000)"),
817 ("--color-data-categorical-blue", "light-dark(#0171E3, #0171E3)"),
819 ("--color-data-categorical-brown", "light-dark(#965E03, #965E03)"),
820 ("--color-data-categorical-cyan", "light-dark(#0171A4, #0171A4)"),
821 ("--color-data-categorical-green", "light-dark(#0B991F, #0B991F)"),
822 ("--color-data-categorical-indigo", "light-dark(#6F8AFF, #6F8AFF)"),
823 ("--color-data-categorical-orange", "light-dark(#EB6E00, #EB6E00)"),
824 ("--color-data-categorical-pink", "light-dark(#F351C0, #F351C0)"),
825 ("--color-data-categorical-purple", "light-dark(#6B1EFD, #6B1EFD)"),
826 ("--color-data-categorical-red", "light-dark(#F5394F, #F5394F)"),
827 ("--color-data-categorical-teal", "light-dark(#08A3A3, #08A3A3)"),
828 ("--radius-none", "0px"),
830 ("--radius-inner", "4px"),
831 ("--radius-element", "8px"),
832 ("--radius-container", "12px"),
833 ("--radius-page", "28px"),
834 ("--radius-chat", "28px"),
835 ("--radius-full", "9999px"),
836 ("--size-element-sm", "28px"),
837 ("--size-element-md", "32px"),
838 ("--size-element-lg", "36px"),
839 ("--border-width", "1px"),
840 ("--focus-outline-width", "2px"),
841 ("--focus-outline-offset", "3px"),
842 ("--focus-outline-color", "var(--color-accent)"),
844 (
846 "--shadow-low",
847 "0px 1px 1px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
848 0px 2px 8px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
849 ),
850 (
851 "--shadow-med",
852 "0px 1px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
853 0px 2px 12px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
854 ),
855 (
856 "--shadow-high",
857 "0px 2px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
858 0px 8px 24px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3))",
859 ),
860 ("--shadow-inset-hover", "inset 0px 0px 0px 2px light-dark(rgba(5, 54, 89, 0.15), rgba(223, 226, 229, 0.2))"),
861 ("--shadow-inset-selected", "inset 0px 0px 0px 2px rgba(1, 113, 227, 0.5)"),
862 ("--shadow-inset-success", "inset 0px 0px 0px 2px rgba(38, 167, 86, 0.3)"),
863 ("--shadow-inset-warning", "inset 0px 0px 0px 2px rgba(226, 164, 0, 0.3)"),
864 ("--shadow-inset-error", "inset 0px 0px 0px 2px rgba(227, 25, 59, 0.3)"),
865 ("--spacing-0", "0rem"),
867 ("--spacing-0-5", "0.125rem"),
868 ("--spacing-1", "0.25rem"),
869 ("--spacing-1-5", "0.375rem"),
870 ("--spacing-2", "0.5rem"),
871 ("--spacing-3", "0.75rem"),
872 ("--spacing-4", "1rem"),
873 ("--spacing-5", "1.25rem"),
874 ("--spacing-6", "1.5rem"),
875 ("--spacing-7", "1.75rem"),
876 ("--spacing-8", "2rem"),
877 ("--spacing-9", "2.25rem"),
878 ("--spacing-10", "2.5rem"),
879 ("--spacing-11", "2.75rem"),
880 ("--spacing-12", "3rem"),
881 ("--duration-fast-min", "130ms"),
883 ("--duration-fast", "175ms"),
884 ("--duration-fast-max", "230ms"),
885 ("--duration-medium-min", "310ms"),
886 ("--duration-medium", "410ms"),
887 ("--duration-medium-max", "550ms"),
888 ("--duration-slow-min", "730ms"),
889 ("--duration-slow", "975ms"),
890 ("--duration-slow-max", "1300ms"),
891 ("--ease-standard", "cubic-bezier(0.24, 1, 0.4, 1)"),
892 ("--ease-entrance", "cubic-bezier(0.24, 1, 0.4, 1)"),
893 ("--ease-move", "cubic-bezier(0.24, 1, 0.4, 1)"),
894 ("--ease-exit", "cubic-bezier(0.3, 0, 0.6, 0.6)"),
895 ("--font-size-4xs", "0.375rem"),
897 ("--font-size-3xs", "0.4375rem"),
898 ("--font-size-2xs", "0.5rem"),
899 ("--font-size-xs", "0.625rem"),
900 ("--font-size-sm", "0.75rem"),
901 ("--font-size-base", "0.875rem"),
902 ("--font-size-lg", "1.0625rem"),
903 ("--font-size-xl", "1.25rem"),
904 ("--font-size-2xl", "1.5rem"),
905 ("--font-size-3xl", "1.8125rem"),
906 ("--font-size-4xl", "2.1875rem"),
907 ("--font-size-5xl", "2.625rem"),
908 ("--font-weight-normal", "400"),
909 ("--font-weight-medium", "500"),
910 ("--font-weight-semibold", "600"),
911 ("--font-weight-bold", "700"),
912 ("--text-display-1-size", "var(--font-size-5xl)"),
914 ("--text-display-1-weight", "var(--font-weight-normal)"),
915 ("--text-display-1-leading", "1.2381"),
916 ("--text-display-2-size", "var(--font-size-4xl)"),
917 ("--text-display-2-weight", "var(--font-weight-normal)"),
918 ("--text-display-2-leading", "1.2571"),
919 ("--text-display-3-size", "var(--font-size-3xl)"),
920 ("--text-display-3-weight", "var(--font-weight-normal)"),
921 ("--text-display-3-leading", "1.2414"),
922 ("--text-heading-1-size", "var(--font-size-2xl)"),
923 ("--text-heading-1-weight", "var(--font-weight-semibold)"),
924 ("--text-heading-1-leading", "1.3333"),
925 ("--text-heading-2-size", "var(--font-size-xl)"),
926 ("--text-heading-2-weight", "var(--font-weight-semibold)"),
927 ("--text-heading-2-leading", "1.4"),
928 ("--text-heading-3-size", "var(--font-size-lg)"),
929 ("--text-heading-3-weight", "var(--font-weight-semibold)"),
930 ("--text-heading-3-leading", "1.4118"),
931 ("--text-heading-4-size", "var(--font-size-base)"),
932 ("--text-heading-4-weight", "var(--font-weight-semibold)"),
933 ("--text-heading-4-leading", "1.4286"),
934 ("--text-heading-5-size", "var(--font-size-sm)"),
935 ("--text-heading-5-weight", "var(--font-weight-semibold)"),
936 ("--text-heading-5-leading", "1.6667"),
937 ("--text-heading-6-size", "var(--font-size-xs)"),
938 ("--text-heading-6-weight", "var(--font-weight-semibold)"),
939 ("--text-heading-6-leading", "1.6"),
940 ("--text-large-size", "var(--font-size-lg)"),
941 ("--text-large-weight", "var(--font-weight-semibold)"),
942 ("--text-large-leading", "1.4118"),
943 ("--text-body-size", "var(--font-size-base)"),
944 ("--text-body-weight", "var(--font-weight-normal)"),
945 ("--text-body-leading", "1.4286"),
946 ("--text-label-size", "var(--font-size-base)"),
947 ("--text-label-weight", "var(--font-weight-medium)"),
948 ("--text-label-leading", "1.4286"),
949 ("--text-supporting-size", "var(--font-size-sm)"),
950 ("--text-supporting-weight", "var(--font-weight-normal)"),
951 ("--text-supporting-leading", "1.6667"),
952 ("--font-family-body", "system-ui, 'Segoe UI', Tahoma, Arial, 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif"),
953 ("--font-family-display", "system-ui, 'Segoe UI', Arial, 'Microsoft YaHei UI', sans-serif"),
954 ("--font-family-mono", "Cascadia Code, Consolas, 'SF Mono', Menlo, 'Microsoft YaHei UI', monospace"),
955 ("--text-code-size", "var(--font-size-base)"),
956 ("--text-code-weight", "var(--font-weight-normal)"),
957 ("--text-code-leading", "1.4286"),
958];
959
960#[derive(Clone, Copy, Debug, PartialEq)]
969pub struct Scales {
970 pub radius_base: f32,
972 pub radius_multiplier: f32,
974 pub text_base: f32,
976 pub text_ratio: f32,
978 pub motion_fast_ms: f32,
980 pub motion_medium_ms: f32,
982 pub motion_slow_ms: f32,
984 pub motion_ratio: f32,
986}
987
988impl Default for Scales {
989 fn default() -> Self {
990 Self {
991 radius_base: 4.0,
992 radius_multiplier: 1.0,
993 text_base: 14.0,
994 text_ratio: 1.2,
995 motion_fast_ms: 175.0,
996 motion_medium_ms: 410.0,
997 motion_slow_ms: 975.0,
998 motion_ratio: 0.75,
999 }
1000 }
1001}
1002
1003fn px(value: f32) -> String {
1005 let rounded = value.round();
1006 if (value - rounded).abs() < 0.005 {
1007 format!("{rounded:.0}px")
1008 } else {
1009 format!("{value:.2}px")
1010 }
1011}
1012
1013fn ms10(value: f32) -> f32 {
1015 (value / 10.0).round() * 10.0
1016}
1017
1018impl Scales {
1019 fn generate(&self) -> Vec<(&'static str, String)> {
1024 let mut out = Vec::new();
1025 let unit = self.radius_base * self.radius_multiplier;
1026 for (token, factor) in [
1027 (LengthToken::RadiusInner, 1.0),
1028 (LengthToken::RadiusElement, 2.0),
1029 (LengthToken::RadiusContainer, 3.0),
1030 (LengthToken::RadiusPage, 7.0),
1031 (LengthToken::RadiusChat, 7.0),
1032 ] {
1033 out.push((token.as_str(), px(unit * factor)));
1034 }
1035 for token in FontSizeToken::ALL {
1036 let size = self.text_base * self.text_ratio.powi(token.step());
1037 out.push((token.as_str(), px(size.round())));
1038 }
1039 for (center, name, min_name, max_name) in [
1040 (self.motion_fast_ms, "--duration-fast", "--duration-fast-min", "--duration-fast-max"),
1041 (self.motion_medium_ms, "--duration-medium", "--duration-medium-min", "--duration-medium-max"),
1042 (self.motion_slow_ms, "--duration-slow", "--duration-slow-min", "--duration-slow-max"),
1043 ] {
1044 out.push((name, format!("{center:.0}ms")));
1045 out.push((min_name, format!("{:.0}ms", ms10(center * self.motion_ratio))));
1046 out.push((max_name, format!("{:.0}ms", ms10(center / self.motion_ratio))));
1047 }
1048 out
1049 }
1050}
1051
1052#[derive(Clone, Debug, Default, PartialEq)]
1058pub struct TokenOverrides {
1059 entries: BTreeMap<String, String>,
1060}
1061
1062impl TokenOverrides {
1063 pub fn new() -> Self {
1064 Self::default()
1065 }
1066
1067 pub fn len(&self) -> usize {
1068 self.entries.len()
1069 }
1070
1071 pub fn is_empty(&self) -> bool {
1072 self.entries.is_empty()
1073 }
1074
1075 pub fn set(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
1077 let name = name.trim();
1078 let kind = kind_of(name).ok_or_else(|| TokenError::UnknownName(name.to_string()))?;
1079 let atom = parse_atom(value.trim());
1080 let shaped = match kind {
1081 Kind::Color => matches!(atom, Atom::Color(_) | Atom::Ref { .. } | Atom::LightDark(..)),
1082 Kind::Number => matches!(atom, Atom::Num(_) | Atom::Ref { .. } | Atom::LightDark(..)),
1083 Kind::Shadow | Kind::Easing | Kind::FontStack => true,
1085 };
1086 if !shaped {
1087 return Err(TokenError::BadValue { name: name.to_string(), value: value.to_string() });
1088 }
1089 self.entries.insert(name.to_string(), value.trim().to_string());
1090 Ok(())
1091 }
1092
1093 pub fn get(&self, name: &str) -> Option<&str> {
1094 self.entries.get(name).map(String::as_str)
1095 }
1096
1097 pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
1098 self.entries.iter().map(|(key, value)| (key.as_str(), value.as_str()))
1099 }
1100}
1101
1102#[derive(Clone, Debug, PartialEq, Eq)]
1104pub enum TokenError {
1105 UnknownName(String),
1107 BadValue { name: String, value: String },
1109}
1110
1111impl fmt::Display for TokenError {
1112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113 match self {
1114 Self::UnknownName(name) => write!(f, "未知的主题 token 名: {name}"),
1115 Self::BadValue { name, value } => write!(f, "token {name} 的值无法解析: {value}"),
1116 }
1117 }
1118}
1119
1120impl std::error::Error for TokenError {}
1121
1122#[derive(Clone, Debug, PartialEq)]
1131pub struct ThemeDefinition {
1132 ident: String,
1133 scales: Scales,
1134 overrides: TokenOverrides,
1135}
1136
1137pub fn define_theme() -> ThemeDefinition {
1139 ThemeDefinition { ident: "neutral".to_string(), scales: Scales::default(), overrides: TokenOverrides::new() }
1140}
1141
1142impl ThemeDefinition {
1143 pub fn named(mut self, name: impl Into<String>) -> Self {
1145 self.ident = name.into();
1146 self
1147 }
1148
1149 pub fn name(&self) -> &str {
1150 &self.ident
1151 }
1152
1153 pub fn radius_multiplier(mut self, multiplier: f32) -> Self {
1155 self.scales.radius_multiplier = multiplier.clamp(0.0, 2.0);
1156 self
1157 }
1158
1159 pub fn radius_base(mut self, base: f32) -> Self {
1161 self.scales.radius_base = base.max(0.0);
1162 self
1163 }
1164
1165 pub fn text_scale(mut self, base: f32, ratio: f32) -> Self {
1167 self.scales.text_base = base.max(1.0);
1168 self.scales.text_ratio = ratio.clamp(1.01, 2.0);
1169 self
1170 }
1171
1172 pub fn motion_scale(mut self, fast_ms: f32, medium_ms: f32, slow_ms: f32, ratio: f32) -> Self {
1174 self.scales.motion_fast_ms = fast_ms.max(0.0);
1175 self.scales.motion_medium_ms = medium_ms.max(0.0);
1176 self.scales.motion_slow_ms = slow_ms.max(0.0);
1177 self.scales.motion_ratio = ratio.clamp(0.1, 1.0);
1178 self
1179 }
1180
1181 pub fn scales(&self) -> Scales {
1182 self.scales
1183 }
1184
1185 pub fn token(mut self, name: &str, value: &str) -> Result<Self, TokenError> {
1187 self.overrides.set(name, value)?;
1188 Ok(self)
1189 }
1190
1191 pub fn set_token(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
1193 self.overrides.set(name, value)
1194 }
1195
1196 pub fn set_color(&mut self, token: ColorToken, light: Color, dark: Color) {
1198 let value = format!("light-dark({}, {})", hex_of(light), hex_of(dark));
1199 let _ = self.overrides.set(token.as_str(), &value);
1201 }
1202
1203 pub fn color(mut self, token: ColorToken, light: Color, dark: Color) -> Self {
1205 self.set_color(token, light, dark);
1206 self
1207 }
1208
1209 pub fn tokens(mut self, overrides: TokenOverrides) -> Self {
1210 self.overrides = overrides;
1211 self
1212 }
1213
1214 pub fn overrides(&self) -> &TokenOverrides {
1215 &self.overrides
1216 }
1217
1218 pub fn resolve(&self, dark: bool) -> Tokens {
1220 Tokens::resolve(self, dark)
1221 }
1222}
1223
1224fn hex_of(color: Color) -> String {
1226 let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
1227 let (r, g, b) = (channel(color.r), channel(color.g), channel(color.b));
1228 if color.a >= 0.999 {
1229 format!("#{r:02X}{g:02X}{b:02X}")
1230 } else {
1231 format!("#{r:02X}{g:02X}{b:02X}{:02X}", channel(color.a))
1232 }
1233}
1234
1235struct TokenTable {
1241 sources: BTreeMap<String, String>,
1242}
1243
1244const MAX_REF_DEPTH: u32 = 12;
1246
1247impl TokenTable {
1248 fn build(definition: &ThemeDefinition) -> Self {
1249 let mut sources: BTreeMap<String, String> =
1250 BASE_TOKENS.iter().map(|(name, value)| ((*name).to_string(), (*value).to_string())).collect();
1251 for (name, value) in definition.scales.generate() {
1252 sources.insert(name.to_string(), value);
1253 }
1254 for (name, value) in definition.overrides.iter() {
1255 sources.insert(name.to_string(), value.to_string());
1256 }
1257 Self { sources }
1258 }
1259
1260 fn source(&self, name: &str) -> Option<&str> {
1261 self.sources.get(name).map(String::as_str)
1262 }
1263
1264 fn expand(&self, text: &str, dark: bool, depth: u32) -> Option<Atom> {
1266 self.expand_atom(&parse_atom(text), dark, depth)
1267 }
1268
1269 fn expand_atom(&self, atom: &Atom, dark: bool, depth: u32) -> Option<Atom> {
1271 if depth > MAX_REF_DEPTH {
1272 return None;
1273 }
1274 match atom {
1275 Atom::LightDark(light, dark_value) => {
1276 let chosen = if dark { dark_value } else { light };
1277 self.expand_atom(chosen, dark, depth + 1)
1278 }
1279 Atom::Ref { name, fallback } => match self.source(name) {
1280 Some(source) => self.expand(source, dark, depth + 1),
1281 None => match fallback {
1282 Some(atom) => self.expand_atom(atom, dark, depth + 1),
1283 None => None,
1284 },
1285 },
1286 other => Some(other.clone()),
1287 }
1288 }
1289
1290 fn color(&self, name: &str, dark: bool) -> Option<Color> {
1291 self.color_from_source(self.source(name)?, dark)
1292 }
1293
1294 fn color_from_source(&self, text: &str, dark: bool) -> Option<Color> {
1296 match self.expand(text, dark, 0)? {
1297 Atom::Color(color) => Some(color),
1298 _ => None,
1299 }
1300 }
1301
1302 fn number(&self, name: &str, dark: bool) -> Option<f32> {
1303 match self.expand(self.source(name)?, dark, 0)? {
1304 Atom::Num(value) => Some(value),
1305 _ => None,
1306 }
1307 }
1308
1309 fn easing(&self, name: &str, dark: bool) -> Option<[f32; 4]> {
1310 let Atom::Text(text) = self.expand(self.source(name)?, dark, 0)? else {
1311 return None;
1312 };
1313 let lower = text.to_ascii_lowercase();
1314 let inner = strip_call(&lower, "cubic-bezier")?;
1315 let parts: Vec<f32> = inner.split(',').filter_map(|part| part.trim().parse::<f32>().ok()).collect();
1316 if parts.len() != 4 {
1317 return None;
1318 }
1319 let mut points = [0.0f32; 4];
1320 points.copy_from_slice(&parts);
1321 Some(points)
1322 }
1323}
1324
1325#[derive(Clone, Debug, PartialEq)]
1331pub enum Value {
1332 Color(Color),
1333 Number(f32),
1335 Shadow(Shadow),
1336 Easing([f32; 4]),
1338 Text(Rc<str>),
1339}
1340
1341#[derive(Clone, Copy, Debug, PartialEq)]
1343pub struct TextRoleStyle {
1344 pub size: f32,
1345 pub weight: f32,
1346 pub leading: f32,
1347}
1348
1349#[derive(Clone, Debug, PartialEq)]
1351pub struct Tokens {
1352 ident: Rc<str>,
1353 dark: bool,
1354 scales: Scales,
1355 values: BTreeMap<String, Value>,
1356}
1357
1358impl Tokens {
1359 fn resolve(definition: &ThemeDefinition, dark: bool) -> Self {
1360 let table = TokenTable::build(definition);
1361 let mut values: BTreeMap<String, Value> = BTreeMap::new();
1362 for name in table.sources.keys() {
1363 let value = match kind_of(name) {
1364 Some(Kind::Color) => Value::Color(table.color(name, dark).unwrap_or(Color::TRANSPARENT)),
1365 Some(Kind::Number) => Value::Number(table.number(name, dark).unwrap_or(0.0)),
1366 Some(Kind::Shadow) => Value::Shadow(parse_shadow(table.source(name).unwrap_or_default(), &table, dark)),
1367 Some(Kind::Easing) => match table.easing(name, dark) {
1368 Some(points) => Value::Easing(points),
1369 None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
1370 },
1371 Some(Kind::FontStack) | None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
1372 };
1373 values.insert(name.clone(), value);
1374 }
1375 Self { ident: Rc::from(definition.name()), dark, scales: definition.scales(), values }
1376 }
1377
1378 pub fn name(&self) -> &str {
1380 &self.ident
1381 }
1382
1383 pub fn is_dark(&self) -> bool {
1384 self.dark
1385 }
1386
1387 pub fn scales(&self) -> Scales {
1388 self.scales
1389 }
1390
1391 pub fn value(&self, name: &str) -> Option<&Value> {
1393 self.values.get(name)
1394 }
1395
1396 pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
1397 self.values.iter().map(|(key, value)| (key.as_str(), value))
1398 }
1399
1400 fn number(&self, name: &str, fallback: f32) -> f32 {
1401 match self.value(name) {
1402 Some(Value::Number(value)) => *value,
1403 _ => fallback,
1404 }
1405 }
1406
1407 pub fn font_stack(&self, token: FontFamilyToken) -> &str {
1410 match self.value(token.as_str()) {
1411 Some(Value::Text(text)) => text,
1412 _ => "",
1413 }
1414 }
1415
1416 pub fn color(&self, token: ColorToken) -> Color {
1417 match self.value(token.as_str()) {
1418 Some(Value::Color(color)) => *color,
1419 _ => Color::TRANSPARENT,
1420 }
1421 }
1422
1423 pub fn length(&self, token: LengthToken) -> f32 {
1424 self.number(token.as_str(), 0.0)
1425 }
1426
1427 pub fn spacing(&self, step: SpacingStep) -> f32 {
1428 self.number(step.as_str(), 0.0)
1429 }
1430
1431 pub fn duration(&self, token: DurationToken) -> f32 {
1432 self.number(token.as_str(), 0.0)
1433 }
1434
1435 pub fn font_size(&self, token: FontSizeToken) -> f32 {
1436 self.number(token.as_str(), self.scales.text_base)
1437 }
1438
1439 pub fn font_weight(&self, token: FontWeightToken) -> f32 {
1440 self.number(token.as_str(), 400.0)
1441 }
1442
1443 pub fn shadow(&self, token: ShadowToken) -> Shadow {
1444 match self.value(token.as_str()) {
1445 Some(Value::Shadow(shadow)) => shadow.clone(),
1446 _ => Shadow::default(),
1447 }
1448 }
1449
1450 pub fn easing(&self, token: EasingToken) -> [f32; 4] {
1451 match self.value(token.as_str()) {
1452 Some(Value::Easing(points)) => *points,
1453 _ => [0.24, 1.0, 0.4, 1.0],
1454 }
1455 }
1456
1457 pub fn text_role(&self, role: TextRole) -> TextRoleStyle {
1458 TextRoleStyle {
1459 size: self.number(&role.size_name(), self.font_size(FontSizeToken::Base)),
1460 weight: self.number(&role.weight_name(), 400.0),
1461 leading: self.number(&role.leading_name(), 1.4),
1462 }
1463 }
1464
1465 pub fn border_width(&self) -> f32 {
1467 self.length(LengthToken::BorderWidth)
1468 }
1469
1470 pub fn focus(&self) -> FocusTokens {
1471 FocusTokens {
1472 width: self.length(LengthToken::FocusOutlineWidth),
1473 offset: self.length(LengthToken::FocusOutlineOffset),
1474 color: self.color(ColorToken::FocusOutline),
1475 }
1476 }
1477
1478 pub fn radius(&self) -> RadiusTokens {
1479 RadiusTokens {
1480 none: self.length(LengthToken::RadiusNone),
1481 inner: self.length(LengthToken::RadiusInner),
1482 element: self.length(LengthToken::RadiusElement),
1483 container: self.length(LengthToken::RadiusContainer),
1484 page: self.length(LengthToken::RadiusPage),
1485 chat: self.length(LengthToken::RadiusChat),
1486 full: self.length(LengthToken::RadiusFull),
1487 }
1488 }
1489
1490 pub fn element_size(&self) -> SizeTokens {
1492 SizeTokens {
1493 sm: self.length(LengthToken::SizeElementSm),
1494 md: self.length(LengthToken::SizeElementMd),
1495 lg: self.length(LengthToken::SizeElementLg),
1496 }
1497 }
1498
1499 pub fn hovered(&self, base: Color) -> Color {
1501 overlay(base, self.color(ColorToken::OverlayHover))
1502 }
1503
1504 pub fn pressed(&self, base: Color) -> Color {
1506 overlay(base, self.color(ColorToken::OverlayPressed))
1507 }
1508
1509 pub fn color_rows(&self) -> Vec<(&'static str, Color)> {
1511 ColorToken::ALL.iter().map(|token| (token.as_str(), self.color(*token))).collect()
1512 }
1513}
1514
1515#[derive(Clone, Copy, Debug, PartialEq)]
1517pub struct FocusTokens {
1518 pub width: f32,
1519 pub offset: f32,
1520 pub color: Color,
1521}
1522
1523#[derive(Clone, Copy, Debug, PartialEq)]
1525pub struct RadiusTokens {
1526 pub none: f32,
1527 pub inner: f32,
1528 pub element: f32,
1529 pub container: f32,
1530 pub page: f32,
1531 pub chat: f32,
1532 pub full: f32,
1533}
1534
1535#[derive(Clone, Copy, Debug, PartialEq)]
1537pub struct SizeTokens {
1538 pub sm: f32,
1539 pub md: f32,
1540 pub lg: f32,
1541}
1542
1543pub fn overlay(base: Color, top: Color) -> Color {
1547 if top.a >= 1.0 {
1548 return top;
1549 }
1550 let keep = 1.0 - top.a;
1551 Color {
1552 r: top.r * top.a + base.r * keep,
1553 g: top.g * top.a + base.g * keep,
1554 b: top.b * top.a + base.b * keep,
1555 a: base.a + top.a * (1.0 - base.a),
1556 }
1557}
1558
1559#[cfg(test)]
1564mod tests {
1565 use super::*;
1566
1567 fn luminance(color: Color) -> f32 {
1569 let channel = |v: f32| {
1570 if v <= 0.04045 {
1571 v / 12.92
1572 } else {
1573 ((v + 0.055) / 1.055).powf(2.4)
1574 }
1575 };
1576 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
1577 }
1578
1579 fn contrast(a: Color, b: Color) -> f32 {
1580 let (la, lb) = (luminance(a), luminance(b));
1581 let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
1582 (hi + 0.05) / (lo + 0.05)
1583 }
1584
1585 #[test]
1586 fn parses_color_shapes() {
1587 let table = TokenTable::build(&define_theme());
1588 let cases = [
1589 ("#0064E0", Color::from_rgb8(0x00, 0x64, 0xE0)),
1590 ("#abc", Color::from_rgb8(0xAA, 0xBB, 0xCC)),
1591 ("#0536590C", Color::from_rgba8(0x05, 0x36, 0x59, 0x0C)),
1592 ("rgba(5, 54, 89, 0.1)", Color::rgba(5.0 / 255.0, 54.0 / 255.0, 89.0 / 255.0, 0.1)),
1593 ("black", Color::BLACK),
1594 ("white", Color::WHITE),
1595 ("light-dark(#111111, #EEEEEE)", Color::from_rgb8(0x11, 0x11, 0x11)),
1596 ];
1597 for (text, expect) in cases {
1598 let light = table.color_from_source(text, false).unwrap_or_else(|| panic!("解析失败: {text}"));
1599 assert_eq!(light, expect, "明档 {text}");
1600 }
1601 let dark = table.color_from_source("light-dark(#111111, #EEEEEE)", true).unwrap();
1602 assert_eq!(dark, Color::from_rgb8(0xEE, 0xEE, 0xEE), "暗档取第二边");
1603 }
1604
1605 #[test]
1606 fn font_family_tokens_resolve_css_stacks() {
1607 let tokens = define_theme().resolve(true);
1608 for role in FontFamilyToken::ALL {
1609 let stack = tokens.font_stack(*role);
1610 assert!(!stack.is_empty(), "{} 应有 CSS 字体栈", role.as_str());
1611 assert!(stack.contains("sans-serif") || stack.contains("monospace"), "{stack}");
1612 }
1613 let custom =
1614 define_theme().token("--font-family-body", "'My Font', sans-serif").expect("token override").resolve(false);
1615 assert_eq!(custom.font_stack(FontFamilyToken::Body), "'My Font', sans-serif");
1616 }
1617
1618 #[test]
1619 fn leading_values_are_positive_numbers() {
1620 let tokens = define_theme().resolve(false);
1621 for role in TextRole::ALL {
1622 let style = tokens.text_role(*role);
1623 assert!(style.leading > 0.0 && style.leading.is_finite(), "{role:?} leading={}", style.leading);
1624 }
1625 }
1626
1627 #[test]
1628 fn parses_units() {
1629 assert_eq!(parse_atom("8px"), Atom::Num(8.0));
1630 assert_eq!(parse_atom("1.0625rem"), Atom::Num(17.0));
1631 assert_eq!(parse_atom("175ms"), Atom::Num(0.175));
1632 assert_eq!(parse_atom("1.4286"), Atom::Num(1.4286));
1633 assert_eq!(parse_atom("400"), Atom::Num(400.0));
1634 assert_eq!(parse_atom("#0064E0"), Atom::Color(Color::from_rgb8(0x00, 0x64, 0xE0)));
1635 }
1636
1637 #[test]
1638 fn neutral_defaults_match_astryx() {
1639 let light = define_theme().resolve(false);
1640 let dark = define_theme().resolve(true);
1641 assert_eq!(light.color(ColorToken::Accent), Color::from_rgb8(0x00, 0x64, 0xE0));
1642 assert_eq!(dark.color(ColorToken::Accent), Color::from_rgb8(0x26, 0x94, 0xFE));
1643 assert_eq!(light.color(ColorToken::TextPrimary), Color::from_rgb8(0x0A, 0x13, 0x17));
1644 assert_eq!(dark.color(ColorToken::BackgroundBody), Color::from_rgb8(0x11, 0x11, 0x12));
1645 assert_eq!(light.length(LengthToken::RadiusElement), 8.0);
1646 assert_eq!(light.length(LengthToken::SizeElementMd), 32.0);
1647 assert_eq!(light.length(LengthToken::RadiusFull), 9999.0);
1648 assert_eq!(light.font_size(FontSizeToken::Base), 14.0);
1649 assert_eq!(light.font_size(FontSizeToken::FiveXl), 42.0);
1650 assert_eq!(light.font_size(FontSizeToken::FourXs), 6.0);
1651 assert_eq!(light.spacing(SpacingStep::S4), 16.0);
1652 assert_eq!(light.spacing(SpacingStep::S1_5), 6.0);
1653 assert!((light.duration(DurationToken::Fast) - 0.175).abs() < 1e-6);
1654 assert_eq!(light.font_weight(FontWeightToken::Semibold), 600.0);
1655 assert_eq!(light.text_role(TextRole::HeadingOne).size, 24.0);
1656 assert_eq!(light.text_role(TextRole::HeadingOne).weight, 600.0);
1657 assert_eq!(light.text_role(TextRole::Body).size, 14.0);
1658 assert_eq!(light.text_role(TextRole::Supporting).size, 12.0);
1659 assert_eq!(light.easing(EasingToken::Standard), [0.24, 1.0, 0.4, 1.0]);
1660 assert_eq!(light.easing(EasingToken::Exit), [0.3, 0.0, 0.6, 0.6]);
1661 assert_eq!(light.name(), "neutral");
1662 }
1663
1664 #[test]
1665 fn scale_generation_reproduces_neutral_base() {
1666 let base: BTreeMap<&str, &str> = BASE_TOKENS.iter().copied().collect();
1668 let generated = Scales::default().generate();
1669 assert!(!generated.is_empty());
1670 for (name, value) in &generated {
1671 let literal = base.get(*name).unwrap_or_else(|| panic!("基表缺少 {name}"));
1672 assert_eq!(&parse_atom(value), &parse_atom(literal), "scale 默认值改变了 {name}");
1673 }
1674 let overridden =
1676 define_theme().radius_multiplier(2.0).token("--radius-element", "10px").unwrap().resolve(false);
1677 assert_eq!(overridden.length(LengthToken::RadiusElement), 10.0);
1678 assert_eq!(overridden.length(LengthToken::RadiusContainer), 24.0);
1679 }
1680
1681 #[test]
1682 fn radius_multiplier_scales_named_radii_but_not_none_or_full() {
1683 let tokens = define_theme().radius_multiplier(1.5).resolve(false);
1684 assert_eq!(tokens.length(LengthToken::RadiusInner), 6.0);
1685 assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
1686 assert_eq!(tokens.length(LengthToken::RadiusContainer), 18.0);
1687 assert_eq!(tokens.length(LengthToken::RadiusPage), 42.0);
1688 assert_eq!(tokens.length(LengthToken::RadiusNone), 0.0, "0 不该被放大");
1689 assert_eq!(tokens.length(LengthToken::RadiusFull), 9999.0, "完全圆不该被放大");
1690 assert_eq!(tokens.radius().element, 12.0);
1691 }
1692
1693 #[test]
1694 fn text_and_motion_scales_move_the_whole_ladder() {
1695 let tokens = define_theme().text_scale(16.0, 1.25).resolve(false);
1696 assert_eq!(tokens.font_size(FontSizeToken::Base), 16.0);
1697 assert_eq!(tokens.font_size(FontSizeToken::Lg), 20.0);
1698 assert_eq!(tokens.text_role(TextRole::Body).size, 16.0);
1700 assert_eq!(tokens.text_role(TextRole::HeadingOne).size, 31.0);
1701
1702 let slow = define_theme().motion_scale(200.0, 500.0, 1000.0, 0.8).resolve(false);
1703 assert!((slow.duration(DurationToken::Fast) - 0.2).abs() < 1e-6);
1704 assert!((slow.duration(DurationToken::FastMin) - 0.16).abs() < 1e-6);
1705 assert!((slow.duration(DurationToken::FastMax) - 0.25).abs() < 1e-6);
1706 assert!((slow.duration(DurationToken::Slow) - 1.0).abs() < 1e-6);
1707 }
1708
1709 #[test]
1710 fn overriding_accent_also_moves_the_focus_ring() {
1711 let tokens = define_theme().token("--color-accent", "#7B61FF").unwrap().resolve(false);
1713 assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x7B, 0x61, 0xFF));
1714 assert_eq!(tokens.focus().color, Color::from_rgb8(0x7B, 0x61, 0xFF));
1715 }
1716
1717 #[test]
1718 fn status_colors_follow_the_hue_chain() {
1719 let tokens = define_theme().resolve(true);
1721 assert_eq!(tokens.color(ColorToken::TextError), tokens.color(ColorToken::TextRed));
1722 assert_eq!(tokens.color(ColorToken::IconError), tokens.color(ColorToken::TextError));
1723 assert_eq!(tokens.color(ColorToken::BorderError), tokens.color(ColorToken::TextError));
1724 let tokens = define_theme().token("--color-text-red", "#FF0000").unwrap().resolve(false);
1726 assert_eq!(tokens.color(ColorToken::TextError), Color::from_rgb8(0xFF, 0x00, 0x00));
1727 assert_eq!(tokens.color(ColorToken::BorderError), Color::from_rgb8(0xFF, 0x00, 0x00));
1728 }
1729
1730 #[test]
1731 fn override_beats_base_for_both_modes() {
1732 let def = define_theme().token("--color-background-surface", "light-dark(#111111, #EEEEEE)").unwrap();
1733 assert_eq!(def.resolve(false).color(ColorToken::BackgroundSurface), Color::from_rgb8(0x11, 0x11, 0x11));
1734 assert_eq!(def.resolve(true).color(ColorToken::BackgroundSurface), Color::from_rgb8(0xEE, 0xEE, 0xEE));
1735 }
1736
1737 #[test]
1738 fn color_helper_writes_two_variants() {
1739 let tokens = define_theme()
1740 .color(ColorToken::Accent, Color::from_rgb8(0x10, 0x20, 0x30), Color::from_rgb8(0xF0, 0xE0, 0xD0))
1741 .resolve(false);
1742 assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x10, 0x20, 0x30));
1743 assert_eq!(tokens.color(ColorToken::FocusOutline), Color::from_rgb8(0x10, 0x20, 0x30));
1744 assert_eq!(hex_of(Color::from_rgb8(0x10, 0x20, 0x30)), "#102030");
1745 }
1746
1747 #[test]
1748 fn bad_token_names_and_values_are_rejected() {
1749 assert!(matches!(define_theme().token("--color-nope", "#fff"), Err(TokenError::UnknownName(_))));
1750 assert!(matches!(define_theme().token("--radius-element", "not-a-length"), Err(TokenError::BadValue { .. })));
1751 assert!(matches!(define_theme().token("--color-accent", "8px"), Err(TokenError::BadValue { .. })));
1752 assert!(matches!(define_theme().token("--font-size-base", "#FFFFFF"), Err(TokenError::BadValue { .. })));
1753 }
1754
1755 macro_rules! assert_tokens_present {
1757 ($tokens:expr, $($enum:ident),* $(,)?) => {
1758 $(
1759 for token in $enum::ALL {
1760 assert!(
1761 $tokens.value(token.as_str()).is_some(),
1762 "基表缺少 token {}",
1763 token.as_str()
1764 );
1765 }
1766 )*
1767 };
1768 }
1769
1770 #[test]
1771 fn every_typed_token_has_a_base_value() {
1772 let tokens = define_theme().resolve(false);
1774 assert_tokens_present!(
1775 tokens,
1776 ColorToken,
1777 LengthToken,
1778 SpacingStep,
1779 DurationToken,
1780 FontSizeToken,
1781 FontWeightToken,
1782 ShadowToken,
1783 EasingToken,
1784 );
1785 for role in TextRole::ALL {
1786 for name in [role.size_name(), role.weight_name(), role.leading_name()] {
1787 assert!(tokens.value(&name).is_some(), "基表缺少 {name}");
1788 }
1789 }
1790 }
1791
1792 #[test]
1793 fn every_base_token_name_is_known_to_the_override_layer() {
1794 let mut unknown = Vec::new();
1795 for (name, _) in BASE_TOKENS {
1796 if kind_of(name).is_none() {
1797 unknown.push(*name);
1798 }
1799 }
1800 assert!(unknown.is_empty(), "覆盖层不认识的基表名: {unknown:?}");
1801 }
1802
1803 #[test]
1804 fn shadows_are_multi_layer_with_mode_specific_colors() {
1805 let light = define_theme().resolve(false);
1806 let dark = define_theme().resolve(true);
1807 let low = light.shadow(ShadowToken::Low);
1808 assert_eq!(low.layers.len(), 2);
1809 let first = low.first().unwrap();
1810 assert_eq!((first.offset_x, first.offset_y, first.blur, first.spread), (0.0, 1.0, 1.0, 0.0));
1811 assert!(!first.inset);
1812 assert_eq!(first.color, Color::rgba(0.0, 0.0, 0.0, 0.1));
1813 assert_eq!(dark.shadow(ShadowToken::Low).first().unwrap().color, Color::rgba(0.0, 0.0, 0.0, 0.2));
1814 let ring = light.shadow(ShadowToken::InsetHover).ring().expect("inset 描边环");
1815 assert!(ring.inset && ring.blur == 0.0 && ring.spread == 2.0);
1816 assert!(light.shadow(ShadowToken::Low).ring().is_none());
1817 }
1818
1819 #[test]
1820 fn shadow_can_reference_color_shadow_token() {
1821 let mut overrides = TokenOverrides::new();
1822 overrides.set("--shadow-low", "0px 2px 4px var(--color-shadow)").unwrap();
1823 let tokens = define_theme().tokens(overrides).resolve(true);
1824 let layer = tokens.shadow(ShadowToken::Low).first().unwrap();
1825 assert_eq!(layer.color, tokens.color(ColorToken::Shadow));
1826 assert_eq!(layer.blur, 4.0);
1827 }
1828
1829 #[test]
1830 fn overlay_helpers_composite_alpha_tokens() {
1831 for dark in [false, true] {
1832 let tokens = define_theme().resolve(dark);
1833 let base = tokens.color(ColorToken::BackgroundSurface);
1834 let hover = tokens.hovered(base);
1835 let pressed = tokens.pressed(base);
1836 assert!(hover.a > 0.99, "叠加后仍是不透明底色");
1837 assert_ne!(hover, base, "hover 必须看得见");
1838 assert_ne!(hover, pressed, "hover 与 pressed 不同档");
1839 let strength = |a: Color, b: Color| (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs();
1841 assert!(strength(base, pressed) > strength(base, hover), "dark={dark}");
1842 }
1843 }
1844
1845 #[test]
1846 fn neutral_text_on_surface_meets_aa_contrast() {
1847 for dark in [false, true] {
1848 let tokens = define_theme().resolve(dark);
1849 let on_surface =
1850 contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundSurface));
1851 assert!(on_surface >= 4.5, "正文/表面 对比度 {on_surface:.2} < 4.5 (dark={dark})");
1852 let on_body = contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundBody));
1853 assert!(on_body >= 4.5, "正文/画布 对比度 {on_body:.2} < 4.5 (dark={dark})");
1854 let secondary =
1855 contrast(tokens.color(ColorToken::TextSecondary), tokens.color(ColorToken::BackgroundSurface));
1856 assert!(secondary >= 4.5, "次要文本/表面 对比度 {secondary:.2} < 4.5 (dark={dark})");
1857 }
1858 }
1859
1860 #[test]
1861 fn ref_cycles_and_unknown_refs_fall_back_without_panicking() {
1862 let mut overrides = TokenOverrides::new();
1863 overrides.set("--color-accent", "var(--color-accent)").unwrap();
1864 overrides.set("--color-text-red", "var(--nope)").unwrap();
1865 let tokens = define_theme().tokens(overrides).resolve(false);
1866 assert_eq!(tokens.color(ColorToken::Accent), Color::TRANSPARENT);
1868 assert_eq!(tokens.color(ColorToken::TextError), Color::TRANSPARENT);
1869 let mut overrides = TokenOverrides::new();
1871 overrides.set("--color-accent", "var(--nope, #123456)").unwrap();
1872 let tokens = define_theme().tokens(overrides).resolve(false);
1873 assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x12, 0x34, 0x56));
1874 }
1875}