mgui-core 0.8.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! 阶段 4-A:Theme + Direction — 第一个 InheritedWidget 用例
//!
//! 设计文档 § 6 + § 19.Theme:全局视觉风格沿树向下传递。
//!
//! ```ignore
//! ThemeWidget::new(ThemeData::dark())
//!     .direction(Direction::Ltr)
//!     .child(MyApp())
//! ```
//!
//! 任何后代 widget 在 `state.build(ctx)` 中调 `ctx.depend_on::<ThemeWidget>()` 或
//! 便捷的 `ctx.theme()` / `ctx.direction()` 拿当前主题。

use crate::inherited::InheritedWidget;
use crate::widget::{Widget, WidgetNode};
use crate::{Color, Point, Size};
use std::any::Any;
use std::rc::Rc;

pub mod tokens;

pub use tokens::{
    define_theme, overlay, ColorToken, DurationToken, EasingToken, FocusTokens, FontFamilyToken, FontSizeToken,
    FontWeightToken, LengthToken, RadiusTokens, Shadow, ShadowLayer, ShadowToken, SizeTokens, SpacingStep, TextRole,
    TextRoleStyle, ThemeDefinition, TokenError, TokenOverrides, Tokens, Value as TokenValue, Variant,
};

// =================================================================
// ThemeData — 纯数据,无 Widget 概念
// =================================================================

/// Text style defaults (theme-level).
/// Individual TextWidget can override via TextStyle.
#[derive(Debug, Clone, PartialEq)]
pub struct TextTheme {
    pub headline: TextStyleTheme,
    pub title: TextStyleTheme,
    pub body: TextStyleTheme,
    pub caption: TextStyleTheme,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TextStyleTheme {
    pub font_size: f32,
    pub color: Color,
}

/// Button style defaults.
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonStyle {
    pub background: Color,
    pub foreground: Color,
    pub radius: f32,
    /// 全局焦点环颜色(button / checkbox / input / nav 等复用同一令牌)
    pub focus_ring_color: Color,
    /// 全局焦点环宽度
    pub focus_ring_width: f32,
}

/// 按钮语义变体(对应组件侧 `ButtonType`)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonVariant {
    /// 主操作
    Primary,
    /// 中性 / 次要操作(可有描边)
    Normal,
    /// 三级 / 低强调
    Tertiary,
    /// 成功
    Success,
    /// 警告
    Warning,
    /// 危险
    Error,
    /// 信息
    Info,
}

/// 单个按钮变体的五态配色。
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonVariantStyle {
    pub background: Color,
    pub foreground: Color,
    /// `Color::TRANSPARENT` = 无描边
    pub border: Color,
    pub hover_background: Color,
    pub pressed_background: Color,
}

/// 全部按钮变体。
#[derive(Debug, Clone, PartialEq)]
pub struct ButtonVariants {
    pub primary: ButtonVariantStyle,
    pub normal: ButtonVariantStyle,
    pub tertiary: ButtonVariantStyle,
    pub success: ButtonVariantStyle,
    pub warning: ButtonVariantStyle,
    pub error: ButtonVariantStyle,
    pub info: ButtonVariantStyle,
}

impl ButtonVariants {
    /// 按语义变体取样式。
    pub fn get(&self, variant: ButtonVariant) -> &ButtonVariantStyle {
        match variant {
            ButtonVariant::Primary => &self.primary,
            ButtonVariant::Normal => &self.normal,
            ButtonVariant::Tertiary => &self.tertiary,
            ButtonVariant::Success => &self.success,
            ButtonVariant::Warning => &self.warning,
            ButtonVariant::Error => &self.error,
            ButtonVariant::Info => &self.info,
        }
    }
}

/// Avatar 样式(首字头像)。
#[derive(Debug, Clone, PartialEq)]
pub struct AvatarStyle {
    /// 按名称哈希轮换的底色池
    pub palette: [Color; 6],
    pub foreground: Color,
}

/// 表单控件(Checkbox / Radio / Toggle / Slider)的控件令牌,由 Astryx token 推导(见 `ThemeData::from_tokens`)。
#[derive(Debug, Clone, PartialEq)]
pub struct ControlStyle {
    /// 未选中控件底色(color-background-control-default)
    pub background: Color,
    /// 控件描边(color-border-control-default)
    pub border: Color,
    /// 选中底色(color-background-control-checked)
    pub checked_background: Color,
    /// 选中前景(对勾 / 圆点颜色)
    pub checked_foreground: Color,
    /// 禁用底色(color-background-control-disabled)
    pub disabled_background: Color,
    /// 禁用描边
    pub disabled_border: Color,
    /// Toggle 关闭态轨道(color-background-toggle-default)
    pub toggle_off: Color,
    /// Slider 轨道底色(color-background-slider-track-default)
    pub slider_track: Color,
    /// Slider 拖拽中已填充段(color-background-slider-range-active)
    pub slider_range_active: Color,
}

/// 表单控件的**几何**令牌(Checkbox / Radio 的指示器尺寸、描边、焦点环)。
///
/// 与 [`ControlStyle`](只管颜色)分开,是为了把两种来源写清楚:
/// - `border_width` / `focus_ring_*` / `label_gap` 来自 token(`--border-width`、
///   `--focus-outline-width`、`--focus-outline-offset`、`--spacing-2`),改 token 就该跟着变;
/// - `indicator_size` 是 Astryx **组件 CSS 里的常量**(Checkbox / Radio 指示器实测 24×24),
///   Astryx 自己也没有为它设 token,所以这里是有出处的常量,不伪装成 token。
///   出处与测量方式见 `crates/mgui-core/src/theme/tokens.rs`。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ControlGeometry {
    /// Checkbox / Radio 指示器边长,见 [`MGUI_INDICATOR_SIZE`](Astryx 原值 24,mgui 取 18)。
    pub indicator_size: f32,
    /// 指示器描边宽度(`--border-width`)。
    pub border_width: f32,
    /// 指示器与标签的间距(`--spacing-2`)。
    pub label_gap: f32,
    /// 焦点环线宽(`--focus-outline-width`)。
    pub focus_ring_width: f32,
    /// 焦点环与控件之间的间隙(`--focus-outline-offset`)。
    pub focus_ring_offset: f32,
    /// 指示器圆角:Checkbox 用 `--radius-inner`;Radio 画成正圆(边长一半)。
    pub indicator_radius: f32,
    /// 按钮三档高度(**token 驱动**:`--size-element-sm/md/lg`,Astryx 实测 Button/IconButton 就是按档取)。
    pub button_height_sm: f32,
    pub button_height_md: f32,
    pub button_height_lg: f32,
    /// 按钮水平内距(`--spacing-3`,Astryx Button 实测 12px)。
    pub button_padding_h: f32,
    /// 按钮描边宽度(`--border-width`;以前组件里写死 1.5)。
    pub button_border_width: f32,
    /// Toggle 轨道尺寸与滑块(Astryx 组件 CSS 实测 40×24、滑块 20、内缩 2)。
    pub switch_width: f32,
    pub switch_height: f32,
    pub switch_thumb: f32,
    pub switch_thumb_inset: f32,
    /// Slider 轨道粗细与滑块边长(Astryx 实测 4 / 20;滑块色是 `--color-icon-primary`)。
    pub slider_track_height: f32,
    pub slider_thumb_size: f32,
}

