Skip to main content

strata_layout/
box_model.rs

1//! CSS 2.1 Section 8.3.1 Box Model and Vertical Margin Collapsing Engine.
2
3use crate::geometry::{LayoutGeometry, Rect};
4use crate::tree::LayoutNode;
5use strata_style::types::{BoxSizing, Dimension, Position};
6
7/// Collapses two adjacent vertical margins according to CSS 2.1 §8.3.1.
8///
9/// Rules:
10/// - If both are positive, the result is the maximum of the two: $\max(m_1, m_2)$.
11/// - If both are negative, the result is the most negative: $-\max(|m_1|, |m_2|)$.
12/// - If one is positive and one is negative, add the most negative to the most positive:
13///   $\max(m_1, m_2, 0) + \min(m_1, m_2, 0)$.
14pub fn collapse_margins(m1: f32, m2: f32) -> f32 {
15    let m1 = if m1.is_finite() {
16        m1.clamp(-1e7, 1e7)
17    } else {
18        0.0
19    };
20    let m2 = if m2.is_finite() {
21        m2.clamp(-1e7, 1e7)
22    } else {
23        0.0
24    };
25    if m1 >= 0.0 && m2 >= 0.0 {
26        m1.max(m2)
27    } else if m1 < 0.0 && m2 < 0.0 {
28        -(-m1).max(-m2)
29    } else {
30        let max_pos = m1.max(m2).max(0.0);
31        let min_neg = m1.min(m2).min(0.0);
32        max_pos + min_neg
33    }
34}
35
36/// Resolves a CSS `Dimension` into concrete pixels relative to an available length.
37pub fn resolve_dimension(dim: Dimension, available: f32) -> Option<f32> {
38    const MAX_DIMENSION: f32 = 1e7;
39
40    let avail = if available.is_finite() {
41        available.clamp(-MAX_DIMENSION, MAX_DIMENSION)
42    } else {
43        0.0
44    };
45
46    match dim {
47        Dimension::Auto => None,
48        Dimension::Px(px) => {
49            if px.is_finite() {
50                Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
51            } else {
52                None
53            }
54        }
55        Dimension::Percent(pct) => {
56            if pct.is_finite() {
57                let px = avail * (pct / 100.0);
58                if px.is_finite() {
59                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
60                } else {
61                    None
62                }
63            } else {
64                None
65            }
66        }
67        Dimension::Vw(vw) => {
68            if vw.is_finite() {
69                let px = avail * (vw / 100.0);
70                if px.is_finite() {
71                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
72                } else {
73                    None
74                }
75            } else {
76                None
77            }
78        }
79        Dimension::Vh(vh) => {
80            if vh.is_finite() {
81                let px = avail * (vh / 100.0);
82                if px.is_finite() {
83                    Some(px.clamp(-MAX_DIMENSION, MAX_DIMENSION))
84                } else {
85                    None
86                }
87            } else {
88                None
89            }
90        }
91        Dimension::Rem(rem) => {
92            if rem.is_finite() {
93                Some((rem * 16.0).clamp(-MAX_DIMENSION, MAX_DIMENSION))
94            } else {
95                None
96            }
97        }
98        Dimension::Em(em) => {
99            if em.is_finite() {
100                Some((em * 16.0).clamp(-MAX_DIMENSION, MAX_DIMENSION))
101            } else {
102                None
103            }
104        }
105        Dimension::Calc(id) => strata_style::calc::get_calc(id).and_then(|expr| {
106            let ctx = strata_style::calc::CalcContext {
107                parent_size: avail,
108                root_font_size: 16.0,
109                current_font_size: 16.0,
110                viewport_width: 1920.0,
111                viewport_height: 1080.0,
112            };
113            let val = expr.eval(&ctx);
114            if val.is_finite() {
115                Some(val.clamp(-MAX_DIMENSION, MAX_DIMENSION))
116            } else {
117                None
118            }
119        }),
120        Dimension::MinContent | Dimension::MaxContent | Dimension::FitContent(_) => None,
121    }
122}
123
124/// Clamps a computed size against `min` and `max` constraints.
125pub fn clamp_dimension(size: f32, min: Dimension, max: Dimension, available: f32) -> f32 {
126    let mut clamped = if size.is_finite() {
127        size.clamp(0.0, 1e7)
128    } else {
129        0.0
130    };
131    if let Some(min_px) = resolve_dimension(min, available) {
132        clamped = clamped.max(min_px.max(0.0));
133    }
134    if let Some(max_px) = resolve_dimension(max, available) {
135        clamped = clamped.min(max_px.max(0.0));
136    }
137    clamped.clamp(0.0, 1e7)
138}
139
140/// Resolves a CSS `Dimension` into concrete pixels relative to an available length and node context,
141/// evaluating intrinsic keywords (`min-content`, `max-content`, `fit-content`) via `compute_min_max_sizes`.
142pub fn resolve_dimension_with_node(
143    dim: Dimension,
144    available: f32,
145    node: &LayoutNode,
146) -> Option<f32> {
147    match dim {
148        Dimension::MinContent => {
149            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
150            let inline_insets = node.style.padding.left
151                + node.style.padding.right
152                + node.style.border_width.left
153                + node.style.border_width.right;
154            let val = match node.style.box_sizing {
155                BoxSizing::BorderBox => sizes.min_content,
156                BoxSizing::ContentBox => (sizes.min_content - inline_insets).max(0.0),
157            };
158            Some(val)
159        }
160        Dimension::MaxContent => {
161            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
162            let inline_insets = node.style.padding.left
163                + node.style.padding.right
164                + node.style.border_width.left
165                + node.style.border_width.right;
166            let val = match node.style.box_sizing {
167                BoxSizing::BorderBox => sizes.max_content,
168                BoxSizing::ContentBox => (sizes.max_content - inline_insets).max(0.0),
169            };
170            Some(val)
171        }
172        Dimension::FitContent(arg) => {
173            let sizes = crate::intrinsic::compute_min_max_sizes(node, Some(available));
174            let inline_insets = node.style.padding.left
175                + node.style.padding.right
176                + node.style.border_width.left
177                + node.style.border_width.right;
178            let limit = if arg > 0.0 { arg } else { available };
179            let fitted = sizes.shrink_to_fit(limit);
180            let val = match node.style.box_sizing {
181                BoxSizing::BorderBox => fitted,
182                BoxSizing::ContentBox => (fitted - inline_insets).max(0.0),
183            };
184            Some(val)
185        }
186        other => resolve_dimension(other, available),
187    }
188}
189
190/// Clamps a computed size against `min` and `max` constraints with node context.
191pub fn clamp_dimension_with_node(
192    size: f32,
193    min: Dimension,
194    max: Dimension,
195    available: f32,
196    node: &LayoutNode,
197) -> f32 {
198    let mut clamped = if size.is_finite() {
199        size.clamp(0.0, 1e7)
200    } else {
201        0.0
202    };
203    if let Some(min_px) = resolve_dimension_with_node(min, available, node) {
204        clamped = clamped.max(min_px.max(0.0));
205    }
206    if let Some(max_px) = resolve_dimension_with_node(max, available, node) {
207        clamped = clamped.min(max_px.max(0.0));
208    }
209    clamped.clamp(0.0, 1e7)
210}
211
212/// Converts a ComputedStyle into an InlineTextStyle for inline text shaping and typography.
213pub fn inline_style_from_computed_style(
214    style: &strata_style::types::ComputedStyle,
215) -> crate::typography::InlineTextStyle {
216    let is_monospace = crate::text::is_monospace_family(style.font_family);
217
218    crate::typography::InlineTextStyle {
219        font_family: style.font_family,
220        font_size: style.font_size,
221        font_weight: style.font_weight,
222        font_style: style.font_style,
223        color: style.color,
224        background_color: style.background_color,
225        text_decoration: style.text_decoration,
226        vertical_align: match style.vertical_align {
227            strata_style::types::VerticalAlign::Baseline => {
228                crate::typography::VerticalAlignment::Baseline
229            }
230            strata_style::types::VerticalAlign::Top => crate::typography::VerticalAlignment::Top,
231            strata_style::types::VerticalAlign::Bottom => {
232                crate::typography::VerticalAlignment::Bottom
233            }
234            strata_style::types::VerticalAlign::Middle => {
235                crate::typography::VerticalAlignment::Middle
236            }
237            strata_style::types::VerticalAlign::Sub => crate::typography::VerticalAlignment::Sub,
238            strata_style::types::VerticalAlign::Super => {
239                crate::typography::VerticalAlignment::Super
240            }
241            strata_style::types::VerticalAlign::TextTop => {
242                crate::typography::VerticalAlignment::TextTop
243            }
244            strata_style::types::VerticalAlign::TextBottom => {
245                crate::typography::VerticalAlignment::TextBottom
246            }
247        },
248        letter_spacing: style.letter_spacing,
249        line_height: Some(style.font_size * style.line_height),
250        is_monospace,
251        href: style
252            .get_custom_property(strata_primitives::AtomId::HREF)
253            .and_then(strata_primitives::atom::resolve),
254    }
255}
256
257/// Returns whether a child layout node is an inline phrasing element.
258pub fn is_inline_phrasing_node(child: &LayoutNode) -> bool {
259    matches!(
260        child.style.display,
261        strata_style::types::Display::Inline
262            | strata_style::types::Display::InlineBlock
263            | strata_style::types::Display::None
264    ) || child.text.is_some()
265}
266
267/// Refreshes inline fragment paint styles after a style-only change.
268///
269/// Geometry and line boxes are preserved from a previous layout pass. When
270/// hover toggles only paint properties (color, background, decoration), the
271/// text runs still carry the previous inline style clones. This rebuilds the
272/// inline item stream from the freshly styled children and patches each line
273/// fragment's paint-only style fields by item index.
274pub fn refresh_inline_fragment_styles(node: &mut LayoutNode) {
275    let mut stack = vec![node];
276    while let Some(curr) = stack.pop() {
277        if !curr.line_boxes.is_empty() {
278            if !curr.children.is_empty() {
279                let mut items = Vec::new();
280                collect_inline_items_from_children(
281                    &curr.children,
282                    None,
283                    None,
284                    &mut items,
285                    curr.geometry.content_box.width,
286                    curr.geometry.content_box.height,
287                );
288                curr.inline_items = items;
289            }
290            for line in &mut curr.line_boxes {
291                for frag in &mut line.text_fragments {
292                    if let Some(crate::typography::InlineItem::Text { style, .. }) =
293                        curr.inline_items.get(frag.item_index)
294                    {
295                        frag.style.color = style.color;
296                        frag.style.background_color = style.background_color;
297                        frag.style.text_decoration = style.text_decoration;
298                        frag.style.font_family = style.font_family;
299                        frag.font_family = style.font_family;
300                    } else if curr.inline_items.is_empty() && curr.text.is_some() {
301                        let style = inline_style_from_computed_style(&curr.style);
302                        frag.style.color = style.color;
303                        frag.style.background_color = style.background_color;
304                        frag.style.text_decoration = style.text_decoration;
305                        frag.style.font_family = style.font_family;
306                        frag.font_family = style.font_family;
307                    }
308                }
309            }
310        }
311        for child in &mut curr.children {
312            stack.push(child);
313        }
314    }
315}
316
317/// Recursively clears line boxes from inline phrasing descendants whose text is absorbed by parent IFC using an iterative heap stack.
318pub fn clear_inline_descendant_line_boxes(node: &mut LayoutNode) {
319    if node.style.display != strata_style::types::Display::Inline {
320        return;
321    }
322    let mut stack = vec![node];
323    while let Some(curr) = stack.pop() {
324        if curr.style.display == strata_style::types::Display::Inline {
325            curr.line_boxes.clear();
326            for child in &mut curr.children {
327                stack.push(child);
328            }
329        }
330    }
331}
332
333#[derive(Clone, Copy)]
334struct InheritedInlineStyle {
335    font_family: strata_primitives::AtomId,
336    background_color: Option<strata_style::types::Color>,
337    text_decoration: strata_style::types::TextDecoration,
338    href: Option<strata_primitives::AtomId>,
339}
340
341impl InheritedInlineStyle {
342    #[inline]
343    fn from_style(style: &strata_style::types::ComputedStyle) -> Self {
344        Self {
345            font_family: style.font_family,
346            background_color: if style.display == strata_style::types::Display::Inline {
347                style.background_color
348            } else {
349                None
350            },
351            text_decoration: style.text_decoration,
352            href: style.get_custom_property(strata_primitives::AtomId::HREF),
353        }
354    }
355
356    #[inline]
357    fn inherit_into(self, child: &strata_style::types::ComputedStyle) -> Self {
358        let font_family = if child.font_family == strata_primitives::AtomId::FONT_SANS
359            && self.font_family != strata_primitives::AtomId::FONT_SANS
360        {
361            self.font_family
362        } else {
363            child.font_family
364        };
365        let background_color = if child.display == strata_style::types::Display::Inline {
366            child.background_color.or(self.background_color)
367        } else {
368            None
369        };
370        let text_decoration = if child.text_decoration == strata_style::types::TextDecoration::None
371        {
372            self.text_decoration
373        } else {
374            child.text_decoration
375        };
376        let href = child
377            .get_custom_property(strata_primitives::AtomId::HREF)
378            .or(self.href);
379        Self {
380            font_family,
381            background_color,
382            text_decoration,
383            href,
384        }
385    }
386}
387
388struct InlineCollectFrame<'a> {
389    children: &'a [LayoutNode],
390    idx: usize,
391    inherited: Option<InheritedInlineStyle>,
392    top_idx: Option<usize>,
393    depth: usize,
394}
395
396/// Iteratively flattens inline phrasing children into an InlineItem stream (`O(1)` call stack,
397/// bounded by `MAX_LAYOUT_DEPTH`, zero `ComputedStyle::clone()` stack allocations).
398fn collect_inline_items_from_children(
399    children: &[LayoutNode],
400    parent_style: Option<&strata_style::types::ComputedStyle>,
401    top_level_idx: Option<usize>,
402    items: &mut Vec<crate::typography::InlineItem>,
403    content_width: f32,
404    available_height: f32,
405) {
406    let _prof = crate::prof::Scope::new(crate::prof::Slot::StyleClone);
407    let init_inherited = parent_style.map(InheritedInlineStyle::from_style);
408    let mut stack = vec![InlineCollectFrame {
409        children,
410        idx: 0,
411        inherited: init_inherited,
412        top_idx: top_level_idx,
413        depth: 0,
414    }];
415
416    while let Some(frame) = stack.last_mut() {
417        if frame.idx >= frame.children.len() {
418            stack.pop();
419            continue;
420        }
421        let child_idx = frame.idx;
422        let child = &frame.children[child_idx];
423        frame.idx += 1;
424
425        if child.style.display == strata_style::types::Display::None {
426            continue;
427        }
428        let effective_top_idx = frame.top_idx.unwrap_or(child_idx);
429        let cur_inherited = frame.inherited;
430        let cur_depth = frame.depth;
431
432        if let Some(ref text) = child.text {
433            let mut s = inline_style_from_computed_style(&child.style);
434            if let Some(p) = cur_inherited {
435                if child.style.font_family == strata_primitives::AtomId::FONT_SANS
436                    && p.font_family != strata_primitives::AtomId::FONT_SANS
437                {
438                    s.font_family = p.font_family;
439                    s.is_monospace = crate::text::is_monospace_family(p.font_family);
440                }
441                if s.background_color.is_none() {
442                    s.background_color = p.background_color;
443                }
444                if s.text_decoration == strata_style::types::TextDecoration::None
445                    && p.text_decoration != strata_style::types::TextDecoration::None
446                {
447                    s.text_decoration = p.text_decoration;
448                }
449                if s.href.is_none() {
450                    s.href = p.href.and_then(strata_primitives::atom::resolve);
451                }
452            }
453            items.push(crate::typography::InlineItem::text(text.clone(), s));
454        } else if child.style.display == strata_style::types::Display::Inline
455            && !child.children.is_empty()
456        {
457            if cur_depth < crate::tree::MAX_LAYOUT_DEPTH {
458                let merged = match cur_inherited {
459                    Some(p) => p.inherit_into(&child.style),
460                    None => InheritedInlineStyle::from_style(&child.style),
461                };
462                stack.push(InlineCollectFrame {
463                    children: child.children.as_slice(),
464                    idx: 0,
465                    inherited: Some(merged),
466                    top_idx: Some(effective_top_idx),
467                    depth: cur_depth + 1,
468                });
469            }
470        } else {
471            let mut w =
472                resolve_dimension_with_node(child.style.width, content_width, child).unwrap_or(0.0);
473            let mut h = resolve_dimension(child.style.height, available_height).unwrap_or(0.0);
474            if w == 0.0 && child.geometry.border_box.width > 0.0 {
475                w = child.geometry.border_box.width;
476            }
477            if h == 0.0 && child.geometry.border_box.height > 0.0 {
478                h = child.geometry.border_box.height;
479            }
480            if h == 0.0 && w > 0.0 && child.children.is_empty() {
481                // Under W3C CSS 2.1 §10.6.2, replaced/atomic elements with auto height default to 1:1 aspect ratio
482                h = w;
483            }
484            items.push(crate::typography::InlineItem::atomic(
485                effective_top_idx,
486                w,
487                h,
488                child.style.margin.left,
489                child.style.margin.right,
490                crate::typography::VerticalAlignment::Baseline,
491            ));
492        }
493    }
494}
495
496/// Recursively propagates atomic inline fragment bounds down through nested `Display::Inline` containers using an iterative heap stack.
497fn propagate_atomic_bounds_to_inline_descendants(node: &mut LayoutNode, bounds: Rect) {
498    if node.style.display != strata_style::types::Display::Inline {
499        return;
500    }
501    let mut stack = vec![node];
502    while let Some(curr) = stack.pop() {
503        for child in &mut curr.children {
504            child.geometry.border_box.x = bounds.x;
505            child.geometry.border_box.y = bounds.y;
506            if child.geometry.border_box.width == 0.0 {
507                child.geometry.border_box.width = bounds.width;
508            }
509            if child.geometry.border_box.height == 0.0 {
510                child.geometry.border_box.height = bounds.height;
511            }
512            if child.style.display == strata_style::types::Display::Inline {
513                stack.push(child);
514            }
515        }
516    }
517}
518
519/// Recursively translates layout geometry and line box fragments of a node and its descendants.
520pub fn translate_node_and_descendants(node: &mut LayoutNode, dx: f32, dy: f32) {
521    if dx == 0.0 && dy == 0.0 {
522        return;
523    }
524    node.translate(dx, dy);
525}
526
527/// Applies `text-overflow: ellipsis` to the laid-out inline stream.
528///
529/// Only clipping containers are eligible. When a line's text extends past the
530/// content width, the fragment that crosses the boundary is cut at the last
531/// character boundary that leaves room for U+2026 HORIZONTAL ELLIPSIS, and the
532/// remaining fragments on that line are discarded. This mirrors the single
533/// line truncation produced by `overflow: hidden; text-overflow: ellipsis;
534/// white-space: nowrap`.
535fn truncate_inline_overflow(
536    node: &LayoutNode,
537    res: &mut crate::typography::InlineLayoutResult,
538    content_width: f32,
539) {
540    use strata_style::types::{Overflow, TextOverflow};
541
542    if node.style.text_overflow != TextOverflow::Ellipsis
543        || node.style.overflow_x == Overflow::Visible
544        || content_width <= 0.0
545    {
546        return;
547    }
548
549    for line in &mut res.lines {
550        let mut new_fragments = Vec::with_capacity(line.text_fragments.len());
551        let mut cut = false;
552        for fragment in line.text_fragments.drain(..) {
553            if cut {
554                continue;
555            }
556            let frag_start = fragment.bounds.x;
557            let frag_end = frag_start + fragment.bounds.width;
558            if frag_end <= content_width + 1.0 {
559                new_fragments.push(fragment);
560                continue;
561            }
562
563            let available = content_width - frag_start;
564            if available <= 0.0 {
565                cut = true;
566                continue;
567            }
568
569            let style = &fragment.style;
570            let multiplier = match style.line_height {
571                Some(line_h) if style.font_size > 0.0 => (line_h / style.font_size).max(0.01),
572                _ => 1.2,
573            };
574            let measure = |text: &str| {
575                crate::text::measure_text_bounds_styled_with_family(
576                    text,
577                    style.font_size,
578                    multiplier,
579                    None,
580                    style.is_monospace,
581                    style.font_family,
582                    style.font_weight,
583                    style.font_style,
584                )
585                .0
586            };
587
588            let ellipsis_width = measure("\u{2026}");
589            if ellipsis_width > available {
590                cut = true;
591                continue;
592            }
593
594            // Binary search the largest character-boundary prefix that fits
595            // alongside the ellipsis within the available width.
596            let boundaries: Vec<usize> = fragment
597                .text
598                .char_indices()
599                .map(|(idx, _)| idx)
600                .chain(std::iter::once(fragment.text.len()))
601                .collect();
602            let mut low = 0usize;
603            let mut high = boundaries.len().saturating_sub(1);
604            let mut best = 0usize;
605            while low <= high {
606                let mid = (low + high) / 2;
607                let end = boundaries[mid];
608                let prefix = &fragment.text[..end];
609                if measure(prefix) + ellipsis_width <= available + 0.01 {
610                    best = mid;
611                    low = mid + 1;
612                } else if mid == 0 {
613                    break;
614                } else {
615                    high = mid - 1;
616                }
617            }
618
619            let end = boundaries[best];
620            let mut text = fragment.text[..end].to_string();
621            text.push('\u{2026}');
622            let width = measure(&text);
623            let mut truncated_fragment = fragment;
624            truncated_fragment.text = text;
625            truncated_fragment.bounds.width = width;
626            new_fragments.push(truncated_fragment);
627            cut = true;
628        }
629
630        if let Some(last) = new_fragments.last() {
631            line.bounds.width = last.bounds.x + last.bounds.width;
632        } else {
633            line.bounds.width = 0.0;
634        }
635        line.text_fragments = new_fragments;
636    }
637
638    res.total_width = res
639        .lines
640        .iter()
641        .map(|line| line.bounds.width)
642        .fold(0.0f32, f32::max);
643}
644
645/// Positions in-flow block children vertically with CSS 2.1 §8.3.1 margin collapsing, IFC, and floats.
646pub fn solve_block_children(
647    node: &mut LayoutNode,
648    content_width: f32,
649    available_height: f32,
650) -> f32 {
651    solve_block_children_with_exclusions(node, content_width, available_height, None, 0.0)
652}
653
654/// Positions in-flow block children with active exclusion space tracking and float dispatch.
655pub fn solve_block_children_with_exclusions(
656    node: &mut LayoutNode,
657    content_width: f32,
658    available_height: f32,
659    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
660    bfc_offset_y: f32,
661) -> f32 {
662    solve_block_children_with_exclusions_guarded(
663        node,
664        content_width,
665        available_height,
666        parent_exclusions,
667        bfc_offset_y,
668        crate::tree::LayoutDepthGuard::root(),
669    )
670}
671
672/// Returns true if an in-flow block element has zero computed height, no padding or border,
673/// and no in-flow content, allowing its top and bottom margins to collapse through under CSS 2.1 §8.3.1.
674#[inline]
675pub fn is_empty_collapsible_block(node: &LayoutNode) -> bool {
676    node.children.is_empty()
677        && node.text.is_none()
678        && node.inline_items.is_empty()
679        && node.style.border_width.top == 0.0
680        && node.style.border_width.bottom == 0.0
681        && node.style.padding.top == 0.0
682        && node.style.padding.bottom == 0.0
683        && matches!(node.style.height, Dimension::Auto | Dimension::Px(0.0))
684        && matches!(node.style.min_height, Dimension::Auto | Dimension::Px(0.0))
685        && node.style.clear == strata_style::types::Clear::None
686        && node.style.float == strata_style::types::Float::None
687        && node.style.overflow_x == strata_style::types::Overflow::Visible
688        && node.style.overflow_y == strata_style::types::Overflow::Visible
689}
690
691/// Returns true if an element establishes an independent formatting context (BFC, FFC, GFC),
692/// preventing margin collapsing across its boundaries under W3C CSS 2.1 §8.3.1 and CSS Display Level 3.
693#[inline]
694pub fn node_establishes_bfc(node: &LayoutNode) -> bool {
695    node.style.float != strata_style::types::Float::None
696        || matches!(node.style.position, Position::Absolute | Position::Fixed)
697        || matches!(
698            node.style.display,
699            strata_style::types::Display::InlineBlock
700                | strata_style::types::Display::TableCell
701                | strata_style::types::Display::TableCaption
702                | strata_style::types::Display::Flex
703                | strata_style::types::Display::Grid
704                | strata_style::types::Display::InlineFlex
705                | strata_style::types::Display::InlineGrid
706                | strata_style::types::Display::Table
707                | strata_style::types::Display::InlineTable
708        )
709        || node.style.overflow_x != strata_style::types::Overflow::Visible
710        || node.style.overflow_y != strata_style::types::Overflow::Visible
711        || node.style.contain.layout
712        || child_is_layout_boundary(node)
713}
714
715#[inline]
716fn child_is_layout_boundary(node: &LayoutNode) -> bool {
717    node.is_layout_boundary()
718}
719
720/// Positions in-flow block children with active exclusion space tracking and depth guard.
721#[inline(never)]
722fn layout_ellipsis_text_leaf_children(node: &mut LayoutNode, content_width: f32) -> Option<f32> {
723    let text = node.text.clone()?;
724    let padding = node.style.padding;
725    let border = node.style.border_width;
726    let style = inline_style_from_computed_style(&node.style);
727    let items = vec![crate::typography::InlineItem::text(text, style)];
728    let opt = crate::typography::InlineLayoutOptions {
729        font_size: node.style.font_size,
730        line_height: Some(node.style.font_size * node.style.line_height),
731        max_width: Some(content_width),
732        white_space: match node.style.white_space {
733            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
734            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
735            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
736            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
737            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
738        },
739        vertical_align: crate::typography::VerticalAlignment::Baseline,
740        is_monospace: crate::text::is_monospace_family(node.style.font_family),
741        exclusion_space: None,
742        bfc_offset_y: 0.0,
743    };
744    let ifc = crate::typography::InlineFormattingContext::new();
745    let mut res = ifc.layout_inline_stream(&items, &opt);
746    truncate_inline_overflow(node, &mut res, content_width);
747
748    let origin_x = node.geometry.border_box.x + border.left + padding.left;
749    let origin_y = node.geometry.border_box.y + border.top + padding.top;
750    let mut lines = res.lines;
751    for line in &mut lines {
752        line.bounds.x += origin_x;
753        line.bounds.y += origin_y;
754        for frag in &mut line.text_fragments {
755            frag.bounds.x += origin_x;
756            frag.bounds.y += origin_y;
757            frag.baseline_y += origin_y;
758        }
759        for atomic in &mut line.atomic_fragments {
760            atomic.bounds.x += origin_x;
761            atomic.bounds.y += origin_y;
762        }
763    }
764    let total_h = res.total_height;
765    node.inline_items = items;
766    node.line_boxes = lines;
767    Some(total_h + padding.top + padding.bottom + border.top + border.bottom)
768}
769
770#[inline(never)]
771fn finish_ifc_inline_layout(
772    node: &mut LayoutNode,
773    content_width: f32,
774    parent_exclusions: Option<&crate::exclusions::ExclusionSpace>,
775    bfc_offset_y: f32,
776) -> f32 {
777    let padding = node.style.padding;
778    let border = node.style.border_width;
779    let ifc = crate::typography::InlineFormattingContext::new();
780    let opt = crate::typography::InlineLayoutOptions {
781        font_size: node.style.font_size,
782        line_height: Some(node.style.font_size * node.style.line_height),
783        max_width: Some(content_width),
784        white_space: match node.style.white_space {
785            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
786            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
787            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
788            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
789            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
790        },
791        vertical_align: match node.style.vertical_align {
792            strata_style::types::VerticalAlign::Baseline => {
793                crate::typography::VerticalAlignment::Baseline
794            }
795            strata_style::types::VerticalAlign::Top => crate::typography::VerticalAlignment::Top,
796            strata_style::types::VerticalAlign::Bottom => {
797                crate::typography::VerticalAlignment::Bottom
798            }
799            strata_style::types::VerticalAlign::Middle => {
800                crate::typography::VerticalAlignment::Middle
801            }
802            strata_style::types::VerticalAlign::Sub => crate::typography::VerticalAlignment::Sub,
803            strata_style::types::VerticalAlign::Super => {
804                crate::typography::VerticalAlignment::Super
805            }
806            strata_style::types::VerticalAlign::TextTop => {
807                crate::typography::VerticalAlignment::TextTop
808            }
809            strata_style::types::VerticalAlign::TextBottom => {
810                crate::typography::VerticalAlignment::TextBottom
811            }
812        },
813        is_monospace: crate::text::is_monospace_family(node.style.font_family),
814        exclusion_space: parent_exclusions,
815        bfc_offset_y: bfc_offset_y + padding.top + border.top,
816    };
817
818    let mut res = ifc.layout_inline_stream(&node.inline_items, &opt);
819    truncate_inline_overflow(node, &mut res, content_width);
820    let content_origin_x = node.geometry.border_box.x + border.left + padding.left;
821    let content_origin_y = node.geometry.border_box.y + border.top + padding.top;
822
823    let mut positioned_lines = res.lines;
824    for line in &mut positioned_lines {
825        let align_offset_x = match node.style.text_align {
826            strata_style::types::TextAlign::Center => {
827                ((content_width - line.bounds.width) / 2.0).max(0.0)
828            }
829            strata_style::types::TextAlign::Right => (content_width - line.bounds.width).max(0.0),
830            _ => 0.0,
831        };
832
833        let total_shift_x = content_origin_x + align_offset_x;
834        line.bounds.x += total_shift_x;
835        line.bounds.y += content_origin_y;
836        for frag in &mut line.text_fragments {
837            frag.bounds.x += total_shift_x;
838            frag.bounds.y += content_origin_y;
839            frag.baseline_y += content_origin_y;
840        }
841        for at in &mut line.atomic_fragments {
842            at.bounds.x += total_shift_x;
843            at.bounds.y += content_origin_y;
844            if at.node_index < node.children.len() {
845                let child = &mut node.children[at.node_index];
846                let dx = at.bounds.x - child.geometry.border_box.x;
847                let dy = at.bounds.y - child.geometry.border_box.y;
848                child.geometry.border_box.width = at.bounds.width;
849                child.geometry.border_box.height = at.bounds.height;
850                child.translate(dx, dy);
851
852                let target_bounds = child.geometry.border_box;
853                propagate_atomic_bounds_to_inline_descendants(child, target_bounds);
854            }
855        }
856    }
857
858    let total_h = res.total_height;
859    for child in &mut node.children {
860        if let Some(ref text) = child.text {
861            let mut found = false;
862            for line in &positioned_lines {
863                for frag in &line.text_fragments {
864                    if frag.text.contains(text.as_str()) || text.contains(frag.text.as_str()) {
865                        child.geometry.border_box = frag.bounds;
866                        found = true;
867                        break;
868                    }
869                }
870                if found {
871                    break;
872                }
873            }
874            if !found {
875                child.geometry.border_box.x = content_origin_x;
876                child.geometry.border_box.y = content_origin_y;
877            }
878        }
879    }
880    node.line_boxes = positioned_lines;
881    total_h + padding.top + padding.bottom + border.top + border.bottom
882}
883
884pub fn solve_block_children_with_exclusions_guarded(
885    node: &mut LayoutNode,
886    content_width: f32,
887    available_height: f32,
888    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
889    bfc_offset_y: f32,
890    guard: crate::tree::LayoutDepthGuard,
891) -> f32 {
892    let _prof = crate::prof::Scope::new(crate::prof::Slot::Block);
893    let padding = node.style.padding;
894    let border = node.style.border_width;
895
896    if guard.is_exhausted() {
897        crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
898        return padding.top + border.top + padding.bottom + border.bottom;
899    }
900
901    if node.children.is_empty()
902        && node.inline_items.is_empty()
903        && node.style.text_overflow == strata_style::types::TextOverflow::Ellipsis
904    {
905        if let Some(h) = layout_ellipsis_text_leaf_children(node, content_width) {
906            return h;
907        }
908    }
909
910    // Check if this container establishes an Inline Formatting Context (IFC)
911    let has_implicit_inlines =
912        !node.children.is_empty() && node.children.iter().all(is_inline_phrasing_node);
913    let has_explicit_inlines = node.children.is_empty() && !node.inline_items.is_empty();
914
915    if has_explicit_inlines || has_implicit_inlines {
916        if has_implicit_inlines {
917            let child_guard = guard.enter();
918            for child in &mut node.children {
919                if let Some(cg) = child_guard {
920                    child.compute_layout_guarded(content_width, available_height, None, 0.0, cg);
921                } else {
922                    child.compute_layout_guarded(content_width, available_height, None, 0.0, guard);
923                }
924                clear_inline_descendant_line_boxes(child);
925            }
926            let mut items = Vec::new();
927            collect_inline_items_from_children(
928                &node.children,
929                None,
930                None,
931                &mut items,
932                content_width,
933                available_height,
934            );
935            node.inline_items = items;
936        }
937        return finish_ifc_inline_layout(
938            node,
939            content_width,
940            parent_exclusions.as_deref(),
941            bfc_offset_y,
942        );
943    }
944
945    // W3C CSS 2.1 §9.4.1 Block Formatting Context (BFC) root determination:
946    // Normal in-flow block boxes with overflow: visible share their parent BFC's ExclusionSpace
947    // so floats inside a <section> or <div> overhang into subsequent sibling sections.
948    let establishes_bfc = node_establishes_bfc(node);
949
950    let is_root_exclusion_context = parent_exclusions.is_none();
951    let mut local_exclusions = crate::exclusions::ExclusionSpace::new();
952    let (exclusion_space, base_bfc_y): (&mut crate::exclusions::ExclusionSpace, f32) =
953        if establishes_bfc || is_root_exclusion_context {
954            (&mut local_exclusions, 0.0)
955        } else if let Some(pe) = parent_exclusions {
956            (pe, bfc_offset_y)
957        } else {
958            (&mut local_exclusions, 0.0)
959        };
960    let initial_exclusions_count = exclusion_space.exclusions().len();
961    let parent_top_adjoining = !establishes_bfc && border.top == 0.0 && padding.top == 0.0;
962    let parent_bottom_adjoining = !establishes_bfc
963        && border.bottom == 0.0
964        && padding.bottom == 0.0
965        && node.style.height == Dimension::Auto;
966
967    let mut current_y = border.top + padding.top;
968    let mut pending_margin: Option<f32> = None;
969    let mut is_first_in_flow = true;
970    let mut last_child_establishes_bfc = false;
971
972    for child in &mut node.children {
973        if child.style.position == Position::Absolute || child.style.position == Position::Fixed {
974            continue;
975        }
976
977        // Handle CSS clear in BFC coordinate space for in-flow blocks
978        if child.style.float == strata_style::types::Float::None
979            && child.style.clear != strata_style::types::Clear::None
980        {
981            let cleared_bfc_y =
982                exclusion_space.clearance_offset(child.style.clear, base_bfc_y + current_y);
983            if cleared_bfc_y > base_bfc_y + current_y {
984                current_y = cleared_bfc_y - base_bfc_y;
985                pending_margin = None;
986            }
987        }
988
989        // Handle CSS float
990        if child.style.float != strata_style::types::Float::None {
991            // Layout float child as an independent BFC to compute its dimensions
992            let child_guard = guard.enter();
993            if let Some(cg) = child_guard {
994                child.compute_layout_guarded(content_width, available_height, None, 0.0, cg);
995            } else {
996                child.compute_layout_guarded(content_width, available_height, None, 0.0, guard);
997            }
998            let float_margin = child.style.margin;
999            let float_w = child.geometry.border_box.width + float_margin.left + float_margin.right;
1000            let float_h = child.geometry.border_box.height + float_margin.top + float_margin.bottom;
1001
1002            // Query line opportunity at float_bfc_y in BFC coordinate space, respecting float's own clearance
1003            let mut float_bfc_y = base_bfc_y + current_y;
1004            if child.style.clear != strata_style::types::Clear::None {
1005                let cleared_bfc_y =
1006                    exclusion_space.clearance_offset(child.style.clear, float_bfc_y);
1007                if cleared_bfc_y > float_bfc_y {
1008                    float_bfc_y = cleared_bfc_y;
1009                }
1010            }
1011            let mut opp = exclusion_space.line_opportunity(float_bfc_y, float_h, content_width);
1012            if opp.available_width < float_w && content_width >= float_w {
1013                // Drop down if float does not fit horizontally
1014                while let Some(next_bfc_y) = exclusion_space.next_float_bottom_after(float_bfc_y) {
1015                    float_bfc_y = next_bfc_y;
1016                    opp = exclusion_space.line_opportunity(float_bfc_y, float_h, content_width);
1017                    if opp.available_width >= float_w {
1018                        break;
1019                    }
1020                }
1021            }
1022            let local_float_y = float_bfc_y - base_bfc_y;
1023
1024            let (target_x, target_y) = match child.style.float {
1025                strata_style::types::Float::Left | strata_style::types::Float::InlineStart => {
1026                    let float_x =
1027                        border.left + padding.left + opp.left_float_edge + float_margin.left;
1028                    let float_y = local_float_y + float_margin.top;
1029                    let excl_rect = crate::geometry::Rect::from_xywh(
1030                        opp.left_float_edge,
1031                        float_bfc_y,
1032                        float_w,
1033                        float_h,
1034                    );
1035                    exclusion_space
1036                        .add_exclusion(excl_rect, crate::exclusions::ExclusionKind::FloatLeft);
1037                    (
1038                        node.geometry.border_box.x + float_x,
1039                        node.geometry.border_box.y + float_y,
1040                    )
1041                }
1042                strata_style::types::Float::Right | strata_style::types::Float::InlineEnd => {
1043                    let start_r = opp.right_float_edge;
1044                    let float_x =
1045                        border.left + padding.left + start_r - float_w + float_margin.left;
1046                    let float_y = local_float_y + float_margin.top;
1047                    let excl_rect = crate::geometry::Rect::from_xywh(
1048                        start_r - float_w,
1049                        float_bfc_y,
1050                        float_w,
1051                        float_h,
1052                    );
1053                    exclusion_space
1054                        .add_exclusion(excl_rect, crate::exclusions::ExclusionKind::FloatRight);
1055                    (
1056                        node.geometry.border_box.x + float_x,
1057                        node.geometry.border_box.y + float_y,
1058                    )
1059                }
1060                strata_style::types::Float::None => unreachable!(),
1061            };
1062
1063            let old_x = child.geometry.border_box.x;
1064            let old_y = child.geometry.border_box.y;
1065            let dx = target_x - old_x;
1066            let dy = target_y - old_y;
1067            translate_node_and_descendants(child, dx, dy);
1068
1069            // Floats do not advance in-flow block cursor or participate in margin collapsing
1070            continue;
1071        }
1072
1073        let child_margin = child.style.margin;
1074
1075        // CSS 2.1 §8.3.1: An empty block's top and bottom margins collapse through
1076        if is_empty_collapsible_block(child) {
1077            let through_margin = collapse_margins(child_margin.top, child_margin.bottom);
1078            let combined = match pending_margin {
1079                Some(pm) => collapse_margins(pm, through_margin),
1080                None => through_margin,
1081            };
1082
1083            if is_first_in_flow && parent_top_adjoining {
1084                node.style.margin.top = collapse_margins(node.style.margin.top, combined);
1085                pending_margin = None;
1086            } else {
1087                pending_margin = Some(combined);
1088            }
1089
1090            child.geometry.border_box.x =
1091                node.geometry.border_box.x + border.left + padding.left + child_margin.left;
1092            child.geometry.border_box.y =
1093                node.geometry.border_box.y + current_y + pending_margin.unwrap_or(0.0);
1094            child.geometry.border_box.width = content_width;
1095            child.geometry.border_box.height = 0.0;
1096            continue;
1097        }
1098
1099        let child_establishes_bfc = node_establishes_bfc(child);
1100
1101        let mut collapsed_v_margin = match pending_margin.take() {
1102            Some(prev_m) => collapse_margins(prev_m, child_margin.top),
1103            None => child_margin.top,
1104        };
1105
1106        if is_first_in_flow {
1107            is_first_in_flow = false;
1108            if parent_top_adjoining && !child_establishes_bfc {
1109                node.style.margin.top = collapse_margins(node.style.margin.top, collapsed_v_margin);
1110                collapsed_v_margin = 0.0;
1111            }
1112        }
1113
1114        current_y += collapsed_v_margin;
1115
1116        let mut child_available_width = content_width;
1117        let mut child_x = border.left + padding.left + child_margin.left;
1118
1119        // 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
1120        if child_establishes_bfc && !exclusion_space.exclusions().is_empty() {
1121            let mut child_bfc_y = base_bfc_y + current_y;
1122            let mut opp = exclusion_space.line_opportunity(child_bfc_y, 0.0, content_width);
1123
1124            if opp.available_width < content_width || opp.left_float_edge > 0.0 {
1125                let child_desired_w =
1126                    resolve_dimension_with_node(child.style.width, content_width, child);
1127                if let Some(w) = child_desired_w {
1128                    if w + child_margin.left + child_margin.right > opp.available_width {
1129                        // Element does not fit beside the float; clear by placing it below preceding floats
1130                        while let Some(next_y) =
1131                            exclusion_space.next_float_bottom_after(child_bfc_y)
1132                        {
1133                            child_bfc_y = next_y;
1134                            opp = exclusion_space.line_opportunity(child_bfc_y, 0.0, content_width);
1135                            if opp.available_width >= w + child_margin.left + child_margin.right {
1136                                break;
1137                            }
1138                        }
1139                        current_y = child_bfc_y - base_bfc_y;
1140                    }
1141                }
1142
1143                child_available_width =
1144                    (opp.available_width - child_margin.left - child_margin.right).max(0.0);
1145                child_x = border.left + padding.left + opp.left_float_edge + child_margin.left;
1146            }
1147        }
1148
1149        child.geometry.border_box.x = node.geometry.border_box.x + child_x;
1150        child.geometry.border_box.y = node.geometry.border_box.y + current_y;
1151
1152        // Pass the active BFC exclusion space down to in-flow block children so floats can overhang across sections,
1153        // EXCEPT when child establishes its own BFC or exclusion space is currently empty.
1154        let passed_exclusions = if child_establishes_bfc || exclusion_space.exclusions().is_empty()
1155        {
1156            None
1157        } else {
1158            Some(&mut *exclusion_space)
1159        };
1160
1161        let child_guard = guard.enter();
1162        if let Some(cg) = child_guard {
1163            child.compute_layout_guarded(
1164                child_available_width,
1165                available_height,
1166                passed_exclusions,
1167                base_bfc_y + current_y,
1168                cg,
1169            );
1170        } else {
1171            child.compute_layout_guarded(
1172                child_available_width,
1173                available_height,
1174                passed_exclusions,
1175                base_bfc_y + current_y,
1176                guard,
1177            );
1178        }
1179
1180        // Auto margin horizontal centering (mx-auto / ml-auto / mr-auto)
1181        if child.style.margin_auto_left && child.style.margin_auto_right {
1182            let free_space = child_available_width - child.geometry.border_box.width;
1183            let auto_m = (free_space / 2.0).max(0.0);
1184            let target_x = node.geometry.border_box.x + child_x - child_margin.left + auto_m;
1185            let dx = target_x - child.geometry.border_box.x;
1186            if dx != 0.0 {
1187                translate_node_and_descendants(child, dx, 0.0);
1188            }
1189        } else if child.style.margin_auto_left {
1190            let free_space =
1191                child_available_width - child.geometry.border_box.width - child_margin.right;
1192            let target_x =
1193                node.geometry.border_box.x + child_x - child_margin.left + free_space.max(0.0);
1194            let dx = target_x - child.geometry.border_box.x;
1195            if dx != 0.0 {
1196                translate_node_and_descendants(child, dx, 0.0);
1197            }
1198        } else if node.style.text_align == strata_style::types::TextAlign::Center {
1199            let free_space = content_width - child.geometry.border_box.width;
1200            if free_space > 0.0 {
1201                let offset_x = (free_space / 2.0).max(0.0);
1202                let target_x = node.geometry.border_box.x + border.left + padding.left + offset_x;
1203                let dx = target_x - child.geometry.border_box.x;
1204                if dx != 0.0 {
1205                    translate_node_and_descendants(child, dx, 0.0);
1206                }
1207            }
1208        } else if node.style.text_align == strata_style::types::TextAlign::Right {
1209            let free_space = content_width - child.geometry.border_box.width;
1210            if free_space > 0.0 {
1211                let target_x = node.geometry.border_box.x + border.left + padding.left + free_space;
1212                let dx = target_x - child.geometry.border_box.x;
1213                if dx != 0.0 {
1214                    translate_node_and_descendants(child, dx, 0.0);
1215                }
1216            }
1217        }
1218
1219        current_y += child.geometry.border_box.height;
1220        pending_margin = Some(child_margin.bottom);
1221        last_child_establishes_bfc = child_establishes_bfc;
1222    }
1223
1224    if let Some(trailing_margin) = pending_margin {
1225        if parent_bottom_adjoining && !last_child_establishes_bfc {
1226            node.style.margin.bottom = collapse_margins(node.style.margin.bottom, trailing_margin);
1227        } else {
1228            current_y += trailing_margin;
1229        }
1230    }
1231
1232    // CSS 2.1 §10.6.7 BFC float containment: BFC roots or layout tree root expand auto height to enclose floats
1233    if (establishes_bfc || is_root_exclusion_context)
1234        && exclusion_space.exclusions().len() > initial_exclusions_count
1235    {
1236        let max_float_bottom = exclusion_space.max_float_bottom();
1237        if max_float_bottom > current_y {
1238            current_y = max_float_bottom;
1239        }
1240    }
1241
1242    current_y += padding.bottom + border.bottom;
1243
1244    current_y
1245}
1246
1247/// Executes normal-flow block layout with vertical margin collapsing.
1248pub fn solve_block(node: &mut LayoutNode, available_width: f32, available_height: f32) {
1249    solve_block_with_exclusions_guarded(
1250        node,
1251        available_width,
1252        available_height,
1253        None,
1254        0.0,
1255        crate::tree::LayoutDepthGuard::root(),
1256    );
1257}
1258
1259/// Executes normal-flow block layout passing parent exclusion space for float obstructions.
1260pub fn solve_block_with_exclusions(
1261    node: &mut LayoutNode,
1262    available_width: f32,
1263    available_height: f32,
1264    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1265    bfc_offset_y: f32,
1266) {
1267    solve_block_with_exclusions_guarded(
1268        node,
1269        available_width,
1270        available_height,
1271        parent_exclusions,
1272        bfc_offset_y,
1273        crate::tree::LayoutDepthGuard::root(),
1274    );
1275}
1276
1277#[cold]
1278#[inline(never)]
1279fn solve_block_depth_exhausted(
1280    node: &mut LayoutNode,
1281    available_width: f32,
1282    available_height: f32,
1283    guard: crate::tree::LayoutDepthGuard,
1284) {
1285    crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
1286    let padding = node.style.padding;
1287    let border = node.style.border_width;
1288    let margin = node.style.margin;
1289    let border_box_width =
1290        match resolve_dimension_with_node(node.style.width, available_width, node) {
1291            Some(w) => clamp_dimension_with_node(
1292                w,
1293                node.style.min_width,
1294                node.style.max_width,
1295                available_width,
1296                node,
1297            ),
1298            None => (available_width - margin.left - margin.right).max(0.0),
1299        };
1300    let border_box_height = match resolve_dimension(node.style.height, available_height) {
1301        Some(h) => clamp_dimension(
1302            h,
1303            node.style.min_height,
1304            node.style.max_height,
1305            available_height,
1306        ),
1307        None => 0.0,
1308    };
1309    let border_box = Rect::new(
1310        node.geometry.border_box.x,
1311        node.geometry.border_box.y,
1312        border_box_width,
1313        border_box_height,
1314    );
1315    node.geometry = LayoutGeometry::from_border_box(border_box, padding, border, margin);
1316    node.geometry.snap_to_pixel();
1317}
1318
1319#[cold]
1320#[inline(never)]
1321fn solve_block_content_visibility_hidden(
1322    node: &mut LayoutNode,
1323    available_width: f32,
1324    available_height: f32,
1325) {
1326    let padding = node.style.padding;
1327    let border = node.style.border_width;
1328    let margin = node.style.margin;
1329    let intrinsic_w = node
1330        .style
1331        .contain_intrinsic_width
1332        .and_then(|dim| resolve_dimension_with_node(dim, available_width, node));
1333    let intrinsic_h = node
1334        .style
1335        .contain_intrinsic_height
1336        .and_then(|dim| resolve_dimension(dim, available_height))
1337        .unwrap_or(0.0);
1338    let border_box_width =
1339        match resolve_dimension_with_node(node.style.width, available_width, node).or(intrinsic_w) {
1340            Some(w) => clamp_dimension_with_node(
1341                w,
1342                node.style.min_width,
1343                node.style.max_width,
1344                available_width,
1345                node,
1346            ),
1347            None => (available_width - margin.left - margin.right).max(0.0),
1348        };
1349    let border_box_height = match resolve_dimension(node.style.height, available_height) {
1350        Some(h) => clamp_dimension(
1351            h,
1352            node.style.min_height,
1353            node.style.max_height,
1354            available_height,
1355        ),
1356        None => clamp_dimension(
1357            intrinsic_h,
1358            node.style.min_height,
1359            node.style.max_height,
1360            available_height,
1361        ),
1362    };
1363    let border_box = Rect::new(
1364        node.geometry.border_box.x,
1365        node.geometry.border_box.y,
1366        border_box_width,
1367        border_box_height,
1368    );
1369    node.geometry = LayoutGeometry::from_border_box(border_box, padding, border, margin);
1370    node.geometry.snap_to_pixel();
1371}
1372
1373#[inline(never)]
1374fn measure_block_leaf_inline_or_text(
1375    node: &LayoutNode,
1376    text_avail_w: f32,
1377    parent_exclusions: Option<&crate::exclusions::ExclusionSpace>,
1378    bfc_offset_y: f32,
1379) -> (f32, f32) {
1380    if node.children.is_empty() && !node.inline_items.is_empty() {
1381        let ifc = crate::typography::InlineFormattingContext::new();
1382        let opt = crate::typography::InlineLayoutOptions {
1383            font_size: node.style.font_size,
1384            line_height: Some(node.style.font_size * node.style.line_height),
1385            max_width: Some(text_avail_w),
1386            white_space: match node.style.white_space {
1387                strata_style::types::WhiteSpace::Normal => {
1388                    crate::typography::WhiteSpaceMode::Normal
1389                }
1390                strata_style::types::WhiteSpace::NoWrap => {
1391                    crate::typography::WhiteSpaceMode::NoWrap
1392                }
1393                strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
1394                strata_style::types::WhiteSpace::PreWrap => {
1395                    crate::typography::WhiteSpaceMode::PreWrap
1396                }
1397                strata_style::types::WhiteSpace::PreLine => {
1398                    crate::typography::WhiteSpaceMode::PreLine
1399                }
1400            },
1401            vertical_align: crate::typography::VerticalAlignment::Baseline,
1402            is_monospace: crate::text::is_monospace_family(node.style.font_family),
1403            exclusion_space: parent_exclusions,
1404            bfc_offset_y,
1405        };
1406        let res = ifc.layout_inline_stream(&node.inline_items, &opt);
1407        (res.total_width, res.total_height)
1408    } else if let Some(ref text) = node.text {
1409        let is_mono = crate::text::is_monospace_family(node.style.font_family);
1410        crate::text::measure_text_bounds_with_white_space(
1411            text,
1412            node.style.font_size,
1413            node.style.line_height,
1414            Some(text_avail_w),
1415            is_mono,
1416            node.style.white_space,
1417        )
1418    } else {
1419        (0.0, 0.0)
1420    }
1421}
1422
1423#[inline(never)]
1424fn finalize_block_geometry(node: &mut LayoutNode, border_box_width: f32, border_box_height: f32) {
1425    let border_box = Rect::new(
1426        node.geometry.border_box.x,
1427        node.geometry.border_box.y,
1428        border_box_width,
1429        border_box_height,
1430    );
1431    node.geometry = LayoutGeometry::from_border_box(
1432        border_box,
1433        node.style.padding,
1434        node.style.border_width,
1435        node.style.margin,
1436    );
1437    node.geometry.snap_to_pixel();
1438}
1439
1440#[inline(never)]
1441fn publish_truncated_ellipsis_text_leaf(node: &mut LayoutNode, content_width: f32) {
1442    let Some(ref text) = node.text else {
1443        return;
1444    };
1445    let inline_style = inline_style_from_computed_style(&node.style);
1446    let item = crate::typography::InlineItem::text(text.clone(), inline_style);
1447    let ifc = crate::typography::InlineFormattingContext::new();
1448    let opt = crate::typography::InlineLayoutOptions {
1449        font_size: node.style.font_size,
1450        line_height: Some(node.style.font_size * node.style.line_height),
1451        max_width: Some(content_width),
1452        white_space: match node.style.white_space {
1453            strata_style::types::WhiteSpace::Normal => crate::typography::WhiteSpaceMode::Normal,
1454            strata_style::types::WhiteSpace::NoWrap => crate::typography::WhiteSpaceMode::NoWrap,
1455            strata_style::types::WhiteSpace::Pre => crate::typography::WhiteSpaceMode::Pre,
1456            strata_style::types::WhiteSpace::PreWrap => crate::typography::WhiteSpaceMode::PreWrap,
1457            strata_style::types::WhiteSpace::PreLine => crate::typography::WhiteSpaceMode::PreLine,
1458        },
1459        vertical_align: crate::typography::VerticalAlignment::Baseline,
1460        is_monospace: crate::text::is_monospace_family(node.style.font_family),
1461        exclusion_space: None,
1462        bfc_offset_y: 0.0,
1463    };
1464    let mut res = ifc.layout_inline_stream(&[item], &opt);
1465    truncate_inline_overflow(node, &mut res, content_width);
1466    let origin_x = node.geometry.content_box.x;
1467    let origin_y = node.geometry.content_box.y;
1468    for line in &mut res.lines {
1469        let align_offset_x = match node.style.text_align {
1470            strata_style::types::TextAlign::Center => {
1471                ((content_width - line.bounds.width) / 2.0).max(0.0)
1472            }
1473            strata_style::types::TextAlign::Right => (content_width - line.bounds.width).max(0.0),
1474            _ => 0.0,
1475        };
1476        line.bounds.x += origin_x + align_offset_x;
1477        line.bounds.y += origin_y;
1478        for frag in &mut line.text_fragments {
1479            frag.bounds.x += origin_x + align_offset_x;
1480            frag.bounds.y += origin_y;
1481            frag.baseline_y += origin_y;
1482        }
1483    }
1484    node.line_boxes = res.lines;
1485}
1486
1487/// Executes normal-flow block layout with an active depth guard to prevent stack overflow.
1488pub fn solve_block_with_exclusions_guarded(
1489    node: &mut LayoutNode,
1490    available_width: f32,
1491    available_height: f32,
1492    parent_exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1493    bfc_offset_y: f32,
1494    guard: crate::tree::LayoutDepthGuard,
1495) {
1496    if guard.is_exhausted() {
1497        solve_block_depth_exhausted(node, available_width, available_height, guard);
1498        return;
1499    }
1500
1501    // Content-Visibility: Hidden virtualization (W3C CSS Containment Level 2)
1502    if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
1503        solve_block_content_visibility_hidden(node, available_width, available_height);
1504        return;
1505    }
1506
1507    let padding = node.style.padding;
1508    let border = node.style.border_width;
1509    let margin = node.style.margin;
1510
1511    let inset_h = padding.left + padding.right + border.left + border.right;
1512    let avail_border_w = (available_width - margin.left - margin.right).max(0.0);
1513    let max_border_limit = if let Some(explicit_w) =
1514        resolve_dimension_with_node(node.style.width, available_width, node)
1515    {
1516        let clamped = clamp_dimension_with_node(
1517            explicit_w,
1518            node.style.min_width,
1519            node.style.max_width,
1520            available_width,
1521            node,
1522        );
1523        match node.style.box_sizing {
1524            BoxSizing::BorderBox => clamped,
1525            BoxSizing::ContentBox => clamped + inset_h,
1526        }
1527    } else {
1528        let mut limit = avail_border_w;
1529        if let Some(max_w) =
1530            resolve_dimension_with_node(node.style.max_width, available_width, node)
1531        {
1532            let max_border = match node.style.box_sizing {
1533                BoxSizing::BorderBox => max_w,
1534                BoxSizing::ContentBox => max_w + inset_h,
1535            };
1536            limit = limit.min(max_border.max(0.0));
1537        }
1538        if let Some(min_w) =
1539            resolve_dimension_with_node(node.style.min_width, available_width, node)
1540        {
1541            let min_border = match node.style.box_sizing {
1542                BoxSizing::BorderBox => min_w,
1543                BoxSizing::ContentBox => min_w + inset_h,
1544            };
1545            limit = limit.max(min_border.max(0.0));
1546        }
1547        limit
1548    };
1549    let base_text_avail_w = (max_border_limit - inset_h).max(0.0);
1550    let text_avail_w = node
1551        .transition_content_width()
1552        .map_or(base_text_avail_w, |tw| base_text_avail_w.max(tw));
1553
1554    let (text_w, text_h) = if (node.children.is_empty() && !node.inline_items.is_empty())
1555        || node.text.is_some()
1556    {
1557        measure_block_leaf_inline_or_text(
1558            node,
1559            text_avail_w,
1560            parent_exclusions.as_deref(),
1561            bfc_offset_y,
1562        )
1563    } else {
1564        (0.0, 0.0)
1565    };
1566
1567    // 1. Resolve element width
1568    let resolved_width = match resolve_dimension_with_node(node.style.width, available_width, node)
1569    {
1570        Some(w) => clamp_dimension_with_node(
1571            w,
1572            node.style.min_width,
1573            node.style.max_width,
1574            available_width,
1575            node,
1576        ),
1577        None => {
1578            if node.text.is_some()
1579                || matches!(
1580                    node.style.display,
1581                    strata_style::types::Display::Inline
1582                        | strata_style::types::Display::InlineBlock
1583                )
1584            {
1585                // Shrink-to-fit for text or inline-block elements per W3C CSS 2.1 §10.3.9:
1586                // shrink_to_fit = min(max(min_content, available_width), max_content)
1587                let base_w = if !node.children.is_empty() {
1588                    let min_max =
1589                        crate::intrinsic::compute_min_max_sizes(node, Some(available_width));
1590                    let avail_content_w = (available_width
1591                        - padding.left
1592                        - padding.right
1593                        - border.left
1594                        - border.right
1595                        - margin.left
1596                        - margin.right)
1597                        .max(0.0);
1598                    min_max
1599                        .min_content
1600                        .max(avail_content_w)
1601                        .min(min_max.max_content)
1602                        .max(text_w)
1603                } else {
1604                    text_w
1605                };
1606                let mut fit_w = base_w + padding.left + padding.right + border.left + border.right;
1607                if node.style.overflow_x != strata_style::types::Overflow::Visible {
1608                    fit_w = fit_w.min(max_border_limit);
1609                }
1610                clamp_dimension_with_node(
1611                    fit_w,
1612                    node.style.min_width,
1613                    node.style.max_width,
1614                    available_width,
1615                    node,
1616                )
1617            } else {
1618                // In CSS block layout, auto width fills available width minus margins
1619                let auto_w = (available_width - margin.left - margin.right).max(0.0);
1620                clamp_dimension_with_node(
1621                    auto_w,
1622                    node.style.min_width,
1623                    node.style.max_width,
1624                    available_width,
1625                    node,
1626                )
1627            }
1628        }
1629    };
1630
1631    let border_box_width = match node.style.box_sizing {
1632        BoxSizing::BorderBox => resolved_width,
1633        BoxSizing::ContentBox => {
1634            resolved_width + padding.left + padding.right + border.left + border.right
1635        }
1636    };
1637
1638    let content_width =
1639        (border_box_width - padding.left - padding.right - border.left - border.right).max(0.0);
1640    let child_layout_width = node
1641        .transition_content_width()
1642        .map_or(content_width, |tw| content_width.max(tw));
1643
1644    // 2. Lay out in-flow children vertically with margin collapsing and floats
1645    let children_height = if node.children.is_empty() && node.text.is_some() {
1646        text_h + padding.top + padding.bottom + border.top + border.bottom
1647    } else {
1648        solve_block_children_with_exclusions_guarded(
1649            node,
1650            child_layout_width,
1651            available_height,
1652            parent_exclusions,
1653            bfc_offset_y,
1654            guard,
1655        )
1656    };
1657
1658    // 3. Resolve element height
1659    let resolved_height = match resolve_dimension(node.style.height, available_height) {
1660        Some(h) => {
1661            let clamped_h = clamp_dimension(
1662                h,
1663                node.style.min_height,
1664                node.style.max_height,
1665                available_height,
1666            );
1667            match node.style.box_sizing {
1668                BoxSizing::BorderBox => clamped_h,
1669                BoxSizing::ContentBox => {
1670                    clamped_h + padding.top + padding.bottom + border.top + border.bottom
1671                }
1672            }
1673        }
1674        None => {
1675            // Auto height wraps children
1676            clamp_dimension(
1677                children_height,
1678                node.style.min_height,
1679                node.style.max_height,
1680                available_height,
1681            )
1682        }
1683    };
1684
1685    // 4. Finalize concentric geometry boxes
1686    finalize_block_geometry(node, border_box_width, resolved_height);
1687
1688    // A text leaf that truncates must publish positioned line boxes so paint
1689    // renders the clipped ellipsis fragment instead of the full string.
1690    if node.children.is_empty()
1691        && node.style.text_overflow == strata_style::types::TextOverflow::Ellipsis
1692        && node.style.overflow_x != strata_style::types::Overflow::Visible
1693        && content_width > 0.0
1694        && node.text.is_some()
1695    {
1696        publish_truncated_ellipsis_text_leaf(node, content_width);
1697    }
1698}