Skip to main content

euv_core/layout/engine/
impl.rs

1use super::*;
2
3/// Core layout solver and hit-testing operations for `LayoutEngine`.
4impl LayoutEngine {
5    /// Computes layout for the entire `tree` within `viewport`, skipping clean cached subtrees.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable layout engine.
10    /// - `&mut SceneTree` - Retained scene tree to lay out.
11    /// - `Size` - Logical viewport dimensions.
12    ///
13    /// # Returns
14    ///
15    /// - `LayoutStats` - Computed vs cached subtree counts.
16    pub fn compute(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
17        let Self {
18            track_damage,
19            damage_fallback,
20            layout_snapshots,
21            ..
22        } = self;
23        *track_damage = false;
24        *damage_fallback = LAYOUT_FALLBACK_NONE;
25        layout_snapshots.clear();
26        self.compute_inner(tree, viewport)
27    }
28
29    /// Computes layout for `tree` while recording pre/post-layout conservative bounds diffs into a tight `LayoutDamageReport`.
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Mutable layout engine.
34    /// - `&mut SceneTree` - Retained scene tree to lay out.
35    /// - `Size` - Logical viewport dimensions.
36    /// - `f32` - Active display scale factor for outward-rounded physical damage rects.
37    ///
38    /// # Returns
39    ///
40    /// - `(LayoutStats, LayoutDamageReport)` - Layout pass stats and surgical physical damage or fallback cause.
41    pub(crate) fn compute_with_damage(
42        &mut self,
43        tree: &mut SceneTree,
44        viewport: Size,
45        scale: f32,
46    ) -> (LayoutStats, LayoutDamageReport) {
47        {
48            let Self {
49                track_damage,
50                damage_fallback,
51                layout_snapshots,
52                ..
53            } = self;
54            *track_damage = true;
55            *damage_fallback = LAYOUT_FALLBACK_NONE;
56            layout_snapshots.clear();
57        }
58        let stats: LayoutStats = self.compute_inner(tree, viewport);
59        let fallback_after: u8 = {
60            let Self {
61                track_damage,
62                damage_fallback,
63                ..
64            } = self;
65            *track_damage = false;
66            *damage_fallback
67        };
68        if fallback_after != LAYOUT_FALLBACK_NONE {
69            let Self {
70                layout_snapshots, ..
71            } = self;
72            layout_snapshots.clear();
73            return (
74                stats,
75                LayoutDamageReport {
76                    damage: DamageRegion::full(),
77                    fallback_kind: fallback_after,
78                },
79            );
80        }
81        let mut damage: DamageRegion = DamageRegion::default();
82        let mut final_fallback: u8 = LAYOUT_FALLBACK_NONE;
83        let Self {
84            layout_snapshots, ..
85        } = self;
86        for snap in layout_snapshots.iter().copied() {
87            let Some(node) = tree.get_node(snap.id) else {
88                continue;
89            };
90            let lbox: LayoutBox = node.get_layout_box();
91            let new_bounds: Rect = lbox.get_bounds();
92            let new_content_bounds: Rect = lbox.get_content_bounds();
93            let new_content_size: Size = lbox.get_content_size();
94            let bounds_changed: bool = !Self::rect_approx_eq(snap.old_bounds, new_bounds);
95            let content_changed: bool =
96                !Self::rect_approx_eq(snap.old_content_bounds, new_content_bounds);
97            let is_scroll_box: bool =
98                node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
99            let scroll_content_changed: bool =
100                is_scroll_box && !Self::size_approx_eq(snap.old_content_size, new_content_size);
101            let geom_changed: bool = bounds_changed || content_changed;
102            if !geom_changed && !scroll_content_changed {
103                continue;
104            }
105            let is_portal_or_fixed: bool = matches!(node.get_kind(), NodeKind::Portal)
106                || node.style_ref().layout_ref().get_position() == Position::Fixed;
107            if is_portal_or_fixed {
108                final_fallback = LAYOUT_FALLBACK_PORTAL;
109                break;
110            }
111            if snap.has_old_screen {
112                damage.add_rect(SceneTree::scale_logical_to_phys_rect(
113                    snap.old_screen,
114                    scale,
115                ));
116            }
117            if new_bounds.get_width() > 0.0 && new_bounds.get_height() > 0.0 {
118                match tree.node_conservative_logical_rect(snap.id) {
119                    Some(new_screen) => {
120                        damage.add_rect(SceneTree::scale_logical_to_phys_rect(new_screen, scale));
121                    }
122                    None => {
123                        final_fallback = LAYOUT_FALLBACK_UNSAFE;
124                        break;
125                    }
126                }
127            }
128        }
129        layout_snapshots.clear();
130        if final_fallback != LAYOUT_FALLBACK_NONE {
131            return (
132                stats,
133                LayoutDamageReport {
134                    damage: DamageRegion::full(),
135                    fallback_kind: final_fallback,
136                },
137            );
138        }
139        (
140            stats,
141            LayoutDamageReport {
142                damage,
143                fallback_kind: LAYOUT_FALLBACK_NONE,
144            },
145        )
146    }
147
148    /// Executes the core layout traversal over `tree` using the current `track_damage` mode.
149    ///
150    /// # Arguments
151    ///
152    /// - `&Self` - Mutable layout engine.
153    /// - `&mut SceneTree` - Retained scene tree to lay out.
154    /// - `Size` - Logical viewport dimensions.
155    ///
156    /// # Returns
157    ///
158    /// - `LayoutStats` - Computed vs cached subtree counts.
159    fn compute_inner(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
160        let root_id: NodeId = tree.get_root();
161        let space: AvailableSpace = AvailableSpace::root(viewport);
162        let mut stats: LayoutStats = LayoutStats::default();
163        self.get_mut_children_scratch().clear();
164        self.get_mut_flow_scratch().clear();
165        self.get_mut_abs_scratch().clear();
166        self.get_mut_flex_items_scratch().clear();
167        self.get_mut_flex_lines_scratch().clear();
168        self.get_mut_translate_scratch().clear();
169        self.layout_node(tree, root_id, space, &mut stats);
170        debug_assert!(self.get_children_scratch().is_empty());
171        debug_assert!(self.get_flow_scratch().is_empty());
172        debug_assert!(self.get_abs_scratch().is_empty());
173        debug_assert!(self.get_flex_items_scratch().is_empty());
174        debug_assert!(self.get_flex_lines_scratch().is_empty());
175        debug_assert!(self.get_mut_translate_scratch().is_empty());
176        self.set_last_stats(stats);
177        let invalidations: u64 = tree.get_layout_invalidations();
178        let changed_now: u64 = stats.get_nodes_changed() as u64;
179        let telemetry: &mut LayoutTelemetry = self.get_mut_telemetry();
180        telemetry.set_invalidations(invalidations);
181        telemetry.set_passes(telemetry.get_passes().saturating_add(1));
182        if changed_now > 0 {
183            telemetry.set_changed_passes(telemetry.get_changed_passes().saturating_add(1));
184            telemetry.set_changed_nodes_total(
185                telemetry
186                    .get_changed_nodes_total()
187                    .saturating_add(changed_now),
188            );
189        }
190        stats
191    }
192
193    /// Returns cumulative `LayoutTelemetry` counters (`invalidations`, `passes`, `changed_passes`, `changed_nodes_total`).
194    ///
195    /// # Arguments
196    ///
197    /// - `&Self` - Layout engine reference.
198    ///
199    /// # Returns
200    ///
201    /// - `LayoutTelemetry` - Cumulative layout telemetry snapshot.
202    #[must_use]
203    pub fn layout_telemetry(&self) -> LayoutTelemetry {
204        self.get_telemetry()
205    }
206
207    /// Resets cumulative `LayoutTelemetry` counters to zero.
208    ///
209    /// # Arguments
210    ///
211    /// - `&Self` - Mutable layout engine.
212    pub fn reset_telemetry(&mut self) {
213        self.set_telemetry(LayoutTelemetry::default());
214    }
215
216    /// Records the first pre-layout geometry snapshot of `node_id` when surgical damage tracking is active.
217    ///
218    /// # Arguments
219    ///
220    /// - `&Self` - Mutable layout engine.
221    /// - `&SceneTree` - Retained scene tree prior to writing `node_id`'s updated layout box.
222    /// - `NodeId` - Target node handle about to be mutated.
223    #[inline]
224    fn record_layout_snapshot(&mut self, tree: &SceneTree, node_id: NodeId) {
225        let Self {
226            track_damage,
227            damage_fallback,
228            layout_snapshots,
229            ..
230        } = self;
231        if !*track_damage || *damage_fallback != LAYOUT_FALLBACK_NONE {
232            return;
233        }
234        if layout_snapshots
235            .iter()
236            .any(|snap: &LayoutNodeSnapshot| snap.id == node_id)
237        {
238            return;
239        }
240        if layout_snapshots.len() >= DIRTY_PAINT_FULL_THRESHOLD {
241            *damage_fallback = LAYOUT_FALLBACK_OVERFLOW;
242            return;
243        }
244        let Some(node) = tree.get_node(node_id) else {
245            return;
246        };
247        let lbox: LayoutBox = node.get_layout_box();
248        let old_bounds: Rect = lbox.get_bounds();
249        let old_content_bounds: Rect = lbox.get_content_bounds();
250        let old_content_size: Size = lbox.get_content_size();
251        let (has_old_screen, old_screen): (bool, Rect) =
252            if old_bounds.get_width() > 0.0 && old_bounds.get_height() > 0.0 {
253                match tree.node_conservative_logical_rect(node_id) {
254                    Some(rect) => (true, rect),
255                    None => {
256                        *damage_fallback = LAYOUT_FALLBACK_UNSAFE;
257                        return;
258                    }
259                }
260            } else {
261                (false, Rect::default())
262            };
263        layout_snapshots.push(LayoutNodeSnapshot {
264            id: node_id,
265            old_bounds,
266            old_content_bounds,
267            old_content_size,
268            has_old_screen,
269            old_screen,
270        });
271    }
272
273    /// Returns `true` when two layout rectangles are equal within subpixel tolerance.
274    ///
275    /// # Arguments
276    ///
277    /// - `Rect` - First rectangle.
278    /// - `Rect` - Second rectangle.
279    ///
280    /// # Returns
281    ///
282    /// - `bool` - Whether position and dimensions match within `0.001` logical pixels.
283    #[inline]
284    fn rect_approx_eq(a: Rect, b: Rect) -> bool {
285        (a.get_x() - b.get_x()).abs() <= 0.001
286            && (a.get_y() - b.get_y()).abs() <= 0.001
287            && (a.get_width() - b.get_width()).abs() <= 0.001
288            && (a.get_height() - b.get_height()).abs() <= 0.001
289    }
290
291    /// Returns `true` when two layout sizes are equal within subpixel tolerance.
292    ///
293    /// # Arguments
294    ///
295    /// - `Size` - First size.
296    /// - `Size` - Second size.
297    ///
298    /// # Returns
299    ///
300    /// - `bool` - Whether width and height match within `0.001` logical pixels.
301    #[inline]
302    fn size_approx_eq(a: Size, b: Size) -> bool {
303        (a.get_width() - b.get_width()).abs() <= 0.001
304            && (a.get_height() - b.get_height()).abs() <= 0.001
305    }
306
307    /// Measures text bounding dimensions through the bounded `TextSizeCache`, delegating misses to `TextMeasurer::measure_size`.
308    ///
309    /// # Arguments
310    ///
311    /// - `&Self` - Mutable layout engine reference.
312    /// - `&str` - UTF-8 text content to measure.
313    /// - `TextStyle` - Active typography style.
314    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
315    ///
316    /// # Returns
317    ///
318    /// - `Size` - Exact measured bounding dimensions.
319    fn measure_text_cached(
320        &mut self,
321        text: &str,
322        style: TextStyle,
323        max_width: Option<f32>,
324    ) -> Size {
325        let measurer: DeterministicTextMeasurer = self.get_measurer();
326        self.get_mut_text_size_cache().get_or_measure(
327            text,
328            style,
329            max_width,
330            |raw: &str, text_style: TextStyle, limit: Option<f32>| {
331                measurer.measure_size(raw, text_style, limit)
332            },
333        )
334    }
335
336    /// Performs recursive layout on `node_id` with O(1) clean-subtree caching.
337    ///
338    /// # Arguments
339    ///
340    /// - `&Self` - Mutable layout engine reference.
341    /// - `&mut SceneTree` - Mutable scene tree.
342    /// - `NodeId` - Node handle to compute.
343    /// - `AvailableSpace` - Parent space constraint and origin.
344    /// - `&mut LayoutStats` - Mutable telemetry counters.
345    ///
346    /// # Returns
347    ///
348    /// - `Size` - Computed border-box dimensions of `node_id`.
349    fn layout_node(
350        &mut self,
351        tree: &mut SceneTree,
352        node_id: NodeId,
353        space: AvailableSpace,
354        stats: &mut LayoutStats,
355    ) -> Size {
356        let Some(node) = tree.get_node(node_id) else {
357            return Size::default();
358        };
359        if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
360            && let Some(prev_space) = node.cached_constraint()
361            && prev_space.can_reuse(space)
362        {
363            let prev_bounds: Rect = node.get_layout_box().get_bounds();
364            let cached_size: Size = Size::new(prev_bounds.get_width(), prev_bounds.get_height());
365            if !prev_space.same_origin(space) {
366                let dx: f32 = space.get_origin_x() - prev_space.get_origin_x();
367                let dy: f32 = space.get_origin_y() - prev_space.get_origin_y();
368                self.translate_subtree(tree, node_id, dx, dy);
369                if dx.abs() > 0.001 || dy.abs() > 0.001 {
370                    stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
371                }
372            }
373            stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
374            return cached_size;
375        }
376        stats.set_nodes_computed(stats.get_nodes_computed() + 1);
377        let style_ref: &Style = node.style_ref();
378        let Style {
379            layout: layout_ref,
380            paint: paint_ref,
381            text: text_ref,
382        } = style_ref;
383        if layout_ref.get_display() == Display::None {
384            let stack_base: usize = self.get_children_scratch().len();
385            self.get_mut_children_scratch().push(node_id);
386            while self.get_children_scratch().len() > stack_base {
387                if let Some(hid) = self.get_mut_children_scratch().pop() {
388                    self.record_layout_snapshot(tree, hid);
389                    if let Some(hidden_node) = tree.get_node_mut(hid) {
390                        let old_b: Rect = hidden_node.get_layout_box().get_bounds();
391                        if !Self::rect_approx_eq(old_b, Rect::default()) {
392                            stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
393                        }
394                        hidden_node.get_mut_layout_box().set_bounds(Rect::default());
395                        hidden_node
396                            .get_mut_layout_box()
397                            .set_content_bounds(Rect::default());
398                        if hid == node_id {
399                            hidden_node.set_last_constraint(Some(space));
400                        } else {
401                            hidden_node.set_last_constraint(None);
402                        }
403                        hidden_node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
404                        self.get_mut_children_scratch()
405                            .extend_from_slice(hidden_node.get_children().as_slice());
406                    }
407                }
408            }
409            return Size::default();
410        }
411        let padding: Edges = layout_ref.get_padding();
412        let border_w: f32 = paint_ref.get_border().get_width();
413        let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
414        let chrome_v: f32 = padding.vertical() + border_w * 2.0;
415        let explicit_w: Option<f32> = layout_ref
416            .get_width()
417            .resolve(space.get_width(), space.get_viewport());
418        let explicit_h: Option<f32> = layout_ref
419            .get_height()
420            .resolve(space.get_height(), space.get_viewport());
421        let mut resolved_w: Option<f32> = explicit_w;
422        let mut resolved_h: Option<f32> = explicit_h;
423        let stretched_w: bool = resolved_w.is_none() && space.get_stretch_width();
424        let stretched_h: bool = resolved_h.is_none() && space.get_stretch_height();
425        if stretched_w {
426            resolved_w = Some(space.get_width());
427        }
428        if stretched_h {
429            resolved_h = Some(space.get_height());
430        }
431        let min_w: f32 = layout_ref
432            .get_min_width()
433            .resolve(space.get_width(), space.get_viewport())
434            .unwrap_or(0.0);
435        let min_h: f32 = layout_ref
436            .get_min_height()
437            .resolve(space.get_height(), space.get_viewport())
438            .unwrap_or(0.0);
439        let max_w: f32 = layout_ref
440            .get_max_width()
441            .resolve(space.get_width(), space.get_viewport())
442            .unwrap_or(f32::INFINITY)
443            .max(min_w);
444        let max_h: f32 = layout_ref
445            .get_max_height()
446            .resolve(space.get_height(), space.get_viewport())
447            .unwrap_or(f32::INFINITY)
448            .max(min_h);
449        let aspect_ratio: Option<f32> = layout_ref.aspect_ratio_value();
450        if let Some(ratio) = aspect_ratio
451            && ratio > 0.0
452        {
453            if let Some(w) = resolved_w
454                && resolved_h.is_none()
455            {
456                resolved_h = Some(w.clamp(min_w, max_w) / ratio);
457            } else if let Some(h) = resolved_h
458                && resolved_w.is_none()
459            {
460                resolved_w = Some(h.clamp(min_h, max_h) * ratio);
461            }
462        }
463        let avail_w_outer: f32 = resolved_w
464            .unwrap_or(space.get_width())
465            .max(min_w)
466            .min(max_w);
467        let avail_h_outer: f32 = resolved_h
468            .unwrap_or(space.get_height())
469            .max(min_h)
470            .min(max_h);
471        let inner_avail_w: f32 = (avail_w_outer - chrome_h).max(0.0);
472        let inner_avail_h: f32 = (avail_h_outer - chrome_v).max(0.0);
473        let origin_x: f32 = space.get_origin_x();
474        let origin_y: f32 = space.get_origin_y();
475        let content_origin_x: f32 = origin_x + padding.get_left() + border_w;
476        let content_origin_y: f32 = origin_y + padding.get_top() + border_w;
477        let node_overflow: Overflow = layout_ref.get_overflow();
478        let node_flex_grow: f32 = layout_ref.get_flex_grow();
479        let width_independent: bool = explicit_w.is_some()
480            || (stretched_w
481                && resolved_w.is_some()
482                && (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
483        let height_independent: bool =
484            resolved_h.is_some() && layout_ref.get_height() != Length::Auto;
485        let skip_leaf_measure: bool =
486            node_overflow != Overflow::Scroll && width_independent && height_independent;
487        let mut child_range: Option<(usize, usize)> = None;
488        let leaf_content_size: Option<Size> = match node.get_kind() {
489            NodeKind::Text(text) => {
490                if skip_leaf_measure {
491                    Some(Size::new(inner_avail_w, inner_avail_h))
492                } else {
493                    Some(self.measure_text_cached(
494                        text.as_str(),
495                        *text_ref,
496                        Some(inner_avail_w.max(1.0)),
497                    ))
498                }
499            }
500            NodeKind::Image(img) => {
501                Some(Size::new(img.get_width() as f32, img.get_height() as f32))
502            }
503            NodeKind::Input(input_state) => {
504                if skip_leaf_measure {
505                    Some(Size::new(inner_avail_w, inner_avail_h))
506                } else {
507                    let sample: &str = if input_state.get_value().is_empty() {
508                        input_state.get_placeholder().as_str()
509                    } else {
510                        input_state.get_value().as_str()
511                    };
512                    let measured_size: Size =
513                        self.measure_text_cached(sample, *text_ref, Some(inner_avail_w.max(1.0)));
514                    Some(Size::new(
515                        measured_size.get_width().max(120.0),
516                        measured_size.get_height().max(20.0),
517                    ))
518                }
519            }
520            NodeKind::View
521            | NodeKind::ScrollView
522            | NodeKind::Portal
523            | NodeKind::Fragment
524            | NodeKind::Canvas => {
525                let node_children: &[NodeId] = node.get_children().as_slice();
526                if node_children.is_empty() {
527                    Some(Size::default())
528                } else {
529                    let start: usize = self.get_children_scratch().len();
530                    self.get_mut_children_scratch()
531                        .extend_from_slice(node_children);
532                    let end: usize = self.get_children_scratch().len();
533                    child_range = Some((start, end));
534                    None
535                }
536            }
537        };
538        let content_size: Size = if let Some(size) = leaf_content_size {
539            size
540        } else if let Some((child_start, child_end)) = child_range {
541            let frame: ContainerFrame = ContainerFrame::new(
542                *layout_ref,
543                Size::new(inner_avail_w, inner_avail_h),
544                space.get_viewport(),
545                Point::new(content_origin_x, content_origin_y),
546                resolved_w.is_some(),
547                resolved_h.is_some(),
548            );
549            let size: Size = self.layout_children(tree, child_start, child_end, frame, stats);
550            self.get_mut_children_scratch().truncate(child_start);
551            size
552        } else {
553            Size::default()
554        };
555        let content_outer_w: f32 = content_size.get_width() + chrome_h;
556        let content_outer_h: f32 = content_size.get_height() + chrome_v;
557        let mut final_w: f32 = match (explicit_w, stretched_w) {
558            (Some(w), _) => w,
559            (None, true) => {
560                let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
561                if node_overflow == Overflow::Visible
562                    && node_flex_grow <= 0.0
563                    && content_outer_w > base_w + 0.5
564                {
565                    content_outer_w
566                } else {
567                    base_w
568                }
569            }
570            (None, false) => content_outer_w,
571        };
572        let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
573        if let Some(ratio) = aspect_ratio
574            && ratio > 0.0
575        {
576            if resolved_w.is_some() && resolved_h.is_none() {
577                final_h = final_w / ratio;
578            } else if resolved_h.is_some() && resolved_w.is_none() {
579                final_w = final_h * ratio;
580            }
581        }
582        final_w = final_w.clamp(min_w, max_w).max(0.0);
583        final_h = final_h.clamp(min_h, max_h).max(0.0);
584        let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
585        let content_bounds: Rect = Rect::new(
586            content_origin_x,
587            content_origin_y,
588            (final_w - chrome_h).max(0.0),
589            (final_h - chrome_v).max(0.0),
590        );
591        self.record_layout_snapshot(tree, node_id);
592        if let Some(node) = tree.get_node_mut(node_id) {
593            let prev_box: LayoutBox = node.get_layout_box();
594            let changed: bool = !Self::rect_approx_eq(prev_box.get_bounds(), bounds)
595                || !Self::rect_approx_eq(prev_box.get_content_bounds(), content_bounds)
596                || !Self::size_approx_eq(prev_box.get_content_size(), content_size);
597            if changed {
598                stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
599            }
600            node.get_mut_layout_box().set_bounds(bounds);
601            node.get_mut_layout_box().set_content_bounds(content_bounds);
602            node.get_mut_layout_box().set_content_size(content_size);
603            node.set_last_constraint(Some(space));
604            node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
605        }
606        Size::new(final_w, final_h)
607    }
608
609    /// Lays out children according to Flex, Grid, or Block rules plus Absolute/Fixed overlays.
610    ///
611    /// # Arguments
612    ///
613    /// - `&Self` - Mutable layout engine reference.
614    /// - `&mut SceneTree` - Mutable scene tree.
615    /// - `usize` - Inclusive start index into `children_scratch`.
616    /// - `usize` - Exclusive end index into `children_scratch`.
617    /// - `ContainerFrame` - Parent layout constraints and origin.
618    /// - `&mut LayoutStats` - Mutable telemetry counters.
619    ///
620    /// # Returns
621    ///
622    /// - `Size` - Intrinsic aggregate content size occupied by flow children.
623    fn layout_children(
624        &mut self,
625        tree: &mut SceneTree,
626        child_start: usize,
627        child_end: usize,
628        frame: ContainerFrame,
629        stats: &mut LayoutStats,
630    ) -> Size {
631        let child_count: usize = child_end.saturating_sub(child_start);
632        if child_count == 0 {
633            return Size::default();
634        }
635        let parent_layout: LayoutStyle = frame.get_parent_layout();
636        let inner_avail: Size = frame.get_inner_avail();
637        let viewport: Size = frame.get_viewport();
638        let content_origin: Point = frame.get_content_origin();
639        let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
640            Display::Grid => None,
641            Display::Block => Some(FlexDirection::Column),
642            Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
643        };
644        let is_row_dir: bool = matches!(
645            flex_dir_opt,
646            Some(FlexDirection::Row | FlexDirection::RowReverse)
647        );
648        let is_reverse_dir: bool = matches!(
649            flex_dir_opt,
650            Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
651        );
652        let parent_align: AlignItems = parent_layout.get_align_items();
653        let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
654        let mut single_pass_ok: bool = flex_dir_opt.is_some()
655            && parent_layout.get_flex_wrap() != FlexWrap::Wrap
656            && !is_reverse_dir
657            && parent_layout.get_justify_content() == JustifyContent::Start;
658        let flow_start: usize = self.get_flow_scratch().len();
659        let abs_start: usize = self.get_abs_scratch().len();
660        for idx in child_start..child_end {
661            let child_id: NodeId = self.get_children_scratch()[idx];
662            if let Some(child_node) = tree.get_node(child_id) {
663                let Style {
664                    layout: child_layout,
665                    ..
666                } = child_node.style_ref();
667                if child_layout.get_display() == Display::None {
668                    let _: Size = self.layout_node(
669                        tree,
670                        child_id,
671                        AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
672                        stats,
673                    );
674                    continue;
675                }
676                match child_layout.get_position() {
677                    Position::Relative => {
678                        if single_pass_ok {
679                            if child_layout.get_flex_grow() > 0.0 {
680                                single_pass_ok = false;
681                            } else {
682                                let align: AlignItems = match child_layout.get_align_self() {
683                                    AlignSelf::Auto => parent_align,
684                                    AlignSelf::Stretch => AlignItems::Stretch,
685                                    AlignSelf::Start => AlignItems::Start,
686                                    AlignSelf::Center => AlignItems::Center,
687                                    AlignSelf::End => AlignItems::End,
688                                };
689                                let non_start_align: bool =
690                                    matches!(align, AlignItems::Center | AlignItems::End);
691                                let auto_row_stretch: bool = align == AlignItems::Stretch
692                                    && is_row_dir
693                                    && child_layout.get_height() == Length::Auto
694                                    && parent_height_auto;
695                                if non_start_align || auto_row_stretch {
696                                    single_pass_ok = false;
697                                }
698                            }
699                        }
700                        self.get_mut_flow_scratch().push(child_id);
701                    }
702                    Position::Absolute | Position::Fixed => {
703                        self.get_mut_abs_scratch().push(child_id)
704                    }
705                }
706            }
707        }
708        let flow_end: usize = self.get_flow_scratch().len();
709        let abs_end: usize = self.get_abs_scratch().len();
710        let flow_size: Size = if let Some(flex_dir) = flex_dir_opt {
711            self.layout_flex(
712                tree,
713                (flow_start, flow_end),
714                frame,
715                flex_dir,
716                single_pass_ok,
717                stats,
718            )
719        } else {
720            self.layout_grid(tree, flow_start, flow_end, frame, stats)
721        };
722        self.get_mut_flow_scratch().truncate(flow_start);
723        for abs_idx in abs_start..abs_end {
724            let abs_id: NodeId = self.get_abs_scratch()[abs_idx];
725            let child_layout_opt: Option<LayoutStyle> = tree
726                .get_node(abs_id)
727                .map(|node: &SceneNode| node.style_ref().get_layout());
728            let Some(child_layout) = child_layout_opt else {
729                continue;
730            };
731            let is_fixed: bool = child_layout.get_position() == Position::Fixed;
732            let ref_origin: Point = if is_fixed {
733                Point::new(0.0, 0.0)
734            } else {
735                content_origin
736            };
737            let ref_size: Size = if is_fixed { viewport } else { inner_avail };
738            let resolved_w: Option<f32> = child_layout
739                .get_width()
740                .resolve(ref_size.get_width(), viewport);
741            let resolved_h: Option<f32> = child_layout
742                .get_height()
743                .resolve(ref_size.get_height(), viewport);
744            let needs_intrinsic: bool = (resolved_w.is_none()
745                && child_layout.left_offset().is_none()
746                && child_layout.right_offset().is_some())
747                || (resolved_h.is_none()
748                    && child_layout.top_offset().is_none()
749                    && child_layout.bottom_offset().is_some());
750            let probed: Size = if needs_intrinsic {
751                let probe_space: AvailableSpace = AvailableSpace::new(
752                    ref_size.get_width(),
753                    ref_size.get_height(),
754                    viewport,
755                    ref_origin.get_x(),
756                    ref_origin.get_y(),
757                );
758                self.layout_node(tree, abs_id, probe_space, stats)
759            } else {
760                Size::new(ref_size.get_width(), ref_size.get_height())
761            };
762            let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
763            let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
764            let x: f32 = if let Some(left) = child_layout.left_offset() {
765                ref_origin.get_x() + left
766            } else if let Some(right) = child_layout.right_offset() {
767                ref_origin.get_x() + (ref_size.get_width() - child_w - right)
768            } else {
769                ref_origin.get_x()
770            };
771            let y: f32 = if let Some(top) = child_layout.top_offset() {
772                ref_origin.get_y() + top
773            } else if let Some(bottom) = child_layout.bottom_offset() {
774                ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
775            } else {
776                ref_origin.get_y()
777            };
778            let abs_space: AvailableSpace =
779                AvailableSpace::new(ref_size.get_width(), ref_size.get_height(), viewport, x, y);
780            let _: Size = self.layout_node(tree, abs_id, abs_space, stats);
781        }
782        self.get_mut_abs_scratch().truncate(abs_start);
783        flow_size
784    }
785
786    /// Executes single-line or multi-line Flexbox layout with grow, gap, justification, and alignment.
787    ///
788    /// # Arguments
789    ///
790    /// - `&Self` - Mutable layout engine reference.
791    /// - `&mut SceneTree` - Mutable scene tree.
792    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
793    /// - `ContainerFrame` - Container constraints and origin.
794    /// - `FlexDirection` - Effective main-axis direction.
795    /// - `bool` - Whether single-pass flex fast-path eligibility was confirmed while collecting flow children.
796    /// - `&mut LayoutStats` - Mutable telemetry counters.
797    ///
798    /// # Returns
799    ///
800    /// - `Size` - Aggregate content size of all flex lines.
801    fn layout_flex(
802        &mut self,
803        tree: &mut SceneTree,
804        flow_range: (usize, usize),
805        frame: ContainerFrame,
806        direction: FlexDirection,
807        single_pass_ok: bool,
808        stats: &mut LayoutStats,
809    ) -> Size {
810        let (flow_start, flow_end): (usize, usize) = flow_range;
811        let count_all: usize = flow_end.saturating_sub(flow_start);
812        if count_all == 0 {
813            return Size::default();
814        }
815        let parent_layout: LayoutStyle = frame.get_parent_layout();
816        let inner_avail: Size = frame.get_inner_avail();
817        let viewport: Size = frame.get_viewport();
818        let content_origin: Point = frame.get_content_origin();
819        let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
820        let is_reverse: bool = matches!(
821            direction,
822            FlexDirection::RowReverse | FlexDirection::ColumnReverse
823        );
824        let main_gap: f32 = if is_row {
825            parent_layout.get_column_gap()
826        } else {
827            parent_layout.get_row_gap()
828        };
829        let cross_gap: f32 = if is_row {
830            parent_layout.get_row_gap()
831        } else {
832            parent_layout.get_column_gap()
833        };
834        let main_avail: f32 = if is_row {
835            inner_avail.get_width()
836        } else {
837            inner_avail.get_height()
838        };
839        let cross_avail: f32 = if is_row {
840            inner_avail.get_height()
841        } else {
842            inner_avail.get_width()
843        };
844        if is_reverse {
845            self.get_mut_flow_scratch()[flow_start..flow_end].reverse();
846        }
847        let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
848        if single_pass_ok {
849            let parent_align: AlignItems = parent_layout.get_align_items();
850            let mut main_cursor: f32 = 0.0;
851            let mut max_cross: f32 = 0.0;
852            let records_start: usize = self.get_flex_items_scratch().len();
853            for offset in 0..count_all {
854                let child_id: NodeId = self.get_flow_scratch()[flow_start + offset];
855                let (margin, align, width_auto, height_auto, clean_cache): (
856                    Edges,
857                    AlignItems,
858                    bool,
859                    bool,
860                    Option<(AvailableSpace, Size)>,
861                ) = if let Some(node) = tree.get_node(child_id) {
862                    let Style {
863                        layout: child_layout,
864                        ..
865                    } = node.style_ref();
866                    let a: AlignItems = match child_layout.get_align_self() {
867                        AlignSelf::Auto => parent_align,
868                        AlignSelf::Stretch => AlignItems::Stretch,
869                        AlignSelf::Start => AlignItems::Start,
870                        AlignSelf::Center => AlignItems::Center,
871                        AlignSelf::End => AlignItems::End,
872                    };
873                    let cached: Option<(AvailableSpace, Size)> =
874                        if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
875                            && let Some(prev_space) = node.cached_constraint()
876                        {
877                            let prev_bounds: Rect = node.get_layout_box().get_bounds();
878                            Some((
879                                prev_space,
880                                Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
881                            ))
882                        } else {
883                            None
884                        };
885                    (
886                        child_layout.get_margin(),
887                        a,
888                        child_layout.get_width() == Length::Auto,
889                        child_layout.get_height() == Length::Auto,
890                        cached,
891                    )
892                } else {
893                    (Edges::default(), parent_align, true, true, None)
894                };
895                let (x, y): (f32, f32) = if is_row {
896                    (
897                        content_origin.get_x() + main_cursor + margin.get_left(),
898                        content_origin.get_y() + margin.get_top(),
899                    )
900                } else {
901                    (
902                        content_origin.get_x() + margin.get_left(),
903                        content_origin.get_y() + main_cursor + margin.get_top(),
904                    )
905                };
906                let stretch_w: bool = !is_row && align == AlignItems::Stretch && width_auto;
907                let stretch_h: bool = is_row && align == AlignItems::Stretch && height_auto;
908                let space_w: f32 = if stretch_w {
909                    (inner_avail.get_width() - margin.horizontal()).max(0.0)
910                } else {
911                    inner_avail.get_width()
912                };
913                let space_h: f32 = if stretch_h {
914                    (inner_avail.get_height() - margin.vertical()).max(0.0)
915                } else {
916                    inner_avail.get_height()
917                };
918                let final_space: AvailableSpace =
919                    AvailableSpace::new(space_w, space_h, viewport, x, y)
920                        .with_stretch(stretch_w, stretch_h);
921                let placed: Size = if let Some((prev_space, prev_size)) = clean_cache
922                    && prev_space.can_reuse(final_space)
923                {
924                    if !prev_space.same_origin(final_space) {
925                        let dx: f32 = x - prev_space.get_origin_x();
926                        let dy: f32 = y - prev_space.get_origin_y();
927                        self.translate_subtree(tree, child_id, dx, dy);
928                    }
929                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
930                    prev_size
931                } else {
932                    self.layout_node(tree, child_id, final_space, stats)
933                };
934                let target_w: f32 = if stretch_w {
935                    space_w.max(placed.get_width())
936                } else {
937                    placed.get_width()
938                };
939                let target_h: f32 = if stretch_h {
940                    space_h.max(placed.get_height())
941                } else {
942                    placed.get_height()
943                };
944                if (stretch_w && target_w > placed.get_width() + 0.01)
945                    || (stretch_h && target_h > placed.get_height() + 0.01)
946                {
947                    self.record_layout_snapshot(tree, child_id);
948                    if let Some(node) = tree.get_node_mut(child_id) {
949                        let mut b: Rect = node.get_layout_box().get_bounds();
950                        b.set_width(target_w);
951                        b.set_height(target_h);
952                        node.get_mut_layout_box().set_bounds(b);
953                    }
954                }
955                if stretch_w {
956                    self.get_mut_flex_items_scratch().push(FlexItemRecord {
957                        node_id: child_id,
958                        size: Size::new(target_w, target_h),
959                        probed_size: Size::default(),
960                        probed_origin: Point::default(),
961                        margin,
962                        flex_grow: 0.0,
963                        align_self: AlignSelf::Stretch,
964                        overflow: Overflow::Visible,
965                        flags: 0,
966                    });
967                }
968                if is_row {
969                    main_cursor += target_w + margin.horizontal();
970                    max_cross = max_cross.max(target_h + margin.vertical());
971                } else {
972                    main_cursor += target_h + margin.vertical();
973                    max_cross = max_cross.max(target_w + margin.horizontal());
974                }
975                if offset + 1 < count_all {
976                    main_cursor += main_gap;
977                }
978            }
979            let records_end: usize = self.get_flex_items_scratch().len();
980            if records_end > records_start && max_cross > cross_avail + 0.5 {
981                for rec_idx in records_start..records_end {
982                    let rec: FlexItemRecord = self.get_flex_items_scratch()[rec_idx];
983                    let widened: f32 =
984                        (max_cross - rec.margin.horizontal()).max(rec.size.get_width());
985                    self.record_layout_snapshot(tree, rec.node_id);
986                    if let Some(node) = tree.get_node_mut(rec.node_id) {
987                        let mut b: Rect = node.get_layout_box().get_bounds();
988                        b.set_width(widened);
989                        node.get_mut_layout_box().set_bounds(b);
990                    }
991                }
992            }
993            self.get_mut_flex_items_scratch().truncate(records_start);
994            return if is_row {
995                Size::new(main_cursor, max_cross)
996            } else {
997                Size::new(max_cross, main_cursor)
998            };
999        }
1000        let items_start: usize = self.get_flex_items_scratch().len();
1001        let probe_template: AvailableSpace = AvailableSpace::new(
1002            inner_avail.get_width(),
1003            inner_avail.get_height(),
1004            viewport,
1005            content_origin.get_x(),
1006            content_origin.get_y(),
1007        );
1008        let mut total_grow: f32 = 0.0;
1009        let mut single_line_main: f32 = 0.0;
1010        let mut single_line_cross: f32 = 0.0;
1011        for flow_idx in flow_start..flow_end {
1012            let child_id: NodeId = self.get_flow_scratch()[flow_idx];
1013            let mut rec: FlexItemRecord = FlexItemRecord {
1014                node_id: child_id,
1015                size: Size::default(),
1016                probed_size: Size::default(),
1017                probed_origin: Point::default(),
1018                margin: Edges::default(),
1019                flex_grow: 0.0,
1020                align_self: AlignSelf::Auto,
1021                overflow: Overflow::Visible,
1022                flags: FLEX_ITEM_DEFAULT_LEAF_FLAGS,
1023            };
1024            let mut zero_basis_size: Option<Size> = None;
1025            let mut clean_probe: Option<(Size, Point)> = None;
1026            if let Some(node) = tree.get_node(child_id) {
1027                let style_ref: &Style = node.style_ref();
1028                let Style {
1029                    layout: child_layout,
1030                    paint: child_paint,
1031                    ..
1032                } = style_ref;
1033                let width_len: Length = child_layout.get_width();
1034                let height_len: Length = child_layout.get_height();
1035                let grow: f32 = child_layout.get_flex_grow();
1036                let width_auto: bool = width_len == Length::Auto;
1037                let height_auto: bool = height_len == Length::Auto;
1038                let is_leaf: bool = matches!(
1039                    node.get_kind(),
1040                    NodeKind::Text(_) | NodeKind::Image(_) | NodeKind::Input(_)
1041                ) || node.get_children().is_empty();
1042                let mut f: u16 = 0;
1043                if width_auto {
1044                    f |= FLEX_ITEM_WIDTH_AUTO;
1045                }
1046                if height_auto {
1047                    f |= FLEX_ITEM_HEIGHT_AUTO;
1048                }
1049                if matches!(width_len, Length::Percent(_)) {
1050                    f |= FLEX_ITEM_WIDTH_PERCENT;
1051                }
1052                if matches!(height_len, Length::Percent(_)) {
1053                    f |= FLEX_ITEM_HEIGHT_PERCENT;
1054                }
1055                if matches!(child_layout.get_min_width(), Length::Percent(_))
1056                    || matches!(child_layout.get_max_width(), Length::Percent(_))
1057                {
1058                    f |= FLEX_ITEM_MINMAX_W_PERCENT;
1059                }
1060                if matches!(child_layout.get_min_height(), Length::Percent(_))
1061                    || matches!(child_layout.get_max_height(), Length::Percent(_))
1062                {
1063                    f |= FLEX_ITEM_MINMAX_H_PERCENT;
1064                }
1065                if child_layout.aspect_ratio_value().is_some() {
1066                    f |= FLEX_ITEM_HAS_ASPECT_RATIO;
1067                }
1068                if child_layout.get_min_height() != Length::Auto
1069                    || child_layout.get_max_height() != Length::Auto
1070                {
1071                    f |= FLEX_ITEM_MINMAX_H_SET;
1072                }
1073                if is_leaf {
1074                    f |= FLEX_ITEM_IS_LEAF;
1075                }
1076                let zero_basis: bool =
1077                    !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1078                if zero_basis {
1079                    zero_basis_size = if is_row {
1080                        let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1081                        Some(Size::new(0.0, h))
1082                    } else {
1083                        let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1084                        Some(Size::new(w, 0.0))
1085                    };
1086                } else if !node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1087                    && let Some(prev) = node.cached_constraint()
1088                    && prev.can_reuse(probe_template)
1089                {
1090                    let b: Rect = node.get_layout_box().get_bounds();
1091                    let probed_h: f32 = if is_leaf
1092                        && height_auto
1093                        && (f & (FLEX_ITEM_MINMAX_H_SET | FLEX_ITEM_HAS_ASPECT_RATIO)) == 0
1094                    {
1095                        let pad: Edges = child_layout.get_padding();
1096                        let bw: f32 = child_paint.get_border().get_width();
1097                        let chrome_v: f32 = pad.vertical() + bw * 2.0;
1098                        (node.get_layout_box().get_content_size().get_height() + chrome_v).max(0.0)
1099                    } else {
1100                        b.get_height()
1101                    };
1102                    clean_probe = Some((
1103                        Size::new(b.get_width(), probed_h),
1104                        Point::new(prev.get_origin_x(), prev.get_origin_y()),
1105                    ));
1106                }
1107                rec.margin = child_layout.get_margin();
1108                rec.flex_grow = grow;
1109                rec.align_self = child_layout.get_align_self();
1110                rec.overflow = child_layout.get_overflow();
1111                rec.flags = f;
1112            }
1113            total_grow += rec.flex_grow;
1114            let (child_size, probed_origin): (Size, Point) = if let Some(zb) = zero_basis_size {
1115                (zb, content_origin)
1116            } else if let Some((cached_size, cached_origin)) = clean_probe {
1117                rec.flags |= FLEX_ITEM_PROBED;
1118                stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1119                (cached_size, cached_origin)
1120            } else {
1121                let measured: Size = self.layout_node(tree, child_id, probe_template, stats);
1122                rec.flags |= FLEX_ITEM_PROBED;
1123                (measured, content_origin)
1124            };
1125            if !wrap_enabled {
1126                if is_row {
1127                    single_line_main += child_size.get_width() + rec.margin.horizontal();
1128                    single_line_cross =
1129                        single_line_cross.max(child_size.get_height() + rec.margin.vertical());
1130                } else {
1131                    single_line_main += child_size.get_height() + rec.margin.vertical();
1132                    single_line_cross =
1133                        single_line_cross.max(child_size.get_width() + rec.margin.horizontal());
1134                }
1135            }
1136            rec.size = child_size;
1137            rec.probed_size = child_size;
1138            rec.probed_origin = probed_origin;
1139            self.get_mut_flex_items_scratch().push(rec);
1140        }
1141        let items_end: usize = self.get_flex_items_scratch().len();
1142        if !wrap_enabled {
1143            let line_ctx: FlexLineContext = FlexLineContext {
1144                frame,
1145                is_row,
1146                wrap_enabled: false,
1147                main_gap,
1148                main_avail,
1149                cross_avail,
1150                total_grow,
1151                line_count: 1,
1152            };
1153            let line_size: Size = self.layout_flex_line(
1154                tree,
1155                (items_start, items_end),
1156                0.0,
1157                Some((single_line_main, single_line_cross)),
1158                line_ctx,
1159                stats,
1160            );
1161            self.get_mut_flex_items_scratch().truncate(items_start);
1162            return line_size;
1163        }
1164        let lines_start: usize = self.get_flex_lines_scratch().len();
1165        let mut cur_line_start: usize = items_start;
1166        let mut line_main: f32 = 0.0;
1167        for item_idx in items_start..items_end {
1168            let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1169            let item_main: f32 = if is_row {
1170                item.size.get_width() + item.margin.horizontal()
1171            } else {
1172                item.size.get_height() + item.margin.vertical()
1173            };
1174            let line_empty: bool = item_idx == cur_line_start;
1175            let needed: f32 = if line_empty {
1176                item_main
1177            } else {
1178                line_main + main_gap + item_main
1179            };
1180            if !line_empty && needed > main_avail && main_avail > 0.0 {
1181                self.get_mut_flex_lines_scratch()
1182                    .push((cur_line_start, item_idx));
1183                cur_line_start = item_idx;
1184                line_main = item_main;
1185            } else {
1186                line_main = needed;
1187            }
1188        }
1189        if cur_line_start < items_end {
1190            self.get_mut_flex_lines_scratch()
1191                .push((cur_line_start, items_end));
1192        }
1193        let lines_end: usize = self.get_flex_lines_scratch().len();
1194        let mut cross_cursor: f32 = 0.0;
1195        let mut max_main_extent: f32 = 0.0;
1196        let line_count: usize = lines_end.saturating_sub(lines_start);
1197        for line_offset in 0..line_count {
1198            let line_range: (usize, usize) =
1199                self.get_flex_lines_scratch()[lines_start + line_offset];
1200            let mut line_grow: f32 = 0.0;
1201            for item_idx in line_range.0..line_range.1 {
1202                line_grow += self.get_flex_items_scratch()[item_idx].flex_grow;
1203            }
1204            let line_ctx: FlexLineContext = FlexLineContext {
1205                frame,
1206                is_row,
1207                wrap_enabled: true,
1208                main_gap,
1209                main_avail,
1210                cross_avail,
1211                total_grow: line_grow,
1212                line_count,
1213            };
1214            let line_size: Size =
1215                self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1216            if is_row {
1217                max_main_extent = max_main_extent.max(line_size.get_width());
1218                cross_cursor += line_size.get_height();
1219            } else {
1220                max_main_extent = max_main_extent.max(line_size.get_height());
1221                cross_cursor += line_size.get_width();
1222            }
1223            if line_offset + 1 < line_count {
1224                cross_cursor += cross_gap;
1225            }
1226        }
1227        self.get_mut_flex_lines_scratch().truncate(lines_start);
1228        self.get_mut_flex_items_scratch().truncate(items_start);
1229        if is_row {
1230            Size::new(max_main_extent, cross_cursor)
1231        } else {
1232            Size::new(cross_cursor, max_main_extent)
1233        }
1234    }
1235
1236    /// Places a single contiguous flex line slice `[line_start..line_end)` and returns its occupied `(width, height)`.
1237    ///
1238    /// # Arguments
1239    ///
1240    /// - `&Self` - Mutable layout engine reference.
1241    /// - `&mut SceneTree` - Mutable scene tree.
1242    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flex_items_scratch`.
1243    /// - `f32` - Cross-axis cursor offset where this line begins.
1244    /// - `Option<(f32, f32)>` - Optional pre-accumulated `(items_main_sum, line_cross)` for unwrapped single-line passes.
1245    /// - `FlexLineContext` - Enclosing container axis and gap parameters.
1246    /// - `&mut LayoutStats` - Mutable telemetry counters.
1247    ///
1248    /// # Returns
1249    ///
1250    /// - `Size` - Occupied `(width, height)` extent of this flex line.
1251    #[inline(always)]
1252    fn layout_flex_line(
1253        &mut self,
1254        tree: &mut SceneTree,
1255        line_range: (usize, usize),
1256        cross_cursor: f32,
1257        precomputed: Option<(f32, f32)>,
1258        ctx: FlexLineContext,
1259        stats: &mut LayoutStats,
1260    ) -> Size {
1261        let (line_start, line_end): (usize, usize) = line_range;
1262        let frame: ContainerFrame = ctx.frame;
1263        let is_row: bool = ctx.is_row;
1264        let wrap_enabled: bool = ctx.wrap_enabled;
1265        let main_gap: f32 = ctx.main_gap;
1266        let main_avail: f32 = ctx.main_avail;
1267        let cross_avail: f32 = ctx.cross_avail;
1268        let total_grow: f32 = ctx.total_grow;
1269        let line_count: usize = ctx.line_count;
1270        let parent_layout: LayoutStyle = frame.get_parent_layout();
1271        let inner_avail: Size = frame.get_inner_avail();
1272        let viewport: Size = frame.get_viewport();
1273        let content_origin: Point = frame.get_content_origin();
1274        let count: usize = line_end.saturating_sub(line_start);
1275        let gaps_total: f32 = if count > 1 {
1276            main_gap * ((count - 1) as f32)
1277        } else {
1278            0.0
1279        };
1280        let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1281        let effective_main_avail: f32 = if is_row {
1282            if has_definite_or_grow || wrap_enabled {
1283                main_avail
1284            } else {
1285                parent_layout
1286                    .get_min_width()
1287                    .resolve(viewport.get_width(), viewport)
1288                    .map(|mw: f32| (mw - parent_layout.get_padding().horizontal()).max(0.0))
1289                    .unwrap_or(0.0)
1290            }
1291        } else if frame.get_definite_height() {
1292            main_avail
1293        } else {
1294            parent_layout
1295                .get_min_height()
1296                .resolve(viewport.get_height(), viewport)
1297                .map(|mh: f32| (mh - parent_layout.get_padding().vertical()).max(0.0))
1298                .unwrap_or(0.0)
1299        };
1300        let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1301            precomputed
1302            && total_grow == 0.0
1303        {
1304            (items_main + gaps_total, pre_cross)
1305        } else {
1306            let used_main: f32 = if let Some((items_main, _)) = precomputed {
1307                items_main + gaps_total
1308            } else {
1309                let mut acc: f32 = gaps_total;
1310                for item_idx in line_start..line_end {
1311                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1312                    let sz: f32 = if is_row {
1313                        item.size.get_width() + item.margin.horizontal()
1314                    } else {
1315                        item.size.get_height() + item.margin.vertical()
1316                    };
1317                    acc += sz;
1318                }
1319                acc
1320            };
1321            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1322            if total_grow > 0.0 && free_main > 0.0 {
1323                for item_idx in line_start..line_end {
1324                    let item: &mut FlexItemRecord =
1325                        &mut self.get_mut_flex_items_scratch()[item_idx];
1326                    let grow: f32 = item.flex_grow;
1327                    if grow > 0.0 {
1328                        let extra: f32 = free_main * (grow / total_grow);
1329                        if is_row {
1330                            item.size.set_width(item.size.get_width() + extra);
1331                        } else {
1332                            item.size.set_height(item.size.get_height() + extra);
1333                        }
1334                    }
1335                }
1336            }
1337            if total_grow > 0.0 {
1338                for item_idx in line_start..line_end {
1339                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1340                    let auto_cross: bool = item.flex_grow > 0.0
1341                        && if is_row {
1342                            (item.flags & FLEX_ITEM_HEIGHT_AUTO) != 0
1343                        } else {
1344                            (item.flags & FLEX_ITEM_WIDTH_AUTO) != 0
1345                        };
1346                    if auto_cross {
1347                        let probe_w: f32 = if is_row {
1348                            item.size.get_width()
1349                        } else {
1350                            cross_avail
1351                        };
1352                        let probe_h: f32 = if is_row {
1353                            cross_avail
1354                        } else {
1355                            item.size.get_height()
1356                        };
1357                        let probe_sp: AvailableSpace = AvailableSpace::new(
1358                            probe_w,
1359                            probe_h,
1360                            viewport,
1361                            content_origin.get_x(),
1362                            content_origin.get_y(),
1363                        );
1364                        let measured: Size = self.layout_node(tree, item.node_id, probe_sp, stats);
1365                        let slot: &mut FlexItemRecord =
1366                            &mut self.get_mut_flex_items_scratch()[item_idx];
1367                        if is_row {
1368                            slot.size.set_height(measured.get_height());
1369                        } else {
1370                            slot.size.set_width(measured.get_width());
1371                        }
1372                        slot.flags &= !FLEX_ITEM_PROBED;
1373                    }
1374                }
1375            }
1376            let mut sum_main: f32 = gaps_total;
1377            let mut max_cross: f32 = 0.0;
1378            for item_idx in line_start..line_end {
1379                let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1380                if is_row {
1381                    sum_main += item.size.get_width() + item.margin.horizontal();
1382                    max_cross = max_cross.max(item.size.get_height() + item.margin.vertical());
1383                } else {
1384                    sum_main += item.size.get_height() + item.margin.vertical();
1385                    max_cross = max_cross.max(item.size.get_width() + item.margin.horizontal());
1386                }
1387            }
1388            (sum_main, max_cross)
1389        };
1390        let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
1391        let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
1392            JustifyContent::Start => (0.0, 0.0),
1393            JustifyContent::Center => (rem * 0.5, 0.0),
1394            JustifyContent::End => (rem, 0.0),
1395            JustifyContent::SpaceBetween => {
1396                if count > 1 {
1397                    (0.0, rem / ((count - 1) as f32))
1398                } else {
1399                    (0.0, 0.0)
1400                }
1401            }
1402            JustifyContent::SpaceAround => {
1403                let slot: f32 = rem / (count.max(1) as f32);
1404                (slot * 0.5, slot)
1405            }
1406            JustifyContent::SpaceEvenly => {
1407                let slot: f32 = rem / ((count + 1) as f32);
1408                (slot, slot)
1409            }
1410        };
1411        let definite_cross: bool = !is_row || frame.get_definite_height();
1412        let effective_line_cross: f32 = if line_count == 1 && !wrap_enabled && definite_cross {
1413            line_cross.max(cross_avail)
1414        } else {
1415            line_cross
1416        };
1417        let mut actual_line_cross: f32 = line_cross;
1418        let parent_align: AlignItems = parent_layout.get_align_items();
1419        for idx in 0..count {
1420            let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
1421            let child_id: NodeId = rec.node_id;
1422            let child_size: Size = rec.size;
1423            let margin: Edges = rec.margin;
1424            let width_auto: bool = (rec.flags & FLEX_ITEM_WIDTH_AUTO) != 0;
1425            let height_auto: bool = (rec.flags & FLEX_ITEM_HEIGHT_AUTO) != 0;
1426            let is_leaf: bool = (rec.flags & FLEX_ITEM_IS_LEAF) != 0;
1427            let item_cross: f32 = if is_row {
1428                child_size.get_height()
1429            } else {
1430                child_size.get_width()
1431            };
1432            let align: AlignItems = match rec.align_self {
1433                AlignSelf::Auto => parent_align,
1434                AlignSelf::Stretch => AlignItems::Stretch,
1435                AlignSelf::Start => AlignItems::Start,
1436                AlignSelf::Center => AlignItems::Center,
1437                AlignSelf::End => AlignItems::End,
1438            };
1439            let avail_item_cross: f32 = (effective_line_cross
1440                - if is_row {
1441                    margin.vertical()
1442                } else {
1443                    margin.horizontal()
1444                })
1445            .max(0.0);
1446            let cross_offset: f32 = match align {
1447                AlignItems::Start | AlignItems::Stretch => 0.0,
1448                AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
1449                AlignItems::End => (avail_item_cross - item_cross).max(0.0),
1450            };
1451            let auto_cross_grow: bool =
1452                rec.flex_grow > 0.0 && if is_row { height_auto } else { width_auto };
1453            let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
1454                avail_item_cross.max(child_size.get_width())
1455            } else {
1456                child_size.get_width()
1457            };
1458            let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
1459                avail_item_cross.max(child_size.get_height())
1460            } else {
1461                child_size.get_height()
1462            };
1463            let (x, y): (f32, f32) = if is_row {
1464                (
1465                    content_origin.get_x() + main_cursor + margin.get_left(),
1466                    content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
1467                )
1468            } else {
1469                (
1470                    content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
1471                    content_origin.get_y() + main_cursor + margin.get_top(),
1472                )
1473            };
1474            let space_w: f32 = if (rec.flags & FLEX_ITEM_WIDTH_PERCENT) != 0 {
1475                inner_avail.get_width()
1476            } else if auto_cross_grow && !is_row {
1477                cross_avail
1478            } else {
1479                target_w
1480            };
1481            let space_h: f32 = if (rec.flags & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
1482                inner_avail.get_height()
1483            } else if auto_cross_grow && is_row {
1484                cross_avail
1485            } else {
1486                target_h
1487            };
1488            let stretch_child_w: bool = !(auto_cross_grow && !is_row)
1489                && ((!is_row && align == AlignItems::Stretch && width_auto)
1490                    || (is_row && rec.flex_grow > 0.0 && width_auto));
1491            let stretch_child_h: bool = !(auto_cross_grow && is_row)
1492                && ((is_row && align == AlignItems::Stretch && height_auto)
1493                    || (!is_row && rec.flex_grow > 0.0 && height_auto));
1494            let same_w: bool = (target_w - rec.probed_size.get_width()).abs() <= 0.001;
1495            let same_h: bool = (target_h - rec.probed_size.get_height()).abs() <= 0.001;
1496            let width_fixed_or_leaf: bool = is_leaf || !width_auto;
1497            let width_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_W_PERCENT) == 0;
1498            let width_invariant: bool = (space_w - inner_avail.get_width()).abs() <= 0.01
1499                || (width_fixed_or_leaf && width_no_pct_bounds);
1500            let height_fixed_or_leaf: bool = is_leaf || !height_auto;
1501            let height_no_pct_bounds: bool = (rec.flags & FLEX_ITEM_MINMAX_H_PERCENT) == 0;
1502            let height_invariant: bool = (space_h - inner_avail.get_height()).abs() <= 0.01
1503                || (height_fixed_or_leaf && height_no_pct_bounds);
1504            let probed_ok: bool = (rec.flags & FLEX_ITEM_PROBED) != 0
1505                && !auto_cross_grow
1506                && (rec.flags & FLEX_ITEM_HAS_ASPECT_RATIO) == 0
1507                && width_invariant
1508                && height_invariant;
1509            let can_translate_exact: bool = probed_ok
1510                && same_w
1511                && same_h
1512                && (is_leaf || (!stretch_child_w && !stretch_child_h));
1513            let can_stretch_leaf_h: bool = probed_ok
1514                && is_leaf
1515                && is_row
1516                && same_w
1517                && !stretch_child_w
1518                && stretch_child_h
1519                && height_auto
1520                && (rec.flags & FLEX_ITEM_MINMAX_H_SET) == 0;
1521            if can_translate_exact {
1522                let dx: f32 = x - rec.probed_origin.get_x();
1523                let dy: f32 = y - rec.probed_origin.get_y();
1524                if dx.abs() > 0.001 || dy.abs() > 0.001 {
1525                    self.translate_subtree(tree, child_id, dx, dy);
1526                }
1527            } else if can_stretch_leaf_h {
1528                self.record_layout_snapshot(tree, child_id);
1529                if let Some(node) = tree.get_node_mut(child_id) {
1530                    let cur_bounds: Rect = node.get_layout_box().get_bounds();
1531                    let same_box: bool = (cur_bounds.get_x() - x).abs() <= 0.001
1532                        && (cur_bounds.get_y() - y).abs() <= 0.001
1533                        && (cur_bounds.get_width() - target_w).abs() <= 0.001
1534                        && (cur_bounds.get_height() - target_h).abs() <= 0.001;
1535                    if !same_box {
1536                        let Style {
1537                            layout: child_layout,
1538                            paint: child_paint,
1539                            ..
1540                        } = node.style_ref();
1541                        let pad: Edges = child_layout.get_padding();
1542                        let bw: f32 = child_paint.get_border().get_width();
1543                        let chrome_h: f32 = pad.horizontal() + bw * 2.0;
1544                        let chrome_v: f32 = pad.vertical() + bw * 2.0;
1545                        let new_bounds: Rect = Rect::new(x, y, target_w, target_h);
1546                        let new_content: Rect = Rect::new(
1547                            x + pad.get_left() + bw,
1548                            y + pad.get_top() + bw,
1549                            (target_w - chrome_h).max(0.0),
1550                            (target_h - chrome_v).max(0.0),
1551                        );
1552                        node.get_mut_layout_box().set_bounds(new_bounds);
1553                        node.get_mut_layout_box().set_content_bounds(new_content);
1554                        if let Some(mut c) = node.cached_constraint() {
1555                            c.set_origin_x(x);
1556                            c.set_origin_y(y);
1557                            node.set_last_constraint(Some(c));
1558                        }
1559                    }
1560                }
1561            } else {
1562                let final_space: AvailableSpace =
1563                    AvailableSpace::new(space_w, space_h, viewport, x, y)
1564                        .with_stretch(stretch_child_w, stretch_child_h);
1565                let placed: Size = self.layout_node(tree, child_id, final_space, stats);
1566                self.record_layout_snapshot(tree, child_id);
1567                if let Some(node) = tree.get_node_mut(child_id) {
1568                    let mut b: Rect = node.get_layout_box().get_bounds();
1569                    let is_clipped: bool =
1570                        matches!(rec.overflow, Overflow::Hidden | Overflow::Scroll);
1571                    if auto_cross_grow {
1572                        if is_row {
1573                            b.set_width(target_w);
1574                            b.set_height(placed.get_height());
1575                            actual_line_cross =
1576                                actual_line_cross.max(placed.get_height() + margin.vertical());
1577                        } else {
1578                            b.set_width(placed.get_width());
1579                            b.set_height(target_h);
1580                            actual_line_cross =
1581                                actual_line_cross.max(placed.get_width() + margin.horizontal());
1582                        }
1583                    } else if is_clipped || rec.flex_grow > 0.0 {
1584                        b.set_width(target_w);
1585                        b.set_height(target_h);
1586                    } else {
1587                        b.set_width(target_w.max(placed.get_width()));
1588                        b.set_height(target_h.max(placed.get_height()));
1589                    }
1590                    node.get_mut_layout_box().set_bounds(b);
1591                }
1592            }
1593            let advance: f32 = if is_row {
1594                target_w + margin.horizontal()
1595            } else {
1596                target_h + margin.vertical()
1597            };
1598            main_cursor += advance;
1599            if idx + 1 < count {
1600                main_cursor += main_gap + extra_step;
1601            }
1602        }
1603        if is_row {
1604            Size::new(final_used_main, actual_line_cross)
1605        } else {
1606            Size::new(actual_line_cross, final_used_main)
1607        }
1608    }
1609
1610    /// Executes uniform-column CSS Grid layout with row and column gaps.
1611    ///
1612    /// # Arguments
1613    ///
1614    /// - `&Self` - Mutable layout engine reference.
1615    /// - `&mut SceneTree` - Mutable scene tree.
1616    /// - `usize` - Inclusive start index into `flow_scratch`.
1617    /// - `usize` - Exclusive end index into `flow_scratch`.
1618    /// - `ContainerFrame` - Grid container constraints and origin.
1619    /// - `&mut LayoutStats` - Mutable telemetry counters.
1620    ///
1621    /// # Returns
1622    ///
1623    /// - `Size` - Aggregate grid content dimensions.
1624    fn layout_grid(
1625        &mut self,
1626        tree: &mut SceneTree,
1627        flow_start: usize,
1628        flow_end: usize,
1629        frame: ContainerFrame,
1630        stats: &mut LayoutStats,
1631    ) -> Size {
1632        if flow_start >= flow_end {
1633            return Size::default();
1634        }
1635        let parent_layout: LayoutStyle = frame.get_parent_layout();
1636        let inner_avail: Size = frame.get_inner_avail();
1637        let viewport: Size = frame.get_viewport();
1638        let content_origin: Point = frame.get_content_origin();
1639        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
1640        let col_gap: f32 = parent_layout.get_column_gap();
1641        let row_gap: f32 = parent_layout.get_row_gap();
1642        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
1643        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
1644        let col_step: f32 = col_w + col_gap;
1645        let origin_x: f32 = content_origin.get_x();
1646        let origin_y: f32 = content_origin.get_y();
1647        let inner_h: f32 = inner_avail.get_height();
1648        let mut y_cursor: f32 = 0.0;
1649        let mut idx: usize = flow_start;
1650        while idx < flow_end {
1651            let row_end: usize = (idx + cols).min(flow_end);
1652            let mut row_h: f32 = 0.0;
1653            let mut min_row_h: f32 = f32::INFINITY;
1654            let y: f32 = origin_y + y_cursor;
1655            let mut x: f32 = origin_x;
1656            for pos in idx..row_end {
1657                let child_id: NodeId = self.get_flow_scratch()[pos];
1658                let (auto_w, clean_cache): (bool, Option<(AvailableSpace, Size)>) =
1659                    if let Some(n) = tree.get_node(child_id) {
1660                        let Style { layout, .. } = n.style_ref();
1661                        let is_auto_w: bool = layout.get_width() == Length::Auto;
1662                        let cached: Option<(AvailableSpace, Size)> =
1663                            if !n.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
1664                                && let Some(prev_space) = n.cached_constraint()
1665                            {
1666                                let prev_bounds: Rect = n.get_layout_box().get_bounds();
1667                                Some((
1668                                    prev_space,
1669                                    Size::new(prev_bounds.get_width(), prev_bounds.get_height()),
1670                                ))
1671                            } else {
1672                                None
1673                            };
1674                        (is_auto_w, cached)
1675                    } else {
1676                        (false, None)
1677                    };
1678                let cell_space: AvailableSpace =
1679                    AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
1680                let child_size: Size = if let Some((prev_space, prev_size)) = clean_cache
1681                    && prev_space.can_reuse(cell_space)
1682                {
1683                    if !prev_space.same_origin(cell_space) {
1684                        let dx: f32 = x - prev_space.get_origin_x();
1685                        let dy: f32 = y - prev_space.get_origin_y();
1686                        self.translate_subtree(tree, child_id, dx, dy);
1687                    }
1688                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
1689                    prev_size
1690                } else {
1691                    self.layout_node(tree, child_id, cell_space, stats)
1692                };
1693                if (child_size.get_width() - col_w).abs() > 0.001 {
1694                    self.record_layout_snapshot(tree, child_id);
1695                    if let Some(node) = tree.get_node_mut(child_id) {
1696                        let mut b: Rect = node.get_layout_box().get_bounds();
1697                        b.set_width(col_w);
1698                        node.get_mut_layout_box().set_bounds(b);
1699                    }
1700                }
1701                let ch: f32 = child_size.get_height();
1702                row_h = row_h.max(ch);
1703                min_row_h = min_row_h.min(ch);
1704                x += col_step;
1705            }
1706            if row_end - idx > 1 && min_row_h < row_h {
1707                for pos in idx..row_end {
1708                    let child_id: NodeId = self.get_flow_scratch()[pos];
1709                    let needs_stretch: bool =
1710                        tree.get_node(child_id).is_some_and(|n: &SceneNode| {
1711                            n.get_layout_box().get_bounds().get_height() < row_h
1712                        });
1713                    if needs_stretch {
1714                        self.record_layout_snapshot(tree, child_id);
1715                        if let Some(node) = tree.get_node_mut(child_id) {
1716                            let mut b: Rect = node.get_layout_box().get_bounds();
1717                            b.set_height(row_h);
1718                            node.get_mut_layout_box().set_bounds(b);
1719                        }
1720                    }
1721                }
1722            }
1723            y_cursor += row_h;
1724            if row_end < flow_end {
1725                y_cursor += row_gap;
1726            }
1727            idx = row_end;
1728        }
1729        Size::new(inner_avail.get_width(), y_cursor)
1730    }
1731
1732    /// Translates the cached layout geometry of `root_id` and all non-fixed descendants by `(dx, dy)` in O(subtree) without re-running layout or text measurement.
1733    ///
1734    /// # Arguments
1735    ///
1736    /// - `&Self` - Mutable layout engine reference.
1737    /// - `&mut SceneTree` - Mutable retained scene tree.
1738    /// - `NodeId` - Root node of the clean subtree being shifted.
1739    /// - `f32` - Horizontal translation delta in logical pixels.
1740    /// - `f32` - Vertical translation delta in logical pixels.
1741    fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
1742        if dx == 0.0 && dy == 0.0 {
1743            return;
1744        }
1745        self.record_layout_snapshot(tree, root_id);
1746        let Some(root_node) = tree.get_node_mut(root_id) else {
1747            return;
1748        };
1749        let Style { layout, .. } = root_node.style_ref();
1750        let root_none_disp: bool = layout.get_display() == Display::None;
1751        if let Some(mut c) = root_node.cached_constraint() {
1752            c.set_origin_x(c.get_origin_x() + dx);
1753            c.set_origin_y(c.get_origin_y() + dy);
1754            root_node.set_last_constraint(Some(c));
1755        }
1756        if root_none_disp {
1757            return;
1758        }
1759        let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
1760        root_bounds.set_x(root_bounds.get_x() + dx);
1761        root_bounds.set_y(root_bounds.get_y() + dy);
1762        root_node.get_mut_layout_box().set_bounds(root_bounds);
1763        let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
1764        root_content.set_x(root_content.get_x() + dx);
1765        root_content.set_y(root_content.get_y() + dy);
1766        root_node
1767            .get_mut_layout_box()
1768            .set_content_bounds(root_content);
1769        let root_children: &[NodeId] = root_node.get_children().as_slice();
1770        if root_children.is_empty() {
1771            return;
1772        }
1773        self.get_mut_translate_scratch().clear();
1774        self.get_mut_translate_scratch()
1775            .extend_from_slice(root_children);
1776        while let Some(nid) = self.get_mut_translate_scratch().pop() {
1777            let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
1778                Some(node) => {
1779                    let Style { layout, .. } = node.style_ref();
1780                    (
1781                        layout.get_position() == Position::Fixed,
1782                        layout.get_display() == Display::None,
1783                    )
1784                }
1785                None => continue,
1786            };
1787            if is_fixed_pos {
1788                continue;
1789            }
1790            if !is_none_disp {
1791                self.record_layout_snapshot(tree, nid);
1792            }
1793            let Some(node) = tree.get_node_mut(nid) else {
1794                continue;
1795            };
1796            if let Some(mut c) = node.cached_constraint() {
1797                c.set_origin_x(c.get_origin_x() + dx);
1798                c.set_origin_y(c.get_origin_y() + dy);
1799                node.set_last_constraint(Some(c));
1800            }
1801            if is_none_disp {
1802                continue;
1803            }
1804            let mut bounds: Rect = node.get_layout_box().get_bounds();
1805            bounds.set_x(bounds.get_x() + dx);
1806            bounds.set_y(bounds.get_y() + dy);
1807            node.get_mut_layout_box().set_bounds(bounds);
1808            let mut content: Rect = node.get_layout_box().get_content_bounds();
1809            content.set_x(content.get_x() + dx);
1810            content.set_y(content.get_y() + dy);
1811            node.get_mut_layout_box().set_content_bounds(content);
1812            let children_slice: &[NodeId] = node.get_children().as_slice();
1813            if !children_slice.is_empty() {
1814                self.get_mut_translate_scratch()
1815                    .extend_from_slice(children_slice);
1816            }
1817        }
1818    }
1819}