aetna-core 0.3.0

Aetna — backend-agnostic UI library core
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
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
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
//! `RunnerCore` — the backend-agnostic half of every Aetna runner.
//!
//! Holds interaction state ([`UiState`], `last_tree`) and paint scratch
//! buffers (`quad_scratch`, `runs`, `paint_items`) plus the geometry
//! context (`viewport_px`, `surface_size_override`) needed to project
//! layout's logical-pixel rects into physical-pixel scissors. Exposes
//! the identical interaction methods both backends ship: `pointer_*`,
//! `key_down`, `set_hotkeys`, `set_animation_mode`, `ui_state`,
//! `rect_of_key`, `debug_summary`, `set_surface_size`, plus the layout
//! / paint-stream stages that are pure CPU work.
//!
//! Each backend's `Runner` *contains* a `RunnerCore` and forwards the
//! interaction methods to it; only the GPU resources (pipelines,
//! buffers, atlases) and the actual GPU upload + draw work stay
//! per-backend. The split shares what's identical without a trait —
//! same shape as `crate::paint`, larger surface.
//!
//! ## What this module does NOT own
//!
//! - **Pipeline registration.** Each backend builds its own
//!   `pipelines: HashMap<ShaderHandle, BackendPipeline>` because the
//!   pipeline value type is GPU-specific.
//! - **Text upload.** Glyph atlas pages live on the GPU as backend
//!   images; the `TextPaint` that owns them is per-backend. Core
//!   reaches into it through the [`TextRecorder`] trait during the
//!   paint stream loop, then the backend flushes its atlas separately.
//! - **GPU upload of `quad_scratch` / frame uniforms.** Backend
//!   responsibility — `prepare()` orchestrates the full sequence.
//! - **`draw()`.** Both backends walk `core.paint_items` + `core.runs`
//!   themselves because the encoder type (and lifetime) diverges.
//!
//! ## Why no `Painter` trait
//!
//! Extracting a `trait Painter { fn prepare(...); fn draw(...); fn
//! set_scissor(...); }` was considered so backends would share *one*
//! abstraction surface. We declined: the only call sites left after
//! this module + [`crate::paint`] are the two
//! `prepare()` GPU-upload tails and the two `draw()` walks, and both
//! need backend-typed handles (`wgpu::RenderPass<'_>` /
//! `AutoCommandBufferBuilder<...>`) that no trait can hide without
//! generics that re-fragment the surface. A `Painter` trait would
//! reduce to a 1-method `set_scissor` indirection plus host-side
//! ceremony — dead weight. The duplication that *is* worth abstracting
//! is the host harness (winit init, swapchain management,
//! `aetna-{wgpu,vulkano}-demo::run`) — and that lives a layer above
//! the paint surface, not inside it. Revisit if a third backend lands
//! or if the GPU-upload sequences diverge enough to make a typed-state
//! interface earn its keep.

use std::ops::Range;
use std::time::Duration;

use web_time::Instant;

use crate::draw_ops;
use crate::event::{KeyChord, KeyModifiers, PointerButton, UiEvent, UiEventKind, UiKey, UiTarget};
use crate::focus;
use crate::hit_test;
use crate::ir::{DrawOp, TextAnchor};
use crate::layout;
use crate::paint::{
    InstanceRun, PaintItem, PhysicalScissor, QuadInstance, close_run, pack_instance,
    physical_scissor,
};
use crate::shader::ShaderHandle;
use crate::state::{AnimationMode, UiState};
use crate::text::atlas::RunStyle;
use crate::theme::Theme;
use crate::toast;
use crate::tooltip;
use crate::tree::{Color, El, FontWeight, Rect, TextWrap};

/// Logical-pixel overlap kept between the pre-page and post-page
/// viewport when the user clicks the scroll track above/below the
/// thumb. Matches browser convention: paging by `viewport_h - overlap`
/// preserves the bottom (resp. top) row across the jump so context
/// isn't lost.
const SCROLL_PAGE_OVERLAP: f32 = 24.0;

/// Reported back from each backend's `prepare(...)` per frame. The
/// host uses `needs_redraw` to keep the redraw loop ticking only
/// while there is in-flight motion (a hover spring still settling, a
/// focus ring still fading out), then idles. `timings` is a per-frame
/// CPU breakdown for diagnostic logging.
#[derive(Clone, Copy, Debug, Default)]
pub struct PrepareResult {
    pub needs_redraw: bool,
    pub timings: PrepareTimings,
}

/// Outcome of a pointer-move dispatch through
/// [`RunnerCore::pointer_moved`] (or its backend wrappers).
///
/// Wayland and most X11 compositors deliver `CursorMoved` at very
/// high frequency while the cursor sits over the surface — even
/// sub-pixel jitter or per-frame compositor sync ticks count as
/// movement. The vast majority of those moves are visual no-ops
/// (the hovered node didn't change, no drag is active, no scrollbar
/// is dragging), so hosts must gate `request_redraw` on
/// `needs_redraw` to avoid spinning the rebuild + layout + render
/// pipeline on every cursor sample.
#[derive(Debug, Default)]
pub struct PointerMove {
    /// Events to dispatch through `App::on_event`. Empty when the
    /// move didn't trigger a `Drag` or selection update.
    pub events: Vec<UiEvent>,
    /// `true` when the runtime's visual state changed enough to
    /// warrant a redraw — hovered identity changed, scrollbar drag
    /// updated a scroll offset, or `events` is non-empty.
    pub needs_redraw: bool,
}

/// Per-stage CPU timing inside each backend's `prepare`. Cheap to
/// compute (a handful of `Instant::now()` calls per frame) and useful
/// for finding the dominant cost when frame budget is tight.
///
/// Stages:
/// - `layout`: layout pass + focus order sync + state apply + animation tick.
/// - `draw_ops`: tree → DrawOp[] resolution.
/// - `paint`: paint-stream loop (quad packing + text shaping via cosmic-text).
/// - `gpu_upload`: backend-side instance buffer write + atlas flush + frame uniforms.
/// - `snapshot`: cloning the laid-out tree for next-frame hit-testing.
#[derive(Clone, Copy, Debug, Default)]
pub struct PrepareTimings {
    pub layout: Duration,
    pub draw_ops: Duration,
    pub paint: Duration,
    pub gpu_upload: Duration,
    pub snapshot: Duration,
}

/// Backend-agnostic runner state.
///
/// Each backend's `Runner` owns one of these as its `core` field and
/// forwards the public interaction surface to it. The fields are `pub`
/// so backends can read them in `draw()` (which has to traverse
/// `paint_items` + `runs` against backend-specific pipeline and
/// instance-buffer objects).
pub struct RunnerCore {
    pub ui_state: UiState,
    /// Snapshot of the last laid-out tree, kept so pointer events
    /// arriving between frames hit-test against the geometry the user
    /// is actually looking at.
    pub last_tree: Option<El>,

    /// Per-frame quad instance scratch — backends `bytemuck::cast_slice`
    /// this into their VBO upload.
    pub quad_scratch: Vec<QuadInstance>,
    pub runs: Vec<InstanceRun>,
    pub paint_items: Vec<PaintItem>,

    /// Physical viewport size in pixels. Backends use this for `draw()`
    /// scissor binding (logical scissors get projected into this space
    /// inside `prepare_paint`).
    pub viewport_px: (u32, u32),
    /// When set, overrides the physical viewport derived from
    /// `viewport.w * scale_factor` so paint-side scissor math matches
    /// the actual swapchain extent. Backends call
    /// [`Self::set_surface_size`] from their host's surface-config /
    /// resize hook to keep this in lockstep.
    pub surface_size_override: Option<(u32, u32)>,

    /// Theme used when resolving implicit widget surfaces to shaders.
    pub theme: Theme,
}

impl Default for RunnerCore {
    fn default() -> Self {
        Self::new()
    }
}

