aetna-core 0.3.3

Aetna — backend-agnostic UI library core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
//! 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.

use std::sync::Arc;

use crate::scroll::{ScrollAlignment, ScrollRequest};
use crate::state::UiState;
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 {
    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>)")
    }
}

/// 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 and
///   measures (via the intrinsic pass) each row that becomes visible,
///   caching the result on `UiState`. After enough scrolling the cache
///   is fully warm; before then, the scroll position may shift slightly
///   as estimates resolve to actual heights.
///
/// ## 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 { 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 { estimated_row_height: f32 },
}

#[derive(Clone)]
#[non_exhaustive]
pub struct VirtualItems {
    pub count: usize,
    pub mode: VirtualMode,
    pub build_row: Arc<dyn Fn(usize) -> El + Send + Sync>,
}

impl VirtualItems {
    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 },
            build_row: Arc::new(build_row),
        }
    }

    pub fn new_dyn<F>(count: usize, estimated_row_height: f32, build_row: F) -> Self
    where
        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,
            },
            build_row: Arc::new(build_row),
        }
    }
}

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("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 node's laid-out rect by its `computed_id`. 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.
    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 Aetna 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_id(root, "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) {
    {
        crate::profile_span!("layout::root_setup");
        ui_state
            .layout
            .computed_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();
    }
    crate::profile_span!("layout::children");
    layout_children(root, viewport, 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 role = role_token(&child.kind);
    let suffix = match (&child.key, role) {
        (Some(k), r) => format!("{r}[{k}]"),
        (None, r) => format!("{r}.{child_index}"),
    };
    assign_id(child, &format!("{parent_id}.{suffix}"));
}

/// 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();
    fn visit(node: &El, index: &mut rustc_hash::FxHashMap<String, String>) {
        if let Some(key) = &node.key {
            index
                .entry(key.clone())
                .or_insert_with(|| node.computed_id.clone());
        }
        for c in &node.children {
            visit(c, index);
        }
    }
    visit(root, &mut ui_state.layout.key_index);
}

/// 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) {
    assign_id(root, "root");
}

fn assign_id(node: &mut El, path: &str) {
    node.computed_id = path.to_string();
    for (i, c) in node.children.iter_mut().enumerate() {
        let role = role_token(&c.kind);
        let suffix = match (&c.key, role) {
            (Some(k), r) => format!("{r}[{k}]"),
            (None, r) => format!("{r}.{i}"),
        };
        let child_path = format!("{path}.{suffix}");
        assign_id(c, &child_path);
    }
}

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::Custom(name) => name,
    }
}

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 {
            ui_state.layout.computed_rects.insert(
                c.computed_id.clone(),
                Rect::new(node_rect.x, node_rect.y, 0.0, 0.0),
            );
            // 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.clone() {
        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);
        }
        return;
    }
    match node.axis {
        Axis::Overlay => {
            let inner = node_rect.inset(node.padding);
            for c in &mut node.children {
                let c_rect = overlay_rect(c, inner, node.align, node.justify);
                ui_state
                    .layout
                    .computed_rects
                    .insert(c.computed_id.clone(), c_rect);
                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);
    }
}

fn layout_custom(node: &mut El, node_rect: Rect, layout_fn: LayoutFn, ui_state: &mut UiState) {
    let inner = node_rect.inset(node.padding);
    let measure = |c: &El| intrinsic(c);
    // Split-borrow `ui_state` so the `rect_of_key` closure reads the
    // key index + computed rects while the surrounding function still
    // holds the mutable borrow needed to insert this node's children
    // back into `computed_rects` afterwards.
    let key_index = &ui_state.layout.key_index;
    let computed_rects = &ui_state.layout.computed_rects;
    let rect_of_key = |key: &str| -> Option<Rect> {
        let id = key_index.get(key)?;
        computed_rects.get(id).copied()
    };
    let rect_of_id = |id: &str| -> Option<Rect> { computed_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) {
        ui_state
            .layout
            .computed_rects
            .insert(c.computed_id.clone(), c_rect);
        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,
        } => layout_virtual_dynamic(
            node,
            inner,
            items.count,
            estimated_row_height,
            items.build_row,
            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>(
    node: &El,
    inner: Rect,
    count: usize,
    row_extent: F,
    ui_state: &mut UiState,
) where
    F: Fn(usize) -> (f32, f32),
{
    if ui_state.scroll.pending_requests.is_empty() {
        return;
    }
    let Some(key) = node.key.as_deref() else {
        return;
    };
    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,
            // 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;

    for req in matched {
        let ScrollRequest::ToRow { row, align, .. } = req else {
            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.clone(), new_offset);
    }
}

/// 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_end(node, stored, max_offset, ui_state);
    let offset = stored.clamp(0.0, max_offset);
    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.clone(), offset);
    ui_state.scroll.metrics.insert(
        node.computed_id.clone(),
        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);
    offset
}

