strata-layout 0.1.2

Chromium-parity Box Model, Flexbox (L1), and CSS Grid (L2) layout engine in pure Rust
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
//! CSS 2.1 Section 8.3.1 Box Model and Vertical Margin Collapsing Engine.

use crate::geometry::{LayoutGeometry, Rect};
use crate::tree::LayoutNode;
use strata_style::types::{BoxSizing, Dimension, Position};

/// Collapses two adjacent vertical margins according to CSS 2.1 ยง8.3.1.
///
/// Rules:
/// - If both are positive, the result is the maximum of the two: $\max(m_1, m_2)$.
/// - If both are negative, the result is the most negative: $-\max(|m_1|, |m_2|)$.
/// - If one is positive and one is negative, add the most negative to the most positive:
///   $\max(m_1, m_2, 0) + \min(m_1, m_2, 0)$.
pub fn collapse_margins(m1: f32, m2: f32) -> f32 {
    let m1 = if m1.is_finite() {
        m1.clamp(-1e7, 1e7)
    } else {
        0.0
    };
    let m2 = if m2.is_finite() {
        m2.clamp(-1e7, 1e7)
    } else {
        0.0
    };
    if m1 >= 0.0 && m2 >= 0.0 {
        m1.max(m2)
    } else if m1 < 0.0 && m2 < 0.0 {
        -(-m1).max(-m2)
    } else {
        let max_pos = m1.max(m2).max(0.0);
        let min_neg = m1.min(m2).min(0.0);
        max_pos + min_neg
    }
}

/// Resolves a CSS `Dimension` into concrete pixels relative to an available length.
pub fn resolve_dimension(dim: Dimension, available: f32) -> Option<f32> {
    const MAX_DIMENSION: f32 = 1e7;

    let avail = if available.is_finite() {
        available.clamp(-MAX_DIMENSION, MAX_DIMENSION)
    } else {
        0.0
    };

    match dim {
        Dimension::Auto => None,
        Dimension::Px(px) => {
            if px.is_finite() {
                Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
            } else {
                None
            }
        }
        Dimension::Percent(pct) => {
            if pct.is_finite() {
                let px = avail * (pct / 100.0);
                if px.is_finite() {
                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
                } else {
                    None
                }
            } else {
                None
            }
        }
        Dimension::Vw(vw) => {
            if vw.is_finite() {
                let px = avail * (vw / 100.0);
                if px.is_finite() {
                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
                } else {
                    None
                }
            } else {
                None
            }
        }
        Dimension::Vh(vh) => {
            if vh.is_finite() {
                let px = avail * (vh / 100.0);
                if px.is_finite() {
                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
                } else {
                    None
                }
            } else {
                None
            }
        }
        Dimension::Rem(rem) => {
            if rem.is_finite() {
                Some((rem * 16.0).clamp(-MAX_DIMENSION, MAX_DIMENSION))
            } else {
                None
            }
        }
        Dimension::Em(em) => {
            if em.is_finite() {
                Some((em * 16.0).clamp(-MAX_DIMENSION, MAX_DIMENSION))
            } else {
                None
            }
        }
        Dimension::Calc(id) => strata_style::calc::get_calc(id).and_then(|expr| {
            let ctx = strata_style::calc::CalcContext {
                parent_size: avail,
                root_font_size: 16.0,
                current_font_size: 16.0,
                viewport_width: 1920.0,
                viewport_height: 1080.0,
            };
            let val = expr.eval(&ctx);
            if val.is_finite() {
                Some(val.clamp(-MAX_DIMENSION, MAX_DIMENSION))
            } else {
                None
            }
        }),
        Dimension::MinContent | Dimension::MaxContent | Dimension::FitContent(_) => None,
    }
}

/// Clamps a computed size against `min` and `max` constraints.
pub fn clamp_dimension(size: f32, min: Dimension, max: Dimension, available: f32) -> f32 {
    let mut clamped = if size.is_finite() {
        size.clamp(0.0, 1e7)
    } else {
        0.0
    };
    if let Some(min_px) = resolve_dimension(min, available) {
        clamped = clamped.max(min_px.max(0.0));
    }
    if let Some(max_px) = resolve_dimension(max, available) {
        clamped = clamped.min(max_px.max(0.0));
    }
    clamped.clamp(0.0, 1e7)
}

/// Resolves a CSS `Dimension` into concrete pixels relative to an available length and node context,
/// evaluating intrinsic keywords (`min-content`, `max-content`, `fit-content`) via `compute_min_max_sizes`.
pub fn resolve_dimension_with_node(
    dim: Dimension,
    available: f32,
    node: &LayoutNode,
) -> Option<f32> {
    match dim {
        Dimension::MinContent => {
            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
            let inline_insets = node.style.padding.left
                + node.style.padding.right
                + node.style.border_width.left
                + node.style.border_width.right;
            let val = match node.style.box_sizing {
                BoxSizing::BorderBox => sizes.min_content,
                BoxSizing::ContentBox => (sizes.min_content - inline_insets).max(0.0),
            };
            Some(val)
        }
        Dimension::MaxContent => {
            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
            let inline_insets = node.style.padding.left
                + node.style.padding.right
                + node.style.border_width.left
                + node.style.border_width.right;
            let val = match node.style.box_sizing {
                BoxSizing::BorderBox => sizes.max_content,
                BoxSizing::ContentBox => (sizes.max_content - inline_insets).max(0.0),
            };
            Some(val)
        }
        Dimension::FitContent(arg) => {
            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
            let inline_insets = node.style.padding.left
                + node.style.padding.right
                + node.style.border_width.left
                + node.style.border_width.right;
            let limit = if arg > 0.0 { arg } else { available };
            let fitted = sizes.shrink_to_fit(limit);
            let val = match node.style.box_sizing {
                BoxSizing::BorderBox => fitted,
                BoxSizing::ContentBox => (fitted - inline_insets).max(0.0),
            };
            Some(val)
        }
        other => resolve_dimension(other, available),
    }
}

/// Clamps a computed size against `min` and `max` constraints with node context.
pub fn clamp_dimension_with_node(
    size: f32,
    min: Dimension,
    max: Dimension,
    available: f32,
    node: &LayoutNode,
) -> f32 {
    let mut clamped = if size.is_finite() {
        size.clamp(0.0, 1e7)
    } else {
        0.0
    };
    if let Some(min_px) = resolve_dimension_with_node(min, available, node) {
        clamped = clamped.max(min_px.max(0.0));
    }
    if let Some(max_px) = resolve_dimension_with_node(max, available, node) {
        clamped = clamped.min(max_px.max(0.0));
    }
    clamped.clamp(0.0, 1e7)
}