impl Default for ControlGeometry {
    /// 默认档(token 取基表值,指示器尺寸见 [`MGUI_INDICATOR_SIZE`])
    fn default() -> Self {
        Self {
            indicator_size: MGUI_INDICATOR_SIZE,
            border_width: 1.0,
            label_gap: 8.0,
            focus_ring_width: 2.0,
            focus_ring_offset: 3.0,
            switch_width: 40.0,
            switch_height: 24.0,
            switch_thumb: 20.0,
            switch_thumb_inset: 2.0,
            slider_track_height: 4.0,
            slider_thumb_size: 20.0,
            indicator_radius: 4.0,
            button_height_sm: 28.0,
            button_height_md: 32.0,
            button_height_lg: 36.0,
            button_padding_h: 12.0,
            button_border_width: 1.0,
        }
    }
}

impl ControlGeometry {
    /// 按档取按钮高度:0 = sm、1 = md、2 = lg(越界按 lg 收)。
    ///
    /// 组件侧的 `ButtonSize` 只负责把枚举映射成下标,高度本身仍来自 token,
    /// 这样 `--size-element-md` 一改,Button 和 IconButton 会一起动。
    pub fn button_height_at(&self, which: usize) -> f32 {
        match which {
            0 => self.button_height_sm,
            1 => self.button_height_md,
            _ => self.button_height_lg,
        }
    }
}

/// Checkbox / Radio 指示器边长。
///
/// **这是对 Astryx 的有意偏离**:Astryx 组件 CSS 实测是 24×24
/// (见 `crates/mgui-core/src/theme/tokens.rs`),但它配的是自己的行高与间距语境;
/// mgui 正文默认 14px,24 的盒子压在 14px 文字旁边比例失衡(真机反馈"太大、跟文字不衬"),
/// 所以这里取 18。要回到 Astryx 原值只改这一个常量即可。
pub const MGUI_INDICATOR_SIZE: f32 = 18.0;

/// sRGB 相对亮度(WCAG 2.x 定义)。
fn luminance(color: Color) -> f32 {
    let channel = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
    0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b)
}

