Skip to main content

mgui_core/
theme.rs

1//! 阶段 4-A:Theme + Direction — 第一个 InheritedWidget 用例
2//!
3//! 设计文档 § 6 + § 19.Theme:全局视觉风格沿树向下传递。
4//!
5//! ```ignore
6//! ThemeWidget::new(ThemeData::dark())
7//!     .direction(Direction::Ltr)
8//!     .child(MyApp())
9//! ```
10//!
11//! 任何后代 widget 在 `state.build(ctx)` 中调 `ctx.depend_on::<ThemeWidget>()` 或
12//! 便捷的 `ctx.theme()` / `ctx.direction()` 拿当前主题。
13
14use crate::inherited::InheritedWidget;
15use crate::widget::{Widget, WidgetNode};
16use crate::{Color, Point, Size};
17use std::any::Any;
18use std::rc::Rc;
19
20pub mod tokens;
21
22pub use tokens::{
23    define_theme, overlay, ColorToken, DurationToken, EasingToken, FocusTokens, FontFamilyToken, FontSizeToken,
24    FontWeightToken, LengthToken, RadiusTokens, Shadow, ShadowLayer, ShadowToken, SizeTokens, SpacingStep, TextRole,
25    TextRoleStyle, ThemeDefinition, TokenError, TokenOverrides, Tokens, Value as TokenValue, Variant,
26};
27
28// =================================================================
29// ThemeData — 纯数据,无 Widget 概念
30// =================================================================
31
32/// Text style defaults (theme-level).
33/// Individual TextWidget can override via TextStyle.
34#[derive(Debug, Clone, PartialEq)]
35pub struct TextTheme {
36    pub headline: TextStyleTheme,
37    pub title: TextStyleTheme,
38    pub body: TextStyleTheme,
39    pub caption: TextStyleTheme,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub struct TextStyleTheme {
44    pub font_size: f32,
45    pub color: Color,
46}
47
48/// Button style defaults.
49#[derive(Debug, Clone, PartialEq)]
50pub struct ButtonStyle {
51    pub background: Color,
52    pub foreground: Color,
53    pub radius: f32,
54    /// 全局焦点环颜色(button / checkbox / input / nav 等复用同一令牌)
55    pub focus_ring_color: Color,
56    /// 全局焦点环宽度
57    pub focus_ring_width: f32,
58}
59
60/// 按钮语义变体(对应组件侧 `ButtonType`)。
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum ButtonVariant {
63    /// 主操作
64    Primary,
65    /// 中性 / 次要操作(可有描边)
66    Normal,
67    /// 三级 / 低强调
68    Tertiary,
69    /// 成功
70    Success,
71    /// 警告
72    Warning,
73    /// 危险
74    Error,
75    /// 信息
76    Info,
77}
78
79/// 单个按钮变体的五态配色。
80#[derive(Debug, Clone, PartialEq)]
81pub struct ButtonVariantStyle {
82    pub background: Color,
83    pub foreground: Color,
84    /// `Color::TRANSPARENT` = 无描边
85    pub border: Color,
86    pub hover_background: Color,
87    pub pressed_background: Color,
88}
89
90/// 全部按钮变体。
91#[derive(Debug, Clone, PartialEq)]
92pub struct ButtonVariants {
93    pub primary: ButtonVariantStyle,
94    pub normal: ButtonVariantStyle,
95    pub tertiary: ButtonVariantStyle,
96    pub success: ButtonVariantStyle,
97    pub warning: ButtonVariantStyle,
98    pub error: ButtonVariantStyle,
99    pub info: ButtonVariantStyle,
100}
101
102impl ButtonVariants {
103    /// 按语义变体取样式。
104    pub fn get(&self, variant: ButtonVariant) -> &ButtonVariantStyle {
105        match variant {
106            ButtonVariant::Primary => &self.primary,
107            ButtonVariant::Normal => &self.normal,
108            ButtonVariant::Tertiary => &self.tertiary,
109            ButtonVariant::Success => &self.success,
110            ButtonVariant::Warning => &self.warning,
111            ButtonVariant::Error => &self.error,
112            ButtonVariant::Info => &self.info,
113        }
114    }
115}
116
117/// Avatar 样式(首字头像)。
118#[derive(Debug, Clone, PartialEq)]
119pub struct AvatarStyle {
120    /// 按名称哈希轮换的底色池
121    pub palette: [Color; 6],
122    pub foreground: Color,
123}
124
125/// 表单控件(Checkbox / Radio / Toggle / Slider)的控件令牌,由 Astryx token 推导(见 `ThemeData::from_tokens`)。
126#[derive(Debug, Clone, PartialEq)]
127pub struct ControlStyle {
128    /// 未选中控件底色(color-background-control-default)
129    pub background: Color,
130    /// 控件描边(color-border-control-default)
131    pub border: Color,
132    /// 选中底色(color-background-control-checked)
133    pub checked_background: Color,
134    /// 选中前景(对勾 / 圆点颜色)
135    pub checked_foreground: Color,
136    /// 禁用底色(color-background-control-disabled)
137    pub disabled_background: Color,
138    /// 禁用描边
139    pub disabled_border: Color,
140    /// Toggle 关闭态轨道(color-background-toggle-default)
141    pub toggle_off: Color,
142    /// Slider 轨道底色(color-background-slider-track-default)
143    pub slider_track: Color,
144    /// Slider 拖拽中已填充段(color-background-slider-range-active)
145    pub slider_range_active: Color,
146}
147
148/// 表单控件的**几何**令牌(Checkbox / Radio 的指示器尺寸、描边、焦点环)。
149///
150/// 与 [`ControlStyle`](只管颜色)分开,是为了把两种来源写清楚:
151/// - `border_width` / `focus_ring_*` / `label_gap` 来自 token(`--border-width`、
152///   `--focus-outline-width`、`--focus-outline-offset`、`--spacing-2`),改 token 就该跟着变;
153/// - `indicator_size` 是 Astryx **组件 CSS 里的常量**(Checkbox / Radio 指示器实测 24×24),
154///   Astryx 自己也没有为它设 token,所以这里是有出处的常量,不伪装成 token。
155///   出处与测量方式见 `crates/mgui-core/src/theme/tokens.rs`。
156#[derive(Debug, Clone, Copy, PartialEq)]
157pub struct ControlGeometry {
158    /// Checkbox / Radio 指示器边长,见 [`MGUI_INDICATOR_SIZE`](Astryx 原值 24,mgui 取 18)。
159    pub indicator_size: f32,
160    /// 指示器描边宽度(`--border-width`)。
161    pub border_width: f32,
162    /// 指示器与标签的间距(`--spacing-2`)。
163    pub label_gap: f32,
164    /// 焦点环线宽(`--focus-outline-width`)。
165    pub focus_ring_width: f32,
166    /// 焦点环与控件之间的间隙(`--focus-outline-offset`)。
167    pub focus_ring_offset: f32,
168    /// 指示器圆角:Checkbox 用 `--radius-inner`;Radio 画成正圆(边长一半)。
169    pub indicator_radius: f32,
170    /// 按钮三档高度(**token 驱动**:`--size-element-sm/md/lg`,Astryx 实测 Button/IconButton 就是按档取)。
171    pub button_height_sm: f32,
172    pub button_height_md: f32,
173    pub button_height_lg: f32,
174    /// 按钮水平内距(`--spacing-3`,Astryx Button 实测 12px)。
175    pub button_padding_h: f32,
176    /// 按钮描边宽度(`--border-width`;以前组件里写死 1.5)。
177    pub button_border_width: f32,
178    /// Toggle 轨道尺寸与滑块(Astryx 组件 CSS 实测 40×24、滑块 20、内缩 2)。
179    pub switch_width: f32,
180    pub switch_height: f32,
181    pub switch_thumb: f32,
182    pub switch_thumb_inset: f32,
183    /// Slider 轨道粗细与滑块边长(Astryx 实测 4 / 20;滑块色是 `--color-icon-primary`)。
184    pub slider_track_height: f32,
185    pub slider_thumb_size: f32,
186}
187
188impl Default for ControlGeometry {
189    /// 默认档(token 取基表值,指示器尺寸见 [`MGUI_INDICATOR_SIZE`])
190    fn default() -> Self {
191        Self {
192            indicator_size: MGUI_INDICATOR_SIZE,
193            border_width: 1.0,
194            label_gap: 8.0,
195            focus_ring_width: 2.0,
196            focus_ring_offset: 3.0,
197            switch_width: 40.0,
198            switch_height: 24.0,
199            switch_thumb: 20.0,
200            switch_thumb_inset: 2.0,
201            slider_track_height: 4.0,
202            slider_thumb_size: 20.0,
203            indicator_radius: 4.0,
204            button_height_sm: 28.0,
205            button_height_md: 32.0,
206            button_height_lg: 36.0,
207            button_padding_h: 12.0,
208            button_border_width: 1.0,
209        }
210    }
211}
212
213impl ControlGeometry {
214    /// 按档取按钮高度:0 = sm、1 = md、2 = lg(越界按 lg 收)。
215    ///
216    /// 组件侧的 `ButtonSize` 只负责把枚举映射成下标,高度本身仍来自 token,
217    /// 这样 `--size-element-md` 一改,Button 和 IconButton 会一起动。
218    pub fn button_height_at(&self, which: usize) -> f32 {
219        match which {
220            0 => self.button_height_sm,
221            1 => self.button_height_md,
222            _ => self.button_height_lg,
223        }
224    }
225}
226
227/// Checkbox / Radio 指示器边长。
228///
229/// **这是对 Astryx 的有意偏离**:Astryx 组件 CSS 实测是 24×24
230/// (见 `crates/mgui-core/src/theme/tokens.rs`),但它配的是自己的行高与间距语境;
231/// mgui 正文默认 14px,24 的盒子压在 14px 文字旁边比例失衡(真机反馈"太大、跟文字不衬"),
232/// 所以这里取 18。要回到 Astryx 原值只改这一个常量即可。
233pub const MGUI_INDICATOR_SIZE: f32 = 18.0;
234
235/// sRGB 相对亮度(WCAG 2.x 定义)。
236fn luminance(color: Color) -> f32 {
237    let channel = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
238    0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
239}
240
241/// 反色容器(Tooltip 这类"底色用 `--color-background-inverted`"的小块)上该写哪种前景。
242///
243/// Astryx 用 `--color-on-dark` / `--color-on-light` 两个 token 表达这件事,按底色明暗二选一。
244fn best_on(tokens: &Tokens, background: Color) -> Color {
245    use crate::theme::tokens::ColorToken;
246    // 暗底用 --color-on-dark,亮底用 --color-on-light
247    if luminance(background) < 0.5 {
248        tokens.color(ColorToken::OnDark)
249    } else {
250        tokens.color(ColorToken::OnLight)
251    }
252}
253
254#[derive(Debug, Clone, PartialEq)]
255pub struct ScrollbarStyle {
256    pub thumb_color: Color,
257    /// 指针悬停(或拖拽中)在 thumb 上时的高亮色
258    pub thumb_hover_color: Color,
259    pub thumb_radius: f32,
260    /// 交叉轴上的可见宽度(命中带由 `scrollbar_bands` 从它推出来)
261    pub thumb_width: f32,
262    /// 交叉轴命中带的最小宽度;比 `thumb_width` 窄时不会裁掉可见 thumb
263    pub hit_width: f32,
264    /// 主轴 thumb 长度下限(长列表真正决定 thumb 长短的是这个,见 `MIN_VISIBLE_RATIO`)
265    pub thumb_min_size: f32,
266}
267
268/// TextField / 输入框样式(描边输入框 + 主色焦点环,颜色全部来自 `--color-*`)。
269#[derive(Debug, Clone, PartialEq)]
270pub struct InputStyle {
271    pub background: Color,
272    pub border: Color,
273    pub focused_border: Color,
274    pub text_color: Color,
275    pub placeholder_color: Color,
276    pub radius: f32,
277}
278
279/// Tooltip 浮层样式。
280#[derive(Debug, Clone, PartialEq)]
281pub struct TooltipStyle {
282    pub background: Color,
283    pub foreground: Color,
284    pub border: Color,
285    pub radius: f32,
286}
287
288/// 菜单 / 右键 ContextMenu / 下拉列表样式。
289#[derive(Debug, Clone, PartialEq)]
290pub struct MenuStyle {
291    pub background: Color,
292    pub foreground: Color,
293    pub hover_background: Color,
294    pub border: Color,
295    pub radius: f32,
296}
297
298/// TabBar / TabView / TabbedPane 样式。
299#[derive(Debug, Clone, PartialEq)]
300pub struct TabStyle {
301    pub background: Color,
302    pub active_foreground: Color,
303    pub inactive_foreground: Color,
304    pub hover_background: Color,
305    pub indicator_color: Color,
306}
307
308/// NavigationMenu 样式。
309#[derive(Debug, Clone, PartialEq)]
310pub struct NavStyle {
311    pub active_background: Color,
312    pub active_foreground: Color,
313    pub foreground: Color,
314    pub hover_background: Color,
315    pub indicator_color: Color,
316}
317
318/// 反馈类组件样式(进度条 / Toast 等)。
319#[derive(Debug, Clone, PartialEq)]
320pub struct FeedbackStyle {
321    pub progress_track: Color,
322    pub progress_value: Color,
323    pub success: Color,
324    pub warning: Color,
325    /// 信息态强调色(Toast Info 等)
326    pub info: Color,
327    /// 错误态强调色(与全局 `error` 同源,供状态容器统一取用)
328    pub error: Color,
329}
330
331/// Dropdown 触发器 + 弹出面板样式。
332#[derive(Debug, Clone, PartialEq)]
333pub struct DropdownStyle {
334    pub background: Color,
335    pub foreground: Color,
336    pub placeholder: Color,
337    pub border: Color,
338    pub open_border: Color,
339    pub hover: Color,
340    pub selected_background: Color,
341    pub disabled: Color,
342}
343
344/// Dialog 遮罩 + 对话框样式。
345#[derive(Debug, Clone, PartialEq)]
346pub struct DialogStyle {
347    pub barrier: Color,
348    pub background: Color,
349    pub radius: f32,
350}
351
352/// ListView / 列表类样式。
353#[derive(Debug, Clone, PartialEq)]
354pub struct ListStyle {
355    pub hover_background: Color,
356    pub selected_background: Color,
357    pub foreground: Color,
358}
359
360/// 4pt 间距刻度 + 组件默认间距(由 `--spacing-*` 生成)。
361#[derive(Debug, Clone, PartialEq)]
362pub struct SpacingScale {
363    /// 2 — 徽标/gap 微调
364    pub xxs: f32,
365    /// 4 — 图标与文字
366    pub xs: f32,
367    /// 8 — 控件内边距 / 紧凑 gap
368    pub s: f32,
369    /// 16 — 容器内边距 / 常规 gap
370    pub m: f32,
371    /// 24 — 区块间距
372    pub l: f32,
373    /// 32 — 页面级间距
374    pub xl: f32,
375    /// 叶子控件默认内边距
376    pub control_padding: f32,
377    /// 容器默认内边距
378    pub container_padding: f32,
379    /// 容器未显式指定 gap 时的默认子项间距
380    pub container_gap: f32,
381}
382
383impl Default for SpacingScale {
384    fn default() -> Self {
385        Self {
386            xxs: 2.0,
387            xs: 4.0,
388            s: 8.0,
389            m: 16.0,
390            l: 24.0,
391            xl: 32.0,
392            control_padding: 8.0,
393            container_padding: 16.0,
394            container_gap: 8.0,
395        }
396    }
397}
398
399/// 主题色板 + 子主题。
400///
401/// 所有 `update_should_notify` 走 `PartialEq` 派生自动比较。
402///
403/// 风格基准:**Astryx Design System 的 `Neutral` 主题**
404/// ([`tokens`] 层的基表 + scale + 覆盖 → [`ThemeData::from_tokens`];
405/// `dark()` / `light()` 是 `neutral(true)` / `neutral(false)` 的别名)。
406///
407/// 想改主题就改 token:`define_theme().token("--color-accent", "#7B61FF")`
408/// 或 `radius_multiplier(1.5)`,再 `ThemeData::from_tokens(&def.resolve(dark))`。
409/// 通用令牌(border / divider / hover)供全部组件共享,做到"一次改 token、全局换肤"。
410#[derive(Debug, Clone, PartialEq)]
411pub struct ThemeData {
412    // --- ColorScheme (core) ---
413    pub background: Color,
414    pub foreground: Color,
415    pub primary: Color,
416    pub accent: Color,
417    pub surface: Color,
418    pub error: Color,
419    /// 高对比度变体标记(由 [`ThemeData::high_contrast`] 设置)。
420    pub high_contrast: bool,
421
422    // --- 通用令牌(全组件共享) ---
423    pub border: Color,    // 组件描边
424    pub divider: Color,   // Divider / 分隔线
425    pub hover: Color,     // hover 覆盖层(带 alpha)
426    pub disabled: Color,  // 禁用态前景(或带 alpha 覆盖)
427    pub selection: Color, // 文本/列表选中背景(primary 系 alpha)
428    pub icon: Color,      // 图标默认 tint
429
430    // --- Radius ---
431    pub radius_sm: f32, // 4.0 — badge / checkbox
432    pub radius_md: f32, // 8.0 — input / item
433    pub radius_lg: f32, // 16.0 — dialog / menu / large container
434
435    // --- Spacing ---
436    pub spacing: f32, // 8.0 — default widget spacing
437    /// 4pt 间距刻度与组件默认间距
438    pub space: SpacingScale,
439
440    // --- Sub-themes ---
441    pub text: TextTheme,
442    pub button: ButtonStyle,
443    /// 按钮语义变体色板(Primary/Normal/Tertiary/Success/Warning/Error/Info)
444    pub button_variants: ButtonVariants,
445    /// Avatar 首字头像样式
446    pub avatar: AvatarStyle,
447    /// 表单控件令牌(Checkbox/Radio/Toggle/Slider)
448    pub control: ControlStyle,
449    /// 表单控件几何(指示器尺寸 / 描边 / 焦点环),见 [`ControlGeometry`]
450    pub geom: ControlGeometry,
451    pub scrollbar: ScrollbarStyle,
452    pub input: InputStyle,
453    pub tooltip: TooltipStyle,
454    pub menu: MenuStyle,
455    pub tab: TabStyle,
456    pub nav: NavStyle,
457    pub feedback: FeedbackStyle,
458    pub dropdown: DropdownStyle,
459    pub dialog: DialogStyle,
460    pub list: ListStyle,
461}
462
463impl Default for ThemeData {
464    fn default() -> Self {
465        Self::neutral_dark()
466    }
467}
468
469impl ThemeData {
470    /// 深色主题(Astryx `Neutral` 暗档)。
471    pub fn dark() -> Self {
472        Self::neutral_dark()
473    }
474
475    /// 浅色主题(Astryx `Neutral` 明档)。
476    pub fn light() -> Self {
477        Self::neutral_light()
478    }
479    /// Astryx `Neutral` 主题 —— 由 [`tokens`] 层的基表 + scale + 覆盖解析而来。
480    ///
481    /// `dark=true` 取每个 `light-dark(明, 暗)` 的暗档。
482    pub fn neutral(dark: bool) -> Self {
483        Self::from_tokens(&crate::theme::tokens::define_theme().resolve(dark))
484    }
485
486    pub fn neutral_light() -> Self {
487        Self::neutral(false)
488    }
489
490    pub fn neutral_dark() -> Self {
491        Self::neutral(true)
492    }
493
494    /// 由一份已解析的 token 集推导组件用的 `ThemeData`。
495    ///
496    /// 这是"主题修改功能"的落点:应用改任意 token(`define_theme().token(...)`),
497    /// 这里就把整套子主题重算一遍。映射原则:
498    ///
499    /// - 每个颜色都能追溯到一个 `--color-*`,本地不做调色(不再混色、不再硬编码 hex);
500    /// - hover / pressed 是**叠加层**,先与所在容器色合成再填(见 [`tokens::overlay`]);
501    /// - 圆角、控件高度、间距、字号全部走 token,所以 radius / 密度 / 字号 scale 会整体生效;
502    /// - 状态色用 `--color-text-*`(保证在容器上的对比度),填充按钮用 `--color-*` + `--color-on-*`。
503    pub fn from_tokens(tokens: &Tokens) -> Self {
504        use crate::theme::tokens::{ColorToken as C, SpacingStep as S, TextRole as R};
505
506        let color = |token: C| tokens.color(token);
507        let radius = tokens.radius();
508        let focus = tokens.focus();
509        let surface = color(C::BackgroundSurface);
510        let popover = color(C::BackgroundPopover);
511        let accent = color(C::Accent);
512
513        let filled_variant = |fill: C, on: C| ButtonVariantStyle {
514            background: color(fill),
515            foreground: color(on),
516            border: Color::TRANSPARENT,
517            hover_background: tokens.hovered(color(fill)),
518            pressed_background: tokens.pressed(color(fill)),
519        };
520        let button_variants = ButtonVariants {
521            primary: filled_variant(C::Accent, C::OnAccent),
522            normal: ButtonVariantStyle {
523                background: surface,
524                foreground: color(C::TextPrimary),
525                border: color(C::BorderEmphasized),
526                hover_background: tokens.hovered(surface),
527                pressed_background: tokens.pressed(surface),
528            },
529            tertiary: ButtonVariantStyle {
530                background: Color::TRANSPARENT,
531                foreground: color(C::TextPrimary),
532                border: Color::TRANSPARENT,
533                hover_background: color(C::OverlayHover),
534                pressed_background: color(C::OverlayPressed),
535            },
536            success: filled_variant(C::Success, C::OnSuccess),
537            warning: filled_variant(C::Warning, C::OnWarning),
538            error: filled_variant(C::Error, C::OnError),
539            info: filled_variant(C::Info, C::OnInfo),
540        };
541
542        // Astryx 的 Tooltip 是反色小块,前景按底色明暗取 --color-on-dark / --color-on-light
543        let tooltip_bg = color(C::BackgroundInverted);
544        let body = tokens.text_role(R::Body);
545        let heading = tokens.text_role(R::HeadingTwo);
546        let text = TextTheme {
547            headline: TextStyleTheme { font_size: tokens.text_role(R::HeadingOne).size, color: color(C::TextPrimary) },
548            title: TextStyleTheme { font_size: heading.size, color: color(C::TextPrimary) },
549            body: TextStyleTheme { font_size: body.size, color: color(C::TextPrimary) },
550            caption: TextStyleTheme { font_size: tokens.text_role(R::Supporting).size, color: color(C::TextSecondary) },
551        };
552
553        let track = color(C::Track);
554        let scrollbar = ScrollbarStyle {
555            thumb_color: track,
556            thumb_hover_color: color(C::BorderEmphasized),
557            thumb_radius: radius.inner,
558            // 可见 8px(--spacing-2)/ 命中 10px,外沿再留 2px 视觉空隙 —— 带的算法在 scrollbar_bands
559            thumb_width: tokens.spacing(S::S2),
560            hit_width: tokens.spacing(S::S2) + 2.0,
561            // 长列表里 thumb 长度实际由这个下限决定(--spacing-6 = 24px)
562            thumb_min_size: tokens.spacing(S::S6),
563        };
564
565        // 按钮三档高度是真 token(--size-element-sm/md/lg)
566        let size = tokens.element_size();
567
568        Self {
569            background: color(C::BackgroundBody),
570            foreground: color(C::TextPrimary),
571            primary: accent,
572            accent: color(C::TextAccent),
573            surface,
574            error: color(C::TextError),
575            high_contrast: false,
576            border: color(C::Border),
577            divider: color(C::Border),
578            hover: color(C::OverlayHover),
579            disabled: color(C::TextDisabled),
580            selection: color(C::AccentMuted),
581            icon: color(C::IconPrimary),
582            radius_sm: radius.inner,
583            radius_md: radius.element,
584            radius_lg: radius.container,
585            spacing: tokens.spacing(S::S2),
586            space: SpacingScale {
587                xxs: tokens.spacing(S::S0_5),
588                xs: tokens.spacing(S::S1),
589                s: tokens.spacing(S::S2),
590                m: tokens.spacing(S::S4),
591                l: tokens.spacing(S::S6),
592                xl: tokens.spacing(S::S8),
593                control_padding: tokens.spacing(S::S2),
594                container_padding: tokens.spacing(S::S4),
595                container_gap: tokens.spacing(S::S2),
596            },
597            text,
598            button: ButtonStyle {
599                background: accent,
600                foreground: color(C::OnAccent),
601                radius: radius.element,
602                focus_ring_color: focus.color,
603                focus_ring_width: focus.width,
604            },
605            button_variants,
606            avatar: AvatarStyle {
607                // Astryx Avatar 按名字哈希在分类色里轮换,前景用反色档
608                palette: [
609                    color(C::DataCategoricalBlue),
610                    color(C::DataCategoricalGreen),
611                    color(C::DataCategoricalOrange),
612                    color(C::DataCategoricalPurple),
613                    color(C::DataCategoricalRed),
614                    color(C::DataCategoricalTeal),
615                ],
616                foreground: color(C::OnAccent),
617            },
618            control: ControlStyle {
619                background: surface,
620                border: color(C::BorderEmphasized),
621                checked_background: accent,
622                checked_foreground: color(C::OnAccent),
623                disabled_background: color(C::BackgroundMuted),
624                disabled_border: color(C::Border),
625                toggle_off: track,
626                slider_track: track,
627                slider_range_active: accent,
628            },
629            geom: ControlGeometry {
630                // 组件常量:见 MGUI_INDICATOR_SIZE(Astryx 原值 24,这里有意收到 18 以配 14px 正文)
631                indicator_size: MGUI_INDICATOR_SIZE,
632                border_width: tokens.border_width(),
633                label_gap: tokens.spacing(S::S2),
634                focus_ring_width: focus.width,
635                focus_ring_offset: focus.offset,
636                indicator_radius: radius.inner,
637                // Toggle / Slider 的尺寸同样是 Astryx 组件 CSS 实测常量(见 theme-tokens.md 规格表)
638                switch_width: 40.0,
639                switch_height: 24.0,
640                switch_thumb: 20.0,
641                switch_thumb_inset: 2.0,
642                slider_track_height: 4.0,
643                slider_thumb_size: 20.0,
644                // 按钮这三档是真 token:element_size() / --spacing-3 / --border-width
645                button_height_sm: size.sm,
646                button_height_md: size.md,
647                button_height_lg: size.lg,
648                button_padding_h: tokens.spacing(S::S3),
649                button_border_width: tokens.border_width(),
650            },
651            scrollbar,
652            input: InputStyle {
653                background: surface,
654                border: color(C::BorderEmphasized),
655                focused_border: focus.color,
656                text_color: color(C::TextPrimary),
657                placeholder_color: color(C::TextSecondary),
658                radius: radius.element,
659            },
660            tooltip: TooltipStyle {
661                background: tooltip_bg,
662                foreground: best_on(tokens, tooltip_bg),
663                border: Color::TRANSPARENT,
664                radius: radius.element,
665            },
666            menu: MenuStyle {
667                background: popover,
668                foreground: color(C::TextPrimary),
669                hover_background: tokens.hovered(popover),
670                border: color(C::Border),
671                radius: radius.container,
672            },
673            tab: TabStyle {
674                background: surface,
675                active_foreground: color(C::TextPrimary),
676                inactive_foreground: color(C::TextSecondary),
677                hover_background: tokens.hovered(surface),
678                indicator_color: accent,
679            },
680            nav: NavStyle {
681                active_background: color(C::AccentMuted),
682                active_foreground: color(C::TextAccent),
683                foreground: color(C::TextPrimary),
684                hover_background: tokens.hovered(surface),
685                indicator_color: accent,
686            },
687            feedback: FeedbackStyle {
688                progress_track: track,
689                progress_value: accent,
690                success: color(C::TextSuccess),
691                warning: color(C::TextWarning),
692                info: color(C::TextInfo),
693                error: color(C::TextError),
694            },
695            dropdown: DropdownStyle {
696                background: popover,
697                foreground: color(C::TextPrimary),
698                placeholder: color(C::TextSecondary),
699                border: color(C::BorderEmphasized),
700                open_border: focus.color,
701                hover: tokens.hovered(popover),
702                selected_background: color(C::AccentMuted),
703                disabled: color(C::TextDisabled),
704            },
705            dialog: DialogStyle {
706                barrier: color(C::Overlay),
707                background: color(C::BackgroundCard),
708                radius: radius.container,
709            },
710            list: ListStyle {
711                hover_background: tokens.hovered(surface),
712                selected_background: color(C::AccentMuted),
713                foreground: color(C::TextPrimary),
714            },
715        }
716    }
717
718    /// 高对比度主题(Windows 高对比度 / 强制对比模式的通用替代)。
719    ///
720    /// 与 `neutral` 走同一条路:**只覆盖 token**,所有子主题由 [`ThemeData::from_tokens`]
721    /// 一起重算,不再逐个字段覆写。强制的内容:
722    /// - 前景/背景 ≥ 7:1,边框/背景 ≥ 3:1,主色/背景 ≥ 4.5:1;
723    /// - 关键文本使用纯黑/纯白,边框与分割线使用前景色;
724    /// - `--radius-*` 归零、`--focus-outline-width` 提到 3px,便于低视力用户辨识;
725    /// - hover / 选中改用高 alpha 叠加层,不再用低对比的 muted 档。
726    ///
727    /// `dark=true` 为黑底白字/金黄主色;`false` 为白底黑字/深蓝主色。
728    /// 系统高对比度色板由平台提供时,应用仍可自行替换核心令牌。
729    pub fn high_contrast(dark: bool) -> Self {
730        use crate::theme::tokens::ColorToken as C;
731
732        let (bg, fg, dim, primary, on_primary, focus, info, error, success, warning, hover, selection, barrier) =
733            if dark {
734                (
735                    Color::BLACK,
736                    Color::WHITE,
737                    Color::from_rgb8(0xB0, 0xB0, 0xB0),
738                    Color::from_rgb8(0xFF, 0xD7, 0x00),
739                    Color::BLACK,
740                    Color::WHITE,
741                    Color::from_rgb8(0x00, 0xFF, 0xFF),
742                    Color::from_rgb8(0xFF, 0x80, 0x80),
743                    Color::from_rgb8(0x7C, 0xFC, 0x7C),
744                    Color::from_rgb8(0xFF, 0xD7, 0x00),
745                    Color::rgba(1.0, 1.0, 1.0, 0.20),
746                    Color::rgba(1.0, 0.843, 0.0, 0.35),
747                    Color::rgba(0.0, 0.0, 0.0, 0.85),
748                )
749            } else {
750                (
751                    Color::WHITE,
752                    Color::BLACK,
753                    Color::from_rgb8(0x50, 0x50, 0x50),
754                    Color::from_rgb8(0x00, 0x33, 0xCC),
755                    Color::WHITE,
756                    Color::BLACK,
757                    Color::from_rgb8(0x00, 0x5A, 0x5A),
758                    Color::from_rgb8(0xB0, 0x00, 0x20),
759                    Color::from_rgb8(0x00, 0x64, 0x00),
760                    Color::from_rgb8(0x7A, 0x4F, 0x00),
761                    Color::rgba(0.0, 0.0, 0.0, 0.12),
762                    Color::rgba(0.0, 0.2, 0.8, 0.18),
763                    Color::rgba(0.0, 0.0, 0.0, 0.60),
764                )
765            };
766
767        let mut def = define_theme().named("high-contrast");
768        for (token, color) in [
769            // 所有容器拉平到同一底色:高对比度下层次靠描边表达,不靠背景明暗
770            (C::BackgroundBody, bg),
771            (C::BackgroundSurface, bg),
772            (C::BackgroundCard, bg),
773            (C::BackgroundPopover, bg),
774            (C::BackgroundMuted, bg),
775            (C::BackgroundInverted, fg),
776            (C::TextPrimary, fg),
777            (C::TextSecondary, dim),
778            (C::TextDisabled, dim),
779            (C::TextAccent, primary),
780            (C::TextInfo, info),
781            (C::TextSuccess, success),
782            (C::TextWarning, warning),
783            (C::TextError, error),
784            (C::IconPrimary, fg),
785            (C::IconSecondary, dim),
786            (C::IconDisabled, dim),
787            (C::Accent, primary),
788            (C::AccentMuted, selection),
789            (C::OnAccent, on_primary),
790            (C::Info, info),
791            (C::OnInfo, on_primary),
792            (C::Success, success),
793            (C::OnSuccess, on_primary),
794            (C::Warning, warning),
795            (C::OnWarning, on_primary),
796            (C::Error, error),
797            (C::OnError, on_primary),
798            (C::Border, fg),
799            (C::BorderEmphasized, fg),
800            (C::BorderInfo, info),
801            (C::BorderSuccess, success),
802            (C::BorderWarning, warning),
803            (C::BorderError, error),
804            (C::OverlayHover, hover),
805            (C::OverlayPressed, hover),
806            (C::Overlay, barrier),
807            (C::Track, dim),
808            (C::Skeleton, dim),
809            (C::Shadow, bg),
810            (C::FocusOutline, focus),
811            // Avatar 轮换池换成低亮度底,保证 on-dark 白字仍可读
812            (C::DataCategoricalBlue, Color::from_rgb8(0x00, 0x50, 0x80)),
813            (C::DataCategoricalGreen, Color::from_rgb8(0x00, 0x50, 0x00)),
814            (C::DataCategoricalOrange, Color::from_rgb8(0x6B, 0x2A, 0x00)),
815            (C::DataCategoricalPurple, Color::from_rgb8(0x3B, 0x00, 0x80)),
816            (C::DataCategoricalRed, Color::from_rgb8(0x90, 0x00, 0x00)),
817            (C::DataCategoricalTeal, Color::from_rgb8(0x00, 0x4A, 0x4A)),
818        ] {
819            def.set_color(token, color, color);
820        }
821        for name in [
822            "--radius-inner",
823            "--radius-element",
824            "--radius-container",
825            "--radius-page",
826            "--radius-chat",
827            "--focus-outline-width",
828        ] {
829            let value = if name == "--focus-outline-width" { "3px" } else { "0px" };
830            def.set_token(name, value).expect("内置 token 名与形状必然合法");
831        }
832
833        let mut theme = Self::from_tokens(&def.resolve(dark));
834        theme.high_contrast = true;
835        theme
836    }
837}
838
839// =================================================================
840// Direction — 文本方向(Ltr / Rtl)
841// =================================================================
842
843#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
844pub enum Direction {
845    #[default]
846    Ltr,
847    Rtl,
848}
849
850// =================================================================
851// ThemeWidget + InheritedWidget impl
852// =================================================================
853
854/// 用户显式颜色优先,否则回退到主题/token 值。
855///
856/// P1-8:用 `Option` 表达"未覆盖",不再依赖与默认色相等的 sentinel 判断
857/// (用户显式选择与哨兵相同的颜色时也能正确覆盖)。
858pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
859    match explicit {
860        Some(color) => color,
861        None => themed,
862    }
863}
864
865/// 数值版 `resolve_color`:显式尺寸/宽度优先,否则用主题/回退值。
866pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
867    match explicit {
868        Some(value) => value,
869        None => themed,
870    }
871}
872
873/// Theme 提供者 widget。挂到树中,所有后代可通过 `ctx.theme()` 访问。
874///
875/// `theme` 用 `Rc` 共享:State 缓存主题时只 clone 引用,不再复制整份 ThemeData。
876#[derive(Debug)]
877pub struct ThemeWidget {
878    pub theme: Rc<ThemeData>,
879    pub direction: Direction,
880    pub child: Option<WidgetNode>,
881}
882
883impl ThemeWidget {
884    pub fn new(theme: ThemeData) -> Self {
885        Self::from_rc(Rc::new(theme))
886    }
887
888    pub fn from_rc(theme: Rc<ThemeData>) -> Self {
889        Self { theme, direction: Direction::Ltr, child: None }
890    }
891
892    pub fn dark() -> Self {
893        Self::new(ThemeData::dark())
894    }
895
896    pub fn light() -> Self {
897        Self::new(ThemeData::light())
898    }
899
900    pub fn with_direction(mut self, d: Direction) -> Self {
901        self.direction = d;
902        self
903    }
904
905    pub fn child(mut self, c: impl Widget) -> Self {
906        self.child = Some(WidgetNode::new(c));
907        self
908    }
909
910    pub fn child_node(mut self, c: WidgetNode) -> Self {
911        self.child = Some(c);
912        self
913    }
914}
915
916impl InheritedWidget for ThemeWidget {
917    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
918        // downcast old 到 ThemeWidget 比较 theme + direction
919        if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
920            if Rc::ptr_eq(&self.theme, &old_theme.theme) {
921                return self.direction != old_theme.direction;
922            }
923            *self.theme != *old_theme.theme || self.direction != old_theme.direction
924        } else {
925            true
926        }
927    }
928
929    fn as_any(&self) -> &dyn Any {
930        self
931    }
932}
933
934impl ThemeWidget {
935    pub fn theme(&self) -> &ThemeData {
936        &self.theme
937    }
938
939    pub fn direction(&self) -> Direction {
940        self.direction
941    }
942}
943
944impl Widget for ThemeWidget {
945    fn as_any(&self) -> &dyn Any {
946        self
947    }
948
949    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
950        Some(self)
951    }
952
953    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
954        // 透传 child RO,但必须**包一层 ProxyRenderObject**:
955        // 直接把 child widget 的 RO 树当自己的 RO,会让 element 树(1 个 child)
956        // 与 RO 树(child 的整棵子树)不同构;propagate 只能按索引替换前 N 个 slot,
957        // 其余 slot 成为陈旧副本(Theme 根节点会重复绘制 nested boundary)。
958        match &self.child {
959            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
960            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
961        }
962    }
963
964    fn children(&self) -> Vec<WidgetNode> {
965        self.child.clone().into_iter().collect()
966    }
967
968    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
969        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
970    }
971}
972
973// =================================================================
974// DirectionWidget — 单独暴露 direction(如果只想用 Direction 不想用 Theme)
975// =================================================================
976
977/// 单独的 Direction 提供者,方便只想换方向不换主题的场景。
978#[derive(Debug)]
979pub struct DirectionWidget {
980    pub direction: Direction,
981    pub child: Option<WidgetNode>,
982}
983
984impl DirectionWidget {
985    pub fn new(d: Direction) -> Self {
986        Self { direction: d, child: None }
987    }
988
989    pub fn child(mut self, c: impl Widget) -> Self {
990        self.child = Some(WidgetNode::new(c));
991        self
992    }
993}
994
995impl InheritedWidget for DirectionWidget {
996    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
997        if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
998            self.direction != old_dir.direction
999        } else {
1000            true
1001        }
1002    }
1003
1004    fn as_any(&self) -> &dyn Any {
1005        self
1006    }
1007}
1008
1009impl DirectionWidget {
1010    pub fn direction(&self) -> Direction {
1011        self.direction
1012    }
1013}
1014
1015impl Widget for DirectionWidget {
1016    fn as_any(&self) -> &dyn Any {
1017        self
1018    }
1019
1020    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
1021        Some(self)
1022    }
1023
1024    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
1025        // 与 ThemeWidget 相同:透传 child 必须包 Proxy,保证 element/RO 同构。
1026        match &self.child {
1027            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
1028            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
1029        }
1030    }
1031
1032    fn children(&self) -> Vec<WidgetNode> {
1033        self.child.clone().into_iter().collect()
1034    }
1035
1036    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
1037        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
1038    }
1039}
1040
1041// =================================================================
1042// LocaleSnapshot / LocaleWidget — 运行时语言切换(0.7)
1043// =================================================================
1044
1045/// 应用级语言快照。只存 BCP-47 子集 tag,不依赖 i18n crate;`mgui-i18n` 负责解析/格式化。
1046#[derive(Debug, Clone, PartialEq, Eq)]
1047pub struct LocaleSnapshot {
1048    pub tag: Rc<str>,
1049    pub direction: Direction,
1050    /// 每次真实语言变化推进;同 tag 重复设置不 bump。用于精准失效文案/RTL 布局。
1051    pub generation: u64,
1052}
1053
1054impl LocaleSnapshot {
1055    pub fn new(tag: impl Into<Rc<str>>, direction: Direction, generation: u64) -> Self {
1056        Self { tag: tag.into(), direction, generation }
1057    }
1058
1059    pub fn tag(&self) -> &str {
1060        &self.tag
1061    }
1062}
1063
1064/// 语言提供者。切换语言时替换 `LocaleWidget`,后代通过 `ctx.locale()` 自动 dirty。
1065#[derive(Debug)]
1066pub struct LocaleWidget {
1067    pub locale: LocaleSnapshot,
1068    pub child: Option<WidgetNode>,
1069}
1070
1071impl LocaleWidget {
1072    pub fn new(locale: LocaleSnapshot) -> Self {
1073        Self { locale, child: None }
1074    }
1075
1076    pub fn child_node(mut self, c: WidgetNode) -> Self {
1077        self.child = Some(c);
1078        self
1079    }
1080
1081    pub fn locale(&self) -> &LocaleSnapshot {
1082        &self.locale
1083    }
1084}
1085
1086impl InheritedWidget for LocaleWidget {
1087    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
1088        old.as_any().downcast_ref::<LocaleWidget>().map(|old| self.locale != old.locale).unwrap_or(true)
1089    }
1090
1091    fn as_any(&self) -> &dyn Any {
1092        self
1093    }
1094}
1095
1096impl Widget for LocaleWidget {
1097    fn as_any(&self) -> &dyn Any {
1098        self
1099    }
1100
1101    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
1102        Some(self)
1103    }
1104
1105    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
1106        match &self.child {
1107            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
1108            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
1109        }
1110    }
1111
1112    fn children(&self) -> Vec<WidgetNode> {
1113        self.child.clone().into_iter().collect()
1114    }
1115
1116    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
1117        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
1118    }
1119}
1120
1121#[cfg(test)]
1122mod tests {
1123    use super::tokens::{ColorToken as C, FontSizeToken, LengthToken, SpacingStep};
1124    use super::*;
1125    use crate::inherited::InheritedWidget;
1126
1127    #[test]
1128    fn locale_widget_notifies_on_generation_change() {
1129        let a = LocaleWidget::new(LocaleSnapshot::new("en", Direction::Ltr, 1));
1130        let b = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
1131        let same = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
1132        assert!(b.update_should_notify(&a));
1133        assert!(!same.update_should_notify(&b));
1134    }
1135
1136    fn contrast(a: Color, b: Color) -> f32 {
1137        let (la, lb) = (luminance(a), luminance(b));
1138        (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
1139    }
1140
1141    /// 用 token 覆盖生成一份主题,再推导 ThemeData。
1142    fn themed(definition: tokens::ThemeDefinition, dark: bool) -> ThemeData {
1143        ThemeData::from_tokens(&definition.resolve(dark))
1144    }
1145
1146    #[test]
1147    fn neutral_palette_matches_astryx_tokens() {
1148        let light = ThemeData::neutral_light();
1149        assert_eq!(light.primary, Color::from_rgb8(0x00, 0x64, 0xE0));
1150        assert_eq!(light.background, Color::from_rgb8(0xF1, 0xF4, 0xF7));
1151        assert_eq!(light.surface, Color::WHITE);
1152        assert_eq!(light.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
1153        assert_eq!(light.button.foreground, Color::WHITE);
1154        assert_eq!(light.button.radius, 8.0, "Astryx 按钮用 --radius-element");
1155        assert_eq!(light.input.radius, 8.0);
1156        assert_eq!(light.dialog.radius, 12.0, "Astryx 容器用 --radius-container");
1157
1158        let dark = ThemeData::neutral_dark();
1159        assert_eq!(dark.primary, Color::from_rgb8(0x26, 0x94, 0xFE));
1160        assert_eq!(dark.background, Color::from_rgb8(0x11, 0x11, 0x12));
1161        assert_eq!(dark.surface, Color::from_rgb8(0x1F, 0x1F, 0x22));
1162        assert_eq!(dark.foreground, Color::from_rgb8(0xDF, 0xE2, 0xE5));
1163        // --color-on-error 在深色档是深字(白字在该底色上达不到 4.5:1)
1164        assert_eq!(dark.button_variants.error.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
1165
1166        // 尺寸与间距全部来自 token,不再散落硬编码
1167        assert_eq!((light.radius_sm, light.radius_md, light.radius_lg), (4.0, 8.0, 12.0));
1168        assert_eq!(light.text.body.font_size, 14.0, "--text-body-size");
1169        assert_eq!(light.text.headline.font_size, 24.0, "--text-heading-1-size");
1170        assert_eq!(light.text.caption.font_size, 12.0, "--text-supporting-size");
1171        assert_eq!(light.spacing, 8.0, "--spacing-2");
1172        assert_eq!(light.scrollbar.thumb_width, 8.0);
1173    }
1174
1175    #[test]
1176    fn aliases_and_default_are_the_same_theme() {
1177        assert_eq!(ThemeData::dark(), ThemeData::neutral(true));
1178        assert_eq!(ThemeData::light(), ThemeData::neutral(false));
1179        assert_eq!(ThemeData::default(), ThemeData::neutral_dark());
1180        assert_ne!(ThemeData::neutral_light(), ThemeData::neutral_dark());
1181    }
1182
1183    /// 按钮三档高度/内距/描边必须是真 token 驱动(#91 的 Button / IconButton 就靠这几条):
1184    /// 改 `--size-element-md`、`--spacing-3`、`--border-width` 都要反映到 `ThemeData::geom`。
1185    #[test]
1186    fn button_metrics_follow_element_spacing_and_border_tokens() {
1187        let base = themed(define_theme(), false);
1188        assert_eq!(
1189            (base.geom.button_height_sm, base.geom.button_height_md, base.geom.button_height_lg),
1190            (28.0, 32.0, 36.0),
1191            "Astryx --size-element-sm/md/lg 默认档"
1192        );
1193        assert_eq!((base.geom.button_padding_h, base.geom.button_border_width), (12.0, 1.0));
1194
1195        let tuned = themed(
1196            define_theme()
1197                .token("--size-element-md", "2.5rem")
1198                .expect("合法 token")
1199                .token("--spacing-3", "1rem")
1200                .expect("合法 token")
1201                .token("--border-width", "2px")
1202                .expect("合法 token"),
1203            false,
1204        );
1205        assert_eq!(tuned.geom.button_height_md, 40.0, "2.5rem = 40px,只有 md 变");
1206        assert_eq!((tuned.geom.button_height_sm, tuned.geom.button_height_lg), (28.0, 36.0));
1207        assert_eq!((tuned.geom.button_padding_h, tuned.geom.button_border_width), (16.0, 2.0));
1208
1209        // 圆角倍率不该动高度(两轴各自独立)
1210        let rounded = themed(define_theme().radius_multiplier(1.5), false);
1211        assert_eq!(rounded.geom.button_height_md, 32.0);
1212        assert!(rounded.geom.indicator_radius > base.geom.indicator_radius);
1213    }
1214
1215    #[test]
1216    fn emphasis_and_focus_all_follow_the_accent_token() {
1217        for t in [ThemeData::neutral_light(), ThemeData::neutral_dark()] {
1218            assert_eq!(t.button.focus_ring_color, t.primary);
1219            assert_eq!(t.tab.indicator_color, t.primary);
1220            assert_eq!(t.nav.indicator_color, t.primary);
1221            assert_eq!(t.feedback.progress_value, t.primary);
1222            assert_eq!(t.dropdown.open_border, t.primary);
1223            assert_eq!(t.input.focused_border, t.primary);
1224            assert_eq!(t.text.body.color, t.foreground);
1225            assert_eq!(t.button.focus_ring_width, 2.0, "--focus-outline-width");
1226        }
1227    }
1228
1229    #[test]
1230    fn button_variants_and_avatar_come_from_status_tokens() {
1231        let light = ThemeData::neutral_light();
1232        assert_eq!(light.button_variants.primary.background, light.primary);
1233        assert_eq!(light.button_variants.primary.foreground, Color::WHITE);
1234        assert_eq!(light.button_variants.tertiary.background, Color::TRANSPARENT);
1235        assert_eq!(light.button_variants.normal.background, light.surface);
1236        assert_ne!(light.button_variants.normal.border, Color::TRANSPARENT, "常规按钮有描边");
1237
1238        let dark = ThemeData::neutral_dark();
1239        assert_eq!(dark.button_variants.success.background, Color::from_rgb8(0x0D, 0x86, 0x26));
1240        assert_eq!(dark.button_variants.error.background, Color::from_rgb8(0xF5, 0x39, 0x4F));
1241        // 状态文本色(--color-text-*)与状态填充色(--color-*)是两套 token
1242        assert_ne!(dark.feedback.success, dark.button_variants.success.background);
1243        assert_eq!(dark.avatar.foreground, Color::WHITE, "分类色上写 --color-on-dark");
1244        let mut seen = std::collections::HashSet::new();
1245        for color in dark.avatar.palette {
1246            let key = ((color.r * 255.0) as i32, (color.g * 255.0) as i32, (color.b * 255.0) as i32);
1247            assert!(seen.insert(key), "Avatar 轮换池不该重复");
1248        }
1249    }
1250
1251    #[test]
1252    fn hover_and_pressed_are_composited_overlays() {
1253        for dark in [false, true] {
1254            let t = ThemeData::neutral(dark);
1255            assert!(t.hover.a < 1.0, "--color-overlay-hover 是带 alpha 的叠加层");
1256            let primary = t.button_variants.primary;
1257            assert_ne!(primary.hover_background, primary.background);
1258            assert_ne!(primary.hover_background, primary.pressed_background, "hover 与 pressed 不同档");
1259            assert!(primary.hover_background.a >= 1.0, "叠加后填色仍是不透明色");
1260            assert_ne!(t.list.hover_background, t.surface);
1261            assert_ne!(t.menu.hover_background, t.dropdown.background);
1262        }
1263    }
1264
1265    #[test]
1266    fn overriding_one_token_restyles_the_whole_tree() {
1267        // 这就是"主题修改功能"的验收点:改 --color-accent 一处,主按钮 / 焦点环 /
1268        // Tab 指示条 / 进度条 / 输入框聚焦边全部跟着变
1269        let base = ThemeData::neutral_dark();
1270        let brand = themed(tokens::define_theme().token("--color-accent", "#7B61FF").unwrap(), true);
1271        let purple = Color::from_rgb8(0x7B, 0x61, 0xFF);
1272        assert_eq!(brand.primary, purple);
1273        assert_eq!(brand.button.background, purple);
1274        assert_eq!(brand.button.focus_ring_color, purple);
1275        assert_eq!(brand.input.focused_border, purple);
1276        assert_eq!(brand.tab.indicator_color, purple);
1277        assert_eq!(brand.nav.indicator_color, purple);
1278        assert_eq!(brand.feedback.progress_value, purple);
1279        assert_eq!(brand.button_variants.primary.hover_background, tokens::overlay(purple, base.hover));
1280        assert_ne!(brand, base);
1281
1282        // 圆角倍率与字号 scale 同样整体生效
1283        let square = themed(tokens::define_theme().radius_multiplier(0.0), false);
1284        assert_eq!((square.radius_sm, square.radius_md, square.radius_lg), (0.0, 0.0, 0.0));
1285        assert_eq!(square.button.radius, 0.0);
1286        assert_eq!(square.dialog.radius, 0.0);
1287        assert_eq!(square.input.radius, 0.0);
1288
1289        let large = themed(tokens::define_theme().text_scale(18.0, 1.2), false);
1290        let large_tokens = tokens::define_theme().text_scale(18.0, 1.2).resolve(false);
1291        assert_eq!(large.text.body.font_size, large_tokens.font_size(FontSizeToken::Base));
1292        assert_eq!(large.text.body.font_size, 18.0);
1293        assert_eq!(large.text.caption.font_size, large_tokens.font_size(FontSizeToken::Sm));
1294        assert_eq!(large.text.caption.font_size, 15.0, "--text-supporting-size = --font-size-sm");
1295
1296        // 密度:把间距 token 拉大一档
1297        let roomy = themed(tokens::define_theme().token("--spacing-2", "12px").unwrap(), false);
1298        assert_eq!(roomy.spacing, 12.0);
1299        assert_eq!(roomy.space.s, 12.0);
1300        assert_eq!(roomy.space.control_padding, 12.0);
1301    }
1302
1303    #[test]
1304    fn status_text_meets_aa_contrast_on_both_surfaces() {
1305        for dark in [false, true] {
1306            let t = ThemeData::neutral(dark);
1307            for (label, color, bg) in [
1308                ("正文/表面", t.foreground, t.surface),
1309                ("次要/表面", t.text.caption.color, t.surface),
1310                ("成功/表面", t.feedback.success, t.surface),
1311                ("警告/表面", t.feedback.warning, t.surface),
1312                ("错误/表面", t.feedback.error, t.surface),
1313                ("信息/表面", t.feedback.info, t.surface),
1314                ("正文/画布", t.foreground, t.background),
1315            ] {
1316                let ratio = contrast(color, bg);
1317                assert!(ratio >= 4.5, "{label} 对比度 {ratio:.2} < 4.5 (dark={dark})");
1318            }
1319        }
1320    }
1321
1322    #[test]
1323    /// 填充按钮的文字对比度按 Astryx 原样保留,这里只做下限守护。
1324    ///
1325    /// Astryx `Neutral` 的 `--color-on-accent` 两档都是白:浅色档白字压 `#0064E0` 有 5.1:1,
1326    /// 深色档白字压 `#2694FE` 只有 **3.1:1**(未达正文 4.5:1,达到大号/加粗文本的 3:1 线)。
1327    /// 这是 Astryx 的设计取舍,mgui 不偷偷改色值;需要 ≥4.5 时用
1328    /// [`ThemeData::high_contrast`](对应 Astryx `color.contrast: high`)。
1329    fn filled_button_label_keeps_the_astryx_contrast_floor() {
1330        let light = ThemeData::neutral_light();
1331        assert!(contrast(light.button.foreground, light.button.background) >= 4.5, "浅色档主按钮应达 4.5:1");
1332        let dark = ThemeData::neutral_dark();
1333        let ratio = contrast(dark.button.foreground, dark.button.background);
1334        assert!(ratio >= 3.0, "深色档主按钮文字对比度 {ratio:.2} < 3.0(Astryx 原值即 3.11)");
1335        // 高对比度主题必须补到 4.5 以上
1336        let hc = ThemeData::high_contrast(true);
1337        assert!(contrast(hc.button.foreground, hc.button.background) >= 4.5, "高对比度档主按钮不足 4.5:1");
1338    }
1339
1340    #[test]
1341    fn overlay_tokens_are_visible_on_their_own_container() {
1342        for dark in [false, true] {
1343            let tokens = tokens::define_theme().resolve(dark);
1344            let surface = tokens.color(C::BackgroundSurface);
1345            assert_ne!(tokens.hovered(surface), surface, "dark={dark}");
1346            assert_ne!(tokens.pressed(surface), tokens.hovered(surface), "dark={dark}");
1347        }
1348    }
1349
1350    #[test]
1351    fn neutral_light_and_dark_have_opposite_luminance() {
1352        let light = ThemeData::neutral_light();
1353        let dark = ThemeData::neutral_dark();
1354        let luma = |c: Color| c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
1355        assert!(luma(light.background) > 0.8, "浅色画布应接近白色");
1356        assert!(luma(dark.background) < 0.15, "深色画布应接近黑色");
1357        assert!(luma(light.foreground) < 0.2, "浅色主题正文应为深色");
1358        assert!(luma(dark.foreground) > 0.6, "深色主题正文应为浅色");
1359    }
1360
1361    #[test]
1362    fn high_contrast_palette_meets_wcag_and_uses_square_corners() {
1363        for dark in [false, true] {
1364            let theme = ThemeData::high_contrast(dark);
1365            assert!(theme.high_contrast);
1366            assert_eq!(theme.background, if dark { Color::BLACK } else { Color::WHITE });
1367            assert!(contrast(theme.foreground, theme.background) >= 7.0, "正文对比度不足");
1368            assert!(contrast(theme.primary, theme.background) >= 4.5, "主色对比度不足");
1369            assert!(contrast(theme.border, theme.background) >= 3.0, "边框对比度不足");
1370            assert!(contrast(theme.text.caption.color, theme.background) >= 4.5, "次要文字对比度不足");
1371            assert!(contrast(theme.button.foreground, theme.button.background) >= 4.5, "主按钮文字对比度不足");
1372            assert!(
1373                contrast(theme.button_variants.normal.foreground, theme.button_variants.normal.background) >= 4.5,
1374                "常规按钮文字对比度不足"
1375            );
1376            assert!(contrast(theme.input.text_color, theme.input.background) >= 7.0, "输入框文字对比度不足");
1377            assert!(contrast(theme.tooltip.foreground, theme.tooltip.background) >= 7.0, "Tooltip 文字对比度不足");
1378            assert_eq!(theme.radius_sm, 0.0);
1379            assert_eq!(theme.radius_md, 0.0);
1380            assert_eq!(theme.radius_lg, 0.0);
1381            assert_eq!(theme.button.radius, 0.0);
1382            assert_eq!(theme.input.radius, 0.0);
1383            assert_eq!(theme.dialog.radius, 0.0);
1384            assert_eq!(theme.menu.radius, 0.0);
1385            assert!(theme.button.focus_ring_width >= 3.0);
1386            assert_eq!(theme.divider, theme.foreground, "分割线走前景色");
1387        }
1388    }
1389
1390    #[test]
1391    /// 实时改 token 的前提:一次完整派生必须是微秒级,不能是拖滑杆时的卡顿来源。
1392    fn theme_derivation_is_cheap_enough_for_live_editing() {
1393        let definition = crate::theme::tokens::define_theme().radius_multiplier(1.5);
1394        let iterations = 200;
1395        let start = std::time::Instant::now();
1396        for _ in 0..iterations {
1397            let theme = ThemeData::from_tokens(&definition.resolve(true));
1398            std::hint::black_box(&theme);
1399        }
1400        let per = start.elapsed().as_micros() as f64 / iterations as f64;
1401        assert!(per < 2_000.0, "单次 resolve + from_tokens = {per:.0}µs,实时改 token 会掉帧");
1402    }
1403
1404    #[test]
1405    fn spacing_scale_defaults() {
1406        let s = ThemeData::neutral_dark().space;
1407        assert_eq!((s.xxs, s.xs, s.s, s.m, s.l, s.xl), (2.0, 4.0, 8.0, 16.0, 24.0, 32.0));
1408        assert_eq!(s.control_padding, 8.0, "控件默认内边距");
1409        assert_eq!(s.container_padding, 16.0, "容器默认内边距");
1410        assert_eq!(s.container_gap, 8.0, "容器默认子项间距");
1411
1412        // 同一份刻度能从 token 层直接读到
1413        let tokens = tokens::define_theme().resolve(true);
1414        assert_eq!(tokens.spacing(SpacingStep::S0_5), 2.0);
1415        assert_eq!(tokens.spacing(SpacingStep::S8), 32.0);
1416        assert_eq!(tokens.length(LengthToken::RadiusContainer), 12.0);
1417    }
1418}