impl RunnerCore {
    pub fn new() -> Self {
        Self {
            ui_state: UiState::default(),
            last_tree: None,
            quad_scratch: Vec::new(),
            runs: Vec::new(),
            paint_items: Vec::new(),
            viewport_px: (1, 1),
            surface_size_override: None,
            theme: Theme::default(),
        }
    }

    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
    }

    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    /// Override the physical viewport size. Call after the host's
    /// surface configure or resize so scissor math sees the swapchain's
    /// real extent (fractional `scale_factor` round-trips can otherwise
    /// land `viewport_px` one pixel off and trip
    /// `set_scissor_rect` validation).
    pub fn set_surface_size(&mut self, width: u32, height: u32) {
        self.surface_size_override = Some((width.max(1), height.max(1)));
    }

    pub fn ui_state(&self) -> &UiState {
        &self.ui_state
    }

    pub fn debug_summary(&self) -> String {
        self.ui_state.debug_summary()
    }

    pub fn rect_of_key(&self, key: &str) -> Option<Rect> {
        self.last_tree
            .as_ref()
            .and_then(|t| self.ui_state.rect_of_key(t, key))
    }

    // ---- Input plumbing ----

    /// Pointer moved to `(x, y)` (logical px). Updates the hovered
    /// node (readable via `ui_state().hovered`) and, if the primary
    /// button is currently held, returns a `Drag` event routed to the
    /// originally pressed target. The event's `modifiers` field
    /// reflects the mask currently tracked on `UiState` (set by the
    /// host via `set_modifiers`).
    pub fn pointer_moved(&mut self, x: f32, y: f32) -> PointerMove {
        self.ui_state.pointer_pos = Some((x, y));

        // Active scrollbar drag: translate cursor delta into
        // `scroll.offsets` updates. The drag is captured at
        // `pointer_down` so we can map directly onto the scroll
        // container without going through hit-test, and we suppress
        // the normal hover/Drag event emission while it's in flight.
        if let Some(drag) = self.ui_state.scroll.thumb_drag.clone() {
            let dy = y - drag.start_pointer_y;
            let new_offset = if drag.track_remaining > 0.0 {
                drag.start_offset + dy * (drag.max_offset / drag.track_remaining)
            } else {
                drag.start_offset
            };
            let clamped = new_offset.clamp(0.0, drag.max_offset);
            let prev = self.ui_state.scroll.offsets.insert(drag.scroll_id, clamped);
            let changed = prev.is_none_or(|old| (old - clamped).abs() > f32::EPSILON);
            return PointerMove {
                events: Vec::new(),
                needs_redraw: changed,
            };
        }

        let hit = self
            .last_tree
            .as_ref()
            .and_then(|t| hit_test::hit_test_target(t, &self.ui_state, (x, y)));
        let hover_changed = self.ui_state.set_hovered(hit, Instant::now());
        let modifiers = self.ui_state.modifiers;

        let mut out = Vec::new();

        // Selection drag-extend takes precedence over the focusable
        // Drag emission. Cross-leaf: if the pointer hits a selectable
        // leaf, head migrates there. Otherwise we project the pointer
        // onto the closest selectable leaf in document order so that
        // dragging *past* the last leaf extends to its end (rather
        // than snapping the head home to the anchor leaf).
        if let Some(drag) = self.ui_state.selection.drag.clone()
            && let Some(tree) = self.last_tree.as_ref()
        {
            let head_point =
                head_for_drag(tree, &self.ui_state, (x, y)).unwrap_or_else(|| drag.anchor.clone());
            let new_sel = crate::selection::Selection {
                range: Some(crate::selection::SelectionRange {
                    anchor: drag.anchor.clone(),
                    head: head_point,
                }),
            };
            if new_sel != self.ui_state.current_selection {
                self.ui_state.current_selection = new_sel.clone();
                out.push(selection_event(new_sel, modifiers, Some((x, y))));
            }
        }

        // Drag: pointer moved while primary button is down → emit Drag
        // to the originally pressed target. Cursor escape from the
        // pressed node is the *normal* drag-extend case (e.g. text
        // selection inside an editable widget); we keep emitting until
        // pointer_up clears `pressed`.
        if let Some(p) = self.ui_state.pressed.clone() {
            // Caret-blink reset: drag-selecting inside a text input
            // is ongoing editing activity, so keep the caret solid
            // for the duration of the drag.
            if self.focused_captures_keys() {
                self.ui_state.bump_caret_activity(Instant::now());
            }
            out.push(UiEvent {
                key: Some(p.key.clone()),
                target: Some(p),
                pointer: Some((x, y)),
                key_press: None,
                text: None,
                selection: None,
                modifiers,
                click_count: 0,
                kind: UiEventKind::Drag,
            });
        }

        let needs_redraw = hover_changed || !out.is_empty();
        PointerMove {
            events: out,
            needs_redraw,
        }
    }

    pub fn pointer_left(&mut self) {
        self.ui_state.pointer_pos = None;
        self.ui_state.set_hovered(None, Instant::now());
        self.ui_state.pressed = None;
        self.ui_state.pressed_secondary = None;
    }

    /// Primary/secondary/middle pointer button pressed at `(x, y)`.
    /// For the primary button, focuses the hit target and stashes it
    /// as the pressed target; emits a `PointerDown` event so widgets
    /// like text_input can react at down-time (e.g., set the selection
    /// anchor before any drag extends it). Secondary/middle store on a
    /// separate channel and never emit a `PointerDown`.
    ///
    /// Also drives the library's text-selection manager: a primary
    /// press on a `selectable` text leaf starts a drag and produces a
    /// `SelectionChanged` event; a press on any other element clears
    /// any active static-text selection by emitting a
    /// `SelectionChanged` with an empty range.
    pub fn pointer_down(&mut self, x: f32, y: f32, button: PointerButton) -> Vec<UiEvent> {
        // Scrollbar track pre-empts normal hit-test: a primary press
        // inside a scrollable's track column either captures a thumb
        // drag (when the press lands inside the visible thumb rect)
        // or pages the scroll offset by a viewport (when it lands
        // above or below the thumb). Both branches suppress focus /
        // press / event chains for the press itself; `pointer_moved`
        // then drives the drag (no-op for paged clicks) and
        // `pointer_up` clears the drag.
        if matches!(button, PointerButton::Primary)
            && let Some((scroll_id, _track, thumb_rect)) = self.ui_state.thumb_at(x, y)
        {
            let metrics = self
                .ui_state
                .scroll
                .metrics
                .get(&scroll_id)
                .copied()
                .unwrap_or_default();
            let start_offset = self
                .ui_state
                .scroll
                .offsets
                .get(&scroll_id)
                .copied()
                .unwrap_or(0.0);

            // Grab when the press lands inside the visible thumb;
            // page otherwise. The track is wider than the thumb
            // horizontally, so this branch is decided by `y` alone.
            let grabbed = y >= thumb_rect.y && y <= thumb_rect.y + thumb_rect.h;
            if grabbed {
                let track_remaining = (metrics.viewport_h - thumb_rect.h).max(0.0);
                self.ui_state.scroll.thumb_drag = Some(crate::state::ThumbDrag {
                    scroll_id,
                    start_pointer_y: y,
                    start_offset,
                    track_remaining,
                    max_offset: metrics.max_offset,
                });
            } else {
                // Click-to-page. Browser convention: each press
                // shifts the offset by ~one viewport with a small
                // overlap so context isn't lost. Direction is
                // decided by which side of the thumb the press
                // landed on.
                let page = (metrics.viewport_h - SCROLL_PAGE_OVERLAP).max(0.0);
                let delta = if y < thumb_rect.y { -page } else { page };
                let new_offset = (start_offset + delta).clamp(0.0, metrics.max_offset);
                self.ui_state.scroll.offsets.insert(scroll_id, new_offset);
            }
            return Vec::new();
        }

        let hit = self
            .last_tree
            .as_ref()
            .and_then(|t| hit_test::hit_test_target(t, &self.ui_state, (x, y)));
        // Only the primary button drives focus + the visual press
        // envelope. Secondary/middle clicks shouldn't yank focus from
        // the currently-focused element (matches browser/native behavior
        // where right-clicking a button doesn't take focus).
        if !matches!(button, PointerButton::Primary) {
            // Stash the down-target on the secondary/middle channel so
            // pointer_up can confirm the click landed on the same node.
            self.ui_state.pressed_secondary = hit.map(|h| (h, button));
            return Vec::new();
        }

        self.ui_state.set_focus(hit.clone());
        self.ui_state.pressed = hit.clone();
        // A press on the hovered node dismisses any tooltip for
        // the rest of this hover session — matches native UIs.
        self.ui_state.tooltip.dismissed_for_hover = true;
        let modifiers = self.ui_state.modifiers;

        // Click counting: extend a multi-click sequence when the press
        // lands on the same target inside the time + distance window.
        let now = Instant::now();
        let click_count =
            self.ui_state
                .next_click_count(now, (x, y), hit.as_ref().map(|t| t.node_id.as_str()));

        let mut out = Vec::new();
        if let Some(p) = hit.clone() {
            // Caret-blink reset: a press inside the focused widget
            // (e.g., to reposition the caret in an already-focused
            // input) is editing activity. The earlier `set_focus`
            // call bumps when focus *changes*; this catches the
            // same-target case so click-to-move-caret resets the
            // blink too.
            if self.focused_captures_keys() {
                self.ui_state.bump_caret_activity(now);
            }
            out.push(UiEvent {
                key: Some(p.key.clone()),
                target: Some(p),
                pointer: Some((x, y)),
                key_press: None,
                text: None,
                selection: None,
                modifiers,
                click_count,
                kind: UiEventKind::PointerDown,
            });
        }

        // Selection routing. The selection hit-test is independent of
        // the focusable hit: a `text(...).key("p").selectable()` leaf is
        // both a (non-focusable) keyed PointerDown target and a
        // selectable text leaf. Apps see both events; selection drag
        // starts in either case. A press that lands on neither a
        // selectable nor a focusable widget clears any active
        // selection.
        if let Some(point) = self
            .last_tree
            .as_ref()
            .and_then(|t| hit_test::selection_point_at(t, &self.ui_state, (x, y)))
        {
            self.start_selection_drag(point, &mut out, modifiers, (x, y), click_count);
        } else if !self.ui_state.current_selection.is_empty() {
            // Clear-on-click only when the press lands somewhere that
            // can't take selection ownership itself.
            //
            // - If the press is on the widget that already owns the
            //   selection (same key), the widget's PointerDown
            //   handler updates its own caret; a runtime clear here
            //   races and collapses the app's selection back to
            //   default. (User-visible bug: caret alternated between
            //   the click position and byte 0 on every other click.)
            //
            // - If the press is on a *different* capture_keys widget
            //   (e.g., dragging from one text_input into another),
            //   that widget's PointerDown will replace the selection
            //   with one anchored at the click position. The runtime
            //   clear would arrive after the replace and wipe the
            //   anchor — so when the drag began, only `head` would
            //   advance and `anchor` would default to 0, jumping the
            //   selection start to the beginning of the text.
            //
            // Press on a regular focusable (button, etc.) or in dead
            // space still clears, matching the browser idiom.
            let click_handles_selection = match (&hit, &self.ui_state.current_selection.range) {
                (Some(h), Some(range)) => {
                    h.key == range.anchor.key
                        || h.key == range.head.key
                        || self
                            .last_tree
                            .as_ref()
                            .and_then(|t| find_capture_keys(t, &h.node_id))
                            .unwrap_or(false)
                }
                _ => false,
            };
            if !click_handles_selection {
                out.push(selection_event(
                    crate::selection::Selection::default(),
                    modifiers,
                    Some((x, y)),
                ));
                self.ui_state.current_selection = crate::selection::Selection::default();
                self.ui_state.selection.drag = None;
            }
        }

        out
    }

    /// Stamp a new [`crate::state::SelectionDrag`] and emit a
    /// `SelectionChanged` event seeded by `point`. For
    /// `click_count == 2` the anchor / head pair expands to the word
    /// range around `point.byte`; for `click_count >= 3` it expands to
    /// the whole leaf (static-text triple-click typically wants the
    /// paragraph). For other counts (single click, default) the
    /// selection is collapsed at `point`.
    fn start_selection_drag(
        &mut self,
        point: crate::selection::SelectionPoint,
        out: &mut Vec<UiEvent>,
        modifiers: KeyModifiers,
        pointer: (f32, f32),
        click_count: u8,
    ) {
        let leaf_text = self
            .last_tree
            .as_ref()
            .and_then(|t| crate::selection::find_keyed_text(t, &point.key))
            .unwrap_or_default();
        let (anchor_byte, head_byte) = match click_count {
            2 => crate::selection::word_range_at(&leaf_text, point.byte),
            n if n >= 3 => (0, leaf_text.len()),
            _ => (point.byte, point.byte),
        };
        let anchor = crate::selection::SelectionPoint::new(point.key.clone(), anchor_byte);
        let head = crate::selection::SelectionPoint::new(point.key.clone(), head_byte);
        let new_sel = crate::selection::Selection {
            range: Some(crate::selection::SelectionRange {
                anchor: anchor.clone(),
                head,
            }),
        };
        self.ui_state.current_selection = new_sel.clone();
        // The drag anchors at the multi-click range's start so a
        // subsequent drag extends from there rather than from the
        // initial click position.
        self.ui_state.selection.drag = Some(crate::state::SelectionDrag { anchor });
        out.push(selection_event(new_sel, modifiers, Some(pointer)));
    }

    /// Pointer released. For the primary button, fires `PointerUp`
    /// (always, with the originally pressed target so drag-aware
    /// widgets see drag-end) and additionally `Click` if the release
    /// landed on the same node as the down. For secondary / middle,
    /// fires the corresponding click variant when the up landed on the
    /// same node; no analogue of `PointerUp` since drag is a primary-
    /// button concept here.
    pub fn pointer_up(&mut self, x: f32, y: f32, button: PointerButton) -> Vec<UiEvent> {
        // Scrollbar drag ends without producing app-level events —
        // the press never went through `pressed` / `pressed_secondary`
        // so there's nothing else to clean up. Released from anywhere;
        // the drag is global once captured, matching native scrollbars.
        if matches!(button, PointerButton::Primary) && self.ui_state.scroll.thumb_drag.is_some() {
            self.ui_state.scroll.thumb_drag = None;
            return Vec::new();
        }

        // End any active text-selection drag. The selection itself
        // persists; only the "currently dragging" flag goes away.
        if matches!(button, PointerButton::Primary) {
            self.ui_state.selection.drag = None;
        }

        let hit = self
            .last_tree
            .as_ref()
            .and_then(|t| hit_test::hit_test_target(t, &self.ui_state, (x, y)));
        let modifiers = self.ui_state.modifiers;
        let mut out = Vec::new();
        match button {
            PointerButton::Primary => {
                let pressed = self.ui_state.pressed.take();
                let click_count = self.ui_state.current_click_count();
                if let Some(p) = pressed.clone() {
                    out.push(UiEvent {
                        key: Some(p.key.clone()),
                        target: Some(p),
                        pointer: Some((x, y)),
                        key_press: None,
                        text: None,
                        selection: None,
                        modifiers,
                        click_count,
                        kind: UiEventKind::PointerUp,
                    });
                }
                if let (Some(p), Some(h)) = (pressed, hit)
                    && p.node_id == h.node_id
                {
                    // Toast dismiss buttons are runtime-managed —
                    // the click drops the matching toast from the
                    // queue and is *not* surfaced to the app, so
                    // `on_event` doesn't have to know about toast
                    // bookkeeping.
                    if let Some(id) = toast::parse_dismiss_key(&p.key) {
                        self.ui_state.dismiss_toast(id);
                    } else {
                        out.push(UiEvent {
                            key: Some(p.key.clone()),
                            target: Some(p),
                            pointer: Some((x, y)),
                            key_press: None,
                            text: None,
                            selection: None,
                            modifiers,
                            click_count,
                            kind: UiEventKind::Click,
                        });
                    }
                }
            }
            PointerButton::Secondary | PointerButton::Middle => {
                let pressed = self.ui_state.pressed_secondary.take();
                if let (Some((p, b)), Some(h)) = (pressed, hit)
                    && b == button
                    && p.node_id == h.node_id
                {
                    let kind = match button {
                        PointerButton::Secondary => UiEventKind::SecondaryClick,
                        PointerButton::Middle => UiEventKind::MiddleClick,
                        PointerButton::Primary => unreachable!(),
                    };
                    out.push(UiEvent {
                        key: Some(p.key.clone()),
                        target: Some(p),
                        pointer: Some((x, y)),
                        key_press: None,
                        text: None,
                        selection: None,
                        modifiers,
                        click_count: 1,
                        kind,
                    });
                }
            }
        }
        out
    }

    pub fn key_down(&mut self, key: UiKey, modifiers: KeyModifiers, repeat: bool) -> Vec<UiEvent> {
        // Capture path: when the focused node opted into raw key
        // capture, the library's Tab/Enter/Escape interpretation is
        // bypassed and the event is delivered as a raw `KeyDown` to
        // the focused target. Hotkeys still match first — an app's
        // global Ctrl+S beats a text input's local consumption of S.
        if self.focused_captures_keys() {
            if let Some(event) = self.ui_state.try_hotkey(&key, modifiers, repeat) {
                return vec![event];
            }
            // Caret-blink reset: any key arriving at a capture_keys
            // widget is text-editing activity (caret motion, edit,
            // shortcut), so the caret should snap back to solid even
            // when the app doesn't propagate its `Selection` back via
            // `App::selection()`. Without this, hammering arrow keys
            // produces no visible blink reset.
            self.ui_state.bump_caret_activity(Instant::now());
            return self
                .ui_state
                .key_down_raw(key, modifiers, repeat)
                .into_iter()
                .collect();
        }

        // Arrow-nav: if the focused node sits inside an arrow-navigable
        // group (typically a popover_panel of menu items), Up / Down /
        // Home / End move focus among its focusable siblings rather
        // than emitting a `KeyDown` event. Hotkeys are still matched
        // first so a global Ctrl+ArrowUp chord beats menu navigation.
        if matches!(
            key,
            UiKey::ArrowUp | UiKey::ArrowDown | UiKey::Home | UiKey::End
        ) && let Some(siblings) = self.focused_arrow_nav_group()
        {
            if let Some(event) = self.ui_state.try_hotkey(&key, modifiers, repeat) {
                return vec![event];
            }
            self.move_focus_in_group(&key, &siblings);
            return Vec::new();
        }

        let mut out: Vec<UiEvent> = self
            .ui_state
            .key_down(key, modifiers, repeat)
            .into_iter()
            .collect();

        // Esc clears any active text selection (parallels the
        // pointer_down "press lands outside selectable+focusable"
        // path). The Escape event itself still fires so apps can
        // dismiss popovers / modals; the SelectionChanged is emitted
        // alongside it. This only runs in the non-capture-keys path,
        // so pressing Esc while typing in an input doesn't clobber
        // the input's selection — matching browser behavior.
        if matches!(out.first().map(|e| e.kind), Some(UiEventKind::Escape))
            && !self.ui_state.current_selection.is_empty()
        {
            self.ui_state.current_selection = crate::selection::Selection::default();
            self.ui_state.selection.drag = None;
            out.push(selection_event(
                crate::selection::Selection::default(),
                modifiers,
                None,
            ));
        }

        out
    }

    /// Look up the focused node's nearest [`El::arrow_nav_siblings`]
    /// parent in the last laid-out tree and return the focusable
    /// siblings (the navigation targets for Up / Down / Home / End).
    /// Returns `None` when no node is focused, the tree hasn't been
    /// built yet, or the focused element isn't inside an
    /// arrow-navigable parent.
    fn focused_arrow_nav_group(&self) -> Option<Vec<UiTarget>> {
        let focused = self.ui_state.focused.as_ref()?;
        let tree = self.last_tree.as_ref()?;
        focus::arrow_nav_group(tree, &self.ui_state, &focused.node_id)
    }

    /// Move the focused element to the appropriate sibling for `key`.
    /// `Up` / `Down` step by one (saturating at the ends — no wrap, so
    /// holding the key doesn't loop visually); `Home` / `End` jump to
    /// the first / last sibling.
    fn move_focus_in_group(&mut self, key: &UiKey, siblings: &[UiTarget]) {
        if siblings.is_empty() {
            return;
        }
        let focused_id = match self.ui_state.focused.as_ref() {
            Some(t) => t.node_id.clone(),
            None => return,
        };
        let idx = siblings.iter().position(|t| t.node_id == focused_id);
        let next_idx = match (key, idx) {
            (UiKey::ArrowUp, Some(i)) => i.saturating_sub(1),
            (UiKey::ArrowDown, Some(i)) => (i + 1).min(siblings.len() - 1),
            (UiKey::Home, _) => 0,
            (UiKey::End, _) => siblings.len() - 1,
            _ => return,
        };
        if Some(next_idx) != idx {
            self.ui_state.set_focus(Some(siblings[next_idx].clone()));
        }
    }

    /// Look up the focused node in the last laid-out tree and return
    /// its `capture_keys` flag. False when no node is focused or the
    /// tree hasn't been built yet.
    fn focused_captures_keys(&self) -> bool {
        let Some(focused) = self.ui_state.focused.as_ref() else {
            return false;
        };
        let Some(tree) = self.last_tree.as_ref() else {
            return false;
        };
        find_capture_keys(tree, &focused.node_id).unwrap_or(false)
    }

    /// OS-composed text input (printable characters after dead-key /
    /// shift / IME composition). Routed to the focused element as a
    /// `TextInput` event. Returns `None` if no node has focus, or if
    /// `text` is empty (some platforms emit empty composition strings
    /// during IME selection).
    pub fn text_input(&mut self, text: String) -> Option<UiEvent> {
        if text.is_empty() {
            return None;
        }
        let target = self.ui_state.focused.clone()?;
        let modifiers = self.ui_state.modifiers;
        // Caret-blink reset: typing into the focused widget is
        // text-editing activity. See the matching bump in `key_down`.
        self.ui_state.bump_caret_activity(Instant::now());
        Some(UiEvent {
            key: Some(target.key.clone()),
            target: Some(target),
            pointer: None,
            key_press: None,
            text: Some(text),
            selection: None,
            modifiers,
            click_count: 0,
            kind: UiEventKind::TextInput,
        })
    }

    pub fn set_hotkeys(&mut self, hotkeys: Vec<(KeyChord, String)>) {
        self.ui_state.set_hotkeys(hotkeys);
    }

    /// Push the app's current [`crate::selection::Selection`] into the
    /// runtime so the painter can draw highlight bands. Hosts call
    /// this once per frame alongside `set_hotkeys`, sourcing the value
    /// from [`crate::event::App::selection`].
    pub fn set_selection(&mut self, selection: crate::selection::Selection) {
        if self.ui_state.current_selection != selection {
            self.ui_state.bump_caret_activity(Instant::now());
        }
        self.ui_state.current_selection = selection;
    }

    /// Queue toast specs onto the runtime's toast stack. Each spec
    /// is stamped with a monotonic id and `expires_at = now + ttl`;
    /// the next `prepare_layout` call drops expired entries and
    /// synthesizes a `toast_stack` floating layer over the rest.
    /// Hosts wire this from `App::drain_toasts` once per frame.
    pub fn push_toasts(&mut self, specs: Vec<crate::toast::ToastSpec>) {
        let now = Instant::now();
        for spec in specs {
            self.ui_state.push_toast(spec, now);
        }
    }

    /// Programmatically dismiss a single toast by id. Mostly useful
    /// when the app wants to cancel a long-TTL toast in response to
    /// some external event (e.g., the connection reconnected).
    pub fn dismiss_toast(&mut self, id: u64) {
        self.ui_state.dismiss_toast(id);
    }

    pub fn set_animation_mode(&mut self, mode: AnimationMode) {
        self.ui_state.set_animation_mode(mode);
    }

    pub fn pointer_wheel(&mut self, x: f32, y: f32, dy: f32) -> bool {
        let Some(tree) = self.last_tree.as_ref() else {
            return false;
        };
        self.ui_state.pointer_wheel(tree, (x, y), dy)
    }

    // ---- Per-frame staging ----

    /// Layout + state apply + animation tick + viewport projection +
    /// `DrawOp` resolution. Returns the resolved op list and whether
    /// visual animations need another frame; writes per-stage timings
    /// into `timings` (`layout` + `draw_ops`).
    pub fn prepare_layout(
        &mut self,
        root: &mut El,
        viewport: Rect,
        scale_factor: f32,
        timings: &mut PrepareTimings,
    ) -> (Vec<DrawOp>, bool) {
        let t0 = Instant::now();
        // Tooltip + toast synthesis run before the real layout: assign
        // ids first so the tooltip pass can resolve the hover anchor
        // by computed_id, then append the runtime-managed floating
        // layers. The subsequent `layout::layout` call re-assigns
        // (idempotently — same path shapes produce the same ids) and
        // lays out the appended layers alongside everything else.
        layout::assign_ids(root);
        let tooltip_pending = tooltip::synthesize_tooltip(root, &self.ui_state, t0);
        let toast_pending = toast::synthesize_toasts(root, &mut self.ui_state, t0);
        self.theme.apply_metrics(root);
        layout::layout(root, &mut self.ui_state, viewport);
        self.ui_state.sync_focus_order(root);
        self.ui_state.sync_selection_order(root);
        focus::sync_popover_focus(root, &mut self.ui_state);
        self.ui_state.apply_to_state();
        let needs_redraw = self.ui_state.tick_visual_animations(root, Instant::now())
            || tooltip_pending
            || toast_pending;
        self.viewport_px = self.surface_size_override.unwrap_or_else(|| {
            (
                (viewport.w * scale_factor).ceil().max(1.0) as u32,
                (viewport.h * scale_factor).ceil().max(1.0) as u32,
            )
        });
        let t_after_layout = Instant::now();
        let ops = draw_ops::draw_ops_with_theme(root, &self.ui_state, &self.theme);
        let t_after_draw_ops = Instant::now();
        timings.layout = t_after_layout - t0;
        timings.draw_ops = t_after_draw_ops - t_after_layout;
        (ops, needs_redraw)
    }

    /// Walk the resolved `DrawOp` list, packing quads into
    /// `quad_scratch` + grouping them into `runs`, interleaving text
    /// records via the backend-supplied [`TextRecorder`]. Returns the
    /// number of quad instances written (so the backend can size its
    /// instance buffer).
    ///
    /// Callers must call `text.frame_begin()` themselves *before*
    /// invoking this — `prepare_paint` does not call it for them
    /// because backends often want to clear other per-frame text
    /// scratch in the same step.
    pub fn prepare_paint<F1, F2>(
        &mut self,
        ops: &[DrawOp],
        is_registered: F1,
        samples_backdrop: F2,
        text: &mut dyn TextRecorder,
        scale_factor: f32,
        timings: &mut PrepareTimings,
    ) where
        F1: Fn(&ShaderHandle) -> bool,
        F2: Fn(&ShaderHandle) -> bool,
    {
        let t0 = Instant::now();
        self.quad_scratch.clear();
        self.runs.clear();
        self.paint_items.clear();

        let mut current: Option<(ShaderHandle, Option<PhysicalScissor>)> = None;
        let mut run_first: u32 = 0;
        // At most one snapshot per frame. Auto-inserted before
        // the first paint that samples the backdrop.
        let mut snapshot_emitted = false;

        for op in ops {
            match op {
                DrawOp::Quad {
                    rect,
                    scissor,
                    shader,
                    uniforms,
                    ..
                } => {
                    if !is_registered(shader) {
                        continue;
                    }
                    let phys = physical_scissor(*scissor, scale_factor, self.viewport_px);
                    if matches!(phys, Some(s) if s.w == 0 || s.h == 0) {
                        continue;
                    }
                    if !snapshot_emitted && samples_backdrop(shader) {
                        close_run(
                            &mut self.runs,
                            &mut self.paint_items,
                            current,
                            run_first,
                            self.quad_scratch.len() as u32,
                        );
                        current = None;
                        run_first = self.quad_scratch.len() as u32;
                        self.paint_items.push(PaintItem::BackdropSnapshot);
                        snapshot_emitted = true;
                    }
                    let inst = pack_instance(*rect, *shader, uniforms);

                    let key = (*shader, phys);
                    if current != Some(key) {
                        close_run(
                            &mut self.runs,
                            &mut self.paint_items,
                            current,
                            run_first,
                            self.quad_scratch.len() as u32,
                        );
                        current = Some(key);
                        run_first = self.quad_scratch.len() as u32;
                    }
                    self.quad_scratch.push(inst);
                }
                DrawOp::GlyphRun {
                    rect,
                    scissor,
                    color,
                    text: glyph_text,
                    size,
                    line_height,
                    family,
                    weight,
                    wrap,
                    anchor,
                    underline,
                    strikethrough,
                    link,
                    ..
                } => {
                    close_run(
                        &mut self.runs,
                        &mut self.paint_items,
                        current,
                        run_first,
                        self.quad_scratch.len() as u32,
                    );
                    current = None;
                    run_first = self.quad_scratch.len() as u32;

                    let phys = physical_scissor(*scissor, scale_factor, self.viewport_px);
                    if matches!(phys, Some(s) if s.w == 0 || s.h == 0) {
                        continue;
                    }
                    let mut style =
                        crate::text::atlas::RunStyle::new(*weight, *color).family(*family);
                    if *underline {
                        style = style.underline();
                    }
                    if *strikethrough {
                        style = style.strikethrough();
                    }
                    if let Some(url) = link {
                        style = style.with_link(url.clone());
                    }
                    let layers = text.record(
                        *rect,
                        phys,
                        &style,
                        glyph_text,
                        *size,
                        *line_height,
                        *wrap,
                        *anchor,
                        scale_factor,
                    );
                    for index in layers {
                        self.paint_items.push(PaintItem::Text(index));
                    }
                }
                DrawOp::AttributedText {
                    rect,
                    scissor,
                    runs,
                    size,
                    line_height,
                    wrap,
                    anchor,
                    ..
                } => {
                    close_run(
                        &mut self.runs,
                        &mut self.paint_items,
                        current,
                        run_first,
                        self.quad_scratch.len() as u32,
                    );
                    current = None;
                    run_first = self.quad_scratch.len() as u32;

                    let phys = physical_scissor(*scissor, scale_factor, self.viewport_px);
                    if matches!(phys, Some(s) if s.w == 0 || s.h == 0) {
                        continue;
                    }
                    let layers = text.record_runs(
                        *rect,
                        phys,
                        runs,
                        *size,
                        *line_height,
                        *wrap,
                        *anchor,
                        scale_factor,
                    );
                    for index in layers {
                        self.paint_items.push(PaintItem::Text(index));
                    }
                }
                DrawOp::Icon {
                    rect,
                    scissor,
                    source,
                    color,
                    size,
                    stroke_width,
                    ..
                } => {
                    close_run(
                        &mut self.runs,
                        &mut self.paint_items,
                        current,
                        run_first,
                        self.quad_scratch.len() as u32,
                    );
                    current = None;
                    run_first = self.quad_scratch.len() as u32;

                    let phys = physical_scissor(*scissor, scale_factor, self.viewport_px);
                    if matches!(phys, Some(s) if s.w == 0 || s.h == 0) {
                        continue;
                    }
                    let recorded = text.record_icon(
                        *rect,
                        phys,
                        source,
                        *color,
                        *size,
                        *stroke_width,
                        scale_factor,
                    );
                    match recorded {
                        RecordedPaint::Text(layers) => {
                            for index in layers {
                                self.paint_items.push(PaintItem::Text(index));
                            }
                        }
                        RecordedPaint::Icon(runs) => {
                            for index in runs {
                                self.paint_items.push(PaintItem::IconRun(index));
                            }
                        }
                    }
                }
                DrawOp::Image {
                    rect,
                    scissor,
                    image,
                    tint,
                    radius,
                    fit,
                    ..
                } => {
                    close_run(
                        &mut self.runs,
                        &mut self.paint_items,
                        current,
                        run_first,
                        self.quad_scratch.len() as u32,
                    );
                    current = None;
                    run_first = self.quad_scratch.len() as u32;

                    let phys = physical_scissor(*scissor, scale_factor, self.viewport_px);
                    if matches!(phys, Some(s) if s.w == 0 || s.h == 0) {
                        continue;
                    }
                    let recorded =
                        text.record_image(*rect, phys, image, *tint, *radius, *fit, scale_factor);
                    for index in recorded {
                        self.paint_items.push(PaintItem::Image(index));
                    }
                }
                DrawOp::BackdropSnapshot => {
                    close_run(
                        &mut self.runs,
                        &mut self.paint_items,
                        current,
                        run_first,
                        self.quad_scratch.len() as u32,
                    );
                    current = None;
                    run_first = self.quad_scratch.len() as u32;
                    // Cap at one snapshot per frame; an explicit op only
                    // lands if the auto-emitter hasn't fired yet.
                    if !snapshot_emitted {
                        self.paint_items.push(PaintItem::BackdropSnapshot);
                        snapshot_emitted = true;
                    }
                }
            }
        }
        close_run(
            &mut self.runs,
            &mut self.paint_items,
            current,
            run_first,
            self.quad_scratch.len() as u32,
        );
        timings.paint = Instant::now() - t0;
    }

    /// Take a clone of the laid-out tree for next-frame hit-testing.
    /// Call after the per-frame work completes (GPU upload, atlas
    /// flush, etc.) so the snapshot reflects final geometry. Writes
    /// `timings.snapshot`.
    pub fn snapshot(&mut self, root: &El, timings: &mut PrepareTimings) {
        let t0 = Instant::now();
        self.last_tree = Some(root.clone());
        timings.snapshot = Instant::now() - t0;
    }
}