/// 反色容器(Tooltip 这类"底色用 `--color-background-inverted`"的小块)上该写哪种前景。
///
/// Astryx 用 `--color-on-dark` / `--color-on-light` 两个 token 表达这件事,按底色明暗二选一。
fn best_on(tokens: &Tokens, background: Color) -> Color {
    use crate::theme::tokens::ColorToken;
    // 暗底用 --color-on-dark,亮底用 --color-on-light
    if luminance(background) < 0.5 {
        tokens.color(ColorToken::OnDark)
    } else {
        tokens.color(ColorToken::OnLight)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ScrollbarStyle {
    pub thumb_color: Color,
    /// 指针悬停(或拖拽中)在 thumb 上时的高亮色
    pub thumb_hover_color: Color,
    pub thumb_radius: f32,
    /// 交叉轴上的可见宽度(命中带由 `scrollbar_bands` 从它推出来)
    pub thumb_width: f32,
    /// 交叉轴命中带的最小宽度;比 `thumb_width` 窄时不会裁掉可见 thumb
    pub hit_width: f32,
    /// 主轴 thumb 长度下限(长列表真正决定 thumb 长短的是这个,见 `MIN_VISIBLE_RATIO`)
    pub thumb_min_size: f32,
}

/// TextField / 输入框样式(描边输入框 + 主色焦点环,颜色全部来自 `--color-*`)。
#[derive(Debug, Clone, PartialEq)]
pub struct InputStyle {
    pub background: Color,
    pub border: Color,
    pub focused_border: Color,
    pub text_color: Color,
    pub placeholder_color: Color,
    pub radius: f32,
}

/// Tooltip 浮层样式。
#[derive(Debug, Clone, PartialEq)]
pub struct TooltipStyle {
    pub background: Color,
    pub foreground: Color,
    pub border: Color,
    pub radius: f32,
}

/// 菜单 / 右键 ContextMenu / 下拉列表样式。
#[derive(Debug, Clone, PartialEq)]
pub struct MenuStyle {
    pub background: Color,
    pub foreground: Color,
    pub hover_background: Color,
    pub border: Color,
    pub radius: f32,
}

/// TabBar / TabView / TabbedPane 样式。
#[derive(Debug, Clone, PartialEq)]
pub struct TabStyle {
    pub background: Color,
    pub active_foreground: Color,
    pub inactive_foreground: Color,
    pub hover_background: Color,
    pub indicator_color: Color,
}

/// NavigationMenu 样式。
#[derive(Debug, Clone, PartialEq)]
pub struct NavStyle {
    pub active_background: Color,
    pub active_foreground: Color,
    pub foreground: Color,
    pub hover_background: Color,
    pub indicator_color: Color,
}

/// 反馈类组件样式(进度条 / Toast 等)。
#[derive(Debug, Clone, PartialEq)]
pub struct FeedbackStyle {
    pub progress_track: Color,
    pub progress_value: Color,
    pub success: Color,
    pub warning: Color,
    /// 信息态强调色(Toast Info 等)
    pub info: Color,
    /// 错误态强调色(与全局 `error` 同源,供状态容器统一取用)
    pub error: Color,
}

/// Dropdown 触发器 + 弹出面板样式。
#[derive(Debug, Clone, PartialEq)]
pub struct DropdownStyle {
    pub background: Color,
    pub foreground: Color,
    pub placeholder: Color,
    pub border: Color,
    pub open_border: Color,
    pub hover: Color,
    pub selected_background: Color,
    pub disabled: Color,
}

/// Dialog 遮罩 + 对话框样式。
#[derive(Debug, Clone, PartialEq)]
pub struct DialogStyle {
    pub barrier: Color,
    pub background: Color,
    pub radius: f32,
}

/// ListView / 列表类样式。
#[derive(Debug, Clone, PartialEq)]
pub struct ListStyle {
    pub hover_background: Color,
    pub selected_background: Color,
    pub foreground: Color,
}

/// 4pt 间距刻度 + 组件默认间距(由 `--spacing-*` 生成)。
#[derive(Debug, Clone, PartialEq)]
pub struct SpacingScale {
    /// 2 — 徽标/gap 微调
    pub xxs: f32,
    /// 4 — 图标与文字
    pub xs: f32,
    /// 8 — 控件内边距 / 紧凑 gap
    pub s: f32,
    /// 16 — 容器内边距 / 常规 gap
    pub m: f32,
    /// 24 — 区块间距
    pub l: f32,
    /// 32 — 页面级间距
    pub xl: f32,
    /// 叶子控件默认内边距
    pub control_padding: f32,
    /// 容器默认内边距
    pub container_padding: f32,
    /// 容器未显式指定 gap 时的默认子项间距
    pub container_gap: f32,
}

impl Default for SpacingScale {
    fn default() -> Self {
        Self {
            xxs: 2.0,
            xs: 4.0,
            s: 8.0,
            m: 16.0,
            l: 24.0,
            xl: 32.0,
            control_padding: 8.0,
            container_padding: 16.0,
            container_gap: 8.0,
        }
    }
}

/// 主题色板 + 子主题。
///
/// 所有 `update_should_notify` 走 `PartialEq` 派生自动比较。
///
/// 风格基准:**Astryx Design System 的 `Neutral` 主题**
/// ([`tokens`] 层的基表 + scale + 覆盖 → [`ThemeData::from_tokens`];
/// `dark()` / `light()` 是 `neutral(true)` / `neutral(false)` 的别名)。
///
/// 想改主题就改 token:`define_theme().token("--color-accent", "#7B61FF")`
/// 或 `radius_multiplier(1.5)`,再 `ThemeData::from_tokens(&def.resolve(dark))`。
/// 通用令牌(border / divider / hover)供全部组件共享,做到"一次改 token、全局换肤"。
#[derive(Debug, Clone, PartialEq)]
pub struct ThemeData {
    // --- ColorScheme (core) ---
    pub background: Color,
    pub foreground: Color,
    pub primary: Color,
    pub accent: Color,
    pub surface: Color,
    pub error: Color,
    /// 高对比度变体标记(由 [`ThemeData::high_contrast`] 设置)。
    pub high_contrast: bool,

    // --- 通用令牌(全组件共享) ---
    pub border: Color,    // 组件描边
    pub divider: Color,   // Divider / 分隔线
    pub hover: Color,     // hover 覆盖层(带 alpha)
    pub disabled: Color,  // 禁用态前景(或带 alpha 覆盖)
    pub selection: Color, // 文本/列表选中背景(primary 系 alpha)
    pub icon: Color,      // 图标默认 tint

    // --- Radius ---
    pub radius_sm: f32, // 4.0 — badge / checkbox
    pub radius_md: f32, // 8.0 — input / item
    pub radius_lg: f32, // 16.0 — dialog / menu / large container

    // --- Spacing ---
    pub spacing: f32, // 8.0 — default widget spacing
    /// 4pt 间距刻度与组件默认间距
    pub space: SpacingScale,

    // --- Sub-themes ---
    pub text: TextTheme,
    pub button: ButtonStyle,
    /// 按钮语义变体色板(Primary/Normal/Tertiary/Success/Warning/Error/Info)
    pub button_variants: ButtonVariants,
    /// Avatar 首字头像样式
    pub avatar: AvatarStyle,
    /// 表单控件令牌(Checkbox/Radio/Toggle/Slider)
    pub control: ControlStyle,
    /// 表单控件几何(指示器尺寸 / 描边 / 焦点环),见 [`ControlGeometry`]
    pub geom: ControlGeometry,
    pub scrollbar: ScrollbarStyle,
    pub input: InputStyle,
    pub tooltip: TooltipStyle,
    pub menu: MenuStyle,
    pub tab: TabStyle,
    pub nav: NavStyle,
    pub feedback: FeedbackStyle,
    pub dropdown: DropdownStyle,
    pub dialog: DialogStyle,
    pub list: ListStyle,
}

impl Default for ThemeData {
    fn default() -> Self {
        Self::neutral_dark()
    }
}

impl ThemeData {
    /// 深色主题(Astryx `Neutral` 暗档)。
    pub fn dark() -> Self {
        Self::neutral_dark()
    }

    /// 浅色主题(Astryx `Neutral` 明档)。
    pub fn light() -> Self {
        Self::neutral_light()
    }
    /// Astryx `Neutral` 主题 —— 由 [`tokens`] 层的基表 + scale + 覆盖解析而来。
    ///
    /// `dark=true` 取每个 `light-dark(明, 暗)` 的暗档。
    pub fn neutral(dark: bool) -> Self {
        Self::from_tokens(&crate::theme::tokens::define_theme().resolve(dark))
    }

    pub fn neutral_light() -> Self {
        Self::neutral(false)
    }

    pub fn neutral_dark() -> Self {
        Self::neutral(true)
    }

    /// 由一份已解析的 token 集推导组件用的 `ThemeData`。
    ///
    /// 这是"主题修改功能"的落点:应用改任意 token(`define_theme().token(...)`),
    /// 这里就把整套子主题重算一遍。映射原则:
    ///
    /// - 每个颜色都能追溯到一个 `--color-*`,本地不做调色(不再混色、不再硬编码 hex);
    /// - hover / pressed 是**叠加层**,先与所在容器色合成再填(见 [`tokens::overlay`]);
    /// - 圆角、控件高度、间距、字号全部走 token,所以 radius / 密度 / 字号 scale 会整体生效;
    /// - 状态色用 `--color-text-*`(保证在容器上的对比度),填充按钮用 `--color-*` + `--color-on-*`。
    pub fn from_tokens(tokens: &Tokens) -> Self {
        use crate::theme::tokens::{ColorToken as C, SpacingStep as S, TextRole as R};

        let color = |token: C| tokens.color(token);
        let radius = tokens.radius();
        let focus = tokens.focus();
        let surface = color(C::BackgroundSurface);
        let popover = color(C::BackgroundPopover);
        let accent = color(C::Accent);

        let filled_variant = |fill: C, on: C| ButtonVariantStyle {
            background: color(fill),
            foreground: color(on),
            border: Color::TRANSPARENT,
            hover_background: tokens.hovered(color(fill)),
            pressed_background: tokens.pressed(color(fill)),
        };
        let button_variants = ButtonVariants {
            primary: filled_variant(C::Accent, C::OnAccent),
            normal: ButtonVariantStyle {
                background: surface,
                foreground: color(C::TextPrimary),
                border: color(C::BorderEmphasized),
                hover_background: tokens.hovered(surface),
                pressed_background: tokens.pressed(surface),
            },
            tertiary: ButtonVariantStyle {
                background: Color::TRANSPARENT,
                foreground: color(C::TextPrimary),
                border: Color::TRANSPARENT,
                hover_background: color(C::OverlayHover),
                pressed_background: color(C::OverlayPressed),
            },
            success: filled_variant(C::Success, C::OnSuccess),
            warning: filled_variant(C::Warning, C::OnWarning),
            error: filled_variant(C::Error, C::OnError),
            info: filled_variant(C::Info, C::OnInfo),
        };

        // Astryx 的 Tooltip 是反色小块,前景按底色明暗取 --color-on-dark / --color-on-light
        let tooltip_bg = color(C::BackgroundInverted);
        let body = tokens.text_role(R::Body);
        let heading = tokens.text_role(R::HeadingTwo);
        let text = TextTheme {
            headline: TextStyleTheme { font_size: tokens.text_role(R::HeadingOne).size, color: color(C::TextPrimary) },
            title: TextStyleTheme { font_size: heading.size, color: color(C::TextPrimary) },
            body: TextStyleTheme { font_size: body.size, color: color(C::TextPrimary) },
            caption: TextStyleTheme { font_size: tokens.text_role(R::Supporting).size, color: color(C::TextSecondary) },
        };

        let track = color(C::Track);
        let scrollbar = ScrollbarStyle {
            thumb_color: track,
            thumb_hover_color: color(C::BorderEmphasized),
            thumb_radius: radius.inner,
            // 可见 8px(--spacing-2)/ 命中 10px,外沿再留 2px 视觉空隙 —— 带的算法在 scrollbar_bands
            thumb_width: tokens.spacing(S::S2),
            hit_width: tokens.spacing(S::S2) + 2.0,
            // 长列表里 thumb 长度实际由这个下限决定(--spacing-6 = 24px)
            thumb_min_size: tokens.spacing(S::S6),
        };

        // 按钮三档高度是真 token(--size-element-sm/md/lg)
        let size = tokens.element_size();

        Self {
            background: color(C::BackgroundBody),
            foreground: color(C::TextPrimary),
            primary: accent,
            accent: color(C::TextAccent),
            surface,
            error: color(C::TextError),
            high_contrast: false,
            border: color(C::Border),
            divider: color(C::Border),
            hover: color(C::OverlayHover),
            disabled: color(C::TextDisabled),
            selection: color(C::AccentMuted),
            icon: color(C::IconPrimary),
            radius_sm: radius.inner,
            radius_md: radius.element,
            radius_lg: radius.container,
            spacing: tokens.spacing(S::S2),
            space: SpacingScale {
                xxs: tokens.spacing(S::S0_5),
                xs: tokens.spacing(S::S1),
                s: tokens.spacing(S::S2),
                m: tokens.spacing(S::S4),
                l: tokens.spacing(S::S6),
                xl: tokens.spacing(S::S8),
                control_padding: tokens.spacing(S::S2),
                container_padding: tokens.spacing(S::S4),
                container_gap: tokens.spacing(S::S2),
            },
            text,
            button: ButtonStyle {
                background: accent,
                foreground: color(C::OnAccent),
                radius: radius.element,
                focus_ring_color: focus.color,
                focus_ring_width: focus.width,
            },
            button_variants,
            avatar: AvatarStyle {
                // Astryx Avatar 按名字哈希在分类色里轮换,前景用反色档
                palette: [
                    color(C::DataCategoricalBlue),
                    color(C::DataCategoricalGreen),
                    color(C::DataCategoricalOrange),
                    color(C::DataCategoricalPurple),
                    color(C::DataCategoricalRed),
                    color(C::DataCategoricalTeal),
                ],
                foreground: color(C::OnAccent),
            },
            control: ControlStyle {
                background: surface,
                border: color(C::BorderEmphasized),
                checked_background: accent,
                checked_foreground: color(C::OnAccent),
                disabled_background: color(C::BackgroundMuted),
                disabled_border: color(C::Border),
                toggle_off: track,
                slider_track: track,
                slider_range_active: accent,
            },
            geom: ControlGeometry {
                // 组件常量:见 MGUI_INDICATOR_SIZE(Astryx 原值 24,这里有意收到 18 以配 14px 正文)
                indicator_size: MGUI_INDICATOR_SIZE,
                border_width: tokens.border_width(),
                label_gap: tokens.spacing(S::S2),
                focus_ring_width: focus.width,
                focus_ring_offset: focus.offset,
                indicator_radius: radius.inner,
                // Toggle / Slider 的尺寸同样是 Astryx 组件 CSS 实测常量(见 theme-tokens.md 规格表)
                switch_width: 40.0,
                switch_height: 24.0,
                switch_thumb: 20.0,
                switch_thumb_inset: 2.0,
                slider_track_height: 4.0,
                slider_thumb_size: 20.0,
                // 按钮这三档是真 token:element_size() / --spacing-3 / --border-width
                button_height_sm: size.sm,
                button_height_md: size.md,
                button_height_lg: size.lg,
                button_padding_h: tokens.spacing(S::S3),
                button_border_width: tokens.border_width(),
            },
            scrollbar,
            input: InputStyle {
                background: surface,
                border: color(C::BorderEmphasized),
                focused_border: focus.color,
                text_color: color(C::TextPrimary),
                placeholder_color: color(C::TextSecondary),
                radius: radius.element,
            },
            tooltip: TooltipStyle {
                background: tooltip_bg,
                foreground: best_on(tokens, tooltip_bg),
                border: Color::TRANSPARENT,
                radius: radius.element,
            },
            menu: MenuStyle {
                background: popover,
                foreground: color(C::TextPrimary),
                hover_background: tokens.hovered(popover),
                border: color(C::Border),
                radius: radius.container,
            },
            tab: TabStyle {
                background: surface,
                active_foreground: color(C::TextPrimary),
                inactive_foreground: color(C::TextSecondary),
                hover_background: tokens.hovered(surface),
                indicator_color: accent,
            },
            nav: NavStyle {
                active_background: color(C::AccentMuted),
                active_foreground: color(C::TextAccent),
                foreground: color(C::TextPrimary),
                hover_background: tokens.hovered(surface),
                indicator_color: accent,
            },
            feedback: FeedbackStyle {
                progress_track: track,
                progress_value: accent,
                success: color(C::TextSuccess),
                warning: color(C::TextWarning),
                info: color(C::TextInfo),
                error: color(C::TextError),
            },
            dropdown: DropdownStyle {
                background: popover,
                foreground: color(C::TextPrimary),
                placeholder: color(C::TextSecondary),
                border: color(C::BorderEmphasized),
                open_border: focus.color,
                hover: tokens.hovered(popover),
                selected_background: color(C::AccentMuted),
                disabled: color(C::TextDisabled),
            },
            dialog: DialogStyle {
                barrier: color(C::Overlay),
                background: color(C::BackgroundCard),
                radius: radius.container,
            },
            list: ListStyle {
                hover_background: tokens.hovered(surface),
                selected_background: color(C::AccentMuted),
                foreground: color(C::TextPrimary),
            },
        }
    }

    /// 高对比度主题(Windows 高对比度 / 强制对比模式的通用替代)。
    ///
    /// 与 `neutral` 走同一条路:**只覆盖 token**,所有子主题由 [`ThemeData::from_tokens`]
    /// 一起重算,不再逐个字段覆写。强制的内容:
    /// - 前景/背景 ≥ 7:1,边框/背景 ≥ 3:1,主色/背景 ≥ 4.5:1;
    /// - 关键文本使用纯黑/纯白,边框与分割线使用前景色;
    /// - `--radius-*` 归零、`--focus-outline-width` 提到 3px,便于低视力用户辨识;
    /// - hover / 选中改用高 alpha 叠加层,不再用低对比的 muted 档。
    ///
    /// `dark=true` 为黑底白字/金黄主色;`false` 为白底黑字/深蓝主色。
    /// 系统高对比度色板由平台提供时,应用仍可自行替换核心令牌。
    pub fn high_contrast(dark: bool) -> Self {
        use crate::theme::tokens::ColorToken as C;

        let (bg, fg, dim, primary, on_primary, focus, info, error, success, warning, hover, selection, barrier) =
            if dark {
                (
                    Color::BLACK,
                    Color::WHITE,
                    Color::from_rgb8(0xB0, 0xB0, 0xB0),
                    Color::from_rgb8(0xFF, 0xD7, 0x00),
                    Color::BLACK,
                    Color::WHITE,
                    Color::from_rgb8(0x00, 0xFF, 0xFF),
                    Color::from_rgb8(0xFF, 0x80, 0x80),
                    Color::from_rgb8(0x7C, 0xFC, 0x7C),
                    Color::from_rgb8(0xFF, 0xD7, 0x00),
                    Color::rgba(1.0, 1.0, 1.0, 0.20),
                    Color::rgba(1.0, 0.843, 0.0, 0.35),
                    Color::rgba(0.0, 0.0, 0.0, 0.85),
                )
            } else {
                (
                    Color::WHITE,
                    Color::BLACK,
                    Color::from_rgb8(0x50, 0x50, 0x50),
                    Color::from_rgb8(0x00, 0x33, 0xCC),
                    Color::WHITE,
                    Color::BLACK,
                    Color::from_rgb8(0x00, 0x5A, 0x5A),
                    Color::from_rgb8(0xB0, 0x00, 0x20),
                    Color::from_rgb8(0x00, 0x64, 0x00),
                    Color::from_rgb8(0x7A, 0x4F, 0x00),
                    Color::rgba(0.0, 0.0, 0.0, 0.12),
                    Color::rgba(0.0, 0.2, 0.8, 0.18),
                    Color::rgba(0.0, 0.0, 0.0, 0.60),
                )
            };

        let mut def = define_theme().named("high-contrast");
        for (token, color) in [
            // 所有容器拉平到同一底色:高对比度下层次靠描边表达,不靠背景明暗
            (C::BackgroundBody, bg),
            (C::BackgroundSurface, bg),
            (C::BackgroundCard, bg),
            (C::BackgroundPopover, bg),
            (C::BackgroundMuted, bg),
            (C::BackgroundInverted, fg),
            (C::TextPrimary, fg),
            (C::TextSecondary, dim),
            (C::TextDisabled, dim),
            (C::TextAccent, primary),
            (C::TextInfo, info),
            (C::TextSuccess, success),
            (C::TextWarning, warning),
            (C::TextError, error),
            (C::IconPrimary, fg),
            (C::IconSecondary, dim),
            (C::IconDisabled, dim),
            (C::Accent, primary),
            (C::AccentMuted, selection),
            (C::OnAccent, on_primary),
            (C::Info, info),
            (C::OnInfo, on_primary),
            (C::Success, success),
            (C::OnSuccess, on_primary),
            (C::Warning, warning),
            (C::OnWarning, on_primary),
            (C::Error, error),
            (C::OnError, on_primary),
            (C::Border, fg),
            (C::BorderEmphasized, fg),
            (C::BorderInfo, info),
            (C::BorderSuccess, success),
            (C::BorderWarning, warning),
            (C::BorderError, error),
            (C::OverlayHover, hover),
            (C::OverlayPressed, hover),
            (C::Overlay, barrier),
            (C::Track, dim),
            (C::Skeleton, dim),
            (C::Shadow, bg),
            (C::FocusOutline, focus),
            // Avatar 轮换池换成低亮度底,保证 on-dark 白字仍可读
            (C::DataCategoricalBlue, Color::from_rgb8(0x00, 0x50, 0x80)),
            (C::DataCategoricalGreen, Color::from_rgb8(0x00, 0x50, 0x00)),
            (C::DataCategoricalOrange, Color::from_rgb8(0x6B, 0x2A, 0x00)),
            (C::DataCategoricalPurple, Color::from_rgb8(0x3B, 0x00, 0x80)),
            (C::DataCategoricalRed, Color::from_rgb8(0x90, 0x00, 0x00)),
            (C::DataCategoricalTeal, Color::from_rgb8(0x00, 0x4A, 0x4A)),
        ] {
            def.set_color(token, color, color);
        }
        for name in [
            "--radius-inner",
            "--radius-element",
            "--radius-container",
            "--radius-page",
            "--radius-chat",
            "--focus-outline-width",
        ] {
            let value = if name == "--focus-outline-width" { "3px" } else { "0px" };
            def.set_token(name, value).expect("内置 token 名与形状必然合法");
        }

        let mut theme = Self::from_tokens(&def.resolve(dark));
        theme.high_contrast = true;
        theme
    }
}

// =================================================================
// Direction — 文本方向(Ltr / Rtl)
// =================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Direction {
    #[default]
    Ltr,
    Rtl,
}

// =================================================================
// ThemeWidget + InheritedWidget impl
// =================================================================

/// 用户显式颜色优先,否则回退到主题/token 值。
///
/// P1-8:用 `Option` 表达"未覆盖",不再依赖与默认色相等的 sentinel 判断
/// (用户显式选择与哨兵相同的颜色时也能正确覆盖)。
pub const fn resolve_color(explicit: Option<Color>, themed: Color) -> Color {
    match explicit {
        Some(color) => color,
        None => themed,
    }
}

/// 数值版 `resolve_color`:显式尺寸/宽度优先,否则用主题/回退值。
pub const fn resolve_f32(explicit: Option<f32>, themed: f32) -> f32 {
    match explicit {
        Some(value) => value,
        None => themed,
    }
}

/// Theme 提供者 widget。挂到树中,所有后代可通过 `ctx.theme()` 访问。
///
/// `theme` 用 `Rc` 共享:State 缓存主题时只 clone 引用,不再复制整份 ThemeData。
#[derive(Debug)]
pub struct ThemeWidget {
    pub theme: Rc<ThemeData>,
    pub direction: Direction,
    pub child: Option<WidgetNode>,
}

impl ThemeWidget {
    pub fn new(theme: ThemeData) -> Self {
        Self::from_rc(Rc::new(theme))
    }

    pub fn from_rc(theme: Rc<ThemeData>) -> Self {
        Self { theme, direction: Direction::Ltr, child: None }
    }

    pub fn dark() -> Self {
        Self::new(ThemeData::dark())
    }

    pub fn light() -> Self {
        Self::new(ThemeData::light())
    }

    pub fn with_direction(mut self, d: Direction) -> Self {
        self.direction = d;
        self
    }

    pub fn child(mut self, c: impl Widget) -> Self {
        self.child = Some(WidgetNode::new(c));
        self
    }

    pub fn child_node(mut self, c: WidgetNode) -> Self {
        self.child = Some(c);
        self
    }
}

impl InheritedWidget for ThemeWidget {
    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
        // downcast old 到 ThemeWidget 比较 theme + direction
        if let Some(old_theme) = old.as_any().downcast_ref::<ThemeWidget>() {
            if Rc::ptr_eq(&self.theme, &old_theme.theme) {
                return self.direction != old_theme.direction;
            }
            *self.theme != *old_theme.theme || self.direction != old_theme.direction
        } else {
            true
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl ThemeWidget {
    pub fn theme(&self) -> &ThemeData {
        &self.theme
    }

    pub fn direction(&self) -> Direction {
        self.direction
    }
}

impl Widget for ThemeWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
        Some(self)
    }

    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
        // 透传 child RO,但必须**包一层 ProxyRenderObject**:
        // 直接把 child widget 的 RO 树当自己的 RO,会让 element 树(1 个 child)
        // 与 RO 树(child 的整棵子树)不同构;propagate 只能按索引替换前 N 个 slot,
        // 其余 slot 成为陈旧副本(Theme 根节点会重复绘制 nested boundary)。
        match &self.child {
            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        }
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.clone().into_iter().collect()
    }

    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
    }
}

