Skip to main content

strata_layout/
tree.rs

1//! Layout tree node definition and top-level formatting context dispatcher.
2
3use crate::geometry::LayoutGeometry;
4use std::cell::{Cell, RefCell};
5use strata_style::types::{ComputedStyle, Display};
6
7/// SVG stroke line cap.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum StrokeLineCap {
10    #[default]
11    Butt,
12    Round,
13    Square,
14}
15
16/// SVG stroke line join.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum StrokeLineJoin {
19    #[default]
20    Miter,
21    Round,
22    Bevel,
23}
24
25/// SVG fill rule.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum FillRule {
28    #[default]
29    NonZero,
30    EvenOdd,
31}
32
33/// An SVG `<text>` or `<tspan>` text span positioned within an `<svg>` coordinate system.
34#[derive(Debug, Clone, PartialEq)]
35pub struct SvgTextData {
36    pub content: String,
37    pub x: f32,
38    pub y: f32,
39    pub font_size: f32,
40    pub font_weight: strata_style::types::FontWeight,
41    pub text_anchor: strata_style::TextAlign,
42}
43
44/// An individual SVG vector or text item within a layout node.
45#[derive(Debug, Clone, PartialEq)]
46pub struct SvgItem {
47    pub path_data: String,
48    pub text: Option<SvgTextData>,
49    pub stroke_color: Option<strata_style::types::Color>,
50    pub fill_color: Option<strata_style::types::Color>,
51    pub stroke_is_current_color: bool,
52    pub fill_is_current_color: bool,
53    pub stroke_width: f32,
54    pub stroke_linecap: StrokeLineCap,
55    pub stroke_linejoin: StrokeLineJoin,
56    pub stroke_dasharray: Vec<f32>,
57    pub fill_rule: FillRule,
58    pub view_box: (f32, f32),
59}
60
61impl SvgItem {
62    pub fn new(path_data: String, view_box: (f32, f32)) -> Self {
63        Self {
64            path_data,
65            text: None,
66            stroke_color: None,
67            fill_color: None,
68            stroke_is_current_color: false,
69            fill_is_current_color: false,
70            stroke_width: 1.0,
71            stroke_linecap: StrokeLineCap::Butt,
72            stroke_linejoin: StrokeLineJoin::Miter,
73            stroke_dasharray: Vec::new(),
74            fill_rule: FillRule::NonZero,
75            view_box,
76        }
77    }
78}
79
80use crate::typography::{InlineItem, LineBox};
81
82/// An encoded raster image carried on a layout node.
83#[derive(Debug, Clone, PartialEq)]
84pub struct ImageResource {
85    pub data: std::sync::Arc<Vec<u8>>,
86    pub width: u32,
87    pub height: u32,
88}
89
90/// Compact layout result cache for O(1) subtree re-entry during multi-pass formatting.
91#[derive(Debug, Clone, Copy, PartialEq, Default)]
92pub struct LayoutCacheEntry {
93    pub available_w: f32,
94    pub available_h: f32,
95    pub result_w: f32,
96    pub result_h: f32,
97    pub origin_x: f32,
98    pub origin_y: f32,
99    pub is_valid: bool,
100}
101
102impl LayoutCacheEntry {
103    #[inline]
104    pub const fn invalid() -> Self {
105        Self {
106            available_w: 0.0,
107            available_h: 0.0,
108            result_w: 0.0,
109            result_h: 0.0,
110            origin_x: 0.0,
111            origin_y: 0.0,
112            is_valid: false,
113        }
114    }
115}
116
117/// Maximum allowable call-stack recursion depth for layout tree formatting.
118/// Bounded to 512 frames to guarantee that total call-stack consumption stays
119/// safely bounded within default OS and test-runner stack budgets (2 MB) across all
120/// platforms and unoptimized debug builds while supporting deep enterprise DOM trees.
121pub const MAX_LAYOUT_DEPTH: usize = 512;
122
123/// Lightweight Copy-context passed through layout formatting contexts to track recursion budget.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct LayoutDepthGuard {
126    depth: usize,
127    max_depth: usize,
128}
129
130impl LayoutDepthGuard {
131    /// Constructs a root guard with default MAX_LAYOUT_DEPTH.
132    #[inline]
133    pub const fn root() -> Self {
134        Self {
135            depth: 0,
136            max_depth: MAX_LAYOUT_DEPTH,
137        }
138    }
139
140    /// Constructs a guard with a custom maximum depth limit (e.g. for testing).
141    #[inline]
142    pub const fn with_max_depth(max_depth: usize) -> Self {
143        Self {
144            depth: 0,
145            max_depth,
146        }
147    }
148
149    /// Advances the guard into a child node frame. Returns `None` if the depth budget is exhausted.
150    #[inline]
151    pub fn enter(&self) -> Option<Self> {
152        if self.depth >= self.max_depth {
153            None
154        } else {
155            Some(Self {
156                depth: self.depth + 1,
157                max_depth: self.max_depth,
158            })
159        }
160    }
161
162    #[inline]
163    pub fn current_depth(&self) -> usize {
164        self.depth
165    }
166
167    #[inline]
168    pub fn max_depth(&self) -> usize {
169        self.max_depth
170    }
171
172    #[inline]
173    pub fn is_exhausted(&self) -> bool {
174        self.depth >= self.max_depth
175    }
176}
177
178type LayoutOverflowCallback = Box<dyn Fn(usize, usize) + Send + Sync>;
179
180thread_local! {
181    static LAYOUT_OVERFLOW_CALLBACK: RefCell<Option<LayoutOverflowCallback>> = const { RefCell::new(None) };
182    static LAST_LAYOUT_OVERFLOW: Cell<Option<(usize, usize)>> = const { Cell::new(None) };
183}
184
185/// Registers an event callback triggered when layout depth exceeds MAX_LAYOUT_DEPTH.
186pub fn set_on_layout_overflow<F: Fn(usize, usize) + Send + Sync + 'static>(cb: Option<F>) {
187    LAYOUT_OVERFLOW_CALLBACK.with(|c| {
188        *c.borrow_mut() = cb.map(|f| Box::new(f) as LayoutOverflowCallback);
189    });
190}
191
192/// Returns the last recorded layout depth overflow as (depth, max_depth), if any.
193pub fn last_layout_overflow() -> Option<(usize, usize)> {
194    LAST_LAYOUT_OVERFLOW.with(|c| c.get())
195}
196
197/// Clears any recorded layout depth overflow.
198pub fn clear_layout_overflow() {
199    LAST_LAYOUT_OVERFLOW.with(|c| c.set(None));
200}
201
202/// Records a layout depth overflow occurrence, updates diagnostics, and fires the registered callback.
203pub fn record_layout_overflow(depth: usize, max_depth: usize) {
204    LAST_LAYOUT_OVERFLOW.with(|c| c.set(Some((depth, max_depth))));
205    LAYOUT_OVERFLOW_CALLBACK.with(|cb| {
206        if let Some(ref f) = *cb.borrow() {
207            f(depth, max_depth);
208        }
209    });
210}
211
212/// Placement of an anchored top-layer portal or floating element relative to its anchor box.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
214pub enum AnchorPlacement {
215    Bottom,
216    BottomStart,
217    #[default]
218    BottomEnd,
219    Top,
220    TopStart,
221    TopEnd,
222    Left,
223    LeftStart,
224    LeftEnd,
225    Right,
226    RightStart,
227    RightEnd,
228}
229
230impl AnchorPlacement {
231    /// Parses a CSS/Floating-UI placement string such as `"bottom-end"`, `"top-start"`, `"bottom"`, etc.
232    pub fn parse(raw: &str) -> Option<Self> {
233        match raw.trim().to_ascii_lowercase().as_str() {
234            "bottom" | "block-end" => Some(Self::Bottom),
235            "bottom-start" | "bottom_start" | "bottom-left" => Some(Self::BottomStart),
236            "bottom-end" | "bottom_end" | "bottom-right" => Some(Self::BottomEnd),
237            "top" | "block-start" => Some(Self::Top),
238            "top-start" | "top_start" | "top-left" => Some(Self::TopStart),
239            "top-end" | "top_end" | "top-right" => Some(Self::TopEnd),
240            "left" | "inline-start" => Some(Self::Left),
241            "left-start" | "left_start" | "left-top" => Some(Self::LeftStart),
242            "left-end" | "left_end" | "left-bottom" => Some(Self::LeftEnd),
243            "right" | "inline-end" => Some(Self::Right),
244            "right-start" | "right_start" | "right-top" => Some(Self::RightStart),
245            "right-end" | "right_end" | "right-bottom" => Some(Self::RightEnd),
246            _ => None,
247        }
248    }
249
250    /// Canonical kebab-case string representation.
251    pub const fn as_str(self) -> &'static str {
252        match self {
253            Self::Bottom => "bottom",
254            Self::BottomStart => "bottom-start",
255            Self::BottomEnd => "bottom-end",
256            Self::Top => "top",
257            Self::TopStart => "top-start",
258            Self::TopEnd => "top-end",
259            Self::Left => "left",
260            Self::LeftStart => "left-start",
261            Self::LeftEnd => "left-end",
262            Self::Right => "right",
263            Self::RightStart => "right-start",
264            Self::RightEnd => "right-end",
265        }
266    }
267
268    /// Returns the opposite primary-axis placement preserving cross-axis alignment (`bottom-end <-> top-end`).
269    pub const fn opposite(self) -> Self {
270        match self {
271            Self::Bottom => Self::Top,
272            Self::BottomStart => Self::TopStart,
273            Self::BottomEnd => Self::TopEnd,
274            Self::Top => Self::Bottom,
275            Self::TopStart => Self::BottomStart,
276            Self::TopEnd => Self::BottomEnd,
277            Self::Left => Self::Right,
278            Self::LeftStart => Self::RightStart,
279            Self::LeftEnd => Self::RightEnd,
280            Self::Right => Self::Left,
281            Self::RightStart => Self::LeftStart,
282            Self::RightEnd => Self::LeftEnd,
283        }
284    }
285
286    #[inline]
287    fn raw_coords(
288        self,
289        anchor: crate::geometry::Rect,
290        floating_w: f32,
291        floating_h: f32,
292        offset: f32,
293    ) -> (f32, f32) {
294        match self {
295            Self::Bottom => (
296                anchor.x + (anchor.width - floating_w) * 0.5,
297                anchor.y + anchor.height + offset,
298            ),
299            Self::BottomStart => (anchor.x, anchor.y + anchor.height + offset),
300            Self::BottomEnd => (
301                anchor.x + anchor.width - floating_w,
302                anchor.y + anchor.height + offset,
303            ),
304            Self::Top => (
305                anchor.x + (anchor.width - floating_w) * 0.5,
306                anchor.y - floating_h - offset,
307            ),
308            Self::TopStart => (anchor.x, anchor.y - floating_h - offset),
309            Self::TopEnd => (
310                anchor.x + anchor.width - floating_w,
311                anchor.y - floating_h - offset,
312            ),
313            Self::Left => (
314                anchor.x - floating_w - offset,
315                anchor.y + (anchor.height - floating_h) * 0.5,
316            ),
317            Self::LeftStart => (anchor.x - floating_w - offset, anchor.y),
318            Self::LeftEnd => (
319                anchor.x - floating_w - offset,
320                anchor.y + anchor.height - floating_h,
321            ),
322            Self::Right => (
323                anchor.x + anchor.width + offset,
324                anchor.y + (anchor.height - floating_h) * 0.5,
325            ),
326            Self::RightStart => (anchor.x + anchor.width + offset, anchor.y),
327            Self::RightEnd => (
328                anchor.x + anchor.width + offset,
329                anchor.y + anchor.height - floating_h,
330            ),
331        }
332    }
333}
334
335/// Computes the viewport-aware anchored `(x, y, resolved_placement)` for a floating/top-layer element,
336/// performing automatic primary-axis collision flipping (`bottom-end <-> top-end`, `left <-> right`)
337/// and cross-axis viewport shift clamping.
338#[allow(clippy::too_many_arguments)]
339pub fn solve_anchored_position(
340    anchor: crate::geometry::Rect,
341    floating_w: f32,
342    floating_h: f32,
343    placement: AnchorPlacement,
344    offset: f32,
345    flip: bool,
346    shift: bool,
347    padding: f32,
348    viewport: crate::geometry::Rect,
349) -> (f32, f32, AnchorPlacement) {
350    let min_x = viewport.x + padding;
351    let min_y = viewport.y + padding;
352    let max_x = (viewport.x + viewport.width - padding).max(min_x);
353    let max_y = (viewport.y + viewport.height - padding).max(min_y);
354
355    let mut chosen = placement;
356    let (mut x, mut y) = chosen.raw_coords(anchor, floating_w, floating_h, offset);
357
358    if flip {
359        match placement {
360            AnchorPlacement::Bottom | AnchorPlacement::BottomStart | AnchorPlacement::BottomEnd => {
361                if y + floating_h > max_y {
362                    let opp = placement.opposite();
363                    let (ox, oy) = opp.raw_coords(anchor, floating_w, floating_h, offset);
364                    let space_above = anchor.y - min_y;
365                    let space_below = max_y - (anchor.y + anchor.height);
366                    if oy >= min_y || space_above > space_below {
367                        chosen = opp;
368                        x = ox;
369                        y = oy;
370                    }
371                }
372            }
373            AnchorPlacement::Top | AnchorPlacement::TopStart | AnchorPlacement::TopEnd => {
374                if y < min_y {
375                    let opp = placement.opposite();
376                    let (ox, oy) = opp.raw_coords(anchor, floating_w, floating_h, offset);
377                    let space_above = anchor.y - min_y;
378                    let space_below = max_y - (anchor.y + anchor.height);
379                    if oy + floating_h <= max_y || space_below > space_above {
380                        chosen = opp;
381                        x = ox;
382                        y = oy;
383                    }
384                }
385            }
386            AnchorPlacement::Right | AnchorPlacement::RightStart | AnchorPlacement::RightEnd => {
387                if x + floating_w > max_x {
388                    let opp = placement.opposite();
389                    let (ox, oy) = opp.raw_coords(anchor, floating_w, floating_h, offset);
390                    let space_left = anchor.x - min_x;
391                    let space_right = max_x - (anchor.x + anchor.width);
392                    if ox >= min_x || space_left > space_right {
393                        chosen = opp;
394                        x = ox;
395                        y = oy;
396                    }
397                }
398            }
399            AnchorPlacement::Left | AnchorPlacement::LeftStart | AnchorPlacement::LeftEnd => {
400                if x < min_x {
401                    let opp = placement.opposite();
402                    let (ox, oy) = opp.raw_coords(anchor, floating_w, floating_h, offset);
403                    let space_left = anchor.x - min_x;
404                    let space_right = max_x - (anchor.x + anchor.width);
405                    if ox + floating_w <= max_x || space_right > space_left {
406                        chosen = opp;
407                        x = ox;
408                        y = oy;
409                    }
410                }
411            }
412        }
413    }
414
415    if shift {
416        let upper_x = (max_x - floating_w).max(min_x);
417        let upper_y = (max_y - floating_h).max(min_y);
418        x = x.clamp(min_x, upper_x);
419        y = y.clamp(min_y, upper_y);
420    }
421
422    (x, y, chosen)
423}
424
425/// Configuration attaching a top-layer portal or CSS anchor-positioned box to a trigger element.
426#[derive(Debug, Clone, PartialEq)]
427pub struct PortalAnchorSpec {
428    pub anchor_id: String,
429    pub placement: AnchorPlacement,
430    pub offset: f32,
431    pub flip: bool,
432    pub shift: bool,
433    pub viewport_padding: f32,
434    pub match_width: bool,
435}
436
437impl PortalAnchorSpec {
438    pub fn new(anchor_id: impl Into<String>, placement: AnchorPlacement) -> Self {
439        Self {
440            anchor_id: anchor_id.into(),
441            placement,
442            offset: 4.0,
443            flip: true,
444            shift: true,
445            viewport_padding: 8.0,
446            match_width: false,
447        }
448    }
449}
450
451/// Thread-safe type-erased handle to an embedded 3D scene (`Arc<Scene3D>`) carried on a layout node
452/// so the 2D CSS compositor can emit `DrawViewport3D` at the exact stacking-context paint order.
453#[derive(Clone)]
454pub struct ViewportSceneHandle(pub std::sync::Arc<dyn std::any::Any + Send + Sync>);
455
456impl std::fmt::Debug for ViewportSceneHandle {
457    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
458        f.debug_tuple("ViewportSceneHandle")
459            .field(&"<scene_3d>")
460            .finish()
461    }
462}
463
464impl PartialEq for ViewportSceneHandle {
465    fn eq(&self, other: &Self) -> bool {
466        std::sync::Arc::ptr_eq(&self.0, &other.0)
467    }
468}
469
470/// A node participating in the layout tree.
471#[derive(Debug, Clone, PartialEq)]
472pub struct LayoutNode {
473    pub style: ComputedStyle,
474    pub geometry: LayoutGeometry,
475    pub children: Vec<LayoutNode>,
476    pub text: Option<String>,
477    pub svg_path: Option<String>,
478    pub svg_items: Vec<SvgItem>,
479    pub image: Option<ImageResource>,
480    pub scene_3d: Option<ViewportSceneHandle>,
481    pub inline_items: Vec<InlineItem>,
482    pub line_boxes: Vec<LineBox>,
483    pub layout_cache: LayoutCacheEntry,
484    /// Content-box size used the last time this node formatted its descendants.
485    pub last_child_layout_content: Option<(f32, f32)>,
486    /// Table border grid matrix for collapsed border rendering (CSS 2.1 §17.6.2).
487    pub table_grid: Option<crate::table::TableBorderGrid>,
488    /// Unique 64-bit entity identifier associating this layout node with its blueprint element.
489    pub entity_id: strata_primitives::EntityId,
490    /// True when one or more CSS `transition-*` interpolations are currently in-flight on this node.
491    pub active_transitions: bool,
492    /// DOM `id` or `data-anchor-id` attribute used for live anchor lookup.
493    pub element_id: Option<String>,
494    /// CSS `anchor-name` (e.g. `--card-menu-trigger`) declared on this element.
495    pub anchor_name: Option<String>,
496    /// True when this element renders in the root Top Layer (`<Portal>` / `create_portal`),
497    /// escaping all ancestor `overflow`, `transform`, `filter`, and stacking-context boundaries.
498    pub is_top_layer: bool,
499    /// Live anchor positioning specification resolved against post-scroll trigger bounds.
500    pub portal_anchor: Option<Box<PortalAnchorSpec>>,
501}
502
503impl LayoutNode {
504    /// Constructs a leaf layout node with specified computed styles.
505    pub fn new(style: ComputedStyle) -> Self {
506        Self {
507            style,
508            geometry: LayoutGeometry::default(),
509            children: Vec::new(),
510            text: None,
511            svg_path: None,
512            svg_items: Vec::new(),
513            image: None,
514            scene_3d: None,
515            inline_items: Vec::new(),
516            line_boxes: Vec::new(),
517            layout_cache: LayoutCacheEntry::invalid(),
518            last_child_layout_content: None,
519            table_grid: None,
520            entity_id: strata_primitives::EntityId::NONE,
521            active_transitions: false,
522            element_id: None,
523            anchor_name: None,
524            is_top_layer: false,
525            portal_anchor: None,
526        }
527    }
528
529    /// Constructs a layout node with child nodes.
530    pub fn with_children(style: ComputedStyle, children: Vec<LayoutNode>) -> Self {
531        Self {
532            style,
533            geometry: LayoutGeometry::default(),
534            children,
535            text: None,
536            svg_path: None,
537            svg_items: Vec::new(),
538            image: None,
539            scene_3d: None,
540            inline_items: Vec::new(),
541            line_boxes: Vec::new(),
542            layout_cache: LayoutCacheEntry::invalid(),
543            last_child_layout_content: None,
544            table_grid: None,
545            entity_id: strata_primitives::EntityId::NONE,
546            active_transitions: false,
547            element_id: None,
548            anchor_name: None,
549            is_top_layer: false,
550            portal_anchor: None,
551        }
552    }
553
554    /// Constructs a text leaf node with computed styles and string content.
555    pub fn with_text(style: ComputedStyle, text: String) -> Self {
556        Self {
557            style,
558            geometry: LayoutGeometry::default(),
559            children: Vec::new(),
560            text: Some(text),
561            svg_path: None,
562            svg_items: Vec::new(),
563            image: None,
564            scene_3d: None,
565            inline_items: Vec::new(),
566            line_boxes: Vec::new(),
567            layout_cache: LayoutCacheEntry::invalid(),
568            last_child_layout_content: None,
569            table_grid: None,
570            entity_id: strata_primitives::EntityId::NONE,
571            active_transitions: false,
572            element_id: None,
573            anchor_name: None,
574            is_top_layer: false,
575            portal_anchor: None,
576        }
577    }
578
579    /// Constructs an inline phrasing container with an inline item stream.
580    pub fn with_inline_items(style: ComputedStyle, inline_items: Vec<InlineItem>) -> Self {
581        Self {
582            style,
583            geometry: LayoutGeometry::default(),
584            children: Vec::new(),
585            text: None,
586            svg_path: None,
587            svg_items: Vec::new(),
588            image: None,
589            scene_3d: None,
590            inline_items,
591            line_boxes: Vec::new(),
592            layout_cache: LayoutCacheEntry::invalid(),
593            last_child_layout_content: None,
594            table_grid: None,
595            entity_id: strata_primitives::EntityId::NONE,
596            active_transitions: false,
597            element_id: None,
598            anchor_name: None,
599            is_top_layer: false,
600            portal_anchor: None,
601        }
602    }
603
604    /// Constructs an SVG vector path leaf node with computed styles and path string.
605    pub fn with_svg_path(style: ComputedStyle, svg_path: String) -> Self {
606        Self {
607            style,
608            geometry: LayoutGeometry::default(),
609            children: Vec::new(),
610            text: None,
611            svg_path: Some(svg_path.clone()),
612            svg_items: vec![SvgItem {
613                path_data: svg_path,
614                stroke_color: None,
615                fill_color: None,
616                stroke_is_current_color: true,
617                fill_is_current_color: false,
618                stroke_width: 2.0,
619                stroke_linecap: StrokeLineCap::Round,
620                stroke_linejoin: StrokeLineJoin::Round,
621                stroke_dasharray: Vec::new(),
622                fill_rule: FillRule::NonZero,
623                view_box: (24.0, 24.0),
624                text: None,
625            }],
626            image: None,
627            scene_3d: None,
628            inline_items: Vec::new(),
629            line_boxes: Vec::new(),
630            layout_cache: LayoutCacheEntry::invalid(),
631            last_child_layout_content: None,
632            table_grid: None,
633            entity_id: strata_primitives::EntityId::NONE,
634            active_transitions: false,
635            element_id: None,
636            anchor_name: None,
637            is_top_layer: false,
638            portal_anchor: None,
639        }
640    }
641
642    /// Constructs an SVG layout node with multiple styled vector items and viewBox.
643    pub fn with_svg_items(style: ComputedStyle, svg_items: Vec<SvgItem>) -> Self {
644        let first_path = svg_items.first().map(|i| i.path_data.clone());
645        Self {
646            style,
647            geometry: LayoutGeometry::default(),
648            children: Vec::new(),
649            text: None,
650            svg_path: first_path,
651            svg_items,
652            image: None,
653            scene_3d: None,
654            inline_items: Vec::new(),
655            line_boxes: Vec::new(),
656            layout_cache: LayoutCacheEntry::invalid(),
657            last_child_layout_content: None,
658            table_grid: None,
659            entity_id: strata_primitives::EntityId::NONE,
660            active_transitions: false,
661            element_id: None,
662            anchor_name: None,
663            is_top_layer: false,
664            portal_anchor: None,
665        }
666    }
667
668    /// Constructs a replaced raster image leaf node with intrinsic dimensions.
669    pub fn with_image(style: ComputedStyle, image: ImageResource) -> Self {
670        Self {
671            style,
672            geometry: LayoutGeometry::default(),
673            children: Vec::new(),
674            text: None,
675            svg_path: None,
676            svg_items: Vec::new(),
677            image: Some(image),
678            scene_3d: None,
679            inline_items: Vec::new(),
680            line_boxes: Vec::new(),
681            layout_cache: LayoutCacheEntry::invalid(),
682            last_child_layout_content: None,
683            table_grid: None,
684            entity_id: strata_primitives::EntityId::NONE,
685            active_transitions: false,
686            element_id: None,
687            anchor_name: None,
688            is_top_layer: false,
689            portal_anchor: None,
690        }
691    }
692
693    /// Returns `true` if this node or any of its descendants currently has an active CSS transition.
694    pub fn has_active_transitions(&self) -> bool {
695        if self.active_transitions {
696            return true;
697        }
698        self.children.iter().any(|c| c.has_active_transitions())
699    }
700
701    /// Attaches a 3D viewport scene handle to this layout node.
702    pub fn with_scene_3d(mut self, handle: ViewportSceneHandle) -> Self {
703        self.scene_3d = Some(handle);
704        self
705    }
706
707    /// Mutably sets or clears the 3D viewport scene handle on this layout node.
708    pub fn set_scene_3d(&mut self, handle: Option<ViewportSceneHandle>) {
709        self.scene_3d = handle;
710    }
711
712    /// Sets the EntityId on this layout node.
713    pub fn with_entity_id(mut self, entity_id: strata_primitives::EntityId) -> Self {
714        self.entity_id = entity_id;
715        self
716    }
717
718    /// Mutably assigns the EntityId on this layout node.
719    pub fn set_entity_id(&mut self, entity_id: strata_primitives::EntityId) {
720        self.entity_id = entity_id;
721    }
722
723    /// Recursively locates a layout node by its EntityId.
724    pub fn find_by_entity_id(&self, target_id: strata_primitives::EntityId) -> Option<&LayoutNode> {
725        if !target_id.is_valid() {
726            return None;
727        }
728        if self.entity_id == target_id {
729            return Some(self);
730        }
731        for child in &self.children {
732            if let Some(found) = child.find_by_entity_id(target_id) {
733                return Some(found);
734            }
735        }
736        None
737    }
738
739    /// Recursively locates a mutable layout node by its EntityId.
740    pub fn find_by_entity_id_mut(
741        &mut self,
742        target_id: strata_primitives::EntityId,
743    ) -> Option<&mut LayoutNode> {
744        if !target_id.is_valid() {
745            return None;
746        }
747        if self.entity_id == target_id {
748            return Some(self);
749        }
750        for child in &mut self.children {
751            if let Some(found) = child.find_by_entity_id_mut(target_id) {
752                return Some(found);
753            }
754        }
755        None
756    }
757
758    /// Appends a child layout node.
759    pub fn add_child(&mut self, child: LayoutNode) {
760        self.children.push(child);
761    }
762
763    /// Evaluates if this layout node establishes an atomic CSS stacking context within `parent_display`.
764    #[inline]
765    pub fn establishes_stacking_context_in(
766        &self,
767        parent_display: Option<Display>,
768        is_root: bool,
769    ) -> bool {
770        self.style
771            .establishes_stacking_context_in(parent_display, is_root)
772    }
773
774    /// Translates this node's geometry and all descendants by (dx, dy) using an iterative heap stack (O(1) call stack).
775    pub fn translate(&mut self, dx: f32, dy: f32) {
776        if dx == 0.0 && dy == 0.0 {
777            return;
778        }
779
780        let mut stack: Vec<&mut LayoutNode> = vec![self];
781        while let Some(node) = stack.pop() {
782            node.geometry.translate(dx, dy);
783            node.layout_cache.origin_x += dx;
784            node.layout_cache.origin_y += dy;
785            for line in &mut node.line_boxes {
786                line.bounds.x += dx;
787                line.bounds.y += dy;
788                for frag in &mut line.text_fragments {
789                    frag.bounds.x += dx;
790                    frag.bounds.y += dy;
791                    frag.baseline_y += dy;
792                }
793                for atomic in &mut line.atomic_fragments {
794                    atomic.bounds.x += dx;
795                    atomic.bounds.y += dy;
796                }
797            }
798            if let Some(ref mut grid) = node.table_grid {
799                grid.translate(dx, dy);
800            }
801            for child in &mut node.children {
802                stack.push(child);
803            }
804        }
805    }
806
807    /// Translates descendants of a scroll container by `(dx, dy)` while honoring CSS containing-block
808    /// escape semantics:
809    /// - `Position::Fixed` subtrees do not scroll unless an ancestor at or inside the scroll container
810    ///   established a fixed containing block (`transform`, `filter`, `backdrop-filter`).
811    /// - `Position::Absolute` subtrees do not scroll unless an ancestor at or inside the scroll container
812    ///   established an absolute containing block (`position != Static` or fixed CB).
813    pub fn translate_scrolled(
814        &mut self,
815        dx: f32,
816        dy: f32,
817        parent_is_abs_cb: bool,
818        parent_is_fixed_cb: bool,
819    ) {
820        if dx == 0.0 && dy == 0.0 {
821            return;
822        }
823
824        let mut stack: Vec<(&mut LayoutNode, bool, bool)> =
825            vec![(self, parent_is_abs_cb, parent_is_fixed_cb)];
826        while let Some((node, abs_cb_inside, fixed_cb_inside)) = stack.pop() {
827            if node.is_top_layer {
828                continue;
829            }
830            match node.style.position {
831                strata_style::types::Position::Fixed if !fixed_cb_inside => {
832                    continue;
833                }
834                strata_style::types::Position::Absolute if !abs_cb_inside => {
835                    continue;
836                }
837                _ => {}
838            }
839
840            node.geometry.translate(dx, dy);
841            node.layout_cache.origin_x += dx;
842            node.layout_cache.origin_y += dy;
843            for line in &mut node.line_boxes {
844                line.bounds.x += dx;
845                line.bounds.y += dy;
846                for frag in &mut line.text_fragments {
847                    frag.bounds.x += dx;
848                    frag.bounds.y += dy;
849                    frag.baseline_y += dy;
850                }
851                for atomic in &mut line.atomic_fragments {
852                    atomic.bounds.x += dx;
853                    atomic.bounds.y += dy;
854                }
855            }
856            if let Some(ref mut grid) = node.table_grid {
857                grid.translate(dx, dy);
858            }
859
860            let child_fixed_cb = fixed_cb_inside || node.style.establishes_fixed_containing_block();
861            let child_abs_cb = abs_cb_inside
862                || node.style.position != strata_style::types::Position::Static
863                || child_fixed_cb;
864
865            for child in &mut node.children {
866                stack.push((child, child_abs_cb, child_fixed_cb));
867            }
868        }
869    }
870
871    /// Formats the children of this node within its already-resolved content box.
872    pub fn layout_children(&mut self) {
873        self.layout_children_guarded(LayoutDepthGuard::root());
874    }
875
876    /// Formats the children of this node with an active depth guard.
877    pub fn layout_children_guarded(&mut self, guard: LayoutDepthGuard) {
878        self.layout_children_inner_guarded(guard, true);
879    }
880
881    pub(crate) fn layout_children_inner_guarded(
882        &mut self,
883        guard: LayoutDepthGuard,
884        resolve_positioned: bool,
885    ) {
886        if (self.children.is_empty() && self.inline_items.is_empty()) || guard.is_exhausted() {
887            return;
888        }
889
890        let content_w = self.geometry.content_box.width;
891        let content_h = self.geometry.content_box.height;
892        let preserved_geom = self.geometry;
893
894        let saved_w = self.style.width;
895        let saved_h = self.style.height;
896        let saved_min_w = self.style.min_width;
897        let saved_max_w = self.style.max_width;
898        let saved_min_h = self.style.min_height;
899        let saved_max_h = self.style.max_height;
900
901        let pin_w = preserved_geom.border_box.width > 0.0
902            || matches!(saved_w, strata_style::types::Dimension::Percent(_));
903        let pin_h = preserved_geom.border_box.height > 0.0
904            || matches!(saved_h, strata_style::types::Dimension::Percent(_));
905
906        let container_avail_w = if pin_w {
907            self.style.width = strata_style::types::Dimension::Px(preserved_geom.border_box.width);
908            self.style.min_width = strata_style::types::Dimension::Auto;
909            self.style.max_width = strata_style::types::Dimension::Auto;
910            preserved_geom.border_box.width
911        } else {
912            preserved_geom.border_box.width + self.style.margin.left + self.style.margin.right
913        };
914
915        let container_avail_h = if pin_h {
916            self.style.height =
917                strata_style::types::Dimension::Px(preserved_geom.border_box.height);
918            self.style.min_height = strata_style::types::Dimension::Auto;
919            self.style.max_height = strata_style::types::Dimension::Auto;
920            preserved_geom.border_box.height
921        } else {
922            preserved_geom.border_box.height + self.style.margin.top + self.style.margin.bottom
923        };
924
925        match self.style.display {
926            Display::Flex | Display::InlineFlex => {
927                let definite_cross = if content_h > 0.0 && !pin_h {
928                    Some(content_h)
929                } else {
930                    None
931                };
932                crate::flexbox::solve_flexbox_with_definite_cross_guarded(
933                    self,
934                    container_avail_w,
935                    container_avail_h,
936                    definite_cross,
937                    guard,
938                );
939            }
940            Display::Grid | Display::InlineGrid => {
941                crate::grid::solve_grid_guarded(self, container_avail_w, container_avail_h, guard);
942            }
943            Display::Table | Display::InlineTable => {
944                crate::table::solve_table_guarded(
945                    self,
946                    container_avail_w,
947                    container_avail_h,
948                    guard,
949                );
950            }
951            Display::Block
952            | Display::ListItem
953            | Display::Inline
954            | Display::InlineBlock
955            | Display::TableRowGroup
956            | Display::TableHeaderGroup
957            | Display::TableFooterGroup
958            | Display::TableRow
959            | Display::TableCell
960            | Display::TableCaption
961            | Display::TableColumnGroup
962            | Display::TableColumn => {
963                let block_h = crate::box_model::solve_block_children_with_exclusions_guarded(
964                    self, content_w, content_h, None, 0.0, guard,
965                );
966                if saved_h == strata_style::types::Dimension::Auto {
967                    self.geometry.border_box.height = crate::box_model::clamp_dimension(
968                        block_h,
969                        saved_min_h,
970                        saved_max_h,
971                        content_h,
972                    );
973                }
974            }
975            Display::None => {}
976        }
977
978        self.style.width = saved_w;
979        self.style.height = saved_h;
980        self.style.min_width = saved_min_w;
981        self.style.max_width = saved_max_w;
982        self.style.min_height = saved_min_h;
983        self.style.max_height = saved_max_h;
984
985        let clips_y = self.style.overflow_y != strata_style::types::Overflow::Visible;
986        let final_h = if self.style.height == strata_style::types::Dimension::Auto && !clips_y {
987            self.geometry
988                .border_box
989                .height
990                .max(preserved_geom.border_box.height)
991        } else if preserved_geom.border_box.height > 0.0 {
992            preserved_geom.border_box.height
993        } else {
994            self.geometry.border_box.height
995        };
996
997        let clips_x = self.style.overflow_x != strata_style::types::Overflow::Visible;
998        let final_w = if self.style.width == strata_style::types::Dimension::Auto && !clips_x {
999            self.geometry
1000                .border_box
1001                .width
1002                .max(preserved_geom.border_box.width)
1003        } else if preserved_geom.border_box.width > 0.0 {
1004            preserved_geom.border_box.width
1005        } else {
1006            self.geometry.border_box.width
1007        };
1008
1009        self.geometry = LayoutGeometry::from_border_box(
1010            crate::geometry::Rect::new(
1011                preserved_geom.border_box.x,
1012                preserved_geom.border_box.y,
1013                final_w,
1014                final_h,
1015            ),
1016            self.style.padding,
1017            self.style.border_width,
1018            self.style.margin,
1019        );
1020
1021        if resolve_positioned && self.style.position != strata_style::types::Position::Static {
1022            crate::positioning::solve_positioning_guarded(self, content_w, content_h, guard);
1023        }
1024        self.geometry.snap_to_pixel();
1025        self.update_scroll_metrics();
1026        self.last_child_layout_content = Some((content_w, content_h));
1027        self.layout_cache.is_valid = false;
1028    }
1029
1030    /// Computes layout geometry for this node and all descendants given available bounds.
1031    pub fn compute_layout(&mut self, available_width: f32, available_height: f32) {
1032        let session_root = crate::intrinsic::begin_layout_session();
1033        let _guard = crate::prof::LayoutGuard::new();
1034        let guard = LayoutDepthGuard::root();
1035        self.compute_layout_guarded(available_width, available_height, None, 0.0, guard);
1036        crate::intrinsic::end_layout_session(session_root);
1037    }
1038
1039    /// Computes layout geometry passing an active exclusion space for float obstructions.
1040    pub fn compute_layout_with_exclusions(
1041        &mut self,
1042        available_width: f32,
1043        available_height: f32,
1044        exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1045        bfc_offset_y: f32,
1046    ) {
1047        let guard = LayoutDepthGuard::root();
1048        self.compute_layout_guarded(
1049            available_width,
1050            available_height,
1051            exclusions,
1052            bfc_offset_y,
1053            guard,
1054        );
1055    }
1056
1057    /// Computes layout geometry passing an active exclusion space and depth guard.
1058    pub fn compute_layout_guarded(
1059        &mut self,
1060        available_width: f32,
1061        available_height: f32,
1062        exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1063        bfc_offset_y: f32,
1064        guard: LayoutDepthGuard,
1065    ) {
1066        let _guard = crate::prof::LayoutGuard::new();
1067        crate::prof::observe_width(self.children.len());
1068
1069        let available_width = if available_width.is_finite() && available_width >= 0.0 {
1070            available_width.min(1e7)
1071        } else {
1072            0.0
1073        };
1074        let available_height = if available_height.is_finite() && available_height >= 0.0 {
1075            available_height.min(1e7)
1076        } else {
1077            0.0
1078        };
1079
1080        if self.style.display == Display::None {
1081            self.geometry = LayoutGeometry::default();
1082            self.layout_cache.is_valid = false;
1083            return;
1084        }
1085
1086        if guard.is_exhausted() {
1087            record_layout_overflow(guard.current_depth(), guard.max_depth());
1088            let padding = self.style.padding;
1089            let border = self.style.border_width;
1090            let margin = self.style.margin;
1091
1092            let w = crate::box_model::resolve_dimension_with_node(
1093                self.style.width,
1094                available_width,
1095                self,
1096            )
1097            .unwrap_or(available_width)
1098            .max(0.0);
1099            let h = crate::box_model::resolve_dimension(self.style.height, available_height)
1100                .unwrap_or_else(|| {
1101                    if self.text.is_some() {
1102                        self.style.font_size * self.style.line_height
1103                    } else {
1104                        0.0
1105                    }
1106                })
1107                .max(0.0);
1108
1109            self.geometry = LayoutGeometry::from_border_box(
1110                crate::geometry::Rect::new(
1111                    self.geometry.border_box.x,
1112                    self.geometry.border_box.y,
1113                    w,
1114                    h,
1115                ),
1116                padding,
1117                border,
1118                margin,
1119            );
1120            self.geometry.snap_to_pixel();
1121            self.layout_cache.is_valid = false;
1122            return;
1123        }
1124
1125        let is_unconstrained_root = exclusions
1126            .as_ref()
1127            .is_none_or(|e| e.exclusions().is_empty());
1128
1129        // Subtree layout cache hit: skip re-traversal if available dimensions are unchanged
1130        let height_independent = self.style.height == strata_style::types::Dimension::Auto
1131            && self.style.flex_basis == strata_style::types::Dimension::Auto
1132            && self.style.flex_grow == 0.0
1133            && !matches!(
1134                self.style.min_height,
1135                strata_style::types::Dimension::Percent(_)
1136            )
1137            && !matches!(
1138                self.style.max_height,
1139                strata_style::types::Dimension::Percent(_)
1140            )
1141            && !(matches!(
1142                self.style.position,
1143                strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
1144            ) && (!matches!(
1145                self.style.insets.bottom,
1146                strata_style::types::Dimension::Auto
1147            ) || matches!(
1148                self.style.insets.top,
1149                strata_style::types::Dimension::Percent(_)
1150            )))
1151            && !self.has_height_dependent_descendant();
1152        let height_matches = (available_height - self.layout_cache.available_h).abs() < 0.01
1153            || (height_independent
1154                && (self.style.content_visibility == strata_style::types::ContentVisibility::Auto
1155                    || self.layout_cache.is_valid));
1156
1157        if is_unconstrained_root
1158            && self.layout_cache.is_valid
1159            && (available_width - self.layout_cache.available_w).abs() < 0.01
1160            && height_matches
1161        {
1162            let dx = self.geometry.border_box.x - self.layout_cache.origin_x;
1163            let dy = self.geometry.border_box.y - self.layout_cache.origin_y;
1164            if dx.abs() > 0.001 || dy.abs() > 0.001 {
1165                for line in &mut self.line_boxes {
1166                    line.bounds.x += dx;
1167                    line.bounds.y += dy;
1168                    for frag in &mut line.text_fragments {
1169                        frag.bounds.x += dx;
1170                        frag.bounds.y += dy;
1171                        frag.baseline_y += dy;
1172                    }
1173                    for at in &mut line.atomic_fragments {
1174                        at.bounds.x += dx;
1175                        at.bounds.y += dy;
1176                    }
1177                }
1178                for child in &mut self.children {
1179                    child.translate(dx, dy);
1180                }
1181                self.layout_cache.origin_x = self.geometry.border_box.x;
1182                self.layout_cache.origin_y = self.geometry.border_box.y;
1183            }
1184            return;
1185        }
1186
1187        // Dispatch according to container display formatting context
1188        match self.style.display {
1189            Display::Flex | Display::InlineFlex => {
1190                crate::flexbox::solve_flexbox_guarded(
1191                    self,
1192                    available_width,
1193                    available_height,
1194                    guard,
1195                );
1196            }
1197            Display::Grid | Display::InlineGrid => {
1198                crate::grid::solve_grid_guarded(self, available_width, available_height, guard);
1199            }
1200            Display::Table | Display::InlineTable => {
1201                crate::table::solve_table_guarded(self, available_width, available_height, guard);
1202            }
1203            Display::Block
1204            | Display::ListItem
1205            | Display::Inline
1206            | Display::InlineBlock
1207            | Display::TableRowGroup
1208            | Display::TableHeaderGroup
1209            | Display::TableFooterGroup
1210            | Display::TableRow
1211            | Display::TableCell
1212            | Display::TableCaption
1213            | Display::TableColumnGroup
1214            | Display::TableColumn => {
1215                crate::box_model::solve_block_with_exclusions_guarded(
1216                    self,
1217                    available_width,
1218                    available_height,
1219                    exclusions,
1220                    bfc_offset_y,
1221                    guard,
1222                );
1223            }
1224            Display::None => unreachable!(),
1225        }
1226
1227        // Resolve relative and out-of-flow absolute/fixed positioned children
1228        crate::positioning::solve_positioning_guarded(
1229            self,
1230            available_width,
1231            available_height,
1232            guard,
1233        );
1234
1235        // Subpixel snapping and geometry sanitization
1236        self.geometry.snap_to_pixel();
1237        self.geometry.sanitize();
1238
1239        // Update scrollable overflow metrics
1240        self.update_scroll_metrics();
1241
1242        if !self.children.is_empty() || !self.inline_items.is_empty() || self.text.is_some() {
1243            self.last_child_layout_content = Some((
1244                self.geometry.content_box.width,
1245                self.geometry.content_box.height,
1246            ));
1247        }
1248
1249        // Record layout result in cache for subsequent multi-pass probes
1250        if is_unconstrained_root {
1251            self.layout_cache = LayoutCacheEntry {
1252                available_w: available_width,
1253                available_h: available_height,
1254                result_w: self.geometry.border_box.width,
1255                result_h: self.geometry.border_box.height,
1256                origin_x: self.geometry.border_box.x,
1257                origin_y: self.geometry.border_box.y,
1258                is_valid: true,
1259            };
1260        }
1261    }
1262
1263    /// Returns true if any descendant (up to an explicit pixel-height boundary) depends on parent height.
1264    fn has_height_dependent_descendant(&self) -> bool {
1265        use strata_style::types::{Dimension, Position};
1266        let mut stack: Vec<&LayoutNode> = self.children.iter().collect();
1267        while let Some(node) = stack.pop() {
1268            if matches!(node.style.height, Dimension::Percent(_))
1269                || matches!(node.style.min_height, Dimension::Percent(_))
1270                || matches!(node.style.max_height, Dimension::Percent(_))
1271                || matches!(node.style.flex_basis, Dimension::Percent(_))
1272            {
1273                return true;
1274            }
1275            if matches!(node.style.position, Position::Absolute | Position::Fixed)
1276                && (!matches!(node.style.insets.bottom, Dimension::Auto)
1277                    || matches!(node.style.insets.top, Dimension::Percent(_)))
1278            {
1279                return true;
1280            }
1281            if !matches!(node.style.height, Dimension::Px(_)) {
1282                for grand in &node.children {
1283                    stack.push(grand);
1284                }
1285            }
1286        }
1287        false
1288    }
1289
1290    /// Invalidates layout cache on this node and all descendants using an iterative heap stack.
1291    pub fn invalidate_cache(&mut self) {
1292        let mut stack: Vec<&mut LayoutNode> = vec![self];
1293        while let Some(node) = stack.pop() {
1294            node.layout_cache.is_valid = false;
1295            for child in &mut node.children {
1296                stack.push(child);
1297            }
1298        }
1299    }
1300
1301    /// Returns true if this node forms an isolated layout boundary (W3C CSS Containment Level 2 §3.1).
1302    ///
1303    /// An element is a layout boundary if internal descendant changes can never affect
1304    /// the layout of ancestor or sibling elements outside this boundary:
1305    /// 1. Explicit CSS `contain: strict` or `contain: content`
1306    /// 2. Explicit CSS `contain: layout` combined with `contain: size` or definite pixel dimensions
1307    /// 3. CSS `content-visibility: auto` or `hidden` with definite pixel dimensions
1308    /// 4. Out-of-flow positioned boxes with clipping and definite pixel dimensions
1309    pub fn is_layout_boundary(&self) -> bool {
1310        // 1. Explicit contain: strict or contain: content
1311        if self.style.contain == strata_style::types::Containment::STRICT
1312            || self.style.contain == strata_style::types::Containment::CONTENT
1313        {
1314            return true;
1315        }
1316
1317        // 2. Explicit contain: layout with contain: size
1318        if self.style.contain.layout && self.style.contain.size {
1319            return true;
1320        }
1321
1322        // 3. Explicit contain: layout with definite width and height
1323        if self.style.contain.layout && self.has_definite_dimensions() {
1324            return true;
1325        }
1326
1327        // 4. Content-visibility containment with definite dimensions
1328        if self.style.content_visibility != strata_style::types::ContentVisibility::Visible
1329            && self.has_definite_dimensions()
1330        {
1331            return true;
1332        }
1333
1334        // 5. Out-of-flow positioned boxes with clipping and definite dimensions
1335        if matches!(
1336            self.style.position,
1337            strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
1338        ) && self.has_definite_dimensions()
1339            && self.style.overflow_x != strata_style::types::Overflow::Visible
1340            && self.style.overflow_y != strata_style::types::Overflow::Visible
1341        {
1342            return true;
1343        }
1344
1345        false
1346    }
1347
1348    /// Checks if both width and height are definite non-auto pixel dimensions.
1349    #[inline]
1350    pub fn has_definite_dimensions(&self) -> bool {
1351        matches!(self.style.width, strata_style::types::Dimension::Px(_))
1352            && matches!(self.style.height, strata_style::types::Dimension::Px(_))
1353    }
1354
1355    /// Recursively searches for the nearest ancestor layout boundary containing the given index path.
1356    /// Returns the prefix of `path` that terminates at the nearest layout boundary container.
1357    pub fn find_layout_boundary_path<'a>(&self, path: &'a [usize]) -> Option<&'a [usize]> {
1358        let mut best_boundary_len = if self.is_layout_boundary() {
1359            Some(0)
1360        } else {
1361            None
1362        };
1363
1364        let mut curr = self;
1365        for (i, &child_idx) in path.iter().enumerate() {
1366            if child_idx >= curr.children.len() {
1367                break;
1368            }
1369            curr = &curr.children[child_idx];
1370            if curr.is_layout_boundary() {
1371                best_boundary_len = Some(i + 1);
1372            }
1373        }
1374
1375        best_boundary_len.map(|len| &path[..len])
1376    }
1377
1378    /// Recomputes layout for the subtree rooted at `path` within its containing layout boundary.
1379    ///
1380    /// If an ancestor layout boundary exists along `path`, layout is recomputed ONLY for that
1381    /// boundary container and its descendants, guaranteeing zero re-layouts on the rest of the tree.
1382    /// Returns `true` if a layout boundary was found and laid out locally, or `false` if root
1383    /// layout recomputation is required.
1384    pub fn compute_subgrid_or_boundary_layout(&mut self, path: &[usize]) -> bool {
1385        let boundary_len = match self.find_layout_boundary_path(path) {
1386            Some(subpath) => subpath.len(),
1387            None => return false,
1388        };
1389
1390        if boundary_len == 0 {
1391            // Root itself is the layout boundary
1392            self.layout_children();
1393            return true;
1394        }
1395
1396        // Navigate to the boundary node mutably
1397        let mut curr = self;
1398        for &idx in &path[..boundary_len] {
1399            if idx >= curr.children.len() {
1400                return false;
1401            }
1402            curr = &mut curr.children[idx];
1403        }
1404
1405        // Recompute layout strictly within the isolated boundary
1406        curr.layout_children();
1407        true
1408    }
1409
1410    /// Invalidates layout cache only for nodes along `path` under the nearest layout boundary.
1411    pub fn invalidate_layout_boundary(&mut self, path: &[usize]) -> bool {
1412        let boundary_len = match self.find_layout_boundary_path(path) {
1413            Some(subpath) => subpath.len(),
1414            None => {
1415                self.invalidate_cache();
1416                return false;
1417            }
1418        };
1419
1420        let mut curr = self;
1421        for &idx in &path[..boundary_len] {
1422            if idx >= curr.children.len() {
1423                return false;
1424            }
1425            curr = &mut curr.children[idx];
1426        }
1427
1428        curr.invalidate_cache();
1429        true
1430    }
1431
1432    /// Recursively calculates the index path to the layout node with matching EntityId.
1433    pub fn find_path_by_entity_id(
1434        &self,
1435        target_id: strata_primitives::EntityId,
1436    ) -> Option<Vec<usize>> {
1437        if !target_id.is_valid() {
1438            return None;
1439        }
1440        let mut path = Vec::new();
1441        if self.find_path_by_entity_id_internal(target_id, &mut path) {
1442            Some(path)
1443        } else {
1444            None
1445        }
1446    }
1447
1448    fn find_path_by_entity_id_internal(
1449        &self,
1450        target_id: strata_primitives::EntityId,
1451        path: &mut Vec<usize>,
1452    ) -> bool {
1453        if self.entity_id == target_id {
1454            return true;
1455        }
1456        for (i, child) in self.children.iter().enumerate() {
1457            path.push(i);
1458            if child.find_path_by_entity_id_internal(target_id, path) {
1459                return true;
1460            }
1461            path.pop();
1462        }
1463        false
1464    }
1465
1466    /// Invalidates layout cache on self and all ancestors leading down to `path`.
1467    pub fn invalidate_ancestors(&mut self, path: &[usize]) {
1468        self.layout_cache.is_valid = false;
1469        let mut curr = self;
1470        for &idx in path {
1471            if idx >= curr.children.len() {
1472                break;
1473            }
1474            curr = &mut curr.children[idx];
1475            curr.layout_cache.is_valid = false;
1476        }
1477    }
1478
1479    /// Evaluates child geometry to compute `scroll_bounds` and `has_scroll` for this container.
1480    pub fn update_scroll_metrics(&mut self) {
1481        let origin_x = self.geometry.padding_box.x;
1482        let origin_y = self.geometry.padding_box.y;
1483        let mut max_extent_x = self.geometry.content_box.width;
1484        let mut max_extent_y = self.geometry.content_box.height;
1485
1486        for child in &self.children {
1487            if child.style.display == strata_style::types::Display::None
1488                || child.style.position == strata_style::types::Position::Fixed
1489            {
1490                continue;
1491            }
1492            let child_end_x = child.geometry.border_box.max_x() - origin_x;
1493            let child_end_y = child.geometry.border_box.max_y() - origin_y;
1494            if child_end_x.is_finite() && child_end_x > max_extent_x {
1495                max_extent_x = child_end_x;
1496            }
1497            if child_end_y.is_finite() && child_end_y > max_extent_y {
1498                max_extent_y = child_end_y;
1499            }
1500        }
1501
1502        for line in &self.line_boxes {
1503            let line_end_x = line.bounds.max_x() - origin_x;
1504            let line_end_y = line.bounds.max_y() - origin_y;
1505            if line_end_x.is_finite() && line_end_x > max_extent_x {
1506                max_extent_x = line_end_x;
1507            }
1508            if line_end_y.is_finite() && line_end_y > max_extent_y {
1509                max_extent_y = line_end_y;
1510            }
1511        }
1512
1513        self.geometry.scroll_bounds = crate::geometry::Size::new(max_extent_x, max_extent_y);
1514
1515        let has_scroll_x = match self.style.overflow_x {
1516            strata_style::types::Overflow::Scroll => true,
1517            strata_style::types::Overflow::Auto => max_extent_x > self.geometry.padding_box.width,
1518            _ => false,
1519        };
1520        let has_scroll_y = match self.style.overflow_y {
1521            strata_style::types::Overflow::Scroll => true,
1522            strata_style::types::Overflow::Auto => max_extent_y > self.geometry.padding_box.height,
1523            _ => false,
1524        };
1525        self.geometry.has_scroll = (has_scroll_x, has_scroll_y);
1526        self.geometry.scroll_offset = self
1527            .geometry
1528            .clamp_scroll_offset(self.geometry.scroll_offset);
1529    }
1530}
1531
1532impl Drop for LayoutNode {
1533    fn drop(&mut self) {
1534        // Drain descendants iteratively onto a heap stack to prevent recursion stack overflow
1535        // during deallocation of deeply nested trees (e.g. 10,000+ levels).
1536        let mut stack = std::mem::take(&mut self.children);
1537        while let Some(mut node) = stack.pop() {
1538            if !node.children.is_empty() {
1539                let grandchildren = std::mem::take(&mut node.children);
1540                stack.extend(grandchildren);
1541            }
1542        }
1543    }
1544}