damascene-core 0.6.0

Damascene — 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
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
//! Flex-style layout pass over the [`El`] tree.
//!
//! Sizing per axis:
//! - `Fixed(px)` — exact size on its axis.
//! - `Hug` — intrinsic size (text width, sum of children, etc.). Default.
//! - `Fill(weight)` — share leftover main-axis space proportionally.
//!
//! Defaults match CSS flex's `flex: 0 1 auto`: children content-size
//! on the main axis, defer to the parent's [`Align`] on the cross
//! axis. `Align::Stretch` (the column / scroll default) stretches both
//! `Hug` and `Fill` children to the container's full cross extent —
//! the analog of CSS `align-items: stretch`. `Align::Center | Start |
//! End` shrinks them to intrinsic so the alignment can actually
//! position them — matching CSS's behavior when align-items is
//! non-stretch. Main-axis distribution is governed by [`Justify`] (or
//! insert a [`spacer`]).
//!
//! The layout pass also assigns each node a stable path-based
//! [`El::computed_id`]: `root.0.card[account].2.button` — a node's ID is
//! parent-id + dot + role-or-key + sibling-index. IDs survive minor
//! refactors and are usable as patch / lint / draw-op targets.
//!
//! Rects do not live on `El` — the layout pass writes them to
//! `UiState`'s computed-rect side map, keyed by `computed_id`. The
//! container rect flows down the recursion as a parameter; child rects
//! are computed per-axis and inserted into the side map. Scroll offsets
//! likewise read/write `UiState`'s scroll-offset side map directly.
//!
//! Text intrinsic measurement uses bundled-font glyph advances via
//! [`crate::text::metrics`]. Full shaping still belongs to the renderer
//! for now; this keeps layout/lint/SVG close enough to glyphon output
//! without committing to the final text stack.

// Lock in full per-item documentation for this module (issue #73).
#![warn(missing_docs)]

use std::cell::RefCell;
use std::sync::Arc;

use rustc_hash::FxHashSet;

use crate::scroll::{ScrollAlignment, ScrollRequest};
use crate::state::dyn_height::DynHeightIndex;
use crate::state::{ScrollAnchor, UiState, VirtualAnchor};
use crate::text::metrics as text_metrics;
use crate::tree::*;

/// Second escape hatch: author-supplied layout function.
///
/// When set on a node via [`El::layout`], the layout pass calls this
/// function instead of running the column/row/overlay distribution for
/// that node's direct children. The function returns one [`Rect`] per
/// child (in source order), positioned anywhere inside the container.
/// The library still recurses into each child (so descendants lay out
/// normally) and still drives hit-test, focus, animation, scroll —
/// those all read from `UiState`'s computed-rect side map, which receives the
/// rects this function produces.
///
/// Authors typically write a free `fn(LayoutCtx) -> Vec<Rect>` and
/// pass it directly: `column(children).layout(my_layout)`.
///
/// ## What you get
///
/// - [`LayoutCtx::container`] — the rect available for placement
///   (parent rect minus this node's padding).
/// - [`LayoutCtx::children`] — read-only slice of the node's children;
///   index here matches the index in your returned `Vec<Rect>`.
/// - [`LayoutCtx::measure`] — call to get a child's intrinsic
///   `(width, height)` if you need it for sizing decisions.
///
/// ## Scope limits (will panic)
///
/// - The custom-layout node itself must size with [`Size::Fixed`] or
///   [`Size::Fill`] on both axes. `Size::Hug` would require a separate
///   intrinsic callback and is not yet supported.
/// - The returned `Vec<Rect>` length must equal `children.len()`.
#[derive(Clone)]
pub struct LayoutFn(pub Arc<dyn Fn(LayoutCtx) -> Vec<Rect> + Send + Sync>);

impl LayoutFn {
    /// Wrap a closure as a [`LayoutFn`]. Equivalent to passing a free
    /// `fn` directly to [`El::layout`].
    pub fn new<F>(f: F) -> Self
    where
        F: Fn(LayoutCtx) -> Vec<Rect> + Send + Sync + 'static,
    {
        LayoutFn(Arc::new(f))
    }
}

impl std::fmt::Debug for LayoutFn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("LayoutFn(<fn>)")
    }
}

/// Sizing-pass counters. The per-frame intrinsic-measurement *cache*
/// is gone — the sizing pass visits each node exactly once, so there
/// is nothing left to cache — but the counter type and
/// [`take_intrinsic_cache_stats`] survive so host diagnostics keep
/// their shape: `misses` now counts sizing-pass node visits (expect
/// ≈ the tree's node count, once per frame) and `hits` is always 0.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayoutIntrinsicCacheStats {
    /// Always 0 — retained for diagnostic-field compatibility.
    pub hits: u64,
    /// Nodes visited by the sizing pass (one visit per node per frame).
    pub misses: u64,
}

/// Counters for the scroll-layout prune optimization, which skips
/// recursing into scroll-container children that lie far outside the
/// visible range. Recorded during each layout pass; retrieve the latest
/// pass's numbers with [`take_prune_stats`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayoutPruneStats {
    /// Off-screen child subtrees whose recursion was skipped.
    pub subtrees: u64,
    /// Total descendant nodes inside those skipped subtrees.
    pub nodes: u64,
}

thread_local! {
    /// Sizing-pass visit counter for the layout pass currently running
    /// on this thread; drained into `LAST_SIZING_STATS` at the end of
    /// `layout_post_assign` and read back via
    /// [`take_intrinsic_cache_stats`].
    static SIZING_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    static LAST_SIZING_STATS: RefCell<LayoutIntrinsicCacheStats> =
        const { RefCell::new(LayoutIntrinsicCacheStats { hits: 0, misses: 0 }) };
    static PRUNE_STATS: RefCell<LayoutPruneStats> =
        const { RefCell::new(LayoutPruneStats { subtrees: 0, nodes: 0 }) };
    static LAST_PRUNE_STATS: RefCell<LayoutPruneStats> =
        const { RefCell::new(LayoutPruneStats { subtrees: 0, nodes: 0 }) };
}

/// Take (and reset) the sizing-pass stats recorded by this thread's
/// most recent layout pass. The runtime drains this once per frame into
/// its timing diagnostics. (Name kept from the retired per-frame
/// intrinsic cache; see [`LayoutIntrinsicCacheStats`].)
pub fn take_intrinsic_cache_stats() -> LayoutIntrinsicCacheStats {
    LAST_SIZING_STATS.with(|stats| std::mem::take(&mut *stats.borrow_mut()))
}

/// Take (and reset) the scroll-prune stats recorded by this thread's
/// most recent layout pass. The runtime drains this once per frame into
/// its timing diagnostics.
pub fn take_prune_stats() -> LayoutPruneStats {
    LAST_PRUNE_STATS.with(|stats| std::mem::take(&mut *stats.borrow_mut()))
}

/// Virtualized list state attached to a [`Kind::VirtualList`] node.
/// Holds the row count, the row-height policy, and the closure that
/// realizes a row by global index. Set via [`crate::virtual_list`] or
/// [`crate::virtual_list_dyn`]; the layout pass calls `build_row(i)`
/// only for indices whose rect intersects the viewport.
///
/// ## Row-height policies
///
/// - [`VirtualMode::Fixed`] — every row is the same logical-pixel
///   height. Scroll → visible-range is O(1).
/// - [`VirtualMode::Dynamic`] — rows vary in height. The library uses
///   `estimated_row_height` as a placeholder for unmeasured rows,
///   measures visible rows at the current layout width, and preserves a
///   row anchor on screen while estimates become measurements.
///
/// ## Other current scope
///
/// - **Vertical only** — feed/chat-log-shaped lists are the target.
///   A horizontal variant can come later.
/// - **No row pooling** — visible rows are rebuilt from scratch each
///   layout pass. Fine for thousands of items; if it bottlenecks we
///   add a pool keyed by stable row keys.
#[derive(Clone, Debug)]
pub enum VirtualMode {
    /// Every row is exactly `row_height` logical pixels tall.
    Fixed {
        /// Uniform row height in logical pixels. Must be > 0.
        row_height: f32,
    },
    /// Rows have variable heights. `estimated_row_height` seeds the
    /// content-height total and the visible-range walk for rows that
    /// haven't been measured yet.
    Dynamic {
        /// Placeholder height (logical pixels) for not-yet-measured
        /// rows. Must be > 0.
        estimated_row_height: f32,
        /// Opt-in contract: across frames the row sequence changes
        /// **only** by appending rows at the tail and/or dropping a
        /// contiguous prefix at the head (an append-at-bottom feed or a
        /// capped ring buffer). When set, layout maintains an
        /// incremental per-row height index so the per-frame cost is
        /// O(visible) instead of several O(n) walks — the difference
        /// that lets a 100k-row chat log stay inside frame budget while
        /// scrolling (issue #107). Reordering, mid-list insertion, or
        /// re-keying a surviving row violates the contract: debug builds
        /// assert, release self-heals with a one-frame O(n) rebuild.
        /// Set via [`VirtualItems::append_only`] /
        /// [`crate::tree::El::append_only`].
        append_only: bool,
    },
}

/// Policy used to pick the next dynamic virtual-list anchor after each
/// layout pass. The previous anchor solves the current frame; this
/// policy rebases the next frame onto a coherent in-viewport row point.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VirtualAnchorPolicy {
    /// Pick the row point nearest `y_fraction` through the viewport.
    /// `0.0` is the top, `1.0` is the bottom. Good default for feeds.
    ViewportFraction {
        /// Fraction of the viewport height (clamped to `0.0..=1.0`)
        /// where the anchor point is sampled.
        y_fraction: f32,
    },
    /// Prefer the first fully visible row; fall back to the first
    /// partially visible row.
    FirstVisible,
    /// Prefer the last fully visible row; fall back to the last
    /// partially visible row.
    LastVisible,
}

impl Default for VirtualAnchorPolicy {
    fn default() -> Self {
        Self::ViewportFraction { y_fraction: 0.25 }
    }
}

/// Virtualized list state attached to a [`Kind::VirtualList`] node:
/// row count, row-height policy, and the closures that identify and
/// realize rows. Built via [`Self::new`] / [`Self::new_dyn`] or,
/// more commonly, the [`crate::virtual_list`] /
/// [`crate::virtual_list_dyn`] builders. See [`VirtualMode`] for the
/// scope and policy discussion.
#[derive(Clone)]
#[non_exhaustive]
pub struct VirtualItems {
    /// Total number of rows in the list (realized or not).
    pub count: usize,
    /// Row-height policy — see [`VirtualMode`].
    pub mode: VirtualMode,
    /// How the next frame's scroll anchor is chosen after each layout
    /// pass (dynamic mode only).
    pub anchor_policy: VirtualAnchorPolicy,
    /// Stable identity for a row by global index. Keys measured heights
    /// and [`ScrollRequest::ToRowKey`] targets across reorders /
    /// insertions; defaults to the index itself in fixed mode.
    pub row_key: Arc<dyn Fn(usize) -> String + Send + Sync>,
    /// Realize the row at a global index. Called only for rows whose
    /// rect intersects the viewport.
    pub build_row: Arc<dyn Fn(usize) -> El + Send + Sync>,
}

impl VirtualItems {
    /// Fixed-height list: every row is `row_height` logical pixels.
    /// Row keys default to the stringified index. Panics if
    /// `row_height <= 0.0`. Prefer the [`crate::virtual_list`] builder.
    pub fn new<F>(count: usize, row_height: f32, build_row: F) -> Self
    where
        F: Fn(usize) -> El + Send + Sync + 'static,
    {
        assert!(
            row_height > 0.0,
            "VirtualItems::new requires row_height > 0.0 (got {row_height})"
        );
        VirtualItems {
            count,
            mode: VirtualMode::Fixed { row_height },
            anchor_policy: VirtualAnchorPolicy::default(),
            row_key: Arc::new(|i| i.to_string()),
            build_row: Arc::new(build_row),
        }
    }

    /// Variable-height list: rows start at `estimated_row_height`
    /// logical pixels and are replaced by real measurements as they
    /// become visible. `row_key` must give each row a stable identity.
    /// Panics if `estimated_row_height <= 0.0`. Prefer the
    /// [`crate::virtual_list_dyn`] builder.
    pub fn new_dyn<K, F>(count: usize, estimated_row_height: f32, row_key: K, build_row: F) -> Self
    where
        K: Fn(usize) -> String + Send + Sync + 'static,
        F: Fn(usize) -> El + Send + Sync + 'static,
    {
        assert!(
            estimated_row_height > 0.0,
            "VirtualItems::new_dyn requires estimated_row_height > 0.0 (got {estimated_row_height})"
        );
        VirtualItems {
            count,
            mode: VirtualMode::Dynamic {
                estimated_row_height,
                append_only: false,
            },
            anchor_policy: VirtualAnchorPolicy::default(),
            row_key: Arc::new(row_key),
            build_row: Arc::new(build_row),
        }
    }

    /// Declare the append-only contract on a dynamic list — see
    /// [`VirtualMode::Dynamic::append_only`]. No-op (and harmless) on a
    /// fixed list, whose range math is already O(1).
    pub fn append_only(mut self) -> Self {
        if let VirtualMode::Dynamic {
            ref mut append_only,
            ..
        } = self.mode
        {
            *append_only = true;
        }
        self
    }

    /// Replace the default anchor policy
    /// ([`VirtualAnchorPolicy::ViewportFraction`] at 0.25).
    pub fn anchor_policy(mut self, policy: VirtualAnchorPolicy) -> Self {
        self.anchor_policy = policy;
        self
    }
}

impl std::fmt::Debug for VirtualItems {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VirtualItems")
            .field("count", &self.count)
            .field("mode", &self.mode)
            .field("anchor_policy", &self.anchor_policy)
            .field("row_key", &"<fn>")
            .field("build_row", &"<fn>")
            .finish()
    }
}

/// Context handed to a [`LayoutFn`]. Marked `#[non_exhaustive]` so
/// future fields (intrinsic-at-width, scroll context, …) can be added
/// without breaking author code that currently reads `container` /
/// `children` / `measure`.
#[non_exhaustive]
pub struct LayoutCtx<'a> {
    /// Inner rect of the parent (after padding) — the area available
    /// for child placement. Children may be positioned anywhere; the
    /// library does not clamp returned rects to this region.
    pub container: Rect,
    /// Direct children of the node, in source order. Read-only — return
    /// positions through your `Vec<Rect>`.
    pub children: &'a [El],
    /// Intrinsic `(width, height)` for any child. Wrapped text returns
    /// its unwrapped width here; if you need width-dependent wrapping
    /// you'll need to size the child with `Fixed` / `Fill` instead.
    pub measure: &'a dyn Fn(&El) -> (f32, f32),
    /// Look up any keyed node's laid-out rect. Returns `None` when the
    /// key is absent from the tree, when the node hasn't been laid out
    /// yet (siblings later in source order), or when the key was used
    /// on a node without a recorded rect. Used by widgets like
    /// [`crate::widgets::popover::popover`] to position children
    /// relative to elements outside their own subtree.
    pub rect_of_key: &'a dyn Fn(&str) -> Option<Rect>,
    /// Look up a **keyed** node's laid-out rect by its `computed_id`
    /// (the root resolves too, via `"root"`). Same semantics as
    /// [`Self::rect_of_key`] but skips the `key → computed_id`
    /// translation — useful for runtime-synthesized layers (tooltips,
    /// focus rings) that anchor to a node the library already knows by
    /// id; those anchors are always keyed (hover / focus targets
    /// require keys). Unkeyed nodes have no id-indexed entry — their
    /// rects live only on the nodes themselves
    /// ([`crate::tree::El::computed_rect`]).
    pub rect_of_id: &'a dyn Fn(&str) -> Option<Rect>,
}

/// Lay out the whole tree into the given viewport rect. Assigns
/// `computed_id`s, rebuilds the key index, and runs the layout walk.
///
/// Hosts that drive their own pipeline (the Damascene runtime does this in
/// [`crate::runtime::RunnerCore::prepare_layout`]) typically call
/// [`assign_ids`] before synthesizing floating layers (tooltips,
/// toasts), then route the laid-out call through
/// [`layout_post_assign`] so the id walk doesn't run twice per frame.
pub fn layout(root: &mut El, ui_state: &mut UiState, viewport: Rect) {
    {
        crate::profile_span!("layout::assign_ids");
        assign_ids(root);
    }
    layout_post_assign(root, ui_state, viewport);
}

/// Like [`layout`], but skips the recursive `assign_id` walk. Callers
/// are responsible for ensuring every node's `computed_id` is already
/// set — typically by invoking [`assign_ids`] earlier in the pipeline,
/// then having any per-frame floating-layer synthesis pass call
/// [`assign_id_appended`] on its newly pushed layer.
pub fn layout_post_assign(root: &mut El, ui_state: &mut UiState, viewport: Rect) {
    SIZING_VISITS.with(|c| c.set(0));
    PRUNE_STATS.with(|s| *s.borrow_mut() = LayoutPruneStats::default());
    {
        crate::profile_span!("layout::root_setup");
        root.computed_rect = viewport;
        // The root always gets a keyed-map entry (whether or not it
        // carries a key): custom layouts anchor to it via
        // `rect_of_id("root")` (toast layer, diagnostics overlay).
        ui_state
            .layout
            .keyed_rects
            .insert(root.computed_id.clone(), viewport);
        rebuild_key_index(root, ui_state);
        // Per-scrollable scratch is rebuilt every layout — entries for
        // scrollables that disappeared mid-frame must not leave stale
        // thumb rects behind for hit-test or paint to find.
        ui_state.scroll.metrics.clear();
        ui_state.scroll.thumb_rects.clear();
        ui_state.scroll.thumb_tracks.clear();
        ui_state.scroll.visible_ranges.clear();
        ui_state.resize.bands.clear();
        // Same for per-viewport gesture metrics (issue #129): every
        // live viewport re-inserts in `apply_viewport_transform`, so
        // anything left over is an unmounted (or pruned-offscreen)
        // viewport whose stale inner rect would keep claiming wheel /
        // pan gestures at its old screen position. The persistent
        // pan/zoom lives in `viewport.views` (LRU), not here.
        ui_state.viewport.metrics.clear();
        // One fused pre-walk (traversal count dominates on large
        // trees): rewrite `.user_resizable()` panes' user-dragged
        // sizes to ordinary `Fixed`, and resolve `Size::Ch(n)`
        // (the CSS `ch` unit) to `Fixed(n · digit-advance)`
        // against each node's own font — so every downstream
        // sizing path sees plain `Fixed` values.
        apply_size_rewrites(root, ui_state, None);
    }
    {
        // The single sizing recursion: every node's measured size at
        // the available width its tree position implies, stored
        // in-node. Placement below never re-measures — the per-frame
        // intrinsic cache this replaced existed only because the old
        // place walk re-entered the measure recursion from every
        // ancestor level at shifting widths.
        crate::profile_span!("layout::size");
        size_tree(root, Some(viewport.w));
    }
    {
        crate::profile_span!("layout::children");
        layout_children(root, viewport, ui_state);
    }
    // Band geometry needs final rects, so it runs as a post-pass.
    publish_resize_bands(root, ui_state);
    LAST_SIZING_STATS.with(|s| {
        *s.borrow_mut() = LayoutIntrinsicCacheStats {
            hits: 0,
            misses: SIZING_VISITS.with(|c| c.get()),
        };
    });
    LAST_PRUNE_STATS.with(|last| *last.borrow_mut() = PRUNE_STATS.with(|s| *s.borrow()));
}

/// Drag clamp for a `.user_resizable()` pane along its parent's
/// `axis`, from the pane's CSS-shaped min/max fields. Missing bounds
/// fall back to `[0, ∞)`; a min above max resolves to the lower bound,
/// matching the documented `min_width`/`max_width` conflict rule.
fn resize_clamp(child: &El, axis: Axis) -> (f32, f32) {
    let (min, max) = match axis {
        Axis::Column => (child.min_height, child.max_height),
        _ => (child.min_width, child.max_width),
    };
    let min = min.unwrap_or(0.0).max(0.0);
    (min, max.unwrap_or(f32::INFINITY).max(min))
}

/// Pre-pass for `.user_resizable()` panes (issue #106): where the user
/// has dragged a size, rewrite the pane's declared main-axis size to
/// `Fixed(override)` — clamped to the pane's min/max — before the
/// layout walk. The declared size remains the default until the first
/// drag writes an override.
/// Fused pre-layout size rewrites — resize overrides + `ch` units in
/// one traversal. `parent_axis` is `None` at the root (the root pane
/// is never user-resized; only children along a parent's axis are).
fn apply_size_rewrites(node: &mut El, ui_state: &UiState, parent_axis: Option<Axis>) {
    if node.user_resizable
        && let Some(axis) = parent_axis
        && !matches!(axis, Axis::Overlay)
    {
        let id = node.key.as_deref().unwrap_or(&node.computed_id);
        if let Some(&px) = ui_state.resize.overrides.get(id) {
            let (min, max) = resize_clamp(node, axis);
            let px = px.clamp(min, max);
            match axis {
                Axis::Column => node.height = Size::Fixed(px),
                _ => node.width = Size::Fixed(px),
            }
        }
    }
    if let Size::Ch(n) = node.width {
        node.width = Size::Fixed((n * ch_unit(node)).max(0.0));
    }
    if let Size::Ch(n) = node.height {
        node.height = Size::Fixed((n * ch_unit(node)).max(0.0));
    }
    let axis = node.axis;
    for child in &mut node.children {
        apply_size_rewrites(child, ui_state, Some(axis));
    }
}

/// The node's `0`-digit advance in its own resolved font — the CSS `ch`
/// length. Uses the node's tabular-numerals setting so a reserved field
/// (`.tabular_numerals().width(Size::Ch(n))`) is sized to the actual digit
/// slot. Cheap: the text-metrics layout cache keys on these inputs.
fn ch_unit(node: &El) -> f32 {
    text_metrics::layout_text_with_family(
        "0",
        node.font_size,
        node.font_family,
        node.font_weight,
        node.font_mono,
        node.text_tabular_numerals,
        TextWrap::NoWrap,
        None,
    )
    .width
    .max(0.0)
}

/// Post-pass for `.user_resizable()` panes: publish each pane's grab
/// band — an invisible [`crate::state::resize::RESIZE_BAND_THICKNESS`]
/// strip straddling the pane's seam edge — into
/// `ui_state.resize.bands` for the runtime's pointer pre-emption and
/// cursor resolution. The band sits on the trailing edge along the
/// parent's axis when a sibling follows, and on the leading edge when
/// the pane is the last child (a right- or bottom-anchored pane).
fn publish_resize_bands(node: &El, ui_state: &mut UiState) {
    use crate::state::resize::{RESIZE_BAND_THICKNESS as T, ResizeBand};
    let axis = node.axis;
    if !matches!(axis, Axis::Overlay) && node.children.iter().any(|c| c.user_resizable) {
        let parent_rect = node.computed_rect;
        let inner_main = match axis {
            Axis::Column => parent_rect.h - node.padding.top - node.padding.bottom,
            _ => parent_rect.w - node.padding.left - node.padding.right,
        };
        let count = node.children.len();
        for (idx, child) in node.children.iter().enumerate() {
            if !child.user_resizable {
                continue;
            }
            let rect = child.computed_rect;
            // Trailing edge when a sibling follows (or the pane is
            // alone); leading edge for a last child with siblings
            // before it.
            let trailing = idx + 1 < count || count == 1;
            let band = match (axis, trailing) {
                (Axis::Column, true) => Rect::new(rect.x, rect.y + rect.h - T / 2.0, rect.w, T),
                (Axis::Column, false) => Rect::new(rect.x, rect.y - T / 2.0, rect.w, T),
                (_, true) => Rect::new(rect.x + rect.w - T / 2.0, rect.y, T, rect.h),
                (_, false) => Rect::new(rect.x - T / 2.0, rect.y, T, rect.h),
            };
            let (min, max) = resize_clamp(child, axis);
            // The seam must stay inside the parent: cap the drag at
            // the parent's inner extent so the band can't be pushed
            // out of reach.
            let max = max.min(inner_main.max(min));
            ui_state.resize.bands.push(ResizeBand {
                id: child
                    .key
                    .clone()
                    .unwrap_or_else(|| child.computed_id.to_string()),
                key: child.key.clone(),
                container_id: node.computed_id.to_string(),
                band,
                axis,
                sign: if trailing { 1.0 } else { -1.0 },
                current: match axis {
                    Axis::Column => rect.h,
                    _ => rect.w,
                },
                min,
                max,
            });
        }
    }
    for child in &node.children {
        publish_resize_bands(child, ui_state);
    }
}

/// Assign `computed_id`s to a child that was just appended to an
/// already-id-assigned `parent`. Companion to [`layout_post_assign`]:
/// floating-layer synthesis (tooltip, toast) pushes one new child onto
/// the root and uses this to give the new subtree the same path-style
/// ids the recursive `assign_id` would have, without re-walking the
/// rest of the tree.
pub fn assign_id_appended(parent_id: &str, child: &mut El, child_index: usize) {
    let mut path = String::with_capacity(parent_id.len() + 24);
    path.push_str(parent_id);
    push_id_suffix(&mut path, child, child_index);
    assign_id(child, &mut path);
}

/// Walk the tree once and refresh `ui_state.layout.key_index` so
/// `LayoutCtx::rect_of_key` can resolve `key → computed_id` without
/// re-scanning the tree per lookup. First key wins — duplicate keys
/// are an author bug, but we don't want to crash layout over it.
fn rebuild_key_index(root: &El, ui_state: &mut UiState) {
    ui_state.layout.key_index.clear();
    // Count computed_ids in the same walk so the duplicate-id check
    // (issue #64) costs no extra traversal. Two same-role siblings
    // sharing a key collide on computed_id (`assign_id` produces
    // `parent.role[key]` for both) — the second then overwrites the
    // first's keyed-rect entry (both resolve `rect_of_key` to one
    // rect) and the intrinsic cache returns one sibling's measurement
    // for the other. The failure is silent and non-local.
    let mut id_counts: rustc_hash::FxHashMap<&str, u32> = Default::default();
    fn visit<'a>(
        node: &'a El,
        index: &mut rustc_hash::FxHashMap<String, std::sync::Arc<str>>,
        id_counts: &mut rustc_hash::FxHashMap<&'a str, u32>,
    ) {
        if let Some(key) = &node.key {
            index
                .entry(key.clone())
                .or_insert_with(|| node.computed_id.clone());
        }
        *id_counts.entry(node.computed_id.as_ref()).or_insert(0) += 1;
        for c in &node.children {
            visit(c, index, id_counts);
        }
    }
    visit(root, &mut ui_state.layout.key_index, &mut id_counts);
    warn_duplicate_ids(&id_counts, &mut ui_state.layout.warned_duplicate_ids);
}

/// Emit a once-per-id warning for every colliding `computed_id`. The
/// bundle lint already catches this as [`crate::bundle::lint::
/// FindingKind::DuplicateId`], but runtime-only apps never run it — so
/// this reuses the same finding vocabulary at log-warn level. Deduped
/// via the persistent `warned` set so a standing duplicate warns once,
/// not every layout (issue #64).
fn warn_duplicate_ids(
    id_counts: &rustc_hash::FxHashMap<&str, u32>,
    warned: &mut rustc_hash::FxHashSet<String>,
) {
    for (&id, &n) in id_counts {
        if n > 1 && warned.insert(id.to_string()) {
            log::warn!(
                "DuplicateId: {n} nodes share id {id} — duplicate sibling key; \
                 their rects and intrinsic-cache entries collide silently (issue #64)"
            );
        }
    }
}

/// Assign every node's `computed_id` without positioning anything else.
/// Useful when callers need to read or seed side-map entries (e.g.,
/// scroll offsets) before `layout` runs.
pub fn assign_ids(root: &mut El) {
    let mut path = String::with_capacity(128);
    path.push_str("root");
    assign_id(root, &mut path);
}

/// Append one child's id segment (`.role[key]` / `.role.index`) to the
/// shared path buffer.
fn push_id_suffix(path: &mut String, child: &El, child_index: usize) {
    use std::fmt::Write;
    path.push('.');
    path.push_str(role_token(&child.kind));
    match &child.key {
        Some(k) => {
            path.push('[');
            path.push_str(k);
            path.push(']');
        }
        None => {
            let _ = write!(path, ".{child_index}");
        }
    }
}

/// Walk with a single reused path buffer (push segment / recurse /
/// truncate): one `Arc<str>` allocation per node — the id itself —
/// instead of the former three intermediate `format!` strings.
fn assign_id(node: &mut El, path: &mut String) {
    node.computed_id = std::sync::Arc::from(path.as_str());
    for (i, c) in node.children.iter_mut().enumerate() {
        let len = path.len();
        push_id_suffix(path, c, i);
        assign_id(c, path);
        path.truncate(len);
    }
}

fn role_token(k: &Kind) -> &'static str {
    match k {
        Kind::Group => "group",
        Kind::Card => "card",
        Kind::Button => "button",
        Kind::Badge => "badge",
        Kind::Text => "text",
        Kind::Heading => "heading",
        Kind::Spacer => "spacer",
        Kind::Divider => "divider",
        Kind::Overlay => "overlay",
        Kind::Scrim => "scrim",
        Kind::Modal => "modal",
        Kind::Scroll => "scroll",
        Kind::VirtualList => "virtual_list",
        Kind::Inlines => "inlines",
        Kind::HardBreak => "hard_break",
        Kind::Math => "math",
        Kind::Image => "image",
        Kind::Surface => "surface",
        Kind::Vector => "vector",
        Kind::Scene3D => "scene3d",
        Kind::Plot => "plot",
        Kind::Viewport => "viewport",
        Kind::Custom(name) => name,
    }
}