// =================================================================
// DirectionWidget — 单独暴露 direction(如果只想用 Direction 不想用 Theme)
// =================================================================

/// 单独的 Direction 提供者,方便只想换方向不换主题的场景。
#[derive(Debug)]
pub struct DirectionWidget {
    pub direction: Direction,
    pub child: Option<WidgetNode>,
}

impl DirectionWidget {
    pub fn new(d: Direction) -> Self {
        Self { direction: d, child: None }
    }

    pub fn child(mut self, c: impl Widget) -> Self {
        self.child = Some(WidgetNode::new(c));
        self
    }
}

impl InheritedWidget for DirectionWidget {
    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
        if let Some(old_dir) = old.as_any().downcast_ref::<DirectionWidget>() {
            self.direction != old_dir.direction
        } else {
            true
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl DirectionWidget {
    pub fn direction(&self) -> Direction {
        self.direction
    }
}

impl Widget for DirectionWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
        Some(self)
    }

    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
        // 与 ThemeWidget 相同:透传 child 必须包 Proxy,保证 element/RO 同构。
        match &self.child {
            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        }
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.clone().into_iter().collect()
    }

    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
    }
}

// =================================================================
// LocaleSnapshot / LocaleWidget — 运行时语言切换(0.7)
// =================================================================

/// 应用级语言快照。只存 BCP-47 子集 tag,不依赖 i18n crate;`mgui-i18n` 负责解析/格式化。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleSnapshot {
    pub tag: Rc<str>,
    pub direction: Direction,
    /// 每次真实语言变化推进;同 tag 重复设置不 bump。用于精准失效文案/RTL 布局。
    pub generation: u64,
}

