Skip to main content

taffy/compute/grid/
track_sizing.rs

1//! Implements the track sizing algorithm
2//! <https://www.w3.org/TR/css-grid-1/#layout-algorithm>
3use super::types::{GridItem, GridTrack, TrackCounts};
4use crate::geometry::{AbstractAxis, Line, Size};
5use crate::style::{AlignContent, AlignContentKeyword, AlignSelf, AvailableSpace};
6use crate::style_helpers::TaffyMinContent;
7use crate::tree::{LayoutPartialTree, LayoutPartialTreeExt, SizingMode};
8use crate::util::sys::{f32_max, f32_min, Vec};
9use crate::util::{MaybeMath, ResolveOrZero};
10use crate::CompactLength;
11use core::cmp::Ordering;
12
13/// Takes an axis, and a list of grid items sorted firstly by whether they cross a flex track
14/// in the specified axis (items that don't cross a flex track first) and then by the number
15/// of tracks they cross in specified axis (ascending order).
16struct ItemBatcher {
17    /// The axis in which the ItemBatcher is operating. Used when querying properties from items.
18    axis: AbstractAxis,
19    /// The starting index of the current batch
20    index_offset: usize,
21    /// The span of the items in the current batch
22    current_span: u16,
23    /// Whether the current batch of items cross a flexible track
24    current_is_flex: bool,
25}
26
27impl ItemBatcher {
28    /// Create a new ItemBatcher for the specified axis
29    #[inline(always)]
30    fn new(axis: AbstractAxis) -> Self {
31        ItemBatcher { index_offset: 0, axis, current_span: 1, current_is_flex: false }
32    }
33
34    /// This is basically a manual version of Iterator::next which passes `items`
35    /// in as a parameter on each iteration to work around borrow checker rules
36    #[inline]
37    fn next<'items>(&mut self, items: &'items mut [GridItem]) -> Option<(&'items mut [GridItem], bool)> {
38        if self.current_is_flex || self.index_offset >= items.len() {
39            return None;
40        }
41
42        let item = &items[self.index_offset];
43        self.current_span = item.span(self.axis);
44        self.current_is_flex = item.crosses_flexible_track(self.axis);
45
46        let next_index_offset = if self.current_is_flex {
47            items.len()
48        } else {
49            items
50                .iter()
51                .position(|item: &GridItem| {
52                    item.crosses_flexible_track(self.axis) || item.span(self.axis) > self.current_span
53                })
54                .unwrap_or(items.len())
55        };
56
57        let batch_range = self.index_offset..next_index_offset;
58        self.index_offset = next_index_offset;
59
60        let batch = &mut items[batch_range];
61        Some((batch, self.current_is_flex))
62    }
63}
64
65/// This struct captures a bunch of variables which are used to compute the intrinsic sizes of children so that those variables
66/// don't have to be passed around all over the place below. It then has methods that implement the intrinsic sizing computations
67struct IntrinsicSizeMeasurer<'tree, 'oat, Tree, EstimateFunction>
68where
69    Tree: LayoutPartialTree,
70    EstimateFunction: Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
71{
72    /// The layout tree
73    tree: &'tree mut Tree,
74    /// The tracks in the opposite axis to the one we are currently sizing
75    other_axis_tracks: &'oat [GridTrack],
76    /// A function that computes an estimate of an other-axis track's size which is passed to
77    /// the child size measurement functions
78    get_track_size_estimate: EstimateFunction,
79    /// The axis we are currently sizing
80    axis: AbstractAxis,
81    /// The available grid space
82    inner_node_size: Size<Option<f32>>,
83}
84
85impl<Tree, EstimateFunction> IntrinsicSizeMeasurer<'_, '_, Tree, EstimateFunction>
86where
87    Tree: LayoutPartialTree,
88    EstimateFunction: Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
89{
90    /// Compute the available_space to be passed to the child sizing functions
91    /// These are estimates based on either the max track sizing function or the provisional base size in the opposite
92    /// axis to the one currently being sized.
93    /// https://www.w3.org/TR/css-grid-1/#algo-overview
94    #[inline(always)]
95    fn grid_area_size(&self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> Size<Option<f32>> {
96        item.grid_area_size_cached(
97            self.axis,
98            axis_tracks,
99            self.other_axis_tracks,
100            self.inner_node_size,
101            |track, basis| (self.get_track_size_estimate)(track, basis, self.tree),
102            &|val, basis| self.tree.calc(val, basis),
103        )
104    }
105
106    /// Compute the item's resolved margins for size contributions. Horizontal percentage margins always resolve
107    /// to zero if the container size is indefinite as otherwise this would introduce a cyclic dependency.
108    #[inline(always)]
109    fn margins_axis_sums_with_baseline_shims(&self, item: &GridItem, percentage_basis: Option<f32>) -> Size<f32> {
110        item.margins_axis_sums_with_baseline_shims(percentage_basis, self.tree)
111    }
112
113    /// Simple pass-through function to `LayoutPartialTreeExt::calc`
114    #[inline(always)]
115    fn calc(&self, val: *const (), basis: f32) -> f32 {
116        self.tree.calc(val, basis)
117    }
118
119    /// Retrieve the item's min content contribution from the cache or compute it using the provided parameters
120    #[inline(always)]
121    fn min_content_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
122        let grid_area_size = self.grid_area_size(item, axis_tracks);
123        let available_space = grid_area_size.with(self.axis, None);
124        let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
125        let contribution = item.min_content_contribution_cached(self.axis, self.tree, grid_area_size, available_space);
126        contribution + margin_axis_sums.get(self.axis)
127    }
128
129    /// Retrieve the item's max content contribution from the cache or compute it using the provided parameters
130    #[inline(always)]
131    fn max_content_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
132        let grid_area_size = self.grid_area_size(item, axis_tracks);
133        let available_space = grid_area_size.with(self.axis, None);
134        let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
135        let contribution = item.max_content_contribution_cached(self.axis, self.tree, grid_area_size, available_space);
136        contribution + margin_axis_sums.get(self.axis)
137    }
138
139    /// The minimum contribution of an item is the smallest outer size it can have.
140    /// Specifically:
141    ///   - If the item’s computed preferred size behaves as auto or depends on the size of its containing block in the relevant axis:
142    ///     Its minimum contribution is the outer size that would result from assuming the item’s used minimum size as its preferred size;
143    ///   - Else the item’s minimum contribution is its min-content contribution.
144    ///
145    /// Because the minimum contribution often depends on the size of the item’s content, it is considered a type of intrinsic size contribution.
146    #[inline(always)]
147    fn minimum_contribution(&mut self, item: &mut GridItem, axis_tracks: &[GridTrack]) -> f32 {
148        let grid_area_size = self.grid_area_size(item, axis_tracks);
149        let available_space = grid_area_size.with(self.axis, None);
150        let margin_axis_sums = self.margins_axis_sums_with_baseline_shims(item, available_space.width);
151        let contribution =
152            item.minimum_contribution_cached(self.tree, self.axis, axis_tracks, grid_area_size, self.inner_node_size);
153        contribution + margin_axis_sums.get(self.axis)
154    }
155}
156
157/// To make track sizing efficient we want to order tracks
158/// Here a placement is either a Line<i16> representing a row-start/row-end or a column-start/column-end
159#[inline(always)]
160pub(super) fn cmp_by_cross_flex_then_span_then_start(
161    axis: AbstractAxis,
162) -> impl FnMut(&GridItem, &GridItem) -> Ordering {
163    move |item_a: &GridItem, item_b: &GridItem| -> Ordering {
164        match (item_a.crosses_flexible_track(axis), item_b.crosses_flexible_track(axis)) {
165            (false, true) => Ordering::Less,
166            (true, false) => Ordering::Greater,
167            _ => {
168                let placement_a = item_a.placement(axis);
169                let placement_b = item_b.placement(axis);
170                match placement_a.span().cmp(&placement_b.span()) {
171                    Ordering::Less => Ordering::Less,
172                    Ordering::Greater => Ordering::Greater,
173                    Ordering::Equal => placement_a.start.cmp(&placement_b.start),
174                }
175            }
176        }
177    }
178}
179
180/// When applying the track sizing algorithm and estimating the size in the other axis for content sizing items
181/// we should take into account align-content/justify-content if both the grid container and all items in the
182/// other axis have definite sizes. This function computes such a per-gutter additional size adjustment.
183#[inline(always)]
184pub(super) fn compute_alignment_gutter_adjustment(
185    alignment: AlignContent,
186    axis_inner_node_size: Option<f32>,
187    get_track_size_estimate: impl Fn(&GridTrack, Option<f32>) -> Option<f32>,
188    tracks: &[GridTrack],
189) -> f32 {
190    if tracks.len() <= 1 {
191        return 0.0;
192    }
193
194    // As items never cross the outermost gutters in a grid, we can simplify our calculations by
195    // treating Start and End the same. The safety modifier doesn't influence gutter weight;
196    // overflow fallback is handled when offsets are computed.
197    let outer_gutter_weight = match alignment.keyword() {
198        AlignContentKeyword::Start
199        | AlignContentKeyword::FlexStart
200        | AlignContentKeyword::End
201        | AlignContentKeyword::FlexEnd
202        | AlignContentKeyword::Center => 1,
203        AlignContentKeyword::Stretch => 0,
204        AlignContentKeyword::SpaceBetween => 0,
205        AlignContentKeyword::SpaceAround => 1,
206        AlignContentKeyword::SpaceEvenly => 1,
207    };
208
209    let inner_gutter_weight = match alignment.keyword() {
210        AlignContentKeyword::FlexStart
211        | AlignContentKeyword::Start
212        | AlignContentKeyword::FlexEnd
213        | AlignContentKeyword::End
214        | AlignContentKeyword::Center
215        | AlignContentKeyword::Stretch => 0,
216        AlignContentKeyword::SpaceBetween => 1,
217        AlignContentKeyword::SpaceAround => 2,
218        AlignContentKeyword::SpaceEvenly => 1,
219    };
220
221    if inner_gutter_weight == 0 {
222        return 0.0;
223    }
224
225    if let Some(axis_inner_node_size) = axis_inner_node_size {
226        let free_space = tracks
227            .iter()
228            .map(|track| get_track_size_estimate(track, Some(axis_inner_node_size)))
229            .sum::<Option<f32>>()
230            .map(|track_size_sum| f32_max(0.0, axis_inner_node_size - track_size_sum))
231            .unwrap_or(0.0);
232
233        let weighted_track_count =
234            (((tracks.len() - 3) / 2) * inner_gutter_weight as usize) + (2 * outer_gutter_weight as usize);
235
236        return (free_space / weighted_track_count as f32) * inner_gutter_weight as f32;
237    }
238
239    0.0
240}
241
242/// Convert origin-zero coordinates track placement in grid track vector indexes
243#[inline(always)]
244pub(super) fn resolve_item_track_indexes(items: &mut [GridItem], column_counts: TrackCounts, row_counts: TrackCounts) {
245    for item in items {
246        item.column_indexes = item.column.map(|line| line.into_track_vec_index(column_counts) as u16);
247        item.row_indexes = item.row.map(|line| line.into_track_vec_index(row_counts) as u16);
248    }
249}
250
251/// Determine (in each axis) whether the item crosses any flexible tracks
252#[inline(always)]
253pub(super) fn determine_if_item_crosses_flexible_or_intrinsic_tracks(
254    items: &mut Vec<GridItem>,
255    columns: &[GridTrack],
256    rows: &[GridTrack],
257) {
258    for item in items {
259        item.crosses_flexible_column =
260            item.track_range_excluding_lines(AbstractAxis::Inline).any(|i| columns[i].is_flexible());
261        item.crosses_intrinsic_column =
262            item.track_range_excluding_lines(AbstractAxis::Inline).any(|i| columns[i].has_intrinsic_sizing_function());
263        item.crosses_flexible_row =
264            item.track_range_excluding_lines(AbstractAxis::Block).any(|i| rows[i].is_flexible());
265        item.crosses_intrinsic_row =
266            item.track_range_excluding_lines(AbstractAxis::Block).any(|i| rows[i].has_intrinsic_sizing_function());
267    }
268}
269
270/// Track sizing algorithm
271/// Note: Gutters are treated as empty fixed-size tracks for the purpose of the track sizing algorithm.
272#[allow(clippy::too_many_arguments)]
273pub(super) fn track_sizing_algorithm<Tree: LayoutPartialTree>(
274    tree: &mut Tree,
275    axis: AbstractAxis,
276    axis_min_size: Option<f32>,
277    axis_max_size: Option<f32>,
278    axis_alignment: AlignContent,
279    other_axis_alignment: AlignContent,
280    available_grid_space: Size<AvailableSpace>,
281    inner_node_size: Size<Option<f32>>,
282    axis_tracks: &mut [GridTrack],
283    other_axis_tracks: &mut [GridTrack],
284    items: &mut [GridItem],
285    get_track_size_estimate: fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
286    has_baseline_aligned_item: bool,
287) {
288    // 11.4 Initialise Track sizes
289    // Initialize each track’s base size and growth limit.
290    let percentage_basis = inner_node_size.get(axis).or(axis_min_size);
291    initialize_track_sizes(tree, axis_tracks, percentage_basis);
292
293    // 11.5.1 Shim item baselines
294    if has_baseline_aligned_item {
295        resolve_item_baselines(tree, axis, items, inner_node_size);
296    }
297
298    // If all tracks have base_size = growth_limit, then skip the rest of this function.
299    // Note: this can only happen both track sizing function have the same fixed track sizing function
300    if axis_tracks.iter().all(|track| track.base_size == track.growth_limit) {
301        return;
302    }
303
304    // Pre-computations for 11.5 Resolve Intrinsic Track Sizes
305
306    // Compute an additional amount to add to each spanned gutter when computing item's estimated size in the
307    // in the opposite axis based on the alignment, container size, and estimated track sizes in that axis
308    let gutter_alignment_adjustment = compute_alignment_gutter_adjustment(
309        other_axis_alignment,
310        inner_node_size.get(axis.other()),
311        |track, basis| get_track_size_estimate(track, basis, tree),
312        other_axis_tracks,
313    );
314    if other_axis_tracks.len() > 3 {
315        let len = other_axis_tracks.len();
316        let inner_gutter_tracks = other_axis_tracks[2..len].iter_mut().step_by(2);
317        for track in inner_gutter_tracks {
318            track.content_alignment_adjustment = gutter_alignment_adjustment;
319        }
320    }
321
322    // 11.5 Resolve Intrinsic Track Sizes
323    resolve_intrinsic_track_sizes(
324        tree,
325        axis,
326        axis_tracks,
327        other_axis_tracks,
328        items,
329        available_grid_space.get(axis),
330        inner_node_size,
331        get_track_size_estimate,
332    );
333
334    // 11.6. Maximise Tracks
335    // Distributes free space (if any) to tracks with FINITE growth limits, up to their limits.
336    maximise_tracks(axis_tracks, inner_node_size.get(axis), available_grid_space.get(axis));
337
338    // For the purpose of the final two expansion steps ("Expand Flexible Tracks" and "Stretch auto Tracks"), we only want to expand
339    // into space generated by the grid container's size (as defined by either it's preferred size style or by it's parent node through
340    // something like stretch alignment), not just any available space. To do this we map definite available space to AvailableSpace::MaxContent
341    // in the case that inner_node_size is None
342    let axis_available_space_for_expansion = if let Some(available_space) = inner_node_size.get(axis) {
343        AvailableSpace::Definite(available_space)
344    } else {
345        match available_grid_space.get(axis) {
346            AvailableSpace::MinContent => AvailableSpace::MinContent,
347            AvailableSpace::MaxContent | AvailableSpace::Definite(_) => AvailableSpace::MaxContent,
348        }
349    };
350
351    // 11.7. Expand Flexible Tracks
352    // This step sizes flexible tracks using the largest value it can assign to an fr without exceeding the available space.
353    expand_flexible_tracks(
354        tree,
355        axis,
356        axis_tracks,
357        items,
358        axis_min_size,
359        axis_max_size,
360        axis_available_space_for_expansion,
361    );
362
363    // 11.8. Stretch auto Tracks
364    // This step expands tracks that have an auto max track sizing function by dividing any remaining positive, definite free space equally amongst them.
365    if axis_alignment == AlignContent::STRETCH {
366        stretch_auto_tracks(axis_tracks, axis_min_size, axis_available_space_for_expansion);
367    }
368}
369
370/// Whether it is a minimum or maximum size's space being distributed
371/// This controls behaviour of the space distribution algorithm when distributing beyond limits
372/// See "distributing space beyond limits" at https://www.w3.org/TR/css-grid-1/#extra-space
373#[derive(Copy, Clone, Debug, PartialEq, Eq)]
374enum IntrinsicContributionType {
375    /// It's a minimum size's space being distributed
376    Minimum,
377    /// It's a maximum size's space being distributed
378    Maximum,
379}
380
381/// Add any planned base size increases to the base size after a round of distributing space to base sizes
382/// Reset the planed base size increase to zero ready for the next round.
383#[inline(always)]
384fn flush_planned_base_size_increases(tracks: &mut [GridTrack]) {
385    for track in tracks {
386        track.base_size += track.base_size_planned_increase;
387        track.base_size_planned_increase = 0.0;
388    }
389}
390
391/// Add any planned growth limit increases to the growth limit after a round of distributing space to growth limits
392/// Reset the planed growth limit increase to zero ready for the next round.
393#[inline(always)]
394fn flush_planned_growth_limit_increases(tracks: &mut [GridTrack], set_infinitely_growable: bool) {
395    for track in tracks {
396        if track.growth_limit_planned_increase > 0.0 {
397            track.growth_limit = if track.growth_limit == f32::INFINITY {
398                track.base_size + track.growth_limit_planned_increase
399            } else {
400                track.growth_limit + track.growth_limit_planned_increase
401            };
402            track.infinitely_growable = set_infinitely_growable;
403        } else {
404            track.infinitely_growable = false;
405        }
406        track.growth_limit_planned_increase = 0.0
407    }
408}
409
410/// 11.4 Initialise Track sizes
411/// Initialize each track’s base size and growth limit.
412#[inline(always)]
413fn initialize_track_sizes(
414    tree: &impl LayoutPartialTree,
415    axis_tracks: &mut [GridTrack],
416    axis_inner_node_size: Option<f32>,
417) {
418    for track in axis_tracks.iter_mut() {
419        // For each track, if the track’s min track sizing function is:
420        // - A fixed sizing function
421        //     Resolve to an absolute length and use that size as the track’s initial base size.
422        //     Note: Indefinite lengths cannot occur, as they’re treated as auto.
423        // - An intrinsic sizing function
424        //     Use an initial base size of zero.
425        track.base_size = track
426            .min_track_sizing_function
427            .definite_value(axis_inner_node_size, |val, basis| tree.calc(val, basis))
428            .unwrap_or(0.0);
429
430        // For each track, if the track’s max track sizing function is:
431        // - A fixed sizing function
432        //     Resolve to an absolute length and use that size as the track’s initial growth limit.
433        // - An intrinsic sizing function
434        //     Use an initial growth limit of infinity.
435        // - A flexible sizing function
436        //     Use an initial growth limit of infinity.
437        track.growth_limit = track
438            .max_track_sizing_function
439            .definite_value(axis_inner_node_size, |val, basis| tree.calc(val, basis))
440            .unwrap_or(f32::INFINITY);
441
442        // In all cases, if the growth limit is less than the base size, increase the growth limit to match the base size.
443        if track.growth_limit < track.base_size {
444            track.growth_limit = track.base_size;
445        }
446    }
447}
448
449/// 11.5.1 Shim baseline-aligned items so their intrinsic size contributions reflect their baseline alignment.
450fn resolve_item_baselines(
451    tree: &mut impl LayoutPartialTree,
452    axis: AbstractAxis,
453    items: &mut [GridItem],
454    inner_node_size: Size<Option<f32>>,
455) {
456    // Sort items by track in the other axis (row) start position so that we can iterate items in groups which
457    // are in the same track in the other axis (row)
458    let other_axis = axis.other();
459    items.sort_by_key(|item| item.placement(other_axis).start);
460
461    // Iterate over grid rows
462    let mut remaining_items = &mut items[0..];
463    while !remaining_items.is_empty() {
464        // Get the row index of the current row
465        let current_row = remaining_items[0].placement(other_axis).start;
466
467        // Find the item index of the first item that is in a different row (or None if we've reached the end of the list)
468        let next_row_first_item =
469            remaining_items.iter().position(|item| item.placement(other_axis).start != current_row);
470
471        // Use this index to split the `remaining_items` slice in two slices:
472        //    - A `row_items` slice containing the items (that start) in the current row
473        //    - A new `remaining_items` consisting of the remainder of the `remaining_items` slice
474        //      that hasn't been split off into `row_items
475        let row_items = if let Some(index) = next_row_first_item {
476            let (row_items, tail) = remaining_items.split_at_mut(index);
477            remaining_items = tail;
478            row_items
479        } else {
480            let row_items = remaining_items;
481            remaining_items = &mut [];
482            row_items
483        };
484
485        // Count how many items in *this row* are baseline aligned
486        // If a row has one or zero items participating in baseline alignment then baseline alignment is a no-op
487        // for those items and we skip further computations for that row
488        let row_baseline_item_count = row_items.iter().filter(|item| item.align_self == AlignSelf::BASELINE).count();
489        if row_baseline_item_count <= 1 {
490            continue;
491        }
492
493        // Compute the baselines of all items in the row
494        for item in row_items.iter_mut() {
495            let measured_size_and_baselines = tree.perform_child_layout(
496                item.node,
497                Size::NONE,
498                inner_node_size,
499                Size::MIN_CONTENT,
500                SizingMode::InherentSize,
501                Line::FALSE,
502            );
503
504            let baseline = measured_size_and_baselines.first_baselines.y;
505            let height = measured_size_and_baselines.size.height;
506
507            item.baseline = Some(
508                baseline.unwrap_or(height)
509                    + item.margin.top.resolve_or_zero(inner_node_size.width, |val, basis| tree.calc(val, basis)),
510            );
511        }
512
513        // Compute the max baseline of all items in the row
514        let row_max_baseline =
515            row_items.iter().map(|item| item.baseline.unwrap_or(0.0)).max_by(|a, b| a.total_cmp(b)).unwrap();
516
517        // Compute the baseline shim for each item in the row
518        for item in row_items.iter_mut() {
519            item.baseline_shim = row_max_baseline - item.baseline.unwrap_or(0.0);
520        }
521    }
522}
523
524/// 11.5 Resolve Intrinsic Track Sizes
525#[allow(clippy::too_many_arguments)]
526fn resolve_intrinsic_track_sizes<Tree: LayoutPartialTree>(
527    tree: &mut Tree,
528    axis: AbstractAxis,
529    axis_tracks: &mut [GridTrack],
530    other_axis_tracks: &[GridTrack],
531    items: &mut [GridItem],
532    axis_available_grid_space: AvailableSpace,
533    inner_node_size: Size<Option<f32>>,
534    get_track_size_estimate: impl Fn(&GridTrack, Option<f32>, &Tree) -> Option<f32>,
535) {
536    // Step 1. Shim baseline-aligned items so their intrinsic size contributions reflect their baseline alignment.
537
538    // Already done at this point. See resolve_item_baselines function.
539
540    // Step 2.
541
542    // The track sizing algorithm requires us to iterate through the items in ascending order of the number of
543    // tracks they span (first items that span 1 track, then items that span 2 tracks, etc).
544    // To avoid having to do multiple iterations of the items, we pre-sort them into this order.
545    items.sort_by(cmp_by_cross_flex_then_span_then_start(axis));
546
547    // Step 2, Step 3 and Step 4
548    // 2 & 3. Iterate over items that don't cross a flex track. Items should have already been sorted in ascending order
549    // of the number of tracks they span. Step 2 is the 1 track case and has an optimised implementation
550    // 4. Next, repeat the previous step instead considering (together, rather than grouped by span size) all items
551    // that do span a track with a flexible sizing function while
552
553    // Compute item's intrinsic (content-based) sizes
554    // Note: For items with a specified minimum size of auto (the initial value), the minimum contribution is usually equivalent
555    // to the min-content contribution—but can differ in some cases, see §6.6 Automatic Minimum Size of Grid Items.
556    // Also, minimum contribution <= min-content contribution <= max-content contribution.
557
558    let axis_inner_node_size = inner_node_size.get(axis);
559    let mut item_sizer =
560        IntrinsicSizeMeasurer { tree, other_axis_tracks, axis, inner_node_size, get_track_size_estimate };
561
562    let mut batched_item_iterator = ItemBatcher::new(axis);
563    while let Some((batch, is_flex)) = batched_item_iterator.next(items) {
564        // 2. Size tracks to fit non-spanning items: For each track with an intrinsic track sizing function and not a flexible sizing function,
565        // consider the items in it with a span of 1:
566        let batch_span = batch[0].placement(axis).span();
567        if !is_flex && batch_span == 1 {
568            for item in batch.iter_mut() {
569                let track_index = item.placement_indexes(axis).start + 1;
570                let track = &axis_tracks[track_index as usize];
571
572                // Handle base sizes
573                let new_base_size = match track.min_track_sizing_function.0.tag() {
574                    CompactLength::MIN_CONTENT_TAG => {
575                        f32_max(track.base_size, item_sizer.min_content_contribution(item, axis_tracks))
576                    }
577                    // If the container size is indefinite and has not yet been resolved then percentage sized
578                    // tracks should be treated as min-content (this matches Chrome's behaviour and seems sensible)
579                    CompactLength::PERCENT_TAG => {
580                        if axis_inner_node_size.is_none() {
581                            f32_max(track.base_size, item_sizer.min_content_contribution(item, axis_tracks))
582                        } else {
583                            track.base_size
584                        }
585                    }
586                    CompactLength::MAX_CONTENT_TAG => {
587                        f32_max(track.base_size, item_sizer.max_content_contribution(item, axis_tracks))
588                    }
589                    CompactLength::AUTO_TAG => {
590                        let space = match axis_available_grid_space {
591                            // QUIRK: The spec says that:
592                            //
593                            //   If the grid container is being sized under a min- or max-content constraint, use the items’ limited
594                            //   min-content contributions in place of their minimum contributions here.
595                            //
596                            // However, in practice browsers only seem to apply this rule if the item is not a scroll container
597                            // (note that overflow:hidden counts as a scroll container), giving the automatic minimum size of scroll
598                            // containers (zero) precedence over the min-content contributions.
599                            AvailableSpace::MinContent | AvailableSpace::MaxContent
600                                if !item.overflow.get(axis).is_scroll_container() =>
601                            {
602                                let axis_minimum_size = item_sizer.minimum_contribution(item, axis_tracks);
603                                let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
604                                let limit = track
605                                    .max_track_sizing_function
606                                    .definite_limit(axis_inner_node_size, |val, basis| item_sizer.calc(val, basis));
607                                axis_min_content_size.maybe_min(limit).max(axis_minimum_size)
608                            }
609                            _ => item_sizer.minimum_contribution(item, axis_tracks),
610                        };
611                        f32_max(track.base_size, space)
612                    }
613                    CompactLength::LENGTH_TAG => {
614                        // Do nothing as it's not an intrinsic track sizing function
615                        track.base_size
616                    }
617                    // Handle calc() like percentage
618                    #[cfg(feature = "calc")]
619                    _ if track.min_track_sizing_function.0.is_calc() => {
620                        if axis_inner_node_size.is_none() {
621                            f32_max(track.base_size, item_sizer.min_content_contribution(item, axis_tracks))
622                        } else {
623                            track.base_size
624                        }
625                    }
626                    _ => unreachable!(),
627                };
628                let growth_limit_min_content_contribution = if !item.overflow.get(axis).is_scroll_container() {
629                    Some(item_sizer.min_content_contribution(item, axis_tracks))
630                } else {
631                    None
632                };
633                let growth_limit_max_content_contribution = item_sizer.max_content_contribution(item, axis_tracks);
634                let growth_limit_intrinsic_min_content_contribution =
635                    item_sizer.min_content_contribution(item, axis_tracks);
636                let track = &mut axis_tracks[track_index as usize];
637                track.base_size = new_base_size;
638
639                // Handle growth limits
640                if track.max_track_sizing_function.is_fit_content() {
641                    // If item is not a scroll container, then increase the growth limit to at least the
642                    // size of the min-content contribution
643                    if let Some(min_content_contribution) = growth_limit_min_content_contribution {
644                        track.growth_limit_planned_increase =
645                            f32_max(track.growth_limit_planned_increase, min_content_contribution);
646                    }
647
648                    // Always increase the growth limit to at least the size of the *fit-content limited*
649                    // max-content contribution
650                    let fit_content_limit = track.fit_content_limit(axis_inner_node_size);
651                    let max_content_contribution = f32_min(growth_limit_max_content_contribution, fit_content_limit);
652                    track.growth_limit_planned_increase =
653                        f32_max(track.growth_limit_planned_increase, max_content_contribution);
654                } else if track.max_track_sizing_function.is_max_content_alike()
655                    || track.max_track_sizing_function.uses_percentage() && axis_inner_node_size.is_none()
656                {
657                    // If the container size is indefinite and has not yet been resolved then percentage sized
658                    // tracks should be treated as auto (this matches Chrome's behaviour and seems sensible)
659                    track.growth_limit_planned_increase =
660                        f32_max(track.growth_limit_planned_increase, growth_limit_max_content_contribution);
661                } else if track.max_track_sizing_function.is_intrinsic() {
662                    track.growth_limit_planned_increase =
663                        f32_max(track.growth_limit_planned_increase, growth_limit_intrinsic_min_content_contribution);
664                }
665            }
666
667            for track in axis_tracks.iter_mut() {
668                if track.growth_limit_planned_increase > 0.0 {
669                    track.growth_limit = if track.growth_limit == f32::INFINITY {
670                        track.growth_limit_planned_increase
671                    } else {
672                        f32_max(track.growth_limit, track.growth_limit_planned_increase)
673                    };
674                }
675                track.infinitely_growable = false;
676                track.growth_limit_planned_increase = 0.0;
677                if track.growth_limit < track.base_size {
678                    track.growth_limit = track.base_size;
679                }
680            }
681
682            continue;
683        }
684
685        // 1. For intrinsic minimums:
686        // First increase the base size of tracks with an intrinsic min track sizing function
687        for item in batch.iter_mut().filter(|item| item.crosses_intrinsic_track(axis)) {
688            // ...by distributing extra space as needed to accommodate these items’ minimum contributions.
689            //
690            // QUIRK: The spec says that:
691            //
692            //   If the grid container is being sized under a min- or max-content constraint, use the items’ limited min-content contributions
693            //   in place of their minimum contributions here.
694            //
695            // However, in practice browsers only seem to apply this rule if the item is not a scroll container (note that overflow:hidden counts as
696            // a scroll container), giving the automatic minimum size of scroll containers (zero) precedence over the min-content contributions.
697            let space = match axis_available_grid_space {
698                AvailableSpace::MinContent | AvailableSpace::MaxContent
699                    if !item.overflow.get(axis).is_scroll_container() =>
700                {
701                    let axis_minimum_size = item_sizer.minimum_contribution(item, axis_tracks);
702                    let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
703                    let limit = item.spanned_track_limit(axis, axis_tracks, axis_inner_node_size, &|val, basis| {
704                        item_sizer.calc(val, basis)
705                    });
706                    axis_min_content_size.maybe_min(limit).max(axis_minimum_size)
707                }
708                _ => item_sizer.minimum_contribution(item, axis_tracks),
709            };
710            let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
711            if space > 0.0 {
712                let has_intrinsic_min_track_sizing_function = |track: &GridTrack| {
713                    track
714                        .min_track_sizing_function
715                        .definite_value(axis_inner_node_size, |val, basis| item_sizer.calc(val, basis))
716                        .is_none()
717                };
718                if item.overflow.get(axis).is_scroll_container() {
719                    let fit_content_limit =
720                        move |track: &GridTrack| track.fit_content_limited_growth_limit(axis_inner_node_size);
721                    distribute_item_space_to_base_size(
722                        is_flex,
723                        space,
724                        tracks,
725                        has_intrinsic_min_track_sizing_function,
726                        fit_content_limit,
727                        IntrinsicContributionType::Minimum,
728                        axis_inner_node_size,
729                    );
730                } else {
731                    distribute_item_space_to_base_size(
732                        is_flex,
733                        space,
734                        tracks,
735                        has_intrinsic_min_track_sizing_function,
736                        |track| track.growth_limit,
737                        IntrinsicContributionType::Minimum,
738                        axis_inner_node_size,
739                    );
740                }
741            }
742        }
743        flush_planned_base_size_increases(axis_tracks);
744
745        // 2. For content-based minimums:
746        // Next continue to increase the base size of tracks with a min track sizing function of min-content or max-content
747        // by distributing extra space as needed to account for these items' min-content contributions.
748        let has_min_or_max_content_min_track_sizing_function =
749            move |track: &GridTrack| track.min_track_sizing_function.is_min_or_max_content();
750        for item in batch.iter_mut() {
751            let space = item_sizer.min_content_contribution(item, axis_tracks);
752            let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
753            if space > 0.0 {
754                if item.overflow.get(axis).is_scroll_container() {
755                    let fit_content_limit =
756                        move |track: &GridTrack| track.fit_content_limited_growth_limit(axis_inner_node_size);
757                    distribute_item_space_to_base_size(
758                        is_flex,
759                        space,
760                        tracks,
761                        has_min_or_max_content_min_track_sizing_function,
762                        fit_content_limit,
763                        IntrinsicContributionType::Minimum,
764                        axis_inner_node_size,
765                    );
766                } else {
767                    distribute_item_space_to_base_size(
768                        is_flex,
769                        space,
770                        tracks,
771                        has_min_or_max_content_min_track_sizing_function,
772                        |track| track.growth_limit,
773                        IntrinsicContributionType::Minimum,
774                        axis_inner_node_size,
775                    );
776                }
777            }
778        }
779        flush_planned_base_size_increases(axis_tracks);
780
781        // 3. For max-content minimums:
782
783        // If the grid container is being sized under a max-content constraint, continue to increase the base size of tracks with
784        // a min track sizing function of auto or max-content by distributing extra space as needed to account for these items'
785        // limited max-content contributions.
786
787        // Define fit_content_limited_growth_limit function. This is passed to the distribute_space_up_to_limits
788        // helper function, and is used to compute the limit to distribute up to for each track.
789        // Wrapping the method on GridTrack is necessary in order to resolve percentage fit-content arguments.
790        if axis_available_grid_space == AvailableSpace::MaxContent {
791            /// Whether a track:
792            ///   - has an Auto MIN track sizing function
793            ///   - Does not have a MinContent MAX track sizing function
794            ///
795            /// The latter condition was added in order to match Chrome. But I believe it is due to the provision
796            /// under minmax here https://www.w3.org/TR/css-grid-1/#track-sizes which states that:
797            ///
798            ///    "If the max is less than the min, then the max will be floored by the min (essentially yielding minmax(min, min))"
799            #[inline(always)]
800            fn has_auto_min_track_sizing_function(track: &GridTrack) -> bool {
801                track.min_track_sizing_function.is_auto() && !track.max_track_sizing_function.is_min_content()
802            }
803
804            /// Whether a track has a MaxContent min track sizing function
805            #[inline(always)]
806            fn has_max_content_min_track_sizing_function(track: &GridTrack) -> bool {
807                track.min_track_sizing_function.is_max_content()
808            }
809
810            for item in batch.iter_mut() {
811                let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
812                let limit = item.spanned_track_limit(axis, axis_tracks, axis_inner_node_size, &|val, basis| {
813                    item_sizer.calc(val, basis)
814                });
815                let space = axis_max_content_size.maybe_min(limit);
816                let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
817                if space > 0.0 {
818                    // If any of the tracks spanned by the item have a MaxContent min track sizing function then
819                    // distribute space only to those tracks. Otherwise distribute space to tracks with an Auto min
820                    // track sizing function.
821                    //
822                    // Note: this prioritisation of MaxContent over Auto is not mentioned in the spec (which suggests that
823                    // we ought to distribute space evenly between MaxContent and Auto tracks). But it is implemented like
824                    // this in both Chrome and Firefox (and it does have a certain logic to it), so we implement it too for
825                    // compatibility.
826                    //
827                    // See: https://www.w3.org/TR/css-grid-1/#track-size-max-content-min
828                    if tracks.iter().any(has_max_content_min_track_sizing_function) {
829                        distribute_item_space_to_base_size(
830                            is_flex,
831                            space,
832                            tracks,
833                            has_max_content_min_track_sizing_function,
834                            |_| f32::INFINITY,
835                            IntrinsicContributionType::Maximum,
836                            axis_inner_node_size,
837                        );
838                    } else {
839                        let fit_content_limited_growth_limit =
840                            move |track: &GridTrack| track.fit_content_limited_growth_limit(axis_inner_node_size);
841                        distribute_item_space_to_base_size(
842                            is_flex,
843                            space,
844                            tracks,
845                            has_auto_min_track_sizing_function,
846                            fit_content_limited_growth_limit,
847                            IntrinsicContributionType::Maximum,
848                            axis_inner_node_size,
849                        );
850                    }
851                }
852            }
853            flush_planned_base_size_increases(axis_tracks);
854        }
855
856        // In all cases, continue to increase the base size of tracks with a min track sizing function of max-content by distributing
857        // extra space as needed to account for these items' max-content contributions.
858        let has_max_content_min_track_sizing_function =
859            move |track: &GridTrack| track.min_track_sizing_function.is_max_content();
860        for item in batch.iter_mut() {
861            let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
862            let space = axis_max_content_size;
863            let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
864            if space > 0.0 {
865                distribute_item_space_to_base_size(
866                    is_flex,
867                    space,
868                    tracks,
869                    has_max_content_min_track_sizing_function,
870                    |track| track.growth_limit,
871                    IntrinsicContributionType::Maximum,
872                    axis_inner_node_size,
873                );
874            }
875        }
876        flush_planned_base_size_increases(axis_tracks);
877
878        // 4. If at this point any track’s growth limit is now less than its base size, increase its growth limit to match its base size.
879        for track in axis_tracks.iter_mut() {
880            if track.growth_limit < track.base_size {
881                track.growth_limit = track.base_size;
882            }
883        }
884
885        // If a track is a flexible track, then it has flexible max track sizing function
886        // It cannot also have an intrinsic max track sizing function, so these steps do not apply.
887        if !is_flex {
888            // 5. For intrinsic maximums: Next increase the growth limit of tracks with an intrinsic max track sizing function by
889            // distributing extra space as needed to account for these items' min-content contributions.
890            let has_intrinsic_max_track_sizing_function =
891                move |track: &GridTrack| !track.max_track_sizing_function.has_definite_value(axis_inner_node_size);
892            for item in batch.iter_mut() {
893                let axis_min_content_size = item_sizer.min_content_contribution(item, axis_tracks);
894                let space = axis_min_content_size;
895                let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
896                if space > 0.0 {
897                    distribute_item_space_to_growth_limit(
898                        space,
899                        tracks,
900                        has_intrinsic_max_track_sizing_function,
901                        inner_node_size.get(axis),
902                    );
903                }
904            }
905            // Mark any tracks whose growth limit changed from infinite to finite in this step as infinitely growable for the next step.
906            flush_planned_growth_limit_increases(axis_tracks, true);
907
908            // 6. For max-content maximums: Lastly continue to increase the growth limit of tracks with a max track sizing function of max-content
909            // by distributing extra space as needed to account for these items' max-content contributions. However, limit the growth of any
910            // fit-content() tracks by their fit-content() argument.
911            let has_max_content_max_track_sizing_function = |track: &GridTrack| {
912                track.max_track_sizing_function.is_max_content_alike()
913                    || (track.max_track_sizing_function.uses_percentage() && axis_inner_node_size.is_none())
914            };
915            for item in batch.iter_mut() {
916                let axis_max_content_size = item_sizer.max_content_contribution(item, axis_tracks);
917                let space = axis_max_content_size;
918                let tracks = &mut axis_tracks[item.track_range_excluding_lines(axis)];
919                if space > 0.0 {
920                    distribute_item_space_to_growth_limit(
921                        space,
922                        tracks,
923                        has_max_content_max_track_sizing_function,
924                        inner_node_size.get(axis),
925                    );
926                }
927            }
928            // Mark any tracks whose growth limit changed from infinite to finite in this step as infinitely growable for the next step.
929            flush_planned_growth_limit_increases(axis_tracks, false);
930        }
931    }
932
933    // Step 5. If any track still has an infinite growth limit (because, for example, it had no items placed
934    // in it or it is a flexible track), set its growth limit to its base size.
935    // NOTE: this step is super-important to ensure that the "Maximise Tracks" step doesn't affect flexible tracks
936    axis_tracks
937        .iter_mut()
938        .filter(|track| track.growth_limit == f32::INFINITY)
939        .for_each(|track| track.growth_limit = track.base_size);
940}
941
942/// 11.5.1. Distributing Extra Space Across Spanned Tracks
943/// https://www.w3.org/TR/css-grid-1/#extra-space
944#[inline(always)]
945fn distribute_item_space_to_base_size(
946    is_flex: bool,
947    space: f32,
948    tracks: &mut [GridTrack],
949    track_is_affected: impl Fn(&GridTrack) -> bool,
950    track_limit: impl Fn(&GridTrack) -> f32,
951    intrinsic_contribution_type: IntrinsicContributionType,
952    axis_inner_node_size: Option<f32>,
953) {
954    if is_flex {
955        let filter = |track: &GridTrack| track.is_flexible() && track_is_affected(track);
956
957        // If the sum of the flex factors of the affected tracks is greater than zero, distribute
958        // space according to the ratios of the tracks' flex factors. Otherwise distribute space equally.
959        //
960        // Note: the spec says to compute the sum over all flexible tracks spanned by the item, and to
961        // blend flex-factor-proportional and equal distribution when the sum is below one. But Chrome
962        // computes the sum over only the affected tracks and uses pure flex-factor ratios whenever
963        // that sum is non-zero, so we do the same for compatibility.
964        let flex_factor_sum: f32 = tracks.iter().filter(|track| filter(track)).map(|track| track.flex_factor()).sum();
965        if flex_factor_sum > 0.0 {
966            distribute_item_space_to_base_size_inner(
967                space,
968                tracks,
969                filter,
970                |track| track.flex_factor(),
971                track_limit,
972                intrinsic_contribution_type,
973                axis_inner_node_size,
974            )
975        } else {
976            distribute_item_space_to_base_size_inner(
977                space,
978                tracks,
979                filter,
980                |_| 1.0,
981                track_limit,
982                intrinsic_contribution_type,
983                axis_inner_node_size,
984            )
985        }
986    } else {
987        distribute_item_space_to_base_size_inner(
988            space,
989            tracks,
990            track_is_affected,
991            |_| 1.0,
992            track_limit,
993            intrinsic_contribution_type,
994            axis_inner_node_size,
995        )
996    }
997
998    /// Inner function that doesn't account for differences due to distributing to flex items
999    /// This difference is handled by the closure passed in above
1000    fn distribute_item_space_to_base_size_inner(
1001        space: f32,
1002        tracks: &mut [GridTrack],
1003        track_is_affected: impl Fn(&GridTrack) -> bool,
1004        track_distribution_proportion: impl Fn(&GridTrack) -> f32,
1005        track_limit: impl Fn(&GridTrack) -> f32,
1006        intrinsic_contribution_type: IntrinsicContributionType,
1007        axis_inner_node_size: Option<f32>,
1008    ) {
1009        // Skip this distribution if there is either
1010        //   - no space to distribute
1011        //   - no affected tracks to distribute space to
1012        if space == 0.0 || !tracks.iter().any(&track_is_affected) {
1013            return;
1014        }
1015
1016        // Define get_base_size function. This is passed to the distribute_space_up_to_limits helper function
1017        // to indicate that it is the base size that is being distributed to.
1018        let get_base_size = |track: &GridTrack| track.base_size;
1019
1020        // 1. Find the space to distribute
1021        let track_sizes: f32 = tracks.iter().map(|track| track.base_size).sum();
1022        let extra_space: f32 = f32_max(0.0, space - track_sizes);
1023
1024        // 2. Distribute space up to limits:
1025        // Note: there are two exit conditions to this loop:
1026        //   - We run out of space to distribute (extra_space falls below THRESHOLD)
1027        //   - We run out of growable tracks to distribute to
1028
1029        /// Define a small constant to avoid infinite loops due to rounding errors. Rather than stopping distributing
1030        /// extra space when it gets to exactly zero, we will stop when it falls below this amount
1031        const THRESHOLD: f32 = 0.000001;
1032
1033        let extra_space = distribute_space_up_to_limits(
1034            extra_space,
1035            tracks,
1036            &track_is_affected,
1037            &track_distribution_proportion,
1038            get_base_size,
1039            &track_limit,
1040        );
1041
1042        // 3. Distribute remaining span beyond limits (if any)
1043        if extra_space > THRESHOLD {
1044            // When accommodating minimum contributions or accommodating min-content contributions:
1045            //   - any affected track that happens to also have an intrinsic max track sizing function;
1046            // When accommodating max-content contributions:
1047            //   - any affected track that happens to also have a max-content max track sizing function
1048            let mut filter = match intrinsic_contribution_type {
1049                IntrinsicContributionType::Minimum => {
1050                    (|track: &GridTrack| track.max_track_sizing_function.is_intrinsic()) as fn(&GridTrack) -> bool
1051                }
1052                IntrinsicContributionType::Maximum => {
1053                    (|track: &GridTrack| track.max_track_sizing_function.is_max_or_fit_content())
1054                        as fn(&GridTrack) -> bool
1055                }
1056            };
1057
1058            // If there are no such tracks (matching filter above), then use all affected tracks.
1059            let number_of_tracks =
1060                tracks.iter().filter(|track| track_is_affected(track)).filter(|track| filter(track)).count();
1061            if number_of_tracks == 0 {
1062                filter = (|_| true) as fn(&GridTrack) -> bool;
1063            }
1064
1065            // When distributing beyond limits, growth limits are ignored, but the argument
1066            // to any fit-content() max track sizing function still caps growth.
1067            distribute_space_up_to_limits(
1068                extra_space,
1069                tracks,
1070                |track| track_is_affected(track) && filter(track),
1071                &track_distribution_proportion,
1072                get_base_size,
1073                |track| track.fit_content_limit(axis_inner_node_size),
1074            );
1075        }
1076
1077        // 4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned increase
1078        // set the track’s planned increase to that value.
1079        for track in tracks.iter_mut() {
1080            if track.item_incurred_increase > track.base_size_planned_increase {
1081                track.base_size_planned_increase = track.item_incurred_increase;
1082            }
1083
1084            // Reset the item_incurresed increase ready for the next space distribution
1085            track.item_incurred_increase = 0.0;
1086        }
1087    }
1088}
1089
1090/// 11.5.1. Distributing Extra Space Across Spanned Tracks
1091/// This is simplified (and faster) version of the algorithm for growth limits
1092/// https://www.w3.org/TR/css-grid-1/#extra-space
1093fn distribute_item_space_to_growth_limit(
1094    space: f32,
1095    tracks: &mut [GridTrack],
1096    track_is_affected: impl Fn(&GridTrack) -> bool,
1097    axis_inner_node_size: Option<f32>,
1098) {
1099    // Skip this distribution if there is either
1100    //   - no space to distribute
1101    //   - no affected tracks to distribute space to
1102    if space == 0.0 || tracks.iter().filter(|track| track_is_affected(track)).count() == 0 {
1103        return;
1104    }
1105
1106    // 1. Find the space to distribute
1107    let track_sizes: f32 = tracks
1108        .iter()
1109        .map(|track| if track.growth_limit == f32::INFINITY { track.base_size } else { track.growth_limit })
1110        .sum();
1111    let extra_space: f32 = f32_max(0.0, space - track_sizes);
1112
1113    // 2. Distribute space up to limits:
1114    // For growth limits the limit is either Infinity, or the growth limit itself. Which means that:
1115    //   - If there are any tracks with infinite limits then all space will be distributed to those track(s).
1116    //   - Otherwise no space will be distributed as part of this step
1117    let number_of_growable_tracks = tracks
1118        .iter()
1119        .filter(|track| track_is_affected(track))
1120        .filter(|track| {
1121            track.infinitely_growable || track.fit_content_limited_growth_limit(axis_inner_node_size) == f32::INFINITY
1122        })
1123        .count();
1124    if number_of_growable_tracks > 0 {
1125        let item_incurred_increase = extra_space / number_of_growable_tracks as f32;
1126        for track in tracks.iter_mut().filter(|track| track_is_affected(track)).filter(|track| {
1127            track.infinitely_growable || track.fit_content_limited_growth_limit(axis_inner_node_size) == f32::INFINITY
1128        }) {
1129            track.item_incurred_increase = item_incurred_increase;
1130        }
1131    } else {
1132        // 3. Distribute space beyond limits
1133        // If space remains after all tracks are frozen, unfreeze and continue to distribute space to the item-incurred increase
1134        // ...when handling any intrinsic growth limit: all affected tracks.
1135        distribute_space_up_to_limits(
1136            extra_space,
1137            tracks,
1138            track_is_affected,
1139            |_| 1.0,
1140            |track| if track.growth_limit == f32::INFINITY { track.base_size } else { track.growth_limit },
1141            move |track| track.fit_content_limit(axis_inner_node_size),
1142        );
1143    };
1144
1145    // 4. For each affected track, if the track’s item-incurred increase is larger than the track’s planned increase
1146    // set the track’s planned increase to that value.
1147    for track in tracks.iter_mut() {
1148        if track.item_incurred_increase > track.growth_limit_planned_increase {
1149            track.growth_limit_planned_increase = track.item_incurred_increase;
1150        }
1151
1152        // Reset the item_incurresed increase ready for the next space distribution
1153        track.item_incurred_increase = 0.0;
1154    }
1155}
1156
1157/// 11.6 Maximise Tracks
1158/// Distributes free space (if any) to tracks with FINITE growth limits, up to their limits.
1159#[inline(always)]
1160fn maximise_tracks(
1161    axis_tracks: &mut [GridTrack],
1162    axis_inner_node_size: Option<f32>,
1163    axis_available_grid_space: AvailableSpace,
1164) {
1165    let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
1166    let free_space = axis_available_grid_space.compute_free_space(used_space);
1167    if free_space == f32::INFINITY {
1168        axis_tracks.iter_mut().for_each(|track| track.base_size = track.growth_limit);
1169    } else if free_space > 0.0 {
1170        distribute_space_up_to_limits(
1171            free_space,
1172            axis_tracks,
1173            |_| true,
1174            |_| 1.0,
1175            |track| track.base_size,
1176            move |track: &GridTrack| track.fit_content_limited_growth_limit(axis_inner_node_size),
1177        );
1178        for track in axis_tracks.iter_mut() {
1179            track.base_size += track.item_incurred_increase;
1180            track.item_incurred_increase = 0.0;
1181        }
1182    }
1183}
1184
1185/// 11.7. Expand Flexible Tracks
1186/// This step sizes flexible tracks using the largest value it can assign to an fr without exceeding the available space.
1187#[allow(clippy::too_many_arguments)]
1188#[inline(always)]
1189fn expand_flexible_tracks(
1190    tree: &mut impl LayoutPartialTree,
1191    axis: AbstractAxis,
1192    axis_tracks: &mut [GridTrack],
1193    items: &mut [GridItem],
1194    axis_min_size: Option<f32>,
1195    axis_max_size: Option<f32>,
1196    axis_available_space_for_expansion: AvailableSpace,
1197) {
1198    // First, find the grid’s used flex fraction:
1199    let flex_fraction = match axis_available_space_for_expansion {
1200        // If the free space is zero:
1201        //    The used flex fraction is zero.
1202        // Otherwise, if the free space is a definite length:
1203        //   The used flex fraction is the result of finding the size of an fr using all of the grid tracks and
1204        //   a space to fill of the available grid space.
1205        AvailableSpace::Definite(available_space) => {
1206            let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
1207            let free_space = available_space - used_space;
1208            if free_space <= 0.0 {
1209                0.0
1210            } else {
1211                find_size_of_fr(axis_tracks, available_space)
1212            }
1213        }
1214        // If ... sizing the grid container under a min-content constraint the used flex fraction is zero.
1215        AvailableSpace::MinContent => 0.0,
1216        // Otherwise, if the free space is an indefinite length:
1217        AvailableSpace::MaxContent => {
1218            // The used flex fraction is the maximum of:
1219            let flex_fraction = f32_max(
1220                // For each flexible track, if the flexible track’s flex factor is greater than one,
1221                // the result of dividing the track’s base size by its flex factor; otherwise, the track’s base size.
1222                axis_tracks
1223                    .iter()
1224                    .filter(|track| track.max_track_sizing_function.is_fr())
1225                    .map(|track| {
1226                        let flex_factor = track.flex_factor();
1227                        if flex_factor > 1.0 {
1228                            track.base_size / flex_factor
1229                        } else {
1230                            track.base_size
1231                        }
1232                    })
1233                    .max_by(|a, b| a.total_cmp(b))
1234                    .unwrap_or(0.0),
1235                // For each grid item that crosses a flexible track, the result of finding the size of an fr using all the grid tracks
1236                // that the item crosses and a space to fill of the item’s max-content contribution.
1237                items
1238                    .iter_mut()
1239                    .filter(|item| item.crosses_flexible_track(axis))
1240                    .map(|item| {
1241                        let tracks = &axis_tracks[item.track_range_excluding_lines(axis)];
1242                        // TODO: plumb estimate of other axis size (known_dimensions) in here rather than just passing Size::NONE?
1243                        let max_content_contribution =
1244                            item.max_content_contribution_cached(axis, tree, Size::NONE, Size::NONE);
1245                        find_size_of_fr(tracks, max_content_contribution)
1246                    })
1247                    .max_by(|a, b| a.total_cmp(b))
1248                    .unwrap_or(0.0),
1249            );
1250
1251            // If using this flex fraction would cause the grid to be smaller than the grid container’s min-width/height (or larger than the
1252            // grid container’s max-width/height), then redo this step, treating the free space as definite and the available grid space as equal
1253            // to the grid container’s inner size when it’s sized to its min-width/height (max-width/height).
1254            // (Note: min_size takes precedence over max_size)
1255            let hypothetical_grid_size: f32 = axis_tracks
1256                .iter()
1257                .map(|track| {
1258                    if track.max_track_sizing_function.is_fr() {
1259                        let track_flex_factor = track.max_track_sizing_function.0.value();
1260                        f32_max(track.base_size, track_flex_factor * flex_fraction)
1261                    } else {
1262                        track.base_size
1263                    }
1264                })
1265                .sum();
1266            let axis_min_size = axis_min_size.unwrap_or(0.0);
1267            let axis_max_size = axis_max_size.unwrap_or(f32::INFINITY);
1268            if hypothetical_grid_size < axis_min_size {
1269                find_size_of_fr(axis_tracks, axis_min_size)
1270            } else if hypothetical_grid_size > axis_max_size {
1271                find_size_of_fr(axis_tracks, axis_max_size)
1272            } else {
1273                flex_fraction
1274            }
1275        }
1276    };
1277
1278    // For each flexible track, if the product of the used flex fraction and the track’s flex factor is greater
1279    // than the track’s base size, set its base size to that product.
1280    for track in axis_tracks.iter_mut().filter(|track| track.max_track_sizing_function.is_fr()) {
1281        let track_flex_factor = track.max_track_sizing_function.0.value();
1282        track.base_size = f32_max(track.base_size, track_flex_factor * flex_fraction);
1283    }
1284}
1285
1286/// 11.7.1. Find the Size of an fr
1287/// This algorithm finds the largest size that an fr unit can be without exceeding the target size.
1288/// It must be called with a set of grid tracks and some quantity of space to fill.
1289#[inline(always)]
1290fn find_size_of_fr(tracks: &[GridTrack], space_to_fill: f32) -> f32 {
1291    // Handle the trivial case where there is no space to fill
1292    // Do not remove as otherwise the loop below will loop infinitely
1293    if space_to_fill == 0.0 {
1294        return 0.0;
1295    }
1296
1297    // If the product of the hypothetical fr size (computed below) and any flexible track’s flex factor
1298    // is less than the track’s base size, then we must restart this algorithm treating all such tracks as inflexible.
1299    // We therefore wrap the entire algorithm in a loop, with an hypothetical_fr_size of INFINITY such that the above
1300    // condition can never be true for the first iteration.
1301    let mut hypothetical_fr_size = f32::INFINITY;
1302    let mut previous_iter_hypothetical_fr_size;
1303    loop {
1304        // Let leftover space be the space to fill minus the base sizes of the non-flexible grid tracks.
1305        // Let flex factor sum be the sum of the flex factors of the flexible tracks. If this value is less than 1, set it to 1 instead.
1306        // We compute both of these in a single loop to avoid iterating over the data twice
1307        let mut used_space = 0.0;
1308        let mut naive_flex_factor_sum = 0.0;
1309        for track in tracks.iter() {
1310            // Tracks for which flex_factor * hypothetical_fr_size < track.base_size are treated as inflexible
1311            if track.max_track_sizing_function.is_fr()
1312                && track.max_track_sizing_function.0.value() * hypothetical_fr_size >= track.base_size
1313            {
1314                naive_flex_factor_sum += track.max_track_sizing_function.0.value();
1315            } else {
1316                used_space += track.base_size;
1317            };
1318        }
1319        let leftover_space = space_to_fill - used_space;
1320        let flex_factor = f32_max(naive_flex_factor_sum, 1.0);
1321
1322        // Let the hypothetical fr size be the leftover space divided by the flex factor sum.
1323        previous_iter_hypothetical_fr_size = hypothetical_fr_size;
1324        hypothetical_fr_size = leftover_space / flex_factor;
1325
1326        // If the product of the hypothetical fr size and a flexible track’s flex factor is less than the track’s base size,
1327        // restart this algorithm treating all such tracks as inflexible.
1328        // We keep track of the hypothetical_fr_size
1329        let hypothetical_fr_size_is_valid = tracks.iter().all(|track| {
1330            if track.max_track_sizing_function.is_fr() {
1331                let flex_factor = track.max_track_sizing_function.0.value();
1332                flex_factor * hypothetical_fr_size >= track.base_size
1333                    || flex_factor * previous_iter_hypothetical_fr_size < track.base_size
1334            } else {
1335                true
1336            }
1337        });
1338        if hypothetical_fr_size_is_valid {
1339            break;
1340        }
1341    }
1342
1343    // Return the hypothetical fr size.
1344    hypothetical_fr_size
1345}
1346
1347/// 11.8. Stretch auto Tracks
1348/// This step expands tracks that have an auto max track sizing function by dividing any remaining positive, definite free space equally amongst them.
1349#[inline(always)]
1350fn stretch_auto_tracks(
1351    axis_tracks: &mut [GridTrack],
1352    axis_min_size: Option<f32>,
1353    axis_available_space_for_expansion: AvailableSpace,
1354) {
1355    let num_auto_tracks = axis_tracks.iter().filter(|track| track.max_track_sizing_function.is_auto()).count();
1356    if num_auto_tracks > 0 {
1357        let used_space: f32 = axis_tracks.iter().map(|track| track.base_size).sum();
1358
1359        // If the free space is indefinite, but the grid container has a definite min-width/height
1360        // use that size to calculate the free space for this step instead.
1361        let free_space = if axis_available_space_for_expansion.is_definite() {
1362            axis_available_space_for_expansion.compute_free_space(used_space)
1363        } else {
1364            match axis_min_size {
1365                Some(size) => size - used_space,
1366                None => 0.0,
1367            }
1368        };
1369        if free_space > 0.0 {
1370            let extra_space_per_auto_track = free_space / num_auto_tracks as f32;
1371            axis_tracks
1372                .iter_mut()
1373                .filter(|track| track.max_track_sizing_function.is_auto())
1374                .for_each(|track| track.base_size += extra_space_per_auto_track);
1375        }
1376    }
1377}
1378
1379/// Helper function for distributing space to tracks evenly
1380/// Used by both distribute_item_space_to_base_size and maximise_tracks steps
1381#[inline(always)]
1382fn distribute_space_up_to_limits(
1383    space_to_distribute: f32,
1384    tracks: &mut [GridTrack],
1385    track_is_affected: impl Fn(&GridTrack) -> bool,
1386    track_distribution_proportion: impl Fn(&GridTrack) -> f32,
1387    track_affected_property: impl Fn(&GridTrack) -> f32,
1388    track_limit: impl Fn(&GridTrack) -> f32,
1389) -> f32 {
1390    /// Define a small constant to avoid infinite loops due to rounding errors. Rather than stopping distributing
1391    /// extra space when it gets to exactly zero, we will stop when it falls below this amount
1392    const THRESHOLD: f32 = 0.01;
1393
1394    let mut space_to_distribute = space_to_distribute;
1395    while space_to_distribute > THRESHOLD {
1396        let track_distribution_proportion_sum: f32 = tracks
1397            .iter()
1398            .filter(|track| track_affected_property(track) + track.item_incurred_increase < track_limit(track))
1399            .filter(|track| track_is_affected(track))
1400            .map(&track_distribution_proportion)
1401            .sum();
1402
1403        if track_distribution_proportion_sum == 0.0 {
1404            break;
1405        }
1406
1407        // Compute item-incurred increase for this iteration
1408        let min_increase_limit = tracks
1409            .iter()
1410            .filter(|track| track_affected_property(track) + track.item_incurred_increase < track_limit(track))
1411            .filter(|track| track_is_affected(track))
1412            .map(|track| {
1413                (track_limit(track) - track_affected_property(track) - track.item_incurred_increase)
1414                    / track_distribution_proportion(track)
1415            })
1416            .min_by(|a, b| a.total_cmp(b))
1417            .unwrap(); // We will never pass an empty track list to this function
1418        let iteration_item_incurred_increase =
1419            f32_min(min_increase_limit, space_to_distribute / track_distribution_proportion_sum);
1420
1421        for track in tracks.iter_mut().filter(|track| track_is_affected(track)) {
1422            let increase = iteration_item_incurred_increase * track_distribution_proportion(track);
1423            if increase > 0.0
1424                && track_affected_property(track) + track.item_incurred_increase + increase
1425                    <= track_limit(track) + THRESHOLD
1426            {
1427                track.item_incurred_increase += increase;
1428                space_to_distribute -= increase;
1429            }
1430        }
1431    }
1432
1433    space_to_distribute
1434}