tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

Rust 501HTML 254C 19JavaScript 81414 Definitions

⎇ 66bcb10bff823bfde7828eeef133cb2fa7de7dba src/compute/flexbox.rs Rust · 2166 lines · 100.6 KB History Who touched what raw

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