tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 231Rust 9TOML 3CSS 1345 Sutichaykuna

⎇ 9383fd4d33c14b9b1e4d0cff3c59f668f6d4eb4f src/compute/grid/mod.rs Rust · 717 siq'ikuna · 30.1 KB Ñawpa willay Pi imata llamkarqan ch'uya

Fix grid info for empty grid (#782) 9383fd4d3 · Steven Novaryo ·

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