/// 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 suffix = match (&child.key, role) {
        (Some(k), r) => format!("{r}[{k}]"),
        (None, r) => format!("{r}.{global_i}"),
    };
    assign_id(child, &format!("{parent_id}.{suffix}"));
}

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 total_h = count as f32 * row_height;
    resolve_scroll_requests(
        node,
        inner,
        count,
        |i| (i as f32 * row_height, row_height),
        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.
    let start = (offset / row_height).floor() as usize;
    let end = (((offset + inner.h) / row_height).ceil() as usize).min(count);

    let mut realized: Vec<El> = (start..end).map(|i| (build_row)(i)).collect();
    for (vis_i, child) in realized.iter_mut().enumerate() {
        let global_i = start + vis_i;
        assign_virtual_row_id(child, &node.computed_id, global_i);

        let row_y = inner.y + global_i as f32 * row_height - offset;
        let c_rect = Rect::new(inner.x, row_y, inner.w, row_height);
        ui_state
            .layout
            .computed_rects
            .insert(child.computed_id.clone(), c_rect);
        layout_children(child, c_rect, ui_state);
    }
    node.children = realized;
}

/// Variable-height virtualization. Each row's height comes from the
/// `UiState` measurement cache if the row has been seen before, else
/// from `estimated_row_height`. Visible rows are measured via
/// [`intrinsic_constrained`] at the viewport width; the measured value
/// is what positions sibling rows on this frame *and* gets written to
/// the cache for the next.
///
/// Trade-off: when a row is first seen, the estimate it replaced may
/// have been wrong by ~tens of pixels. The cumulative offset of the
/// rows above it is then slightly off, so the scroll position appears
/// to jump as the user scrolls into never-seen regions. Once the cache
/// is warm for a region, scrolling is stable.
fn layout_virtual_dynamic(
    node: &mut El,
    inner: Rect,
    count: usize,
    estimated_row_height: f32,
    build_row: Arc<dyn Fn(usize) -> El + Send + Sync>,
    ui_state: &mut UiState,
) {
    // Drop measurements past the new end if the data shrunk.
    if let Some(map) = ui_state
        .scroll
        .measured_row_heights
        .get_mut(&node.computed_id)
    {
        map.retain(|i, _| *i < count);
        if map.is_empty() {
            ui_state
                .scroll
                .measured_row_heights
                .remove(&node.computed_id);
        }
    }

    let (measured_sum, measured_count) = ui_state
        .scroll
        .measured_row_heights
        .get(&node.computed_id)
        .map(|m| (m.values().sum::<f32>(), m.len()))
        .unwrap_or((0.0, 0));
    let unmeasured = count.saturating_sub(measured_count);
    let total_h = measured_sum + (unmeasured as f32) * estimated_row_height;

    // 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::EnsureVisible { .. } => false,
        })
    });
    if has_request {
        // Snapshot the cache so the closure can read it while
        // `ui_state` stays mutably borrowed for the offsets write.
        let measured = ui_state
            .scroll
            .measured_row_heights
            .get(&node.computed_id)
            .cloned();
        resolve_scroll_requests(
            node,
            inner,
            count,
            |target| {
                let row_h = |i: usize| -> f32 {
                    measured
                        .as_ref()
                        .and_then(|m| m.get(&i).copied())
                        .unwrap_or(estimated_row_height)
                };
                let mut top = 0.0_f32;
                for i in 0..target {
                    top += row_h(i);
                }
                (top, row_h(target))
            },
            ui_state,
        );
    }

    let offset = write_virtual_scroll_state(node, inner, total_h, ui_state);

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

    // Find the first row whose bottom edge is past `offset` using a
    // scoped immutable borrow; releasing it before the render loop
    // keeps `ui_state` mutably available below.
    let (start, start_y) = {
        let measured = ui_state.scroll.measured_row_heights.get(&node.computed_id);
        let row_h = |i: usize| -> f32 {
            measured
                .and_then(|m| m.get(&i).copied())
                .unwrap_or(estimated_row_height)
        };
        let mut y = 0.0_f32;
        let mut start = 0;
        while start < count {
            let h = row_h(start);
            if y + h > offset {
                break;
            }
            y += h;
            start += 1;
        }
        (start, y)
    };
    let mut cursor_y = start_y;
    let mut idx = start;

    let mut realized: Vec<El> = Vec::new();
    let mut new_measurements: Vec<(usize, f32)> = Vec::new();

    while idx < count && cursor_y < offset + inner.h {
        let mut child = (build_row)(idx);
        assign_virtual_row_id(&mut child, &node.computed_id, idx);

        // Mirror the column-child sizing rules from `layout_axis`:
        // Fixed → literal, Hug → intrinsic, Fill → invalid here.
        let actual_h = match child.height {
            Size::Fixed(v) => v.max(0.0),
            Size::Hug => intrinsic_constrained(&child, Some(inner.w)).1.max(0.0),
            Size::Fill(_) => panic!(
                "virtual_list_dyn row {idx} on {:?} must size with Size::Fixed or Size::Hug; \
                 Size::Fill would absorb the viewport's height and break virtualization",
                node.computed_id,
            ),
        };
        new_measurements.push((idx, actual_h));

        let row_y = inner.y + cursor_y - offset;
        let c_rect = Rect::new(inner.x, row_y, inner.w, actual_h);
        ui_state
            .layout
            .computed_rects
            .insert(child.computed_id.clone(), c_rect);
        layout_children(&mut child, c_rect, ui_state);

        realized.push(child);
        cursor_y += actual_h;
        idx += 1;
    }

    if !new_measurements.is_empty() {
        let entry = ui_state
            .scroll
            .measured_row_heights
            .entry(node.computed_id.clone())
            .or_default();
        for (i, h) in new_measurements {
            entry.insert(i, h);
        }
    }

    node.children = realized;
}