/// Record `rect` as `node`'s layout output: on the node itself
/// ([`El::computed_rect`], the full-tree store every per-node consumer
/// reads), and additionally in the keyed side map when the node
/// carries an author key, so `rect_of_key` / custom-layout anchoring
/// can resolve it without the `El` in hand.
#[inline]
fn set_rect(node: &mut El, rect: Rect, ui_state: &mut UiState) {
    node.computed_rect = rect;
    if node.key.is_some() {
        ui_state
            .layout
            .keyed_rects
            .insert(node.computed_id.clone(), rect);
    }
}

/// Resolve a descendant's rect by its path-shaped `computed_id`,
/// descending only into the child whose id prefixes the target — the
/// id namespace mirrors the tree path, so this costs O(depth ×
/// siblings), not a subtree walk. Used for scroll-anchor resolution,
/// where the anchor id was recorded on a previous frame and may name
/// any (unkeyed) descendant. Returns `None` when the id no longer
/// names a node in this subtree.
fn find_descendant_rect(node: &El, target_id: &str) -> Option<Rect> {
    for c in &node.children {
        if &*c.computed_id == target_id {
            return Some(c.computed_rect);
        }
        if target_id
            .strip_prefix(&*c.computed_id)
            .is_some_and(|rest| rest.starts_with('.'))
        {
            return find_descendant_rect(c, target_id);
        }
    }
    None
}

fn layout_children(node: &mut El, node_rect: Rect, ui_state: &mut UiState) {
    if matches!(node.kind, Kind::Inlines) {
        // The paragraph paints as a single AttributedText DrawOp;
        // child Text/HardBreak nodes are aggregated by draw_ops::
        // push_node and don't paint independently. Give each child a
        // zero-size rect so the rest of the engine (hit-test, focus,
        // animation, lint) treats them as non-paint pseudo-nodes. The
        // paragraph's hit-test target is the Inlines node itself,
        // sized by node_rect.
        for c in &mut node.children {
            set_rect(c, Rect::new(node_rect.x, node_rect.y, 0.0, 0.0), ui_state);
            // Recurse so descendants of Text/HardBreak nodes (rare —
            // these are leaves in practice — but keeping the invariant
            // simple) still get their rects assigned.
            layout_children(c, Rect::new(node_rect.x, node_rect.y, 0.0, 0.0), ui_state);
        }
        return;
    }
    if let Some(items) = node.virtual_items.as_deref().cloned() {
        layout_virtual(node, node_rect, items, ui_state);
        return;
    }
    if let Some(layout_fn) = node.layout_override.clone() {
        layout_custom(node, node_rect, layout_fn, ui_state);
        if node.scrollable {
            apply_scroll_offset(node, node_rect, ui_state);
        }
        if node.viewport.is_some() {
            apply_viewport_transform(node, node_rect, ui_state);
        }
        return;
    }
    match node.axis {
        Axis::Overlay => {
            let inner = node_rect.inset(node.padding);
            // A `viewport()` lets its content size to full intrinsic — the
            // pan/zoom transform reveals what extends past the frame.
            // Modals and other overlays still clamp to the frame.
            let clamp_to_parent = node.viewport.is_none();
            for c in &mut node.children {
                let c_rect = overlay_rect(c, inner, node.align, node.justify, clamp_to_parent);
                resize_if_width_diverged(c, c_rect.w);
                set_rect(c, c_rect, ui_state);
                layout_children(c, c_rect, ui_state);
            }
        }
        Axis::Column => layout_axis(node, node_rect, true, ui_state),
        Axis::Row => layout_axis(node, node_rect, false, ui_state),
    }
    if node.scrollable {
        apply_scroll_offset(node, node_rect, ui_state);
    }
    if node.viewport.is_some() {
        apply_viewport_transform(node, node_rect, ui_state);
    }
}

fn layout_custom(node: &mut El, node_rect: Rect, layout_fn: LayoutFn, ui_state: &mut UiState) {
    let inner = node_rect.inset(node.padding);
    // `size_tree` measured custom-layout children unconstrained, so
    // `measure` reads the stored naturals — same values the old
    // on-demand `intrinsic(c)` produced, without the subtree walk.
    let measure = |c: &El| c.measured_size;
    // Split-borrow `ui_state` so the `rect_of_key` closure reads the
    // key index + keyed rects while the surrounding function still
    // holds the mutable borrow needed to write this node's children's
    // rects afterwards. Both closures resolve keyed nodes (plus the
    // root) — anchors must carry a key, which every anchor producer
    // (popover trigger, tooltip hover target) already guarantees.
    let key_index = &ui_state.layout.key_index;
    let keyed_rects = &ui_state.layout.keyed_rects;
    let rect_of_key = |key: &str| -> Option<Rect> {
        let id = key_index.get(key)?;
        keyed_rects.get(id).copied()
    };
    let rect_of_id = |id: &str| -> Option<Rect> { keyed_rects.get(id).copied() };
    let rects = (layout_fn.0)(LayoutCtx {
        container: inner,
        children: &node.children,
        measure: &measure,
        rect_of_key: &rect_of_key,
        rect_of_id: &rect_of_id,
    });
    assert_eq!(
        rects.len(),
        node.children.len(),
        "LayoutFn for {:?} returned {} rects for {} children",
        node.computed_id,
        rects.len(),
        node.children.len(),
    );
    for (c, c_rect) in node.children.iter_mut().zip(rects) {
        // A custom layout may assign a width far from the child's
        // natural (sized unconstrained by `size_tree`); wrap-text
        // descendants must re-measure at the width they will paint at.
        resize_if_width_diverged(c, c_rect.w);
        set_rect(c, c_rect, ui_state);
        layout_children(c, c_rect, ui_state);
    }
}

/// Virtualized list realization. Dispatches by [`VirtualMode`] —
/// `Fixed` uses an O(1) division to find the visible range; `Dynamic`
/// walks measured-or-estimated heights, measures each visible row's
/// natural intrinsic height, and writes the result back to the height
/// cache on `UiState` so subsequent frames have it available.
fn layout_virtual(node: &mut El, node_rect: Rect, items: VirtualItems, ui_state: &mut UiState) {
    let inner = node_rect.inset(node.padding);
    match items.mode {
        VirtualMode::Fixed { row_height } => layout_virtual_fixed(
            node,
            inner,
            items.count,
            row_height,
            items.build_row,
            ui_state,
        ),
        VirtualMode::Dynamic {
            estimated_row_height,
            append_only,
        } => {
            let fns = DynamicVirtualFns {
                anchor_policy: items.anchor_policy,
                row_key: items.row_key,
                build_row: items.build_row,
            };
            if append_only {
                layout_virtual_dynamic_incremental(
                    node,
                    inner,
                    items.count,
                    estimated_row_height,
                    fns,
                    ui_state,
                );
            } else {
                layout_virtual_dynamic(
                    node,
                    inner,
                    items.count,
                    estimated_row_height,
                    fns,
                    ui_state,
                );
            }
        }
    }
}

/// Consume any pending [`ScrollRequest`]s targeting this list's `key`,
/// resolving each into a target offset using the live viewport rect and
/// the caller-supplied row-extent function. Writes the resolved offset
/// directly into `scroll.offsets`; the immediately-following
/// `write_virtual_scroll_state` call clamps it to `[0, max_offset]`.
///
/// Requests for other lists are left in the queue for sibling lists in
/// the same layout pass. Anything still queued after layout completes is
/// dropped by the runtime (see `prepare_layout`).
fn resolve_scroll_requests<F, K>(
    node: &El,
    inner: Rect,
    count: usize,
    row_extent: F,
    row_for_key: K,
    ui_state: &mut UiState,
) -> bool
where
    F: Fn(usize) -> (f32, f32),
    K: Fn(&str) -> Option<usize>,
{
    if ui_state.scroll.pending_requests.is_empty() {
        return false;
    }
    let Some(key) = node.key.as_deref() else {
        return false;
    };
    let pending = std::mem::take(&mut ui_state.scroll.pending_requests);
    let (matched, remaining): (Vec<ScrollRequest>, Vec<ScrollRequest>) =
        pending.into_iter().partition(|req| match req {
            ScrollRequest::ToRow { list_key, .. } => list_key == key,
            ScrollRequest::ToRowKey { list_key, .. } => list_key == key,
            // EnsureVisible isn't a virtual-list-row request; let the
            // non-virtual scroll resolver pick it up downstream.
            ScrollRequest::EnsureVisible { .. } => false,
        });
    ui_state.scroll.pending_requests = remaining;

    let mut wrote = false;
    for req in matched {
        let (row, align) = match req {
            ScrollRequest::ToRow { row, align, .. } => (row, align),
            ScrollRequest::ToRowKey { row_key, align, .. } => {
                let Some(row) = row_for_key(&row_key) else {
                    continue;
                };
                (row, align)
            }
            ScrollRequest::EnsureVisible { .. } => continue,
        };
        if row >= count {
            continue;
        }
        let (row_top, row_h) = row_extent(row);
        let row_bottom = row_top + row_h;
        let viewport_h = inner.h;
        let current = ui_state
            .scroll
            .offsets
            .get(&*node.computed_id)
            .copied()
            .unwrap_or(0.0);
        let new_offset = match align {
            ScrollAlignment::Start => row_top,
            ScrollAlignment::End => row_bottom - viewport_h,
            ScrollAlignment::Center => row_top + (row_h - viewport_h) / 2.0,
            ScrollAlignment::Visible => {
                if row_top < current {
                    row_top
                } else if row_bottom > current + viewport_h {
                    row_bottom - viewport_h
                } else {
                    continue;
                }
            }
        };
        ui_state
            .scroll
            .offsets
            .insert(node.computed_id.to_string(), new_offset);
        wrote = true;
    }
    wrote
}

/// Clamp the stored scroll offset, write the metrics + thumb rect, and
/// return the clamped offset. Shared scaffold for both virtual modes.
fn write_virtual_scroll_state(node: &El, inner: Rect, total_h: f32, ui_state: &mut UiState) -> f32 {
    let max_offset = (total_h - inner.h).max(0.0);
    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let stored = resolve_pin(node, stored, max_offset, ui_state);
    let offset = stored.clamp(0.0, max_offset);
    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.to_string(), offset);
    write_virtual_scroll_metrics(node, inner, total_h, max_offset, offset, ui_state);
    offset
}

fn write_virtual_scroll_metrics(
    node: &El,
    inner: Rect,
    total_h: f32,
    max_offset: f32,
    offset: f32,
    ui_state: &mut UiState,
) {
    ui_state.scroll.metrics.insert(
        node.computed_id.to_string(),
        crate::state::ScrollMetrics {
            viewport_h: inner.h,
            content_h: total_h,
            max_offset,
        },
    );
    write_thumb_rect(node, inner, total_h, max_offset, offset, ui_state);
}

/// Assign the realized row a path-style `computed_id` matching the
/// regular tree's role/key/index convention so hit-test, focus, and
/// state lookups remain stable across scrolls.
fn assign_virtual_row_id(child: &mut El, parent_id: &str, global_i: usize) {
    let role = role_token(&child.kind);
    let mut path = String::with_capacity(parent_id.len() + 24);
    path.push_str(parent_id);
    path.push('.');
    path.push_str(role);
    match &child.key {
        Some(k) => {
            path.push('[');
            path.push_str(k);
            path.push(']');
        }
        None => {
            use std::fmt::Write;
            let _ = write!(path, ".{global_i}");
        }
    }
    assign_id(child, &mut path);
}

fn layout_virtual_fixed(
    node: &mut El,
    inner: Rect,
    count: usize,
    row_height: f32,
    build_row: Arc<dyn Fn(usize) -> El + Send + Sync>,
    ui_state: &mut UiState,
) {
    let gap = node.gap.max(0.0);
    let pitch = row_height + gap;
    let total_h = virtual_total_height(count, count as f32 * row_height, gap);
    resolve_scroll_requests(
        node,
        inner,
        count,
        |i| (i as f32 * pitch, row_height),
        |row_key| row_key.parse::<usize>().ok().filter(|row| *row < count),
        ui_state,
    );
    let offset = write_virtual_scroll_state(node, inner, total_h, ui_state);

    if count == 0 {
        node.children.clear();
        return;
    }

    // Visible index range — `start` floors, `end` ceils, both clamped.
    // Include one extra candidate because a large gap can make the
    // pitch-based ceil land on the gap before the next visible row.
    let start = (offset / pitch).floor() as usize;
    let end = ((((offset + inner.h) / pitch).ceil() as usize) + 1).min(count);

    let mut realized: Vec<El> = Vec::new();
    let mut realized_range: Option<(usize, usize)> = None;
    for global_i in start..end {
        let row_top = global_i as f32 * pitch;
        if row_top >= offset + inner.h || row_top + row_height <= offset {
            continue;
        }
        let mut child = (build_row)(global_i);
        assign_virtual_row_id(&mut child, &node.computed_id, global_i);
        // Rows are realized after the tree-wide sizing pass ran, so
        // size each fresh subtree here at the list's inner width.
        size_tree(&mut child, Some(inner.w));

        let row_y = inner.y + row_top - offset;
        let c_rect = Rect::new(inner.x, row_y, inner.w, row_height);
        set_rect(&mut child, c_rect, ui_state);
        layout_children(&mut child, c_rect, ui_state);
        realized.push(child);
        realized_range = Some(match realized_range {
            None => (global_i, global_i + 1),
            Some((s, _)) => (s, global_i + 1),
        });
    }
    if let Some((s, e)) = realized_range {
        ui_state
            .scroll
            .visible_ranges
            .insert(node.computed_id.to_string(), (s, e));
    }
    node.children = realized;
}

/// Append-only fast path for `VirtualMode::Dynamic { append_only: true }`.
/// Behaviourally identical to [`layout_virtual_dynamic`] (anchoring,
/// pinning, scroll-request resolution, measurement, the offset-correction
/// pass) — it reuses the same semantic helpers — but it never
/// materializes the full `Vec` of keys or heights. A persistent
/// [`DynHeightIndex`] holds the per-row heights across frames; this pass
/// reconciles it trim-then-append and answers every height / row-top /
/// visible-range query off the index, so per-frame cost is O(visible)
/// (plus O(√n) range queries) instead of the general path's several O(n)
/// walks (issue #107). See the dispatch in [`layout_virtual`] and the
/// contract on [`VirtualMode::Dynamic::append_only`].
fn layout_virtual_dynamic_incremental(
    node: &mut El,
    inner: Rect,
    count: usize,
    estimated_row_height: f32,
    fns: DynamicVirtualFns,
    ui_state: &mut UiState,
) {
    let gap = node.gap.max(0.0);
    let width_bucket = virtual_width_bucket(inner.w);

    if count == 0 {
        ui_state.scroll.virtual_anchors.remove(&*node.computed_id);
        ui_state.scroll.dyn_height_index.remove(&*node.computed_id);
        let offset = write_virtual_scroll_state(node, inner, 0.0, ui_state);
        debug_assert_eq!(offset, 0.0);
        node.children.clear();
        return;
    }

    // Pull the persistent height index out of `ui_state` so it is an
    // owned local for the rest of the pass (sidestepping the borrow
    // against `&mut ui_state` the helpers need). Reconcile it against
    // this frame as trim-then-append, or cold-rebuild when that's not
    // possible (first frame, width change, or a contract violation —
    // self-healing to correct geometry at an O(n) cost for that frame).
    let existing = ui_state.scroll.dyn_height_index.remove(&*node.computed_id);
    let head_key = (fns.row_key)(0);
    let mut trimmed_keys: Vec<String> = Vec::new();
    let reconciled = existing.and_then(|mut ix| {
        let ok = ix.reconcile(
            width_bucket,
            estimated_row_height,
            count,
            &head_key,
            |i| (fns.row_key)(i),
            |_i, key| {
                cached_row_height(
                    ui_state,
                    &node.computed_id,
                    key,
                    width_bucket,
                    estimated_row_height,
                )
            },
            &mut trimmed_keys,
        );
        ok.then_some(ix)
    });
    let mut index = match reconciled {
        Some(ix) => ix,
        None => DynHeightIndex::build(width_bucket, estimated_row_height, count, |i| {
            let key = (fns.row_key)(i);
            let h = cached_row_height(
                ui_state,
                &node.computed_id,
                &key,
                width_bucket,
                estimated_row_height,
            );
            (key, h)
        }),
    };
    // Evict measurement-cache entries for rows trimmed off the head, so
    // the cache stays bounded over a long ring-buffer feed. This is the
    // incremental analogue of the general path's per-frame O(n)
    // `prune_dynamic_measurements`; here it's O(trimmed).
    if !trimmed_keys.is_empty()
        && let Some(measured) = ui_state
            .scroll
            .measured_row_heights
            .get_mut(&*node.computed_id)
    {
        for key in &trimmed_keys {
            measured.remove(key);
        }
        if measured.is_empty() {
            ui_state
                .scroll
                .measured_row_heights
                .remove(&*node.computed_id);
        }
    }

    // Skip the cache snapshot entirely when nothing in the queue targets
    // this list (see the general path for the rationale).
    let has_request = node.key.as_deref().is_some_and(|k| {
        ui_state.scroll.pending_requests.iter().any(|r| match r {
            ScrollRequest::ToRow { list_key, .. } => list_key == k,
            ScrollRequest::ToRowKey { list_key, .. } => list_key == k,
            ScrollRequest::EnsureVisible { .. } => false,
        })
    });
    let mut request_wrote = false;
    if has_request {
        request_wrote = resolve_scroll_requests(
            node,
            inner,
            count,
            |target| (index.row_top(target, gap), index.height(target)),
            |row_key| index.index_for_key(row_key),
            ui_state,
        );
    }

    let total_h = virtual_total_height(count, index.heights_sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let pin_active = pin_would_be_active(node, stored, max_offset, ui_state).unwrap_or(false);
    let provisional_offset = if pin_active {
        match node.pin_policy {
            crate::tree::PinPolicy::End => max_offset,
            crate::tree::PinPolicy::Start => 0.0,
            crate::tree::PinPolicy::None => unreachable!(),
        }
    } else if request_wrote {
        stored
    } else {
        dynamic_anchor_offset_indexed(node, &index, gap, stored, ui_state).unwrap_or(stored)
    }
    .clamp(0.0, max_offset);

    let (measure_start, _, measure_end) = index.visible_range(gap, provisional_offset, inner.h);
    measure_dynamic_range(
        node,
        DynamicRangeCtx {
            inner,
            keys: KeySource::Func(&*fns.row_key),
            width_bucket,
            build_row: &fns.build_row,
        },
        measure_start,
        measure_end,
        ui_state,
    );
    refresh_index_range(
        &mut index,
        &node.computed_id,
        width_bucket,
        measure_start,
        measure_end,
        &*fns.row_key,
        estimated_row_height,
        ui_state,
    );

    let total_h = virtual_total_height(count, index.heights_sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let pin_resolved = resolve_pin(node, stored, max_offset, ui_state);
    let pin_active = !matches!(node.pin_policy, crate::tree::PinPolicy::None)
        && ui_state
            .scroll
            .pin_active
            .get(&*node.computed_id)
            .copied()
            .unwrap_or(false);
    let mut offset = if pin_active {
        pin_resolved
    } else if request_wrote {
        stored
    } else {
        dynamic_anchor_offset_indexed(node, &index, gap, stored, ui_state).unwrap_or(stored)
    }
    .clamp(0.0, max_offset);

    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.to_string(), offset);

    let (start, start_y, end) = index.visible_range(gap, offset, inner.h);
    let mut realized_rows = layout_dynamic_range(
        node,
        DynamicRangeCtx {
            inner,
            keys: KeySource::Func(&*fns.row_key),
            width_bucket,
            build_row: &fns.build_row,
        },
        offset,
        start,
        start_y,
        end,
        ui_state,
    );
    refresh_index_range(
        &mut index,
        &node.computed_id,
        width_bucket,
        start,
        end,
        &*fns.row_key,
        estimated_row_height,
        ui_state,
    );

    let total_h = virtual_total_height(count, index.heights_sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let corrected_offset = if pin_active {
        match node.pin_policy {
            crate::tree::PinPolicy::End => max_offset,
            crate::tree::PinPolicy::Start => 0.0,
            crate::tree::PinPolicy::None => unreachable!(),
        }
    } else if request_wrote {
        offset
    } else {
        dynamic_anchor_offset_indexed(node, &index, gap, stored, ui_state).unwrap_or(offset)
    }
    .clamp(0.0, max_offset);
    if (corrected_offset - offset).abs() > 0.01 {
        let dy = offset - corrected_offset;
        for child in &mut node.children {
            shift_subtree_y(child, dy, ui_state);
        }
        for row in &mut realized_rows {
            row.rect.y += dy;
        }
        offset = corrected_offset;
        ui_state
            .scroll
            .offsets
            .insert(node.computed_id.to_string(), offset);
    }
    if matches!(node.pin_policy, crate::tree::PinPolicy::End) {
        ui_state
            .scroll
            .pin_prev_max
            .insert(node.computed_id.to_string(), max_offset);
    }
    write_virtual_scroll_metrics(node, inner, total_h, max_offset, offset, ui_state);

    if let Some(anchor) = choose_dynamic_anchor(fns.anchor_policy, inner, offset, &realized_rows) {
        ui_state
            .scroll
            .virtual_anchors
            .insert(node.computed_id.to_string(), anchor);
    } else {
        ui_state.scroll.virtual_anchors.remove(&*node.computed_id);
    }

    ui_state
        .scroll
        .dyn_height_index
        .insert(node.computed_id.to_string(), index);
}

/// Measured-or-estimated height for one row, read from the persistent
/// measurement cache exactly as the general path's `dynamic_row_heights`
/// does (keyed by list id → row key → width bucket).
fn cached_row_height(
    ui_state: &UiState,
    id: &str,
    key: &str,
    width_bucket: u32,
    estimated_row_height: f32,
) -> f32 {
    ui_state
        .scroll
        .measured_row_heights
        .get(id)
        .and_then(|m| m.get(key))
        .and_then(|by_width| by_width.get(&width_bucket))
        .copied()
        .unwrap_or(estimated_row_height)
}

/// Fold the freshly measured heights for the realized window `[start,
/// end)` back into the height index, so the next query sees real
/// measurements instead of the estimate. O(visible).
#[allow(clippy::too_many_arguments)]
fn refresh_index_range(
    index: &mut DynHeightIndex,
    id: &str,
    width_bucket: u32,
    start: usize,
    end: usize,
    row_key: &(dyn Fn(usize) -> String + Send + Sync),
    estimated_row_height: f32,
    ui_state: &UiState,
) {
    for idx in start..end {
        let key = row_key(idx);
        let h = cached_row_height(ui_state, id, &key, width_bucket, estimated_row_height);
        index.set_height(idx, h);
    }
}

/// Index-backed equivalent of [`dynamic_anchor_offset`]: resolve the
/// stored anchor's row through the height index (O(1) key→index, O(√n)
/// row-top) instead of a linear scan over a materialized key slice.
fn dynamic_anchor_offset_indexed(
    node: &El,
    index: &DynHeightIndex,
    gap: f32,
    stored: f32,
    ui_state: &UiState,
) -> Option<f32> {
    let anchor = ui_state.scroll.virtual_anchors.get(&*node.computed_id)?;
    let idx = index.index_for_key(&anchor.row_key)?;
    let row_h = index.height(idx).max(0.0);
    let row_point = row_h * anchor.row_fraction.clamp(0.0, 1.0);
    let scroll_delta = stored - anchor.resolved_offset;
    let viewport_y = anchor.viewport_y - scroll_delta;
    Some(index.row_top(idx, gap) + row_point - viewport_y)
}

fn layout_virtual_dynamic(
    node: &mut El,
    inner: Rect,
    count: usize,
    estimated_row_height: f32,
    fns: DynamicVirtualFns,
    ui_state: &mut UiState,
) {
    let gap = node.gap.max(0.0);
    let width_bucket = virtual_width_bucket(inner.w);
    let row_keys = (0..count).map(|i| (fns.row_key)(i)).collect::<Vec<_>>();
    prune_dynamic_measurements(node, &row_keys, ui_state);

    if count == 0 {
        ui_state.scroll.virtual_anchors.remove(&*node.computed_id);
        let offset = write_virtual_scroll_state(node, inner, 0.0, ui_state);
        debug_assert_eq!(offset, 0.0);
        node.children.clear();
        return;
    }

    let mut row_heights = dynamic_row_heights(
        node,
        &row_keys,
        width_bucket,
        estimated_row_height,
        ui_state,
    );

    // Skip the cache snapshot entirely when nothing in the queue
    // targets this list — a hot path on dynamic lists with warm
    // caches (potentially thousands of entries) that would otherwise
    // pay a per-frame HashMap clone for an operation that fires
    // maybe once a minute.
    let has_request = node.key.as_deref().is_some_and(|k| {
        ui_state.scroll.pending_requests.iter().any(|r| match r {
            ScrollRequest::ToRow { list_key, .. } => list_key == k,
            ScrollRequest::ToRowKey { list_key, .. } => list_key == k,
            ScrollRequest::EnsureVisible { .. } => false,
        })
    });
    let mut request_wrote = false;
    if has_request {
        request_wrote = resolve_scroll_requests(
            node,
            inner,
            count,
            |target| {
                (
                    dynamic_row_top(&row_heights, gap, target),
                    row_heights[target],
                )
            },
            |row_key| row_keys.iter().position(|key| key == row_key),
            ui_state,
        );
    }

    let total_h = virtual_total_height(count, row_heights.iter().sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let pin_active = pin_would_be_active(node, stored, max_offset, ui_state).unwrap_or(false);
    let provisional_offset = if pin_active {
        match node.pin_policy {
            crate::tree::PinPolicy::End => max_offset,
            crate::tree::PinPolicy::Start => 0.0,
            crate::tree::PinPolicy::None => unreachable!(),
        }
    } else if request_wrote {
        stored
    } else {
        dynamic_anchor_offset(node, &row_keys, &row_heights, gap, stored, ui_state)
            .unwrap_or(stored)
    }
    .clamp(0.0, max_offset);

    let (measure_start, _, measure_end) =
        dynamic_visible_range(&row_heights, gap, provisional_offset, inner.h);
    measure_dynamic_range(
        node,
        DynamicRangeCtx {
            inner,
            keys: KeySource::Slice(&row_keys),
            width_bucket,
            build_row: &fns.build_row,
        },
        measure_start,
        measure_end,
        ui_state,
    );

    row_heights = dynamic_row_heights(
        node,
        &row_keys,
        width_bucket,
        estimated_row_height,
        ui_state,
    );
    let total_h = virtual_total_height(count, row_heights.iter().sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let pin_resolved = resolve_pin(node, stored, max_offset, ui_state);
    let pin_active = !matches!(node.pin_policy, crate::tree::PinPolicy::None)
        && ui_state
            .scroll
            .pin_active
            .get(&*node.computed_id)
            .copied()
            .unwrap_or(false);
    let mut offset = if pin_active {
        pin_resolved
    } else if request_wrote {
        stored
    } else {
        dynamic_anchor_offset(node, &row_keys, &row_heights, gap, stored, ui_state)
            .unwrap_or(stored)
    }
    .clamp(0.0, max_offset);

    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.to_string(), offset);

    let (start, start_y, end) = dynamic_visible_range(&row_heights, gap, offset, inner.h);
    let mut realized_rows = layout_dynamic_range(
        node,
        DynamicRangeCtx {
            inner,
            keys: KeySource::Slice(&row_keys),
            width_bucket,
            build_row: &fns.build_row,
        },
        offset,
        start,
        start_y,
        end,
        ui_state,
    );

    row_heights = dynamic_row_heights(
        node,
        &row_keys,
        width_bucket,
        estimated_row_height,
        ui_state,
    );
    let total_h = virtual_total_height(count, row_heights.iter().sum(), gap);
    let max_offset = (total_h - inner.h).max(0.0);
    let corrected_offset = if pin_active {
        match node.pin_policy {
            crate::tree::PinPolicy::End => max_offset,
            crate::tree::PinPolicy::Start => 0.0,
            crate::tree::PinPolicy::None => unreachable!(),
        }
    } else if request_wrote {
        offset
    } else {
        dynamic_anchor_offset(node, &row_keys, &row_heights, gap, stored, ui_state)
            .unwrap_or(offset)
    }
    .clamp(0.0, max_offset);
    if (corrected_offset - offset).abs() > 0.01 {
        let dy = offset - corrected_offset;
        for child in &mut node.children {
            shift_subtree_y(child, dy, ui_state);
        }
        for row in &mut realized_rows {
            row.rect.y += dy;
        }
        offset = corrected_offset;
        ui_state
            .scroll
            .offsets
            .insert(node.computed_id.to_string(), offset);
    }
    if matches!(node.pin_policy, crate::tree::PinPolicy::End) {
        ui_state
            .scroll
            .pin_prev_max
            .insert(node.computed_id.to_string(), max_offset);
    }
    write_virtual_scroll_metrics(node, inner, total_h, max_offset, offset, ui_state);

    if let Some(anchor) = choose_dynamic_anchor(fns.anchor_policy, inner, offset, &realized_rows) {
        ui_state
            .scroll
            .virtual_anchors
            .insert(node.computed_id.to_string(), anchor);
    } else {
        ui_state.scroll.virtual_anchors.remove(&*node.computed_id);
    }
}

struct DynamicVirtualFns {
    anchor_policy: VirtualAnchorPolicy,
    row_key: Arc<dyn Fn(usize) -> String + Send + Sync>,
    build_row: Arc<dyn Fn(usize) -> El + Send + Sync>,
}

#[derive(Clone, Copy)]
struct DynamicRangeCtx<'a> {
    inner: Rect,
    keys: KeySource<'a>,
    width_bucket: u32,
    build_row: &'a Arc<dyn Fn(usize) -> El + Send + Sync>,
}

/// Source of stable row keys over a realized range. The general dynamic
/// path already has every key materialized as a slice; the append-only
/// incremental path resolves keys on demand for the visible window only
/// (it never materializes all `n`). Both feed the same range
/// realization code (`measure_dynamic_range` / `layout_dynamic_range`).
#[derive(Clone, Copy)]
enum KeySource<'a> {
    Slice(&'a [String]),
    Func(&'a (dyn Fn(usize) -> String + Send + Sync)),
}

impl KeySource<'_> {
    fn key(&self, idx: usize) -> String {
        match self {
            KeySource::Slice(keys) => keys[idx].clone(),
            KeySource::Func(f) => f(idx),
        }
    }
}

fn virtual_width_bucket(width: f32) -> u32 {
    width.max(0.0).round().min(u32::MAX as f32) as u32
}

fn prune_dynamic_measurements(node: &El, row_keys: &[String], ui_state: &mut UiState) {
    let Some(measurements) = ui_state
        .scroll
        .measured_row_heights
        .get_mut(&*node.computed_id)
    else {
        return;
    };
    let live_keys = row_keys
        .iter()
        .map(String::as_str)
        .collect::<FxHashSet<_>>();
    measurements.retain(|key, widths| {
        let live = live_keys.contains(key.as_str());
        if live {
            widths.retain(|_, h| h.is_finite() && *h >= 0.0);
        }
        live && !widths.is_empty()
    });
    if measurements.is_empty() {
        ui_state
            .scroll
            .measured_row_heights
            .remove(&*node.computed_id);
    }
}

fn dynamic_row_heights(
    node: &El,
    row_keys: &[String],
    width_bucket: u32,
    estimated_row_height: f32,
    ui_state: &UiState,
) -> Vec<f32> {
    let measurements = ui_state.scroll.measured_row_heights.get(&*node.computed_id);
    row_keys
        .iter()
        .map(|key| {
            measurements
                .and_then(|m| m.get(key))
                .and_then(|by_width| by_width.get(&width_bucket))
                .copied()
                .unwrap_or(estimated_row_height)
        })
        .collect()
}

fn dynamic_row_top(row_heights: &[f32], gap: f32, target: usize) -> f32 {
    row_heights
        .iter()
        .take(target)
        .fold(0.0, |y, h| y + *h + gap)
}

fn dynamic_visible_range(
    row_heights: &[f32],
    gap: f32,
    offset: f32,
    viewport_h: f32,
) -> (usize, f32, usize) {
    let count = row_heights.len();
    let mut start = 0;
    let mut y = 0.0_f32;
    while start < count {
        let h = row_heights[start];
        if y + h > offset {
            break;
        }
        y += h + gap;
        start += 1;
    }

    let mut end = start;
    let mut cursor = y;
    let viewport_bottom = offset + viewport_h;
    while end < count && cursor < viewport_bottom {
        let h = row_heights[end];
        end += 1;
        cursor += h + gap;
    }
    (start, y, end)
}

fn dynamic_anchor_offset(
    node: &El,
    row_keys: &[String],
    row_heights: &[f32],
    gap: f32,
    stored: f32,
    ui_state: &UiState,
) -> Option<f32> {
    let anchor = ui_state.scroll.virtual_anchors.get(&*node.computed_id)?;
    let idx = if anchor.row_index < row_keys.len() && row_keys[anchor.row_index] == anchor.row_key {
        anchor.row_index
    } else {
        row_keys.iter().position(|key| key == &anchor.row_key)?
    };
    let row_h = row_heights.get(idx).copied().unwrap_or(0.0).max(0.0);
    let row_point = row_h * anchor.row_fraction.clamp(0.0, 1.0);
    let scroll_delta = stored - anchor.resolved_offset;
    let viewport_y = anchor.viewport_y - scroll_delta;
    Some(dynamic_row_top(row_heights, gap, idx) + row_point - viewport_y)
}

fn measure_dynamic_range(
    node: &El,
    ctx: DynamicRangeCtx<'_>,
    start: usize,
    end: usize,
    ui_state: &mut UiState,
) {
    if start >= end {
        return;
    }
    let mut new_measurements = Vec::new();
    for idx in start..end {
        let key = ctx.keys.key(idx);
        let mut child = (ctx.build_row)(idx);
        assign_virtual_row_id(&mut child, &node.computed_id, idx);
        // This realization exists only to measure: the height lands in
        // the persistent per-row height store (`measured_row_heights`),
        // which is what keeps re-measures rare across frames now that
        // the per-pass intrinsic cache is gone (issue #59's dedup
        // concern is handled by that store, not by an in-frame cache).
        size_tree(&mut child, Some(ctx.inner.w));
        let actual_h = measure_dynamic_row(node, idx, ctx.inner.w, &child);
        new_measurements.push((key, actual_h));
    }
    store_dynamic_measurements(node, ctx.width_bucket, new_measurements, ui_state);
}

fn measure_dynamic_row(node: &El, idx: usize, width: f32, child: &El) -> f32 {
    match child.height {
        Size::Fixed(v) => v.max(0.0),
        Size::Ch(n) => (n * ch_unit(child)).max(0.0),
        // The caller ran `size_tree(child, Some(width))` just before —
        // the stored measure IS the height-at-list-width.
        Size::Hug => child.measured_size.1.max(0.0),
        Size::Aspect(r) => (width * r).max(0.0),
        Size::Fill(_) => panic!(
            "virtual_list_dyn row {idx} on {:?} must size with Size::Fixed, Size::Hug, \
             or Size::Aspect; Size::Fill would absorb the viewport's height and break \
             virtualization",
            node.computed_id,
        ),
    }
}

/// Width buckets retained per measured row. Buckets are 1-logical-px
/// granular ([`virtual_width_bucket`]), so a user dragging a window
/// edge sweeps through hundreds of distinct buckets; without a cap
/// every one is retained for the list's lifetime (issue #57). Only the
/// buckets nearest the current width matter — heights at distant
/// widths are stale guesses anyway once content rewraps.
const MAX_WIDTH_BUCKETS_PER_ROW: usize = 8;

fn store_dynamic_measurements(
    node: &El,
    width_bucket: u32,
    measurements: Vec<(String, f32)>,
    ui_state: &mut UiState,
) {
    if measurements.is_empty() {
        return;
    }
    let entry = ui_state
        .scroll
        .measured_row_heights
        .entry(node.computed_id.to_string())
        .or_default();
    for (row_key, h) in measurements {
        let buckets = entry.entry(row_key).or_default();
        buckets.insert(width_bucket, h);
        if buckets.len() > MAX_WIDTH_BUCKETS_PER_ROW {
            // Keep the buckets closest to the width we're laying out
            // at; drop the farthest.
            let mut widths: Vec<u32> = buckets.keys().copied().collect();
            widths.sort_unstable_by_key(|w| (i64::from(*w) - i64::from(width_bucket)).abs());
            for w in widths.drain(MAX_WIDTH_BUCKETS_PER_ROW..) {
                buckets.remove(&w);
            }
        }
    }
}

#[derive(Clone, Debug)]
struct DynamicRealizedRow {
    index: usize,
    key: String,
    rect: Rect,
}

fn layout_dynamic_range(
    node: &mut El,
    ctx: DynamicRangeCtx<'_>,
    offset: f32,
    start: usize,
    start_y: f32,
    end: usize,
    ui_state: &mut UiState,
) -> Vec<DynamicRealizedRow> {
    let gap = node.gap.max(0.0);
    let mut cursor_y = start_y;
    let mut realized = Vec::new();
    let mut realized_rows = Vec::new();
    let mut new_measurements = Vec::new();

    for idx in start..end {
        let key = ctx.keys.key(idx);
        let mut child = (ctx.build_row)(idx);
        assign_virtual_row_id(&mut child, &node.computed_id, idx);
        // Realized after the tree-wide sizing pass — size the fresh
        // subtree at the list's inner width so `measure_dynamic_row`
        // and the placement below read stored measures.
        size_tree(&mut child, Some(ctx.inner.w));
        let actual_h = measure_dynamic_row(node, idx, ctx.inner.w, &child);
        new_measurements.push((key.clone(), actual_h));

        let row_y = ctx.inner.y + cursor_y - offset;
        let c_rect = Rect::new(ctx.inner.x, row_y, ctx.inner.w, actual_h);
        set_rect(&mut child, c_rect, ui_state);
        layout_children(&mut child, c_rect, ui_state);

        realized_rows.push(DynamicRealizedRow {
            index: idx,
            key,
            rect: c_rect,
        });
        realized.push(child);
        cursor_y += actual_h + gap;
    }

    store_dynamic_measurements(node, ctx.width_bucket, new_measurements, ui_state);
    if let (Some(first), Some(last)) = (realized_rows.first(), realized_rows.last()) {
        ui_state
            .scroll
            .visible_ranges
            .insert(node.computed_id.to_string(), (first.index, last.index + 1));
    }
    node.children = realized;
    realized_rows
}

fn choose_dynamic_anchor(
    policy: VirtualAnchorPolicy,
    inner: Rect,
    offset: f32,
    rows: &[DynamicRealizedRow],
) -> Option<VirtualAnchor> {
    let visible = rows
        .iter()
        .filter(|row| row.rect.bottom() > inner.y && row.rect.y < inner.bottom())
        .collect::<Vec<_>>();
    if visible.is_empty() {
        return None;
    }

    let chosen = match policy {
        VirtualAnchorPolicy::ViewportFraction { y_fraction } => {
            let target_y = inner.y + inner.h * y_fraction.clamp(0.0, 1.0);
            visible
                .iter()
                .min_by(|a, b| {
                    let ad = distance_to_interval(target_y, a.rect.y, a.rect.bottom());
                    let bd = distance_to_interval(target_y, b.rect.y, b.rect.bottom());
                    ad.total_cmp(&bd)
                })
                .copied()
                .map(|row| {
                    let anchor_y = target_y.clamp(row.rect.y, row.rect.bottom());
                    (row.clone(), anchor_y)
                })
        }
        VirtualAnchorPolicy::FirstVisible => {
            let row = visible
                .iter()
                .find(|row| row.rect.y >= inner.y && row.rect.bottom() <= inner.bottom())
                .or_else(|| visible.first())
                .copied()?;
            let anchor_y = row.rect.y.max(inner.y);
            Some((row.clone(), anchor_y))
        }
        VirtualAnchorPolicy::LastVisible => {
            let row = visible
                .iter()
                .rev()
                .find(|row| row.rect.y >= inner.y && row.rect.bottom() <= inner.bottom())
                .or_else(|| visible.last())
                .copied()?;
            let anchor_y = row.rect.bottom().min(inner.bottom());
            Some((row.clone(), anchor_y))
        }
    }?;

    let (row, anchor_y) = chosen;
    let row_h = row.rect.h.max(0.0);
    let row_fraction = if row_h > 0.0 {
        ((anchor_y - row.rect.y) / row_h).clamp(0.0, 1.0)
    } else {
        0.0
    };
    Some(VirtualAnchor {
        row_key: row.key.clone(),
        row_index: row.index,
        row_fraction,
        viewport_y: anchor_y - inner.y,
        resolved_offset: offset,
    })
}

fn distance_to_interval(y: f32, top: f32, bottom: f32) -> f32 {
    if y < top {
        top - y
    } else if y > bottom {
        y - bottom
    } else {
        0.0
    }
}

fn virtual_total_height(count: usize, row_sum: f32, gap: f32) -> f32 {
    if count == 0 {
        0.0
    } else {
        row_sum + gap * count.saturating_sub(1) as f32
    }
}

/// Scrollable post-pass: measure content height from the laid-out
/// children's stored rects, clamp the scroll offset to the available
/// range, and shift every descendant rect by `-offset`.
///
/// Children should size with `Hug` or `Fixed` on the main axis —
/// `Fill` children would absorb the viewport's height and there would
/// be nothing to scroll.
fn apply_scroll_offset(node: &mut El, node_rect: Rect, ui_state: &mut UiState) {
    let inner = node_rect.inset(node.padding);
    if node.children.is_empty() {
        ui_state
            .scroll
            .offsets
            .insert(node.computed_id.to_string(), 0.0);
        ui_state.scroll.scroll_anchors.remove(&*node.computed_id);
        ui_state.scroll.metrics.insert(
            node.computed_id.to_string(),
            crate::state::ScrollMetrics {
                viewport_h: inner.h,
                content_h: 0.0,
                max_offset: 0.0,
            },
        );
        return;
    }
    let content_bottom = node
        .children
        .iter()
        .map(|c| c.computed_rect.bottom())
        .fold(f32::NEG_INFINITY, f32::max);
    let content_h = (content_bottom - inner.y).max(0.0);
    let max_offset = (content_h - inner.h).max(0.0);

    // Resolve any matching `ScrollRequest::EnsureVisible` against
    // this scroll BEFORE reading the stored offset, so the request's
    // chosen offset wins (and gets clamped below, just like
    // wheel-driven offsets do). A request matches when the node
    // keyed `container_key` is an ancestor of this scroll —
    // `key_index` resolves the key to a computed_id and a
    // prefix-match on `node.computed_id` tells us we're inside.
    let request_wrote = resolve_ensure_visible_for_scroll(node, inner, content_h, ui_state);

    let stored = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0);
    let stored = resolve_pin(node, stored, max_offset, ui_state);
    let pin_active = !matches!(node.pin_policy, crate::tree::PinPolicy::None)
        && ui_state
            .scroll
            .pin_active
            .get(&*node.computed_id)
            .copied()
            .unwrap_or(false);
    let stored = if pin_active || request_wrote {
        stored
    } else {
        scroll_anchor_offset(node, inner, stored, ui_state).unwrap_or(stored)
    };
    let clamped = stored.clamp(0.0, max_offset);
    if clamped > 0.0 {
        for c in &mut node.children {
            shift_subtree_y(c, -clamped, ui_state);
        }
    }
    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.to_string(), clamped);
    ui_state.scroll.metrics.insert(
        node.computed_id.to_string(),
        crate::state::ScrollMetrics {
            viewport_h: inner.h,
            content_h,
            max_offset,
        },
    );

    write_thumb_rect(node, inner, content_h, max_offset, clamped, ui_state);

    if let Some(anchor) = choose_scroll_anchor(node, inner, clamped) {
        ui_state
            .scroll
            .scroll_anchors
            .insert(node.computed_id.to_string(), anchor);
    } else {
        ui_state.scroll.scroll_anchors.remove(&*node.computed_id);
    }
}

