taffy 0.15.0

A flexible UI layout library
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
//! Computes the CSS block layout algorithm in the case that the block container being laid out contains only block-level boxes
use crate::geometry::{Line, Point, Rect, Size};
use crate::style::{
    AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AlignmentSafety, AvailableSpace,
    CoreStyle, LengthPercentageAuto, Overflow, Position,
};
use crate::style_helpers::TaffyMaxContent;
use crate::tree::{
    AxisStaticPosition, LayoutPartialTree, LayoutPartialTreeExt, NodeId, OofCandidate, OofCandidates,
    OofPositioningArea,
};
use crate::tree::{Baselines, CollapsibleMarginSet, Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
use crate::util::debug::debug_log;
use crate::util::sys::f32_max;
use crate::util::sys::Vec;
use crate::util::MaybeMath;
use crate::util::{MaybeResolve, ResolveOrZero};
use crate::{
    BlockContainerStyle, BlockItemStyle, BoxGenerationMode, BoxSizing, Contain, Dimension, Direction,
    LayoutBlockContainer, RequestedAxis, TextAlign,
};

#[cfg(feature = "float_layout")]
use super::float::{BfcSlot, ContentSlot, FloatContext, FloatIntrinsicWidthCalculator, FIT_TOLERANCE};
#[cfg(feature = "float_layout")]
use crate::{Clear, Float, FloatDirection};

/// Compute the block-axis offset that `align-content` applies to the in-flow content of a block
/// container, given the free space between the container's content box and its content.
///
/// The entire stack of in-flow content is treated as a single alignment subject, so the
/// distribution keywords (`space-*`, `stretch`) invoke their single-subject fallbacks. This is
/// used both by block layout and by inline formatting contexts (line boxes) which are laid out
/// externally to Taffy.
pub fn compute_block_align_content_offset(align_content: AlignContent, free_space: f32) -> f32 {
    let keyword = apply_alignment_fallback(free_space, 1, align_content);
    compute_alignment_offset(free_space, 1, 0.0, keyword, false, true)
}

/// Context for positioning Block and Float boxes within a Block Formatting Context
pub struct BlockFormattingContext {
    /// The float positioning context that handles positioning floats within this Block Formatting Context
    #[cfg(feature = "float_layout")]
    float_context: FloatContext,
}

impl Default for BlockFormattingContext {
    fn default() -> Self {
        Self {
            #[cfg(feature = "float_layout")]
            float_context: FloatContext::new(),
        }
    }
}

impl BlockFormattingContext {
    /// Create a new `BlockFormattingContext` with the specified width constraint
    pub fn new() -> Self {
        Default::default()
    }

    /// Create an initial `BlockContext` for this `BlockFormattingContext`
    pub fn root_block_context(&mut self) -> BlockContext<'_> {
        BlockContext {
            bfc: self,
            y_offset: 0.0,
            insets: [0.0, 0.0],
            content_box_insets: [0.0, 0.0],
            float_content_contribution: f32::NEG_INFINITY,
            is_root: true,
            #[cfg(feature = "float_layout")]
            adjoining_floats: [false, false],
            #[cfg(feature = "float_layout")]
            top_adjoining_floats: None,
        }
    }
}

/// Context for each individual Block within a Block Formatting Context
///
/// Contains a mutable reference to the BlockFormattingContext + block-specific data
pub struct BlockContext<'bfc> {
    /// A mutable reference to the root BlockFormatttingContext that this BlockContext belongs to
    bfc: &'bfc mut BlockFormattingContext,
    /// The y-offset of the border-top of the block node, relative to the to the border-top of the
    /// root node of the Block Formatting Context it belongs to.
    y_offset: f32,
    /// The x-inset of the border-box in from each side of the block node, relative to the root node of the Block Formatting Context it belongs to.
    insets: [f32; 2],
    /// The x-insets of the content box
    content_box_insets: [f32; 2],
    /// The height that floats take up in the element (`f32::NEG_INFINITY` if the element's
    /// subtree does not contain any floats)
    float_content_contribution: f32,
    /// Whether the node is the root of the Block Formatting Context is belongs to.
    is_root: bool,
    /// Whether a float has been placed (on each side) whose position adjoins the current
    /// margin-collapse strut of this block (i.e. whose final position can still be moved by
    /// margins that collapse into that strut). Such floats force clearance on cleared elements
    /// whose margins adjoin the same strut.
    #[cfg(feature = "float_layout")]
    adjoining_floats: [bool; 2],
    /// The value of `adjoining_floats` frozen at the first point at which in-flow content was
    /// committed within this block (resolving the position of the block's top margin strut).
    /// `None` if no in-flow content has been committed yet.
    #[cfg(feature = "float_layout")]
    top_adjoining_floats: Option<[bool; 2]>,
}

impl BlockContext<'_> {
    /// Create a sub-`BlockContext` for a child block node
    pub fn sub_context(&mut self, additional_y_offset: f32, insets: [f32; 2]) -> BlockContext<'_> {
        let insets = [self.insets[0] + insets[0], self.insets[1] + insets[1]];
        BlockContext {
            bfc: self.bfc,
            y_offset: self.y_offset + additional_y_offset,
            insets,
            content_box_insets: insets,
            float_content_contribution: f32::NEG_INFINITY,
            is_root: false,
            // Floats adjoining the parent's current strut also adjoin this block's top strut
            // (if this block's top margin collapses with its first child's, which is checked separately)
            #[cfg(feature = "float_layout")]
            adjoining_floats: self.adjoining_floats,
            #[cfg(feature = "float_layout")]
            top_adjoining_floats: None,
        }
    }

    /// Returns whether this block is the root block of it's Block Formatting Context
    pub fn is_bfc_root(&self) -> bool {
        self.is_root
    }
}

#[cfg(feature = "float_layout")]
impl BlockContext<'_> {
    /// Set the width of the overall Block Formatting Context. This is used to resolve positions
    /// that are relative to the right of the context such as right-floated boxes.
    ///
    /// Sub-blocks within a Block Formatting Context should use the `Self::sub_context` method to create
    /// a sub-`BlockContext` with `insets` instead.
    pub fn set_width(&mut self, available_width: f32) {
        self.bfc.float_context.set_width(available_width);
    }

    /// Set the x-axis content-box insets of the `BlockContext`. These are the difference between the border-box
    /// and the content-box of the box (padding + border + scrollbar_gutter).
    pub fn apply_content_box_inset(&mut self, content_box_x_insets: [f32; 2]) {
        self.content_box_insets[0] = self.insets[0] + content_box_x_insets[0];
        self.content_box_insets[1] = self.insets[1] + content_box_x_insets[1];
    }

    /// Whether the float context contains any floats
    #[inline(always)]
    pub fn has_floats(&self) -> bool {
        self.bfc.float_context.has_floats()
    }

    /// Whether the float context contains any floats that extend to or below min_y
    #[inline(always)]
    pub fn has_active_floats(&self, min_y: f32) -> bool {
        self.bfc.float_context.has_active_floats(min_y + self.y_offset)
    }

    /// Position a floated box with the context
    pub fn place_floated_box(
        &mut self,
        floated_box: Size<f32>,
        min_y: f32,
        direction: FloatDirection,
        clear: Clear,
        adjoins_unresolved_strut: bool,
    ) -> Point<f32> {
        if adjoins_unresolved_strut {
            self.adjoining_floats[direction as usize] = true;
        }
        let mut pos = self.bfc.float_context.place_floated_box(
            floated_box,
            min_y + self.y_offset,
            self.content_box_insets,
            direction,
            clear,
        );
        pos.y -= self.y_offset;
        pos.x -= self.insets[0];

        self.float_content_contribution = self.float_content_contribution.max(pos.y + floated_box.height);

        pos
    }

    /// Search a space suitable for laying out non-floated content into
    pub fn find_content_slot(&self, min_y: f32, clear: Clear, after: Option<usize>) -> ContentSlot {
        let mut slot =
            self.bfc.float_context.find_content_slot(min_y + self.y_offset, self.content_box_insets, clear, after);
        slot.y -= self.y_offset;
        slot.x -= self.insets[0];
        slot
    }

    /// Search for a space suitable for laying out a box that establishes an independent
    /// formatting context (whose border box must not overlap floats)
    pub fn find_bfc_slot(
        &self,
        min_y: f32,
        margins: [f32; 2],
        direction: Direction,
        clear: Clear,
        after: Option<usize>,
    ) -> BfcSlot {
        let mut slot = self.bfc.float_context.find_bfc_slot(
            min_y + self.y_offset,
            self.content_box_insets,
            margins,
            direction,
            clear,
            after,
        );
        slot.y -= self.y_offset;
        slot.x -= self.insets[0];
        slot
    }

    /// Get the bottom of lowest relevant float for the specific clear property
    pub fn cleared_threshold(&self, clear: Clear) -> Option<f32> {
        self.bfc.float_context.cleared_threshold(clear).map(|threshold| threshold - self.y_offset)
    }

    /// Whether a float that is adjoining the current margin-collapse strut has been placed
    /// on the side(s) relevant to the passed clear property
    pub fn has_adjoining_float(&self, clear: Clear) -> bool {
        match clear {
            Clear::Left => self.adjoining_floats[0],
            Clear::Right => self.adjoining_floats[1],
            Clear::Both => self.adjoining_floats[0] || self.adjoining_floats[1],
            Clear::None => false,
        }
    }

    /// Merge adjoining float flags propagated from a child block into this block's flags
    fn merge_adjoining_floats(&mut self, flags: [bool; 2]) {
        self.adjoining_floats[0] |= flags[0];
        self.adjoining_floats[1] |= flags[1];
    }

    /// Record that in-flow content has been committed within this block, resolving the position of
    /// the current margin-collapse strut. Floats placed before this point no longer adjoin the
    /// current strut. The flags for the block's top strut are frozen at the first commit.
    fn commit_strut(&mut self) {
        if self.top_adjoining_floats.is_none() {
            self.top_adjoining_floats = Some(self.adjoining_floats);
        }
        self.adjoining_floats = [false, false];
    }

    /// The adjoining float flags for this block's top margin strut: floats placed while the
    /// position of the block's top strut was still unresolved
    fn top_adjoining_floats(&self) -> [bool; 2] {
        self.top_adjoining_floats.unwrap_or(self.adjoining_floats)
    }

    /// Update the height that descendent floats consume with the height that floats consume
    /// within a particular child (`child_contribution` is relative to this block's border-top)
    pub fn add_child_floated_content_height_contribution(&mut self, child_contribution: f32) {
        self.float_content_contribution = self.float_content_contribution.max(child_contribution);
    }

    /// Returns the height that descendent floats consume
    pub fn floated_content_height_contribution(&self) -> f32 {
        self.float_content_contribution
    }
}