/// 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: &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.clone(), 0.0);
        ui_state.scroll.metrics.insert(
            node.computed_id.clone(),
            crate::state::ScrollMetrics {
                viewport_h: inner.h,
                content_h: 0.0,
                max_offset: 0.0,
            },
        );
        return;
    }
    let content_bottom = node
        .children
        .iter()
        .map(|c| ui_state.rect(&c.computed_id).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.
    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_end(node, stored, max_offset, ui_state);
    let clamped = stored.clamp(0.0, max_offset);
    if clamped > 0.0 {
        for c in &node.children {
            shift_subtree_y(c, -clamped, ui_state);
        }
    }
    ui_state
        .scroll
        .offsets
        .insert(node.computed_id.clone(), clamped);
    ui_state.scroll.metrics.insert(
        node.computed_id.clone(),
        crate::state::ScrollMetrics {
            viewport_h: inner.h,
            content_h,
            max_offset,
        },
    );

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

/// Stored offset within this much of `max_offset` counts as "at the
/// tail" for [`El::pin_end`]. Wheel deltas are integer pixels, so a
/// half-pixel slack absorbs floating-point rounding without admitting
/// any deliberate user scroll.
const PIN_END_EPSILON: f32 = 0.5;

/// Apply [`El::pin_end`] semantics to `stored`. Reads the previous
/// frame's `max_offset` from `scroll.metrics` to decide whether the
/// stored offset has moved off the tail since last frame (user wheel /
/// drag / programmatic write), and updates `scroll.pin_active`
/// accordingly. Returns the offset that should be clamped + written
/// downstream — `max_offset` when the pin is 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.
fn resolve_pin_end(node: &El, stored: f32, max_offset: f32, ui_state: &mut UiState) -> f32 {
    if !node.pin_end {
        ui_state.scroll.pin_active.remove(&node.computed_id);
        ui_state.scroll.pin_prev_max.remove(&node.computed_id);
        return stored;
    }
    let prev_max = ui_state.scroll.pin_prev_max.get(&node.computed_id).copied();
    let prev_active = ui_state.scroll.pin_active.get(&node.computed_id).copied();
    let active = match prev_active {
        None => true,
        Some(prev) => {
            let prev_max = prev_max.unwrap_or(0.0);
            if prev && stored < prev_max - PIN_END_EPSILON {
                // Wheel / drag / EnsureVisible moved the offset off
                // the tail since last frame.
                false
            } else if !prev && prev_max > 0.0 && stored >= prev_max - PIN_END_EPSILON {
                // Returned to (or past) the previous tail (wheel-back,
                // jump-to-latest EnsureVisible, programmatic
                // set_scroll_offset). Compared against `prev_max`
                // rather than the current `max_offset` so a wheel-back
                // to the bottom re-engages even when content grew
                // between frames.
                true
            } else {
                prev
            }
        }
    };
    ui_state
        .scroll
        .pin_active
        .insert(node.computed_id.clone(), active);
    ui_state
        .scroll
        .pin_prev_max
        .insert(node.computed_id.clone(), max_offset);
    if active { max_offset } else { stored }
}

/// 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,
) {
    if ui_state.scroll.pending_requests.is_empty() {
        return;
    }
    let pending = std::mem::take(&mut ui_state.scroll.pending_requests);
    let mut remaining: Vec<ScrollRequest> = Vec::with_capacity(pending.len());
    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_str())
                .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.clone(), new_offset);
    }
    ui_state.scroll.pending_requests = remaining;
}

