tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 231Rust 8TOML 3CSS 1317 Definitions

⎇ main src/compute/flexbox.rs Rust · 2594 lines · 121.2 KB History Who touched what raw

Flexbox: apply transferred min/max sizes to flex base size and hypothetical sizes (#989) 0972b84ee · Nico Burns ·

1//! Computes the [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) layout algorithm on [`TaffyTree`](crate::TaffyTree) according to the [spec](https://www.w3.org/TR/css-flexbox-1/)
2use crate::compute::common::alignment::{compute_alignment_offset, resolve_self_alignment_safety};
3use crate::geometry::{Line, Point, Rect, Size};
4use crate::style::{
5    AlignContent, AlignContentKeyword, AlignItems, AlignItemsKeyword, AlignSelf, AvailableSpace, FlexWrap,
6    JustifyContent, LengthPercentageAuto, Overflow, Position,
7};
8use crate::style::{CoreStyle, FlexDirection, FlexboxContainerStyle, FlexboxItemStyle};
9use crate::style_helpers::{TaffyMaxContent, TaffyMinContent};
10use crate::tree::{Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
11use crate::tree::{LayoutFlexboxContainer, LayoutPartialTreeExt, NodeId};
12use crate::util::debug::debug_log;
13use crate::util::sys::{f32_max, new_vec_with_capacity, Vec};
14use crate::util::MaybeMath;
15use crate::util::{MaybeResolve, ResolveOrZero};
16use crate::{BoxGenerationMode, BoxSizing, Direction, RequestedAxis};
17
18use super::common::alignment::apply_alignment_fallback;
19#[cfg(feature = "content_size")]
20use super::common::content_size::compute_content_size_contribution;
21
22/// The intermediate results of a flexbox calculation for a single item
23struct FlexItem {
24    /// The identifier for the associated node
25    node: NodeId,
26
27    /// The order of the node relative to it's siblings
28    order: u32,
29
30    /// The base size of this item
31    size: Size<Option<f32>>,
32    /// The minimum allowable size of this item
33    min_size: Size<Option<f32>>,
34    /// The maximum allowable size of this item
35    max_size: Size<Option<f32>>,
36    /// The aspect ratio of this item
37    aspect_ratio: Option<f32>,
38    /// The cross-alignment of this item
39    align_self: AlignSelf,
40
41    /// The overflow style of the item
42    overflow: Point<Overflow>,
43    /// The width of the scrollbars (if it has any)
44    scrollbar_width: f32,
45    /// The flex shrink style of the item
46    flex_shrink: f32,
47    /// The flex grow style of the item
48    flex_grow: f32,
49
50    /// The minimum size of the item. This differs from min_size above because it also
51    /// takes into account content based automatic minimum sizes
52    resolved_minimum_main_size: f32,
53
54    /// The final offset of this item
55    inset: Rect<Option<f32>>,
56    /// The margin of this item
57    margin: Rect<f32>,
58    /// Whether each margin is an auto margin or not
59    margin_is_auto: Rect<bool>,
60    /// The padding of this item
61    padding: Rect<f32>,
62    /// The border of this item
63    border: Rect<f32>,
64
65    /// The default size of this item
66    flex_basis: f32,
67    /// The default size of this item, minus padding and border
68    inner_flex_basis: f32,
69    /// The amount by which this item has deviated from its target size
70    violation: f32,
71    /// Is the size of this item locked
72    frozen: bool,
73
74    /// Either the max- or min- content flex fraction
75    /// See https://www.w3.org/TR/css-flexbox-1/#intrinsic-main-sizes
76    content_flex_fraction: f32,
77
78    /// The proposed inner size of this item
79    hypothetical_inner_size: Size<f32>,
80    /// The proposed outer size of this item
81    hypothetical_outer_size: Size<f32>,
82    /// The size that this item wants to be
83    target_size: Size<f32>,
84    /// The size that this item wants to be, plus any padding and border
85    outer_target_size: Size<f32>,
86
87    /// The position of the bottom edge of this item
88    baseline: f32,
89
90    /// A temporary value for the main offset
91    ///
92    /// Offset is the relative position from the item's natural flow position based on
93    /// relative position values, alignment, and justification. Does not include margin/padding/border.
94    offset_main: f32,
95    /// A temporary value for the cross offset
96    ///
97    /// Offset is the relative position from the item's natural flow position based on
98    /// relative position values, alignment, and justification. Does not include margin/padding/border.
99    offset_cross: f32,
100}
101
102impl FlexItem {
103    /// Returns true if the item is a <https://www.w3.org/TR/css-overflow-3/#scroll-container>
104    fn is_scroll_container(&self) -> bool {
105        self.overflow.x.is_scroll_container() | self.overflow.y.is_scroll_container()
106    }
107}
108
109/// A line of [`FlexItem`] used for intermediate computation
110struct FlexLine<'a> {
111    /// The slice of items to iterate over during computation of this line
112    items: &'a mut [FlexItem],
113    /// The dimensions of the cross-axis
114    cross_size: f32,
115    /// The relative offset of the cross-axis
116    offset_cross: f32,
117}
118
119/// Values that can be cached during the flexbox algorithm
120struct AlgoConstants {
121    /// The direction of the current segment being laid out
122    dir: FlexDirection,
123    /// The layout direction of the current segment being laid out
124    layout_direction: Direction,
125    /// Is this segment a row
126    is_row: bool,
127    /// Is this segment a column
128    is_column: bool,
129    /// Is wrapping enabled (in either direction)
130    is_wrap: bool,
131    /// Is the wrap direction inverted
132    is_wrap_reverse: bool,
133
134    /// The item's min_size style
135    min_size: Size<Option<f32>>,
136    /// The item's max_size style
137    max_size: Size<Option<f32>>,
138    /// The margin of this section
139    margin: Rect<f32>,
140    /// The border of this section
141    border: Rect<f32>,
142    /// The space between the content box and the border box.
143    /// This consists of padding + border + scrollbar_gutter.
144    content_box_inset: Rect<f32>,
145    /// The size reserved for scrollbar gutters in each axis
146    scrollbar_gutter: Point<f32>,
147    /// The gap of this section
148    gap: Size<f32>,
149    /// The align_items property of this node
150    align_items: AlignItems,
151    /// The align_content property of this node
152    align_content: AlignContent,
153    /// The justify_content property of this node
154    justify_content: Option<JustifyContent>,
155
156    /// The border-box size of the node being laid out (if known)
157    node_outer_size: Size<Option<f32>>,
158    /// The content-box size of the node being laid out (if known)
159    node_inner_size: Size<Option<f32>>,
160
161    /// The size of the virtual container containing the flex items.
162    container_size: Size<f32>,
163    /// The size of the internal container
164    inner_container_size: Size<f32>,
165}
166
167/// Computes the layout of a box according to the flexbox algorithm
168pub fn compute_flexbox_layout(
169    tree: &mut impl LayoutFlexboxContainer,
170    node: NodeId,
171    inputs: LayoutInput,
172) -> LayoutOutput {
173    let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
174    let style = tree.get_flexbox_container_style(node);
175
176    // Pull these out earlier to avoid borrowing issues
177    let aspect_ratio = style.aspect_ratio();
178    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
179    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
180    let padding_border_sum = padding.sum_axes() + border.sum_axes();
181    let box_sizing_adjustment =
182        if style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
183
184    let min_size = style
185        .min_size()
186        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
187        .maybe_apply_aspect_ratio(aspect_ratio)
188        .maybe_add(box_sizing_adjustment);
189    let max_size = style
190        .max_size()
191        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
192        .maybe_apply_aspect_ratio(aspect_ratio)
193        .maybe_add(box_sizing_adjustment);
194    let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
195        style
196            .size()
197            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
198            .maybe_apply_aspect_ratio(aspect_ratio)
199            .maybe_add(box_sizing_adjustment)
200            .maybe_clamp(min_size, max_size)
201    } else {
202        Size::NONE
203    };
204
205    // If both min and max in a given axis are set and max <= min then this determines the size in that axis
206    let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
207        (Some(min), Some(max)) if max <= min => Some(min),
208        _ => None,
209    });
210
211    // The size of the container should be floored by the padding and border
212    let styled_based_known_dimensions =
213        known_dimensions.or(min_max_definite_size.or(clamped_style_size).maybe_max(padding_border_sum));
214
215    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
216    // is ComputeSize (and thus the container's size is all that we're interested in)
217    if run_mode == RunMode::ComputeSize {
218        if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
219            return LayoutOutput::from_outer_size(Size { width, height });
220        }
221
222        // We can also short-circuit if the width is known and only the width has been requested.
223        if inputs.axis == RequestedAxis::Horizontal {
224            if let Some(width) = styled_based_known_dimensions.width {
225                return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
226            }
227        }
228    }
229
230    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
231    // is ComputeSize (and thus the container's size is all that we're interested in)
232    if run_mode == RunMode::ComputeSize {
233        if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
234            return LayoutOutput::from_outer_size(Size { width, height });
235        }
236    }
237
238    debug_log!("FLEX:", dbg:style.flex_direction());
239    drop(style);
240
241    compute_preliminary(tree, node, LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs })
242}
243
244/// Compute a preliminary size for an item
245fn compute_preliminary(tree: &mut impl LayoutFlexboxContainer, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
246    let LayoutInput { known_dimensions, parent_size, available_space, run_mode, .. } = inputs;
247
248    // Define some general constants we will need for the remainder of the algorithm.
249    let mut constants = compute_constants(tree, tree.get_flexbox_container_style(node), known_dimensions, parent_size);
250
251    // 9. Flex Layout Algorithm
252
253    // 9.1. Initial Setup
254
255    // 1. Generate anonymous flex items as described in §4 Flex Items.
256    debug_log!("generate_anonymous_flex_items");
257    let mut flex_items = generate_anonymous_flex_items(tree, node, &constants);
258
259    // 9.2. Line Length Determination
260
261    // 2. Determine the available main and cross space for the flex items
262    debug_log!("determine_available_space");
263    let available_space = determine_available_space(known_dimensions, available_space, &constants);
264
265    // 3. Determine the flex base size and hypothetical main size of each item.
266    debug_log!("determine_flex_base_size");
267    determine_flex_base_size(tree, &constants, available_space, &mut flex_items);
268
269    #[cfg(feature = "debug")]
270    for item in flex_items.iter() {
271        debug_log!("item.flex_basis", item.flex_basis);
272        debug_log!("item.inner_flex_basis", item.inner_flex_basis);
273        debug_log!("item.hypothetical_outer_size", dbg:item.hypothetical_outer_size);
274        debug_log!("item.hypothetical_inner_size", dbg:item.hypothetical_inner_size);
275        debug_log!("item.resolved_minimum_main_size", dbg:item.resolved_minimum_main_size);
276    }
277
278    // 4. Determine the main size of the flex container
279    // This has already been done as part of compute_constants. The inner size is exposed as constants.node_inner_size.
280
281    // 9.3. Main Size Determination
282
283    // 5. Collect flex items into flex lines.
284    debug_log!("collect_flex_lines");
285    let mut flex_lines = collect_flex_lines(&constants, available_space, &mut flex_items);
286
287    // If container size is undefined, determine the container's main size
288    // and then re-resolve gaps based on newly determined size
289    debug_log!("determine_container_main_size");
290    if let Some(inner_main_size) = constants.node_inner_size.main(constants.dir) {
291        let outer_main_size = inner_main_size + constants.content_box_inset.main_axis_sum(constants.dir);
292        constants.inner_container_size.set_main(constants.dir, inner_main_size);
293        constants.container_size.set_main(constants.dir, outer_main_size);
294    } else {
295        // Sets constants.container_size and constants.outer_container_size
296        determine_container_main_size(tree, available_space, &mut flex_lines, &mut constants);
297        constants.node_inner_size.set_main(constants.dir, Some(constants.inner_container_size.main(constants.dir)));
298        constants.node_outer_size.set_main(constants.dir, Some(constants.container_size.main(constants.dir)));
299
300        debug_log!("constants.node_outer_size", dbg:constants.node_outer_size);
301        debug_log!("constants.node_inner_size", dbg:constants.node_inner_size);
302
303        // Re-resolve percentage gaps
304        let style = tree.get_flexbox_container_style(node);
305        let inner_container_size = constants.inner_container_size.main(constants.dir);
306        let new_gap = style
307            .gap()
308            .main(constants.dir)
309            .maybe_resolve(inner_container_size, |val, basis| tree.calc(val, basis))
310            .unwrap_or(0.0);
311        constants.gap.set_main(constants.dir, new_gap);
312    }
313
314    // 6. Resolve the flexible lengths of all the flex items to find their used main size.
315    debug_log!("resolve_flexible_lengths");
316    for line in &mut flex_lines {
317        resolve_flexible_lengths(line, &constants);
318    }
319
320    // 9.4. Cross Size Determination
321
322    // 7. Determine the hypothetical cross size of each item.
323    debug_log!("determine_hypothetical_cross_size");
324    for line in &mut flex_lines {
325        determine_hypothetical_cross_size(tree, line, &constants, available_space);
326    }
327
328    // Calculate child baselines. This function is internally smart and only computes child baselines
329    // if they are necessary.
330    debug_log!("calculate_children_base_lines");
331    calculate_children_base_lines(tree, known_dimensions, available_space, &mut flex_lines, &constants);
332
333    // 8. Calculate the cross size of each flex line.
334    debug_log!("calculate_cross_size");
335    calculate_cross_size(&mut flex_lines, known_dimensions, &constants);
336
337    // 9. Handle 'align-content: stretch'.
338    debug_log!("handle_align_content_stretch");
339    handle_align_content_stretch(&mut flex_lines, known_dimensions, &constants);
340
341    // 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
342    //     note the cross size of the line they’re in as the item’s strut size, and restart
343    //     layout from the beginning.
344    //
345    //     In this second layout round, when collecting items into lines, treat the collapsed
346    //     items as having zero main size. For the rest of the algorithm following that step,
347    //     ignore the collapsed items entirely (as if they were display:none) except that after
348    //     calculating the cross size of the lines, if any line’s cross size is less than the
349    //     largest strut size among all the collapsed items in the line, set its cross size to
350    //     that strut size.
351    //
352    //     Skip this step in the second layout round.
353
354    // TODO implement once (if ever) we support visibility:collapse
355
356    // 11. Determine the used cross size of each flex item.
357    debug_log!("determine_used_cross_size");
358    determine_used_cross_size(tree, &mut flex_lines, &constants);
359
360    // 9.5. Main-Axis Alignment
361
362    // 12. Distribute any remaining free space.
363    debug_log!("distribute_remaining_free_space");
364    distribute_remaining_free_space(&mut flex_lines, &constants);
365
366    // 9.6. Cross-Axis Alignment
367
368    // 13. Resolve cross-axis auto margins (also includes 14).
369    debug_log!("resolve_cross_axis_auto_margins");
370    resolve_cross_axis_auto_margins(&mut flex_lines, &constants);
371
372    // 15. Determine the flex container’s used cross size.
373    debug_log!("determine_container_cross_size");
374    let total_line_cross_size = determine_container_cross_size(&flex_lines, known_dimensions, &mut constants);
375
376    // We have the container size.
377    // If our caller does not care about performing layout we are done now.
378    if run_mode == RunMode::ComputeSize {
379        return LayoutOutput::from_outer_size(constants.container_size);
380    }
381
382    // 16. Align all flex lines per align-content.
383    debug_log!("align_flex_lines_per_align_content");
384    align_flex_lines_per_align_content(&mut flex_lines, &constants, total_line_cross_size);
385
386    // Do a final layout pass and gather the resulting layouts
387    debug_log!("final_layout_pass");
388    let inflow_content_size = final_layout_pass(tree, &mut flex_lines, &constants);
389
390    // Before returning we perform absolute layout on all absolutely positioned children
391    debug_log!("perform_absolute_layout_on_absolute_children");
392    let absolute_content_size = perform_absolute_layout_on_absolute_children(tree, node, &constants);
393
394    debug_log!("hidden_layout");
395    let len = tree.child_count(node);
396    for order in 0..len {
397        let child = tree.get_child_id(node, order);
398        if tree.get_flexbox_child_style(child).box_generation_mode() == BoxGenerationMode::None {
399            tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
400            tree.perform_child_layout(
401                child,
402                Size::NONE,
403                Size::NONE,
404                Size::MAX_CONTENT,
405                SizingMode::InherentSize,
406                Line::FALSE,
407            );
408        }
409    }
410
411    // 8.5. Flex Container Baselines: calculate the flex container's first baseline
412    // See https://www.w3.org/TR/css-flexbox-1/#flex-baselines
413    let first_vertical_baseline = if flex_lines.is_empty() {
414        None
415    } else {
416        flex_lines[0]
417            .items
418            .iter()
419            .find(|item| constants.is_column || item.align_self == AlignSelf::BASELINE)
420            .or_else(|| flex_lines[0].items.iter().next())
421            .map(|child| {
422                let offset_vertical = if constants.is_row { child.offset_cross } else { child.offset_main };
423                offset_vertical + child.baseline
424            })
425    };
426
427    LayoutOutput::from_sizes_and_baselines(
428        constants.container_size,
429        inflow_content_size.f32_max(absolute_content_size),
430        Point { x: None, y: first_vertical_baseline },
431    )
432}
433
434/// Compute constants that can be reused during the flexbox algorithm.
435#[inline]
436fn compute_constants(
437    tree: &impl LayoutFlexboxContainer,
438    style: impl FlexboxContainerStyle,
439    known_dimensions: Size<Option<f32>>,
440    parent_size: Size<Option<f32>>,
441) -> AlgoConstants {
442    let dir = style.flex_direction();
443    let is_row = dir.is_row();
444    let is_column = dir.is_column();
445    let is_wrap = matches!(style.flex_wrap(), FlexWrap::Wrap | FlexWrap::WrapReverse);
446    let is_wrap_reverse = style.flex_wrap() == FlexWrap::WrapReverse;
447
448    let aspect_ratio = style.aspect_ratio();
449    let margin = style.margin().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
450    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
451    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
452    let padding_border_sum = padding.sum_axes() + border.sum_axes();
453    let box_sizing_adjustment =
454        if style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
455
456    let align_items = style.align_items().unwrap_or(AlignItems::STRETCH);
457    let align_content = style.align_content().unwrap_or(AlignContent::STRETCH);
458    let justify_content = style.justify_content();
459    let layout_direction = style.direction();
460
461    // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
462    // However, the axis are switched (transposed) because a node that scrolls vertically needs
463    // *horizontal* space to be reserved for a scrollbar
464    let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
465        Overflow::Scroll => style.scrollbar_width(),
466        _ => 0.0,
467    });
468    let mut content_box_inset = padding + border;
469    content_box_inset.bottom += scrollbar_gutter.y;
470
471    match layout_direction {
472        Direction::Ltr => content_box_inset.right += scrollbar_gutter.x,
473        Direction::Rtl => content_box_inset.left += scrollbar_gutter.x,
474    };
475
476    let node_outer_size = known_dimensions;
477    let node_inner_size = node_outer_size.maybe_sub(content_box_inset.sum_axes());
478    let gap = style.gap().resolve_or_zero(node_inner_size.or(Size::zero()), |val, basis| tree.calc(val, basis));
479
480    let container_size = Size::zero();
481    let inner_container_size = Size::zero();
482
483    AlgoConstants {
484        dir,
485        layout_direction,
486        is_row,
487        is_column,
488        is_wrap,
489        is_wrap_reverse,
490        min_size: style
491            .min_size()
492            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
493            .maybe_apply_aspect_ratio(aspect_ratio)
494            .maybe_add(box_sizing_adjustment),
495        max_size: style
496            .max_size()
497            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
498            .maybe_apply_aspect_ratio(aspect_ratio)
499            .maybe_add(box_sizing_adjustment),
500        margin,
501        border,
502        gap,
503        content_box_inset,
504        scrollbar_gutter,
505        align_items,
506        align_content,
507        justify_content,
508        node_outer_size,
509        node_inner_size,
510        container_size,
511        inner_container_size,
512    }
513}
514
515/// Generate anonymous flex items.
516///
517/// # [9.1. Initial Setup](https://www.w3.org/TR/css-flexbox-1/#box-manip)
518///
519/// - [**Generate anonymous flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-anon-box) as described in [§4 Flex Items](https://www.w3.org/TR/css-flexbox-1/#flex-items).
520#[inline]
521fn generate_anonymous_flex_items(
522    tree: &impl LayoutFlexboxContainer,
523    node: NodeId,
524    constants: &AlgoConstants,
525) -> Vec<FlexItem> {
526    tree.child_ids(node)
527        .enumerate()
528        .map(|(index, child)| (index, child, tree.get_flexbox_child_style(child)))
529        .filter(|(_, _, style)| style.position() != Position::Absolute)
530        .filter(|(_, _, style)| style.box_generation_mode() != BoxGenerationMode::None)
531        .map(|(index, child, child_style)| {
532            let aspect_ratio = child_style.aspect_ratio();
533            let padding = child_style
534                .padding()
535                .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
536            let border = child_style
537                .border()
538                .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis));
539            let pb_sum = (padding + border).sum_axes();
540            let box_sizing_adjustment =
541                if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
542            FlexItem {
543                node: child,
544                order: index as u32,
545                size: child_style
546                    .size()
547                    .maybe_resolve(constants.node_inner_size, |val, basis| tree.calc(val, basis))
548                    .maybe_apply_aspect_ratio(aspect_ratio)
549                    .maybe_add(box_sizing_adjustment),
550                min_size: child_style
551                    .min_size()
552                    .maybe_resolve(constants.node_inner_size, |val, basis| tree.calc(val, basis))
553                    .maybe_add(box_sizing_adjustment),
554                max_size: child_style
555                    .max_size()
556                    .maybe_resolve(constants.node_inner_size, |val, basis| tree.calc(val, basis))
557                    .maybe_add(box_sizing_adjustment),
558                aspect_ratio,
559
560                inset: child_style
561                    .inset()
562                    .zip_size(constants.node_inner_size, |p, s| p.maybe_resolve(s, |val, basis| tree.calc(val, basis))),
563                margin: child_style
564                    .margin()
565                    .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
566                margin_is_auto: child_style.margin().map(LengthPercentageAuto::is_auto),
567                padding: child_style
568                    .padding()
569                    .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
570                border: child_style
571                    .border()
572                    .resolve_or_zero(constants.node_inner_size.width, |val, basis| tree.calc(val, basis)),
573                align_self: child_style.align_self().unwrap_or(constants.align_items),
574                overflow: child_style.overflow(),
575                scrollbar_width: child_style.scrollbar_width(),
576                flex_grow: child_style.flex_grow(),
577                flex_shrink: child_style.flex_shrink(),
578                flex_basis: 0.0,
579                inner_flex_basis: 0.0,
580                violation: 0.0,
581                frozen: false,
582
583                resolved_minimum_main_size: 0.0,
584                hypothetical_inner_size: Size::zero(),
585                hypothetical_outer_size: Size::zero(),
586                target_size: Size::zero(),
587                outer_target_size: Size::zero(),
588                content_flex_fraction: 0.0,
589
590                baseline: 0.0,
591
592                offset_main: 0.0,
593                offset_cross: 0.0,
594            }
595        })
596        .collect()
597}
598
599/// Determine the available main and cross space for the flex items.
600///
601/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
602///
603/// - [**Determine the available main and cross space for the flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-available).
604///
605/// For each dimension, if that dimension of the flex container’s content box is a definite size, use that;
606/// if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint;
607/// otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value.
608/// **This might result in an infinite value**.
609#[inline]
610#[must_use]
611fn determine_available_space(
612    known_dimensions: Size<Option<f32>>,
613    outer_available_space: Size<AvailableSpace>,
614    constants: &AlgoConstants,
615) -> Size<AvailableSpace> {
616    // Note: min/max/preferred size styles have already been applied to known_dimensions in the `compute` function above
617    let width = match known_dimensions.width {
618        Some(node_width) => AvailableSpace::Definite(node_width - constants.content_box_inset.horizontal_axis_sum()),
619        None => outer_available_space
620            .width
621            .maybe_sub(constants.margin.horizontal_axis_sum())
622            .maybe_sub(constants.content_box_inset.horizontal_axis_sum()),
623    };
624
625    let height = match known_dimensions.height {
626        Some(node_height) => AvailableSpace::Definite(node_height - constants.content_box_inset.vertical_axis_sum()),
627        None => outer_available_space
628            .height
629            .maybe_sub(constants.margin.vertical_axis_sum())
630            .maybe_sub(constants.content_box_inset.vertical_axis_sum()),
631    };
632
633    Size { width, height }
634}
635
636/// Determine the flex base size and hypothetical main size of each item.
637///
638/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
639///
640/// - [**Determine the flex base size and hypothetical main size of each item:**](https://www.w3.org/TR/css-flexbox-1/#algo-main-item)
641///
642///     - A. If the item has a definite used flex basis, that’s the flex base size.
643///
644///     - B. If the flex item has ...
645///
646///         - an intrinsic aspect ratio,
647///         - a used flex basis of content, and
648///         - a definite cross size,
649///
650///       then the flex base size is calculated from its inner cross size and the flex item’s intrinsic aspect ratio.
651///
652///     - C. If the used flex basis is content or depends on its available space, and the flex container is being sized under a min-content
653///       or max-content constraint (e.g. when performing automatic table layout \[CSS21\]), size the item under that constraint.
654///       The flex base size is the item’s resulting main size.
655///
656///     - E. Otherwise, size the item into the available space using its used flex basis in place of its main size, treating a value of content as max-content.
657///       If a cross size is needed to determine the main size (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
658///       in this calculation use fit-content as the flex item’s cross size. The flex base size is the item’s resulting main size.
659///
660///   When determining the flex base size, the item’s min and max main sizes are ignored (no clamping occurs).
661///   Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
662///   (For example, an item with a specified size of zero, positive padding, and box-sizing: border-box will have an outer flex base size of zero—and hence a negative inner flex base size.)
663#[inline]
664fn determine_flex_base_size(
665    tree: &mut impl LayoutFlexboxContainer,
666    constants: &AlgoConstants,
667    available_space: Size<AvailableSpace>,
668    flex_items: &mut [FlexItem],
669) {
670    let dir = constants.dir;
671
672    for child in flex_items.iter_mut() {
673        let child_style = tree.get_flexbox_child_style(child.node);
674
675        // Parent size for child sizing
676        let cross_axis_parent_size = constants.node_inner_size.cross(dir);
677        let child_parent_size = Size::from_cross(dir, cross_axis_parent_size);
678
679        // Available space for child sizing
680        // Min/max sizes transferred through the aspect ratio are taken into account here
681        // https://github.com/w3c/csswg-drafts/issues/10997
682        let cross_axis_margin_sum = constants.margin.cross_axis_sum(dir);
683        let transferred_min_size = child.min_size.maybe_apply_aspect_ratio(child.aspect_ratio);
684        let transferred_max_size = child.max_size.maybe_apply_aspect_ratio(child.aspect_ratio);
685        let child_min_cross = transferred_min_size.cross(dir).maybe_add(cross_axis_margin_sum);
686        let child_max_cross = transferred_max_size.cross(dir).maybe_add(cross_axis_margin_sum);
687
688        // Clamp available space by min- and max- size
689        let cross_axis_available_space: AvailableSpace = match available_space.cross(dir) {
690            AvailableSpace::Definite(val) => AvailableSpace::Definite(
691                cross_axis_parent_size.unwrap_or(val).maybe_clamp(child_min_cross, child_max_cross),
692            ),
693            AvailableSpace::MinContent => match child_min_cross {
694                Some(min) => AvailableSpace::Definite(min),
695                None => AvailableSpace::MinContent,
696            },
697            AvailableSpace::MaxContent => match child_max_cross {
698                Some(max) => AvailableSpace::Definite(max),
699                None => AvailableSpace::MaxContent,
700            },
701        };
702
703        // Known dimensions for child sizing
704        let child_known_dimensions = {
705            let mut ckd = child.size.with_main(dir, None);
706            // Clamp the definite cross size by the cross min/max sizes so that sizes
707            // transferred through an intrinsic aspect ratio (e.g. for replaced elements)
708            // are based on the used cross size.
709            ckd.set_cross(
710                dir,
711                ckd.cross(dir).maybe_clamp(transferred_min_size.cross(dir), transferred_max_size.cross(dir)),
712            );
713            if child.align_self == AlignSelf::STRETCH
714                && !child.margin_is_auto.cross_start(constants.dir)
715                && !child.margin_is_auto.cross_end(constants.dir)
716                && ckd.cross(dir).is_none()
717            {
718                ckd.set_cross(
719                    dir,
720                    cross_axis_available_space.into_option().maybe_sub(child.margin.cross_axis_sum(dir)),
721                );
722            }
723            ckd
724        };
725
726        let container_width = constants.node_inner_size.main(dir);
727        let box_sizing_adjustment = if child_style.box_sizing() == BoxSizing::ContentBox {
728            let padding = child_style.padding().resolve_or_zero(container_width, |val, basis| tree.calc(val, basis));
729            let border = child_style.border().resolve_or_zero(container_width, |val, basis| tree.calc(val, basis));
730            (padding + border).sum_axes()
731        } else {
732            Size::ZERO
733        }
734        .main(dir);
735        let flex_basis = child_style
736            .flex_basis()
737            .maybe_resolve(container_width, |val, basis| tree.calc(val, basis))
738            .maybe_add(box_sizing_adjustment);
739
740        drop(child_style);
741
742        child.flex_basis = 'flex_basis: {
743            // A. If the item has a definite used flex basis, that’s the flex base size.
744
745            // B. If the flex item has an intrinsic aspect ratio,
746            //    a used flex basis of content, and a definite cross size,
747            //    then the flex base size is calculated from its inner
748            //    cross size and the flex item’s intrinsic aspect ratio.
749
750            // Note: `child.size` has already been resolved against aspect_ratio in generate_anonymous_flex_items
751            // So B will just work here by using main_size without special handling for aspect_ratio
752            let main_size = child.size.main(dir);
753            if let Some(flex_basis) = flex_basis.or(main_size) {
754                break 'flex_basis flex_basis;
755            };
756
757            // C. If the used flex basis is content or depends on its available space,
758            //    and the flex container is being sized under a min-content or max-content
759            //    constraint (e.g. when performing automatic table layout [CSS21]),
760            //    size the item under that constraint. The flex base size is the item’s
761            //    resulting main size.
762
763            // This is covered by the implementation of E below, which passes the available_space constraint
764            // through to the child size computation. It may need a separate implementation if/when D is implemented.
765
766            // D. Otherwise, if the used flex basis is content or depends on its
767            //    available space, the available main size is infinite, and the flex item’s
768            //    inline axis is parallel to the main axis, lay the item out using the rules
769            //    for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
770            //    is the item’s max-content main size.
771
772            // TODO if/when vertical writing modes are supported
773
774            // E. Otherwise, size the item into the available space using its used flex basis
775            //    in place of its main size, treating a value of content as max-content.
776            //    If a cross size is needed to determine the main size (e.g. when the
777            //    flex item’s main size is in its block axis) and the flex item’s cross size
778            //    is auto and not definite, in this calculation use fit-content as the
779            //    flex item’s cross size. The flex base size is the item’s resulting main size.
780
781            let child_available_space = Size::MAX_CONTENT
782                .with_main(
783                    dir,
784                    // Map AvailableSpace::Definite to AvailableSpace::MaxContent
785                    if available_space.main(dir) == AvailableSpace::MinContent {
786                        AvailableSpace::MinContent
787                    } else {
788                        AvailableSpace::MaxContent
789                    },
790                )
791                .with_cross(dir, cross_axis_available_space);
792
793            debug_log!("COMPUTE CHILD BASE SIZE:");
794            break 'flex_basis tree.measure_child_size(
795                child.node,
796                child_known_dimensions,
797                child_parent_size,
798                child_available_space,
799                SizingMode::ContentSize,
800                dir.main_axis(),
801                Line::FALSE,
802            );
803        };
804
805        // Floor flex-basis by the padding_border_sum (floors inner_flex_basis at zero)
806        // This seems to be in violation of the spec which explicitly states that the content box should not be floored at zero
807        // (like it usually is) when calculating the flex-basis. But including this matches both Chrome and Firefox's behaviour.
808        //
809        // TODO: resolve spec violation
810        // Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
811        // Spec: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
812        let padding_border_sum = child.padding.main_axis_sum(constants.dir) + child.border.main_axis_sum(constants.dir);
813        child.flex_basis = child.flex_basis.max(padding_border_sum);
814
815        // The hypothetical main size is the item’s flex base size clamped according to its
816        // used min and max main sizes (and flooring the content box size at zero).
817
818        child.inner_flex_basis =
819            child.flex_basis - child.padding.main_axis_sum(constants.dir) - child.border.main_axis_sum(constants.dir);
820
821        let padding_border_axes_sums = (child.padding + child.border).sum_axes().map(Some);
822
823        // Note that it is important that the `parent_size` parameter in the main axis is not set for this
824        // function call as it used for resolving percentages, and percentage size in an axis should not contribute
825        // to a min-content contribution in that same axis. However the `parent_size` and `available_space` *should*
826        // be set to their usual values in the cross axis so that wrapping content can wrap correctly.
827        //
828        // See https://drafts.csswg.org/css-sizing-3/#min-percentage-contribution
829        let style_min_main_size =
830            child.min_size.or(child.overflow.map(Overflow::maybe_into_automatic_min_size).into()).main(dir);
831
832        child.resolved_minimum_main_size = style_min_main_size.unwrap_or({
833            let min_content_main_size = {
834                let child_available_space = Size::MIN_CONTENT.with_cross(dir, cross_axis_available_space);
835
836                debug_log!("COMPUTE CHILD MIN SIZE:");
837                tree.measure_child_size(
838                    child.node,
839                    child_known_dimensions,
840                    child_parent_size,
841                    child_available_space,
842                    SizingMode::ContentSize,
843                    dir.main_axis(),
844                    Line::FALSE,
845                )
846            };
847
848            // 4.5. Automatic Minimum Size of Flex Items
849            // https://www.w3.org/TR/css-flexbox-1/#min-size-auto
850            let clamped_min_content_size =
851                min_content_main_size.maybe_min(child.size.main(dir)).maybe_min(transferred_max_size.main(dir));
852            clamped_min_content_size.maybe_max(padding_border_axes_sums.main(dir))
853        });
854
855        // Sizes transferred through the aspect ratio clamp the hypothetical main size,
856        // but do not participate in resolving flexible lengths or clamping the final size.
857        // https://github.com/w3c/csswg-drafts/issues/10997
858        let hypothetical_inner_min_main = child
859            .resolved_minimum_main_size
860            .maybe_max(transferred_min_size.main(constants.dir))
861            .maybe_max(padding_border_axes_sums.main(constants.dir));
862        let hypothetical_inner_size =
863            child.flex_basis.maybe_clamp(Some(hypothetical_inner_min_main), transferred_max_size.main(constants.dir));
864        let hypothetical_outer_size = hypothetical_inner_size + child.margin.main_axis_sum(constants.dir);
865
866        child.hypothetical_inner_size.set_main(constants.dir, hypothetical_inner_size);
867        child.hypothetical_outer_size.set_main(constants.dir, hypothetical_outer_size);
868    }
869}
870
871/// Collect flex items into flex lines.
872///
873/// # [9.3. Main Size Determination](https://www.w3.org/TR/css-flexbox-1/#main-sizing)
874///
875/// - [**Collect flex items into flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-break):
876///
877///     - If the flex container is single-line, collect all the flex items into a single flex line.
878///
879///     - Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size
880///       (or until a forced break is encountered, see [§10 Fragmenting Flex Layout](https://www.w3.org/TR/css-flexbox-1/#pagination)).
881///       If the very first uncollected item wouldn't fit, collect just it into the line.
882///
883///       For this step, the size of a flex item is its outer hypothetical main size. (**Note: This can be negative**.)
884///
885///       Repeat until all flex items have been collected into flex lines.
886///
887///       **Note that the "collect as many" line will collect zero-sized flex items onto the end of the previous line even if the last non-zero item exactly "filled up" the line**.
888#[inline]
889fn collect_flex_lines<'a>(
890    constants: &AlgoConstants,
891    available_space: Size<AvailableSpace>,
892    flex_items: &'a mut Vec<FlexItem>,
893) -> Vec<FlexLine<'a>> {
894    if !constants.is_wrap {
895        let mut lines = new_vec_with_capacity(1);
896        lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
897        lines
898    } else {
899        let main_axis_available_space = match constants.max_size.main(constants.dir) {
900            Some(max_size) => AvailableSpace::Definite(
901                available_space
902                    .main(constants.dir)
903                    .into_option()
904                    .unwrap_or(max_size)
905                    .maybe_max(constants.min_size.main(constants.dir)),
906            ),
907            None => available_space.main(constants.dir),
908        };
909
910        match main_axis_available_space {
911            // If we're sizing under a max-content constraint then the flex items will never wrap
912            // (at least for now - future extensions to the CSS spec may add provisions for forced wrap points)
913            AvailableSpace::MaxContent => {
914                let mut lines = new_vec_with_capacity(1);
915                lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
916                lines
917            }
918            // If flex-wrap is Wrap and we're sizing under a min-content constraint, then we take every possible wrapping opportunity
919            // and place each item in it's own line
920            AvailableSpace::MinContent => {
921                let mut lines = new_vec_with_capacity(flex_items.len());
922                let mut items = &mut flex_items[..];
923                while !items.is_empty() {
924                    let (line_items, rest) = items.split_at_mut(1);
925                    lines.push(FlexLine { items: line_items, cross_size: 0.0, offset_cross: 0.0 });
926                    items = rest;
927                }
928                lines
929            }
930            AvailableSpace::Definite(main_axis_available_space) => {
931                let mut lines = new_vec_with_capacity(1);
932                let mut flex_items = &mut flex_items[..];
933                let main_axis_gap = constants.gap.main(constants.dir);
934
935                while !flex_items.is_empty() {
936                    // Find index of the first item in the next line
937                    // (or the last item if all remaining items are in the current line)
938                    let mut line_length = 0.0;
939                    let index = flex_items
940                        .iter()
941                        .enumerate()
942                        .find(|&(idx, child)| {
943                            // Gaps only occur between items (not before the first one or after the last one)
944                            // So first item in the line does not contribute a gap to the line length
945                            let gap_contribution = if idx == 0 { 0.0 } else { main_axis_gap };
946                            line_length += child.hypothetical_outer_size.main(constants.dir) + gap_contribution;
947                            line_length > main_axis_available_space && idx != 0
948                        })
949                        .map(|(idx, _)| idx)
950                        .unwrap_or(flex_items.len());
951
952                    let (items, rest) = flex_items.split_at_mut(index);
953                    lines.push(FlexLine { items, cross_size: 0.0, offset_cross: 0.0 });
954                    flex_items = rest;
955                }
956                lines
957            }
958        }
959    }
960}
961
962/// Determine the container's main size (if not already known)
963fn determine_container_main_size(
964    tree: &mut impl LayoutFlexboxContainer,
965    available_space: Size<AvailableSpace>,
966    lines: &mut [FlexLine<'_>],
967    constants: &mut AlgoConstants,
968) {
969    let dir = constants.dir;
970    let main_content_box_inset = constants.content_box_inset.main_axis_sum(constants.dir);
971
972    let outer_main_size: f32 = constants.node_outer_size.main(constants.dir).unwrap_or_else(|| {
973        match available_space.main(dir) {
974            AvailableSpace::Definite(main_axis_available_space) => {
975                let longest_line_length: f32 = lines
976                    .iter()
977                    .map(|line| {
978                        let line_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
979                        let total_target_size = line
980                            .items
981                            .iter()
982                            .map(|child| {
983                                let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
984                                (child.flex_basis.maybe_max(child.min_size.main(constants.dir))
985                                    + child.margin.main_axis_sum(constants.dir))
986                                .max(padding_border_sum)
987                            })
988                            .sum::<f32>();
989                        total_target_size + line_main_axis_gap
990                    })
991                    .max_by(|a, b| a.total_cmp(b))
992                    .unwrap_or(0.0);
993                let size = longest_line_length + main_content_box_inset;
994                if lines.len() > 1 {
995                    f32_max(size, main_axis_available_space)
996                } else {
997                    size
998                }
999            }
1000            AvailableSpace::MinContent if constants.is_wrap => {
1001                let longest_line_length: f32 = lines
1002                    .iter()
1003                    .map(|line| {
1004                        let line_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
1005                        let total_target_size = line
1006                            .items
1007                            .iter()
1008                            .map(|child| {
1009                                let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
1010                                (child.flex_basis.maybe_max(child.min_size.main(constants.dir))
1011                                    + child.margin.main_axis_sum(constants.dir))
1012                                .max(padding_border_sum)
1013                            })
1014                            .sum::<f32>();
1015                        total_target_size + line_main_axis_gap
1016                    })
1017                    .max_by(|a, b| a.total_cmp(b))
1018                    .unwrap_or(0.0);
1019                longest_line_length + main_content_box_inset
1020            }
1021            AvailableSpace::MinContent | AvailableSpace::MaxContent => {
1022                // Define a base main_size variable. This is mutated once for iteration over the outer
1023                // loop over the flex lines as:
1024                //   "The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line."
1025                let mut main_size = 0.0;
1026
1027                for line in lines.iter_mut() {
1028                    for item in line.items.iter_mut() {
1029                        let style_min = item.min_size.main(constants.dir);
1030                        let style_preferred = item.size.main(constants.dir);
1031                        let style_max = item.max_size.main(constants.dir);
1032
1033                        // The spec seems a bit unclear on this point (my initial reading was that the `.maybe_max(style_preferred)` should
1034                        // not be included here), however this matches both Chrome and Firefox as of 9th March 2023.
1035                        //
1036                        // Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
1037                        // Spec modification: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
1038                        // Issue: https://github.com/w3c/csswg-drafts/issues/1435
1039                        // Gentest: padding_border_overrides_size_flex_basis_0.html
1040                        let clamping_basis = Some(item.flex_basis).maybe_max(style_preferred);
1041                        let flex_basis_min = clamping_basis.filter(|_| item.flex_shrink == 0.0);
1042                        let flex_basis_max = clamping_basis.filter(|_| item.flex_grow == 0.0);
1043
1044                        let min_main_size = style_min
1045                            .maybe_max(flex_basis_min)
1046                            .or(flex_basis_min)
1047                            .unwrap_or(item.resolved_minimum_main_size)
1048                            .max(item.resolved_minimum_main_size);
1049                        let max_main_size =
1050                            style_max.maybe_min(flex_basis_max).or(flex_basis_max).unwrap_or(f32::INFINITY);
1051
1052                        let content_contribution = match (min_main_size, style_preferred, max_main_size) {
1053                            // If the clamping values are such that max <= min, then we can avoid the expensive step of computing the content size
1054                            // as we know that the clamping values will override it anyway
1055                            (min, Some(pref), max) if max <= min || max <= pref => {
1056                                pref.min(max).max(min) + item.margin.main_axis_sum(constants.dir)
1057                            }
1058                            (min, _, max) if max <= min => min + item.margin.main_axis_sum(constants.dir),
1059
1060                            // Else compute the min- or -max content size and apply the full formula for computing the
1061                            // min- or max- content contribution
1062                            _ if item.is_scroll_container() => {
1063                                item.flex_basis + item.margin.main_axis_sum(constants.dir)
1064                            }
1065                            _ => {
1066                                // Parent size for child sizing
1067                                let cross_axis_parent_size = constants.node_inner_size.cross(dir);
1068
1069                                // Available space for child sizing
1070                                let cross_axis_margin_sum = constants.margin.cross_axis_sum(dir);
1071                                let child_min_cross = item.min_size.cross(dir).maybe_add(cross_axis_margin_sum);
1072                                let child_max_cross = item.max_size.cross(dir).maybe_add(cross_axis_margin_sum);
1073                                let cross_axis_available_space: AvailableSpace = available_space
1074                                    .cross(dir)
1075                                    .map_definite_value(|val| cross_axis_parent_size.unwrap_or(val))
1076                                    .maybe_clamp(child_min_cross, child_max_cross);
1077
1078                                let child_available_space = available_space.with_cross(dir, cross_axis_available_space);
1079
1080                                // Known dimensions for child sizing
1081                                let child_known_dimensions = {
1082                                    let mut ckd = item.size.with_main(dir, None);
1083                                    if item.align_self == AlignSelf::STRETCH && ckd.cross(dir).is_none() {
1084                                        ckd.set_cross(
1085                                            dir,
1086                                            cross_axis_available_space
1087                                                .into_option()
1088                                                .maybe_sub(item.margin.cross_axis_sum(dir)),
1089                                        );
1090                                    }
1091                                    ckd
1092                                };
1093
1094                                // Either the min- or max- content size depending on which constraint we are sizing under.
1095                                // TODO: Optimise by using already computed values where available
1096                                debug_log!("COMPUTE CHILD BASE SIZE (for intrinsic main size):");
1097                                let content_main_size = tree.measure_child_size(
1098                                    item.node,
1099                                    child_known_dimensions,
1100                                    constants.node_inner_size,
1101                                    child_available_space,
1102                                    SizingMode::InherentSize,
1103                                    dir.main_axis(),
1104                                    Line::FALSE,
1105                                ) + item.margin.main_axis_sum(constants.dir);
1106
1107                                // This is somewhat bizarre in that it's asymmetrical depending whether the flex container is a column or a row.
1108                                //
1109                                // I *think* this might relate to https://drafts.csswg.org/css-flexbox-1/#algo-main-container:
1110                                //
1111                                //    "The automatic block size of a block-level flex container is its max-content size."
1112                                //
1113                                // Which could suggest that flex-basis defining a vertical size does not shrink because it is in the block axis, and the automatic size
1114                                // in the block axis is a MAX content size. Whereas a flex-basis defining a horizontal size does shrink because the automatic size in
1115                                // inline axis is MIN content size (although I don't have a reference for that).
1116                                //
1117                                // Ultimately, this was not found by reading the spec, but by trial and error fixing tests to align with Webkit/Firefox output.
1118                                // (see the `flex_basis_unconstraint_row` and `flex_basis_uncontraint_column` generated tests which demonstrate this)
1119                                if constants.is_row {
1120                                    content_main_size.maybe_clamp(style_min, style_max).max(main_content_box_inset)
1121                                } else {
1122                                    content_main_size
1123                                        .max(item.flex_basis)
1124                                        .maybe_clamp(style_min, style_max)
1125                                        .max(main_content_box_inset)
1126                                }
1127                            }
1128                        };
1129                        item.content_flex_fraction = {
1130                            let diff = content_contribution - item.flex_basis;
1131                            if diff > 0.0 {
1132                                diff / f32_max(1.0, item.flex_grow)
1133                            } else if diff < 0.0 {
1134                                let scaled_shrink_factor = f32_max(1.0, item.flex_shrink * item.inner_flex_basis);
1135                                diff / scaled_shrink_factor
1136                            } else {
1137                                // We are assuming that diff is 0.0 here and that we haven't accidentally introduced a NaN
1138                                0.0
1139                            }
1140                        };
1141                    }
1142
1143                    // TODO Spec says to scale everything by the line's max flex fraction. But neither Chrome nor firefox implement this
1144                    // so we don't either. But if we did want to, we'd need this computation here (and to use it below):
1145                    //
1146                    // Within each line, find the largest max-content flex fraction among all the flex items.
1147                    // let line_flex_fraction = line
1148                    //     .items
1149                    //     .iter()
1150                    //     .map(|item| item.content_flex_fraction)
1151                    //     .max_by(|a, b| a.total_cmp(b))
1152                    //     .unwrap_or(0.0); // Unwrap case never gets hit because there is always at least one item a line
1153
1154                    // Add each item’s flex base size to the product of:
1155                    //   - its flex grow factor (or scaled flex shrink factor,if the chosen max-content flex fraction was negative)
1156                    //   - the chosen max-content flex fraction
1157                    // then clamp that result by the max main size floored by the min main size.
1158                    //
1159                    // The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line.
1160                    let item_main_size_sum = line
1161                        .items
1162                        .iter_mut()
1163                        .map(|item| {
1164                            let flex_fraction = item.content_flex_fraction;
1165                            // let flex_fraction = line_flex_fraction;
1166
1167                            let flex_contribution = if item.content_flex_fraction > 0.0 {
1168                                f32_max(1.0, item.flex_grow) * flex_fraction
1169                            } else if item.content_flex_fraction < 0.0 {
1170                                let scaled_shrink_factor = f32_max(1.0, item.flex_shrink) * item.inner_flex_basis;
1171                                scaled_shrink_factor * flex_fraction
1172                            } else {
1173                                0.0
1174                            };
1175                            let size = item.flex_basis + flex_contribution;
1176                            item.outer_target_size.set_main(constants.dir, size);
1177                            item.target_size.set_main(constants.dir, size);
1178                            size
1179                        })
1180                        .sum::<f32>();
1181
1182                    let gap_sum = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
1183                    main_size = f32_max(main_size, item_main_size_sum + gap_sum)
1184                }
1185
1186                main_size + main_content_box_inset
1187            }
1188        }
1189    });
1190
1191    let outer_main_size = outer_main_size
1192        .maybe_clamp(constants.min_size.main(constants.dir), constants.max_size.main(constants.dir))
1193        .max(main_content_box_inset - constants.scrollbar_gutter.main(constants.dir));
1194
1195    // let outer_main_size = inner_main_size + constants.padding_border.main_axis_sum(constants.dir);
1196    let inner_main_size = f32_max(outer_main_size - main_content_box_inset, 0.0);
1197    constants.container_size.set_main(constants.dir, outer_main_size);
1198    constants.inner_container_size.set_main(constants.dir, inner_main_size);
1199    constants.node_inner_size.set_main(constants.dir, Some(inner_main_size));
1200}
1201
1202/// Resolve the flexible lengths of the items within a flex line.
1203/// Sets the `main` component of each item's `target_size` and `outer_target_size`
1204///
1205/// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
1206#[inline]
1207fn resolve_flexible_lengths(line: &mut FlexLine, constants: &AlgoConstants) {
1208    let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
1209
1210    // 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
1211    //    items on the line. If the sum is less than the flex container’s inner main size,
1212    //    use the flex grow factor for the rest of this algorithm; otherwise, use the
1213    //    flex shrink factor.
1214
1215    let total_hypothetical_outer_main_size =
1216        line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum::<f32>();
1217    let used_flex_factor: f32 = total_main_axis_gap + total_hypothetical_outer_main_size;
1218    let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
1219    let shrinking = used_flex_factor > constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
1220    let exactly_sized = !growing & !shrinking;
1221
1222    // 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
1223    //    - Any item that has a flex factor of zero
1224    //    - If using the flex grow factor: any item that has a flex base size
1225    //      greater than its hypothetical main size
1226    //    - If using the flex shrink factor: any item that has a flex base size
1227    //      smaller than its hypothetical main size
1228
1229    for child in line.items.iter_mut() {
1230        let inner_target_size = child.hypothetical_inner_size.main(constants.dir);
1231        child.target_size.set_main(constants.dir, inner_target_size);
1232
1233        if exactly_sized
1234            || (child.flex_grow == 0.0 && child.flex_shrink == 0.0)
1235            || (growing && child.flex_basis > child.hypothetical_inner_size.main(constants.dir))
1236            || (shrinking && child.flex_basis < child.hypothetical_inner_size.main(constants.dir))
1237        {
1238            child.frozen = true;
1239            let outer_target_size = inner_target_size + child.margin.main_axis_sum(constants.dir);
1240            child.outer_target_size.set_main(constants.dir, outer_target_size);
1241        }
1242    }
1243
1244    if exactly_sized {
1245        return;
1246    }
1247
1248    // 3. Calculate initial free space. Sum the outer sizes of all items on the line,
1249    //    and subtract this from the flex container’s inner main size. For frozen items,
1250    //    use their outer target main size; for other items, use their outer flex base size.
1251
1252    let used_space: f32 = total_main_axis_gap
1253        + line
1254            .items
1255            .iter()
1256            .map(|child| {
1257                if child.frozen {
1258                    child.outer_target_size.main(constants.dir)
1259                } else {
1260                    child.flex_basis + child.margin.main_axis_sum(constants.dir)
1261                }
1262            })
1263            .sum::<f32>();
1264
1265    let initial_free_space = constants.node_inner_size.main(constants.dir).maybe_sub(used_space).unwrap_or(0.0);
1266
1267    // 4. Loop
1268
1269    loop {
1270        // a. Check for flexible items. If all the flex items on the line are frozen,
1271        //    free space has been distributed; exit this loop.
1272
1273        if line.items.iter().all(|child| child.frozen) {
1274            break;
1275        }
1276
1277        // b. Calculate the remaining free space as for initial free space, above.
1278        //    If the sum of the unfrozen flex items’ flex factors is less than one,
1279        //    multiply the initial free space by this sum. If the magnitude of this
1280        //    value is less than the magnitude of the remaining free space, use this
1281        //    as the remaining free space.
1282
1283        let used_space: f32 = total_main_axis_gap
1284            + line
1285                .items
1286                .iter()
1287                .map(|child| {
1288                    if child.frozen {
1289                        child.outer_target_size.main(constants.dir)
1290                    } else {
1291                        child.flex_basis + child.margin.main_axis_sum(constants.dir)
1292                    }
1293                })
1294                .sum::<f32>();
1295
1296        let mut unfrozen: Vec<&mut FlexItem> = line.items.iter_mut().filter(|child| !child.frozen).collect();
1297
1298        let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
1299            unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
1300                (flex_grow + item.flex_grow, flex_shrink + item.flex_shrink)
1301            });
1302
1303        let free_space = if growing && sum_flex_grow < 1.0 {
1304            (initial_free_space * sum_flex_grow - total_main_axis_gap)
1305                .maybe_min(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
1306        } else if shrinking && sum_flex_shrink < 1.0 {
1307            (initial_free_space * sum_flex_shrink - total_main_axis_gap)
1308                .maybe_max(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
1309        } else {
1310            (constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
1311                .unwrap_or(used_flex_factor - used_space)
1312        };
1313
1314        // c. Distribute free space proportional to the flex factors.
1315        //    - If the remaining free space is zero
1316        //        Do Nothing
1317        //    - If using the flex grow factor
1318        //        Find the ratio of the item’s flex grow factor to the sum of the
1319        //        flex grow factors of all unfrozen items on the line. Set the item’s
1320        //        target main size to its flex base size plus a fraction of the remaining
1321        //        free space proportional to the ratio.
1322        //    - If using the flex shrink factor
1323        //        For every unfrozen item on the line, multiply its flex shrink factor by
1324        //        its inner flex base size, and note this as its scaled flex shrink factor.
1325        //        Find the ratio of the item’s scaled flex shrink factor to the sum of the
1326        //        scaled flex shrink factors of all unfrozen items on the line. Set the item’s
1327        //        target main size to its flex base size minus a fraction of the absolute value
1328        //        of the remaining free space proportional to the ratio. Note this may result
1329        //        in a negative inner main size; it will be corrected in the next step.
1330        //    - Otherwise
1331        //        Do Nothing
1332
1333        if free_space.is_normal() {
1334            if growing && sum_flex_grow > 0.0 {
1335                for child in &mut unfrozen {
1336                    child
1337                        .target_size
1338                        .set_main(constants.dir, child.flex_basis + free_space * (child.flex_grow / sum_flex_grow));
1339                }
1340            } else if shrinking && sum_flex_shrink > 0.0 {
1341                let sum_scaled_shrink_factor: f32 =
1342                    unfrozen.iter().map(|child| child.inner_flex_basis * child.flex_shrink).sum();
1343
1344                if sum_scaled_shrink_factor > 0.0 {
1345                    for child in &mut unfrozen {
1346                        let scaled_shrink_factor = child.inner_flex_basis * child.flex_shrink;
1347                        child.target_size.set_main(
1348                            constants.dir,
1349                            child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
1350                        )
1351                    }
1352                }
1353            }
1354        }
1355
1356        // d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
1357        //    used min and max main sizes and floor its content-box size at zero. If the
1358        //    item’s target main size was made smaller by this, it’s a max violation.
1359        //    If the item’s target main size was made larger by this, it’s a min violation.
1360
1361        let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
1362            let resolved_min_main: Option<f32> = child.resolved_minimum_main_size.into();
1363            let max_main = child.max_size.main(constants.dir);
1364            let clamped = child.target_size.main(constants.dir).maybe_clamp(resolved_min_main, max_main).max(0.0);
1365            child.violation = clamped - child.target_size.main(constants.dir);
1366            child.target_size.set_main(constants.dir, clamped);
1367            child.outer_target_size.set_main(
1368                constants.dir,
1369                child.target_size.main(constants.dir) + child.margin.main_axis_sum(constants.dir),
1370            );
1371
1372            acc + child.violation
1373        });
1374
1375        // e. Freeze over-flexed items. The total violation is the sum of the adjustments
1376        //    from the previous step ∑(clamped size - unclamped size). If the total violation is:
1377        //    - Zero
1378        //        Freeze all items.
1379        //    - Positive
1380        //        Freeze all the items with min violations.
1381        //    - Negative
1382        //        Freeze all the items with max violations.
1383
1384        for child in &mut unfrozen {
1385            match total_violation {
1386                v if v > 0.0 => child.frozen = child.violation > 0.0,
1387                v if v < 0.0 => child.frozen = child.violation < 0.0,
1388                _ => child.frozen = true,
1389            }
1390        }
1391
1392        // f. Return to the start of this loop.
1393    }
1394}
1395
1396/// Determine the hypothetical cross size of each item.
1397///
1398/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1399///
1400/// - [**Determine the hypothetical cross size of each item**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-item)
1401///   by performing layout with the used main size and the available space, treating auto as fit-content.
1402#[inline]
1403fn determine_hypothetical_cross_size(
1404    tree: &mut impl LayoutFlexboxContainer,
1405    line: &mut FlexLine,
1406    constants: &AlgoConstants,
1407    available_space: Size<AvailableSpace>,
1408) {
1409    for child in line.items.iter_mut() {
1410        let padding_border_sum = (child.padding + child.border).cross_axis_sum(constants.dir);
1411
1412        let child_known_main = constants.container_size.main(constants.dir).into();
1413
1414        // Sizes transferred through the aspect ratio clamp the hypothetical cross size
1415        // https://github.com/w3c/csswg-drafts/issues/10997
1416        let transferred_min_cross = child.min_size.maybe_apply_aspect_ratio(child.aspect_ratio).cross(constants.dir);
1417        let transferred_max_cross = child.max_size.maybe_apply_aspect_ratio(child.aspect_ratio).cross(constants.dir);
1418
1419        let child_cross = child
1420            .size
1421            .cross(constants.dir)
1422            .maybe_clamp(transferred_min_cross, transferred_max_cross)
1423            .maybe_max(padding_border_sum);
1424
1425        let child_available_cross = available_space
1426            .cross(constants.dir)
1427            .maybe_clamp(transferred_min_cross, transferred_max_cross)
1428            .maybe_max(padding_border_sum);
1429
1430        let child_inner_cross = child_cross.unwrap_or_else(|| {
1431            tree.measure_child_size(
1432                child.node,
1433                Size {
1434                    width: if constants.is_row { child.target_size.width.into() } else { child_cross },
1435                    height: if constants.is_row { child_cross } else { child.target_size.height.into() },
1436                },
1437                constants.node_inner_size,
1438                Size {
1439                    width: if constants.is_row { child_known_main } else { child_available_cross },
1440                    height: if constants.is_row { child_available_cross } else { child_known_main },
1441                },
1442                SizingMode::ContentSize,
1443                constants.dir.cross_axis(),
1444                Line::FALSE,
1445            )
1446            .maybe_clamp(transferred_min_cross, transferred_max_cross)
1447            .max(padding_border_sum)
1448        });
1449        let child_outer_cross = child_inner_cross + child.margin.cross_axis_sum(constants.dir);
1450
1451        child.hypothetical_inner_size.set_cross(constants.dir, child_inner_cross);
1452        child.hypothetical_outer_size.set_cross(constants.dir, child_outer_cross);
1453    }
1454}
1455
1456/// Calculate the base lines of the children.
1457#[inline]
1458fn calculate_children_base_lines(
1459    tree: &mut impl LayoutFlexboxContainer,
1460    node_size: Size<Option<f32>>,
1461    available_space: Size<AvailableSpace>,
1462    flex_lines: &mut [FlexLine],
1463    constants: &AlgoConstants,
1464) {
1465    // Only compute baselines for flex rows because we only support baseline alignment in the cross axis
1466    // where that axis is also the inline axis
1467    // TODO: this may need revisiting if/when we support vertical writing modes
1468    if !constants.is_row {
1469        return;
1470    }
1471
1472    for line in flex_lines {
1473        // If a flex line has one or zero items participating in baseline alignment then baseline alignment is a no-op so we skip
1474        let line_baseline_child_count =
1475            line.items.iter().filter(|child| child.align_self == AlignSelf::BASELINE).count();
1476        if line_baseline_child_count <= 1 {
1477            continue;
1478        }
1479
1480        for child in line.items.iter_mut() {
1481            // Only calculate baselines for children participating in baseline alignment
1482            if child.align_self != AlignSelf::BASELINE {
1483                continue;
1484            }
1485
1486            let measured_size_and_baselines = tree.perform_child_layout(
1487                child.node,
1488                Size {
1489                    width: if constants.is_row {
1490                        child.target_size.width.into()
1491                    } else {
1492                        child.hypothetical_inner_size.width.into()
1493                    },
1494                    height: if constants.is_row {
1495                        child.hypothetical_inner_size.height.into()
1496                    } else {
1497                        child.target_size.height.into()
1498                    },
1499                },
1500                constants.node_inner_size,
1501                Size {
1502                    width: if constants.is_row {
1503                        constants.container_size.width.into()
1504                    } else {
1505                        available_space.width.maybe_set(node_size.width)
1506                    },
1507                    height: if constants.is_row {
1508                        available_space.height.maybe_set(node_size.height)
1509                    } else {
1510                        constants.container_size.height.into()
1511                    },
1512                },
1513                SizingMode::ContentSize,
1514                Line::FALSE,
1515            );
1516
1517            let baseline = measured_size_and_baselines.first_baselines.y;
1518            let height = measured_size_and_baselines.size.height;
1519
1520            // Scroll containers' baselines are determined from their content as if scrolled to the
1521            // initial position, but are additionally clamped to their border box.
1522            // See https://github.com/w3c/csswg-drafts/issues/7660
1523            let baseline = if child.overflow.y.is_scroll_container() {
1524                baseline.unwrap_or(height).min(height).max(0.0)
1525            } else {
1526                baseline.unwrap_or(height)
1527            };
1528
1529            child.baseline = baseline + child.margin.top;
1530        }
1531    }
1532}
1533
1534/// Calculate the cross size of each flex line.
1535///
1536/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1537///
1538/// - [**Calculate the cross size of each flex line**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-line).
1539#[inline]
1540fn calculate_cross_size(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
1541    // If the flex container is single-line and has a definite cross size,
1542    // the cross size of the flex line is the flex container’s inner cross size.
1543    if !constants.is_wrap && node_size.cross(constants.dir).is_some() {
1544        let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
1545        let cross_min_size = constants.min_size.cross(constants.dir);
1546        let cross_max_size = constants.max_size.cross(constants.dir);
1547        flex_lines[0].cross_size = node_size
1548            .cross(constants.dir)
1549            .maybe_clamp(cross_min_size, cross_max_size)
1550            .maybe_sub(cross_axis_padding_border)
1551            .maybe_max(0.0)
1552            .unwrap_or(0.0);
1553    } else {
1554        // Otherwise, for each flex line:
1555        //
1556        //    1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
1557        //       align-self is baseline, and whose cross-axis margins are both non-auto. Find the
1558        //       largest of the distances between each item’s baseline and its hypothetical outer
1559        //       cross-start edge, and the largest of the distances between each item’s baseline
1560        //       and its hypothetical outer cross-end edge, and sum these two values.
1561
1562        //    2. Among all the items not collected by the previous step, find the largest
1563        //       outer hypothetical cross size.
1564
1565        //    3. The used cross-size of the flex line is the largest of the numbers found in the
1566        //       previous two steps and zero.
1567        for line in flex_lines.iter_mut() {
1568            let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
1569            line.cross_size = line
1570                .items
1571                .iter()
1572                .map(|child| {
1573                    if child.align_self == AlignSelf::BASELINE
1574                        && !child.margin_is_auto.cross_start(constants.dir)
1575                        && !child.margin_is_auto.cross_end(constants.dir)
1576                    {
1577                        max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
1578                    } else {
1579                        child.hypothetical_outer_size.cross(constants.dir)
1580                    }
1581                })
1582                .fold(0.0, |acc, x| acc.max(x));
1583        }
1584
1585        // If the flex container is single-line, then clamp the line’s cross-size to be within the container’s computed min and max cross sizes.
1586        // Note that if CSS 2.1’s definition of min/max-width/height applied more generally, this behavior would fall out automatically.
1587        if !constants.is_wrap {
1588            let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
1589            let cross_min_size = constants.min_size.cross(constants.dir);
1590            let cross_max_size = constants.max_size.cross(constants.dir);
1591            flex_lines[0].cross_size = flex_lines[0].cross_size.maybe_clamp(
1592                cross_min_size.maybe_sub(cross_axis_padding_border),
1593                cross_max_size.maybe_sub(cross_axis_padding_border),
1594            );
1595        }
1596    }
1597}
1598
1599/// Handle 'align-content: stretch'.
1600///
1601/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1602///
1603/// - [**Handle 'align-content: stretch'**](https://www.w3.org/TR/css-flexbox-1/#algo-line-stretch). If the flex container has a definite cross size, align-content is stretch,
1604///   and the sum of the flex lines' cross sizes is less than the flex container’s inner cross size,
1605///   increase the cross size of each flex line by equal amounts such that the sum of their cross sizes exactly equals the flex container’s inner cross size.
1606#[inline]
1607fn handle_align_content_stretch(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
1608    if constants.align_content == AlignContent::STRETCH {
1609        let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
1610        let cross_min_size = constants.min_size.cross(constants.dir);
1611        let cross_max_size = constants.max_size.cross(constants.dir);
1612        let container_min_inner_cross = node_size
1613            .cross(constants.dir)
1614            .or(cross_min_size)
1615            .maybe_clamp(cross_min_size, cross_max_size)
1616            .maybe_sub(cross_axis_padding_border)
1617            .maybe_max(0.0)
1618            .unwrap_or(0.0);
1619
1620        let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
1621        let lines_total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>() + total_cross_axis_gap;
1622
1623        if lines_total_cross < container_min_inner_cross {
1624            let remaining = container_min_inner_cross - lines_total_cross;
1625            let addition = remaining / flex_lines.len() as f32;
1626            flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
1627        }
1628    }
1629}
1630
1631/// Determine the used cross size of each flex item.
1632///
1633/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
1634///
1635/// - [**Determine the used cross size of each flex item**](https://www.w3.org/TR/css-flexbox-1/#algo-stretch). If a flex item has align-self: stretch, its computed cross size property is auto,
1636///   and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s used min and max cross sizes.
1637///   Otherwise, the used cross size is the item’s hypothetical cross size.
1638///
1639///   If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.
1640///
1641///   **Note that this step does not affect the main size of the flex item, even if it has an intrinsic aspect ratio**.
1642#[inline]
1643fn determine_used_cross_size(
1644    tree: &impl LayoutFlexboxContainer,
1645    flex_lines: &mut [FlexLine],
1646    constants: &AlgoConstants,
1647) {
1648    for line in flex_lines {
1649        let line_cross_size = line.cross_size;
1650
1651        for child in line.items.iter_mut() {
1652            let child_style = tree.get_flexbox_child_style(child.node);
1653            child.target_size.set_cross(
1654                constants.dir,
1655                if child.align_self == AlignSelf::STRETCH
1656                    && !child.margin_is_auto.cross_start(constants.dir)
1657                    && !child.margin_is_auto.cross_end(constants.dir)
1658                    && child_style.size().cross(constants.dir).is_auto()
1659                {
1660                    // For some reason this particular usage of max_width is an exception to the rule that max_width's transfer
1661                    // using the aspect_ratio (if set). Both Chrome and Firefox agree on this. And reading the spec, it seems like
1662                    // a reasonable interpretation. Although it seems to me that the spec *should* apply aspect_ratio here.
1663                    let padding = child_style
1664                        .padding()
1665                        .resolve_or_zero(constants.node_inner_size, |val, basis| tree.calc(val, basis));
1666                    let border = child_style
1667                        .border()
1668                        .resolve_or_zero(constants.node_inner_size, |val, basis| tree.calc(val, basis));
1669                    let pb_sum = (padding + border).sum_axes();
1670                    let box_sizing_adjustment =
1671                        if child_style.box_sizing() == BoxSizing::ContentBox { pb_sum } else { Size::ZERO };
1672
1673                    let max_size_ignoring_aspect_ratio = child_style
1674                        .max_size()
1675                        .maybe_resolve(constants.node_inner_size, |val, basis| tree.calc(val, basis))
1676                        .maybe_add(box_sizing_adjustment);
1677
1678                    (line_cross_size - child.margin.cross_axis_sum(constants.dir)).maybe_clamp(
1679                        child.min_size.cross(constants.dir),
1680                        max_size_ignoring_aspect_ratio.cross(constants.dir),
1681                    )
1682                } else {
1683                    child.hypothetical_inner_size.cross(constants.dir)
1684                },
1685            );
1686
1687            child.outer_target_size.set_cross(
1688                constants.dir,
1689                child.target_size.cross(constants.dir) + child.margin.cross_axis_sum(constants.dir),
1690            );
1691        }
1692    }
1693}
1694
1695/// Distribute any remaining free space.
1696///
1697/// # [9.5. Main-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#main-alignment)
1698///
1699/// - [**Distribute any remaining free space**](https://www.w3.org/TR/css-flexbox-1/#algo-main-align). For each flex line:
1700///
1701///   1. If the remaining free space is positive and at least one main-axis margin on this line is `auto`, distribute the free space equally among these margins.
1702///      Otherwise, set all `auto` margins to zero.
1703///
1704///   2. Align the items along the main-axis per `justify-content`.
1705#[inline]
1706fn distribute_remaining_free_space(flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
1707    for line in flex_lines {
1708        let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
1709        let used_space: f32 = total_main_axis_gap
1710            + line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum::<f32>();
1711        let free_space = constants.inner_container_size.main(constants.dir) - used_space;
1712        let mut num_auto_margins = 0;
1713
1714        for child in line.items.iter_mut() {
1715            if child.margin_is_auto.main_start(constants.dir) {
1716                num_auto_margins += 1;
1717            }
1718            if child.margin_is_auto.main_end(constants.dir) {
1719                num_auto_margins += 1;
1720            }
1721        }
1722
1723        if free_space > 0.0 && num_auto_margins > 0 {
1724            let margin = free_space / num_auto_margins as f32;
1725
1726            for child in line.items.iter_mut() {
1727                if child.margin_is_auto.main_start(constants.dir) {
1728                    if constants.is_row {
1729                        child.margin.left = margin;
1730                    } else {
1731                        child.margin.top = margin;
1732                    }
1733                }
1734                if child.margin_is_auto.main_end(constants.dir) {
1735                    if constants.is_row {
1736                        child.margin.right = margin;
1737                    } else {
1738                        child.margin.bottom = margin;
1739                    }
1740                }
1741            }
1742        }
1743
1744        let num_items = line.items.len();
1745        let layout_reverse = constants.dir.is_reverse();
1746        let gap = constants.gap.main(constants.dir);
1747        let raw_justify_content_mode = constants.justify_content.unwrap_or(JustifyContent::FLEX_START);
1748        let justify_content_mode = apply_alignment_fallback(free_space, num_items, raw_justify_content_mode);
1749
1750        let justify_item = |(i, child): (usize, &mut FlexItem)| {
1751            child.offset_main =
1752                compute_alignment_offset(free_space, num_items, gap, justify_content_mode, layout_reverse, i == 0);
1753        };
1754
1755        if layout_reverse {
1756            line.items.iter_mut().rev().enumerate().for_each(justify_item);
1757        } else {
1758            line.items.iter_mut().enumerate().for_each(justify_item);
1759        }
1760    }
1761}
1762
1763/// Resolve cross-axis `auto` margins.
1764///
1765/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1766///
1767/// - [**Resolve cross-axis `auto` margins**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-margins).
1768///   If a flex item has auto cross-axis margins:
1769///
1770///   - If its outer cross size (treating those auto margins as zero) is less than the cross size of its flex line,
1771///     distribute the difference in those sizes equally to the auto margins.
1772///
1773///   - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis) is auto, set it to zero.
1774///     Set the opposite margin so that the outer cross size of the item equals the cross size of its flex line.
1775#[inline]
1776fn resolve_cross_axis_auto_margins(flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
1777    for line in flex_lines {
1778        let line_cross_size = line.cross_size;
1779        let max_baseline: f32 = line.items.iter_mut().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
1780
1781        for child in line.items.iter_mut() {
1782            let free_space = line_cross_size - child.outer_target_size.cross(constants.dir);
1783
1784            if child.margin_is_auto.cross_start(constants.dir) && child.margin_is_auto.cross_end(constants.dir) {
1785                if constants.is_row {
1786                    child.margin.top = free_space / 2.0;
1787                    child.margin.bottom = free_space / 2.0;
1788                } else {
1789                    child.margin.left = free_space / 2.0;
1790                    child.margin.right = free_space / 2.0;
1791                }
1792            } else if child.margin_is_auto.cross_start(constants.dir) {
1793                if constants.is_row {
1794                    child.margin.top = free_space;
1795                } else {
1796                    child.margin.left = free_space;
1797                }
1798            } else if child.margin_is_auto.cross_end(constants.dir) {
1799                if constants.is_row {
1800                    child.margin.bottom = free_space;
1801                } else {
1802                    child.margin.right = free_space;
1803                }
1804            } else {
1805                // 14. Align all flex items along the cross-axis.
1806                child.offset_cross = align_flex_items_along_cross_axis(child, free_space, max_baseline, constants);
1807            }
1808        }
1809    }
1810}
1811
1812/// Align all flex items along the cross-axis.
1813///
1814/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1815///
1816/// - [**Align all flex items along the cross-axis**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-align) per `align-self`,
1817///   if neither of the item's cross-axis margins are `auto`.
1818#[inline]
1819fn align_flex_items_along_cross_axis(
1820    child: &FlexItem,
1821    free_space: f32,
1822    max_baseline: f32,
1823    constants: &AlgoConstants,
1824) -> f32 {
1825    let cross_axis_should_reverse = constants.is_column && matches!(constants.layout_direction, Direction::Rtl);
1826
1827    // If align-self uses a "safe" overflow-position keyword and the item would overflow its
1828    // line cross size, fall back to logical Start to avoid data loss. See CSS Box Alignment 3
1829    // §4.3 <https://www.w3.org/TR/css-align-3/#overflow-values>. Otherwise, drop the safety
1830    // field so the match below operates on a bare keyword and stays exhaustive.
1831    let align_keyword = if child.align_self.is_safe() && free_space < 0.0 {
1832        AlignItemsKeyword::Start
1833    } else {
1834        child.align_self.keyword
1835    };
1836
1837    match align_keyword {
1838        AlignItemsKeyword::Start => {
1839            if cross_axis_should_reverse {
1840                free_space
1841            } else {
1842                0.0
1843            }
1844        }
1845        AlignItemsKeyword::FlexStart => {
1846            if constants.is_wrap_reverse ^ cross_axis_should_reverse {
1847                free_space
1848            } else {
1849                0.0
1850            }
1851        }
1852        AlignItemsKeyword::End => {
1853            if cross_axis_should_reverse {
1854                0.0
1855            } else {
1856                free_space
1857            }
1858        }
1859        AlignItemsKeyword::FlexEnd => {
1860            if constants.is_wrap_reverse ^ cross_axis_should_reverse {
1861                0.0
1862            } else {
1863                free_space
1864            }
1865        }
1866        AlignItemsKeyword::Center => free_space / 2.0,
1867        AlignItemsKeyword::Baseline => {
1868            if constants.is_row {
1869                max_baseline - child.baseline
1870            } else {
1871                // Until we support vertical writing modes, baseline alignment only makes sense if
1872                // the constants.direction is row, so we treat it as flex-start alignment in columns.
1873                let baseline_column_should_reverse = cross_axis_should_reverse && !constants.is_wrap;
1874                if constants.is_wrap_reverse ^ baseline_column_should_reverse {
1875                    free_space
1876                } else {
1877                    0.0
1878                }
1879            }
1880        }
1881        AlignItemsKeyword::Stretch => {
1882            if constants.is_wrap_reverse ^ cross_axis_should_reverse {
1883                free_space
1884            } else {
1885                0.0
1886            }
1887        }
1888    }
1889}
1890
1891/// Determine the flex container’s used cross size.
1892///
1893/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1894///
1895/// - [**Determine the flex container’s used cross size**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-container):
1896///
1897///     - If the cross size property is a definite size, use that, clamped by the used min and max cross sizes of the flex container.
1898///
1899///     - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used min and max cross sizes of the flex container.
1900#[inline]
1901#[must_use]
1902fn determine_container_cross_size(
1903    flex_lines: &[FlexLine],
1904    node_size: Size<Option<f32>>,
1905    constants: &mut AlgoConstants,
1906) -> f32 {
1907    let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
1908    let total_line_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>();
1909
1910    let padding_border_sum = constants.content_box_inset.cross_axis_sum(constants.dir);
1911    let cross_scrollbar_gutter = constants.scrollbar_gutter.cross(constants.dir);
1912    let min_cross_size = constants.min_size.cross(constants.dir);
1913    let max_cross_size = constants.max_size.cross(constants.dir);
1914    let outer_container_size = node_size
1915        .cross(constants.dir)
1916        .unwrap_or(total_line_cross_size + total_cross_axis_gap + padding_border_sum)
1917        .maybe_clamp(min_cross_size, max_cross_size)
1918        .max(padding_border_sum - cross_scrollbar_gutter);
1919    let inner_container_size = f32_max(outer_container_size - padding_border_sum, 0.0);
1920
1921    constants.container_size.set_cross(constants.dir, outer_container_size);
1922    constants.inner_container_size.set_cross(constants.dir, inner_container_size);
1923
1924    total_line_cross_size
1925}
1926
1927/// Align all flex lines per `align-content`.
1928///
1929/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
1930///
1931/// - [**Align all flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-align) per `align-content`.
1932#[inline]
1933fn align_flex_lines_per_align_content(flex_lines: &mut [FlexLine], constants: &AlgoConstants, total_cross_size: f32) {
1934    let num_lines = flex_lines.len();
1935    let gap = constants.gap.cross(constants.dir);
1936    let total_cross_axis_gap = sum_axis_gaps(gap, num_lines);
1937    let free_space = constants.inner_container_size.cross(constants.dir) - total_cross_size - total_cross_axis_gap;
1938
1939    let align_content_mode = apply_alignment_fallback(free_space, num_lines, constants.align_content);
1940
1941    let align_line = |(i, line): (usize, &mut FlexLine)| {
1942        line.offset_cross =
1943            compute_alignment_offset(free_space, num_lines, gap, align_content_mode, constants.is_wrap_reverse, i == 0);
1944    };
1945
1946    if constants.is_wrap_reverse {
1947        flex_lines.iter_mut().rev().enumerate().for_each(align_line);
1948    } else {
1949        flex_lines.iter_mut().enumerate().for_each(align_line);
1950    }
1951}
1952
1953/// Calculates the layout for a flex-item
1954#[allow(clippy::too_many_arguments)]
1955fn calculate_flex_item(
1956    tree: &mut impl LayoutFlexboxContainer,
1957    item: &mut FlexItem,
1958    total_offset_main: &mut f32,
1959    total_offset_cross: f32,
1960    line_offset_cross: f32,
1961    #[cfg(feature = "content_size")] total_content_size: &mut Size<f32>,
1962    container_size: Size<f32>,
1963    node_inner_size: Size<Option<f32>>,
1964    direction: FlexDirection,
1965    layout_direction: Direction,
1966) {
1967    let layout_output = tree.perform_child_layout(
1968        item.node,
1969        item.target_size.map(|s| s.into()),
1970        node_inner_size,
1971        container_size.map(|s| s.into()),
1972        SizingMode::ContentSize,
1973        Line::FALSE,
1974    );
1975    let LayoutOutput {
1976        size,
1977        #[cfg(feature = "content_size")]
1978        content_size,
1979        ..
1980    } = layout_output;
1981
1982    let is_rtl_row = direction.is_row() && layout_direction.is_rtl();
1983    let is_rtl_column = direction.is_column() && layout_direction.is_rtl();
1984    let main_relative_inset = if is_rtl_row {
1985        item.inset.main_end(direction).or(item.inset.main_start(direction).map(|pos| -pos)).unwrap_or(0.0)
1986    } else {
1987        item.inset.main_start(direction).or(item.inset.main_end(direction).map(|pos| -pos)).unwrap_or(0.0)
1988    };
1989    let cross_relative_inset = if is_rtl_column {
1990        item.inset.cross_end(direction).map(|pos| -pos).or(item.inset.cross_start(direction)).unwrap_or(0.0)
1991    } else {
1992        item.inset.cross_start(direction).or(item.inset.cross_end(direction).map(|pos| -pos)).unwrap_or(0.0)
1993    };
1994    let effective_line_offset_cross = if is_rtl_column { 0.0 } else { line_offset_cross };
1995
1996    let offset_main = if is_rtl_row {
1997        *total_offset_main - item.offset_main - item.margin.main_end(direction) - main_relative_inset - size.width
1998    } else {
1999        *total_offset_main + item.offset_main + item.margin.main_start(direction) + main_relative_inset
2000    };
2001
2002    let offset_cross = total_offset_cross
2003        + item.offset_cross
2004        + effective_line_offset_cross
2005        + item.margin.cross_start(direction)
2006        + cross_relative_inset;
2007
2008    if direction.is_row() {
2009        let baseline_offset_cross =
2010            total_offset_cross + item.offset_cross + effective_line_offset_cross + item.margin.cross_start(direction);
2011        // Scroll containers' baselines are determined from their content as if scrolled to the initial
2012        // position, but are additionally clamped to their border box.
2013        // See https://github.com/w3c/csswg-drafts/issues/7660
2014        let inner_baseline = {
2015            let baseline = layout_output.first_baselines.y.unwrap_or(size.height);
2016            if item.overflow.y.is_scroll_container() {
2017                baseline.min(size.height).max(0.0)
2018            } else {
2019                baseline
2020            }
2021        };
2022        item.baseline = baseline_offset_cross + inner_baseline;
2023    } else {
2024        let baseline_offset_main = *total_offset_main + item.offset_main + item.margin.main_start(direction);
2025        let inner_baseline = layout_output.first_baselines.y.unwrap_or(size.height);
2026        item.baseline = baseline_offset_main + inner_baseline;
2027    }
2028
2029    let location = if direction.is_row() {
2030        Point { x: offset_main, y: offset_cross }
2031    } else {
2032        Point { x: offset_cross, y: offset_main }
2033    };
2034    let scrollbar_size = Size {
2035        width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
2036        height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
2037    };
2038
2039    tree.set_unrounded_layout(
2040        item.node,
2041        &Layout {
2042            order: item.order,
2043            size,
2044            #[cfg(feature = "content_size")]
2045            content_size,
2046            scrollbar_size,
2047            location,
2048            padding: item.padding,
2049            border: item.border,
2050            margin: item.margin,
2051        },
2052    );
2053
2054    if is_rtl_row {
2055        *total_offset_main -= item.offset_main + item.margin.main_axis_sum(direction) + size.main(direction);
2056    } else {
2057        *total_offset_main += item.offset_main + item.margin.main_axis_sum(direction) + size.main(direction);
2058    }
2059
2060    #[cfg(feature = "content_size")]
2061    {
2062        let contribution_location = if layout_direction.is_rtl() {
2063            Point { x: container_size.width - (location.x + size.width), y: location.y }
2064        } else {
2065            location
2066        };
2067        *total_content_size = total_content_size.f32_max(compute_content_size_contribution(
2068            contribution_location,
2069            size,
2070            content_size,
2071            item.overflow,
2072        ));
2073    }
2074}
2075
2076/// Calculates the layout line
2077#[allow(clippy::too_many_arguments)]
2078fn calculate_layout_line(
2079    tree: &mut impl LayoutFlexboxContainer,
2080    line: &mut FlexLine,
2081    total_offset_cross: &mut f32,
2082    #[cfg(feature = "content_size")] content_size: &mut Size<f32>,
2083    container_size: Size<f32>,
2084    node_inner_size: Size<Option<f32>>,
2085    padding_border: Rect<f32>,
2086    direction: FlexDirection,
2087    layout_direction: Direction,
2088) {
2089    let mut total_offset_main = if layout_direction.is_rtl() && direction.is_row() {
2090        container_size.width - padding_border.main_end(direction)
2091    } else {
2092        padding_border.main_start(direction)
2093    };
2094    let line_offset_cross = line.offset_cross;
2095
2096    let is_rtl_column = layout_direction.is_rtl() && direction.is_column();
2097    if is_rtl_column {
2098        *total_offset_cross -= line_offset_cross + line.cross_size;
2099    }
2100
2101    if direction.is_reverse() {
2102        for item in line.items.iter_mut().rev() {
2103            calculate_flex_item(
2104                tree,
2105                item,
2106                &mut total_offset_main,
2107                *total_offset_cross,
2108                line_offset_cross,
2109                #[cfg(feature = "content_size")]
2110                content_size,
2111                container_size,
2112                node_inner_size,
2113                direction,
2114                layout_direction,
2115            );
2116        }
2117    } else {
2118        for item in line.items.iter_mut() {
2119            calculate_flex_item(
2120                tree,
2121                item,
2122                &mut total_offset_main,
2123                *total_offset_cross,
2124                line_offset_cross,
2125                #[cfg(feature = "content_size")]
2126                content_size,
2127                container_size,
2128                node_inner_size,
2129                direction,
2130                layout_direction,
2131            );
2132        }
2133    }
2134
2135    if !is_rtl_column {
2136        *total_offset_cross += line_offset_cross + line.cross_size;
2137    }
2138}
2139
2140/// Do a final layout pass and collect the resulting layouts.
2141#[inline]
2142fn final_layout_pass(
2143    tree: &mut impl LayoutFlexboxContainer,
2144    flex_lines: &mut [FlexLine],
2145    constants: &AlgoConstants,
2146) -> Size<f32> {
2147    let mut total_offset_cross = if constants.is_column && constants.layout_direction.is_rtl() {
2148        constants.container_size.width - constants.content_box_inset.cross_end(constants.dir)
2149    } else {
2150        constants.content_box_inset.cross_start(constants.dir)
2151    };
2152
2153    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
2154    let mut content_size = Size::ZERO;
2155
2156    if constants.is_wrap_reverse {
2157        for line in flex_lines.iter_mut().rev() {
2158            calculate_layout_line(
2159                tree,
2160                line,
2161                &mut total_offset_cross,
2162                #[cfg(feature = "content_size")]
2163                &mut content_size,
2164                constants.container_size,
2165                constants.node_inner_size,
2166                constants.content_box_inset,
2167                constants.dir,
2168                constants.layout_direction,
2169            );
2170        }
2171    } else {
2172        for line in flex_lines.iter_mut() {
2173            calculate_layout_line(
2174                tree,
2175                line,
2176                &mut total_offset_cross,
2177                #[cfg(feature = "content_size")]
2178                &mut content_size,
2179                constants.container_size,
2180                constants.node_inner_size,
2181                constants.content_box_inset,
2182                constants.dir,
2183                constants.layout_direction,
2184            );
2185        }
2186    }
2187
2188    content_size.width += if constants.layout_direction.is_rtl() {
2189        constants.content_box_inset.left - constants.border.left - constants.scrollbar_gutter.x
2190    } else {
2191        constants.content_box_inset.right - constants.border.right - constants.scrollbar_gutter.x
2192    };
2193    content_size.height += constants.content_box_inset.bottom - constants.border.bottom - constants.scrollbar_gutter.y;
2194
2195    content_size
2196}
2197
2198/// Perform absolute layout on all absolutely positioned children.
2199#[inline]
2200fn perform_absolute_layout_on_absolute_children(
2201    tree: &mut impl LayoutFlexboxContainer,
2202    node: NodeId,
2203    constants: &AlgoConstants,
2204) -> Size<f32> {
2205    let container_width = constants.container_size.width;
2206    let container_height = constants.container_size.height;
2207    let inset_relative_size =
2208        constants.container_size - constants.border.sum_axes() - constants.scrollbar_gutter.into();
2209
2210    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
2211    let mut content_size = Size::ZERO;
2212
2213    for order in 0..tree.child_count(node) {
2214        let child = tree.get_child_id(node, order);
2215        let child_style = tree.get_flexbox_child_style(child);
2216
2217        // Skip items that are display:none or are not position:absolute
2218        if child_style.box_generation_mode() == BoxGenerationMode::None || child_style.position() != Position::Absolute
2219        {
2220            continue;
2221        }
2222
2223        let overflow = child_style.overflow();
2224        let scrollbar_width = child_style.scrollbar_width();
2225        let aspect_ratio = child_style.aspect_ratio();
2226        let align_self = child_style.align_self().unwrap_or(constants.align_items);
2227        let margin = child_style
2228            .margin()
2229            .map(|margin| margin.resolve_to_option(inset_relative_size.width, |val, basis| tree.calc(val, basis)));
2230        let padding =
2231            child_style.padding().resolve_or_zero(Some(inset_relative_size.width), |val, basis| tree.calc(val, basis));
2232        let border =
2233            child_style.border().resolve_or_zero(Some(inset_relative_size.width), |val, basis| tree.calc(val, basis));
2234        let padding_border_sum = (padding + border).sum_axes();
2235        let box_sizing_adjustment =
2236            if child_style.box_sizing() == BoxSizing::ContentBox { padding_border_sum } else { Size::ZERO };
2237
2238        // Resolve inset
2239        // Insets are resolved against the container size minus border
2240        let left =
2241            child_style.inset().left.maybe_resolve(inset_relative_size.width, |val, basis| tree.calc(val, basis));
2242        let right =
2243            child_style.inset().right.maybe_resolve(inset_relative_size.width, |val, basis| tree.calc(val, basis));
2244        let top = child_style.inset().top.maybe_resolve(inset_relative_size.height, |val, basis| tree.calc(val, basis));
2245        let bottom =
2246            child_style.inset().bottom.maybe_resolve(inset_relative_size.height, |val, basis| tree.calc(val, basis));
2247
2248        // Compute known dimensions from min/max/inherent size styles
2249        let style_size = child_style
2250            .size()
2251            .maybe_resolve(inset_relative_size, |val, basis| tree.calc(val, basis))
2252            .maybe_apply_aspect_ratio(aspect_ratio)
2253            .maybe_add(box_sizing_adjustment);
2254        let min_size = child_style
2255            .min_size()
2256            .maybe_resolve(inset_relative_size, |val, basis| tree.calc(val, basis))
2257            .maybe_apply_aspect_ratio(aspect_ratio)
2258            .maybe_add(box_sizing_adjustment)
2259            .or(padding_border_sum.map(Some))
2260            .maybe_max(padding_border_sum);
2261        let max_size = child_style
2262            .max_size()
2263            .maybe_resolve(inset_relative_size, |val, basis| tree.calc(val, basis))
2264            .maybe_apply_aspect_ratio(aspect_ratio)
2265            .maybe_add(box_sizing_adjustment);
2266        let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
2267
2268        drop(child_style);
2269
2270        // Fill in width from left/right and reapply aspect ratio if:
2271        //   - Width is not already known
2272        //   - Item has both left and right inset properties set
2273        if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
2274            let new_width_raw = inset_relative_size.width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
2275            known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
2276            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
2277        }
2278
2279        // Fill in height from top/bottom and reapply aspect ratio if:
2280        //   - Height is not already known
2281        //   - Item has both top and bottom inset properties set
2282        if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
2283            let new_height_raw =
2284                inset_relative_size.height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
2285            known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
2286            known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
2287        }
2288        let measured_size = tree.measure_child_size_both(
2289            child,
2290            known_dimensions,
2291            constants.node_inner_size,
2292            Size {
2293                width: AvailableSpace::Definite(container_width.maybe_clamp(min_size.width, max_size.width)),
2294                height: AvailableSpace::Definite(container_height.maybe_clamp(min_size.height, max_size.height)),
2295            },
2296            SizingMode::InherentSize,
2297            Line::FALSE,
2298        );
2299        let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
2300
2301        let layout_output = tree.perform_child_layout(
2302            child,
2303            final_size.map(Some),
2304            constants.node_inner_size,
2305            Size {
2306                width: AvailableSpace::Definite(container_width.maybe_clamp(min_size.width, max_size.width)),
2307                height: AvailableSpace::Definite(container_height.maybe_clamp(min_size.height, max_size.height)),
2308            },
2309            SizingMode::InherentSize,
2310            Line::FALSE,
2311        );
2312
2313        let non_auto_margin = margin.map(|m| m.unwrap_or(0.0));
2314
2315        let free_space = Size {
2316            width: constants.container_size.width - final_size.width - non_auto_margin.horizontal_axis_sum(),
2317            height: constants.container_size.height - final_size.height - non_auto_margin.vertical_axis_sum(),
2318        }
2319        .f32_max(Size::ZERO);
2320
2321        // Expand auto margins to fill available space
2322        let resolved_margin = {
2323            let auto_margin_size = Size {
2324                width: {
2325                    let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
2326                    if auto_margin_count > 0 {
2327                        free_space.width / auto_margin_count as f32
2328                    } else {
2329                        0.0
2330                    }
2331                },
2332                height: {
2333                    let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
2334                    if auto_margin_count > 0 {
2335                        free_space.height / auto_margin_count as f32
2336                    } else {
2337                        0.0
2338                    }
2339                },
2340            };
2341
2342            Rect {
2343                left: margin.left.unwrap_or(auto_margin_size.width),
2344                right: margin.right.unwrap_or(auto_margin_size.width),
2345                top: margin.top.unwrap_or(auto_margin_size.height),
2346                bottom: margin.bottom.unwrap_or(auto_margin_size.height),
2347            }
2348        };
2349
2350        // Determine flex-relative insets
2351        let (start_main, end_main) = if constants.is_row { (left, right) } else { (top, bottom) };
2352        let (start_cross, end_cross) = if constants.is_row { (top, bottom) } else { (left, right) };
2353        let main_axis_is_horizontal = constants.is_row;
2354        let cross_axis_is_horizontal = !constants.is_row;
2355        let main_is_rtl = main_axis_is_horizontal && constants.layout_direction.is_rtl();
2356        let cross_is_rtl = cross_axis_is_horizontal && constants.layout_direction.is_rtl();
2357        let main_axis_flex_start_reversed = constants.dir.is_reverse() ^ main_is_rtl;
2358        let cross_axis_flex_start_reversed = constants.is_wrap_reverse ^ cross_is_rtl;
2359        let main_start_scrollbar_offset =
2360            if main_is_rtl { constants.scrollbar_gutter.main(constants.dir) } else { 0.0 };
2361        let cross_start_scrollbar_offset =
2362            if cross_is_rtl { constants.scrollbar_gutter.cross(constants.dir) } else { 0.0 };
2363        let main_end_scrollbar_offset = if main_is_rtl { 0.0 } else { constants.scrollbar_gutter.main(constants.dir) };
2364        let cross_end_scrollbar_offset =
2365            if cross_is_rtl { 0.0 } else { constants.scrollbar_gutter.cross(constants.dir) };
2366
2367        // Apply main-axis alignment
2368        // let free_main_space = free_space.main(constants.dir) - resolved_margin.main_axis_sum(constants.dir);
2369        let offset_main = if start_main.is_some() || end_main.is_some() {
2370            if main_is_rtl && end_main.is_some() {
2371                constants.container_size.main(constants.dir)
2372                    - constants.border.main_end(constants.dir)
2373                    - main_end_scrollbar_offset
2374                    - final_size.main(constants.dir)
2375                    - end_main.unwrap_or(0.0)
2376                    - resolved_margin.main_end(constants.dir)
2377            } else if let Some(start) = start_main {
2378                start
2379                    + constants.border.main_start(constants.dir)
2380                    + main_start_scrollbar_offset
2381                    + resolved_margin.main_start(constants.dir)
2382            } else {
2383                constants.container_size.main(constants.dir)
2384                    - constants.border.main_end(constants.dir)
2385                    - main_end_scrollbar_offset
2386                    - final_size.main(constants.dir)
2387                    - end_main.unwrap_or(0.0)
2388                    - resolved_margin.main_end(constants.dir)
2389            }
2390        } else {
2391            // Stretch is an invalid value for justify_content in the flexbox algorithm, so we
2392            // treat it as if it wasn't set (and thus we default to FlexStart behaviour).
2393            //
2394            // The `safe` overflow-position keyword is intentionally NOT applied here, even when
2395            // the abs-positioned item would overflow the main axis: Chrome does not apply safe
2396            // fallback to `justify-content` on absolutely-positioned flex items (only the
2397            // cross-axis `align-self` does so). Matching the layout authority over a strict
2398            // spec read keeps gentest fixtures green; reconsider if Chromium changes behavior.
2399            match (constants.justify_content.unwrap_or(JustifyContent::START).keyword(), main_axis_flex_start_reversed)
2400            {
2401                (AlignContentKeyword::SpaceBetween, _)
2402                | (AlignContentKeyword::Stretch, false)
2403                | (AlignContentKeyword::FlexStart, false)
2404                | (AlignContentKeyword::FlexEnd, true) => {
2405                    constants.content_box_inset.main_start(constants.dir) + resolved_margin.main_start(constants.dir)
2406                }
2407                (AlignContentKeyword::Start, false) => {
2408                    constants.content_box_inset.main_start(constants.dir) + resolved_margin.main_start(constants.dir)
2409                }
2410                (AlignContentKeyword::Start, true) => {
2411                    constants.container_size.main(constants.dir)
2412                        - constants.content_box_inset.main_end(constants.dir)
2413                        - final_size.main(constants.dir)
2414                        - resolved_margin.main_end(constants.dir)
2415                }
2416                (AlignContentKeyword::End, false) => {
2417                    constants.container_size.main(constants.dir)
2418                        - constants.content_box_inset.main_end(constants.dir)
2419                        - final_size.main(constants.dir)
2420                        - resolved_margin.main_end(constants.dir)
2421                }
2422                (AlignContentKeyword::End, true) => {
2423                    constants.content_box_inset.main_start(constants.dir) + resolved_margin.main_start(constants.dir)
2424                }
2425                (AlignContentKeyword::FlexEnd, false)
2426                | (AlignContentKeyword::FlexStart, true)
2427                | (AlignContentKeyword::Stretch, true) => {
2428                    constants.container_size.main(constants.dir)
2429                        - constants.content_box_inset.main_end(constants.dir)
2430                        - final_size.main(constants.dir)
2431                        - resolved_margin.main_end(constants.dir)
2432                }
2433                (AlignContentKeyword::SpaceEvenly, _)
2434                | (AlignContentKeyword::SpaceAround, _)
2435                | (AlignContentKeyword::Center, _) => {
2436                    (constants.container_size.main(constants.dir)
2437                        + constants.content_box_inset.main_start(constants.dir)
2438                        - constants.content_box_inset.main_end(constants.dir)
2439                        - final_size.main(constants.dir)
2440                        + resolved_margin.main_start(constants.dir)
2441                        - resolved_margin.main_end(constants.dir))
2442                        / 2.0
2443                }
2444            }
2445        };
2446
2447        // Apply cross-axis alignment
2448        // let free_cross_space = free_space.cross(constants.dir) - resolved_margin.cross_axis_sum(constants.dir);
2449        let offset_cross = if start_cross.is_some() || end_cross.is_some() {
2450            if cross_is_rtl && end_cross.is_some() {
2451                constants.container_size.cross(constants.dir)
2452                    - constants.border.cross_end(constants.dir)
2453                    - cross_end_scrollbar_offset
2454                    - final_size.cross(constants.dir)
2455                    - end_cross.unwrap_or(0.0)
2456                    - resolved_margin.cross_end(constants.dir)
2457            } else if let Some(start) = start_cross {
2458                start
2459                    + constants.border.cross_start(constants.dir)
2460                    + cross_start_scrollbar_offset
2461                    + resolved_margin.cross_start(constants.dir)
2462            } else {
2463                constants.container_size.cross(constants.dir)
2464                    - constants.border.cross_end(constants.dir)
2465                    - cross_end_scrollbar_offset
2466                    - final_size.cross(constants.dir)
2467                    - end_cross.unwrap_or(0.0)
2468                    - resolved_margin.cross_end(constants.dir)
2469            }
2470        } else {
2471            let cross_overflows = final_size.cross(constants.dir) + resolved_margin.cross_axis_sum(constants.dir)
2472                > constants.container_size.cross(constants.dir)
2473                    - constants.content_box_inset.cross_axis_sum(constants.dir);
2474            let cross_keyword = resolve_self_alignment_safety(align_self, cross_overflows);
2475            match (cross_keyword, cross_axis_flex_start_reversed) {
2476                // Stretch alignment does not apply to absolutely positioned items
2477                // See "Example 3" at https://www.w3.org/TR/css-flexbox-1/#abspos-items
2478                // Note: Stretch should be FlexStart not Start when we support both
2479                (AlignItemsKeyword::Start, false) => {
2480                    constants.content_box_inset.cross_start(constants.dir) + resolved_margin.cross_start(constants.dir)
2481                }
2482                (AlignItemsKeyword::Start, true) => {
2483                    constants.container_size.cross(constants.dir)
2484                        - constants.content_box_inset.cross_end(constants.dir)
2485                        - final_size.cross(constants.dir)
2486                        - resolved_margin.cross_end(constants.dir)
2487                }
2488                (AlignItemsKeyword::End, false) => {
2489                    constants.container_size.cross(constants.dir)
2490                        - constants.content_box_inset.cross_end(constants.dir)
2491                        - final_size.cross(constants.dir)
2492                        - resolved_margin.cross_end(constants.dir)
2493                }
2494                (AlignItemsKeyword::End, true) => {
2495                    constants.content_box_inset.cross_start(constants.dir) + resolved_margin.cross_start(constants.dir)
2496                }
2497                (AlignItemsKeyword::Baseline | AlignItemsKeyword::Stretch | AlignItemsKeyword::FlexStart, false)
2498                | (AlignItemsKeyword::FlexEnd, true) => {
2499                    constants.content_box_inset.cross_start(constants.dir) + resolved_margin.cross_start(constants.dir)
2500                }
2501                (AlignItemsKeyword::Baseline | AlignItemsKeyword::Stretch | AlignItemsKeyword::FlexStart, true)
2502                | (AlignItemsKeyword::FlexEnd, false) => {
2503                    constants.container_size.cross(constants.dir)
2504                        - constants.content_box_inset.cross_end(constants.dir)
2505                        - final_size.cross(constants.dir)
2506                        - resolved_margin.cross_end(constants.dir)
2507                }
2508                (AlignItemsKeyword::Center, _) => {
2509                    (constants.container_size.cross(constants.dir)
2510                        + constants.content_box_inset.cross_start(constants.dir)
2511                        - constants.content_box_inset.cross_end(constants.dir)
2512                        - final_size.cross(constants.dir)
2513                        + resolved_margin.cross_start(constants.dir)
2514                        - resolved_margin.cross_end(constants.dir))
2515                        / 2.0
2516                }
2517            }
2518        };
2519
2520        let location = match constants.is_row {
2521            true => Point { x: offset_main, y: offset_cross },
2522            false => Point { x: offset_cross, y: offset_main },
2523        };
2524        let scrollbar_size = Size {
2525            width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
2526            height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
2527        };
2528        tree.set_unrounded_layout(
2529            child,
2530            &Layout {
2531                order: order as u32,
2532                size: final_size,
2533                #[cfg(feature = "content_size")]
2534                content_size: layout_output.content_size,
2535                scrollbar_size,
2536                location,
2537                padding,
2538                border,
2539                margin: resolved_margin,
2540            },
2541        );
2542
2543        #[cfg(feature = "content_size")]
2544        {
2545            let size_content_size_contribution = Size {
2546                width: match overflow.x {
2547                    Overflow::Visible => f32_max(final_size.width, layout_output.content_size.width),
2548                    _ => final_size.width,
2549                },
2550                height: match overflow.y {
2551                    Overflow::Visible => f32_max(final_size.height, layout_output.content_size.height),
2552                    _ => final_size.height,
2553                },
2554            };
2555            if size_content_size_contribution.has_non_zero_area() {
2556                let absolute_area_offset = Point {
2557                    x: constants.border.left
2558                        + if constants.layout_direction.is_rtl() { constants.scrollbar_gutter.x } else { 0.0 },
2559                    y: constants.border.top,
2560                };
2561                let relative_location =
2562                    Point { x: location.x - absolute_area_offset.x, y: location.y - absolute_area_offset.y };
2563                let content_size_contribution = Size {
2564                    width: if constants.layout_direction.is_rtl() {
2565                        let overflow_extra_width =
2566                            f32_max(size_content_size_contribution.width - final_size.width, 0.0);
2567                        f32_max(inset_relative_size.width - relative_location.x, 0.0) + overflow_extra_width
2568                    } else {
2569                        relative_location.x + size_content_size_contribution.width
2570                    },
2571                    height: relative_location.y + size_content_size_contribution.height,
2572                };
2573                content_size = content_size.f32_max(content_size_contribution);
2574            }
2575        }
2576    }
2577
2578    content_size
2579}
2580
2581/// Computes the total space taken up by gaps in an axis given:
2582///   - The size of each gap
2583///   - The number of items (children or flex-lines) between which there are gaps
2584#[inline(always)]
2585fn sum_axis_gaps(gap: f32, num_items: usize) -> f32 {
2586    // Gaps only exist between items, so...
2587    if num_items <= 1 {
2588        // ...if there are less than 2 items then there are no gaps
2589        0.0
2590    } else {
2591        // ...otherwise there are (num_items - 1) gaps
2592        gap * (num_items - 1) as f32
2593    }
2594}