fission-layout 0.3.0

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

use anyhow::Result;
use fission_diagnostics::prelude as diag;
use fission_ir::op::{RichTextAnnotation, TextParagraphStyle, TextRun};
use fission_ir::{FlexDirection as IrFlexDirection, FlexWrap as IrFlexWrap, NodeId};
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::Arc;

pub use fission_ir::{FlexDirection, GridPlacement, GridTrack, LayoutOp};

/// A source of scroll offsets for scroll containers.
///
/// The layout engine calls [`get_offset`](ScrollDataSource::get_offset) for each
/// [`LayoutOp::Scroll`] node to learn how far the user has scrolled. Platform
/// backends implement this trait (or pass a closure, which also implements it).
///
/// # Example
///
/// ```rust
/// use fission_layout::ScrollDataSource;
/// use fission_ir::NodeId;
///
/// // A closure works as a ScrollDataSource:
/// let source = |_node: NodeId| -> f32 { 0.0 };
/// assert_eq!(source.get_offset(NodeId::explicit("scroll")), 0.0);
/// ```
pub trait ScrollDataSource {
    /// Returns the current scroll offset for the given scroll container node.
    fn get_offset(&self, node_id: NodeId) -> f32;
}

impl<F> ScrollDataSource for F
where
    F: Fn(NodeId) -> f32,
{
    fn get_offset(&self, node_id: NodeId) -> f32 {
        self(node_id)
    }
}

/// The scalar type used for all layout measurements.
///
/// Currently `f32`. Matches [`fission_ir::op::LayoutUnit`].
pub type LayoutUnit = f32;

/// Returns `value` if it is finite, otherwise `fallback`.
fn finite_or(value: LayoutUnit, fallback: LayoutUnit) -> LayoutUnit {
    if value.is_finite() {
        value
    } else {
        fallback
    }
}

/// A 2D point in layout coordinate space.
///
/// Represents an (x, y) position in logical pixels. Used for node origins and
/// coordinate calculations throughout the layout engine.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub struct LayoutPoint {
    /// Horizontal position in logical pixels.
    pub x: LayoutUnit,
    /// Vertical position in logical pixels.
    pub y: LayoutUnit,
}

impl LayoutPoint {
    /// The origin point: `(0.0, 0.0)`.
    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };

    /// Creates a new point from x and y coordinates.
    pub fn new(x: LayoutUnit, y: LayoutUnit) -> Self {
        Self { x, y }
    }
}

/// A 2D size in layout coordinate space.
///
/// Represents a width and height in logical pixels. Used as the output of layout
/// measurement and as input to constraints.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub struct LayoutSize {
    /// Width in logical pixels.
    pub width: LayoutUnit,
    /// Height in logical pixels.
    pub height: LayoutUnit,
}

impl LayoutSize {
    /// A zero-sized size: `(0.0, 0.0)`.
    pub const ZERO: Self = Self {
        width: 0.0,
        height: 0.0,
    };

    /// Creates a new size from width and height values.
    pub fn new(width: LayoutUnit, height: LayoutUnit) -> Self {
        Self { width, height }
    }
}

/// Minimum and maximum width/height bounds passed from parent to child during layout.
///
/// `BoxConstraints` is the fundamental mechanism for top-down size negotiation. A
/// parent creates constraints describing the space available to a child, and the
/// child returns a [`LayoutSize`] that satisfies those constraints.
///
/// There are two common patterns:
///
/// * **Tight constraints** -- `min == max`, forcing the child to a specific size.
///   Created with [`BoxConstraints::tight`].
/// * **Loose constraints** -- `min == 0`, giving the child freedom to be smaller
///   than the max. Created with [`BoxConstraints::loose`].
///
/// # Example
///
/// ```rust
/// use fission_layout::{BoxConstraints, LayoutSize};
///
/// let constraints = BoxConstraints::loose(800.0, 600.0);
/// assert_eq!(constraints.min_w, 0.0);
///
/// let child_wants = LayoutSize::new(300.0, 200.0);
/// let actual = constraints.constrain(child_wants);
/// assert_eq!(actual, child_wants); // fits within the constraints
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BoxConstraints {
    /// Minimum width the child must occupy.
    pub min_w: LayoutUnit,
    /// Maximum width the child may occupy. Can be `f32::INFINITY` for unbounded.
    pub max_w: LayoutUnit,
    /// Minimum height the child must occupy.
    pub min_h: LayoutUnit,
    /// Maximum height the child may occupy. Can be `f32::INFINITY` for unbounded.
    pub max_h: LayoutUnit,
}

impl BoxConstraints {
    /// Creates tight constraints that force a child to exactly `size`.
    ///
    /// Both min and max are set to the given width/height.
    pub fn tight(size: LayoutSize) -> Self {
        Self {
            min_w: size.width,
            max_w: size.width,
            min_h: size.height,
            max_h: size.height,
        }
    }

    /// Creates loose constraints: min is zero, max is the given values.
    ///
    /// The child can be anywhere from zero to `max_w` x `max_h`.
    pub fn loose(max_w: LayoutUnit, max_h: LayoutUnit) -> Self {
        Self {
            min_w: 0.0,
            max_w,
            min_h: 0.0,
            max_h,
        }
    }

    /// Returns `true` if the maximum width is finite (not `f32::INFINITY`).
    pub fn is_width_bounded(&self) -> bool {
        self.max_w.is_finite()
    }

    /// Returns `true` if the maximum height is finite (not `f32::INFINITY`).
    pub fn is_height_bounded(&self) -> bool {
        self.max_h.is_finite()
    }

    /// Clamps `size` so it falls within these constraints.
    ///
    /// The returned width is `max(min_w, min(size.width, max_w))`, and likewise
    /// for height.
    pub fn constrain(&self, size: LayoutSize) -> LayoutSize {
        LayoutSize {
            width: size.width.max(self.min_w).min(self.max_w),
            height: size.height.max(self.min_h).min(self.max_h),
        }
    }

    /// Returns the smallest size that satisfies these constraints: `(min_w, min_h)`.
    pub fn smallest(&self) -> LayoutSize {
        LayoutSize::new(self.min_w, self.min_h)
    }

    /// Returns new constraints shrunk inward by `padding`.
    ///
    /// Padding is `[left, right, top, bottom]`. Horizontal padding reduces the
    /// width bounds; vertical padding reduces the height bounds. Bounds are
    /// clamped to zero.
    pub fn deflate(&self, padding: [LayoutUnit; 4]) -> Self {
        let horiz = padding[0] + padding[1];
        let vert = padding[2] + padding[3];
        let max_w = (self.max_w - horiz).max(0.0);
        let max_h = (self.max_h - vert).max(0.0);
        let min_w = (self.min_w - horiz).max(0.0).min(max_w);
        let min_h = (self.min_h - vert).max(0.0).min(max_h);
        Self {
            min_w,
            max_w,
            min_h,
            max_h,
        }
    }

    /// Makes the constraints tighter by fixing the width and/or height.
    ///
    /// If `width` is `Some`, both `min_w` and `max_w` are set to that value
    /// (clamped to the current bounds). Same for `height`.
    pub fn tighten(&self, width: Option<LayoutUnit>, height: Option<LayoutUnit>) -> Self {
        let mut out = *self;
        if let Some(w) = width {
            let clamped = w.min(out.max_w).max(out.min_w);
            out.min_w = clamped;
            out.max_w = clamped;
        }
        if let Some(h) = height {
            let clamped = h.min(out.max_h).max(out.min_h);
            out.min_h = clamped;
            out.max_h = clamped;
        }
        if out.max_w < out.min_w {
            out.max_w = out.min_w;
        }
        if out.max_h < out.min_h {
            out.max_h = out.min_h;
        }
        out
    }

    /// Applies additional min/max constraints on top of the current ones.
    ///
    /// Each `Some` value further restricts the corresponding bound. `None` values
    /// leave the bound unchanged. After adjustment, max is clamped to be at least
    /// min.
    pub fn apply_min_max(
        &self,
        min_w: Option<LayoutUnit>,
        max_w: Option<LayoutUnit>,
        min_h: Option<LayoutUnit>,
        max_h: Option<LayoutUnit>,
    ) -> Self {
        let mut out = *self;
        if let Some(w) = min_w {
            out.min_w = out.min_w.max(w);
        }
        if let Some(h) = min_h {
            out.min_h = out.min_h.max(h);
        }
        if let Some(w) = max_w {
            out.max_w = out.max_w.min(w);
        }
        if let Some(h) = max_h {
            out.max_h = out.max_h.min(h);
        }
        if out.max_w < out.min_w {
            out.max_w = out.min_w;
        }
        if out.max_h < out.min_h {
            out.max_h = out.min_h;
        }
        out
    }

