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