Skip to main content

mgui_core/theme/
tokens.rs

1//! Design token 层 —— 按 [Astryx](https://astryx.atmeta.com/)(Meta 开源设计系统)的
2//! token 命名与取值定义,让 mgui 的主题可以**逐 token 修改**,而不是一整套换掉。
3//!
4//! 基表取值逐条抓取自 Astryx 站点默认主题(`:root`,即 `Neutral`)编译出的 StyleX CSS,
5//! 变量名与字面量都照抄(`--color-accent: light-dark(#0064E0, #2694FE)`)。
6//!
7//! 三层结构(与 Astryx 一致):
8//!
9//! 1. **基表** [`BASE_TOKENS`]:Astryx `Neutral` 主题的默认值。颜色一律两档,等价于 CSS 的
10//!    `light-dark()`;mgui 没有 CSS 引擎,所以在 `resolve(dark)` 时按档选一边。
11//! 2. **scale 配置** [`Scales`]:Astryx 的 `radius` / `typography.scale` / `motion` 三组生成器
12//!    参数(半径基准与倍率、字号锚点与台阶比、动效节奏)。
13//! 3. **覆盖层** [`TokenOverrides`]:按**变量名**覆盖,值可以是任意 Astryx 字面量
14//!    (`#hex` / `rgba()` / `light-dark(a, b)` / `8px` / `1rem` / `175ms` / `var(--x)`),
15//!    所以将来可以直接吃 Astryx 导出的主题。
16//!
17//! 优先级与 Astryx 相同:**显式覆盖 > scale 生成 > 基表**(按 token 逐条比较)。
18//!
19//! 解析结果 [`Tokens`] 是某个明暗档下的实际取值(带类型),paint 期零解析;拼错变量名或值
20//! 形状不对,在 [`ThemeDefinition::token`] 返回的 [`TokenError`] 上就报出来。`ThemeData`
21//! (组件实际读的那份)由 `Tokens` 推导,见 `ThemeData::from_tokens`。
22//!
23//! ```
24//! use mgui_core::theme::tokens::{define_theme, ColorToken, LengthToken};
25//! // 基于 Neutral:元素圆角 12px、主色换紫色,解析成深色 token 集
26//! let def = define_theme()
27//!     .named("brand")
28//!     .radius_multiplier(1.5)
29//!     .token("--color-accent", "#7B61FF")
30//!     .unwrap();
31//! let tokens = def.resolve(true);
32//! assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
33//! assert_eq!(tokens.color(ColorToken::Accent), mgui_core::Color::from_rgb8(0x7B, 0x61, 0xFF));
34//! // 焦点环引用 --color-accent,所以跟着主色走
35//! assert_eq!(tokens.color(ColorToken::FocusOutline), tokens.color(ColorToken::Accent));
36//! ```
37//!
38//! **未实现的 Astryx 域**(后续按需补齐):`color` palette 生成器(种子色 → 整套明暗色阶)、
39//! `components` 组件级样式覆盖、`adaptations` 媒体条件规则(视口宽度 / pointer 精度 /
40//! 减弱动效)、`--font-family-*`(mgui 字体由 `mgui-text` 的回退链决定)、data-viz 色阶
41//! `--color-data-*`(只收录 Avatar 用到的 categorical 档)、`--text-*-leading`
42//! (值可读,但当前文本布局没有行高概念,组件未消费)。
43
44use crate::Color;
45use std::collections::BTreeMap;
46use std::fmt;
47use std::rc::Rc;
48
49// =================================================================
50// 明暗两档
51// =================================================================
52
53/// 明 / 暗两档取值 —— Astryx `light-dark(明, 暗)` 的对应物。
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct Variant<T> {
56    pub light: T,
57    pub dark: T,
58}
59
60impl<T> Variant<T> {
61    pub fn of(light: T, dark: T) -> Self {
62        Self { light, dark }
63    }
64
65    pub fn get(&self, dark: bool) -> &T {
66        if dark {
67            &self.dark
68        } else {
69            &self.light
70        }
71    }
72}
73
74impl<T: Clone> Variant<T> {
75    pub fn both(value: T) -> Self {
76        Self { light: value.clone(), dark: value }
77    }
78}
79
80impl<T: Copy> Variant<T> {
81    pub fn value(&self, dark: bool) -> T {
82        *self.get(dark)
83    }
84
85    pub fn map<U: Copy>(&self, mut f: impl FnMut(&T) -> U) -> Variant<U> {
86        Variant { light: f(&self.light), dark: f(&self.dark) }
87    }
88}
89
90// =================================================================
91// token 名(Astryx CSS 变量名的强类型镜像)
92// =================================================================
93
94/// 生成一组带 `ALL` / `as_str()` / `from_name()` 的 token 名枚举。
95///
96/// 变体名 = Astryx 变量名的大驼峰形式,`as_str()` 给出变量名原文,`from_name()` 供覆盖层
97/// 按名反查并做拼写校验。
98macro_rules! named_tokens {
99    (
100        $(#[$meta:meta])*
101        pub enum $name:ident { $( $(#[$attr:meta])* $variant:ident => $css:literal ),* $(,)? }
102    ) => {
103        $(#[$meta])*
104        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
105        pub enum $name { $( $(#[$attr])* $variant, )* }
106
107        impl $name {
108            /// 全部 token(按声明顺序)。
109            pub const ALL: &'static [Self] = &[$(Self::$variant),*];
110
111            /// Astryx 变量名原文。
112            pub fn as_str(self) -> &'static str {
113                match self { $(Self::$variant => $css),* }
114            }
115
116            /// 按变量名反查。
117            pub fn from_name(text: &str) -> Option<Self> {
118                Self::ALL.iter().copied().find(|token| token.as_str() == text)
119            }
120        }
121    };
122}
123
124named_tokens! {
125    /// 颜色 token。语义命名与 Astryx 完全一致(`on-*` = 该色之上的前景色)。
126    pub enum ColorToken {
127        Accent => "--color-accent",
128        AccentMuted => "--color-accent-muted",
129        OnAccent => "--color-on-accent",
130        /// 中性提示色(Astryx 用它做低强调描边 / 填充)
131        Neutral => "--color-neutral",
132        BackgroundSurface => "--color-background-surface",
133        BackgroundBody => "--color-background-body",
134        BackgroundCard => "--color-background-card",
135        BackgroundPopover => "--color-background-popover",
136        BackgroundMuted => "--color-background-muted",
137        BackgroundInverted => "--color-background-inverted",
138        BackgroundErrorInverted => "--color-background-error-inverted",
139        TextPrimary => "--color-text-primary",
140        TextSecondary => "--color-text-secondary",
141        TextDisabled => "--color-text-disabled",
142        TextAccent => "--color-text-accent",
143        TextBlue => "--color-text-blue",
144        TextGreen => "--color-text-green",
145        TextYellow => "--color-text-yellow",
146        TextRed => "--color-text-red",
147        TextInfo => "--color-text-info",
148        TextSuccess => "--color-text-success",
149        TextWarning => "--color-text-warning",
150        TextError => "--color-text-error",
151        IconPrimary => "--color-icon-primary",
152        IconSecondary => "--color-icon-secondary",
153        IconDisabled => "--color-icon-disabled",
154        IconAccent => "--color-icon-accent",
155        IconInfo => "--color-icon-info",
156        IconSuccess => "--color-icon-success",
157        IconWarning => "--color-icon-warning",
158        IconError => "--color-icon-error",
159        /// 常规 1px 描边(带 alpha)
160        Border => "--color-border",
161        /// 需要被看清的描边(输入框 / 按钮 / 控件)
162        BorderEmphasized => "--color-border-emphasized",
163        BorderInfo => "--color-border-info",
164        BorderSuccess => "--color-border-success",
165        BorderWarning => "--color-border-warning",
166        BorderError => "--color-border-error",
167        Info => "--color-info",
168        InfoMuted => "--color-info-muted",
169        OnInfo => "--color-on-info",
170        OnInfoMuted => "--color-on-info-muted",
171        Success => "--color-success",
172        SuccessMuted => "--color-success-muted",
173        OnSuccess => "--color-on-success",
174        OnSuccessMuted => "--color-on-success-muted",
175        Error => "--color-error",
176        ErrorMuted => "--color-error-muted",
177        OnError => "--color-on-error",
178        OnErrorMuted => "--color-on-error-muted",
179        Warning => "--color-warning",
180        WarningMuted => "--color-warning-muted",
181        OnWarning => "--color-on-warning",
182        OnWarningMuted => "--color-on-warning-muted",
183        /// 遮罩(Dialog / Drawer 的 barrier)
184        Overlay => "--color-overlay",
185        /// hover 叠加色(带 alpha,盖在容器色上)
186        OverlayHover => "--color-overlay-hover",
187        /// 按下叠加色(带 alpha)
188        OverlayPressed => "--color-overlay-pressed",
189        Shadow => "--color-shadow",
190        /// 骨架屏占位色
191        Skeleton => "--color-skeleton",
192        /// 滑杆 / 开关的未填充轨道
193        Track => "--color-track",
194        /// hover 提色调(浅色主题叠黑、深色主题叠白)
195        TintHover => "--color-tint-hover",
196        OnDark => "--color-on-dark",
197        OnLight => "--color-on-light",
198        /// 焦点环颜色,默认 `var(--color-accent)`
199        FocusOutline => "--focus-outline-color",
200        DataCategoricalBlue => "--color-data-categorical-blue",
201        DataCategoricalBrown => "--color-data-categorical-brown",
202        DataCategoricalCyan => "--color-data-categorical-cyan",
203        DataCategoricalGreen => "--color-data-categorical-green",
204        DataCategoricalIndigo => "--color-data-categorical-indigo",
205        DataCategoricalOrange => "--color-data-categorical-orange",
206        DataCategoricalPink => "--color-data-categorical-pink",
207        DataCategoricalPurple => "--color-data-categorical-purple",
208        DataCategoricalRed => "--color-data-categorical-red",
209        DataCategoricalTeal => "--color-data-categorical-teal",
210    }
211}
212
213named_tokens! {
214    /// 长度类 token:圆角、控件尺寸、边框宽度、焦点环。单位统一解析为 px。
215    pub enum LengthToken {
216        /// 0px —— 不受半径倍率影响
217        RadiusNone => "--radius-none",
218        /// 4px —— 容器内部的小元素
219        RadiusInner => "--radius-inner",
220        /// 8px —— 按钮 / 输入框 / 行
221        RadiusElement => "--radius-element",
222        /// 12px —— 卡片 / 浮层
223        RadiusContainer => "--radius-container",
224        /// 28px —— 页面级容器
225        RadiusPage => "--radius-page",
226        /// 28px —— 气泡
227        RadiusChat => "--radius-chat",
228        /// 9999px —— 完全圆,不受半径倍率影响
229        RadiusFull => "--radius-full",
230        /// 28px —— 紧凑控件高度
231        SizeElementSm => "--size-element-sm",
232        /// 32px —— 默认控件高度
233        SizeElementMd => "--size-element-md",
234        /// 36px —— 触控友好高度
235        SizeElementLg => "--size-element-lg",
236        /// 1px
237        BorderWidth => "--border-width",
238        /// 2px
239        FocusOutlineWidth => "--focus-outline-width",
240        /// 3px
241        FocusOutlineOffset => "--focus-outline-offset",
242    }
243}
244
245named_tokens! {
246    /// 间距档位。Astryx 是 `--spacing-0` … `--spacing-12`(每档 `0.25rem` = 4px),
247    /// 外加 `--spacing-0-5` / `--spacing-1-5` 两个半步。
248    pub enum SpacingStep {
249        S0 => "--spacing-0",
250        S0_5 => "--spacing-0-5",
251        S1 => "--spacing-1",
252        S1_5 => "--spacing-1-5",
253        S2 => "--spacing-2",
254        S3 => "--spacing-3",
255        S4 => "--spacing-4",
256        S5 => "--spacing-5",
257        S6 => "--spacing-6",
258        S7 => "--spacing-7",
259        S8 => "--spacing-8",
260        S9 => "--spacing-9",
261        S10 => "--spacing-10",
262        S11 => "--spacing-11",
263        S12 => "--spacing-12",
264    }
265}
266
267named_tokens! {
268    /// 动效时长(解析后统一为**秒**)。min/max 是同一档的微调区间。
269    pub enum DurationToken {
270        Fast => "--duration-fast",
271        FastMin => "--duration-fast-min",
272        FastMax => "--duration-fast-max",
273        Medium => "--duration-medium",
274        MediumMin => "--duration-medium-min",
275        MediumMax => "--duration-medium-max",
276        Slow => "--duration-slow",
277        SlowMin => "--duration-slow-min",
278        SlowMax => "--duration-slow-max",
279    }
280}
281
282named_tokens! {
283    /// 字号阶梯:以 `--font-size-base`(14px)为锚点、按 1.2 倍生成,单位解析为 px。
284    pub enum FontSizeToken {
285        FourXs => "--font-size-4xs",
286        ThreeXs => "--font-size-3xs",
287        TwoXs => "--font-size-2xs",
288        Xs => "--font-size-xs",
289        Sm => "--font-size-sm",
290        Base => "--font-size-base",
291        Lg => "--font-size-lg",
292        Xl => "--font-size-xl",
293        TwoXl => "--font-size-2xl",
294        ThreeXl => "--font-size-3xl",
295        FourXl => "--font-size-4xl",
296        FiveXl => "--font-size-5xl",
297    }
298}
299
300impl FontSizeToken {
301    /// 相对 `--font-size-base` 的台阶指数(base = 0,往上为正、往下为负)。
302    fn step(self) -> i32 {
303        match self {
304            Self::FourXs => -5,
305            Self::ThreeXs => -4,
306            Self::TwoXs => -3,
307            Self::Xs => -2,
308            Self::Sm => -1,
309            Self::Base => 0,
310            Self::Lg => 1,
311            Self::Xl => 2,
312            Self::TwoXl => 3,
313            Self::ThreeXl => 4,
314            Self::FourXl => 5,
315            Self::FiveXl => 6,
316        }
317    }
318}
319
320named_tokens! {
321    /// 字重(无单位数值)。
322    pub enum FontWeightToken {
323        Normal => "--font-weight-normal",
324        Medium => "--font-weight-medium",
325        Semibold => "--font-weight-semibold",
326        Bold => "--font-weight-bold",
327    }
328}
329
330named_tokens! {
331    /// 阴影 token。`low` / `med` / `high` 是两层外阴影,`inset-*` 是 2px 内描边环。
332    pub enum ShadowToken {
333        Low => "--shadow-low",
334        Med => "--shadow-med",
335        High => "--shadow-high",
336        InsetHover => "--shadow-inset-hover",
337        InsetSelected => "--shadow-inset-selected",
338        InsetSuccess => "--shadow-inset-success",
339        InsetWarning => "--shadow-inset-warning",
340        InsetError => "--shadow-inset-error",
341    }
342}
343
344named_tokens! {
345    /// 缓动曲线(三次贝塞尔控制点)。
346    pub enum EasingToken {
347        Standard => "--ease-standard",
348        Entrance => "--ease-entrance",
349        Move => "--ease-move",
350        Exit => "--ease-exit",
351    }
352}
353
354named_tokens! {
355    /// 文本角色(Astryx `--text-*` 三件套:size / weight / leading)。
356    ///
357    /// 角色的 size / weight 通过 `var()` 引用字号 / 字重阶梯,所以调
358    /// [`Scales::text_base`] 时整套角色跟着变。
359    pub enum TextRole {
360        DisplayOne => "--text-display-1",
361        DisplayTwo => "--text-display-2",
362        DisplayThree => "--text-display-3",
363        HeadingOne => "--text-heading-1",
364        HeadingTwo => "--text-heading-2",
365        HeadingThree => "--text-heading-3",
366        HeadingFour => "--text-heading-4",
367        HeadingFive => "--text-heading-5",
368        HeadingSix => "--text-heading-6",
369        Large => "--text-large",
370        Body => "--text-body",
371        Label => "--text-label",
372        Supporting => "--text-supporting",
373        Code => "--text-code",
374    }
375}
376
377impl TextRole {
378    /// `--text-body` → `body`。
379    pub fn stem(self) -> &'static str {
380        match self {
381            Self::DisplayOne => "display-1",
382            Self::DisplayTwo => "display-2",
383            Self::DisplayThree => "display-3",
384            Self::HeadingOne => "heading-1",
385            Self::HeadingTwo => "heading-2",
386            Self::HeadingThree => "heading-3",
387            Self::HeadingFour => "heading-4",
388            Self::HeadingFive => "heading-5",
389            Self::HeadingSix => "heading-6",
390            Self::Large => "large",
391            Self::Body => "body",
392            Self::Label => "label",
393            Self::Supporting => "supporting",
394            Self::Code => "code",
395        }
396    }
397
398    pub fn size_name(self) -> String {
399        format!("{}-size", self.as_str())
400    }
401
402    pub fn weight_name(self) -> String {
403        format!("{}-weight", self.as_str())
404    }
405
406    pub fn leading_name(self) -> String {
407        format!("{}-leading", self.as_str())
408    }
409}
410
411/// token 的值类型 —— 决定覆盖层接受什么形状的字面量。
412#[derive(Clone, Copy, Debug, PartialEq, Eq)]
413enum Kind {
414    Color,
415    /// 长度 / 时长 / 字号 / 字重 / 行高
416    Number,
417    Shadow,
418    Easing,
419}
420
421/// 变量名 → 值类型。未收录的名字视为未知(覆盖层直接报错)。
422fn kind_of(name: &str) -> Option<Kind> {
423    if ColorToken::from_name(name).is_some() {
424        return Some(Kind::Color);
425    }
426    if LengthToken::from_name(name).is_some()
427        || SpacingStep::from_name(name).is_some()
428        || DurationToken::from_name(name).is_some()
429        || FontSizeToken::from_name(name).is_some()
430        || FontWeightToken::from_name(name).is_some()
431    {
432        return Some(Kind::Number);
433    }
434    if ShadowToken::from_name(name).is_some() {
435        return Some(Kind::Shadow);
436    }
437    if EasingToken::from_name(name).is_some() {
438        return Some(Kind::Easing);
439    }
440    // --text-*-size / -weight / -leading 由 TextRole 拼出来,不在上面的枚举里
441    if let Some(stem) = name.strip_prefix("--text-") {
442        if stem.ends_with("-size") || stem.ends_with("-weight") || stem.ends_with("-leading") {
443            return Some(Kind::Number);
444        }
445    }
446    None
447}
448
449// =================================================================
450// 字面量解析
451// =================================================================
452
453/// 一个 token 字面量的中间表示。
454#[derive(Clone, Debug, PartialEq)]
455enum Atom {
456    Color(Color),
457    /// 长度(px) / 时长(秒) / 无单位数字
458    Num(f32),
459    /// `light-dark(明, 暗)`
460    LightDark(Rc<Atom>, Rc<Atom>),
461    /// `var(--x)` 或 `var(--x, 回退)`
462    Ref {
463        name: String,
464        fallback: Option<Rc<Atom>>,
465    },
466    /// 其余按原文留着(缓动曲线、字体族栈等)
467    Text(Rc<str>),
468}
469
470/// `rem` 的基准。Astryx 的网页基准是 16px;mgui 没有根字号概念,固定按 16px 换算。
471const REM_PX: f32 = 16.0;
472
473/// 解析一个 CSS 风格字面量。单位归一:`px` 原值、`rem` × 16、`ms` ÷ 1000、`s` 原值。
474fn parse_atom(text: &str) -> Atom {
475    let text = text.trim();
476    if text.is_empty() {
477        return Atom::Text(Rc::from(""));
478    }
479    let lower = text.to_ascii_lowercase();
480    if let Some(inner) = strip_call(&lower, "light-dark") {
481        if let Some((light, dark)) = split_top(inner, ',') {
482            return Atom::LightDark(Rc::new(parse_atom(light)), Rc::new(parse_atom(dark)));
483        }
484    }
485    if let Some(inner) = strip_call(&lower, "var") {
486        let (name, fallback) = match split_top(inner, ',') {
487            Some((name, fallback)) => (name.trim().to_string(), Some(Rc::new(parse_atom(fallback)))),
488            None => (inner.trim().to_string(), None),
489        };
490        return Atom::Ref { name, fallback };
491    }
492    if let Some(color) = parse_color(&lower) {
493        return Atom::Color(color);
494    }
495    if let Some(value) = parse_number(&lower) {
496        return Atom::Num(value);
497    }
498    Atom::Text(Rc::from(text))
499}
500
501/// `#RGB` / `#RRGGBB` / `#RRGGBBAA` / `rgb()` / `rgba()` / Astryx 用到的颜色关键字。
502fn parse_color(lower: &str) -> Option<Color> {
503    if let Some(digits) = lower.strip_prefix('#') {
504        return parse_hex(digits);
505    }
506    for name in ["rgba", "rgb"] {
507        if let Some(inner) = strip_call(lower, name) {
508            return parse_rgba(inner);
509        }
510    }
511    match lower {
512        "black" => Some(Color::BLACK),
513        "white" => Some(Color::WHITE),
514        "transparent" => Some(Color::TRANSPARENT),
515        _ => None,
516    }
517}
518
519fn parse_hex(digits: &str) -> Option<Color> {
520    let byte = |s: &str| u8::from_str_radix(s, 16).ok();
521    match digits.len() {
522        3 => {
523            let r = byte(&digits[0..1])?;
524            let g = byte(&digits[1..2])?;
525            let b = byte(&digits[2..3])?;
526            Some(Color::from_rgb8(r * 17, g * 17, b * 17))
527        }
528        6 => Some(Color::from_rgb8(byte(&digits[0..2])?, byte(&digits[2..4])?, byte(&digits[4..6])?)),
529        // Astryx 用 8 位 hex 表示带 alpha 的叠加色:#RRGGBBAA
530        8 => Some(Color::from_rgba8(
531            byte(&digits[0..2])?,
532            byte(&digits[2..4])?,
533            byte(&digits[4..6])?,
534            byte(&digits[6..8])?,
535        )),
536        _ => None,
537    }
538}
539
540/// `rgba(r, g, b, a)`:r/g/b 是 0–255,a 是 0–1
541fn parse_rgba(inner: &str) -> Option<Color> {
542    let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
543    if parts.len() != 4 {
544        return None;
545    }
546    let r: f32 = parts[0].parse().ok()?;
547    let g: f32 = parts[1].parse().ok()?;
548    let b: f32 = parts[2].parse().ok()?;
549    let a: f32 = parts[3].parse().ok()?;
550    Some(Color::rgba(r / 255.0, g / 255.0, b / 255.0, a))
551}
552
553/// `12px` / `0.875rem` / `175ms` / `1.4` / `400`
554fn parse_number(lower: &str) -> Option<f32> {
555    if let Some(px) = lower.strip_suffix("px") {
556        return px.trim().parse::<f32>().ok();
557    }
558    if let Some(rem) = lower.strip_suffix("rem") {
559        return rem.trim().parse::<f32>().ok().map(|v| v * REM_PX);
560    }
561    if let Some(ms) = lower.strip_suffix("ms") {
562        return ms.trim().parse::<f32>().ok().map(|v| v / 1000.0);
563    }
564    if let Some(sec) = lower.strip_suffix('s') {
565        return sec.trim().parse::<f32>().ok();
566    }
567    lower.parse::<f32>().ok()
568}
569
570/// `name(a, b)` → `Some("a, b")`(调用方传小写文本,要求括号配平)
571fn strip_call<'a>(lower: &'a str, name: &str) -> Option<&'a str> {
572    let rest = lower.strip_prefix(name)?.trim_start();
573    let rest = rest.strip_prefix('(')?;
574    rest.strip_suffix(')')
575}
576
577/// 按**顶层**逗号(或其他单字符分隔符)切成两段;括号内的分隔符不算。
578fn split_top(text: &str, sep: char) -> Option<(&str, &str)> {
579    let mut depth = 0usize;
580    for (index, ch) in text.char_indices() {
581        match ch {
582            '(' => depth += 1,
583            ')' => depth = depth.saturating_sub(1),
584            c if c == sep && depth == 0 => return Some((&text[..index], &text[index + 1..])),
585            _ => {}
586        }
587    }
588    None
589}
590
591/// 按顶层逗号切成任意多段(box-shadow 的多层列表)。
592fn split_top_all(text: &str, sep: char) -> Vec<&str> {
593    let mut out = Vec::new();
594    let mut depth = 0usize;
595    let mut start = 0usize;
596    for (index, ch) in text.char_indices() {
597        match ch {
598            '(' => depth += 1,
599            ')' => depth = depth.saturating_sub(1),
600            c if c == sep && depth == 0 => {
601                out.push(text[start..index].trim());
602                start = index + 1;
603            }
604            _ => {}
605        }
606    }
607    out.push(text[start..].trim());
608    out
609}
610
611/// 按顶层空白切分(`0px 1px 1px light-dark(...)` → 4 段)。
612fn split_top_space(text: &str) -> Vec<&str> {
613    let mut out = Vec::new();
614    let mut depth = 0usize;
615    let mut start: Option<usize> = None;
616    for (index, ch) in text.char_indices() {
617        if ch == '(' {
618            depth += 1;
619            continue;
620        }
621        if ch == ')' {
622            depth = depth.saturating_sub(1);
623            continue;
624        }
625        if depth != 0 {
626            continue;
627        }
628        if ch.is_whitespace() {
629            if let Some(from) = start.take() {
630                out.push(&text[from..index]);
631            }
632        } else if start.is_none() {
633            start = Some(index);
634        }
635    }
636    if let Some(from) = start {
637        out.push(&text[from..]);
638    }
639    out
640}
641
642// =================================================================
643// 阴影
644// =================================================================
645
646/// 一层 box-shadow。
647#[derive(Clone, Copy, Debug, PartialEq)]
648pub struct ShadowLayer {
649    pub inset: bool,
650    pub offset_x: f32,
651    pub offset_y: f32,
652    pub blur: f32,
653    pub spread: f32,
654    pub color: Color,
655}
656
657/// 一组阴影(Astryx 的 `--shadow-low/med/high` 是两层,`--shadow-inset-*` 是一层内描边)。
658#[derive(Clone, Debug, Default, PartialEq)]
659pub struct Shadow {
660    pub layers: Vec<ShadowLayer>,
661}
662
663impl Shadow {
664    /// 第一层投影(桌面端绘制最常用的取法)。
665    pub fn first(&self) -> Option<ShadowLayer> {
666        self.layers.first().copied()
667    }
668
669    /// `inset` + 纯 spread 构成的"描边环"(Astryx 用它表达 hover / selected 的内圈)。
670    pub fn ring(&self) -> Option<ShadowLayer> {
671        self.layers.iter().copied().find(|layer| layer.inset && layer.blur == 0.0)
672    }
673
674    pub fn is_empty(&self) -> bool {
675        self.layers.is_empty()
676    }
677}
678
679/// 解析 `0px 1px 1px <color>, 0px 2px 8px <color>` 形式。
680fn parse_shadow(text: &str, table: &TokenTable, dark: bool) -> Shadow {
681    let mut layers = Vec::new();
682    for part in split_top_all(text, ',') {
683        if part.is_empty() {
684            continue;
685        }
686        layers.push(parse_shadow_layer(part, table, dark));
687    }
688    Shadow { layers }
689}
690
691fn parse_shadow_layer(text: &str, table: &TokenTable, dark: bool) -> ShadowLayer {
692    let mut inset = false;
693    let mut numbers: Vec<f32> = Vec::new();
694    let mut color_source = String::new();
695    for part in split_top_space(text) {
696        if part.eq_ignore_ascii_case("inset") {
697            inset = true;
698            continue;
699        }
700        if let Some(value) = parse_number(&part.to_ascii_lowercase()) {
701            numbers.push(value);
702            continue;
703        }
704        if !color_source.is_empty() {
705            color_source.push(' ');
706        }
707        color_source.push_str(part);
708    }
709    let color = if color_source.is_empty() {
710        Color::TRANSPARENT
711    } else {
712        table.color_from_source(&color_source, dark).unwrap_or(Color::TRANSPARENT)
713    };
714    ShadowLayer {
715        inset,
716        offset_x: numbers.first().copied().unwrap_or(0.0),
717        offset_y: numbers.get(1).copied().unwrap_or(0.0),
718        blur: numbers.get(2).copied().unwrap_or(0.0),
719        spread: numbers.get(3).copied().unwrap_or(0.0),
720        color,
721    }
722}
723
724// =================================================================
725// 基表:Astryx `Neutral` 主题默认值
726// =================================================================
727
728/// 与 Astryx 站点 `:root`(`Neutral` 主题)编译产物逐条一致。
729pub const BASE_TOKENS: &[(&str, &str)] = &[
730    // ---- 品牌 / 中性 ----
731    ("--color-accent", "light-dark(#0064E0, #2694FE)"),
732    ("--color-accent-muted", "light-dark(#0082FB33, #0082FB3F)"),
733    ("--color-on-accent", "light-dark(#FFFFFF, #FFFFFF)"),
734    ("--color-neutral", "light-dark(rgba(5, 54, 89, 0.1), rgba(223, 226, 229, 0.2))"),
735    // ---- 背景 ----
736    ("--color-background-surface", "light-dark(#FFFFFF, #1F1F22)"),
737    ("--color-background-body", "light-dark(#F1F4F7, #111112)"),
738    ("--color-background-card", "light-dark(#FFFFFF, #1F1F22)"),
739    ("--color-background-popover", "light-dark(#FFFFFF, #28292C)"),
740    ("--color-background-muted", "light-dark(#0536590C, #1111127F)"),
741    ("--color-background-inverted", "light-dark(#0A1317, #FFFFFF)"),
742    ("--color-background-error-inverted", "light-dark(#AA071E, #E3193B)"),
743    // ---- 文本 ----
744    ("--color-text-primary", "light-dark(#0A1317, #DFE2E5)"),
745    ("--color-text-secondary", "light-dark(#4E606F, #AAAFB5)"),
746    ("--color-text-disabled", "light-dark(#A4B0BC, #6F747C)"),
747    ("--color-text-accent", "light-dark(#0064E0, #3E9EFB)"),
748    ("--color-text-blue", "light-dark(#042F97, #AFD7FF)"),
749    ("--color-text-green", "light-dark(#09441F, #A5F690)"),
750    ("--color-text-yellow", "light-dark(#753F07, #FBCE03)"),
751    ("--color-text-red", "light-dark(#7B0210, #FFB2B8)"),
752    ("--color-text-info", "var(--color-text-blue)"),
753    ("--color-text-success", "var(--color-text-green)"),
754    ("--color-text-warning", "var(--color-text-yellow)"),
755    ("--color-text-error", "var(--color-text-red)"),
756    // ---- 图标 ----
757    ("--color-icon-primary", "light-dark(#0A1317, #DFE2E5)"),
758    ("--color-icon-secondary", "light-dark(#4E606F, #AAAFB5)"),
759    ("--color-icon-disabled", "light-dark(#A4B0BC, #6F747C)"),
760    ("--color-icon-accent", "light-dark(#0064E0, #2694FE)"),
761    ("--color-icon-info", "var(--color-text-info)"),
762    ("--color-icon-success", "var(--color-text-success)"),
763    ("--color-icon-warning", "var(--color-text-warning)"),
764    ("--color-icon-error", "var(--color-text-error)"),
765    // ---- 描边 ----
766    ("--color-border", "light-dark(#05365919, #F2F4F619)"),
767    ("--color-border-emphasized", "light-dark(#CCD3DB, #494D53)"),
768    ("--color-border-info", "var(--color-text-info)"),
769    ("--color-border-success", "var(--color-text-success)"),
770    ("--color-border-warning", "var(--color-text-warning)"),
771    ("--color-border-error", "var(--color-text-error)"),
772    // ---- 状态 ----
773    ("--color-info", "light-dark(#0064E0, #0064E0)"),
774    ("--color-info-muted", "light-dark(#0082FB33, #0082FB3F)"),
775    ("--color-on-info", "light-dark(#FFFFFF, #FFFFFF)"),
776    ("--color-on-info-muted", "var(--color-text-blue)"),
777    ("--color-success", "light-dark(#0D8626, #0D8626)"),
778    ("--color-success-muted", "light-dark(#0B991F33, #0B991F3F)"),
779    ("--color-on-success", "light-dark(#FFFFFF, #FFFFFF)"),
780    ("--color-on-success-muted", "var(--color-text-green)"),
781    ("--color-error", "light-dark(#E3193B, #F5394F)"),
782    ("--color-error-muted", "light-dark(#E3193B33, #F5394F3F)"),
783    // 深色 error 太亮,白字达不到 4.5:1,所以它上面的文字用深色
784    ("--color-on-error", "light-dark(#FFFFFF, #0A1317)"),
785    ("--color-on-error-muted", "var(--color-text-red)"),
786    ("--color-warning", "light-dark(#E9AF08, #F2C00B)"),
787    ("--color-warning-muted", "light-dark(#E2A40033, #E2A4003F)"),
788    ("--color-on-warning", "light-dark(#0A1317, #0A1317)"),
789    ("--color-on-warning-muted", "var(--color-text-yellow)"),
790    // ---- 叠加层 / 阴影色 / 轨道 ----
791    ("--color-overlay", "light-dark(#01122866, #11111299)"),
792    ("--color-overlay-hover", "light-dark(#0536590C, #FFFFFF0C)"),
793    ("--color-overlay-pressed", "light-dark(#05365919, #FFFFFF19)"),
794    ("--color-shadow", "light-dark(rgba(5, 54, 89, 0.1), rgba(0, 0, 0, 0.3))"),
795    ("--color-skeleton", "light-dark(#CCD3DB, #5A5E66)"),
796    ("--color-track", "light-dark(#CCD3DB, #5A5E66)"),
797    ("--color-tint-hover", "light-dark(black, white)"),
798    ("--color-on-dark", "light-dark(#FFFFFF, #FFFFFF)"),
799    ("--color-on-light", "light-dark(#000000, #000000)"),
800    // ---- 分类色(Avatar 轮换池用到) ----
801    ("--color-data-categorical-blue", "light-dark(#0171E3, #0171E3)"),
802    ("--color-data-categorical-brown", "light-dark(#965E03, #965E03)"),
803    ("--color-data-categorical-cyan", "light-dark(#0171A4, #0171A4)"),
804    ("--color-data-categorical-green", "light-dark(#0B991F, #0B991F)"),
805    ("--color-data-categorical-indigo", "light-dark(#6F8AFF, #6F8AFF)"),
806    ("--color-data-categorical-orange", "light-dark(#EB6E00, #EB6E00)"),
807    ("--color-data-categorical-pink", "light-dark(#F351C0, #F351C0)"),
808    ("--color-data-categorical-purple", "light-dark(#6B1EFD, #6B1EFD)"),
809    ("--color-data-categorical-red", "light-dark(#F5394F, #F5394F)"),
810    ("--color-data-categorical-teal", "light-dark(#08A3A3, #08A3A3)"),
811    // ---- 圆角 / 尺寸 / 边框 / 焦点 ----
812    ("--radius-none", "0px"),
813    ("--radius-inner", "4px"),
814    ("--radius-element", "8px"),
815    ("--radius-container", "12px"),
816    ("--radius-page", "28px"),
817    ("--radius-chat", "28px"),
818    ("--radius-full", "9999px"),
819    ("--size-element-sm", "28px"),
820    ("--size-element-md", "32px"),
821    ("--size-element-lg", "36px"),
822    ("--border-width", "1px"),
823    ("--focus-outline-width", "2px"),
824    ("--focus-outline-offset", "3px"),
825    // 焦点环颜色引用主色:覆盖 --color-accent 时它跟着走
826    ("--focus-outline-color", "var(--color-accent)"),
827    // ---- 阴影(Astryx 是两层外阴影;inset-* 是 2px 内描边环) ----
828    (
829        "--shadow-low",
830        "0px 1px 1px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
831         0px 2px 8px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
832    ),
833    (
834        "--shadow-med",
835        "0px 1px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
836         0px 2px 12px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2))",
837    ),
838    (
839        "--shadow-high",
840        "0px 2px 2px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), \
841         0px 8px 24px light-dark(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3))",
842    ),
843    ("--shadow-inset-hover", "inset 0px 0px 0px 2px light-dark(rgba(5, 54, 89, 0.15), rgba(223, 226, 229, 0.2))"),
844    ("--shadow-inset-selected", "inset 0px 0px 0px 2px rgba(1, 113, 227, 0.5)"),
845    ("--shadow-inset-success", "inset 0px 0px 0px 2px rgba(38, 167, 86, 0.3)"),
846    ("--shadow-inset-warning", "inset 0px 0px 0px 2px rgba(226, 164, 0, 0.3)"),
847    ("--shadow-inset-error", "inset 0px 0px 0px 2px rgba(227, 25, 59, 0.3)"),
848    // ---- 间距:0–12 档(每档 0.25rem = 4px),含两个半步 ----
849    ("--spacing-0", "0rem"),
850    ("--spacing-0-5", "0.125rem"),
851    ("--spacing-1", "0.25rem"),
852    ("--spacing-1-5", "0.375rem"),
853    ("--spacing-2", "0.5rem"),
854    ("--spacing-3", "0.75rem"),
855    ("--spacing-4", "1rem"),
856    ("--spacing-5", "1.25rem"),
857    ("--spacing-6", "1.5rem"),
858    ("--spacing-7", "1.75rem"),
859    ("--spacing-8", "2rem"),
860    ("--spacing-9", "2.25rem"),
861    ("--spacing-10", "2.5rem"),
862    ("--spacing-11", "2.75rem"),
863    ("--spacing-12", "3rem"),
864    // ---- 动效 ----
865    ("--duration-fast-min", "130ms"),
866    ("--duration-fast", "175ms"),
867    ("--duration-fast-max", "230ms"),
868    ("--duration-medium-min", "310ms"),
869    ("--duration-medium", "410ms"),
870    ("--duration-medium-max", "550ms"),
871    ("--duration-slow-min", "730ms"),
872    ("--duration-slow", "975ms"),
873    ("--duration-slow-max", "1300ms"),
874    ("--ease-standard", "cubic-bezier(0.24, 1, 0.4, 1)"),
875    ("--ease-entrance", "cubic-bezier(0.24, 1, 0.4, 1)"),
876    ("--ease-move", "cubic-bezier(0.24, 1, 0.4, 1)"),
877    ("--ease-exit", "cubic-bezier(0.3, 0, 0.6, 0.6)"),
878    // ---- 字号(1.2 台阶,锚点 14px)与字重 ----
879    ("--font-size-4xs", "0.375rem"),
880    ("--font-size-3xs", "0.4375rem"),
881    ("--font-size-2xs", "0.5rem"),
882    ("--font-size-xs", "0.625rem"),
883    ("--font-size-sm", "0.75rem"),
884    ("--font-size-base", "0.875rem"),
885    ("--font-size-lg", "1.0625rem"),
886    ("--font-size-xl", "1.25rem"),
887    ("--font-size-2xl", "1.5rem"),
888    ("--font-size-3xl", "1.8125rem"),
889    ("--font-size-4xl", "2.1875rem"),
890    ("--font-size-5xl", "2.625rem"),
891    ("--font-weight-normal", "400"),
892    ("--font-weight-medium", "500"),
893    ("--font-weight-semibold", "600"),
894    ("--font-weight-bold", "700"),
895    // ---- 文本角色:引用阶梯,所以调 base / ratio 时整套角色跟着变 ----
896    ("--text-display-1-size", "var(--font-size-5xl)"),
897    ("--text-display-1-weight", "var(--font-weight-normal)"),
898    ("--text-display-1-leading", "1.2381"),
899    ("--text-display-2-size", "var(--font-size-4xl)"),
900    ("--text-display-2-weight", "var(--font-weight-normal)"),
901    ("--text-display-2-leading", "1.2571"),
902    ("--text-display-3-size", "var(--font-size-3xl)"),
903    ("--text-display-3-weight", "var(--font-weight-normal)"),
904    ("--text-display-3-leading", "1.2414"),
905    ("--text-heading-1-size", "var(--font-size-2xl)"),
906    ("--text-heading-1-weight", "var(--font-weight-semibold)"),
907    ("--text-heading-1-leading", "1.3333"),
908    ("--text-heading-2-size", "var(--font-size-xl)"),
909    ("--text-heading-2-weight", "var(--font-weight-semibold)"),
910    ("--text-heading-2-leading", "1.4"),
911    ("--text-heading-3-size", "var(--font-size-lg)"),
912    ("--text-heading-3-weight", "var(--font-weight-semibold)"),
913    ("--text-heading-3-leading", "1.4118"),
914    ("--text-heading-4-size", "var(--font-size-base)"),
915    ("--text-heading-4-weight", "var(--font-weight-semibold)"),
916    ("--text-heading-4-leading", "1.4286"),
917    ("--text-heading-5-size", "var(--font-size-sm)"),
918    ("--text-heading-5-weight", "var(--font-weight-semibold)"),
919    ("--text-heading-5-leading", "1.6667"),
920    ("--text-heading-6-size", "var(--font-size-xs)"),
921    ("--text-heading-6-weight", "var(--font-weight-semibold)"),
922    ("--text-heading-6-leading", "1.6"),
923    ("--text-large-size", "var(--font-size-lg)"),
924    ("--text-large-weight", "var(--font-weight-semibold)"),
925    ("--text-large-leading", "1.4118"),
926    ("--text-body-size", "var(--font-size-base)"),
927    ("--text-body-weight", "var(--font-weight-normal)"),
928    ("--text-body-leading", "1.4286"),
929    ("--text-label-size", "var(--font-size-base)"),
930    ("--text-label-weight", "var(--font-weight-medium)"),
931    ("--text-label-leading", "1.4286"),
932    ("--text-supporting-size", "var(--font-size-sm)"),
933    ("--text-supporting-weight", "var(--font-weight-normal)"),
934    ("--text-supporting-leading", "1.6667"),
935    ("--text-code-size", "var(--font-size-base)"),
936    ("--text-code-weight", "var(--font-weight-normal)"),
937    ("--text-code-leading", "1.4286"),
938];
939
940// =================================================================
941// scale 配置(Astryx 的 radius / typography.scale / motion 生成器)
942// =================================================================
943
944/// 三组 scale 参数,默认值 = Astryx `Neutral`。
945///
946/// 用默认值生成的 token 与 [`BASE_TOKENS`] 逐条等值(有测试兜住),所以这里只做"按参数
947/// 重新生成",不引入第二套事实。
948#[derive(Clone, Copy, Debug, PartialEq)]
949pub struct Scales {
950    /// `radius.base`:半径基准(px,Astryx = 4)
951    pub radius_base: f32,
952    /// `radius.multiplier`:0–2,1 = Astryx 默认
953    pub radius_multiplier: f32,
954    /// `typography.scale.base`:字号锚点(px)
955    pub text_base: f32,
956    /// `typography.scale.ratio`:台阶比(Astryx = 1.2)
957    pub text_ratio: f32,
958    /// `motion.fast`(ms)
959    pub motion_fast_ms: f32,
960    /// `motion.medium`(ms)
961    pub motion_medium_ms: f32,
962    /// `motion.slow`(ms)
963    pub motion_slow_ms: f32,
964    /// `motion.ratio`:min/max 相对中心的收缩比(Astryx = 0.75)
965    pub motion_ratio: f32,
966}
967
968impl Default for Scales {
969    fn default() -> Self {
970        Self {
971            radius_base: 4.0,
972            radius_multiplier: 1.0,
973            text_base: 14.0,
974            text_ratio: 1.2,
975            motion_fast_ms: 175.0,
976            motion_medium_ms: 410.0,
977            motion_slow_ms: 975.0,
978            motion_ratio: 0.75,
979        }
980    }
981}
982
983/// `12px` 形式的长度字符串(整数值不留小数点,避免与基表字面量无谓漂移)。
984fn px(value: f32) -> String {
985    let rounded = value.round();
986    if (value - rounded).abs() < 0.005 {
987        format!("{rounded:.0}px")
988    } else {
989        format!("{value:.2}px")
990    }
991}
992
993/// duration 的 min/max 就近取到 10ms 整数倍(Astryx 的 duration 表都是整十)。
994fn ms10(value: f32) -> f32 {
995    (value / 10.0).round() * 10.0
996}
997
998impl Scales {
999    /// 需要按参数重算的 token 字面量。
1000    ///
1001    /// 半径只生成 `inner` / `element` / `container` / `page` / `chat`(Astryx 同);
1002    /// `none` 恒为 0、`full` 恒为 9999px,倍率不该动它们。
1003    fn generate(&self) -> Vec<(&'static str, String)> {
1004        let mut out = Vec::new();
1005        let unit = self.radius_base * self.radius_multiplier;
1006        for (token, factor) in [
1007            (LengthToken::RadiusInner, 1.0),
1008            (LengthToken::RadiusElement, 2.0),
1009            (LengthToken::RadiusContainer, 3.0),
1010            (LengthToken::RadiusPage, 7.0),
1011            (LengthToken::RadiusChat, 7.0),
1012        ] {
1013            out.push((token.as_str(), px(unit * factor)));
1014        }
1015        for token in FontSizeToken::ALL {
1016            let size = self.text_base * self.text_ratio.powi(token.step());
1017            out.push((token.as_str(), px(size.round())));
1018        }
1019        for (center, name, min_name, max_name) in [
1020            (self.motion_fast_ms, "--duration-fast", "--duration-fast-min", "--duration-fast-max"),
1021            (self.motion_medium_ms, "--duration-medium", "--duration-medium-min", "--duration-medium-max"),
1022            (self.motion_slow_ms, "--duration-slow", "--duration-slow-min", "--duration-slow-max"),
1023        ] {
1024            out.push((name, format!("{center:.0}ms")));
1025            out.push((min_name, format!("{:.0}ms", ms10(center * self.motion_ratio))));
1026            out.push((max_name, format!("{:.0}ms", ms10(center / self.motion_ratio))));
1027        }
1028        out
1029    }
1030}
1031
1032// =================================================================
1033// 覆盖层
1034// =================================================================
1035
1036/// 按 Astryx 变量名记录的 token 覆盖。
1037#[derive(Clone, Debug, Default, PartialEq)]
1038pub struct TokenOverrides {
1039    entries: BTreeMap<String, String>,
1040}
1041
1042impl TokenOverrides {
1043    pub fn new() -> Self {
1044        Self::default()
1045    }
1046
1047    pub fn len(&self) -> usize {
1048        self.entries.len()
1049    }
1050
1051    pub fn is_empty(&self) -> bool {
1052        self.entries.is_empty()
1053    }
1054
1055    /// 记录一条覆盖;值先过一遍形状校验,写错立刻报错(而不是到 paint 期才发现)。
1056    pub fn set(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
1057        let name = name.trim();
1058        let kind = kind_of(name).ok_or_else(|| TokenError::UnknownName(name.to_string()))?;
1059        let atom = parse_atom(value.trim());
1060        let shaped = match kind {
1061            Kind::Color => matches!(atom, Atom::Color(_) | Atom::Ref { .. } | Atom::LightDark(..)),
1062            Kind::Number => matches!(atom, Atom::Num(_) | Atom::Ref { .. } | Atom::LightDark(..)),
1063            // 阴影与缓动按原文保留,解析失败只会在 resolve 时退化成"无阴影"
1064            Kind::Shadow | Kind::Easing => true,
1065        };
1066        if !shaped {
1067            return Err(TokenError::BadValue { name: name.to_string(), value: value.to_string() });
1068        }
1069        self.entries.insert(name.to_string(), value.trim().to_string());
1070        Ok(())
1071    }
1072
1073    pub fn get(&self, name: &str) -> Option<&str> {
1074        self.entries.get(name).map(String::as_str)
1075    }
1076
1077    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
1078        self.entries.iter().map(|(key, value)| (key.as_str(), value.as_str()))
1079    }
1080}
1081
1082/// token 覆盖的错误。
1083#[derive(Clone, Debug, PartialEq, Eq)]
1084pub enum TokenError {
1085    /// 不认识的变量名(mgui 实现的是 Astryx 核心 token 集,见模块文档)
1086    UnknownName(String),
1087    /// 值的形状与该 token 的类型不符
1088    BadValue { name: String, value: String },
1089}
1090
1091impl fmt::Display for TokenError {
1092    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1093        match self {
1094            Self::UnknownName(name) => write!(f, "未知的主题 token 名: {name}"),
1095            Self::BadValue { name, value } => write!(f, "token {name} 的值无法解析: {value}"),
1096        }
1097    }
1098}
1099
1100impl std::error::Error for TokenError {}
1101
1102// =================================================================
1103// 主题定义(Astryx `defineTheme` 的对应物)
1104// =================================================================
1105
1106/// 一份主题定义:基表 + scale + 覆盖。
1107///
1108/// 只描述"改了什么",不预先算结果 —— [`ThemeDefinition::resolve`] 才是实际取值,
1109/// 所以一份定义可以同时服务明暗两档。
1110#[derive(Clone, Debug, PartialEq)]
1111pub struct ThemeDefinition {
1112    ident: String,
1113    scales: Scales,
1114    overrides: TokenOverrides,
1115}
1116
1117/// 以 Astryx `Neutral` 为基底开一份主题定义。
1118pub fn define_theme() -> ThemeDefinition {
1119    ThemeDefinition { ident: "neutral".to_string(), scales: Scales::default(), overrides: TokenOverrides::new() }
1120}
1121
1122impl ThemeDefinition {
1123    /// 主题名(Astryx `defineTheme({ name })`)。
1124    pub fn named(mut self, name: impl Into<String>) -> Self {
1125        self.ident = name.into();
1126        self
1127    }
1128
1129    pub fn name(&self) -> &str {
1130        &self.ident
1131    }
1132
1133    /// 半径倍率(Astryx `radius.multiplier`,0–2)。`--radius-none` / `--radius-full` 不受影响。
1134    pub fn radius_multiplier(mut self, multiplier: f32) -> Self {
1135        self.scales.radius_multiplier = multiplier.clamp(0.0, 2.0);
1136        self
1137    }
1138
1139    /// 半径基准(Astryx `radius.base`,px)。
1140    pub fn radius_base(mut self, base: f32) -> Self {
1141        self.scales.radius_base = base.max(0.0);
1142        self
1143    }
1144
1145    /// 字号锚点 + 台阶比(Astryx `typography.scale`)。
1146    pub fn text_scale(mut self, base: f32, ratio: f32) -> Self {
1147        self.scales.text_base = base.max(1.0);
1148        self.scales.text_ratio = ratio.clamp(1.01, 2.0);
1149        self
1150    }
1151
1152    /// 动效节奏(Astryx `motion`;单位 ms,min/max 按 `ratio` 生成)。
1153    pub fn motion_scale(mut self, fast_ms: f32, medium_ms: f32, slow_ms: f32, ratio: f32) -> Self {
1154        self.scales.motion_fast_ms = fast_ms.max(0.0);
1155        self.scales.motion_medium_ms = medium_ms.max(0.0);
1156        self.scales.motion_slow_ms = slow_ms.max(0.0);
1157        self.scales.motion_ratio = ratio.clamp(0.1, 1.0);
1158        self
1159    }
1160
1161    pub fn scales(&self) -> Scales {
1162        self.scales
1163    }
1164
1165    /// 覆盖单个 token(Astryx 变量名 + 字面量)。
1166    pub fn token(mut self, name: &str, value: &str) -> Result<Self, TokenError> {
1167        self.overrides.set(name, value)?;
1168        Ok(self)
1169    }
1170
1171    /// [`ThemeDefinition::token`] 的 `&mut self` 版本 —— 循环里构造主题时不用来回搬 `self`。
1172    pub fn set_token(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
1173        self.overrides.set(name, value)
1174    }
1175
1176    /// [`ThemeDefinition::color`] 的 `&mut self` 版本。
1177    pub fn set_color(&mut self, token: ColorToken, light: Color, dark: Color) {
1178        let value = format!("light-dark({}, {})", hex_of(light), hex_of(dark));
1179        // 值由本方法拼装,形状必然合法
1180        let _ = self.overrides.set(token.as_str(), &value);
1181    }
1182
1183    /// 覆盖 color token 的便捷写法:明暗两档分别给 `Color`。
1184    pub fn color(mut self, token: ColorToken, light: Color, dark: Color) -> Self {
1185        self.set_color(token, light, dark);
1186        self
1187    }
1188
1189    pub fn tokens(mut self, overrides: TokenOverrides) -> Self {
1190        self.overrides = overrides;
1191        self
1192    }
1193
1194    pub fn overrides(&self) -> &TokenOverrides {
1195        &self.overrides
1196    }
1197
1198    /// 解析成某个明暗档下的实际 token 取值。
1199    pub fn resolve(&self, dark: bool) -> Tokens {
1200        Tokens::resolve(self, dark)
1201    }
1202}
1203
1204/// `Color` → Astryx 颜色字面量(`#RRGGBB`,带 alpha 时写 8 位)。
1205fn hex_of(color: Color) -> String {
1206    let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
1207    let (r, g, b) = (channel(color.r), channel(color.g), channel(color.b));
1208    if color.a >= 0.999 {
1209        format!("#{r:02X}{g:02X}{b:02X}")
1210    } else {
1211        format!("#{r:02X}{g:02X}{b:02X}{:02X}", channel(color.a))
1212    }
1213}
1214
1215// =================================================================
1216// 解析
1217// =================================================================
1218
1219/// 字面量表(变量名 → 原文):基表已被 scale 与覆盖改写过。
1220struct TokenTable {
1221    sources: BTreeMap<String, String>,
1222}
1223
1224/// `var()` 展开深度上限,用来兜住成环引用。
1225const MAX_REF_DEPTH: u32 = 12;
1226
1227impl TokenTable {
1228    fn build(definition: &ThemeDefinition) -> Self {
1229        let mut sources: BTreeMap<String, String> =
1230            BASE_TOKENS.iter().map(|(name, value)| ((*name).to_string(), (*value).to_string())).collect();
1231        for (name, value) in definition.scales.generate() {
1232            sources.insert(name.to_string(), value);
1233        }
1234        for (name, value) in definition.overrides.iter() {
1235            sources.insert(name.to_string(), value.to_string());
1236        }
1237        Self { sources }
1238    }
1239
1240    fn source(&self, name: &str) -> Option<&str> {
1241        self.sources.get(name).map(String::as_str)
1242    }
1243
1244    /// 取字面量并展开成单值。
1245    fn expand(&self, text: &str, dark: bool, depth: u32) -> Option<Atom> {
1246        self.expand_atom(&parse_atom(text), dark, depth)
1247    }
1248
1249    /// 按明暗档选一边、按 `var()` 追引用;成环或断链返回 `None`。
1250    fn expand_atom(&self, atom: &Atom, dark: bool, depth: u32) -> Option<Atom> {
1251        if depth > MAX_REF_DEPTH {
1252            return None;
1253        }
1254        match atom {
1255            Atom::LightDark(light, dark_value) => {
1256                let chosen = if dark { dark_value } else { light };
1257                self.expand_atom(chosen, dark, depth + 1)
1258            }
1259            Atom::Ref { name, fallback } => match self.source(name) {
1260                Some(source) => self.expand(source, dark, depth + 1),
1261                None => match fallback {
1262                    Some(atom) => self.expand_atom(atom, dark, depth + 1),
1263                    None => None,
1264                },
1265            },
1266            other => Some(other.clone()),
1267        }
1268    }
1269
1270    fn color(&self, name: &str, dark: bool) -> Option<Color> {
1271        self.color_from_source(self.source(name)?, dark)
1272    }
1273
1274    /// 阴影里的颜色段可能是 `light-dark(...)` / `var(--color-shadow)` / 直接 hex。
1275    fn color_from_source(&self, text: &str, dark: bool) -> Option<Color> {
1276        match self.expand(text, dark, 0)? {
1277            Atom::Color(color) => Some(color),
1278            _ => None,
1279        }
1280    }
1281
1282    fn number(&self, name: &str, dark: bool) -> Option<f32> {
1283        match self.expand(self.source(name)?, dark, 0)? {
1284            Atom::Num(value) => Some(value),
1285            _ => None,
1286        }
1287    }
1288
1289    fn easing(&self, name: &str, dark: bool) -> Option<[f32; 4]> {
1290        let Atom::Text(text) = self.expand(self.source(name)?, dark, 0)? else {
1291            return None;
1292        };
1293        let lower = text.to_ascii_lowercase();
1294        let inner = strip_call(&lower, "cubic-bezier")?;
1295        let parts: Vec<f32> = inner.split(',').filter_map(|part| part.trim().parse::<f32>().ok()).collect();
1296        if parts.len() != 4 {
1297            return None;
1298        }
1299        let mut points = [0.0f32; 4];
1300        points.copy_from_slice(&parts);
1301        Some(points)
1302    }
1303}
1304
1305// =================================================================
1306// 解析结果
1307// =================================================================
1308
1309/// 一个 token 在某个明暗档下的实际取值。
1310#[derive(Clone, Debug, PartialEq)]
1311pub enum Value {
1312    Color(Color),
1313    /// 长度(px) / 时长(秒) / 字号(px) / 字重与行高(无单位)
1314    Number(f32),
1315    Shadow(Shadow),
1316    /// 三次贝塞尔控制点
1317    Easing([f32; 4]),
1318    Text(Rc<str>),
1319}
1320
1321/// 文本角色解析结果。
1322#[derive(Clone, Copy, Debug, PartialEq)]
1323pub struct TextRoleStyle {
1324    pub size: f32,
1325    pub weight: f32,
1326    pub leading: f32,
1327}
1328
1329/// 一份主题在某一明暗档下的全部实际取值。
1330#[derive(Clone, Debug, PartialEq)]
1331pub struct Tokens {
1332    ident: Rc<str>,
1333    dark: bool,
1334    scales: Scales,
1335    values: BTreeMap<String, Value>,
1336}
1337
1338impl Tokens {
1339    fn resolve(definition: &ThemeDefinition, dark: bool) -> Self {
1340        let table = TokenTable::build(definition);
1341        let mut values: BTreeMap<String, Value> = BTreeMap::new();
1342        for name in table.sources.keys() {
1343            let value = match kind_of(name) {
1344                Some(Kind::Color) => Value::Color(table.color(name, dark).unwrap_or(Color::TRANSPARENT)),
1345                Some(Kind::Number) => Value::Number(table.number(name, dark).unwrap_or(0.0)),
1346                Some(Kind::Shadow) => Value::Shadow(parse_shadow(table.source(name).unwrap_or_default(), &table, dark)),
1347                Some(Kind::Easing) => match table.easing(name, dark) {
1348                    Some(points) => Value::Easing(points),
1349                    None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
1350                },
1351                None => Value::Text(Rc::from(table.source(name).unwrap_or_default())),
1352            };
1353            values.insert(name.clone(), value);
1354        }
1355        Self { ident: Rc::from(definition.name()), dark, scales: definition.scales(), values }
1356    }
1357
1358    /// 主题名(Astryx `defineTheme({ name })`)。
1359    pub fn name(&self) -> &str {
1360        &self.ident
1361    }
1362
1363    pub fn is_dark(&self) -> bool {
1364        self.dark
1365    }
1366
1367    pub fn scales(&self) -> Scales {
1368        self.scales
1369    }
1370
1371    /// 按变量名原文读任意 token(DevTools / showcase 用)。
1372    pub fn value(&self, name: &str) -> Option<&Value> {
1373        self.values.get(name)
1374    }
1375
1376    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
1377        self.values.iter().map(|(key, value)| (key.as_str(), value))
1378    }
1379
1380    fn number(&self, name: &str, fallback: f32) -> f32 {
1381        match self.value(name) {
1382            Some(Value::Number(value)) => *value,
1383            _ => fallback,
1384        }
1385    }
1386
1387    pub fn color(&self, token: ColorToken) -> Color {
1388        match self.value(token.as_str()) {
1389            Some(Value::Color(color)) => *color,
1390            _ => Color::TRANSPARENT,
1391        }
1392    }
1393
1394    pub fn length(&self, token: LengthToken) -> f32 {
1395        self.number(token.as_str(), 0.0)
1396    }
1397
1398    pub fn spacing(&self, step: SpacingStep) -> f32 {
1399        self.number(step.as_str(), 0.0)
1400    }
1401
1402    pub fn duration(&self, token: DurationToken) -> f32 {
1403        self.number(token.as_str(), 0.0)
1404    }
1405
1406    pub fn font_size(&self, token: FontSizeToken) -> f32 {
1407        self.number(token.as_str(), self.scales.text_base)
1408    }
1409
1410    pub fn font_weight(&self, token: FontWeightToken) -> f32 {
1411        self.number(token.as_str(), 400.0)
1412    }
1413
1414    pub fn shadow(&self, token: ShadowToken) -> Shadow {
1415        match self.value(token.as_str()) {
1416            Some(Value::Shadow(shadow)) => shadow.clone(),
1417            _ => Shadow::default(),
1418        }
1419    }
1420
1421    pub fn easing(&self, token: EasingToken) -> [f32; 4] {
1422        match self.value(token.as_str()) {
1423            Some(Value::Easing(points)) => *points,
1424            _ => [0.24, 1.0, 0.4, 1.0],
1425        }
1426    }
1427
1428    pub fn text_role(&self, role: TextRole) -> TextRoleStyle {
1429        TextRoleStyle {
1430            size: self.number(&role.size_name(), self.font_size(FontSizeToken::Base)),
1431            weight: self.number(&role.weight_name(), 400.0),
1432            leading: self.number(&role.leading_name(), 1.4),
1433        }
1434    }
1435
1436    /// 边框宽度(`--border-width`)。
1437    pub fn border_width(&self) -> f32 {
1438        self.length(LengthToken::BorderWidth)
1439    }
1440
1441    pub fn focus(&self) -> FocusTokens {
1442        FocusTokens {
1443            width: self.length(LengthToken::FocusOutlineWidth),
1444            offset: self.length(LengthToken::FocusOutlineOffset),
1445            color: self.color(ColorToken::FocusOutline),
1446        }
1447    }
1448
1449    pub fn radius(&self) -> RadiusTokens {
1450        RadiusTokens {
1451            none: self.length(LengthToken::RadiusNone),
1452            inner: self.length(LengthToken::RadiusInner),
1453            element: self.length(LengthToken::RadiusElement),
1454            container: self.length(LengthToken::RadiusContainer),
1455            page: self.length(LengthToken::RadiusPage),
1456            chat: self.length(LengthToken::RadiusChat),
1457            full: self.length(LengthToken::RadiusFull),
1458        }
1459    }
1460
1461    /// 控件三档高度(`--size-element-sm/md/lg`)。
1462    pub fn element_size(&self) -> SizeTokens {
1463        SizeTokens {
1464            sm: self.length(LengthToken::SizeElementSm),
1465            md: self.length(LengthToken::SizeElementMd),
1466            lg: self.length(LengthToken::SizeElementLg),
1467        }
1468    }
1469
1470    /// `base` 上盖 `--color-overlay-hover`。
1471    pub fn hovered(&self, base: Color) -> Color {
1472        overlay(base, self.color(ColorToken::OverlayHover))
1473    }
1474
1475    /// `base` 上盖 `--color-overlay-pressed`。
1476    pub fn pressed(&self, base: Color) -> Color {
1477        overlay(base, self.color(ColorToken::OverlayPressed))
1478    }
1479
1480    /// 全部颜色 token 的当前值(showcase / DevTools 的 token 表格用)。
1481    pub fn color_rows(&self) -> Vec<(&'static str, Color)> {
1482        ColorToken::ALL.iter().map(|token| (token.as_str(), self.color(*token))).collect()
1483    }
1484}
1485
1486/// 焦点环打包(宽度 / 外扩 / 颜色)。
1487#[derive(Clone, Copy, Debug, PartialEq)]
1488pub struct FocusTokens {
1489    pub width: f32,
1490    pub offset: f32,
1491    pub color: Color,
1492}
1493
1494/// 圆角打包。
1495#[derive(Clone, Copy, Debug, PartialEq)]
1496pub struct RadiusTokens {
1497    pub none: f32,
1498    pub inner: f32,
1499    pub element: f32,
1500    pub container: f32,
1501    pub page: f32,
1502    pub chat: f32,
1503    pub full: f32,
1504}
1505
1506/// 控件三档尺寸。
1507#[derive(Clone, Copy, Debug, PartialEq)]
1508pub struct SizeTokens {
1509    pub sm: f32,
1510    pub md: f32,
1511    pub lg: f32,
1512}
1513
1514/// 叠加色合成:把带 alpha 的 token(hover / pressed / overlay)盖在底色上。
1515///
1516/// Astryx 的 hover / pressed 是"叠加层"而不是"另一个色值",桌面绘制要先合成再填。
1517pub fn overlay(base: Color, top: Color) -> Color {
1518    if top.a >= 1.0 {
1519        return top;
1520    }
1521    let keep = 1.0 - top.a;
1522    Color {
1523        r: top.r * top.a + base.r * keep,
1524        g: top.g * top.a + base.g * keep,
1525        b: top.b * top.a + base.b * keep,
1526        a: base.a + top.a * (1.0 - base.a),
1527    }
1528}
1529
1530// =================================================================
1531// 测试
1532// =================================================================
1533
1534#[cfg(test)]
1535mod tests {
1536    use super::*;
1537
1538    /// WCAG 对比度(断言用)。
1539    fn luminance(color: Color) -> f32 {
1540        let channel = |v: f32| {
1541            if v <= 0.04045 {
1542                v / 12.92
1543            } else {
1544                ((v + 0.055) / 1.055).powf(2.4)
1545            }
1546        };
1547        0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
1548    }
1549
1550    fn contrast(a: Color, b: Color) -> f32 {
1551        let (la, lb) = (luminance(a), luminance(b));
1552        let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
1553        (hi + 0.05) / (lo + 0.05)
1554    }
1555
1556    #[test]
1557    fn parses_color_shapes() {
1558        let table = TokenTable::build(&define_theme());
1559        let cases = [
1560            ("#0064E0", Color::from_rgb8(0x00, 0x64, 0xE0)),
1561            ("#abc", Color::from_rgb8(0xAA, 0xBB, 0xCC)),
1562            ("#0536590C", Color::from_rgba8(0x05, 0x36, 0x59, 0x0C)),
1563            ("rgba(5, 54, 89, 0.1)", Color::rgba(5.0 / 255.0, 54.0 / 255.0, 89.0 / 255.0, 0.1)),
1564            ("black", Color::BLACK),
1565            ("white", Color::WHITE),
1566            ("light-dark(#111111, #EEEEEE)", Color::from_rgb8(0x11, 0x11, 0x11)),
1567        ];
1568        for (text, expect) in cases {
1569            let light = table.color_from_source(text, false).unwrap_or_else(|| panic!("解析失败: {text}"));
1570            assert_eq!(light, expect, "明档 {text}");
1571        }
1572        let dark = table.color_from_source("light-dark(#111111, #EEEEEE)", true).unwrap();
1573        assert_eq!(dark, Color::from_rgb8(0xEE, 0xEE, 0xEE), "暗档取第二边");
1574    }
1575
1576    #[test]
1577    fn parses_units() {
1578        assert_eq!(parse_atom("8px"), Atom::Num(8.0));
1579        assert_eq!(parse_atom("1.0625rem"), Atom::Num(17.0));
1580        assert_eq!(parse_atom("175ms"), Atom::Num(0.175));
1581        assert_eq!(parse_atom("1.4286"), Atom::Num(1.4286));
1582        assert_eq!(parse_atom("400"), Atom::Num(400.0));
1583        assert_eq!(parse_atom("#0064E0"), Atom::Color(Color::from_rgb8(0x00, 0x64, 0xE0)));
1584    }
1585
1586    #[test]
1587    fn neutral_defaults_match_astryx() {
1588        let light = define_theme().resolve(false);
1589        let dark = define_theme().resolve(true);
1590        assert_eq!(light.color(ColorToken::Accent), Color::from_rgb8(0x00, 0x64, 0xE0));
1591        assert_eq!(dark.color(ColorToken::Accent), Color::from_rgb8(0x26, 0x94, 0xFE));
1592        assert_eq!(light.color(ColorToken::TextPrimary), Color::from_rgb8(0x0A, 0x13, 0x17));
1593        assert_eq!(dark.color(ColorToken::BackgroundBody), Color::from_rgb8(0x11, 0x11, 0x12));
1594        assert_eq!(light.length(LengthToken::RadiusElement), 8.0);
1595        assert_eq!(light.length(LengthToken::SizeElementMd), 32.0);
1596        assert_eq!(light.length(LengthToken::RadiusFull), 9999.0);
1597        assert_eq!(light.font_size(FontSizeToken::Base), 14.0);
1598        assert_eq!(light.font_size(FontSizeToken::FiveXl), 42.0);
1599        assert_eq!(light.font_size(FontSizeToken::FourXs), 6.0);
1600        assert_eq!(light.spacing(SpacingStep::S4), 16.0);
1601        assert_eq!(light.spacing(SpacingStep::S1_5), 6.0);
1602        assert!((light.duration(DurationToken::Fast) - 0.175).abs() < 1e-6);
1603        assert_eq!(light.font_weight(FontWeightToken::Semibold), 600.0);
1604        assert_eq!(light.text_role(TextRole::HeadingOne).size, 24.0);
1605        assert_eq!(light.text_role(TextRole::HeadingOne).weight, 600.0);
1606        assert_eq!(light.text_role(TextRole::Body).size, 14.0);
1607        assert_eq!(light.text_role(TextRole::Supporting).size, 12.0);
1608        assert_eq!(light.easing(EasingToken::Standard), [0.24, 1.0, 0.4, 1.0]);
1609        assert_eq!(light.easing(EasingToken::Exit), [0.3, 0.0, 0.6, 0.6]);
1610        assert_eq!(light.name(), "neutral");
1611    }
1612
1613    #[test]
1614    fn scale_generation_reproduces_neutral_base() {
1615        // scale 默认参数必须逐条还原基表取值,否则等于引入第二套事实
1616        let base: BTreeMap<&str, &str> = BASE_TOKENS.iter().copied().collect();
1617        let generated = Scales::default().generate();
1618        assert!(!generated.is_empty());
1619        for (name, value) in &generated {
1620            let literal = base.get(*name).unwrap_or_else(|| panic!("基表缺少 {name}"));
1621            assert_eq!(&parse_atom(value), &parse_atom(literal), "scale 默认值改变了 {name}");
1622        }
1623        // 显式覆盖仍然优先于 scale 生成
1624        let overridden =
1625            define_theme().radius_multiplier(2.0).token("--radius-element", "10px").unwrap().resolve(false);
1626        assert_eq!(overridden.length(LengthToken::RadiusElement), 10.0);
1627        assert_eq!(overridden.length(LengthToken::RadiusContainer), 24.0);
1628    }
1629
1630    #[test]
1631    fn radius_multiplier_scales_named_radii_but_not_none_or_full() {
1632        let tokens = define_theme().radius_multiplier(1.5).resolve(false);
1633        assert_eq!(tokens.length(LengthToken::RadiusInner), 6.0);
1634        assert_eq!(tokens.length(LengthToken::RadiusElement), 12.0);
1635        assert_eq!(tokens.length(LengthToken::RadiusContainer), 18.0);
1636        assert_eq!(tokens.length(LengthToken::RadiusPage), 42.0);
1637        assert_eq!(tokens.length(LengthToken::RadiusNone), 0.0, "0 不该被放大");
1638        assert_eq!(tokens.length(LengthToken::RadiusFull), 9999.0, "完全圆不该被放大");
1639        assert_eq!(tokens.radius().element, 12.0);
1640    }
1641
1642    #[test]
1643    fn text_and_motion_scales_move_the_whole_ladder() {
1644        let tokens = define_theme().text_scale(16.0, 1.25).resolve(false);
1645        assert_eq!(tokens.font_size(FontSizeToken::Base), 16.0);
1646        assert_eq!(tokens.font_size(FontSizeToken::Lg), 20.0);
1647        // 角色通过 var() 引用阶梯,所以自动跟
1648        assert_eq!(tokens.text_role(TextRole::Body).size, 16.0);
1649        assert_eq!(tokens.text_role(TextRole::HeadingOne).size, 31.0);
1650
1651        let slow = define_theme().motion_scale(200.0, 500.0, 1000.0, 0.8).resolve(false);
1652        assert!((slow.duration(DurationToken::Fast) - 0.2).abs() < 1e-6);
1653        assert!((slow.duration(DurationToken::FastMin) - 0.16).abs() < 1e-6);
1654        assert!((slow.duration(DurationToken::FastMax) - 0.25).abs() < 1e-6);
1655        assert!((slow.duration(DurationToken::Slow) - 1.0).abs() < 1e-6);
1656    }
1657
1658    #[test]
1659    fn overriding_accent_also_moves_the_focus_ring() {
1660        // --focus-outline-color 是 var(--color-accent)
1661        let tokens = define_theme().token("--color-accent", "#7B61FF").unwrap().resolve(false);
1662        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x7B, 0x61, 0xFF));
1663        assert_eq!(tokens.focus().color, Color::from_rgb8(0x7B, 0x61, 0xFF));
1664    }
1665
1666    #[test]
1667    fn status_colors_follow_the_hue_chain() {
1668        // --color-text-error → var(--color-text-red)
1669        let tokens = define_theme().resolve(true);
1670        assert_eq!(tokens.color(ColorToken::TextError), tokens.color(ColorToken::TextRed));
1671        assert_eq!(tokens.color(ColorToken::IconError), tokens.color(ColorToken::TextError));
1672        assert_eq!(tokens.color(ColorToken::BorderError), tokens.color(ColorToken::TextError));
1673        // 覆盖链条上的锚点,语义色一起变
1674        let tokens = define_theme().token("--color-text-red", "#FF0000").unwrap().resolve(false);
1675        assert_eq!(tokens.color(ColorToken::TextError), Color::from_rgb8(0xFF, 0x00, 0x00));
1676        assert_eq!(tokens.color(ColorToken::BorderError), Color::from_rgb8(0xFF, 0x00, 0x00));
1677    }
1678
1679    #[test]
1680    fn override_beats_base_for_both_modes() {
1681        let def = define_theme().token("--color-background-surface", "light-dark(#111111, #EEEEEE)").unwrap();
1682        assert_eq!(def.resolve(false).color(ColorToken::BackgroundSurface), Color::from_rgb8(0x11, 0x11, 0x11));
1683        assert_eq!(def.resolve(true).color(ColorToken::BackgroundSurface), Color::from_rgb8(0xEE, 0xEE, 0xEE));
1684    }
1685
1686    #[test]
1687    fn color_helper_writes_two_variants() {
1688        let tokens = define_theme()
1689            .color(ColorToken::Accent, Color::from_rgb8(0x10, 0x20, 0x30), Color::from_rgb8(0xF0, 0xE0, 0xD0))
1690            .resolve(false);
1691        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x10, 0x20, 0x30));
1692        assert_eq!(tokens.color(ColorToken::FocusOutline), Color::from_rgb8(0x10, 0x20, 0x30));
1693        assert_eq!(hex_of(Color::from_rgb8(0x10, 0x20, 0x30)), "#102030");
1694    }
1695
1696    #[test]
1697    fn bad_token_names_and_values_are_rejected() {
1698        assert!(matches!(define_theme().token("--color-nope", "#fff"), Err(TokenError::UnknownName(_))));
1699        assert!(matches!(define_theme().token("--radius-element", "not-a-length"), Err(TokenError::BadValue { .. })));
1700        assert!(matches!(define_theme().token("--color-accent", "8px"), Err(TokenError::BadValue { .. })));
1701        assert!(matches!(define_theme().token("--font-size-base", "#FFFFFF"), Err(TokenError::BadValue { .. })));
1702    }
1703
1704    /// 逐枚举检查基表覆盖情况(不同 token 枚举没法直接 chain 起来)。
1705    macro_rules! assert_tokens_present {
1706        ($tokens:expr, $($enum:ident),* $(,)?) => {
1707            $(
1708                for token in $enum::ALL {
1709                    assert!(
1710                        $tokens.value(token.as_str()).is_some(),
1711                        "基表缺少 token {}",
1712                        token.as_str()
1713                    );
1714                }
1715            )*
1716        };
1717    }
1718
1719    #[test]
1720    fn every_typed_token_has_a_base_value() {
1721        // 基表漏一个 token,resolve 会静默给透明 / 0 —— 这里兜住
1722        let tokens = define_theme().resolve(false);
1723        assert_tokens_present!(
1724            tokens,
1725            ColorToken,
1726            LengthToken,
1727            SpacingStep,
1728            DurationToken,
1729            FontSizeToken,
1730            FontWeightToken,
1731            ShadowToken,
1732            EasingToken,
1733        );
1734        for role in TextRole::ALL {
1735            for name in [role.size_name(), role.weight_name(), role.leading_name()] {
1736                assert!(tokens.value(&name).is_some(), "基表缺少 {name}");
1737            }
1738        }
1739    }
1740
1741    #[test]
1742    fn every_base_token_name_is_known_to_the_override_layer() {
1743        let mut unknown = Vec::new();
1744        for (name, _) in BASE_TOKENS {
1745            if kind_of(name).is_none() {
1746                unknown.push(*name);
1747            }
1748        }
1749        assert!(unknown.is_empty(), "覆盖层不认识的基表名: {unknown:?}");
1750    }
1751
1752    #[test]
1753    fn shadows_are_multi_layer_with_mode_specific_colors() {
1754        let light = define_theme().resolve(false);
1755        let dark = define_theme().resolve(true);
1756        let low = light.shadow(ShadowToken::Low);
1757        assert_eq!(low.layers.len(), 2);
1758        let first = low.first().unwrap();
1759        assert_eq!((first.offset_x, first.offset_y, first.blur, first.spread), (0.0, 1.0, 1.0, 0.0));
1760        assert!(!first.inset);
1761        assert_eq!(first.color, Color::rgba(0.0, 0.0, 0.0, 0.1));
1762        assert_eq!(dark.shadow(ShadowToken::Low).first().unwrap().color, Color::rgba(0.0, 0.0, 0.0, 0.2));
1763        let ring = light.shadow(ShadowToken::InsetHover).ring().expect("inset 描边环");
1764        assert!(ring.inset && ring.blur == 0.0 && ring.spread == 2.0);
1765        assert!(light.shadow(ShadowToken::Low).ring().is_none());
1766    }
1767
1768    #[test]
1769    fn shadow_can_reference_color_shadow_token() {
1770        let mut overrides = TokenOverrides::new();
1771        overrides.set("--shadow-low", "0px 2px 4px var(--color-shadow)").unwrap();
1772        let tokens = define_theme().tokens(overrides).resolve(true);
1773        let layer = tokens.shadow(ShadowToken::Low).first().unwrap();
1774        assert_eq!(layer.color, tokens.color(ColorToken::Shadow));
1775        assert_eq!(layer.blur, 4.0);
1776    }
1777
1778    #[test]
1779    fn overlay_helpers_composite_alpha_tokens() {
1780        for dark in [false, true] {
1781            let tokens = define_theme().resolve(dark);
1782            let base = tokens.color(ColorToken::BackgroundSurface);
1783            let hover = tokens.hovered(base);
1784            let pressed = tokens.pressed(base);
1785            assert!(hover.a > 0.99, "叠加后仍是不透明底色");
1786            assert_ne!(hover, base, "hover 必须看得见");
1787            assert_ne!(hover, pressed, "hover 与 pressed 不同档");
1788            // pressed 比 hover 更强
1789            let strength = |a: Color, b: Color| (a.r - b.r).abs() + (a.g - b.g).abs() + (a.b - b.b).abs();
1790            assert!(strength(base, pressed) > strength(base, hover), "dark={dark}");
1791        }
1792    }
1793
1794    #[test]
1795    fn neutral_text_on_surface_meets_aa_contrast() {
1796        for dark in [false, true] {
1797            let tokens = define_theme().resolve(dark);
1798            let on_surface =
1799                contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundSurface));
1800            assert!(on_surface >= 4.5, "正文/表面 对比度 {on_surface:.2} < 4.5 (dark={dark})");
1801            let on_body = contrast(tokens.color(ColorToken::TextPrimary), tokens.color(ColorToken::BackgroundBody));
1802            assert!(on_body >= 4.5, "正文/画布 对比度 {on_body:.2} < 4.5 (dark={dark})");
1803            let secondary =
1804                contrast(tokens.color(ColorToken::TextSecondary), tokens.color(ColorToken::BackgroundSurface));
1805            assert!(secondary >= 4.5, "次要文本/表面 对比度 {secondary:.2} < 4.5 (dark={dark})");
1806        }
1807    }
1808
1809    #[test]
1810    fn ref_cycles_and_unknown_refs_fall_back_without_panicking() {
1811        let mut overrides = TokenOverrides::new();
1812        overrides.set("--color-accent", "var(--color-accent)").unwrap();
1813        overrides.set("--color-text-red", "var(--nope)").unwrap();
1814        let tokens = define_theme().tokens(overrides).resolve(false);
1815        // 成环 → 透明;断链 → 透明;都不 panic
1816        assert_eq!(tokens.color(ColorToken::Accent), Color::TRANSPARENT);
1817        assert_eq!(tokens.color(ColorToken::TextError), Color::TRANSPARENT);
1818        // var() 的回退值会被用上
1819        let mut overrides = TokenOverrides::new();
1820        overrides.set("--color-accent", "var(--nope, #123456)").unwrap();
1821        let tokens = define_theme().tokens(overrides).resolve(false);
1822        assert_eq!(tokens.color(ColorToken::Accent), Color::from_rgb8(0x12, 0x34, 0x56));
1823    }
1824}