impl LocaleSnapshot {
    pub fn new(tag: impl Into<Rc<str>>, direction: Direction, generation: u64) -> Self {
        Self { tag: tag.into(), direction, generation }
    }

    pub fn tag(&self) -> &str {
        &self.tag
    }
}

/// 语言提供者。切换语言时替换 `LocaleWidget`,后代通过 `ctx.locale()` 自动 dirty。
#[derive(Debug)]
pub struct LocaleWidget {
    pub locale: LocaleSnapshot,
    pub child: Option<WidgetNode>,
}

impl LocaleWidget {
    pub fn new(locale: LocaleSnapshot) -> Self {
        Self { locale, child: None }
    }

    pub fn child_node(mut self, c: WidgetNode) -> Self {
        self.child = Some(c);
        self
    }

    pub fn locale(&self) -> &LocaleSnapshot {
        &self.locale
    }
}

impl InheritedWidget for LocaleWidget {
    fn update_should_notify(&self, old: &dyn InheritedWidget) -> bool {
        old.as_any().downcast_ref::<LocaleWidget>().map(|old| self.locale != old.locale).unwrap_or(true)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Widget for LocaleWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_inherited(&self) -> Option<&dyn crate::inherited::InheritedWidget> {
        Some(self)
    }

    fn create_render_object(&self) -> Box<dyn crate::render_object::RenderObject> {
        match &self.child {
            Some(c) => Box::new(crate::render_object::ProxyRenderObject::new(c.0.create_render_object())),
            None => Box::new(crate::render_object::RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
        }
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.clone().into_iter().collect()
    }

    fn children_with_positions(&self) -> Vec<(Point, WidgetNode)> {
        self.child.clone().into_iter().map(|c| (Point::ZERO, c)).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::tokens::{ColorToken as C, FontSizeToken, LengthToken, SpacingStep};
    use super::*;
    use crate::inherited::InheritedWidget;

    #[test]
    fn locale_widget_notifies_on_generation_change() {
        let a = LocaleWidget::new(LocaleSnapshot::new("en", Direction::Ltr, 1));
        let b = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
        let same = LocaleWidget::new(LocaleSnapshot::new("ar", Direction::Rtl, 2));
        assert!(b.update_should_notify(&a));
        assert!(!same.update_should_notify(&b));
    }

    fn contrast(a: Color, b: Color) -> f32 {
        let (la, lb) = (luminance(a), luminance(b));
        (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
    }

    /// 用 token 覆盖生成一份主题,再推导 ThemeData。
    fn themed(definition: tokens::ThemeDefinition, dark: bool) -> ThemeData {
        ThemeData::from_tokens(&definition.resolve(dark))
    }

    #[test]
    fn neutral_palette_matches_astryx_tokens() {
        let light = ThemeData::neutral_light();
        assert_eq!(light.primary, Color::from_rgb8(0x00, 0x64, 0xE0));
        assert_eq!(light.background, Color::from_rgb8(0xF1, 0xF4, 0xF7));
        assert_eq!(light.surface, Color::WHITE);
        assert_eq!(light.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));
        assert_eq!(light.button.foreground, Color::WHITE);
        assert_eq!(light.button.radius, 8.0, "Astryx 按钮用 --radius-element");
        assert_eq!(light.input.radius, 8.0);
        assert_eq!(light.dialog.radius, 12.0, "Astryx 容器用 --radius-container");

        let dark = ThemeData::neutral_dark();
        assert_eq!(dark.primary, Color::from_rgb8(0x26, 0x94, 0xFE));
        assert_eq!(dark.background, Color::from_rgb8(0x11, 0x11, 0x12));
        assert_eq!(dark.surface, Color::from_rgb8(0x1F, 0x1F, 0x22));
        assert_eq!(dark.foreground, Color::from_rgb8(0xDF, 0xE2, 0xE5));
        // --color-on-error 在深色档是深字(白字在该底色上达不到 4.5:1)
        assert_eq!(dark.button_variants.error.foreground, Color::from_rgb8(0x0A, 0x13, 0x17));

        // 尺寸与间距全部来自 token,不再散落硬编码
        assert_eq!((light.radius_sm, light.radius_md, light.radius_lg), (4.0, 8.0, 12.0));
        assert_eq!(light.text.body.font_size, 14.0, "--text-body-size");
        assert_eq!(light.text.headline.font_size, 24.0, "--text-heading-1-size");
        assert_eq!(light.text.caption.font_size, 12.0, "--text-supporting-size");
        assert_eq!(light.spacing, 8.0, "--spacing-2");
        assert_eq!(light.scrollbar.thumb_width, 8.0);
    }

    #[test]
    fn aliases_and_default_are_the_same_theme() {
        assert_eq!(ThemeData::dark(), ThemeData::neutral(true));
        assert_eq!(ThemeData::light(), ThemeData::neutral(false));
        assert_eq!(ThemeData::default(), ThemeData::neutral_dark());
        assert_ne!(ThemeData::neutral_light(), ThemeData::neutral_dark());
    }

    /// 按钮三档高度/内距/描边必须是真 token 驱动(#91 的 Button / IconButton 就靠这几条):
    /// 改 `--size-element-md`、`--spacing-3`、`--border-width` 都要反映到 `ThemeData::geom`。
    #[test]
    fn button_metrics_follow_element_spacing_and_border_tokens() {
        let base = themed(define_theme(), false);
        assert_eq!(
            (base.geom.button_height_sm, base.geom.button_height_md, base.geom.button_height_lg),
            (28.0, 32.0, 36.0),
            "Astryx --size-element-sm/md/lg 默认档"
        );
        assert_eq!((base.geom.button_padding_h, base.geom.button_border_width), (12.0, 1.0));

        let tuned = themed(
            define_theme()
                .token("--size-element-md", "2.5rem")
                .expect("合法 token")
                .token("--spacing-3", "1rem")
                .expect("合法 token")
                .token("--border-width", "2px")
                .expect("合法 token"),
            false,
        );
        assert_eq!(tuned.geom.button_height_md, 40.0, "2.5rem = 40px,只有 md 变");
        assert_eq!((tuned.geom.button_height_sm, tuned.geom.button_height_lg), (28.0, 36.0));
        assert_eq!((tuned.geom.button_padding_h, tuned.geom.button_border_width), (16.0, 2.0));

        // 圆角倍率不该动高度(两轴各自独立)
        let rounded = themed(define_theme().radius_multiplier(1.5), false);
        assert_eq!(rounded.geom.button_height_md, 32.0);
        assert!(rounded.geom.indicator_radius > base.geom.indicator_radius);
    }

    #[test]
    fn emphasis_and_focus_all_follow_the_accent_token() {
        for t in [ThemeData::neutral_light(), ThemeData::neutral_dark()] {
            assert_eq!(t.button.focus_ring_color, t.primary);
            assert_eq!(t.tab.indicator_color, t.primary);
            assert_eq!(t.nav.indicator_color, t.primary);
            assert_eq!(t.feedback.progress_value, t.primary);
            assert_eq!(t.dropdown.open_border, t.primary);
            assert_eq!(t.input.focused_border, t.primary);
            assert_eq!(t.text.body.color, t.foreground);
            assert_eq!(t.button.focus_ring_width, 2.0, "--focus-outline-width");
        }
    }

    #[test]
    fn button_variants_and_avatar_come_from_status_tokens() {
        let light = ThemeData::neutral_light();
        assert_eq!(light.button_variants.primary.background, light.primary);
        assert_eq!(light.button_variants.primary.foreground, Color::WHITE);
        assert_eq!(light.button_variants.tertiary.background, Color::TRANSPARENT);
        assert_eq!(light.button_variants.normal.background, light.surface);
        assert_ne!(light.button_variants.normal.border, Color::TRANSPARENT, "常规按钮有描边");

        let dark = ThemeData::neutral_dark();
        assert_eq!(dark.button_variants.success.background, Color::from_rgb8(0x0D, 0x86, 0x26));
        assert_eq!(dark.button_variants.error.background, Color::from_rgb8(0xF5, 0x39, 0x4F));
        // 状态文本色(--color-text-*)与状态填充色(--color-*)是两套 token
        assert_ne!(dark.feedback.success, dark.button_variants.success.background);
        assert_eq!(dark.avatar.foreground, Color::WHITE, "分类色上写 --color-on-dark");
        let mut seen = std::collections::HashSet::new();
        for color in dark.avatar.palette {
            let key = ((color.r * 255.0) as i32, (color.g * 255.0) as i32, (color.b * 255.0) as i32);
            assert!(seen.insert(key), "Avatar 轮换池不该重复");
        }
    }

    #[test]
    fn hover_and_pressed_are_composited_overlays() {
        for dark in [false, true] {
            let t = ThemeData::neutral(dark);
            assert!(t.hover.a < 1.0, "--color-overlay-hover 是带 alpha 的叠加层");
            let primary = t.button_variants.primary;
            assert_ne!(primary.hover_background, primary.background);
            assert_ne!(primary.hover_background, primary.pressed_background, "hover 与 pressed 不同档");
            assert!(primary.hover_background.a >= 1.0, "叠加后填色仍是不透明色");
            assert_ne!(t.list.hover_background, t.surface);
            assert_ne!(t.menu.hover_background, t.dropdown.background);
        }
    }

    #[test]
    fn overriding_one_token_restyles_the_whole_tree() {
        // 这就是"主题修改功能"的验收点:改 --color-accent 一处,主按钮 / 焦点环 /
        // Tab 指示条 / 进度条 / 输入框聚焦边全部跟着变
        let base = ThemeData::neutral_dark();
        let brand = themed(tokens::define_theme().token("--color-accent", "#7B61FF").unwrap(), true);
        let purple = Color::from_rgb8(0x7B, 0x61, 0xFF);
        assert_eq!(brand.primary, purple);
        assert_eq!(brand.button.background, purple);
        assert_eq!(brand.button.focus_ring_color, purple);
        assert_eq!(brand.input.focused_border, purple);
        assert_eq!(brand.tab.indicator_color, purple);
        assert_eq!(brand.nav.indicator_color, purple);
        assert_eq!(brand.feedback.progress_value, purple);
        assert_eq!(brand.button_variants.primary.hover_background, tokens::overlay(purple, base.hover));
        assert_ne!(brand, base);

        // 圆角倍率与字号 scale 同样整体生效
        let square = themed(tokens::define_theme().radius_multiplier(0.0), false);
        assert_eq!((square.radius_sm, square.radius_md, square.radius_lg), (0.0, 0.0, 0.0));
        assert_eq!(square.button.radius, 0.0);
        assert_eq!(square.dialog.radius, 0.0);
        assert_eq!(square.input.radius, 0.0);

        let large = themed(tokens::define_theme().text_scale(18.0, 1.2), false);
        let large_tokens = tokens::define_theme().text_scale(18.0, 1.2).resolve(false);
        assert_eq!(large.text.body.font_size, large_tokens.font_size(FontSizeToken::Base));
        assert_eq!(large.text.body.font_size, 18.0);
        assert_eq!(large.text.caption.font_size, large_tokens.font_size(FontSizeToken::Sm));
        assert_eq!(large.text.caption.font_size, 15.0, "--text-supporting-size = --font-size-sm");

        // 密度:把间距 token 拉大一档
        let roomy = themed(tokens::define_theme().token("--spacing-2", "12px").unwrap(), false);
        assert_eq!(roomy.spacing, 12.0);
        assert_eq!(roomy.space.s, 12.0);
        assert_eq!(roomy.space.control_padding, 12.0);
    }

    #[test]
    fn status_text_meets_aa_contrast_on_both_surfaces() {
        for dark in [false, true] {
            let t = ThemeData::neutral(dark);
            for (label, color, bg) in [
                ("正文/表面", t.foreground, t.surface),
                ("次要/表面", t.text.caption.color, t.surface),
                ("成功/表面", t.feedback.success, t.surface),
                ("警告/表面", t.feedback.warning, t.surface),
                ("错误/表面", t.feedback.error, t.surface),
                ("信息/表面", t.feedback.info, t.surface),
                ("正文/画布", t.foreground, t.background),
            ] {
                let ratio = contrast(color, bg);
                assert!(ratio >= 4.5, "{label} 对比度 {ratio:.2} < 4.5 (dark={dark})");
            }
        }
    }

    #[test]
    /// 填充按钮的文字对比度按 Astryx 原样保留,这里只做下限守护。
    ///
    /// Astryx `Neutral` 的 `--color-on-accent` 两档都是白:浅色档白字压 `#0064E0` 有 5.1:1,
    /// 深色档白字压 `#2694FE` 只有 **3.1:1**(未达正文 4.5:1,达到大号/加粗文本的 3:1 线)。
    /// 这是 Astryx 的设计取舍,mgui 不偷偷改色值;需要 ≥4.5 时用
    /// [`ThemeData::high_contrast`](对应 Astryx `color.contrast: high`)。
    fn filled_button_label_keeps_the_astryx_contrast_floor() {
        let light = ThemeData::neutral_light();
        assert!(contrast(light.button.foreground, light.button.background) >= 4.5, "浅色档主按钮应达 4.5:1");
        let dark = ThemeData::neutral_dark();
        let ratio = contrast(dark.button.foreground, dark.button.background);
        assert!(ratio >= 3.0, "深色档主按钮文字对比度 {ratio:.2} < 3.0(Astryx 原值即 3.11)");
        // 高对比度主题必须补到 4.5 以上
        let hc = ThemeData::high_contrast(true);
        assert!(contrast(hc.button.foreground, hc.button.background) >= 4.5, "高对比度档主按钮不足 4.5:1");
    }

    #[test]
    fn overlay_tokens_are_visible_on_their_own_container() {
        for dark in [false, true] {
            let tokens = tokens::define_theme().resolve(dark);
            let surface = tokens.color(C::BackgroundSurface);
            assert_ne!(tokens.hovered(surface), surface, "dark={dark}");
            assert_ne!(tokens.pressed(surface), tokens.hovered(surface), "dark={dark}");
        }
    }

    #[test]
    fn neutral_light_and_dark_have_opposite_luminance() {
        let light = ThemeData::neutral_light();
        let dark = ThemeData::neutral_dark();
        let luma = |c: Color| c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722;
        assert!(luma(light.background) > 0.8, "浅色画布应接近白色");
        assert!(luma(dark.background) < 0.15, "深色画布应接近黑色");
        assert!(luma(light.foreground) < 0.2, "浅色主题正文应为深色");
        assert!(luma(dark.foreground) > 0.6, "深色主题正文应为浅色");
    }

    #[test]
    fn high_contrast_palette_meets_wcag_and_uses_square_corners() {
        for dark in [false, true] {
            let theme = ThemeData::high_contrast(dark);
            assert!(theme.high_contrast);
            assert_eq!(theme.background, if dark { Color::BLACK } else { Color::WHITE });
            assert!(contrast(theme.foreground, theme.background) >= 7.0, "正文对比度不足");
            assert!(contrast(theme.primary, theme.background) >= 4.5, "主色对比度不足");
            assert!(contrast(theme.border, theme.background) >= 3.0, "边框对比度不足");
            assert!(contrast(theme.text.caption.color, theme.background) >= 4.5, "次要文字对比度不足");
            assert!(contrast(theme.button.foreground, theme.button.background) >= 4.5, "主按钮文字对比度不足");
            assert!(
                contrast(theme.button_variants.normal.foreground, theme.button_variants.normal.background) >= 4.5,
                "常规按钮文字对比度不足"
            );
            assert!(contrast(theme.input.text_color, theme.input.background) >= 7.0, "输入框文字对比度不足");
            assert!(contrast(theme.tooltip.foreground, theme.tooltip.background) >= 7.0, "Tooltip 文字对比度不足");
            assert_eq!(theme.radius_sm, 0.0);
            assert_eq!(theme.radius_md, 0.0);
            assert_eq!(theme.radius_lg, 0.0);
            assert_eq!(theme.button.radius, 0.0);
            assert_eq!(theme.input.radius, 0.0);
            assert_eq!(theme.dialog.radius, 0.0);
            assert_eq!(theme.menu.radius, 0.0);
            assert!(theme.button.focus_ring_width >= 3.0);
            assert_eq!(theme.divider, theme.foreground, "分割线走前景色");
        }
    }

    #[test]
    /// 实时改 token 的前提:一次完整派生必须是微秒级,不能是拖滑杆时的卡顿来源。
    fn theme_derivation_is_cheap_enough_for_live_editing() {
        let definition = crate::theme::tokens::define_theme().radius_multiplier(1.5);
        let iterations = 200;
        let start = std::time::Instant::now();
        for _ in 0..iterations {
            let theme = ThemeData::from_tokens(&definition.resolve(true));
            std::hint::black_box(&theme);
        }
        let per = start.elapsed().as_micros() as f64 / iterations as f64;
        assert!(per < 2_000.0, "单次 resolve + from_tokens = {per:.0}µs,实时改 token 会掉帧");
    }

    #[test]
    fn spacing_scale_defaults() {
        let s = ThemeData::neutral_dark().space;
        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));
        assert_eq!(s.control_padding, 8.0, "控件默认内边距");
        assert_eq!(s.container_padding, 16.0, "容器默认内边距");
        assert_eq!(s.container_gap, 8.0, "容器默认子项间距");

        // 同一份刻度能从 token 层直接读到
        let tokens = tokens::define_theme().resolve(true);
        assert_eq!(tokens.spacing(SpacingStep::S0_5), 2.0);
        assert_eq!(tokens.spacing(SpacingStep::S8), 32.0);
        assert_eq!(tokens.length(LengthToken::RadiusContainer), 12.0);
    }
}