#[cfg(not(feature = "float_layout"))]
impl BlockContext<'_> {
    #[inline(always)]
    /// Returns the height that descendent floats consume (always 0.0 when the float feature is disabled)
    fn float_content_contribution(&self) -> f32 {
        0.0
    }
}

use super::common::alignment::{apply_alignment_fallback, compute_alignment_offset};
#[cfg(feature = "content_size")]
use super::common::scrollable_overflow::compute_scrollable_overflow_contribution;
use super::common::sizing_keyword::{resolve_sizing_keyword, SizingKeywordResolution};

/// Per-child data that is accumulated and modified over the course of the layout algorithm
struct BlockItem {
    /// The identifier for the associated node
    node_id: NodeId,

    /// The "source order" of the item. This is the index of the item within the children iterator,
    /// and controls the order in which the nodes are placed
    order: u32,

    /// Items that are tables don't have stretch sizing applied to them
    is_table: bool,

    /// Compressible replaced items resolve an auto width to their intrinsic size rather than
    /// being stretch-sized <https://www.w3.org/TR/CSS22/visudet.html#block-replaced-width>
    is_compressible_replaced: bool,

    /// Whether the child is a non-independent block or inline node
    is_in_same_bfc: bool,

    #[cfg(feature = "float_layout")]
    /// The `float` style of the node
    float: Float,
    #[cfg(feature = "float_layout")]
    /// The `clear` style of the node
    clear: Clear,

    /// The size style of this item. Used to detect and resolve sizing keywords
    /// (`min-content`, `max-content`, `fit-content`, `fit-content(...)`, and `stretch`).
    /// In the height (block) axis only `stretch` requires resolution: the intrinsic sizing
    /// keywords are all equal to the content size, which is what an auto height already
    /// resolves to.
    size_style: Size<Dimension>,

    /// The base size of this item
    size: Size<Option<f32>>,
    /// The minimum allowable size of this item
    min_size: Size<Option<f32>>,
    /// The maximum allowable size of this item
    max_size: Size<Option<f32>>,

    /// The overflow style of the item
    overflow: Point<Overflow>,
    /// The contain style of the item
    contain: Contain,
    /// The width of the item's scrollbars (if it has scrollbars)
    scrollbar_width: f32,

    /// The position style of the item
    position: Position,
    /// The `direction` style of the item (used to resolve `self-start`/`self-end`)
    direction: Direction,
    /// The `align-self` style of the item (used to derive the static position of out-of-flow items)
    align_self: Option<AlignSelf>,
    /// The `justify-self` style of the item (used to align in-flow items and to derive the static position of
    /// out-of-flow items)
    justify_self: Option<AlignSelf>,
    /// The final offset of this item
    inset: Rect<LengthPercentageAuto>,
    /// The margin of this item
    margin: Rect<LengthPercentageAuto>,
    /// The margin of this item
    padding: Rect<f32>,
    /// The margin of this item
    border: Rect<f32>,
    /// The sum of padding and border for this item
    padding_border_sum: Size<f32>,

    /// The computed border box size of this item
    computed_size: Size<f32>,
    /// The computed "static position" of this item. The static position is the position
    /// taking into account padding, border, margins, and scrollbar_gutters but not inset
    static_position: Point<f32>,
    /// Whether margins can be collapsed through this item
    can_be_collapsed_through: bool,

    /// Pending layout for in-flow non-floated items. Held back from `set_unrounded_layout` so the
    /// post-loop `align-content` pass in `compute_inner` can shift `location.y` before commit.
    final_layout: Option<Layout>,

    /// Out-of-flow candidates bubbled out of this (in-flow) item's subtree. Anchors are relative
    /// to the item's border box until they are translated at merge time.
    oof_candidates: OofCandidates,
}

/// Computes the layout of [`LayoutPartialTree`] according to the block layout algorithm
pub fn compute_block_layout(
    tree: &mut impl LayoutBlockContainer,
    node_id: NodeId,
    inputs: LayoutInput,
    block_ctx: Option<&mut BlockContext<'_>>,
) -> LayoutOutput {
    let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
    let style = tree.get_block_container_style(node_id);

    // Pull these out earlier to avoid borrowing issues
    let overflow = style.overflow();
    let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
    let contain = style.contain();
    // css-align-3 §5.1.1: a non-`normal` `align-content` makes a block container establish an
    // independent formatting context. <https://drafts.csswg.org/css-align-3/#distribution-block>
    // Layout and paint containment also establish an independent formatting context.
    // <https://drafts.csswg.org/css-contain-2/#containment-layout>
    let establishes_new_bfc = is_scroll_container
        || style.align_content().keyword != AlignContentKeyword::Normal
        || contain.establishes_independent_formatting_context();
    let aspect_ratio = style.aspect_ratio();
    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
    let padding_border_size = (padding + border).sum_axes();
    let box_sizing_adjustment =
        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };

    let min_size = style
        .min_size()
        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
        .maybe_apply_aspect_ratio(aspect_ratio)
        .maybe_add(box_sizing_adjustment);
    let max_size = style
        .max_size()
        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
        .maybe_apply_aspect_ratio(aspect_ratio)
        .maybe_add(box_sizing_adjustment);
    let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
        style
            .size()
            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
            .maybe_apply_aspect_ratio(aspect_ratio)
            .maybe_add(box_sizing_adjustment)
            .maybe_clamp(min_size, max_size)
    } else {
        Size::NONE
    };

    drop(style);

    // If both min and max in a given axis are set and max <= min then this determines the size in that axis
    let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
        (Some(min), Some(max)) if max <= min => Some(min),
        _ => None,
    });

    let styled_based_known_dimensions =
        known_dimensions.or(min_max_definite_size).or(clamped_style_size).maybe_max(padding_border_size);

    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
    // is ComputeSize (and thus the container's size is all that we're interested in)
    if run_mode == RunMode::ComputeSize {
        if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
            return LayoutOutput::from_outer_size(Size { width, height });
        }

        // We can also short-circuit if the width is known and only the width has been requested.
        if inputs.axis == RequestedAxis::Horizontal {
            if let Some(width) = styled_based_known_dimensions.width {
                return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
            }
        }
    }

    // Unwrap the block formatting context if one was passed, or else create a new one
    debug_log!("BLOCK");
    let mut output = match block_ctx {
        Some(inherited_bfc) if !establishes_new_bfc => compute_inner(
            tree,
            node_id,
            LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
            inherited_bfc,
        ),
        _ => {
            let mut root_bfc = BlockFormattingContext::new();
            let mut root_ctx = root_bfc.root_block_context();
            compute_inner(
                tree,
                node_id,
                LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs },
                &mut root_ctx,
            )
        }
    };

    // Layout containment suppresses the box's baseline for baseline-alignment purposes
    if contain.suppresses_baseline() {
        output.baselines = Baselines::NONE;
    }

    output
}

