lieui 0.1.0-alpha.3

A retained-tree GUI toolkit in pure Rust: retained view tree + reactive signals + pure-CPU rendering
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
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
//! 内置组件的**绘制**分派:`Kind` 枚举 → 绘制原语(设计 §3.8 "按 `Kind` 枚举分派")。
//!
//! 为什么在这里而不是在 `scene.rs`:`scene.rs` 只负责"树 → 列表"的遍历与状态
//! (裁剪/变换/不透明度/子节点顺序),**组件长什么样**属于组件自己的知识。
//! M5 会把行为(`handle`)也放到这个目录,形成"构造 / 行为 / 绘制"三件套。
//!
//! 视图态(hover / pressed / disabled)在这里解析 ⇒ 鼠标划过只需重绘,不必重跑 `view()`。

use lieui_geom::{Color, Point, Rect, Size};
use lieui_text::{TextEngine, TextSpec};

use crate::cmd::CmdBuf;
use crate::event::{Event, EventKind, EventView, KeyCode, NamedKey, PointerButton, Routing};
use crate::render::scene::{Cull, Op, Scene, TextCache};
use crate::track::{
    FocusState, Kind, KindTag, Node, NodeId, ScrollDrag, Track, clamp_to_char_boundary,
};
use crate::transform::Affine;

// ───────────────────────── 内置行为(M5)─────────────────────────

/// 沿命中链执行**框架内置行为**。
///
/// 与用户处理器的分工(设计 §3.5 的两段式分发):
/// - 内置行为需要 `&mut Track`(改视图态、按几何算值),所以它是 `dispatch` 里**独立的先一遍**,
///   而不是塞进 `HandlerSlot` 的闭包(闭包只拿得到 `&mut Ctx`);
/// - 顺序按路由策略(`Tunnel` 外→内 / `Bubble` 内→外 / `Direct` 只目标),
///   与用户处理器的顺序一致,因此"滑块在自己身上处理按压,父容器再收到冒泡"是自然结果。
pub fn handle_route(track: &mut Track, path: &[NodeId], ev: &Event, cmd: &mut CmdBuf) {
    match ev.kind().routing() {
        Routing::Tunnel => {
            for id in path {
                handle(track, *id, ev, cmd);
            }
        }
        Routing::Bubble => {
            for id in path.iter().rev() {
                handle(track, *id, ev, cmd);
            }
        }
        Routing::Direct => {
            if let Some(t) = path.last() {
                handle(track, *t, ev, cmd);
            }
        }
    }
}

/// 单个节点的内置行为(按 `Kind` 枚举分派)
///
/// 收 `&Event` 而不只是 `&EventView`:IME 预编辑/提交带字符串 payload,
/// 而 `EventView` 是 `Copy` 的定长摘要(放不下字符串)。
pub fn handle(track: &mut Track, id: NodeId, ev: &Event, cmd: &mut CmdBuf) {
    let Some(node) = track.get(id) else {
        return;
    };
    if !node.interaction.enabled {
        return;
    }
    // 滚动条是"虚拟部件":不占节点,行为挂在滚动容器自身上(先于组件行为)
    if node.layout.overflow_scroll && node.layout.show_scrollbar {
        scroll_handle(track, id, ev, cmd);
        if track.get(id).is_none() {
            return; // 处理中被销毁的极端情况
        }
    }
    let Some(node) = track.get(id) else {
        return;
    };
    if !node.interaction.enabled {
        return;
    }
    match node.kind.tag() {
        KindTag::Slider => slider_handle(track, id, &ev.summary(), cmd),
        KindTag::Checkbox => checkbox_handle(track, id, &ev.summary()),
        KindTag::Switch => switch_handle(track, id, &ev.summary()),
        KindTag::Radio => radio_handle(track, id, &ev.summary()),
        KindTag::Input => input_handle(track, id, ev, cmd),
        // 自定义节点:转交它自己的状态机(不拿 Track;树操作走 cmd)
        KindTag::Custom => {
            if let Some(Kind::Custom(cell)) = track.get(id).map(|n| n.kind.clone())
                && let Some(mut inst) = cell.try_borrow_mut()
            {
                inst.on_event(id, &ev.summary(), cmd);
            }
        }
        // Box / Text / Image / Button / Progress 没有框架内置行为:
        // 点击由用户在 `view()` 里 `.on(EventKind::Tapped, ..)` 决定。
        _ => {}
    }
}

/// 滑块:按下取捕获 + 拖拽改值(值写回绑定 signal)
///
/// **只在有绑定时生效**(与复选框同一条规则):`slider(0.5)` 是"显示这个值",
/// `slider_bound(&sig)` 才是"能拖、并且改的是模型"。
/// 不这样规定的话,"拖动一个未绑定的滑块"会得到一个**下次 view() 才回弹**的中间态,
/// 它的可见性取决于"下一次 view() 何时发生"——不可预测,索性不允许。
fn slider_handle(track: &mut Track, id: NodeId, ev: &EventView, cmd: &mut CmdBuf) {
    let bound = track
        .get(id)
        .map(|n| n.bindings.value.is_some())
        .unwrap_or(false);
    if !bound {
        return;
    }
    match ev.kind {
        EventKind::PointerPressed => {
            if ev.button != PointerButton::Left {
                return;
            }
            track.set_dragging(id, true);
            // 指针捕获:拖出滑块范围也继续跟随(否则拖快一点就丢)
            cmd.capture(ev.pointer, id);
            track.slider_drag_to(id, ev.pos.x);
        }
        EventKind::PointerMoved => {
            let dragging = matches!(
                track.get(id).map(|n| &n.kind),
                Some(Kind::Slider { dragging: true, .. })
            );
            if dragging {
                track.slider_drag_to(id, ev.pos.x);
            }
        }
        EventKind::PointerReleased
        | EventKind::PointerCaptureLost
        | EventKind::PointerCanceled => {
            track.set_dragging(id, false);
            cmd.release(ev.pointer);
        }
        _ => {}
    }
}

/// 复选框:点击翻转(**只在有绑定时**——≈ `v-model` 语义)
fn checkbox_handle(track: &mut Track, id: NodeId, ev: &EventView) {
    if ev.kind != EventKind::Tapped {
        return;
    }
    let bound = track
        .get(id)
        .map(|n| n.bindings.checked.is_some())
        .unwrap_or(false);
    if !bound {
        return; // 未绑定 ⇒ 交给用户处理器(模型说了算)
    }
    track.toggle_checked(id);
}

/// 开关:点击翻转(只在有绑定时生效——≈ `v-model` 语义)
fn switch_handle(track: &mut Track, id: NodeId, ev: &EventView) {
    if ev.kind != EventKind::Tapped {
        return;
    }
    let bound = track
        .get(id)
        .map(|n| n.bindings.checked.is_some())
        .unwrap_or(false);
    if !bound {
        return;
    }
    track.toggle_switch(id);
}

/// 单选:点击把本项 value 写回组 signal(只在有绑定时生效)
fn radio_handle(track: &mut Track, id: NodeId, ev: &EventView) {
    if ev.kind != EventKind::Tapped {
        return;
    }
    let bound = track
        .get(id)
        .map(|n| n.bindings.text.is_some())
        .unwrap_or(false);
    if !bound {
        return;
    }
    track.select_radio(id);
}

// ───────────────────────── 输入框(M5)─────────────────────────