/// Converts a ComputedStyle into an InlineTextStyle for inline text shaping and typography.
pub fn inline_style_from_computed_style(
    style: &strata_style::types::ComputedStyle,
) -> crate::typography::InlineTextStyle {
    let is_monospace = crate::text::is_monospace_family(style.font_family);

    crate::typography::InlineTextStyle {
        font_family: style.font_family,
        font_size: style.font_size,
        font_weight: style.font_weight,
        font_style: style.font_style,
        color: style.color,
        background_color: style.background_color,
        text_decoration: style.text_decoration,
        vertical_align: match style.vertical_align {
            strata_style::types::VerticalAlign::Baseline => {
                crate::typography::VerticalAlignment::Baseline
            }
            strata_style::types::VerticalAlign::Top => crate::typography::VerticalAlignment::Top,
            strata_style::types::VerticalAlign::Bottom => {
                crate::typography::VerticalAlignment::Bottom
            }
            strata_style::types::VerticalAlign::Middle => {
                crate::typography::VerticalAlignment::Middle
            }
            strata_style::types::VerticalAlign::Sub => crate::typography::VerticalAlignment::Sub,
            strata_style::types::VerticalAlign::Super => {
                crate::typography::VerticalAlignment::Super
            }
            strata_style::types::VerticalAlign::TextTop => {
                crate::typography::VerticalAlignment::TextTop
            }
            strata_style::types::VerticalAlign::TextBottom => {
                crate::typography::VerticalAlignment::TextBottom
            }
        },
        letter_spacing: style.letter_spacing,
        line_height: Some(style.font_size * style.line_height),
        is_monospace,
        href: style
            .get_custom_property(strata_primitives::AtomId::HREF)
            .and_then(strata_primitives::atom::resolve),
    }
}

/// Returns whether a child layout node is an inline phrasing element.
pub fn is_inline_phrasing_node(child: &LayoutNode) -> bool {
    matches!(
        child.style.display,
        strata_style::types::Display::Inline
            | strata_style::types::Display::InlineBlock
            | strata_style::types::Display::None
    ) || child.text.is_some()
}

/// Refreshes inline fragment paint styles after a style-only change.
///
/// Geometry and line boxes are preserved from a previous layout pass. When
/// hover toggles only paint properties (color, background, decoration), the
/// text runs still carry the previous inline style clones. This rebuilds the
/// inline item stream from the freshly styled children and patches each line
/// fragment's paint-only style fields by item index.
pub fn refresh_inline_fragment_styles(node: &mut LayoutNode) {
    let mut stack = vec![node];
    while let Some(curr) = stack.pop() {
        if !curr.line_boxes.is_empty() {
            if !curr.children.is_empty() {
                let mut items = Vec::new();
                collect_inline_items_from_children(
                    &curr.children,
                    None,
                    None,
                    &mut items,
                    curr.geometry.content_box.width,
                    curr.geometry.content_box.height,
                );
                curr.inline_items = items;
            }
            for line in &mut curr.line_boxes {
                for frag in &mut line.text_fragments {
                    if let Some(crate::typography::InlineItem::Text { style, .. }) =
                        curr.inline_items.get(frag.item_index)
                    {
                        frag.style.color = style.color;
                        frag.style.background_color = style.background_color;
                        frag.style.text_decoration = style.text_decoration;
                        frag.style.font_family = style.font_family;
                        frag.font_family = style.font_family;
                    } else if curr.inline_items.is_empty() && curr.text.is_some() {
                        let style = inline_style_from_computed_style(&curr.style);
                        frag.style.color = style.color;
                        frag.style.background_color = style.background_color;
                        frag.style.text_decoration = style.text_decoration;
                        frag.style.font_family = style.font_family;
                        frag.font_family = style.font_family;
                    }
                }
            }
        }
        for child in &mut curr.children {
            stack.push(child);
        }
    }
}

/// Recursively clears line boxes from inline phrasing descendants whose text is absorbed by parent IFC using an iterative heap stack.
pub fn clear_inline_descendant_line_boxes(node: &mut LayoutNode) {
    if node.style.display != strata_style::types::Display::Inline {
        return;
    }
    let mut stack = vec![node];
    while let Some(curr) = stack.pop() {
        if curr.style.display == strata_style::types::Display::Inline {
            curr.line_boxes.clear();
            for child in &mut curr.children {
                stack.push(child);
            }
        }
    }
}

#[derive(Clone, Copy)]
struct InheritedInlineStyle {
    font_family: strata_primitives::AtomId,
    background_color: Option<strata_style::types::Color>,
    text_decoration: strata_style::types::TextDecoration,
    href: Option<strata_primitives::AtomId>,
}

impl InheritedInlineStyle {
    #[inline]
    fn from_style(style: &strata_style::types::ComputedStyle) -> Self {
        Self {
            font_family: style.font_family,
            background_color: if style.display == strata_style::types::Display::Inline {
                style.background_color
            } else {
                None
            },
            text_decoration: style.text_decoration,
            href: style.get_custom_property(strata_primitives::AtomId::HREF),
        }
    }

    #[inline]
    fn inherit_into(self, child: &strata_style::types::ComputedStyle) -> Self {
        let font_family = if child.font_family == strata_primitives::AtomId::FONT_SANS
            && self.font_family != strata_primitives::AtomId::FONT_SANS
        {
            self.font_family
        } else {
            child.font_family
        };
        let background_color = if child.display == strata_style::types::Display::Inline {
            child.background_color.or(self.background_color)
        } else {
            None
        };
        let text_decoration = if child.text_decoration == strata_style::types::TextDecoration::None
        {
            self.text_decoration
        } else {
            child.text_decoration
        };
        let href = child
            .get_custom_property(strata_primitives::AtomId::HREF)
            .or(self.href);
        Self {
            font_family,
            background_color,
            text_decoration,
            href,
        }
    }
}

struct InlineCollectFrame<'a> {
    children: &'a [LayoutNode],
    idx: usize,
    inherited: Option<InheritedInlineStyle>,
    top_idx: Option<usize>,
    depth: usize,
}