/// 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);
    let thumb_x = inner.right() - thumb_w - track_inset;
    let track_x = inner.right() - track_w - track_inset;
    ui_state.scroll.thumb_rects.insert(
        node.computed_id.clone(),
        Rect::new(thumb_x, thumb_y, thumb_w, thumb_h),
    );
    ui_state.scroll.thumb_tracks.insert(
        node.computed_id.clone(),
        Rect::new(track_x, inner.y, track_w, inner.h),
    );
}

fn shift_subtree_y(node: &El, dy: f32, ui_state: &mut UiState) {
    if let Some(rect) = ui_state.layout.computed_rects.get_mut(&node.computed_id) {
        rect.y += dy;
    }
    for c in &node.children {
        shift_subtree_y(c, dy, ui_state);
    }
}

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 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 };

    let intrinsics: Vec<(f32, f32)> = {
        crate::profile_span!("layout::axis::intrinsics");
        node.children
            .iter()
            .map(|c| child_intrinsic(c, vertical, cross_extent, node.align))
            .collect()
    };

    let mut consumed = 0.0;
    let mut fill_weight_total = 0.0;
    for (c, (iw, ih)) in node.children.iter().zip(intrinsics.iter()) {
        match main_size_of(c, *iw, *ih, vertical) {
            MainSize::Resolved(v) => consumed += v,
            MainSize::Fill(w) => fill_weight_total += w.max(0.001),
        }
    }
    let remaining = (main_extent - consumed - total_gap).max(0.0);

    // Free space after children + gaps. When there are Fill children they
    // claim it all, so justify is moot; otherwise this is what center/end
    // distribute around.
    let free_after_used = if fill_weight_total == 0.0 {
        remaining
    } else {
        0.0
    };
    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 && fill_weight_total == 0.0 {
            remaining / (n - 1) as f32
        } else {
            0.0
        };

    crate::profile_span!("layout::axis::place");
    for (i, (c, (iw, ih))) in node.children.iter_mut().zip(intrinsics).enumerate() {
        let main_size = match main_size_of(c, iw, ih, vertical) {
            MainSize::Resolved(v) => v,
            MainSize::Fill(w) => remaining * w.max(0.001) / fill_weight_total.max(0.001),
        };

        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.
        let cross_size = match cross_intent {
            Size::Fixed(v) => v,
            Size::Hug | Size::Fill(_) => match node.align {
                Align::Stretch => cross_extent,
                Align::Start | Align::Center | Align::End => cross_intrinsic,
            },
        };

        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)
        };
        ui_state
            .layout
            .computed_rects
            .insert(c.computed_id.clone(), c_rect);
        layout_children(c, c_rect, ui_state);

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

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 };
    match s {
        Size::Fixed(v) => MainSize::Resolved(v),
        Size::Hug => MainSize::Resolved(intr),
        Size::Fill(w) => MainSize::Fill(w),
    }
}