/// Computes the layout of [`LayoutBlockContainer`] according to the block layout algorithm
fn compute_inner(
    tree: &mut impl LayoutBlockContainer,
    node_id: NodeId,
    inputs: LayoutInput,
    #[allow(unused_mut)] mut block_ctx: &mut BlockContext<'_>,
) -> LayoutOutput {
    let LayoutInput {
        known_dimensions, parent_size, available_space, run_mode, vertical_margins_are_collapsible, ..
    } = inputs;

    let style = tree.get_block_container_style(node_id);
    let raw_padding = style.padding();
    let raw_border = style.border();
    let raw_margin = style.margin();
    let aspect_ratio = style.aspect_ratio();
    let padding = raw_padding.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
    let border = raw_border.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
    let direction = style.direction();

    // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
    // However, the axis are switched (transposed) because a node that scrolls vertically needs
    // *horizontal* space to be reserved for a scrollbar
    let scrollbar_gutter = {
        let offsets = style.overflow().transpose().map(|overflow| match overflow {
            Overflow::Scroll => style.scrollbar_width(),
            _ => 0.0,
        });
        match direction {
            Direction::Ltr => Rect { top: 0.0, left: 0.0, right: offsets.x, bottom: offsets.y },
            Direction::Rtl => Rect { top: 0.0, left: offsets.x, right: 0.0, bottom: offsets.y },
        }
    };
    let padding_border = padding + border;
    let padding_border_size = padding_border.sum_axes();
    let content_box_inset = padding_border + scrollbar_gutter;

    // Apply content box inset
    #[cfg(feature = "float_layout")]
    block_ctx.apply_content_box_inset([content_box_inset.left, content_box_inset.right]);

    let box_sizing_adjustment =
        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
    let size = style
        .size()
        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
        .maybe_apply_aspect_ratio(aspect_ratio)
        .maybe_add(box_sizing_adjustment);
    let min_size = style
        .min_size()
        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
        .maybe_apply_aspect_ratio(aspect_ratio)
        .maybe_add(box_sizing_adjustment);
    let max_size = style
        .max_size()
        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
        .maybe_apply_aspect_ratio(aspect_ratio)
        .maybe_add(box_sizing_adjustment);

    // css-sizing-4: a definite size in one axis transfers through `aspect-ratio`
    // to make the other definite. Deriving it from `known_dimensions` self-gates
    // the transfer — a block parent fills an axis only when it's a real
    // constraint (e.g. the stretched width at final layout) and leaves it None
    // while probing intrinsic sizes, so measure passes stay content-based. Only a
    // newly-filled axis is adopted (and clamped); an incoming known size is left
    // as the parent resolved it (re-clamping would undo padding/border overrides).
    let known_dimensions = {
        let derived = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
        Size { width: known_dimensions.width.or(derived.width), height: known_dimensions.height.or(derived.height) }
    };
    let percentage_basis_dimensions = Size {
        width: known_dimensions.width,
        height: known_dimensions.height.filter(|_| inputs.known_dimensions_are_definite.height),
    };
    let container_content_box_size = percentage_basis_dimensions.maybe_sub(content_box_inset.sum_axes());

    let overflow = style.overflow();
    let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
    let establishes_new_bfc = is_scroll_container
        || style.align_content().keyword != AlignContentKeyword::Normal
        || style.contain().establishes_independent_formatting_context();

    // Determine margin collapsing behaviour
    //
    // Whether a child's margins could collapse through each of this box's block-axis edges: the
    // box does not establish a new BFC and has neither border nor padding on that side.
    let children_margins_adjoin_own_edges = Line {
        start: vertical_margins_are_collapsible.start
            && !establishes_new_bfc
            && !style.position().is_out_of_flow()
            && padding.top == 0.0
            && border.top == 0.0,
        end: vertical_margins_are_collapsible.end
            && !establishes_new_bfc
            && !style.position().is_out_of_flow()
            && padding.bottom == 0.0
            && border.bottom == 0.0,
    };
    let own_margins_collapse_with_children = Line {
        start: children_margins_adjoin_own_edges.start,
        end: children_margins_adjoin_own_edges.end && size.height.is_none(),
    };
    let has_styles_preventing_being_collapsed_through = !style.is_block()
        || block_ctx.is_bfc_root()
        || establishes_new_bfc
        || style.position().is_out_of_flow()
        || padding.top > 0.0
        || padding.bottom > 0.0
        || border.top > 0.0
        || border.bottom > 0.0;

    let text_align = style.text_align();
    let align_content = style.align_content();
    let justify_items = style.justify_items();
    drop(style);

    // 1. Generate items
    let mut items = generate_item_list(tree, node_id, container_content_box_size);

    // 2. Compute container width
    let container_outer_width = known_dimensions.width.unwrap_or_else(|| {
        let available_width = available_space.width.maybe_sub(content_box_inset.horizontal_axis_sum());
        let intrinsic_width = determine_content_based_container_width(tree, &items, available_width)
            + content_box_inset.horizontal_axis_sum();
        intrinsic_width.maybe_clamp(min_size.width, max_size.width).maybe_max(Some(padding_border_size.width))
    });

    // Short-circuit if computing size and both dimensions known
    if let (RunMode::ComputeSize, Some(container_outer_height)) = (run_mode, known_dimensions.height) {
        return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: container_outer_height });
    }

    // We can also short-circuit if the width is known and only the width has been requested.
    if run_mode == RunMode::ComputeSize && inputs.axis == RequestedAxis::Horizontal {
        return LayoutOutput::from_outer_size(Size { width: container_outer_width, height: 0.0 });
    }

    // Under `SizingMode::ContentSize` the container's own `height`/`min-height` are ignored,
    // so they cannot serve as the percentage basis for children either
    // (https://drafts.csswg.org/css-flexbox/#min-size-auto: the content size suggestion
    // must not be influenced by the item's specified height).
    let container_percentage_resolution_height = percentage_basis_dimensions
        .height
        .or(if inputs.sizing_mode == SizingMode::InherentSize { size.height.maybe_max(min_size.height) } else { None });

    // 3. Perform final item layout and return content height
    //
    // Percentage padding and borders resolve against the *containing block's* width
    // (`parent_size`), not the box's own width. These only differ when the box has a
    // non-stretch width. Fall back to the box's own width when the parent size is
    // unknown (e.g. at the root of the layout tree).
    let percentage_resolution_width = parent_size.width.unwrap_or(container_outer_width);
    let resolved_padding =
        raw_padding.resolve_or_zero(Some(percentage_resolution_width), |val, basis| tree.calc(val, basis));
    let resolved_border =
        raw_border.resolve_or_zero(Some(percentage_resolution_width), |val, basis| tree.calc(val, basis));
    let resolved_content_box_inset = resolved_padding + resolved_border + scrollbar_gutter;
    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
    let (
        mut inflow_overflow_rect,
        mut intrinsic_outer_height,
        first_child_top_margin_set,
        last_child_bottom_margin_set,
        mut first_baseline,
    ) = perform_final_layout_on_in_flow_children(
        tree,
        run_mode,
        &mut items,
        container_outer_width,
        container_percentage_resolution_height,
        content_box_inset,
        resolved_content_box_inset,
        resolved_border,
        text_align,
        justify_items,
        direction,
        own_margins_collapse_with_children,
        children_margins_adjoin_own_edges,
        #[cfg(feature = "content_size")]
        is_scroll_container,
        block_ctx,
    );

    // Root BFCs contain floats
    #[cfg(feature = "float_layout")]
    if block_ctx.is_bfc_root() || establishes_new_bfc {
        intrinsic_outer_height = intrinsic_outer_height.max(block_ctx.floated_content_height_contribution());
    }

    let container_outer_height = known_dimensions
        .height
        .unwrap_or(intrinsic_outer_height.maybe_clamp(min_size.height, max_size.height))
        .maybe_max(Some(padding_border_size.height));
    let final_outer_size = Size { width: container_outer_width, height: container_outer_height };

    // CSS2 §8.3.1: the bottom margin of a block with `height: auto` collapses with its last
    // in-flow child's bottom margin only if the box's `min-height` is less than the box's
    // used height. When `min-height` determines the used height, the last child's bottom
    // margin no longer adjoins the box's bottom edge, so it stays inside the box instead of
    // collapsing with the box's own bottom margin. (`max-height` has no such effect.)
    let height_constrained_by_min_height = matches!(min_size.height, Some(h) if h > 0.0 && h >= container_outer_height);
    let own_bottom_margin_collapses_with_children =
        own_margins_collapse_with_children.end && !height_constrained_by_min_height;

    // Apply `align-content` to in-flow non-floated items if requested. The per-item layouts were
    // held back in `item.final_layout` so that this step can shift `location.y` before tree commit.
    //
    // For block layout the entire stack of in-flow children is treated as a single alignment
    // subject. That means distribution keywords (`space-between`, `space-around`,
    // `space-evenly`, `stretch`) must invoke the single-subject fallback unconditionally —
    // which is what passing `num_items = 1` to `apply_alignment_fallback` does. The whole
    // group then shifts by one offset, with zero inter-item gap.
    if align_content.keyword != AlignContentKeyword::Normal {
        let container_inner_height = container_outer_height - resolved_content_box_inset.vertical_axis_sum();
        let inflow_content_height = intrinsic_outer_height - resolved_content_box_inset.vertical_axis_sum();
        let free_space = container_inner_height - inflow_content_height;
        let group_offset = compute_block_align_content_offset(align_content, free_space);
        first_baseline = first_baseline.map(|baseline| baseline + group_offset);
        for item in items.iter_mut() {
            if let Some(layout) = item.final_layout.as_mut() {
                layout.location.y += group_offset;
            }
            // The static positions of out-of-flow children move with the in-flow content
            if item.position.is_out_of_flow() {
                item.static_position.y += group_offset;
            }
        }
        let any_in_flow = items.iter().any(|item| item.final_layout.is_some());
        if any_in_flow {
            #[cfg(feature = "content_size")]
            {
                inflow_overflow_rect = Rect::ZERO;
                for item in items.iter() {
                    if let Some(layout) = item.final_layout.as_ref() {
                        let contribution_location = if direction.is_rtl() {
                            Point {
                                x: container_outer_width
                                    - (layout.location.x + layout.size.width)
                                    - resolved_border.right,
                                y: layout.location.y - resolved_border.top,
                            }
                        } else {
                            Point {
                                x: layout.location.x - resolved_border.left,
                                y: layout.location.y - resolved_border.top,
                            }
                        };
                        inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
                            contribution_location,
                            layout.size,
                            layout.scrollable_overflow_rect,
                            item.overflow,
                            item.contain,
                            is_scroll_container,
                        ));
                    }
                }
            }
        }
    }

    // Determine whether this node can be collapsed through
    let all_in_flow_children_can_be_collapsed_through = items.iter().all(|item| {
        #[cfg(feature = "float_layout")]
        if item.float.is_floated() {
            return true;
        }
        item.position.is_out_of_flow() || item.can_be_collapsed_through
    });
    // CSS2 §8.3.1: a box's top and bottom margins collapse through it only if its *used* height
    // is zero, so `height`/`min-height`/`max-height` are judged by the height they resolve to
    // (e.g. `height: 1px; max-height: 0` collapses, `min-height: 1%` under an auto-height
    // parent collapses) rather than by their computed values.
    let can_be_collapsed_through = !has_styles_preventing_being_collapsed_through
        && container_outer_height == 0.0
        && all_in_flow_children_can_be_collapsed_through;

    let mut output = LayoutOutput {
        size: final_outer_size,
        #[cfg(feature = "content_size")]
        scrollable_overflow_rect: Rect::ZERO,
        baselines: Baselines::from_first(first_baseline),
        top_margin: if own_margins_collapse_with_children.start {
            first_child_top_margin_set
        } else {
            let margin_top = raw_margin.top.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
            CollapsibleMarginSet::from_margin(margin_top)
        },
        bottom_margin: if own_bottom_margin_collapses_with_children {
            last_child_bottom_margin_set
        } else {
            let margin_bottom =
                raw_margin.bottom.resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
            CollapsibleMarginSet::from_margin(margin_bottom)
        },
        margins_can_collapse_through: can_be_collapsed_through,
        oof_candidates: OofCandidates::NONE,
        oof_positioning_area: None,
    };

    // Short-circuit if computing size.
    //
    // Note: it is important that we return the margin-collapsing related outputs here as Parent block containers
    // rely on the `top_margin`/`bottom_margin` of their children to compute their own intrinsic height.
    if run_mode == RunMode::ComputeSize {
        return output;
    }

    // Commit deferred child layouts to the tree.
    for item in items.iter() {
        if let Some(layout) = item.final_layout.as_ref() {
            tree.set_unrounded_layout(item.node_id, layout);
        }
    }

    // 4. Collect out-of-flow candidates in document order (direct out-of-flow children plus
    // candidates bubbled from in-flow children's subtrees). These are laid out by the
    // out-of-flow positioning pass (`compute_oof_layout`), which runs after this algorithm.
    let mut candidates = OofCandidates::new();
    for item in items.iter_mut() {
        if item.position.is_out_of_flow() {
            // The static-position rectangle of an out-of-flow child of a block container spans
            // the container's content box in the inline axis, and is a zero-height line at the
            // child's hypothetical position in the block axis. The child's self-alignment
            // properties determine how it is aligned within that rectangle.
            // <https://www.w3.org/TR/css-position-3/#staticpos-rect>
            let inline_area = Line {
                start: resolved_content_box_inset.left,
                end: container_outer_width - resolved_content_box_inset.right,
            };
            let block_area = Line { start: item.static_position.y, end: item.static_position.y };
            // A `justify_self` of `None` takes the container's `justify-items`. Block containers have
            // no `align-items`, so an `align_self` of `None` behaves as `normal`.
            let justify_self =
                item.justify_self.unwrap_or(justify_items).resolve_self_relative(item.direction, direction, true);
            let align_self =
                item.align_self.unwrap_or(AlignItems::NORMAL).resolve_self_relative(item.direction, direction, false);
            candidates.push(OofCandidate {
                node: item.node_id,
                order: item.order,
                position: item.position,
                static_position: Point {
                    x: AxisStaticPosition::from_alignment(justify_self, inline_area, direction.is_rtl()),
                    y: AxisStaticPosition::from_alignment(align_self, block_area, false),
                },
            });
        } else if !item.oof_candidates.is_empty() {
            // Translate anchors from item-relative to container-relative coordinates
            if let Some(layout) = item.final_layout.as_ref() {
                item.oof_candidates.translate(layout.location);
            }
            candidates.append(&mut item.oof_candidates);
        }
    }

    let absolute_position_inset = resolved_border + scrollbar_gutter;
    let absolute_position_area = final_outer_size - absolute_position_inset.sum_axes();
    let absolute_position_offset = Point { x: absolute_position_inset.left, y: absolute_position_inset.top };
    output.oof_candidates = candidates;
    output.oof_positioning_area =
        Some(OofPositioningArea { size: absolute_position_area, offset: absolute_position_offset });

    #[cfg(feature = "content_size")]
    {
        // A scroll container's own padding at the end of the content is part of its scrollable
        // overflow region, so it is included in the in-flow overflow rect. Boxes that are not
        // scroll containers do not extend their overflow region by their own padding.
        if is_scroll_container {
            inflow_overflow_rect.right +=
                if direction.is_rtl() { resolved_padding.left } else { resolved_padding.right };
            inflow_overflow_rect.bottom += resolved_padding.bottom;
        }
        output.scrollable_overflow_rect = inflow_overflow_rect;
    }

    // 5. Perform hidden layout on hidden children
    let len = tree.child_count(node_id);
    for order in 0..len {
        let child = tree.get_child_id(node_id, order);
        let child_style = tree.get_block_child_style(child);
        if child_style.box_generation_mode() == BoxGenerationMode::None {
            drop(child_style);
            tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
            tree.perform_child_layout(
                child,
                Size::NONE,
                Size::NONE,
                Size::MAX_CONTENT,
                SizingMode::InherentSize,
                Line::FALSE,
            );
        }
    }

    output
}

