tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5544Rust 88Markdown 11TOML 91926 Definitions

⎇ df4873ec33473556892439341dbc5f9a88ed8808 src/compute/flexbox.rs Rust · 2135 lines · 98.8 KB History Who touched what raw

Flexbox: pass correct cross-axis available space when computing an item's intrinsic main size (+misc fixes) (#522) df4873ec3 · Nico Burns ·

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