    /// Returns loose constraints with the same maximums but zeroed minimums.
    ///
    /// Useful when a parent wants to let a child be as small as it likes while
    /// still capping its maximum size.
    pub fn loosen(&self) -> Self {
        Self {
            min_w: 0.0,
            max_w: self.max_w,
            min_h: 0.0,
            max_h: self.max_h,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MeasureCacheKey {
    node_id: u128,
    min_w: u32,
    max_w: u32,
    min_h: u32,
    max_h: u32,
}

impl MeasureCacheKey {
    fn new(node_id: NodeId, constraints: BoxConstraints) -> Self {
        Self {
            node_id: node_id.as_u128(),
            min_w: constraints.min_w.to_bits(),
            max_w: constraints.max_w.to_bits(),
            min_h: constraints.min_h.to_bits(),
            max_h: constraints.max_h.to_bits(),
        }
    }
}

#[derive(Debug, Clone, Default)]
struct LayoutGraphValidationState {
    duplicate_nodes: Vec<NodeId>,
    missing_parent_refs: Vec<(NodeId, NodeId)>,
    missing_child_refs: Vec<(NodeId, NodeId)>,
    parent_child_mismatches: Vec<(NodeId, NodeId, Option<NodeId>)>,
    cycle_nodes: Vec<NodeId>,
    root_nodes: Vec<NodeId>,
}

impl LayoutGraphValidationState {
    fn first_error(&self) -> Option<anyhow::Error> {
        if let Some(node_id) = self.duplicate_nodes.first() {
            return Some(anyhow::anyhow!(
                "[layout] duplicate node id encountered during graph build: {:?}",
                node_id
            ));
        }
        if let Some((node_id, parent_id)) = self.missing_parent_refs.first() {
            return Some(anyhow::anyhow!(
                "[layout] node {:?} references missing parent {:?}",
                node_id,
                parent_id
            ));
        }
        if let Some((node_id, child_id)) = self.missing_child_refs.first() {
            return Some(anyhow::anyhow!(
                "[layout] node {:?} references missing child {:?}",
                node_id,
                child_id
            ));
        }
        if let Some((parent_id, child_id, actual_parent)) = self.parent_child_mismatches.first() {
            return Some(anyhow::anyhow!(
                "[layout] parent/child mismatch parent={:?} child={:?} child.parent_id={:?}",
                parent_id,
                child_id,
                actual_parent
            ));
        }
        if let Some(node_id) = self.cycle_nodes.first() {
            return Some(anyhow::anyhow!(
                "[layout] cycle detected while rebuilding graph at {:?}",
                node_id
            ));
        }
        None
    }
}

#[derive(Debug, Clone, Default)]
struct LayoutGraphState {
    graph_version: u64,
    last_layout_version: Option<u64>,
    node_order: Vec<NodeId>,
    node_fingerprints: HashMap<NodeId, u64>,
    nodes: HashMap<NodeId, LayoutInputNode>,
    parents: HashMap<NodeId, Option<NodeId>>,
    children: HashMap<NodeId, Vec<NodeId>>,
    roots: Vec<NodeId>,
    validation: LayoutGraphValidationState,
}

#[derive(Debug, Clone, Default)]
struct IncrementalLayoutReuseState {
    previous_snapshot: LayoutSnapshot,
    dirty_ancestors: HashSet<NodeId>,
}

impl LayoutGraphState {
    fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    fn mark_layout_complete(&mut self) {
        self.last_layout_version = Some(self.graph_version);
    }

    fn matches_input_nodes(&self, input_nodes: &[LayoutInputNode]) -> bool {
        if self.nodes.len() != input_nodes.len() || self.node_order.len() != input_nodes.len() {
            return false;
        }

        for (expected_id, node) in self.node_order.iter().zip(input_nodes.iter()) {
            if *expected_id != node.id {
                return false;
            }
            let Some(existing) = self.node_fingerprints.get(&node.id) else {
                return false;
            };
            if *existing != layout_input_fingerprint(node) {
                return false;
            }
        }

        true
    }

    fn from_input_nodes(input_nodes: &[LayoutInputNode], version: u64) -> Self {
        let mut state = Self {
            graph_version: version,
            ..Self::default()
        };
        state.replace_all_nodes(input_nodes);
        state
    }

    fn replace_all_nodes(&mut self, input_nodes: &[LayoutInputNode]) {
        self.node_order.clear();
        self.node_fingerprints.clear();
        self.nodes.clear();
        self.last_layout_version = None;

        let mut validation = LayoutGraphValidationState::default();
        let mut seen = HashSet::new();
        for node in input_nodes {
            if !seen.insert(node.id) {
                validation.duplicate_nodes.push(node.id);
            } else {
                self.node_order.push(node.id);
            }
            self.node_fingerprints
                .insert(node.id, layout_input_fingerprint(node));
            self.nodes.insert(node.id, node.clone());
        }

        self.rebuild_topology(validation);
    }

    fn update_nodes(&mut self, input_nodes: &[LayoutInputNode]) {
        let mut validation = LayoutGraphValidationState::default();
        let mut seen = HashSet::new();
        let mut next_order = Vec::with_capacity(input_nodes.len());
        let mut next_fingerprints = HashMap::with_capacity(input_nodes.len());
        let mut next_nodes = HashMap::with_capacity(input_nodes.len());

        for node in input_nodes {
            if !seen.insert(node.id) {
                validation.duplicate_nodes.push(node.id);
                continue;
            }
            next_order.push(node.id);
            next_fingerprints.insert(node.id, layout_input_fingerprint(node));
            next_nodes.insert(node.id, node.clone());
        }

        self.node_order = next_order;
        self.node_fingerprints = next_fingerprints;
        self.nodes = next_nodes;
        self.last_layout_version = None;
        self.rebuild_topology(validation);
    }

    fn rebuild_topology(&mut self, mut validation: LayoutGraphValidationState) {
        self.parents.clear();
        self.children.clear();
        self.roots.clear();

        for node_id in &self.node_order {
            let Some(node) = self.nodes.get(node_id) else {
                continue;
            };
            self.parents.insert(*node_id, node.parent_id);
            self.children.insert(*node_id, node.children_ids.clone());
            if node.parent_id.is_none() {
                self.roots.push(*node_id);
            } else if let Some(parent_id) = node.parent_id {
                if !self.nodes.contains_key(&parent_id) {
                    validation.missing_parent_refs.push((*node_id, parent_id));
                }
            }
        }

        for node_id in &self.node_order {
            let Some(node) = self.nodes.get(node_id) else {
                continue;
            };
            for child_id in &node.children_ids {
                let Some(child) = self.nodes.get(child_id) else {
                    validation.missing_child_refs.push((*node_id, *child_id));
                    continue;
                };
                if child.parent_id != Some(*node_id) {
                    validation
                        .parent_child_mismatches
                        .push((*node_id, *child_id, child.parent_id));
                }
            }
        }

        validation.root_nodes = self.roots.clone();
        validation.cycle_nodes = self.detect_cycle_nodes();
        self.validation = validation;
    }

    fn node(&self, node_id: NodeId) -> Option<&LayoutInputNode> {
        self.nodes.get(&node_id)
    }

    fn children_of(&self, node_id: NodeId) -> &[NodeId] {
        self.children
            .get(&node_id)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    fn parent_of(&self, node_id: NodeId) -> Option<NodeId> {
        self.parents.get(&node_id).copied().flatten()
    }

    fn ordered_nodes(&self) -> impl Iterator<Item = &LayoutInputNode> {
        self.node_order
            .iter()
            .filter_map(|node_id| self.nodes.get(node_id))
    }

    fn detect_cycle_nodes(&self) -> Vec<NodeId> {
        fn dfs(
            node_id: NodeId,
            children: &HashMap<NodeId, Vec<NodeId>>,
            visited: &mut HashSet<NodeId>,
            stack: &mut HashSet<NodeId>,
            cycle_nodes: &mut Vec<NodeId>,
        ) {
            if stack.contains(&node_id) {
                cycle_nodes.push(node_id);
                return;
            }
            if !visited.insert(node_id) {
                return;
            }

            stack.insert(node_id);
            if let Some(child_nodes) = children.get(&node_id) {
                for child_id in child_nodes {
                    dfs(*child_id, children, visited, stack, cycle_nodes);
                }
            }
            stack.remove(&node_id);
        }

        let mut visited = HashSet::new();
        let mut stack = HashSet::new();
        let mut cycle_nodes = Vec::new();
        for node_id in &self.node_order {
            dfs(
                *node_id,
                &self.children,
                &mut visited,
                &mut stack,
                &mut cycle_nodes,
            );
        }
        cycle_nodes.sort_by_key(|node_id| node_id.as_u128());
        cycle_nodes.dedup();
        cycle_nodes
    }
}

#[cfg(test)]
mod tests {
    use super::{LayoutEngine, LayoutGraphState, LayoutInputNode};
    use fission_ir::{LayoutOp, NodeId};

    fn box_node(
        id: NodeId,
        parent_id: Option<NodeId>,
        children_ids: Vec<NodeId>,
    ) -> LayoutInputNode {
        LayoutInputNode {
            id,
            parent_id,
            op: LayoutOp::Box {
                width: Some(40.0),
                height: Some(20.0),
                min_width: None,
                max_width: None,
                min_height: None,
                max_height: None,
                padding: [0.0; 4],
                flex_grow: 0.0,
                flex_shrink: 0.0,
                aspect_ratio: None,
            },
            children_ids,
            debug_name: format!("node-{}", id.as_u128()),
            width: Some(40.0),
            height: Some(20.0),
            flex_grow: 0.0,
            flex_shrink: 0.0,
            rich_text: None,
        }
    }

    #[test]
    fn matches_input_nodes_rejects_reordered_flattened_inputs() {
        let root = NodeId::from_u128(1);
        let first = NodeId::from_u128(2);
        let second = NodeId::from_u128(3);
        let canonical = vec![
            box_node(root, None, vec![first, second]),
            box_node(first, Some(root), vec![]),
            box_node(second, Some(root), vec![]),
        ];
        let reordered = vec![
            box_node(root, None, vec![first, second]),
            box_node(second, Some(root), vec![]),
            box_node(first, Some(root), vec![]),
        ];

        let state = LayoutGraphState::from_input_nodes(&canonical, 1);
        assert!(!state.matches_input_nodes(&reordered));
    }

    #[test]
    fn update_refreshes_node_order_for_reordered_flattened_inputs() {
        let root = NodeId::from_u128(10);
        let first = NodeId::from_u128(11);
        let second = NodeId::from_u128(12);
        let canonical = vec![
            box_node(root, None, vec![first, second]),
            box_node(first, Some(root), vec![]),
            box_node(second, Some(root), vec![]),
        ];
        let reordered = vec![
            box_node(root, None, vec![first, second]),
            box_node(second, Some(root), vec![]),
            box_node(first, Some(root), vec![]),
        ];

        let mut engine = LayoutEngine::new();
        engine.update(&canonical);
        engine.update(&reordered);

        let ordered = engine
            .graph_state
            .ordered_nodes()
            .map(|node| node.id)
            .collect::<Vec<_>>();
        assert_eq!(ordered, vec![root, second, first]);
    }
}

fn layout_input_fingerprint(node: &LayoutInputNode) -> u64 {
    let mut hasher = DefaultHasher::new();
    format!("{node:?}").hash(&mut hasher);
    hasher.finish()
}

/// An axis-aligned rectangle: an origin point plus a size.
///
/// `LayoutRect` is the final output for every node after layout: it says exactly
/// where the node sits on screen and how large it is.
///
/// # Example
///
/// ```rust
/// use fission_layout::{LayoutRect, LayoutPoint};
///
/// let rect = LayoutRect::new(10.0, 20.0, 300.0, 200.0);
/// assert_eq!(rect.right(), 310.0);
/// assert!(rect.contains(LayoutPoint::new(15.0, 25.0)));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct LayoutRect {
    /// The top-left corner of the rectangle.
    pub origin: LayoutPoint,
    /// The width and height of the rectangle.
    pub size: LayoutSize,
}

impl LayoutRect {
    /// Creates a rectangle from x, y, width, and height.
    pub fn new(x: LayoutUnit, y: LayoutUnit, width: LayoutUnit, height: LayoutUnit) -> Self {
        Self {
            origin: LayoutPoint { x, y },
            size: LayoutSize { width, height },
        }
    }

    /// The x coordinate of the left edge.
    pub fn x(&self) -> LayoutUnit {
        self.origin.x
    }
    /// The y coordinate of the top edge.
    pub fn y(&self) -> LayoutUnit {
        self.origin.y
    }
    /// The width of the rectangle.
    pub fn width(&self) -> LayoutUnit {
        self.size.width
    }
    /// The height of the rectangle.
    pub fn height(&self) -> LayoutUnit {
        self.size.height
    }

    /// The x coordinate of the right edge (`x + width`).
    pub fn right(&self) -> LayoutUnit {
        self.origin.x + self.size.width
    }
    /// The y coordinate of the bottom edge (`y + height`).
    pub fn bottom(&self) -> LayoutUnit {
        self.origin.y + self.size.height
    }

    /// Returns `true` if the point `p` lies within this rectangle (inclusive on
    /// the left/top edges, exclusive on the right/bottom edges).
    pub fn contains(&self, p: LayoutPoint) -> bool {
        p.x >= self.x() && p.x < self.right() && p.y >= self.y() && p.y < self.bottom()
    }
}

/// The computed geometry of a single layout node.
///
/// After layout, every node has a bounding rectangle (its position and size on
/// screen) and a content size (how large its content actually is, which may exceed
/// the rect for scroll containers).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LayoutNodeGeometry {
    /// The bounding rectangle of this node in absolute (screen) coordinates.
    pub rect: LayoutRect,
    /// The natural size of the node's content before clipping. For scroll containers,
    /// this may be larger than `rect.size`, indicating scrollable overflow.
    pub content_size: LayoutSize,
}

/// The complete output of a layout pass.
///
/// `LayoutSnapshot` maps every node to its computed geometry and records the
/// viewport size that was used. It is the primary interface between the layout
/// engine and downstream consumers (the renderer, hit testing, accessibility).
///
/// # Example
///
/// ```rust,no_run
/// use fission_layout::{LayoutSnapshot, LayoutSize};
/// use fission_ir::NodeId;
///
/// let snapshot = LayoutSnapshot::new(LayoutSize::new(800.0, 600.0));
/// assert_eq!(snapshot.viewport_size.width, 800.0);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct LayoutSnapshot {
    /// Computed geometry for every node, keyed by [`NodeId`].
    pub nodes: HashMap<NodeId, LayoutNodeGeometry>,
    /// The constraints that were passed to each node during layout. Useful for
    /// debugging. Skipped during serialization.
    #[serde(skip)]
    pub constraints: HashMap<NodeId, BoxConstraints>,
    /// The viewport size used for this layout pass.
    pub viewport_size: LayoutSize,
}

impl LayoutSnapshot {
    /// Creates an empty snapshot for the given viewport size.
    pub fn new(viewport_size: LayoutSize) -> Self {
        Self {
            nodes: HashMap::new(),
            constraints: HashMap::new(),
            viewport_size,
        }
    }