fn child_intrinsic(
    c: &El,
    vertical: bool,
    parent_cross_extent: f32,
    parent_align: Align,
) -> (f32, f32) {
    if !vertical {
        return intrinsic(c);
    }
    let available_width = match c.width {
        Size::Fixed(v) => Some(v),
        Size::Fill(_) => Some(parent_cross_extent),
        Size::Hug => match parent_align {
            Align::Stretch => Some(parent_cross_extent),
            Align::Start | Align::Center | Align::End => Some(parent_cross_extent),
        },
    };
    intrinsic_constrained(c, available_width)
}

fn overlay_rect(c: &El, parent: Rect, align: Align, justify: Justify) -> Rect {
    // Wrap-text height depends on width, so constrain the intrinsic
    // measurement to the width the child will actually be laid out at
    // — same shape as `child_intrinsic` does for column/row children.
    // Without this, a Fixed-width modal with a wrappable paragraph
    // measures as a single-line block and the modal's Hug height ends
    // up shorter than the actual content needs, eating bottom padding.
    let constrained_width = match c.width {
        Size::Fixed(v) => Some(v),
        Size::Fill(_) | Size::Hug => Some(parent.w),
    };
    let (iw, ih) = intrinsic_constrained(c, constrained_width);
    let w = match c.width {
        Size::Fixed(v) => v,
        Size::Hug => iw.min(parent.w),
        Size::Fill(_) => parent.w,
    };
    let h = match c.height {
        Size::Fixed(v) => v,
        Size::Hug => ih.min(parent.h),
        Size::Fill(_) => parent.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.
pub fn intrinsic(c: &El) -> (f32, f32) {
    intrinsic_constrained(c, None)
}

fn intrinsic_constrained(c: &El, available_width: Option<f32>) -> (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 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 apply_min(c, 0.0, 0.0);
    }
    if matches!(c.kind, Kind::Inlines) {
        return 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 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 apply_min(
                c,
                layout.width + c.padding.left + c.padding.right,
                layout.height() + c.padding.top + c.padding.bottom,
            );
        }
        return apply_min(c, 0.0, 0.0);
    }
    if c.icon.is_some() {
        return 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 apply_min(c, w, h);
    }
    if let Some(text) = &c.text {
        let unwrapped = text_metrics::layout_text_with_family(
            text,
            c.font_size,
            c.font_family,
            c.font_weight,
            c.font_mono,
            TextWrap::NoWrap,
            None,
        );
        let content_available = match c.text_wrap {
            TextWrap::NoWrap => None,
            TextWrap::Wrap => available_width
                .or(match c.width {
                    Size::Fixed(v) => Some(v),
                    Size::Fill(_) | Size::Hug => 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_wrap,
            content_available,
        );
        let w = content_available
            .map(|available| unwrapped.width.min(available) + c.padding.left + c.padding.right)
            .unwrap_or(layout.width + c.padding.left + c.padding.right);
        let h = layout.height + c.padding.top + c.padding.bottom;
        return apply_min(c, w, h);
    }
    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::Fill(_) | Size::Hug => 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_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,
        )
    } 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;
    }
    (w, h)
}