/// Create a `Vec` of `BlockItem` structs where each item in the `Vec` represents a child of the current node
#[inline]
fn generate_item_list(
    tree: &impl LayoutBlockContainer,
    node: NodeId,
    node_inner_size: Size<Option<f32>>,
) -> Vec<BlockItem> {
    tree.child_ids(node)
        .map(|child_node_id| (child_node_id, tree.get_block_child_style(child_node_id)))
        .filter(|(_, style)| style.box_generation_mode() != BoxGenerationMode::None)
        .enumerate()
        .map(|(order, (child_node_id, child_style))| {
            let aspect_ratio = child_style.aspect_ratio();
            let padding =
                child_style.padding().resolve_or_zero(node_inner_size.width, |val, basis| tree.calc(val, basis));
            let border =
                child_style.border().resolve_or_zero(node_inner_size.width, |val, basis| tree.calc(val, basis));
            let pb_sum = (padding + border).sum_axes();
            let box_sizing_adjustment =
                if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };

            let position = child_style.position();
            let overflow = child_style.overflow();

            #[cfg(feature = "float_layout")]
            let float = child_style.float();
            #[cfg(feature = "float_layout")]
            let is_not_floated = float == Float::None;

            #[cfg(not(feature = "float_layout"))]
            let is_not_floated = true;

            let is_block = child_style.is_block();
            let is_table = child_style.is_table();
            let is_compressible_replaced = child_style.is_compressible_replaced();
            let is_scroll_container = overflow.x.is_scroll_container() || overflow.y.is_scroll_container();
            let contain = child_style.contain();

            let is_in_same_bfc: bool = is_block
                && !is_table
                && !position.is_out_of_flow()
                && is_not_floated
                && !is_scroll_container
                && !contain.establishes_independent_formatting_context()
                && child_style.align_content().keyword == AlignContentKeyword::Normal;

            BlockItem {
                node_id: child_node_id,
                order: order as u32,
                is_table,
                is_compressible_replaced,
                is_in_same_bfc,
                #[cfg(feature = "float_layout")]
                float,
                #[cfg(feature = "float_layout")]
                clear: child_style.clear(),
                size_style: child_style.size(),
                size: child_style
                    .size()
                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
                    .maybe_apply_aspect_ratio(aspect_ratio)
                    .maybe_add(box_sizing_adjustment),
                min_size: child_style
                    .min_size()
                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
                    .maybe_apply_aspect_ratio(aspect_ratio)
                    .maybe_add(box_sizing_adjustment),
                max_size: child_style
                    .max_size()
                    .maybe_resolve(node_inner_size, |val, basis| tree.calc(val, basis))
                    .maybe_apply_aspect_ratio(aspect_ratio)
                    .maybe_add(box_sizing_adjustment),
                overflow,
                contain,
                scrollbar_width: child_style.scrollbar_width(),
                position,
                direction: child_style.direction(),
                align_self: child_style.align_self(),
                justify_self: child_style.justify_self(),
                inset: child_style.inset(),
                margin: child_style.margin(),
                padding,
                border,
                padding_border_sum: pb_sum,

                // Fields to be computed later (for now we initialise with dummy values)
                computed_size: Size::zero(),
                static_position: Point::zero(),
                can_be_collapsed_through: false,
                final_layout: None,
                oof_candidates: OofCandidates::new(),
            }
        })
        .collect()
}