/// Iteratively flattens inline phrasing children into an InlineItem stream (`O(1)` call stack,
/// bounded by `MAX_LAYOUT_DEPTH`, zero `ComputedStyle::clone()` stack allocations).
fn collect_inline_items_from_children(
    children: &[LayoutNode],
    parent_style: Option<&strata_style::types::ComputedStyle>,
    top_level_idx: Option<usize>,
    items: &mut Vec<crate::typography::InlineItem>,
    content_width: f32,
    available_height: f32,
) {
    let _prof = crate::prof::Scope::new(crate::prof::Slot::StyleClone);
    let init_inherited = parent_style.map(InheritedInlineStyle::from_style);
    let mut stack = vec![InlineCollectFrame {
        children,
        idx: 0,
        inherited: init_inherited,
        top_idx: top_level_idx,
        depth: 0,
    }];

    while let Some(frame) = stack.last_mut() {
        if frame.idx >= frame.children.len() {
            stack.pop();
            continue;
        }
        let child_idx = frame.idx;
        let child = &frame.children[child_idx];
        frame.idx += 1;

        if child.style.display == strata_style::types::Display::None {
            continue;
        }
        let effective_top_idx = frame.top_idx.unwrap_or(child_idx);
        let cur_inherited = frame.inherited;
        let cur_depth = frame.depth;

        if let Some(ref text) = child.text {
            let mut s = inline_style_from_computed_style(&child.style);
            if let Some(p) = cur_inherited {
                if child.style.font_family == strata_primitives::AtomId::FONT_SANS
                    && p.font_family != strata_primitives::AtomId::FONT_SANS
                {
                    s.font_family = p.font_family;
                    s.is_monospace = crate::text::is_monospace_family(p.font_family);
                }
                if s.background_color.is_none() {
                    s.background_color = p.background_color;
                }
                if s.text_decoration == strata_style::types::TextDecoration::None
                    && p.text_decoration != strata_style::types::TextDecoration::None
                {
                    s.text_decoration = p.text_decoration;
                }
                if s.href.is_none() {
                    s.href = p.href.and_then(strata_primitives::atom::resolve);
                }
            }
            items.push(crate::typography::InlineItem::text(text.clone(), s));
        } else if child.style.display == strata_style::types::Display::Inline
            && !child.children.is_empty()
        {
            if cur_depth < crate::tree::MAX_LAYOUT_DEPTH {
                let merged = match cur_inherited {
                    Some(p) => p.inherit_into(&child.style),
                    None => InheritedInlineStyle::from_style(&child.style),
                };
                stack.push(InlineCollectFrame {
                    children: child.children.as_slice(),
                    idx: 0,
                    inherited: Some(merged),
                    top_idx: Some(effective_top_idx),
                    depth: cur_depth + 1,
                });
            }
        } else {
            let mut w =
                resolve_dimension_with_node(child.style.width, content_width, child).unwrap_or(0.0);
            let mut h = resolve_dimension(child.style.height, available_height).unwrap_or(0.0);
            if w == 0.0 && child.geometry.border_box.width > 0.0 {
                w = child.geometry.border_box.width;
            }
            if h == 0.0 && child.geometry.border_box.height > 0.0 {
                h = child.geometry.border_box.height;
            }
            if h == 0.0 && w > 0.0 && child.children.is_empty() {
                // Under W3C CSS 2.1 ยง10.6.2, replaced/atomic elements with auto height default to 1:1 aspect ratio
                h = w;
            }
            items.push(crate::typography::InlineItem::atomic(
                effective_top_idx,
                w,
                h,
                child.style.margin.left,
                child.style.margin.right,
                crate::typography::VerticalAlignment::Baseline,
            ));
        }
    }
}

/// Recursively propagates atomic inline fragment bounds down through nested `Display::Inline` containers using an iterative heap stack.
fn propagate_atomic_bounds_to_inline_descendants(node: &mut LayoutNode, bounds: Rect) {
    if node.style.display != strata_style::types::Display::Inline {
        return;
    }
    let mut stack = vec![node];
    while let Some(curr) = stack.pop() {
        for child in &mut curr.children {
            child.geometry.border_box.x = bounds.x;
            child.geometry.border_box.y = bounds.y;
            if child.geometry.border_box.width == 0.0 {
                child.geometry.border_box.width = bounds.width;
            }
            if child.geometry.border_box.height == 0.0 {
                child.geometry.border_box.height = bounds.height;
            }
            if child.style.display == strata_style::types::Display::Inline {
                stack.push(child);
            }
        }
    }
}

/// Recursively translates layout geometry and line box fragments of a node and its descendants.
pub fn translate_node_and_descendants(node: &mut LayoutNode, dx: f32, dy: f32) {
    if dx == 0.0 && dy == 0.0 {
        return;
    }
    node.translate(dx, dy);
}

/// Applies `text-overflow: ellipsis` to the laid-out inline stream.
///
/// Only clipping containers are eligible. When a line's text extends past the
/// content width, the fragment that crosses the boundary is cut at the last
/// character boundary that leaves room for U+2026 HORIZONTAL ELLIPSIS, and the
/// remaining fragments on that line are discarded. This mirrors the single
/// line truncation produced by `overflow: hidden; text-overflow: ellipsis;
/// white-space: nowrap`.
fn truncate_inline_overflow(
    node: &LayoutNode,
    res: &mut crate::typography::InlineLayoutResult,
    content_width: f32,
) {
    use strata_style::types::{Overflow, TextOverflow};

    if node.style.text_overflow != TextOverflow::Ellipsis
        || node.style.overflow_x == Overflow::Visible
        || content_width <= 0.0
    {
        return;
    }

    for line in &mut res.lines {
        let mut new_fragments = Vec::with_capacity(line.text_fragments.len());
        let mut cut = false;
        for fragment in line.text_fragments.drain(..) {
            if cut {
                continue;
            }
            let frag_start = fragment.bounds.x;
            let frag_end = frag_start + fragment.bounds.width;
            if frag_end <= content_width + 1.0 {
                new_fragments.push(fragment);
                continue;
            }

            let available = content_width - frag_start;
            if available <= 0.0 {
                cut = true;
                continue;
            }

            let style = &fragment.style;
            let multiplier = match style.line_height {
                Some(line_h) if style.font_size > 0.0 => (line_h / style.font_size).max(0.01),
                _ => 1.2,
            };
            let measure = |text: &str| {
                crate::text::measure_text_bounds_styled_with_family(
                    text,
                    style.font_size,
                    multiplier,
                    None,
                    style.is_monospace,
                    style.font_family,
                    style.font_weight,
                    style.font_style,
                )
                .0
            };

            let ellipsis_width = measure("\u{2026}");
            if ellipsis_width > available {
                cut = true;
                continue;
            }

            // Binary search the largest character-boundary prefix that fits
            // alongside the ellipsis within the available width.
            let boundaries: Vec<usize> = fragment
                .text
                .char_indices()
                .map(|(idx, _)| idx)
                .chain(std::iter::once(fragment.text.len()))
                .collect();
            let mut low = 0usize;
            let mut high = boundaries.len().saturating_sub(1);
            let mut best = 0usize;
            while low <= high {
                let mid = (low + high) / 2;
                let end = boundaries[mid];
                let prefix = &fragment.text[..end];
                if measure(prefix) + ellipsis_width <= available + 0.01 {
                    best = mid;
                    low = mid + 1;
                } else if mid == 0 {
                    break;
                } else {
                    high = mid - 1;
                }
            }

            let end = boundaries[best];
            let mut text = fragment.text[..end].to_string();
            text.push('\u{2026}');
            let width = measure(&text);
            let mut truncated_fragment = fragment;
            truncated_fragment.text = text;
            truncated_fragment.bounds.width = width;
            new_fragments.push(truncated_fragment);
            cut = true;
        }

        if let Some(last) = new_fragments.last() {
            line.bounds.width = last.bounds.x + last.bounds.width;
        } else {
            line.bounds.width = 0.0;
        }
        line.text_fragments = new_fragments;
    }

    res.total_width = res
        .lines
        .iter()
        .map(|line| line.bounds.width)
        .fold(0.0f32, f32::max);
}

/// Positions in-flow block children vertically with CSS 2.1 ยง8.3.1 margin collapsing, IFC, and floats.
pub fn solve_block_children(
    node: &mut LayoutNode,
    content_width: f32,
    available_height: f32,
) -> f32 {
    solve_block_children_with_exclusions(node, content_width, available_height, None, 0.0)
}

