morphorm 0.9.0

A UI layout engine
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
use smallvec::SmallVec;

use crate::{
    Alignment, Cache, CacheExt, Direction, LayoutType, LayoutWrap, Node, NodeExt, PositionType, Size, Units, Units::*,
};

const DEFAULT_MIN: f32 = -f32::MAX;
const DEFAULT_MAX: f32 = f32::MAX;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ItemType {
    Size,
    After,
}

/// Represents a space or size which has stretch units.
#[derive(Copy, Clone)]
struct StretchItem {
    // The child index of the item.
    index: usize,
    // The stretch factor of the item.
    factor: f32,
    // The type of stretch item, either space-before, size, or space-after.
    item_type: ItemType,
    // The violation of the stretch item after clamping.
    violation: f32,
    // The computed size of the stretch item.
    computed: f32,
    // The measured size from the current flex iteration.
    measured: f32,
    // Whether or not the stretch item is frozen.
    frozen: bool,
    // The minimum size of the stretch item.
    min: f32,
    // The maximum size of the stretch item.
    max: f32,
}

impl StretchItem {
    pub fn new(index: usize, factor: f32, item_type: ItemType, min: f32, max: f32) -> Self {
        Self { index, factor, item_type, violation: 0.0, computed: 0.0, measured: 0.0, frozen: false, min, max }
    }
}

#[derive(Debug, Copy, Clone)]
struct ChildNode<'a, N: Node> {
    // A reference to the node.
    node: &'a N,
    // Computed cross size of the node.
    cross: f32,
    // Computed main size of the node.
    main: f32,

    main_after: f32,
    // Last parent constraints used to lay out this child.
    last_layout_main: f32,
    last_layout_cross: f32,
    has_layout_constraints: bool,
}

fn flip_alignment_horizontal(alignment: Alignment) -> Alignment {
    match alignment {
        Alignment::TopLeft => Alignment::TopRight,
        Alignment::TopRight => Alignment::TopLeft,
        Alignment::Left => Alignment::Right,
        Alignment::Right => Alignment::Left,
        Alignment::BottomLeft => Alignment::BottomRight,
        Alignment::BottomRight => Alignment::BottomLeft,
        alignment => alignment,
    }
}

#[inline]
fn same_f32(a: f32, b: f32) -> bool {
    a.to_bits() == b.to_bits()
}

#[allow(clippy::too_many_arguments)]
fn clamp_with_aspect_ratio(
    parent_layout_type: LayoutType,
    aspect_ratio: Option<f32>,
    main_is_auto: bool,
    cross_is_auto: bool,
    min_main: f32,
    max_main: f32,
    min_cross: f32,
    max_cross: f32,
    computed_main: &mut f32,
    computed_cross: &mut f32,
) {
    *computed_main = computed_main.max(min_main).min(max_main);
    *computed_cross = computed_cross.max(min_cross).min(max_cross);

    let Some(ratio) = aspect_ratio else {
        return;
    };

    if !ratio.is_finite() || ratio <= 0.0 {
        return;
    }

    let derive_main_from_cross = |cross: f32| match parent_layout_type {
        LayoutType::Row | LayoutType::Overlay | LayoutType::Grid => cross * ratio,
        LayoutType::Column => cross / ratio,
    };

    let derive_cross_from_main = |main: f32| match parent_layout_type {
        LayoutType::Row | LayoutType::Overlay | LayoutType::Grid => main / ratio,
        LayoutType::Column => main * ratio,
    };

    match (main_is_auto, cross_is_auto) {
        (true, false) => {
            *computed_main = derive_main_from_cross(*computed_cross);
        }

        (false, true) => {
            *computed_cross = derive_cross_from_main(*computed_main);
        }

        (true, true) => {
            if *computed_main > 0.0 {
                *computed_cross = derive_cross_from_main(*computed_main);
            } else if *computed_cross > 0.0 {
                *computed_main = derive_main_from_cross(*computed_cross);
            } else if min_main > 0.0 {
                *computed_main = min_main;
                *computed_cross = derive_cross_from_main(*computed_main);
            } else if min_cross > 0.0 {
                *computed_cross = min_cross;
                *computed_main = derive_main_from_cross(*computed_cross);
            }
        }

        (false, false) => {}
    }

    *computed_main = computed_main.max(min_main).min(max_main);
    *computed_cross = computed_cross.max(min_cross).min(max_cross);
}

fn alignment_fractions(alignment: Alignment) -> (f32, f32) {
    // Convert alignment into normalized horizontal/vertical fractions in [0, 1].
    // These fractions are later multiplied by available free space.
    match alignment {
        Alignment::TopLeft => (0.0, 0.0),
        Alignment::TopCenter => (0.5, 0.0),
        Alignment::TopRight => (1.0, 0.0),
        Alignment::Left => (0.0, 0.5),
        Alignment::Center => (0.5, 0.5),
        Alignment::Right => (1.0, 0.5),
        Alignment::BottomLeft => (0.0, 1.0),
        Alignment::BottomCenter => (0.5, 1.0),
        Alignment::BottomRight => (1.0, 1.0),
    }
}