/// 输入框:聚焦 / 点选光标 / 拖选 / 键盘编辑 / IME。
///
/// **编辑只在有绑定时生效**(与滑块、复选框同一条规则):没有绑定的输入框
/// 是"只显示模型给出的文本",否则编辑结果会在下次 `view()` 时被描述值覆盖。
fn input_handle(track: &mut Track, id: NodeId, ev: &Event, cmd: &mut CmdBuf) {
    let bound = track
        .get(id)
        .map(|n| n.bindings.text.is_some())
        .unwrap_or(false);
    let view = ev.summary();

    match view.kind {
        EventKind::PointerPressed => {
            if view.button != PointerButton::Left {
                return;
            }
            // 点进来即拿焦点(键盘编辑的前提)
            cmd.focus(id, FocusState::Pointer);
            cmd.capture(view.pointer, id);
            if bound {
                let caret = caret_at_x(track, id, view.pos.x);
                track.input_set_caret(id, caret, false);
            }
        }
        EventKind::PointerMoved => {
            if !bound || track.captured_by(view.pointer) != Some(id) {
                return;
            }
            // 按住拖动 ⇒ 扩选(anchor 不动)
            let caret = caret_at_x(track, id, view.pos.x);
            track.input_set_caret(id, caret, true);
        }
        EventKind::PointerReleased | EventKind::PointerCanceled => {
            cmd.release(view.pointer);
        }
        EventKind::LostFocus => {
            // 失焦结束 IME 组合(否则组合串会留在框里)
            track.input_set_preedit(id, String::new());
        }
        EventKind::KeyDown => {
            if bound {
                input_key(track, id, &view);
            }
        }
        EventKind::CharacterReceived => {
            // 字符只进"当前真正持有焦点"的输入框(避免多窗口/多框串字)
            if !bound || !track.input_is_active(id) {
                return;
            }
            let text = match ev {
                Event::Key {
                    text: Some(t), ..
                } => t.clone(),
                _ => match view.key {
                    Some(KeyCode::Char(c)) => c.to_string(),
                    _ => return,
                },
            };
            track.input_insert(id, &text);
        }
        EventKind::TextCompositionChanged => {
            if !bound {
                return;
            }
            if let Event::ImePreedit { text, .. } = ev {
                track.input_set_preedit(id, text.clone());
            }
        }
        _ => {}
    }
}

// ───────────────────────── 滚动条(M5:thumb 绘制 + 拖动)─────────────────────────

/// 滚动条的粗细(绘制宽 / 命中带宽都用它)
pub const SCROLLBAR_WIDTH: f32 = 8.0;
/// thumb 与视口边缘的间距
const SCROLLBAR_INSET: f32 = 2.0;
/// thumb 的最小长度(再短的视口比例也可抓)
const MIN_THUMB_LEN: f32 = 24.0;
/// thumb 命中带比绘制更宽(触摸容差)
const SCROLLBAR_HIT_INFLATE: f32 = 6.0;

/// 竖直滚动条的 `(track, thumb)`;内容没有竖直溢出 ⇒ `None`
pub(crate) fn vscroll_parts(view: Rect, content: Size, offset: f32) -> Option<(Rect, Rect)> {
    scroll_parts(view, content.height, offset, view.height, true)
}

/// 水平滚动条的 `(track, thumb)`;内容没有水平溢出 ⇒ `None`
pub(crate) fn hscroll_parts(view: Rect, content: Size, offset: f32) -> Option<(Rect, Rect)> {
    scroll_parts(view, content.width, offset, view.width, false)
}

fn scroll_parts(
    view: Rect,
    content_len: f32,
    offset: f32,
    view_len: f32,
    vertical: bool,
) -> Option<(Rect, Rect)> {
    if content_len <= view_len + 0.5 {
        return None; // 没溢出就没滚动条
    }
    let (track_len, base, across) = if vertical {
        (view.height - SCROLLBAR_INSET * 2.0, view.y + SCROLLBAR_INSET, view.right() - SCROLLBAR_WIDTH - SCROLLBAR_INSET)
    } else {
        (view.width - SCROLLBAR_INSET * 2.0, view.x + SCROLLBAR_INSET, view.bottom() - SCROLLBAR_WIDTH - SCROLLBAR_INSET)
    };
    let max_scroll = (content_len - view_len).max(0.0);
    let thumb_len = (track_len * view_len / content_len).clamp(MIN_THUMB_LEN, track_len);
    let travel = (track_len - thumb_len).max(0.0);
    let pos = base + travel * if max_scroll > 0.0 { (offset / max_scroll).clamp(0.0, 1.0) } else { 0.0 };
    let track_rect = if vertical {
        Rect::new(across, base, SCROLLBAR_WIDTH, track_len)
    } else {
        Rect::new(base, across, track_len, SCROLLBAR_WIDTH)
    };
    let thumb = if vertical {
        Rect::new(across, pos, SCROLLBAR_WIDTH, thumb_len)
    } else {
        Rect::new(pos, across, thumb_len, SCROLLBAR_WIDTH)
    };
    Some((track_rect, thumb))
}

/// 滚动条 thumb 的拖拽行为(按下抓取 / 拖动映射 / 松手释放)
fn scroll_handle(track: &mut Track, id: NodeId, ev: &Event, cmd: &mut CmdBuf) {
    let view = ev.summary();
    // 一次性把需要的几何/状态拷出来(全是 Copy),避免与 get_mut 冲突
    let Some((rect, content, drag, (ox, oy))) =
        track.get(id).map(|n| (n.rect(), n.content_size, n.scroll_drag, n.scroll_offset))
    else {
        return;
    };

    match view.kind {
        EventKind::PointerPressed => {
            if view.button != PointerButton::Left {
                return;
            }
            // 竖直优先(内容通常竖直溢出);命中带比可见 thumb 更宽
            if let Some((track_r, thumb)) = vscroll_parts(rect, content, oy)
                && view.pos.x >= track_r.x - SCROLLBAR_HIT_INFLATE
                && view.pos.x <= track_r.right() + SCROLLBAR_HIT_INFLATE
                && view.pos.y >= thumb.y - SCROLLBAR_HIT_INFLATE
                && view.pos.y <= thumb.bottom() + SCROLLBAR_HIT_INFLATE
            {
                track.get_mut(id).unwrap().scroll_drag =
                    Some(ScrollDrag { pointer: view.pointer, vertical: true, grab: view.pos.y - thumb.y });
                cmd.capture(view.pointer, id);
                cmd.damage(id);
                return;
            }
            if let Some((track_r, thumb)) = hscroll_parts(rect, content, ox)
                && view.pos.y >= track_r.y - SCROLLBAR_HIT_INFLATE
                && view.pos.y <= track_r.bottom() + SCROLLBAR_HIT_INFLATE
                && view.pos.x >= thumb.x - SCROLLBAR_HIT_INFLATE
                && view.pos.x <= thumb.right() + SCROLLBAR_HIT_INFLATE
            {
                track.get_mut(id).unwrap().scroll_drag =
                    Some(ScrollDrag { pointer: view.pointer, vertical: false, grab: view.pos.x - thumb.x });
                cmd.capture(view.pointer, id);
                cmd.damage(id);
            }
        }
        EventKind::PointerMoved => {
            let Some(d) = drag else { return };
            if d.pointer != view.pointer || track.captured_by(view.pointer) != Some(id) {
                return;
            }
            if d.vertical {
                let Some((track_r, thumb)) = vscroll_parts(rect, content, oy) else { return };
                let max_scroll = (content.height - rect.height).max(0.0);
                let travel = (track_r.height - thumb.height).max(0.0);
                let pos = (view.pos.y - d.grab - track_r.y).clamp(0.0, travel);
                let ny = if travel > 0.0 { pos / travel * max_scroll } else { 0.0 };
                track.set_scroll_offset(id, (ox, ny));
            } else {
                let Some((track_r, thumb)) = hscroll_parts(rect, content, ox) else { return };
                let max_scroll = (content.width - rect.width).max(0.0);
                let travel = (track_r.width - thumb.width).max(0.0);
                let pos = (view.pos.x - d.grab - track_r.x).clamp(0.0, travel);
                let nx = if travel > 0.0 { pos / travel * max_scroll } else { 0.0 };
                track.set_scroll_offset(id, (nx, oy));
            }
        }
        EventKind::PointerReleased | EventKind::PointerCanceled => {
            if let Some(d) = drag
                && d.pointer == view.pointer
            {
                track.get_mut(id).unwrap().scroll_drag = None;
                cmd.release(view.pointer);
                cmd.damage(id);
            }
        }
        _ => {}
    }
}

