gioser

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 5544Rust 88Markdown 11TOML 91926 Sutichaykuna

⎇ 230ab9359bba75fdda0ff35319d082e79189046f src/compute/grid/mod.rs Rust · 782 siq'ikuna · 33.5 KB Ñawpa willay Pi imata llamkarqan ch'uya

implement `direction` property 230ab9359 · Kane Wang ·

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