    /// Returns the full geometry (rect + content size) for a node, or `None` if
    /// the node was not part of this layout pass.
    pub fn get_node_geometry(&self, node_id: NodeId) -> Option<&LayoutNodeGeometry> {
        self.nodes.get(&node_id)
    }

    /// Returns just the bounding rectangle for a node, or `None` if not found.
    pub fn get_node_rect(&self, node_id: NodeId) -> Option<LayoutRect> {
        self.nodes.get(&node_id).map(|g| g.rect)
    }

    /// Returns the constraints that were passed to a node during layout, or `None`
    /// if not found. Useful for debugging layout issues.
    pub fn get_node_constraints(&self, node_id: NodeId) -> Option<BoxConstraints> {
        self.constraints.get(&node_id).copied()
    }
}

/// A flattened representation of a layout node, ready for the layout engine.
///
/// The widget compiler produces a list of `LayoutInputNode`s from the IR. Each node
/// carries its layout operation, parent/child relationships, flex participation
/// parameters, and optional rich text content for text measurement.
///
/// The layout engine operates on `&[LayoutInputNode]` rather than traversing the
/// IR directly, which keeps the engine decoupled from the IR's internal structure.
#[derive(Debug, Clone)]
pub struct LayoutInputNode {
    /// The unique identity of this node.
    pub id: NodeId,
    /// The parent node's ID, or `None` for the root.
    pub parent_id: Option<NodeId>,
    /// The layout operation this node performs.
    pub op: LayoutOp,
    /// Ordered list of child node IDs.
    pub children_ids: Vec<NodeId>,
    /// A human-readable name for debugging and diagnostics.
    pub debug_name: String,
    /// Explicit width override, or `None` to derive from constraints.
    pub width: Option<LayoutUnit>,
    /// Explicit height override, or `None` to derive from constraints.
    pub height: Option<LayoutUnit>,
    /// How much extra main-axis space this node claims from its flex parent.
    pub flex_grow: LayoutUnit,
    /// How much this node shrinks when its flex parent overflows.
    pub flex_shrink: LayoutUnit,
    /// Optional rich text content. When present, the layout engine uses the
    /// [`TextMeasurer`] to determine the node's intrinsic size from the text.
    pub rich_text: Option<Vec<TextRun>>,
}

/// Per-line metrics returned by text measurement.
///
/// When the layout engine or hit-testing code needs to know about individual lines
/// of text (e.g., for cursor positioning in a multi-line text field), it calls
/// [`TextMeasurer::get_line_metrics`] and receives a `Vec<LineMetric>`.
pub struct LineMetric {
    /// Byte index where this line starts in the source string.
    pub start_index: usize,
    /// Byte index where this line ends in the source string (exclusive).
    pub end_index: usize,
    /// Distance from the top of the line to its alphabetic baseline, in logical pixels.
    pub baseline: f32,
    /// Total height of the line (ascent + descent + leading), in logical pixels.
    pub height: f32,
    /// Measured width of the line's content, in logical pixels.
    pub width: f32,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RichTextInlineBox {
    pub id: u64,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RichTextLayoutInfo {
    pub width: f32,
    pub height: f32,
    pub inline_boxes: Vec<RichTextInlineBox>,
}

/// A platform-provided text measurement backend.
///
/// The layout engine does not shape or measure text itself. Instead, platform
/// backends implement `TextMeasurer` to wrap their native text engine (CoreText
/// on macOS, DirectWrite on Windows, HarfBuzz + FreeType on Linux, etc.).
///
/// All methods have default implementations that return zero-sized results, so
/// you only need to override the methods your backend supports.
///
/// # Required
///
/// * [`measure`](TextMeasurer::measure) -- must be implemented to get correct text layout.
///
/// # Optional
///
/// * [`hit_test`](TextMeasurer::hit_test) -- needed for click-to-cursor in text fields.
/// * [`get_line_metrics`](TextMeasurer::get_line_metrics) -- needed for multi-line cursor navigation.
/// * [`get_caret_position`](TextMeasurer::get_caret_position) -- needed for drawing the text cursor.
/// * [`measure_rich_text`](TextMeasurer::measure_rich_text) -- needed for mixed-style text.
pub trait TextMeasurer: Send + Sync {
    /// Measures single-style text and returns `(width, height)` in logical pixels.
    ///
    /// If `available_width` is `Some`, the text should be wrapped at that width.
    /// If `None`, the text is measured as a single unwrapped line.
    fn measure(&self, text: &str, font_size: f32, available_width: Option<f32>) -> (f32, f32);

    /// Returns the byte index of the character closest to the point `(x, y)`,
    /// relative to the text's origin. Used for click-to-cursor in text fields.
    ///
    /// The default implementation returns `0`.
    fn hit_test(
        &self,
        _text: &str,
        _font_size: f32,
        _available_width: Option<f32>,
        _x: f32,
        _y: f32,
    ) -> usize {
        0
    }

    /// Returns per-line metrics for the given text. Used for multi-line text fields
    /// and line-based cursor navigation.
    ///
    /// The default implementation returns an empty vec.
    fn get_line_metrics(
        &self,
        _text: &str,
        _font_size: f32,
        _available_width: Option<f32>,
    ) -> Vec<LineMetric> {
        vec![]
    }

    /// Returns the `(x, y)` position of the text cursor at `caret_index` (byte offset),
    /// relative to the text's origin.
    ///
    /// The default implementation returns `(0.0, 0.0)`.
    fn get_caret_position(
        &self,
        _text: &str,
        _font_size: f32,
        _available_width: Option<f32>,
        _caret_index: usize,
    ) -> (f32, f32) {
        (0.0, 0.0)
    }

    /// Measures multi-style (rich) text and returns `(width, height)` in logical pixels.
    ///
    /// The default implementation returns `(0.0, 0.0)`.
    fn measure_rich_text(&self, _runs: &[TextRun], _available_width: Option<f32>) -> (f32, f32) {
        (0.0, 0.0)
    }

    /// Measures rich text and returns positioned inline-widget boxes, if any.
    ///
    /// Backends that understand inline rich-text widget markers should override
    /// this so layout can place the child widgets at the same coordinates used
    /// by text shaping.
    fn layout_rich_text(
        &self,
        runs: &[TextRun],
        available_width: Option<f32>,
    ) -> RichTextLayoutInfo {
        let (width, height) = if runs.len() == 1 {
            let run = &runs[0];
            self.measure(&run.text, run.style.font_size, available_width)
        } else {
            self.measure_rich_text(runs, available_width)
        };
        RichTextLayoutInfo {
            width,
            height,
            inline_boxes: Vec::new(),
        }
    }

    /// Hit-test rich text (styled runs) at the given (x, y) position.
    /// Returns the byte offset into the concatenated text of all runs.
    /// Default falls back to plain hit_test using the first run's font size.
    fn hit_test_rich(
        &self,
        runs: &[TextRun],
        _available_width: Option<f32>,
        x: f32,
        y: f32,
    ) -> usize {
        // Default: concatenate text and use plain hit_test
        let text: String = runs.iter().map(|r| r.text.as_str()).collect();
        let font_size = runs.first().map(|r| r.style.font_size).unwrap_or(13.0);
        self.hit_test(&text, font_size, None, x, y)
    }

    /// Resolves the rich-text annotation at the given point, if any.
    ///
    /// This is used for interactive rich-text spans that need hit testing
    /// against shaped rich text rather than box nodes.
    fn resolve_rich_text_annotation_at_point(
        &self,
        _runs: &[TextRun],
        _available_width: Option<f32>,
        _x: f32,
        _y: f32,
        _paragraph_style: TextParagraphStyle,
        _annotations: &[RichTextAnnotation],
    ) -> Option<RichTextAnnotation> {
        None
    }
}

/// The constraint-based layout solver.
///
/// `LayoutEngine` walks the node tree top-down, passing [`BoxConstraints`] from
/// parent to child, and bottom-up, returning [`LayoutSize`] from child to parent.
/// The final result is a [`LayoutSnapshot`] that maps every node to its absolute
/// screen-space rectangle.
///
/// The engine optionally holds a [`TextMeasurer`] for sizing text nodes. Without
/// one, text nodes are treated as zero-sized.
///
/// # Example
///
/// ```rust,no_run
/// use fission_layout::*;
/// use fission_ir::NodeId;
/// use std::sync::Arc;
///
/// let mut engine = LayoutEngine::new();
/// // engine = engine.with_measurer(my_text_measurer);
///
/// // let snapshot = engine.compute_layout(&nodes, root_id, viewport, &|_| 0.0).unwrap();
/// ```
pub struct LayoutEngine {
    measurer: Option<Arc<dyn TextMeasurer>>,
    graph_state: LayoutGraphState,
    next_graph_version: u64,
    incremental_reuse: Option<IncrementalLayoutReuseState>,
}

impl LayoutEngine {
    const MAX_LAYOUT_RECURSION_DEPTH: usize = 100;

    /// Creates a new layout engine with no text measurer.
    ///
    /// Text nodes will be treated as zero-sized until a measurer is provided
    /// via [`with_measurer`](LayoutEngine::with_measurer).
    pub fn new() -> Self {
        Self {
            measurer: None,
            graph_state: LayoutGraphState::default(),
            next_graph_version: 1,
            incremental_reuse: None,
        }
    }

    /// Returns a new engine with the given text measurer attached.
    ///
    /// This is a builder-style method that consumes and returns `self`.
    pub fn with_measurer(mut self, measurer: Arc<dyn TextMeasurer>) -> Self {
        self.measurer = Some(measurer);
        self
    }

    fn allocate_graph_version(&mut self) -> u64 {
        let version = self.next_graph_version;
        self.next_graph_version = self.next_graph_version.saturating_add(1);
        version
    }

    fn refresh_graph_state(&mut self, input_nodes: &[LayoutInputNode]) {
        let version = self.allocate_graph_version();
        self.graph_state = LayoutGraphState::from_input_nodes(input_nodes, version);
    }

    fn ensure_graph_state(&mut self, input_nodes: &[LayoutInputNode]) {
        if self.graph_state.is_empty() || !self.graph_state.matches_input_nodes(input_nodes) {
            self.refresh_graph_state(input_nodes);
        }
    }

    fn validate_graph_state(&self, root: NodeId) -> Result<()> {
        if let Some(err) = self.graph_state.validation.first_error() {
            return Err(err);
        }
        if !self.graph_state.nodes.contains_key(&root) {
            anyhow::bail!("[verify] missing node {:?}", root);
        }
        if !self.graph_state.roots.contains(&root)
            && self
                .graph_state
                .parents
                .get(&root)
                .copied()
                .flatten()
                .is_some()
        {
            anyhow::bail!("[verify] root {:?} is not a graph root", root);
        }
        if let Some(last_layout_version) = self.graph_state.last_layout_version {
            if last_layout_version > self.graph_state.graph_version {
                anyhow::bail!(
                    "[verify] cached layout version {} exceeds graph version {}",
                    last_layout_version,
                    self.graph_state.graph_version
                );
            }
        }
        Ok(())
    }

    /// Refreshes the cached graph state after upstream layout edits.
    ///
    /// Unchanged nodes keep their cached graph entries while edited topology and
    /// fingerprints are synchronized to the latest flattened node list.
    pub fn update(&mut self, input_nodes: &[LayoutInputNode]) {
        if self.graph_state.is_empty() {
            self.refresh_graph_state(input_nodes);
            return;
        }

        if self.graph_state.matches_input_nodes(input_nodes) {
            return;
        }

        let version = self.allocate_graph_version();
        self.graph_state.graph_version = version;
        self.graph_state.update_nodes(input_nodes);
    }

    /// Rebuilds internal data structures from the full node list.
    pub fn rebuild(&mut self, input_nodes: &[LayoutInputNode]) -> Result<()> {
        self.refresh_graph_state(input_nodes);
        if let Some(err) = self.graph_state.validation.first_error() {
            return Err(err);
        }
        Ok(())
    }

    /// Verifies parent-child consistency and checks for cycles in the node graph.
    ///
    /// Call this during development/testing to catch malformed IR before it causes
    /// layout panics. Returns `Err` with a description of the first problem found.
    pub fn verify_post_update(&self, input_nodes: &[LayoutInputNode], root: NodeId) -> Result<()> {
        if self.graph_state.matches_input_nodes(input_nodes) {
            return self.validate_graph_state(root);
        }

        let node_map: HashMap<NodeId, &LayoutInputNode> =
            input_nodes.iter().map(|n| (n.id, n)).collect();
        // Parent/child consistency
        for n in input_nodes {
            for child in &n.children_ids {
                let child_node = node_map
                    .get(child)
                    .ok_or_else(|| anyhow::anyhow!("[verify] child {:?} not found", child))?;
                if child_node.parent_id != Some(n.id) {
                    anyhow::bail!("[verify] parent/child mismatch parent={:?} child={:?} child.parent_id={:?}", n.id, child, child_node.parent_id);
                }
            }
        }
        // Cycle via DFS
        fn dfs(
            id: NodeId,
            map: &HashMap<NodeId, &LayoutInputNode>,
            visited: &mut HashSet<NodeId>,
            stack: &mut HashSet<NodeId>,
        ) -> Result<()> {
            if !visited.insert(id) {
                return Ok(());
            }
            stack.insert(id);
            let node = map
                .get(&id)
                .ok_or_else(|| anyhow::anyhow!("[verify] missing node {:?}", id))?;
            for child in &node.children_ids {
                if stack.contains(child) {
                    anyhow::bail!("[verify] cycle detected at {:?} -> {:?}", id, child);
                }
                dfs(*child, map, visited, stack)?;
            }
            stack.remove(&id);
            Ok(())
        }
        let mut visited = HashSet::new();
        let mut stack = HashSet::new();
        dfs(root, &node_map, &mut visited, &mut stack)?;
        Ok(())
    }

    /// Computes layout for the entire node tree and returns a snapshot.
    ///
    /// This is the main entry point. It runs the constraint-based layout algorithm
    /// starting from `root_node_id`, using `viewport_size` as the root constraints,
    /// and querying `scroll_source` for scroll offsets. After layout, it emits scroll
    /// diagnostics for debugging.
    ///
    /// # Arguments
    ///
    /// * `input_nodes` -- The flat list of all layout nodes.
    /// * `root_node_id` -- Which node is the root of the tree.
    /// * `viewport_size` -- The size of the window/screen.
    /// * `scroll_source` -- Provides scroll offsets for scroll containers.
    ///
    /// # Errors
    ///
    /// Returns `Err` if a cycle is detected or a required node is missing.
    pub fn compute_layout(
        &mut self,
        input_nodes: &[LayoutInputNode],
        root_node_id: NodeId,
        viewport_size: LayoutSize,
        scroll_source: &impl ScrollDataSource,
    ) -> Result<LayoutSnapshot> {
        self.ensure_graph_state(input_nodes);
        self.validate_graph_state(root_node_id)?;
        let snapshot = self.compute_layout_constraints(
            input_nodes,
            root_node_id,
            viewport_size,
            scroll_source,
        )?;
        self.emit_scroll_diagnostics(&snapshot);
        Ok(snapshot)
    }

    /// Lower-level layout that skips scroll diagnostics.
    ///
    /// Same as [`compute_layout`](LayoutEngine::compute_layout) but does not emit
    /// diagnostic events. Useful when you need the snapshot but not the debug output.
    pub fn compute_layout_constraints(
        &mut self,
        input_nodes: &[LayoutInputNode],
        root_node_id: NodeId,
        viewport_size: LayoutSize,
        scroll_source: &impl ScrollDataSource,
    ) -> Result<LayoutSnapshot> {
        self.ensure_graph_state(input_nodes);
        self.validate_graph_state(root_node_id)?;

        // Root constraints should be tight to the viewport size if no explicit size is given
        let mut constraints = BoxConstraints::tight(viewport_size);
        if let Some(root) = self.graph_state.node(root_node_id) {
            // Only loosen if explicit dimensions are provided for the root node
            if root.width.is_some() || root.height.is_some() {
                constraints = BoxConstraints::loose(viewport_size.width, viewport_size.height)
                    .tighten(root.width, root.height);
            }
        }

        let mut snapshot = LayoutSnapshot::new(viewport_size);
        let mut measure_cache = HashMap::new();
        self.layout_node_constraints(
            root_node_id,
            constraints,
            LayoutPoint::ZERO,
            &mut snapshot.nodes,
            &mut snapshot.constraints,
            &mut measure_cache,
            scroll_source,
            true,
            0,
        )?;

        let visual_location = |node_id: NodeId| -> Option<LayoutPoint> {
            let mut pos = snapshot.nodes.get(&node_id)?.rect.origin;
            let mut current = self.graph_state.parent_of(node_id);
            while let Some(parent_id) = current {
                if let Some(parent) = self.graph_state.node(parent_id) {
                    if let LayoutOp::Scroll { direction, .. } = &parent.op {
                        let offset = scroll_source.get_offset(parent_id);
                        match direction {
                            FlexDirection::Row => pos.x -= offset,
                            FlexDirection::Column => pos.y -= offset,
                        }
                    }
                    current = self.graph_state.parent_of(parent_id);
                } else {
                    break;
                }
            }
            Some(pos)
        };

        let mut flyout_abs_overrides: HashMap<NodeId, (f32, f32)> = HashMap::new();
        for node in self.graph_state.ordered_nodes() {
            if let LayoutOp::Flyout { anchor, content } = node.op {
                if let (Some(anchor_geom), Some(content_geom)) =
                    (snapshot.nodes.get(&anchor), snapshot.nodes.get(&content))
                {
                    if let Some(anchor_abs) = visual_location(anchor) {
                        let content_w = content_geom.rect.width();
                        let content_h = content_geom.rect.height();
                        let anchor_h = anchor_geom.rect.height();
                        let max_left = (snapshot.viewport_size.width - content_w).max(0.0);
                        let left_rel = anchor_abs.x.clamp(0.0, max_left);

                        let below_top = anchor_abs.y + anchor_h;
                        let max_top = (snapshot.viewport_size.height - content_h).max(0.0);
                        let top_rel = if below_top + content_h <= snapshot.viewport_size.height {
                            below_top
                        } else {
                            let above_top = anchor_abs.y - content_h;
                            if above_top >= 0.0 {
                                above_top
                            } else {
                                below_top.clamp(0.0, max_top)
                            }
                        };
                        flyout_abs_overrides.insert(content, (left_rel, top_rel));
                    }
                }
            }
        }

        if !flyout_abs_overrides.is_empty() {
            for (nid, (abs_x, abs_y)) in flyout_abs_overrides {
                if let Some(current) = snapshot.nodes.get(&nid) {
                    let dx = abs_x - current.rect.origin.x;
                    let dy = abs_y - current.rect.origin.y;
                    let mut stack = vec![(nid, 0usize)];
                    while let Some((current_id, depth)) = stack.pop() {
                        if depth > Self::MAX_LAYOUT_RECURSION_DEPTH {
                            return Err(self.layout_depth_overflow(current_id, depth));
                        }
                        if let Some(geometry) = snapshot.nodes.get_mut(&current_id) {
                            geometry.rect.origin.x += dx;
                            geometry.rect.origin.y += dy;
                        }
                        for child_id in self.graph_state.children_of(current_id).iter().rev() {
                            stack.push((*child_id, depth + 1));
                        }
                    }
                }
            }
        }

        self.graph_state.mark_layout_complete();
        self.incremental_reuse = None;

        Ok(snapshot)
    }

    pub fn compute_layout_incremental(
        &mut self,
        input_nodes: &[LayoutInputNode],
        root_node_id: NodeId,
        viewport_size: LayoutSize,
        scroll_source: &impl ScrollDataSource,
        previous_snapshot: &LayoutSnapshot,
        dirty_nodes: &HashSet<NodeId>,
    ) -> Result<LayoutSnapshot> {
        self.ensure_graph_state(input_nodes);
        self.validate_graph_state(root_node_id)?;

        let mut dirty_ancestors = HashSet::new();
        for node_id in dirty_nodes {
            let mut current = Some(*node_id);
            while let Some(id) = current {
                if !dirty_ancestors.insert(id) {
                    break;
                }
                current = self.graph_state.parent_of(id);
            }
        }
        dirty_ancestors.insert(root_node_id);

        self.incremental_reuse = Some(IncrementalLayoutReuseState {
            previous_snapshot: previous_snapshot.clone(),
            dirty_ancestors,
        });
        let result = self.compute_layout_constraints(
            input_nodes,
            root_node_id,
            viewport_size,
            scroll_source,
        );
        self.incremental_reuse = None;
        result
    }

    fn emit_scroll_diagnostics(&self, snapshot: &LayoutSnapshot) {
        use fission_diagnostics::prelude as diag;
        let trace_scroll = std::env::var("FISSION_SCROLL_TRACE").ok().as_deref() == Some("1");
        for n in self.graph_state.ordered_nodes() {
            if let LayoutOp::Scroll { .. } = n.op {
                if let Some(g) = snapshot.nodes.get(&n.id) {
                    let note = if g.rect.height() <= 0.0 {
                        let parent_op = n
                            .parent_id
                            .and_then(|pid| self.graph_state.node(pid))
                            .map(|p| format!("{:?}", p.op));
                        let parent_constraints = n
                            .parent_id
                            .and_then(|pid| snapshot.constraints.get(&pid))
                            .copied();
                        snapshot
                            .constraints
                            .get(&n.id)
                            .map(|c| {
                                format!(
                                    "op={:?} parent={:?} parent_op={:?} parent_constraints={:?} constraints={:?}",
                                    n.op,
                                    n.parent_id,
                                    parent_op,
                                    parent_constraints,
                                    c
                                )
                            })
                    } else {
                        None
                    };
                    diag::emit(
                        diag::DiagCategory::Layout,
                        diag::DiagLevel::Debug,
                        diag::DiagEventKind::ScrollExtent {
                            node: n.id.as_u128(),
                            viewport_w: g.rect.width(),
                            viewport_h: g.rect.height(),
                            content_w: g.content_size.width,
                            content_h: g.content_size.height,
                            note,
                        },
                    );
                    if trace_scroll {
                        eprintln!(
                            "[scroll-trace] node={} viewport=({:.1},{:.1}) content=({:.1},{:.1})",
                            n.id.as_u128(),
                            g.rect.width(),
                            g.rect.height(),
                            g.content_size.width,
                            g.content_size.height
                        );
                    }
                }
            }
        }
    }

    fn layout_depth_overflow(&self, node_id: NodeId, depth: usize) -> anyhow::Error {
        let details = format!(
            "layout recursion depth {} exceeded max {} at node {}",
            depth,
            Self::MAX_LAYOUT_RECURSION_DEPTH,
            node_id.as_u128()
        );
        diag::emit(
            diag::DiagCategory::Invariants,
            diag::DiagLevel::Error,
            diag::DiagEventKind::InvariantViolation {
                kind: "layout_recursion_depth".into(),
                node: Some(node_id.as_u128()),
                details: details.clone(),
                dump_ref: None,
            },
        );
        anyhow::anyhow!(details)
    }

    fn copy_cached_subtree(
        &self,
        node_id: NodeId,
        origin: LayoutPoint,
        current_constraints: BoxConstraints,
        out: &mut HashMap<NodeId, LayoutNodeGeometry>,
        constraints_out: &mut HashMap<NodeId, BoxConstraints>,
    ) -> Result<Option<LayoutSize>> {
        let Some(reuse) = self.incremental_reuse.as_ref() else {
            return Ok(None);
        };
        if reuse.dirty_ancestors.contains(&node_id) {
            return Ok(None);
        }

        let Some(previous_geometry) = reuse.previous_snapshot.nodes.get(&node_id) else {
            return Ok(None);
        };
        let Some(previous_constraints) = reuse.previous_snapshot.constraints.get(&node_id).copied()
        else {
            return Ok(None);
        };
        if previous_constraints != current_constraints {
            return Ok(None);
        }

        let dx = origin.x - previous_geometry.rect.origin.x;
        let dy = origin.y - previous_geometry.rect.origin.y;
        let mut stack = vec![(node_id, 0usize)];
        while let Some((current_id, depth)) = stack.pop() {
            if depth > Self::MAX_LAYOUT_RECURSION_DEPTH {
                return Err(self.layout_depth_overflow(current_id, depth));
            }
            let Some(previous_geometry) = reuse.previous_snapshot.nodes.get(&current_id) else {
                return Ok(None);
            };
            let Some(previous_constraints) = reuse
                .previous_snapshot
                .constraints
                .get(&current_id)
                .copied()
            else {
                return Ok(None);
            };

            let mut geometry = previous_geometry.clone();
            geometry.rect.origin.x += dx;
            geometry.rect.origin.y += dy;
            out.insert(current_id, geometry);
            constraints_out.insert(current_id, previous_constraints);

            let children = self.graph_state.children_of(current_id);
            for child_id in children.iter().rev() {
                stack.push((*child_id, depth + 1));
            }
        }

        Ok(Some(previous_geometry.content_size))
    }

    fn layout_node_constraints(
        &self,
        node_id: NodeId,
        constraints: BoxConstraints,
        origin: LayoutPoint,
        out: &mut HashMap<NodeId, LayoutNodeGeometry>,
        constraints_out: &mut HashMap<NodeId, BoxConstraints>,
        measure_cache: &mut HashMap<MeasureCacheKey, LayoutSize>,
        scroll_source: &impl ScrollDataSource,
        record: bool,
        depth: usize,
    ) -> Result<LayoutSize> {
        if depth > Self::MAX_LAYOUT_RECURSION_DEPTH {
            return Err(self.layout_depth_overflow(node_id, depth));
        }
        if !record {
            let cache_key = MeasureCacheKey::new(node_id, constraints);
            if let Some(cached) = measure_cache.get(&cache_key).copied() {
                return Ok(cached);
            }
        }
        let node = match self.graph_state.node(node_id) {
            Some(node) => node,
            None => return Ok(LayoutSize::ZERO),
        };

        if record {
            constraints_out.insert(node_id, constraints);
        }

        if record {
            if let Some(reused) =
                self.copy_cached_subtree(node_id, origin, constraints, out, constraints_out)?
            {
                return Ok(reused);
            }
        }

        let mut flow_children: Vec<NodeId> = Vec::new();
        let mut abs_children: Vec<NodeId> = Vec::new();
        for child_id in self.graph_state.children_of(node_id) {
            let is_absolute = matches!(
                self.graph_state.node(*child_id).map(|n| &n.op),
                Some(LayoutOp::AbsoluteFill) | Some(LayoutOp::Positioned { .. })
            );
            if is_absolute {
                abs_children.push(*child_id);
            } else {
                flow_children.push(*child_id);
            }
        }
        let rich_text_inline_children = node.rich_text.is_some() && !flow_children.is_empty();

        let mut content_size;
        let size = match &node.op {
            LayoutOp::Box {
                width,
                height,
                min_width,
                max_width,
                min_height,
                max_height,
                padding,
                aspect_ratio,
                ..
            } => {
                let mut local =
                    constraints.apply_min_max(*min_width, *max_width, *min_height, *max_height);
                local = local.tighten(*width, *height);
                if let Some(ratio) = aspect_ratio.filter(|r| *r > 0.0) {
                    let mut target_w = *width;
                    let mut target_h = *height;

                    if target_w.is_some() && target_h.is_none() {
                        target_h = Some(target_w.unwrap() / ratio);
                    } else if target_h.is_some() && target_w.is_none() {
                        target_w = Some(target_h.unwrap() * ratio);
                    } else if target_w.is_none() && target_h.is_none() {
                        if local.is_width_bounded() || local.is_height_bounded() {
                            let (mut w, mut h) = if local.is_width_bounded() {
                                let w = local.max_w;
                                let h = w / ratio;
                                (w, h)
                            } else {
                                let h = local.max_h;
                                let w = h * ratio;
                                (w, h)
                            };
                            if local.is_width_bounded()
                                && local.is_height_bounded()
                                && h > local.max_h
                            {
                                h = local.max_h;
                                w = h * ratio;
                            }
                            target_w = Some(w);
                            target_h = Some(h);
                        }
                    }

                    if target_w.is_some() || target_h.is_some() {
                        local = local.tighten(target_w, target_h);
                    }
                }
                let base_child_constraints = local.deflate(*padding);
                let mut max_child = LayoutSize::ZERO;
                let mut measured_children: Vec<(NodeId, BoxConstraints, LayoutSize)> = Vec::new();
                if !rich_text_inline_children {
                    for child_id in &flow_children {
                        let (child_width, child_height, child_max_width, child_max_height) = self
                            .graph_state
                            .node(*child_id)
                            .map(|child| match &child.op {
                                LayoutOp::Box {
                                    width,
                                    height,
                                    max_width,
                                    max_height,
                                    ..
                                } => (*width, *height, *max_width, *max_height),
                                LayoutOp::Scroll {
                                    width,
                                    height,
                                    max_width,
                                    max_height,
                                    ..
                                } => (*width, *height, *max_width, *max_height),
                                LayoutOp::Embed { width, height, .. } => {
                                    (*width, *height, None, None)
                                }
                                _ => (None, None, None, None),
                            })
                            .unwrap_or((None, None, None, None));
                        let mut child_constraints = base_child_constraints;
                        let stretch_width = child_constraints.min_w == child_constraints.max_w
                            && child_width.is_none()
                            && child_max_width.is_none();
                        if stretch_width {
                            child_constraints.min_w = child_constraints.max_w;
                        } else {
                            child_constraints.min_w = 0.0;
                        }
                        let stretch_height = child_constraints.min_h == child_constraints.max_h
                            && child_height.is_none()
                            && child_max_height.is_none();
                        if stretch_height {
                            child_constraints.min_h = child_constraints.max_h;
                        } else {
                            child_constraints.min_h = 0.0;
                        }
                        let child_size = self.layout_node_constraints(
                            *child_id,
                            child_constraints,
                            LayoutPoint::ZERO,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            false,
                            depth + 1,
                        )?;
                        max_child.width = max_child.width.max(child_size.width);
                        max_child.height = max_child.height.max(child_size.height);
                        measured_children.push((*child_id, child_constraints, child_size));
                    }
                }
                let padded = LayoutSize::new(
                    max_child.width + padding[0] + padding[1],
                    max_child.height + padding[2] + padding[3],
                );
                let size = local.constrain(padded);
                if record {
                    for (child_id, child_constraints, _child_size) in measured_children {
                        self.layout_node_constraints(
                            child_id,
                            child_constraints,
                            LayoutPoint::new(origin.x + padding[0], origin.y + padding[2]),
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                    if !abs_children.is_empty() {
                        let abs_constraints = BoxConstraints::loose(size.width, size.height);
                        for child_id in abs_children {
                            self.layout_node_constraints(
                                child_id,
                                abs_constraints,
                                origin,
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                        }
                    }
                }
                content_size = padded;
                size
            }
            LayoutOp::Flex {
                direction,
                wrap,
                padding,
                gap,
                align_items,
                justify_content,
                flex_grow,
                ..
            } => {
                let gap = gap.unwrap_or(0.0);
                let local = constraints.tighten(node.width, node.height);
                let inner = local.deflate(*padding);
                let is_row = matches!(direction, IrFlexDirection::Row);

                let max_main = if is_row { inner.max_w } else { inner.max_h };
                let max_cross = if is_row { inner.max_h } else { inner.max_w };
                let min_main = if is_row { inner.min_w } else { inner.min_h };
                let min_cross = if is_row { inner.min_h } else { inner.min_w };
                let main_bounded = if is_row {
                    inner.is_width_bounded()
                } else {
                    inner.is_height_bounded()
                };
                let cross_bounded = if is_row {
                    inner.is_height_bounded()
                } else {
                    inner.is_width_bounded()
                };

                if matches!(wrap, IrFlexWrap::Wrap | IrFlexWrap::WrapReverse) {
                    let mut lines: Vec<(Vec<(NodeId, LayoutSize, BoxConstraints)>, f32, f32)> =
                        Vec::new();
                    let mut line_children: Vec<(NodeId, LayoutSize, BoxConstraints)> = Vec::new();
                    let mut line_main = 0.0f32;
                    let mut line_cross = 0.0f32;
                    let mut max_line_main = 0.0f32;

                    for child_id in &flow_children {
                        let child_constraints = if is_row {
                            BoxConstraints {
                                min_w: 0.0,
                                max_w: max_main,
                                min_h: 0.0,
                                max_h: max_cross,
                            }
                        } else {
                            BoxConstraints {
                                min_w: 0.0,
                                max_w: max_cross,
                                min_h: 0.0,
                                max_h: max_main,
                            }
                        };
                        let child_size = self.layout_node_constraints(
                            *child_id,
                            child_constraints,
                            LayoutPoint::ZERO,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            false,
                            depth + 1,
                        )?;
                        let child_main = if is_row {
                            child_size.width
                        } else {
                            child_size.height
                        };
                        let child_cross = if is_row {
                            child_size.height
                        } else {
                            child_size.width
                        };
                        let next_main = if line_children.is_empty() {
                            child_main
                        } else {
                            line_main + gap + child_main
                        };

                        if main_bounded && !line_children.is_empty() && next_main > max_main {
                            max_line_main = max_line_main.max(line_main);
                            lines.push((line_children, line_main, line_cross));
                            line_children = Vec::new();
                            line_main = 0.0;
                            line_cross = 0.0;
                        }

                        if !line_children.is_empty() {
                            line_main += gap;
                        }
                        line_main += child_main;
                        line_cross = line_cross.max(child_cross);
                        line_children.push((*child_id, child_size, child_constraints));
                    }

                    if !line_children.is_empty() {
                        max_line_main = max_line_main.max(line_main);
                        lines.push((line_children, line_main, line_cross));
                    }

                    let mut container_main = if main_bounded && *flex_grow > 0.0 {
                        max_main
                    } else {
                        max_line_main
                    };
                    container_main = container_main.max(min_main);
                    let total_lines_cross: f32 =
                        lines.iter().map(|(_, _, cross)| *cross).sum::<f32>()
                            + gap * lines.len().saturating_sub(1) as f32;
                    let container_cross = total_lines_cross.max(min_cross);
                    let size = if is_row {
                        local.constrain(LayoutSize::new(
                            container_main + padding[0] + padding[1],
                            container_cross + padding[2] + padding[3],
                        ))
                    } else {
                        local.constrain(LayoutSize::new(
                            container_cross + padding[0] + padding[1],
                            container_main + padding[2] + padding[3],
                        ))
                    };

                    let inner_main = if is_row {
                        size.width - padding[0] - padding[1]
                    } else {
                        size.height - padding[2] - padding[3]
                    };
                    let inner_cross = if is_row {
                        size.height - padding[2] - padding[3]
                    } else {
                        size.width - padding[0] - padding[1]
                    };

                    let mut ordered_lines = lines;
                    if matches!(wrap, IrFlexWrap::WrapReverse) {
                        ordered_lines.reverse();
                    }

                    let mut line_cursor = if matches!(wrap, IrFlexWrap::WrapReverse) {
                        (inner_cross - total_lines_cross).max(0.0)
                    } else {
                        0.0
                    };

                    for (line_children, line_main, line_cross) in ordered_lines {
                        let remaining_space = (inner_main - line_main).max(0.0);
                        let mut extra_gap = 0.0;
                        let mut offset_main = 0.0;
                        match justify_content {
                            fission_ir::op::JustifyContent::Start => {}
                            fission_ir::op::JustifyContent::End => offset_main = remaining_space,
                            fission_ir::op::JustifyContent::Center => {
                                offset_main = remaining_space / 2.0
                            }
                            fission_ir::op::JustifyContent::SpaceBetween => {
                                if line_children.len() > 1 {
                                    extra_gap =
                                        remaining_space / (line_children.len() as f32 - 1.0);
                                }
                            }
                            fission_ir::op::JustifyContent::SpaceAround => {
                                if !line_children.is_empty() {
                                    extra_gap = remaining_space / line_children.len() as f32;
                                    offset_main = extra_gap / 2.0;
                                }
                            }
                            fission_ir::op::JustifyContent::SpaceEvenly => {
                                if !line_children.is_empty() {
                                    extra_gap =
                                        remaining_space / (line_children.len() as f32 + 1.0);
                                    offset_main = extra_gap;
                                }
                            }
                        }

                        let mut cursor = offset_main;
                        for (child_id, child_size, mut child_constraints) in line_children {
                            let child_main = if is_row {
                                child_size.width
                            } else {
                                child_size.height
                            };
                            let child_cross = if is_row {
                                child_size.height
                            } else {
                                child_size.width
                            };
                            if matches!(align_items, fission_ir::op::AlignItems::Stretch) {
                                if is_row {
                                    child_constraints.min_h = line_cross;
                                    child_constraints.max_h = line_cross;
                                } else {
                                    child_constraints.min_w = line_cross;
                                    child_constraints.max_w = line_cross;
                                }
                            }
                            let cross_offset = match align_items {
                                fission_ir::op::AlignItems::Start
                                | fission_ir::op::AlignItems::Stretch => 0.0,
                                fission_ir::op::AlignItems::End => {
                                    (line_cross - child_cross).max(0.0)
                                }
                                fission_ir::op::AlignItems::Center => {
                                    ((line_cross - child_cross) / 2.0).max(0.0)
                                }
                                fission_ir::op::AlignItems::Baseline => 0.0,
                            };
                            let child_origin = if is_row {
                                LayoutPoint::new(
                                    origin.x + padding[0] + cursor,
                                    origin.y + padding[2] + line_cursor + cross_offset,
                                )
                            } else {
                                LayoutPoint::new(
                                    origin.x + padding[0] + line_cursor + cross_offset,
                                    origin.y + padding[2] + cursor,
                                )
                            };
                            self.layout_node_constraints(
                                child_id,
                                child_constraints,
                                child_origin,
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                            cursor += child_main + gap + extra_gap;
                        }

                        line_cursor += line_cross + gap;
                    }

                    if record && !abs_children.is_empty() {
                        let abs_constraints = BoxConstraints::loose(size.width, size.height);
                        for child_id in abs_children {
                            self.layout_node_constraints(
                                child_id,
                                abs_constraints,
                                origin,
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                        }
                    }
                    content_size = size;
                    size
                } else {
                    struct FlexChildEntry {
                        id: NodeId,
                        flex: f32,
                        size: LayoutSize,
                        constraints: BoxConstraints,
                        is_flex: bool,
                    }
                    let mut measured: Vec<FlexChildEntry> = Vec::new();
                    let mut total_flex = 0.0f32;
                    let mut nonflex_main = 0.0f32;
                    let mut max_child_cross = 0.0f32;
                    let treat_flex_as_nonflex = !main_bounded;

                    for child_id in &flow_children {
                        let child = match self.graph_state.node(*child_id) {
                            Some(child) => child,
                            None => continue,
                        };
                        let flex = child.flex_grow;
                        if flex > 0.0 && !treat_flex_as_nonflex {
                            total_flex += flex;
                            measured.push(FlexChildEntry {
                                id: *child_id,
                                flex,
                                size: LayoutSize::ZERO,
                                constraints: BoxConstraints::loose(0.0, 0.0),
                                is_flex: true,
                            });
                            continue;
                        }
                        let child_constraints = if is_row {
                            let cross =
                                if matches!(align_items, fission_ir::op::AlignItems::Stretch)
                                    && cross_bounded
                                {
                                    BoxConstraints {
                                        min_w: 0.0,
                                        max_w: f32::INFINITY,
                                        min_h: max_cross,
                                        max_h: max_cross,
                                    }
                                } else {
                                    BoxConstraints {
                                        min_w: 0.0,
                                        max_w: f32::INFINITY,
                                        min_h: 0.0,
                                        max_h: max_cross,
                                    }
                                };
                            cross
                        } else {
                            let cross =
                                if matches!(align_items, fission_ir::op::AlignItems::Stretch)
                                    && cross_bounded
                                {
                                    BoxConstraints {
                                        min_w: max_cross,
                                        max_w: max_cross,
                                        min_h: 0.0,
                                        max_h: f32::INFINITY,
                                    }
                                } else {
                                    BoxConstraints {
                                        min_w: 0.0,
                                        max_w: max_cross,
                                        min_h: 0.0,
                                        max_h: f32::INFINITY,
                                    }
                                };
                            cross
                        };
                        let child_size = self.layout_node_constraints(
                            *child_id,
                            child_constraints,
                            LayoutPoint::ZERO,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            false,
                            depth + 1,
                        )?;
                        let child_main = if is_row {
                            child_size.width
                        } else {
                            child_size.height
                        };
                        let child_cross = if is_row {
                            child_size.height
                        } else {
                            child_size.width
                        };
                        nonflex_main += child_main;
                        max_child_cross = max_child_cross.max(child_cross);
                        measured.push(FlexChildEntry {
                            id: *child_id,
                            flex,
                            size: child_size,
                            constraints: child_constraints,
                            is_flex: false,
                        });
                    }

                    let gap_total = gap * flow_children.len().saturating_sub(1) as f32;
                    let remaining = if main_bounded {
                        (max_main - nonflex_main - gap_total).max(0.0)
                    } else {
                        0.0
                    };

                    for entry in measured.iter_mut().filter(|e| e.is_flex) {
                        let flex = entry.flex;
                        let allocated = if main_bounded && total_flex > 0.0 {
                            remaining * (flex / total_flex)
                        } else {
                            0.0
                        };
                        let child_constraints = if is_row {
                            let cross =
                                if matches!(align_items, fission_ir::op::AlignItems::Stretch)
                                    && cross_bounded
                                {
                                    BoxConstraints {
                                        min_w: allocated,
                                        max_w: allocated,
                                        min_h: max_cross,
                                        max_h: max_cross,
                                    }
                                } else {
                                    BoxConstraints {
                                        min_w: allocated,
                                        max_w: allocated,
                                        min_h: 0.0,
                                        max_h: max_cross,
                                    }
                                };
                            cross
                        } else {
                            let cross =
                                if matches!(align_items, fission_ir::op::AlignItems::Stretch)
                                    && cross_bounded
                                {
                                    BoxConstraints {
                                        min_w: max_cross,
                                        max_w: max_cross,
                                        min_h: allocated,
                                        max_h: allocated,
                                    }
                                } else {
                                    BoxConstraints {
                                        min_w: 0.0,
                                        max_w: max_cross,
                                        min_h: allocated,
                                        max_h: allocated,
                                    }
                                };
                            cross
                        };
                        let child_size = self.layout_node_constraints(
                            entry.id,
                            child_constraints,
                            LayoutPoint::ZERO,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            false,
                            depth + 1,
                        )?;
                        let child_cross = if is_row {
                            child_size.height
                        } else {
                            child_size.width
                        };
                        max_child_cross = max_child_cross.max(child_cross);
                        entry.size = child_size;
                        entry.constraints = child_constraints;
                    }

                    let final_children_main: f32 = measured
                        .iter()
                        .map(|entry| {
                            if is_row {
                                entry.size.width
                            } else {
                                entry.size.height
                            }
                        })
                        .sum();

                    let mut container_main = if main_bounded && *flex_grow > 0.0 {
                        max_main
                    } else {
                        final_children_main + gap_total
                    };
                    container_main = container_main.max(min_main);

                    if main_bounded && final_children_main + gap_total > max_main {
                        // SHRINK logic
                        let mut total_shrink_scaled = 0.0f32;
                        for entry in &measured {
                            let child = self.graph_state.node(entry.id).unwrap();
                            let main_size = if is_row {
                                entry.size.width
                            } else {
                                entry.size.height
                            };
                            total_shrink_scaled += main_size * child.flex_shrink;
                        }

                        if total_shrink_scaled > 0.0 {
                            let overflow = (final_children_main + gap_total) - max_main;
                            for entry in &mut measured {
                                let child = self.graph_state.node(entry.id).unwrap();
                                let main_size = if is_row {
                                    entry.size.width
                                } else {
                                    entry.size.height
                                };
                                let shrink_amount = (main_size * child.flex_shrink
                                    / total_shrink_scaled)
                                    * overflow;
                                // Don't shrink below a reasonable minimum. Items with
                                // flex_shrink > 0 can shrink but not to zero - preserve at
                                // least a small fraction of their natural size.
                                let floor = if child.flex_shrink > 0.0 {
                                    // Check for explicit min/fixed dimension
                                    let explicit_min = match &child.op {
                                        LayoutOp::Box {
                                            min_width,
                                            min_height,
                                            height,
                                            width,
                                            ..
                                        } => {
                                            if is_row {
                                                min_width.or(*width).unwrap_or(0.0)
                                            } else {
                                                min_height.or(*height).unwrap_or(0.0)
                                            }
                                        }
                                        _ => 0.0,
                                    };
                                    explicit_min
                                } else {
                                    main_size // flex_shrink == 0 means don't shrink at all
                                };
                                let new_main = (main_size - shrink_amount).max(floor);

                                let mut child_constraints = entry.constraints;
                                if is_row {
                                    child_constraints.min_w = new_main;
                                    child_constraints.max_w = new_main;
                                } else {
                                    child_constraints.min_h = new_main;
                                    child_constraints.max_h = new_main;
                                }
                                let new_size = self.layout_node_constraints(
                                    entry.id,
                                    child_constraints,
                                    LayoutPoint::ZERO,
                                    out,
                                    constraints_out,
                                    measure_cache,
                                    scroll_source,
                                    false,
                                    depth + 1,
                                )?;
                                entry.size = new_size;
                                entry.constraints = child_constraints;
                            }
                        }
                    }

                    let container_cross = max_child_cross.max(min_cross);
                    let size = if is_row {
                        local.constrain(LayoutSize::new(
                            container_main + padding[0] + padding[1],
                            container_cross + padding[2] + padding[3],
                        ))
                    } else {
                        local.constrain(LayoutSize::new(
                            container_cross + padding[0] + padding[1],
                            container_main + padding[2] + padding[3],
                        ))
                    };

                    let inner_main = if is_row {
                        size.width - padding[0] - padding[1]
                    } else {
                        size.height - padding[2] - padding[3]
                    };
                    let inner_cross = if is_row {
                        size.height - padding[2] - padding[3]
                    } else {
                        size.width - padding[0] - padding[1]
                    };

                    let final_children_main: f32 = measured
                        .iter()
                        .map(|entry| {
                            if is_row {
                                entry.size.width
                            } else {
                                entry.size.height
                            }
                        })
                        .sum();

                    let remaining_space = (inner_main - final_children_main - gap_total).max(0.0);
                    let mut extra_gap = 0.0;
                    let mut offset_main = 0.0;
                    match justify_content {
                        fission_ir::op::JustifyContent::Start => {}
                        fission_ir::op::JustifyContent::End => offset_main = remaining_space,
                        fission_ir::op::JustifyContent::Center => {
                            offset_main = remaining_space / 2.0
                        }
                        fission_ir::op::JustifyContent::SpaceBetween => {
                            if measured.len() > 1 {
                                extra_gap = remaining_space / (measured.len() as f32 - 1.0);
                            }
                        }
                        fission_ir::op::JustifyContent::SpaceAround => {
                            if !measured.is_empty() {
                                extra_gap = remaining_space / measured.len() as f32;
                                offset_main = extra_gap / 2.0;
                            }
                        }
                        fission_ir::op::JustifyContent::SpaceEvenly => {
                            if !measured.is_empty() {
                                extra_gap = remaining_space / (measured.len() as f32 + 1.0);
                                offset_main = extra_gap;
                            }
                        }
                    }

                    let mut cursor = offset_main;
                    for entry in measured {
                        let child_main = if is_row {
                            entry.size.width
                        } else {
                            entry.size.height
                        };
                        let child_cross = if is_row {
                            entry.size.height
                        } else {
                            entry.size.width
                        };
                        let cross_offset = match align_items {
                            fission_ir::op::AlignItems::Start
                            | fission_ir::op::AlignItems::Stretch => 0.0,
                            fission_ir::op::AlignItems::End => (inner_cross - child_cross).max(0.0),
                            fission_ir::op::AlignItems::Center => {
                                ((inner_cross - child_cross) / 2.0).max(0.0)
                            }
                            fission_ir::op::AlignItems::Baseline => 0.0,
                        };
                        let child_origin = if is_row {
                            LayoutPoint::new(
                                origin.x + padding[0] + cursor,
                                origin.y + padding[2] + cross_offset,
                            )
                        } else {
                            LayoutPoint::new(
                                origin.x + padding[0] + cross_offset,
                                origin.y + padding[2] + cursor,
                            )
                        };

                        let mut child_constraints = entry.constraints;
                        if matches!(align_items, fission_ir::op::AlignItems::Stretch) {
                            // Only stretch children that don't have an explicit cross-axis size.
                            let child_node = self.graph_state.node(entry.id);
                            let has_explicit_cross = child_node
                                .map(|n| match &n.op {
                                    LayoutOp::Box { width, height, .. } => {
                                        if is_row {
                                            height.is_some()
                                        } else {
                                            width.is_some()
                                        }
                                    }
                                    _ => false,
                                })
                                .unwrap_or(false);
                            if !has_explicit_cross {
                                if is_row {
                                    child_constraints.min_h = inner_cross;
                                    child_constraints.max_h = inner_cross;
                                } else {
                                    child_constraints.min_w = inner_cross;
                                    child_constraints.max_w = inner_cross;
                                }
                            }
                        }

                        self.layout_node_constraints(
                            entry.id,
                            child_constraints,
                            child_origin,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                        cursor += child_main + gap + extra_gap;
                    }

                    if record && !abs_children.is_empty() {
                        let abs_constraints = BoxConstraints::loose(size.width, size.height);
                        for child_id in abs_children {
                            self.layout_node_constraints(
                                child_id,
                                abs_constraints,
                                origin,
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                        }
                    }
                    content_size = size;
                    size
                }
            }
            LayoutOp::Grid {
                columns,
                rows,
                column_gap,
                row_gap,
                padding,
            } => {
                let gap_x = column_gap.unwrap_or(0.0);
                let gap_y = row_gap.unwrap_or(0.0);
                let inner = constraints.deflate(*padding);
                let bounded_w = inner.is_width_bounded();
                let bounded_h = inner.is_height_bounded();
                let available_w = if bounded_w { inner.max_w } else { 0.0 };
                let available_h = if bounded_h { inner.max_h } else { 0.0 };

                let col_count = columns.len().max(1);
                let mut col_widths = vec![0.0f32; col_count];
                let mut fr_total = 0.0f32;
                let mut fixed_total = 0.0f32;
                for (i, track) in columns.iter().enumerate() {
                    match track {
                        GridTrack::Points(p) => {
                            col_widths[i] = *p;
                            fixed_total += *p;
                        }
                        GridTrack::Percent(p) => {
                            let w = if bounded_w {
                                available_w * (*p / 100.0)
                            } else {
                                0.0
                            };
                            col_widths[i] = w;
                            fixed_total += w;
                        }
                        GridTrack::Fr(f) => fr_total += *f,
                        _ => {}
                    }
                }
                if fr_total > 0.0 && bounded_w {
                    let remaining =
                        (available_w - fixed_total - gap_x * (col_count.saturating_sub(1) as f32))
                            .max(0.0);
                    for (i, track) in columns.iter().enumerate() {
                        if let GridTrack::Fr(f) = track {
                            col_widths[i] = remaining * (*f / fr_total);
                        }
                    }
                }

                let child_count = flow_children.len();
                let row_count = if rows.is_empty() {
                    (child_count + col_count - 1) / col_count
                } else {
                    rows.len()
                };
                let mut row_heights = vec![0.0f32; row_count.max(1)];

                if !rows.is_empty() {
                    let mut row_fr_total = 0.0f32;
                    let mut row_fixed_total = 0.0f32;
                    for (i, track) in rows.iter().enumerate() {
                        if i >= row_heights.len() {
                            break;
                        }
                        match track {
                            GridTrack::Points(p) => {
                                row_heights[i] = *p;
                                row_fixed_total += *p;
                            }
                            GridTrack::Percent(p) => {
                                let h = if bounded_h {
                                    available_h * (*p / 100.0)
                                } else {
                                    0.0
                                };
                                row_heights[i] = h;
                                row_fixed_total += h;
                            }
                            GridTrack::Fr(f) => row_fr_total += *f,
                            _ => {}
                        }
                    }
                    if row_fr_total > 0.0 && bounded_h {
                        let remaining = (available_h
                            - row_fixed_total
                            - gap_y * (row_heights.len().saturating_sub(1) as f32))
                            .max(0.0);
                        for (i, track) in rows.iter().enumerate() {
                            if let GridTrack::Fr(f) = track {
                                row_heights[i] = remaining * (*f / row_fr_total);
                            }
                        }
                    }
                }

                let mut cell_assignments = Vec::new();
                let mut auto_row = 0;
                let mut auto_col = 0;

                for child_id in &flow_children {
                    let child = self.graph_state.node(*child_id).unwrap();
                    let (row, col) = if let LayoutOp::GridItem {
                        row_start,
                        col_start,
                        ..
                    } = &child.op
                    {
                        let r = match row_start {
                            fission_ir::op::GridPlacement::Line(l) => {
                                (*l as usize).saturating_sub(1)
                            }
                            _ => auto_row,
                        };
                        let c = match col_start {
                            fission_ir::op::GridPlacement::Line(l) => {
                                (*l as usize).saturating_sub(1)
                            }
                            _ => auto_col,
                        };
                        (r, c)
                    } else {
                        let res = (auto_row, auto_col);
                        auto_col += 1;
                        if auto_col >= col_count {
                            auto_col = 0;
                            auto_row += 1;
                        }
                        res
                    };
                    cell_assignments.push((*child_id, row, col));
                }

                for (child_id, row, col) in &cell_assignments {
                    if *row >= row_heights.len() || *col >= col_widths.len() {
                        continue;
                    }
                    let cell_w = col_widths[*col];
                    let cell_constraints = BoxConstraints {
                        min_w: cell_w,
                        max_w: cell_w,
                        min_h: 0.0,
                        max_h: if row_heights[*row] > 0.0 {
                            row_heights[*row]
                        } else {
                            f32::INFINITY
                        },
                    };
                    let child_size = self.layout_node_constraints(
                        *child_id,
                        cell_constraints,
                        LayoutPoint::ZERO,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                    if row_heights[*row] == 0.0 {
                        row_heights[*row] = child_size.height;
                    } else {
                        row_heights[*row] = row_heights[*row].max(child_size.height);
                    }
                }

                let grid_w: f32 =
                    col_widths.iter().sum::<f32>() + gap_x * (col_count.saturating_sub(1) as f32);
                let grid_h: f32 = row_heights.iter().sum::<f32>()
                    + gap_y * (row_heights.len().saturating_sub(1) as f32);
                let size = constraints.constrain(LayoutSize::new(
                    grid_w + padding[0] + padding[1],
                    grid_h + padding[2] + padding[3],
                ));

                if record {
                    let padding_origin_x = origin.x + padding[0];
                    let padding_origin_y = origin.y + padding[2];
                    for (child_id, row, col) in &cell_assignments {
                        if *row >= row_heights.len() || *col >= col_widths.len() {
                            continue;
                        }
                        let mut cell_x = padding_origin_x;
                        for i in 0..*col {
                            cell_x += col_widths[i] + gap_x;
                        }
                        let mut cell_y = padding_origin_y;
                        for i in 0..*row {
                            cell_y += row_heights[i] + gap_y;
                        }
                        let cell_w = col_widths[*col];
                        let cell_h = row_heights[*row];
                        let child_constraints = BoxConstraints {
                            min_w: cell_w,
                            max_w: cell_w,
                            min_h: cell_h,
                            max_h: cell_h,
                        };
                        self.layout_node_constraints(
                            *child_id,
                            child_constraints,
                            LayoutPoint::new(cell_x, cell_y),
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                }

                if record && !abs_children.is_empty() {
                    let abs_constraints = BoxConstraints::loose(size.width, size.height);
                    for child_id in abs_children {
                        self.layout_node_constraints(
                            child_id,
                            abs_constraints,
                            origin,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                }
                content_size = size;
                size
            }
            LayoutOp::GridItem { .. } => {
                let mut child_size = LayoutSize::ZERO;
                if let Some(child_id) = node.children_ids.first() {
                    child_size = self.layout_node_constraints(
                        *child_id,
                        constraints,
                        origin,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                content_size = child_size;
                constraints.constrain(child_size)
            }
            LayoutOp::Scroll {
                direction,
                width,
                height,
                min_width,
                max_width,
                min_height,
                max_height,
                padding,
                ..
            } => {
                let mut local =
                    constraints.apply_min_max(*min_width, *max_width, *min_height, *max_height);
                local = local.tighten(*width, *height);
                let is_horizontal = matches!(direction, FlexDirection::Row);
                let mut child_constraints = local.deflate(*padding);
                if is_horizontal {
                    child_constraints.min_w = 0.0;
                    child_constraints.max_w = f32::INFINITY;
                } else {
                    child_constraints.min_h = 0.0;
                    child_constraints.max_h = f32::INFINITY;
                }
                let mut child_size = LayoutSize::ZERO;
                if let Some(child_id) = flow_children.first() {
                    child_size = self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        LayoutPoint::ZERO,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                }
                let size = local.constrain(LayoutSize::new(
                    child_size.width + padding[0] + padding[1],
                    child_size.height + padding[2] + padding[3],
                ));
                if record {
                    if let Some(child_id) = flow_children.first() {
                        self.layout_node_constraints(
                            *child_id,
                            child_constraints,
                            LayoutPoint::new(origin.x + padding[0], origin.y + padding[2]),
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                    if !abs_children.is_empty() {
                        let abs_constraints = BoxConstraints::loose(size.width, size.height);
                        for child_id in abs_children {
                            self.layout_node_constraints(
                                child_id,
                                abs_constraints,
                                origin,
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                        }
                    }
                }
                content_size = child_size;
                size
            }
            LayoutOp::Align => {
                let child_constraints = BoxConstraints::loose(constraints.max_w, constraints.max_h);
                let mut child_size = LayoutSize::ZERO;
                if let Some(child_id) = flow_children.first() {
                    child_size = self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        LayoutPoint::ZERO,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                }
                let size = if constraints.is_width_bounded() || constraints.is_height_bounded() {
                    constraints.constrain(LayoutSize::new(
                        if constraints.is_width_bounded() {
                            constraints.max_w
                        } else {
                            child_size.width
                        },
                        if constraints.is_height_bounded() {
                            constraints.max_h
                        } else {
                            child_size.height
                        },
                    ))
                } else {
                    child_size
                };
                if let Some(child_id) = flow_children.first() {
                    let dx = ((size.width - child_size.width) / 2.0).max(0.0);
                    let dy = ((size.height - child_size.height) / 2.0).max(0.0);
                    self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        LayoutPoint::new(origin.x + dx, origin.y + dy),
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                if record && !abs_children.is_empty() {
                    let abs_constraints = BoxConstraints::loose(size.width, size.height);
                    for child_id in abs_children {
                        self.layout_node_constraints(
                            child_id,
                            abs_constraints,
                            origin,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                }
                content_size = child_size;
                size
            }
            LayoutOp::ZStack => {
                let mut max_child = LayoutSize::ZERO;
                for child_id in &flow_children {
                    let child_size = self.layout_node_constraints(
                        *child_id,
                        BoxConstraints::loose(constraints.max_w, constraints.max_h),
                        LayoutPoint::ZERO,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                    max_child.width = max_child.width.max(child_size.width);
                    max_child.height = max_child.height.max(child_size.height);
                }
                let size = if constraints.is_width_bounded() || constraints.is_height_bounded() {
                    constraints.constrain(LayoutSize::new(
                        if constraints.is_width_bounded() {
                            constraints.max_w
                        } else {
                            max_child.width
                        },
                        if constraints.is_height_bounded() {
                            constraints.max_h
                        } else {
                            max_child.height
                        },
                    ))
                } else {
                    max_child
                };
                for child_id in &flow_children {
                    let child_constraints = BoxConstraints::loose(size.width, size.height);
                    let child_origin = LayoutPoint::new(origin.x, origin.y);
                    self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        child_origin,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                if record && !abs_children.is_empty() {
                    let abs_constraints = BoxConstraints::loose(size.width, size.height);
                    for child_id in abs_children {
                        self.layout_node_constraints(
                            child_id,
                            abs_constraints,
                            origin,
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                }
                content_size = size;
                size
            }
            LayoutOp::Positioned {
                top,
                left,
                bottom,
                right,
                width,
                height,
            } => {
                let target_w = finite_or(constraints.max_w, finite_or(constraints.min_w, 0.0));
                let target_h = finite_or(constraints.max_h, finite_or(constraints.min_h, 0.0));
                let size = constraints.constrain(LayoutSize::new(target_w, target_h));
                let mut child_constraints = BoxConstraints::loose(size.width, size.height);
                if let (Some(l), Some(r)) = (left, right) {
                    let w = (size.width - l - r).max(0.0);
                    child_constraints = child_constraints.tighten(Some(w), None);
                }
                if let (Some(t), Some(b)) = (top, bottom) {
                    let h = (size.height - t - b).max(0.0);
                    child_constraints = child_constraints.tighten(None, Some(h));
                }
                child_constraints = child_constraints.tighten(*width, *height);
                if let Some(child_id) = node.children_ids.first() {
                    let child_size = self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        LayoutPoint::ZERO,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                    let x = left.unwrap_or_else(|| {
                        right
                            .map(|r| (size.width - r - child_size.width).max(0.0))
                            .unwrap_or(0.0)
                    });
                    let y = top.unwrap_or_else(|| {
                        bottom
                            .map(|b| (size.height - b - child_size.height).max(0.0))
                            .unwrap_or(0.0)
                    });
                    self.layout_node_constraints(
                        *child_id,
                        child_constraints,
                        LayoutPoint::new(origin.x + x, origin.y + y),
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                content_size = size;
                size
            }
            LayoutOp::Embed { width, height, .. } => {
                let local = constraints.tighten(*width, *height);
                let w = if local.is_width_bounded() {
                    local.max_w
                } else {
                    local.min_w
                };
                let h = if local.is_height_bounded() {
                    local.max_h
                } else {
                    local.min_h
                };
                let size = local.constrain(LayoutSize::new(w, h));
                content_size = size;
                size
            }
            LayoutOp::AbsoluteFill => {
                let target_w = finite_or(constraints.max_w, finite_or(constraints.min_w, 0.0));
                let target_h = finite_or(constraints.max_h, finite_or(constraints.min_h, 0.0));
                let size = constraints.constrain(LayoutSize::new(target_w, target_h));
                for child_id in self.graph_state.children_of(node_id) {
                    self.layout_node_constraints(
                        *child_id,
                        BoxConstraints::tight(size),
                        origin,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                content_size = size;
                size
            }
            LayoutOp::Transform { .. } | LayoutOp::Clip { .. } => {
                let mut child_size = LayoutSize::ZERO;
                if let Some(child_id) = node.children_ids.first() {
                    child_size = self.layout_node_constraints(
                        *child_id,
                        constraints,
                        origin,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        record,
                        depth + 1,
                    )?;
                }
                content_size = child_size;
                constraints.constrain(child_size)
            }
            LayoutOp::Flyout { anchor, content: _ } => {
                let loose = BoxConstraints::loose(
                    if constraints.is_width_bounded() {
                        constraints.max_w
                    } else {
                        f32::INFINITY
                    },
                    if constraints.is_height_bounded() {
                        constraints.max_h
                    } else {
                        f32::INFINITY
                    },
                );
                let mut child_size = LayoutSize::ZERO;
                for child_id in self.graph_state.children_of(node_id) {
                    child_size = self.layout_node_constraints(
                        *child_id,
                        loose,
                        origin,
                        out,
                        constraints_out,
                        measure_cache,
                        scroll_source,
                        false,
                        depth + 1,
                    )?;
                }
                if record {
                    let anchor_rect = out.get(anchor).map(|g| g.rect);
                    let place_x = anchor_rect.map(|r| r.x()).unwrap_or(origin.x);
                    let place_y = anchor_rect.map(|r| r.y() + r.height()).unwrap_or(origin.y);
                    for child_id in self.graph_state.children_of(node_id) {
                        self.layout_node_constraints(
                            *child_id,
                            loose,
                            LayoutPoint::new(place_x, place_y),
                            out,
                            constraints_out,
                            measure_cache,
                            scroll_source,
                            record,
                            depth + 1,
                        )?;
                    }
                }
                content_size = child_size;
                child_size
            }
        };

        if let Some(runs) = &node.rich_text {
            if let Some(measurer) = &self.measurer {
                let node_max_w = match &node.op {
                    LayoutOp::Box { max_width, .. } => *max_width,
                    _ => None,
                };
                let avail_w = {
                    let from_constraints = if constraints.is_width_bounded() {
                        Some(constraints.max_w)
                    } else {
                        None
                    };
                    match (from_constraints, node_max_w) {
                        (Some(c), Some(m)) => Some(c.min(m)),
                        (Some(c), None) => Some(c),
                        (None, Some(m)) => Some(m),
                        (None, None) => None,
                    }
                };
                let rich_layout = measurer.layout_rich_text(runs, avail_w);
                let text_content = LayoutSize::new(rich_layout.width, rich_layout.height);
                let measured = constraints.constrain(text_content);
                if rich_text_inline_children
                    && rich_layout.inline_boxes.len() == flow_children.len()
                {
                    let result =
                        self.record_geometry(node_id, origin, measured, text_content, out, record);
                    if record {
                        let mut inline_boxes = rich_layout.inline_boxes;
                        inline_boxes.sort_by_key(|inline_box| inline_box.id);
                        for (child_id, inline_box) in flow_children.iter().zip(inline_boxes.iter())
                        {
                            self.layout_node_constraints(
                                *child_id,
                                BoxConstraints::tight(LayoutSize::new(
                                    inline_box.width,
                                    inline_box.height,
                                )),
                                LayoutPoint::new(origin.x + inline_box.x, origin.y + inline_box.y),
                                out,
                                constraints_out,
                                measure_cache,
                                scroll_source,
                                record,
                                depth + 1,
                            )?;
                        }
                    }
                    if !record {
                        measure_cache.insert(MeasureCacheKey::new(node_id, constraints), result);
                    }
                    return Ok(result);
                }
                if node.children_ids.is_empty() {
                    let result =
                        self.record_geometry(node_id, origin, measured, text_content, out, record);
                    if !record {
                        measure_cache.insert(MeasureCacheKey::new(node_id, constraints), result);
                    }
                    return Ok(result);
                }
                content_size.width = content_size.width.max(text_content.width);
                content_size.height = content_size.height.max(text_content.height);
            }
        }

        let result = self.record_geometry(node_id, origin, size, content_size, out, record);
        if !record {
            measure_cache.insert(MeasureCacheKey::new(node_id, constraints), result);
        }
        Ok(result)
    }

    fn record_geometry(
        &self,
        node_id: NodeId,
        origin: LayoutPoint,
        size: LayoutSize,
        content_size: LayoutSize,
        out: &mut HashMap<NodeId, LayoutNodeGeometry>,
        record: bool,
    ) -> LayoutSize {
        let mut rect_origin = origin;
        let mut rect_size = size;
        let mut rect_content = content_size;
        let mut had_non_finite = false;

        if !rect_origin.x.is_finite() {
            rect_origin.x = 0.0;
            had_non_finite = true;
        }
        if !rect_origin.y.is_finite() {
            rect_origin.y = 0.0;
            had_non_finite = true;
        }
        if !rect_size.width.is_finite() {
            rect_size.width = 0.0;
            had_non_finite = true;
        }
        if !rect_size.height.is_finite() {
            rect_size.height = 0.0;
            had_non_finite = true;
        }
        if !rect_content.width.is_finite() {
            rect_content.width = 0.0;
            had_non_finite = true;
        }
        if !rect_content.height.is_finite() {
            rect_content.height = 0.0;
            had_non_finite = true;
        }

        if had_non_finite {
            diag::emit(
                diag::DiagCategory::Invariants,
                diag::DiagLevel::Error,
                diag::DiagEventKind::InvariantViolation {
                    kind: "non_finite_layout".into(),
                    node: Some(node_id.as_u128()),
                    details: format!(
                        "origin=({:.2},{:.2}) size=({:.2},{:.2}) content=({:.2},{:.2})",
                        origin.x,
                        origin.y,
                        size.width,
                        size.height,
                        content_size.width,
                        content_size.height
                    ),
                    dump_ref: None,
                },
            );
        }

        if record {
            let rect = LayoutRect::new(
                rect_origin.x,
                rect_origin.y,
                rect_size.width,
                rect_size.height,
            );
            out.insert(
                node_id,
                LayoutNodeGeometry {
                    rect,
                    content_size: rect_content,
                },
            );
        }
        rect_size
    }
}