/// Positions in-flow block children with active exclusion space tracking and float dispatch.
pub fn solve_block_children_with_exclusions(
    node: &mut LayoutNode,
    content_width: f32,
    available_height: f32,
    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
) -> f32 {
    solve_block_children_with_exclusions_guarded(
        node,
        content_width,
        available_height,
        parent_exclusions,
        bfc_offset_y,
        crate::tree::LayoutDepthGuard::root(),
    )
}

/// Returns true if an in-flow block element has zero computed height, no padding or border,
/// and no in-flow content, allowing its top and bottom margins to collapse through under CSS 2.1 ยง8.3.1.
#[inline]
pub fn is_empty_collapsible_block(node: &LayoutNode) -> bool {
    node.children.is_empty()
        && node.text.is_none()
        && node.inline_items.is_empty()
        && node.style.border_width.top == 0.0
        && node.style.border_width.bottom == 0.0
        && node.style.padding.top == 0.0
        && node.style.padding.bottom == 0.0
        && matches!(node.style.height, Dimension::Auto | Dimension::Px(0.0))
        && matches!(node.style.min_height, Dimension::Auto | Dimension::Px(0.0))
        && node.style.clear == strata_style::types::Clear::None
        && node.style.float == strata_style::types::Float::None
        && node.style.overflow_x == strata_style::types::Overflow::Visible
        && node.style.overflow_y == strata_style::types::Overflow::Visible
}

/// Returns true if an element establishes an independent formatting context (BFC, FFC, GFC),
/// preventing margin collapsing across its boundaries under W3C CSS 2.1 ยง8.3.1 and CSS Display Level 3.
#[inline]
pub fn node_establishes_bfc(node: &LayoutNode) -> bool {
    node.style.float != strata_style::types::Float::None
        || matches!(node.style.position, Position::Absolute | Position::Fixed)
        || matches!(
            node.style.display,
            strata_style::types::Display::InlineBlock
                | strata_style::types::Display::TableCell
                | strata_style::types::Display::TableCaption
                | strata_style::types::Display::Flex
                | strata_style::types::Display::Grid
                | strata_style::types::Display::InlineFlex
                | strata_style::types::Display::InlineGrid
                | strata_style::types::Display::Table
                | strata_style::types::Display::InlineTable
        )
        || node.style.overflow_x != strata_style::types::Overflow::Visible
        || node.style.overflow_y != strata_style::types::Overflow::Visible
        || node.style.contain.layout
        || child_is_layout_boundary(node)
}

#[inline]
fn child_is_layout_boundary(node: &LayoutNode) -> bool {
    node.is_layout_boundary()
}

/// Positions in-flow block children with active exclusion space tracking and depth guard.
#[inline(never)]
fn layout_ellipsis_text_leaf_children(node: &mut LayoutNode, content_width: f32) -> Option<f32> {
    let text = node.text.clone()?;
    let padding = node.style.padding;
    let border = node.style.border_width;
    let style = inline_style_from_computed_style(&node.style);
    let items = vec![crate::typography::InlineItem::text(text, style)];
    let opt = crate::typography::InlineLayoutOptions {
        font_size: node.style.font_size,
        line_height: Some(node.style.font_size * node.style.line_height),
        max_width: Some(content_width),
        white_space: match node.style.white_space {
            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
        },
        vertical_align: crate::typography::VerticalAlignment::Baseline,
        is_monospace: crate::text::is_monospace_family(node.style.font_family),
        exclusion_space: None,
        bfc_offset_y: 0.0,
    };
    let ifc = crate::typography::InlineFormattingContext::new();
    let mut res = ifc.layout_inline_stream(&items, &opt);
    truncate_inline_overflow(node, &mut res, content_width);

    let origin_x = node.geometry.border_box.x + border.left + padding.left;
    let origin_y = node.geometry.border_box.y + border.top + padding.top;
    let mut lines = res.lines;
    for line in &mut lines {
        line.bounds.x += origin_x;
        line.bounds.y += origin_y;
        for frag in &mut line.text_fragments {
            frag.bounds.x += origin_x;
            frag.bounds.y += origin_y;
            frag.baseline_y += origin_y;
        }
        for atomic in &mut line.atomic_fragments {
            atomic.bounds.x += origin_x;
            atomic.bounds.y += origin_y;
        }
    }
    let total_h = res.total_height;
    node.inline_items = items;
    node.line_boxes = lines;
    Some(total_h + padding.top + padding.bottom + border.top + border.bottom)
}

#[inline(never)]
fn finish_ifc_inline_layout(
    node: &mut LayoutNode,
    content_width: f32,
    parent_exclusions: Option<&crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
) -> f32 {
    let padding = node.style.padding;
    let border = node.style.border_width;
    let ifc = crate::typography::InlineFormattingContext::new();
    let opt = crate::typography::InlineLayoutOptions {
        font_size: node.style.font_size,
        line_height: Some(node.style.font_size * node.style.line_height),
        max_width: Some(content_width),
        white_space: match node.style.white_space {
            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
        },
        vertical_align: match node.style.vertical_align {
            strata_style::types::VerticalAlign::Baseline => {
                crate::typography::VerticalAlignment::Baseline
            }
            strata_style::types::VerticalAlign::Top => crate::typography::VerticalAlignment::Top,
            strata_style::types::VerticalAlign::Bottom => {
                crate::typography::VerticalAlignment::Bottom
            }
            strata_style::types::VerticalAlign::Middle => {
                crate::typography::VerticalAlignment::Middle
            }
            strata_style::types::VerticalAlign::Sub => crate::typography::VerticalAlignment::Sub,
            strata_style::types::VerticalAlign::Super => {
                crate::typography::VerticalAlignment::Super
            }
            strata_style::types::VerticalAlign::TextTop => {
                crate::typography::VerticalAlignment::TextTop
            }
            strata_style::types::VerticalAlign::TextBottom => {
                crate::typography::VerticalAlignment::TextBottom
            }
        },
        is_monospace: crate::text::is_monospace_family(node.style.font_family),
        exclusion_space: parent_exclusions,
        bfc_offset_y: bfc_offset_y + padding.top + border.top,
    };

    let mut res = ifc.layout_inline_stream(&node.inline_items, &opt);
    truncate_inline_overflow(node, &mut res, content_width);
    let content_origin_x = node.geometry.border_box.x + border.left + padding.left;
    let content_origin_y = node.geometry.border_box.y + border.top + padding.top;

    let mut positioned_lines = res.lines;
    for line in &mut positioned_lines {
        let align_offset_x = match node.style.text_align {
            strata_style::types::TextAlign::Center => {
                ((content_width - line.bounds.width) / 2.0).max(0.0)
            }
            strata_style::types::TextAlign::Right => (content_width - line.bounds.width).max(0.0),
            _ => 0.0,
        };

        let total_shift_x = content_origin_x + align_offset_x;
        line.bounds.x += total_shift_x;
        line.bounds.y += content_origin_y;
        for frag in &mut line.text_fragments {
            frag.bounds.x += total_shift_x;
            frag.bounds.y += content_origin_y;
            frag.baseline_y += content_origin_y;
        }
        for at in &mut line.atomic_fragments {
            at.bounds.x += total_shift_x;
            at.bounds.y += content_origin_y;
            if at.node_index < node.children.len() {
                let child = &mut node.children[at.node_index];
                let dx = at.bounds.x - child.geometry.border_box.x;
                let dy = at.bounds.y - child.geometry.border_box.y;
                child.geometry.border_box.width = at.bounds.width;
                child.geometry.border_box.height = at.bounds.height;
                child.translate(dx, dy);

                let target_bounds = child.geometry.border_box;
                propagate_atomic_bounds_to_inline_descendants(child, target_bounds);
            }
        }
    }

    let total_h = res.total_height;
    for child in &mut node.children {
        if let Some(ref text) = child.text {
            let mut found = false;
            for line in &positioned_lines {
                for frag in &line.text_fragments {
                    if frag.text.contains(text.as_str()) || text.contains(frag.text.as_str()) {
                        child.geometry.border_box = frag.bounds;
                        found = true;
                        break;
                    }
                }
                if found {
                    break;
                }
            }
            if !found {
                child.geometry.border_box.x = content_origin_x;
                child.geometry.border_box.y = content_origin_y;
            }
        }
    }
    node.line_boxes = positioned_lines;
    total_h + padding.top + padding.bottom + border.top + border.bottom
}