/// 画滚动条(滚动容器专用;不溢出的轴不画)——由 [`draw_scrollbar_overlay`] 调用
fn draw_scrollbars(
    out: &mut Scene,
    cull: &Cull,
    n: &Node,
    rect: Rect,
    transform: Affine,
    theme: &crate::theme::Theme,
) {
    if !n.layout.show_scrollbar {
        return;
    }
    let dragging = n.scroll_drag.is_some();
    let color = if dragging {
        theme.scrollbar_thumb_drag
    } else {
        theme.scrollbar_thumb
    };
    if let Some((_, thumb)) = vscroll_parts(rect, n.content_size, n.scroll_offset.1) {
        push(
            out,
            cull,
            transform,
            thumb,
            Op::Rect { rect: thumb, radius: SCROLLBAR_WIDTH * 0.5, color, transform },
        );
    }
    if let Some((_, thumb)) = hscroll_parts(rect, n.content_size, n.scroll_offset.0) {
        push(
            out,
            cull,
            transform,
            thumb,
            Op::Rect { rect: thumb, radius: SCROLLBAR_WIDTH * 0.5, color, transform },
        );
    }
}

/// 键盘编辑(方向键 / 退格删除 / Home End / Ctrl+A)
fn input_key(track: &mut Track, id: NodeId, view: &EventView) {
    let Some(code) = view.key else {
        return;
    };
    let extend = view.modifiers.shift();
    match code {
        KeyCode::Named(NamedKey::Backspace) => {
            track.input_backspace(id);
        }
        KeyCode::Named(NamedKey::Delete) => {
            track.input_delete(id);
        }
        KeyCode::Named(NamedKey::Left) => {
            track.input_move_caret(id, -1, extend);
        }
        KeyCode::Named(NamedKey::Right) => {
            track.input_move_caret(id, 1, extend);
        }
        KeyCode::Named(NamedKey::Home) => {
            track.input_set_caret(id, 0, extend);
        }
        KeyCode::Named(NamedKey::End) => {
            track.input_set_caret(id, usize::MAX, extend);
        }
        KeyCode::Char('a') | KeyCode::Char('A') if view.modifiers.ctrl() => {
            track.input_select_all(id);
        }
        _ => {}
    }
}

/// 显示串 = `text` 在光标处插入 IME 组合串
fn display_text(text: &str, preedit: &str, caret: usize) -> String {
    if preedit.is_empty() {
        return text.to_string();
    }
    let caret = clamp_to_char_boundary(text, caret);
    format!("{}{}{}", &text[..caret], preedit, &text[caret..])
}

/// 显示串偏移 → 文本偏移(组合串内部的点击夹到光标位)
fn display_to_text(text: &str, preedit: &str, caret: usize, offset: usize) -> usize {
    if preedit.is_empty() {
        return clamp_to_char_boundary(text, offset);
    }
    let caret = clamp_to_char_boundary(text, caret);
    if offset <= caret {
        offset
    } else if offset <= caret + preedit.len() {
        caret
    } else {
        clamp_to_char_boundary(text, offset - preedit.len())
    }
}

/// 点击位置 → 文本偏移(按前缀实测宽度取最近)
fn caret_at_x(track: &Track, id: NodeId, x: f32) -> usize {
    let Some(n) = track.get(id) else {
        return 0;
    };
    let Kind::Input {
        text,
        preedit,
        caret,
        scroll,
        ..
    } = &n.kind
    else {
        return 0;
    };
    let display = display_text(text, preedit, *caret);
    // 补偿水平滚动:点击位置对应"内容坐标" = 屏幕 x - 左内边距 + scroll
    let local = (x - n.rect().x - pad_left(n) + *scroll).max(0.0) as f64;
    let spec = &n.text.spec;

    let mut best = 0usize;
    let mut best_d = f64::MAX;
    let mut probe = |offset: usize| {
        let w = TextEngine::measure_text(&display[..offset], spec).0;
        let d = (w - local).abs();
        if d < best_d {
            best_d = d;
            best = offset;
        }
    };
    for (i, _) in display.char_indices() {
        probe(i);
    }
    probe(display.len());
    display_to_text(text, preedit, *caret, best)
}

/// 节点左内边距(输入框文本/光标的起点)
fn pad_left(n: &Node) -> f32 {
    n.layout.padding[lieui_layout::CSSDirection::Left as usize]
}

/// 节点上内边距
fn pad_top(n: &Node) -> f32 {
    n.layout.padding[lieui_layout::CSSDirection::Top as usize]
}

/// 内容盒:`rect` 去掉四边内边距。
///
/// 文本/墨迹应该落在**内容盒**里而不是 border box —— 否则"文本 + 对称内边距"的盒子
/// (tooltip 就是典型)padding 会被吃掉,视觉上看着偏。
fn content_rect(n: &Node, rect: Rect) -> Rect {
    use lieui_layout::CSSDirection::{Bottom, Left, Right, Top};
    let pad = |d: lieui_layout::CSSDirection| n.layout.padding[d as usize];
    let (l, t, r, b) = (pad(Left), pad(Top), pad(Right), pad(Bottom));
    Rect::new(
        rect.x + l,
        rect.y + t,
        (rect.width - l - r).max(0.0),
        (rect.height - t - b).max(0.0),
    )
}

/// 归一化选区(无选区 ⇒ `None`)
fn selection_of(caret: usize, anchor: usize) -> Option<(usize, usize)> {
    if caret == anchor {
        None
    } else {
        Some((caret.min(anchor), caret.max(anchor)))
    }
}

/// 显示串前缀的实测宽度(字节偏移 → 像素);走 `lieui-text` 的测度缓存
fn measure(display: &str, spec: &TextSpec, offset: usize) -> f32 {
    let offset = clamp_to_char_boundary(display, offset);
    TextEngine::measure_text(&display[..offset], spec).0 as f32
}

/// 输入框正文(左对齐、给定原点),复用文本排版缓存
#[allow(clippy::too_many_arguments)]
fn push_input_text(
    cache: &mut TextCache,
    out: &mut Scene,
    cull: &Cull,
    text: &str,
    spec: &TextSpec,
    color: Color,
    origin: Point,
    transform: Affine,
) {
    let (layout, hit) = cache.get_or_build_counted(text, spec, color);
    if hit {
        out.stats.text_cache_hits += 1;
    } else {
        out.stats.text_layouts_built += 1;
    }
    let op = Op::Text {
        layout,
        origin,
        color,
        transform,
    };
    let bounds = op
        .screen_bounds()
        .unwrap_or(Rect::new(origin.x, origin.y, 1.0, 1.0));
    if cull.hit(&bounds) {
        out.push(op);
    } else {
        out.stats.prims_culled += 1;
    }
}