fn absolute_axis_position(before: Units, after: Units, parent_size: f32, child_size: f32) -> f32 {
    // Resolve a child position on one axis from before/after offsets.
    // This is shared by absolute positioning in stack and overlay layouts.
    match (before, after) {
        (Pixels(val), _) => val,
        (Percentage(val), _) => val * 0.01 * parent_size,
        (_, Pixels(val)) => parent_size - val - child_size,
        (_, Percentage(val)) => parent_size - child_size - val * 0.01 * parent_size,
        (Stretch(b), Stretch(a)) => {
            if b == a {
                (parent_size - child_size) * 0.5
            } else {
                (parent_size - child_size) * (b / (b + a))
            }
        }
        (Stretch(_), Auto) => parent_size - child_size,
        (Auto, Stretch(_)) => 0.0,
        (Auto, Auto) => 0.0,
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_overlay<N, C>(
    node: &N,
    parent_layout_type: LayoutType,
    parent_main: f32,
    parent_cross: f32,
    cache: &mut C,
    tree: &<N as Node>::Tree,
    store: &<N as Node>::Store,
    sublayout: &mut <N as Node>::SubLayout<'_>,
) -> Size
where
    N: Node,
    C: Cache<Node = N>,
{
    // Interpret parent-provided main/cross as concrete width/height for overlay.
    // Use parent dimensions as the containing block for percentage-based constraints,
    // so that auto-sizing doesn't collapse percentage max constraints to zero.
    let (contain_width, contain_height) = match parent_layout_type {
        LayoutType::Column => (parent_cross, parent_main),
        LayoutType::Row | LayoutType::Overlay | LayoutType::Grid => (parent_main, parent_cross),
    };

    let (mut computed_width, mut computed_height) = (contain_width, contain_height);

    // Resolve this node's own size constraints in physical width/height axes.
    // Use containing block dimensions (parent) as the reference for percentage resolution,
    // not the computed size (which may be 0 during auto-sizing).
    let width = node.width(store).unwrap_or(Stretch(1.0));
    let height = node.height(store).unwrap_or(Stretch(1.0));
    let mut min_width = node.min_width(store).unwrap_or(Pixels(0.0)).to_px(contain_width, DEFAULT_MIN);
    let mut max_width = node.max_width(store).unwrap_or(Pixels(f32::MAX)).to_px(contain_width, DEFAULT_MAX);
    let mut min_height = node.min_height(store).unwrap_or(Pixels(0.0)).to_px(contain_height, DEFAULT_MIN);
    let mut max_height = node.max_height(store).unwrap_or(Pixels(f32::MAX)).to_px(contain_height, DEFAULT_MAX);

    let padding_left = node.padding_left(store).unwrap_or_default().to_px(contain_width, 0.0);
    let padding_right = node.padding_right(store).unwrap_or_default().to_px(contain_width, 0.0);
    let padding_top = node.padding_top(store).unwrap_or_default().to_px(contain_height, 0.0);
    let padding_bottom = node.padding_bottom(store).unwrap_or_default().to_px(contain_height, 0.0);

    // Split visible children by position type; relative children participate in
    // overlay alignment, absolute children keep explicit edge-based positioning.
    let mut relative_children = SmallVec::<[&N; 32]>::new();
    let mut absolute_children = SmallVec::<[&N; 8]>::new();
    for child in node.children(tree).filter(|child| child.visible(store)) {
        match child.position_type(store).unwrap_or_default() {
            PositionType::Relative => relative_children.push(child),
            PositionType::Absolute => absolute_children.push(child),
        }
    }

    let num_children = relative_children.len() + absolute_children.len();
    let num_relative_children = relative_children.len();

    let mut children = SmallVec::<[ChildNode<N>; 32]>::with_capacity(num_children);

    // Two-pass stabilization:
    // pass 1 measures children with initial size,
    // pass 2 remeasures only if auto/min/max constraints changed the container size.
    for _ in 0..2 {
        children.clear();

        // Relative children are laid out against the parent content box.
        let available_width = computed_width - padding_left - padding_right;
        let available_height = computed_height - padding_top - padding_bottom;

        for child in relative_children.iter().copied() {
            let child_width = child.width(store).unwrap_or(Stretch(1.0));
            let child_height = child.height(store).unwrap_or(Stretch(1.0));

            let child_min_width = child.min_width(store).unwrap_or(Pixels(0.0));
            let child_max_width = child.max_width(store).unwrap_or(Pixels(f32::MAX));
            let child_min_height = child.min_height(store).unwrap_or(Pixels(0.0));
            let child_max_height = child.max_height(store).unwrap_or(Pixels(f32::MAX));

            // Stretch children are constrained directly to available space,
            // while non-stretch children are measured against that space.
            let target_width = if child_width.is_stretch() {
                available_width.clamp(
                    child_min_width.to_px(available_width, DEFAULT_MIN),
                    child_max_width.to_px(available_width, DEFAULT_MAX),
                )
            } else {
                available_width
            };

            let target_height = if child_height.is_stretch() {
                available_height.clamp(
                    child_min_height.to_px(available_height, DEFAULT_MIN),
                    child_max_height.to_px(available_height, DEFAULT_MAX),
                )
            } else {
                available_height
            };

            // Overlay children recurse with Overlay parent semantics so descendants
            // inherit overlay axis behavior when needed.
            let child_size =
                layout(child, LayoutType::Overlay, target_width, target_height, cache, tree, store, sublayout);

            children.push(ChildNode {
                node: child,
                cross: child_size.cross,
                main: child_size.main,
                main_after: 0.0,
                last_layout_main: target_width,
                last_layout_cross: target_height,
                has_layout_constraints: true,
            });
        }

        if num_relative_children == 0 {
            break;
        }

        let max_child_width = children.iter().map(|child| child.main).reduce(f32::max).unwrap_or_default();
        let max_child_height = children.iter().map(|child| child.cross).reduce(f32::max).unwrap_or_default();

        // Auto-size in overlay is based on max extents (not sums), because
        // children can overlap and are independently aligned in the same box.
        if width.is_auto() || node.min_width(store).unwrap_or(Pixels(0.0)).is_auto() {
            min_width = max_child_width + padding_left + padding_right;
        }

        if node.max_width(store).unwrap_or(Pixels(f32::MAX)).is_auto() && max_child_width != 0.0 {
            max_width = max_child_width + padding_left + padding_right;
        }

        if height.is_auto() || node.min_height(store).unwrap_or(Pixels(0.0)).is_auto() {
            min_height = max_child_height + padding_top + padding_bottom;
        }

        if node.max_height(store).unwrap_or(Pixels(f32::MAX)).is_auto() && max_child_height != 0.0 {
            max_height = max_child_height + padding_top + padding_bottom;
        }

        let next_width = computed_width.max(min_width).min(max_width);
        let next_height = computed_height.max(min_height).min(max_height);

        if same_f32(next_width, computed_width) && same_f32(next_height, computed_height) {
            break;
        }

        computed_width = next_width;
        computed_height = next_height;
    }

    // Final clamped container size after stabilization.
    computed_width = computed_width.max(min_width).min(max_width);
    computed_height = computed_height.max(min_height).min(max_height);

    // Relative children are positioned inside the padded content box.
    let available_width = computed_width - padding_left - padding_right;
    let available_height = computed_height - padding_top - padding_bottom;

    let mut alignment = node.alignment(store).unwrap_or_default();
    if node.direction(store).unwrap_or_default() == Direction::RightToLeft {
        alignment = flip_alignment_horizontal(alignment);
    }
    // Alignment gives each child its own anchor point in the same content box,
    // which is what enables intentional overlap.
    let (align_x, align_y) = alignment_fractions(alignment);

    for child in &children {
        let child_posx = align_x * (available_width - child.main);
        let child_posy = align_y * (available_height - child.cross);

        cache.set_rect(
            child.node,
            LayoutType::Overlay,
            child_posx + padding_left,
            child_posy + padding_top,
            child.main,
            child.cross,
        );
    }

    // Absolute children are sized in the same box model used by stack/wrap:
    // padding box (content + padding).
    let abs_width = computed_width;
    let abs_height = computed_height;

    // Mirror the stack layout's RTL semantics: under RightToLeft, left/right are
    // swapped so that `left` becomes the trailing edge and `right` the leading edge,
    // matching the behavior of absolute children in Row/Column parents.
    let is_rtl = node.direction(store).unwrap_or_default() == Direction::RightToLeft;

    for child in absolute_children.into_iter() {
        // Under RTL, left and right are logically swapped on the horizontal axis.
        let (child_leading, child_trailing) = if is_rtl {
            (child.right(store).unwrap_or_default(), child.left(store).unwrap_or_default())
        } else {
            (child.left(store).unwrap_or_default(), child.right(store).unwrap_or_default())
        };

        // Stretch sizing for absolute children consumes remaining axis size after offsets.
        let child_width = if child.width(store).unwrap_or(Stretch(1.0)).is_stretch() {
            let child_min_width = child.min_width(store).unwrap_or(Pixels(0.0)).to_px(abs_width, DEFAULT_MIN);
            let child_max_width = child.max_width(store).unwrap_or(Pixels(f32::MAX)).to_px(abs_width, DEFAULT_MAX);
            let leading_px = child_leading.to_px(abs_width, 0.0);
            let trailing_px = child_trailing.to_px(abs_width, 0.0);

            abs_width.clamp(child_min_width, child_max_width) - leading_px - trailing_px
        } else {
            abs_width
        };

        let child_height = if child.height(store).unwrap_or(Stretch(1.0)).is_stretch() {
            let child_min_height = child.min_height(store).unwrap_or(Pixels(0.0)).to_px(abs_height, DEFAULT_MIN);
            let child_max_height = child.max_height(store).unwrap_or(Pixels(f32::MAX)).to_px(abs_height, DEFAULT_MAX);
            let child_top = child.top(store).unwrap_or_default().to_px(abs_height, 0.0);
            let child_bottom = child.bottom(store).unwrap_or_default().to_px(abs_height, 0.0);

            abs_height.clamp(child_min_height, child_max_height) - child_top - child_bottom
        } else {
            abs_height
        };

        // Recurse first to resolve intrinsic/auto behavior under the resolved constraints.
        let child_size = layout(child, LayoutType::Overlay, child_width, child_height, cache, tree, store, sublayout);

        // Then resolve explicit absolute offsets for final placement.
        // Horizontal axis respects RTL via the already-swapped leading/trailing values.
        let child_posx = absolute_axis_position(child_leading, child_trailing, abs_width, child_size.main);
        let child_posy = absolute_axis_position(
            child.top(store).unwrap_or_default(),
            child.bottom(store).unwrap_or_default(),
            abs_height,
            child_size.cross,
        );

        cache.set_rect(child, LayoutType::Overlay, child_posx, child_posy, child_size.main, child_size.cross);
    }

    // Return in caller's axis orientation (main/cross abstraction).
    match parent_layout_type {
        LayoutType::Column => Size { main: computed_height, cross: computed_width },
        LayoutType::Row | LayoutType::Overlay | LayoutType::Grid => {
            Size { main: computed_width, cross: computed_height }
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_grid<N, C>(
    node: &N,
    parent_layout_type: LayoutType,
    parent_main: f32,
    parent_cross: f32,
    cache: &mut C,
    tree: &<N as Node>::Tree,
    store: &<N as Node>::Store,
    sublayout: &mut <N as Node>::SubLayout<'_>,
) -> Size
where
    N: Node,
    C: Cache<Node = N>,
{
    let computed_main = parent_main;
    let computed_cross = parent_cross;

    let (mut parent_width, mut parent_height) = match parent_layout_type {
        LayoutType::Column => (parent_cross, parent_main),
        LayoutType::Row | LayoutType::Overlay | LayoutType::Grid => (parent_main, parent_cross),
    };

    let padding_left = node.padding_left(store).unwrap_or_default().to_px(parent_width, 0.0);
    let padding_right = node.padding_right(store).unwrap_or_default().to_px(parent_width, 0.0);
    let padding_top = node.padding_top(store).unwrap_or_default().to_px(parent_height, 0.0);
    let padding_bottom = node.padding_bottom(store).unwrap_or_default().to_px(parent_height, 0.0);

    parent_width -= padding_left + padding_right;
    parent_height -= padding_top + padding_bottom;

    let grid_cols = node.grid_columns(store).unwrap_or_default();
    let grid_rows = node.grid_rows(store).unwrap_or_default();

    let mut computed_grid_cols = vec![0.0; 2 * grid_cols.len() + 2];
    let mut computed_grid_rows = vec![0.0; 2 * grid_rows.len() + 2];

    let horizontal_gap = node.horizontal_gap(store).unwrap_or_default();
    let vertical_gap = node.vertical_gap(store).unwrap_or_default();

    // Sum of all space and size flex factors on the col-axis of the node.
    let mut col_flex_sum = 0.0;

    // List of stretch nodes for the col axis.
    let mut col_axis = SmallVec::<[StretchItem; 32]>::new();

    // Sum of all space and size flex factors on the row-axis of the node.
    let mut row_flex_sum = 0.0;

    // List of stretch nodes for the row axis.
    let mut row_axis = SmallVec::<[StretchItem; 32]>::new();

    for (i, col) in grid_cols.iter().enumerate() {
        let idx = 2 * i + 1;
        computed_grid_cols[idx] = col.to_px(parent_width, 0.0);

        if let Stretch(val) = col {
            col_flex_sum += val;
            col_axis.push(StretchItem::new(idx, *val, ItemType::Size, 0.0, 1000.0));
        }

        if i < grid_cols.len() - 1 {
            let gutter_idx = 2 * i + 2;
            computed_grid_cols[gutter_idx] = horizontal_gap.to_px(parent_width, 0.0);

            if let Stretch(val) = horizontal_gap {
                col_flex_sum += val;
                col_axis.push(StretchItem::new(gutter_idx, val, ItemType::Size, 0.0, 1000.0));
            }
        }
    }

    for (i, row) in grid_rows.iter().enumerate() {
        let idx = 2 * i + 1;
        computed_grid_rows[idx] = row.to_px(parent_height, 0.0);

        if let Stretch(val) = row {
            row_flex_sum += val;
            row_axis.push(StretchItem::new(idx, *val, ItemType::Size, 0.0, 1000.0));
        }

        if i < grid_rows.len() - 1 {
            let gutter_idx = 2 * i + 2;
            computed_grid_rows[gutter_idx] = vertical_gap.to_px(parent_height, 0.0);

            if let Stretch(val) = vertical_gap {
                row_flex_sum += val;
                row_axis.push(StretchItem::new(gutter_idx, val, ItemType::Size, 0.0, 1000.0));
            }
        }
    }

    // === Auto column measurement pass ===
    // For each Auto column, determine its natural width from single-span children in that column.
    // Only single-span children contribute; multi-span children are not considered.
    if grid_cols.iter().any(|col| matches!(col, Auto)) {
        let mut max_col_widths = vec![0.0f32; grid_cols.len()];

        for child in node
            .children(tree)
            .filter(|child| child.visible(store))
            .filter(|child| child.position_type(store).unwrap_or_default() == PositionType::Relative)
        {
            let cs = child.column_start(store).unwrap_or_default();
            let cspan = child.column_span(store).unwrap_or(1);

            if cspan == 1 && cs < grid_cols.len() && matches!(grid_cols[cs], Auto) {
                // Lay out with zero parent size to measure the child's natural (min-content) width.
                // Use the returned Size rather than cache.width(), because layout() stores
                // the child's own bounds only after the parent calls set_rect.
                let size = layout(child, LayoutType::Row, 0.0, 0.0, cache, tree, store, sublayout);
                max_col_widths[cs] = max_col_widths[cs].max(size.main);
            }
        }

        for (i, col) in grid_cols.iter().enumerate() {
            if matches!(col, Auto) {
                computed_grid_cols[2 * i + 1] = max_col_widths[i];
            }
        }
    }

    // === Auto row measurement pass ===
    // For each Auto row, determine its natural height from single-span children in that row.
    // Column widths from the Auto pass above (and Pixels/Percentage) are used so that children
    // with Auto height can measure themselves against their correct cell width.
    // Stretch columns are still 0 at this point, which gives a conservative (min-content) height.
    if grid_rows.iter().any(|row| matches!(row, Auto)) {
        let mut max_row_heights = vec![0.0f32; grid_rows.len()];

        for child in node
            .children(tree)
            .filter(|child| child.visible(store))
            .filter(|child| child.position_type(store).unwrap_or_default() == PositionType::Relative)
        {
            let rs = child.row_start(store).unwrap_or_default();
            let rspan = child.row_span(store).unwrap_or(1);

            if rspan == 1 && rs < grid_rows.len() && matches!(grid_rows[rs], Auto) {
                let cs = child.column_start(store).unwrap_or_default();
                let cspan = child.column_span(store).unwrap_or(1);

                // Sum the column widths and inter-column gaps for the child's cell span
                // from the pre-prefix-sum computed_grid_cols (indices 2*cs+1 .. 2*(cs+cspan)-1).
                let col_from = 2 * cs + 1;
                let col_to = 2 * (cs + cspan) - 1;
                let cell_width: f32 = if col_from <= col_to && col_to < computed_grid_cols.len() {
                    computed_grid_cols[col_from..=col_to].iter().sum()
                } else {
                    0.0
                };

                // Lay out with the known cell width and zero height to measure natural height.
                // Use the returned Size rather than cache.height() (layout() does not write
                // the node's own bounds; that is the parent's responsibility via set_rect).
                let size = layout(child, LayoutType::Row, cell_width, 0.0, cache, tree, store, sublayout);
                max_row_heights[rs] = max_row_heights[rs].max(size.cross);
            }
        }

        for (j, row) in grid_rows.iter().enumerate() {
            if matches!(row, Auto) {
                computed_grid_rows[2 * j + 1] = max_row_heights[j];
            }
        }
    }

    let mut width_sum: f32 = computed_grid_cols.iter().sum();
    let mut height_sum: f32 = computed_grid_rows.iter().sum();

    if !col_axis.is_empty() {
        loop {
            // If all stretch items are frozen, exit the loop.
            if col_axis.iter().all(|item| item.frozen) {
                break;
            }

            // Calculate free space on the main-axis.
            let free_col_space = parent_width - width_sum;

            let mut total_violation = 0.0;

            for item in col_axis.iter_mut().filter(|item| !item.frozen) {
                let actual_main = (item.factor * free_col_space / col_flex_sum).round();

                let clamped = actual_main.min(item.max).max(item.min);
                item.violation = clamped - actual_main;
                total_violation += item.violation;
                item.measured = actual_main;
                item.computed = clamped;
            }

            for item in col_axis.iter_mut().filter(|item| !item.frozen) {
                // Freeze over-stretched items.
                item.frozen = match total_violation {
                    total if total > 0.0 => item.violation > 0.0,
                    total if total < 0.0 => item.violation < 0.0,
                    _ => true,
                };

                // If the item is frozen, adjust the used_space and sum of cross stretch factors.
                if item.frozen {
                    col_flex_sum -= item.factor;
                    let prev = computed_grid_cols[item.index];
                    computed_grid_cols[item.index] = item.computed;
                    width_sum += item.computed - prev;
                }
            }
        }
    }

    if !row_axis.is_empty() {
        loop {
            // If all stretch items are frozen, exit the loop.
            if row_axis.iter().all(|item| item.frozen) {
                break;
            }

            // Calculate free space on the main-axis.
            let free_row_space = parent_height - height_sum;

            let mut total_violation = 0.0;

            for item in row_axis.iter_mut().filter(|item| !item.frozen) {
                let actual_main = (item.factor * free_row_space / row_flex_sum).round();

                let clamped = actual_main.min(item.max).max(item.min);
                item.violation = clamped - actual_main;
                total_violation += item.violation;
                item.measured = actual_main;
                item.computed = clamped;
            }

            for item in row_axis.iter_mut().filter(|item| !item.frozen) {
                // Freeze over-stretched items.
                item.frozen = match total_violation {
                    total if total > 0.0 => item.violation > 0.0,
                    total if total < 0.0 => item.violation < 0.0,
                    _ => true,
                };

                // If the item is frozen, adjust the used_space and sum of cross stretch factors.
                if item.frozen {
                    row_flex_sum -= item.factor;
                    let prev = computed_grid_rows[item.index];
                    computed_grid_rows[item.index] = item.computed;
                    height_sum += item.computed - prev;
                }
            }
        }
    }

    // println!("{:?} {:?}", computed_grid_cols, computed_grid_rows);

    let mut current_col_pos = 0.0;
    for col in &mut computed_grid_cols {
        current_col_pos += *col;
        *col = current_col_pos;
    }

    let mut current_row_pos = 0.0;
    for row in &mut computed_grid_rows {
        current_row_pos += *row;
        *row = current_row_pos;
    }

    // println!("{:?} {:?}", computed_grid_cols, computed_grid_rows);

    let mut alignment = node.alignment(store).unwrap_or_default();

    if node.direction(store).unwrap_or_default() == Direction::RightToLeft {
        alignment = flip_alignment_horizontal(alignment);
    }

    let (mut child_posx, mut child_posy) = match alignment {
        Alignment::TopLeft => (0.0, 0.0),
        Alignment::TopCenter => (0.0, 0.5),
        Alignment::TopRight => (0.0, 1.0),
        Alignment::Left => (0.5, 0.0),
        Alignment::Center => (0.5, 0.5),
        Alignment::Right => (0.5, 1.0),
        Alignment::BottomLeft => (1.0, 0.0),
        Alignment::BottomCenter => (1.0, 0.5),
        Alignment::BottomRight => (1.0, 1.0),
    };

    child_posx *= parent_width - width_sum;
    child_posy *= parent_height - height_sum;

    let node_children = node
        .children(tree)
        .filter(|child| child.visible(store))
        .filter(|child| child.position_type(store).unwrap_or_default() == PositionType::Relative);

    // Compute space and size of non-flexible relative children.
    for child in node_children {
        let column_start = 2 * child.column_start(store).unwrap_or_default();
        let column_span = 2 * child.column_span(store).unwrap_or(1) - 1;
        let column_end = column_start + column_span;

        let row_start = 2 * child.row_start(store).unwrap_or_default();
        let row_span = 2 * child.row_span(store).unwrap_or(1) - 1;
        let row_end = row_start + row_span;

        let posx = computed_grid_cols[column_start];
        let width = computed_grid_cols[column_end] - posx;

        let posy = computed_grid_rows[row_start];
        let height = computed_grid_rows[row_end] - posy;

        layout(child, LayoutType::Row, width, height, cache, tree, store, sublayout);

        cache.set_rect(
            child,
            LayoutType::Row,
            posx + padding_left + child_posx,
            posy + padding_top + child_posy,
            width,
            height,
        );
    }

    Size { main: computed_main, cross: computed_cross }
}

/// Performs wrapped layout on the given node, arranging children into multiple lines
/// along the main axis when they overflow the available space.
///
/// Called from [`layout`] when a node has [`LayoutWrap::Wrap`] set.
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout_wrap<N, C>(
    node: &N,
    parent_layout_type: LayoutType,
    parent_main: f32,
    parent_cross: f32,
    cache: &mut C,
    tree: &<N as Node>::Tree,
    store: &<N as Node>::Store,
    sublayout: &mut <N as Node>::SubLayout<'_>,
) -> Size
where
    N: Node,
    C: Cache<Node = N>,
{
    let layout_type = node.layout_type(store).unwrap_or_default();

    // Convert parent-provided main/cross (which are in parent layout axes)
    // into this node's layout axes.
    let (parent_main, parent_cross) =
        if parent_layout_type == layout_type { (parent_main, parent_cross) } else { (parent_cross, parent_main) };

    let padding_main_before = node.padding_main_before(store, layout_type).to_px(parent_main, 0.0);
    let padding_main_after = node.padding_main_after(store, layout_type).to_px(parent_main, 0.0);
    let padding_cross_before = node.padding_cross_before(store, layout_type).to_px(parent_cross, 0.0);
    let padding_cross_after = node.padding_cross_after(store, layout_type).to_px(parent_cross, 0.0);

    // Available space for children after subtracting padding.
    let avail_main = parent_main - padding_main_before - padding_main_after;
    let avail_cross = parent_cross - padding_cross_before - padding_cross_after;

    // Gap between items within a line (on the main axis).
    let min_main_between = node.min_main_between(store, layout_type);
    let max_main_between = node.max_main_between(store, layout_type);
    let item_gap_px =
        node.main_between(store, layout_type).to_px_clamped(avail_main, 0.0, min_main_between, max_main_between);

    // Gap between lines (on the cross axis).
    let line_gap_px = node.cross_between(store, layout_type).to_px(avail_cross, 0.0);

    let is_inline_rtl = matches!(layout_type, LayoutType::Row | LayoutType::Column)
        && node.direction(store).unwrap_or_default() == Direction::RightToLeft;

    let relative_children = node
        .children(tree)
        .filter(|c| c.visible(store))
        .filter(|c| c.position_type(store).unwrap_or_default() == PositionType::Relative)
        .collect::<SmallVec<[&N; 32]>>();

    let num_rel = relative_children.len();

    // Per-item data used during layout.
    struct WrapItem {
        main: f32,
        cross: f32,
        /// Non-zero when this item has Stretch units on the main axis.
        stretch_main_factor: f32,
        cross_is_stretch: bool,
        min_main: f32,
        max_main: f32,
        min_cross: f32,
        max_cross: f32,
    }

    // Phase 1: Compute sizes for all relative children.
    // Stretch-main items are deferred; their sizes are resolved per-line in phase 3.
    let mut items: SmallVec<[WrapItem; 32]> = SmallVec::with_capacity(num_rel);
    for child in relative_children.iter() {
        let child_main_units = child.main(store, layout_type);
        let child_min_main = child.min_main(store, layout_type);
        let child_max_main = child.max_main(store, layout_type);
        let child_min_cross = child.min_cross(store, layout_type);
        let child_max_cross = child.max_cross(store, layout_type);
        let child_cross_is_stretch = child.cross(store, layout_type).is_stretch();

        let min_main_px = child_min_main.to_px(avail_main, DEFAULT_MIN);
        let max_main_px = child_max_main.to_px(avail_main, DEFAULT_MAX);
        let min_cross_px = child_min_cross.to_px(avail_cross, DEFAULT_MIN);
        let max_cross_px = child_max_cross.to_px(avail_cross, DEFAULT_MAX);

        if let Stretch(factor) = child_main_units {
            // Use min size as base for line-break decisions; actual size resolved later.
            let base = min_main_px.max(0.0);
            items.push(WrapItem {
                main: base,
                cross: 0.0,
                stretch_main_factor: factor,
                cross_is_stretch: child_cross_is_stretch,
                min_main: min_main_px,
                max_main: max_main_px,
                min_cross: min_cross_px,
                max_cross: max_cross_px,
            });
        } else {
            let size = layout(*child, layout_type, avail_main, avail_cross, cache, tree, store, sublayout);
            items.push(WrapItem {
                main: size.main,
                cross: size.cross,
                stretch_main_factor: 0.0,
                cross_is_stretch: child_cross_is_stretch,
                min_main: min_main_px,
                max_main: max_main_px,
                min_cross: min_cross_px,
                max_cross: max_cross_px,
            });
        }
    }

    // Phase 2: Assign children to lines.
    // A new line begins when adding the next child would exceed avail_main.
    // Stretch-main children use their min contribution for break decisions.
    // If avail_main <= 0 (auto-width container), no breaks occur.
    let mut lines: SmallVec<[std::ops::Range<usize>; 8]> = SmallVec::new();
    if num_rel > 0 {
        let mut line_start = 0usize;
        let mut line_main_used = 0.0f32;
        let mut items_in_line = 0usize;

        for i in 0..num_rel {
            // Stretch items contribute their min size to the line-break decision (0 if no min set).
            let size_contribution = items[i].main;
            let gap_before = if items_in_line > 0 { item_gap_px } else { 0.0 };
            let projected = line_main_used + gap_before + size_contribution;

            if avail_main > 0.0 && items_in_line > 0 && projected > avail_main {
                // Finish current line and start a new one.
                lines.push(line_start..i);
                line_start = i;
                line_main_used = size_contribution;
                items_in_line = 1;
            } else {
                line_main_used = projected;
                items_in_line += 1;
            }
        }
        lines.push(line_start..num_rel);
    }

    // Phase 3: Per-line flex resolution for stretch-main items.
    for line in lines.iter() {
        let start = line.start;
        let end = line.end;
        let count = line.len();
        if count == 0 {
            continue;
        }

        let mut stretch_sum = 0.0f32;
        let mut fixed_sum = 0.0f32;
        for i in start..end {
            if items[i].stretch_main_factor > 0.0 {
                stretch_sum += items[i].stretch_main_factor;
            } else {
                fixed_sum += items[i].main;
            }
        }

        if stretch_sum > 0.0 {
            let gap_total = (count - 1) as f32 * item_gap_px;
            let mut remaining_main = (avail_main - fixed_sum - gap_total).max(0.0);
            let mut remaining_stretch_sum = stretch_sum;

            #[derive(Clone, Copy)]
            struct StretchAlloc {
                index: usize,
                factor: f32,
                min: f32,
                max: f32,
                frozen: bool,
                measured: f32,
                computed: f32,
                violation: f32,
            }

            let mut stretch_items: SmallVec<[StretchAlloc; 16]> = SmallVec::new();
            for i in start..end {
                if items[i].stretch_main_factor > 0.0 {
                    stretch_items.push(StretchAlloc {
                        index: i,
                        factor: items[i].stretch_main_factor,
                        min: items[i].min_main,
                        max: items[i].max_main,
                        frozen: false,
                        measured: 0.0,
                        computed: 0.0,
                        violation: 0.0,
                    });
                }
            }

            while !stretch_items.iter().all(|item| item.frozen) {
                let mut total_violation = 0.0f32;

                for item in stretch_items.iter_mut().filter(|item| !item.frozen) {
                    let measured = if remaining_stretch_sum > 0.0 {
                        (item.factor * remaining_main / remaining_stretch_sum).round()
                    } else {
                        0.0
                    };
                    let computed = measured.clamp(item.min, item.max);

                    item.measured = measured;
                    item.computed = computed;
                    item.violation = computed - measured;
                    total_violation += item.violation;
                }

                for item in stretch_items.iter_mut().filter(|item| !item.frozen) {
                    item.frozen = match total_violation {
                        total if total > 0.0 => item.violation > 0.0,
                        total if total < 0.0 => item.violation < 0.0,
                        _ => true,
                    };

                    if item.frozen {
                        remaining_stretch_sum -= item.factor;
                        remaining_main = (remaining_main - item.computed).max(0.0);
                    }
                }
            }

            for item in stretch_items.iter() {
                let size = layout(
                    relative_children[item.index],
                    layout_type,
                    item.computed,
                    avail_cross,
                    cache,
                    tree,
                    store,
                    sublayout,
                );
                items[item.index].main = size.main;
                items[item.index].cross = size.cross;
            }
        }
    }

    // Phase 4: Compute the cross extent of each line from non-cross-stretch children.
    let mut line_cross: SmallVec<[f32; 8]> = SmallVec::with_capacity(lines.len());
    for line in lines.iter() {
        let start = line.start;
        let end = line.end;
        let mut max_cross = 0.0f32;
        for i in start..end {
            if !items[i].cross_is_stretch {
                max_cross = max_cross.max(items[i].cross);
            }
        }
        line_cross.push(max_cross);
    }

    // Phase 5: Resolve cross-stretch children to fill their line's cross extent.
    // This runs in two passes:
    // 1) stretch against the current estimate,
    // 2) stretch again against the settled line max.
    // The second pass is required when all line items are cross-stretch and one
    // item's min/max constraint determines the line cross-size.
    for (line_idx, line) in lines.iter().enumerate() {
        let start = line.start;
        let end = line.end;

        let resolve_stretch_line = |target_cross: f32,
                                    items: &mut SmallVec<[WrapItem; 32]>,
                                    cache: &mut C,
                                    sublayout: &mut <N as Node>::SubLayout<'_>| {
            for i in start..end {
                if items[i].cross_is_stretch {
                    let child = relative_children[i];
                    let clamped_cross = target_cross.clamp(items[i].min_cross, items[i].max_cross);
                    let size = layout(child, layout_type, items[i].main, clamped_cross, cache, tree, store, sublayout);
                    items[i].main = size.main;
                    items[i].cross = size.cross;
                }
            }
        };

        let compute_line_max = |items: &SmallVec<[WrapItem; 32]>| {
            let mut max_cross = 0.0f32;
            for i in start..end {
                max_cross = max_cross.max(items[i].cross);
            }
            max_cross
        };

        resolve_stretch_line(line_cross[line_idx], &mut items, cache, sublayout);
        let settled_cross = compute_line_max(&items);
        resolve_stretch_line(settled_cross, &mut items, cache, sublayout);
        line_cross[line_idx] = compute_line_max(&items);
    }

    // Phase 6: Determine the final cross size of the container.
    let num_lines = lines.len();
    let total_content_cross = if num_lines > 0 {
        line_cross.iter().sum::<f32>() + (num_lines.saturating_sub(1)) as f32 * line_gap_px
    } else {
        0.0
    };

    let cross_units = node.cross(store, layout_type);
    let final_cross = if cross_units.is_auto() || parent_cross == 0.0 {
        let raw = total_content_cross + padding_cross_before + padding_cross_after;
        let min_c = node.min_cross(store, layout_type).to_px(0.0, DEFAULT_MIN);
        let max_c = node.max_cross(store, layout_type).to_px(0.0, DEFAULT_MAX);
        raw.max(min_c).min(max_c)
    } else {
        parent_cross
    };

    // Recompute auto main size (for containers with Auto main axis).
    let main_units = node.main(store, layout_type);
    let final_main = if main_units.is_auto() || parent_main == 0.0 {
        let raw = lines
            .iter()
            .map(|line| {
                let mut sum = 0.0f32;
                for i in line.start..line.end {
                    sum += items[i].main;
                }
                sum + (line.len().saturating_sub(1)) as f32 * item_gap_px
            })
            .fold(0.0f32, f32::max);
        let raw = raw + padding_main_before + padding_main_after;
        let min_m = node.min_main(store, layout_type).to_px(0.0, DEFAULT_MIN);
        let max_m = node.max_main(store, layout_type).to_px(0.0, DEFAULT_MAX);
        raw.max(min_m).min(max_m)
    } else {
        parent_main
    };

    // Phase 7: Lay out absolute children against the container bounds.
    // Absolute children are sized against the padding box (content box + padding, excluding border).
    let abs_avail_main = final_main;
    let abs_avail_cross = final_cross;

    let abs_children = node
        .children(tree)
        .filter(|c| c.position_type(store).unwrap_or_default() == PositionType::Absolute)
        .filter(|c| c.visible(store));

    let mut abs_items: SmallVec<[ChildNode<N>; 8]> = SmallVec::new();
    for child in abs_children {
        let main = if child.main(store, layout_type).is_stretch() {
            let child_min_main = child.min_main(store, layout_type).to_px(abs_avail_main, DEFAULT_MIN);
            let child_max_main = child.max_main(store, layout_type).to_px(abs_avail_main, DEFAULT_MAX);
            let main_before = child.main_before(store, layout_type).to_px(abs_avail_main, 0.0);
            let main_after = child.main_after(store, layout_type).to_px(abs_avail_main, 0.0);
            abs_avail_main.clamp(child_min_main, child_max_main) - main_before - main_after
        } else {
            abs_avail_main
        };

        let cross = if child.cross(store, layout_type).is_stretch() {
            let child_min_cross = child.min_cross(store, layout_type).to_px(abs_avail_cross, DEFAULT_MIN);
            let child_max_cross = child.max_cross(store, layout_type).to_px(abs_avail_cross, DEFAULT_MAX);
            let cross_before = child.cross_before(store, layout_type).to_px(abs_avail_cross, 0.0);
            let cross_after = child.cross_after(store, layout_type).to_px(abs_avail_cross, 0.0);
            abs_avail_cross.clamp(child_min_cross, child_max_cross) - cross_before - cross_after
        } else {
            abs_avail_cross
        };

        let size = layout(child, layout_type, main, cross, cache, tree, store, sublayout);
        abs_items.push(ChildNode {
            node: child,
            main: size.main,
            cross: size.cross,
            main_after: 0.0,
            last_layout_main: 0.0,
            last_layout_cross: 0.0,
            has_layout_constraints: false,
        });
    }

    // Phase 8: Position all children.
    // Decompose alignment into (main-fraction, cross-fraction) where the
    // main-fraction offsets the whole group and cross-fraction aligns each item
    // within its line's cross extent.  The swap mirrors what the non-wrap layout
    // does so that `TopLeft` means the same visual position regardless of
    // layout_type.
    let mut alignment = node.alignment(store).unwrap_or_default();

    // For RTL inline layouts, flip horizontal alignment so TopLeft becomes TopRight.
    if is_inline_rtl {
        alignment = flip_alignment_horizontal(alignment);
    }

    let (mut main_align_frac, mut cross_align_frac) = match alignment {
        Alignment::TopLeft => (0.0f32, 0.0f32),
        Alignment::TopCenter => (0.0, 0.5),
        Alignment::TopRight => (0.0, 1.0),
        Alignment::Left => (0.5, 0.0),
        Alignment::Center => (0.5, 0.5),
        Alignment::Right => (0.5, 1.0),
        Alignment::BottomLeft => (1.0, 0.0),
        Alignment::BottomCenter => (1.0, 0.5),
        Alignment::BottomRight => (1.0, 1.0),
    };
    if layout_type == LayoutType::Row {
        std::mem::swap(&mut main_align_frac, &mut cross_align_frac);
    }

    let mut cross_cursor = padding_cross_before;

    for (line_idx, line) in lines.iter().enumerate() {
        let start = line.start;
        let end = line.end;
        let lc = line_cross[line_idx];
        let count = line.len();
        let gap_total = (count.saturating_sub(1)) as f32 * item_gap_px;
        let mut line_main_sum = 0.0f32;
        for i in start..end {
            line_main_sum += items[i].main;
        }
        let free_main = (avail_main - line_main_sum - gap_total).max(0.0);

        if layout_type == LayoutType::Row && node.direction(store).unwrap_or_default() == Direction::RightToLeft {
            // RTL positioning: place items in reverse order within each wrapped line.
            // Alignment is flipped above so TopLeft maps to TopRight semantics.
            let mut main_cursor = padding_main_before + main_align_frac * free_main;

            for (item_idx, i) in (start..end).rev().enumerate() {
                let item = &items[i];
                let child = relative_children[i];
                let item_cross_offset = cross_align_frac * (lc - item.cross);

                cache.set_rect(
                    child,
                    layout_type,
                    main_cursor,
                    cross_cursor + item_cross_offset,
                    item.main,
                    item.cross,
                );

                main_cursor += item.main;
                if item_idx + 1 < count {
                    main_cursor += item_gap_px;
                }
            }
        } else {
            // LTR positioning: items are positioned left-to-right within the line
            let mut main_cursor = padding_main_before + main_align_frac * free_main;

            for i in start..end {
                let item = &items[i];
                let child = relative_children[i];

                let item_cross_offset = cross_align_frac * (lc - item.cross);

                cache.set_rect(
                    child,
                    layout_type,
                    main_cursor,
                    cross_cursor + item_cross_offset,
                    item.main,
                    item.cross,
                );

                main_cursor += item.main;
                if i + 1 < end {
                    main_cursor += item_gap_px;
                }
            }
        }

        cross_cursor += lc;
        if line_idx + 1 < num_lines {
            cross_cursor += line_gap_px;
        }
    }

    // Position absolute children.
    for abs_child in &abs_items {
        let (child_main_before, child_main_after) =
            if layout_type == LayoutType::Row && node.direction(store).unwrap_or_default() == Direction::RightToLeft {
                (abs_child.node.main_after(store, layout_type), abs_child.node.main_before(store, layout_type))
            } else {
                (abs_child.node.main_before(store, layout_type), abs_child.node.main_after(store, layout_type))
            };
        let (child_cross_before, child_cross_after) = if layout_type == LayoutType::Column
            && node.direction(store).unwrap_or_default() == Direction::RightToLeft
        {
            (abs_child.node.cross_after(store, layout_type), abs_child.node.cross_before(store, layout_type))
        } else {
            (abs_child.node.cross_before(store, layout_type), abs_child.node.cross_after(store, layout_type))
        };

        let pma = abs_avail_main;
        let pca = abs_avail_cross;

        let child_main_pos = match (child_main_before, child_main_after) {
            (Pixels(val), _) => val,
            (Percentage(val), _) => val * 0.01 * pma,
            (_, Pixels(val)) => pma - val - abs_child.main,
            (_, Percentage(val)) => pma - abs_child.main - val * 0.01 * pma,
            (Stretch(b), Stretch(a)) => {
                if b == a {
                    (pma - abs_child.main) * 0.5
                } else {
                    (pma - abs_child.main) * (b / (b + a))
                }
            }
            (Stretch(_), Auto) => pma - abs_child.main,
            (Auto, Stretch(_)) => 0.0,
            (Auto, Auto) => 0.0,
        };

        let child_cross_pos = match (child_cross_before, child_cross_after) {
            (Pixels(val), _) => val,
            (Percentage(val), _) => val * 0.01 * pca,
            (_, Pixels(val)) => pca - val - abs_child.cross,
            (_, Percentage(val)) => pca - abs_child.cross - val * 0.01 * pca,
            (Stretch(b), Stretch(a)) => {
                if b == a {
                    (pca - abs_child.cross) * 0.5
                } else {
                    (pca - abs_child.cross) * (b / (b + a))
                }
            }
            (Stretch(_), Auto) => pca - abs_child.cross,
            (Auto, Stretch(_)) => 0.0,
            (Auto, Auto) => 0.0,
        };

        cache.set_rect(abs_child.node, layout_type, child_main_pos, child_cross_pos, abs_child.main, abs_child.cross);
    }

    if parent_layout_type == layout_type {
        Size { main: final_main, cross: final_cross }
    } else {
        Size { main: final_cross, cross: final_main }
    }
}

/// Performs layout on the given node returning its computed size.
///
/// The algorithm recurses down the tree, in depth-first order, and performs
/// layout on every node starting from the input `node`.
///
/// # Arguments
///
/// * `node` - Root node to start layout from.
/// * `parent_layout_type` - The [`LayoutType`] of the parent of the `node`.
/// * `parent_main` - The size of the parent of the `node` on its main axis or the main-size of the node if the node is stretch (determined by parent).
/// * `parent_cross` - The size of the parent of the `node` on its cross axis or the cross-size of the node if the node is stretch (determined by parent).
/// * `cache` - A mutable reference to the [`Cache`].
/// * `tree` - A mutable reference to the [`Tree`](crate::Node::Tree).
/// * `store` - A mutable reference to the [`Store`](crate::Node::Store).
/// * `sublayout` - A mutable reference to the [`SubLayout`](crate::Node::SubLayout) context.
///
/// # Example
///
/// ```
/// layout(&root, LayoutType::Column, 600.0, 600.0, &mut cache, &tree, &store, &mut sublayout);
/// ```
#[allow(clippy::too_many_arguments)]
pub(crate) fn layout<N, C>(
    node: &N,
    parent_layout_type: LayoutType,
    parent_main: f32,
    parent_cross: f32,
    cache: &mut C,
    tree: &<N as Node>::Tree,
    store: &<N as Node>::Store,
    sublayout: &mut <N as Node>::SubLayout<'_>,
) -> Size
where
    N: Node,
    C: Cache<Node = N>,
{
    // The layout type of the node. Determines the main and cross axes of the children.
    let layout_type = node.layout_type(store).unwrap_or_default();

    // The desired main-axis and cross-axis sizes of the node.
    let main = node.main(store, parent_layout_type);
    let cross = node.cross(store, parent_layout_type);
    let aspect_ratio = node.aspect_ratio(store).filter(|ratio| ratio.is_finite() && *ratio > 0.0);

    let mut min_main = if main.is_stretch() {
        DEFAULT_MIN
    } else {
        node.min_main(store, parent_layout_type).to_px(parent_main, DEFAULT_MIN)
    };

    let mut max_main = if main.is_stretch() {
        DEFAULT_MAX
    } else {
        node.max_main(store, parent_layout_type).to_px(parent_main, DEFAULT_MAX)
    };

    let mut min_cross = node.min_cross(store, parent_layout_type).to_px(parent_cross, DEFAULT_MIN);

    let mut max_cross = node.max_cross(store, parent_layout_type).to_px(parent_cross, DEFAULT_MAX);

    // Compute main-axis size.
    let mut computed_main = match main {
        Pixels(val) => val,
        Percentage(val) => (parent_main * (val / 100.0)).round(),
        Stretch(_) => parent_main,
        Auto => 0.0,
    };

    // Compute cross-axis size.
    let mut computed_cross = match cross {
        Pixels(val) => val,
        Percentage(val) => (parent_cross * (val / 100.0)).round(),
        Stretch(_) => parent_cross,
        Auto => 0.0,
    };

    // Classify visible children once to avoid repeated tree traversals.
    let mut relative_children = SmallVec::<[&N; 32]>::new();
    let mut absolute_children = SmallVec::<[&N; 8]>::new();
    for child in node.children(tree).filter(|child| child.visible(store)) {
        match child.position_type(store).unwrap_or_default() {
            PositionType::Relative => relative_children.push(child),
            PositionType::Absolute => absolute_children.push(child),
        }
    }

    // Get the total number of children of the node.
    let num_children = relative_children.len() + absolute_children.len();

    // Get the total number of relative children of the node.
    let num_parent_directed_children = relative_children.len();

    // Apply content sizing.
    if (node.min_main(store, parent_layout_type).is_auto() || node.min_cross(store, parent_layout_type).is_auto())
        && num_parent_directed_children == 0
    {
        let p_main = if node.min_main(store, parent_layout_type).is_auto() { None } else { Some(computed_main) };
        let p_cross = if node.min_cross(store, parent_layout_type).is_auto() { None } else { Some(computed_cross) };

        if let Some(content_size) = node.content_sizing(store, sublayout, parent_layout_type, p_main, p_cross) {
            min_main = content_size.0;
            min_cross = content_size.1;
        }
    }

    if (main.is_auto() || cross.is_auto()) && num_parent_directed_children == 0 {
        let p_main = if main.is_auto() { None } else { Some(computed_main) };
        let p_cross = if cross.is_auto() { None } else { Some(computed_cross) };

        if let Some(content_size) = node.content_sizing(store, sublayout, parent_layout_type, p_main, p_cross) {
            computed_main = content_size.0;
            computed_cross = content_size.1;
        }
    }

    clamp_with_aspect_ratio(
        parent_layout_type,
        aspect_ratio,
        main.is_auto(),
        cross.is_auto(),
        min_main,
        max_main,
        min_cross,
        max_cross,
        &mut computed_main,
        &mut computed_cross,
    );

    if layout_type == LayoutType::Grid {
        return layout_grid(node, parent_layout_type, computed_main, computed_cross, cache, tree, store, sublayout);
    }

    if layout_type == LayoutType::Overlay {
        return layout_overlay(node, parent_layout_type, computed_main, computed_cross, cache, tree, store, sublayout);
    }

    if node.wrap(store).unwrap_or_default() == LayoutWrap::Wrap {
        return layout_wrap(node, parent_layout_type, computed_main, computed_cross, cache, tree, store, sublayout);
    }

    // Determine the parent_main/cross size to pass to the children based on the layout type of the parent and the node.
    // i.e. if the parent layout type and the node layout type are different, swap the main and the cross axes.
    let (mut parent_main, mut parent_cross) = if parent_layout_type == layout_type {
        (computed_main, computed_cross)
    } else {
        (computed_cross, computed_main)
    };

    // Sum of all space and size flex factors on the main-axis of the node.
    let mut main_flex_sum = 0.0;

    // List of child nodes for the current node.
    let mut children = SmallVec::<[ChildNode<N>; 32]>::with_capacity(num_children);

    // List of stretch nodes for the current node.
    // A stretch node is any flexible space/size. e.g. main_before, main, and main_after are separate stretch nodes
    let mut main_axis = SmallVec::<[StretchItem; 32]>::new();

    // Parent overrides for child auto space.
    let padding_main_before = node.padding_main_before(store, layout_type).to_px(parent_main, 0.0);
    let padding_main_after = node.padding_main_after(store, layout_type).to_px(parent_main, 0.0);
    let padding_cross_before = node.padding_cross_before(store, layout_type).to_px(parent_cross, 0.0);
    let padding_cross_after = node.padding_cross_after(store, layout_type).to_px(parent_cross, 0.0);

    let min_main_between = node.min_main_between(store, layout_type);
    let max_main_between = node.max_main_between(store, layout_type);

    parent_main = parent_main - padding_main_before - padding_main_after;
    parent_cross = parent_cross - padding_cross_before - padding_cross_after;

    let is_row_rtl =
        layout_type == LayoutType::Row && node.direction(store).unwrap_or_default() == Direction::RightToLeft;

    let is_column_rtl =
        layout_type == LayoutType::Column && node.direction(store).unwrap_or_default() == Direction::RightToLeft;

    if is_row_rtl {
        relative_children.reverse();
    }

    let last = relative_children.len().checked_sub(1);

    // Compute space and size of non-flexible relative children.
    for (index, child) in relative_children.into_iter().enumerate() {
        let child_main = child.main(store, layout_type);
        let child_cross = child.cross(store, layout_type);

        // Get fixed-size constraints.
        let child_min_main = child.min_main(store, layout_type);
        let child_max_main = child.max_main(store, layout_type);

        let child_min_cross = child.min_cross(store, layout_type);
        let child_max_cross = child.max_cross(store, layout_type);

        let mut computed_child_main_after = 0.0f32;

        if last != Some(index) {
            let child_main_after = node.main_between(store, layout_type);

            if let Stretch(factor) = child_main_after {
                main_flex_sum += factor;
                main_axis.push(StretchItem::new(
                    index,
                    factor,
                    ItemType::After,
                    min_main_between.to_px(parent_main, DEFAULT_MIN),
                    max_main_between.to_px(parent_main, DEFAULT_MAX),
                ));
            } else {
                computed_child_main_after =
                    child_main_after.to_px_clamped(parent_main, 0.0, min_main_between, max_main_between);
            }
        }

        let mut computed_child_main = 0.0;

        // Collect stretch main items.
        if let Stretch(factor) = child_main {
            main_flex_sum += factor;
            main_axis.push(StretchItem::new(
                index,
                factor,
                ItemType::Size,
                child_min_main.to_px(parent_main, DEFAULT_MIN),
                child_max_main.to_px(parent_main, DEFAULT_MAX),
            ));
        } else {
            computed_child_main = child_main.to_px_clamped(parent_cross, 0.0, child_min_main, child_max_main);
        }

        let mut computed_child_cross = child_cross.to_px_clamped(parent_cross, 0.0, child_min_cross, child_max_cross);

        // Compute fixed-size child main and cross.
        let mut has_layout_constraints = false;
        let mut last_layout_main = 0.0;
        let mut last_layout_cross = 0.0;

        if !child_main.is_stretch() && (!child_cross.is_stretch() || child_min_cross.is_auto()) {
            let child_size = layout(child, layout_type, parent_main, parent_cross, cache, tree, store, sublayout);

            computed_child_main = child_size.main;
            computed_child_cross = child_size.cross;
            has_layout_constraints = true;
            last_layout_main = parent_main;
            last_layout_cross = parent_cross;
        }

        children.push(ChildNode {
            node: child,
            cross: computed_child_cross,
            main: computed_child_main,
            main_after: computed_child_main_after,
            last_layout_main,
            last_layout_cross,
            has_layout_constraints,
        });
    }

    // Sum of all child nodes on the main-axis.
    let mut main_sum: f32 = children.iter().map(|child| child.main + child.main_after).sum();

    // Maximum of all child nodes on the cross-axis.
    let mut cross_max: f32 = children.iter().map(|child| child.cross).reduce(f32::max).unwrap_or_default();

    // Determine auto main and cross size from space and size of children.
    if num_parent_directed_children != 0 {
        if main.is_auto() || node.min_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_main = main_sum + padding_main_before + padding_main_after;
            } else {
                min_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if node.max_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && main_sum != 0.0 {
                max_main = main_sum + padding_main_before + padding_main_after;
            } else if cross_max != 0.0 {
                max_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if cross.is_auto() || node.min_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_cross = cross_max + padding_cross_before + padding_cross_after;
            } else {
                min_cross = main_sum + padding_main_before + padding_main_after;
            }
        }

        if node.max_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && cross_max != 0.0 {
                max_cross = cross_max + padding_cross_before + padding_cross_after;
            } else if main_sum != 0.0 {
                max_cross = main_sum + padding_main_before + padding_main_after;
            }
        }
    }

    clamp_with_aspect_ratio(
        parent_layout_type,
        aspect_ratio,
        main.is_auto(),
        cross.is_auto(),
        min_main,
        max_main,
        min_cross,
        max_cross,
        &mut computed_main,
        &mut computed_cross,
    );

    let (mut parent_main, mut parent_cross) = if parent_layout_type == layout_type {
        (computed_main, computed_cross)
    } else {
        (computed_cross, computed_main)
    };

    parent_main = parent_main - padding_main_before - padding_main_after;
    parent_cross = parent_cross - padding_cross_before - padding_cross_after;

    // Compute stretch size on the cross-axis for relative children.
    for child in children
        .iter_mut()
        .filter(|child| child.node.position_type(store).unwrap_or_default() == PositionType::Relative)
        .filter(|child| child.node.cross(store, layout_type).is_stretch())
    {
        if !child.node.main(store, layout_type).is_stretch() {
            if !child.has_layout_constraints
                || !same_f32(child.last_layout_main, parent_main)
                || !same_f32(child.last_layout_cross, parent_cross)
            {
                let child_size =
                    layout(child.node, layout_type, parent_main, parent_cross, cache, tree, store, sublayout);
                child.main = child_size.main;
                child.cross = child_size.cross;
                child.last_layout_main = parent_main;
                child.last_layout_cross = parent_cross;
                child.has_layout_constraints = true;
            }
        } else {
            let child_min_cross = if child.node.min_cross(store, layout_type).is_auto() {
                child.cross
            } else {
                child.node.min_cross(store, layout_type).to_px(parent_cross, DEFAULT_MIN)
            };

            let child_max_cross = child.node.max_cross(store, layout_type).to_px(parent_cross, DEFAULT_MAX);

            child.cross = parent_cross.clamp(child_min_cross, child_max_cross);
        }
    }

    main_sum = children.iter().map(|child| child.main + child.main_after).sum();
    cross_max = children.iter().map(|child| child.cross).reduce(f32::max).unwrap_or_default();

    // Determine auto main and cross size from space and size of children.
    if num_parent_directed_children != 0 {
        if main.is_auto() || node.min_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_main = main_sum + padding_main_before + padding_main_after;
            } else {
                min_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if node.max_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && main_sum != 0.0 {
                max_main = main_sum + padding_main_before + padding_main_after;
            } else if cross_max != 0.0 {
                max_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if cross.is_auto() || node.min_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_cross = cross_max + padding_cross_before + padding_cross_after;
            } else {
                min_cross = main_sum + padding_main_before + padding_main_after;
            }
        }

        if node.max_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && cross_max != 0.0 {
                max_cross = cross_max + padding_cross_before + padding_cross_after;
            } else if main_sum != 0.0 {
                max_cross = main_sum + padding_main_before + padding_main_after;
            }
        }
    }

    clamp_with_aspect_ratio(
        parent_layout_type,
        aspect_ratio,
        main.is_auto(),
        cross.is_auto(),
        min_main,
        max_main,
        min_cross,
        max_cross,
        &mut computed_main,
        &mut computed_cross,
    );

    // Compute flexible space and size on the main axis for relative children.
    if !main_axis.is_empty() {
        loop {
            // If all stretch items are frozen, exit the loop.
            if main_axis.iter().all(|item| item.frozen) {
                break;
            }

            // Calculate free space on the main-axis.
            let free_main_space = parent_main - main_sum;

            let mut total_violation = 0.0;

            for item in main_axis.iter_mut().filter(|item| !item.frozen) {
                let input_main = (item.factor * free_main_space / main_flex_sum).round();
                let mut actual_main = input_main;

                let child = &mut children[item.index];

                if item.item_type == ItemType::Size {
                    let target_cross =
                        if child.node.cross(store, layout_type).is_stretch() { child.cross } else { parent_cross };

                    if !child.has_layout_constraints
                        || !same_f32(child.last_layout_main, input_main)
                        || !same_f32(child.last_layout_cross, target_cross)
                    {
                        let child_size =
                            layout(child.node, layout_type, input_main, target_cross, cache, tree, store, sublayout);
                        child.cross = child_size.cross;
                        actual_main = child_size.main;
                        item.measured = actual_main;
                        child.last_layout_main = input_main;
                        child.last_layout_cross = target_cross;
                        child.has_layout_constraints = true;
                    } else {
                        actual_main = item.measured;
                    }

                    if child.node.min_main(store, layout_type).is_auto() {
                        item.min = child.main;
                    }
                }

                let clamped = actual_main.min(item.max).max(item.min);
                item.violation = clamped - actual_main;
                total_violation += item.violation;
                item.computed = clamped;
            }

            for item in main_axis.iter_mut().filter(|item| !item.frozen) {
                let child = &mut children[item.index];

                // Freeze over-stretched items.
                item.frozen = match total_violation {
                    total if total > 0.0 => item.violation > 0.0,
                    total if total < 0.0 => item.violation < 0.0,
                    _ => true,
                };

                // If the item is frozen, adjust the used_space and sum of cross stretch factors.
                if item.frozen {
                    main_flex_sum -= item.factor;
                    let previous_total = child.main + child.main_after;

                    match item.item_type {
                        ItemType::Size => {
                            if (item.computed - item.measured).abs() > f32::EPSILON {
                                let target_cross = if child.node.cross(store, layout_type).is_stretch() {
                                    child.cross
                                } else {
                                    parent_cross
                                };

                                if !child.has_layout_constraints
                                    || !same_f32(child.last_layout_main, item.computed)
                                    || !same_f32(child.last_layout_cross, target_cross)
                                {
                                    let child_size = layout(
                                        child.node,
                                        layout_type,
                                        item.computed,
                                        target_cross,
                                        cache,
                                        tree,
                                        store,
                                        sublayout,
                                    );

                                    child.cross = child_size.cross;
                                    item.measured = child_size.main;
                                    child.last_layout_main = item.computed;
                                    child.last_layout_cross = target_cross;
                                    child.has_layout_constraints = true;
                                }
                            }

                            child.main = item.computed;
                        }

                        ItemType::After => {
                            child.main_after = item.computed;
                        }
                    }

                    main_sum += (child.main + child.main_after) - previous_total;
                }
            }
        }
    }

    main_sum = children.iter().map(|child| child.main + child.main_after).sum();
    cross_max = children.iter().map(|child| child.cross).reduce(f32::max).unwrap_or_default();

    // Determine auto main and cross size from space and size of children.
    if num_parent_directed_children != 0 {
        if main.is_auto() || node.min_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_main = main_sum + padding_main_before + padding_main_after;
            } else {
                min_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if node.max_main(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && main_sum != 0.0 {
                max_main = main_sum + padding_main_before + padding_main_after;
            } else if cross_max != 0.0 {
                max_main = cross_max + padding_cross_before + padding_cross_after;
            }
        }

        if cross.is_auto() || node.min_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type {
                min_cross = cross_max + padding_cross_before + padding_cross_after;
            } else {
                min_cross = main_sum + padding_main_before + padding_main_after;
            }
        }

        if node.max_cross(store, parent_layout_type).is_auto() {
            if parent_layout_type == layout_type && cross_max != 0.0 {
                max_cross = cross_max + padding_cross_before + padding_cross_after;
            } else if main_sum != 0.0 {
                max_cross = main_sum + padding_main_before + padding_main_after;
            }
        }
    }

    clamp_with_aspect_ratio(
        parent_layout_type,
        aspect_ratio,
        main.is_auto(),
        cross.is_auto(),
        min_main,
        max_main,
        min_cross,
        max_cross,
        &mut computed_main,
        &mut computed_cross,
    );

    let (mut parent_main, mut parent_cross) = if parent_layout_type == layout_type {
        (computed_main, computed_cross)
    } else {
        (computed_cross, computed_main)
    };

    parent_main = parent_main - padding_main_before - padding_main_after;
    parent_cross = parent_cross - padding_cross_before - padding_cross_after;

    for child in children
        .iter_mut()
        .filter(|child| child.node.position_type(store).unwrap_or_default() == PositionType::Relative)
        .filter(|child| child.node.cross(store, layout_type).is_stretch())
    {
        let child_min_cross = if child.node.min_cross(store, layout_type).is_auto() {
            child.cross
        } else {
            child.node.min_cross(store, layout_type).to_px(parent_cross, DEFAULT_MIN)
        };

        let child_max_cross = child.node.max_cross(store, layout_type).to_px(parent_cross, DEFAULT_MAX);

        child.cross = parent_cross.clamp(child_min_cross, child_max_cross);
    }

    // Re-run relative children with their final resolved constraints so descendant
    // layout uses the same dimensions that are ultimately cached for each child.
    // Only rerun children that have descendants (skip leaf nodes).
    for child in children
        .iter_mut()
        .filter(|child| child.node.position_type(store).unwrap_or_default() == PositionType::Relative)
        .filter(|child| child.node.children(tree).next().is_some())
    {
        let child_main_is_stretch = child.node.main(store, layout_type).is_stretch();
        let child_cross_is_stretch = child.node.cross(store, layout_type).is_stretch();

        let target_main = if child_main_is_stretch { child.main } else { parent_main };
        let target_cross = if child_cross_is_stretch { child.cross } else { parent_cross };

        if child.has_layout_constraints
            && same_f32(child.last_layout_main, target_main)
            && same_f32(child.last_layout_cross, target_cross)
        {
            continue;
        }

        let child_size = layout(child.node, layout_type, target_main, target_cross, cache, tree, store, sublayout);

        child.last_layout_main = target_main;
        child.last_layout_cross = target_cross;
        child.has_layout_constraints = true;

        if !child_main_is_stretch {
            child.main = child_size.main;
        }

        child.cross = child_size.cross;
    }

    // Absolute Children

    // Absolute children are sized against the padding box (content box + padding, excluding border).
    let abs_size_main = parent_main + padding_main_before + padding_main_after;
    let abs_size_cross = parent_cross + padding_cross_before + padding_cross_after;

    // Compute space and size of non-flexible absolute children.
    for child in absolute_children.into_iter() {
        let main = if child.main(store, layout_type).is_stretch() {
            let child_min_main = child.min_main(store, layout_type).to_px(abs_size_main, DEFAULT_MIN);
            let child_max_main = child.max_main(store, layout_type).to_px(abs_size_main, DEFAULT_MAX);

            let child_main_before = child.main_before(store, layout_type).to_px(abs_size_main, 0.0);
            let child_main_after = child.main_after(store, layout_type).to_px(abs_size_main, 0.0);

            abs_size_main.clamp(child_min_main, child_max_main) - child_main_before - child_main_after
        } else {
            abs_size_main
        };

        let cross = if child.cross(store, layout_type).is_stretch() {
            let child_min_cross = child.min_cross(store, layout_type).to_px(abs_size_cross, DEFAULT_MIN);
            let child_max_cross = child.max_cross(store, layout_type).to_px(abs_size_cross, DEFAULT_MAX);

            let child_cross_before = child.cross_before(store, layout_type).to_px(abs_size_cross, 0.0);
            let child_cross_after = child.cross_after(store, layout_type).to_px(abs_size_cross, 0.0);

            abs_size_cross.clamp(child_min_cross, child_max_cross) - child_cross_before - child_cross_after
        } else {
            abs_size_cross
        };

        let child_size = layout(child, layout_type, main, cross, cache, tree, store, sublayout);

        let computed_child_main = child_size.main;
        let computed_child_cross = child_size.cross;

        children.push(ChildNode {
            node: child,
            cross: computed_child_cross,
            main: computed_child_main,
            main_after: 0.0,
            last_layout_main: 0.0,
            last_layout_cross: 0.0,
            has_layout_constraints: false,
        });
    }

    let mut alignment = node.alignment(store).unwrap_or_default();

    if matches!(layout_type, LayoutType::Row | LayoutType::Column)
        && node.direction(store).unwrap_or_default() == Direction::RightToLeft
    {
        alignment = flip_alignment_horizontal(alignment);
    }

    // Set size and position of children in the cache.
    let mut main_pos = padding_main_before;
    for child in children.iter() {
        let child_position = child.node.position_type(store).unwrap_or_default();

        match child_position {
            PositionType::Absolute => {
                // RTL mirrors horizontal offsets only.
                // In rows, horizontal is the main axis; in columns, horizontal is the cross axis.
                let (child_main_before, child_main_after) = if is_row_rtl {
                    (child.node.main_after(store, layout_type), child.node.main_before(store, layout_type))
                } else {
                    (child.node.main_before(store, layout_type), child.node.main_after(store, layout_type))
                };
                let (child_cross_before, child_cross_after) = if is_column_rtl {
                    (child.node.cross_after(store, layout_type), child.node.cross_before(store, layout_type))
                } else {
                    (child.node.cross_before(store, layout_type), child.node.cross_after(store, layout_type))
                };

                let parent_main = parent_main + padding_main_before + padding_main_after;
                let parent_cross = parent_cross + padding_cross_before + padding_cross_after;

                let child_main_pos =
                    absolute_axis_position(child_main_before, child_main_after, parent_main, child.main);

                let child_cross_pos =
                    absolute_axis_position(child_cross_before, child_cross_after, parent_cross, child.cross);

                cache.set_rect(child.node, layout_type, child_main_pos, child_cross_pos, child.main, child.cross);
            }

            PositionType::Relative => {
                let (mut child_main_pos, mut child_cross_pos) = match alignment {
                    Alignment::TopLeft => (0.0, 0.0),
                    Alignment::TopCenter => (0.0, 0.5),
                    Alignment::TopRight => (0.0, 1.0),
                    Alignment::Left => (0.5, 0.0),
                    Alignment::Center => (0.5, 0.5),
                    Alignment::Right => (0.5, 1.0),
                    Alignment::BottomLeft => (1.0, 0.0),
                    Alignment::BottomCenter => (1.0, 0.5),
                    Alignment::BottomRight => (1.0, 1.0),
                };

                if layout_type == LayoutType::Row {
                    std::mem::swap(&mut child_main_pos, &mut child_cross_pos);
                }

                child_main_pos *= parent_main - main_sum;
                child_cross_pos *= parent_cross - child.cross;

                cache.set_rect(
                    child.node,
                    layout_type,
                    main_pos + child_main_pos,
                    child_cross_pos + padding_cross_before,
                    child.main,
                    child.cross,
                );
                main_pos += child.main + child.main_after;
            }
        };
    }

    // Return the computed size, propagating it back up the tree.
    Size { main: computed_main, cross: computed_cross }
}