Skip to main content

strata_layout/
flexbox.rs

1//! W3C Flexible Box Layout Level 1 Multi-Pass Solver.
2
3use crate::box_model::{
4    clamp_dimension, clamp_dimension_with_node, resolve_dimension, resolve_dimension_with_node,
5};
6use crate::geometry::{LayoutGeometry, Rect};
7use crate::tree::LayoutNode;
8use strata_style::types::{
9    AlignItems, AlignSelf, Dimension, FlexDirection, FlexWrap, JustifyContent, Overflow, Position,
10};
11
12struct FlexItemMeta {
13    index: usize,
14    hypothetical_main: f32,
15    hypothetical_cross: f32,
16    resolved_main: f32,
17    resolved_cross: f32,
18    flex_grow: f32,
19    flex_shrink: f32,
20    align_self: AlignSelf,
21    margin_main_start: f32,
22    margin_main_end: f32,
23    margin_cross_start: f32,
24    margin_cross_end: f32,
25    auto_margin_main_start: bool,
26    auto_margin_main_end: bool,
27    auto_margin_cross_start: bool,
28    auto_margin_cross_end: bool,
29    baseline_offset: f32,
30}
31
32struct FlexLine {
33    items: Vec<FlexItemMeta>,
34    cross_size: f32,
35    max_baseline_ascent: f32,
36}
37
38/// Computes the first baseline offset from the top border box of a layout node iteratively (O(1) call stack).
39fn compute_first_baseline(node: &LayoutNode) -> f32 {
40    let mut cur = node;
41    let mut acc_y = 0.0f32;
42    loop {
43        if let Some(first_line) = cur.line_boxes.first() {
44            return acc_y
45                + (first_line.bounds.y - cur.geometry.border_box.y).max(0.0)
46                + first_line.baseline;
47        }
48        if cur.text.is_some() {
49            return acc_y
50                + cur.style.padding.top
51                + cur.style.border_width.top
52                + cur.style.font_size * 0.8;
53        }
54        let next = cur
55            .children
56            .iter()
57            .find(|c| c.style.position != Position::Absolute && c.style.position != Position::Fixed);
58        if let Some(child) = next {
59            acc_y += (child.geometry.border_box.y - cur.geometry.border_box.y).max(0.0);
60            cur = child;
61        } else {
62            return acc_y + cur.geometry.border_box.height;
63        }
64    }
65}
66
67/// Computes the line cross size and maximum baseline ascent for a flex line.
68fn compute_line_cross_and_baseline(
69    items: &[FlexItemMeta],
70    container_align_items: AlignItems,
71    is_row: bool,
72    use_resolved: bool,
73) -> (f32, f32) {
74    if items.is_empty() {
75        return (0.0, 0.0);
76    }
77    let mut max_non_baseline_cross = 0.0f32;
78    let mut max_baseline_ascent = 0.0f32;
79    let mut max_baseline_descent = 0.0f32;
80    let mut has_baseline = false;
81
82    for it in items {
83        let cross = if use_resolved {
84            it.resolved_cross
85        } else {
86            it.hypothetical_cross
87        };
88        let effective_align = match it.align_self {
89            AlignSelf::Auto => container_align_items,
90            AlignSelf::Stretch => AlignItems::Stretch,
91            AlignSelf::FlexStart => AlignItems::FlexStart,
92            AlignSelf::FlexEnd => AlignItems::FlexEnd,
93            AlignSelf::Center => AlignItems::Center,
94            AlignSelf::Baseline => AlignItems::Baseline,
95        };
96
97        let is_baseline = is_row
98            && effective_align == AlignItems::Baseline
99            && !it.auto_margin_cross_start
100            && !it.auto_margin_cross_end;
101
102        if is_baseline {
103            has_baseline = true;
104            let ascent = it.margin_cross_start + it.baseline_offset;
105            let descent = (cross - it.baseline_offset).max(0.0) + it.margin_cross_end;
106            if ascent > max_baseline_ascent {
107                max_baseline_ascent = ascent;
108            }
109            if descent > max_baseline_descent {
110                max_baseline_descent = descent;
111            }
112        } else {
113            let total_cross = cross + it.margin_cross_start + it.margin_cross_end;
114            if total_cross > max_non_baseline_cross {
115                max_non_baseline_cross = total_cross;
116            }
117        }
118    }
119
120    let cross_size = if has_baseline {
121        max_non_baseline_cross.max(max_baseline_ascent + max_baseline_descent)
122    } else {
123        max_non_baseline_cross
124    };
125
126    (cross_size, max_baseline_ascent)
127}
128
129/// Solves W3C Flexbox Level 1 layout for a flex container and its children.
130pub fn solve_flexbox(container: &mut LayoutNode, available_width: f32, available_height: f32) {
131    solve_flexbox_guarded(
132        container,
133        available_width,
134        available_height,
135        crate::tree::LayoutDepthGuard::root(),
136    );
137}
138
139/// Solves W3C Flexbox Level 1 layout with an active depth guard to prevent stack overflow.
140pub fn solve_flexbox_guarded(
141    container: &mut LayoutNode,
142    available_width: f32,
143    available_height: f32,
144    guard: crate::tree::LayoutDepthGuard,
145) {
146    solve_flexbox_with_definite_cross_guarded(
147        container,
148        available_width,
149        available_height,
150        None,
151        guard,
152    );
153}
154
155/// Solves flexbox layout with an explicitly definite inner cross size.
156///
157/// Absolutely positioned boxes can derive their final height from `top`/`bottom`
158/// insets after the normal flow pass. When that happens the flex algorithm must
159/// treat the resolved inner height as definite, otherwise a single flex line is
160/// only as tall as its items and `align-items: center` has no free space to
161/// distribute.
162pub fn solve_flexbox_with_definite_cross(
163    container: &mut LayoutNode,
164    available_width: f32,
165    available_height: f32,
166    definite_inner_cross: Option<f32>,
167) {
168    solve_flexbox_with_definite_cross_guarded(
169        container,
170        available_width,
171        available_height,
172        definite_inner_cross,
173        crate::tree::LayoutDepthGuard::root(),
174    );
175}
176
177/// Solves flexbox layout with definite inner cross size and an active depth guard.
178pub fn solve_flexbox_with_definite_cross_guarded(
179    container: &mut LayoutNode,
180    available_width: f32,
181    available_height: f32,
182    definite_inner_cross: Option<f32>,
183    guard: crate::tree::LayoutDepthGuard,
184) {
185    let _prof = crate::prof::Scope::new(crate::prof::Slot::Flex);
186    if guard.is_exhausted() {
187        crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
188        return;
189    }
190    let padding = container.style.padding;
191    let border = container.style.border_width;
192    let margin = container.style.margin;
193
194    let is_row = matches!(
195        container.style.flex_direction,
196        FlexDirection::Row | FlexDirection::RowReverse
197    );
198    let is_reverse = matches!(
199        container.style.flex_direction,
200        FlexDirection::RowReverse | FlexDirection::ColumnReverse
201    );
202
203    // 1. Resolve container dimensions
204    let resolved_width =
205        match resolve_dimension_with_node(container.style.width, available_width, container) {
206            Some(w) => clamp_dimension_with_node(
207                w,
208                container.style.min_width,
209                container.style.max_width,
210                available_width,
211                container,
212            ),
213            None => {
214                // Only inline-level flex containers shrink-to-fit. A block-level
215                // flex container with `width: auto` fills its containing block
216                // regardless of its own `flex-shrink`, which describes how the
217                // container behaves as an item of its parent, not how it sizes
218                // its content.
219                let is_inline_or_shrink = container.style.display
220                    == strata_style::types::Display::InlineFlex
221                    || container.style.display == strata_style::types::Display::Inline;
222                if is_inline_or_shrink {
223                    let mut sum_children = 0.0f32;
224                    for child in &mut container.children {
225                        if child.style.position == Position::Absolute
226                            || child.style.position == Position::Fixed
227                        {
228                            continue;
229                        }
230                        let cw =
231                            resolve_dimension_with_node(child.style.width, available_width, child)
232                                .unwrap_or_else(|| {
233                                    if child.geometry.border_box.width > 0.0 {
234                                        child.geometry.border_box.width
235                                    } else {
236                                        let min_max = crate::intrinsic::compute_min_max_sizes(
237                                            child,
238                                            Some(available_width),
239                                        );
240                                        min_max.max_content.min(available_width)
241                                    }
242                                });
243                        let mw = child.style.margin.left + child.style.margin.right;
244                        if is_row {
245                            sum_children += cw + mw;
246                        } else {
247                            sum_children = sum_children.max(cw + mw);
248                        }
249                    }
250                    let in_flow_count = container
251                        .children
252                        .iter()
253                        .filter(|c| {
254                            c.style.position != Position::Absolute
255                                && c.style.position != Position::Fixed
256                        })
257                        .count();
258                    let gap_val = if is_row {
259                        container.style.gap_col.max(container.style.gap)
260                    } else {
261                        container.style.gap_row.max(container.style.gap)
262                    };
263                    let gaps = if is_row && in_flow_count > 1 {
264                        (in_flow_count - 1) as f32 * gap_val
265                    } else {
266                        0.0
267                    };
268                    let fit_w = (sum_children
269                        + gaps
270                        + padding.left
271                        + padding.right
272                        + border.left
273                        + border.right)
274                        .min(available_width);
275                    clamp_dimension(
276                        fit_w,
277                        container.style.min_width,
278                        container.style.max_width,
279                        available_width,
280                    )
281                } else {
282                    let auto_w = (available_width - margin.left - margin.right).max(0.0);
283                    clamp_dimension(
284                        auto_w,
285                        container.style.min_width,
286                        container.style.max_width,
287                        available_width,
288                    )
289                }
290            }
291        };
292
293    let base_inner_w =
294        (resolved_width - padding.left - padding.right - border.left - border.right).max(0.0);
295    let inner_width = container
296        .transition_content_width()
297        .map_or(base_inner_w, |tw| base_inner_w.max(tw));
298    let resolved_height = resolve_dimension(container.style.height, available_height).map(|h| {
299        clamp_dimension(
300            h,
301            container.style.min_height,
302            container.style.max_height,
303            available_height,
304        )
305    });
306
307    let base_inner_h = match resolved_height {
308        Some(h) => Some((h - padding.top - padding.bottom - border.top - border.bottom).max(0.0)),
309        None => definite_inner_cross,
310    };
311    let inner_height = match (base_inner_h, container.transition_content_height()) {
312        (Some(h), Some(th)) => Some(h.max(th)),
313        (None, Some(th)) => Some(th),
314        (other, _) => other,
315    };
316
317    let main_gap = if is_row {
318        container.style.gap_col.max(container.style.gap)
319    } else {
320        container.style.gap_row.max(container.style.gap)
321    };
322    let cross_gap = if is_row {
323        container.style.gap_row.max(container.style.gap)
324    } else {
325        container.style.gap_col.max(container.style.gap)
326    };
327
328    let container_main = if is_row {
329        inner_width
330    } else {
331        inner_height.unwrap_or(0.0)
332    };
333
334    let target_avail_h = inner_height.unwrap_or(available_height);
335
336    // 2. Collect in-flow flex items and determine hypothetical sizes
337    let mut item_metas = Vec::new();
338    for (idx, child) in container.children.iter_mut().enumerate() {
339        if child.style.position == Position::Absolute || child.style.position == Position::Fixed {
340            continue;
341        }
342
343        let effective_align = match child.style.align_self {
344            AlignSelf::Auto => container.style.align_items,
345            AlignSelf::Stretch => AlignItems::Stretch,
346            AlignSelf::FlexStart => AlignItems::FlexStart,
347            AlignSelf::FlexEnd => AlignItems::FlexEnd,
348            AlignSelf::Center => AlignItems::Center,
349            AlignSelf::Baseline => AlignItems::Baseline,
350        };
351
352        let item_w_opt = resolve_dimension_with_node(child.style.width, inner_width, child)
353            .or_else(|| {
354                if is_row && child.style.flex_basis != Dimension::Auto {
355                    let basis =
356                        resolve_dimension_with_node(child.style.flex_basis, inner_width, child)?;
357                    if basis > 0.0 {
358                        Some(basis)
359                    } else {
360                        // When flex-basis is 0 (e.g. flex: 1), the item will receive distributed space.
361                        // For measuring its cross size, give it the available inner_width so text doesn't wrap to 0px.
362                        None
363                    }
364                } else if is_row || effective_align != AlignItems::Stretch {
365                    let min_max = crate::intrinsic::compute_min_max_sizes(child, Some(inner_width));
366                    let avail_child_w =
367                        (inner_width - child.style.margin.left - child.style.margin.right).max(0.0);
368                    Some(min_max.max_content.min(avail_child_w))
369                } else {
370                    None
371                }
372            });
373
374        // `text-overflow` is not inherited, but in flex layout the text is an
375        // anonymous item of the flex container. Apply the container's clipping
376        // and ellipsis mode to the text item so its glyph runs can be truncated
377        // even though the class/style lives on the container.
378        if child.text.is_some()
379            && container.style.text_overflow == strata_style::types::TextOverflow::Ellipsis
380            && container.style.overflow_x != Overflow::Visible
381        {
382            let mut mutated = false;
383            if child.style.text_overflow != strata_style::types::TextOverflow::Ellipsis {
384                child.style.text_overflow = strata_style::types::TextOverflow::Ellipsis;
385                mutated = true;
386            }
387            if child.style.overflow_x != Overflow::Hidden {
388                child.style.overflow_x = Overflow::Hidden;
389                mutated = true;
390            }
391            if child.style.overflow_y != Overflow::Hidden {
392                child.style.overflow_y = Overflow::Hidden;
393                mutated = true;
394            }
395            if container.style.white_space == strata_style::types::WhiteSpace::NoWrap
396                && child.style.white_space != strata_style::types::WhiteSpace::NoWrap
397            {
398                child.style.white_space = strata_style::types::WhiteSpace::NoWrap;
399                mutated = true;
400            }
401            if mutated {
402                child.invalidate_self_caches();
403            }
404        }
405
406        let cg = guard.enter().unwrap_or(guard);
407        let clamped_item_w = item_w_opt.map(|w| {
408            clamp_dimension_with_node(
409                w,
410                child.style.min_width,
411                child.style.max_width,
412                inner_width,
413                child,
414            )
415        });
416        let resolved_item_h = resolve_dimension(child.style.height, target_avail_h).map(|h| {
417            clamp_dimension(
418                h,
419                child.style.min_height,
420                child.style.max_height,
421                target_avail_h,
422            )
423        });
424        let (mut child_w, mut child_h, cached_baseline_opt) =
425            match (clamped_item_w, resolved_item_h) {
426                (Some(w), Some(h)) => {
427                    let saved_w = child.style.width;
428                    let saved_min_w = child.style.min_width;
429                    let saved_max_w = child.style.max_width;
430                    let saved_h = child.style.height;
431                    let saved_min_h = child.style.min_height;
432                    let saved_max_h = child.style.max_height;
433                    child.style.width = Dimension::Px(w);
434                    child.style.min_width = Dimension::Auto;
435                    child.style.max_width = Dimension::Auto;
436                    child.style.height = Dimension::Px(h);
437                    child.style.min_height = Dimension::Auto;
438                    child.style.max_height = Dimension::Auto;
439                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
440                    let res = if let Some((_, _, bl)) = child.lookup_measure_cache(w, h, pin_hash) {
441                        (w, h, Some(bl))
442                    } else {
443                        child.compute_layout_guarded(w, h, None, 0.0, cg);
444                        let bl = compute_first_baseline(child);
445                        child.store_measure_cache(0, w, h, pin_hash, w, h, bl);
446                        (w, h, Some(bl))
447                    };
448                    child.style.width = saved_w;
449                    child.style.min_width = saved_min_w;
450                    child.style.max_width = saved_max_w;
451                    child.style.height = saved_h;
452                    child.style.min_height = saved_min_h;
453                    child.style.max_height = saved_max_h;
454                    res
455                }
456                (Some(w), None) => {
457                    let saved_w = child.style.width;
458                    let saved_min_w = child.style.min_width;
459                    let saved_max_w = child.style.max_width;
460                    child.style.width = Dimension::Px(w);
461                    child.style.min_width = Dimension::Auto;
462                    child.style.max_width = Dimension::Auto;
463                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
464                    let res = if let Some((_, mh, bl)) =
465                        child.lookup_measure_cache(w, target_avail_h, pin_hash)
466                    {
467                        (w, mh, Some(bl))
468                    } else {
469                        child.compute_layout_guarded(w, target_avail_h, None, 0.0, cg);
470                        let mh = child.geometry.border_box.height;
471                        let bl = compute_first_baseline(child);
472                        child.store_measure_cache(0, w, target_avail_h, pin_hash, w, mh, bl);
473                        (w, mh, Some(bl))
474                    };
475                    child.style.width = saved_w;
476                    child.style.min_width = saved_min_w;
477                    child.style.max_width = saved_max_w;
478                    res
479                }
480                (None, Some(h)) => {
481                    let saved_h = child.style.height;
482                    let saved_min_h = child.style.min_height;
483                    let saved_max_h = child.style.max_height;
484                    child.style.height = Dimension::Px(h);
485                    child.style.min_height = Dimension::Auto;
486                    child.style.max_height = Dimension::Auto;
487                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
488                    let res = if let Some((mw, _, bl)) =
489                        child.lookup_measure_cache(inner_width, h, pin_hash)
490                    {
491                        (mw, h, Some(bl))
492                    } else {
493                        child.compute_layout_guarded(inner_width, h, None, 0.0, cg);
494                        let mw = child.geometry.border_box.width;
495                        let bl = compute_first_baseline(child);
496                        child.store_measure_cache(0, inner_width, h, pin_hash, mw, h, bl);
497                        (mw, h, Some(bl))
498                    };
499                    child.style.height = saved_h;
500                    child.style.min_height = saved_min_h;
501                    child.style.max_height = saved_max_h;
502                    res
503                }
504                (None, None) => {
505                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
506                    if let Some((mw, mh, bl)) =
507                        child.lookup_measure_cache(inner_width, target_avail_h, pin_hash)
508                    {
509                        (mw, mh, Some(bl))
510                    } else {
511                        child.compute_layout_guarded(inner_width, target_avail_h, None, 0.0, cg);
512                        let mw = child.geometry.border_box.width;
513                        let mh = child.geometry.border_box.height;
514                        let bl = compute_first_baseline(child);
515                        child.store_measure_cache(
516                            0,
517                            inner_width,
518                            target_avail_h,
519                            pin_hash,
520                            mw,
521                            mh,
522                            bl,
523                        );
524                        (mw, mh, Some(bl))
525                    }
526                }
527            };
528
529        if let Some(ref text_str) = child.text {
530            if inner_width > 0.0 && child_w > inner_width {
531                let (_, wrapped_h) = crate::text::measure_text_bounds_with_white_space(
532                    text_str,
533                    child.style.font_size,
534                    child.style.line_height,
535                    Some(inner_width),
536                    crate::text::is_monospace_family(child.style.font_family),
537                    child.style.white_space,
538                );
539                child_w = inner_width;
540                child_h = wrapped_h;
541                let new_w = Dimension::Px(child_w);
542                let new_h = Dimension::Px(child_h);
543                if child.style.width != new_w || child.style.height != new_h {
544                    child.style.width = new_w;
545                    child.style.height = new_h;
546                    child.invalidate_self_caches();
547                }
548            }
549        }
550
551        let (mut main_size, mut cross_size) = if is_row {
552            (child_w, child_h)
553        } else {
554            (child_h, child_w)
555        };
556
557        let has_content =
558            !child.children.is_empty() || child.text.is_some() || !child.inline_items.is_empty();
559
560        let auto_min_main = if !has_content {
561            0.0
562        } else if is_row {
563            crate::intrinsic::compute_min_max_sizes(child, Some(inner_width)).min_content
564        } else {
565            child_h
566        };
567
568        // If flex-basis is specified, use flex-basis for hypothetical main size.
569        // Per W3C Flexbox Level 1 §9.2: If container main size is indefinite (column with height: auto),
570        // percentage or 0 flex-basis falls back to content size.
571        let mut has_explicit_basis = false;
572        if child.style.flex_basis != Dimension::Auto && (is_row || inner_height.is_some()) {
573            if let Some(basis_px) =
574                resolve_dimension_with_node(child.style.flex_basis, container_main, child)
575            {
576                main_size = basis_px;
577                has_explicit_basis = true;
578            }
579        }
580
581        // Automatic minimum size per W3C Flexbox Section 4.5:
582        // For a flex item with min-size: auto (the initial value) and visible overflow,
583        // the minimum main size is clamped by its content size when flex-basis is auto.
584        let is_auto_min = if is_row {
585            child.style.min_width == Dimension::Auto && child.style.overflow_x == Overflow::Visible
586        } else {
587            child.style.min_height == Dimension::Auto && child.style.overflow_y == Overflow::Visible
588        };
589        if is_auto_min && !has_explicit_basis {
590            main_size = main_size.max(auto_min_main);
591        }
592
593        // Clamp main and cross sizes
594        if is_row {
595            main_size = clamp_dimension(
596                main_size,
597                child.style.min_width,
598                child.style.max_width,
599                inner_width,
600            );
601            cross_size = clamp_dimension(
602                cross_size,
603                child.style.min_height,
604                child.style.max_height,
605                inner_height.unwrap_or(available_height),
606            );
607        } else {
608            main_size = clamp_dimension(
609                main_size,
610                child.style.min_height,
611                child.style.max_height,
612                inner_height.unwrap_or(available_height),
613            );
614            cross_size = clamp_dimension(
615                cross_size,
616                child.style.min_width,
617                child.style.max_width,
618                inner_width,
619            );
620        }
621
622        let (m_main_start, m_main_end, m_cross_start, m_cross_end) = if is_row {
623            (
624                child.style.margin.left,
625                child.style.margin.right,
626                child.style.margin.top,
627                child.style.margin.bottom,
628            )
629        } else {
630            (
631                child.style.margin.top,
632                child.style.margin.bottom,
633                child.style.margin.left,
634                child.style.margin.right,
635            )
636        };
637
638        let (auto_m_main_start, auto_m_main_end, auto_m_cross_start, auto_m_cross_end) = if is_row {
639            (
640                child.style.margin_auto_left,
641                child.style.margin_auto_right,
642                child.style.margin_auto_top,
643                child.style.margin_auto_bottom,
644            )
645        } else {
646            (
647                child.style.margin_auto_top,
648                child.style.margin_auto_bottom,
649                child.style.margin_auto_left,
650                child.style.margin_auto_right,
651            )
652        };
653
654        let baseline_offset = cached_baseline_opt.unwrap_or_else(|| compute_first_baseline(child));
655
656        item_metas.push(FlexItemMeta {
657            index: idx,
658            hypothetical_main: main_size,
659            hypothetical_cross: cross_size,
660            resolved_main: main_size,
661            resolved_cross: cross_size,
662            flex_grow: child.style.flex_grow,
663            flex_shrink: child.style.flex_shrink,
664            align_self: child.style.align_self,
665            margin_main_start: m_main_start,
666            margin_main_end: m_main_end,
667            margin_cross_start: m_cross_start,
668            margin_cross_end: m_cross_end,
669            auto_margin_main_start: auto_m_main_start,
670            auto_margin_main_end: auto_m_main_end,
671            auto_margin_cross_start: auto_m_cross_start,
672            auto_margin_cross_end: auto_m_cross_end,
673            baseline_offset,
674        });
675    }
676
677    // 3. Break flex items into flex lines (wrapping)
678    let is_wrap = matches!(
679        container.style.flex_wrap,
680        FlexWrap::Wrap | FlexWrap::WrapReverse
681    );
682    let mut lines: Vec<FlexLine> = Vec::new();
683
684    if !item_metas.is_empty() {
685        if !is_wrap || container_main <= 0.0 {
686            // Single line (nowrap)
687            let (cross_size, max_baseline) = compute_line_cross_and_baseline(
688                &item_metas,
689                container.style.align_items,
690                is_row,
691                false,
692            );
693            let cross_size = if is_row {
694                if let Some(h) = inner_height {
695                    h
696                } else {
697                    cross_size
698                }
699            } else {
700                inner_width
701            };
702            lines.push(FlexLine {
703                items: item_metas,
704                cross_size,
705                max_baseline_ascent: max_baseline,
706            });
707        } else {
708            // Multi-line wrapping
709            let mut current_line_items = Vec::new();
710            let mut current_line_main = 0.0;
711
712            for it in item_metas {
713                let item_len = it.hypothetical_main + it.margin_main_start + it.margin_main_end;
714                let needed = if current_line_items.is_empty() {
715                    item_len
716                } else {
717                    current_line_main + main_gap + item_len
718                };
719
720                if !current_line_items.is_empty() && needed > container_main {
721                    let (cross, max_baseline) = compute_line_cross_and_baseline(
722                        &current_line_items,
723                        container.style.align_items,
724                        is_row,
725                        false,
726                    );
727                    lines.push(FlexLine {
728                        items: current_line_items,
729                        cross_size: cross,
730                        max_baseline_ascent: max_baseline,
731                    });
732                    current_line_items = vec![it];
733                    current_line_main = item_len;
734                } else {
735                    current_line_main = needed;
736                    current_line_items.push(it);
737                }
738            }
739
740            if !current_line_items.is_empty() {
741                let (cross, max_baseline) = compute_line_cross_and_baseline(
742                    &current_line_items,
743                    container.style.align_items,
744                    is_row,
745                    false,
746                );
747                lines.push(FlexLine {
748                    items: current_line_items,
749                    cross_size: cross,
750                    max_baseline_ascent: max_baseline,
751                });
752            }
753        }
754    }
755
756    // 4. Resolve flexible lengths on main axis for each line
757    let is_main_definite = if is_row { true } else { inner_height.is_some() };
758
759    for line in &mut lines {
760        let count = line.items.len();
761        if count == 0 {
762            continue;
763        }
764
765        let total_gaps = if count > 1 {
766            (count - 1) as f32 * main_gap
767        } else {
768            0.0
769        };
770        let sum_hypothetical: f32 = line
771            .items
772            .iter()
773            .map(|it| it.hypothetical_main + it.margin_main_start + it.margin_main_end)
774            .sum();
775
776        let min_container_main = if is_row {
777            resolve_dimension_with_node(container.style.min_width, available_width, container)
778        } else {
779            resolve_dimension_with_node(container.style.min_height, available_height, container)
780        };
781
782        let item_min_max = |ch: &LayoutNode, hyp_main: f32, is_scroll_main: bool| -> (f32, f32) {
783            let min_main = if is_row {
784                if is_scroll_main {
785                    let explicit_min = resolve_dimension(ch.style.min_width, inner_width).unwrap_or(0.0);
786                    hyp_main.max(explicit_min)
787                } else if ch.style.min_width == Dimension::Auto {
788                    let ch_has_content =
789                        !ch.children.is_empty() || ch.text.is_some() || !ch.inline_items.is_empty();
790                    let content_size = if ch.style.overflow_x == Overflow::Visible && ch_has_content
791                    {
792                        crate::intrinsic::compute_min_max_sizes(ch, Some(inner_width)).min_content
793                    } else {
794                        0.0
795                    };
796                    // W3C CSS Flexbox §4.5: automatic minimum size = min(specified_size, content_size)
797                    let specified_size = resolve_dimension_with_node(ch.style.width, inner_width, ch)
798                        .map(|w| match ch.style.box_sizing {
799                            strata_style::types::BoxSizing::BorderBox => w,
800                            strata_style::types::BoxSizing::ContentBox => {
801                                w + ch.style.padding.left
802                                    + ch.style.padding.right
803                                    + ch.style.border_width.left
804                                    + ch.style.border_width.right
805                            }
806                        })
807                        .unwrap_or(f32::INFINITY);
808                    let mut auto_min = content_size.min(specified_size);
809                    if let Some(max_w) =
810                        resolve_dimension_with_node(ch.style.max_width, inner_width, ch)
811                    {
812                        auto_min = auto_min.min(max_w);
813                    }
814                    auto_min
815                } else {
816                    resolve_dimension_with_node(ch.style.min_width, inner_width, ch).unwrap_or(0.0)
817                }
818            } else if is_scroll_main {
819                let explicit_min =
820                    resolve_dimension(ch.style.min_height, target_avail_h).unwrap_or(0.0);
821                hyp_main.max(explicit_min)
822            } else if ch.style.min_height == Dimension::Auto {
823                if ch.style.overflow_y == Overflow::Visible
824                    && (!ch.children.is_empty()
825                        || ch.text.is_some()
826                        || !ch.inline_items.is_empty())
827                {
828                    hyp_main
829                } else {
830                    0.0
831                }
832            } else {
833                resolve_dimension(ch.style.min_height, target_avail_h).unwrap_or(0.0)
834            };
835
836            let max_main = if is_row {
837                resolve_dimension_with_node(ch.style.max_width, inner_width, ch)
838                    .unwrap_or(f32::INFINITY)
839            } else {
840                resolve_dimension(ch.style.max_height, target_avail_h).unwrap_or(f32::INFINITY)
841            };
842
843            (min_main, max_main.max(min_main))
844        };
845
846        let distribute_grow =
847            |items: &mut [FlexItemMeta], target_main: f32, bounds: &[(f32, f32)]| {
848                let n = items.len();
849                let mut frozen: Vec<bool> = items.iter().map(|it| it.flex_grow <= 0.0).collect();
850                for _ in 0..=n {
851                    let used_frozen: f32 = items
852                        .iter()
853                        .zip(&frozen)
854                        .filter(|(_, &f)| f)
855                        .map(|(it, _)| it.resolved_main + it.margin_main_start + it.margin_main_end)
856                        .sum();
857                    let used_unfrozen: f32 = items
858                        .iter()
859                        .zip(&frozen)
860                        .filter(|(_, &f)| !f)
861                        .map(|(it, _)| {
862                            it.hypothetical_main + it.margin_main_start + it.margin_main_end
863                        })
864                        .sum();
865                    let rem_free = target_main - total_gaps - used_frozen - used_unfrozen;
866                    if rem_free <= 0.001 {
867                        break;
868                    }
869                    let total_grow: f32 = items
870                        .iter()
871                        .zip(&frozen)
872                        .filter(|(_, &f)| !f)
873                        .map(|(it, _)| it.flex_grow)
874                        .sum();
875                    if total_grow <= 0.0 {
876                        break;
877                    }
878                    if strata_primitives::target::is_tui_target() {
879                        let grow_shares: Vec<f32> = items
880                            .iter()
881                            .zip(&frozen)
882                            .map(|(it, &f)| if f { 0.0 } else { it.flex_grow })
883                            .collect();
884                        let free_cells = rem_free.round().max(0.0) as u16;
885                        let quants =
886                            strata_primitives::quantization::largest_remainder_quantization(
887                                &grow_shares,
888                                free_cells,
889                            );
890                        for (it, &q) in items.iter_mut().zip(&quants) {
891                            if it.flex_grow > 0.0 {
892                                it.resolved_main = it.hypothetical_main.round() + q as f32;
893                            }
894                        }
895                        break;
896                    }
897                    let mut hit_max = false;
898                    for i in 0..n {
899                        if frozen[i] {
900                            continue;
901                        }
902                        let delta = (items[i].flex_grow / total_grow) * rem_free;
903                        let cand = items[i].hypothetical_main + delta;
904                        let max_m = bounds[i].1;
905                        if cand > max_m + 0.001 && items[i].hypothetical_main <= max_m + 0.001 {
906                            items[i].resolved_main = max_m;
907                            frozen[i] = true;
908                            hit_max = true;
909                        }
910                    }
911                    if !hit_max {
912                        for i in 0..n {
913                            if !frozen[i] {
914                                let delta = (items[i].flex_grow / total_grow) * rem_free;
915                                items[i].resolved_main = items[i].hypothetical_main + delta;
916                            }
917                        }
918                        break;
919                    }
920                }
921            };
922
923        let is_scroll_main = if is_row {
924            matches!(
925                container.style.overflow_x,
926                Overflow::Auto | Overflow::Scroll
927            )
928        } else {
929            matches!(
930                container.style.overflow_y,
931                Overflow::Auto | Overflow::Scroll
932            )
933        };
934        let bounds: Vec<(f32, f32)> = line
935            .items
936            .iter()
937            .map(|it| {
938                item_min_max(
939                    &container.children[it.index],
940                    it.hypothetical_main,
941                    is_scroll_main,
942                )
943            })
944            .collect();
945
946        if is_main_definite {
947            let free_space = container_main - sum_hypothetical - total_gaps;
948
949            if free_space > 0.0 {
950                distribute_grow(&mut line.items, container_main, &bounds);
951            } else if free_space < 0.0 {
952                // W3C CSS Flexbox §9.7 iterative contraction via flex-shrink
953                let n = line.items.len();
954                let mut frozen: Vec<bool> = line
955                    .items
956                    .iter()
957                    .map(|it| it.flex_shrink <= 0.0 || it.hypothetical_main <= 0.0)
958                    .collect();
959
960                for _ in 0..=n {
961                    let used_frozen: f32 = line
962                        .items
963                        .iter()
964                        .zip(&frozen)
965                        .filter(|(_, &f)| f)
966                        .map(|(it, _)| it.resolved_main + it.margin_main_start + it.margin_main_end)
967                        .sum();
968                    let used_unfrozen: f32 = line
969                        .items
970                        .iter()
971                        .zip(&frozen)
972                        .filter(|(_, &f)| !f)
973                        .map(|(it, _)| {
974                            it.hypothetical_main + it.margin_main_start + it.margin_main_end
975                        })
976                        .sum();
977                    let rem_free = container_main - total_gaps - used_frozen - used_unfrozen;
978                    if rem_free >= -0.001 {
979                        break;
980                    }
981                    let total_scaled_shrink: f32 = line
982                        .items
983                        .iter()
984                        .zip(&frozen)
985                        .filter(|(_, &f)| !f)
986                        .map(|(it, _)| it.flex_shrink * it.hypothetical_main)
987                        .sum();
988                    if total_scaled_shrink <= 0.0 {
989                        break;
990                    }
991                    let abs_free = -rem_free;
992                    let mut clamped_any = false;
993                    for i in 0..n {
994                        if frozen[i] {
995                            continue;
996                        }
997                        let scaled = line.items[i].flex_shrink * line.items[i].hypothetical_main;
998                        let reduction = (scaled / total_scaled_shrink) * abs_free;
999                        let cand = line.items[i].hypothetical_main - reduction;
1000                        let min_main = bounds[i].0;
1001                        if cand < min_main - 0.001 {
1002                            line.items[i].resolved_main = min_main;
1003                            frozen[i] = true;
1004                            clamped_any = true;
1005                        }
1006                    }
1007                    if !clamped_any {
1008                        for i in 0..n {
1009                            if !frozen[i] {
1010                                let scaled =
1011                                    line.items[i].flex_shrink * line.items[i].hypothetical_main;
1012                                let reduction = (scaled / total_scaled_shrink) * abs_free;
1013                                line.items[i].resolved_main =
1014                                    (line.items[i].hypothetical_main - reduction).max(bounds[i].0);
1015                            }
1016                        }
1017                        break;
1018                    }
1019                }
1020            }
1021        } else if let Some(min_main) = min_container_main {
1022            let free_space = min_main - sum_hypothetical - total_gaps;
1023            if free_space > 0.0 {
1024                distribute_grow(&mut line.items, min_main, &bounds);
1025            }
1026        }
1027
1028        // Apply the item's resolved min/max constraints to the final flexed
1029        // size, not only to the hypothetical size. A `flex: 1` item with
1030        // `max-width` (for example `flex-1 max-w-md`) must stop growing at the
1031        // max size; the leftover free space stays available for alignment.
1032        for it in &mut line.items {
1033            let child = &container.children[it.index];
1034            if is_row {
1035                it.resolved_main = clamp_dimension(
1036                    it.resolved_main,
1037                    child.style.min_width,
1038                    child.style.max_width,
1039                    inner_width,
1040                );
1041                it.resolved_cross = clamp_dimension(
1042                    it.resolved_cross,
1043                    child.style.min_height,
1044                    child.style.max_height,
1045                    inner_height.unwrap_or(available_height),
1046                );
1047            } else {
1048                it.resolved_main = clamp_dimension(
1049                    it.resolved_main,
1050                    child.style.min_height,
1051                    child.style.max_height,
1052                    inner_height.unwrap_or(available_height),
1053                );
1054                it.resolved_cross = clamp_dimension(
1055                    it.resolved_cross,
1056                    child.style.min_width,
1057                    child.style.max_width,
1058                    inner_width,
1059                );
1060            }
1061        }
1062
1063        // Recompute line cross size after main sizing (CSS Flexbox Level 1 §9.4)
1064        let cg = guard.enter().unwrap_or(guard);
1065        for it in &mut line.items {
1066            let prev_main = if is_row {
1067                container.children[it.index].geometry.border_box.width
1068            } else {
1069                container.children[it.index].geometry.border_box.height
1070            };
1071            if (it.resolved_main - it.hypothetical_main).abs() > 0.5
1072                || (is_row && (it.resolved_main - prev_main).abs() > 0.5)
1073            {
1074                let child = &mut container.children[it.index];
1075                if is_row {
1076                    let saved_w = child.style.width;
1077                    let saved_min_w = child.style.min_width;
1078                    let saved_max_w = child.style.max_width;
1079                    let saved_h = child.style.height;
1080                    child.style.width = Dimension::Px(it.resolved_main);
1081                    child.style.min_width = Dimension::Auto;
1082                    child.style.max_width = Dimension::Auto;
1083                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
1084                    let (mut res_h, bl) = if let Some((_, mh, cached_bl)) =
1085                        child.lookup_measure_cache(it.resolved_main, target_avail_h, pin_hash)
1086                    {
1087                        (mh, cached_bl)
1088                    } else {
1089                        child.compute_layout_guarded(
1090                            it.resolved_main,
1091                            target_avail_h,
1092                            None,
1093                            0.0,
1094                            cg,
1095                        );
1096                        let mh = child.geometry.border_box.height;
1097                        let computed_bl = compute_first_baseline(child);
1098                        child.store_measure_cache(
1099                            1,
1100                            it.resolved_main,
1101                            target_avail_h,
1102                            pin_hash,
1103                            it.resolved_main,
1104                            mh,
1105                            computed_bl,
1106                        );
1107                        (mh, computed_bl)
1108                    };
1109                    if res_h <= 0.0 && child.children.is_empty() {
1110                        if let Some(ref text_str) = child.text {
1111                            let content_w = (it.resolved_main
1112                                - child.style.padding.left
1113                                - child.style.padding.right
1114                                - child.style.border_width.left
1115                                - child.style.border_width.right)
1116                                .max(0.0);
1117                            let (_, text_h) = crate::text::measure_text_bounds_with_white_space(
1118                                text_str,
1119                                child.style.font_size,
1120                                child.style.line_height,
1121                                if content_w > 0.0 {
1122                                    Some(content_w)
1123                                } else {
1124                                    None
1125                                },
1126                                crate::text::is_monospace_family(child.style.font_family),
1127                                child.style.white_space,
1128                            );
1129                            res_h = text_h
1130                                + child.style.padding.top
1131                                + child.style.padding.bottom
1132                                + child.style.border_width.top
1133                                + child.style.border_width.bottom;
1134                        }
1135                    }
1136                    child.style.width = saved_w;
1137                    child.style.min_width = saved_min_w;
1138                    child.style.max_width = saved_max_w;
1139                    child.style.height = saved_h;
1140                    it.resolved_cross = res_h;
1141                    it.baseline_offset = bl;
1142                } else {
1143                    let saved_h = child.style.height;
1144                    let saved_min_h = child.style.min_height;
1145                    let saved_max_h = child.style.max_height;
1146                    child.style.height = Dimension::Px(it.resolved_main);
1147                    child.style.min_height = Dimension::Auto;
1148                    child.style.max_height = Dimension::Auto;
1149                    let pin_hash = crate::tree::layout_style_pin_hash(&child.style);
1150                    let (res_w, bl) = if let Some((mw, _, cached_bl)) =
1151                        child.lookup_measure_cache(inner_width, it.resolved_main, pin_hash)
1152                    {
1153                        (mw, cached_bl)
1154                    } else {
1155                        child.compute_layout_guarded(inner_width, it.resolved_main, None, 0.0, cg);
1156                        let mw = child.geometry.border_box.width;
1157                        let computed_bl = compute_first_baseline(child);
1158                        child.store_measure_cache(
1159                            1,
1160                            inner_width,
1161                            it.resolved_main,
1162                            pin_hash,
1163                            mw,
1164                            it.resolved_main,
1165                            computed_bl,
1166                        );
1167                        (mw, computed_bl)
1168                    };
1169                    child.style.height = saved_h;
1170                    child.style.min_height = saved_min_h;
1171                    child.style.max_height = saved_max_h;
1172                    it.resolved_cross = res_w;
1173                    it.baseline_offset = bl;
1174                }
1175            }
1176        }
1177        let (recomputed_cross, max_baseline) =
1178            compute_line_cross_and_baseline(&line.items, container.style.align_items, is_row, true);
1179        line.max_baseline_ascent = max_baseline;
1180        line.cross_size = if is_row && inner_height.is_none() {
1181            recomputed_cross
1182        } else {
1183            line.cross_size.max(recomputed_cross)
1184        };
1185    }
1186
1187    if lines.len() == 1 {
1188        if is_row {
1189            if let Some(h) = inner_height {
1190                lines[0].cross_size = lines[0].cross_size.max(h);
1191            }
1192        } else {
1193            lines[0].cross_size = lines[0].cross_size.max(inner_width);
1194        }
1195    }
1196
1197    // 5. Total container height if Auto
1198    let total_lines_cross: f32 = lines.iter().map(|l| l.cross_size).sum();
1199    let total_cross_gaps = if lines.len() > 1 {
1200        (lines.len() - 1) as f32 * cross_gap
1201    } else {
1202        0.0
1203    };
1204    let content_cross_size = total_lines_cross + total_cross_gaps;
1205
1206    let raw_height = match resolved_height {
1207        Some(h) => h,
1208        None => {
1209            if is_row {
1210                content_cross_size + padding.top + padding.bottom + border.top + border.bottom
1211            } else {
1212                let sum_main: f32 = lines
1213                    .iter()
1214                    .flat_map(|l| {
1215                        l.items
1216                            .iter()
1217                            .map(|i| i.resolved_main + i.margin_main_start + i.margin_main_end)
1218                    })
1219                    .sum();
1220                let gaps = if lines.iter().flat_map(|l| &l.items).count() > 1 {
1221                    (lines.iter().flat_map(|l| &l.items).count() - 1) as f32 * main_gap
1222                } else {
1223                    0.0
1224                };
1225                sum_main + gaps + padding.top + padding.bottom + border.top + border.bottom
1226            }
1227        }
1228    };
1229    let final_height = clamp_dimension(
1230        raw_height,
1231        container.style.min_height,
1232        container.style.max_height,
1233        available_height,
1234    );
1235
1236    let border_box = Rect::new(
1237        container.geometry.border_box.x,
1238        container.geometry.border_box.y,
1239        resolved_width,
1240        final_height,
1241    );
1242    container.geometry = LayoutGeometry::from_border_box(border_box, padding, border, margin);
1243
1244    // 6. Positioning flex items across lines
1245    let mut current_line_cross = if is_row {
1246        container.geometry.content_box.y
1247    } else {
1248        container.geometry.content_box.x
1249    };
1250
1251    for line in lines {
1252        let count = line.items.len();
1253        if count == 0 {
1254            continue;
1255        }
1256
1257        let mut line_items = line.items;
1258        let total_item_main: f32 = line_items
1259            .iter()
1260            .map(|it| it.resolved_main + it.margin_main_start + it.margin_main_end)
1261            .sum();
1262        let total_gaps = if count > 1 {
1263            (count - 1) as f32 * main_gap
1264        } else {
1265            0.0
1266        };
1267        let remaining_main = if is_main_definite {
1268            (container_main - total_item_main - total_gaps).max(0.0)
1269        } else {
1270            0.0
1271        };
1272
1273        // Section 8.1: Distribute remaining positive free space to auto margins on main axis
1274        let num_auto_main: usize = line_items
1275            .iter()
1276            .map(|it| (it.auto_margin_main_start as usize) + (it.auto_margin_main_end as usize))
1277            .sum();
1278
1279        let (effective_remaining_main, auto_margin_px) =
1280            if num_auto_main > 0 && remaining_main > 0.0 {
1281                (0.0, remaining_main / num_auto_main as f32)
1282            } else {
1283                (remaining_main, 0.0)
1284            };
1285
1286        if num_auto_main > 0 {
1287            for it in &mut line_items {
1288                if it.auto_margin_main_start {
1289                    it.margin_main_start = auto_margin_px;
1290                }
1291                if it.auto_margin_main_end {
1292                    it.margin_main_end = auto_margin_px;
1293                }
1294            }
1295        }
1296
1297        // Main axis alignment distribution
1298        let (start_offset, step_between) = match container.style.justify_content {
1299            JustifyContent::FlexStart => (0.0, main_gap),
1300            JustifyContent::FlexEnd => (effective_remaining_main, main_gap),
1301            JustifyContent::Center => (effective_remaining_main / 2.0, main_gap),
1302            JustifyContent::SpaceBetween => {
1303                if count > 1 {
1304                    (
1305                        0.0,
1306                        main_gap + (effective_remaining_main / (count - 1) as f32),
1307                    )
1308                } else {
1309                    (0.0, main_gap)
1310                }
1311            }
1312            JustifyContent::SpaceAround => {
1313                let item_space = effective_remaining_main / count as f32;
1314                (item_space / 2.0, main_gap + item_space)
1315            }
1316            JustifyContent::SpaceEvenly => {
1317                let item_space = effective_remaining_main / (count + 1) as f32;
1318                (item_space, main_gap + item_space)
1319            }
1320        };
1321
1322        let mut current_main = if is_row {
1323            container.geometry.content_box.x + start_offset
1324        } else {
1325            container.geometry.content_box.y + start_offset
1326        };
1327
1328        let mut ordered_items = line_items;
1329        if is_reverse {
1330            ordered_items.reverse();
1331        }
1332
1333        for mut it in ordered_items {
1334            let child = &mut container.children[it.index];
1335
1336            // Cross-axis auto margins and alignment per Section 8.1 and Section 9.5
1337            let has_cross_auto = it.auto_margin_cross_start || it.auto_margin_cross_end;
1338            let (cross_offset, final_cross_size, actual_m_cross_start) = if has_cross_auto {
1339                let remaining_cross = (line.cross_size
1340                    - it.resolved_cross
1341                    - (if it.auto_margin_cross_start {
1342                        0.0
1343                    } else {
1344                        it.margin_cross_start
1345                    })
1346                    - (if it.auto_margin_cross_end {
1347                        0.0
1348                    } else {
1349                        it.margin_cross_end
1350                    }))
1351                .max(0.0);
1352                let (m_start, m_end) = if it.auto_margin_cross_start && it.auto_margin_cross_end {
1353                    (remaining_cross / 2.0, remaining_cross / 2.0)
1354                } else if it.auto_margin_cross_start {
1355                    (remaining_cross, it.margin_cross_end)
1356                } else {
1357                    (it.margin_cross_start, remaining_cross)
1358                };
1359                it.margin_cross_start = m_start;
1360                it.margin_cross_end = m_end;
1361                (0.0, it.resolved_cross, m_start)
1362            } else {
1363                let effective_align = match it.align_self {
1364                    AlignSelf::Auto => container.style.align_items,
1365                    AlignSelf::Stretch => AlignItems::Stretch,
1366                    AlignSelf::FlexStart => AlignItems::FlexStart,
1367                    AlignSelf::FlexEnd => AlignItems::FlexEnd,
1368                    AlignSelf::Center => AlignItems::Center,
1369                    AlignSelf::Baseline => AlignItems::Baseline,
1370                };
1371
1372                let mut size = it.resolved_cross;
1373                let offset = match effective_align {
1374                    AlignItems::FlexStart => 0.0,
1375                    AlignItems::FlexEnd => {
1376                        line.cross_size - (size + it.margin_cross_start + it.margin_cross_end)
1377                    }
1378                    AlignItems::Center => {
1379                        (line.cross_size - (size + it.margin_cross_start + it.margin_cross_end))
1380                            / 2.0
1381                    }
1382                    AlignItems::Stretch => {
1383                        let has_auto_cross = if is_row {
1384                            child.style.height == Dimension::Auto
1385                                || matches!(child.style.height, Dimension::Percent(_))
1386                        } else {
1387                            child.style.width == Dimension::Auto
1388                                || matches!(child.style.width, Dimension::Percent(_))
1389                        };
1390                        if has_auto_cross {
1391                            let stretched =
1392                                (line.cross_size - it.margin_cross_start - it.margin_cross_end)
1393                                    .max(0.0);
1394                            size = if is_row {
1395                                clamp_dimension(
1396                                    stretched,
1397                                    child.style.min_height,
1398                                    child.style.max_height,
1399                                    inner_height.unwrap_or(available_height),
1400                                )
1401                            } else {
1402                                clamp_dimension(
1403                                    stretched,
1404                                    child.style.min_width,
1405                                    child.style.max_width,
1406                                    inner_width,
1407                                )
1408                            };
1409                        }
1410                        0.0
1411                    }
1412                    AlignItems::Baseline => {
1413                        if is_row && line.max_baseline_ascent > 0.0 {
1414                            (line.max_baseline_ascent
1415                                - (it.margin_cross_start + it.baseline_offset))
1416                                .max(0.0)
1417                        } else {
1418                            0.0
1419                        }
1420                    }
1421                };
1422                (offset, size, it.margin_cross_start)
1423            };
1424
1425            let (item_x, item_y, item_w, item_h) = if is_row {
1426                (
1427                    current_main + it.margin_main_start,
1428                    current_line_cross + actual_m_cross_start + cross_offset,
1429                    it.resolved_main,
1430                    final_cross_size,
1431                )
1432            } else {
1433                (
1434                    current_line_cross + actual_m_cross_start + cross_offset,
1435                    current_main + it.margin_main_start,
1436                    final_cross_size,
1437                    it.resolved_main,
1438                )
1439            };
1440
1441            let mut child_margin = child.style.margin;
1442            if is_row {
1443                child_margin.left = it.margin_main_start;
1444                child_margin.right = it.margin_main_end;
1445                child_margin.top = it.margin_cross_start;
1446                child_margin.bottom = it.margin_cross_end;
1447            } else {
1448                child_margin.top = it.margin_main_start;
1449                child_margin.bottom = it.margin_main_end;
1450                child_margin.left = it.margin_cross_start;
1451                child_margin.right = it.margin_cross_end;
1452            }
1453
1454            let old_x = child.geometry.border_box.x;
1455            let old_y = child.geometry.border_box.y;
1456            let old_w = child.geometry.border_box.width;
1457            let old_h = child.geometry.border_box.height;
1458
1459            let desired_content_w = (item_w
1460                - child.style.padding.left
1461                - child.style.padding.right
1462                - child.style.border_width.left
1463                - child.style.border_width.right)
1464                .max(0.0);
1465            let desired_content_h = (item_h
1466                - child.style.padding.top
1467                - child.style.padding.bottom
1468                - child.style.border_width.top
1469                - child.style.border_width.bottom)
1470                .max(0.0);
1471            // A previous pass may have formatted the descendants for a
1472            // different content size while the border box already matches the
1473            // final placement size. Trusting the border box alone would leave
1474            // children laid out at their max-content width after a cross-axis
1475            // stretch. Re-run child layout whenever the content size changed,
1476            // regardless of `flex-shrink`.
1477            let children_current = child.children_layout_clean
1478                && child.last_child_layout_content.map_or(
1479                    child.children.is_empty()
1480                        && child.inline_items.is_empty()
1481                        && child.text.is_none(),
1482                    |(w, h)| {
1483                        (w - desired_content_w).abs() < 0.05 && (h - desired_content_h).abs() < 0.05
1484                    },
1485                );
1486
1487            if children_current
1488                && old_w > 0.0
1489                && (item_w - old_w).abs() < 0.05
1490                && (item_h - old_h).abs() < 0.05
1491            {
1492                let saved_scroll_bounds = child.geometry.scroll_bounds;
1493                let saved_has_scroll = child.geometry.has_scroll;
1494                let saved_scroll_offset = child.geometry.scroll_offset;
1495                let mut new_geom = LayoutGeometry::from_border_box(
1496                    Rect::new(item_x, item_y, item_w, item_h),
1497                    child.style.padding,
1498                    child.style.border_width,
1499                    child_margin,
1500                );
1501                new_geom.snap_to_pixel();
1502                let dx = new_geom.border_box.x - old_x;
1503                let dy = new_geom.border_box.y - old_y;
1504                if dx.abs() > 0.001 || dy.abs() > 0.001 {
1505                    child.translate(dx, dy);
1506                }
1507                child.geometry = new_geom;
1508                child.applied_relative_offset = (0.0, 0.0);
1509                child.geometry.scroll_bounds = saved_scroll_bounds;
1510                child.geometry.has_scroll = saved_has_scroll;
1511                child.geometry.scroll_offset = saved_scroll_offset;
1512                child.last_child_layout_content = Some((desired_content_w, desired_content_h));
1513            } else {
1514                child.geometry = LayoutGeometry::from_border_box(
1515                    Rect::new(item_x, item_y, item_w, item_h),
1516                    child.style.padding,
1517                    child.style.border_width,
1518                    child_margin,
1519                );
1520                child.applied_relative_offset = (0.0, 0.0);
1521                child.geometry.snap_to_pixel();
1522                if !child.children.is_empty() {
1523                    if let Some(cg) = guard.enter() {
1524                        child.layout_children_guarded(cg);
1525                    }
1526                } else if !child.inline_items.is_empty() || child.text.is_some() {
1527                    let content_w = child.geometry.content_box.width;
1528                    let content_h = child.geometry.content_box.height;
1529                    if let Some(cg) = guard.enter() {
1530                        crate::box_model::solve_block_children_with_exclusions_guarded(
1531                            child, content_w, content_h, None, 0.0, cg,
1532                        );
1533                    }
1534                    child.subtree_hit_flags &= !crate::tree::SUBTREE_META_VALID;
1535                    child.update_scroll_metrics();
1536                    child.last_child_layout_content = Some((content_w, content_h));
1537                    child.children_layout_clean = true;
1538                } else {
1539                    child.subtree_hit_flags &= !crate::tree::SUBTREE_META_VALID;
1540                    child.update_scroll_metrics();
1541                    child.last_child_layout_content = Some((desired_content_w, desired_content_h));
1542                    child.children_layout_clean = true;
1543                }
1544            }
1545
1546            current_main +=
1547                it.margin_main_start + it.resolved_main + it.margin_main_end + step_between;
1548        }
1549
1550        current_line_cross += line.cross_size + cross_gap;
1551    }
1552
1553    container.geometry.snap_to_pixel();
1554}