pub fn solve_block_children_with_exclusions_guarded(
    node: &mut LayoutNode,
    content_width: f32,
    available_height: f32,
    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
    guard: crate::tree::LayoutDepthGuard,
) -> f32 {
    let _prof = crate::prof::Scope::new(crate::prof::Slot::Block);
    let padding = node.style.padding;
    let border = node.style.border_width;

    if guard.is_exhausted() {
        crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
        return padding.top + border.top + padding.bottom + border.bottom;
    }

    if node.children.is_empty()
        && node.inline_items.is_empty()
        && node.style.text_overflow == strata_style::types::TextOverflow::Ellipsis
    {
        if let Some(h) = layout_ellipsis_text_leaf_children(node, content_width) {
            return h;
        }
    }

    // Check if this container establishes an Inline Formatting Context (IFC)
    let has_implicit_inlines =
        !node.children.is_empty() && node.children.iter().all(is_inline_phrasing_node);
    let has_explicit_inlines = node.children.is_empty() && !node.inline_items.is_empty();

    if has_explicit_inlines || has_implicit_inlines {
        if has_implicit_inlines {
            let child_guard = guard.enter();
            for child in &mut node.children {
                if let Some(cg) = child_guard {
                    child.compute_layout_guarded(content_width, available_height, None, 0.0, cg);
                } else {
                    child.compute_layout_guarded(content_width, available_height, None, 0.0, guard);
                }
                clear_inline_descendant_line_boxes(child);
            }
            let mut items = Vec::new();
            collect_inline_items_from_children(
                &node.children,
                None,
                None,
                &mut items,
                content_width,
                available_height,
            );
            node.inline_items = items;
        }
        return finish_ifc_inline_layout(
            node,
            content_width,
            parent_exclusions.as_deref(),
            bfc_offset_y,
        );
    }

    // W3C CSS 2.1 ยง9.4.1 Block Formatting Context (BFC) root determination:
    // Normal in-flow block boxes with overflow: visible share their parent BFC's ExclusionSpace
    // so floats inside a <section> or <div> overhang into subsequent sibling sections.
    let establishes_bfc = node_establishes_bfc(node);

    let is_root_exclusion_context = parent_exclusions.is_none();
    let mut local_exclusions = crate::exclusions::ExclusionSpace::new();
    let (exclusion_space, base_bfc_y): (&mut crate::exclusions::ExclusionSpace, f32) =
        if establishes_bfc || is_root_exclusion_context {
            (&mut local_exclusions, 0.0)
        } else if let Some(pe) = parent_exclusions {
            (pe, bfc_offset_y)
        } else {
            (&mut local_exclusions, 0.0)
        };
    let initial_exclusions_count = exclusion_space.exclusions().len();
    let parent_top_adjoining = !establishes_bfc && border.top == 0.0 && padding.top == 0.0;
    let parent_bottom_adjoining = !establishes_bfc
        && border.bottom == 0.0
        && padding.bottom == 0.0
        && node.style.height == Dimension::Auto;

    let mut current_y = border.top + padding.top;
    let mut pending_margin: Option<f32> = None;
    let mut is_first_in_flow = true;
    let mut last_child_establishes_bfc = false;

    for child in &mut node.children {
        if child.style.position == Position::Absolute || child.style.position == Position::Fixed {
            continue;
        }

        // Handle CSS clear in BFC coordinate space for in-flow blocks
        if child.style.float == strata_style::types::Float::None
            && child.style.clear != strata_style::types::Clear::None
        {
            let cleared_bfc_y =
                exclusion_space.clearance_offset(child.style.clear, base_bfc_y + current_y);
            if cleared_bfc_y > base_bfc_y + current_y {
                current_y = cleared_bfc_y - base_bfc_y;
                pending_margin = None;
            }
        }

        // Handle CSS float
        if child.style.float != strata_style::types::Float::None {
            // Layout float child as an independent BFC to compute its dimensions
            let child_guard = guard.enter();
            if let Some(cg) = child_guard {
                child.compute_layout_guarded(content_width, available_height, None, 0.0, cg);
            } else {
                child.compute_layout_guarded(content_width, available_height, None, 0.0, guard);
            }
            let float_margin = child.style.margin;
            let float_w = child.geometry.border_box.width + float_margin.left + float_margin.right;
            let float_h = child.geometry.border_box.height + float_margin.top + float_margin.bottom;

            // Query line opportunity at float_bfc_y in BFC coordinate space, respecting float's own clearance
            let mut float_bfc_y = base_bfc_y + current_y;
            if child.style.clear != strata_style::types::Clear::None {
                let cleared_bfc_y =
                    exclusion_space.clearance_offset(child.style.clear, float_bfc_y);
                if cleared_bfc_y > float_bfc_y {
                    float_bfc_y = cleared_bfc_y;
                }
            }
            let mut opp = exclusion_space.line_opportunity(float_bfc_y, float_h, content_width);
            if opp.available_width < float_w && content_width >= float_w {
                // Drop down if float does not fit horizontally
                while let Some(next_bfc_y) = exclusion_space.next_float_bottom_after(float_bfc_y) {
                    float_bfc_y = next_bfc_y;
                    opp = exclusion_space.line_opportunity(float_bfc_y, float_h, content_width);
                    if opp.available_width >= float_w {
                        break;
                    }
                }
            }
            let local_float_y = float_bfc_y - base_bfc_y;

            let (target_x, target_y) = match child.style.float {
                strata_style::types::Float::Left | strata_style::types::Float::InlineStart => {
                    let float_x =
                        border.left + padding.left + opp.left_float_edge + float_margin.left;
                    let float_y = local_float_y + float_margin.top;
                    let excl_rect = crate::geometry::Rect::from_xywh(
                        opp.left_float_edge,
                        float_bfc_y,
                        float_w,
                        float_h,
                    );
                    exclusion_space
                        .add_exclusion(excl_rect, crate::exclusions::ExclusionKind::FloatLeft);
                    (
                        node.geometry.border_box.x + float_x,
                        node.geometry.border_box.y + float_y,
                    )
                }
                strata_style::types::Float::Right | strata_style::types::Float::InlineEnd => {
                    let start_r = opp.right_float_edge;
                    let float_x =
                        border.left + padding.left + start_r - float_w + float_margin.left;
                    let float_y = local_float_y + float_margin.top;
                    let excl_rect = crate::geometry::Rect::from_xywh(
                        start_r - float_w,
                        float_bfc_y,
                        float_w,
                        float_h,
                    );
                    exclusion_space
                        .add_exclusion(excl_rect, crate::exclusions::ExclusionKind::FloatRight);
                    (
                        node.geometry.border_box.x + float_x,
                        node.geometry.border_box.y + float_y,
                    )
                }
                strata_style::types::Float::None => unreachable!(),
            };

            let old_x = child.geometry.border_box.x;
            let old_y = child.geometry.border_box.y;
            let dx = target_x - old_x;
            let dy = target_y - old_y;
            translate_node_and_descendants(child, dx, dy);

            // Floats do not advance in-flow block cursor or participate in margin collapsing
            continue;
        }

        let child_margin = child.style.margin;

        // CSS 2.1 ยง8.3.1: An empty block's top and bottom margins collapse through
        if is_empty_collapsible_block(child) {
            let through_margin = collapse_margins(child_margin.top, child_margin.bottom);
            let combined = match pending_margin {
                Some(pm) => collapse_margins(pm, through_margin),
                None => through_margin,
            };

            if is_first_in_flow && parent_top_adjoining {
                node.style.margin.top = collapse_margins(node.style.margin.top, combined);
                pending_margin = None;
            } else {
                pending_margin = Some(combined);
            }

            child.geometry.border_box.x =
                node.geometry.border_box.x + border.left + padding.left + child_margin.left;
            child.geometry.border_box.y =
                node.geometry.border_box.y + current_y + pending_margin.unwrap_or(0.0);
            child.geometry.border_box.width = content_width;
            child.geometry.border_box.height = 0.0;
            continue;
        }

        let child_establishes_bfc = node_establishes_bfc(child);

        let mut collapsed_v_margin = match pending_margin.take() {
            Some(prev_m) => collapse_margins(prev_m, child_margin.top),
            None => child_margin.top,
        };

        if is_first_in_flow {
            is_first_in_flow = false;
            if parent_top_adjoining && !child_establishes_bfc {
                node.style.margin.top = collapse_margins(node.style.margin.top, collapsed_v_margin);
                collapsed_v_margin = 0.0;
            }
        }

        current_y += collapsed_v_margin;

        let mut child_available_width = content_width;
        let mut child_x = border.left + padding.left + child_margin.left;

        // CSS 2.1 ยง9.5: An in-flow element that establishes a new BFC must not overlap the margin box of any floats in the same BFC
        if child_establishes_bfc && !exclusion_space.exclusions().is_empty() {
            let mut child_bfc_y = base_bfc_y + current_y;
            let mut opp = exclusion_space.line_opportunity(child_bfc_y, 0.0, content_width);

            if opp.available_width < content_width || opp.left_float_edge > 0.0 {
                let child_desired_w =
                    resolve_dimension_with_node(child.style.width, content_width, child);
                if let Some(w) = child_desired_w {
                    if w + child_margin.left + child_margin.right > opp.available_width {
                        // Element does not fit beside the float; clear by placing it below preceding floats
                        while let Some(next_y) =
                            exclusion_space.next_float_bottom_after(child_bfc_y)
                        {
                            child_bfc_y = next_y;
                            opp = exclusion_space.line_opportunity(child_bfc_y, 0.0, content_width);
                            if opp.available_width >= w + child_margin.left + child_margin.right {
                                break;
                            }
                        }
                        current_y = child_bfc_y - base_bfc_y;
                    }
                }

                child_available_width =
                    (opp.available_width - child_margin.left - child_margin.right).max(0.0);
                child_x = border.left + padding.left + opp.left_float_edge + child_margin.left;
            }
        }

        child.geometry.border_box.x = node.geometry.border_box.x + child_x;
        child.geometry.border_box.y = node.geometry.border_box.y + current_y;

        // Pass the active BFC exclusion space down to in-flow block children so floats can overhang across sections,
        // EXCEPT when child establishes its own BFC or exclusion space is currently empty.
        let passed_exclusions = if child_establishes_bfc || exclusion_space.exclusions().is_empty()
        {
            None
        } else {
            Some(&mut *exclusion_space)
        };

        let child_guard = guard.enter();
        if let Some(cg) = child_guard {
            child.compute_layout_guarded(
                child_available_width,
                available_height,
                passed_exclusions,
                base_bfc_y + current_y,
                cg,
            );
        } else {
            child.compute_layout_guarded(
                child_available_width,
                available_height,
                passed_exclusions,
                base_bfc_y + current_y,
                guard,
            );
        }

        // Auto margin horizontal centering (mx-auto / ml-auto / mr-auto)
        if child.style.margin_auto_left && child.style.margin_auto_right {
            let free_space = child_available_width - child.geometry.border_box.width;
            let auto_m = (free_space / 2.0).max(0.0);
            let target_x = node.geometry.border_box.x + child_x - child_margin.left + auto_m;
            let dx = target_x - child.geometry.border_box.x;
            if dx != 0.0 {
                translate_node_and_descendants(child, dx, 0.0);
            }
        } else if child.style.margin_auto_left {
            let free_space =
                child_available_width - child.geometry.border_box.width - child_margin.right;
            let target_x =
                node.geometry.border_box.x + child_x - child_margin.left + free_space.max(0.0);
            let dx = target_x - child.geometry.border_box.x;
            if dx != 0.0 {
                translate_node_and_descendants(child, dx, 0.0);
            }
        } else if node.style.text_align == strata_style::types::TextAlign::Center {
            let free_space = content_width - child.geometry.border_box.width;
            if free_space > 0.0 {
                let offset_x = (free_space / 2.0).max(0.0);
                let target_x = node.geometry.border_box.x + border.left + padding.left + offset_x;
                let dx = target_x - child.geometry.border_box.x;
                if dx != 0.0 {
                    translate_node_and_descendants(child, dx, 0.0);
                }
            }
        } else if node.style.text_align == strata_style::types::TextAlign::Right {
            let free_space = content_width - child.geometry.border_box.width;
            if free_space > 0.0 {
                let target_x = node.geometry.border_box.x + border.left + padding.left + free_space;
                let dx = target_x - child.geometry.border_box.x;
                if dx != 0.0 {
                    translate_node_and_descendants(child, dx, 0.0);
                }
            }
        }

        current_y += child.geometry.border_box.height;
        pending_margin = Some(child_margin.bottom);
        last_child_establishes_bfc = child_establishes_bfc;
    }

    if let Some(trailing_margin) = pending_margin {
        if parent_bottom_adjoining && !last_child_establishes_bfc {
            node.style.margin.bottom = collapse_margins(node.style.margin.bottom, trailing_margin);
        } else {
            current_y += trailing_margin;
        }
    }

    // CSS 2.1 ยง10.6.7 BFC float containment: BFC roots or layout tree root expand auto height to enclose floats
    if (establishes_bfc || is_root_exclusion_context)
        && exclusion_space.exclusions().len() > initial_exclusions_count
    {
        let max_float_bottom = exclusion_space.max_float_bottom();
        if max_float_bottom > current_y {
            current_y = max_float_bottom;
        }
    }

    current_y += padding.bottom + border.bottom;

    current_y
}