/// Resolve a [`viewport()`](crate::tree::viewport)'s pan/zoom and bake it
/// into its descendants' rects — the 2D pan + uniform-zoom analogue of
/// [`apply_scroll_offset`]. Runs after the viewport's children have been
/// laid out in un-transformed *content space*; measures the content
/// bounding box, consumes any matching
/// [`ViewportRequest`](crate::viewport::ViewportRequest), clamps the
/// result, then maps every descendant rect through the transform. Because
/// the transform lands in each descendant's `computed_rect`, hit-test /
/// links / selection follow it automatically (paint additionally scales
/// the descendants' scalar visuals; see `draw_ops`).
fn apply_viewport_transform(node: &mut El, node_rect: Rect, ui_state: &mut UiState) {
    use crate::viewport::ViewportView;
    let cfg = node
        .viewport
        .as_deref()
        .copied()
        .expect("apply_viewport_transform called on a non-viewport node");
    let inner = node_rect.inset(node.padding);
    let origin = (inner.x, inner.y);
    let content = viewport_content_bbox(node);

    // Start from the stored view, then fold in any programmatic requests
    // that name this viewport's key (consuming them).
    let mut view = ui_state
        .viewport
        .views
        .get(&*node.computed_id)
        .copied()
        .unwrap_or_default();
    if let Some(key) = node.key.as_deref() {
        let mut i = 0;
        while i < ui_state.viewport.pending_requests.len() {
            if ui_state.viewport.pending_requests[i].key() == key {
                let req = ui_state.viewport.pending_requests.remove(i);
                let mut target = apply_viewport_request(&req, cfg, inner, origin, content, view);
                // Under a `Contain` policy, a fit / reset settles on the
                // *policy* framing (its padding wins — see the request
                // docs). The instant path gets that from the policy
                // re-fit below after the re-arm; a flight must aim at it
                // directly, or it would fly to the request's own resolve
                // and visibly snap to the policy fit on arrival.
                if let crate::viewport::FitPolicy::Contain { padding } = cfg.fit
                    && matches!(
                        req,
                        crate::viewport::ViewportRequest::FitContent { .. }
                            | crate::viewport::ViewportRequest::ResetView { .. }
                    )
                {
                    target = viewport_fit_view(cfg, inner, origin, content, target, padding);
                }
                // A smooth request flies when there's something to fly
                // on: `Settled` mode snaps (headless determinism), a
                // `Lock`ed viewport isn't free to leave home, a zero-size
                // viewport has no geometry to frame, and an at-target
                // request needs no flight.
                let fly = req.behavior() == crate::viewport::ViewportBehavior::Smooth
                    && ui_state.animation.mode == crate::state::AnimationMode::Live
                    && !matches!(cfg.fit, crate::viewport::FitPolicy::Lock { .. })
                    && inner.w > 0.0
                    && inner.h > 0.0
                    && target != view;
                // Fit / reset restore the home framing (re-arming a
                // `FitPolicy::Contain`); `CenterOn` / `FrameRect`
                // deliberately steer away from it. A *flying* fit/reset
                // defers the re-arm to arrival — the view is off home
                // for the whole flight, and an armed policy would
                // otherwise snap over the animation.
                let rearm = matches!(
                    req,
                    crate::viewport::ViewportRequest::FitContent { .. }
                        | crate::viewport::ViewportRequest::ResetView { .. }
                );
                if rearm && !fly {
                    ui_state.viewport.taken_over.remove(&*node.computed_id);
                } else {
                    ui_state
                        .viewport
                        .taken_over
                        .insert(node.computed_id.to_string());
                }
                if fly {
                    let path = crate::viewport::ZoomPath::new(
                        view_framing(view, inner, origin),
                        view_framing(target, inner, origin),
                    );
                    let ms = (f64::from(path.length()) * VIEWPORT_FLIGHT_MS_PER_UNIT)
                        .clamp(VIEWPORT_FLIGHT_MS_MIN, VIEWPORT_FLIGHT_MS_MAX);
                    ui_state.viewport.flights.insert(
                        node.computed_id.to_string(),
                        crate::state::ViewportFlight {
                            path,
                            started: viewport_clock(ui_state),
                            duration: std::time::Duration::from_secs_f64(ms / 1000.0),
                            rearm_on_arrival: rearm,
                        },
                    );
                } else {
                    // An instant request grounds any flight in progress.
                    ui_state.viewport.flights.remove(&*node.computed_id);
                    view = target;
                }
            } else {
                i += 1;
            }
        }
    }

    // Maintain the declarative fit policy: `Lock` re-fits every pass;
    // `Contain` re-fits until the user (or a `CenterOn`) takes the view
    // over. Recomputing the fit each pass — rather than diffing rects —
    // makes the framing track container resizes *and* content-extent
    // changes for free; with unchanged inputs the fit is bit-identical,
    // so a settled viewport stays put.
    match cfg.fit {
        crate::viewport::FitPolicy::Manual => {}
        crate::viewport::FitPolicy::Contain { padding } => {
            if !ui_state.viewport.taken_over.contains(&*node.computed_id) {
                view = viewport_fit_view(cfg, inner, origin, content, view, padding);
            }
        }
        crate::viewport::FitPolicy::Lock { padding } => {
            // A locked viewport is at its home framing by construction —
            // clear any stray takeover (a `CenterOn` or seeded view that
            // raced the lock) so the at-home readback stays truthful.
            ui_state.viewport.taken_over.remove(&*node.computed_id);
            view = viewport_fit_view(cfg, inner, origin, content, view, padding);
        }
    }

    // Sample any smooth navigation in flight. The eased path owns the
    // view until arrival, which lands on the path's exact endpoint and
    // performs the deferred policy re-arm. (`Settled` mode never creates
    // flights, but snap any that were mid-air when the mode switched.)
    if matches!(cfg.fit, crate::viewport::FitPolicy::Lock { .. }) {
        // A viewport that became `Lock`ed mid-flight is grounded: the
        // lock's fit (applied above) is not free to leave home.
        ui_state.viewport.flights.remove(&*node.computed_id);
    } else if let Some(flight) = ui_state.viewport.flights.get(&*node.computed_id).copied() {
        let t = if flight.duration.is_zero()
            || ui_state.animation.mode == crate::state::AnimationMode::Settled
        {
            1.0
        } else {
            (viewport_clock(ui_state)
                .saturating_duration_since(flight.started)
                .as_secs_f32()
                / flight.duration.as_secs_f32())
            .min(1.0)
        };
        let (cx, cy, w) = flight.path.sample(ease_in_out_cubic(t));
        // Clamp the framing's width to the zoom range *before* deriving
        // the view, so the pan stays coherent with the clamped zoom and
        // the camera center stays on the path when the arc's zoom-out
        // hump exceeds `min_zoom` (the global zoom clamp below would
        // otherwise warp the trajectory toward the content origin).
        let w = w.clamp(
            inner.w / cfg.max_zoom.max(1e-6),
            inner.w / cfg.min_zoom.max(1e-6),
        );
        view = framing_view((cx, cy, w), inner, origin);
        if t >= 1.0 {
            ui_state.viewport.flights.remove(&*node.computed_id);
            if flight.rearm_on_arrival {
                ui_state.viewport.taken_over.remove(&*node.computed_id);
                // Land on the *live* policy fit: the flight's endpoint
                // was resolved at request time, and content or viewport
                // geometry may have changed mid-flight. The policy's own
                // maintenance block already ran this pass (dormant while
                // taken over), so correcting here keeps arrival exact in
                // a single frame. Unchanged inputs re-fit bit-identically.
                if let crate::viewport::FitPolicy::Contain { padding } = cfg.fit {
                    view = viewport_fit_view(cfg, inner, origin, content, view, padding);
                }
            }
        }
    }

    // Clamp zoom to the configured range, then clamp pan per the
    // configured bounds policy so the content can't drift past it.
    view.zoom = view.zoom.clamp(cfg.min_zoom, cfg.max_zoom);
    if let Some(c) = content {
        clamp_viewport_pan(&mut view, cfg.pan_bounds, inner, origin, c);
    }

    // Bake into descendant rects. Identity is a no-op — skip the walk.
    if view != ViewportView::default() {
        transform_viewport_subtree(node, view, origin, ui_state);
    }

    ui_state
        .viewport
        .views
        .insert(node.computed_id.to_string(), view);
    ui_state.viewport.metrics.insert(
        node.computed_id.to_string(),
        crate::state::ViewportMetrics {
            inner,
            content,
            cfg,
        },
    );
}

/// Bounding box of all of `node`'s descendant rects, in content space
/// (the rects as laid out before the viewport transform). `None` when the
/// viewport has no children with rects.
fn viewport_content_bbox(node: &El) -> Option<Rect> {
    let mut acc: Option<Rect> = None;
    for c in &node.children {
        let r = c.computed_rect;
        acc = Some(acc.map_or(r, |a| union_rect(a, r)));
        if let Some(bb) = viewport_content_bbox(c) {
            acc = Some(acc.map_or(bb, |a| union_rect(a, bb)));
        }
    }
    acc
}

/// Smallest rect covering both inputs.
fn union_rect(a: Rect, b: Rect) -> Rect {
    let x = a.x.min(b.x);
    let y = a.y.min(b.y);
    let r = a.right().max(b.right());
    let bot = a.bottom().max(b.bottom());
    Rect::new(x, y, r - x, bot - y)
}

/// Map every descendant rect of a viewport through `view` about `origin`.
/// The viewport node's own rect is left untouched (it is the window).
fn transform_viewport_subtree(
    node: &mut El,
    view: crate::viewport::ViewportView,
    origin: (f32, f32),
    ui_state: &mut UiState,
) {
    for c in &mut node.children {
        let rect = c.computed_rect;
        let (nx, ny) = view.project((rect.x, rect.y), origin);
        c.computed_rect = Rect::new(nx, ny, rect.w * view.zoom, rect.h * view.zoom);
        // `get_mut`, not insert: every keyed node in this subtree went
        // through `set_rect` earlier in the same pass, so the entry
        // exists — this walk only runs as a post-pass over freshly
        // laid-out children (same invariant as `shift_subtree_y`).
        if c.key.is_some()
            && let Some(r) = ui_state.layout.keyed_rects.get_mut(&c.computed_id)
        {
            *r = c.computed_rect;
        }
        transform_viewport_subtree(c, view, origin, ui_state);
    }
}

/// Flight pacing for smooth viewport navigations: wall-clock ms per unit
/// of [`ZoomPath::length`](crate::viewport::ZoomPath::length), and its
/// bounds. ~350 ms/unit lands a typical one-screen flight around half a
/// second; long cross-canvas flights saturate at the cap instead of
/// dragging on. There is deliberately no per-request duration knob
/// (mirroring DOM smooth scrolling).
const VIEWPORT_FLIGHT_MS_PER_UNIT: f64 = 350.0;
const VIEWPORT_FLIGHT_MS_MIN: f64 = 200.0;
const VIEWPORT_FLIGHT_MS_MAX: f64 = 800.0;

/// The clock smooth navigations fly on — `Instant::now()`, unless a test
/// pinned `clock_override` to step flights deterministically.
fn viewport_clock(ui_state: &UiState) -> web_time::Instant {
    ui_state
        .viewport
        .clock_override
        .unwrap_or_else(web_time::Instant::now)
}

/// Cubic ease-in-out over `t ∈ [0, 1]` — soft takeoff and landing on top
/// of the [`ZoomPath`](crate::viewport::ZoomPath)'s constant-perceptual-
/// velocity parameterization (the pairing d3's zoom transitions use).
/// Exact at both endpoints, so arrival still lands bit-exactly.
fn ease_in_out_cubic(t: f32) -> f32 {
    if t < 0.5 {
        4.0 * t * t * t
    } else {
        1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
    }
}

/// A viewport view expressed as a [`ZoomPath`](crate::viewport::ZoomPath)
/// framing `(cx, cy, w)`: the content-space point under the inner rect's
/// center, and the content-space width the viewport shows.
fn view_framing(
    view: crate::viewport::ViewportView,
    inner: Rect,
    origin: (f32, f32),
) -> (f32, f32, f32) {
    let c = view.unproject((inner.center_x(), inner.center_y()), origin);
    (c.0, c.1, inner.w / view.zoom.max(1e-6))
}

/// Inverse of [`view_framing`]: the view that shows framing `(cx, cy, w)`
/// in `inner`.
fn framing_view(
    (cx, cy, w): (f32, f32, f32),
    inner: Rect,
    origin: (f32, f32),
) -> crate::viewport::ViewportView {
    viewport_center_on(inner, origin, inner.w / w.max(1e-6), (cx, cy))
}

/// Resolve one programmatic request to its target view, given the live
/// inner rect / origin / content bbox. `current` carries the zoom for
/// `CenterOn` (and degenerate `FrameRect`s) and is the fallback when
/// `FitContent` has nothing to frame. Pure — the caller decides whether
/// to jump to the target or fly.
fn apply_viewport_request(
    req: &crate::viewport::ViewportRequest,
    cfg: crate::viewport::ViewportConfig,
    inner: Rect,
    origin: (f32, f32),
    content: Option<Rect>,
    current: crate::viewport::ViewportView,
) -> crate::viewport::ViewportView {
    use crate::viewport::{ViewportRequest, ViewportView};
    match req {
        ViewportRequest::ResetView { .. } => ViewportView::default(),
        ViewportRequest::CenterOn { point, .. } => {
            viewport_center_on(inner, origin, current.zoom, *point)
        }
        ViewportRequest::FitContent { padding, .. } => {
            viewport_fit_view(cfg, inner, origin, content, current, *padding)
        }
        ViewportRequest::FrameRect { rect, padding, .. } => {
            viewport_fit_rect(cfg, inner, origin, *rect, current, *padding)
        }
    }
}

/// The fit-to-content framing: the largest zoom (within the configured
/// range) that fits the content bbox inside `inner` with `padding` px of
/// margin, centered. `current` when there is nothing measurable to
/// frame. Shared by [`ViewportRequest::FitContent`] and the sustained
/// [`FitPolicy`](crate::viewport::FitPolicy) framings.
fn viewport_fit_view(
    cfg: crate::viewport::ViewportConfig,
    inner: Rect,
    origin: (f32, f32),
    content: Option<Rect>,
    current: crate::viewport::ViewportView,
    padding: f32,
) -> crate::viewport::ViewportView {
    match content {
        Some(c) if c.w > 0.0 || c.h > 0.0 => {
            viewport_fit_rect(cfg, inner, origin, c, current, padding)
        }
        _ => current,
    }
}