/// Resolve the `stretch` sizing keyword for an item's height style. In the block axis the
/// intrinsic sizing keywords (`min-content`, `max-content`, `fit-content`, `fit-content(...)`)
/// are all equal to the content size, which is what an auto height already resolves to, so
/// only `stretch` requires explicit resolution.
///
/// Each of the item's block-axis margins is subtracted from the stretch size unless it is
/// flagged in `margins_treated_as_zero`: when stretching a block-level box, a margin that
/// could collapse through the corresponding edge of the containing block (which has neither
/// border nor padding on that side and does not establish a new BFC) is treated as zero.
/// <https://github.com/w3c/csswg-drafts/issues/11044#issuecomment-2599101601>
/// <https://github.com/w3c/csswg-drafts/issues/13260>
#[inline]
fn resolve_stretch_height(
    height_style: Dimension,
    container_inner_height: Option<f32>,
    item_margin: Rect<f32>,
    margins_treated_as_zero: Line<bool>,
) -> Option<f32> {
    if !height_style.is_stretch() {
        return None;
    }
    let mut height = container_inner_height?;
    if !margins_treated_as_zero.start {
        height -= item_margin.top;
    }
    if !margins_treated_as_zero.end {
        height -= item_margin.bottom;
    }
    Some(height)
}

/// Compute the content-based width in the case that the width of the container is not known
#[inline]
fn determine_content_based_container_width(
    tree: &mut impl LayoutPartialTree,
    items: &[BlockItem],
    available_width: AvailableSpace,
) -> f32 {
    let available_space = Size { width: available_width, height: AvailableSpace::MinContent };

    let mut max_child_width = 0.0;
    #[cfg(feature = "float_layout")]
    let mut float_contribution = FloatIntrinsicWidthCalculator::new(available_width);
    for item in items.iter().filter(|item| !item.position.is_out_of_flow()) {
        let known_dimensions = item.size.maybe_clamp(item.min_size, item.max_size);

        let item_x_margin_sum = item
            .margin
            .resolve_or_zero(available_space.width.into_option(), |val, basis| tree.calc(val, basis))
            .horizontal_axis_sum();
        let width = known_dimensions.width.unwrap_or_else(|| {
            let item_available_width =
                match resolve_sizing_keyword(item.size_style.width, None, None, |val, basis| tree.calc(val, basis)) {
                    Some(SizingKeywordResolution::Measure(available_width)) => available_width,
                    Some(SizingKeywordResolution::Exact(width)) => AvailableSpace::Definite(width),
                    None => available_space.width.maybe_sub(item_x_margin_sum),
                };
            tree.measure_child_size(
                item.node_id,
                known_dimensions,
                Size::NONE,
                Size { width: item_available_width, height: available_space.height },
                SizingMode::InherentSize,
                crate::AbsoluteAxis::Horizontal,
                // Must match the value passed when laying the item out (see `Cache`)
                if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
            )
        });

        let width = f32_max(width, item.padding_border_sum.width) + item_x_margin_sum;

        #[cfg(feature = "float_layout")]
        if let Some(direction) = item.float.float_direction() {
            float_contribution.add_float(width, direction, item.clear);
            continue;
        }

        max_child_width = f32_max(max_child_width, width);
    }

    #[cfg(feature = "float_layout")]
    {
        max_child_width = max_child_width.max(float_contribution.result());
    }

    max_child_width
}