/// Executes normal-flow block layout with vertical margin collapsing.
pub fn solve_block(node: &mut LayoutNode, available_width: f32, available_height: f32) {
    solve_block_with_exclusions_guarded(
        node,
        available_width,
        available_height,
        None,
        0.0,
        crate::tree::LayoutDepthGuard::root(),
    );
}

/// Executes normal-flow block layout passing parent exclusion space for float obstructions.
pub fn solve_block_with_exclusions(
    node: &mut LayoutNode,
    available_width: f32,
    available_height: f32,
    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
) {
    solve_block_with_exclusions_guarded(
        node,
        available_width,
        available_height,
        parent_exclusions,
        bfc_offset_y,
        crate::tree::LayoutDepthGuard::root(),
    );
}

#[cold]
#[inline(never)]
fn solve_block_depth_exhausted(
    node: &mut LayoutNode,
    available_width: f32,
    available_height: f32,
    guard: crate::tree::LayoutDepthGuard,
) {
    crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
    let padding = node.style.padding;
    let border = node.style.border_width;
    let margin = node.style.margin;
    let border_box_width =
        match resolve_dimension_with_node(node.style.width, available_width, node) {
            Some(w) => clamp_dimension_with_node(
                w,
                node.style.min_width,
                node.style.max_width,
                available_width,
                node,
            ),
            None => (available_width - margin.left - margin.right).max(0.0),
        };
    let border_box_height = match resolve_dimension(node.style.height, available_height) {
        Some(h) => clamp_dimension(
            h,
            node.style.min_height,
            node.style.max_height,
            available_height,
        ),
        None => 0.0,
    };
    let border_box = Rect::new(
        node.geometry.border_box.x,
        node.geometry.border_box.y,
        border_box_width,
        border_box_height,
    );
    node.geometry = LayoutGeometry::from_border_box(border_box, padding, border, margin);
    node.geometry.snap_to_pixel();
}

