gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 498HTML 254C 19JavaScript 81339 Sutichaykuna

⎇ 120bb7a2e501822b324fd48de955450ebbba1c1a src/compute/flexbox.rs Rust · 2168 siq'ikuna · 100.6 KB Ñawpa willay Pi imata llamkarqan ch'uya

Pass cross-axis known_dimension when computing flex item min size (#545) 120bb7a2e · Nico Burns ·

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