/// 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 unwrapped = text_metrics::layout_text_with_line_height_and_family(
        &concat,
        size,
        line_height,
        node.font_family,
        FontWeight::Regular,
        false,
        TextWrap::NoWrap,
        None,
    );
    let content_available = match node.text_wrap {
        TextWrap::NoWrap => None,
        TextWrap::Wrap => available_width
            .or(match node.width {
                Size::Fixed(v) => Some(v),
                Size::Fill(_) | Size::Hug => 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,
        node.text_wrap,
        content_available,
    );
    let w = content_available
        .map(|av| unwrapped.width.min(av) + node.padding.left + node.padding.right)
        .unwrap_or(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::Fill(_) | Size::Hug => None,
        }),
        TextWrap::NoWrap => None,
    }
    .map(|w| (w - node.padding.left - node.padding.right).max(1.0));

    let mut breaker = crate::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,
        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;

    /// 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 = state.rect(&root.children[0].computed_id);
        // 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
        );
    }

    /// `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 = state.rect(&root.children[0].computed_id);
        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
        );
    }

    /// 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 = state.rect(&root.children[0].computed_id);
        // 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 = state.rect(&root.children[0].computed_id);
        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 = state.rect(&root.children[0].computed_id).y;
        let y1 = state.rect(&root.children[1].computed_id).y;
        let y2 = state.rect(&root.children[2].computed_id).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 = state.rect(&root.children[0].computed_id).h;
        let small_h = state.rect(&root.children[1].computed_id).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 = state.rect(&root.children[0].computed_id);
        // 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 = state.rect(&root.children[0].computed_id);
        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(), 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 = state.rect(&root.children[0].computed_id);
        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(), 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(), 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 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(), 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 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 = state.rect(&root.children[0].computed_id);
        let r1 = state.rect(&root.children[1].computed_id);
        let r2 = state.rect(&root.children[2].computed_id);
        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 `computed_rects`
        // 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_id = &popover_layer.children[0].computed_id;
        let panel_rect = state.rect(panel_id);
        // 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 = state.rect(&root.children[0].computed_id);
        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 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(), 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 = state.rect(&root.children[0].computed_id);
        assert!(
            (r0.y - (-20.0)).abs() < 0.5,
            "row 2 expected y≈-20, got {}",
            r0.y
        );
    }

    #[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(), 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(), 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(), 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 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| {
            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| state.rect(&c.computed_id).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_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| {
            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");
        // At least the realized rows (≈ ceil(200/30) = 7) should be cached.
        assert!(
            measured.len() >= 7,
            "expected ≥ 7 cached row heights, got {}",
            measured.len()
        );
        for (_, h) in measured.iter() {
            assert!(
                (h - 30.0).abs() < 0.5,
                "expected cached height ≈ 30, got {h}"
            );
        }
    }

    #[test]
    fn virtual_list_dyn_total_height_uses_measured_plus_estimate() {
        // 20 rows of fixed 30px in a 200px viewport. First frame realizes
        // 7 rows (200/30 = 6.66, ceil = 7). Cache holds 7 × 30 = 210;
        // remaining 13 × estimate 50 = 650; content_h = 860; max_offset =
        // 660. A second frame with offset 9999 must clamp to that 660.
        let make_root = || {
            crate::tree::virtual_list_dyn(20, 50.0, |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));

        let measured_count = state
            .scroll
            .measured_row_heights
            .get(&root.computed_id)
            .map(|m| m.len())
            .unwrap_or(0);
        let expected_total = measured_count as f32 * 30.0 + (20 - measured_count) as f32 * 50.0;
        let expected_max_offset = expected_total - 200.0;

        state
            .scroll
            .offsets
            .insert(root.computed_id.clone(), 9999.0);
        let mut root2 = make_root();
        layout(&mut root2, &mut state, Rect::new(0.0, 0.0, 300.0, 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}"
        );
    }

    #[test]
    fn virtual_list_dyn_empty_count_realizes_no_children() {
        let mut root =
            crate::tree::virtual_list_dyn(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 = "estimated_row_height > 0.0")]
    fn virtual_list_dyn_zero_estimate_panics() {
        let _ =
            crate::tree::virtual_list_dyn(10, 0.0, |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 = state.rect(&root.children[0].computed_id);
        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 = state.rect(&root.children[0].computed_id);
        assert_eq!(panel_rect.w, PANEL_W, "panel keeps its Fixed width");

        let para_rect = state.rect(&root.children[0].children[0].computed_id);
        let button_rect = state.rect(&root.children[0].children[1].computed_id);

        // 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 aetna-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 = state.rect(&root.children[0].computed_id);
        let row1_rect = state.rect(&root.children[1].computed_id);
        let para0_rect = state.rect(&root.children[0].children[1].computed_id);

        // 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,
        );
    }
}