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//! 减弱动效)、data-viz 色阶 `--color-data-*`(只收录 Avatar 用到的 categorical 档)。
41//!
42//! 已实现并按 0.6 Text 2.0 打通到文本服务:`--font-family-*` → `Tokens::font_stack`
43//! (CSS 字体栈原文,交给 parley 回退链);`--text-*-leading` → `TextRoleStyle::leading`
44//! → `mgui_text::text::set_text_line_height`(布局与绘制同一 shaping 真值,行高进 shape 缓存 key)。
45
46use crate::Color;
47use std::collections::BTreeMap;
48use std::fmt;
49use std::rc::Rc;
50
51// =================================================================
52// 明暗两档
53// =================================================================
54
55/// 明 / 暗两档取值 —— Astryx `light-dark(明, 暗)` 的对应物。
56#[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
92// =================================================================
93// token 名(Astryx CSS 变量名的强类型镜像)
94// =================================================================
95
96/// 生成一组带 `ALL` / `as_str()` / `from_name()` 的 token 名枚举。
97///
98/// 变体名 = Astryx 变量名的大驼峰形式,`as_str()` 给出变量名原文,`from_name()` 供覆盖层
99/// 按名反查并做拼写校验。
100macro_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            /// 全部 token(按声明顺序)。
111            pub const ALL: &'static [Self] = &[$(Self::$variant),*];
112
113            /// Astryx 变量名原文。
114            pub fn as_str(self) -> &'static str {
115                match self { $(Self::$variant => $css),* }
116            }
117
118            /// 按变量名反查。
119            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    /// 颜色 token。语义命名与 Astryx 完全一致(`on-*` = 该色之上的前景色)。
128    pub enum ColorToken {
129        Accent => "--color-accent",
130        AccentMuted => "--color-accent-muted",
131        OnAccent => "--color-on-accent",
132        /// 中性提示色(Astryx 用它做低强调描边 / 填充)
133        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        /// 常规 1px 描边(带 alpha)
162        Border => "--color-border",
163        /// 需要被看清的描边(输入框 / 按钮 / 控件)
164        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        /// 遮罩(Dialog / Drawer 的 barrier)
186        Overlay => "--color-overlay",
187        /// hover 叠加色(带 alpha,盖在容器色上)
188        OverlayHover => "--color-overlay-hover",
189        /// 按下叠加色(带 alpha)
190        OverlayPressed => "--color-overlay-pressed",
191        Shadow => "--color-shadow",
192        /// 骨架屏占位色
193        Skeleton => "--color-skeleton",
194        /// 滑杆 / 开关的未填充轨道
195        Track => "--color-track",
196        /// hover 提色调(浅色主题叠黑、深色主题叠白)
197        TintHover => "--color-tint-hover",
198        OnDark => "--color-on-dark",
199        OnLight => "--color-on-light",
200        /// 焦点环颜色,默认 `var(--color-accent)`
201        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    /// 长度类 token:圆角、控件尺寸、边框宽度、焦点环。单位统一解析为 px。
217    pub enum LengthToken {
218        /// 0px —— 不受半径倍率影响
219        RadiusNone => "--radius-none",
220        /// 4px —— 容器内部的小元素
221        RadiusInner => "--radius-inner",
222        /// 8px —— 按钮 / 输入框 / 行
223        RadiusElement => "--radius-element",
224        /// 12px —— 卡片 / 浮层
225        RadiusContainer => "--radius-container",
226        /// 28px —— 页面级容器
227        RadiusPage => "--radius-page",
228        /// 28px —— 气泡
229        RadiusChat => "--radius-chat",
230        /// 9999px —— 完全圆,不受半径倍率影响
231        RadiusFull => "--radius-full",
232        /// 28px —— 紧凑控件高度
233        SizeElementSm => "--size-element-sm",
234        /// 32px —— 默认控件高度
235        SizeElementMd => "--size-element-md",
236        /// 36px —— 触控友好高度
237        SizeElementLg => "--size-element-lg",
238        /// 1px
239        BorderWidth => "--border-width",
240        /// 2px
241        FocusOutlineWidth => "--focus-outline-width",
242        /// 3px
243        FocusOutlineOffset => "--focus-outline-offset",
244    }
245}
246
247named_tokens! {
248    /// 间距档位。Astryx 是 `--spacing-0` … `--spacing-12`(每档 `0.25rem` = 4px),
249    /// 外加 `--spacing-0-5` / `--spacing-1-5` 两个半步。
250    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    /// 动效时长(解析后统一为**秒**)。min/max 是同一档的微调区间。
271    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    /// 字号阶梯:以 `--font-size-base`(14px)为锚点、按 1.2 倍生成,单位解析为 px。
286    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    /// 相对 `--font-size-base` 的台阶指数(base = 0,往上为正、往下为负)。
304    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    /// 字重(无单位数值)。
324    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    /// 阴影 token。`low` / `med` / `high` 是两层外阴影,`inset-*` 是 2px 内描边环。
334    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    /// 缓动曲线(三次贝塞尔控制点)。
348    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    /// 文本角色(Astryx `--text-*` 三件套:size / weight / leading)。
358    ///
359    /// 角色的 size / weight 通过 `var()` 引用字号 / 字重阶梯,所以调
360    /// [`Scales::text_base`] 时整套角色跟着变。
361    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    /// `--text-body` → `body`。
381    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    /// 字体栈角色(`--font-family-*`)。值按 CSS `font-family` 字面量原文保留,
415    /// 由 `mgui-text` 的 parley/fontique 回退链消费(CJK/emoji 自动落到后备字体)。
416    pub enum FontFamilyToken {
417        Body => "--font-family-body",
418        Display => "--font-family-display",
419        Mono => "--font-family-mono",
420    }
421}
422
423/// token 的值类型 —— 决定覆盖层接受什么形状的字面量。
424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
425enum Kind {
426    Color,
427    /// 长度 / 时长 / 字号 / 字重 / 行高
428    Number,
429    Shadow,
430    Easing,
431    /// CSS 字体栈原文(交给 mgui-text 的 parley 回退链消费)
432    FontStack,
433}
434
435/// 变量名 → 值类型。未收录的名字视为未知(覆盖层直接报错)。
436fn 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    // --text-*-size / -weight / -leading 由 TextRole 拼出来,不在上面的枚举里
458    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// =================================================================
467// 字面量解析
468// =================================================================
469
470/// 一个 token 字面量的中间表示。
471#[derive(Clone, Debug, PartialEq)]
472enum Atom {
473    Color(Color),
474    /// 长度(px) / 时长(秒) / 无单位数字
475    Num(f32),
476    /// `light-dark(明, 暗)`
477    LightDark(Rc<Atom>, Rc<Atom>),
478    /// `var(--x)` 或 `var(--x, 回退)`
479    Ref {
480        name: String,
481        fallback: Option<Rc<Atom>>,
482    },
483    /// 其余按原文留着(缓动曲线、字体族栈等)
484    Text(Rc<str>),
485}
486
487/// `rem` 的基准。Astryx 的网页基准是 16px;mgui 没有根字号概念,固定按 16px 换算。
488const REM_PX: f32 = 16.0;
489
490/// 解析一个 CSS 风格字面量。单位归一:`px` 原值、`rem` × 16、`ms` ÷ 1000、`s` 原值。
491fn 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
518/// `#RGB` / `#RRGGBB` / `#RRGGBBAA` / `rgb()` / `rgba()` / Astryx 用到的颜色关键字。
519fn 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        // Astryx 用 8 位 hex 表示带 alpha 的叠加色:#RRGGBBAA
547        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
557/// `rgba(r, g, b, a)`:r/g/b 是 0–255,a 是 0–1
558fn 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
570/// `12px` / `0.875rem` / `175ms` / `1.4` / `400`
571fn 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
587/// `name(a, b)` → `Some("a, b")`(调用方传小写文本,要求括号配平)
588fn 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
594/// 按**顶层**逗号(或其他单字符分隔符)切成两段;括号内的分隔符不算。
595fn 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
608/// 按顶层逗号切成任意多段(box-shadow 的多层列表)。
609fn 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
628/// 按顶层空白切分(`0px 1px 1px light-dark(...)` → 4 段)。
629fn 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// =================================================================
660// 阴影
661// =================================================================
662
663/// 一层 box-shadow。
664#[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/// 一组阴影(Astryx 的 `--shadow-low/med/high` 是两层,`--shadow-inset-*` 是一层内描边)。
675#[derive(Clone, Debug, Default, PartialEq)]
676pub struct Shadow {
677    pub layers: Vec<ShadowLayer>,
678}
679
680impl Shadow {
681    /// 第一层投影(桌面端绘制最常用的取法)。
682    pub fn first(&self) -> Option<ShadowLayer> {
683        self.layers.first().copied()
684    }
685
686    /// `inset` + 纯 spread 构成的"描边环"(Astryx 用它表达 hover / selected 的内圈)。
687    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
696/// 解析 `0px 1px 1px <color>, 0px 2px 8px <color>` 形式。
697fn 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
741// =================================================================
742// 基表:Astryx `Neutral` 主题默认值
743// =================================================================
744
745/// 与 Astryx 站点 `:root`(`Neutral` 主题)编译产物逐条一致。
746pub const BASE_TOKENS: &[(&str, &str)] = &[
747    // ---- 品牌 / 中性 ----
748    ("--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    // ---- 背景 ----
753    ("--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    // ---- 文本 ----
761    ("--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    // ---- 图标 ----
774    ("--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    // ---- 描边 ----
783    ("--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    // ---- 状态 ----
790    ("--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    // 深色 error 太亮,白字达不到 4.5:1,所以它上面的文字用深色
801    ("--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    // ---- 叠加层 / 阴影色 / 轨道 ----
808    ("--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    // ---- 分类色(Avatar 轮换池用到) ----
818    ("--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    // ---- 圆角 / 尺寸 / 边框 / 焦点 ----
829    ("--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    // 焦点环颜色引用主色:覆盖 --color-accent 时它跟着走
843    ("--focus-outline-color", "var(--color-accent)"),
844    // ---- 阴影(Astryx 是两层外阴影;inset-* 是 2px 内描边环) ----
845    (
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    // ---- 间距:0–12 档(每档 0.25rem = 4px),含两个半步 ----
866    ("--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    // ---- 动效 ----
882    ("--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    // ---- 字号(1.2 台阶,锚点 14px)与字重 ----
896    ("--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    // ---- 文本角色:引用阶梯,所以调 base / ratio 时整套角色跟着变 ----
913    ("--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// =================================================================
961// scale 配置(Astryx 的 radius / typography.scale / motion 生成器)
962// =================================================================
963
964/// 三组 scale 参数,默认值 = Astryx `Neutral`。
965///
966/// 用默认值生成的 token 与 [`BASE_TOKENS`] 逐条等值(有测试兜住),所以这里只做"按参数
967/// 重新生成",不引入第二套事实。
968#[derive(Clone, Copy, Debug, PartialEq)]
969pub struct Scales {
970    /// `radius.base`:半径基准(px,Astryx = 4)
971    pub radius_base: f32,
972    /// `radius.multiplier`:0–2,1 = Astryx 默认
973    pub radius_multiplier: f32,
974    /// `typography.scale.base`:字号锚点(px)
975    pub text_base: f32,
976    /// `typography.scale.ratio`:台阶比(Astryx = 1.2)
977    pub text_ratio: f32,
978    /// `motion.fast`(ms)
979    pub motion_fast_ms: f32,
980    /// `motion.medium`(ms)
981    pub motion_medium_ms: f32,
982    /// `motion.slow`(ms)
983    pub motion_slow_ms: f32,
984    /// `motion.ratio`:min/max 相对中心的收缩比(Astryx = 0.75)
985    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
1003/// `12px` 形式的长度字符串(整数值不留小数点,避免与基表字面量无谓漂移)。
1004fn 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
1013/// duration 的 min/max 就近取到 10ms 整数倍(Astryx 的 duration 表都是整十)。
1014fn ms10(value: f32) -> f32 {
1015    (value / 10.0).round() * 10.0
1016}
1017
1018impl Scales {
1019    /// 需要按参数重算的 token 字面量。
1020    ///
1021    /// 半径只生成 `inner` / `element` / `container` / `page` / `chat`(Astryx 同);
1022    /// `none` 恒为 0、`full` 恒为 9999px,倍率不该动它们。
1023    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// =================================================================
1053// 覆盖层
1054// =================================================================
1055
1056/// 按 Astryx 变量名记录的 token 覆盖。
1057#[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    /// 记录一条覆盖;值先过一遍形状校验,写错立刻报错(而不是到 paint 期才发现)。
1076    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            // 阴影、缓动与字体栈按原文保留,解析失败只会在 resolve 时退化
1084            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/// token 覆盖的错误。
1103#[derive(Clone, Debug, PartialEq, Eq)]
1104pub enum TokenError {
1105    /// 不认识的变量名(mgui 实现的是 Astryx 核心 token 集,见模块文档)
1106    UnknownName(String),
1107    /// 值的形状与该 token 的类型不符
1108    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// =================================================================
1123// 主题定义(Astryx `defineTheme` 的对应物)
1124// =================================================================
1125
1126/// 一份主题定义:基表 + scale + 覆盖。
1127///
1128/// 只描述"改了什么",不预先算结果 —— [`ThemeDefinition::resolve`] 才是实际取值,
1129/// 所以一份定义可以同时服务明暗两档。
1130#[derive(Clone, Debug, PartialEq)]
1131pub struct ThemeDefinition {
1132    ident: String,
1133    scales: Scales,
1134    overrides: TokenOverrides,
1135}
1136
1137/// 以 Astryx `Neutral` 为基底开一份主题定义。
1138pub fn define_theme() -> ThemeDefinition {
1139    ThemeDefinition { ident: "neutral".to_string(), scales: Scales::default(), overrides: TokenOverrides::new() }
1140}
1141
1142impl ThemeDefinition {
1143    /// 主题名(Astryx `defineTheme({ name })`)。
1144    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    /// 半径倍率(Astryx `radius.multiplier`,0–2)。`--radius-none` / `--radius-full` 不受影响。
1154    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    /// 半径基准(Astryx `radius.base`,px)。
1160    pub fn radius_base(mut self, base: f32) -> Self {
1161        self.scales.radius_base = base.max(0.0);
1162        self
1163    }
1164
1165    /// 字号锚点 + 台阶比(Astryx `typography.scale`)。
1166    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    /// 动效节奏(Astryx `motion`;单位 ms,min/max 按 `ratio` 生成)。
1173    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    /// 覆盖单个 token(Astryx 变量名 + 字面量)。
1186    pub fn token(mut self, name: &str, value: &str) -> Result<Self, TokenError> {
1187        self.overrides.set(name, value)?;
1188        Ok(self)
1189    }
1190
1191    /// [`ThemeDefinition::token`] 的 `&mut self` 版本 —— 循环里构造主题时不用来回搬 `self`。
1192    pub fn set_token(&mut self, name: &str, value: &str) -> Result<(), TokenError> {
1193        self.overrides.set(name, value)
1194    }
1195
1196    /// [`ThemeDefinition::color`] 的 `&mut self` 版本。
1197    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        // 值由本方法拼装,形状必然合法
1200        let _ = self.overrides.set(token.as_str(), &value);
1201    }
1202
1203    /// 覆盖 color token 的便捷写法:明暗两档分别给 `Color`。
1204    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    /// 解析成某个明暗档下的实际 token 取值。
1219    pub fn resolve(&self, dark: bool) -> Tokens {
1220        Tokens::resolve(self, dark)
1221    }
1222}
1223
1224/// `Color` → Astryx 颜色字面量(`#RRGGBB`,带 alpha 时写 8 位)。
1225fn 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
1235// =================================================================
1236// 解析
1237// =================================================================
1238
1239/// 字面量表(变量名 → 原文):基表已被 scale 与覆盖改写过。
1240struct TokenTable {
1241    sources: BTreeMap<String, String>,
1242}
1243
1244/// `var()` 展开深度上限,用来兜住成环引用。
1245const 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    /// 取字面量并展开成单值。
1265    fn expand(&self, text: &str, dark: bool, depth: u32) -> Option<Atom> {
1266        self.expand_atom(&parse_atom(text), dark, depth)
1267    }
1268
1269    /// 按明暗档选一边、按 `var()` 追引用;成环或断链返回 `None`。
1270    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    /// 阴影里的颜色段可能是 `light-dark(...)` / `var(--color-shadow)` / 直接 hex。
1295    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// =================================================================
1326// 解析结果
1327// =================================================================
1328
1329/// 一个 token 在某个明暗档下的实际取值。
1330#[derive(Clone, Debug, PartialEq)]
1331pub enum Value {
1332    Color(Color),
1333    /// 长度(px) / 时长(秒) / 字号(px) / 字重与行高(无单位)
1334    Number(f32),
1335    Shadow(Shadow),
1336    /// 三次贝塞尔控制点
1337    Easing([f32; 4]),
1338    Text(Rc<str>),
1339}
1340
1341/// 文本角色解析结果。
1342#[derive(Clone, Copy, Debug, PartialEq)]
1343pub struct TextRoleStyle {
1344    pub size: f32,
1345    pub weight: f32,
1346    pub leading: f32,
1347}
1348
1349/// 一份主题在某一明暗档下的全部实际取值。
1350#[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    /// 主题名(Astryx `defineTheme({ name })`)。
1379    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    /// 按变量名原文读任意 token(DevTools / showcase 用)。
1392    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    /// CSS 字体栈原文(`--font-family-*`)。交给 `mgui-text` 的 shaped-line API 消费;
1408    /// 字体栈 hash 已进入 shape 缓存 key,切换不会串缓存。
1409    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    /// 边框宽度(`--border-width`)。
1466    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    /// 控件三档高度(`--size-element-sm/md/lg`)。
1491    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    /// `base` 上盖 `--color-overlay-hover`。
1500    pub fn hovered(&self, base: Color) -> Color {
1501        overlay(base, self.color(ColorToken::OverlayHover))
1502    }
1503
1504    /// `base` 上盖 `--color-overlay-pressed`。
1505    pub fn pressed(&self, base: Color) -> Color {
1506        overlay(base, self.color(ColorToken::OverlayPressed))
1507    }
1508
1509    /// 全部颜色 token 的当前值(showcase / DevTools 的 token 表格用)。
1510    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/// 焦点环打包(宽度 / 外扩 / 颜色)。
1516#[derive(Clone, Copy, Debug, PartialEq)]
1517pub struct FocusTokens {
1518    pub width: f32,
1519    pub offset: f32,
1520    pub color: Color,
1521}
1522
1523/// 圆角打包。
1524#[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/// 控件三档尺寸。
1536#[derive(Clone, Copy, Debug, PartialEq)]
1537pub struct SizeTokens {
1538    pub sm: f32,
1539    pub md: f32,
1540    pub lg: f32,
1541}
1542
1543/// 叠加色合成:把带 alpha 的 token(hover / pressed / overlay)盖在底色上。
1544///
1545/// Astryx 的 hover / pressed 是"叠加层"而不是"另一个色值",桌面绘制要先合成再填。
1546pub 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// =================================================================
1560// 测试
1561// =================================================================
1562
1563#[cfg(test)]
1564mod tests {
1565    use super::*;
1566
1567    /// WCAG 对比度(断言用)。
1568    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        // scale 默认参数必须逐条还原基表取值,否则等于引入第二套事实
1667        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        // 显式覆盖仍然优先于 scale 生成
1675        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        // 角色通过 var() 引用阶梯,所以自动跟
1699        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        // --focus-outline-color 是 var(--color-accent)
1712        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        // --color-text-error → var(--color-text-red)
1720        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        // 覆盖链条上的锚点,语义色一起变
1725        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    /// 逐枚举检查基表覆盖情况(不同 token 枚举没法直接 chain 起来)。
1756    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        // 基表漏一个 token,resolve 会静默给透明 / 0 —— 这里兜住
1773        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            // pressed 比 hover 更强
1840            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        // 成环 → 透明;断链 → 透明;都不 panic
1867        assert_eq!(tokens.color(ColorToken::Accent), Color::TRANSPARENT);
1868        assert_eq!(tokens.color(ColorToken::TextError), Color::TRANSPARENT);
1869        // var() 的回退值会被用上
1870        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}