#[cold]
#[inline(never)]
fn solve_block_content_visibility_hidden(
    node: &mut LayoutNode,
    available_width: f32,
    available_height: f32,
) {
    let padding = node.style.padding;
    let border = node.style.border_width;
    let margin = node.style.margin;
    let intrinsic_w = node
        .style
        .contain_intrinsic_width
        .and_then(|dim| resolve_dimension_with_node(dim, available_width, node));
    let intrinsic_h = node
        .style
        .contain_intrinsic_height
        .and_then(|dim| resolve_dimension(dim, available_height))
        .unwrap_or(0.0);
    let border_box_width =
        match resolve_dimension_with_node(node.style.width, available_width, node).or(intrinsic_w) {
            Some(w) => clamp_dimension_with_node(
                w,
                node.style.min_width,
                node.style.max_width,
                available_width,
                node,
            ),
            None => (available_width - margin.left - margin.right).max(0.0),
        };
    let border_box_height = match resolve_dimension(node.style.height, available_height) {
        Some(h) => clamp_dimension(
            h,
            node.style.min_height,
            node.style.max_height,
            available_height,
        ),
        None => clamp_dimension(
            intrinsic_h,
            node.style.min_height,
            node.style.max_height,
            available_height,
        ),
    };
    let border_box = Rect::new(
        node.geometry.border_box.x,
        node.geometry.border_box.y,
        border_box_width,
        border_box_height,
    );
    node.geometry = LayoutGeometry::from_border_box(border_box, padding, border, margin);
    node.geometry.snap_to_pixel();
}

#[inline(never)]
fn measure_block_leaf_inline_or_text(
    node: &LayoutNode,
    text_avail_w: f32,
    parent_exclusions: Option<&crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
) -> (f32, f32) {
    if node.children.is_empty() && !node.inline_items.is_empty() {
        let ifc = crate::typography::InlineFormattingContext::new();
        let opt = crate::typography::InlineLayoutOptions {
            font_size: node.style.font_size,
            line_height: Some(node.style.font_size * node.style.line_height),
            max_width: Some(text_avail_w),
            white_space: match node.style.white_space {
                strata_style::types::WhiteSpace::Normal => {
                    crate::typography::WhiteSpaceMode::Normal
                }
                strata_style::types::WhiteSpace::NoWrap => {
                    crate::typography::WhiteSpaceMode::NoWrap
                }
                strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
                strata_style::types::WhiteSpace::PreWrap => {
                    crate::typography::WhiteSpaceMode::PreWrap
                }
                strata_style::types::WhiteSpace::PreLine => {
                    crate::typography::WhiteSpaceMode::PreLine
                }
            },
            vertical_align: crate::typography::VerticalAlignment::Baseline,
            is_monospace: crate::text::is_monospace_family(node.style.font_family),
            exclusion_space: parent_exclusions,
            bfc_offset_y,
        };
        let res = ifc.layout_inline_stream(&node.inline_items, &opt);
        (res.total_width, res.total_height)
    } else if let Some(ref text) = node.text {
        let is_mono = crate::text::is_monospace_family(node.style.font_family);
        crate::text::measure_text_bounds_with_white_space(
            text,
            node.style.font_size,
            node.style.line_height,
            Some(text_avail_w),
            is_mono,
            node.style.white_space,
        )
    } else {
        (0.0, 0.0)
    }
}

#[inline(never)]
fn finalize_block_geometry(node: &mut LayoutNode, border_box_width: f32, border_box_height: f32) {
    let border_box = Rect::new(
        node.geometry.border_box.x,
        node.geometry.border_box.y,
        border_box_width,
        border_box_height,
    );
    node.geometry = LayoutGeometry::from_border_box(
        border_box,
        node.style.padding,
        node.style.border_width,
        node.style.margin,
    );
    node.geometry.snap_to_pixel();
}

#[inline(never)]
fn publish_truncated_ellipsis_text_leaf(node: &mut LayoutNode, content_width: f32) {
    let Some(ref text) = node.text else {
        return;
    };
    let inline_style = inline_style_from_computed_style(&node.style);
    let item = crate::typography::InlineItem::text(text.clone(), inline_style);
    let ifc = crate::typography::InlineFormattingContext::new();
    let opt = crate::typography::InlineLayoutOptions {
        font_size: node.style.font_size,
        line_height: Some(node.style.font_size * node.style.line_height),
        max_width: Some(content_width),
        white_space: match node.style.white_space {
            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
        },
        vertical_align: crate::typography::VerticalAlignment::Baseline,
        is_monospace: crate::text::is_monospace_family(node.style.font_family),
        exclusion_space: None,
        bfc_offset_y: 0.0,
    };
    let mut res = ifc.layout_inline_stream(&[item], &opt);
    truncate_inline_overflow(node, &mut res, content_width);
    let origin_x = node.geometry.content_box.x;
    let origin_y = node.geometry.content_box.y;
    for line in &mut res.lines {
        let align_offset_x = match node.style.text_align {
            strata_style::types::TextAlign::Center => {
                ((content_width - line.bounds.width) / 2.0).max(0.0)
            }
            strata_style::types::TextAlign::Right => (content_width - line.bounds.width).max(0.0),
            _ => 0.0,
        };
        line.bounds.x += origin_x + align_offset_x;
        line.bounds.y += origin_y;
        for frag in &mut line.text_fragments {
            frag.bounds.x += origin_x + align_offset_x;
            frag.bounds.y += origin_y;
            frag.baseline_y += origin_y;
        }
    }
    node.line_boxes = res.lines;
}