/// 节点自身内容进绘制列表
pub(crate) fn draw(
    cache: &mut TextCache,
    track: &Track,
    id: NodeId,
    transform: Affine,
    cull: &Cull,
    out: &mut Scene,
    theme: &crate::theme::Theme,
) {
    let Some(n) = track.get(id) else {
        return;
    };
    let rect = n.rect();
    if rect.is_empty() {
        return;
    }

    // ── ① 投影(kinds 之前,避免盖住自身内容)──
    if let Some(sh) = n.paint.shadow {
        let r = Rect::new(
            rect.x + sh.offset_x,
            rect.y + sh.offset_y,
            rect.width,
            rect.height,
        )
        .inflate(sh.spread);
        push(
            out,
            cull,
            transform,
            r,
            Op::Shadow {
                rect: r,
                radius: n.paint.border_radius,
                std_dev: (sh.blur * 0.5).max(0.0),
                color: dim_if_disabled(sh.color, n),
                transform,
            },
        );
    }

    // ── ② 背景(hover / pressed 配色在这里解析)──
    let radius = n
        .paint
        .border_radius
        .min(rect.width * 0.5)
        .min(rect.height * 0.5);
    if let Some(color) = resolve_background(n) {
        push(
            out,
            cull,
            transform,
            rect,
            Op::Rect {
                rect,
                radius,
                color: dim_if_disabled(color, n),
                transform,
            },
        );
    }

    // ── ③ 边框 ──
    if n.paint.border_width > 0.0
        && let Some(color) = n.paint.border_color
    {
        push(
            out,
            cull,
            transform,
            rect,
            Op::Border {
                rect,
                radius,
                width: n.paint.border_width,
                color: dim_if_disabled(color, n),
                transform,
            },
        );
    }

    // ── ④ 组件自身内容 ──
    let text_color = dim_if_disabled(resolve_text_color(n), n);
    match &n.kind {
        // 纯容器;Image 的绘制留到 M5(需要 ImageFit / 圆角裁剪的像素级 blit)
        // 纯容器
        Kind::Box => {}

        // 图片:等比缩放(contain)放进节点 rect;手动 blit(见 raster)
        Kind::Image(img) => {
            let bounds = transform.bounding_box(rect);
            if cull.hit(&bounds) {
                out.push(Op::Image {
                    image: img.clone(),
                    rect,
                    transform,
                });
            } else {
                out.stats.prims_culled += 1;
            }
        }

        // 自定义节点:整块交给用户(只读;坐标已是窗口坐标系)
        Kind::Custom(cell) => {
            let inst = cell.borrow();
            inst.draw(out, rect, transform);
        }

        Kind::Text(_) => {
            if let Kind::Text(s) = &n.kind {
                let spec = draw_spec(n);
                // 光学对齐时按**内容盒**放墨迹:节点高度 = 墨迹高 + padding,
                // 若仍贴 border box 上缘,padding 会被吃掉(文本看着往上顶)。
                // 非光学路径保持原样(行盒自带 leading,既有布局按 border box 定位)。
                let r = if spec.optical_align {
                    content_rect(n, rect)
                } else {
                    rect
                };
                push_text(cache, out, cull, s, &spec, text_color, r, false, transform);
            }
        }

        Kind::Button { label } => {
            let spec = draw_spec(n);
            push_text(cache, out, cull, label, &spec, text_color, rect, true, transform);
        }

        // 输入框:文本(或 placeholder)+ 选区 + 光标 + IME 组合下划线
        Kind::Input {
            text,
            placeholder,
            caret,
            anchor,
            preedit,
            scroll,
        } => {
            // 水平滚动:内容随偏移左移,超出部分由节点的 clip_content 裁掉
            let x0 = rect.x + pad_left(n) - scroll;
            let top = rect.y + pad_top(n);
            let display = display_text(text, preedit, *caret);
            let empty = text.is_empty() && preedit.is_empty();

            // 选区(失焦时不显示,与实际产品一致)
            if let Some((a, b)) = selection_of(*caret, *anchor)
                && n.interaction.focused
            {
                let sx = x0 + measure(&display, &n.text.spec, a);
                let ex = x0 + measure(&display, &n.text.spec, b);
                let line_h = TextEngine::measure_text("x", &n.text.spec).1 as f32;
                let sel = Rect::new(sx, top, (ex - sx).max(1.0), line_h.max(rect.height - pad_top(n) * 2.0));
                push(
                    out,
                    cull,
                    transform,
                    sel,
                    Op::Rect {
                        rect: sel,
                        radius: 2.0,
                        color: theme.selection,
                        transform,
                    },
                );
            }

            // 正文 / 占位提示
            let (shown, color) = if empty {
                (placeholder.as_str(), theme.text_secondary)
            } else {
                (display.as_str(), text_color)
            };
            if !shown.is_empty() {
                let (_, th) = TextEngine::measure_text("x", &n.text.spec);
                let origin = Point::new(x0, rect.y + (rect.height - th as f32) * 0.5);
                push_input_text(cache, out, cull, shown, &n.text.spec, color, origin, transform);
            }

            // IME 组合串下划线
            if !preedit.is_empty() {
                let px = x0 + measure(&display, &n.text.spec, *caret);
                let pw = TextEngine::measure_text(preedit, &n.text.spec).0 as f32;
                let (_, th) = TextEngine::measure_text("x", &n.text.spec);
                let y = rect.y + (rect.height + th as f32) * 0.5;
                let underline = Rect::new(px, y, pw.max(1.0), 1.0);
                push(
                    out,
                    cull,
                    transform,
                    underline,
                    Op::Rect {
                        rect: underline,
                        radius: 0.0,
                        color: text_color,
                        transform,
                    },
                );
            }

            // 光标(键盘焦点 + 闪烁相位才画;相位由帧驱动翻转——聚焦才动,空闲帧零功耗)
            if n.interaction.focused && n.interaction.enabled && track.blink_on {
                let cx = x0 + measure(&display, &n.text.spec, *caret);
                let caret_rect = Rect::new(
                    cx,
                    rect.y + pad_top(n),
                    1.5,
                    (rect.height - pad_top(n) * 2.0).max(4.0),
                );
                push(
                    out,
                    cull,
                    transform,
                    caret_rect,
                    Op::Rect {
                        rect: caret_rect,
                        radius: 0.0,
                        color: theme.caret,
                        transform,
                    },
                );
            }
        }

        Kind::Checkbox { checked } => {
            let box_size = rect.height.min(18.0);
            let b = Rect::new(
                rect.x,
                rect.y + (rect.height - box_size) * 0.5,
                box_size,
                box_size,
            );
            let border = n.paint.border_color.unwrap_or(text_color);
            push(
                out,
                cull,
                transform,
                b,
                Op::Border {
                    rect: b,
                    radius: 3.0,
                    width: 1.5,
                    color: border,
                    transform,
                },
            );
            if *checked {
                let inner = b.inflate(-4.0);
                push(
                    out,
                    cull,
                    transform,
                    inner,
                    Op::Rect {
                        rect: inner,
                        radius: 1.5,
                        color: border,
                        transform,
                    },
                );
            }
        }

        Kind::Slider {
            value, min, max, ..
        } => {
            let track_h = 4.0;
            let track = Rect::new(
                rect.x,
                rect.y + (rect.height - track_h) * 0.5,
                rect.width,
                track_h,
            );
            let accent = n.paint.background_color.unwrap_or(theme.accent);
            let knob = 12.0;
            // 归一化到 min..max(0..1 范围外也能画对;max <= min 时退化到 0)
            let t = if *max > *min {
                ((value - *min) / (*max - *min)).clamp(0.0, 1.0)
            } else {
                0.0
            };
            let x = rect.x + (rect.width - knob).max(0.0) * t;
            push(
                out,
                cull,
                transform,
                track,
                Op::Rect {
                    rect: track,
                    radius: track_h * 0.5,
                    color: theme.control_border,
                    transform,
                },
            );
            let filled = Rect::new(track.x, track.y, (x + knob * 0.5) - track.x, track_h);
            push(
                out,
                cull,
                transform,
                filled,
                Op::Rect {
                    rect: filled,
                    radius: track_h * 0.5,
                    color: accent,
                    transform,
                },
            );
            let k = Rect::new(
                x,
                rect.y + (rect.height - knob) * 0.5,
                knob,
                knob,
            );
            push(
                out,
                cull,
                transform,
                k,
                Op::Rect {
                    rect: k,
                    radius: knob * 0.5,
                    color: accent,
                    transform,
                },
            );
        }

        // 开关:药丸轨道 + 圆 thumb(on = accent,off = 边框色)
        Kind::Switch { on } => {
            let track_w = 40.0_f32.min(rect.width);
            let track_h = 20.0_f32.min(rect.height);
            let t = Rect::new(rect.x, rect.y + (rect.height - track_h) * 0.5, track_w, track_h);
            let accent = n.paint.background_color.unwrap_or(theme.accent);
            let (fill, thumb_c) = if *on {
                (accent, Color::WHITE)
            } else {
                (theme.control_border, theme.control)
            };
            push(
                out,
                cull,
                transform,
                t,
                Op::Rect { rect: t, radius: track_h * 0.5, color: fill, transform },
            );
            let r = track_h - 4.0;
            let tx = if *on {
                t.right() - r - 2.0
            } else {
                t.x + 2.0
            };
            let thumb = Rect::new(tx, t.y + 2.0, r, r);
            push(
                out,
                cull,
                transform,
                thumb,
                Op::Rect { rect: thumb, radius: r * 0.5, color: thumb_c, transform },
            );
        }

        // 单选:圆环 + 选中圆点(点 = accent)
        Kind::Radio { selected, .. } => {
            let d = rect.height.min(18.0);
            let b = Rect::new(
                rect.x,
                rect.y + (rect.height - d) * 0.5,
                d,
                d,
            );
            let border = n.paint.border_color.unwrap_or(theme.control_border);
            let accent = n.paint.background_color.unwrap_or(theme.accent);
            push(
                out,
                cull,
                transform,
                b,
                Op::Border {
                    rect: b,
                    radius: d * 0.5,
                    width: 1.5,
                    color: if *selected { accent } else { border },
                    transform,
                },
            );
            if *selected {
                let inner = b.inflate(-4.0);
                push(
                    out,
                    cull,
                    transform,
                    inner,
                    Op::Rect {
                        rect: inner,
                        radius: inner.width * 0.5,
                        color: accent,
                        transform,
                    },
                );
            }
        }

        Kind::Progress { value } => {
            let filled = Rect::new(
                rect.x,
                rect.y,
                rect.width * value.clamp(0.0, 1.0),
                rect.height,
            );
            let accent = n.paint.background_color.unwrap_or(theme.accent);
            push(
                out,
                cull,
                transform,
                filled,
                Op::Rect {
                    rect: filled,
                    radius,
                    color: accent,
                    transform,
                },
            );
        }
    }

    // ── ⑤ 滚动条:**不在这里画** ──
    // 它是覆盖层(虚拟部件),必须画在**子项之后**,否则会被列表项/内容子节点盖住。
    // 由 `scene::walk` 在走完 children 之后调用 [`draw_scrollbar_overlay`]。
}