/// Find the `capture_keys` flag of the node whose `computed_id`
/// equals `id`, walking the laid-out tree. Returns `None` when the id
/// isn't found (the focused target outlived its node — a one-frame
/// race after a rebuild).
pub(crate) fn find_capture_keys(node: &El, id: &str) -> Option<bool> {
    if node.computed_id == id {
        return Some(node.capture_keys);
    }
    node.children.iter().find_map(|c| find_capture_keys(c, id))
}

/// Construct a `SelectionChanged` event carrying the new selection.
fn selection_event(
    new_sel: crate::selection::Selection,
    modifiers: KeyModifiers,
    pointer: Option<(f32, f32)>,
) -> UiEvent {
    UiEvent {
        kind: UiEventKind::SelectionChanged,
        key: None,
        target: None,
        pointer,
        key_press: None,
        text: None,
        selection: Some(new_sel),
        modifiers,
        click_count: 0,
    }
}

/// Resolve the head's [`SelectionPoint`] for the current pointer
/// position during a drag. Browser-style projection rules:
///
/// - If the pointer hits a selectable leaf, head goes there.
/// - Otherwise, head goes to the closest selectable leaf in document
///   order, with `(x, y)` projected onto that leaf's vertical extent.
///   Above all leaves → first leaf at byte 0; below all → last leaf
///   at end; in the gap between two adjacent leaves → whichever is
///   nearer in y.
/// - Horizontally outside the chosen leaf's text → snap to the
///   leaf's left edge (byte 0) or right edge (`text.len()`).
fn head_for_drag(
    root: &El,
    ui_state: &UiState,
    point: (f32, f32),
) -> Option<crate::selection::SelectionPoint> {
    if let Some(p) = hit_test::selection_point_at(root, ui_state, point) {
        return Some(p);
    }

    let order = &ui_state.selection.order;
    if order.is_empty() {
        return None;
    }
    // Prefer a leaf whose vertical extent contains the pointer's y;
    // otherwise pick the y-closest leaf. min_by visits in document
    // order so ties (multiple leaves at the same y-distance) resolve
    // to the earliest one.
    let target = order
        .iter()
        .find(|t| point.1 >= t.rect.y && point.1 < t.rect.y + t.rect.h)
        .or_else(|| {
            order.iter().min_by(|a, b| {
                let da = y_distance(a.rect, point.1);
                let db = y_distance(b.rect, point.1);
                da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
            })
        })?;
    let target_rect = target.rect;
    let cy = point
        .1
        .clamp(target_rect.y, target_rect.y + target_rect.h - 1.0);
    if let Some(p) = hit_test::selection_point_at(root, ui_state, (point.0, cy)) {
        return Some(p);
    }
    // Couldn't hit-test (likely because the pointer's x is outside
    // the leaf's rendered text width). Snap to the nearest edge.
    let leaf_len = find_text_len(root, &target.node_id).unwrap_or(0);
    let byte = if point.0 < target_rect.x { 0 } else { leaf_len };
    Some(crate::selection::SelectionPoint {
        key: target.key.clone(),
        byte,
    })
}

