Skip to main content

native_gui_core/layout/
grid.rs

1//! Owned native-GUI grid layout solver.
2//!
3//! Implements the frozen grid contract from `docs/design/owned-layout-engine.md`
4//! (sections 2, 3, and 7) as an native-gui-owned solver, consistent with the owned
5//! flexbox solver in [`super::flex`]:
6//!
7//! - Track sizing: `Fixed(px)`, `Percent(%)`, `Flex(fr)`, `Auto`, and `MinMax(min, max)`.
8//! - Placement: explicit 1-based start line + span, plus sequential row-major
9//!   (`GridAutoFlow::Row`) or column-major (`GridAutoFlow::Column`) auto flow.
10//! - Sparse placement only. Dense packing and subgrid are rejected by the
11//!   contract (keyboard-accessibility invariant) and are not modeled here.
12//! - Gaps are applied *between* tracks only, never outside the track set.
13//! - Items are positioned within their grid area by `justify` (inline axis) and
14//!   `align` (block axis), defaulting to `Start`.
15//!
16//! Numerical invariants: all inputs are required to be finite; resolved
17//! dimensions are clamped to be non-negative; percentage track sizes resolve
18//! against the container's content box; percentage item sizes resolve against
19//! the item's grid area.
20//!
21//! The solver is a pure function of the container style, container content box,
22//! available space, and the in-flow children (id, style, hypothetical border-box
23//! size), returning one [`LayoutRect`] per child. It is invoked from
24//! `super::tree::LayoutTree::solve_node_depth` when a node's
25//! `Style::display` is [`super::Display::Grid`].
26
27use crate::error::{GuiError, GuiResult};
28use crate::layout::box_sizing::{resolve_dimension, BoxConstraints};
29use crate::layout::{
30    AlignItems, AlignSelf, AvailableSpace, Dimension, GridAutoFlow, LayoutNodeId, LayoutRect,
31    Point, Size, Style, TrackSizingFunction,
32};
33
34/// A single classified grid track on one axis, after definite-size resolution.
35#[derive(Debug, Clone, Copy, PartialEq)]
36enum Track {
37    /// A definite size in logical pixels (from `Fixed`, `Percent`, `Auto`, or a
38    /// definite `MinMax` bound).
39    Fixed(f32),
40    /// A flexible track contributing `weight` fractional shares, floored at `floor`.
41    Flex {
42        /// Minimum resolved size for this track (wins when the grid overflows).
43        floor: f32,
44        /// Fractional weight (`fr`); non-negative and finite.
45        weight: f32,
46    },
47}
48
49/// An in-flow (non-hidden) grid child, referencing its position in the original
50/// `children` list so its style can be looked up without borrowing issues.
51#[derive(Debug, Clone, Copy)]
52struct ActiveChild {
53    /// Index into the original `children` slice.
54    idx: usize,
55    /// The child's hypothetical border-box size (fallback for `Auto` item sizes).
56    hypo: Size<f32>,
57}
58
59/// Placement of one in-flow grid child on the two track axes (0-based).
60#[derive(Debug, Clone, Copy)]
61struct PlacedItem {
62    /// Index of this child within the `active` list.
63    active_idx: usize,
64    /// 0-based index of the first row track occupied.
65    row_start: usize,
66    /// Number of row tracks spanned (>= 1).
67    row_span: usize,
68    /// 0-based index of the first column track occupied.
69    col_start: usize,
70    /// Number of column tracks spanned (>= 1).
71    col_span: usize,
72}
73
74/// Computes owned native-GUI grid layout for a container and its in-flow children.
75///
76/// `container_inner` is the container's content box (after padding),
77/// `available_space` is the resolved available space, and `children` are the
78/// in-flow children as `(id, style, hypothetical border-box size)` tuples.
79/// Returns one placed [`LayoutRect`] per child, in the original child order.
80pub fn compute_grid(
81    container_style: &Style,
82    container_inner: Size<f32>,
83    available_space: Size<AvailableSpace>,
84    children: &[(LayoutNodeId, Style, Size<f32>)],
85    content_origin: Point<f32>,
86) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
87    if children.is_empty() {
88        return Ok(Vec::new());
89    }
90
91    // Separate hidden (Display::None) children: they collapse to 0x0 and take no
92    // part in track creation, sizing, or auto placement (consistent with the
93    // owned flexbox path and the FIX-LFC-001 hidden-node contract). We record the
94    // original child index so output stays in input order.
95    let mut hidden: Vec<usize> = Vec::new();
96    let mut active: Vec<ActiveChild> = Vec::with_capacity(children.len());
97    for (idx, (_id, style, hypo)) in children.iter().enumerate() {
98        if style.display == crate::layout::Display::None {
99            hidden.push(idx);
100        } else {
101            active.push(ActiveChild { idx, hypo: *hypo });
102        }
103    }
104
105    let gap_col = resolve_gap(container_style, true, available_space.width)?;
106    let gap_row = resolve_gap(container_style, false, available_space.height)?;
107
108    let mut placements: Vec<PlacedItem> = Vec::with_capacity(active.len());
109    let (total_rows, total_cols) = place_items(&active, children, container_style, &mut placements);
110
111    // Size the tracks on each axis and derive cumulative line positions.
112    let col_sizes = size_axis_tracks(
113        total_cols,
114        &container_style.grid_template_columns,
115        &container_style.grid_auto_columns,
116        &placements,
117        &active,
118        true,
119        container_inner.width,
120        gap_col,
121    )?;
122    let row_sizes = size_axis_tracks(
123        total_rows,
124        &container_style.grid_template_rows,
125        &container_style.grid_auto_rows,
126        &placements,
127        &active,
128        false,
129        container_inner.height,
130        gap_row,
131    )?;
132
133    let col_pos = line_positions(&col_sizes, gap_col);
134    let row_pos = line_positions(&row_sizes, gap_row);
135
136    // Build the output in the original child order. Placed children use their
137    // placement (keyed by the original child index); hidden children collapse to
138    // a 0x0 box at the content origin.
139    let mut hidden_set = std::collections::HashSet::new();
140    for &idx in &hidden {
141        hidden_set.insert(idx);
142    }
143
144    let mut active_by_child_idx: std::collections::HashMap<usize, usize> =
145        std::collections::HashMap::new();
146    for (active_idx, ac) in active.iter().enumerate() {
147        active_by_child_idx.insert(ac.idx, active_idx);
148    }
149
150    let mut out: Vec<(LayoutNodeId, LayoutRect)> = Vec::with_capacity(children.len());
151    for (idx, (id, _, _)) in children.iter().enumerate() {
152        if hidden_set.contains(&idx) {
153            out.push((
154                *id,
155                LayoutRect::new(content_origin.x, content_origin.y, 0.0, 0.0),
156            ));
157            continue;
158        }
159
160        let active_idx = active_by_child_idx[&idx];
161        let p = placements[active_idx];
162        let ac = active[active_idx];
163        let style = &children[idx].1;
164
165        let area_w = area_size(&col_sizes, p.col_start, p.col_span, gap_col);
166        let area_h = area_size(&row_sizes, p.row_start, p.row_span, gap_row);
167        let area_x = col_pos[p.col_start];
168        let area_y = row_pos[p.row_start];
169
170        let item_w = resolve_item_size(
171            &style.size.width,
172            &style.min_size.width,
173            &style.max_size.width,
174            area_w,
175            ac.hypo.width,
176        );
177        let item_h = resolve_item_size(
178            &style.size.height,
179            &style.min_size.height,
180            &style.max_size.height,
181            area_h,
182            ac.hypo.height,
183        );
184
185        let justify = effective_align(style.justify_self, container_style.justify_items);
186        let align = effective_align(style.align_self, container_style.align_items);
187
188        let x = content_origin.x + area_x + align_offset(item_w, area_w, justify);
189        let y = content_origin.y + area_y + align_offset(item_h, area_h, align);
190
191        out.push((*id, LayoutRect::new(x, y, item_w, item_h)));
192    }
193
194    Ok(out)
195}
196
197/// Resolves the gap along one axis against available space. Percentages against
198/// indefinite space resolve to 0.0; negative gaps are rejected.
199fn resolve_gap(
200    container_style: &Style,
201    horizontal: bool,
202    available: AvailableSpace,
203) -> GuiResult<f32> {
204    let gap = if horizontal {
205        container_style.gap.width
206    } else {
207        container_style.gap.height
208    };
209    match gap {
210        crate::layout::LengthPercentage::Length(px) => {
211            if !px.is_finite() {
212                return Err(GuiError::InvalidNumericInput);
213            }
214            Ok(px.max(0.0))
215        }
216        crate::layout::LengthPercentage::Percent(p) => {
217            if !p.is_finite() {
218                return Err(GuiError::InvalidNumericInput);
219            }
220            match available {
221                AvailableSpace::Definite(base) => Ok((base * p).max(0.0)),
222                _ => Ok(0.0),
223            }
224        }
225    }
226}
227
228/// Assigns each active child a (row, col) track range and returns the total track
229/// counts required on both axes.
230///
231/// Explicitly placed items (`grid_row`/`grid_column` with a positive start line)
232/// use their 1-based start line and span. Auto-placed items use sequential
233/// row-major or column-major placement per `grid_auto_flow`.
234fn place_items(
235    active: &[ActiveChild],
236    children: &[(LayoutNodeId, Style, Size<f32>)],
237    container_style: &Style,
238    placements: &mut Vec<PlacedItem>,
239) -> (usize, usize) {
240    let row_capacity = container_style.grid_template_rows.len();
241    let col_capacity = container_style.grid_template_columns.len();
242
243    let mut next_row = 0usize;
244    let mut next_col = 0usize;
245    let flow = container_style.grid_auto_flow;
246
247    for (active_idx, ac) in active.iter().enumerate() {
248        let style = &children[ac.idx].1;
249        let row_span = (style.grid_row.span.max(1) as usize).max(1);
250        let col_span = (style.grid_column.span.max(1) as usize).max(1);
251
252        let explicit_row = if style.grid_row.start > 0 {
253            Some((style.grid_row.start as usize) - 1)
254        } else {
255            None
256        };
257        let explicit_col = if style.grid_column.start > 0 {
258            Some((style.grid_column.start as usize) - 1)
259        } else {
260            None
261        };
262
263        let (row_start, col_start) = match (explicit_row, explicit_col) {
264            // Both axes explicitly placed: use the designated cell.
265            (Some(r), Some(c)) => (r, c),
266            // One axis explicit: keep the auto axis at its current cursor.
267            (Some(r), None) => (r, next_col),
268            (None, Some(c)) => (next_row, c),
269            // Fully auto: sequential placement along the flow direction.
270            (None, None) => {
271                if flow == GridAutoFlow::Column {
272                    let r = next_row;
273                    let c = next_col;
274                    next_row += row_span;
275                    if row_capacity > 0 && next_row >= row_capacity {
276                        next_row = 0;
277                        next_col += col_span;
278                    }
279                    (r, c)
280                } else {
281                    let r = next_row;
282                    let c = next_col;
283                    next_col += col_span;
284                    if col_capacity > 0 && next_col >= col_capacity {
285                        next_col = 0;
286                        next_row += row_span;
287                    }
288                    (r, c)
289                }
290            }
291        };
292
293        placements.push(PlacedItem {
294            active_idx,
295            row_start,
296            row_span,
297            col_start,
298            col_span,
299        });
300    }
301
302    let mut total_rows = row_capacity.max(1);
303    let mut total_cols = col_capacity.max(1);
304    for p in placements {
305        total_rows = total_rows.max(p.row_start + p.row_span);
306        total_cols = total_cols.max(p.col_start + p.col_span);
307    }
308    (total_rows, total_cols)
309}
310
311/// Resolves a single `TrackSizingFunction` to a definite logical length.
312/// `Flex` and the flexible bound of `MinMax` resolve to their definite part
313/// (their floor); the flexible share is applied during distribution.
314fn resolve_definite(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<f32> {
315    match func {
316        TrackSizingFunction::Fixed(px) => {
317            if !px.is_finite() {
318                return Err(GuiError::InvalidNumericInput);
319            }
320            Ok(px.max(0.0))
321        }
322        TrackSizingFunction::Percent(p) => {
323            if !p.is_finite() {
324                return Err(GuiError::InvalidNumericInput);
325            }
326            Ok((base * p).max(0.0))
327        }
328        TrackSizingFunction::Auto => Ok(content.max(0.0)),
329        TrackSizingFunction::Flex(_fr) => Ok(0.0),
330        TrackSizingFunction::MinMax(min, max) => {
331            let min_res = resolve_definite(min, base, content)?;
332            let max_res = resolve_definite(max, base, content)?;
333            Ok(min_res.max(max_res))
334        }
335    }
336}
337
338/// Classifies a `TrackSizingFunction` into a definite or flexible track.
339fn classify_track(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<Track> {
340    match func {
341        TrackSizingFunction::Fixed(px) => {
342            if !px.is_finite() {
343                return Err(GuiError::InvalidNumericInput);
344            }
345            Ok(Track::Fixed(px.max(0.0)))
346        }
347        TrackSizingFunction::Percent(p) => {
348            if !p.is_finite() {
349                return Err(GuiError::InvalidNumericInput);
350            }
351            Ok(Track::Fixed((base * p).max(0.0)))
352        }
353        TrackSizingFunction::Auto => Ok(Track::Fixed(content.max(0.0))),
354        TrackSizingFunction::Flex(fr) => {
355            let fr = *fr;
356            if !fr.is_finite() || fr < 0.0 {
357                return Err(GuiError::InvalidNumericInput);
358            }
359            Ok(Track::Flex {
360                floor: 0.0,
361                weight: fr,
362            })
363        }
364        TrackSizingFunction::MinMax(min, max) => {
365            let min_res = resolve_definite(min, base, content)?;
366            if let TrackSizingFunction::Flex(fr) = **max {
367                if !fr.is_finite() || fr < 0.0 {
368                    return Err(GuiError::InvalidNumericInput);
369                }
370                Ok(Track::Flex {
371                    floor: min_res.max(content.max(0.0)),
372                    weight: fr,
373                })
374            } else {
375                let max_res = resolve_definite(max, base, content)?;
376                Ok(Track::Fixed(min_res.max(max_res)))
377            }
378        }
379    }
380}
381
382/// Sizes the tracks on one axis and returns per-track sizes.
383///
384/// `horizontal` selects the column tracks (inline axis); otherwise the row
385/// tracks (block axis). `base` is the container's content size on that axis.
386#[allow(clippy::too_many_arguments)]
387fn size_axis_tracks(
388    total: usize,
389    template: &[TrackSizingFunction],
390    auto: &[TrackSizingFunction],
391    placements: &[PlacedItem],
392    active: &[ActiveChild],
393    horizontal: bool,
394    base: f32,
395    gap: f32,
396) -> GuiResult<Vec<f32>> {
397    if total == 0 {
398        return Ok(Vec::new());
399    }
400
401    // Max hypothetical size of any active child covering each track.
402    let mut content = vec![0.0f32; total];
403    for p in placements {
404        let hypo = active[p.active_idx].hypo;
405        let (start, span, len) = if horizontal {
406            (p.col_start, p.col_span, hypo.width)
407        } else {
408            (p.row_start, p.row_span, hypo.height)
409        };
410        let end = (start + span).min(total);
411        if start < total {
412            for c in &mut content[start..end] {
413                *c = c.max(len);
414            }
415        }
416    }
417
418    let mut tracks = Vec::with_capacity(total);
419    for t in 0..total {
420        let func: &TrackSizingFunction = if t < template.len() {
421            &template[t]
422        } else {
423            auto.first().unwrap_or(&TrackSizingFunction::Auto)
424        };
425        tracks.push(classify_track(func, base, content[t])?);
426    }
427
428    // Distribute remaining space among flexible tracks; definite tracks are fixed.
429    let fixed_sum: f32 = tracks
430        .iter()
431        .map(|t| match t {
432            Track::Fixed(x) => *x,
433            Track::Flex { floor, .. } => *floor,
434        })
435        .sum();
436    let gap_sum = (total.saturating_sub(1) as f32) * gap;
437    let free = base - fixed_sum - gap_sum;
438    let floor_sum: f32 = tracks
439        .iter()
440        .map(|t| match t {
441            Track::Flex { floor, .. } => *floor,
442            Track::Fixed(_) => 0.0,
443        })
444        .sum();
445    let distributable = (free - floor_sum).max(0.0);
446    let total_weight: f32 = tracks
447        .iter()
448        .map(|t| match t {
449            Track::Flex { weight, .. } => *weight,
450            Track::Fixed(_) => 0.0,
451        })
452        .sum();
453
454    let mut sizes = Vec::with_capacity(total);
455    for t in tracks {
456        match t {
457            Track::Fixed(x) => sizes.push(x),
458            Track::Flex { floor, weight } => {
459                let share = if total_weight > 0.0 {
460                    distributable * (weight / total_weight)
461                } else {
462                    0.0
463                };
464                sizes.push((floor + share).max(0.0));
465            }
466        }
467    }
468
469    Ok(sizes)
470}
471
472/// Cumulative start position of each track, applying the inter-track gap.
473fn line_positions(sizes: &[f32], gap: f32) -> Vec<f32> {
474    let mut pos = Vec::with_capacity(sizes.len());
475    let mut cursor = 0.0f32;
476    for (i, &s) in sizes.iter().enumerate() {
477        if i > 0 {
478            cursor += gap;
479        }
480        pos.push(cursor);
481        cursor += s;
482    }
483    pos
484}
485
486/// Total size of a spanned region: the sum of the covered track sizes plus the
487/// gaps *between* them (not outside).
488fn area_size(sizes: &[f32], start: usize, span: usize, gap: f32) -> f32 {
489    let end = (start + span).min(sizes.len());
490    if end <= start {
491        return 0.0;
492    }
493    let total: f32 = sizes[start..end].iter().sum();
494    total + (span.saturating_sub(1) as f32) * gap
495}
496
497/// Resolves an item dimension against its grid-area size, falling back to the
498/// hypothetical content size for `Auto`, and clamps with min/max constraints.
499fn resolve_item_size(
500    dim: &Dimension,
501    min_dim: &Dimension,
502    max_dim: &Dimension,
503    area_base: f32,
504    hypo: f32,
505) -> f32 {
506    let base_space = AvailableSpace::Definite(area_base.max(0.0));
507    let requested = resolve_dimension(*dim, base_space).unwrap_or(hypo.max(0.0));
508    let min_val = resolve_dimension(*min_dim, base_space);
509    let max_val = resolve_dimension(*max_dim, base_space);
510    BoxConstraints::clamp_dimension(requested.max(0.0), min_val, max_val)
511}
512
513/// Resolves the effective alignment for one axis from the item override and the
514/// container default, defaulting to `Start` for the native-GUI grid contract.
515fn effective_align(
516    item_align: Option<AlignSelf>,
517    container_align: Option<AlignItems>,
518) -> AlignItems {
519    if let Some(a) = item_align {
520        return to_align_items(a);
521    }
522    container_align.unwrap_or(AlignItems::Start)
523}
524
525/// Maps an item-level [`AlignSelf`] onto the container-level [`AlignItems`] set.
526fn to_align_items(align: AlignSelf) -> AlignItems {
527    match align {
528        AlignSelf::Start => AlignItems::Start,
529        AlignSelf::End => AlignItems::End,
530        AlignSelf::Center => AlignItems::Center,
531        // Baseline and Stretch have no distinct grid-area offset in the frozen
532        // contract; they align as `Start`.
533        AlignSelf::Baseline | AlignSelf::Stretch => AlignItems::Start,
534    }
535}
536
537/// Offset of an item within its grid area along one axis, given its alignment.
538fn align_offset(item_size: f32, area_size: f32, align: AlignItems) -> f32 {
539    match align {
540        AlignItems::Start => 0.0,
541        AlignItems::End => (area_size - item_size).max(0.0),
542        AlignItems::Center => ((area_size - item_size) * 0.5).max(0.0),
543        // Space* distribution is not part of the per-item grid-area contract;
544        // it aligns as `Start`.
545        AlignItems::Baseline | AlignItems::Stretch => 0.0,
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    fn leaf(size: Size<f32>, style: Option<Style>) -> (LayoutNodeId, Style, Size<f32>) {
554        let style = style.unwrap_or_else(|| Style {
555            size: Size::new(
556                Dimension::Length(size.width),
557                Dimension::Length(size.height),
558            ),
559            ..Default::default()
560        });
561        (LayoutNodeId::new(0, 0), style, size)
562    }
563
564    fn grid_style(cols: Vec<TrackSizingFunction>, rows: Vec<TrackSizingFunction>) -> Style {
565        Style {
566            display: crate::layout::Display::Grid,
567            grid_template_columns: cols,
568            grid_template_rows: rows,
569            ..Default::default()
570        }
571    }
572
573    /// Runs the solver over a single container and returns rects keyed by the
574    /// input child order (which is the returned order).
575    fn run(
576        style: &Style,
577        inner: Size<f32>,
578        children: &[(LayoutNodeId, Style, Size<f32>)],
579    ) -> Vec<LayoutRect> {
580        compute_grid(
581            style,
582            inner,
583            Size::new(
584                AvailableSpace::Definite(inner.width),
585                AvailableSpace::Definite(inner.height),
586            ),
587            children,
588            Point::new(0.0, 0.0),
589        )
590        .unwrap()
591        .into_iter()
592        .map(|(_, r)| r)
593        .collect()
594    }
595
596    fn approx(a: f32, b: f32) -> bool {
597        (a - b).abs() <= crate::layout::STRICT_TOLERANCE_PX
598    }
599
600    // FIX-GRD-001: fixed track widths (100, 150, 50).
601    #[test]
602    fn grd_001_fixed_tracks() {
603        let style = grid_style(
604            vec![
605                TrackSizingFunction::Fixed(100.0),
606                TrackSizingFunction::Fixed(150.0),
607                TrackSizingFunction::Fixed(50.0),
608            ],
609            vec![],
610        );
611        let children = vec![
612            leaf(Size::new(100.0, 40.0), None),
613            leaf(Size::new(150.0, 40.0), None),
614            leaf(Size::new(50.0, 40.0), None),
615        ];
616        let rects = run(&style, Size::new(300.0, 100.0), &children);
617        assert!(
618            approx(rects[0].x, 0.0)
619                && approx(rects[0].width, 100.0)
620                && approx(rects[0].height, 40.0)
621        );
622        assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 150.0));
623        assert!(approx(rects[2].x, 250.0) && approx(rects[2].width, 50.0));
624    }
625
626    // FIX-GRD-002: fractional tracks 1fr / 2fr in 300px -> 100 / 200.
627    #[test]
628    fn grd_002_fractional_tracks() {
629        let style = grid_style(
630            vec![
631                TrackSizingFunction::Flex(1.0),
632                TrackSizingFunction::Flex(2.0),
633            ],
634            vec![],
635        );
636        let children = vec![
637            leaf(Size::new(100.0, 40.0), None),
638            leaf(Size::new(100.0, 40.0), None),
639        ];
640        let rects = run(&style, Size::new(300.0, 100.0), &children);
641        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
642        assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 100.0));
643    }
644
645    // FIX-GRD-003: auto track matches the largest child (140px wide).
646    #[test]
647    fn grd_003_auto_track_content() {
648        let style = grid_style(vec![TrackSizingFunction::Auto], vec![]);
649        let children = vec![leaf(Size::new(140.0, 40.0), None)];
650        let rects = run(&style, Size::new(300.0, 100.0), &children);
651        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 140.0));
652    }
653
654    // FIX-GRD-004: MinMax(50px, 1fr) never drops below 50px.
655    #[test]
656    fn grd_004_minmax_track() {
657        let style = grid_style(
658            vec![TrackSizingFunction::MinMax(
659                Box::new(TrackSizingFunction::Fixed(50.0)),
660                Box::new(TrackSizingFunction::Flex(1.0)),
661            )],
662            vec![],
663        );
664        let children = vec![leaf(Size::new(20.0, 20.0), None)];
665        let rects = run(&style, Size::new(100.0, 50.0), &children);
666        assert!(rects[0].width >= 20.0);
667    }
668
669    // FIX-GRD-005: span 2 across two 100px columns with a 100%-wide item.
670    #[test]
671    fn grd_005_multi_column_span() {
672        let style = grid_style(
673            vec![
674                TrackSizingFunction::Fixed(100.0),
675                TrackSizingFunction::Fixed(100.0),
676            ],
677            vec![],
678        );
679        let item = Style {
680            grid_column: crate::layout::GridPlacement::new(0, 2),
681            size: Size::new(Dimension::Percent(1.0), Dimension::Length(40.0)),
682            ..Default::default()
683        };
684        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(200.0, 40.0))];
685        let rects = run(&style, Size::new(200.0, 100.0), &children);
686        assert!(
687            approx(rects[0].x, 0.0)
688                && approx(rects[0].width, 200.0)
689                && approx(rects[0].height, 40.0)
690        );
691    }
692
693    // FIX-GRD-006: explicit cell at row 2, column 3 in a 3x2 grid.
694    #[test]
695    fn grd_006_explicit_cell_placement() {
696        let style = grid_style(
697            vec![
698                TrackSizingFunction::Fixed(100.0),
699                TrackSizingFunction::Fixed(100.0),
700                TrackSizingFunction::Fixed(100.0),
701            ],
702            vec![
703                TrackSizingFunction::Fixed(50.0),
704                TrackSizingFunction::Fixed(50.0),
705            ],
706        );
707        let item = Style {
708            grid_row: crate::layout::GridPlacement::new(2, 1),
709            grid_column: crate::layout::GridPlacement::new(3, 1),
710            size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
711            ..Default::default()
712        };
713        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 50.0))];
714        let rects = run(&style, Size::new(300.0, 100.0), &children);
715        assert!(
716            approx(rects[0].x, 200.0) && approx(rects[0].y, 50.0) && approx(rects[0].width, 100.0)
717        );
718    }
719
720    // FIX-GRD-007: gaps are applied between tracks, not outside.
721    #[test]
722    fn grd_007_grid_gaps() {
723        let style = grid_style(
724            vec![
725                TrackSizingFunction::Fixed(100.0),
726                TrackSizingFunction::Fixed(100.0),
727            ],
728            vec![],
729        );
730        let style = Style {
731            gap: Size::new(
732                crate::layout::LengthPercentage::Length(10.0),
733                crate::layout::LengthPercentage::Length(10.0),
734            ),
735            ..style
736        };
737        let children = vec![
738            leaf(Size::new(100.0, 50.0), None),
739            leaf(Size::new(100.0, 50.0), None),
740        ];
741        let rects = run(&style, Size::new(300.0, 100.0), &children);
742        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
743        assert!(approx(rects[1].x, 110.0) && approx(rects[1].width, 100.0));
744    }
745
746    // FIX-GRD-008: a nested (flex) child inside a 150px grid cell keeps its own size.
747    #[test]
748    fn grd_008_nested_container_in_cell() {
749        let style = grid_style(vec![TrackSizingFunction::Fixed(150.0)], vec![]);
750        let child = Style {
751            size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
752            ..Default::default()
753        };
754        let children = vec![(LayoutNodeId::new(0, 0), child, Size::new(100.0, 50.0))];
755        let rects = run(&style, Size::new(200.0, 100.0), &children);
756        assert!(
757            approx(rects[0].x, 0.0)
758                && approx(rects[0].width, 100.0)
759                && approx(rects[0].height, 50.0)
760        );
761    }
762
763    // Hidden (Display::None) grid children collapse to 0x0 and do not displace
764    // their in-flow siblings.
765    #[test]
766    fn grid_hidden_child_collapses() {
767        let style = grid_style(
768            vec![
769                TrackSizingFunction::Fixed(100.0),
770                TrackSizingFunction::Fixed(100.0),
771            ],
772            vec![],
773        );
774        let hidden = Style {
775            display: crate::layout::Display::None,
776            size: Size::new(Dimension::Length(80.0), Dimension::Length(80.0)),
777            ..Default::default()
778        };
779        let children = vec![
780            leaf(Size::new(100.0, 40.0), None),
781            (LayoutNodeId::new(1, 0), hidden, Size::new(80.0, 80.0)),
782            leaf(Size::new(100.0, 40.0), None),
783        ];
784        let rects = run(&style, Size::new(200.0, 100.0), &children);
785        assert!(approx(rects[1].width, 0.0) && approx(rects[1].height, 0.0));
786        // Siblings keep their own column slots despite the hidden middle child.
787        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
788    }
789
790    // Column-flow auto placement fills the column first, then advances the column.
791    #[test]
792    fn grid_column_flow_placement() {
793        let mut style = grid_style(
794            vec![TrackSizingFunction::Fixed(100.0)],
795            vec![
796                TrackSizingFunction::Fixed(50.0),
797                TrackSizingFunction::Fixed(50.0),
798            ],
799        );
800        style.grid_auto_flow = GridAutoFlow::Column;
801        let children = vec![
802            leaf(Size::new(100.0, 50.0), None),
803            leaf(Size::new(100.0, 50.0), None),
804            leaf(Size::new(100.0, 50.0), None),
805        ];
806        let rects = run(&style, Size::new(100.0, 100.0), &children);
807        // item0 -> (row0,col0); item1 -> (row1,col0); item2 -> (row0,col1)
808        assert!(approx(rects[0].x, 0.0) && approx(rects[0].y, 0.0));
809        assert!(approx(rects[1].x, 0.0) && approx(rects[1].y, 50.0));
810        assert!(approx(rects[2].x, 100.0) && approx(rects[2].y, 0.0));
811    }
812
813    // Percent item size resolves against the item's grid area.
814    #[test]
815    fn grid_percent_item_size_uses_area() {
816        let style = grid_style(
817            vec![
818                TrackSizingFunction::Fixed(60.0),
819                TrackSizingFunction::Fixed(40.0),
820            ],
821            vec![TrackSizingFunction::Fixed(100.0)],
822        );
823        // Item spans both columns (area width 100) at 50% width => 50px.
824        let item = Style {
825            grid_column: crate::layout::GridPlacement::new(0, 2),
826            size: Size::new(Dimension::Percent(0.5), Dimension::Length(100.0)),
827            ..Default::default()
828        };
829        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 100.0))];
830        let rects = run(&style, Size::new(100.0, 100.0), &children);
831        assert!(approx(rects[0].width, 50.0) && approx(rects[0].height, 100.0));
832    }
833}