/// Executes normal-flow block layout with an active depth guard to prevent stack overflow.
pub fn solve_block_with_exclusions_guarded(
    node: &mut LayoutNode,
    available_width: f32,
    available_height: f32,
    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
    bfc_offset_y: f32,
    guard: crate::tree::LayoutDepthGuard,
) {
    if guard.is_exhausted() {
        solve_block_depth_exhausted(node, available_width, available_height, guard);
        return;
    }

    // Content-Visibility: Hidden virtualization (W3C CSS Containment Level 2)
    if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
        solve_block_content_visibility_hidden(node, available_width, available_height);
        return;
    }

    let padding = node.style.padding;
    let border = node.style.border_width;
    let margin = node.style.margin;

    let inset_h = padding.left + padding.right + border.left + border.right;
    let avail_border_w = (available_width - margin.left - margin.right).max(0.0);
    let max_border_limit = if let Some(explicit_w) =
        resolve_dimension_with_node(node.style.width, available_width, node)
    {
        let clamped = clamp_dimension_with_node(
            explicit_w,
            node.style.min_width,
            node.style.max_width,
            available_width,
            node,
        );
        match node.style.box_sizing {
            BoxSizing::BorderBox => clamped,
            BoxSizing::ContentBox => clamped + inset_h,
        }
    } else {
        let mut limit = avail_border_w;
        if let Some(max_w) =
            resolve_dimension_with_node(node.style.max_width, available_width, node)
        {
            let max_border = match node.style.box_sizing {
                BoxSizing::BorderBox => max_w,
                BoxSizing::ContentBox => max_w + inset_h,
            };
            limit = limit.min(max_border.max(0.0));
        }
        if let Some(min_w) =
            resolve_dimension_with_node(node.style.min_width, available_width, node)
        {
            let min_border = match node.style.box_sizing {
                BoxSizing::BorderBox => min_w,
                BoxSizing::ContentBox => min_w + inset_h,
            };
            limit = limit.max(min_border.max(0.0));
        }
        limit
    };
    let base_text_avail_w = (max_border_limit - inset_h).max(0.0);
    let text_avail_w = node
        .transition_content_width()
        .map_or(base_text_avail_w, |tw| base_text_avail_w.max(tw));

    let (text_w, text_h) = if (node.children.is_empty() && !node.inline_items.is_empty())
        || node.text.is_some()
    {
        measure_block_leaf_inline_or_text(
            node,
            text_avail_w,
            parent_exclusions.as_deref(),
            bfc_offset_y,
        )
    } else {
        (0.0, 0.0)
    };

    // 1. Resolve element width
    let resolved_width = match resolve_dimension_with_node(node.style.width, available_width, node)
    {
        Some(w) => clamp_dimension_with_node(
            w,
            node.style.min_width,
            node.style.max_width,
            available_width,
            node,
        ),
        None => {
            if node.text.is_some()
                || matches!(
                    node.style.display,
                    strata_style::types::Display::Inline
                        | strata_style::types::Display::InlineBlock
                )
            {
                // Shrink-to-fit for text or inline-block elements per W3C CSS 2.1 ยง10.3.9:
                // shrink_to_fit = min(max(min_content, available_width), max_content)
                let base_w = if !node.children.is_empty() {
                    let min_max =
                        crate::intrinsic::compute_min_max_sizes(node, Some(available_width));
                    let avail_content_w = (available_width
                        - padding.left
                        - padding.right
                        - border.left
                        - border.right
                        - margin.left
                        - margin.right)
                        .max(0.0);
                    min_max
                        .min_content
                        .max(avail_content_w)
                        .min(min_max.max_content)
                        .max(text_w)
                } else {
                    text_w
                };
                let mut fit_w = base_w + padding.left + padding.right + border.left + border.right;
                if node.style.overflow_x != strata_style::types::Overflow::Visible {
                    fit_w = fit_w.min(max_border_limit);
                }
                clamp_dimension_with_node(
                    fit_w,
                    node.style.min_width,
                    node.style.max_width,
                    available_width,
                    node,
                )
            } else {
                // In CSS block layout, auto width fills available width minus margins
                let auto_w = (available_width - margin.left - margin.right).max(0.0);
                clamp_dimension_with_node(
                    auto_w,
                    node.style.min_width,
                    node.style.max_width,
                    available_width,
                    node,
                )
            }
        }
    };

    let border_box_width = match node.style.box_sizing {
        BoxSizing::BorderBox => resolved_width,
        BoxSizing::ContentBox => {
            resolved_width + padding.left + padding.right + border.left + border.right
        }
    };

    let content_width =
        (border_box_width - padding.left - padding.right - border.left - border.right).max(0.0);
    let child_layout_width = node
        .transition_content_width()
        .map_or(content_width, |tw| content_width.max(tw));

    // 2. Lay out in-flow children vertically with margin collapsing and floats
    let children_height = if node.children.is_empty() && node.text.is_some() {
        text_h + padding.top + padding.bottom + border.top + border.bottom
    } else {
        solve_block_children_with_exclusions_guarded(
            node,
            child_layout_width,
            available_height,
            parent_exclusions,
            bfc_offset_y,
            guard,
        )
    };

    // 3. Resolve element height
    let resolved_height = match resolve_dimension(node.style.height, available_height) {
        Some(h) => {
            let clamped_h = clamp_dimension(
                h,
                node.style.min_height,
                node.style.max_height,
                available_height,
            );
            match node.style.box_sizing {
                BoxSizing::BorderBox => clamped_h,
                BoxSizing::ContentBox => {
                    clamped_h + padding.top + padding.bottom + border.top + border.bottom
                }
            }
        }
        None => {
            // Auto height wraps children
            clamp_dimension(
                children_height,
                node.style.min_height,
                node.style.max_height,
                available_height,
            )
        }
    };

    // 4. Finalize concentric geometry boxes
    finalize_block_geometry(node, border_box_width, resolved_height);

    // A text leaf that truncates must publish positioned line boxes so paint
    // renders the clipped ellipsis fragment instead of the full string.
    if node.children.is_empty()
        && node.style.text_overflow == strata_style::types::TextOverflow::Ellipsis
        && node.style.overflow_x != strata_style::types::Overflow::Visible
        && content_width > 0.0
        && node.text.is_some()
    {
        publish_truncated_ellipsis_text_leaf(node, content_width);
    }
}