fn y_distance(rect: Rect, y: f32) -> f32 {
    if y < rect.y {
        rect.y - y
    } else if y > rect.y + rect.h {
        y - (rect.y + rect.h)
    } else {
        0.0
    }
}

fn find_text_len(node: &El, id: &str) -> Option<usize> {
    if node.computed_id == id {
        return node.text.as_ref().map(|t| t.len());
    }
    node.children.iter().find_map(|c| find_text_len(c, id))
}

/// Recorded output from an icon draw op. Backends without a vector-icon
/// path use `Text` fallback layers; wgpu can return dedicated icon runs.
pub enum RecordedPaint {
    Text(Range<usize>),
    Icon(Range<usize>),
}

/// Glyph-recording surface implemented by each backend's `TextPaint`.
/// `prepare_paint` calls into it exactly the same way wgpu and vulkano
/// would call their per-backend equivalents.
pub trait TextRecorder {
    /// Append per-glyph instances for `text` and return the range of
    /// indices written into the backend's `TextLayer` storage. Each
    /// returned index lands in `paint_items` as a `PaintItem::Text`.
    ///
    /// `style` carries weight + color + (optional) decoration flags
    /// — backends fold it into a single-element `(text, style)` slice
    /// and run the same shaping path as [`Self::record_runs`].
    #[allow(clippy::too_many_arguments)]
    fn record(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        style: &RunStyle,
        text: &str,
        size: f32,
        line_height: f32,
        wrap: TextWrap,
        anchor: TextAnchor,
        scale_factor: f32,
    ) -> Range<usize>;

    /// Append per-glyph instances for an attributed paragraph (one
    /// shaped run with per-character RunStyle metadata). Wrapping
    /// decisions cross run boundaries — the result is one ShapedRun
    /// just like a single-style call.
    #[allow(clippy::too_many_arguments)]
    fn record_runs(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        runs: &[(String, RunStyle)],
        size: f32,
        line_height: f32,
        wrap: TextWrap,
        anchor: TextAnchor,
        scale_factor: f32,
    ) -> Range<usize>;

    /// Append a vector icon. Backends with a native vector painter
    /// override this; the default keeps experimental/simple backends on
    /// the previous text-symbol fallback. Built-in icons fall back to
    /// their named glyph; app-supplied SVG icons fall back to a
    /// generic placeholder since they have no canonical glyph.
    #[allow(clippy::too_many_arguments)]
    fn record_icon(
        &mut self,
        rect: Rect,
        scissor: Option<PhysicalScissor>,
        source: &crate::svg_icon::IconSource,
        color: Color,
        size: f32,
        _stroke_width: f32,
        scale_factor: f32,
    ) -> RecordedPaint {
        let glyph = match source {
            crate::svg_icon::IconSource::Builtin(name) => name.fallback_glyph(),
            crate::svg_icon::IconSource::Custom(_) => "?",
        };
        RecordedPaint::Text(self.record(
            rect,
            scissor,
            &RunStyle::new(FontWeight::Regular, color),
            glyph,
            size,
            crate::text::metrics::line_height(size),
            TextWrap::NoWrap,
            TextAnchor::Middle,
            scale_factor,
        ))
    }

