Skip to main content

strata_layout/
tree.rs

1//! Layout tree node definition and top-level formatting context dispatcher.
2
3use crate::geometry::{LayoutGeometry, Rect};
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/// Computes a compact 64-bit hash of the sizing and overflow style fields that flexbox/grid
91/// passes temporarily override or that affect layout box measurement.
92#[inline]
93pub(crate) fn layout_style_pin_hash(style: &ComputedStyle) -> u64 {
94    use strata_style::types::Dimension;
95    #[inline(always)]
96    fn dim_bits(d: Dimension) -> u64 {
97        match d {
98            Dimension::Auto => 0x01,
99            Dimension::Px(v) => 0x02 | ((v.to_bits() as u64) << 8),
100            Dimension::Percent(v) => 0x03 | ((v.to_bits() as u64) << 8),
101            Dimension::Vw(v) => 0x04 | ((v.to_bits() as u64) << 8),
102            Dimension::Vh(v) => 0x05 | ((v.to_bits() as u64) << 8),
103            Dimension::Rem(v) => 0x06 | ((v.to_bits() as u64) << 8),
104            Dimension::Em(v) => 0x07 | ((v.to_bits() as u64) << 8),
105            Dimension::Calc(id) => 0x08 | ((id.0 as u64) << 8),
106            Dimension::MinContent => 0x09,
107            Dimension::MaxContent => 0x0A,
108            Dimension::FitContent(v) => 0x0B | ((v.to_bits() as u64) << 8),
109        }
110    }
111    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
112    let mut mix = |v: u64| {
113        h ^= v;
114        h = h.wrapping_mul(0x100_0000_01b3);
115    };
116    mix(dim_bits(style.width));
117    mix(dim_bits(style.height));
118    mix(dim_bits(style.min_width));
119    mix(dim_bits(style.max_width));
120    mix(dim_bits(style.min_height));
121    mix(dim_bits(style.max_height));
122    mix(dim_bits(style.flex_basis));
123    mix(style.flex_grow.to_bits() as u64);
124    mix(style.flex_shrink.to_bits() as u64);
125    mix(((style.overflow_x as u64) << 16)
126        | ((style.overflow_y as u64) << 8)
127        | ((style.white_space as u64) << 4)
128        | (style.text_overflow as u64));
129    h
130}
131
132/// Compact layout result cache for O(1) subtree re-entry during multi-pass formatting.
133#[derive(Debug, Clone, Copy, PartialEq, Default)]
134pub struct LayoutCacheEntry {
135    pub available_w: f32,
136    pub available_h: f32,
137    pub result_w: f32,
138    pub result_h: f32,
139    pub origin_x: f32,
140    pub origin_y: f32,
141    pub style_pin_hash: u64,
142    pub is_valid: bool,
143}
144
145impl LayoutCacheEntry {
146    #[inline]
147    pub const fn invalid() -> Self {
148        Self {
149            available_w: 0.0,
150            available_h: 0.0,
151            result_w: 0.0,
152            result_h: 0.0,
153            origin_x: 0.0,
154            origin_y: 0.0,
155            style_pin_hash: 0,
156            is_valid: false,
157        }
158    }
159}
160
161/// Cached flexbox/grid measurement probe result (`(available_w, available_h, style_pin_hash) ->
162/// (result_w, result_h, baseline_offset)`), allowing clean subtrees to skip Pass-1 / Pass-2
163/// measurement traversals in O(1) without disturbing their final Pass-4 child geometry.
164#[derive(Debug, Clone, Copy, PartialEq, Default)]
165pub struct MeasureCacheEntry {
166    pub available_w: f32,
167    pub available_h: f32,
168    pub style_pin_hash: u64,
169    pub result_w: f32,
170    pub result_h: f32,
171    pub baseline_offset: f32,
172    pub is_valid: bool,
173}
174
175impl MeasureCacheEntry {
176    #[inline]
177    pub const fn invalid() -> Self {
178        Self {
179            available_w: 0.0,
180            available_h: 0.0,
181            style_pin_hash: 0,
182            result_w: 0.0,
183            result_h: 0.0,
184            baseline_offset: 0.0,
185            is_valid: false,
186        }
187    }
188}
189
190/// Lock-free, 2-slot persistent intrinsic [`crate::intrinsic::MinMaxSizes`] cache stored inline
191/// on every [`LayoutNode`].
192///
193/// Slot 0 caches `parent_size == None`, and Slot 1 caches the most recent `parent_size == Some(w)`.
194/// Cleared whenever this node or any descendant is invalidated, eliminating full-tree text shaping
195/// and intrinsic min/max re-traversal on unchanged reconciled subtrees across frames.
196pub struct IntrinsicCacheCell {
197    keys: [std::sync::atomic::AtomicU64; 2],
198    vals: [std::sync::atomic::AtomicU64; 2],
199}
200
201impl IntrinsicCacheCell {
202    #[inline]
203    pub const fn empty() -> Self {
204        Self {
205            keys: [
206                std::sync::atomic::AtomicU64::new(0),
207                std::sync::atomic::AtomicU64::new(0),
208            ],
209            vals: [
210                std::sync::atomic::AtomicU64::new(0),
211                std::sync::atomic::AtomicU64::new(0),
212            ],
213        }
214    }
215
216    #[inline]
217    fn encode_key(parent_size: Option<f32>) -> (usize, u64) {
218        match parent_size {
219            None => (0, 1),
220            Some(w) => (1, 2u64.wrapping_add(w.to_bits() as u64)),
221        }
222    }
223
224    #[inline]
225    pub fn get(&self, parent_size: Option<f32>) -> Option<crate::intrinsic::MinMaxSizes> {
226        let (slot, expected_key) = Self::encode_key(parent_size);
227        let k = self.keys[slot].load(std::sync::atomic::Ordering::Relaxed);
228        if k == expected_key {
229            let v = self.vals[slot].load(std::sync::atomic::Ordering::Relaxed);
230            let min_c = f32::from_bits(v as u32);
231            let max_c = f32::from_bits((v >> 32) as u32);
232            Some(crate::intrinsic::MinMaxSizes::new(min_c, max_c))
233        } else {
234            None
235        }
236    }
237
238    #[inline]
239    pub fn set(&self, parent_size: Option<f32>, sizes: crate::intrinsic::MinMaxSizes) {
240        let (slot, key) = Self::encode_key(parent_size);
241        let packed = (sizes.min_content.to_bits() as u64) | ((sizes.max_content.to_bits() as u64) << 32);
242        self.vals[slot].store(packed, std::sync::atomic::Ordering::Relaxed);
243        self.keys[slot].store(key, std::sync::atomic::Ordering::Relaxed);
244    }
245
246    #[inline]
247    pub fn clear(&self) {
248        self.keys[0].store(0, std::sync::atomic::Ordering::Relaxed);
249        self.keys[1].store(0, std::sync::atomic::Ordering::Relaxed);
250    }
251}
252
253impl Clone for IntrinsicCacheCell {
254    fn clone(&self) -> Self {
255        Self {
256            keys: [
257                std::sync::atomic::AtomicU64::new(
258                    self.keys[0].load(std::sync::atomic::Ordering::Relaxed),
259                ),
260                std::sync::atomic::AtomicU64::new(
261                    self.keys[1].load(std::sync::atomic::Ordering::Relaxed),
262                ),
263            ],
264            vals: [
265                std::sync::atomic::AtomicU64::new(
266                    self.vals[0].load(std::sync::atomic::Ordering::Relaxed),
267                ),
268                std::sync::atomic::AtomicU64::new(
269                    self.vals[1].load(std::sync::atomic::Ordering::Relaxed),
270                ),
271            ],
272        }
273    }
274}
275
276impl PartialEq for IntrinsicCacheCell {
277    fn eq(&self, _other: &Self) -> bool {
278        true
279    }
280}
281
282impl std::fmt::Debug for IntrinsicCacheCell {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("IntrinsicCacheCell").finish_non_exhaustive()
285    }
286}
287
288/// Maximum allowable call-stack recursion depth for layout tree formatting.
289/// Bounded to 512 frames to guarantee that total call-stack consumption stays
290/// safely bounded within default OS and test-runner stack budgets (2 MB) across all
291/// platforms and unoptimized debug builds while supporting deep enterprise DOM trees.
292pub const MAX_LAYOUT_DEPTH: usize = 512;
293
294/// Lightweight Copy-context passed through layout formatting contexts to track recursion budget.
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296pub struct LayoutDepthGuard {
297    depth: usize,
298    max_depth: usize,
299}
300
301impl LayoutDepthGuard {
302    /// Constructs a root guard with default MAX_LAYOUT_DEPTH.
303    #[inline]
304    pub const fn root() -> Self {
305        Self {
306            depth: 0,
307            max_depth: MAX_LAYOUT_DEPTH,
308        }
309    }
310
311    /// Constructs a guard with a custom maximum depth limit (e.g. for testing).
312    #[inline]
313    pub const fn with_max_depth(max_depth: usize) -> Self {
314        Self {
315            depth: 0,
316            max_depth,
317        }
318    }
319
320    /// Advances the guard into a child node frame. Returns `None` if the depth budget is exhausted.
321    #[inline]
322    pub fn enter(&self) -> Option<Self> {
323        if self.depth >= self.max_depth {
324            None
325        } else {
326            Some(Self {
327                depth: self.depth + 1,
328                max_depth: self.max_depth,
329            })
330        }
331    }
332
333    #[inline]
334    pub fn current_depth(&self) -> usize {
335        self.depth
336    }
337
338    #[inline]
339    pub fn max_depth(&self) -> usize {
340        self.max_depth
341    }
342
343    #[inline]
344    pub fn is_exhausted(&self) -> bool {
345        self.depth >= self.max_depth
346    }
347}
348
349type LayoutOverflowCallback = Box<dyn Fn(usize, usize) + Send + Sync>;
350
351thread_local! {
352    static LAYOUT_OVERFLOW_CALLBACK: RefCell<Option<LayoutOverflowCallback>> = const { RefCell::new(None) };
353    static LAST_LAYOUT_OVERFLOW: Cell<Option<(usize, usize)>> = const { Cell::new(None) };
354}
355
356/// Registers an event callback triggered when layout depth exceeds MAX_LAYOUT_DEPTH.
357pub fn set_on_layout_overflow<F: Fn(usize, usize) + Send + Sync + 'static>(cb: Option<F>) {
358    LAYOUT_OVERFLOW_CALLBACK.with(|c| {
359        *c.borrow_mut() = cb.map(|f| Box::new(f) as LayoutOverflowCallback);
360    });
361}
362
363/// Returns the last recorded layout depth overflow as (depth, max_depth), if any.
364pub fn last_layout_overflow() -> Option<(usize, usize)> {
365    LAST_LAYOUT_OVERFLOW.with(|c| c.get())
366}
367
368/// Clears any recorded layout depth overflow.
369pub fn clear_layout_overflow() {
370    LAST_LAYOUT_OVERFLOW.with(|c| c.set(None));
371}
372
373/// Records a layout depth overflow occurrence, updates diagnostics, and fires the registered callback.
374pub fn record_layout_overflow(depth: usize, max_depth: usize) {
375    LAST_LAYOUT_OVERFLOW.with(|c| c.set(Some((depth, max_depth))));
376    LAYOUT_OVERFLOW_CALLBACK.with(|cb| {
377        if let Some(ref f) = *cb.borrow() {
378            f(depth, max_depth);
379        }
380    });
381}
382
383/// Placement of an anchored top-layer portal or floating element relative to its anchor box.
384#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
385pub enum AnchorPlacement {
386    Bottom,
387    BottomStart,
388    #[default]
389    BottomEnd,
390    Top,
391    TopStart,
392    TopEnd,
393    Left,
394    LeftStart,
395    LeftEnd,
396    Right,
397    RightStart,
398    RightEnd,
399}
400
401impl AnchorPlacement {
402    /// Parses a CSS/Floating-UI placement string such as `"bottom-end"`, `"top-start"`, `"bottom"`, etc.
403    pub fn parse(raw: &str) -> Option<Self> {
404        match raw.trim().to_ascii_lowercase().as_str() {
405            "bottom" | "block-end" => Some(Self::Bottom),
406            "bottom-start" | "bottom_start" | "bottom-left" => Some(Self::BottomStart),
407            "bottom-end" | "bottom_end" | "bottom-right" => Some(Self::BottomEnd),
408            "top" | "block-start" => Some(Self::Top),
409            "top-start" | "top_start" | "top-left" => Some(Self::TopStart),
410            "top-end" | "top_end" | "top-right" => Some(Self::TopEnd),
411            "left" | "inline-start" => Some(Self::Left),
412            "left-start" | "left_start" | "left-top" => Some(Self::LeftStart),
413            "left-end" | "left_end" | "left-bottom" => Some(Self::LeftEnd),
414            "right" | "inline-end" => Some(Self::Right),
415            "right-start" | "right_start" | "right-top" => Some(Self::RightStart),
416            "right-end" | "right_end" | "right-bottom" => Some(Self::RightEnd),
417            _ => None,
418        }
419    }
420
421    /// Canonical kebab-case string representation.
422    pub const fn as_str(self) -> &'static str {
423        match self {
424            Self::Bottom => "bottom",
425            Self::BottomStart => "bottom-start",
426            Self::BottomEnd => "bottom-end",
427            Self::Top => "top",
428            Self::TopStart => "top-start",
429            Self::TopEnd => "top-end",
430            Self::Left => "left",
431            Self::LeftStart => "left-start",
432            Self::LeftEnd => "left-end",
433            Self::Right => "right",
434            Self::RightStart => "right-start",
435            Self::RightEnd => "right-end",
436        }
437    }
438
439    /// Returns the opposite primary-axis placement preserving cross-axis alignment (`bottom-end <-> top-end`).
440    pub const fn opposite(self) -> Self {
441        match self {
442            Self::Bottom => Self::Top,
443            Self::BottomStart => Self::TopStart,
444            Self::BottomEnd => Self::TopEnd,
445            Self::Top => Self::Bottom,
446            Self::TopStart => Self::BottomStart,
447            Self::TopEnd => Self::BottomEnd,
448            Self::Left => Self::Right,
449            Self::LeftStart => Self::RightStart,
450            Self::LeftEnd => Self::RightEnd,
451            Self::Right => Self::Left,
452            Self::RightStart => Self::LeftStart,
453            Self::RightEnd => Self::LeftEnd,
454        }
455    }
456
457    #[inline]
458    fn raw_coords(
459        self,
460        anchor: crate::geometry::Rect,
461        floating_w: f32,
462        floating_h: f32,
463        offset: f32,
464    ) -> (f32, f32) {
465        match self {
466            Self::Bottom => (
467                anchor.x + (anchor.width - floating_w) * 0.5,
468                anchor.y + anchor.height + offset,
469            ),
470            Self::BottomStart => (anchor.x, anchor.y + anchor.height + offset),
471            Self::BottomEnd => (
472                anchor.x + anchor.width - floating_w,
473                anchor.y + anchor.height + offset,
474            ),
475            Self::Top => (
476                anchor.x + (anchor.width - floating_w) * 0.5,
477                anchor.y - floating_h - offset,
478            ),
479            Self::TopStart => (anchor.x, anchor.y - floating_h - offset),
480            Self::TopEnd => (
481                anchor.x + anchor.width - floating_w,
482                anchor.y - floating_h - offset,
483            ),
484            Self::Left => (
485                anchor.x - floating_w - offset,
486                anchor.y + (anchor.height - floating_h) * 0.5,
487            ),
488            Self::LeftStart => (anchor.x - floating_w - offset, anchor.y),
489            Self::LeftEnd => (
490                anchor.x - floating_w - offset,
491                anchor.y + anchor.height - floating_h,
492            ),
493            Self::Right => (
494                anchor.x + anchor.width + offset,
495                anchor.y + (anchor.height - floating_h) * 0.5,
496            ),
497            Self::RightStart => (anchor.x + anchor.width + offset, anchor.y),
498            Self::RightEnd => (
499                anchor.x + anchor.width + offset,
500                anchor.y + anchor.height - floating_h,
501            ),
502        }
503    }
504}
505
506/// Computes the viewport-aware anchored `(x, y, resolved_placement)` for a floating/top-layer element,
507/// performing automatic primary-axis collision flipping (`bottom-end <-> top-end`, `left <-> right`)
508/// and cross-axis viewport shift clamping.
509#[allow(clippy::too_many_arguments)]
510pub fn solve_anchored_position(
511    anchor: crate::geometry::Rect,
512    floating_w: f32,
513    floating_h: f32,
514    placement: AnchorPlacement,
515    offset: f32,
516    flip: bool,
517    shift: bool,
518    padding: f32,
519    viewport: crate::geometry::Rect,
520) -> (f32, f32, AnchorPlacement) {
521    let min_x = viewport.x + padding;
522    let min_y = viewport.y + padding;
523    let max_x = (viewport.x + viewport.width - padding).max(min_x);
524    let max_y = (viewport.y + viewport.height - padding).max(min_y);
525
526    let axis_score = |cand: AnchorPlacement, cx: f32, cy: f32| -> f32 {
527        let left_ov = (min_x - cx).max(0.0);
528        let right_ov = (cx + floating_w - max_x).max(0.0);
529        let top_ov = (min_y - cy).max(0.0);
530        let bottom_ov = (cy + floating_h - max_y).max(0.0);
531        if !shift {
532            return left_ov + right_ov + top_ov + bottom_ov;
533        }
534        // When shift is enabled, cross-axis overflow (e.g. horizontal clamp on Bottom*) is resolved
535        // cleanly by viewport clamping unless another primary/cardinal side fits with zero overflow.
536        let cross_fits = left_ov <= 0.001 && right_ov <= 0.001;
537        let vert_fits = top_ov <= 0.001 && bottom_ov <= 0.001;
538        match cand {
539            AnchorPlacement::Bottom
540            | AnchorPlacement::BottomStart
541            | AnchorPlacement::BottomEnd
542            | AnchorPlacement::Top
543            | AnchorPlacement::TopStart
544            | AnchorPlacement::TopEnd => {
545                let main_ov = top_ov + bottom_ov;
546                if main_ov <= 0.001 && cross_fits {
547                    0.0
548                } else {
549                    main_ov
550                }
551            }
552            AnchorPlacement::Left
553            | AnchorPlacement::LeftStart
554            | AnchorPlacement::LeftEnd
555            | AnchorPlacement::Right
556            | AnchorPlacement::RightStart
557            | AnchorPlacement::RightEnd => {
558                let main_ov = left_ov + right_ov;
559                if main_ov <= 0.001 && vert_fits {
560                    0.0
561                } else {
562                    main_ov + (top_ov + bottom_ov) * 0.25
563                }
564            }
565        }
566    };
567
568    let candidates: [AnchorPlacement; 6] = if shift {
569        match placement {
570            AnchorPlacement::BottomStart => [
571                AnchorPlacement::BottomStart,
572                AnchorPlacement::TopStart,
573                AnchorPlacement::RightStart,
574                AnchorPlacement::LeftStart,
575                AnchorPlacement::BottomEnd,
576                AnchorPlacement::TopEnd,
577            ],
578            AnchorPlacement::BottomEnd => [
579                AnchorPlacement::BottomEnd,
580                AnchorPlacement::TopEnd,
581                AnchorPlacement::LeftEnd,
582                AnchorPlacement::RightEnd,
583                AnchorPlacement::BottomStart,
584                AnchorPlacement::TopStart,
585            ],
586            AnchorPlacement::Bottom => [
587                AnchorPlacement::Bottom,
588                AnchorPlacement::Top,
589                AnchorPlacement::Right,
590                AnchorPlacement::Left,
591                AnchorPlacement::BottomStart,
592                AnchorPlacement::BottomEnd,
593            ],
594            AnchorPlacement::TopStart => [
595                AnchorPlacement::TopStart,
596                AnchorPlacement::BottomStart,
597                AnchorPlacement::RightStart,
598                AnchorPlacement::LeftStart,
599                AnchorPlacement::TopEnd,
600                AnchorPlacement::BottomEnd,
601            ],
602            AnchorPlacement::TopEnd => [
603                AnchorPlacement::TopEnd,
604                AnchorPlacement::BottomEnd,
605                AnchorPlacement::LeftEnd,
606                AnchorPlacement::RightEnd,
607                AnchorPlacement::TopStart,
608                AnchorPlacement::BottomStart,
609            ],
610            AnchorPlacement::Top => [
611                AnchorPlacement::Top,
612                AnchorPlacement::Bottom,
613                AnchorPlacement::Right,
614                AnchorPlacement::Left,
615                AnchorPlacement::TopStart,
616                AnchorPlacement::TopEnd,
617            ],
618            AnchorPlacement::RightStart => [
619                AnchorPlacement::RightStart,
620                AnchorPlacement::LeftStart,
621                AnchorPlacement::BottomStart,
622                AnchorPlacement::TopStart,
623                AnchorPlacement::RightEnd,
624                AnchorPlacement::LeftEnd,
625            ],
626            AnchorPlacement::RightEnd => [
627                AnchorPlacement::RightEnd,
628                AnchorPlacement::LeftEnd,
629                AnchorPlacement::BottomEnd,
630                AnchorPlacement::TopEnd,
631                AnchorPlacement::RightStart,
632                AnchorPlacement::LeftStart,
633            ],
634            AnchorPlacement::Right => [
635                AnchorPlacement::Right,
636                AnchorPlacement::Left,
637                AnchorPlacement::Bottom,
638                AnchorPlacement::Top,
639                AnchorPlacement::RightStart,
640                AnchorPlacement::RightEnd,
641            ],
642            AnchorPlacement::LeftStart => [
643                AnchorPlacement::LeftStart,
644                AnchorPlacement::RightStart,
645                AnchorPlacement::BottomStart,
646                AnchorPlacement::TopStart,
647                AnchorPlacement::LeftEnd,
648                AnchorPlacement::RightEnd,
649            ],
650            AnchorPlacement::LeftEnd => [
651                AnchorPlacement::LeftEnd,
652                AnchorPlacement::RightEnd,
653                AnchorPlacement::BottomEnd,
654                AnchorPlacement::TopEnd,
655                AnchorPlacement::LeftStart,
656                AnchorPlacement::RightStart,
657            ],
658            AnchorPlacement::Left => [
659                AnchorPlacement::Left,
660                AnchorPlacement::Right,
661                AnchorPlacement::Bottom,
662                AnchorPlacement::Top,
663                AnchorPlacement::LeftStart,
664                AnchorPlacement::LeftEnd,
665            ],
666        }
667    } else {
668        match placement {
669            AnchorPlacement::BottomStart => [
670                AnchorPlacement::BottomStart,
671                AnchorPlacement::TopStart,
672                AnchorPlacement::BottomEnd,
673                AnchorPlacement::TopEnd,
674                AnchorPlacement::RightStart,
675                AnchorPlacement::LeftStart,
676            ],
677            AnchorPlacement::BottomEnd => [
678                AnchorPlacement::BottomEnd,
679                AnchorPlacement::TopEnd,
680                AnchorPlacement::BottomStart,
681                AnchorPlacement::TopStart,
682                AnchorPlacement::LeftEnd,
683                AnchorPlacement::RightEnd,
684            ],
685            AnchorPlacement::Bottom => [
686                AnchorPlacement::Bottom,
687                AnchorPlacement::Top,
688                AnchorPlacement::BottomStart,
689                AnchorPlacement::BottomEnd,
690                AnchorPlacement::Right,
691                AnchorPlacement::Left,
692            ],
693            AnchorPlacement::TopStart => [
694                AnchorPlacement::TopStart,
695                AnchorPlacement::BottomStart,
696                AnchorPlacement::TopEnd,
697                AnchorPlacement::BottomEnd,
698                AnchorPlacement::RightStart,
699                AnchorPlacement::LeftStart,
700            ],
701            AnchorPlacement::TopEnd => [
702                AnchorPlacement::TopEnd,
703                AnchorPlacement::BottomEnd,
704                AnchorPlacement::TopStart,
705                AnchorPlacement::BottomStart,
706                AnchorPlacement::LeftEnd,
707                AnchorPlacement::RightEnd,
708            ],
709            AnchorPlacement::Top => [
710                AnchorPlacement::Top,
711                AnchorPlacement::Bottom,
712                AnchorPlacement::TopStart,
713                AnchorPlacement::TopEnd,
714                AnchorPlacement::Right,
715                AnchorPlacement::Left,
716            ],
717            AnchorPlacement::RightStart => [
718                AnchorPlacement::RightStart,
719                AnchorPlacement::LeftStart,
720                AnchorPlacement::RightEnd,
721                AnchorPlacement::LeftEnd,
722                AnchorPlacement::BottomStart,
723                AnchorPlacement::TopStart,
724            ],
725            AnchorPlacement::RightEnd => [
726                AnchorPlacement::RightEnd,
727                AnchorPlacement::LeftEnd,
728                AnchorPlacement::RightStart,
729                AnchorPlacement::LeftStart,
730                AnchorPlacement::BottomEnd,
731                AnchorPlacement::TopEnd,
732            ],
733            AnchorPlacement::Right => [
734                AnchorPlacement::Right,
735                AnchorPlacement::Left,
736                AnchorPlacement::RightStart,
737                AnchorPlacement::RightEnd,
738                AnchorPlacement::Bottom,
739                AnchorPlacement::Top,
740            ],
741            AnchorPlacement::LeftStart => [
742                AnchorPlacement::LeftStart,
743                AnchorPlacement::RightStart,
744                AnchorPlacement::LeftEnd,
745                AnchorPlacement::RightEnd,
746                AnchorPlacement::BottomStart,
747                AnchorPlacement::TopStart,
748            ],
749            AnchorPlacement::LeftEnd => [
750                AnchorPlacement::LeftEnd,
751                AnchorPlacement::RightEnd,
752                AnchorPlacement::LeftStart,
753                AnchorPlacement::RightStart,
754                AnchorPlacement::BottomEnd,
755                AnchorPlacement::TopEnd,
756            ],
757            AnchorPlacement::Left => [
758                AnchorPlacement::Left,
759                AnchorPlacement::Right,
760                AnchorPlacement::LeftStart,
761                AnchorPlacement::LeftEnd,
762                AnchorPlacement::Bottom,
763                AnchorPlacement::Top,
764            ],
765        }
766    };
767
768    let mut chosen = placement;
769    let (mut x, mut y) = chosen.raw_coords(anchor, floating_w, floating_h, offset);
770
771    if flip {
772        let eval_len = if shift { 4 } else { candidates.len() };
773        let mut best_score = axis_score(chosen, x, y);
774        if best_score > 0.001 {
775            for &cand in &candidates[1..eval_len] {
776                let (cx, cy) = cand.raw_coords(anchor, floating_w, floating_h, offset);
777                let score = axis_score(cand, cx, cy);
778                if score + 0.001 < best_score {
779                    best_score = score;
780                    chosen = cand;
781                    x = cx;
782                    y = cy;
783                    if best_score <= 0.001 {
784                        break;
785                    }
786                }
787            }
788        }
789    }
790
791    if shift {
792        let upper_x = (max_x - floating_w).max(min_x);
793        let upper_y = (max_y - floating_h).max(min_y);
794        x = x.clamp(min_x, upper_x);
795        y = y.clamp(min_y, upper_y);
796    }
797
798    (x, y, chosen)
799}
800
801/// Configuration attaching a top-layer portal or CSS anchor-positioned box to a trigger element.
802#[derive(Debug, Clone, PartialEq)]
803pub struct PortalAnchorSpec {
804    pub anchor_id: String,
805    pub placement: AnchorPlacement,
806    pub offset: f32,
807    pub flip: bool,
808    pub shift: bool,
809    pub viewport_padding: f32,
810    pub match_width: bool,
811    pub min_width_from_anchor: bool,
812}
813
814impl PortalAnchorSpec {
815    pub fn new(anchor_id: impl Into<String>, placement: AnchorPlacement) -> Self {
816        Self {
817            anchor_id: anchor_id.into(),
818            placement,
819            offset: 4.0,
820            flip: true,
821            shift: true,
822            viewport_padding: 8.0,
823            match_width: false,
824            min_width_from_anchor: false,
825        }
826    }
827}
828
829/// Thread-safe type-erased handle to an embedded 3D scene (`Arc<Scene3D>`) carried on a layout node
830/// so the 2D CSS compositor can emit `DrawViewport3D` at the exact stacking-context paint order.
831#[derive(Clone)]
832pub struct ViewportSceneHandle(pub std::sync::Arc<dyn std::any::Any + Send + Sync>);
833
834impl std::fmt::Debug for ViewportSceneHandle {
835    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836        f.debug_tuple("ViewportSceneHandle")
837            .field(&"<scene_3d>")
838            .finish()
839    }
840}
841
842impl PartialEq for ViewportSceneHandle {
843    fn eq(&self, other: &Self) -> bool {
844        std::sync::Arc::ptr_eq(&self.0, &other.0)
845    }
846}
847
848/// Subtree hit-testing bitflags stored on [`LayoutNode::subtree_hit_flags`].
849pub const SUBTREE_HAS_TOP_LAYER: u8 = 1 << 0;
850pub const SUBTREE_HAS_HOISTED: u8 = 1 << 1;
851pub const SUBTREE_HAS_TRANSFORM: u8 = 1 << 2;
852pub const SUBTREE_META_VALID: u8 = 1 << 3;
853/// Cached summary bit indicating whether any descendant (up to an explicit pixel-height boundary)
854/// depends on parent height (`has_height_dependent_descendant`).
855pub const SUBTREE_HAS_HEIGHT_DEP_DESCENDANT: u8 = 1 << 4;
856
857/// A node participating in the layout tree.
858#[derive(Debug, Clone, PartialEq)]
859pub struct LayoutNode {
860    pub style: ComputedStyle,
861    pub geometry: LayoutGeometry,
862    pub children: Vec<LayoutNode>,
863    pub text: Option<String>,
864    pub svg_path: Option<String>,
865    pub svg_items: Vec<SvgItem>,
866    pub image: Option<ImageResource>,
867    pub scene_3d: Option<ViewportSceneHandle>,
868    pub inline_items: Vec<InlineItem>,
869    pub line_boxes: Vec<LineBox>,
870    pub layout_cache: LayoutCacheEntry,
871    /// Two-slot measurement probe cache used by Flexbox Pass 1 & Pass 2 to skip clean subtrees
872    /// in O(1) without clobbering their final Pass-4 child geometry.
873    pub measure_cache: [MeasureCacheEntry; 2],
874    /// Persistent per-node intrinsic min/max sizing cache cleared only on subtree invalidation.
875    pub intrinsic_cache: IntrinsicCacheCell,
876    /// Content-box size used the last time this node formatted its descendants.
877    pub last_child_layout_content: Option<(f32, f32)>,
878    /// True when this node's descendants have been laid out for the current style/tree state and
879    /// neither `self` nor any descendant has been invalidated since.
880    pub children_layout_clean: bool,
881    /// Last preserved box parameters `(x, y, border_w, border_h, resolve_positioned)` formatted by
882    /// `layout_children_inner_guarded`, enabling O(1) skip + translate when unchanged.
883    pub last_preserved_box: Option<(f32, f32, f32, f32, bool)>,
884    /// Table border grid matrix for collapsed border rendering (CSS 2.1 ยง17.6.2).
885    pub table_grid: Option<crate::table::TableBorderGrid>,
886    /// Unique 64-bit entity identifier associating this layout node with its blueprint element.
887    pub entity_id: strata_primitives::EntityId,
888    /// True when one or more CSS `transition-*` interpolations are currently in-flight on this node.
889    pub active_transitions: bool,
890    /// DOM `id` or `data-anchor-id` attribute used for live anchor lookup.
891    pub element_id: Option<String>,
892    /// CSS `anchor-name` (e.g. `--card-menu-trigger`) declared on this element.
893    pub anchor_name: Option<String>,
894    /// True when this element renders in the root Top Layer (`<Portal>` / `create_portal`),
895    /// escaping all ancestor `overflow`, `transform`, `filter`, and stacking-context boundaries.
896    pub is_top_layer: bool,
897    /// Live anchor positioning specification resolved against post-scroll trigger bounds.
898    pub portal_anchor: Option<Box<PortalAnchorSpec>>,
899    /// Bitflags summarizing descendants (`SUBTREE_HAS_*`, `SUBTREE_META_VALID`).
900    pub subtree_hit_flags: u8,
901    /// Conservative axis-aligned bounding box covering this node and in-flow descendants.
902    pub subtree_bounds: Rect,
903    /// Expanded border-box width locked during collapse/expand transitions so children avoid 0px squeeze.
904    pub transition_layout_width_px: Option<f32>,
905    /// Expanded border-box height locked during collapse/expand transitions so children avoid 0px squeeze.
906    pub transition_layout_height_px: Option<f32>,
907}
908
909impl LayoutNode {
910    /// Constructs a leaf layout node with specified computed styles.
911    pub fn new(style: ComputedStyle) -> Self {
912        Self {
913            style,
914            geometry: LayoutGeometry::default(),
915            children: Vec::new(),
916            text: None,
917            svg_path: None,
918            svg_items: Vec::new(),
919            image: None,
920            scene_3d: None,
921            inline_items: Vec::new(),
922            line_boxes: Vec::new(),
923            layout_cache: LayoutCacheEntry::invalid(),
924            measure_cache: [MeasureCacheEntry::invalid(); 2],
925            intrinsic_cache: IntrinsicCacheCell::empty(),
926            last_child_layout_content: None,
927            children_layout_clean: false,
928            last_preserved_box: None,
929            table_grid: None,
930            entity_id: strata_primitives::EntityId::NONE,
931            active_transitions: false,
932            element_id: None,
933            anchor_name: None,
934            is_top_layer: false,
935            portal_anchor: None,
936            subtree_hit_flags: 0,
937            subtree_bounds: Rect::new(0.0, 0.0, 0.0, 0.0),
938            transition_layout_width_px: None,
939            transition_layout_height_px: None,
940        }
941    }
942
943    /// Constructs a layout node with child nodes.
944    pub fn with_children(style: ComputedStyle, children: Vec<LayoutNode>) -> Self {
945        let mut node = Self::new(style);
946        node.children = children;
947        node
948    }
949
950    /// Constructs a text leaf node with computed styles and string content.
951    pub fn with_text(style: ComputedStyle, text: String) -> Self {
952        let mut node = Self::new(style);
953        node.text = Some(text);
954        node
955    }
956
957    /// Constructs an inline phrasing container with an inline item stream.
958    pub fn with_inline_items(style: ComputedStyle, inline_items: Vec<InlineItem>) -> Self {
959        let mut node = Self::new(style);
960        node.inline_items = inline_items;
961        node
962    }
963
964    /// Constructs an SVG vector path leaf node with computed styles and path string.
965    pub fn with_svg_path(style: ComputedStyle, svg_path: String) -> Self {
966        let mut node = Self::new(style);
967        node.svg_path = Some(svg_path.clone());
968        node.svg_items = vec![SvgItem {
969            path_data: svg_path,
970            stroke_color: None,
971            fill_color: None,
972            stroke_is_current_color: true,
973            fill_is_current_color: false,
974            stroke_width: 2.0,
975            stroke_linecap: StrokeLineCap::Round,
976            stroke_linejoin: StrokeLineJoin::Round,
977            stroke_dasharray: Vec::new(),
978            fill_rule: FillRule::NonZero,
979            view_box: (24.0, 24.0),
980            text: None,
981        }];
982        node
983    }
984
985    /// Constructs an SVG layout node with multiple styled vector items and viewBox.
986    pub fn with_svg_items(style: ComputedStyle, svg_items: Vec<SvgItem>) -> Self {
987        let first_path = svg_items.first().map(|i| i.path_data.clone());
988        let mut node = Self::new(style);
989        node.svg_path = first_path;
990        node.svg_items = svg_items;
991        node
992    }
993
994    /// Constructs a replaced raster image leaf node with intrinsic dimensions.
995    pub fn with_image(style: ComputedStyle, image: ImageResource) -> Self {
996        let mut node = Self::new(style);
997        node.image = Some(image);
998        node
999    }
1000
1001    /// Returns `true` if this node or any of its descendants currently has an active CSS transition.
1002    pub fn has_active_transitions(&self) -> bool {
1003        if self.active_transitions {
1004            return true;
1005        }
1006        self.children.iter().any(|c| c.has_active_transitions())
1007    }
1008
1009    /// Inner content-box width override used during collapse/expand transitions so children
1010    /// keep their expanded layout width without squeezing to zero mid-animation.
1011    #[inline]
1012    pub fn transition_content_width(&self) -> Option<f32> {
1013        let inset_h = self.style.padding.left
1014            + self.style.padding.right
1015            + self.style.border_width.left
1016            + self.style.border_width.right;
1017        self.transition_layout_width_px
1018            .map(|w| (w - inset_h).max(0.0))
1019    }
1020
1021    /// Inner content-box height override used during collapse/expand transitions.
1022    #[inline]
1023    pub fn transition_content_height(&self) -> Option<f32> {
1024        let inset_v = self.style.padding.top
1025            + self.style.padding.bottom
1026            + self.style.border_width.top
1027            + self.style.border_width.bottom;
1028        self.transition_layout_height_px
1029            .map(|h| (h - inset_v).max(0.0))
1030    }
1031
1032    /// Attaches a 3D viewport scene handle to this layout node.
1033    pub fn with_scene_3d(mut self, handle: ViewportSceneHandle) -> Self {
1034        self.scene_3d = Some(handle);
1035        self
1036    }
1037
1038    /// Mutably sets or clears the 3D viewport scene handle on this layout node.
1039    pub fn set_scene_3d(&mut self, handle: Option<ViewportSceneHandle>) {
1040        self.scene_3d = handle;
1041    }
1042
1043    /// Sets the EntityId on this layout node.
1044    pub fn with_entity_id(mut self, entity_id: strata_primitives::EntityId) -> Self {
1045        self.entity_id = entity_id;
1046        self
1047    }
1048
1049    /// Mutably assigns the EntityId on this layout node.
1050    pub fn set_entity_id(&mut self, entity_id: strata_primitives::EntityId) {
1051        self.entity_id = entity_id;
1052    }
1053
1054    /// Recursively locates a layout node by its EntityId.
1055    pub fn find_by_entity_id(&self, target_id: strata_primitives::EntityId) -> Option<&LayoutNode> {
1056        if !target_id.is_valid() {
1057            return None;
1058        }
1059        if self.entity_id == target_id {
1060            return Some(self);
1061        }
1062        for child in &self.children {
1063            if let Some(found) = child.find_by_entity_id(target_id) {
1064                return Some(found);
1065            }
1066        }
1067        None
1068    }
1069
1070    /// Recursively locates a mutable layout node by its EntityId.
1071    pub fn find_by_entity_id_mut(
1072        &mut self,
1073        target_id: strata_primitives::EntityId,
1074    ) -> Option<&mut LayoutNode> {
1075        if !target_id.is_valid() {
1076            return None;
1077        }
1078        if self.entity_id == target_id {
1079            return Some(self);
1080        }
1081        for child in &mut self.children {
1082            if let Some(found) = child.find_by_entity_id_mut(target_id) {
1083                return Some(found);
1084            }
1085        }
1086        None
1087    }
1088
1089    /// Appends a child layout node.
1090    pub fn add_child(&mut self, child: LayoutNode) {
1091        self.children.push(child);
1092    }
1093
1094    /// Evaluates if this layout node establishes an atomic CSS stacking context within `parent_display`.
1095    #[inline]
1096    pub fn establishes_stacking_context_in(
1097        &self,
1098        parent_display: Option<Display>,
1099        is_root: bool,
1100    ) -> bool {
1101        self.style
1102            .establishes_stacking_context_in(parent_display, is_root)
1103    }
1104
1105    /// Translates this node's geometry and all descendants by (dx, dy) using an iterative heap stack (O(1) call stack).
1106    pub fn translate(&mut self, dx: f32, dy: f32) {
1107        if dx == 0.0 && dy == 0.0 {
1108            return;
1109        }
1110
1111        let mut stack: Vec<&mut LayoutNode> = vec![self];
1112        while let Some(node) = stack.pop() {
1113            node.geometry.translate(dx, dy);
1114            node.subtree_bounds.x += dx;
1115            node.subtree_bounds.y += dy;
1116            node.layout_cache.origin_x += dx;
1117            node.layout_cache.origin_y += dy;
1118            if let Some(ref mut pb) = node.last_preserved_box {
1119                pb.0 += dx;
1120                pb.1 += dy;
1121            }
1122            for line in &mut node.line_boxes {
1123                line.bounds.x += dx;
1124                line.bounds.y += dy;
1125                for frag in &mut line.text_fragments {
1126                    frag.bounds.x += dx;
1127                    frag.bounds.y += dy;
1128                    frag.baseline_y += dy;
1129                }
1130                for atomic in &mut line.atomic_fragments {
1131                    atomic.bounds.x += dx;
1132                    atomic.bounds.y += dy;
1133                }
1134            }
1135            if let Some(ref mut grid) = node.table_grid {
1136                grid.translate(dx, dy);
1137            }
1138            for child in &mut node.children {
1139                stack.push(child);
1140            }
1141        }
1142    }
1143
1144    /// Translates descendants of a scroll container by `(dx, dy)` while honoring CSS containing-block
1145    /// escape semantics:
1146    /// - `Position::Fixed` subtrees do not scroll unless an ancestor at or inside the scroll container
1147    ///   established a fixed containing block (`transform`, `filter`, `backdrop-filter`).
1148    /// - `Position::Absolute` subtrees do not scroll unless an ancestor at or inside the scroll container
1149    ///   established an absolute containing block (`position != Static` or fixed CB).
1150    pub fn translate_scrolled(
1151        &mut self,
1152        dx: f32,
1153        dy: f32,
1154        parent_is_abs_cb: bool,
1155        parent_is_fixed_cb: bool,
1156    ) {
1157        if dx == 0.0 && dy == 0.0 {
1158            return;
1159        }
1160
1161        let mut stack: Vec<(&mut LayoutNode, bool, bool)> =
1162            vec![(self, parent_is_abs_cb, parent_is_fixed_cb)];
1163        while let Some((node, abs_cb_inside, fixed_cb_inside)) = stack.pop() {
1164            if node.is_top_layer {
1165                continue;
1166            }
1167            match node.style.position {
1168                strata_style::types::Position::Fixed if !fixed_cb_inside => {
1169                    continue;
1170                }
1171                strata_style::types::Position::Absolute if !abs_cb_inside => {
1172                    continue;
1173                }
1174                _ => {}
1175            }
1176
1177            node.geometry.translate(dx, dy);
1178            node.subtree_bounds.x += dx;
1179            node.subtree_bounds.y += dy;
1180            node.layout_cache.origin_x += dx;
1181            node.layout_cache.origin_y += dy;
1182            if let Some(ref mut pb) = node.last_preserved_box {
1183                pb.0 += dx;
1184                pb.1 += dy;
1185            }
1186            for line in &mut node.line_boxes {
1187                line.bounds.x += dx;
1188                line.bounds.y += dy;
1189                for frag in &mut line.text_fragments {
1190                    frag.bounds.x += dx;
1191                    frag.bounds.y += dy;
1192                    frag.baseline_y += dy;
1193                }
1194                for atomic in &mut line.atomic_fragments {
1195                    atomic.bounds.x += dx;
1196                    atomic.bounds.y += dy;
1197                }
1198            }
1199            if let Some(ref mut grid) = node.table_grid {
1200                grid.translate(dx, dy);
1201            }
1202
1203            let child_fixed_cb = fixed_cb_inside || node.style.establishes_fixed_containing_block();
1204            let child_abs_cb = abs_cb_inside
1205                || node.style.position != strata_style::types::Position::Static
1206                || child_fixed_cb;
1207
1208            for child in &mut node.children {
1209                stack.push((child, child_abs_cb, child_fixed_cb));
1210            }
1211        }
1212    }
1213
1214    /// Formats the children of this node within its already-resolved content box.
1215    pub fn layout_children(&mut self) {
1216        self.layout_children_guarded(LayoutDepthGuard::root());
1217    }
1218
1219    /// Formats the children of this node with an active depth guard.
1220    pub fn layout_children_guarded(&mut self, guard: LayoutDepthGuard) {
1221        self.layout_children_inner_guarded(guard, true);
1222    }
1223
1224    pub(crate) fn layout_children_inner_guarded(
1225        &mut self,
1226        guard: LayoutDepthGuard,
1227        resolve_positioned: bool,
1228    ) {
1229        if (self.children.is_empty() && self.inline_items.is_empty()) || guard.is_exhausted() {
1230            return;
1231        }
1232
1233        let content_w = self.geometry.content_box.width;
1234        let content_h = self.geometry.content_box.height;
1235        let preserved_geom = self.geometry;
1236
1237        // O(1) clean subtree fast path: when neither `self` nor any descendant was invalidated
1238        // since the last layout and the preserved box + content dimensions match, simply translate
1239        // descendants if the box origin moved instead of re-solving the entire subtree.
1240        if self.children_layout_clean {
1241            if let Some((prev_x, prev_y, prev_w, prev_h, prev_pos)) = self.last_preserved_box {
1242                if prev_pos == resolve_positioned
1243                    && (prev_w - preserved_geom.border_box.width).abs() < 0.05
1244                    && (prev_h - preserved_geom.border_box.height).abs() < 0.05
1245                    && self.last_child_layout_content.is_some_and(|(cw, ch)| {
1246                        (cw - content_w).abs() < 0.05 && (ch - content_h).abs() < 0.05
1247                    })
1248                {
1249                    let dx = preserved_geom.border_box.x - prev_x;
1250                    let dy = preserved_geom.border_box.y - prev_y;
1251                    if dx.abs() > 0.001 || dy.abs() > 0.001 {
1252                        self.subtree_bounds.x += dx;
1253                        self.subtree_bounds.y += dy;
1254                        for line in &mut self.line_boxes {
1255                            line.bounds.x += dx;
1256                            line.bounds.y += dy;
1257                            for frag in &mut line.text_fragments {
1258                                frag.bounds.x += dx;
1259                                frag.bounds.y += dy;
1260                                frag.baseline_y += dy;
1261                            }
1262                            for at in &mut line.atomic_fragments {
1263                                at.bounds.x += dx;
1264                                at.bounds.y += dy;
1265                            }
1266                        }
1267                        for child in &mut self.children {
1268                            child.translate(dx, dy);
1269                        }
1270                        self.last_preserved_box = Some((
1271                            preserved_geom.border_box.x,
1272                            preserved_geom.border_box.y,
1273                            prev_w,
1274                            prev_h,
1275                            prev_pos,
1276                        ));
1277                    }
1278                    return;
1279                }
1280            }
1281        }
1282
1283        self.subtree_hit_flags &= !SUBTREE_META_VALID;
1284
1285        let saved_w = self.style.width;
1286        let saved_h = self.style.height;
1287        let saved_min_w = self.style.min_width;
1288        let saved_max_w = self.style.max_width;
1289        let saved_min_h = self.style.min_height;
1290        let saved_max_h = self.style.max_height;
1291
1292        let pin_w = preserved_geom.border_box.width > 0.0
1293            || matches!(saved_w, strata_style::types::Dimension::Percent(_));
1294        let pin_h = preserved_geom.border_box.height > 0.0
1295            || matches!(saved_h, strata_style::types::Dimension::Percent(_));
1296
1297        let container_avail_w = if pin_w {
1298            self.style.width = strata_style::types::Dimension::Px(preserved_geom.border_box.width);
1299            self.style.min_width = strata_style::types::Dimension::Auto;
1300            self.style.max_width = strata_style::types::Dimension::Auto;
1301            preserved_geom.border_box.width
1302        } else {
1303            preserved_geom.border_box.width + self.style.margin.left + self.style.margin.right
1304        };
1305
1306        let container_avail_h = if pin_h {
1307            let pinned_h = if saved_h == strata_style::types::Dimension::Auto {
1308                crate::box_model::clamp_dimension_with_node(
1309                    preserved_geom.border_box.height,
1310                    saved_min_h,
1311                    saved_max_h,
1312                    content_h.max(preserved_geom.border_box.height),
1313                    self,
1314                )
1315            } else {
1316                preserved_geom.border_box.height
1317            };
1318            self.style.height = strata_style::types::Dimension::Px(pinned_h);
1319            self.style.min_height = strata_style::types::Dimension::Auto;
1320            self.style.max_height = strata_style::types::Dimension::Auto;
1321            pinned_h
1322        } else {
1323            preserved_geom.border_box.height + self.style.margin.top + self.style.margin.bottom
1324        };
1325
1326        match self.style.display {
1327            Display::Flex | Display::InlineFlex => {
1328                let definite_cross = if content_h > 0.0 && !pin_h {
1329                    Some(content_h)
1330                } else {
1331                    None
1332                };
1333                crate::flexbox::solve_flexbox_with_definite_cross_guarded(
1334                    self,
1335                    container_avail_w,
1336                    container_avail_h,
1337                    definite_cross,
1338                    guard,
1339                );
1340            }
1341            Display::Grid | Display::InlineGrid => {
1342                crate::grid::solve_grid_guarded(self, container_avail_w, container_avail_h, guard);
1343            }
1344            Display::Table | Display::InlineTable => {
1345                crate::table::solve_table_guarded(
1346                    self,
1347                    container_avail_w,
1348                    container_avail_h,
1349                    guard,
1350                );
1351            }
1352            Display::Block
1353            | Display::ListItem
1354            | Display::Inline
1355            | Display::InlineBlock
1356            | Display::TableRowGroup
1357            | Display::TableHeaderGroup
1358            | Display::TableFooterGroup
1359            | Display::TableRow
1360            | Display::TableCell
1361            | Display::TableCaption
1362            | Display::TableColumnGroup
1363            | Display::TableColumn => {
1364                let block_h = crate::box_model::solve_block_children_with_exclusions_guarded(
1365                    self, content_w, content_h, None, 0.0, guard,
1366                );
1367                if saved_h == strata_style::types::Dimension::Auto {
1368                    self.geometry.border_box.height = block_h;
1369                }
1370            }
1371            Display::None => {}
1372        }
1373
1374        self.style.width = saved_w;
1375        self.style.height = saved_h;
1376        self.style.min_width = saved_min_w;
1377        self.style.max_width = saved_max_w;
1378        self.style.min_height = saved_min_h;
1379        self.style.max_height = saved_max_h;
1380
1381        let clamp_avail_h = preserved_geom.border_box.height.max(content_h);
1382        if self.style.height == strata_style::types::Dimension::Auto {
1383            self.geometry.border_box.height = crate::box_model::clamp_dimension_with_node(
1384                self.geometry.border_box.height,
1385                saved_min_h,
1386                saved_max_h,
1387                clamp_avail_h,
1388                self,
1389            );
1390        }
1391
1392        let clips_y = self.style.overflow_y != strata_style::types::Overflow::Visible;
1393        let final_h = if self.style.height == strata_style::types::Dimension::Auto && !clips_y {
1394            let unclipped = self
1395                .geometry
1396                .border_box
1397                .height
1398                .max(preserved_geom.border_box.height);
1399            crate::box_model::clamp_dimension_with_node(
1400                unclipped,
1401                saved_min_h,
1402                saved_max_h,
1403                clamp_avail_h,
1404                self,
1405            )
1406        } else if preserved_geom.border_box.height > 0.0 {
1407            if self.style.height == strata_style::types::Dimension::Auto {
1408                crate::box_model::clamp_dimension_with_node(
1409                    preserved_geom.border_box.height,
1410                    saved_min_h,
1411                    saved_max_h,
1412                    clamp_avail_h,
1413                    self,
1414                )
1415            } else {
1416                preserved_geom.border_box.height
1417            }
1418        } else {
1419            self.geometry.border_box.height
1420        };
1421
1422        let clips_x = self.style.overflow_x != strata_style::types::Overflow::Visible;
1423        let final_w = if self.style.width == strata_style::types::Dimension::Auto && !clips_x {
1424            self.geometry
1425                .border_box
1426                .width
1427                .max(preserved_geom.border_box.width)
1428        } else if preserved_geom.border_box.width > 0.0 {
1429            preserved_geom.border_box.width
1430        } else {
1431            self.geometry.border_box.width
1432        };
1433
1434        self.geometry = LayoutGeometry::from_border_box(
1435            crate::geometry::Rect::new(
1436                preserved_geom.border_box.x,
1437                preserved_geom.border_box.y,
1438                final_w,
1439                final_h,
1440            ),
1441            self.style.padding,
1442            self.style.border_width,
1443            self.style.margin,
1444        );
1445
1446        if resolve_positioned && self.style.position != strata_style::types::Position::Static {
1447            crate::positioning::solve_positioning_guarded(self, content_w, content_h, guard);
1448        }
1449        self.geometry.snap_to_pixel();
1450        self.update_scroll_metrics();
1451        self.last_child_layout_content = Some((content_w, content_h));
1452        self.children_layout_clean = true;
1453        self.last_preserved_box = Some((
1454            self.geometry.border_box.x,
1455            self.geometry.border_box.y,
1456            self.geometry.border_box.width,
1457            self.geometry.border_box.height,
1458            resolve_positioned,
1459        ));
1460        self.layout_cache.is_valid = false;
1461    }
1462
1463    /// Computes layout geometry for this node and all descendants given available bounds.
1464    pub fn compute_layout(&mut self, available_width: f32, available_height: f32) {
1465        let session_root = crate::intrinsic::begin_layout_session();
1466        let _guard = crate::prof::LayoutGuard::new();
1467        let guard = LayoutDepthGuard::root();
1468        self.compute_layout_guarded(available_width, available_height, None, 0.0, guard);
1469        crate::intrinsic::end_layout_session(session_root);
1470        self.refresh_subtree_hit_metadata();
1471    }
1472
1473    /// Computes layout geometry passing an active exclusion space for float obstructions.
1474    pub fn compute_layout_with_exclusions(
1475        &mut self,
1476        available_width: f32,
1477        available_height: f32,
1478        exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1479        bfc_offset_y: f32,
1480    ) {
1481        let guard = LayoutDepthGuard::root();
1482        self.compute_layout_guarded(
1483            available_width,
1484            available_height,
1485            exclusions,
1486            bfc_offset_y,
1487            guard,
1488        );
1489        self.refresh_subtree_hit_metadata();
1490    }
1491
1492    /// Recomputes `subtree_hit_flags` and `subtree_bounds` bottom-up across the layout tree,
1493    /// skipping clean subtrees whose `SUBTREE_META_VALID` flag is already up to date.
1494    pub fn refresh_subtree_hit_metadata(&mut self) {
1495        self.refresh_subtree_hit_metadata_inner(None, true);
1496    }
1497
1498    #[inline]
1499    fn is_self_height_dependent(&self) -> bool {
1500        use strata_style::types::{Dimension, Position};
1501        matches!(self.style.height, Dimension::Percent(_))
1502            || matches!(self.style.min_height, Dimension::Percent(_))
1503            || matches!(self.style.max_height, Dimension::Percent(_))
1504            || matches!(self.style.flex_basis, Dimension::Percent(_))
1505            || (matches!(self.style.position, Position::Absolute | Position::Fixed)
1506                && (!matches!(self.style.insets.bottom, Dimension::Auto)
1507                    || matches!(self.style.insets.top, Dimension::Percent(_))))
1508    }
1509
1510    fn refresh_subtree_hit_metadata_inner(
1511        &mut self,
1512        parent_display: Option<strata_style::types::Display>,
1513        is_root: bool,
1514    ) {
1515        let self_hoisted = !is_root
1516            && (self.style.position != strata_style::types::Position::Static
1517                || self.establishes_stacking_context_in(parent_display, false));
1518        if (self.subtree_hit_flags & SUBTREE_META_VALID) != 0
1519            && (!self_hoisted || (self.subtree_hit_flags & SUBTREE_HAS_HOISTED) != 0)
1520        {
1521            return;
1522        }
1523
1524        if matches!(self.style.display, strata_style::types::Display::None) {
1525            self.subtree_hit_flags = SUBTREE_META_VALID;
1526            self.subtree_bounds = Rect::new(0.0, 0.0, 0.0, 0.0);
1527            return;
1528        }
1529
1530        let mut flags = SUBTREE_META_VALID;
1531        if self.is_top_layer {
1532            flags |= SUBTREE_HAS_TOP_LAYER;
1533        }
1534        if self.style.has_transform() {
1535            flags |= SUBTREE_HAS_TRANSFORM;
1536        }
1537        if self_hoisted {
1538            flags |= SUBTREE_HAS_HOISTED;
1539        }
1540
1541        let own = self.geometry.border_box;
1542        let mut min_x = own.x;
1543        let mut min_y = own.y;
1544        let mut max_x = own.x + own.width.max(0.0);
1545        let mut max_y = own.y + own.height.max(0.0);
1546        let mut has_bounds = own.width > 0.0 || own.height > 0.0 || self.children.is_empty();
1547
1548        let union_rect = |r: Rect,
1549                          min_x: &mut f32,
1550                          min_y: &mut f32,
1551                          max_x: &mut f32,
1552                          max_y: &mut f32,
1553                          has_bounds: &mut bool| {
1554            let rx1 = r.x + r.width.max(0.0);
1555            let ry1 = r.y + r.height.max(0.0);
1556            if *has_bounds {
1557                *min_x = min_x.min(r.x);
1558                *min_y = min_y.min(r.y);
1559                *max_x = max_x.max(rx1);
1560                *max_y = max_y.max(ry1);
1561            } else {
1562                *min_x = r.x;
1563                *min_y = r.y;
1564                *max_x = rx1;
1565                *max_y = ry1;
1566                *has_bounds = true;
1567            }
1568        };
1569
1570        for line in &self.line_boxes {
1571            if line.bounds.width > 0.0 || line.bounds.height > 0.0 {
1572                union_rect(
1573                    line.bounds,
1574                    &mut min_x,
1575                    &mut min_y,
1576                    &mut max_x,
1577                    &mut max_y,
1578                    &mut has_bounds,
1579                );
1580            }
1581        }
1582
1583        let self_display = Some(self.style.display);
1584        for child in &mut self.children {
1585            child.refresh_subtree_hit_metadata_inner(self_display, false);
1586            flags |= child.subtree_hit_flags & !SUBTREE_HAS_HEIGHT_DEP_DESCENDANT;
1587            if child.is_self_height_dependent()
1588                || (!matches!(child.style.height, strata_style::types::Dimension::Px(_))
1589                    && (child.subtree_hit_flags & SUBTREE_HAS_HEIGHT_DEP_DESCENDANT) != 0)
1590            {
1591                flags |= SUBTREE_HAS_HEIGHT_DEP_DESCENDANT;
1592            }
1593            if matches!(child.style.display, strata_style::types::Display::None)
1594                || child.is_top_layer
1595                || child.style.position != strata_style::types::Position::Static
1596                || child.establishes_stacking_context_in(self_display, false)
1597            {
1598                continue;
1599            }
1600            let cb = child.subtree_bounds;
1601            if cb.width > 0.0 || cb.height > 0.0 || (child.children.is_empty() && (cb.x != 0.0 || cb.y != 0.0)) {
1602                union_rect(
1603                    cb,
1604                    &mut min_x,
1605                    &mut min_y,
1606                    &mut max_x,
1607                    &mut max_y,
1608                    &mut has_bounds,
1609                );
1610            }
1611        }
1612
1613        if has_bounds {
1614            if self.style.overflow_x != strata_style::types::Overflow::Visible {
1615                let clip_x0 = own.x;
1616                let clip_x1 = own.x + own.width.max(0.0);
1617                min_x = min_x.max(clip_x0).min(clip_x1);
1618                max_x = max_x.min(clip_x1).max(min_x);
1619            }
1620            if self.style.overflow_y != strata_style::types::Overflow::Visible {
1621                let clip_y0 = own.y;
1622                let clip_y1 = own.y + own.height.max(0.0);
1623                min_y = min_y.max(clip_y0).min(clip_y1);
1624                max_y = max_y.min(clip_y1).max(min_y);
1625            }
1626            self.subtree_bounds = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y);
1627        } else {
1628            self.subtree_bounds = own;
1629        }
1630        self.subtree_hit_flags = flags;
1631    }
1632
1633    #[inline]
1634    pub(crate) fn is_height_independent_for_cache(&self) -> bool {
1635        self.style.height == strata_style::types::Dimension::Auto
1636            && self.style.flex_basis == strata_style::types::Dimension::Auto
1637            && self.style.flex_grow == 0.0
1638            && !matches!(
1639                self.style.min_height,
1640                strata_style::types::Dimension::Percent(_)
1641            )
1642            && !matches!(
1643                self.style.max_height,
1644                strata_style::types::Dimension::Percent(_)
1645            )
1646            && !(matches!(
1647                self.style.position,
1648                strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
1649            ) && (!matches!(
1650                self.style.insets.bottom,
1651                strata_style::types::Dimension::Auto
1652            ) || matches!(
1653                self.style.insets.top,
1654                strata_style::types::Dimension::Percent(_)
1655            )))
1656            && !self.has_height_dependent_descendant_fast()
1657    }
1658
1659    /// Looks up a cached measurement probe `(result_w, result_h, baseline_offset)` for a clean
1660    /// subtree without modifying `self.geometry` or descending into children.
1661    #[inline]
1662    pub(crate) fn lookup_measure_cache(
1663        &self,
1664        available_w: f32,
1665        available_h: f32,
1666        style_pin_hash: u64,
1667    ) -> Option<(f32, f32, f32)> {
1668        if !self.children_layout_clean {
1669            return None;
1670        }
1671        for slot in &self.measure_cache {
1672            if slot.is_valid
1673                && slot.style_pin_hash == style_pin_hash
1674                && (available_w - slot.available_w).abs() < 0.01
1675                && ((available_h - slot.available_h).abs() < 0.01
1676                    || self.is_height_independent_for_cache())
1677            {
1678                return Some((slot.result_w, slot.result_h, slot.baseline_offset));
1679            }
1680        }
1681        None
1682    }
1683
1684    /// Stores a measurement probe result in slot `0` (Pass 1) or `1` (Pass 2).
1685    #[inline]
1686    pub(crate) fn store_measure_cache(
1687        &mut self,
1688        slot_idx: usize,
1689        available_w: f32,
1690        available_h: f32,
1691        style_pin_hash: u64,
1692        result_w: f32,
1693        result_h: f32,
1694        baseline_offset: f32,
1695    ) {
1696        self.measure_cache[slot_idx.min(1)] = MeasureCacheEntry {
1697            available_w,
1698            available_h,
1699            style_pin_hash,
1700            result_w,
1701            result_h,
1702            baseline_offset,
1703            is_valid: true,
1704        };
1705    }
1706
1707    /// Computes layout geometry passing an active exclusion space and depth guard.
1708    pub fn compute_layout_guarded(
1709        &mut self,
1710        available_width: f32,
1711        available_height: f32,
1712        exclusions: Option<&mut crate::exclusions::ExclusionSpace>,
1713        bfc_offset_y: f32,
1714        guard: LayoutDepthGuard,
1715    ) {
1716        let _guard = crate::prof::LayoutGuard::new();
1717        crate::prof::observe_width(self.children.len());
1718
1719        let available_width = if available_width.is_finite() && available_width >= 0.0 {
1720            available_width.min(1e7)
1721        } else {
1722            0.0
1723        };
1724        let available_height = if available_height.is_finite() && available_height >= 0.0 {
1725            available_height.min(1e7)
1726        } else {
1727            0.0
1728        };
1729
1730        if self.style.display == Display::None {
1731            self.geometry = LayoutGeometry::default();
1732            self.layout_cache.is_valid = false;
1733            self.children_layout_clean = false;
1734            self.subtree_hit_flags &= !SUBTREE_META_VALID;
1735            return;
1736        }
1737
1738        if guard.is_exhausted() {
1739            record_layout_overflow(guard.current_depth(), guard.max_depth());
1740            let padding = self.style.padding;
1741            let border = self.style.border_width;
1742            let margin = self.style.margin;
1743
1744            let w = crate::box_model::resolve_dimension_with_node(
1745                self.style.width,
1746                available_width,
1747                self,
1748            )
1749            .unwrap_or(available_width)
1750            .max(0.0);
1751            let h = crate::box_model::resolve_dimension(self.style.height, available_height)
1752                .unwrap_or_else(|| {
1753                    if self.text.is_some() {
1754                        self.style.font_size * self.style.line_height
1755                    } else {
1756                        0.0
1757                    }
1758                })
1759                .max(0.0);
1760
1761            self.geometry = LayoutGeometry::from_border_box(
1762                crate::geometry::Rect::new(
1763                    self.geometry.border_box.x,
1764                    self.geometry.border_box.y,
1765                    w,
1766                    h,
1767                ),
1768                padding,
1769                border,
1770                margin,
1771            );
1772            self.geometry.snap_to_pixel();
1773            self.layout_cache.is_valid = false;
1774            self.children_layout_clean = false;
1775            self.subtree_hit_flags &= !SUBTREE_META_VALID;
1776            return;
1777        }
1778
1779        let is_unconstrained_root = exclusions
1780            .as_ref()
1781            .is_none_or(|e| e.exclusions().is_empty());
1782        let style_pin_hash = layout_style_pin_hash(&self.style);
1783
1784        // Subtree layout cache hit: skip re-traversal if available dimensions & style pins match.
1785        // Only evaluate `is_height_independent_for_cache()` when `available_w` and `style_pin_hash`
1786        // already match and `available_h` differs (avoiding unnecessary subtree walks).
1787        if is_unconstrained_root
1788            && self.layout_cache.is_valid
1789            && self.layout_cache.style_pin_hash == style_pin_hash
1790            && (available_width - self.layout_cache.available_w).abs() < 0.01
1791            && ((available_height - self.layout_cache.available_h).abs() < 0.01
1792                || self.is_height_independent_for_cache())
1793        {
1794            let dx = self.geometry.border_box.x - self.layout_cache.origin_x;
1795            let dy = self.geometry.border_box.y - self.layout_cache.origin_y;
1796            if dx.abs() > 0.001 || dy.abs() > 0.001 {
1797                self.geometry.padding_box.x += dx;
1798                self.geometry.padding_box.y += dy;
1799                self.geometry.content_box.x += dx;
1800                self.geometry.content_box.y += dy;
1801                self.geometry.margin_box.x += dx;
1802                self.geometry.margin_box.y += dy;
1803                self.subtree_bounds.x += dx;
1804                self.subtree_bounds.y += dy;
1805                if let Some(ref mut pb) = self.last_preserved_box {
1806                    pb.0 += dx;
1807                    pb.1 += dy;
1808                }
1809                if let Some(ref mut grid) = self.table_grid {
1810                    grid.translate(dx, dy);
1811                }
1812                for line in &mut self.line_boxes {
1813                    line.bounds.x += dx;
1814                    line.bounds.y += dy;
1815                    for frag in &mut line.text_fragments {
1816                        frag.bounds.x += dx;
1817                        frag.bounds.y += dy;
1818                        frag.baseline_y += dy;
1819                    }
1820                    for at in &mut line.atomic_fragments {
1821                        at.bounds.x += dx;
1822                        at.bounds.y += dy;
1823                    }
1824                }
1825                for child in &mut self.children {
1826                    child.translate(dx, dy);
1827                }
1828                self.layout_cache.origin_x = self.geometry.border_box.x;
1829                self.layout_cache.origin_y = self.geometry.border_box.y;
1830            }
1831            return;
1832        }
1833
1834        self.subtree_hit_flags &= !SUBTREE_META_VALID;
1835
1836        // Dispatch according to container display formatting context
1837        match self.style.display {
1838            Display::Flex | Display::InlineFlex => {
1839                crate::flexbox::solve_flexbox_guarded(
1840                    self,
1841                    available_width,
1842                    available_height,
1843                    guard,
1844                );
1845            }
1846            Display::Grid | Display::InlineGrid => {
1847                crate::grid::solve_grid_guarded(self, available_width, available_height, guard);
1848            }
1849            Display::Table | Display::InlineTable => {
1850                crate::table::solve_table_guarded(self, available_width, available_height, guard);
1851            }
1852            Display::Block
1853            | Display::ListItem
1854            | Display::Inline
1855            | Display::InlineBlock
1856            | Display::TableRowGroup
1857            | Display::TableHeaderGroup
1858            | Display::TableFooterGroup
1859            | Display::TableRow
1860            | Display::TableCell
1861            | Display::TableCaption
1862            | Display::TableColumnGroup
1863            | Display::TableColumn => {
1864                crate::box_model::solve_block_with_exclusions_guarded(
1865                    self,
1866                    available_width,
1867                    available_height,
1868                    exclusions,
1869                    bfc_offset_y,
1870                    guard,
1871                );
1872            }
1873            Display::None => unreachable!(),
1874        }
1875
1876        // Resolve relative and out-of-flow absolute/fixed positioned children
1877        crate::positioning::solve_positioning_guarded(
1878            self,
1879            available_width,
1880            available_height,
1881            guard,
1882        );
1883
1884        // Subpixel snapping and geometry sanitization
1885        self.geometry.snap_to_pixel();
1886        self.geometry.sanitize();
1887
1888        // Update scrollable overflow metrics
1889        self.update_scroll_metrics();
1890
1891        if !self.children.is_empty() || !self.inline_items.is_empty() || self.text.is_some() {
1892            self.last_child_layout_content = Some((
1893                self.geometry.content_box.width,
1894                self.geometry.content_box.height,
1895            ));
1896        }
1897        self.children_layout_clean = true;
1898        self.last_preserved_box = None;
1899
1900        // Record layout result in cache for subsequent multi-pass probes
1901        if is_unconstrained_root {
1902            self.layout_cache = LayoutCacheEntry {
1903                available_w: available_width,
1904                available_h: available_height,
1905                result_w: self.geometry.border_box.width,
1906                result_h: self.geometry.border_box.height,
1907                origin_x: self.geometry.border_box.x,
1908                origin_y: self.geometry.border_box.y,
1909                style_pin_hash,
1910                is_valid: true,
1911            };
1912        }
1913    }
1914
1915    #[inline]
1916    fn has_height_dependent_descendant_fast(&self) -> bool {
1917        if (self.subtree_hit_flags & SUBTREE_META_VALID) != 0 {
1918            return (self.subtree_hit_flags & SUBTREE_HAS_HEIGHT_DEP_DESCENDANT) != 0;
1919        }
1920        self.has_height_dependent_descendant()
1921    }
1922
1923    /// Returns true if any descendant (up to an explicit pixel-height boundary) depends on parent height.
1924    fn has_height_dependent_descendant(&self) -> bool {
1925        use strata_style::types::{Dimension, Position};
1926        let mut stack: Vec<&LayoutNode> = self.children.iter().collect();
1927        while let Some(node) = stack.pop() {
1928            if matches!(node.style.height, Dimension::Percent(_))
1929                || matches!(node.style.min_height, Dimension::Percent(_))
1930                || matches!(node.style.max_height, Dimension::Percent(_))
1931                || matches!(node.style.flex_basis, Dimension::Percent(_))
1932            {
1933                return true;
1934            }
1935            if matches!(node.style.position, Position::Absolute | Position::Fixed)
1936                && (!matches!(node.style.insets.bottom, Dimension::Auto)
1937                    || matches!(node.style.insets.top, Dimension::Percent(_)))
1938            {
1939                return true;
1940            }
1941            if !matches!(node.style.height, Dimension::Px(_)) {
1942                for grand in &node.children {
1943                    stack.push(grand);
1944                }
1945            }
1946        }
1947        false
1948    }
1949
1950    /// Invalidates all layout, measurement, intrinsic sizing, and hit-metadata caches strictly on
1951    /// this node without disturbing clean child subtrees.
1952    #[inline]
1953    pub fn invalidate_self_caches(&mut self) {
1954        self.layout_cache.is_valid = false;
1955        self.measure_cache[0].is_valid = false;
1956        self.measure_cache[1].is_valid = false;
1957        self.intrinsic_cache.clear();
1958        self.last_child_layout_content = None;
1959        self.children_layout_clean = false;
1960        self.last_preserved_box = None;
1961        self.subtree_hit_flags &= !SUBTREE_META_VALID;
1962    }
1963
1964    /// Invalidates layout cache on this node and all descendants using an iterative heap stack.
1965    pub fn invalidate_cache(&mut self) {
1966        let mut stack: Vec<&mut LayoutNode> = vec![self];
1967        while let Some(node) = stack.pop() {
1968            node.invalidate_self_caches();
1969            for child in &mut node.children {
1970                stack.push(child);
1971            }
1972        }
1973    }
1974
1975    /// Returns true if this node forms an isolated layout boundary (W3C CSS Containment Level 2 ยง3.1).
1976    ///
1977    /// An element is a layout boundary if internal descendant changes can never affect
1978    /// the layout of ancestor or sibling elements outside this boundary:
1979    /// 1. Explicit CSS `contain: strict` or `contain: content`
1980    /// 2. Explicit CSS `contain: layout` combined with `contain: size` or definite pixel dimensions
1981    /// 3. CSS `content-visibility: auto` or `hidden` with definite pixel dimensions
1982    /// 4. Out-of-flow positioned boxes with clipping and definite pixel dimensions
1983    pub fn is_layout_boundary(&self) -> bool {
1984        // 1. Explicit contain: strict or contain: content
1985        if self.style.contain == strata_style::types::Containment::STRICT
1986            || self.style.contain == strata_style::types::Containment::CONTENT
1987        {
1988            return true;
1989        }
1990
1991        // 2. Explicit contain: layout with contain: size
1992        if self.style.contain.layout && self.style.contain.size {
1993            return true;
1994        }
1995
1996        // 3. Explicit contain: layout with definite width and height
1997        if self.style.contain.layout && self.has_definite_dimensions() {
1998            return true;
1999        }
2000
2001        // 4. Content-visibility containment with definite dimensions
2002        if self.style.content_visibility != strata_style::types::ContentVisibility::Visible
2003            && self.has_definite_dimensions()
2004        {
2005            return true;
2006        }
2007
2008        // 5. Out-of-flow positioned boxes with clipping and definite dimensions
2009        if matches!(
2010            self.style.position,
2011            strata_style::types::Position::Absolute | strata_style::types::Position::Fixed
2012        ) && self.has_definite_dimensions()
2013            && self.style.overflow_x != strata_style::types::Overflow::Visible
2014            && self.style.overflow_y != strata_style::types::Overflow::Visible
2015        {
2016            return true;
2017        }
2018
2019        false
2020    }
2021
2022    /// Checks if both width and height are definite non-auto pixel dimensions.
2023    #[inline]
2024    pub fn has_definite_dimensions(&self) -> bool {
2025        matches!(self.style.width, strata_style::types::Dimension::Px(_))
2026            && matches!(self.style.height, strata_style::types::Dimension::Px(_))
2027    }
2028
2029    /// Recursively searches for the nearest ancestor layout boundary containing the given index path.
2030    /// Returns the prefix of `path` that terminates at the nearest layout boundary container.
2031    pub fn find_layout_boundary_path<'a>(&self, path: &'a [usize]) -> Option<&'a [usize]> {
2032        let mut best_boundary_len = if self.is_layout_boundary() {
2033            Some(0)
2034        } else {
2035            None
2036        };
2037
2038        let mut curr = self;
2039        for (i, &child_idx) in path.iter().enumerate() {
2040            if child_idx >= curr.children.len() {
2041                break;
2042            }
2043            curr = &curr.children[child_idx];
2044            if curr.is_layout_boundary() {
2045                best_boundary_len = Some(i + 1);
2046            }
2047        }
2048
2049        best_boundary_len.map(|len| &path[..len])
2050    }
2051
2052    /// Recomputes layout for the subtree rooted at `path` within its containing layout boundary.
2053    ///
2054    /// If an ancestor layout boundary exists along `path`, layout is recomputed ONLY for that
2055    /// boundary container and its descendants, guaranteeing zero re-layouts on the rest of the tree.
2056    /// Returns `true` if a layout boundary was found and laid out locally, or `false` if root
2057    /// layout recomputation is required.
2058    pub fn compute_subgrid_or_boundary_layout(&mut self, path: &[usize]) -> bool {
2059        let boundary_len = match self.find_layout_boundary_path(path) {
2060            Some(subpath) => subpath.len(),
2061            None => return false,
2062        };
2063
2064        if boundary_len == 0 {
2065            // Root itself is the layout boundary
2066            self.layout_children();
2067            return true;
2068        }
2069
2070        // Navigate to the boundary node mutably
2071        let mut curr = self;
2072        for &idx in &path[..boundary_len] {
2073            if idx >= curr.children.len() {
2074                return false;
2075            }
2076            curr = &mut curr.children[idx];
2077        }
2078
2079        // Recompute layout strictly within the isolated boundary
2080        curr.layout_children();
2081        true
2082    }
2083
2084    /// Invalidates layout cache only for nodes along `path` under the nearest layout boundary.
2085    pub fn invalidate_layout_boundary(&mut self, path: &[usize]) -> bool {
2086        let boundary_len = match self.find_layout_boundary_path(path) {
2087            Some(subpath) => subpath.len(),
2088            None => {
2089                self.invalidate_cache();
2090                return false;
2091            }
2092        };
2093
2094        let mut curr = self;
2095        for &idx in &path[..boundary_len] {
2096            if idx >= curr.children.len() {
2097                return false;
2098            }
2099            curr = &mut curr.children[idx];
2100        }
2101
2102        curr.invalidate_cache();
2103        true
2104    }
2105
2106    /// Recursively calculates the index path to the layout node with matching EntityId.
2107    pub fn find_path_by_entity_id(
2108        &self,
2109        target_id: strata_primitives::EntityId,
2110    ) -> Option<Vec<usize>> {
2111        if !target_id.is_valid() {
2112            return None;
2113        }
2114        let mut path = Vec::new();
2115        if self.find_path_by_entity_id_internal(target_id, &mut path) {
2116            Some(path)
2117        } else {
2118            None
2119        }
2120    }
2121
2122    fn find_path_by_entity_id_internal(
2123        &self,
2124        target_id: strata_primitives::EntityId,
2125        path: &mut Vec<usize>,
2126    ) -> bool {
2127        if self.entity_id == target_id {
2128            return true;
2129        }
2130        for (i, child) in self.children.iter().enumerate() {
2131            path.push(i);
2132            if child.find_path_by_entity_id_internal(target_id, path) {
2133                return true;
2134            }
2135            path.pop();
2136        }
2137        false
2138    }
2139
2140    /// Invalidates layout cache on self and all ancestors leading down to `path`.
2141    pub fn invalidate_ancestors(&mut self, path: &[usize]) {
2142        self.invalidate_self_caches();
2143        let mut curr = self;
2144        for &idx in path {
2145            if idx >= curr.children.len() {
2146                break;
2147            }
2148            curr = &mut curr.children[idx];
2149            curr.invalidate_self_caches();
2150        }
2151    }
2152
2153    /// Evaluates child geometry to compute `scroll_bounds` and `has_scroll` for this container.
2154    pub fn update_scroll_metrics(&mut self) {
2155        let origin_x = self.geometry.padding_box.x;
2156        let origin_y = self.geometry.padding_box.y;
2157        let mut max_extent_x = self.geometry.content_box.width;
2158        let mut max_extent_y = self.geometry.content_box.height;
2159
2160        for child in &self.children {
2161            if child.style.display == strata_style::types::Display::None
2162                || child.style.position == strata_style::types::Position::Fixed
2163            {
2164                continue;
2165            }
2166            let child_end_x = child.geometry.border_box.max_x() - origin_x;
2167            let child_end_y = child.geometry.border_box.max_y() - origin_y;
2168            if child_end_x.is_finite() && child_end_x > max_extent_x {
2169                max_extent_x = child_end_x;
2170            }
2171            if child_end_y.is_finite() && child_end_y > max_extent_y {
2172                max_extent_y = child_end_y;
2173            }
2174        }
2175
2176        for line in &self.line_boxes {
2177            let line_end_x = line.bounds.max_x() - origin_x;
2178            let line_end_y = line.bounds.max_y() - origin_y;
2179            if line_end_x.is_finite() && line_end_x > max_extent_x {
2180                max_extent_x = line_end_x;
2181            }
2182            if line_end_y.is_finite() && line_end_y > max_extent_y {
2183                max_extent_y = line_end_y;
2184            }
2185        }
2186
2187        self.geometry.scroll_bounds = crate::geometry::Size::new(max_extent_x, max_extent_y);
2188
2189        let has_scroll_x = match self.style.overflow_x {
2190            strata_style::types::Overflow::Scroll => true,
2191            strata_style::types::Overflow::Auto => max_extent_x > self.geometry.padding_box.width,
2192            _ => false,
2193        };
2194        let has_scroll_y = match self.style.overflow_y {
2195            strata_style::types::Overflow::Scroll => true,
2196            strata_style::types::Overflow::Auto => max_extent_y > self.geometry.padding_box.height,
2197            _ => false,
2198        };
2199        self.geometry.has_scroll = (has_scroll_x, has_scroll_y);
2200        self.geometry.scroll_offset = self
2201            .geometry
2202            .clamp_scroll_offset(self.geometry.scroll_offset);
2203    }
2204}
2205
2206impl Drop for LayoutNode {
2207    fn drop(&mut self) {
2208        // Drain descendants iteratively onto a heap stack to prevent recursion stack overflow
2209        // during deallocation of deeply nested trees (e.g. 10,000+ levels).
2210        let mut stack = std::mem::take(&mut self.children);
2211        while let Some(mut node) = stack.pop() {
2212            if !node.children.is_empty() {
2213                let grandchildren = std::mem::take(&mut node.children);
2214                stack.extend(grandchildren);
2215            }
2216        }
2217    }
2218}