Skip to main content

taffy/compute/grid/
mod.rs

1//! This module is a partial implementation of the CSS Grid Level 1 specification
2//! <https://www.w3.org/TR/css-grid-1>
3use crate::geometry::{AbsoluteAxis, AbstractAxis, InBothAbsAxis};
4use crate::geometry::{Line, Point, Rect, Size};
5use crate::style::{AlignItems, AlignSelf, AvailableSpace, Overflow, Position};
6use crate::tree::{Layout, LayoutInput, LayoutOutput, LayoutPartialTreeExt, NodeId, RunMode, SizingMode};
7use crate::util::debug::debug_log;
8use crate::util::sys::{f32_max, f32_min, GridTrackVec, Vec};
9use crate::util::MaybeMath;
10use crate::util::{MaybeResolve, ResolveOrZero};
11use crate::{
12    style_helpers::*, AlignContent, BoxGenerationMode, BoxSizing, CoreStyle, Direction, GridContainerStyle,
13    GridItemStyle, JustifyContent, LayoutGridContainer, RequestedAxis,
14};
15use alignment::{align_and_position_item, align_tracks};
16use explicit_grid::{compute_explicit_grid_size_in_axis, initialize_grid_tracks, AutoRepeatStrategy};
17use implicit_grid::compute_grid_size_estimate;
18use placement::place_grid_items;
19use track_sizing::{
20    determine_if_item_crosses_flexible_or_intrinsic_tracks, resolve_item_track_indexes, track_sizing_algorithm,
21};
22use types::{CellOccupancyMatrix, GridTrack, NamedLineResolver, TrackCounts};
23
24#[cfg(feature = "detailed_layout_info")]
25use types::{GridItem, GridTrackKind};
26
27pub(crate) use types::{GridCoordinate, GridLine, OriginZeroLine};
28
29mod alignment;
30mod explicit_grid;
31mod implicit_grid;
32mod placement;
33mod track_sizing;
34mod types;
35mod util;
36
37/// Grid layout algorithm
38/// This consists of a few phases:
39///   - Resolving the explicit grid
40///   - Placing items (which also resolves the implicit grid)
41///   - Track (row/column) sizing
42///   - Alignment & Final item placement
43pub fn compute_grid_layout<Tree: LayoutGridContainer>(
44    tree: &mut Tree,
45    node: NodeId,
46    inputs: LayoutInput,
47) -> LayoutOutput {
48    let LayoutInput { known_dimensions, parent_size, available_space, run_mode, .. } = inputs;
49
50    let style = tree.get_grid_container_style(node);
51    let direction = style.direction();
52
53    // 1. Compute "available grid space"
54    // https://www.w3.org/TR/css-grid-1/#available-grid-space
55    let aspect_ratio = style.aspect_ratio();
56    let padding = style.padding().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
57    let border = style.border().resolve_or_zero(parent_size.width, |val, basis| tree.calc(val, basis));
58    let padding_border = padding + border;
59    let padding_border_size = padding_border.sum_axes();
60    let box_sizing_adjustment =
61        if style.box_sizing() == BoxSizing::ContentBox { padding_border_size } else { Size::ZERO };
62
63    let min_size = style
64        .min_size()
65        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
66        .maybe_apply_aspect_ratio(aspect_ratio)
67        .maybe_add(box_sizing_adjustment);
68    let max_size = style
69        .max_size()
70        .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
71        .maybe_apply_aspect_ratio(aspect_ratio)
72        .maybe_add(box_sizing_adjustment);
73    let preferred_size = if inputs.sizing_mode == SizingMode::InherentSize {
74        style
75            .size()
76            .maybe_resolve(parent_size, |val, basis| tree.calc(val, basis))
77            .maybe_apply_aspect_ratio(style.aspect_ratio())
78            .maybe_add(box_sizing_adjustment)
79    } else {
80        Size::NONE
81    };
82
83    // Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
84    // However, the axis are switched (transposed) because a node that scrolls vertically needs
85    // *horizontal* space to be reserved for a scrollbar
86    let scrollbar_gutter = style.overflow().transpose().map(|overflow| match overflow {
87        Overflow::Scroll => style.scrollbar_width(),
88        _ => 0.0,
89    });
90    let mut content_box_inset = padding_border;
91    content_box_inset.bottom += scrollbar_gutter.y;
92
93    match direction {
94        Direction::Ltr => content_box_inset.right += scrollbar_gutter.x,
95        Direction::Rtl => content_box_inset.left += scrollbar_gutter.x,
96    };
97
98    let align_content = style.align_content().unwrap_or(AlignContent::STRETCH);
99    let justify_content = style.justify_content().unwrap_or(JustifyContent::STRETCH);
100    let align_items = style.align_items();
101    let justify_items = style.justify_items();
102
103    // Note: we avoid accessing the grid rows/columns methods more than once as this can
104    // cause an expensive-ish computation
105    let grid_template_columns = style.grid_template_columns();
106    let grid_template_rows = style.grid_template_rows();
107    let grid_auto_columns = style.grid_auto_columns();
108    let grid_auto_rows = style.grid_auto_rows();
109
110    let constrained_available_space = known_dimensions
111        .or(preferred_size)
112        .map(|size| size.map(AvailableSpace::Definite))
113        .unwrap_or(available_space)
114        .maybe_clamp(min_size, max_size)
115        .maybe_max(padding_border_size);
116
117    let available_grid_space = Size {
118        width: constrained_available_space
119            .width
120            .map_definite_value(|space| space - content_box_inset.horizontal_axis_sum()),
121        height: constrained_available_space
122            .height
123            .map_definite_value(|space| space - content_box_inset.vertical_axis_sum()),
124    };
125
126    let outer_node_size =
127        known_dimensions.or(preferred_size).maybe_clamp(min_size, max_size).maybe_max(padding_border_size);
128    let mut inner_node_size = Size {
129        width: outer_node_size.width.map(|space| space - content_box_inset.horizontal_axis_sum()),
130        height: outer_node_size.height.map(|space| space - content_box_inset.vertical_axis_sum()),
131    };
132
133    debug_log!("parent_size", dbg:parent_size);
134    debug_log!("outer_node_size", dbg:outer_node_size);
135    debug_log!("inner_node_size", dbg:inner_node_size);
136
137    // Short-circuit layout if the container's size is fully determined by the container's size and the run mode
138    // is ComputeSize (and thus the container's size is all that we're interested in)
139    if run_mode == RunMode::ComputeSize {
140        if let Size { width: Some(width), height: Some(height) } = outer_node_size {
141            return LayoutOutput::from_outer_size(Size { width, height });
142        }
143
144        // We can also short-circuit if the width is known and only the width has been requested.
145        if inputs.axis == RequestedAxis::Horizontal {
146            if let Some(width) = outer_node_size.width {
147                return LayoutOutput::from_outer_size(Size { width, height: 0.0 });
148            }
149        }
150    }
151
152    let get_child_styles_iter =
153        |node| tree.child_ids(node).map(|child_node: NodeId| tree.get_grid_child_style(child_node));
154    let child_styles_iter = get_child_styles_iter(node);
155
156    // 2. Resolve the explicit grid
157
158    // This is very similar to the inner_node_size except if the inner_node_size is not definite but the node
159    // has a min- or max- size style then that will be used in it's place.
160    let auto_fit_container_size = outer_node_size
161        .or(max_size)
162        .or(min_size)
163        .maybe_clamp(min_size, max_size)
164        .maybe_max(padding_border_size)
165        .maybe_sub(content_box_inset.sum_axes());
166
167    // If the grid container has a definite size or max size in the relevant axis:
168    //   - then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow the content
169    //     box of its grid container.
170    // Otherwise, if the grid container has a definite min size in the relevant axis:
171    //   - then the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement
172    // Otherwise, the specified track list repeats only once.
173    let auto_repeat_fit_strategy = outer_node_size.or(max_size).map(|val| match val {
174        Some(_) => AutoRepeatStrategy::MaxRepetitionsThatDoNotOverflow,
175        None => AutoRepeatStrategy::MinRepetitionsThatDoOverflow,
176    });
177
178    // Compute the number of rows and columns in the explicit grid *template*
179    // (explicit tracks from grid_areas are computed separately below)
180    let (col_auto_repetition_count, grid_template_col_count) = compute_explicit_grid_size_in_axis(
181        &style,
182        auto_fit_container_size.width,
183        auto_repeat_fit_strategy.width,
184        |val, basis| tree.calc(val, basis),
185        AbsoluteAxis::Horizontal,
186    );
187    let (row_auto_repetition_count, grid_template_row_count) = compute_explicit_grid_size_in_axis(
188        &style,
189        auto_fit_container_size.height,
190        auto_repeat_fit_strategy.height,
191        |val, basis| tree.calc(val, basis),
192        AbsoluteAxis::Vertical,
193    );
194
195    // type CustomIdent<'a> = <<Tree as LayoutPartialTree>::CoreContainerStyle<'_> as CoreStyle>::CustomIdent;
196    let mut name_resolver = NamedLineResolver::new(&style, col_auto_repetition_count, row_auto_repetition_count);
197
198    let explicit_col_count = grid_template_col_count.max(name_resolver.area_column_count());
199    let explicit_row_count = grid_template_row_count.max(name_resolver.area_row_count());
200
201    name_resolver.set_explicit_column_count(explicit_col_count);
202    name_resolver.set_explicit_row_count(explicit_row_count);
203
204    // 3. Implicit Grid: Estimate Track Counts
205    // Estimate the number of rows and columns in the implicit grid (= the entire grid)
206    // This is necessary as part of placement. Doing it early here is a perf optimisation to reduce allocations.
207    let (est_col_counts, est_row_counts) =
208        compute_grid_size_estimate(explicit_col_count, explicit_row_count, direction, child_styles_iter);
209
210    // 4. Grid Item Placement
211    // Match items (children) to a definite grid position (row start/end and column start/end position)
212    let mut items = Vec::with_capacity(tree.child_count(node));
213    let mut cell_occupancy_matrix = CellOccupancyMatrix::with_track_counts(est_col_counts, est_row_counts);
214    let in_flow_children_iter = || {
215        tree.child_ids(node)
216            .enumerate()
217            .map(|(index, child_node)| (index, child_node, tree.get_grid_child_style(child_node)))
218            .filter(|(_, _, style)| {
219                style.box_generation_mode() != BoxGenerationMode::None && style.position() != Position::Absolute
220            })
221    };
222    place_grid_items(
223        &mut cell_occupancy_matrix,
224        &mut items,
225        in_flow_children_iter,
226        direction,
227        style.grid_auto_flow(),
228        align_items.unwrap_or(AlignItems::STRETCH),
229        justify_items.unwrap_or(AlignItems::STRETCH),
230        &name_resolver,
231    );
232
233    // Extract track counts from previous step (auto-placement can expand the number of tracks)
234    let final_col_counts = *cell_occupancy_matrix.track_counts(AbsoluteAxis::Horizontal);
235    let final_row_counts = *cell_occupancy_matrix.track_counts(AbsoluteAxis::Vertical);
236
237    // 5. Initialize Tracks
238    // Initialize (explicit and implicit) grid tracks (and gutters)
239    // This resolves the min and max track sizing functions for all tracks and gutters
240    let mut columns = GridTrackVec::new();
241    let mut rows = GridTrackVec::new();
242    let mut column_track_counts_for_init = final_col_counts;
243    if direction.is_rtl() && final_col_counts.explicit <= 1 {
244        column_track_counts_for_init.negative_implicit = final_col_counts.positive_implicit;
245        column_track_counts_for_init.positive_implicit = final_col_counts.negative_implicit;
246    }
247    initialize_grid_tracks(
248        &mut columns,
249        column_track_counts_for_init,
250        &style,
251        AbsoluteAxis::Horizontal,
252        |column_index| {
253            let occupancy_index = if direction.is_rtl() {
254                rtl_column_occupancy_index_for_initialization(column_index, final_col_counts)
255            } else {
256                column_index
257            };
258            cell_occupancy_matrix.column_is_occupied(occupancy_index)
259        },
260    );
261    initialize_grid_tracks(&mut rows, final_row_counts, &style, AbsoluteAxis::Vertical, |row_index| {
262        cell_occupancy_matrix.row_is_occupied(row_index)
263    });
264    if direction.is_rtl() {
265        reverse_non_gutter_tracks(&mut columns, final_col_counts);
266    }
267
268    drop(grid_template_rows);
269    drop(grid_template_columns);
270    drop(grid_auto_rows);
271    drop(grid_auto_columns);
272    drop(style);
273
274    // 6. Track Sizing
275
276    // Convert grid placements in origin-zero coordinates to indexes into the GridTrack (rows and columns) vectors
277    // This computation is relatively trivial, but it requires the final number of negative (implicit) tracks in
278    // each axis, and doing it up-front here means we don't have to keep repeating that calculation
279    resolve_item_track_indexes(&mut items, final_col_counts, final_row_counts);
280    // For each item, and in each axis, determine whether the item crosses any flexible (fr) tracks
281    // Record this as a boolean (per-axis) on each item for later use in the track-sizing algorithm
282    determine_if_item_crosses_flexible_or_intrinsic_tracks(&mut items, &columns, &rows);
283
284    // Determine if the grid has any baseline aligned items
285    let has_baseline_aligned_item = items.iter().any(|item| item.align_self == AlignSelf::BASELINE);
286
287    // Run track sizing algorithm for Inline axis
288    track_sizing_algorithm(
289        tree,
290        AbstractAxis::Inline,
291        min_size.get(AbstractAxis::Inline),
292        max_size.get(AbstractAxis::Inline),
293        justify_content,
294        align_content,
295        available_grid_space,
296        inner_node_size,
297        &mut columns,
298        &mut rows,
299        &mut items,
300        |track: &GridTrack, parent_size: Option<f32>, tree: &Tree| {
301            track.max_track_sizing_function.definite_value(parent_size, |val, basis| tree.calc(val, basis))
302        },
303        has_baseline_aligned_item,
304    );
305    let initial_column_sum = columns.iter().map(|track| track.base_size).sum::<f32>();
306    inner_node_size.width = inner_node_size.width.or_else(|| initial_column_sum.into());
307
308    items.iter_mut().for_each(|item| item.grid_area_size_cache = None);
309
310    // Run track sizing algorithm for Block axis
311    track_sizing_algorithm(
312        tree,
313        AbstractAxis::Block,
314        min_size.get(AbstractAxis::Block),
315        max_size.get(AbstractAxis::Block),
316        align_content,
317        justify_content,
318        available_grid_space,
319        inner_node_size,
320        &mut rows,
321        &mut columns,
322        &mut items,
323        |track: &GridTrack, _, _| Some(track.base_size),
324        false, // TODO: Support baseline alignment in the vertical axis
325    );
326    let initial_row_sum = rows.iter().map(|track| track.base_size).sum::<f32>();
327    inner_node_size.height = inner_node_size.height.or_else(|| initial_row_sum.into());
328
329    debug_log!("initial_column_sum", dbg:initial_column_sum);
330    debug_log!(dbg: columns.iter().map(|track| track.base_size).collect::<Vec<_>>());
331    debug_log!("initial_row_sum", dbg:initial_row_sum);
332    debug_log!(dbg: rows.iter().map(|track| track.base_size).collect::<Vec<_>>());
333
334    // 6. Compute container size
335    let resolved_style_size = known_dimensions.or(preferred_size);
336    let mut container_border_box = Size {
337        width: resolved_style_size
338            .get(AbstractAxis::Inline)
339            .unwrap_or_else(|| initial_column_sum + content_box_inset.horizontal_axis_sum())
340            .maybe_clamp(min_size.width, max_size.width)
341            .max(padding_border_size.width),
342        height: resolved_style_size
343            .get(AbstractAxis::Block)
344            .unwrap_or_else(|| initial_row_sum + content_box_inset.vertical_axis_sum())
345            .maybe_clamp(min_size.height, max_size.height)
346            .max(padding_border_size.height),
347    };
348    let mut container_content_box = Size {
349        width: f32_max(0.0, container_border_box.width - content_box_inset.horizontal_axis_sum()),
350        height: f32_max(0.0, container_border_box.height - content_box_inset.vertical_axis_sum()),
351    };
352
353    // If only the container's size has been requested
354    if run_mode == RunMode::ComputeSize {
355        return LayoutOutput::from_outer_size(container_border_box);
356    }
357
358    // 7. Resolve percentage track base sizes
359    // In the case of an indefinitely sized container these resolve to zero during the "Initialise Tracks" step
360    // and therefore need to be re-resolved here based on the content-sized content box of the container
361    if !available_grid_space.width.is_definite() {
362        for column in &mut columns {
363            let min: Option<f32> = column
364                .min_track_sizing_function
365                .resolved_percentage_size(container_content_box.width, |val, basis| tree.calc(val, basis));
366            let max: Option<f32> = column
367                .max_track_sizing_function
368                .resolved_percentage_size(container_content_box.width, |val, basis| tree.calc(val, basis));
369            column.base_size = column.base_size.maybe_clamp(min, max);
370        }
371    }
372    if !available_grid_space.height.is_definite() {
373        for row in &mut rows {
374            let min: Option<f32> = row
375                .min_track_sizing_function
376                .resolved_percentage_size(container_content_box.height, |val, basis| tree.calc(val, basis));
377            let max: Option<f32> = row
378                .max_track_sizing_function
379                .resolved_percentage_size(container_content_box.height, |val, basis| tree.calc(val, basis));
380            row.base_size = row.base_size.maybe_clamp(min, max);
381        }
382    }
383
384    // Column sizing must be re-run (once) if:
385    //   - The grid container's width was initially indefinite and there are any columns with percentage track sizing functions
386    //   - Any grid item crossing an intrinsically sized track's min content contribution width has changed
387    // TODO: Only rerun sizing for tracks that actually require it rather than for all tracks if any need it.
388    let mut rerun_column_sizing;
389    let mut intrinsic_column_contribution_changed = false;
390
391    let has_percentage_column = columns.iter().any(|track| track.uses_percentage());
392    let has_percentage_row = rows.iter().any(|track| track.uses_percentage());
393    let parent_width_indefinite = !available_space.width.is_definite();
394    rerun_column_sizing = parent_width_indefinite && has_percentage_column;
395
396    if !rerun_column_sizing {
397        intrinsic_column_contribution_changed =
398            items.iter_mut().filter(|item| item.crosses_intrinsic_column).any(|item| {
399                let grid_area_size = item.grid_area_size(
400                    AbstractAxis::Inline,
401                    &columns,
402                    &rows,
403                    inner_node_size,
404                    |track: &GridTrack, _| Some(track.base_size),
405                    &|val, basis| tree.calc(val, basis),
406                );
407                let available_space = grid_area_size.with(AbstractAxis::Inline, None);
408                let new_min_content_contribution =
409                    item.min_content_contribution(AbstractAxis::Inline, tree, grid_area_size, available_space);
410
411                let has_changed = Some(new_min_content_contribution) != item.min_content_contribution_cache.width;
412
413                item.grid_area_size_cache = Some(grid_area_size);
414                item.min_content_contribution_cache.width = Some(new_min_content_contribution);
415                item.max_content_contribution_cache.width = None;
416                item.minimum_contribution_cache.width = None;
417
418                has_changed
419            });
420        rerun_column_sizing = intrinsic_column_contribution_changed;
421    } else {
422        // Clear intrinsic width caches
423        items.iter_mut().for_each(|item| {
424            item.grid_area_size_cache = None;
425            item.min_content_contribution_cache.width = None;
426            item.max_content_contribution_cache.width = None;
427            item.minimum_contribution_cache.width = None;
428        });
429    }
430
431    let mut intrinsic_row_contribution_changed = false;
432
433    if rerun_column_sizing {
434        // Re-run track sizing algorithm for Inline axis
435        track_sizing_algorithm(
436            tree,
437            AbstractAxis::Inline,
438            min_size.get(AbstractAxis::Inline),
439            max_size.get(AbstractAxis::Inline),
440            justify_content,
441            align_content,
442            available_grid_space,
443            inner_node_size,
444            &mut columns,
445            &mut rows,
446            &mut items,
447            |track: &GridTrack, _, _| Some(track.base_size),
448            has_baseline_aligned_item,
449        );
450
451        // Row sizing must be re-run (once) if:
452        //   - The grid container's height was initially indefinite and there are any rows with percentage track sizing functions
453        //   - Any grid item crossing an intrinsically sized track's min content contribution height has changed
454        // TODO: Only rerun sizing for tracks that actually require it rather than for all tracks if any need it.
455        let mut rerun_row_sizing;
456
457        let parent_height_indefinite = !available_space.height.is_definite();
458        rerun_row_sizing = parent_height_indefinite && has_percentage_row;
459
460        if !rerun_row_sizing {
461            intrinsic_row_contribution_changed =
462                items.iter_mut().filter(|item| item.crosses_intrinsic_column).any(|item| {
463                    let grid_area_size = item.grid_area_size(
464                        AbstractAxis::Block,
465                        &rows,
466                        &columns,
467                        inner_node_size,
468                        |track: &GridTrack, _| Some(track.base_size),
469                        &|val, basis| tree.calc(val, basis),
470                    );
471                    let available_space = grid_area_size.with(AbstractAxis::Block, None);
472                    let new_min_content_contribution =
473                        item.min_content_contribution(AbstractAxis::Block, tree, grid_area_size, available_space);
474
475                    let has_changed = Some(new_min_content_contribution) != item.min_content_contribution_cache.height;
476
477                    item.grid_area_size_cache = Some(grid_area_size);
478                    item.min_content_contribution_cache.height = Some(new_min_content_contribution);
479                    item.max_content_contribution_cache.height = None;
480                    item.minimum_contribution_cache.height = None;
481
482                    has_changed
483                });
484            rerun_row_sizing = intrinsic_row_contribution_changed;
485        } else {
486            items.iter_mut().for_each(|item| {
487                // Clear intrinsic height caches
488                item.grid_area_size_cache = None;
489                item.min_content_contribution_cache.height = None;
490                item.max_content_contribution_cache.height = None;
491                item.minimum_contribution_cache.height = None;
492            });
493        }
494
495        if rerun_row_sizing {
496            // Re-run track sizing algorithm for Block axis
497            track_sizing_algorithm(
498                tree,
499                AbstractAxis::Block,
500                min_size.get(AbstractAxis::Block),
501                max_size.get(AbstractAxis::Block),
502                align_content,
503                justify_content,
504                available_grid_space,
505                inner_node_size,
506                &mut rows,
507                &mut columns,
508                &mut items,
509                |track: &GridTrack, _, _| Some(track.base_size),
510                false, // TODO: Support baseline alignment in the vertical axis
511            );
512        }
513    }
514
515    if (intrinsic_column_contribution_changed && !has_percentage_column)
516        || (intrinsic_row_contribution_changed && !has_percentage_row)
517    {
518        let final_column_sum = columns.iter().map(|track| track.base_size).sum::<f32>();
519        let final_row_sum = rows.iter().map(|track| track.base_size).sum::<f32>();
520
521        if intrinsic_column_contribution_changed && !has_percentage_column {
522            container_border_box.width = resolved_style_size
523                .get(AbstractAxis::Inline)
524                .unwrap_or_else(|| final_column_sum + content_box_inset.horizontal_axis_sum())
525                .maybe_clamp(min_size.width, max_size.width)
526                .max(padding_border_size.width);
527            container_content_box.width =
528                f32_max(0.0, container_border_box.width - content_box_inset.horizontal_axis_sum());
529        }
530
531        if intrinsic_row_contribution_changed && !has_percentage_row {
532            container_border_box.height = resolved_style_size
533                .get(AbstractAxis::Block)
534                .unwrap_or_else(|| final_row_sum + content_box_inset.vertical_axis_sum())
535                .maybe_clamp(min_size.height, max_size.height)
536                .max(padding_border_size.height);
537            container_content_box.height =
538                f32_max(0.0, container_border_box.height - content_box_inset.vertical_axis_sum());
539        }
540    }
541
542    // If only the container's size has been requested
543    if run_mode == RunMode::ComputeSize {
544        return LayoutOutput::from_outer_size(container_border_box);
545    }
546
547    // 8. Track Alignment
548
549    // Align columns
550    let inline_size_without_scrollbar = f32_max(container_border_box.width - padding_border_size.width, 0.0);
551    let inline_scrollbar_gutter_for_alignment = f32_min(scrollbar_gutter.x, inline_size_without_scrollbar);
552    align_tracks(
553        container_content_box.get(AbstractAxis::Inline),
554        Line {
555            start: padding.left + if direction.is_rtl() { inline_scrollbar_gutter_for_alignment } else { 0.0 },
556            end: padding.right + if direction.is_rtl() { 0.0 } else { inline_scrollbar_gutter_for_alignment },
557        },
558        Line { start: border.left, end: border.right },
559        &mut columns,
560        justify_content,
561        direction.is_rtl(),
562    );
563    // Align rows
564    align_tracks(
565        container_content_box.get(AbstractAxis::Block),
566        Line { start: padding.top, end: padding.bottom },
567        Line { start: border.top, end: border.bottom },
568        &mut rows,
569        align_content,
570        false,
571    );
572
573    // 9. Size, Align, and Position Grid Items
574
575    #[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
576    let mut item_content_size_contribution = Size::ZERO;
577
578    // Sort items back into original order to allow them to be matched up with styles
579    items.sort_by_key(|item| item.source_order);
580
581    let container_alignment_styles = InBothAbsAxis { horizontal: justify_items, vertical: align_items };
582
583    // Position in-flow children (stored in items vector)
584    for (index, item) in items.iter_mut().enumerate() {
585        let grid_area = Rect {
586            top: rows[item.row_indexes.start as usize + 1].offset,
587            bottom: rows[item.row_indexes.end as usize].offset,
588            left: columns[item.column_indexes.start as usize + 1].offset,
589            right: columns[item.column_indexes.end as usize].offset,
590        };
591        #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
592        let (content_size_contribution, y_position, height) = align_and_position_item(
593            tree,
594            item.node,
595            index as u32,
596            grid_area,
597            container_alignment_styles,
598            item.baseline_shim,
599            direction,
600        );
601        item.y_position = y_position;
602        item.height = height;
603
604        #[cfg(feature = "content_size")]
605        {
606            item_content_size_contribution = item_content_size_contribution.f32_max(content_size_contribution);
607        }
608    }
609
610    // Position hidden and absolutely positioned children
611    let mut order = items.len() as u32;
612    (0..tree.child_count(node)).for_each(|index| {
613        let child = tree.get_child_id(node, index);
614        let child_style = tree.get_grid_child_style(child);
615
616        // Position hidden child
617        if child_style.box_generation_mode() == BoxGenerationMode::None {
618            drop(child_style);
619            tree.set_unrounded_layout(child, &Layout::with_order(order));
620            tree.perform_child_layout(
621                child,
622                Size::NONE,
623                Size::NONE,
624                Size::MAX_CONTENT,
625                SizingMode::InherentSize,
626                Line::FALSE,
627            );
628            order += 1;
629            return;
630        }
631
632        // Position absolutely positioned child
633        if child_style.position() == Position::Absolute {
634            // Convert grid-col-{start/end} into Option's of indexes into the columns vector
635            // The Option is None if the style property is Auto and an unresolvable Span
636            let maybe_col_indexes = name_resolver
637                .resolve_column_names(&child_style.grid_column())
638                .into_origin_zero(final_col_counts.explicit)
639                .resolve_absolutely_positioned_grid_tracks()
640                .map(|maybe_grid_line| {
641                    maybe_grid_line
642                        .map(|line: OriginZeroLine| {
643                            if direction.is_rtl() {
644                                OriginZeroLine(final_col_counts.explicit as i16 - line.0)
645                            } else {
646                                line
647                            }
648                        })
649                        .and_then(|line| line.try_into_track_vec_index(final_col_counts))
650                });
651            let maybe_col_indexes = if direction.is_rtl() {
652                Line { start: maybe_col_indexes.end, end: maybe_col_indexes.start }
653            } else {
654                maybe_col_indexes
655            };
656            // Convert grid-row-{start/end} into Option's of indexes into the row vector
657            // The Option is None if the style property is Auto and an unresolvable Span
658            let maybe_row_indexes = name_resolver
659                .resolve_row_names(&child_style.grid_row())
660                .into_origin_zero(final_row_counts.explicit)
661                .resolve_absolutely_positioned_grid_tracks()
662                .map(|maybe_grid_line| {
663                    maybe_grid_line.and_then(|line: OriginZeroLine| line.try_into_track_vec_index(final_row_counts))
664                });
665
666            let grid_area = Rect {
667                top: maybe_row_indexes.start.map(|index| rows[index].offset).unwrap_or(border.top),
668                bottom: maybe_row_indexes
669                    .end
670                    .map(|index| rows[index].offset)
671                    .unwrap_or(container_border_box.height - border.bottom - scrollbar_gutter.y),
672                left: maybe_col_indexes.start.map(|index| columns[index].offset).unwrap_or_else(|| {
673                    if direction.is_rtl() {
674                        border.left + scrollbar_gutter.x
675                    } else {
676                        border.left
677                    }
678                }),
679                right: maybe_col_indexes.end.map(|index| columns[index].offset).unwrap_or_else(|| {
680                    if direction.is_rtl() {
681                        container_border_box.width - border.right
682                    } else {
683                        container_border_box.width - border.right - scrollbar_gutter.x
684                    }
685                }),
686            };
687            drop(child_style);
688
689            // TODO: Baseline alignment support for absolutely positioned items (should check if is actually specified)
690            #[cfg_attr(not(feature = "content_size"), allow(unused_variables))]
691            let (content_size_contribution, _, _) =
692                align_and_position_item(tree, child, order, grid_area, container_alignment_styles, 0.0, direction);
693            #[cfg(feature = "content_size")]
694            {
695                item_content_size_contribution = item_content_size_contribution.f32_max(content_size_contribution);
696            }
697
698            order += 1;
699        }
700    });
701
702    // Set detailed grid information
703    #[cfg(feature = "detailed_layout_info")]
704    tree.set_detailed_grid_info(
705        node,
706        DetailedGridInfo {
707            rows: DetailedGridTracksInfo::from_grid_tracks_and_track_count(final_row_counts, rows),
708            columns: DetailedGridTracksInfo::from_grid_tracks_and_track_count(final_col_counts, columns),
709            items: items.iter().map(DetailedGridItemsInfo::from_grid_item).collect(),
710        },
711    );
712
713    // If there are not items then return just the container size (no baseline)
714    if items.is_empty() {
715        return LayoutOutput::from_outer_size(container_border_box);
716    }
717
718    // Determine the grid container baseline(s) (currently we only compute the first baseline)
719    let grid_container_baseline: f32 = {
720        // Sort items by row start position so that we can iterate items in groups which are in the same row
721        items.sort_by_key(|item| item.row_indexes.start);
722
723        // Get the row index of the first row containing items
724        let first_row = items[0].row_indexes.start;
725
726        // Create a slice of all of the items start in this row (taking advantage of the fact that we have just sorted the array)
727        let first_row_items = &items[0..].split(|item| item.row_indexes.start != first_row).next().unwrap();
728
729        // Check if any items in *this row* are baseline aligned
730        let row_has_baseline_item = first_row_items.iter().any(|item| item.align_self == AlignSelf::BASELINE);
731
732        let item = if row_has_baseline_item {
733            first_row_items.iter().find(|item| item.align_self == AlignSelf::BASELINE).unwrap()
734        } else {
735            &first_row_items[0]
736        };
737
738        item.y_position + item.baseline.unwrap_or(item.height)
739    };
740
741    LayoutOutput::from_sizes_and_baselines(
742        container_border_box,
743        item_content_size_contribution,
744        Point { x: None, y: Some(grid_container_baseline) },
745    )
746}
747
748/// Reverses only non-gutter column tracks in-place while preserving line/gutter slots.
749fn reverse_non_gutter_tracks(tracks: &mut [GridTrack], track_counts: TrackCounts) {
750    // When the explicit grid has 0/1 tracks, visual RTL mirroring is entirely determined by implicit tracks.
751    // Reverse all non-gutter tracks in that case.
752    if track_counts.explicit <= 1 {
753        const MIN_TRACK_VEC_LEN_TO_REVERSE_COLUMNS: usize = 5;
754        if tracks.len() < MIN_TRACK_VEC_LEN_TO_REVERSE_COLUMNS {
755            return;
756        }
757        let mut left = 1;
758        let mut right = tracks.len() - 2;
759        while left < right {
760            tracks.swap(left, right);
761            left += 2;
762            right = right.saturating_sub(2);
763        }
764        return;
765    }
766
767    let explicit_track_count = track_counts.explicit as usize;
768    if explicit_track_count < 2 {
769        return;
770    }
771
772    let mut left = track_counts.negative_implicit as usize;
773    let mut right = left + explicit_track_count - 1;
774    while left < right {
775        tracks.swap((2 * left) + 1, (2 * right) + 1);
776        left += 1;
777        right = right.saturating_sub(1);
778    }
779}
780
781/// Maps initialized column indexes to occupancy-matrix indexes for auto-fit collapsing in RTL.
782fn rtl_column_occupancy_index_for_initialization(column_index: usize, track_counts: TrackCounts) -> usize {
783    if track_counts.explicit <= 1 {
784        return track_counts.len() - column_index - 1;
785    }
786
787    let explicit_start = track_counts.negative_implicit as usize;
788    let explicit_end = explicit_start + track_counts.explicit as usize;
789    if (explicit_start..explicit_end).contains(&column_index) {
790        explicit_start + (explicit_end - column_index - 1)
791    } else {
792        column_index
793    }
794}
795
796/// Information from the computation of grid
797#[derive(Debug, Clone, PartialEq)]
798#[cfg(feature = "detailed_layout_info")]
799pub struct DetailedGridInfo {
800    /// <https://drafts.csswg.org/css-grid-1/#grid-row>
801    pub rows: DetailedGridTracksInfo,
802    /// <https://drafts.csswg.org/css-grid-1/#grid-column>
803    pub columns: DetailedGridTracksInfo,
804    /// <https://drafts.csswg.org/css-grid-1/#grid-items>
805    pub items: Vec<DetailedGridItemsInfo>,
806}
807
808/// Information from the computation of grids tracks
809#[derive(Debug, Clone, PartialEq)]
810#[cfg(feature = "detailed_layout_info")]
811pub struct DetailedGridTracksInfo {
812    /// Number of leading implicit grid tracks
813    pub negative_implicit_tracks: u16,
814    /// Number of explicit grid tracks
815    pub explicit_tracks: u16,
816    /// Number of trailing implicit grid tracks
817    pub positive_implicit_tracks: u16,
818
819    /// Gutters between tracks
820    pub gutters: Vec<f32>,
821    /// The used size of the tracks
822    pub sizes: Vec<f32>,
823}
824
825#[cfg(feature = "detailed_layout_info")]
826impl DetailedGridTracksInfo {
827    /// Get the base_size of [`GridTrack`] with a kind [`types::GridTrackKind`]
828    #[inline(always)]
829    fn grid_track_base_size_of_kind(grid_tracks: &[GridTrack], kind: GridTrackKind) -> Vec<f32> {
830        grid_tracks
831            .iter()
832            .filter_map(|track| match track.kind == kind {
833                true => Some(track.base_size),
834                false => None,
835            })
836            .collect()
837    }
838
839    /// Get the sizes of the gutters
840    fn gutters_from_grid_track_layout(grid_tracks: &[GridTrack]) -> Vec<f32> {
841        DetailedGridTracksInfo::grid_track_base_size_of_kind(grid_tracks, GridTrackKind::Gutter)
842    }
843
844    /// Get the sizes of the tracks
845    fn sizes_from_grid_track_layout(grid_tracks: &[GridTrack]) -> Vec<f32> {
846        DetailedGridTracksInfo::grid_track_base_size_of_kind(grid_tracks, GridTrackKind::Track)
847    }
848
849    /// Construct DetailedGridTracksInfo from TrackCounts and GridTracks
850    fn from_grid_tracks_and_track_count(track_count: TrackCounts, grid_tracks: Vec<GridTrack>) -> Self {
851        DetailedGridTracksInfo {
852            negative_implicit_tracks: track_count.negative_implicit,
853            explicit_tracks: track_count.explicit,
854            positive_implicit_tracks: track_count.positive_implicit,
855            gutters: DetailedGridTracksInfo::gutters_from_grid_track_layout(&grid_tracks),
856            sizes: DetailedGridTracksInfo::sizes_from_grid_track_layout(&grid_tracks),
857        }
858    }
859}
860
861/// Grid area information from the placement algorithm
862///
863/// The values is 1-indexed grid line numbers bounding the area.
864/// This matches the Chrome and Firefox's format as of 2nd Jan 2024.
865#[derive(Debug, Clone, PartialEq)]
866#[cfg(feature = "detailed_layout_info")]
867pub struct DetailedGridItemsInfo {
868    /// row-start with 1-indexed grid line numbers
869    pub row_start: u16,
870    /// row-end with 1-indexed grid line numbers
871    pub row_end: u16,
872    /// column-start with 1-indexed grid line numbers
873    pub column_start: u16,
874    /// column-end with 1-indexed grid line numbers
875    pub column_end: u16,
876}
877
878/// Grid area information from the placement algorithm
879#[cfg(feature = "detailed_layout_info")]
880impl DetailedGridItemsInfo {
881    /// Construct from GridItems
882    #[inline(always)]
883    fn from_grid_item(grid_item: &GridItem) -> Self {
884        /// Conversion from the indexes of Vec<GridTrack> into 1-indexed grid line numbers. See [`GridItem::row_indexes`] or [`GridItem::column_indexes`]
885        #[inline(always)]
886        fn to_one_indexed_grid_line(grid_track_index: u16) -> u16 {
887            grid_track_index / 2 + 1
888        }
889
890        DetailedGridItemsInfo {
891            row_start: to_one_indexed_grid_line(grid_item.row_indexes.start),
892            row_end: to_one_indexed_grid_line(grid_item.row_indexes.end),
893            column_start: to_one_indexed_grid_line(grid_item.column_indexes.start),
894            column_end: to_one_indexed_grid_line(grid_item.column_indexes.end),
895        }
896    }
897}