/// Compute each child's final size and position
#[inline]
#[allow(clippy::too_many_arguments)]
fn perform_final_layout_on_in_flow_children(
    tree: &mut impl LayoutBlockContainer,
    run_mode: RunMode,
    items: &mut [BlockItem],
    container_outer_width: f32,
    container_percentage_resolution_height: Option<f32>,
    content_box_inset: Rect<f32>,
    resolved_content_box_inset: Rect<f32>,
    resolved_border: Rect<f32>,
    text_align: TextAlign,
    justify_items: AlignItems,
    direction: Direction,
    own_margins_collapse_with_children: Line<bool>,
    children_margins_adjoin_own_edges: Line<bool>,
    #[cfg(feature = "content_size")] is_scroll_container: bool,
    block_ctx: &mut BlockContext<'_>,
) -> (Rect<f32>, f32, CollapsibleMarginSet, CollapsibleMarginSet, Option<f32>) {
    // Resolve container_inner_width for sizing child nodes using initial content_box_inset
    let container_inner_width = (container_outer_width - resolved_content_box_inset.horizontal_axis_sum()).max(0.0);
    let container_percentage_resolution_height =
        container_percentage_resolution_height.maybe_sub(resolved_content_box_inset.vertical_axis_sum());
    let parent_size = Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
    // Vertical available space in block flow is indefinite, NOT a min-content
    // constraint: MaxContent is taffy's representation of "indefinite".
    // Passing MinContent here made every descendant grid believe it was being
    // sized under a min-content constraint, in which the maximize-tracks step
    // has zero free space — so auto rows containing only scroll-container
    // items (overflow != visible, automatic minimum size = 0) collapsed to
    // zero height. Browsers size such rows to the item's content.
    let available_space =
        Size { width: AvailableSpace::Definite(container_inner_width), height: AvailableSpace::MaxContent };

    // TODO: handle nested blocks with different widths
    #[cfg(feature = "float_layout")]
    if block_ctx.is_bfc_root() {
        block_ctx.set_width(container_outer_width);
        block_ctx.apply_content_box_inset([resolved_content_box_inset.left, resolved_content_box_inset.right]);
    }

    // If this block's top margin does not collapse with its children's then the position of its
    // top margin strut is resolved relative to it, and floats adjoining ancestor struts do not
    // adjoin this block's strut.
    #[cfg(feature = "float_layout")]
    if !own_margins_collapse_with_children.start {
        block_ctx.commit_strut();
    }

    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
    let mut inflow_overflow_rect = Rect::ZERO;
    let mut committed_y_offset = resolved_content_box_inset.top;
    let mut y_offset_for_absolute = resolved_content_box_inset.top;
    let mut first_child_top_margin_set = CollapsibleMarginSet::ZERO;
    let mut active_collapsible_margin_set = CollapsibleMarginSet::ZERO;
    let mut is_collapsing_with_first_margin_set = true;
    let mut first_baseline: Option<f32> = None;
    // Whether the active margin set contains the margins of a self-collapsing element with
    // clearance. Such margins collapse with the margins of following siblings but the resulting
    // margin does not collapse with the bottom margin of the parent block.
    let mut active_margin_set_has_clearance = false;

    #[cfg(feature = "float_layout")]
    let mut has_active_floats = block_ctx.has_active_floats(committed_y_offset);
    #[cfg(not(feature = "float_layout"))]
    let has_active_floats = false;

    for item in items.iter_mut() {
        if item.position.is_out_of_flow() {
            let x = match direction {
                Direction::Ltr => resolved_content_box_inset.left,
                Direction::Rtl => container_outer_width - resolved_content_box_inset.right,
            };
            item.static_position = Point { x, y: y_offset_for_absolute }
        } else {
            let item_margin = item
                .margin
                .map(|margin| margin.resolve_to_option(container_inner_width, |val, basis| tree.calc(val, basis)));
            let item_non_auto_margin = item_margin.map(|m| m.unwrap_or(0.0));
            let item_non_auto_x_margin_sum = item_non_auto_margin.horizontal_axis_sum();

            let scrollbar_size = Size {
                width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
                height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
            };

            // Handle floated boxes
            #[cfg(feature = "float_layout")]
            if let Some(float_direction) = item.float.float_direction() {
                has_active_floats = true;

                // A float with `width: auto` is shrink-to-fit (fit-content) sized: the available
                // space clamped between its min-content and max-content sizes.
                let available_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
                let (item_known_width, item_available_width) = match resolve_sizing_keyword(
                    item.size_style.width,
                    Some(available_width),
                    Some(container_inner_width),
                    |val, basis| tree.calc(val, basis),
                ) {
                    Some(SizingKeywordResolution::Measure(available)) => (None, available),
                    Some(SizingKeywordResolution::Exact(width)) => (Some(width), AvailableSpace::Definite(width)),
                    None => (None, AvailableSpace::Definite(available_width)),
                };
                let item_known_height = resolve_stretch_height(
                    item.size_style.height,
                    container_percentage_resolution_height,
                    item_non_auto_margin,
                    // The margins of a float never collapse
                    Line::FALSE,
                );
                let mut item_layout = tree.perform_child_layout(
                    item.node_id,
                    Size { width: item_known_width, height: item_known_height },
                    parent_size,
                    Size { width: item_available_width, height: AvailableSpace::MaxContent },
                    SizingMode::InherentSize,
                    // A float establishes a new block formatting context: its margins do not
                    // collapse with the margins of its children
                    Line::FALSE,
                );
                item.oof_candidates = item_layout.oof_candidates.take();
                let margin_box = item_layout.size + item_non_auto_margin.sum_axes();

                // Floats that occur between collapsing margins are positioned as if they had an otherwise
                // empty anonymous block parent taking part in the flow, so the pending collapsible margins
                // contribute to the float's minimum y position (unless those margins collapse with the
                // container's own top margin, in which case they are applied outside the container).
                //
                // In the latter case the position of the float is not fully resolved: margins contributed
                // by later siblings can still collapse into the strut and move the container (and float).
                // Such floats force clearance on cleared elements whose margins adjoin the same strut.
                let adjoins_unresolved_strut =
                    is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start;
                let y_offset_for_float = if adjoins_unresolved_strut {
                    committed_y_offset
                } else {
                    committed_y_offset + active_collapsible_margin_set.resolve()
                };

                let mut location = block_ctx.place_floated_box(
                    margin_box,
                    y_offset_for_float,
                    float_direction,
                    item.clear,
                    adjoins_unresolved_strut,
                );

                // Ensure that content that appears after a float does not get positioned before/above the float
                //
                // FIXME: this isn't quite right, because a second float at the same location
                // shouldn't cause content to push down to it's level
                // committed_y_offset = committed_y_offset.max(location.y);
                // y_offset_for_absolute = y_offset_for_absolute.max(location.y);

                // Convert the margin-box location returned by float placement into a border-box location
                // for the output Layout
                location.y += item_non_auto_margin.top;
                location.x += item_non_auto_margin.left;

                // println!("BLOCK FLOATED BOX ({:?}) {:?}", item.node_id, float_direction);
                // println!("w:{} h:{} x:{}, y:{}", margin_box.width, margin_box.height, location.x, location.y);

                // Deferred to the post-loop pass in `compute_inner` (like in-flow items) so that
                // `align-content` can shift `location.y` before the layout is committed.
                item.final_layout = Some(Layout {
                    order: item.order,
                    size: item_layout.size,
                    #[cfg(feature = "content_size")]
                    scrollable_overflow_rect: item_layout.scrollable_overflow_rect,
                    scrollbar_size,
                    location,
                    padding: item.padding,
                    border: item.border,
                    margin: item_non_auto_margin,
                });

                #[cfg(feature = "content_size")]
                {
                    // TODO: Should the overflow of floated boxes count as "inflow_overflow_rect"
                    // or should it be counted separately?
                    let contribution_location = if direction.is_rtl() {
                        Point {
                            x: container_outer_width - (location.x + item_layout.size.width) - resolved_border.right,
                            y: location.y - resolved_border.top,
                        }
                    } else {
                        Point { x: location.x - resolved_border.left, y: location.y - resolved_border.top }
                    };
                    inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
                        contribution_location,
                        item_layout.size,
                        item_layout.scrollable_overflow_rect,
                        item.overflow,
                        item.contain,
                        is_scroll_container,
                    ));
                }

                continue;
            }

            // Handle non-floated boxes

            let mut y_margin_offset: f32 = 0.0;
            #[cfg(feature = "float_layout")]
            let mut item_avoids_floats = false;
            #[cfg(feature = "float_layout")]
            let mut item_pushed_below_float = false;

            let (stretch_width, float_avoiding_position, float_avoiding_width) = if item.is_in_same_bfc {
                let stretch_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
                let position = Point { x: 0.0, y: 0.0 };
                let width = 0.0;

                (stretch_width, position, width)
            } else {
                'block: {
                    // Set y_margin_offset (different bfc child)
                    if !is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start {
                        y_margin_offset =
                            active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
                    };
                    let min_y = committed_y_offset + y_margin_offset;

                    // In addition to the running flag, check the float context directly:
                    // floats placed by the subtree of a preceding in-flow sibling (in the same
                    // BFC) are not reflected in the flag
                    #[cfg(feature = "float_layout")]
                    if has_active_floats || block_ctx.has_active_floats(min_y) {
                        let x_margins = [item_non_auto_margin.left, item_non_auto_margin.right];
                        // An auto width resolves to at least the negation of the margin sum
                        // (so that the margin box width is non-negative, per CSS2 §10.3.3)
                        let min_auto_width = -item_non_auto_x_margin_sum;

                        // Find the highest slot (at or below `min_y`) with enough horizontal space
                        // for the item's border box, which must not overlap any float
                        let mut slot_segment = None;
                        let slot = loop {
                            let slot = block_ctx.find_bfc_slot(min_y, x_margins, direction, item.clear, slot_segment);
                            let Some(segment_id) = slot.segment_id else { break slot };
                            let width = item
                                .size
                                .width
                                .unwrap_or(slot.stretch_width.max(min_auto_width).max(0.0))
                                .maybe_clamp(item.min_size.width, item.max_size.width);
                            if width <= slot.border_width + FIT_TOLERANCE {
                                break slot;
                            }
                            slot_segment = Some(segment_id);
                        };

                        // If the item had to move down to avoid floats then it "separates from the
                        // float": similarly to clearance, its top margin no longer collapses with
                        // the parent's margins.
                        if slot.y > min_y {
                            item_pushed_below_float = true;
                        }

                        has_active_floats = slot.segment_id.is_some();
                        item_avoids_floats = true;
                        let stretch_width = slot.stretch_width.max(min_auto_width).max(0.0);
                        break 'block (stretch_width, Point { x: slot.x, y: slot.y }, slot.border_width);
                    }

                    if !has_active_floats {
                        let stretch_width = (container_inner_width - item_non_auto_x_margin_sum).max(0.0);
                        break 'block (
                            stretch_width,
                            Point { x: resolved_content_box_inset.left, y: min_y },
                            container_inner_width,
                        );
                    }

                    unreachable!("One of the above cases will always be hit");
                }
            };

            // `justify-self` on an in-flow block-level box (css-align-3 §6.1.1). `None` takes the
            // container's `justify-items`, and `normal` lays the box out according to the default
            // block layout rules. `stretch` does too: the default rules already stretch an
            // auto-width box, so it only differs from `normal` for tables and replaced boxes, which
            // would otherwise resolve their own width.
            let justify_self =
                item.justify_self.unwrap_or(justify_items).resolve_self_relative(item.direction, direction, true);
            let is_stretch = justify_self.keyword == AlignItemsKeyword::Stretch;
            // The (resolved) `justify-self` if it is neither `normal` nor `stretch`
            let non_stretch_justify_self = match justify_self.keyword {
                AlignItemsKeyword::Normal | AlignItemsKeyword::Stretch => None,
                _ => Some(justify_self),
            };

            // Unless stretched, tables and compressible replaced elements resolve their own width
            // <https://www.w3.org/TR/CSS22/visudet.html#block-replaced-width>
            let known_dimensions = if (item.is_table || item.is_compressible_replaced) && !is_stretch {
                Size::NONE
            } else {
                // The automatic width of a block-level box whose `justify-self` is neither `normal` nor `stretch`
                // is equivalent to `fit-content` rather than `stretch`
                let width_style = if non_stretch_justify_self.is_some() && item.size_style.width.is_auto() {
                    Dimension::fit_content()
                } else {
                    item.size_style.width
                };

                // Items with a sizing keyword width (min-content, max-content, fit-content,
                // fit-content(...), stretch) resolve their width either directly or by measuring
                // the item under the corresponding available space constraint
                let keyword_width = resolve_sizing_keyword(
                    width_style,
                    Some(stretch_width),
                    Some(container_inner_width),
                    |val, basis| tree.calc(val, basis),
                )
                .map(|resolution| match resolution {
                    SizingKeywordResolution::Exact(width) => width,
                    SizingKeywordResolution::Measure(item_available_width) => tree.measure_child_size(
                        item.node_id,
                        Size::NONE,
                        parent_size,
                        Size { width: item_available_width, height: AvailableSpace::MaxContent },
                        SizingMode::InherentSize,
                        crate::AbsoluteAxis::Horizontal,
                        // Must match the value passed when laying the item out (see `Cache`)
                        if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
                    ),
                });

                let keyword_height = resolve_stretch_height(
                    item.size_style.height,
                    container_percentage_resolution_height,
                    item_non_auto_margin,
                    children_margins_adjoin_own_edges,
                );

                item.size
                    .map_width(|width| {
                        Some(
                            width
                                .or(keyword_width)
                                .unwrap_or(stretch_width)
                                .maybe_clamp(item.min_size.width, item.max_size.width),
                        )
                    })
                    .map_height(|height| height.or(keyword_height))
                    .maybe_clamp(item.min_size, item.max_size)
            };

            //

            let inputs = LayoutInput {
                run_mode,
                sizing_mode: SizingMode::InherentSize,
                axis: RequestedAxis::Both,
                known_dimensions,
                known_dimensions_are_definite: Size { width: true, height: true },
                parent_size,
                available_space: available_space.map_width(|_| AvailableSpace::Definite(stretch_width)),
                vertical_margins_are_collapsible: if item.is_in_same_bfc { Line::TRUE } else { Line::FALSE },
            };

            #[cfg(feature = "float_layout")]
            let clear_threshold = block_ctx.cleared_threshold(item.clear);
            #[cfg(feature = "float_layout")]
            let clear_pos = clear_threshold.unwrap_or(f32::NEG_INFINITY);
            #[cfg(not(feature = "float_layout"))]
            let clear_pos = f32::NEG_INFINITY;

            // The height consumed by floats within a same-BFC child, relative to the child's
            // border-top. Added to the parent's contribution once the child's position is known.
            #[cfg(feature = "float_layout")]
            let mut child_float_contribution = f32::NEG_INFINITY;

            let mut item_layout = if item.is_in_same_bfc {
                // Replaced elements may not have a known width (they are sized by their
                // measure function rather than stretch-sized)
                let width = known_dimensions.width.unwrap_or(stretch_width).max(item.padding_border_sum.width);

                // TODO: account for auto margins
                let inset_left = item_non_auto_margin.left + content_box_inset.left;
                let inset_right = container_outer_width - width - inset_left;
                let insets = [inset_left, inset_right];

                // Compute child layout. The child's position is estimated from its top margin collapsed with
                // the preceding margins (the child's own collapsed-through margins are not yet known).
                let estimated_y = committed_y_offset
                    + active_collapsible_margin_set.collapse_with_margin(item_non_auto_margin.top).resolve();
                let mut child_block_ctx = block_ctx.sub_context(estimated_y.max(clear_pos), insets);
                let output = tree.compute_block_child_layout(item.node_id, inputs, Some(&mut child_block_ctx));

                // Extract float contribution from child block context
                #[cfg(feature = "float_layout")]
                {
                    child_float_contribution = child_block_ctx.floated_content_height_contribution();
                    let child_top_adjoining_floats = child_block_ctx.top_adjoining_floats();
                    // Floats placed while the position of the child's top margin strut was unresolved
                    // also adjoin this block's current strut
                    block_ctx.merge_adjoining_floats(child_top_adjoining_floats);
                }

                output
            } else {
                tree.compute_child_layout(item.node_id, inputs)
            };
            item.oof_candidates = item_layout.oof_candidates.take();
            let final_size = item_layout.size;

            let top_margin_set = item_layout.top_margin.collapse_with_margin(item_margin.top.unwrap_or(0.0));
            let bottom_margin_set = item_layout.bottom_margin.collapse_with_margin(item_margin.bottom.unwrap_or(0.0));

            // Expand auto margins to fill available space
            // Note: Vertical auto-margins for relatively positioned block items simply resolve to 0.
            // See: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
            let free_x_space = f32_max(0.0, stretch_width - final_size.width);
            let x_axis_auto_margin_size = {
                let auto_margin_count = item_margin.left.is_none() as u8 + item_margin.right.is_none() as u8;
                if auto_margin_count > 0 {
                    free_x_space / auto_margin_count as f32
                } else {
                    0.0
                }
            };
            let resolved_margin = Rect {
                left: item_margin.left.unwrap_or(x_axis_auto_margin_size),
                right: item_margin.right.unwrap_or(x_axis_auto_margin_size),
                top: item_margin.top.unwrap_or(0.0),
                bottom: item_margin.bottom.unwrap_or(0.0),
            };

            // Resolve item inset
            let inset_percentage_basis =
                Size { width: Some(container_inner_width), height: container_percentage_resolution_height };
            let inset = item
                .inset
                .zip_size(inset_percentage_basis, |p, s| p.maybe_resolve(s, |val, basis| tree.calc(val, basis)));
            let inset_offset = if item.position == Position::Relative {
                Point {
                    x: if direction.is_rtl() {
                        inset.right.map(|x| -x).or(inset.left).unwrap_or(0.0)
                    } else {
                        inset.left.or(inset.right.map(|x| -x)).unwrap_or(0.0)
                    },
                    y: inset.top.or(inset.bottom.map(|x| -x)).unwrap_or(0.0),
                }
            } else {
                Point::ZERO
            };

            // Set y_margin_offset (same bfc child)
            if item.is_in_same_bfc
                && (!is_collapsing_with_first_margin_set || !own_margins_collapse_with_children.start)
            {
                y_margin_offset = active_collapsible_margin_set.collapse_with_set(top_margin_set).resolve()
            };

            // Compute clearance (CSS2.2 9.5.2). Clearance is introduced if the hypothetical position of the
            // item's top border edge (the position it would have with normal margin collapsing) is not past
            // the bottom of the relevant floats. When clearance is introduced the item's border edge is
            // placed at `max(float bottom, hypothetical position)`.
            #[cfg(feature = "float_layout")]
            let mut has_clearance = false;
            #[cfg(not(feature = "float_layout"))]
            let has_clearance = false;
            #[cfg(feature = "float_layout")]
            if item.is_in_same_bfc {
                if let Some(threshold) = clear_threshold {
                    // The hypothetical position always includes the item's collapsed top margin set, even
                    // when those margins collapse with the container's own top margin (and are thus applied
                    // outside the container): in that case they still move the container (and hence the item)
                    // relative to the floats.
                    let hypothetical_y =
                        committed_y_offset + active_collapsible_margin_set.collapse_with_set(top_margin_set).resolve();
                    // Clearance is forced (regardless of the hypothetical position) if a relevant float is
                    // adjoining the margin-collapse strut that the item's top margin would collapse into:
                    // if the margins were allowed to collapse they would pull the float down with the item,
                    // so clearance is inserted to separate the two, placing the item just below the float.
                    let forced_clearance = block_ctx.has_adjoining_float(item.clear);
                    if forced_clearance || hypothetical_y < threshold {
                        has_clearance = true;
                        // Clearance stops the item's top margin collapsing with preceding margins. If those
                        // preceding margins collapse with the container's own top margin they are applied
                        // outside the container (moving it down), so the item's cleared position within the
                        // container must be reduced by that amount to keep its absolute position correct.
                        let escaped_margin =
                            if is_collapsing_with_first_margin_set && own_margins_collapse_with_children.start {
                                active_collapsible_margin_set.resolve()
                            } else {
                                0.0
                            };
                        y_margin_offset = threshold - committed_y_offset - escaped_margin;
                    }
                }
            }

            item.computed_size = item_layout.size;
            item.can_be_collapsed_through = item_layout.margins_can_collapse_through && !has_clearance;
            item.static_position = if item.is_in_same_bfc {
                let uncleared_y = committed_y_offset + active_collapsible_margin_set.resolve();
                Point {
                    x: match direction {
                        Direction::Ltr => resolved_content_box_inset.left,
                        Direction::Rtl => container_outer_width - resolved_content_box_inset.right - final_size.width,
                    },
                    y: uncleared_y.max(clear_pos),
                }
            } else {
                // TODO: handle inset and margins
                Point {
                    x: match direction {
                        Direction::Ltr => float_avoiding_position.x,
                        Direction::Rtl => float_avoiding_position.x + float_avoiding_width - final_size.width,
                    },
                    y: float_avoiding_position.y,
                }
            };
            let mut location = if item.is_in_same_bfc {
                Point {
                    x: match direction {
                        Direction::Ltr => resolved_content_box_inset.left + inset_offset.x + resolved_margin.left,
                        Direction::Rtl => {
                            container_outer_width
                                - resolved_content_box_inset.right
                                - final_size.width
                                - resolved_margin.right
                                + inset_offset.x
                        }
                    },
                    y: committed_y_offset + y_margin_offset + inset_offset.y,
                }
            } else {
                // When the item avoids floats, its non-auto margins are already accounted for in the
                // slot's border-box position/width (margins may overlap floats), so only the auto
                // portion of the resolved margin is added here.
                #[cfg(feature = "float_layout")]
                let (extra_margin_left, extra_margin_right) = if item_avoids_floats {
                    (
                        resolved_margin.left - item_non_auto_margin.left,
                        resolved_margin.right - item_non_auto_margin.right,
                    )
                } else {
                    (resolved_margin.left, resolved_margin.right)
                };
                #[cfg(not(feature = "float_layout"))]
                let (extra_margin_left, extra_margin_right) = (resolved_margin.left, resolved_margin.right);

                // TODO: handle inset and margins
                Point {
                    x: match direction {
                        Direction::Ltr => float_avoiding_position.x + extra_margin_left + inset_offset.x,
                        Direction::Rtl => {
                            float_avoiding_position.x + float_avoiding_width - final_size.width - extra_margin_right
                                + inset_offset.x
                        }
                    },
                    y: float_avoiding_position.y + inset_offset.y,
                }
            };

            // Floats within the child are positioned relative to the child's border-top, so the
            // child's (margin-collapsed) position, rather than its relative offset, is added.
            #[cfg(feature = "float_layout")]
            if item.is_in_same_bfc {
                block_ctx.add_child_floated_content_height_contribution(
                    location.y - inset_offset.y + child_float_contribution,
                );
            }

            // Apply alignment. `justify-self` aligns the item's margin box within its alignment
            // container and takes precedence over legacy `text-align`, but auto margins (which have
            // already absorbed the free space) take precedence over `justify-self`.
            let has_auto_x_margin = item_margin.left.is_none() || item_margin.right.is_none();
            let item_outer_width = item_layout.size.width + resolved_margin.horizontal_axis_sum();
            if let (Some(justify_self), false) = (non_stretch_justify_self, has_auto_x_margin) {
                // The alignment container is the containing block, except that a BFC-establishing
                // box placed next to a float aligns within the space left over by the float (in
                // which case the slot is already inset by the item's margins).
                #[cfg(feature = "float_layout")]
                let (container_start, free_x_space) = if item_avoids_floats {
                    (float_avoiding_position.x - resolved_margin.left, float_avoiding_width - item_layout.size.width)
                } else {
                    (resolved_content_box_inset.left, container_inner_width - item_outer_width)
                };
                #[cfg(not(feature = "float_layout"))]
                let (container_start, free_x_space) =
                    (resolved_content_box_inset.left, container_inner_width - item_outer_width);

                let keyword = if matches!(justify_self.safety, AlignmentSafety::Safe) && free_x_space < 0.0 {
                    AlignItemsKeyword::Start
                } else {
                    justify_self.keyword
                };
                let align_to_end = match keyword {
                    AlignItemsKeyword::Center => None,
                    AlignItemsKeyword::End | AlignItemsKeyword::FlexEnd | AlignItemsKeyword::SelfEnd => Some(true),
                    _ => Some(false),
                };
                let offset = match align_to_end {
                    None => free_x_space / 2.0,
                    Some(end) if end != direction.is_rtl() => free_x_space,
                    Some(_) => 0.0,
                };
                location.x = container_start + resolved_margin.left + inset_offset.x + offset;
            } else if non_stretch_justify_self.is_none() && item_outer_width < container_inner_width {
                let free_x_space = container_inner_width - item_outer_width;
                match (text_align, direction) {
                    (TextAlign::Auto, _) => {
                        // Do nothing
                    }
                    (TextAlign::LegacyLeft, Direction::Ltr) => {
                        // Do nothing. Left aligned by default.
                    }
                    (TextAlign::LegacyLeft, Direction::Rtl) => location.x -= free_x_space,
                    (TextAlign::LegacyRight, Direction::Ltr) => location.x += free_x_space,
                    (TextAlign::LegacyRight, Direction::Rtl) => {
                        // Do nothing. Right aligned by default.
                    }
                    (TextAlign::LegacyCenter, Direction::Ltr) => location.x += free_x_space / 2.0,
                    (TextAlign::LegacyCenter, Direction::Rtl) => location.x -= free_x_space / 2.0,
                }
            }

            // A block container's first baseline is the first baseline of its first in-flow child
            // that has one.
            //
            // Scroll containers' baselines are determined from their content as if scrolled to the
            // initial position, but are additionally clamped to their border box. A scroll container
            // with no baseline synthesizes one from its border-box bottom edge.
            // See https://github.com/w3c/csswg-drafts/issues/7660
            if first_baseline.is_none() {
                let child_baseline = if item.overflow.y.is_scroll_container() {
                    Some(
                        item_layout
                            .baselines
                            .first
                            .unwrap_or(item_layout.size.height)
                            .min(item_layout.size.height)
                            .max(0.0),
                    )
                } else {
                    item_layout.baselines.first
                };
                first_baseline = child_baseline.map(|baseline| location.y + baseline);
            }

            // Used auto margins include float-avoidance offsets, unlike the alignment margins above.
            #[cfg(feature = "float_layout")]
            let resolved_margin = {
                let mut margin = resolved_margin;
                if item_avoids_floats {
                    if item_margin.left.is_none() {
                        margin.left += float_avoiding_position.x - resolved_content_box_inset.left;
                    }
                    if item_margin.right.is_none() {
                        margin.right += container_outer_width
                            - resolved_content_box_inset.right
                            - float_avoiding_position.x
                            - float_avoiding_width;
                    }
                }
                margin
            };

            // Defer `set_unrounded_layout` to the post-loop pass in `compute_inner` so that
            // `align-content` can shift `location.y` before the layout is committed to the tree.
            item.final_layout = Some(Layout {
                order: item.order,
                size: item_layout.size,
                #[cfg(feature = "content_size")]
                scrollable_overflow_rect: item_layout.scrollable_overflow_rect,
                scrollbar_size,
                location,
                padding: item.padding,
                border: item.border,
                margin: resolved_margin,
            });

            #[cfg(feature = "content_size")]
            {
                let contribution_location = if direction.is_rtl() {
                    Point {
                        x: container_outer_width - (location.x + final_size.width) - resolved_border.right,
                        y: location.y - resolved_border.top,
                    }
                } else {
                    Point { x: location.x - resolved_border.left, y: location.y - resolved_border.top }
                };
                inflow_overflow_rect = inflow_overflow_rect.union(compute_scrollable_overflow_contribution(
                    contribution_location,
                    final_size,
                    item_layout.scrollable_overflow_rect,
                    item.overflow,
                    item.contain,
                    is_scroll_container,
                ));
            }

            // Update first_child_top_margin_set
            //
            // The top margin of an item with clearance does not collapse with the container's top margin,
            // so clearance terminates collapsing without contributing the item's own margins.
            #[cfg(feature = "float_layout")]
            if is_collapsing_with_first_margin_set && item_pushed_below_float {
                // The item's top margin "separated from the float" and must not
                // propagate to the parent
                is_collapsing_with_first_margin_set = false;
            }
            if is_collapsing_with_first_margin_set && has_clearance {
                is_collapsing_with_first_margin_set = false;
            } else if is_collapsing_with_first_margin_set {
                if item.can_be_collapsed_through {
                    first_child_top_margin_set = first_child_top_margin_set
                        .collapse_with_set(top_margin_set)
                        .collapse_with_set(bottom_margin_set);
                } else {
                    first_child_top_margin_set = first_child_top_margin_set.collapse_with_set(top_margin_set);
                    is_collapsing_with_first_margin_set = false;
                }
            }

            // Update active_collapsible_margin_set
            if item.can_be_collapsed_through {
                active_collapsible_margin_set = active_collapsible_margin_set
                    .collapse_with_set(top_margin_set)
                    .collapse_with_set(bottom_margin_set);
                y_offset_for_absolute = committed_y_offset + item_layout.size.height + y_margin_offset;
            } else {
                committed_y_offset = location.y - inset_offset.y + item_layout.size.height;
                // A self-collapsing item with clearance is not collapsed through (its margins do not collapse
                // with margins of preceding siblings), but its top and bottom margins still collapse with each
                // other and with the margins of following siblings.
                if has_clearance && item_layout.margins_can_collapse_through {
                    // The element's border edge stays at the cleared position, but its collapsed margin
                    // extends below it: the border edge sits `top margin` inside the collapsed margin, so
                    // following content is offset by `collapsed margin - top margin` from the border edge.
                    committed_y_offset -= top_margin_set.resolve();
                    active_collapsible_margin_set = top_margin_set.collapse_with_set(bottom_margin_set);
                    active_margin_set_has_clearance = true;
                } else {
                    active_collapsible_margin_set = bottom_margin_set;
                    active_margin_set_has_clearance = false;
                }
                y_offset_for_absolute = committed_y_offset + active_collapsible_margin_set.resolve();
                // Committing in-flow content resolves the position of the current margin-collapse strut,
                // so floats placed before this point no longer force clearance
                #[cfg(feature = "float_layout")]
                block_ctx.commit_strut();
            }
        }
    }

    // The margins of a self-collapsing element with clearance do not collapse with the bottom
    // margin of the parent block: they extend the parent's content height instead of escaping it
    let last_child_bottom_margin_set =
        if active_margin_set_has_clearance { CollapsibleMarginSet::ZERO } else { active_collapsible_margin_set };
    let bottom_y_margin_offset = if active_margin_set_has_clearance {
        active_collapsible_margin_set.resolve()
    } else if own_margins_collapse_with_children.end {
        0.0
    } else {
        last_child_bottom_margin_set.resolve()
    };

    committed_y_offset += resolved_content_box_inset.bottom + bottom_y_margin_offset;
    let content_height = f32_max(0.0, committed_y_offset);
    (inflow_overflow_rect, content_height, first_child_top_margin_set, last_child_bottom_margin_set, first_baseline)
}