/// 滚动条覆盖层(`scene::walk` 在**子项之后**调用;仍在滚动容器的裁剪内)。
///
/// 为什么单独成一层:滚动条属于滚动容器自身,但视觉上必须在内容之上
/// (旧实现画在容器自己的 draw 里 ⇒ 后画的列表项会把它盖住)。
pub(crate) fn draw_scrollbar_overlay(
    out: &mut Scene,
    cull: &Cull,
    track: &crate::track::Track,
    id: crate::track::NodeId,
    transform: Affine,
    theme: &crate::theme::Theme,
) {
    let Some(n) = track.get(id) else {
        return;
    };
    if !(n.layout.overflow_scroll && n.layout.show_scrollbar) {
        return;
    }
    let rect = n.rect();
    draw_scrollbars(out, cull, n, rect, transform, theme);
}

/// 背景色解析:pressed > hover > 常态
pub fn resolve_background(n: &Node) -> Option<Color> {
    if n.interaction.pressed
        && let Some(c) = n.paint.pressed_background
    {
        return Some(c);
    }
    if n.interaction.pointer_over
        && let Some(c) = n.paint.hover_background
    {
        return Some(c);
    }
    n.paint.background_color
}

/// 文本色解析:pressed > hover > 常态
pub fn resolve_text_color(n: &Node) -> Color {
    if n.interaction.pressed
        && let Some(c) = n.text.pressed_color
    {
        return c;
    }
    if n.interaction.pointer_over
        && let Some(c) = n.text.hover_color
    {
        return c;
    }
    n.text.color
}

/// 绘制用的排版规格:补上**测度时用的换行宽度**。
///
/// 布局引擎按约束宽度测度文本(会换行),绘制若不施加同一约束就会"盒子按两行算、
/// 只画一行"⇒ 文本贴在盒子顶部(看起来顶对齐,且与相邻项无法居中对齐)。
/// 用引擎写回的 `n.text_wrap` 复用同一宽度,测度与绘制逐字一致。
fn draw_spec(n: &Node) -> TextSpec {
    let mut spec = n.text.spec.clone();
    if spec.wrap
        && spec.max_width.is_none()
        && let Some(w) = n.text_wrap
    {
        spec.max_width = Some(f64::from(w));
    }
    spec
}

/// 禁用态:半透明(视觉降级;行为上的禁用由 `hit`/内置行为负责)
fn dim_if_disabled(c: Color, n: &Node) -> Color {
    if n.interaction.enabled {
        c
    } else {
        Color::rgba(c.r, c.g, c.b, c.a / 2)
    }
}

fn push(out: &mut Scene, cull: &Cull, _transform: Affine, bounds: Rect, op: Op) {
    let screen = op.screen_bounds().unwrap_or(bounds);
    if cull.hit(&screen) {
        out.push(op);
    } else {
        out.stats.prims_culled += 1;
    }
}