/// The framing for an arbitrary content-space `rect` — the resolve step
/// of [`ViewportRequest::FrameRect`](crate::viewport::ViewportRequest::FrameRect),
/// and the rect-shaped core [`viewport_fit_view`] applies to the content
/// bbox: the largest zoom (within the configured range) that fits `rect`
/// inside `inner` with `padding` px of margin, centered. A rect with one
/// zero dimension fits the other; a fully degenerate rect (no positive
/// dimension) is a point — centered at the current zoom, `CenterOn`
/// semantics.
fn viewport_fit_rect(
    cfg: crate::viewport::ViewportConfig,
    inner: Rect,
    origin: (f32, f32),
    rect: Rect,
    current: crate::viewport::ViewportView,
    padding: f32,
) -> crate::viewport::ViewportView {
    if rect.w <= 0.0 && rect.h <= 0.0 {
        return viewport_center_on(inner, origin, current.zoom, (rect.x, rect.y));
    }
    let avail_w = (inner.w - 2.0 * padding).max(1.0);
    let avail_h = (inner.h - 2.0 * padding).max(1.0);
    let mut zoom = f32::INFINITY;
    if rect.w > 0.0 {
        zoom = zoom.min(avail_w / rect.w);
    }
    if rect.h > 0.0 {
        zoom = zoom.min(avail_h / rect.h);
    }
    if !zoom.is_finite() {
        return current;
    }
    let zoom = zoom.clamp(cfg.min_zoom, cfg.max_zoom);
    viewport_center_on(inner, origin, zoom, (rect.center_x(), rect.center_y()))
}

/// A view at `zoom` whose pan places content-space `point` at the center
/// of the viewport `inner` rect.
fn viewport_center_on(
    inner: Rect,
    origin: (f32, f32),
    zoom: f32,
    point: (f32, f32),
) -> crate::viewport::ViewportView {
    crate::viewport::ViewportView {
        pan: (
            inner.center_x() - origin.0 - zoom * (point.0 - origin.0),
            inner.center_y() - origin.1 - zoom * (point.1 - origin.1),
        ),
        zoom,
    }
}

/// Clamp `view.pan` against the transformed content bbox per the
/// configured [`PanBounds`] policy. See [`clamp_axis_delta`] for the
/// per-axis rule each policy applies.
fn clamp_viewport_pan(
    view: &mut crate::viewport::ViewportView,
    bounds: crate::viewport::PanBounds,
    inner: Rect,
    origin: (f32, f32),
    content: Rect,
) {
    if matches!(bounds, crate::viewport::PanBounds::Free) {
        return;
    }
    let (lx, ty) = view.project((content.x, content.y), origin);
    let w = content.w * view.zoom;
    let h = content.h * view.zoom;
    view.pan.0 += clamp_axis_delta(bounds, lx, lx + w, inner.x, inner.right(), w, inner.w);
    view.pan.1 += clamp_axis_delta(bounds, ty, ty + h, inner.y, inner.bottom(), h, inner.h);
}

/// Pan delta on one axis that brings the content span `[lo, hi]` into the
/// allowed relation with the viewport span `[vlo, vhi]` under `bounds`.
/// Returns `0.0` when already valid.
fn clamp_axis_delta(
    bounds: crate::viewport::PanBounds,
    lo: f32,
    hi: f32,
    vlo: f32,
    vhi: f32,
    size: f32,
    vsize: f32,
) -> f32 {
    use crate::viewport::PanBounds;
    match bounds {
        // Caller short-circuits Free before reaching here; no-op for safety.
        PanBounds::Free => 0.0,
        // Keep the content bbox overlapping the viewport center, so any
        // content point is reachable to mid-frame.
        PanBounds::Center => {
            let vc = 0.5 * (vlo + vhi);
            if lo > vc {
                vc - lo
            } else if hi < vc {
                vc - hi
            } else {
                0.0
            }
        }
        PanBounds::Contain => {
            if size <= vsize {
                // Content fits: keep it inside the viewport.
                if lo < vlo {
                    vlo - lo
                } else if hi > vhi {
                    vhi - hi
                } else {
                    0.0
                }
            } else {
                // Content overflows: don't allow a gutter past either edge.
                if lo > vlo {
                    vlo - lo
                } else if hi < vhi {
                    vhi - hi
                } else {
                    0.0
                }
            }
        }
    }
}

fn scroll_anchor_offset(node: &El, inner: Rect, stored: f32, ui_state: &UiState) -> Option<f32> {
    let anchor = ui_state.scroll.scroll_anchors.get(&*node.computed_id)?;
    // The anchor names an (often unkeyed) descendant by the id recorded
    // last frame; resolve its freshly laid-out rect by path descent. A
    // `None` (the node left the tree) falls back to the stored offset.
    let rect = &find_descendant_rect(node, anchor.node_id.as_str())?;
    if rect.h <= 0.0 {
        return None;
    }
    let rect_point = rect.h * anchor.rect_fraction.clamp(0.0, 1.0);
    let scroll_delta = stored - anchor.resolved_offset;
    let viewport_y = anchor.viewport_y - scroll_delta;
    Some(rect.y - inner.y + rect_point - viewport_y)
}

fn choose_scroll_anchor(node: &El, inner: Rect, offset: f32) -> Option<ScrollAnchor> {
    if inner.h <= 0.0 {
        return None;
    }
    let target_y = inner.y + inner.h * 0.25;
    let mut best = None;
    for child in &node.children {
        choose_scroll_anchor_in_subtree(child, inner, target_y, 1, &mut best);
    }
    let candidate = best?;
    let anchor_y = target_y.clamp(candidate.rect.y, candidate.rect.bottom());
    let rect_fraction = if candidate.rect.h > 0.0 {
        ((anchor_y - candidate.rect.y) / candidate.rect.h).clamp(0.0, 1.0)
    } else {
        0.0
    };
    Some(ScrollAnchor {
        node_id: candidate.node_id,
        rect_fraction,
        viewport_y: anchor_y - inner.y,
        resolved_offset: offset,
    })
}

#[derive(Clone, Debug)]
struct ScrollAnchorCandidate {
    node_id: String,
    rect: Rect,
    distance: f32,
    depth: usize,
}

fn choose_scroll_anchor_in_subtree(
    node: &El,
    inner: Rect,
    target_y: f32,
    depth: usize,
    best: &mut Option<ScrollAnchorCandidate>,
) {
    let rect = node.computed_rect;
    if rect.w > 0.0 && rect.h > 0.0 && rect.bottom() > inner.y && rect.y < inner.bottom() {
        let distance = distance_to_interval(target_y, rect.y, rect.bottom());
        let candidate = ScrollAnchorCandidate {
            node_id: node.computed_id.clone().to_string(),
            rect,
            distance,
            depth,
        };
        let replace = best.as_ref().is_none_or(|current| {
            candidate.distance < current.distance
                || (candidate.distance == current.distance && candidate.depth > current.depth)
                || (candidate.distance == current.distance
                    && candidate.depth == current.depth
                    && candidate.rect.h < current.rect.h)
        });
        if replace {
            *best = Some(candidate);
        }
    }

    if node.scrollable {
        return;
    }
    for child in &node.children {
        choose_scroll_anchor_in_subtree(child, inner, target_y, depth + 1, best);
    }
}

/// Stored offset within this much of the pinned edge counts as "at
/// the edge" for [`crate::tree::PinPolicy`] activation. Wheel deltas
/// are integer pixels, so a half-pixel slack absorbs floating-point
/// rounding without admitting any deliberate user scroll.
const PIN_EPSILON: f32 = 0.5;

/// Decide whether the pin should be engaged this frame, given the
/// previous frame's active flag and reference offset.
///
/// `policy` selects the edge: `End` references the previous frame's
/// `max_offset` (stored in `scroll.pin_prev_max`) and engages when
/// `stored ≈ prev_max`; `Start` references `0` and engages when
/// `stored ≈ 0`. `None` returns `None` so callers can short-circuit.
fn pin_would_be_active(
    node: &El,
    stored: f32,
    _max_offset: f32,
    ui_state: &UiState,
) -> Option<bool> {
    let prev_active = ui_state.scroll.pin_active.get(&*node.computed_id).copied();
    match node.pin_policy {
        crate::tree::PinPolicy::None => None,
        crate::tree::PinPolicy::End => {
            let prev_max = ui_state
                .scroll
                .pin_prev_max
                .get(&*node.computed_id)
                .copied();
            Some(match prev_active {
                None => true,
                Some(prev) => {
                    let prev_max = prev_max.unwrap_or(0.0);
                    if prev && stored < prev_max - PIN_EPSILON {
                        false
                    } else if !prev && prev_max > 0.0 && stored >= prev_max - PIN_EPSILON {
                        true
                    } else {
                        prev
                    }
                }
            })
        }
        crate::tree::PinPolicy::Start => Some(match prev_active {
            None => true,
            Some(prev) => {
                if prev && stored > PIN_EPSILON {
                    false
                } else if !prev && stored <= PIN_EPSILON {
                    true
                } else {
                    prev
                }
            }
        }),
    }
}

/// Apply this node's [`crate::tree::PinPolicy`] to `stored`. Reads the
/// previous frame's bookkeeping from `scroll.pin_active` /
/// `scroll.pin_prev_max` to decide whether the stored offset has moved
/// off the pinned edge since last frame (user wheel / drag /
/// programmatic write), and updates those maps accordingly. Returns
/// the offset that should be clamped + written downstream — the
/// pinned edge (`0` for `Start`, `max_offset` for `End`) when engaged,
/// the input `stored` otherwise.
///
/// First frame for an opted-in container starts pinned, so a freshly
/// mounted `scroll([...]).pin_end()` paints with its tail visible and
/// `scroll([...]).pin_start()` paints (still) with its head visible.
fn resolve_pin(node: &El, stored: f32, max_offset: f32, ui_state: &mut UiState) -> f32 {
    if matches!(node.pin_policy, crate::tree::PinPolicy::None) {
        ui_state.scroll.pin_active.remove(&*node.computed_id);
        ui_state.scroll.pin_prev_max.remove(&*node.computed_id);
        return stored;
    }
    let active = pin_would_be_active(node, stored, max_offset, ui_state).unwrap_or(false);
    ui_state
        .scroll
        .pin_active
        .insert(node.computed_id.to_string(), active);
    match node.pin_policy {
        crate::tree::PinPolicy::End => {
            ui_state
                .scroll
                .pin_prev_max
                .insert(node.computed_id.to_string(), max_offset);
            if active { max_offset } else { stored }
        }
        crate::tree::PinPolicy::Start => {
            // `pin_prev_max` is unused for Start — drop any stale entry
            // (e.g. if the policy was just flipped from End to Start
            // for the same computed_id).
            ui_state.scroll.pin_prev_max.remove(&*node.computed_id);
            if active { 0.0 } else { stored }
        }
        crate::tree::PinPolicy::None => unreachable!(),
    }
}

/// Walk pending `ScrollRequest::EnsureVisible` requests and pop any
/// whose `container_key` resolves to an ancestor of `node`. For each
/// match, write a stored offset that brings the request's content-
/// space `y..y+h` range into the viewport using minimal-displacement
/// semantics (top edge if above, bottom edge if below, leave alone if
/// already inside). The clamp + shift downstream of this call ensures
/// the resulting offset stays inside `[0, max_offset]`.
///
/// Matching is by computed-id prefix on the keyed ancestor — a
/// scroll is "inside" the keyed widget when its id starts with the
/// ancestor's id followed by `.`, the same rule used by
/// [`crate::state::query::target_in_subtree`].
fn resolve_ensure_visible_for_scroll(
    node: &El,
    inner: Rect,
    content_h: f32,
    ui_state: &mut UiState,
) -> bool {
    if ui_state.scroll.pending_requests.is_empty() {
        return false;
    }
    let pending = std::mem::take(&mut ui_state.scroll.pending_requests);
    let mut remaining: Vec<ScrollRequest> = Vec::with_capacity(pending.len());
    let mut wrote = false;
    for req in pending {
        let ScrollRequest::EnsureVisible {
            container_key,
            y,
            h,
        } = &req
        else {
            remaining.push(req);
            continue;
        };
        let Some(ancestor_id) = ui_state.layout.key_index.get(container_key) else {
            // Container hasn't been laid out yet (or its key isn't
            // in this tree). Keep the request for a future frame —
            // dropped at end-of-frame like row requests for
            // missing lists.
            remaining.push(req);
            continue;
        };
        // Match this scroll only if it sits inside the keyed widget.
        // Same prefix rule as `target_in_subtree`.
        let inside = node.computed_id == *ancestor_id
            || node
                .computed_id
                .strip_prefix(ancestor_id.as_ref())
                .is_some_and(|rest| rest.starts_with('.'));
        if !inside {
            remaining.push(req);
            continue;
        }
        let current = ui_state
            .scroll
            .offsets
            .get(&*node.computed_id)
            .copied()
            .unwrap_or(0.0);
        let target_top = *y;
        let target_bottom = *y + *h;
        let viewport_h = inner.h;
        // Minimal-displacement: if the range is fully visible, no
        // change. If it's above the viewport top, scroll up to it.
        // If it's below the viewport bottom, scroll just enough to
        // expose the bottom edge — but never less than 0 or more
        // than `content_h - viewport_h` (the clamp downstream will
        // do that anyway).
        let new_offset = if target_top < current {
            target_top
        } else if target_bottom > current + viewport_h {
            target_bottom - viewport_h
        } else {
            // Already visible: don't override an in-progress
            // manual scroll just because the caret happens to be
            // mid-viewport. Skip this request without disturbing
            // the offset.
            continue;
        };
        // Clamp against the live content extent so we don't write
        // a wildly-out-of-range offset when the request races a
        // layout pass that hasn't yet measured all rows.
        let max = (content_h - viewport_h).max(0.0);
        let new_offset = new_offset.clamp(0.0, max);
        ui_state
            .scroll
            .offsets
            .insert(node.computed_id.to_string(), new_offset);
        wrote = true;
    }
    ui_state.scroll.pending_requests = remaining;
    wrote
}

/// Compute and store the scrollbar thumb + track rects for `node`
/// when the author opted into a visible scrollbar AND content
/// overflows. Both rects are anchored to the right edge of `inner`.
/// The visible thumb is `SCROLLBAR_THUMB_WIDTH` wide and tracks the
/// scroll offset; the track is `SCROLLBAR_HITBOX_WIDTH` wide and
/// covers the full inner height so a press above/below the thumb
/// can page-scroll.
fn write_thumb_rect(
    node: &El,
    inner: Rect,
    content_h: f32,
    max_offset: f32,
    offset: f32,
    ui_state: &mut UiState,
) {
    if !node.scrollbar || max_offset <= 0.0 || inner.h <= 0.0 || content_h <= 0.0 {
        return;
    }
    let thumb_w = crate::tokens::SCROLLBAR_THUMB_WIDTH;
    let track_w = crate::tokens::SCROLLBAR_HITBOX_WIDTH;
    let track_inset = crate::tokens::SCROLLBAR_TRACK_INSET;
    let min_thumb_h = crate::tokens::SCROLLBAR_THUMB_MIN_H;
    let thumb_h = ((inner.h * inner.h / content_h).max(min_thumb_h)).min(inner.h);
    let track_remaining = (inner.h - thumb_h).max(0.0);
    let thumb_y = inner.y + track_remaining * (offset / max_offset);
    // `scrollbar_gutter` reserved a content-free band on the right via
    // extra padding (metrics pass). The thumb belongs *inside* that
    // band, not at the now-narrower content edge — anchor it where the
    // content edge would be without the gutter, i.e. the band's right.
    let edge = if node.scrollbar_gutter {
        inner.right() + crate::tokens::SCROLLBAR_GUTTER
    } else {
        inner.right()
    };
    let thumb_x = edge - thumb_w - track_inset;
    let track_x = edge - track_w - track_inset;
    ui_state.scroll.thumb_rects.insert(
        node.computed_id.to_string(),
        Rect::new(thumb_x, thumb_y, thumb_w, thumb_h),
    );
    ui_state.scroll.thumb_tracks.insert(
        node.computed_id.to_string(),
        Rect::new(track_x, inner.y, track_w, inner.h),
    );
}

fn shift_subtree_y(node: &mut El, dy: f32, ui_state: &mut UiState) {
    node.computed_rect.y += dy;
    if node.key.is_some()
        && let Some(rect) = ui_state.layout.keyed_rects.get_mut(&node.computed_id)
    {
        rect.y += dy;
    }
    // Thumb/track rects exist only for nodes that opted into a visible
    // scrollbar — gate the probes so the common node pays no hashing.
    if node.scrollbar {
        if let Some(thumb) = ui_state.scroll.thumb_rects.get_mut(&*node.computed_id) {
            thumb.y += dy;
        }
        if let Some(track) = ui_state.scroll.thumb_tracks.get_mut(&*node.computed_id) {
            track.y += dy;
        }
    }
    for c in &mut node.children {
        shift_subtree_y(c, dy, ui_state);
    }
}

/// Reusable per-invocation buffers for [`layout_axis`]'s distribution
/// loops and [`size_tree`]'s row two-pass. Both recursions re-enter
/// themselves, so the buffers are pooled (one entry per active
/// recursion level) rather than being a single thread-local set.
/// Before this, every container heap-allocated fresh Vecs per frame
/// (~tens of thousands of allocations at large node counts).
#[derive(Default)]
struct AxisScratch {
    main_sizes: Vec<f32>,
    fill_weights: Vec<Option<f32>>,
    row_slots: Vec<Option<(f32, f32)>>,
}

impl AxisScratch {
    fn take() -> Self {
        AXIS_SCRATCH_POOL
            .with_borrow_mut(|pool| pool.pop())
            .unwrap_or_default()
    }

    fn release(mut self) {
        self.main_sizes.clear();
        self.fill_weights.clear();
        self.row_slots.clear();
        AXIS_SCRATCH_POOL.with_borrow_mut(|pool| {
            // Depth-bounded in practice; the cap only guards pathology.
            if pool.len() < 256 {
                pool.push(self);
            }
        });
    }
}

