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