#[allow(clippy::too_many_arguments)]
fn push_text(
    cache: &mut TextCache,
    out: &mut Scene,
    cull: &Cull,
    text: &str,
    spec: &TextSpec,
    color: Color,
    rect: Rect,
    center: bool,
    transform: Affine,
) {
    if text.is_empty() || rect.is_empty() {
        return;
    }
    let (layout, ink, hit) = cache.get_full(text, spec, color);
    if hit {
        out.stats.text_cache_hits += 1;
    } else {
        out.stats.text_layouts_built += 1;
    }

    // 光学对齐(`spec.optical_align`):按**墨迹**而不是行盒定位。
    // - 节点矩形的高度由测度给出(= 墨迹高)⇒ 非居中场景把墨迹上缘对到矩形上缘;
    // - 居中场景(按钮等)把墨迹盒居中到矩形里 —— 这才是视觉居中。
    let ink = ink.filter(|b| !b.is_empty());
    let origin = match (ink, center) {
        (Some(b), false) => Point::new(rect.x, rect.y - b.top),
        (Some(b), true) => Point::new(
            rect.x + (rect.width - layout.width()) * 0.5,
            rect.y + (rect.height - b.height()) * 0.5 - b.top,
        ),
        (None, true) => Point::new(
            rect.x + (rect.width - layout.width()) * 0.5,
            rect.y + (rect.height - layout.height()) * 0.5,
        ),
        (None, false) => Point::new(rect.x, rect.y),
    };

    let op = Op::Text {
        layout,
        origin,
        color,
        transform,
    };
    let bounds = op.screen_bounds().unwrap_or(rect);
    if cull.hit(&bounds) {
        out.push(op);
    } else {
        out.stats.prims_culled += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cmd::apply_cmds;
    use crate::event::PointerId;
    use crate::layout::layout;
    use crate::render::scene::{SceneBuilder, SceneOptions};
    use crate::style::{PaintStyle, TextStyle};
    use crate::track::{InteractionState, Layer};
    use lieui_geom::Size;

    fn opts() -> SceneOptions {
        SceneOptions {
            window: Size::new(200.0, 200.0),
            background: Color::new(255, 255, 255),
            focus_ring: false,
            theme: crate::theme::Theme::light(),
        }
    }

    fn node(t: &mut Track, kind: Kind, w: f32, h: f32) -> NodeId {
        let id = t.create(kind, None);
        t.get_mut(id).unwrap().layout.dim = [w, h];
        id
    }

    fn build(t: &Track) -> Scene {
        SceneBuilder::new().build(t, &opts(), &[], true)
    }

    fn green() -> Color {
        Color::new(0, 128, 0)
    }

    fn red() -> Color {
        Color::new(255, 0, 0)
    }

    #[test]
    fn text_node_emits_a_text_op() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Text("hello".into()), 60.0, 20.0);
        t.get_mut(id).unwrap().text = TextStyle::new().font_size(16.0).color(green());
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let text_ops: Vec<_> = scene
            .ops()
            .iter()
            .filter(|op| matches!(op, Op::Text { .. }))
            .collect();
        assert_eq!(text_ops.len(), 1);
        match text_ops[0] {
            Op::Text { color, origin, .. } => {
                assert_eq!(*color, green());
                assert_eq!(origin.x, 0.0);
            }
            _ => unreachable!(),
        }
        assert_eq!(scene.stats.text_layouts_built, 1);
    }

    /// 光学对齐:节点矩形高 = 墨迹高,绘制原点需上移到墨迹上缘之外
    /// (`origin.y = rect.y - ink.top`),字形墨迹才正好贴住矩形上缘。
    #[test]
    fn optical_align_puts_the_ink_top_at_the_rect_top() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        // 不设显式尺寸:高度必须来自测度(光学模式 = 墨迹高)
        let id = t.create(Kind::Text("abc".into()), None);
        {
            let n = t.get_mut(id).unwrap();
            n.text = TextStyle::new().font_size(13.0);
            n.text.spec.optical_align = true;
        }
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let rect = crate::layout::rect_of(&t, id);
        let ink = lieui_text::TextEngine::ink_bounds("abc", &t.get(id).unwrap().text.spec)
            .expect("abc 有墨迹");

        let scene = build(&t);
        let Op::Text { origin, .. } = scene
            .ops()
            .iter()
            .find(|op| matches!(op, Op::Text { .. }))
            .unwrap()
        else {
            unreachable!()
        };
        assert!(
            (rect.height - ink.height()).abs() < 0.01,
            "节点高度 = 墨迹高度:{} vs {}",
            rect.height,
            ink.height()
        );
        assert!(
            (origin.y - (rect.y - ink.top)).abs() < 0.01,
            "绘制原点上移到墨迹上缘:{} vs {}",
            origin.y,
            rect.y - ink.top
        );
    }

    /// 光学对齐 + padding:墨迹落在**内容盒**里(padding 不被吃掉)。
    ///
    /// tooltip 就是这种盒子(文本 + 上下各 6px);若贴 border box 上缘,视觉上会往上顶。
    #[test]
    fn optical_align_keeps_the_padding_around_the_ink() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = t.create(Kind::Text("tooltip".into()), None);
        {
            let n = t.get_mut(id).unwrap();
            n.text = TextStyle::new().font_size(12.0);
            n.text.spec.optical_align = true;
            n.text.spec.wrap = false;
            n.layout = n
                .layout
                .clone()
                .padding_top(6.0)
                .padding_bottom(6.0)
                .padding_left(10.0)
                .padding_right(10.0);
        }
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let rect = crate::layout::rect_of(&t, id);
        let ink = lieui_text::TextEngine::ink_bounds("tooltip", &t.get(id).unwrap().text.spec)
            .expect("tooltip 有墨迹");
        assert!(
            (rect.height - (ink.height() + 12.0)).abs() < 0.01,
            "盒高 = 墨迹高 + 上下 padding:{} vs {}",
            rect.height,
            ink.height()
        );

        let scene = build(&t);
        let Op::Text { origin, .. } = scene
            .ops()
            .iter()
            .find(|op| matches!(op, Op::Text { .. }))
            .unwrap()
        else {
            unreachable!()
        };
        let ink_top = origin.y + ink.top;
        let ink_left = origin.x;
        assert!(
            (ink_top - (rect.y + 6.0)).abs() < 0.01,
            "墨迹上缘落在内容盒上缘(rect.y + 6):{ink_top} vs {}",
            rect.y + 6.0
        );
        assert!(
            (ink_left - (rect.x + 10.0)).abs() < 0.01,
            "墨迹左缘落在内容盒左缘(rect.x + 10):{ink_left} vs {}",
            rect.x + 10.0
        );
        // 上下留白相等 ⇒ 视觉居中
        let bottom_gap = rect.bottom() - (ink_top + ink.height());
        assert!(
            ((ink_top - rect.y) - bottom_gap).abs() < 0.01,
            "上下 padding 对称:上 {} vs 下 {}",
            ink_top - rect.y,
            bottom_gap
        );
    }

    #[test]
    fn empty_text_is_skipped() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Text(String::new()), 60.0, 20.0);
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        assert!(!scene.ops().iter().any(|op| matches!(op, Op::Text { .. })));
        assert_eq!(scene.stats.text_layouts_built, 0);
    }

    #[test]
    fn button_label_is_centered() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Button { label: "OK".into() }, 80.0, 30.0);
        t.get_mut(id).unwrap().text = TextStyle::new().font_size(14.0);
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let Op::Text { layout, origin, .. } = scene
            .ops()
            .iter()
            .find(|op| matches!(op, Op::Text { .. }))
            .unwrap()
        else {
            unreachable!()
        };
        // 水平居中:左右留白相等(±1px 容差)
        let left = origin.x;
        let right = 80.0 - origin.x - layout.width();
        assert!((left - right).abs() < 1.0, "left={left} right={right}");
        // 垂直居中:上下留白相等(label 行盒在按钮内双轴居中)
        let top = origin.y;
        let bottom = 30.0 - origin.y - layout.height();
        assert!((top - bottom).abs() < 1.0, "top={top} bottom={bottom}");
    }

    /// icon_button 的字形行盒在按钮内**双轴居中**(gallery 图标行的对齐依据)。
    #[test]
    fn icon_button_glyph_is_centered_in_the_button() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(
            &mut t,
            Kind::Button {
                label: "\u{e5cd}".into(), // close
            },
            40.0,
            32.0,
        );
        t.get_mut(id).unwrap().text = TextStyle::new().font_size(20.0);
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let Op::Text { layout, origin, .. } = scene
            .ops()
            .iter()
            .find(|op| matches!(op, Op::Text { .. }))
            .unwrap()
        else {
            unreachable!()
        };
        // 行盒(20×20,图标字体行高系数 1.0)应居中于 40×32:上下各 6、左右各 10
        let top = origin.y;
        let bottom = 32.0 - origin.y - layout.height();
        let left = origin.x;
        let right = 40.0 - origin.x - layout.width();
        assert!((top - bottom).abs() < 1.0, "top={top} bottom={bottom}");
        assert!((left - right).abs() < 1.0, "left={left} right={right}");
    }

    #[test]
    fn checkbox_draws_a_border_and_a_mark() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Checkbox { checked: false }, 20.0, 20.0);
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        assert!(scene.ops().iter().any(|op| matches!(op, Op::Border { .. })));
        assert!(!scene.ops().iter().any(|op| matches!(
            op,
            Op::Rect { radius, .. } if (*radius - 1.5).abs() < 1e-6
        )));

        t.get_mut(id).unwrap().kind = Kind::Checkbox { checked: true };
        let scene = build(&t);
        assert!(
            scene.ops().iter().any(|op| matches!(
                op,
                Op::Rect { radius, .. } if (*radius - 1.5).abs() < 1e-6
            )),
            "勾选后应画出标记"
        );
    }

    #[test]
    fn slider_draws_track_and_knob_at_the_value_position() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(
            &mut t,
            Kind::Slider {
                value: 0.5,
                min: 0.0,
                max: 1.0,
                dragging: false,
            },
            100.0,
            20.0,
        );
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        // 轨道 + 已填充 + 滑块 = 3 个矩形(不含底色)
        let rects = scene
            .ops()
            .iter()
            .filter(|op| matches!(op, Op::Rect { rect, .. } if rect.width <= 100.0))
            .count();
        assert_eq!(rects, 3);

        let knob = scene
            .ops()
            .iter()
            .find_map(|op| match op {
                Op::Rect { rect, radius, .. } if (*radius - 6.0).abs() < 1e-6 => Some(*rect),
                _ => None,
            })
            .unwrap();
        assert!((knob.x - (100.0 - 12.0) * 0.5).abs() < 0.01, "滑块在中点:{knob:?}");
    }

    /// 回归:绘制曾把 value 硬归一化到 0..1,范围 0..10 时值 ≥1 就顶死最右
    /// (gallery 音量滑块的症状)。0..10 范围取中点 ⇒ 滑块必须仍在中点。
    #[test]
    fn slider_respects_a_non_unit_range() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(
            &mut t,
            Kind::Slider {
                value: 5.0,
                min: 0.0,
                max: 10.0,
                dragging: false,
            },
            100.0,
            20.0,
        );
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let knob = build(&t)
            .ops()
            .iter()
            .find_map(|op| match op {
                Op::Rect { rect, radius, .. } if (*radius - 6.0).abs() < 1e-6 => Some(*rect),
                _ => None,
            })
            .unwrap();
        assert!((knob.x - (100.0 - 12.0) * 0.5).abs() < 0.01, "值 5/10 ⇒ 滑块在中点:{knob:?}");
    }

    #[test]
    fn progress_fills_proportionally() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(
            &mut t,
            Kind::Progress { value: 0.25 },
            100.0,
            8.0,
        );
        t.get_mut(id).unwrap().paint = PaintStyle::new().background(green());
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let filled = scene
            .ops()
            .iter()
            .find_map(|op| match op {
                // 底色是整条 100 宽,填充部分是 25 宽
                Op::Rect { rect, color, .. } if *color == green() && rect.width < 100.0 => Some(*rect),
                _ => None,
            })
            .unwrap();
        assert_eq!(filled.width, 25.0);
        assert_eq!(filled.height, 8.0);
    }

    #[test]
    fn disabled_content_is_dimmed() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Box, 20.0, 20.0);
        t.get_mut(id).unwrap().paint = PaintStyle::new().background(red());
        t.get_mut(id).unwrap().interaction = InteractionState {
            enabled: false,
            ..InteractionState::default()
        };
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let c = scene
            .ops()
            .iter()
            .find_map(|op| match op {
                Op::Rect { rect, color, .. } if rect.width == 20.0 => Some(*color),
                _ => None,
            })
            .unwrap();
        assert_eq!(c.a, 127, "禁用 ⇒ alpha 减半");
    }

    // ── 输入框绘制 ──

    fn input_node(t: &mut Track, text: &str, placeholder: &str) -> NodeId {
        let id = t.create(
            Kind::Input {
                text: text.to_string(),
                placeholder: placeholder.to_string(),
                caret: text.len(),
                anchor: text.len(),
                preedit: String::new(),
                scroll: 0.0,
            },
            None,
        );
        {
            let n = t.get_mut(id).unwrap();
            n.layout = n
                .layout
                .clone()
                .width(200.0)
                .height(28.0)
                .padding_left(8.0)
                .padding_top(4.0);
            n.paint = PaintStyle::new().background(Color::WHITE);
        }
        id
    }

    fn text_ops(scene: &Scene) -> Vec<(Point, Color)> {
        scene
            .ops()
            .iter()
            .filter_map(|op| match op {
                Op::Text { origin, color, .. } => Some((*origin, *color)),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn input_draws_placeholder_when_empty() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = input_node(&mut t, "", "姓名");
        t.append_child(root, id);
        layout(&mut t, Size::new(300.0, 100.0));

        let scene = build(&t);
        let texts = text_ops(&scene);
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0].0.x, 8.0, "文本从左内边距开始");
        // 空文本 + 未聚焦 ⇒ 没有光标矩形
        assert!(!scene.ops().iter().any(|op| matches!(
            op,
            Op::Rect { rect, .. } if rect.width < 2.0 && rect.height > 10.0
        )));
    }

    #[test]
    fn input_draws_the_text_and_a_caret_when_focused() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = input_node(&mut t, "hi", "");
        t.append_child(root, id);
        layout(&mut t, Size::new(300.0, 100.0));

        let scene = build(&t);
        let texts = text_ops(&scene);
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0].0.x, 8.0);

        // 聚焦 + 闪烁相位为亮 ⇒ 出现光标(1.5px 宽、比文本高)
        t.set_focused(id, crate::track::FocusState::Keyboard);
        t.blink_on = true;
        let scene = build(&t);
        let caret = scene.ops().iter().find_map(|op| match op {
            Op::Rect { rect, .. } if rect.width < 2.0 && rect.height > 10.0 => Some(*rect),
            _ => None,
        });
        let caret = caret.expect("有焦点 ⇒ 画光标");
        assert!(caret.x >= 8.0, "光标在左内边距之后:{caret:?}");
    }

    #[test]
    fn input_draws_a_selection_rect() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = input_node(&mut t, "abcdef", "");
        t.append_child(root, id);
        layout(&mut t, Size::new(300.0, 100.0));

        // 选中前两个字符(caret=2, anchor=0)
        {
            let n = t.get_mut(id).unwrap();
            if let Kind::Input { caret, anchor, .. } = &mut n.kind {
                *caret = 2;
                *anchor = 0;
            }
            n.interaction.focused = true;
        }

        let scene = build(&t);
        let sel = scene.ops().iter().find_map(|op| match op {
            Op::Rect { rect, color, .. } if color.a > 0 && color.a < 200 && rect.width > 1.0 => {
                Some(*rect)
            }
            _ => None,
        });
        let sel = sel.expect("有选区 ⇒ 画高亮");
        assert!(sel.width > 2.0, "选区有宽度:{sel:?}");
        assert!(sel.x >= 8.0);
    }

    #[test]
    fn input_draws_a_preedit_underline() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = input_node(&mut t, "", "");
        t.append_child(root, id);
        layout(&mut t, Size::new(300.0, 100.0));

        let before = build(&t).ops().len();
        t.input_set_preedit(id, "zhong".to_string());
        let scene = build(&t);
        assert!(scene.ops().len() > before, "组合串 ⇒ 文本 + 下划线");
    }

    // ── 滚动条 ──

    const SCROLL_WIN: Size = Size::new(200.0, 100.0);

    /// 滚动容器(200×100,竖直内容 300)+ 内容子节点;已布局
    fn scroll_tree() -> (Track, NodeId, NodeId) {
        let mut t = Track::new();
        let sc = t.create(Kind::Box, None);
        {
            let n = t.get_mut(sc).unwrap();
            n.layout.dim = [200.0, 100.0];
            n.layout.overflow_scroll = true;
            n.layout.show_scrollbar = true;
        }
        t.add_root(Layer::Content, None, sc);
        let content = t.create(Kind::Box, None);
        t.get_mut(content).unwrap().layout.dim = [200.0, 300.0];
        t.append_child(sc, content);
        crate::layout::layout(&mut t, SCROLL_WIN);
        (t, sc, content)
    }

    fn pointer(kind: EventKind, pos: Point) -> Event {
        Event::pointer(kind, PointerId(0), pos, PointerButton::Left)
    }

    #[test]
    fn thumb_geometry_is_proportional_with_a_minimum_length() {
        let (t, sc, _) = scroll_tree();
        let rect = t.get(sc).unwrap().rect();
        let content = t.get(sc).unwrap().content_size;
        assert!((content.height - 300.0).abs() < 0.5, "内容尺寸被布局写回:{content:?}");

        let (track_r, thumb) = vscroll_parts(rect, content, 0.0).expect("溢出 ⇒ 有竖直 thumb");
        assert!((track_r.x + track_r.width - rect.right()).abs() < 3.0, "贴右缘");
        assert!((thumb.height - (100.0 - 4.0) * 100.0 / 300.0).abs() < 0.5, "长度按比例");
        assert!((thumb.y - (rect.y + 2.0)).abs() < 0.5, "offset=0 ⇒ 顶端");

        // 没溢出 ⇒ 无 thumb
        let mut t2 = Track::new();
        let sc2 = t2.create(Kind::Box, None);
        {
            let n = t2.get_mut(sc2).unwrap();
            n.layout.dim = [200.0, 100.0];
            n.layout.overflow_scroll = true;
            n.layout.show_scrollbar = true;
        }
        t2.add_root(Layer::Content, None, sc2);
        let small = t2.create(Kind::Box, None);
        t2.get_mut(small).unwrap().layout.dim = [200.0, 50.0];
        t2.append_child(sc2, small);
        crate::layout::layout(&mut t2, SCROLL_WIN);
        assert!(vscroll_parts(t2.get(sc2).unwrap().rect(), t2.get(sc2).unwrap().content_size, 0.0).is_none());
    }

    #[test]
    fn thumb_drag_maps_position_to_offset_and_releases() {
        let (mut t, sc, _) = scroll_tree();
        let rect = t.get(sc).unwrap().rect();
        let content = t.get(sc).unwrap().content_size;
        let (_, thumb) = vscroll_parts(rect, content, 0.0).unwrap();
        let grab = Point::new(thumb.center().x, thumb.y + 4.0); // 抓在 thumb 上部

        // 按下:建立拖拽会话 + 捕获
        let mut cmds = CmdBuf::new();
        handle(&mut t, sc, &pointer(EventKind::PointerPressed, grab), &mut cmds);
        apply_cmds(&mut t, cmds.as_slice());
        let drag = t.get(sc).unwrap().scroll_drag.expect("按下 thumb ⇒ 进入拖拽");
        assert!(drag.vertical);
        assert_eq!(t.captured_by(PointerId(0)), Some(sc), "拖拽期间捕获指针");

        // 拖到 track 中点 ⇒ offset ≈ max_scroll 的一半
        let travel = rect.height - 4.0 - thumb.height;
        let mid_y = rect.y + 2.0 + travel * 0.5;
        let mut cmds = CmdBuf::new();
        handle(&mut t, sc, &pointer(EventKind::PointerMoved, Point::new(grab.x, mid_y + 4.0)), &mut cmds);
        apply_cmds(&mut t, cmds.as_slice());
        let oy = t.scroll_offset(sc).1;
        let max_scroll = 200.0;
        assert!((oy - max_scroll * 0.5).abs() < 1.5, "拖到中点 ⇒ offset≈一半:{oy}");

        // 松手:会话结束 + 捕获释放,offset 保留
        let mut cmds = CmdBuf::new();
        handle(&mut t, sc, &pointer(EventKind::PointerReleased, Point::new(grab.x, mid_y)), &mut cmds);
        apply_cmds(&mut t, cmds.as_slice());
        assert!(t.get(sc).unwrap().scroll_drag.is_none());
        assert_eq!(t.captured_by(PointerId(0)), None);
        assert!(t.scroll_offset(sc).1 > 0.0, "松手后滚动位置保留");
    }

    #[test]
    fn grabbing_the_thumb_top_does_not_jump_the_scroll() {
        let (mut t, sc, _) = scroll_tree();
        let rect = t.get(sc).unwrap().rect();
        let content = t.get(sc).unwrap().content_size;
        // 先滚到一半再抓 thumb 顶端
        t.set_scroll_offset(sc, (0.0, 100.0));
        let (_, thumb) = vscroll_parts(rect, content, 100.0).unwrap();

        let mut cmds = CmdBuf::new();
        handle(&mut t, sc, &pointer(EventKind::PointerPressed, Point::new(thumb.center().x, thumb.y + 0.5)), &mut cmds);
        apply_cmds(&mut t, cmds.as_slice());
        let oy_before = t.scroll_offset(sc).1;

        // 只往下挪 1px ⇒ offset 只动一点点(≈ max_scroll / travel)
        handle(&mut t, sc, &pointer(EventKind::PointerMoved, Point::new(thumb.center().x, thumb.y + 1.5)), &mut cmds);
        apply_cmds(&mut t, cmds.as_slice());
        let oy = t.scroll_offset(sc).1;
        let step = 200.0 / (rect.height - 4.0 - thumb.height);
        assert!(
            (oy - (oy_before + step)).abs() < 1.0,
            "抓取点不跳:{oy_before} → {oy}(一步应≈{step})"
        );
    }

    #[test]
    fn draw_emits_thumb_when_overflowing() {
        let (t, sc, _) = scroll_tree();
        let scene = build(&t);
        let rect = t.get(sc).unwrap().rect();
        let thumb_x_hit = scene.ops().iter().any(|op| match op {
            Op::Rect { rect: r, color, .. } =>
                *color == crate::theme::Theme::light().scrollbar_thumb
                    && r.width <= SCROLLBAR_WIDTH + 0.5
                    && r.x + r.width <= rect.right() + 0.5,
            _ => false,
        });
        assert!(thumb_x_hit, "溢出 ⇒ 场景里有 thumb 矩形");
    }

    /// 滚动条是**覆盖层**:必须画在子项(列表项)之后,否则会被盖住
    /// (pdfkit 左侧页列表的症状)。
    #[test]
    fn scrollbar_is_drawn_above_the_content() {
        let (mut t, sc, _) = scroll_tree();
        // 给内容子节点一个铺满的底色(模拟列表项的整行背景)
        let content = t.children(sc)[0];
        t.get_mut(content).unwrap().paint.background_color = Some(Color::RED);

        let scene = build(&t);
        let thumb = scene.ops().iter().position(|op| {
            matches!(op, Op::Rect { rect, color, .. }
                if *color == crate::theme::Theme::light().scrollbar_thumb
                    && rect.width <= SCROLLBAR_WIDTH + 0.5)
        });
        let item = scene
            .ops()
            .iter()
            .position(|op| matches!(op, Op::Rect { color, .. } if *color == Color::RED));
        let (thumb, item) = (thumb.expect("有 thumb"), item.expect("有内容底色"));
        assert!(
            thumb > item,
            "滚动条(op #{thumb})必须在内容(op #{item})之后绘制"
        );
    }

    // ── 开关 / 单选 ──

    #[test]
    fn switch_draws_pill_track_with_accent_when_on() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let on = node(&mut t, Kind::Switch { on: true }, 40.0, 20.0);
        let off = node(&mut t, Kind::Switch { on: false }, 40.0, 20.0);
        t.append_child(root, on);
        t.append_child(root, off);
        layout(&mut t, Size::new(200.0, 100.0));

        let light = crate::theme::Theme::light();
        let accent = light.accent;
        let scene = build(&t);
        let tracks: Vec<(Rect, Color)> = scene
            .ops()
            .iter()
            .filter_map(|op| match op {
                Op::Rect { rect, color, radius, .. } if *radius >= 9.0 => Some((*rect, *color)),
                _ => None,
            })
            .collect();
        assert_eq!(tracks.len(), 2, "两个药丸轨道:{tracks:?}");
        assert!(tracks.iter().any(|(r, c)| *c == accent && (r.width - 40.0).abs() < 0.5), "on ⇒ accent 轨道");
        assert!(
            tracks
                .iter()
                .any(|(r, c)| *c == light.control_border && (r.width - 40.0).abs() < 0.5),
            "off ⇒ 边框色轨道"
        );
    }

    #[test]
    fn radio_draws_a_dot_only_when_selected() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let sel = node(&mut t, Kind::Radio { selected: true, value: "a".into() }, 18.0, 18.0);
        let unsel = node(&mut t, Kind::Radio { selected: false, value: "b".into() }, 18.0, 18.0);
        t.append_child(root, sel);
        t.append_child(root, unsel);
        layout(&mut t, Size::new(200.0, 100.0));

        let accent = crate::theme::Theme::light().accent;
        let scene = build(&t);
        let dots = scene.ops().iter().filter(|op| matches!(op,
            Op::Rect { color, .. } if *color == accent));
        assert_eq!(dots.count(), 1, "只有选中的那项画圆点");
    }

    /// 焦点框颜色走主题 token(此前是硬编码的蓝)
    #[test]
    fn focus_ring_uses_the_theme_token() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Button { label: "ok".into() }, 60.0, 24.0);
        {
            let n = t.get_mut(id).unwrap();
            n.interaction.focused = true;
            n.focus_state = crate::track::FocusState::Keyboard;
        }
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let dark = crate::theme::Theme::dark();
        let mut o = opts();
        o.focus_ring = true;
        o.theme = dark;
        let scene = SceneBuilder::new().build(&t, &o, &[], true);
        let borders: Vec<Color> = scene
            .ops()
            .iter()
            .filter_map(|op| match op {
                Op::Border { color, .. } => Some(*color),
                _ => None,
            })
            .collect();
        assert!(
            borders.contains(&dark.focus_ring),
            "焦点框用主题 token:{borders:?}"
        );
    }

    #[test]
    fn shadow_is_offset_and_expanded() {
        let mut t = Track::new();
        let root = t.create(Kind::Box, None);
        t.add_root(Layer::Content, None, root);
        let id = node(&mut t, Kind::Box, 40.0, 40.0);
        t.get_mut(id).unwrap().paint = PaintStyle::new().shadow(crate::style::ShadowSpec::new(
            4.0,
            6.0,
            8.0,
            2.0,
            Color::rgba(0, 0, 0, 60),
        ));
        t.append_child(root, id);
        layout(&mut t, Size::new(200.0, 200.0));

        let scene = build(&t);
        let Op::Shadow {
            rect,
            std_dev,
            color,
            ..
        } = scene
            .ops()
            .iter()
            .find(|op| matches!(op, Op::Shadow { .. }))
            .unwrap()
        else {
            unreachable!()
        };
        assert_eq!(*rect, Rect::new(4.0 - 2.0, 6.0 - 2.0, 44.0, 44.0));
        assert_eq!(*std_dev, 4.0);
        assert_eq!(color.a, 60);
    }
}