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
20// =================================================================
21// ThemeData — 纯数据,无 Widget 概念
22// =================================================================
23
24/// Text style defaults (theme-level).
25/// Individual TextWidget can override via TextStyle.
26#[derive(Debug, Clone, PartialEq)]
27pub struct TextTheme {
28    pub headline: TextStyleTheme,
29    pub title: TextStyleTheme,
30    pub body: TextStyleTheme,
31    pub caption: TextStyleTheme,
32}
33
34#[derive(Debug, Clone, PartialEq)]
35pub struct TextStyleTheme {
36    pub font_size: f32,
37    pub color: Color,
38}
39
40/// Button style defaults.
41#[derive(Debug, Clone, PartialEq)]
42pub struct ButtonStyle {
43    pub background: Color,
44    pub foreground: Color,
45    pub radius: f32,
46    /// 全局焦点环颜色(button / checkbox / input / nav 等复用同一令牌)
47    pub focus_ring_color: Color,
48    /// 全局焦点环宽度
49    pub focus_ring_width: f32,
50}
51
52/// 按钮语义变体(对应组件侧 `ButtonType`)。
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ButtonVariant {
55    /// 主操作
56    Primary,
57    /// 中性 / 次要操作(可有描边)
58    Normal,
59    /// 三级 / 低强调
60    Tertiary,
61    /// 成功
62    Success,
63    /// 警告
64    Warning,
65    /// 危险
66    Error,
67    /// 信息
68    Info,
69}
70
71/// 单个按钮变体的五态配色。
72#[derive(Debug, Clone, PartialEq)]
73pub struct ButtonVariantStyle {
74    pub background: Color,
75    pub foreground: Color,
76    /// `Color::TRANSPARENT` = 无描边
77    pub border: Color,
78    pub hover_background: Color,
79    pub pressed_background: Color,
80}
81
82/// 全部按钮变体。
83#[derive(Debug, Clone, PartialEq)]
84pub struct ButtonVariants {
85    pub primary: ButtonVariantStyle,
86    pub normal: ButtonVariantStyle,
87    pub tertiary: ButtonVariantStyle,
88    pub success: ButtonVariantStyle,
89    pub warning: ButtonVariantStyle,
90    pub error: ButtonVariantStyle,
91    pub info: ButtonVariantStyle,
92}
93
94impl ButtonVariants {
95    /// 按语义变体取样式。
96    pub fn get(&self, variant: ButtonVariant) -> &ButtonVariantStyle {
97        match variant {
98            ButtonVariant::Primary => &self.primary,
99            ButtonVariant::Normal => &self.normal,
100            ButtonVariant::Tertiary => &self.tertiary,
101            ButtonVariant::Success => &self.success,
102            ButtonVariant::Warning => &self.warning,
103            ButtonVariant::Error => &self.error,
104            ButtonVariant::Info => &self.info,
105        }
106    }
107}
108
109/// Avatar 样式(首字头像)。
110#[derive(Debug, Clone, PartialEq)]
111pub struct AvatarStyle {
112    /// 按名称哈希轮换的底色池
113    pub palette: [Color; 6],
114    pub foreground: Color,
115}
116
117/// 表单控件(Checkbox / Radio / Toggle / Slider)的 Cloudscape 令牌。
118#[derive(Debug, Clone, PartialEq)]
119pub struct ControlStyle {
120    /// 未选中控件底色(color-background-control-default)
121    pub background: Color,
122    /// 控件描边(color-border-control-default)
123    pub border: Color,
124    /// 选中底色(color-background-control-checked)
125    pub checked_background: Color,
126    /// 选中前景(对勾 / 圆点颜色)
127    pub checked_foreground: Color,
128    /// 禁用底色(color-background-control-disabled)
129    pub disabled_background: Color,
130    /// 禁用描边
131    pub disabled_border: Color,
132    /// Toggle 关闭态轨道(color-background-toggle-default)
133    pub toggle_off: Color,
134    /// Slider 轨道底色(color-background-slider-track-default)
135    pub slider_track: Color,
136    /// Slider 拖拽中已填充段(color-background-slider-range-active)
137    pub slider_range_active: Color,
138}
139
140/// 线性混合两种颜色(`t` ∈ [0,1],向 `b` 靠拢)。
141fn mix(a: Color, b: Color, t: f32) -> Color {
142    Color { r: a.r + (b.r - a.r) * t, g: a.g + (b.g - a.g) * t, b: a.b + (b.b - a.b) * t, a: a.a + (b.a - a.a) * t }
143}
144
145#[derive(Debug, Clone, PartialEq)]
146pub struct ScrollbarStyle {
147    pub thumb_color: Color,
148    /// 指针悬停(或拖拽中)在 thumb 上时的高亮色
149    pub thumb_hover_color: Color,
150    pub thumb_radius: f32,
151    pub thumb_width: f32,       // paint width (hit area is +2px)
152    pub hit_width: f32,         // hit test area width
153    pub thumb_min_size: f32,    // min thumb size in main axis px
154    pub thumb_track_ratio: f32, // thumb_main = viewport_main * ratio
155}
156
157/// TextField / 输入框样式(Cloudscape:描边输入框 + 焦点蓝边)。
158#[derive(Debug, Clone, PartialEq)]
159pub struct InputStyle {
160    pub background: Color,
161    pub border: Color,
162    pub focused_border: Color,
163    pub text_color: Color,
164    pub placeholder_color: Color,
165    pub radius: f32,
166}
167
168/// Tooltip 浮层样式。
169#[derive(Debug, Clone, PartialEq)]
170pub struct TooltipStyle {
171    pub background: Color,
172    pub foreground: Color,
173    pub border: Color,
174    pub radius: f32,
175}
176
177/// 菜单 / 右键 ContextMenu / 下拉列表样式。
178#[derive(Debug, Clone, PartialEq)]
179pub struct MenuStyle {
180    pub background: Color,
181    pub foreground: Color,
182    pub hover_background: Color,
183    pub border: Color,
184    pub radius: f32,
185}
186
187/// TabBar / TabView / TabbedPane 样式。
188#[derive(Debug, Clone, PartialEq)]
189pub struct TabStyle {
190    pub background: Color,
191    pub active_foreground: Color,
192    pub inactive_foreground: Color,
193    pub hover_background: Color,
194    pub indicator_color: Color,
195}
196
197/// NavigationMenu 样式。
198#[derive(Debug, Clone, PartialEq)]
199pub struct NavStyle {
200    pub active_background: Color,
201    pub active_foreground: Color,
202    pub foreground: Color,
203    pub hover_background: Color,
204    pub indicator_color: Color,
205}
206
207/// 反馈类组件样式(进度条 / Toast 等)。
208#[derive(Debug, Clone, PartialEq)]
209pub struct FeedbackStyle {
210    pub progress_track: Color,
211    pub progress_value: Color,
212    pub success: Color,
213    pub warning: Color,
214    /// 信息态强调色(Toast Info 等)
215    pub info: Color,
216    /// 错误态强调色(与全局 `error` 同源,供状态容器统一取用)
217    pub error: Color,
218}
219
220/// Dropdown 触发器 + 弹出面板样式。
221#[derive(Debug, Clone, PartialEq)]
222pub struct DropdownStyle {
223    pub background: Color,
224    pub foreground: Color,
225    pub placeholder: Color,
226    pub border: Color,
227    pub open_border: Color,
228    pub hover: Color,
229    pub selected_background: Color,
230    pub disabled: Color,
231}
232
233/// Dialog 遮罩 + 对话框样式。
234#[derive(Debug, Clone, PartialEq)]
235pub struct DialogStyle {
236    pub barrier: Color,
237    pub background: Color,
238    pub radius: f32,
239}
240
241/// ListView / 列表类样式。
242#[derive(Debug, Clone, PartialEq)]
243pub struct ListStyle {
244    pub hover_background: Color,
245    pub selected_background: Color,
246    pub foreground: Color,
247}
248
249/// 4pt 间距刻度 + 组件默认间距(Cloudscape spacing scale)。
250#[derive(Debug, Clone, PartialEq)]
251pub struct SpacingScale {
252    /// 2 — 徽标/gap 微调
253    pub xxs: f32,
254    /// 4 — 图标与文字
255    pub xs: f32,
256    /// 8 — 控件内边距 / 紧凑 gap
257    pub s: f32,
258    /// 16 — 容器内边距 / 常规 gap
259    pub m: f32,
260    /// 24 — 区块间距
261    pub l: f32,
262    /// 32 — 页面级间距
263    pub xl: f32,
264    /// 叶子控件默认内边距
265    pub control_padding: f32,
266    /// 容器默认内边距
267    pub container_padding: f32,
268    /// 容器未显式指定 gap 时的默认子项间距
269    pub container_gap: f32,
270}
271
272impl Default for SpacingScale {
273    fn default() -> Self {
274        Self {
275            xxs: 2.0,
276            xs: 4.0,
277            s: 8.0,
278            m: 16.0,
279            l: 24.0,
280            xl: 32.0,
281            control_padding: 8.0,
282            container_padding: 16.0,
283            container_gap: 8.0,
284        }
285    }
286}
287
288/// 主题色板 + 子主题。
289///
290/// 所有 `update_should_notify` 走 `PartialEq` 派生自动比较。
291///
292/// 风格基准:**AWS Cloudscape Design System(Visual Refresh)**
293/// (`cloudscape_dark()` / `cloudscape_light()`,`cloudscape(bool)` 按开关选择;
294/// `dark()` / `light()` 为同一套主题的别名)。
295///
296/// 通用令牌(border / divider / hover)供全部组件共享,做到"一次改主题、全局换肤"。
297#[derive(Debug, Clone, PartialEq)]
298pub struct ThemeData {
299    // --- ColorScheme (core) ---
300    pub background: Color,
301    pub foreground: Color,
302    pub primary: Color,
303    pub accent: Color,
304    pub surface: Color,
305    pub error: Color,
306    /// 高对比度变体标记(由 [`ThemeData::high_contrast`] 设置)。
307    pub high_contrast: bool,
308
309    // --- 通用令牌(全组件共享) ---
310    pub border: Color,    // 组件描边
311    pub divider: Color,   // Divider / 分隔线
312    pub hover: Color,     // hover 覆盖层(带 alpha)
313    pub disabled: Color,  // 禁用态前景(或带 alpha 覆盖)
314    pub selection: Color, // 文本/列表选中背景(primary 系 alpha)
315    pub icon: Color,      // 图标默认 tint
316
317    // --- Radius ---
318    pub radius_sm: f32, // 4.0 — badge / checkbox
319    pub radius_md: f32, // 8.0 — input / item
320    pub radius_lg: f32, // 16.0 — dialog / menu / large container
321
322    // --- Spacing ---
323    pub spacing: f32, // 8.0 — default widget spacing
324    /// 4pt 间距刻度与组件默认间距
325    pub space: SpacingScale,
326
327    // --- Sub-themes ---
328    pub text: TextTheme,
329    pub button: ButtonStyle,
330    /// 按钮语义变体色板(Primary/Normal/Tertiary/Success/Warning/Error/Info)
331    pub button_variants: ButtonVariants,
332    /// Avatar 首字头像样式
333    pub avatar: AvatarStyle,
334    /// 表单控件令牌(Checkbox/Radio/Toggle/Slider)
335    pub control: ControlStyle,
336    pub scrollbar: ScrollbarStyle,
337    pub input: InputStyle,
338    pub tooltip: TooltipStyle,
339    pub menu: MenuStyle,
340    pub tab: TabStyle,
341    pub nav: NavStyle,
342    pub feedback: FeedbackStyle,
343    pub dropdown: DropdownStyle,
344    pub dialog: DialogStyle,
345    pub list: ListStyle,
346}
347
348impl Default for ThemeData {
349    fn default() -> Self {
350        Self::cloudscape_dark()
351    }
352}
353
354impl ThemeData {
355    /// 深色主题(Cloudscape 别名)。
356    pub fn dark() -> Self {
357        Self::cloudscape_dark()
358    }
359
360    /// 浅色主题(Cloudscape 别名)。
361    pub fn light() -> Self {
362        Self::cloudscape_light()
363    }
364
365    /// AWS Cloudscape Design System(Visual Refresh)— 浅色。
366    pub fn cloudscape_light() -> Self {
367        Self::cloudscape(false)
368    }
369
370    /// AWS Cloudscape Design System(Visual Refresh)— 深色。
371    pub fn cloudscape_dark() -> Self {
372        Self::cloudscape(true)
373    }
374
375    /// 按 `dark` 选择 Cloudscape 主题。
376    ///
377    /// 色值取自 Cloudscape design-tokens(visual refresh)官方明/暗令牌:
378    /// 主操作蓝 `#006CE0` / `#42B4FF`、正文 `#0F141A` / `#C6C6CD`、
379    /// 容器 `#FFFFFF` / `#161D26`、分割线 `#C6C6CD` / `#424650`、
380    /// 控件圆角 8、容器圆角 16、主按钮胶囊 20。
381    pub fn cloudscape(dark: bool) -> Self {
382        // ---- Cloudscape visual-refresh 色板 ----
383        let (bg, surface, fg, caption, primary, accent, error) = if dark {
384            (
385                Color::from_rgb8(0x0F, 0x14, 0x1A), // color-background-layout-main
386                Color::from_rgb8(0x16, 0x1D, 0x26), // color-background-container-default
387                Color::from_rgb8(0xC6, 0xC6, 0xCD), // color-text-body-default
388                Color::from_rgb8(0xA4, 0xA4, 0xAD), // color-text-status-inactive
389                Color::from_rgb8(0x42, 0xB4, 0xFF), // color-border-item-focused
390                Color::from_rgb8(0xFB, 0xD3, 0x32), // color-text-status-warning
391                Color::from_rgb8(0xFF, 0x7A, 0x7A), // color-text-status-error
392            )
393        } else {
394            (
395                Color::from_rgb8(0xF3, 0xF3, 0xF7), // 画布(容器 #FFFFFF 之上留出层次)
396                Color::from_rgb8(0xFF, 0xFF, 0xFF), // color-background-container-default
397                Color::from_rgb8(0x0F, 0x14, 0x1A), // color-text-body-default
398                Color::from_rgb8(0x42, 0x46, 0x50), // color-text-body-secondary
399                Color::from_rgb8(0x00, 0x6C, 0xE0), // color-border-item-focused
400                Color::from_rgb8(0x85, 0x59, 0x00), // color-text-status-warning
401                Color::from_rgb8(0xDB, 0x00, 0x00), // color-text-status-error
402            )
403        };
404        let (border, divider, input_border, disabled_token) = if dark {
405            (
406                Color::from_rgb8(0x42, 0x46, 0x50),
407                Color::from_rgb8(0x42, 0x46, 0x50), // color-border-divider-default
408                Color::from_rgb8(0x65, 0x68, 0x71), // color-border-input-default
409                Color::from_rgb8(0x65, 0x68, 0x71), // color-text-input-disabled
410            )
411        } else {
412            (
413                Color::from_rgb8(0xC6, 0xC6, 0xCD),
414                Color::from_rgb8(0xC6, 0xC6, 0xCD), // color-border-divider-default
415                Color::from_rgb8(0x8C, 0x8C, 0x94), // color-border-input-default
416                Color::from_rgb8(0xB4, 0xB4, 0xBB), // color-text-input-disabled
417            )
418        };
419        let (hover_bg, hover_overlay, selected_bg, scrollbar_thumb, scrollbar_hover, menu_hover, nav_hover) = if dark {
420            (
421                Color::from_rgb8(0x1B, 0x23, 0x2D), // 下拉/行 hover
422                Color::rgba(1.0, 1.0, 1.0, 0.06),
423                Color::from_rgb8(0x00, 0x11, 0x29), // color-background-item-selected
424                Color::rgba(0.396, 0.408, 0.443, 0.70), // #656871
425                Color::rgba(0.549, 0.549, 0.580, 0.90), // #8C8C94
426                Color::from_rgb8(0x1B, 0x23, 0x2D),
427                Color::from_rgb8(0x1B, 0x23, 0x2D),
428            )
429        } else {
430            (
431                Color::from_rgb8(0xF3, 0xF3, 0xF7), // color-background-dropdown-item-hover
432                Color::rgba(0.059, 0.078, 0.102, 0.05),
433                Color::from_rgb8(0xF0, 0xFB, 0xFF), // color-background-item-selected
434                Color::rgba(0.549, 0.549, 0.565, 0.55), // #8C8C94
435                Color::rgba(0.259, 0.275, 0.314, 0.85), // #424650
436                Color::from_rgb8(0xF3, 0xF3, 0xF7),
437                Color::from_rgb8(0xF3, 0xF3, 0xF7),
438            )
439        };
440        let (placeholder, tooltip_bg, tooltip_fg, tooltip_border) = if dark {
441            (
442                Color::from_rgb8(0xA4, 0xA4, 0xAD), // color-text-input-placeholder
443                Color::from_rgb8(0x33, 0x38, 0x43),
444                Color::from_rgb8(0xDE, 0xDE, 0xE3),
445                Color::from_rgb8(0x42, 0x46, 0x50),
446            )
447        } else {
448            (
449                Color::from_rgb8(0x65, 0x68, 0x71), // color-text-input-placeholder
450                Color::from_rgb8(0x0F, 0x14, 0x1A),
451                Color::WHITE,
452                Color::from_rgb8(0x0F, 0x14, 0x1A),
453            )
454        };
455        let (success, warning, track) = if dark {
456            (
457                Color::from_rgb8(0x2B, 0xB5, 0x34), // color-text-status-success
458                Color::from_rgb8(0xFB, 0xD3, 0x32), // color-text-status-warning
459                Color::rgba(1.0, 1.0, 1.0, 0.12),
460            )
461        } else {
462            (
463                Color::from_rgb8(0x00, 0x80, 0x2F), // color-text-status-success
464                Color::from_rgb8(0x85, 0x59, 0x00), // color-text-status-warning
465                Color::rgba(0.0, 0.0, 0.0, 0.08),
466            )
467        };
468        let (button_bg, button_fg) = if dark {
469            (primary, Color::from_rgb8(0x0F, 0x14, 0x1A)) // 深色主按钮:浅蓝底 + 深字
470        } else {
471            (primary, Color::WHITE)
472        };
473
474        let text = TextTheme {
475            headline: TextStyleTheme { font_size: 24.0, color: fg },
476            title: TextStyleTheme { font_size: 18.0, color: fg },
477            body: TextStyleTheme { font_size: 14.0, color: fg },
478            caption: TextStyleTheme { font_size: 12.0, color: caption },
479        };
480        let button = ButtonStyle {
481            background: button_bg,
482            foreground: button_fg,
483            radius: 20.0, // border-radius-button
484            focus_ring_color: primary,
485            focus_ring_width: 2.0,
486        };
487        // 按钮变体:Primary 蓝底;Normal 蓝描边;Tertiary 低强调;状态变体由状态色推导 hover/pressed
488        let status_variant = |base: Color| ButtonVariantStyle {
489            background: base,
490            foreground: button_fg,
491            border: Color::TRANSPARENT,
492            hover_background: if dark { mix(base, Color::WHITE, 0.15) } else { mix(base, Color::BLACK, 0.12) },
493            pressed_background: if dark { mix(base, Color::WHITE, 0.28) } else { mix(base, Color::BLACK, 0.22) },
494        };
495        let button_variants = ButtonVariants {
496            primary: ButtonVariantStyle {
497                background: primary,
498                foreground: button_fg,
499                border: Color::TRANSPARENT,
500                hover_background: if dark {
501                    mix(primary, Color::WHITE, 0.20)
502                } else {
503                    Color::from_rgb8(0x00, 0x2B, 0x66)
504                },
505                pressed_background: if dark {
506                    mix(primary, Color::WHITE, 0.30)
507                } else {
508                    Color::from_rgb8(0x00, 0x2B, 0x66)
509                },
510            },
511            normal: ButtonVariantStyle {
512                background: surface,
513                foreground: primary,
514                border: primary,
515                hover_background: if dark {
516                    Color::from_rgb8(0x1B, 0x23, 0x2D)
517                } else {
518                    Color::from_rgb8(0xF0, 0xFB, 0xFF)
519                },
520                pressed_background: if dark {
521                    Color::from_rgb8(0x33, 0x38, 0x43)
522                } else {
523                    Color::from_rgb8(0xD1, 0xF1, 0xFF)
524                },
525            },
526            tertiary: ButtonVariantStyle {
527                background: Color::TRANSPARENT,
528                foreground: fg,
529                border: Color::TRANSPARENT,
530                hover_background: hover_bg,
531                pressed_background: if dark {
532                    Color::from_rgb8(0x33, 0x38, 0x43)
533                } else {
534                    Color::from_rgb8(0xDE, 0xDE, 0xE3)
535                },
536            },
537            success: status_variant(success),
538            warning: status_variant(warning),
539            error: status_variant(error),
540            info: status_variant(primary),
541        };
542        let avatar = AvatarStyle {
543            palette: [
544                Color::from_rgb8(0x00, 0x6C, 0xE0),
545                Color::from_rgb8(0x00, 0x80, 0x2F),
546                Color::from_rgb8(0xC2, 0x5A, 0x00),
547                Color::from_rgb8(0x7B, 0x3F, 0xBF),
548                Color::from_rgb8(0xDB, 0x00, 0x00),
549                Color::from_rgb8(0x00, 0x7E, 0x87),
550            ],
551            foreground: Color::WHITE,
552        };
553        // 表单控件令牌(Cloudscape visual refresh)
554        let control = if dark {
555            ControlStyle {
556                background: Color::from_rgb8(0x16, 0x1D, 0x26),
557                border: Color::from_rgb8(0x8C, 0x8C, 0x94),
558                // Cloudscape 深色 Checkbox/Radio:饱和蓝底 + 白色对勾/圆点
559                checked_background: Color::from_rgb8(0x00, 0x6C, 0xE0),
560                checked_foreground: Color::WHITE,
561                disabled_background: Color::from_rgb8(0x33, 0x38, 0x43),
562                disabled_border: Color::from_rgb8(0x65, 0x68, 0x71),
563                toggle_off: Color::from_rgb8(0x8C, 0x8C, 0x94),
564                slider_track: Color::from_rgb8(0x65, 0x68, 0x71),
565                slider_range_active: Color::from_rgb8(0x75, 0xCF, 0xFF),
566            }
567        } else {
568            ControlStyle {
569                background: Color::WHITE,
570                border: Color::from_rgb8(0x8C, 0x8C, 0x94),
571                checked_background: primary,
572                checked_foreground: Color::WHITE,
573                disabled_background: Color::from_rgb8(0xDE, 0xDE, 0xE3),
574                disabled_border: Color::from_rgb8(0xB4, 0xB4, 0xBB),
575                toggle_off: Color::from_rgb8(0x42, 0x46, 0x50),
576                slider_track: Color::from_rgb8(0x8C, 0x8C, 0x94),
577                slider_range_active: Color::from_rgb8(0x00, 0x4A, 0x9E),
578            }
579        };
580        let scrollbar = ScrollbarStyle {
581            thumb_color: scrollbar_thumb,
582            thumb_hover_color: scrollbar_hover,
583            thumb_radius: 4.0,
584            thumb_width: 8.0,
585            hit_width: 10.0,
586            thumb_min_size: 24.0,
587            thumb_track_ratio: 0.32,
588        };
589        let input = InputStyle {
590            background: surface,
591            border: input_border,
592            focused_border: primary,
593            text_color: fg,
594            placeholder_color: placeholder,
595            radius: 8.0, // border-radius-input
596        };
597        let tooltip =
598            TooltipStyle { background: tooltip_bg, foreground: tooltip_fg, border: tooltip_border, radius: 8.0 };
599        let menu =
600            MenuStyle { background: surface, foreground: fg, hover_background: menu_hover, border, radius: 16.0 };
601        let tab = TabStyle {
602            background: surface,
603            active_foreground: fg,
604            inactive_foreground: caption,
605            hover_background: hover_bg,
606            indicator_color: primary,
607        };
608        let nav = NavStyle {
609            active_background: selected_bg,
610            active_foreground: primary,
611            foreground: fg,
612            hover_background: nav_hover,
613            indicator_color: primary,
614        };
615        let feedback =
616            FeedbackStyle { progress_track: track, progress_value: primary, success, warning, info: primary, error };
617        let dropdown = DropdownStyle {
618            background: surface,
619            foreground: fg,
620            placeholder,
621            border: input_border,
622            open_border: primary,
623            hover: hover_bg,
624            selected_background: selected_bg,
625            disabled: disabled_token,
626        };
627        let dialog = DialogStyle {
628            barrier: if dark { Color::rgba(0.0, 0.0, 0.0, 0.60) } else { Color::rgba(0.0, 0.0, 0.0, 0.45) },
629            background: surface,
630            radius: 16.0, // border-radius-container
631        };
632        let list = ListStyle { hover_background: hover_bg, selected_background: selected_bg, foreground: fg };
633        Self {
634            background: bg,
635            foreground: fg,
636            primary,
637            accent,
638            surface,
639            error,
640            high_contrast: false,
641            border,
642            divider,
643            hover: hover_overlay,
644            disabled: disabled_token,
645            selection: selected_bg,
646            icon: fg,
647            button_variants,
648            avatar,
649            control,
650            radius_sm: 4.0,  // border-radius-badge
651            radius_md: 8.0,  // border-radius-input / item
652            radius_lg: 16.0, // border-radius-container
653            spacing: 8.0,
654            space: SpacingScale::default(),
655            text,
656            button,
657            scrollbar,
658            input,
659            tooltip,
660            menu,
661            tab,
662            nav,
663            feedback,
664            dropdown,
665            dialog,
666            list,
667        }
668    }
669
670    /// 高对比度主题(Windows 高对比度/强制对比模式的通用替代)。
671    ///
672    /// 在 Cloudscape 色板骨架上强制:
673    /// - 前景/背景 ≥ 7:1,边框/背景 ≥ 3:1,主色/背景 ≥ 4.5:1;
674    /// - 关键文本使用纯黑/纯白,边框与分割线使用前景色;
675    /// - 圆角归零、焦点环 3px,便于低视力用户辨识。
676    ///
677    /// `dark=true` 为黑底白字/金黄主色;`false` 为白底黑字/深蓝主色。
678    /// 系统高对比度色板由平台提供时,应用仍可自行替换核心令牌。
679    pub fn high_contrast(dark: bool) -> Self {
680        let mut theme = Self::cloudscape(dark);
681        let (bg, fg, dim, primary, on_primary, focus, accent, error, success, warning, hover, selection) = if dark {
682            (
683                Color::BLACK,
684                Color::WHITE,
685                Color::from_rgb8(0xB0, 0xB0, 0xB0),
686                Color::from_rgb8(0xFF, 0xD7, 0x00),
687                Color::BLACK,
688                Color::WHITE,
689                Color::from_rgb8(0x00, 0xFF, 0xFF),
690                Color::from_rgb8(0xFF, 0x80, 0x80),
691                Color::from_rgb8(0x7C, 0xFC, 0x7C),
692                Color::from_rgb8(0xFF, 0xD7, 0x00),
693                Color::rgba(1.0, 1.0, 1.0, 0.20),
694                Color::rgba(1.0, 0.843, 0.0, 0.35),
695            )
696        } else {
697            (
698                Color::WHITE,
699                Color::BLACK,
700                Color::from_rgb8(0x50, 0x50, 0x50),
701                Color::from_rgb8(0x00, 0x33, 0xCC),
702                Color::WHITE,
703                Color::BLACK,
704                Color::from_rgb8(0x00, 0x5A, 0x5A),
705                Color::from_rgb8(0xB0, 0x00, 0x20),
706                Color::from_rgb8(0x00, 0x64, 0x00),
707                Color::from_rgb8(0x7A, 0x4F, 0x00),
708                Color::rgba(0.0, 0.0, 0.0, 0.12),
709                Color::rgba(0.0, 0.2, 0.8, 0.18),
710            )
711        };
712
713        theme.high_contrast = true;
714        theme.background = bg;
715        theme.surface = bg;
716        theme.foreground = fg;
717        theme.primary = primary;
718        theme.accent = accent;
719        theme.error = error;
720        theme.border = fg;
721        theme.divider = fg;
722        theme.hover = hover;
723        theme.disabled = dim;
724        theme.selection = selection;
725        theme.icon = fg;
726        theme.radius_sm = 0.0;
727        theme.radius_md = 0.0;
728        theme.radius_lg = 0.0;
729
730        for style in [&mut theme.text.headline, &mut theme.text.title, &mut theme.text.body] {
731            style.color = fg;
732        }
733        theme.text.caption.color = dim;
734
735        theme.button.background = primary;
736        theme.button.foreground = on_primary;
737        theme.button.radius = 0.0;
738        theme.button.focus_ring_color = focus;
739        theme.button.focus_ring_width = 3.0;
740
741        theme.button_variants.primary = ButtonVariantStyle {
742            background: primary,
743            foreground: on_primary,
744            border: Color::TRANSPARENT,
745            hover_background: mix(primary, focus, 0.18),
746            pressed_background: mix(primary, bg, 0.20),
747        };
748        theme.button_variants.normal = ButtonVariantStyle {
749            background: bg,
750            foreground: primary,
751            border: primary,
752            hover_background: selection,
753            pressed_background: hover,
754        };
755        theme.button_variants.tertiary = ButtonVariantStyle {
756            background: Color::TRANSPARENT,
757            foreground: fg,
758            border: Color::TRANSPARENT,
759            hover_background: selection,
760            pressed_background: hover,
761        };
762        let status_variant = |fill: Color| ButtonVariantStyle {
763            background: fill,
764            foreground: on_primary,
765            border: Color::TRANSPARENT,
766            hover_background: mix(fill, focus, 0.15),
767            pressed_background: mix(fill, bg, 0.15),
768        };
769        theme.button_variants.success = status_variant(success);
770        theme.button_variants.warning = status_variant(warning);
771        theme.button_variants.error = status_variant(error);
772        theme.button_variants.info = status_variant(accent);
773
774        theme.avatar.palette = [
775            Color::from_rgb8(0x00, 0x50, 0x80),
776            Color::from_rgb8(0x00, 0x50, 0x00),
777            Color::from_rgb8(0x6B, 0x2A, 0x00),
778            Color::from_rgb8(0x3B, 0x00, 0x80),
779            Color::from_rgb8(0x90, 0x00, 0x00),
780            Color::from_rgb8(0x00, 0x4A, 0x4A),
781        ];
782        theme.avatar.foreground = Color::WHITE;
783
784        theme.control.background = bg;
785        theme.control.border = fg;
786        theme.control.checked_background = primary;
787        theme.control.checked_foreground = on_primary;
788        theme.control.disabled_background = bg;
789        theme.control.disabled_border = dim;
790        theme.control.toggle_off = dim;
791        theme.control.slider_track = dim;
792        theme.control.slider_range_active = primary;
793
794        theme.scrollbar.thumb_color = dim;
795        theme.scrollbar.thumb_hover_color = primary;
796
797        theme.input.background = bg;
798        theme.input.border = fg;
799        theme.input.focused_border = primary;
800        theme.input.text_color = fg;
801        theme.input.placeholder_color = dim;
802        theme.input.radius = 0.0;
803
804        theme.tooltip.background = bg;
805        theme.tooltip.foreground = fg;
806        theme.tooltip.border = fg;
807        theme.tooltip.radius = 0.0;
808
809        theme.menu.background = bg;
810        theme.menu.foreground = fg;
811        theme.menu.hover_background = selection;
812        theme.menu.border = fg;
813        theme.menu.radius = 0.0;
814
815        theme.tab.background = bg;
816        theme.tab.active_foreground = fg;
817        theme.tab.inactive_foreground = dim;
818        theme.tab.hover_background = selection;
819        theme.tab.indicator_color = primary;
820
821        theme.nav.active_background = selection;
822        theme.nav.active_foreground = fg;
823        theme.nav.foreground = fg;
824        theme.nav.hover_background = selection;
825        theme.nav.indicator_color = primary;
826
827        theme.feedback.progress_track = dim;
828        theme.feedback.progress_value = primary;
829        theme.feedback.success = success;
830        theme.feedback.warning = warning;
831        theme.feedback.info = accent;
832        theme.feedback.error = error;
833
834        theme.dropdown.background = bg;
835        theme.dropdown.foreground = fg;
836        theme.dropdown.placeholder = dim;
837        theme.dropdown.border = fg;
838        theme.dropdown.open_border = primary;
839        theme.dropdown.hover = selection;
840        theme.dropdown.selected_background = selection;
841        theme.dropdown.disabled = dim;
842
843        theme.dialog.barrier = if dark { Color::rgba(0.0, 0.0, 0.0, 0.85) } else { Color::rgba(0.0, 0.0, 0.0, 0.60) };
844        theme.dialog.background = bg;
845        theme.dialog.radius = 0.0;
846
847        theme.list.hover_background = selection;
848        theme.list.selected_background = selection;
849        theme.list.foreground = fg;
850
851        theme
852    }
853}
854
855// =================================================================
856// Direction — 文本方向(Ltr / Rtl)
857// =================================================================
858
859#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
860pub enum Direction {
861    #[default]
862    Ltr,
863    Rtl,
864}
865
866// =================================================================
867// ThemeWidget + InheritedWidget impl
868// =================================================================
869
870/// 用户显式颜色优先,否则回退到主题/token 值。
871///
872/// P1-8:用 `Option` 表达"未覆盖",不再依赖与默认色相等的 sentinel 判断
873/// (用户显式选择与哨兵相同的颜色时也能正确覆盖)。
874pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
875    match explicit {
876        Some(color) => color,
877        None => themed,
878    }
879}
880
881/// 数值版 `resolve_color`:显式尺寸/宽度优先,否则用主题/回退值。
882pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
883    match explicit {
884        Some(value) => value,
885        None => themed,
886    }
887}
888
889/// Theme 提供者 widget。挂到树中,所有后代可通过 `ctx.theme()` 访问。
890///
891/// `theme` 用 `Rc` 共享:State 缓存主题时只 clone 引用,不再复制整份 ThemeData。
892#[derive(Debug)]
893pub struct ThemeWidget {
894    pub theme: Rc<ThemeData>,
895    pub direction: Direction,
896    pub child: Option<WidgetNode>,
897}
898
899impl ThemeWidget {
900    pub fn new(theme: ThemeData) -> Self {
901        Self::from_rc(Rc::new(theme))
902    }
903
904    pub fn from_rc(theme: Rc<ThemeData>) -> Self {
905        Self { theme, direction: Direction::Ltr, child: None }
906    }
907
908    pub fn dark() -> Self {
909        Self::new(ThemeData::dark())
910    }
911
912    pub fn light() -> Self {
913        Self::new(ThemeData::light())
914    }
915
916    pub fn with_direction(mut self, d: Direction) -> Self {
917        self.direction = d;
918        self
919    }
920
921    pub fn child(mut self, c: impl Widget) -> Self {
922        self.child = Some(WidgetNode::new(c));
923        self
924    }
925
926    pub fn child_node(mut self, c: WidgetNode) -> Self {
927        self.child = Some(c);
928        self
929    }
930}
931
932impl InheritedWidget for ThemeWidget {
933    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
934        // downcast old 到 ThemeWidget 比较 theme + direction
935        if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
936            if Rc::ptr_eq(&self.theme, &old_theme.theme) {
937                return self.direction != old_theme.direction;
938            }
939            *self.theme != *old_theme.theme || self.direction != old_theme.direction
940        } else {
941            true
942        }
943    }
944
945    fn as_any(&self) -> &dyn Any {
946        self
947    }
948}
949
950impl ThemeWidget {
951    pub fn theme(&self) -> &ThemeData {
952        &self.theme
953    }
954
955    pub fn direction(&self) -> Direction {
956        self.direction
957    }
958}
959
960impl Widget for ThemeWidget {
961    fn as_any(&self) -> &dyn Any {
962        self
963    }
964
965    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
966        Some(self)
967    }
968
969    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
970        // 透传 child RO,但必须**包一层 ProxyRenderObject**:
971        // 直接把 child widget 的 RO 树当自己的 RO,会让 element 树(1 个 child)
972        // 与 RO 树(child 的整棵子树)不同构;propagate 只能按索引替换前 N 个 slot,
973        // 其余 slot 成为陈旧副本(Theme 根节点会重复绘制 nested boundary)。
974        match &self.child {
975            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
976            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
977        }
978    }
979
980    fn children(&self) -> Vec<WidgetNode> {
981        self.child.clone().into_iter().collect()
982    }
983
984    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
985        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
986    }
987}
988
989// =================================================================
990// DirectionWidget — 单独暴露 direction(如果只想用 Direction 不想用 Theme)
991// =================================================================
992
993/// 单独的 Direction 提供者,方便只想换方向不换主题的场景。
994#[derive(Debug)]
995pub struct DirectionWidget {
996    pub direction: Direction,
997    pub child: Option<WidgetNode>,
998}
999
1000impl DirectionWidget {
1001    pub fn new(d: Direction) -> Self {
1002        Self { direction: d, child: None }
1003    }
1004
1005    pub fn child(mut self, c: impl Widget) -> Self {
1006        self.child = Some(WidgetNode::new(c));
1007        self
1008    }
1009}
1010
1011impl InheritedWidget for DirectionWidget {
1012    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
1013        if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
1014            self.direction != old_dir.direction
1015        } else {
1016            true
1017        }
1018    }
1019
1020    fn as_any(&self) -> &dyn Any {
1021        self
1022    }
1023}
1024
1025impl DirectionWidget {
1026    pub fn direction(&self) -> Direction {
1027        self.direction
1028    }
1029}
1030
1031impl Widget for DirectionWidget {
1032    fn as_any(&self) -> &dyn Any {
1033        self
1034    }
1035
1036    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
1037        Some(self)
1038    }
1039
1040    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
1041        // 与 ThemeWidget 相同:透传 child 必须包 Proxy,保证 element/RO 同构。
1042        match &self.child {
1043            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
1044            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
1045        }
1046    }
1047
1048    fn children(&self) -> Vec<WidgetNode> {
1049        self.child.clone().into_iter().collect()
1050    }
1051
1052    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
1053        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
1054    }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059    use super::*;
1060
1061    #[test]
1062    fn cloudscape_palette_matches_design_tokens() {
1063        let light = ThemeData::cloudscape_light();
1064        assert_eq!(light.primary, Color::from_rgb8(0x00, 0x6C, 0xE0));
1065        assert_eq!(light.background, Color::from_rgb8(0xF3, 0xF3, 0xF7));
1066        assert_eq!(light.surface, Color::WHITE);
1067        assert_eq!(light.foreground, Color::from_rgb8(0x0F, 0x14, 0x1A));
1068        assert_eq!(light.button.foreground, Color::WHITE);
1069        assert_eq!(light.button.radius, 20.0, "Cloudscape 主按钮为胶囊形");
1070        assert_eq!(light.input.radius, 8.0);
1071        assert_eq!(light.dialog.radius, 16.0);
1072
1073        let dark = ThemeData::cloudscape_dark();
1074        assert_eq!(dark.primary, Color::from_rgb8(0x42, 0xB4, 0xFF));
1075        assert_eq!(dark.background, Color::from_rgb8(0x0F, 0x14, 0x1A));
1076        assert_eq!(dark.surface, Color::from_rgb8(0x16, 0x1D, 0x26));
1077        assert_eq!(dark.foreground, Color::from_rgb8(0xC6, 0xC6, 0xCD));
1078        // 深色主题主按钮:浅蓝底 + 深色文字(Cloudscape 约定)
1079        assert_eq!(dark.button.foreground, dark.background);
1080    }
1081
1082    #[test]
1083    fn cloudscape_selector_and_alias_consistency() {
1084        assert_eq!(ThemeData::cloudscape(false), ThemeData::cloudscape_light());
1085        assert_eq!(ThemeData::cloudscape(true), ThemeData::cloudscape_dark());
1086        assert_ne!(ThemeData::cloudscape_light(), ThemeData::cloudscape_dark());
1087    }
1088
1089    #[test]
1090    fn high_contrast_palette_meets_wcag_and_uses_square_corners() {
1091        fn channel(value: f32) -> f32 {
1092            if value <= 0.04045 {
1093                value / 12.92
1094            } else {
1095                ((value + 0.055) / 1.055).powf(2.4)
1096            }
1097        }
1098        fn luminance(color: Color) -> f32 {
1099            0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
1100        }
1101        fn contrast(a: Color, b: Color) -> f32 {
1102            let (la, lb) = (luminance(a), luminance(b));
1103            (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
1104        }
1105
1106        for dark in [false, true] {
1107            let theme = ThemeData::high_contrast(dark);
1108            assert!(theme.high_contrast);
1109            assert_eq!(theme.background, if dark { Color::BLACK } else { Color::WHITE });
1110            assert!(contrast(theme.foreground, theme.background) >= 7.0, "正文对比度不足");
1111            assert!(contrast(theme.primary, theme.background) >= 4.5, "主色对比度不足");
1112            assert!(contrast(theme.border, theme.background) >= 3.0, "边框对比度不足");
1113            assert!(contrast(theme.text.caption.color, theme.background) >= 4.5, "次要文字对比度不足");
1114            assert!(contrast(theme.button.foreground, theme.button.background) >= 4.5, "主按钮文字对比度不足");
1115            assert!(
1116                contrast(theme.button_variants.normal.foreground, theme.button_variants.normal.background) >= 4.5,
1117                "常规按钮文字对比度不足"
1118            );
1119            assert!(contrast(theme.input.text_color, theme.input.background) >= 7.0, "输入框文字对比度不足");
1120            assert!(contrast(theme.tooltip.foreground, theme.tooltip.background) >= 7.0, "Tooltip 文字对比度不足");
1121            assert_eq!(theme.radius_md, 0.0);
1122            assert_eq!(theme.button.radius, 0.0);
1123            assert_eq!(theme.dialog.radius, 0.0);
1124            assert!(theme.button.focus_ring_width >= 3.0);
1125        }
1126    }
1127
1128    #[test]
1129    fn cloudscape_focus_and_emphasis_follow_primary() {
1130        for t in [ThemeData::cloudscape_light(), ThemeData::cloudscape_dark()] {
1131            assert_eq!(t.button.focus_ring_color, t.primary);
1132            assert_eq!(t.text.body.color, t.foreground);
1133            assert_eq!(t.tab.indicator_color, t.primary);
1134            assert_eq!(t.nav.indicator_color, t.primary);
1135            assert_eq!(t.feedback.progress_value, t.primary);
1136            assert_eq!(t.dropdown.open_border, t.primary);
1137            assert_eq!(t.input.focused_border, t.primary);
1138        }
1139    }
1140
1141    #[test]
1142    fn cloudscape_light_and_dark_have_opposite_luminance() {
1143        let light = ThemeData::cloudscape_light();
1144        let dark = ThemeData::cloudscape_dark();
1145        let luma = |c: Color| c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
1146        assert!(luma(light.background) > 0.8, "浅色画布应接近白色");
1147        assert!(luma(dark.background) < 0.15, "深色画布应接近黑色");
1148        assert!(luma(light.foreground) < 0.2, "浅色主题正文应为深色");
1149        assert!(luma(dark.foreground) > 0.6, "深色主题正文应为浅色");
1150    }
1151
1152    #[test]
1153    fn cloudscape_button_variants_and_avatar_are_themed() {
1154        let light = ThemeData::cloudscape_light();
1155        assert_eq!(light.button_variants.primary.background, light.primary);
1156        assert_eq!(light.button_variants.primary.foreground, Color::WHITE);
1157        assert_eq!(light.button_variants.normal.border, light.primary);
1158        assert_eq!(light.button_variants.normal.background, light.surface);
1159        assert_eq!(light.button_variants.tertiary.background, Color::TRANSPARENT);
1160
1161        let dark = ThemeData::cloudscape_dark();
1162        // 深色主题主按钮:浅蓝底 + 深字
1163        assert_eq!(dark.button_variants.primary.foreground, dark.background);
1164        assert_eq!(dark.button_variants.normal.border, dark.primary);
1165        assert_eq!(dark.avatar.foreground, Color::WHITE);
1166        assert_ne!(dark.avatar.palette[0], dark.avatar.palette[1]);
1167
1168        // 状态变体严格来自反馈状态色
1169        assert_eq!(dark.button_variants.success.background, dark.feedback.success);
1170        assert_eq!(dark.button_variants.warning.background, dark.feedback.warning);
1171        assert_eq!(dark.button_variants.error.background, dark.feedback.error);
1172        assert_eq!(dark.feedback.error, dark.error);
1173    }
1174
1175    #[test]
1176    fn theme_variants_follow_primary_and_status_tokens() {
1177        let t = ThemeData::cloudscape_dark();
1178        assert_eq!(t.button_variants.primary.background, t.primary);
1179        assert_eq!(t.feedback.info, t.primary);
1180        assert_eq!(t.feedback.error, t.error);
1181        assert_eq!(t.avatar.foreground, Color::WHITE);
1182    }
1183
1184    #[test]
1185    fn spacing_scale_defaults() {
1186        let s = ThemeData::cloudscape_dark().space;
1187        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));
1188        assert_eq!(s.control_padding, 8.0, "控件默认内边距");
1189        assert_eq!(s.container_padding, 16.0, "容器默认内边距");
1190        assert_eq!(s.container_gap, 8.0, "容器默认子项间距");
1191    }
1192}