thread_local! {
    static AXIS_SCRATCH_POOL: std::cell::RefCell<Vec<AxisScratch>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

fn layout_axis(node: &mut El, node_rect: Rect, vertical: bool, ui_state: &mut UiState) {
    let inner = node_rect.inset(node.padding);
    let n = node.children.len();
    if n == 0 {
        return;
    }
    let mut scratch = AxisScratch::take();

    let total_gap = node.gap * n.saturating_sub(1) as f32;
    let main_extent = if vertical { inner.h } else { inner.w };
    let cross_extent = if vertical { inner.w } else { inner.h };

    // `main_size_of` resolves main-axis size directly from each child's
    // own sizing intent and its intrinsic. `Size::Aspect` on the main
    // axis is the one case that needs more context: it derives main
    // from the *resolved cross size*, which means we have to compute
    // cross first for that child only (an inversion of the normal
    // main-then-cross ordering). Cross resolution doesn't depend on
    // main except when cross is also Aspect — that's the degenerate
    // both-Aspect case and falls back to intrinsic via main_size_of.
    let resolve_main = |c: &El, iw: f32, ih: f32| -> MainSize {
        let main_intent = if vertical { c.height } else { c.width };
        if let Size::Aspect(r) = main_intent {
            let cross_intent = if vertical { c.width } else { c.height };
            if !matches!(cross_intent, Size::Aspect(_)) {
                let cross_intrinsic = if vertical { iw } else { ih };
                let cross_size = match cross_intent {
                    Size::Fixed(v) => v,
                    Size::Ch(n) => n * ch_unit(c),
                    Size::Hug | Size::Fill(_) => match node.align {
                        Align::Stretch => cross_extent,
                        Align::Start | Align::Center | Align::End => cross_intrinsic,
                    },
                    Size::Aspect(_) => unreachable!(),
                };
                let cross_size = if vertical {
                    clamp_w(c, cross_size)
                } else {
                    clamp_h(c, cross_size)
                };
                let main = cross_size * r.max(0.0);
                let clamped = if vertical {
                    clamp_h(c, main)
                } else {
                    clamp_w(c, main)
                };
                return MainSize::Resolved(clamped);
            }
        }
        main_size_of(c, iw, ih, vertical)
    };

    // Resolve every child's main size up front. Fill children share
    // the free space by weight, with CSS-flex parity for min/max
    // clamps (freeze/violation vocabulary from CSS Flexbox Level 1
    // §9.7 "Resolving Flexible Lengths"; implementation is ours): a fill whose share violates its clamp is frozen at the
    // clamped size, and the space it freed (max) or stole (min) is
    // re-distributed among the still-flexible fills, iterating until
    // a distribution sticks. Each round computes every hypothetical
    // share against the same `remaining` / weight total, then freezes
    // all of that round's violators at once — freezing as it scans
    // would let an early max-freeze spuriously min-freeze a later
    // sibling against a half-updated distribution.
    let AxisScratch {
        main_sizes,
        fill_weights,
        ..
    } = &mut scratch;
    let mut consumed = 0.0;
    for c in node.children.iter() {
        // Sizing-pass output: the child's measured size at the width
        // this container implies (see `size_tree`).
        let (iw, ih) = c.measured_size;
        match resolve_main(c, iw, ih) {
            MainSize::Resolved(v) => {
                consumed += v;
                main_sizes.push(v);
                fill_weights.push(None);
            }
            MainSize::Fill(w) => {
                main_sizes.push(0.0);
                fill_weights.push(Some(w.max(0.001)));
            }
        }
    }
    let mut remaining = (main_extent - consumed - total_gap).max(0.0);
    loop {
        let flexible_weight: f32 = fill_weights.iter().flatten().sum();
        if flexible_weight == 0.0 {
            break;
        }
        let mut frozen_any = false;
        let mut newly_frozen = 0.0;
        for (i, c) in node.children.iter().enumerate() {
            let Some(w) = fill_weights[i] else { continue };
            let raw = remaining * w / flexible_weight;
            let clamped = if vertical {
                clamp_h(c, raw)
            } else {
                clamp_w(c, raw)
            };
            main_sizes[i] = clamped;
            if clamped != raw {
                fill_weights[i] = None;
                frozen_any = true;
                newly_frozen += clamped;
            }
        }
        if !frozen_any {
            // The flexible fills absorbed all the free space.
            remaining = 0.0;
            break;
        }
        remaining = (remaining - newly_frozen).max(0.0);
    }

    // Free space after children + gaps that the fills could not absorb
    // (no fills, or every fill frozen at its max). This is what
    // justify distributes — mirroring flexbox's leftover free space.
    let free_after_used = remaining;
    let mut cursor = match node.justify {
        Justify::Start => 0.0,
        Justify::Center => free_after_used * 0.5,
        Justify::End => free_after_used,
        Justify::SpaceBetween => 0.0,
    };
    let between_extra = if matches!(node.justify, Justify::SpaceBetween) && n > 1 {
        free_after_used / (n - 1) as f32
    } else {
        0.0
    };
    let scroll_visible = scroll_visible_content_rect(node, inner, vertical, ui_state);

    crate::profile_span!("layout::axis::place");
    for (i, c) in node.children.iter_mut().enumerate() {
        let (iw, ih) = c.measured_size;
        let main_size = main_sizes[i];

        let cross_intent = if vertical { c.width } else { c.height };
        let cross_intrinsic = if vertical { iw } else { ih };
        // CSS-flex parity for cross-axis sizing: `Size::Fixed` is an
        // explicit author override and always wins. Otherwise the
        // parent's `Align` decides — `Stretch` (the column default)
        // stretches non-fixed children to the container, `Center` /
        // `Start` / `End` shrink to intrinsic so the alignment can
        // actually position them. This collapses Hug and Fill on the
        // cross axis (both are "follow align-items"), the same way
        // CSS flex doesn't distinguish between them on the cross axis.
        // `Aspect` derives cross from the already-resolved main. The
        // symmetric case (Aspect on main) is handled by `resolve_main`
        // above, which inverts the ordering for that child only.
        let cross_size = match cross_intent {
            Size::Fixed(v) => v,
            Size::Ch(n) => n * ch_unit(c),
            Size::Aspect(r) => main_size * r,
            Size::Hug | Size::Fill(_) => match node.align {
                Align::Stretch => cross_extent,
                Align::Start | Align::Center | Align::End => cross_intrinsic,
            },
        };
        let cross_size = if vertical {
            clamp_w(c, cross_size)
        } else {
            clamp_h(c, cross_size)
        };

        let cross_off = match node.align {
            Align::Start | Align::Stretch => 0.0,
            Align::Center => (cross_extent - cross_size) * 0.5,
            Align::End => cross_extent - cross_size,
        };

        let c_rect = if vertical {
            Rect::new(inner.x + cross_off, inner.y + cursor, cross_size, main_size)
        } else {
            Rect::new(inner.x + cursor, inner.y + cross_off, main_size, cross_size)
        };
        set_rect(c, c_rect, ui_state);
        if can_prune_scroll_child(c, c_rect, scroll_visible) {
            let nodes = zero_descendant_rects(c, c_rect, ui_state);
            record_pruned_subtree(nodes);
        } else {
            resize_if_width_diverged(c, c_rect.w);
            layout_children(c, c_rect, ui_state);
        }

        cursor += main_size + node.gap + if i + 1 < n { between_extra } else { 0.0 };
    }
    scratch.release();
}

const SCROLL_LAYOUT_PRUNE_OVERSCAN: f32 = 256.0;

fn scroll_visible_content_rect(
    node: &El,
    inner: Rect,
    vertical: bool,
    ui_state: &UiState,
) -> Option<Rect> {
    if !vertical || !node.scrollable || !matches!(node.pin_policy, crate::tree::PinPolicy::None) {
        return None;
    }
    let offset = ui_state
        .scroll
        .offsets
        .get(&*node.computed_id)
        .copied()
        .unwrap_or(0.0)
        .max(0.0);
    Some(Rect::new(
        inner.x,
        inner.y + offset - SCROLL_LAYOUT_PRUNE_OVERSCAN,
        inner.w,
        inner.h + 2.0 * SCROLL_LAYOUT_PRUNE_OVERSCAN,
    ))
}

fn can_prune_scroll_child(child: &El, child_rect: Rect, visible: Option<Rect>) -> bool {
    let Some(visible) = visible else {
        return false;
    };
    child_rect.intersect(visible).is_none() && subtree_is_layout_confined(child)
}

/// Also used by draw-op emission's sub-pixel subtree gate: a confined
/// subtree cannot paint outside its layout rect.
pub(crate) fn subtree_is_layout_confined(node: &El) -> bool {
    if node.translate != (0.0, 0.0)
        || node.scale != 1.0
        || node.shadow > 0.0
        || node.paint_overflow != Sides::zero()
        || node.hit_overflow != Sides::zero()
        || node.layout_override.is_some()
        || node.virtual_items.is_some()
    {
        return false;
    }
    node.children.iter().all(subtree_is_layout_confined)
}

fn zero_descendant_rects(node: &mut El, rect: Rect, ui_state: &mut UiState) -> u64 {
    let mut count = 0;
    let zero = Rect::new(rect.x, rect.y, 0.0, 0.0);
    for child in &mut node.children {
        set_rect(child, zero, ui_state);
        count += 1 + zero_descendant_rects(child, zero, ui_state);
    }
    count
}

fn record_pruned_subtree(nodes: u64) {
    PRUNE_STATS.with(|stats| {
        let mut stats = stats.borrow_mut();
        stats.subtrees += 1;
        stats.nodes += nodes;
    });
}

enum MainSize {
    Resolved(f32),
    Fill(f32),
}

fn main_size_of(c: &El, iw: f32, ih: f32, vertical: bool) -> MainSize {
    let s = if vertical { c.height } else { c.width };
    let intr = if vertical { ih } else { iw };
    let clamp = |v: f32| {
        if vertical {
            clamp_h(c, v)
        } else {
            clamp_w(c, v)
        }
    };
    match s {
        Size::Fixed(v) => MainSize::Resolved(clamp(v)),
        Size::Ch(n) => MainSize::Resolved(clamp(n * ch_unit(c))),
        Size::Hug => MainSize::Resolved(clamp(intr)),
        Size::Fill(w) => MainSize::Fill(w),
        // Main-axis Aspect needs the resolved cross size to compute
        // `cross * r`. That requires inverting the normal main-then-
        // cross order and is handled by `layout_axis`'s `resolve_main`
        // closure. If we ever reach this arm (e.g. from a path that
        // bypasses `resolve_main`), fall back to intrinsic so the El
        // still has a finite measure.
        Size::Aspect(_) => MainSize::Resolved(clamp(intr)),
    }
}

/// Resolve an overlay child's rect within `parent`.
///
/// `clamp_to_parent` caps a `Hug` axis at the parent's extent
/// (`intrinsic.min(parent)`) — correct for a centered modal, which
/// shouldn't exceed the screen. A `viewport()` passes `false`: its
/// content sizes to full intrinsic and the pan/zoom transform reveals
/// the part past the frame (issue #112). Either way the node's own
/// `clamp_w`/`clamp_h` (explicit min/max) still apply.
fn overlay_rect(
    c: &El,
    parent: Rect,
    align: Align,
    justify: Justify,
    clamp_to_parent: bool,
) -> Rect {
    // On a `Hug` axis, full intrinsic unless the caller wants it capped
    // at the parent rect.
    let hug_w = |iw: f32| {
        if clamp_to_parent {
            iw.min(parent.w)
        } else {
            iw
        }
    };
    let hug_h = |ih: f32| {
        if clamp_to_parent {
            ih.min(parent.h)
        } else {
            ih
        }
    };
    // Sizing-pass output: `size_tree` measured this child at the
    // overlay's inner width, so wrap-text descendants already reserved
    // the height they will paint at (the Fixed-width modal-paragraph
    // shape the old per-child constrained re-measure handled).
    let (iw, ih) = c.measured_size;
    // Overlay isn't main/cross-asymmetric, so Aspect can resolve on
    // either axis here. Resolve the non-Aspect axis first, then derive
    // the Aspect axis. If both are Aspect (degenerate), fall back to
    // intrinsic for both.
    let (w, h) = match (c.width, c.height) {
        (Size::Aspect(_), Size::Aspect(_)) => (hug_w(iw), hug_h(ih)),
        (Size::Aspect(r), _) => {
            let h = match c.height {
                Size::Fixed(v) => v,
                Size::Ch(n) => n * ch_unit(c),
                Size::Hug => hug_h(ih),
                Size::Fill(_) => parent.h,
                Size::Aspect(_) => unreachable!(),
            };
            (h * r, h)
        }
        (_, Size::Aspect(r)) => {
            let w = match c.width {
                Size::Fixed(v) => v,
                Size::Ch(n) => n * ch_unit(c),
                Size::Hug => hug_w(iw),
                Size::Fill(_) => parent.w,
                Size::Aspect(_) => unreachable!(),
            };
            (w, w * r)
        }
        _ => {
            let w = match c.width {
                Size::Fixed(v) => v,
                Size::Ch(n) => n * ch_unit(c),
                Size::Hug => hug_w(iw),
                Size::Fill(_) => parent.w,
                Size::Aspect(_) => unreachable!(),
            };
            let h = match c.height {
                Size::Fixed(v) => v,
                Size::Ch(n) => n * ch_unit(c),
                Size::Hug => hug_h(ih),
                Size::Fill(_) => parent.h,
                Size::Aspect(_) => unreachable!(),
            };
            (w, h)
        }
    };
    let w = clamp_w(c, w);
    let h = clamp_h(c, h);
    let x = match align {
        Align::Start | Align::Stretch => parent.x,
        Align::Center => parent.x + (parent.w - w) * 0.5,
        Align::End => parent.right() - w,
    };
    let y = match justify {
        Justify::Start | Justify::SpaceBetween => parent.y,
        Justify::Center => parent.y + (parent.h - h) * 0.5,
        Justify::End => parent.bottom() - h,
    };
    Rect::new(x, y, w, h)
}

/// Intrinsic (width, height) for hugging layouts. On-demand measure
/// for app code and [`LayoutCtx::measure`]; the layout pass itself
/// sizes the whole tree in one recursion ([`size_tree`]) and never
/// calls this.
pub fn intrinsic(c: &El) -> (f32, f32) {
    intrinsic_constrained(c, None)
}

fn intrinsic_constrained(c: &El, available_width: Option<f32>) -> (f32, f32) {
    // A node's own Fixed width beats whatever the ancestor chain has
    // available: layout will resolve the node at exactly that width,
    // so measuring at any other width makes Hug ancestors disagree
    // with the final wrap of text descendants (issue #47).
    let available_width = match c.width {
        Size::Fixed(v) => Some(v),
        _ => available_width,
    };
    apply_aspect(
        c,
        available_width,
        intrinsic_constrained_uncached(c, available_width),
    )
}

/// The layout pass's single sizing recursion: measure `node` under
/// `available_width` and store the result in [`El::measured_size`] for
/// the placement pass to consume — for the node and its whole subtree,
/// visiting each node exactly once per frame.
///
/// Semantics mirror [`intrinsic_constrained`] (same leaf rules, same
/// per-axis derivation of child constraints), with two intentional
/// differences: results are written in-node, and `layout_override`
/// children are sized unconstrained so `LayoutCtx::measure` and the
/// place pass have naturals to read (`layout_custom` re-sizes a child
/// whose assigned rect width diverges from its natural).
///
/// This replaces the retired per-frame intrinsic cache: the old place
/// walk re-entered the measure recursion from every ancestor level,
/// and each Hug/Fill boundary re-measured its whole subtree at a new
/// width (~1.2–3 full measures per node on card-heavy trees).
fn size_tree(node: &mut El, available_width: Option<f32>) -> (f32, f32) {
    SIZING_VISITS.with(|c| c.set(c.get() + 1));
    // Own Fixed width beats available — same rule as
    // `intrinsic_constrained` (issue #47). `Ch` resolves the same way
    // (the deleted place-side `child_intrinsic` did this); the main
    // tree has Ch rewritten to Fixed by `apply_size_rewrites`, but
    // virtual-list rows realized mid-place never pass through that
    // rewrite.
    let available_width = match node.width {
        Size::Fixed(v) => Some(v),
        Size::Ch(n) => Some(n * ch_unit(node)),
        _ => available_width,
    };
    let inner = size_tree_inner(node, available_width);
    let size = apply_aspect(node, available_width, inner);
    node.measured_size = size;
    // An unconstrained subtree's measures assume its own natural
    // width — placement at exactly that width needs no re-size.
    node.sized_at_width = available_width.unwrap_or(size.0);
    // Does any measure below here depend on the available width?
    // Wrap text and inline paragraphs re-flow; Aspect derives one
    // axis from constraint-dependent inputs; custom layouts and
    // virtual lists are opaque. Everything else (nowrap text, icons,
    // images, math, fixed boxes) measures identically at any width,
    // so a placed-width divergence can skip the re-size.
    node.width_sensitive = (node.text.is_some() && matches!(node.text_wrap, TextWrap::Wrap))
        || matches!(node.kind, Kind::Inlines)
        || node.layout_override.is_some()
        || node.virtual_items.is_some()
        || matches!(node.width, Size::Aspect(_))
        || matches!(node.height, Size::Aspect(_))
        || node.children.iter().any(|c| c.width_sensitive);
    size
}

/// Re-run the sizing pass on a placed child whose resolved rect width
/// diverged from the width its stored measures assume — min/max clamp
/// freezing in the fill distribution, a stretched-then-clamped cross
/// size, a custom layout assigning a non-natural rect. The old place
/// walk re-measured every subtree implicitly; this hook confines that
/// adaptation to the boundaries where widths actually moved. Childless
/// leaves skip it: their stored measure isn't re-read after placement
/// (paint wraps text at the final rect itself).
#[inline]
fn resize_if_width_diverged(c: &mut El, final_w: f32) {
    if c.width_sensitive && !c.children.is_empty() && (final_w - c.sized_at_width).abs() > 0.5 {
        size_tree(c, Some(final_w));
    }
}

fn size_tree_inner(node: &mut El, available_width: Option<f32>) -> (f32, f32) {
    if let Some(size) = leaf_intrinsic(node, available_width) {
        if node.layout_override.is_some() {
            // Custom-layout children measure unconstrained — the same
            // naturals the old on-demand `intrinsic(child)` produced
            // for `LayoutCtx::measure`. `layout_custom` re-sizes any
            // child whose assigned rect width differs.
            for ch in &mut node.children {
                size_tree(ch, None);
            }
        } else if !node.children.is_empty()
            && node.virtual_items.is_none()
            && !matches!(node.kind, Kind::Inlines)
        {
            // Content-bearing Els (text / icon / image / math) can
            // still carry children: their own measure ignores them,
            // but placement lays them out inside the node's rect per
            // its axis like any container. Size them at the node's
            // measured width. (Inlines children are zero-rect
            // pseudo-nodes; virtual rows are realized and sized during
            // placement.)
            size_tree_children(node, Some(size.0));
        }
        return size;
    }
    size_tree_children(node, available_width)
}

/// The container branches of the sizing recursion: size every child
/// and aggregate this node's own measure from theirs. Content-bearing
/// leaves reuse it for its child-sizing side effect only.
fn size_tree_children(node: &mut El, available_width: Option<f32>) -> (f32, f32) {
    match node.axis {
        Axis::Overlay => {
            let child_available =
                available_width.map(|w| (w - node.padding.left - node.padding.right).max(0.0));
            let mut w: f32 = 0.0;
            let mut h: f32 = 0.0;
            for ch in &mut node.children {
                // Width derives from height for an Aspect child — the
                // old place-side `overlay_rect` deliberately measured
                // those unconstrained so text wrap isn't pre-capped at
                // the overlay width; `apply_aspect` overrides the
                // derived axis regardless.
                let ca = if matches!(ch.width, Size::Aspect(_)) {
                    None
                } else {
                    child_available
                };
                let (cw, chh) = size_tree(ch, ca);
                w = w.max(cw);
                h = h.max(chh);
            }
            apply_min(
                node,
                w + node.padding.left + node.padding.right,
                h + node.padding.top + node.padding.bottom,
            )
        }
        Axis::Column => {
            let mut w: f32 = 0.0;
            let mut h: f32 = node.padding.top + node.padding.bottom;
            let n = node.children.len();
            let child_available =
                available_width.map(|w| (w - node.padding.left - node.padding.right).max(0.0));
            for (i, ch) in node.children.iter_mut().enumerate() {
                let (cw, chh) = size_tree(ch, child_available);
                w = w.max(cw);
                h += chh;
                if i + 1 < n {
                    h += node.gap;
                }
            }
            apply_min(node, w + node.padding.left + node.padding.right, h)
        }
        Axis::Row => {
            // Two-pass measurement so that wrappable Fill children see
            // the width they will actually be laid out at (the
            // `Overflow B=N` shape): Fixed and Hug children measure
            // unconstrained first, then the leftover distributes among
            // Fill children by weight and each measures at its share.
            // The shares are the same simple weight split the place
            // pass starts from; min/max clamp freezing there can move
            // a clamped fill's final rect off its measured width — a
            // pre-existing approximation kept as-is.
            let n = node.children.len();
            let total_gap = node.gap * n.saturating_sub(1) as f32;
            let inner_available = available_width
                .map(|w| (w - node.padding.left - node.padding.right - total_gap).max(0.0));

            let mut scratch = AxisScratch::take();
            let mut consumed: f32 = 0.0;
            let mut fill_weight_total: f32 = 0.0;
            for ch in &mut node.children {
                match ch.width {
                    Size::Fill(w) => {
                        fill_weight_total += w.max(0.001);
                        scratch.row_slots.push(None);
                    }
                    _ => {
                        let (cw, chh) = size_tree(ch, None);
                        consumed += cw;
                        scratch.row_slots.push(Some((cw, chh)));
                    }
                }
            }

            let fill_remaining = inner_available.map(|av| (av - consumed).max(0.0));
            let mut w_total: f32 = node.padding.left + node.padding.right;
            let mut h_max: f32 = 0.0;
            for (i, ch) in node.children.iter_mut().enumerate() {
                let (cw, chh) = match scratch.row_slots[i] {
                    Some(rc) => rc,
                    None => match (fill_remaining, fill_weight_total > 0.0) {
                        (Some(av), true) => {
                            let weight = match ch.width {
                                Size::Fill(w) => w.max(0.001),
                                _ => 1.0,
                            };
                            size_tree(ch, Some(av * weight / fill_weight_total))
                        }
                        _ => size_tree(ch, None),
                    },
                };
                w_total += cw;
                if i + 1 < n {
                    w_total += node.gap;
                }
                h_max = h_max.max(chh);
            }
            scratch.release();
            apply_min(
                node,
                w_total,
                h_max + node.padding.top + node.padding.bottom,
            )
        }
    }
}

/// Apply `Size::Aspect` to a freshly-measured intrinsic by deriving the
/// aspect-locked axis from the other axis. Runs after the inner intrinsic
/// pass so it composes with any content type (image, text, container).
///
/// When the *other* axis is `Fill`, the layout-time size of that axis is
/// the parent's available extent, not the El's inner intrinsic. Using the
/// inner intrinsic would let a hugging parent under-size and the Aspect-
/// derived axis would then overflow at paint. Prefer `available_width`
/// for Fill width; we don't currently plumb available_height, so a Fill
/// height + Aspect width pairing falls back to inner intrinsic.
///
/// Both axes Aspect is degenerate — fall back to the inner intrinsic so
/// the El still has a finite measure. Negative ratios are clamped to zero
/// for the same reason.
fn apply_aspect(c: &El, available_width: Option<f32>, (iw, ih): (f32, f32)) -> (f32, f32) {
    match (c.width, c.height) {
        (Size::Aspect(_), Size::Aspect(_)) => (iw, ih),
        (Size::Aspect(r), _) => {
            // Basis axis is height; ih is already clamped by apply_min.
            // Clamp the derived width against the El's own min/max so
            // a hugging parent sees the intrinsic that layout will
            // actually paint at.
            (clamp_w(c, ih * r.max(0.0)), ih)
        }
        (_, Size::Aspect(r)) => {
            let raw_basis = match c.width {
                Size::Fixed(v) => v,
                Size::Ch(n) => n * ch_unit(c),
                Size::Fill(_) => available_width.unwrap_or(iw),
                Size::Hug | Size::Aspect(_) => iw,
            };
            // Mirror the layout-time ordering in `resolve_main`: clamp
            // the basis by the *basis* axis's min/max first, then derive
            // the other axis and clamp by its own min/max.
            let basis = clamp_w(c, raw_basis);
            (iw, clamp_h(c, basis * r.max(0.0)))
        }
        _ => (iw, ih),
    }
}

fn intrinsic_constrained_uncached(c: &El, available_width: Option<f32>) -> (f32, f32) {
    if let Some(size) = leaf_intrinsic(c, available_width) {
        return size;
    }
    container_intrinsic(c, available_width)
}

/// Measurement for every non-container case — custom layouts, virtual
/// lists, inline paragraphs, math, icons, images, text. Returns `None`
/// for plain containers (column/row/overlay), whose measurement
/// recurses. Shared verbatim between the on-demand
/// [`intrinsic_constrained`] recursion and the layout pass's
/// [`size_tree`] recursion so leaf semantics cannot drift apart.
fn leaf_intrinsic(c: &El, available_width: Option<f32>) -> Option<(f32, f32)> {
    if c.layout_override.is_some() {
        // Custom-layout nodes don't define an intrinsic. Authors must
        // size them with `Fixed` or `Fill` on both axes; the returned
        // (0.0, 0.0) is replaced by `apply_min` for `Fixed` and is
        // unread for `Fill` (parent's distribution decides).
        if matches!(c.width, Size::Hug) || matches!(c.height, Size::Hug) {
            panic!(
                "layout_override on {:?} requires Size::Fixed or Size::Fill on both axes; \
                 Size::Hug is not supported for custom layouts",
                c.computed_id,
            );
        }
        return Some(apply_min(c, 0.0, 0.0));
    }
    if c.virtual_items.is_some() {
        // VirtualList sizes the whole viewport (the parent decides) and
        // realizes only on-screen rows. Hug-sizing it would mean
        // "shrink to fit all rows", defeating virtualization. Same
        // shape as the layout_override guard.
        if matches!(c.width, Size::Hug) || matches!(c.height, Size::Hug) {
            panic!(
                "virtual_list on {:?} requires Size::Fixed or Size::Fill on both axes; \
                 Size::Hug would defeat virtualization",
                c.computed_id,
            );
        }
        return Some(apply_min(c, 0.0, 0.0));
    }
    if matches!(c.kind, Kind::Inlines) {
        return Some(inline_paragraph_intrinsic(c, available_width));
    }
    if matches!(c.kind, Kind::HardBreak) {
        // HardBreak is meaningful only inside Inlines (where draw_ops
        // encodes it as `\n` in the attributed text). Outside Inlines
        // it's a no-op layout-wise.
        return Some(apply_min(c, 0.0, 0.0));
    }
    if matches!(c.kind, Kind::Math) {
        if let Some(expr) = &c.math {
            let layout = crate::math::layout_math(expr, c.font_size, c.math_display);
            return Some(apply_min(
                c,
                layout.width + c.padding.left + c.padding.right,
                layout.height() + c.padding.top + c.padding.bottom,
            ));
        }
        return Some(apply_min(c, 0.0, 0.0));
    }
    if c.icon.is_some() {
        return Some(apply_min(
            c,
            c.font_size + c.padding.left + c.padding.right,
            c.font_size + c.padding.top + c.padding.bottom,
        ));
    }
    if let Some(img) = &c.image {
        // Natural pixel size as a logical-pixel intrinsic. Authors who
        // want a different sized box set `.width()` / `.height()`;
        // the projection inside that box is decided by `image_fit`.
        let w = img.width() as f32 + c.padding.left + c.padding.right;
        let h = img.height() as f32 + c.padding.top + c.padding.bottom;
        return Some(apply_min(c, w, h));
    }
    if let Some(text) = &c.text {
        let content_available = match c.text_wrap {
            TextWrap::NoWrap => None,
            TextWrap::Wrap => available_width
                .or(match c.width {
                    Size::Fixed(v) => Some(v),
                    Size::Ch(n) => Some(n * ch_unit(c)),
                    // Aspect-on-text would be circular (text height
                    // depends on wrap width which would depend on
                    // text height). Treat like Hug — no wrap cap.
                    Size::Fill(_) | Size::Hug | Size::Aspect(_) => None,
                })
                .map(|w| (w - c.padding.left - c.padding.right).max(1.0)),
        };
        let display = display_text_for_measure(c, text, content_available);
        let layout = text_metrics::layout_text_with_line_height_and_family(
            &display,
            c.font_size,
            c.line_height,
            c.font_family,
            c.font_weight,
            c.font_mono,
            c.text_tabular_numerals,
            c.text_letter_spacing,
            c.text_wrap,
            content_available,
        );
        let w = match (content_available, c.width) {
            (Some(available), Size::Hug | Size::Aspect(_)) => {
                let unwrapped = text_metrics::layout_text_with_family(
                    text,
                    c.font_size,
                    c.font_family,
                    c.font_weight,
                    c.font_mono,
                    c.text_tabular_numerals,
                    TextWrap::NoWrap,
                    None,
                );
                unwrapped.width.min(available) + c.padding.left + c.padding.right
            }
            (Some(available), Size::Fixed(_) | Size::Fill(_) | Size::Ch(_)) => {
                available + c.padding.left + c.padding.right
            }
            (None, _) => layout.width + c.padding.left + c.padding.right,
        };
        let h = layout.height + c.padding.top + c.padding.bottom;
        return Some(apply_min(c, w, h));
    }
    None
}

/// On-demand container measurement for [`intrinsic_constrained`] —
/// recurses immutably; the layout pass uses [`size_tree_inner`]'s
/// storing twin of these branches instead.
fn container_intrinsic(c: &El, available_width: Option<f32>) -> (f32, f32) {
    match c.axis {
        Axis::Overlay => {
            let mut w: f32 = 0.0;
            let mut h: f32 = 0.0;
            for ch in &c.children {
                let child_available =
                    available_width.map(|w| (w - c.padding.left - c.padding.right).max(0.0));
                let (cw, chh) = intrinsic_constrained(ch, child_available);
                w = w.max(cw);
                h = h.max(chh);
            }
            apply_min(
                c,
                w + c.padding.left + c.padding.right,
                h + c.padding.top + c.padding.bottom,
            )
        }
        Axis::Column => {
            let mut w: f32 = 0.0;
            let mut h: f32 = c.padding.top + c.padding.bottom;
            let n = c.children.len();
            let child_available =
                available_width.map(|w| (w - c.padding.left - c.padding.right).max(0.0));
            for (i, ch) in c.children.iter().enumerate() {
                let (cw, chh) = intrinsic_constrained(ch, child_available);
                w = w.max(cw);
                h += chh;
                if i + 1 < n {
                    h += c.gap;
                }
            }
            apply_min(c, w + c.padding.left + c.padding.right, h)
        }
        Axis::Row => {
            // Two-pass measurement so that wrappable Fill children see
            // the width they will actually be laid out at. Without
            // this, a `Size::Fill` paragraph inside a row falls through
            // `inline_paragraph_intrinsic`'s `available_width` fallback
            // with `None` and reports its unwrapped single-line height
            // — the row then under-reserves vertical space and the
            // wrapped text overflows downward into the next row. This
            // mirrors how `layout_axis` (the runtime pass) already
            // splits Resolved vs. Fill main-axis sizing.
            let n = c.children.len();
            let total_gap = c.gap * n.saturating_sub(1) as f32;
            let inner_available = available_width
                .map(|w| (w - c.padding.left - c.padding.right - total_gap).max(0.0));

            // First pass: Fixed and Hug children measure unconstrained.
            // Fixed-width wrappable children self-resolve their wrap
            // width via `inline_paragraph_intrinsic`'s own Fixed
            // fallback; Hug children take their natural width. We only
            // need to feed an explicit available width to Fill.
            let mut consumed: f32 = 0.0;
            let mut fill_weight_total: f32 = 0.0;
            let mut sizes: Vec<Option<(f32, f32)>> = Vec::with_capacity(n);
            for ch in &c.children {
                match ch.width {
                    Size::Fill(w) => {
                        fill_weight_total += w.max(0.001);
                        sizes.push(None);
                    }
                    _ => {
                        let (cw, chh) = intrinsic(ch);
                        consumed += cw;
                        sizes.push(Some((cw, chh)));
                    }
                }
            }

            // Second pass: distribute the leftover among Fill children
            // by weight and remeasure each with its share. Without an
            // available_width hint (row inside a Hug ancestor with no
            // outer constraint) we fall back to unconstrained
            // measurement — same lossy shape as the prior code, but
            // limited to the case where there's genuinely no width to
            // distribute.
            let fill_remaining = inner_available.map(|av| (av - consumed).max(0.0));
            let mut w_total: f32 = c.padding.left + c.padding.right;
            let mut h_max: f32 = 0.0;
            for (i, (ch, slot)) in c.children.iter().zip(sizes).enumerate() {
                let (cw, chh) = match slot {
                    Some(rc) => rc,
                    None => match (fill_remaining, fill_weight_total > 0.0) {
                        (Some(av), true) => {
                            let weight = match ch.width {
                                Size::Fill(w) => w.max(0.001),
                                _ => 1.0,
                            };
                            intrinsic_constrained(ch, Some(av * weight / fill_weight_total))
                        }
                        _ => intrinsic(ch),
                    },
                };
                w_total += cw;
                if i + 1 < n {
                    w_total += c.gap;
                }
                h_max = h_max.max(chh);
            }
            apply_min(c, w_total, h_max + c.padding.top + c.padding.bottom)
        }
    }
}

pub(crate) fn text_layout(
    c: &El,
    available_width: Option<f32>,
) -> Option<text_metrics::TextLayout> {
    let text = c.text.as_ref()?;
    let content_available = match c.text_wrap {
        TextWrap::NoWrap => None,
        TextWrap::Wrap => available_width
            .or(match c.width {
                Size::Fixed(v) => Some(v),
                Size::Ch(n) => Some(n * ch_unit(c)),
                Size::Fill(_) | Size::Hug | Size::Aspect(_) => None,
            })
            .map(|w| (w - c.padding.left - c.padding.right).max(1.0)),
    };
    let display = display_text_for_measure(c, text, content_available);
    Some(text_metrics::layout_text_with_line_height_and_family(
        &display,
        c.font_size,
        c.line_height,
        c.font_family,
        c.font_weight,
        c.font_mono,
        c.text_tabular_numerals,
        c.text_letter_spacing,
        c.text_wrap,
        content_available,
    ))
}

fn display_text_for_measure(c: &El, text: &str, available_width: Option<f32>) -> String {
    if let (TextWrap::Wrap, Some(max_lines), Some(width)) =
        (c.text_wrap, c.text_max_lines, available_width)
    {
        text_metrics::clamp_text_to_lines_with_family(
            text,
            c.font_size,
            c.font_family,
            c.font_weight,
            c.font_mono,
            width,
            max_lines.get() as usize,
        )
    } else {
        text.to_string()
    }
}

fn apply_min(c: &El, mut w: f32, mut h: f32) -> (f32, f32) {
    if let Size::Fixed(v) = c.width {
        w = v;
    }
    if let Size::Fixed(v) = c.height {
        h = v;
    }
    (clamp_w(c, w), clamp_h(c, h))
}

/// Apply [`El::min_width`] / [`El::max_width`] to a resolved width,
/// matching CSS's `min-width` over `max-width` precedence (when both
/// constraints conflict, the lower bound wins). Also clamps to a
/// non-negative result so a zero-padding Hug never reports a negative
/// intrinsic.
pub(crate) fn clamp_w(c: &El, mut w: f32) -> f32 {
    if let Some(max_w) = c.max_width {
        w = w.min(max_w);
    }
    if let Some(min_w) = c.min_width {
        w = w.max(min_w);
    }
    w.max(0.0)
}

/// Height-axis companion to [`clamp_w`].
pub(crate) fn clamp_h(c: &El, mut h: f32) -> f32 {
    if let Some(max_h) = c.max_height {
        h = h.min(max_h);
    }
    if let Some(min_h) = c.min_height {
        h = h.max(min_h);
    }
    h.max(0.0)
}

/// Approximate intrinsic measurement for `Kind::Inlines` paragraphs.
///
/// The paragraph paints through cosmic-text's rich-text shaping (which
/// resolves bold/italic/mono runs against fontdb), but layout needs a
/// width and height *before* we get to the renderer. We concatenate
/// the runs' text into one string and call `text_metrics::layout_text`
/// at the dominant font size — same approximation the lint pass uses
/// for single-style text. Bold/italic widths are slightly different
/// from regular; for body-text paragraphs that difference is well
/// under one wrap-line and we accept it. If a fixture wraps within
/// 1-2 characters of a boundary the rendered glyphs may straddle the
/// laid-out rect by a fraction of a glyph.
fn inline_paragraph_intrinsic(node: &El, available_width: Option<f32>) -> (f32, f32) {
    if node.children.iter().any(|c| matches!(c.kind, Kind::Math)) {
        return inline_mixed_intrinsic(node, available_width);
    }
    let concat = concat_inline_text(&node.children);
    let size = inline_paragraph_size(node);
    let line_height = inline_paragraph_line_height(node);
    let content_available = match node.text_wrap {
        TextWrap::NoWrap => None,
        TextWrap::Wrap => available_width
            .or(match node.width {
                Size::Fixed(v) => Some(v),
                Size::Ch(n) => Some(n * ch_unit(node)),
                Size::Fill(_) | Size::Hug | Size::Aspect(_) => None,
            })
            .map(|w| (w - node.padding.left - node.padding.right).max(1.0)),
    };
    let layout = text_metrics::layout_text_with_line_height_and_family(
        &concat,
        size,
        line_height,
        node.font_family,
        FontWeight::Regular,
        false,
        false,
        0.0,
        node.text_wrap,
        content_available,
    );
    let w = match (content_available, node.width) {
        (Some(available), Size::Hug | Size::Aspect(_)) => {
            let unwrapped = text_metrics::layout_text_with_line_height_and_family(
                &concat,
                size,
                line_height,
                node.font_family,
                FontWeight::Regular,
                false,
                false,
                0.0,
                TextWrap::NoWrap,
                None,
            );
            unwrapped.width.min(available) + node.padding.left + node.padding.right
        }
        (Some(available), Size::Fixed(_) | Size::Fill(_) | Size::Ch(_)) => {
            available + node.padding.left + node.padding.right
        }
        (None, _) => layout.width + node.padding.left + node.padding.right,
    };
    let h = layout.height + node.padding.top + node.padding.bottom;
    apply_min(node, w, h)
}

fn inline_mixed_intrinsic(node: &El, available_width: Option<f32>) -> (f32, f32) {
    let wrap_width = match node.text_wrap {
        TextWrap::Wrap => available_width.or(match node.width {
            Size::Fixed(v) => Some(v),
            Size::Ch(n) => Some(n * ch_unit(node)),
            Size::Fill(_) | Size::Hug | Size::Aspect(_) => None,
        }),
        TextWrap::NoWrap => None,
    }
    .map(|w| (w - node.padding.left - node.padding.right).max(1.0));

    let mut breaker = crate::text::inline_mixed::MixedInlineBreaker::new(
        node.text_wrap,
        wrap_width,
        node.font_size * 0.82,
        node.font_size * 0.22,
        node.line_height,
    );

    for child in &node.children {
        match child.kind {
            Kind::HardBreak => {
                breaker.finish_line();
                continue;
            }
            Kind::Text => {
                let text = child.text.as_deref().unwrap_or("");
                for chunk in inline_text_chunks(text) {
                    let is_space = chunk.chars().all(char::is_whitespace);
                    if breaker.skips_leading_space(is_space) {
                        continue;
                    }
                    let (w, ascent, descent) = inline_text_chunk_metrics(child, chunk);
                    if breaker.wraps_before(is_space, w) {
                        breaker.finish_line();
                    }
                    if breaker.skips_overflowing_space(is_space, w) {
                        continue;
                    }
                    breaker.push(w, ascent, descent);
                }
                continue;
            }
            _ => {}
        }
        let (w, ascent, descent) = inline_child_metrics(child);
        if breaker.wraps_before(false, w) {
            breaker.finish_line();
        }
        breaker.push(w, ascent, descent);
    }
    let measurement = breaker.finish();
    let w = measurement.width + node.padding.left + node.padding.right;
    let h = measurement.height + node.padding.top + node.padding.bottom;
    apply_min(node, w, h)
}

fn inline_text_chunks(text: &str) -> Vec<&str> {
    let mut chunks = Vec::new();
    let mut start = 0;
    let mut last_space = None;
    for (i, ch) in text.char_indices() {
        let is_space = ch.is_whitespace();
        match last_space {
            None => last_space = Some(is_space),
            Some(prev) if prev != is_space => {
                chunks.push(&text[start..i]);
                start = i;
                last_space = Some(is_space);
            }
            _ => {}
        }
    }
    if start < text.len() {
        chunks.push(&text[start..]);
    }
    chunks
}

fn inline_text_chunk_metrics(child: &El, text: &str) -> (f32, f32, f32) {
    let layout = text_metrics::layout_text_with_line_height_and_family(
        text,
        child.font_size,
        child.line_height,
        child.font_family,
        child.font_weight,
        child.font_mono,
        child.text_tabular_numerals,
        child.text_letter_spacing,
        TextWrap::NoWrap,
        None,
    );
    (layout.width, child.font_size * 0.82, child.font_size * 0.22)
}

fn inline_child_metrics(child: &El) -> (f32, f32, f32) {
    match child.kind {
        Kind::Text => inline_text_chunk_metrics(child, child.text.as_deref().unwrap_or("")),
        Kind::Math => {
            if let Some(expr) = &child.math {
                let layout = crate::math::layout_math(expr, child.font_size, child.math_display);
                (layout.width, layout.ascent, layout.descent)
            } else {
                (0.0, 0.0, 0.0)
            }
        }
        _ => (0.0, 0.0, 0.0),
    }
}

/// Walk an Inlines paragraph's children and produce the source-order
/// concatenation that draw_ops will hand to the atlas. `Kind::Text`
/// contributes its `text` field; `Kind::HardBreak` contributes a
/// newline; anything else contributes nothing (an unsupported child
/// kind inside Inlines is a programmer error elsewhere — measurement
/// silently ignores it).
fn concat_inline_text(children: &[El]) -> String {
    let mut s = String::new();
    for c in children {
        match c.kind {
            Kind::Text => {
                if let Some(t) = &c.text {
                    s.push_str(t);
                }
            }
            Kind::HardBreak => s.push('\n'),
            _ => {}
        }
    }
    s
}

/// Pick the font size that drives the paragraph's measurement. We use
/// the maximum across text children rather than the parent's own
/// `font_size`, because builders set sizes on the leaf text nodes.
fn inline_paragraph_size(node: &El) -> f32 {
    let mut size: f32 = node.font_size;
    for c in &node.children {
        if matches!(c.kind, Kind::Text) {
            size = size.max(c.font_size);
        }
    }
    size
}

fn inline_paragraph_line_height(node: &El) -> f32 {
    let mut line_height: f32 = node.line_height;
    let mut max_size: f32 = node.font_size;
    for c in &node.children {
        if matches!(c.kind, Kind::Text) && c.font_size >= max_size {
            max_size = c.font_size;
            line_height = c.line_height;
        }
    }
    line_height
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::UiState;

    /// Issue #64: two same-role siblings sharing a key collide on
    /// `computed_id`. Runtime-only apps never run the bundle lint, so
    /// the layout pass flags the collision once per id (reusing the
    /// `DuplicateId` finding vocabulary) and dedupes across frames.
    #[test]
    fn duplicate_sibling_keys_flagged_once() {
        let mut root = column([
            crate::widgets::text::text("a").key("dup"),
            crate::widgets::text::text("b").key("dup"),
        ]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 100.0));

        // Both siblings collapse onto one computed_id...
        assert_eq!(root.children[0].computed_id, root.children[1].computed_id);
        let id = root.children[0].computed_id.clone();
        // ...and that id is flagged.
        assert!(state.layout.warned_duplicate_ids.contains(&*id));

        // A standing duplicate must not re-flag on the next layout.
        let n_before = state.layout.warned_duplicate_ids.len();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 100.0));
        assert_eq!(state.layout.warned_duplicate_ids.len(), n_before);
    }

    /// A tree with unique sibling keys must not flag anything.
    #[test]
    fn distinct_sibling_keys_not_flagged() {
        let mut root = column([
            crate::widgets::text::text("a").key("one"),
            crate::widgets::text::text("b").key("two"),
        ]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 100.0));
        assert!(state.layout.warned_duplicate_ids.is_empty());
    }

    /// CSS-flex parity: a `Size::Fill` child of a column with
    /// `align(Center)` should shrink to its intrinsic cross-axis size
    /// and be horizontally centered, matching `align-items: center`
    /// in CSS flex (which causes flex items to lose their stretch).
    #[test]
    fn align_center_shrinks_fill_child_to_intrinsic() {
        // Column with align(Center). Inner row has the default
        // El::new width = Fill(1.0); without Proposal B it would
        // claim the full 200px and align would be a no-op.
        let mut root = column([crate::row([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])])
        .align(Align::Center)
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 100.0));
        let row_rect = root.children[0].computed_rect;
        // Row's intrinsic width = 40 (single fixed child). 200 - 40 = 160
        // leftover; centered → row starts at x=80.
        assert!(
            (row_rect.x - 80.0).abs() < 0.5,
            "expected x≈80 (centered), got {}",
            row_rect.x
        );
        assert!(
            (row_rect.w - 40.0).abs() < 0.5,
            "expected w≈40 (shrunk to intrinsic), got {}",
            row_rect.w
        );
    }

    /// CSS-flex parity: when a `Fill` sibling hits its `max_width`,
    /// the space it frees is re-distributed to the still-flexible
    /// fills instead of becoming trailing dead space.
    #[test]
    fn max_clamped_fill_frees_space_to_sibling_fills() {
        let mut root = crate::row([
            El::new(Kind::Group).width(Size::Fill(1.0)).max_width(50.0),
            El::new(Kind::Group).width(Size::Fill(1.0)),
        ])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));
        let a = root.children[0].computed_rect;
        let b = root.children[1].computed_rect;
        assert!((a.w - 50.0).abs() < 0.5, "capped fill w={}", a.w);
        assert!(
            (b.w - 350.0).abs() < 0.5,
            "sibling fill should absorb the freed 150px, got w={}",
            b.w
        );
    }

    /// A `min_width` violation steals space symmetrically: the frozen
    /// fill takes its floor and the flexible sibling absorbs what's
    /// left, rather than both overflowing the row.
    #[test]
    fn min_clamped_fill_steals_space_from_sibling_fills() {
        let mut root = crate::row([
            El::new(Kind::Group).width(Size::Fill(1.0)).min_width(300.0),
            El::new(Kind::Group).width(Size::Fill(1.0)),
        ])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));
        let a = root.children[0].computed_rect;
        let b = root.children[1].computed_rect;
        assert!((a.w - 300.0).abs() < 0.5, "floored fill w={}", a.w);
        assert!(
            (b.w - 100.0).abs() < 0.5,
            "sibling fill should shrink to the remaining 100px, got w={}",
            b.w
        );
    }

    /// When every fill freezes at its max, the leftover becomes free
    /// space for `justify` — a centered capped column actually centers
    /// instead of leaving all the slack trailing.
    #[test]
    fn justify_distributes_space_left_by_fully_capped_fills() {
        let mut root = crate::row([El::new(Kind::Group).width(Size::Fill(1.0)).max_width(100.0)])
            .justify(Justify::Center)
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));
        let a = root.children[0].computed_rect;
        assert!((a.w - 100.0).abs() < 0.5, "capped fill w={}", a.w);
        assert!(
            (a.x - 150.0).abs() < 0.5,
            "capped fill should be centered (x≈150), got x={}",
            a.x
        );
    }

    /// `align(Stretch)` (the default) preserves Fill stretching: a
    /// Fill-width child still claims the full cross axis.
    #[test]
    fn align_stretch_preserves_fill_stretch() {
        let mut root = column([crate::row([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])])
        .align(Align::Stretch)
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 100.0));
        let row_rect = root.children[0].computed_rect;
        assert!(
            (row_rect.x - 0.0).abs() < 0.5 && (row_rect.w - 200.0).abs() < 0.5,
            "expected stretched (x=0, w=200), got x={} w={}",
            row_rect.x,
            row_rect.w
        );
    }

    /// A content-bearing El (here: one with `.text(...)`) can still
    /// carry children, which placement lays out inside its rect like
    /// any container. The sizing pass must size those children even
    /// though the node's own measure ignores them — the first cut of
    /// `size_tree` early-returned at the text branch and Hug children
    /// collapsed to zero rects.
    #[test]
    fn children_of_text_bearing_node_still_get_sized() {
        let mut root = column([El::new(Kind::Group)
            .text("label".to_string())
            .child(
                crate::widgets::text::text("nested child")
                    .width(Size::Hug)
                    .height(Size::Hug),
            )
            .width(Size::Fixed(300.0))
            .height(Size::Fixed(100.0))]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 100.0));
        let child = root.children[0].children[0].computed_rect;
        assert!(
            child.w > 10.0 && child.h > 5.0,
            "hug child of a text-bearing parent must size from its own \
             content, got {child:?}"
        );
    }

    /// When min/max clamp freezing moves a fill child's final width off
    /// the share the sizing pass measured it at, the placement pass
    /// re-sizes the subtree at the resolved width — otherwise wrap-text
    /// descendants keep line breaks (and heights) from the unclamped
    /// share. Mirrors the adaptation the old re-measuring place walk
    /// did implicitly.
    #[test]
    fn clamped_fill_resizes_wrap_text_descendants_at_final_width() {
        let long = "words that will definitely wrap at two hundred pixels \
                    but not at three hundred, repeated for effect and \
                    measure, wrapping across several lines";
        let make = |max_w: Option<f32>| {
            let mut fill = column([crate::widgets::text::text(long).wrap_text()])
                .width(Size::Fill(1.0))
                .height(Size::Hug);
            if let Some(m) = max_w {
                fill.max_width = Some(m);
            }
            crate::row([
                crate::tree::spacer()
                    .width(Size::Fixed(100.0))
                    .height(Size::Fixed(10.0)),
                fill,
            ])
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(400.0))
        };
        // Reference: a fill that genuinely gets 200px (300px leftover,
        // clamped vs unclamped must agree once re-sized).
        let mut clamped = make(Some(200.0));
        let mut state = UiState::new();
        layout(&mut clamped, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));
        let col = &clamped.children[1];
        let col_rect = col.computed_rect;
        assert!(
            (col_rect.w - 200.0).abs() < 0.5,
            "fill should clamp to 200, got {}",
            col_rect.w
        );
        // The wrapped paragraph inside must occupy the height of text
        // wrapped at 200px — several lines — not the two-line height
        // of the unclamped 300px share.
        let para = col.children[0].computed_rect;
        let (_, expected_h) = intrinsic_constrained(&col.children[0], Some(200.0));
        assert!(
            (para.h - expected_h).abs() < 0.5,
            "paragraph should reserve wrap-at-200 height {expected_h}, got {}",
            para.h
        );
    }

    /// Issue #47: a Hug ancestor must measure a wrap-text descendant
    /// at the width layout will resolve for it — the node's own Fixed
    /// width — not at whatever wider width the ancestor chain has
    /// available. Inverted precedence here made measure wrap at the
    /// card's inner width while layout wrapped at the text's fixed
    /// width, leaving every Hug ancestor short by the difference.
    #[test]
    fn hug_ancestor_measures_wrap_text_at_its_own_fixed_width() {
        let long = "The quick brown fox jumps over the lazy dog, then \
                    does it again and again until the line is long \
                    enough to wrap several times.";
        // "card": Fill-wide, Hug-tall → measures its subtree. Inner
        // column Fixed(240); wrap text Fixed(200) — measure must use
        // 200, not the card's much wider inner width.
        let mut root = column([column([column([crate::widgets::text::text(long)
            .wrap_text()
            .width(Size::Fixed(200.0))])
        .width(Size::Fixed(240.0))])
        .width(Size::Fill(1.0))]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 600.0));
        let card = root.children[0].computed_rect;
        let text_rect = root.children[0].children[0].children[0].computed_rect;
        assert!(
            text_rect.h > 25.0,
            "text should wrap to multiple lines at 200px, got h={}",
            text_rect.h
        );
        assert!(
            (card.h - text_rect.h).abs() < 0.5,
            "Hug card height {} must match wrapped text height {}",
            card.h,
            text_rect.h
        );
    }

    /// When all children are Hug-sized, `Justify::Center` should split
    /// the leftover space symmetrically across the main axis.
    #[test]
    fn justify_center_centers_hug_children() {
        let mut root = column([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .justify(Justify::Center)
        .height(Size::Fill(1.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 100.0));
        let child_rect = root.children[0].computed_rect;
        // Expected: 100 - 20 = 80 leftover; centered → starts at y=40.
        assert!(
            (child_rect.y - 40.0).abs() < 0.5,
            "expected y≈40, got {}",
            child_rect.y
        );
    }

    #[test]
    fn justify_end_pushes_to_bottom() {
        let mut root = column([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .justify(Justify::End)
        .height(Size::Fill(1.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 100.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.y - 80.0).abs() < 0.5,
            "expected y≈80, got {}",
            child_rect.y
        );
    }

    /// CSS `justify-content: space-between`: when no main-axis Fill
    /// children claim the slack, the leftover space is distributed
    /// evenly *between* (not around) the children — outer edges flush.
    #[test]
    fn justify_space_between_distributes_evenly() {
        let row_child = || {
            crate::widgets::text::text("x")
                .width(Size::Fixed(20.0))
                .height(Size::Fixed(20.0))
        };
        let mut root = column([row_child(), row_child(), row_child()])
            .justify(Justify::SpaceBetween)
            .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 200.0));
        // Used main = 3 * 20 = 60. Leftover = 140 over (n-1) = 2 gaps
        // → 70 between. Positions: 0, 90, 180.
        let y0 = root.children[0].computed_rect.y;
        let y1 = root.children[1].computed_rect.y;
        let y2 = root.children[2].computed_rect.y;
        assert!(
            y0.abs() < 0.5,
            "first child should be flush at y=0, got {y0}"
        );
        assert!(
            (y1 - 90.0).abs() < 0.5,
            "middle child should be at y≈90, got {y1}"
        );
        assert!(
            (y2 - 180.0).abs() < 0.5,
            "last child should be flush at y≈180, got {y2}"
        );
    }

    /// CSS `flex: <weight>`: when multiple `Size::Fill` children share
    /// a container, the available space is distributed in proportion
    /// to their weights.
    #[test]
    fn fill_weight_distributes_proportionally() {
        let big = crate::widgets::text::text("big")
            .width(Size::Fixed(40.0))
            .height(Size::Fill(2.0));
        let small = crate::widgets::text::text("small")
            .width(Size::Fixed(40.0))
            .height(Size::Fill(1.0));
        let mut root = column([big, small]).height(Size::Fixed(300.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 100.0, 300.0));
        // Total weight = 3, available = 300. Big = 200, small = 100.
        let big_h = root.children[0].computed_rect.h;
        let small_h = root.children[1].computed_rect.h;
        assert!(
            (big_h - 200.0).abs() < 0.5,
            "Fill(2.0) should claim 2/3 of 300 ≈ 200, got {big_h}"
        );
        assert!(
            (small_h - 100.0).abs() < 0.5,
            "Fill(1.0) should claim 1/3 of 300 ≈ 100, got {small_h}"
        );
    }

    /// `padding` on a `Hug`-sized container is included in the
    /// container's intrinsic — matching CSS `box-sizing: content-box`
    /// where padding adds to the rendered size.
    #[test]
    fn padding_on_hug_includes_in_intrinsic() {
        let root = column([crate::widgets::text::text("x")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(40.0))])
        .padding(Sides::all(20.0));
        let (w, h) = intrinsic(&root);
        // 40 content + 2*20 padding on each axis = 80.
        assert!((w - 80.0).abs() < 0.5, "expected intrinsic w≈80, got {w}");
        assert!((h - 80.0).abs() < 0.5, "expected intrinsic h≈80, got {h}");
    }

    /// Cross-axis `Align::End` on a row pins children to the bottom
    /// edge — CSS `align-items: flex-end`. Mirror of `justify_end`
    /// but on the cross axis instead of the main axis.
    #[test]
    fn align_end_pins_to_cross_axis_far_edge() {
        let mut root = crate::row([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .align(Align::End)
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 100.0));
        let child_rect = root.children[0].computed_rect;
        // Row cross axis = height. End → child y = 100 - 20 = 80.
        assert!(
            (child_rect.y - 80.0).abs() < 0.5,
            "expected y≈80 (pinned to bottom), got {}",
            child_rect.y
        );
    }

    #[test]
    fn overlay_can_center_hug_child() {
        let mut root = stack([crate::titled_card("Dialog", [crate::text("Body")])
            .width(Size::Fixed(200.0))
            .height(Size::Hug)])
        .align(Align::Center)
        .justify(Justify::Center);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 600.0, 400.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.x - 200.0).abs() < 0.5,
            "expected x≈200, got {}",
            child_rect.x
        );
        assert!(
            child_rect.y > 100.0 && child_rect.y < 200.0,
            "expected centered y, got {}",
            child_rect.y
        );
    }

    #[test]
    fn scroll_offset_translates_children_and_clamps_to_content() {
        // Six 50px-tall rows in a 200px-tall scroll viewport.
        // Content height = 6 * 50 + 5 * 12 (gap) = 360 px. Visible
        // viewport (no padding) = 200 px → max_offset = 160.
        let mut root = scroll(
            (0..6)
                .map(|i| crate::widgets::text::text(format!("row {i}")).height(Size::Fixed(50.0))),
        )
        .key("list")
        .gap(12.0)
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        assign_ids(&mut root);
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 80.0);

        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        // Offset is in range, applied verbatim.
        let stored = state
            .scroll
            .offsets
            .get(&*root.computed_id)
            .copied()
            .unwrap_or(0.0);
        assert!(
            (stored - 80.0).abs() < 0.01,
            "offset clamped unexpectedly: {stored}"
        );
        // First child shifted up by 80.
        let c0 = root.children[0].computed_rect;
        assert!(
            (c0.y - (-80.0)).abs() < 0.01,
            "child 0 y = {} (expected -80)",
            c0.y
        );
        // Now overshoot — should clamp to max_offset=160.
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 9999.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let stored = state
            .scroll
            .offsets
            .get(&*root.computed_id)
            .copied()
            .unwrap_or(0.0);
        assert!(
            (stored - 160.0).abs() < 0.01,
            "overshoot clamped to {stored}"
        );
        // Content fits → offset clamps to 0.
        let mut tiny =
            scroll([crate::widgets::text::text("just one row").height(Size::Fixed(20.0))])
                .height(Size::Fixed(200.0));
        let mut tiny_state = UiState::new();
        assign_ids(&mut tiny);
        tiny_state
            .scroll
            .offsets
            .insert(tiny.computed_id.clone().to_string(), 50.0);
        layout(
            &mut tiny,
            &mut tiny_state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        assert_eq!(
            tiny_state
                .scroll
                .offsets
                .get(&*tiny.computed_id)
                .copied()
                .unwrap_or(0.0),
            0.0
        );
    }

    #[test]
    fn scroll_layout_prunes_far_offscreen_descendants() {
        let far = column([crate::widgets::text::text("far row body").key("far-text")])
            .height(Size::Fixed(40.0));
        let mut root = scroll([
            column([crate::widgets::text::text("near row body")]).height(Size::Fixed(40.0)),
            crate::tree::spacer().height(Size::Fixed(400.0)),
            far,
        ])
        .key("list")
        .height(Size::Fixed(80.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 80.0));
        let stats = take_prune_stats();

        assert!(
            stats.subtrees >= 1,
            "expected at least one far scroll child to be pruned, got {stats:?}"
        );
        assert!(
            stats.nodes >= 1,
            "expected pruned descendants to be zeroed, got {stats:?}"
        );
        let far_text = state
            .rect_of_key("far-text")
            .expect("far text keeps a zero rect while pruned");
        assert_eq!(far_text.w, 0.0);
        assert_eq!(far_text.h, 0.0);
    }

    #[test]
    fn plain_scroll_preserves_visible_anchor_when_width_reflows_content() {
        let make_root = || {
            let paragraph_text = "Variable width text wraps into a different number of lines when \
                                  the viewport narrows, which used to make a plain scroll box lose \
                                  the item the user was reading.";
            scroll([column((0..30).map(|i| {
                crate::widgets::text::paragraph(format!("{i}: {paragraph_text}"))
                    .key(format!("paragraph-{i}"))
            }))
            .gap(8.0)])
            .key("article")
            .height(Size::Fixed(180.0))
        };

        let mut root = make_root();
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 320.0, 180.0));

        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 520.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 320.0, 180.0));

        let anchor = state
            .scroll
            .scroll_anchors
            .get(&*root.computed_id)
            .cloned()
            .expect("plain scroll should store a visible descendant anchor");
        let before_rect = find_descendant_rect(&root, &anchor.node_id).expect("anchor rect before");
        let before_anchor_y = before_rect.y + before_rect.h * anchor.rect_fraction;
        let before_offset = state.scroll_offset(&root.computed_id);

        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 180.0));

        let after_rect = find_descendant_rect(&root, &anchor.node_id).expect("anchor rect after");
        let after_anchor_y = after_rect.y + after_rect.h * anchor.rect_fraction;
        let after_offset = state.scroll_offset(&root.computed_id);
        assert!(
            (after_anchor_y - before_anchor_y).abs() < 0.5,
            "anchor point should stay at y={before_anchor_y}, got {after_anchor_y}"
        );
        assert!(
            (after_offset - before_offset).abs() > 20.0,
            "offset should absorb height changes above the anchor"
        );
    }

    #[test]
    fn scrollbar_thumb_size_and_position_track_overflow() {
        // 6 rows x 50px + 5 gaps x 12 = 360 content; 200 viewport.
        // viewport/content = 200/360 ≈ 0.555 → thumb_h ≈ 111.1.
        let mut root = 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 state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let metrics = state
            .scroll
            .metrics
            .get(&*root.computed_id)
            .copied()
            .expect("scrollable should have metrics");
        assert!((metrics.viewport_h - 200.0).abs() < 0.01);
        assert!((metrics.content_h - 360.0).abs() < 0.01);
        assert!((metrics.max_offset - 160.0).abs() < 0.01);

        let thumb = state
            .scroll
            .thumb_rects
            .get(&*root.computed_id)
            .copied()
            .expect("scrollable with scrollbar() and overflow gets a thumb");
        // viewport^2 / content_h = 200^2 / 360 = 111.11..
        assert!((thumb.h - 111.111).abs() < 0.5, "thumb h = {}", thumb.h);
        assert!((thumb.w - crate::tokens::SCROLLBAR_THUMB_WIDTH).abs() < 0.01);
        // At offset 0, thumb sits at the top of the inner rect.
        assert!(thumb.y.abs() < 0.01);
        // Right-anchored: thumb_x + thumb_w + track_inset == viewport_right.
        assert!(
            (thumb.x + thumb.w + crate::tokens::SCROLLBAR_TRACK_INSET - 300.0).abs() < 0.01,
            "thumb anchored at {} (expected {})",
            thumb.x,
            300.0 - thumb.w - crate::tokens::SCROLLBAR_TRACK_INSET
        );

        // Slide to half — thumb should be at half the track_remaining.
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 80.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let thumb = state
            .scroll
            .thumb_rects
            .get(&*root.computed_id)
            .copied()
            .unwrap();
        let track_remaining = 200.0 - thumb.h;
        let expected_y = track_remaining * (80.0 / 160.0);
        assert!(
            (thumb.y - expected_y).abs() < 0.5,
            "thumb at half-scroll y = {} (expected {expected_y})",
            thumb.y,
        );
    }

    #[test]
    fn scrollbar_track_is_wider_than_thumb_and_full_height() {
        // The track is the click hitbox: wider than the visible
        // thumb (Fitts's law) and tall enough to detect track
        // clicks above and below the thumb for paging.
        let mut root = 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 state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let thumb = state
            .scroll
            .thumb_rects
            .get(&*root.computed_id)
            .copied()
            .unwrap();
        let track = state
            .scroll
            .thumb_tracks
            .get(&*root.computed_id)
            .copied()
            .unwrap();
        // Track wider than thumb on the same right edge.
        assert!(track.w > thumb.w, "track.w {} thumb.w {}", track.w, thumb.w);
        assert!(
            (track.right() - thumb.right()).abs() < 0.01,
            "track and thumb must share the right edge",
        );
        // Track spans the full inner viewport (so above/below thumb
        // are both inside it for click-to-page).
        assert!(
            (track.h - 200.0).abs() < 0.01,
            "track height = {} (expected 200)",
            track.h,
        );
    }

    #[test]
    fn scrollbar_thumb_absent_when_disabled_or_no_overflow() {
        // Same scrollable, but author opted out — no thumb_rect.
        let mut suppressed = scroll(
            (0..6)
                .map(|i| crate::widgets::text::text(format!("row {i}")).height(Size::Fixed(50.0))),
        )
        .no_scrollbar()
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(
            &mut suppressed,
            &mut state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        assert!(
            !state
                .scroll
                .thumb_rects
                .contains_key(&*suppressed.computed_id)
        );

        // Same scrollable, content fits → no thumb either.
        let mut tiny = scroll([crate::widgets::text::text("one row").height(Size::Fixed(20.0))])
            .height(Size::Fixed(200.0));
        let mut tiny_state = UiState::new();
        layout(
            &mut tiny,
            &mut tiny_state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        assert!(
            !tiny_state
                .scroll
                .thumb_rects
                .contains_key(&*tiny.computed_id)
        );
    }

    #[test]
    fn nested_scrollbar_thumb_moves_with_outer_scroll_content() {
        let make_root = || {
            scroll([
                crate::tree::spacer().height(Size::Fixed(80.0)),
                scroll((0..6).map(|i| {
                    crate::widgets::text::text(format!("inner row {i}")).height(Size::Fixed(50.0))
                }))
                .key("inner")
                .height(Size::Fixed(120.0)),
                crate::tree::spacer().height(Size::Fixed(260.0)),
            ])
            .key("outer")
            .height(Size::Fixed(220.0))
        };

        let mut root = make_root();
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 220.0));
        let inner = root
            .children
            .iter()
            .find(|child| child.key.as_deref() == Some("inner"))
            .expect("inner scroll");
        let inner_id = inner.computed_id.clone();
        let inner_rect = state.rect(&inner_id);
        let thumb = state
            .scroll
            .thumb_rects
            .get(&*inner_id)
            .copied()
            .expect("inner scroll should have a thumb");
        let track = state
            .scroll
            .thumb_tracks
            .get(&*inner_id)
            .copied()
            .expect("inner scroll should have a track");
        let thumb_rel_y = thumb.y - inner_rect.y;
        let track_rel_y = track.y - inner_rect.y;

        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 60.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 220.0));
        let inner_rect_after = state.rect(&inner_id);
        let thumb_after = state.scroll.thumb_rects.get(&*inner_id).copied().unwrap();
        let track_after = state.scroll.thumb_tracks.get(&*inner_id).copied().unwrap();

        assert!(
            (inner_rect_after.y - (inner_rect.y - 60.0)).abs() < 0.5,
            "outer scroll should shift the inner viewport"
        );
        assert!(
            (thumb_after.y - inner_rect_after.y - thumb_rel_y).abs() < 0.5,
            "inner thumb should stay fixed relative to its viewport"
        );
        assert!(
            (track_after.y - inner_rect_after.y - track_rel_y).abs() < 0.5,
            "inner track should stay fixed relative to its viewport"
        );
    }

    #[test]
    fn layout_override_places_children_at_returned_rects() {
        // A custom layout that just stacks children diagonally inside the container.
        let mut root = column((0..3).map(|i| {
            crate::widgets::text::text(format!("dot {i}"))
                .width(Size::Fixed(20.0))
                .height(Size::Fixed(20.0))
        }))
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0))
        .layout(|ctx| {
            ctx.children
                .iter()
                .enumerate()
                .map(|(i, _)| {
                    let off = i as f32 * 30.0;
                    Rect::new(ctx.container.x + off, ctx.container.y + off, 20.0, 20.0)
                })
                .collect()
        });
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
        let r0 = root.children[0].computed_rect;
        let r1 = root.children[1].computed_rect;
        let r2 = root.children[2].computed_rect;
        assert_eq!((r0.x, r0.y), (0.0, 0.0));
        assert_eq!((r1.x, r1.y), (30.0, 30.0));
        assert_eq!((r2.x, r2.y), (60.0, 60.0));
    }

    #[test]
    fn layout_override_rect_of_key_resolves_earlier_sibling() {
        // The popover-anchor pattern: a custom-laid-out node positions
        // its child by reading another keyed node's rect via the new
        // LayoutCtx::rect_of_key callback. The trigger lives in an
        // earlier sibling so its rect is already in the keyed-rect
        // map by the time the popover layer's layout_override runs.
        use crate::tree::stack;
        let trigger_x = 40.0;
        let trigger_y = 20.0;
        let trigger_w = 60.0;
        let trigger_h = 30.0;
        let mut root = stack([
            // Earlier sibling: the trigger.
            crate::widgets::button::button("Open")
                .key("trig")
                .width(Size::Fixed(trigger_w))
                .height(Size::Fixed(trigger_h)),
            // Later sibling: a custom-laid-out container that reads
            // the trigger's rect to position its single child.
            stack([crate::widgets::text::text("popover")
                .width(Size::Fixed(80.0))
                .height(Size::Fixed(20.0))])
            .width(Size::Fill(1.0))
            .height(Size::Fill(1.0))
            .layout(|ctx| {
                let trig = (ctx.rect_of_key)("trig").expect("trigger laid out");
                vec![Rect::new(trig.x, trig.bottom() + 4.0, 80.0, 20.0)]
            }),
        ])
        .padding(Sides::xy(trigger_x, trigger_y));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let popover_layer = &root.children[1];
        let panel_rect = popover_layer.children[0].computed_rect;
        // Anchored to (trigger.x, trigger.bottom() + 4.0). With padding
        // (40, 20) and trigger height 30 → expect (40, 54).
        assert!(
            (panel_rect.x - trigger_x).abs() < 0.01,
            "popover x = {} (expected {trigger_x})",
            panel_rect.x,
        );
        assert!(
            (panel_rect.y - (trigger_y + trigger_h + 4.0)).abs() < 0.01,
            "popover y = {} (expected {})",
            panel_rect.y,
            trigger_y + trigger_h + 4.0,
        );
    }

    #[test]
    fn layout_override_rect_of_key_returns_none_for_missing_key() {
        let mut root = column([crate::widgets::text::text("inner")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0))
        .layout(|ctx| {
            assert!((ctx.rect_of_key)("nope").is_none());
            vec![Rect::new(ctx.container.x, ctx.container.y, 40.0, 20.0)]
        });
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
    }

    #[test]
    fn layout_override_rect_of_key_returns_none_for_later_sibling() {
        // First-frame contract: a custom layout running before its
        // target's sibling has been laid out should see `None`, not a
        // zero rect or a panic. This is what makes the popover pattern
        // (trigger first, popover layer second in source order) the
        // supported shape — the reverse direction simply gets `None`.
        use crate::tree::stack;
        let mut root = stack([
            stack([crate::widgets::text::text("panel")
                .width(Size::Fixed(40.0))
                .height(Size::Fixed(20.0))])
            .width(Size::Fill(1.0))
            .height(Size::Fill(1.0))
            .layout(|ctx| {
                assert!(
                    (ctx.rect_of_key)("later").is_none(),
                    "later sibling's rect must not be available yet"
                );
                vec![Rect::new(ctx.container.x, ctx.container.y, 40.0, 20.0)]
            }),
            crate::widgets::button::button("after").key("later"),
        ]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
    }

    #[test]
    fn layout_override_measure_returns_intrinsic() {
        // The custom layout reads `measure` to size each child.
        let mut root = column([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0))
        .layout(|ctx| {
            let (w, h) = (ctx.measure)(&ctx.children[0]);
            assert!((w - 40.0).abs() < 0.01, "measured width {w}");
            assert!((h - 20.0).abs() < 0.01, "measured height {h}");
            vec![Rect::new(ctx.container.x, ctx.container.y, w, h)]
        });
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
        let r = root.children[0].computed_rect;
        assert_eq!((r.w, r.h), (40.0, 20.0));
    }

    #[test]
    #[should_panic(expected = "returned 1 rects for 2 children")]
    fn layout_override_length_mismatch_panics() {
        let mut root = column([
            crate::widgets::text::text("a")
                .width(Size::Fixed(10.0))
                .height(Size::Fixed(10.0)),
            crate::widgets::text::text("b")
                .width(Size::Fixed(10.0))
                .height(Size::Fixed(10.0)),
        ])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0))
        .layout(|ctx| vec![Rect::new(ctx.container.x, ctx.container.y, 10.0, 10.0)]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
    }

    #[test]
    #[should_panic(expected = "Size::Hug is not supported for custom layouts")]
    fn layout_override_hug_panics() {
        // Hug check fires when the parent's layout pass measures the
        // custom-layout child for sizing — i.e. when a layout_override
        // node is a child of a column/row, not when it's the root.
        let mut root = column([column([crate::widgets::text::text("c")])
            .width(Size::Hug)
            .height(Size::Fixed(200.0))
            .layout(|ctx| vec![Rect::new(ctx.container.x, ctx.container.y, 10.0, 10.0)])])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
    }

    #[test]
    fn fit_contain_letterboxes_and_centers() {
        // 16:9 child in a 400×400 container: width binds → 400×225,
        // centered vertically.
        let child = crate::tree::column([crate::widgets::text::text("c")]).key("fitted");
        let mut root = crate::tree::fit_contain(child, 16.0 / 9.0)
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));

        let r = state.rect_of_key("fitted").expect("fitted rect");
        assert_eq!((r.w, r.h), (400.0, 225.0));
        assert_eq!(r.x, 0.0);
        assert!((r.y - 87.5).abs() < 0.01, "centered: y = {}", r.y);

        // Tall container, same ratio: height binds → pillarboxed.
        let child = crate::tree::column([crate::widgets::text::text("c")]).key("fitted2");
        let mut root = crate::tree::fit_contain(child, 16.0 / 9.0)
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(100.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 100.0));
        let r = state.rect_of_key("fitted2").expect("fitted2 rect");
        assert!((r.w - 100.0 * 16.0 / 9.0).abs() < 0.01);
        assert_eq!(r.h, 100.0);
        assert!((r.x - (400.0 - r.w) / 2.0).abs() < 0.01);
    }

    #[test]
    fn fit_cover_overflows_the_slack_axis_and_clips() {
        // 1:1 child covering a 400×200 container: width binds the
        // cover → 400×400, vertically centered (overflowing top and
        // bottom), and the container clips.
        let child = crate::tree::column([crate::widgets::text::text("c")]).key("covered");
        let mut root = crate::tree::fit_cover(child, 1.0)
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(200.0));
        assert!(root.clip, "fit_cover must clip its overflow");
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 200.0));
        let r = state.rect_of_key("covered").expect("covered rect");
        assert_eq!((r.w, r.h), (400.0, 400.0));
        assert!(
            (r.y - -100.0).abs() < 0.01,
            "centered overflow: y = {}",
            r.y
        );
    }

    #[test]
    fn fit_contain_intrinsic_uses_the_child_measure() {
        // A fixed 100×50 child (2:1) in a 400×400 container → 400×200.
        let child = crate::tree::column::<Vec<El>, El>(vec![])
            .width(Size::Fixed(100.0))
            .height(Size::Fixed(50.0))
            .key("intrinsic");
        let mut root = crate::tree::fit_contain_intrinsic(child)
            .width(Size::Fixed(400.0))
            .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));
        let r = state.rect_of_key("intrinsic").expect("intrinsic rect");
        assert_eq!((r.w, r.h), (400.0, 200.0));
    }

    #[test]
    fn virtual_list_realizes_only_visible_rows() {
        // 100 rows × 50px each in a 200px viewport, offset = 120.
        // Visible range: rows whose y in [-50, 200) → start = floor(120/50) = 2,
        // end = ceil((120+200)/50) = ceil(6.4) = 7. Five rows realized.
        let mut root = crate::tree::virtual_list(100, 50.0, |i| {
            crate::widgets::text::text(format!("row {i}")).key(format!("row-{i}"))
        });
        let mut state = UiState::new();
        assign_ids(&mut root);
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 120.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        assert_eq!(
            root.children.len(),
            5,
            "expected 5 realized rows, got {}",
            root.children.len()
        );
        // Identity check: the first realized row should be the row keyed "row-2".
        assert_eq!(root.children[0].key.as_deref(), Some("row-2"));
        assert_eq!(root.children[4].key.as_deref(), Some("row-6"));
        // Position check: first realized row's y = inner.y + 2*50 - 120 = -20.
        let r0 = root.children[0].computed_rect;
        assert!(
            (r0.y - (-20.0)).abs() < 0.5,
            "row 2 expected y≈-20, got {}",
            r0.y
        );
    }

    #[test]
    fn virtual_list_gap_contributes_to_row_positions_and_content_height() {
        let mut root = crate::tree::virtual_list(10, 40.0, |i| {
            crate::widgets::text::text(format!("row {i}")).key(format!("row-{i}"))
        })
        .gap(10.0);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));

        assert_eq!(
            root.children.len(),
            3,
            "rows 0, 1, and 2 should intersect a 120px viewport with 40px rows and 10px gaps"
        );
        let row_1 = root
            .children
            .iter()
            .find(|c| c.key.as_deref() == Some("row-1"))
            .expect("row 1 should be realized");
        assert!(
            (row_1.computed_rect.y - 50.0).abs() < 0.5,
            "gap should place row 1 at y=50"
        );
        let metrics = state
            .scroll
            .metrics
            .get(&*root.computed_id)
            .expect("virtual list writes scroll metrics");
        assert!(
            (metrics.content_h - 490.0).abs() < 0.5,
            "10 rows x 40 plus 9 gaps x 10 should be 490, got {}",
            metrics.content_h
        );
    }

    #[test]
    fn virtual_list_keyed_rows_have_stable_computed_id_across_scroll() {
        let make_root = || {
            crate::tree::virtual_list(50, 50.0, |i| {
                crate::widgets::text::text(format!("row {i}")).key(format!("row-{i}"))
            })
        };

        let mut state = UiState::new();
        let mut root_a = make_root();
        assign_ids(&mut root_a);
        // Scroll so row 5 is visible.
        state
            .scroll
            .offsets
            .insert(root_a.computed_id.clone().to_string(), 250.0);
        layout(&mut root_a, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let id_at_offset_a = root_a
            .children
            .iter()
            .find(|c| c.key.as_deref() == Some("row-5"))
            .unwrap()
            .computed_id
            .clone();

        // Re-layout with a different offset — row 5 is still visible.
        let mut root_b = make_root();
        assign_ids(&mut root_b);
        state
            .scroll
            .offsets
            .insert(root_b.computed_id.clone().to_string(), 200.0);
        layout(&mut root_b, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let id_at_offset_b = root_b
            .children
            .iter()
            .find(|c| c.key.as_deref() == Some("row-5"))
            .unwrap()
            .computed_id
            .clone();

        assert_eq!(
            id_at_offset_a, id_at_offset_b,
            "row-5's computed_id changed when scroll offset moved"
        );
    }

    #[test]
    fn virtual_list_clamps_overshoot_offset() {
        // 10 rows × 50 = 500 content height; viewport 200; max offset = 300.
        let mut root =
            crate::tree::virtual_list(10, 50.0, |i| crate::widgets::text::text(format!("r{i}")));
        let mut state = UiState::new();
        assign_ids(&mut root);
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 9999.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let stored = state
            .scroll
            .offsets
            .get(&*root.computed_id)
            .copied()
            .unwrap_or(0.0);
        assert!(
            (stored - 300.0).abs() < 0.01,
            "expected clamp to 300, got {stored}"
        );
    }

    #[test]
    fn virtual_list_empty_count_realizes_no_children() {
        let mut root =
            crate::tree::virtual_list(0, 50.0, |i| crate::widgets::text::text(format!("r{i}")));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        assert_eq!(root.children.len(), 0);
    }

    #[test]
    #[should_panic(expected = "row_height > 0.0")]
    fn virtual_list_zero_row_height_panics() {
        let _ = crate::tree::virtual_list(10, 0.0, |i| crate::widgets::text::text(format!("r{i}")));
    }

    #[test]
    #[should_panic(expected = "Size::Hug would defeat virtualization")]
    fn virtual_list_hug_panics() {
        let mut root = column([crate::tree::virtual_list(10, 50.0, |i| {
            crate::widgets::text::text(format!("r{i}"))
        })
        .height(Size::Hug)])
        .width(Size::Fixed(300.0))
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
    }

    #[test]
    fn grid_packs_rows_and_aligns_the_partial_tail() {
        // 3 cells in 2 columns at gap 10 inside 210px: two rows; each
        // column is (210 - 10) / 2 = 100 wide. The tail row's single
        // real cell must align with column 0 above (filler holds col 1).
        let cell = |i: usize| {
            crate::tree::column::<Vec<El>, El>(vec![])
                .key(format!("cell-{i}"))
                .height(Size::Fixed(50.0))
        };
        let mut root = crate::tree::grid(2, 10.0, (0..3).map(cell))
            .width(Size::Fixed(210.0))
            .height(Size::Fixed(300.0));
        assert_eq!(root.arrow_nav, Some(crate::tree::ArrowNav::Grid));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 210.0, 300.0));

        let r0 = state.rect_of_key("cell-0").unwrap();
        let r1 = state.rect_of_key("cell-1").unwrap();
        let r2 = state.rect_of_key("cell-2").unwrap();
        assert_eq!((r0.x, r0.w), (0.0, 100.0));
        assert_eq!((r1.x, r1.w), (110.0, 100.0));
        // Tail cell: same column geometry as cell-0, next row (50 + 10 gap).
        assert_eq!((r2.x, r2.w), (0.0, 100.0));
        assert_eq!(r2.y, 60.0);
    }

    #[test]
    fn virtual_grid_realizes_rows_of_packed_cells() {
        // 10 items, 3 columns, 50px cells, 120px viewport: rows 0..3
        // realize (ceil(120/50)+1 candidates, clamped by visibility).
        let mut root = crate::tree::virtual_grid(10, 3, 50.0, 0.0, |i| {
            crate::widgets::text::text(format!("item {i}")).key(format!("item-{i}"))
        })
        .key("vgrid");
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));

        assert_eq!(root.arrow_nav, Some(crate::tree::ArrowNav::Grid));
        // Realized rows are children of the list; cells are children of
        // each packed row. (Keys inside virtual rows resolve through
        // hit-test/event routing, not the pre-layout key index, so the
        // test reads rects by computed_id.)
        let rect_of = |row: usize, col: usize| root.children[row].children[col].computed_rect;
        // First realized row holds items 0..3 packed across the width.
        let i0 = rect_of(0, 0);
        let i2 = rect_of(0, 2);
        assert_eq!(i0.w, 100.0);
        assert_eq!(i2.x, 200.0);
        // Second row starts the next item triplet.
        let i3 = rect_of(1, 0);
        assert_eq!((i3.x, i3.y), (0.0, 50.0));
        // Realized row range is queryable for eviction logic.
        assert!(state.visible_range("vgrid").is_some());
        // Identity check: the first realized cell is item-0.
        assert_eq!(root.children[0].children[0].key.as_deref(), Some("item-0"));
    }

    #[test]
    fn visible_range_tracks_realized_rows() {
        // Same scenario as `virtual_list_realizes_only_visible_rows`:
        // 100 rows x 50px in a 200px viewport at offset 120 realizes
        // rows 2..7. The keyed query must report exactly that range.
        let mut root = crate::tree::virtual_list(100, 50.0, |i| {
            crate::widgets::text::text(format!("row {i}")).key(format!("row-{i}"))
        })
        .key("list");
        let mut state = UiState::new();
        assign_ids(&mut root);
        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 120.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        assert_eq!(state.visible_range("list"), Some(2..7));
        assert_eq!(state.visible_range("not-a-list"), None);

        // Dynamic variant: four rows realize at offset 0 (see
        // `virtual_list_dyn_respects_per_row_fixed_heights`).
        let mut dyn_root = crate::tree::virtual_list_dyn(
            20,
            50.0,
            |i| format!("row-{i}"),
            |i| {
                let h = if i % 2 == 0 { 40.0 } else { 80.0 };
                crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Fixed(h))
            },
        )
        .key("dyn-list");
        let mut dyn_state = UiState::new();
        layout(
            &mut dyn_root,
            &mut dyn_state,
            Rect::new(0.0, 0.0, 300.0, 200.0),
        );
        assert_eq!(dyn_state.visible_range("dyn-list"), Some(0..4));

        // Per-frame scratch: an empty re-layout clears stale ranges.
        let mut empty =
            crate::tree::virtual_list(0, 50.0, |_| crate::widgets::text::text("never")).key("list");
        layout(&mut empty, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        assert_eq!(state.visible_range("list"), None);
    }

    #[test]
    fn virtual_list_dyn_respects_per_row_fixed_heights() {
        // Alternating 40px / 80px rows. With a 200px viewport and offset 0,
        // accumulated y goes 0, 40, 120, 160, 240 — the fifth row starts
        // past the viewport, so four rows are realized.
        let mut root = crate::tree::virtual_list_dyn(
            20,
            50.0,
            |i| format!("row-{i}"),
            |i| {
                let h = if i % 2 == 0 { 40.0 } else { 80.0 };
                crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Fixed(h))
            },
        );
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        assert_eq!(
            root.children.len(),
            4,
            "expected 4 realized rows, got {}",
            root.children.len()
        );
        // y positions: row 0 → 0, row 1 → 40, row 2 → 120, row 3 → 160.
        let ys: Vec<f32> = root.children.iter().map(|c| c.computed_rect.y).collect();
        assert!(
            (ys[0] - 0.0).abs() < 0.5,
            "row 0 expected y≈0, got {}",
            ys[0]
        );
        assert!(
            (ys[1] - 40.0).abs() < 0.5,
            "row 1 expected y≈40, got {}",
            ys[1]
        );
        assert!(
            (ys[2] - 120.0).abs() < 0.5,
            "row 2 expected y≈120, got {}",
            ys[2]
        );
        assert!(
            (ys[3] - 160.0).abs() < 0.5,
            "row 3 expected y≈160, got {}",
            ys[3]
        );
    }

    #[test]
    fn virtual_list_dyn_gap_contributes_to_row_positions_and_content_height() {
        let mut root = crate::tree::virtual_list_dyn(
            10,
            40.0,
            |i| format!("row-{i}"),
            |i| {
                crate::tree::column([crate::widgets::text::text(format!("row {i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Fixed(40.0))
            },
        )
        .gap(10.0);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 120.0));

        assert_eq!(
            root.children.len(),
            3,
            "rows 0, 1, and 2 should intersect a 120px viewport with 40px rows and 10px gaps"
        );
        let row_1 = root
            .children
            .iter()
            .find(|c| c.key.as_deref() == Some("row-1"))
            .expect("row 1 should be realized");
        assert!(
            (row_1.computed_rect.y - 50.0).abs() < 0.5,
            "gap should place row 1 at y=50"
        );
        let metrics = state
            .scroll
            .metrics
            .get(&*root.computed_id)
            .expect("virtual list writes scroll metrics");
        assert!(
            (metrics.content_h - 490.0).abs() < 0.5,
            "10 rows x 40 plus 9 gaps x 10 should be 490, got {}",
            metrics.content_h
        );
    }

    #[test]
    fn virtual_list_dyn_caches_measured_heights() {
        // Build a list where the first frame realizes rows 0..k, measuring
        // each. After layout the cache should hold those measurements and
        // the next frame should read them.
        let mut root = crate::tree::virtual_list_dyn(
            50,
            50.0,
            |i| format!("row-{i}"),
            |i| {
                crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Fixed(30.0))
            },
        );
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let measured = state
            .scroll
            .measured_row_heights
            .get(&*root.computed_id)
            .expect("dynamic virtual list should populate the height cache");
        // The first pass measures the estimate-derived window, then
        // the anchored final pass can extend it with newly revealed
        // rows. At least six rows are visible/cached here.
        assert!(
            measured.len() >= 6,
            "expected ≥ 6 cached row heights, got {}",
            measured.len()
        );
        for by_width in measured.values() {
            let h = by_width
                .get(&300)
                .copied()
                .expect("measurement should be keyed at the 300px width bucket");
            assert!(
                (h - 30.0).abs() < 0.5,
                "expected cached height ≈ 30, got {h}"
            );
        }
    }

    #[test]
    fn virtual_list_dyn_realized_rows_place_at_their_measured_heights() {
        // Successor to the #59 cache-seeding regression test (the
        // per-pass intrinsic cache is gone — `size_tree` sizes each
        // realized row subtree once at the list width). The surviving
        // guarantee: the height the measure realization stored and the
        // rect the layout realization placed agree exactly, so
        // anchoring math and painted rows can't diverge.
        let mut root = crate::tree::virtual_list_dyn(
            50,
            20.0,
            |i| format!("row-{i}"),
            |i| {
                crate::tree::column([crate::widgets::text::text(format!("row body {i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Hug)
            },
        );
        let mut state = UiState::new();
        let _ = take_intrinsic_cache_stats();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        assert!(!root.children.is_empty(), "test requires realized rows");
        let stored = state
            .scroll
            .measured_row_heights
            .get(&*root.computed_id)
            .expect("dynamic list stores per-row heights");
        let bucket = virtual_width_bucket(300.0);
        for row in &root.children {
            let key = row.key.as_deref().expect("rows are keyed");
            let h = stored
                .get(key)
                .and_then(|by_width| by_width.get(&bucket))
                .copied()
                .expect("realized row height stored at the current width bucket");
            assert!(
                (row.computed_rect.h - h).abs() < 0.01,
                "row {key} placed at h={} but measured h={h}",
                row.computed_rect.h,
            );
        }
        // And the sizing pass actually ran (visits reported through the
        // legacy stats shape: hits pinned to 0, misses = node visits).
        let stats = take_intrinsic_cache_stats();
        assert_eq!(stats.hits, 0);
        assert!(stats.misses > 0, "sizing visits should be reported");
    }

    #[test]
    fn virtual_list_dyn_preserves_visible_anchor_when_above_measurement_changes() {
        let make_root = || {
            crate::tree::virtual_list_dyn(
                100,
                40.0,
                |i| format!("row-{i}"),
                |i| {
                    crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                        .key(format!("row-{i}"))
                        .height(Size::Fixed(40.0))
                },
            )
        };
        let mut root = make_root();
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 400.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let anchor = state
            .scroll
            .virtual_anchors
            .get(&*root.computed_id)
            .cloned()
            .expect("dynamic list should store a visible anchor");
        let before_y = root
            .children
            .iter()
            .find(|child| child.key.as_deref() == Some(anchor.row_key.as_str()))
            .map(|child| child.computed_rect.y)
            .expect("anchor row should be realized");
        let before_offset = state.scroll_offset(&root.computed_id);

        state
            .scroll
            .measured_row_heights
            .entry(root.computed_id.clone().to_string())
            .or_default()
            .entry("row-0".to_string())
            .or_default()
            .insert(300, 120.0);

        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        let after_y = root
            .children
            .iter()
            .find(|child| child.key.as_deref() == Some(anchor.row_key.as_str()))
            .map(|child| child.computed_rect.y)
            .expect("anchor row should remain realized");
        let after_offset = state.scroll_offset(&root.computed_id);

        assert!(
            (after_y - before_y).abs() < 0.5,
            "anchor row should stay at y={before_y}, got {after_y}"
        );
        assert!(
            (after_offset - (before_offset + 80.0)).abs() < 0.5,
            "offset should absorb the 80px measurement delta above anchor"
        );
    }

    #[test]
    fn virtual_list_dyn_height_cache_is_width_bucketed() {
        let mut root = crate::tree::virtual_list_dyn(
            20,
            50.0,
            |i| format!("row-{i}"),
            |i| {
                crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                    .key(format!("row-{i}"))
                    .height(Size::Fixed(30.0))
            },
        );
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 240.0, 200.0));

        let row_0 = state
            .scroll
            .measured_row_heights
            .get(&*root.computed_id)
            .and_then(|m| m.get("row-0"))
            .expect("row 0 should be measured");
        assert!(
            row_0.contains_key(&300) && row_0.contains_key(&240),
            "expected width buckets 300 and 240, got {:?}",
            row_0.keys().collect::<Vec<_>>()
        );
    }

    #[test]
    fn virtual_list_dyn_total_height_uses_measured_plus_estimate() {
        // Measured rows use their cached fixed 30px height; rows that
        // have not been seen at this width still use the 50px estimate.
        // An overshoot offset must clamp to the mixed measured/estimated
        // content height after the final visible measurements land.
        let make_root = || {
            crate::tree::virtual_list_dyn(
                20,
                50.0,
                |i| format!("row-{i}"),
                |i| {
                    crate::tree::column([crate::widgets::text::text(format!("r{i}"))])
                        .key(format!("row-{i}"))
                        .height(Size::Fixed(30.0))
                },
            )
        };
        let mut state = UiState::new();
        let mut root = make_root();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        state
            .scroll
            .offsets
            .insert(root.computed_id.clone().to_string(), 9999.0);
        let mut root2 = make_root();
        layout(&mut root2, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));

        let measured = state
            .scroll
            .measured_row_heights
            .get(&*root2.computed_id)
            .expect("dynamic virtual list should populate the height cache");
        let measured_sum = measured
            .values()
            .filter_map(|by_width| by_width.get(&300))
            .sum::<f32>();
        let measured_count = measured
            .values()
            .filter(|by_width| by_width.contains_key(&300))
            .count();
        let expected_total = measured_sum + (20 - measured_count) as f32 * 50.0;
        let expected_max_offset = expected_total - 200.0;

        let stored = state
            .scroll
            .offsets
            .get(&*root2.computed_id)
            .copied()
            .unwrap_or(0.0);
        assert!(
            (stored - expected_max_offset).abs() < 0.5,
            "expected offset clamped to {expected_max_offset}, got {stored}"
        );
    }

    // ---- append_only parity ---------------------------------------
    //
    // The append-only incremental path must produce byte-identical
    // geometry to the general dynamic path for any trim-then-append
    // frame sequence. These tests drive both variants through the same
    // script on independent `UiState`s and compare realized rows, stored
    // offsets, and visible ranges every frame (issue #107).

    /// A chat-shaped row whose height depends only on the *stable*
    /// message id (`first + i`), so a given message keeps its height as
    /// it shifts indices under head-trim. Heights are integer-valued so
    /// both paths' prefix sums are bit-identical regardless of summation
    /// order.
    fn parity_list(first: usize, count: usize, append_only: bool, pin: bool) -> El {
        let mut el = crate::tree::virtual_list_dyn(
            count,
            20.0,
            move |i| format!("m{}", first + i),
            move |i| {
                let id = first + i;
                let h = 30.0 + (id % 7) as f32 * 10.0;
                crate::tree::column([crate::widgets::text::text(format!("m{id}"))])
                    .key(format!("m{id}"))
                    .height(Size::Fixed(h))
            },
        )
        .key("chat")
        .gap(4.0);
        if pin {
            el = el.pin_end();
        }
        if append_only {
            el = el.append_only();
        }
        el
    }

    /// Realized rows as `(key, rect)`, in render order.
    fn parity_rows(root: &El) -> Vec<(String, Rect)> {
        root.children
            .iter()
            .map(|c| (c.key.clone().unwrap_or_default(), c.computed_rect))
            .collect()
    }

    struct Frame {
        first: usize,
        count: usize,
        seed_offset: Option<f32>,
        request: Option<ScrollRequest>,
    }

    fn run_parity(frames: &[Frame], pin: bool) {
        let mut sg = UiState::new(); // general path
        let mut si = UiState::new(); // incremental (append_only) path

        for (n, f) in frames.iter().enumerate() {
            let viewport = Rect::new(0.0, 0.0, 300.0, 200.0);
            let step = |state: &mut UiState, append_only: bool| {
                let mut root = parity_list(f.first, f.count, append_only, pin);
                assign_ids(&mut root);
                if let Some(o) = f.seed_offset {
                    state
                        .scroll
                        .offsets
                        .insert(root.computed_id.clone().to_string(), o);
                }
                if let Some(req) = &f.request {
                    state.push_scroll_requests(vec![req.clone()]);
                }
                layout(&mut root, state, viewport);
                root
            };

            let root_g = step(&mut sg, false);
            let root_i = step(&mut si, true);

            let rows_g = parity_rows(&root_g);
            let rows_i = parity_rows(&root_i);
            assert_eq!(
                rows_g.len(),
                rows_i.len(),
                "frame {n}: realized row count differs (general {} vs incremental {})",
                rows_g.len(),
                rows_i.len()
            );
            for ((kg, rg), (ki, ri)) in rows_g.iter().zip(&rows_i) {
                assert_eq!(kg, ki, "frame {n}: realized key order differs");
                assert!(
                    (rg.x - ri.x).abs() < 1e-2
                        && (rg.y - ri.y).abs() < 1e-2
                        && (rg.w - ri.w).abs() < 1e-2
                        && (rg.h - ri.h).abs() < 1e-2,
                    "frame {n}: rect for {kg} differs: general {rg:?} vs incremental {ri:?}"
                );
            }

            let off_g = sg.scroll.offsets.get(&*root_g.computed_id).copied();
            let off_i = si.scroll.offsets.get(&*root_i.computed_id).copied();
            assert!(
                (off_g.unwrap_or(0.0) - off_i.unwrap_or(0.0)).abs() < 1e-2,
                "frame {n}: stored offset differs: general {off_g:?} vs incremental {off_i:?}"
            );
            assert_eq!(
                sg.visible_range("chat"),
                si.visible_range("chat"),
                "frame {n}: visible range differs"
            );
        }
    }

    #[test]
    fn append_only_matches_general_top_append_scroll_trim() {
        run_parity(
            &[
                // Start at the top.
                Frame {
                    first: 0,
                    count: 30,
                    seed_offset: Some(0.0),
                    request: None,
                },
                // Append 12 rows at the tail.
                Frame {
                    first: 0,
                    count: 42,
                    seed_offset: None,
                    request: None,
                },
                // Scroll to the middle.
                Frame {
                    first: 0,
                    count: 42,
                    seed_offset: Some(400.0),
                    request: None,
                },
                // Trim 8 off the head, append 16 at the tail.
                Frame {
                    first: 8,
                    count: 50,
                    seed_offset: None,
                    request: None,
                },
                // Append more while scrolled mid-list (anchor preservation).
                Frame {
                    first: 8,
                    count: 62,
                    seed_offset: None,
                    request: None,
                },
                // Trim again.
                Frame {
                    first: 20,
                    count: 62,
                    seed_offset: None,
                    request: None,
                },
            ],
            false,
        );
    }

    #[test]
    fn append_only_matches_general_to_row_key_request() {
        run_parity(
            &[
                Frame {
                    first: 0,
                    count: 40,
                    seed_offset: Some(0.0),
                    request: None,
                },
                // Programmatic jump to a specific message by key.
                Frame {
                    first: 0,
                    count: 40,
                    seed_offset: None,
                    request: Some(ScrollRequest::ToRowKey {
                        list_key: "chat".into(),
                        row_key: "m30".into(),
                        align: ScrollAlignment::Start,
                    }),
                },
                // Trim past the anchored row, then append.
                Frame {
                    first: 12,
                    count: 55,
                    seed_offset: None,
                    request: None,
                },
            ],
            false,
        );
    }

    /// A horizontal resize changes the width bucket, which the index
    /// can't reconcile — it must cold-rebuild for the new bucket and
    /// still match the general path (which re-reads the new bucket's
    /// measurements). Drives both variants through width changes
    /// interleaved with append/trim.
    #[test]
    fn append_only_matches_general_across_width_change() {
        let mut sg = UiState::new();
        let mut si = UiState::new();
        // (first, count, viewport_w)
        let script = [
            (0usize, 30usize, 300.0f32),
            (0, 40, 300.0),
            (0, 40, 240.0), // resize → new width bucket
            (6, 52, 240.0), // append + trim at the new width
            (6, 52, 360.0), // resize wider
        ];
        for (n, &(first, count, w)) in script.iter().enumerate() {
            let viewport = Rect::new(0.0, 0.0, w, 200.0);
            let step = |state: &mut UiState, append_only: bool| {
                let mut root = parity_list(first, count, append_only, false);
                assign_ids(&mut root);
                layout(&mut root, state, viewport);
                root
            };
            let rg = step(&mut sg, false);
            let ri = step(&mut si, true);
            let rows_g = parity_rows(&rg);
            let rows_i = parity_rows(&ri);
            assert_eq!(rows_g.len(), rows_i.len(), "frame {n}: row count differs");
            for ((kg, a), (ki, b)) in rows_g.iter().zip(&rows_i) {
                assert_eq!(kg, ki, "frame {n}: key order differs");
                assert!(
                    (a.x - b.x).abs() < 1e-2
                        && (a.y - b.y).abs() < 1e-2
                        && (a.w - b.w).abs() < 1e-2
                        && (a.h - b.h).abs() < 1e-2,
                    "frame {n}: rect for {kg} differs: {a:?} vs {b:?}"
                );
            }
            assert_eq!(
                sg.visible_range("chat"),
                si.visible_range("chat"),
                "frame {n}: visible range differs"
            );
        }
    }

    #[test]
    fn append_only_matches_general_pin_end_stick_to_bottom() {
        run_parity(
            &[
                Frame {
                    first: 0,
                    count: 20,
                    seed_offset: None,
                    request: None,
                },
                // Tail grows: a pinned list must stay at the bottom.
                Frame {
                    first: 0,
                    count: 35,
                    seed_offset: None,
                    request: None,
                },
                // Ring-buffer: trim head while appending tail, still pinned.
                Frame {
                    first: 10,
                    count: 50,
                    seed_offset: None,
                    request: None,
                },
                Frame {
                    first: 25,
                    count: 70,
                    seed_offset: None,
                    request: None,
                },
            ],
            true,
        );
    }

    #[test]
    fn virtual_list_dyn_empty_count_realizes_no_children() {
        let mut root = crate::tree::virtual_list_dyn(
            0,
            50.0,
            |i| format!("row-{i}"),
            |i| crate::widgets::text::text(format!("r{i}")),
        );
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 300.0, 200.0));
        assert_eq!(root.children.len(), 0);
    }

    #[test]
    #[should_panic(expected = "estimated_row_height > 0.0")]
    fn virtual_list_dyn_zero_estimate_panics() {
        let _ = crate::tree::virtual_list_dyn(
            10,
            0.0,
            |i| format!("row-{i}"),
            |i| crate::widgets::text::text(format!("r{i}")),
        );
    }

    #[test]
    fn text_runs_constructor_shape_smoke() {
        let el = crate::tree::text_runs([
            crate::widgets::text::text("Hello, "),
            crate::widgets::text::text("world").bold(),
            crate::tree::hard_break(),
            crate::widgets::text::text("of text").italic(),
        ]);
        assert_eq!(el.kind, Kind::Inlines);
        assert_eq!(el.children.len(), 4);
        assert!(matches!(
            el.children[1].font_weight,
            FontWeight::Bold | FontWeight::Semibold
        ));
        assert_eq!(el.children[2].kind, Kind::HardBreak);
        assert!(el.children[3].text_italic);
    }

    #[test]
    fn wrapped_text_hugs_multiline_height_from_available_width() {
        let mut root = column([crate::paragraph(
            "A longer sentence should wrap into multiple measured lines.",
        )])
        .width(Size::Fill(1.0))
        .height(Size::Hug);

        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 180.0, 200.0));

        let child_rect = root.children[0].computed_rect;
        assert_eq!(child_rect.w, 180.0);
        assert!(
            child_rect.h > crate::tokens::TEXT_SM.size * 1.4,
            "expected multiline paragraph height, got {}",
            child_rect.h
        );
    }

    #[test]
    fn overlay_child_with_wrapped_text_measures_against_its_resolved_width() {
        // Regression: overlay_rect used to call `intrinsic(c)` with no
        // width hint, so a Fixed-width modal containing a wrappable
        // paragraph measured the paragraph as a single line — leaving
        // the modal's Hug height short by the wrapped lines and
        // crowding the buttons against the bottom edge of the panel
        // (rumble cert-pending modal showed this).
        //
        // The fix: pass the child's resolved width as the available
        // width for intrinsic measurement, mirroring what column/row
        // already do.
        const PANEL_W: f32 = 240.0;
        const PADDING: f32 = 18.0;
        const GAP: f32 = 12.0;

        let panel = column([
            crate::paragraph(
                "A long enough warning paragraph that it has to wrap onto a second line \
                 inside this narrow panel.",
            ),
            crate::widgets::button::button("OK").key("ok"),
        ])
        .width(Size::Fixed(PANEL_W))
        .height(Size::Hug)
        .padding(Sides::all(PADDING))
        .gap(GAP)
        .align(Align::Stretch);

        let mut root = crate::stack([panel])
            .width(Size::Fill(1.0))
            .height(Size::Fill(1.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 600.0));

        let panel_rect = root.children[0].computed_rect;
        assert_eq!(panel_rect.w, PANEL_W, "panel keeps its Fixed width");

        let para_rect = root.children[0].children[0].computed_rect;
        let button_rect = root.children[0].children[1].computed_rect;

        // Paragraph wrapped to ≥ 2 lines (exact line count depends on
        // glyph metrics; just guard against the single-line bug).
        assert!(
            para_rect.h > crate::tokens::TEXT_SM.size * 1.4,
            "paragraph should wrap to multiple lines inside the Fixed-width panel; \
             got h={}",
            para_rect.h
        );

        // Panel height must accommodate top padding + paragraph +
        // gap + button + bottom padding. The bug was that the panel
        // came out exactly `padding + gap + 1-line-paragraph + button`
        // — short by the second wrap line — and the button overshot
        // the inner area, leaving zero pixels of bottom padding.
        let bottom_padding = (panel_rect.y + panel_rect.h) - (button_rect.y + button_rect.h);
        assert!(
            (bottom_padding - PADDING).abs() < 0.5,
            "expected {PADDING}px between button and panel bottom, got {bottom_padding}",
        );
    }

    #[test]
    fn row_with_fill_paragraph_propagates_height_to_parent_column() {
        // Regression: the Row branch of `intrinsic_constrained` called
        // `intrinsic(ch)` unconstrained, so a wrappable Fill child
        // (paragraph) measured as a single unwrapped line. Two such rows
        // in a column then got one-line-tall allocations and the second
        // row's gutter rect overlapped the first row's wrapped text
        // (chat-port event-log recipe in damascene-core/README.md hit this).
        //
        // The fix mirrors `layout_axis`: the Row intrinsic distributes
        // its available width across Fill children before measuring,
        // so wrappable Fill children see the width they will actually
        // be laid out at.
        const COL_W: f32 = 600.0;
        const GUTTER_W: f32 = 3.0;

        let long = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, \
                    sed do eiusmod tempor incididunt ut labore et dolore magna \
                    aliqua. Ut enim ad minim veniam, quis nostrud exercitation \
                    ullamco laboris nisi ut aliquip ex ea commodo consequat.";

        let make_row = || {
            let gutter = El::new(Kind::Custom("gutter"))
                .width(Size::Fixed(GUTTER_W))
                .height(Size::Fill(1.0));
            let body = crate::paragraph(long).width(Size::Fill(1.0));
            crate::row([gutter, body]).width(Size::Fill(1.0))
        };

        let mut root = column([make_row(), make_row()])
            .width(Size::Fixed(COL_W))
            .height(Size::Hug)
            .align(Align::Stretch);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, COL_W, 2000.0));

        let row0_rect = root.children[0].computed_rect;
        let row1_rect = root.children[1].computed_rect;
        let para0_rect = root.children[0].children[1].computed_rect;

        // Both the paragraph rect and the row rect must reflect the
        // wrapped (multi-line) height. The bug pinned them to a single
        // line (~`TEXT_SM.line_height` = 20px), so the wrapped text
        // painted outside the row's allocated rect.
        let line_height = crate::tokens::TEXT_SM.line_height;
        assert!(
            para0_rect.h > line_height * 1.5,
            "paragraph should wrap to multiple lines at ~597px wide; \
             got h={} (line_height={})",
            para0_rect.h,
            line_height,
        );
        assert!(
            row0_rect.h > line_height * 1.5,
            "row 0 should accommodate the wrapped paragraph height; \
             got h={} (line_height={})",
            row0_rect.h,
            line_height,
        );

        // Sanity: row 1 sits below row 0's allocated rect, not above it.
        assert!(
            row1_rect.y >= row0_rect.y + row0_rect.h - 0.5,
            "row 1 starts at y={} but row 0 occupies y={}..{}",
            row1_rect.y,
            row0_rect.y,
            row0_rect.y + row0_rect.h,
        );
    }

    /// `min_width` floors a child whose resolved cross-axis size is
    /// below the floor. Tests against an `align(Start)` column so
    /// `Size::Fixed` doesn't get widened by the default Stretch
    /// alignment before clamping has a chance to apply.
    #[test]
    fn min_width_floors_resolved_cross_axis_size() {
        let mut root = column([crate::widgets::text::text("hi")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))
            .min_width(120.0)])
        .align(Align::Start)
        .width(Size::Fixed(500.0))
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 500.0, 200.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.w - 120.0).abs() < 0.5,
            "expected child clamped up to 120 (intrinsic 40 < min 120), got w={}",
            child_rect.w,
        );
    }

    /// `max_width` caps a `Size::Fill` child even when the surrounding
    /// row offers more space.
    #[test]
    fn max_width_caps_fill_child() {
        let mut root = crate::row([crate::widgets::text::text("body")
            .width(Size::Fill(1.0))
            .height(Size::Fixed(20.0))
            .max_width(160.0)])
        .width(Size::Fixed(800.0))
        .height(Size::Fixed(40.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 40.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.w - 160.0).abs() < 0.5,
            "expected Fill child capped at 160, got w={}",
            child_rect.w,
        );
    }

    /// `Size::Ch(n)` (the CSS `ch` unit) reserves a fixed width of `n` digit
    /// slots independent of the value's text, and scales linearly with `n` —
    /// so a live metric anchored in a `ch` field never jitters or reflows.
    #[test]
    fn ch_unit_reserves_constant_digit_width() {
        use crate::widgets::text::text;
        let mut root = column([
            text("8")
                .tabular_numerals()
                .width(Size::Ch(4.0))
                .height(Size::Fixed(20.0)),
            text("123456")
                .tabular_numerals()
                .width(Size::Ch(4.0))
                .height(Size::Fixed(20.0)),
            text("8")
                .tabular_numerals()
                .width(Size::Ch(2.0))
                .height(Size::Fixed(20.0)),
        ]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 500.0, 200.0));
        let four_a = root.children[0].computed_rect.w;
        let four_b = root.children[1].computed_rect.w;
        let two = root.children[2].computed_rect.w;
        assert!(four_a > 0.0);
        // Same ch count → same width regardless of the value's length.
        assert!(
            (four_a - four_b).abs() < 0.01,
            "Ch(4) width must not depend on the text: {four_a} vs {four_b}"
        );
        // Width scales with the digit count: Ch(4) == 2 × Ch(2).
        assert!(
            (four_a - 2.0 * two).abs() < 0.5,
            "Ch(4) should be twice Ch(2): {four_a} vs 2×{two}"
        );
    }

    /// When `min_width` and `max_width` conflict, the lower bound wins
    /// (CSS `min-width` precedence over `max-width`).
    #[test]
    fn min_width_wins_over_max_width_when_conflicting() {
        let mut root = column([crate::widgets::text::text("x")
            .width(Size::Fixed(50.0))
            .height(Size::Fixed(20.0))
            .max_width(80.0)
            .min_width(120.0)]);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 500.0, 200.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.w - 120.0).abs() < 0.5,
            "expected min_width (120) to win over max_width (80), got w={}",
            child_rect.w,
        );
    }

    /// `min_height` floors a Hug child column whose children sum to
    /// less than the floor. Tested through a fixed-size parent so the
    /// resolved rect of the inner column reflects the clamp.
    #[test]
    fn min_height_floors_hug_column_inside_fixed_parent() {
        let inner = column([crate::widgets::text::text("a")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(20.0))])
        .width(Size::Fixed(80.0))
        .height(Size::Hug)
        .min_height(200.0);
        let mut root = column([inner])
            .align(Align::Start)
            .width(Size::Fixed(800.0))
            .height(Size::Fixed(600.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 600.0));
        let inner_rect = root.children[0].computed_rect;
        assert!(
            (inner_rect.h - 200.0).abs() < 0.5,
            "expected inner column floored to min_height=200 (intrinsic ~20), got h={}",
            inner_rect.h,
        );
    }

    /// Row laying out a `Fill` Hug-column with a wrap-text child must
    /// measure the column's height at the column's allocated width, not
    /// unconstrained. Repro for the lint regression that fires on a
    /// `row([column([wrap_text(...).fill_width()]).fill_width(), fixed])`
    /// shape: without the constrained measurement, the column reports
    /// its single-line unwrapped height to the row, the row sizes the
    /// column rect at that height, and the wrapped text then overflows
    /// the column vertically (Overflow `B=N` finding).
    #[test]
    fn row_passes_allocated_width_to_hug_column_with_wrap_text_child() {
        // 200px-wide row. The fixed child takes 40; the Fill column gets
        // 200 - 40 - 12 (gap) = 148. The paragraph wraps at 148px to two
        // lines; the column's intrinsic height should reflect that.
        let mut root = crate::row([
            column([crate::widgets::text::paragraph(
                "A long enough description that must wrap to two lines at 148px",
            )])
            .width(Size::Fill(1.0)),
            crate::widgets::text::text("ok")
                .width(Size::Fixed(40.0))
                .height(Size::Fixed(20.0)),
        ])
        .gap(12.0)
        .align(Align::Center)
        .width(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 600.0));
        // Find the column child (root.children[0]) and its paragraph leaf.
        let col_rect = root.children[0].computed_rect;
        let para_rect = root.children[0].children[0].computed_rect;
        assert!(
            (col_rect.h - para_rect.h).abs() < 0.5,
            "column height ({}) should track its wrapped child's height ({})",
            col_rect.h,
            para_rect.h,
        );
    }

    /// `Size::Aspect` on the main axis (height inside a Column) derives
    /// from the resolved cross size. Width fills its column's 200px;
    /// height should be 200 * 0.5 = 100.
    #[test]
    fn aspect_on_column_main_axis_derives_from_cross() {
        let mut root = column([El::new(Kind::Group)
            .width(Size::Fill(1.0))
            .height(Size::Aspect(0.5))])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 400.0));
        let r = root.children[0].computed_rect;
        assert!(
            (r.w - 200.0).abs() < 0.5,
            "expected w≈200 (Fill), got {}",
            r.w,
        );
        assert!(
            (r.h - 100.0).abs() < 0.5,
            "expected h≈100 (Aspect 0.5 of 200), got {}",
            r.h,
        );
    }

    /// Surrounding layout flows around an Aspect-sized image: a Hug
    /// column containing an Aspect-height El + a fixed-height sibling
    /// must have an outer height equal to derived height + sibling.
    #[test]
    fn aspect_height_pushes_siblings_in_column() {
        let mut root = column([
            El::new(Kind::Group)
                .width(Size::Fill(1.0))
                .height(Size::Aspect(0.25)),
            crate::widgets::text::text("caption")
                .width(Size::Fixed(40.0))
                .height(Size::Fixed(20.0)),
        ])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(500.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 500.0));
        let img = root.children[0].computed_rect;
        let cap = root.children[1].computed_rect;
        assert!(
            (img.h - 100.0).abs() < 0.5,
            "expected aspect-derived height ≈100, got {}",
            img.h,
        );
        assert!(
            (cap.y - 100.0).abs() < 0.5,
            "caption should sit immediately below the aspect-sized El (y≈100), got y={}",
            cap.y,
        );
    }

    /// `Size::Aspect` on the cross axis (width inside a Row) derives
    /// from the resolved main (height). Height fills 200; width should
    /// be 200 * 2.0 = 400.
    #[test]
    fn aspect_on_row_cross_axis_derives_from_main() {
        let mut root = crate::row([El::new(Kind::Group)
            .height(Size::Fill(1.0))
            .width(Size::Aspect(2.0))])
        .width(Size::Fixed(800.0))
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 200.0));
        let r = root.children[0].computed_rect;
        assert!(
            (r.h - 200.0).abs() < 0.5,
            "expected h≈200 (Fill), got {}",
            r.h,
        );
        assert!(
            (r.w - 400.0).abs() < 0.5,
            "expected w≈400 (Aspect 2.0 of 200), got {}",
            r.w,
        );
    }

    /// Both axes `Aspect` is degenerate — falls back to intrinsic so
    /// the El still has a finite measure.
    #[test]
    fn aspect_on_both_axes_falls_back_to_intrinsic() {
        let mut root = column([crate::widgets::text::text("hi")
            .width(Size::Aspect(1.0))
            .height(Size::Aspect(1.0))])
        .width(Size::Fixed(200.0))
        .height(Size::Fixed(200.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 200.0, 200.0));
        let r = root.children[0].computed_rect;
        assert!(
            r.w > 0.0 && r.h > 0.0,
            "expected finite size for both-Aspect fallback, got {}x{}",
            r.w,
            r.h,
        );
    }

    /// `max_height` and `min_height` cap the Aspect-derived axis, and
    /// the hugging parent's intrinsic agrees with the layout-time size
    /// (no overflow, no gap).
    #[test]
    fn aspect_respects_min_and_max_on_derived_axis() {
        // Case 1: max_height caps a too-tall derived height.
        // Fill(1.0) width inside Fixed(400) → 400 wide; Aspect(1.0) →
        // 400 tall; max_height=120 → clamped to 120.
        let mut root = column([column([El::new(Kind::Group)
            .width(Size::Fill(1.0))
            .height(Size::Aspect(1.0))
            .max_height(120.0)])
        .width(Size::Hug)
        .height(Size::Hug)])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(600.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 600.0));
        let panel = root.children[0].computed_rect;
        let img = root.children[0].children[0].computed_rect;
        assert!(
            (img.h - 120.0).abs() < 0.5,
            "max_height should clamp aspect-derived height to 120, got {}",
            img.h,
        );
        assert!(
            (panel.h - 120.0).abs() < 0.5,
            "hugging panel should match clamped child (120), got {}",
            panel.h,
        );

        // Case 2: min_height pushes a too-short derived height up.
        // Aspect(0.1) of 400 = 40; min_height=200 → bumped to 200.
        let mut root = column([column([El::new(Kind::Group)
            .width(Size::Fill(1.0))
            .height(Size::Aspect(0.1))
            .min_height(200.0)])
        .width(Size::Hug)
        .height(Size::Hug)])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(600.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 600.0));
        let panel = root.children[0].computed_rect;
        let img = root.children[0].children[0].computed_rect;
        assert!(
            (img.h - 200.0).abs() < 0.5,
            "min_height should bump aspect-derived height to 200, got {}",
            img.h,
        );
        assert!(
            (panel.h - 200.0).abs() < 0.5,
            "hugging panel should match bumped child (200), got {}",
            panel.h,
        );
    }

    /// `max_width` on the basis axis caps the Fill basis *before* the
    /// Aspect-derived axis is computed, matching the layout-time path.
    #[test]
    fn aspect_basis_is_clamped_before_deriving() {
        // Fill width in 400-wide column, but max_width=100 → basis=100.
        // Aspect(0.5) → height=50, not 200.
        // Align::Stretch (default) so Fill claims the column's cross
        // extent; with Align::Start a Fill child would shrink to its
        // intrinsic (0 for a bare Group), defeating the test.
        let mut root = column([El::new(Kind::Group)
            .width(Size::Fill(1.0))
            .height(Size::Aspect(0.5))
            .max_width(100.0)])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));
        let img = root.children[0].computed_rect;
        assert!(
            (img.w - 100.0).abs() < 0.5,
            "max_width should cap Fill width at 100, got {}",
            img.w,
        );
        assert!(
            (img.h - 50.0).abs() < 0.5,
            "aspect-derived height should follow clamped width (100 * 0.5 = 50), got {}",
            img.h,
        );
    }

    /// Regression: when a `Fill+Aspect` child sits inside a Hug column,
    /// the hugging column must size itself to the Aspect-derived height
    /// derived against the *parent's* available width, not the El's
    /// own natural intrinsic. Otherwise the column hugs too small and
    /// the child overflows downward at paint.
    #[test]
    fn hug_column_around_fill_aspect_child_does_not_overflow() {
        // Outer column is Fixed(400, 400) — the available width handed
        // down. Middle column hugs (the panel/card surrogate); inner
        // image has width=Fill, height=Aspect(0.5). At layout time the
        // image should be (400, 200), so the hugging panel must also
        // hug to (400, 200) — not to (nat_w, nat_w * 0.5) which would
        // be (1, 0.5) for a default-pixel-less El.
        let mut root = column([column([El::new(Kind::Group)
            .width(Size::Fill(1.0))
            .height(Size::Aspect(0.5))])
        .width(Size::Hug)
        .height(Size::Hug)])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));
        let panel = root.children[0].computed_rect;
        let img = root.children[0].children[0].computed_rect;
        assert!(
            (panel.h - 200.0).abs() < 0.5,
            "hugging panel should hug to aspect-derived height 200, got {}",
            panel.h,
        );
        assert!(
            (img.h - 200.0).abs() < 0.5,
            "image should layout to height 200, got {}",
            img.h,
        );
        assert!(
            img.bottom() <= panel.bottom() + 0.5,
            "image (bottom={}) must fit within hugging panel (bottom={})",
            img.bottom(),
            panel.bottom(),
        );
    }

    /// When a parent hugs to its child and the child has `Aspect`, the
    /// hugging parent reports a size that matches what the child will
    /// actually paint at — the intrinsic post-step ensures consistency.
    #[test]
    fn hugging_parent_sees_aspect_corrected_intrinsic() {
        // Inner El has width=Fixed(80), height=Aspect(0.5) → intrinsic
        // height should derive to 40. The hugging column wrapping it
        // should size to (80, 40), not (80, 0) or (80, natural).
        let mut root = column([column([El::new(Kind::Group)
            .width(Size::Fixed(80.0))
            .height(Size::Aspect(0.5))])
        .width(Size::Hug)
        .height(Size::Hug)])
        .width(Size::Fixed(400.0))
        .height(Size::Fixed(400.0))
        .align(Align::Start);
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 400.0, 400.0));
        let hugger = root.children[0].computed_rect;
        assert!(
            (hugger.w - 80.0).abs() < 0.5 && (hugger.h - 40.0).abs() < 0.5,
            "hugging parent should be 80x40 (matching aspect-corrected intrinsic), got {}x{}",
            hugger.w,
            hugger.h,
        );
    }

    /// `max_height` caps a `Hug` overlay child below its intrinsic.
    #[test]
    fn max_height_caps_overlay_child_below_intrinsic() {
        // Overlay parent sized 600x600; child Hug column whose intrinsic
        // height is 300 (single 300-tall fixed leaf), capped at 100.
        let mut root = crate::tree::stack([column([crate::widgets::text::text("tall")
            .width(Size::Fixed(40.0))
            .height(Size::Fixed(300.0))])
        .width(Size::Hug)
        .height(Size::Hug)
        .max_height(100.0)])
        .width(Size::Fixed(600.0))
        .height(Size::Fixed(600.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 600.0, 600.0));
        let child_rect = root.children[0].computed_rect;
        assert!(
            (child_rect.h - 100.0).abs() < 0.5,
            "expected child height capped at 100, got h={}",
            child_rect.h,
        );
    }

    /// `.user_resizable()` (issue #106): layout publishes a grab band
    /// straddling the pane's trailing edge, sized off the pane's rect,
    /// with the clamp range from `min_width`/`max_width`.
    #[test]
    fn user_resizable_publishes_trailing_edge_band() {
        use crate::state::resize::RESIZE_BAND_THICKNESS as T;
        let mut root = crate::tree::row([
            column(Vec::<El>::new())
                .key("nav")
                .user_resizable()
                .width(Size::Fixed(200.0))
                .min_width(120.0)
                .max_width(420.0),
            column(Vec::<El>::new()).width(Size::Fill(1.0)),
        ])
        .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 400.0));

        assert_eq!(state.resize.bands.len(), 1);
        let band = &state.resize.bands[0];
        assert_eq!(band.id, "nav");
        assert_eq!(band.key.as_deref(), Some("nav"));
        assert_eq!(band.sign, 1.0, "trailing edge: drag-right grows");
        assert!((band.current - 200.0).abs() < 0.5);
        assert_eq!((band.min, band.max), (120.0, 420.0));
        // The band straddles the seam at x=200, full pane height.
        assert!((band.band.x - (200.0 - T / 2.0)).abs() < 0.5);
        assert!((band.band.w - T).abs() < 0.5);
        assert!((band.band.h - 400.0).abs() < 0.5);
    }

    /// A last-child resizable pane (right-anchored inspector) gets a
    /// leading-edge band with the drag direction flipped, and a
    /// missing `max_width` caps at the parent's inner extent so the
    /// seam can't be dragged out of reach.
    #[test]
    fn user_resizable_last_child_gets_leading_edge_band() {
        use crate::state::resize::RESIZE_BAND_THICKNESS as T;
        let mut root = crate::tree::row([
            column(Vec::<El>::new()).width(Size::Fill(1.0)),
            column(Vec::<El>::new())
                .key("inspector")
                .user_resizable()
                .width(Size::Fixed(240.0)),
        ])
        .height(Size::Fixed(400.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 400.0));

        assert_eq!(state.resize.bands.len(), 1);
        let band = &state.resize.bands[0];
        assert_eq!(band.sign, -1.0, "leading edge: drag-left grows");
        // Pane spans [560, 800]; the band straddles its left edge.
        assert!((band.band.x - (560.0 - T / 2.0)).abs() < 0.5);
        assert_eq!(band.min, 0.0);
        assert!(
            (band.max - 800.0).abs() < 0.5,
            "no max_width → capped at the parent's inner extent, got {}",
            band.max,
        );
    }

    /// A stored override rewrites the pane's declared size as `Fixed`
    /// on the next layout, clamped to min/max — including overrides
    /// pre-seeded via `set_user_size` before any drag.
    #[test]
    fn user_resizable_override_applies_and_clamps() {
        let build = || {
            crate::tree::row([
                column(Vec::<El>::new())
                    .key("nav")
                    .user_resizable()
                    .width(Size::Fixed(200.0))
                    .min_width(120.0)
                    .max_width(420.0),
                column(Vec::<El>::new()).key("main").width(Size::Fill(1.0)),
            ])
            .height(Size::Fixed(400.0))
        };
        let mut state = UiState::new();
        state.set_user_size("nav", 300.0);
        let mut root = build();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 400.0));
        let nav = state.rect_of_key("nav").unwrap();
        assert!((nav.w - 300.0).abs() < 0.5, "override wins, got {}", nav.w);
        let main = state.rect_of_key("main").unwrap();
        assert!(
            (main.w - 500.0).abs() < 0.5,
            "the Fill sibling absorbs the change, got {}",
            main.w,
        );

        // Out-of-range overrides clamp to the pane's declared bounds.
        state.set_user_size("nav", 9999.0);
        let mut root = build();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 400.0));
        assert!((state.rect_of_key("nav").unwrap().w - 420.0).abs() < 0.5);

        // Clearing returns the pane to its declared size.
        state.clear_user_size("nav");
        let mut root = build();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 400.0));
        assert!((state.rect_of_key("nav").unwrap().w - 200.0).abs() < 0.5);
    }

    /// A resizable pane in a `column` resizes its *height*: the band
    /// lies along the bottom edge and the clamp comes from the height
    /// bounds.
    #[test]
    fn user_resizable_in_column_resizes_height() {
        use crate::state::resize::RESIZE_BAND_THICKNESS as T;
        let mut root = column([
            crate::tree::row(Vec::<El>::new())
                .key("topbar")
                .user_resizable()
                .height(Size::Fixed(100.0))
                .min_height(40.0),
            crate::tree::row(Vec::<El>::new()).height(Size::Fill(1.0)),
        ])
        .width(Size::Fixed(800.0));
        let mut state = UiState::new();
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 600.0));

        assert_eq!(state.resize.bands.len(), 1);
        let band = &state.resize.bands[0];
        assert!((band.band.y - (100.0 - T / 2.0)).abs() < 0.5);
        assert!((band.band.w - 800.0).abs() < 0.5);
        assert_eq!(band.min, 40.0);
        assert!((band.current - 100.0).abs() < 0.5);

        state.set_user_size("topbar", 250.0);
        layout(&mut root, &mut state, Rect::new(0.0, 0.0, 800.0, 600.0));
        assert!((state.rect_of_key("topbar").unwrap().h - 250.0).abs() < 0.5);
    }
}