    /// Append a raster image draw. Backends with texture sampling
    /// override this and return one or more indices into their image
    /// storage (each index lands in `paint_items` as
    /// `PaintItem::Image`). The default returns an empty range —
    /// backends without raster support paint nothing for image Els
    /// (the SVG fallback emits a labelled placeholder rect on its own).
    #[allow(clippy::too_many_arguments)]
    fn record_image(
        &mut self,
        _rect: Rect,
        _scissor: Option<PhysicalScissor>,
        _image: &crate::image::Image,
        _tint: Option<Color>,
        _radius: f32,
        _fit: crate::image::ImageFit,
        _scale_factor: f32,
    ) -> Range<usize> {
        0..0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shader::{ShaderHandle, StockShader, UniformBlock};

    /// Minimal recorder for tests that don't exercise the text path.
    struct NoText;
    impl TextRecorder for NoText {
        fn record(
            &mut self,
            _rect: Rect,
            _scissor: Option<PhysicalScissor>,
            _style: &RunStyle,
            _text: &str,
            _size: f32,
            _line_height: f32,
            _wrap: TextWrap,
            _anchor: TextAnchor,
            _scale_factor: f32,
        ) -> Range<usize> {
            0..0
        }
        fn record_runs(
            &mut self,
            _rect: Rect,
            _scissor: Option<PhysicalScissor>,
            _runs: &[(String, RunStyle)],
            _size: f32,
            _line_height: f32,
            _wrap: TextWrap,
            _anchor: TextAnchor,
            _scale_factor: f32,
        ) -> Range<usize> {
            0..0
        }
    }

    // ---- input plumbing ----

    /// A tree with one focusable button at (10,10,80,40) keyed "btn",
    /// plus an optional capture_keys text input at (10,60,80,40) keyed
    /// "ti". layout() runs against a 200x200 viewport so the rects
    /// land where we expect.
    fn lay_out_input_tree(capture: bool) -> RunnerCore {
        use crate::tree::*;
        let ti = if capture {
            crate::widgets::text::text("input").key("ti").capture_keys()
        } else {
            crate::widgets::text::text("noop").key("ti").focusable()
        };
        let mut tree =
            crate::column([crate::widgets::button::button("Btn").key("btn"), ti]).padding(10.0);
        let mut core = RunnerCore::new();
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 200.0, 200.0),
        );
        core.ui_state.sync_focus_order(&tree);
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);
        core
    }

    #[test]
    fn pointer_up_emits_pointer_up_then_click() {
        let mut core = lay_out_input_tree(false);
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        core.pointer_moved(cx, cy);
        core.pointer_down(cx, cy, PointerButton::Primary);
        let events = core.pointer_up(cx, cy, PointerButton::Primary);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        assert_eq!(kinds, vec![UiEventKind::PointerUp, UiEventKind::Click]);
    }

    #[test]
    fn pointer_up_off_target_emits_only_pointer_up() {
        let mut core = lay_out_input_tree(false);
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        core.pointer_down(cx, cy, PointerButton::Primary);
        // Release off-target (well outside any keyed node).
        let events = core.pointer_up(180.0, 180.0, PointerButton::Primary);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![UiEventKind::PointerUp],
            "drag-off-target should still surface PointerUp so widgets see drag-end"
        );
    }

    #[test]
    fn pointer_moved_while_pressed_emits_drag() {
        let mut core = lay_out_input_tree(false);
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        core.pointer_down(cx, cy, PointerButton::Primary);
        let drag = core
            .pointer_moved(cx + 30.0, cy)
            .events
            .into_iter()
            .find(|e| e.kind == UiEventKind::Drag)
            .expect("drag while pressed");
        assert_eq!(drag.target.as_ref().map(|t| t.key.as_str()), Some("btn"));
        assert_eq!(drag.pointer, Some((cx + 30.0, cy)));
    }

    #[test]
    fn toast_dismiss_click_removes_toast_and_suppresses_click_event() {
        use crate::toast::ToastSpec;
        use crate::tree::Size;
        // Build a fresh runner, queue a toast, prepare once so the
        // toast layer is laid out, then synthesize a click on its
        // dismiss button.
        let mut core = RunnerCore::new();
        core.ui_state
            .push_toast(ToastSpec::success("hi"), Instant::now());
        let toast_id = core.ui_state.toasts()[0].id;

        // Build & lay out a tree with the toast layer appended.
        // Root is `stack(...)` (Axis::Overlay) so the synthesized
        // toast layer overlays rather than competing for flex space.
        let mut tree: El = crate::stack(std::iter::empty::<El>())
            .width(Size::Fill(1.0))
            .height(Size::Fill(1.0));
        crate::layout::assign_ids(&mut tree);
        let _ = crate::toast::synthesize_toasts(&mut tree, &mut core.ui_state, Instant::now());
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 800.0, 600.0),
        );
        core.ui_state.sync_focus_order(&tree);
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);

        let dismiss_key = format!("toast-dismiss-{toast_id}");
        let dismiss_rect = core.rect_of_key(&dismiss_key).expect("dismiss button");
        let cx = dismiss_rect.x + dismiss_rect.w * 0.5;
        let cy = dismiss_rect.y + dismiss_rect.h * 0.5;

        core.pointer_down(cx, cy, PointerButton::Primary);
        let events = core.pointer_up(cx, cy, PointerButton::Primary);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        // PointerUp still fires (kept generic so drag-aware widgets
        // observe drag-end); Click is intercepted by the toast
        // bookkeeping.
        assert!(
            !kinds.contains(&UiEventKind::Click),
            "Click on toast-dismiss should not be surfaced: {kinds:?}",
        );
        assert!(
            core.ui_state.toasts().iter().all(|t| t.id != toast_id),
            "toast {toast_id} should be dropped after dismiss-click",
        );
    }

    #[test]
    fn pointer_moved_without_press_emits_no_drag() {
        let mut core = lay_out_input_tree(false);
        assert!(core.pointer_moved(50.0, 50.0).events.is_empty());
    }

    #[test]
    fn pointer_moved_within_same_hovered_node_does_not_request_redraw() {
        // Wayland delivers CursorMoved at very high frequency while
        // the cursor sits over the surface. Hosts gate request_redraw
        // on `needs_redraw`; this test pins the contract so we don't
        // regress to the unconditional-redraw behaviour that pegged
        // settings_modal at 100% CPU under cursor activity.
        let mut core = lay_out_input_tree(false);
        let btn = core.rect_of_key("btn").expect("btn rect");
        let (cx, cy) = (btn.x + btn.w * 0.5, btn.y + btn.h * 0.5);

        // First move enters the button — hover identity changes.
        let first = core.pointer_moved(cx, cy);
        assert!(first.events.is_empty());
        assert!(
            first.needs_redraw,
            "entering a focusable should warrant a redraw",
        );

        // Same node, slightly different coords. Hover identity is
        // unchanged, no drag is active — must not redraw.
        let second = core.pointer_moved(cx + 1.0, cy);
        assert!(second.events.is_empty());
        assert!(
            !second.needs_redraw,
            "identical hover, no drag → host should idle",
        );

        // Moving off the button into empty space changes hover to
        // None — that's a visible transition (envelope ramps down).
        let off = core.pointer_moved(0.0, 0.0);
        assert!(off.events.is_empty());
        assert!(
            off.needs_redraw,
            "leaving a hovered node still warrants a redraw",
        );
    }

    fn lay_out_paragraph_tree() -> RunnerCore {
        use crate::tree::*;
        let mut tree = crate::column([
            crate::widgets::text::text("First paragraph of text.")
                .key("p1")
                .selectable(),
            crate::widgets::text::text("Second paragraph of text.")
                .key("p2")
                .selectable(),
        ])
        .padding(20.0);
        let mut core = RunnerCore::new();
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 400.0, 300.0),
        );
        core.ui_state.sync_focus_order(&tree);
        core.ui_state.sync_selection_order(&tree);
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);
        core
    }

    #[test]
    fn pointer_down_on_selectable_text_emits_selection_changed() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cx = p1.x + 4.0;
        let cy = p1.y + p1.h * 0.5;
        let events = core.pointer_down(cx, cy, PointerButton::Primary);
        let sel_event = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .expect("SelectionChanged emitted");
        let new_sel = sel_event
            .selection
            .as_ref()
            .expect("SelectionChanged carries a selection");
        let range = new_sel.range.as_ref().expect("collapsed selection at hit");
        assert_eq!(range.anchor.key, "p1");
        assert_eq!(range.head.key, "p1");
        assert_eq!(range.anchor.byte, range.head.byte);
        assert!(core.ui_state.selection.drag.is_some());
    }

    #[test]
    fn pointer_drag_on_selectable_text_extends_head() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cx = p1.x + 4.0;
        let cy = p1.y + p1.h * 0.5;
        core.pointer_moved(cx, cy);
        core.pointer_down(cx, cy, PointerButton::Primary);

        // Drag to the right inside p1.
        let events = core.pointer_moved(p1.x + p1.w - 10.0, cy).events;
        let sel_event = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .expect("Drag emits SelectionChanged");
        let new_sel = sel_event.selection.as_ref().unwrap();
        let range = new_sel.range.as_ref().unwrap();
        assert_eq!(range.anchor.key, "p1");
        assert_eq!(range.head.key, "p1");
        assert!(
            range.head.byte > range.anchor.byte,
            "head should advance past anchor (anchor={}, head={})",
            range.anchor.byte,
            range.head.byte
        );
    }

    #[test]
    fn pointer_up_clears_drag_but_keeps_selection() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cx = p1.x + 4.0;
        let cy = p1.y + p1.h * 0.5;
        core.pointer_down(cx, cy, PointerButton::Primary);
        core.pointer_moved(p1.x + p1.w - 10.0, cy);
        let _ = core.pointer_up(p1.x + p1.w - 10.0, cy, PointerButton::Primary);
        assert!(
            core.ui_state.selection.drag.is_none(),
            "drag flag should clear on pointer_up"
        );
        assert!(
            !core.ui_state.current_selection.is_empty(),
            "selection itself should persist after pointer_up"
        );
    }

    #[test]
    fn drag_past_a_leaf_bottom_keeps_head_in_that_leaf_not_anchor() {
        // Regression: a previous helper (`byte_in_anchor_leaf`)
        // projected any out-of-leaf pointer back onto the anchor leaf.
        // That meant moving the cursor below p2's bottom edge while
        // dragging from p1 caused the head to snap home to p1 — the
        // selection band visibly shrank back instead of extending.
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let p2 = core.rect_of_key("p2").expect("p2 rect");
        // Anchor in p1.
        core.pointer_down(p1.x + 4.0, p1.y + p1.h * 0.5, PointerButton::Primary);
        // Drag into p2 first — head migrates.
        core.pointer_moved(p2.x + 8.0, p2.y + p2.h * 0.5);
        // Now move WELL BELOW p2's rect (well below all selectables).
        // Head should remain in p2 (last leaf in this fixture is p2).
        let events = core.pointer_moved(p2.x + 8.0, p2.y + p2.h + 200.0).events;
        let sel = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .map(|e| e.selection.as_ref().unwrap().clone())
            // No SelectionChanged emitted means the value didn't move
            // — read it back from the live UiState directly.
            .unwrap_or_else(|| core.ui_state.current_selection.clone());
        let r = sel.range.as_ref().expect("selection still active");
        assert_eq!(r.anchor.key, "p1", "anchor unchanged");
        assert_eq!(
            r.head.key, "p2",
            "head must stay in p2 even when pointer is below p2's rect"
        );
    }

    #[test]
    fn drag_into_a_sibling_selectable_extends_head_into_that_leaf() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let p2 = core.rect_of_key("p2").expect("p2 rect");
        // Anchor at the start of p1.
        core.pointer_down(p1.x + 4.0, p1.y + p1.h * 0.5, PointerButton::Primary);
        // Drag down into p2.
        let events = core.pointer_moved(p2.x + 8.0, p2.y + p2.h * 0.5).events;
        let sel_event = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .expect("Drag emits SelectionChanged");
        let new_sel = sel_event.selection.as_ref().unwrap();
        let range = new_sel.range.as_ref().unwrap();
        assert_eq!(range.anchor.key, "p1", "anchor stays in p1");
        assert_eq!(range.head.key, "p2", "head migrates into p2");
    }

    #[test]
    fn pointer_down_on_focusable_owning_selection_does_not_clear_it() {
        // Regression: clicking inside a text_input (focusable but not
        // a `.selectable()` leaf) used to fire SelectionChanged-empty
        // because selection_point_at missed and the runtime's
        // clear-fallback didn't notice the click landed on the same
        // widget that owned the active selection. The input's
        // PointerDown set the caret, then the empty SelectionChanged
        // collapsed it back to byte 0 every other click.
        let mut core = lay_out_input_tree(true);
        // Seed a selection in the input's key — this is what the
        // text_input would have written back via apply_event_with.
        core.set_selection(crate::selection::Selection::caret("ti", 3));
        let ti = core.rect_of_key("ti").expect("ti rect");
        let cx = ti.x + ti.w * 0.5;
        let cy = ti.y + ti.h * 0.5;

        let events = core.pointer_down(cx, cy, PointerButton::Primary);
        let cleared = events.iter().find(|e| {
            e.kind == UiEventKind::SelectionChanged
                && e.selection.as_ref().map(|s| s.is_empty()).unwrap_or(false)
        });
        assert!(
            cleared.is_none(),
            "click on the selection-owning input must not emit a clearing SelectionChanged"
        );
        assert_eq!(
            core.ui_state.current_selection,
            crate::selection::Selection::caret("ti", 3),
            "runtime mirror is preserved when the click owns the selection"
        );
    }

    #[test]
    fn pointer_down_into_a_different_capture_keys_widget_does_not_clear_first() {
        // Regression: clicking into text_input A while the selection
        // lives in text_input B used to trigger the runtime's
        // clear-fallback. The empty SelectionChanged arrived after
        // A's PointerDown (which had set anchor = head = click pos),
        // collapsing the app's selection to default. The next Drag
        // event then read `selection.within(A) = None`, defaulted
        // anchor to 0, and only advanced head — so dragging into A
        // started the selection from byte 0 of the text instead of
        // the click position.
        let mut core = lay_out_input_tree(true);
        // Active selection lives in some other key, not "ti".
        core.set_selection(crate::selection::Selection::caret("other", 4));
        let ti = core.rect_of_key("ti").expect("ti rect");
        let cx = ti.x + ti.w * 0.5;
        let cy = ti.y + ti.h * 0.5;

        let events = core.pointer_down(cx, cy, PointerButton::Primary);
        let cleared = events.iter().any(|e| {
            e.kind == UiEventKind::SelectionChanged
                && e.selection.as_ref().map(|s| s.is_empty()).unwrap_or(false)
        });
        assert!(
            !cleared,
            "click on a different capture_keys widget must not race-clear the selection"
        );
    }

    #[test]
    fn pointer_down_on_non_selectable_clears_existing_selection() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cy = p1.y + p1.h * 0.5;
        // Establish a selection in p1.
        core.pointer_down(p1.x + 4.0, cy, PointerButton::Primary);
        core.pointer_up(p1.x + 4.0, cy, PointerButton::Primary);
        assert!(!core.ui_state.current_selection.is_empty());

        // Press in empty space (no selectable, no focusable).
        let events = core.pointer_down(2.0, 2.0, PointerButton::Primary);
        let cleared = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .expect("clearing emits SelectionChanged");
        let new_sel = cleared.selection.as_ref().unwrap();
        assert!(new_sel.is_empty(), "new selection should be empty");
        assert!(core.ui_state.current_selection.is_empty());
    }

    #[test]
    fn key_down_bumps_caret_activity_when_focused_widget_captures_keys() {
        // Showcase-style scenario: the app doesn't propagate its
        // Selection back via App::selection(), so set_selection always
        // sees the default-empty value and never bumps. The runtime
        // bump path catches arrow-key navigation directly.
        let mut core = lay_out_input_tree(true);
        let target = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "ti")
            .cloned();
        core.ui_state.set_focus(target); // focus moves → first bump
        let after_focus = core.ui_state.caret.activity_at.expect("focus bump");

        std::thread::sleep(std::time::Duration::from_millis(2));
        let _ = core.key_down(UiKey::ArrowRight, KeyModifiers::default(), false);
        let after_arrow = core
            .ui_state
            .caret
            .activity_at
            .expect("arrow key bumps even without app-side selection");
        assert!(
            after_arrow > after_focus,
            "ArrowRight to a capture_keys focused widget bumps caret activity"
        );
    }

    #[test]
    fn text_input_bumps_caret_activity_when_focused() {
        let mut core = lay_out_input_tree(true);
        let target = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "ti")
            .cloned();
        core.ui_state.set_focus(target);
        let after_focus = core.ui_state.caret.activity_at.unwrap();

        std::thread::sleep(std::time::Duration::from_millis(2));
        let _ = core.text_input("a".into());
        let after_text = core.ui_state.caret.activity_at.unwrap();
        assert!(
            after_text > after_focus,
            "TextInput to focused widget bumps caret activity"
        );
    }

    #[test]
    fn pointer_down_inside_focused_input_bumps_caret_activity() {
        // Clicking again inside an already-focused capture_keys widget
        // doesn't change the focus target, so set_focus is a no-op
        // for activity. The runtime catches this so click-to-move-
        // caret resets the blink.
        let mut core = lay_out_input_tree(true);
        let ti = core.rect_of_key("ti").expect("ti rect");
        let cx = ti.x + ti.w * 0.5;
        let cy = ti.y + ti.h * 0.5;

        // First click → focus moves → bump.
        core.pointer_down(cx, cy, PointerButton::Primary);
        let _ = core.pointer_up(cx, cy, PointerButton::Primary);
        let after_first = core.ui_state.caret.activity_at.unwrap();

        // Second click on the same input → focus doesn't move, but
        // it's still caret-relevant activity.
        std::thread::sleep(std::time::Duration::from_millis(2));
        core.pointer_down(cx + 1.0, cy, PointerButton::Primary);
        let after_second = core
            .ui_state
            .caret
            .activity_at
            .expect("second click bumps too");
        assert!(
            after_second > after_first,
            "click within already-focused capture_keys widget still bumps"
        );
    }

    #[test]
    fn arrow_key_through_apply_event_mutates_selection_and_bumps_on_set() {
        // End-to-end check that the path used by the text_input
        // example does in fact differ-then-bump on each arrow-key
        // press. If this regresses, the caret won't reset its blink
        // when the user moves the cursor — exactly what the polish
        // pass is meant to fix.
        use crate::widgets::text_input;
        let mut sel = crate::selection::Selection::caret("ti", 2);
        let mut value = String::from("hello");

        let mut core = RunnerCore::new();
        // Seed the runtime mirror so the first set_selection below
        // doesn't bump from "default → caret(2)".
        core.set_selection(sel.clone());
        let baseline = core.ui_state.caret.activity_at;

        // Build a synthetic ArrowRight KeyDown for the input's key.
        let arrow_right = UiEvent {
            key: Some("ti".into()),
            target: None,
            pointer: None,
            key_press: Some(crate::event::KeyPress {
                key: UiKey::ArrowRight,
                modifiers: KeyModifiers::default(),
                repeat: false,
            }),
            text: None,
            selection: None,
            modifiers: KeyModifiers::default(),
            click_count: 0,
            kind: UiEventKind::KeyDown,
        };

        // 1. App's on_event would call into this path:
        let mutated = text_input::apply_event(&mut value, &mut sel, "ti", &arrow_right);
        assert!(mutated, "ArrowRight should mutate selection");
        assert_eq!(
            sel.within("ti").unwrap().head,
            3,
            "head moved one char right (h-e-l-l-o, byte 2 → 3)"
        );

        // 2. Next frame's set_selection sees the new value → bump.
        std::thread::sleep(std::time::Duration::from_millis(2));
        core.set_selection(sel);
        let after = core.ui_state.caret.activity_at.unwrap();
        // If a baseline existed, the new bump must be later. Either
        // way the activity is now Some, which the .unwrap() above
        // already enforced.
        if let Some(b) = baseline {
            assert!(after > b, "arrow-key flow should bump activity");
        }
    }

    #[test]
    fn set_selection_bumps_caret_activity_only_when_value_changes() {
        let mut core = lay_out_paragraph_tree();
        // First call with the default selection — no bump (mirror is
        // already default-empty).
        core.set_selection(crate::selection::Selection::default());
        assert!(
            core.ui_state.caret.activity_at.is_none(),
            "no-op set_selection should not bump activity"
        );

        // Move the selection to a real range — bump.
        let sel_a = crate::selection::Selection::caret("p1", 3);
        core.set_selection(sel_a.clone());
        let bumped_at = core
            .ui_state
            .caret
            .activity_at
            .expect("first real selection bumps");

        // Same selection again — must NOT bump (else every frame
        // re-bumps and the caret never blinks).
        core.set_selection(sel_a.clone());
        assert_eq!(
            core.ui_state.caret.activity_at,
            Some(bumped_at),
            "set_selection with same value is a no-op"
        );

        // Caret at a different byte (simulating arrow-key motion) →
        // bump again.
        std::thread::sleep(std::time::Duration::from_millis(2));
        let sel_b = crate::selection::Selection::caret("p1", 7);
        core.set_selection(sel_b);
        let new_bump = core.ui_state.caret.activity_at.expect("second bump");
        assert!(
            new_bump > bumped_at,
            "moving the caret bumps activity again",
        );
    }

    #[test]
    fn escape_clears_active_selection_and_emits_selection_changed() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cy = p1.y + p1.h * 0.5;
        // Drag-select inside p1 to establish a non-empty selection.
        core.pointer_down(p1.x + 4.0, cy, PointerButton::Primary);
        core.pointer_moved(p1.x + p1.w - 10.0, cy);
        core.pointer_up(p1.x + p1.w - 10.0, cy, PointerButton::Primary);
        assert!(!core.ui_state.current_selection.is_empty());

        let events = core.key_down(UiKey::Escape, KeyModifiers::default(), false);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![UiEventKind::Escape, UiEventKind::SelectionChanged],
            "Esc emits Escape (for popover dismiss) AND SelectionChanged"
        );
        let cleared = events
            .iter()
            .find(|e| e.kind == UiEventKind::SelectionChanged)
            .unwrap();
        assert!(cleared.selection.as_ref().unwrap().is_empty());
        assert!(core.ui_state.current_selection.is_empty());
    }

    #[test]
    fn consecutive_clicks_on_same_target_extend_count() {
        let mut core = lay_out_input_tree(false);
        let btn = core.rect_of_key("btn").expect("btn rect");
        let cx = btn.x + btn.w * 0.5;
        let cy = btn.y + btn.h * 0.5;

        // First press: count = 1.
        let down1 = core.pointer_down(cx, cy, PointerButton::Primary);
        let pd1 = down1
            .iter()
            .find(|e| e.kind == UiEventKind::PointerDown)
            .expect("PointerDown emitted");
        assert_eq!(pd1.click_count, 1, "first press starts the sequence");
        let up1 = core.pointer_up(cx, cy, PointerButton::Primary);
        let click1 = up1
            .iter()
            .find(|e| e.kind == UiEventKind::Click)
            .expect("Click emitted");
        assert_eq!(
            click1.click_count, 1,
            "Click carries the same count as its PointerDown"
        );

        // Second press immediately after, same target: count = 2.
        let down2 = core.pointer_down(cx, cy, PointerButton::Primary);
        let pd2 = down2
            .iter()
            .find(|e| e.kind == UiEventKind::PointerDown)
            .unwrap();
        assert_eq!(pd2.click_count, 2, "second press extends the sequence");
        let up2 = core.pointer_up(cx, cy, PointerButton::Primary);
        assert_eq!(
            up2.iter()
                .find(|e| e.kind == UiEventKind::Click)
                .unwrap()
                .click_count,
            2
        );

        // Third: count = 3.
        let down3 = core.pointer_down(cx, cy, PointerButton::Primary);
        let pd3 = down3
            .iter()
            .find(|e| e.kind == UiEventKind::PointerDown)
            .unwrap();
        assert_eq!(pd3.click_count, 3, "third press → triple-click");
        core.pointer_up(cx, cy, PointerButton::Primary);
    }

    #[test]
    fn click_count_resets_when_target_changes() {
        let mut core = lay_out_input_tree(false);
        let btn = core.rect_of_key("btn").expect("btn rect");
        let ti = core.rect_of_key("ti").expect("ti rect");

        // Press on btn → count=1.
        let down1 = core.pointer_down(
            btn.x + btn.w * 0.5,
            btn.y + btn.h * 0.5,
            PointerButton::Primary,
        );
        assert_eq!(
            down1
                .iter()
                .find(|e| e.kind == UiEventKind::PointerDown)
                .unwrap()
                .click_count,
            1
        );
        let _ = core.pointer_up(
            btn.x + btn.w * 0.5,
            btn.y + btn.h * 0.5,
            PointerButton::Primary,
        );

        // Press on ti (different target) → count resets to 1.
        let down2 = core.pointer_down(ti.x + ti.w * 0.5, ti.y + ti.h * 0.5, PointerButton::Primary);
        let pd2 = down2
            .iter()
            .find(|e| e.kind == UiEventKind::PointerDown)
            .unwrap();
        assert_eq!(
            pd2.click_count, 1,
            "press on a new target resets the multi-click sequence"
        );
    }

    #[test]
    fn double_click_on_selectable_text_selects_word_at_hit() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cy = p1.y + p1.h * 0.5;
        // Click near the start of "First paragraph of text." — twice
        // within the multi-click window.
        let cx = p1.x + 4.0;
        core.pointer_down(cx, cy, PointerButton::Primary);
        core.pointer_up(cx, cy, PointerButton::Primary);
        core.pointer_down(cx, cy, PointerButton::Primary);
        // The current selection should now span the first word.
        let sel = &core.ui_state.current_selection;
        let r = sel.range.as_ref().expect("selection set");
        assert_eq!(r.anchor.key, "p1");
        assert_eq!(r.head.key, "p1");
        // "First" is 5 bytes.
        assert_eq!(r.anchor.byte.min(r.head.byte), 0);
        assert_eq!(r.anchor.byte.max(r.head.byte), 5);
    }

    #[test]
    fn triple_click_on_selectable_text_selects_whole_leaf() {
        let mut core = lay_out_paragraph_tree();
        let p1 = core.rect_of_key("p1").expect("p1 rect");
        let cy = p1.y + p1.h * 0.5;
        let cx = p1.x + 4.0;
        core.pointer_down(cx, cy, PointerButton::Primary);
        core.pointer_up(cx, cy, PointerButton::Primary);
        core.pointer_down(cx, cy, PointerButton::Primary);
        core.pointer_up(cx, cy, PointerButton::Primary);
        core.pointer_down(cx, cy, PointerButton::Primary);
        let sel = &core.ui_state.current_selection;
        let r = sel.range.as_ref().expect("selection set");
        assert_eq!(r.anchor.byte, 0);
        // "First paragraph of text." is 24 bytes.
        assert_eq!(r.head.byte, 24);
    }

    #[test]
    fn click_count_resets_when_press_drifts_outside_distance_window() {
        let mut core = lay_out_input_tree(false);
        let btn = core.rect_of_key("btn").expect("btn rect");
        let cx = btn.x + btn.w * 0.5;
        let cy = btn.y + btn.h * 0.5;

        let _ = core.pointer_down(cx, cy, PointerButton::Primary);
        let _ = core.pointer_up(cx, cy, PointerButton::Primary);

        // Move 10 px (well outside MULTI_CLICK_DIST=4.0). Even if same
        // target, the second press starts a fresh sequence.
        let down2 = core.pointer_down(cx + 10.0, cy, PointerButton::Primary);
        let pd2 = down2
            .iter()
            .find(|e| e.kind == UiEventKind::PointerDown)
            .unwrap();
        assert_eq!(pd2.click_count, 1);
    }

    #[test]
    fn escape_with_no_selection_emits_only_escape() {
        let mut core = lay_out_paragraph_tree();
        assert!(core.ui_state.current_selection.is_empty());
        let events = core.key_down(UiKey::Escape, KeyModifiers::default(), false);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![UiEventKind::Escape],
            "no selection → no SelectionChanged side-effect"
        );
    }

    /// Build a 200x200 viewport hosting a `scroll([rows...])` whose
    /// content overflows so the thumb is present.
    fn lay_out_scroll_tree() -> (RunnerCore, String) {
        use crate::tree::*;
        let mut tree = crate::scroll(
            (0..6)
                .map(|i| crate::widgets::text::text(format!("row {i}")).height(Size::Fixed(50.0))),
        )
        .gap(12.0)
        .height(Size::Fixed(200.0));
        let mut core = RunnerCore::new();
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        let scroll_id = tree.computed_id.clone();
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);
        (core, scroll_id)
    }

    #[test]
    fn thumb_pointer_down_captures_drag_and_suppresses_events() {
        let (mut core, scroll_id) = lay_out_scroll_tree();
        let thumb = core
            .ui_state
            .scroll
            .thumb_rects
            .get(&scroll_id)
            .copied()
            .expect("scrollable should have a thumb");
        let event = core.pointer_down(
            thumb.x + thumb.w * 0.5,
            thumb.y + thumb.h * 0.5,
            PointerButton::Primary,
        );
        assert!(
            event.is_empty(),
            "thumb press should not emit PointerDown to the app"
        );
        let drag = core
            .ui_state
            .scroll
            .thumb_drag
            .as_ref()
            .expect("scroll.thumb_drag should be set after pointer_down on thumb");
        assert_eq!(drag.scroll_id, scroll_id);
    }

    #[test]
    fn track_click_above_thumb_pages_up_below_pages_down() {
        let (mut core, scroll_id) = lay_out_scroll_tree();
        let track = core
            .ui_state
            .scroll
            .thumb_tracks
            .get(&scroll_id)
            .copied()
            .expect("scrollable should have a track");
        let thumb = core
            .ui_state
            .scroll
            .thumb_rects
            .get(&scroll_id)
            .copied()
            .unwrap();
        let metrics = core
            .ui_state
            .scroll
            .metrics
            .get(&scroll_id)
            .copied()
            .unwrap();

        // Press in the track below the thumb at offset 0 → page down.
        let evt = core.pointer_down(
            track.x + track.w * 0.5,
            thumb.y + thumb.h + 10.0,
            PointerButton::Primary,
        );
        assert!(evt.is_empty(), "track press should not surface PointerDown");
        assert!(
            core.ui_state.scroll.thumb_drag.is_none(),
            "track click outside the thumb should not start a drag",
        );
        let after_down = core.ui_state.scroll_offset(&scroll_id);
        let expected_page = (metrics.viewport_h - SCROLL_PAGE_OVERLAP).max(0.0);
        assert!(
            (after_down - expected_page.min(metrics.max_offset)).abs() < 0.5,
            "page-down offset = {after_down} (expected ~{expected_page})",
        );
        // pointer_up after a track-page is a no-op (no drag to clear).
        let _ = core.pointer_up(0.0, 0.0, PointerButton::Primary);

        // Re-layout to refresh the thumb position at the new offset,
        // then click-to-page up.
        let mut tree = lay_out_scroll_tree_only();
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);
        let track = core
            .ui_state
            .scroll
            .thumb_tracks
            .get(&tree.computed_id)
            .copied()
            .unwrap();
        let thumb = core
            .ui_state
            .scroll
            .thumb_rects
            .get(&tree.computed_id)
            .copied()
            .unwrap();

        core.pointer_down(
            track.x + track.w * 0.5,
            thumb.y - 4.0,
            PointerButton::Primary,
        );
        let after_up = core.ui_state.scroll_offset(&tree.computed_id);
        assert!(
            after_up < after_down,
            "page-up should reduce offset: before={after_down} after={after_up}",
        );
    }

    /// Same fixture as `lay_out_scroll_tree` but doesn't build a
    /// fresh `RunnerCore` — useful when tests want to re-layout
    /// against an existing core to refresh thumb rects after a
    /// scroll offset change.
    fn lay_out_scroll_tree_only() -> El {
        use crate::tree::*;
        crate::scroll(
            (0..6)
                .map(|i| crate::widgets::text::text(format!("row {i}")).height(Size::Fixed(50.0))),
        )
        .gap(12.0)
        .height(Size::Fixed(200.0))
    }

    #[test]
    fn thumb_drag_translates_pointer_delta_into_scroll_offset() {
        let (mut core, scroll_id) = lay_out_scroll_tree();
        let thumb = core
            .ui_state
            .scroll
            .thumb_rects
            .get(&scroll_id)
            .copied()
            .unwrap();
        let metrics = core
            .ui_state
            .scroll
            .metrics
            .get(&scroll_id)
            .copied()
            .unwrap();
        let track_remaining = (metrics.viewport_h - thumb.h).max(0.0);

        let press_y = thumb.y + thumb.h * 0.5;
        core.pointer_down(thumb.x + thumb.w * 0.5, press_y, PointerButton::Primary);
        // Drag 20 px down — offset should advance by `20 * max_offset / track_remaining`.
        let evt = core.pointer_moved(thumb.x + thumb.w * 0.5, press_y + 20.0);
        assert!(
            evt.events.is_empty(),
            "thumb-drag move should suppress Drag event",
        );
        let offset = core.ui_state.scroll_offset(&scroll_id);
        let expected = 20.0 * (metrics.max_offset / track_remaining);
        assert!(
            (offset - expected).abs() < 0.5,
            "offset {offset} (expected {expected})",
        );
        // Overshooting clamps to max_offset.
        core.pointer_moved(thumb.x + thumb.w * 0.5, press_y + 9999.0);
        let offset = core.ui_state.scroll_offset(&scroll_id);
        assert!(
            (offset - metrics.max_offset).abs() < 0.5,
            "overshoot offset {offset} (expected {})",
            metrics.max_offset
        );
        // Release clears the drag without emitting events.
        let events = core.pointer_up(thumb.x, press_y, PointerButton::Primary);
        assert!(events.is_empty(), "thumb release shouldn't emit events");
        assert!(core.ui_state.scroll.thumb_drag.is_none());
    }

    #[test]
    fn secondary_click_does_not_steal_focus_or_press() {
        let mut core = lay_out_input_tree(false);
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        // Focus elsewhere first via primary click on the input.
        let ti_rect = core.rect_of_key("ti").expect("ti rect");
        let tx = ti_rect.x + ti_rect.w * 0.5;
        let ty = ti_rect.y + ti_rect.h * 0.5;
        core.pointer_down(tx, ty, PointerButton::Primary);
        let _ = core.pointer_up(tx, ty, PointerButton::Primary);
        let focused_before = core.ui_state.focused.as_ref().map(|t| t.key.clone());
        // Right-click on the button.
        core.pointer_down(cx, cy, PointerButton::Secondary);
        let events = core.pointer_up(cx, cy, PointerButton::Secondary);
        let kinds: Vec<UiEventKind> = events.iter().map(|e| e.kind).collect();
        assert_eq!(kinds, vec![UiEventKind::SecondaryClick]);
        let focused_after = core.ui_state.focused.as_ref().map(|t| t.key.clone());
        assert_eq!(
            focused_before, focused_after,
            "right-click must not steal focus"
        );
        assert!(
            core.ui_state.pressed.is_none(),
            "right-click must not set primary press"
        );
    }

    #[test]
    fn text_input_routes_to_focused_only() {
        let mut core = lay_out_input_tree(false);
        // No focus yet → no event.
        assert!(core.text_input("a".into()).is_none());
        // Focus the button via primary click.
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        core.pointer_down(cx, cy, PointerButton::Primary);
        let _ = core.pointer_up(cx, cy, PointerButton::Primary);
        let event = core.text_input("hi".into()).expect("focused → event");
        assert_eq!(event.kind, UiEventKind::TextInput);
        assert_eq!(event.text.as_deref(), Some("hi"));
        assert_eq!(event.target.as_ref().map(|t| t.key.as_str()), Some("btn"));
        // Empty text → no event (some IME paths emit empty composition).
        assert!(core.text_input(String::new()).is_none());
    }

    #[test]
    fn capture_keys_bypasses_tab_traversal_for_focused_node() {
        // Focus the capture_keys input. Tab should NOT move focus —
        // it should be delivered as a raw KeyDown to the input.
        let mut core = lay_out_input_tree(true);
        let ti_rect = core.rect_of_key("ti").expect("ti rect");
        let tx = ti_rect.x + ti_rect.w * 0.5;
        let ty = ti_rect.y + ti_rect.h * 0.5;
        core.pointer_down(tx, ty, PointerButton::Primary);
        let _ = core.pointer_up(tx, ty, PointerButton::Primary);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("ti"),
            "primary click on capture_keys node still focuses it"
        );

        let events = core.key_down(UiKey::Tab, KeyModifiers::default(), false);
        assert_eq!(events.len(), 1, "Tab → exactly one KeyDown");
        let event = &events[0];
        assert_eq!(event.kind, UiEventKind::KeyDown);
        assert_eq!(event.target.as_ref().map(|t| t.key.as_str()), Some("ti"));
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("ti"),
            "Tab inside capture_keys must NOT move focus"
        );
    }

    #[test]
    fn capture_keys_falls_back_to_default_when_focus_off_capturing_node() {
        // Tree has both a normal-focusable button and a capture_keys
        // input. Focus the button (normal focusable). Tab should then
        // do library-default focus traversal.
        let mut core = lay_out_input_tree(true);
        let btn_rect = core.rect_of_key("btn").expect("btn rect");
        let cx = btn_rect.x + btn_rect.w * 0.5;
        let cy = btn_rect.y + btn_rect.h * 0.5;
        core.pointer_down(cx, cy, PointerButton::Primary);
        let _ = core.pointer_up(cx, cy, PointerButton::Primary);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("btn"),
            "primary click focuses button"
        );
        // Tab should move focus to the next focusable (the input).
        let _ = core.key_down(UiKey::Tab, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("ti"),
            "Tab from non-capturing focused does library-default traversal"
        );
    }

    /// A column whose three buttons sit inside an `arrow_nav_siblings`
    /// parent (the shape `popover_panel` produces). Layout runs against
    /// a 200x300 viewport with 10px padding; each button is 80px wide
    /// and 36px tall stacked vertically, plenty inside the clip.
    fn lay_out_arrow_nav_tree() -> RunnerCore {
        use crate::tree::*;
        let mut tree = crate::column([
            crate::widgets::button::button("Red").key("opt-red"),
            crate::widgets::button::button("Green").key("opt-green"),
            crate::widgets::button::button("Blue").key("opt-blue"),
        ])
        .arrow_nav_siblings()
        .padding(10.0);
        let mut core = RunnerCore::new();
        crate::layout::layout(
            &mut tree,
            &mut core.ui_state,
            Rect::new(0.0, 0.0, 200.0, 300.0),
        );
        core.ui_state.sync_focus_order(&tree);
        let mut t = PrepareTimings::default();
        core.snapshot(&tree, &mut t);
        // Pre-focus the middle option (the typical state right after a
        // popover opens — we'll exercise transitions from there).
        let target = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "opt-green")
            .cloned();
        core.ui_state.set_focus(target);
        core
    }

    #[test]
    fn arrow_nav_moves_focus_among_siblings() {
        let mut core = lay_out_arrow_nav_tree();

        // ArrowDown moves to next sibling, no event emitted (it was
        // consumed by the navigation path).
        let down = core.key_down(UiKey::ArrowDown, KeyModifiers::default(), false);
        assert!(down.is_empty(), "arrow-nav consumes the key event");
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-blue"),
        );

        // ArrowUp moves back.
        core.key_down(UiKey::ArrowUp, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-green"),
        );

        // Home jumps to first.
        core.key_down(UiKey::Home, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-red"),
        );

        // End jumps to last.
        core.key_down(UiKey::End, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-blue"),
        );
    }

    #[test]
    fn arrow_nav_saturates_at_ends() {
        let mut core = lay_out_arrow_nav_tree();
        // Walk to the first option and try to go before it.
        core.key_down(UiKey::Home, KeyModifiers::default(), false);
        core.key_down(UiKey::ArrowUp, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-red"),
            "ArrowUp at top stays at top — no wrap",
        );
        // Same at the bottom.
        core.key_down(UiKey::End, KeyModifiers::default(), false);
        core.key_down(UiKey::ArrowDown, KeyModifiers::default(), false);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("opt-blue"),
            "ArrowDown at bottom stays at bottom — no wrap",
        );
    }

    /// Build a tree shaped like a real app's `build()` output: a
    /// background row with a "Trigger" button, optionally with a
    /// dropdown popover layered on top.
    fn build_popover_tree(open: bool) -> El {
        use crate::widgets::button::button;
        use crate::widgets::overlay::overlay;
        use crate::widgets::popover::{dropdown, menu_item};
        let mut layers: Vec<El> = vec![button("Trigger").key("trigger")];
        if open {
            layers.push(dropdown(
                "menu",
                "trigger",
                [
                    menu_item("A").key("item-a"),
                    menu_item("B").key("item-b"),
                    menu_item("C").key("item-c"),
                ],
            ));
        }
        overlay(layers).padding(20.0)
    }

    /// Run a full per-frame layout pass against `tree` so all the
    /// post-layout hooks (focus order sync, popover focus stack, etc.)
    /// fire just like a real frame.
    fn run_frame(core: &mut RunnerCore, tree: &mut El) {
        let mut t = PrepareTimings::default();
        core.prepare_layout(tree, Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, &mut t);
        core.snapshot(tree, &mut t);
    }

    #[test]
    fn popover_open_pushes_focus_and_auto_focuses_first_item() {
        let mut core = RunnerCore::new();
        let mut closed = build_popover_tree(false);
        run_frame(&mut core, &mut closed);
        // Pre-focus the trigger as if the user tabbed to it before
        // opening the menu.
        let trigger = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "trigger")
            .cloned();
        core.ui_state.set_focus(trigger);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("trigger"),
        );

        // Open the popover. The runtime should snapshot the trigger
        // onto the focus stack and auto-focus the first menu item.
        let mut open = build_popover_tree(true);
        run_frame(&mut core, &mut open);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("item-a"),
            "popover open should auto-focus the first menu item",
        );
        assert_eq!(
            core.ui_state.popover_focus.focus_stack.len(),
            1,
            "trigger should be saved on the focus stack",
        );
        assert_eq!(
            core.ui_state.popover_focus.focus_stack[0].key.as_str(),
            "trigger",
            "saved focus should be the pre-open target",
        );
    }

    #[test]
    fn popover_close_restores_focus_to_trigger() {
        let mut core = RunnerCore::new();
        let mut closed = build_popover_tree(false);
        run_frame(&mut core, &mut closed);
        let trigger = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "trigger")
            .cloned();
        core.ui_state.set_focus(trigger);

        // Open → focus walks to the menu.
        let mut open = build_popover_tree(true);
        run_frame(&mut core, &mut open);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("item-a"),
        );

        // Close → focus restored to trigger, stack drained.
        let mut closed_again = build_popover_tree(false);
        run_frame(&mut core, &mut closed_again);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("trigger"),
            "closing the popover should pop the saved focus",
        );
        assert!(
            core.ui_state.popover_focus.focus_stack.is_empty(),
            "focus stack should be drained after restore",
        );
    }

    #[test]
    fn popover_close_does_not_override_intentional_focus_move() {
        let mut core = RunnerCore::new();
        // Tree with a second focusable button outside the popover so
        // the user can "click somewhere else" while the menu is open.
        let build = |open: bool| -> El {
            use crate::widgets::button::button;
            use crate::widgets::overlay::overlay;
            use crate::widgets::popover::{dropdown, menu_item};
            let main = crate::row([
                button("Trigger").key("trigger"),
                button("Other").key("other"),
            ]);
            let mut layers: Vec<El> = vec![main];
            if open {
                layers.push(dropdown("menu", "trigger", [menu_item("A").key("item-a")]));
            }
            overlay(layers).padding(20.0)
        };

        let mut closed = build(false);
        run_frame(&mut core, &mut closed);
        let trigger = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "trigger")
            .cloned();
        core.ui_state.set_focus(trigger);

        let mut open = build(true);
        run_frame(&mut core, &mut open);
        assert_eq!(core.ui_state.popover_focus.focus_stack.len(), 1);

        // Simulate an intentional focus move to a sibling that is
        // outside the popover (e.g. the user re-tabbed somewhere). Do
        // this by setting focus directly while the popover is still in
        // the tree — the existing focus-order contains "other".
        let other = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "other")
            .cloned();
        core.ui_state.set_focus(other);

        let mut closed_again = build(false);
        run_frame(&mut core, &mut closed_again);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("other"),
            "focus moved before close should not be overridden by restore",
        );
        assert!(core.ui_state.popover_focus.focus_stack.is_empty());
    }

    #[test]
    fn nested_popovers_stack_and_unwind_focus_correctly() {
        let mut core = RunnerCore::new();
        // Two siblings layered at El root: an outer popover anchored to
        // the trigger, and an inner popover anchored to a button inside
        // the outer panel. Both are real popovers — separate
        // popover_layer ids — so the runtime sees them stack.
        let build = |outer: bool, inner: bool| -> El {
            use crate::widgets::button::button;
            use crate::widgets::overlay::overlay;
            use crate::widgets::popover::{Anchor, popover, popover_panel};
            let main = button("Trigger").key("trigger");
            let mut layers: Vec<El> = vec![main];
            if outer {
                layers.push(popover(
                    "outer",
                    Anchor::below_key("trigger"),
                    popover_panel([button("Open inner").key("inner-trigger")]),
                ));
            }
            if inner {
                layers.push(popover(
                    "inner",
                    Anchor::below_key("inner-trigger"),
                    popover_panel([button("X").key("inner-a"), button("Y").key("inner-b")]),
                ));
            }
            overlay(layers).padding(20.0)
        };

        // Frame 1: nothing open, focus on the trigger.
        let mut closed = build(false, false);
        run_frame(&mut core, &mut closed);
        let trigger = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "trigger")
            .cloned();
        core.ui_state.set_focus(trigger);

        // Frame 2: outer opens. Save trigger, focus inner-trigger.
        let mut outer = build(true, false);
        run_frame(&mut core, &mut outer);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("inner-trigger"),
        );
        assert_eq!(core.ui_state.popover_focus.focus_stack.len(), 1);

        // Frame 3: inner also opens. Save inner-trigger, focus inner-a.
        let mut both = build(true, true);
        run_frame(&mut core, &mut both);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("inner-a"),
        );
        assert_eq!(core.ui_state.popover_focus.focus_stack.len(), 2);

        // Frame 4: inner closes. Pop → restore inner-trigger.
        let mut outer_only = build(true, false);
        run_frame(&mut core, &mut outer_only);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("inner-trigger"),
        );
        assert_eq!(core.ui_state.popover_focus.focus_stack.len(), 1);

        // Frame 5: outer closes. Pop → restore trigger.
        let mut none = build(false, false);
        run_frame(&mut core, &mut none);
        assert_eq!(
            core.ui_state.focused.as_ref().map(|t| t.key.as_str()),
            Some("trigger"),
        );
        assert!(core.ui_state.popover_focus.focus_stack.is_empty());
    }

    #[test]
    fn arrow_nav_does_not_intercept_outside_navigable_groups() {
        // Reuse the input tree (no arrow_nav_siblings parent). Arrow
        // keys must produce a regular `KeyDown` event so a
        // capture_keys widget can interpret them as caret motion.
        let mut core = lay_out_input_tree(false);
        let target = core
            .ui_state
            .focus
            .order
            .iter()
            .find(|t| t.key == "btn")
            .cloned();
        core.ui_state.set_focus(target);
        let events = core.key_down(UiKey::ArrowDown, KeyModifiers::default(), false);
        assert_eq!(
            events.len(),
            1,
            "ArrowDown without navigable parent → event"
        );
        assert_eq!(events[0].kind, UiEventKind::KeyDown);
    }

    fn quad(shader: ShaderHandle) -> DrawOp {
        DrawOp::Quad {
            id: "q".into(),
            rect: Rect::new(0.0, 0.0, 10.0, 10.0),
            scissor: None,
            shader,
            uniforms: UniformBlock::new(),
        }
    }

    #[test]
    fn samples_backdrop_inserts_snapshot_before_first_glass_quad() {
        let mut core = RunnerCore::new();
        core.set_surface_size(100, 100);
        let ops = vec![
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
            quad(ShaderHandle::Custom("liquid_glass")),
            quad(ShaderHandle::Custom("liquid_glass")),
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
        ];
        let mut timings = PrepareTimings::default();
        core.prepare_paint(
            &ops,
            |_| true,
            |s| matches!(s, ShaderHandle::Custom(name) if *name == "liquid_glass"),
            &mut NoText,
            1.0,
            &mut timings,
        );

        let kinds: Vec<&'static str> = core
            .paint_items
            .iter()
            .map(|p| match p {
                PaintItem::QuadRun(_) => "Q",
                PaintItem::IconRun(_) => "I",
                PaintItem::Text(_) => "T",
                PaintItem::Image(_) => "M",
                PaintItem::BackdropSnapshot => "S",
            })
            .collect();
        assert_eq!(
            kinds,
            vec!["Q", "S", "Q", "Q"],
            "expected one stock run, snapshot, then a glass run, then a foreground stock run"
        );
    }

    #[test]
    fn no_snapshot_when_no_glass_drawn() {
        let mut core = RunnerCore::new();
        core.set_surface_size(100, 100);
        let ops = vec![
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
        ];
        let mut timings = PrepareTimings::default();
        core.prepare_paint(&ops, |_| true, |_| false, &mut NoText, 1.0, &mut timings);
        assert!(
            !core
                .paint_items
                .iter()
                .any(|p| matches!(p, PaintItem::BackdropSnapshot)),
            "no glass shader registered → no snapshot"
        );
    }

    #[test]
    fn at_most_one_snapshot_per_frame() {
        let mut core = RunnerCore::new();
        core.set_surface_size(100, 100);
        let ops = vec![
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
            quad(ShaderHandle::Custom("g")),
            quad(ShaderHandle::Stock(StockShader::RoundedRect)),
            quad(ShaderHandle::Custom("g")),
        ];
        let mut timings = PrepareTimings::default();
        core.prepare_paint(
            &ops,
            |_| true,
            |s| matches!(s, ShaderHandle::Custom("g")),
            &mut NoText,
            1.0,
            &mut timings,
        );
        let snapshots = core
            .paint_items
            .iter()
            .filter(|p| matches!(p, PaintItem::BackdropSnapshot))
            .count();
        assert_eq!(snapshots, 1, "backdrop depth is capped at 1");
    }
}