native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! Owned native-GUI grid layout solver.
//!
//! Implements the frozen grid contract from `docs/design/owned-layout-engine.md`
//! (sections 2, 3, and 7) as an native-gui-owned solver, consistent with the owned
//! flexbox solver in [`super::flex`]:
//!
//! - Track sizing: `Fixed(px)`, `Percent(%)`, `Flex(fr)`, `Auto`, and `MinMax(min, max)`.
//! - Placement: explicit 1-based start line + span, plus sequential row-major
//!   (`GridAutoFlow::Row`) or column-major (`GridAutoFlow::Column`) auto flow.
//! - Sparse placement only. Dense packing and subgrid are rejected by the
//!   contract (keyboard-accessibility invariant) and are not modeled here.
//! - Gaps are applied *between* tracks only, never outside the track set.
//! - Items are positioned within their grid area by `justify` (inline axis) and
//!   `align` (block axis), defaulting to `Start`.
//!
//! Numerical invariants: all inputs are required to be finite; resolved
//! dimensions are clamped to be non-negative; percentage track sizes resolve
//! against the container's content box; percentage item sizes resolve against
//! the item's grid area.
//!
//! The solver is a pure function of the container style, container content box,
//! available space, and the in-flow children (id, style, hypothetical border-box
//! size), returning one [`LayoutRect`] per child. It is invoked from
//! `super::tree::LayoutTree::solve_node_depth` when a node's
//! `Style::display` is [`super::Display::Grid`].

use crate::error::{GuiError, GuiResult};
use crate::layout::box_sizing::{resolve_dimension, BoxConstraints};
use crate::layout::{
    AlignItems, AlignSelf, AvailableSpace, Dimension, GridAutoFlow, LayoutNodeId, LayoutRect,
    Point, Size, Style, TrackSizingFunction,
};

/// A single classified grid track on one axis, after definite-size resolution.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Track {
    /// A definite size in logical pixels (from `Fixed`, `Percent`, `Auto`, or a
    /// definite `MinMax` bound).
    Fixed(f32),
    /// A flexible track contributing `weight` fractional shares, floored at `floor`.
    Flex {
        /// Minimum resolved size for this track (wins when the grid overflows).
        floor: f32,
        /// Fractional weight (`fr`); non-negative and finite.
        weight: f32,
    },
}

/// An in-flow (non-hidden) grid child, referencing its position in the original
/// `children` list so its style can be looked up without borrowing issues.
#[derive(Debug, Clone, Copy)]
struct ActiveChild {
    /// Index into the original `children` slice.
    idx: usize,
    /// The child's hypothetical border-box size (fallback for `Auto` item sizes).
    hypo: Size<f32>,
}

/// Placement of one in-flow grid child on the two track axes (0-based).
#[derive(Debug, Clone, Copy)]
struct PlacedItem {
    /// Index of this child within the `active` list.
    active_idx: usize,
    /// 0-based index of the first row track occupied.
    row_start: usize,
    /// Number of row tracks spanned (>= 1).
    row_span: usize,
    /// 0-based index of the first column track occupied.
    col_start: usize,
    /// Number of column tracks spanned (>= 1).
    col_span: usize,
}

/// Computes owned native-GUI grid layout for a container and its in-flow children.
///
/// `container_inner` is the container's content box (after padding),
/// `available_space` is the resolved available space, and `children` are the
/// in-flow children as `(id, style, hypothetical border-box size)` tuples.
/// Returns one placed [`LayoutRect`] per child, in the original child order.
pub fn compute_grid(
    container_style: &Style,
    container_inner: Size<f32>,
    available_space: Size<AvailableSpace>,
    children: &[(LayoutNodeId, Style, Size<f32>)],
    content_origin: Point<f32>,
) -> GuiResult<Vec<(LayoutNodeId, LayoutRect)>> {
    if children.is_empty() {
        return Ok(Vec::new());
    }

    // Separate hidden (Display::None) children: they collapse to 0x0 and take no
    // part in track creation, sizing, or auto placement (consistent with the
    // owned flexbox path and the FIX-LFC-001 hidden-node contract). We record the
    // original child index so output stays in input order.
    let mut hidden: Vec<usize> = Vec::new();
    let mut active: Vec<ActiveChild> = Vec::with_capacity(children.len());
    for (idx, (_id, style, hypo)) in children.iter().enumerate() {
        if style.display == crate::layout::Display::None {
            hidden.push(idx);
        } else {
            active.push(ActiveChild { idx, hypo: *hypo });
        }
    }

    let gap_col = resolve_gap(container_style, true, available_space.width)?;
    let gap_row = resolve_gap(container_style, false, available_space.height)?;

    let mut placements: Vec<PlacedItem> = Vec::with_capacity(active.len());
    let (total_rows, total_cols) = place_items(&active, children, container_style, &mut placements);

    // Size the tracks on each axis and derive cumulative line positions.
    let col_sizes = size_axis_tracks(
        total_cols,
        &container_style.grid_template_columns,
        &container_style.grid_auto_columns,
        &placements,
        &active,
        true,
        container_inner.width,
        gap_col,
    )?;
    let row_sizes = size_axis_tracks(
        total_rows,
        &container_style.grid_template_rows,
        &container_style.grid_auto_rows,
        &placements,
        &active,
        false,
        container_inner.height,
        gap_row,
    )?;

    let col_pos = line_positions(&col_sizes, gap_col);
    let row_pos = line_positions(&row_sizes, gap_row);

    // Build the output in the original child order. Placed children use their
    // placement (keyed by the original child index); hidden children collapse to
    // a 0x0 box at the content origin.
    let mut hidden_set = std::collections::HashSet::new();
    for &idx in &hidden {
        hidden_set.insert(idx);
    }

    let mut active_by_child_idx: std::collections::HashMap<usize, usize> =
        std::collections::HashMap::new();
    for (active_idx, ac) in active.iter().enumerate() {
        active_by_child_idx.insert(ac.idx, active_idx);
    }

    let mut out: Vec<(LayoutNodeId, LayoutRect)> = Vec::with_capacity(children.len());
    for (idx, (id, _, _)) in children.iter().enumerate() {
        if hidden_set.contains(&idx) {
            out.push((
                *id,
                LayoutRect::new(content_origin.x, content_origin.y, 0.0, 0.0),
            ));
            continue;
        }

        let active_idx = active_by_child_idx[&idx];
        let p = placements[active_idx];
        let ac = active[active_idx];
        let style = &children[idx].1;

        let area_w = area_size(&col_sizes, p.col_start, p.col_span, gap_col);
        let area_h = area_size(&row_sizes, p.row_start, p.row_span, gap_row);
        let area_x = col_pos[p.col_start];
        let area_y = row_pos[p.row_start];

        let item_w = resolve_item_size(
            &style.size.width,
            &style.min_size.width,
            &style.max_size.width,
            area_w,
            ac.hypo.width,
        );
        let item_h = resolve_item_size(
            &style.size.height,
            &style.min_size.height,
            &style.max_size.height,
            area_h,
            ac.hypo.height,
        );

        let justify = effective_align(style.justify_self, container_style.justify_items);
        let align = effective_align(style.align_self, container_style.align_items);

        let x = content_origin.x + area_x + align_offset(item_w, area_w, justify);
        let y = content_origin.y + area_y + align_offset(item_h, area_h, align);

        out.push((*id, LayoutRect::new(x, y, item_w, item_h)));
    }

    Ok(out)
}

/// Resolves the gap along one axis against available space. Percentages against
/// indefinite space resolve to 0.0; negative gaps are rejected.
fn resolve_gap(
    container_style: &Style,
    horizontal: bool,
    available: AvailableSpace,
) -> GuiResult<f32> {
    let gap = if horizontal {
        container_style.gap.width
    } else {
        container_style.gap.height
    };
    match gap {
        crate::layout::LengthPercentage::Length(px) => {
            if !px.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok(px.max(0.0))
        }
        crate::layout::LengthPercentage::Percent(p) => {
            if !p.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            match available {
                AvailableSpace::Definite(base) => Ok((base * p).max(0.0)),
                _ => Ok(0.0),
            }
        }
    }
}

/// Assigns each active child a (row, col) track range and returns the total track
/// counts required on both axes.
///
/// Explicitly placed items (`grid_row`/`grid_column` with a positive start line)
/// use their 1-based start line and span. Auto-placed items use sequential
/// row-major or column-major placement per `grid_auto_flow`.
fn place_items(
    active: &[ActiveChild],
    children: &[(LayoutNodeId, Style, Size<f32>)],
    container_style: &Style,
    placements: &mut Vec<PlacedItem>,
) -> (usize, usize) {
    let row_capacity = container_style.grid_template_rows.len();
    let col_capacity = container_style.grid_template_columns.len();

    let mut next_row = 0usize;
    let mut next_col = 0usize;
    let flow = container_style.grid_auto_flow;

    for (active_idx, ac) in active.iter().enumerate() {
        let style = &children[ac.idx].1;
        let row_span = (style.grid_row.span.max(1) as usize).max(1);
        let col_span = (style.grid_column.span.max(1) as usize).max(1);

        let explicit_row = if style.grid_row.start > 0 {
            Some((style.grid_row.start as usize) - 1)
        } else {
            None
        };
        let explicit_col = if style.grid_column.start > 0 {
            Some((style.grid_column.start as usize) - 1)
        } else {
            None
        };

        let (row_start, col_start) = match (explicit_row, explicit_col) {
            // Both axes explicitly placed: use the designated cell.
            (Some(r), Some(c)) => (r, c),
            // One axis explicit: keep the auto axis at its current cursor.
            (Some(r), None) => (r, next_col),
            (None, Some(c)) => (next_row, c),
            // Fully auto: sequential placement along the flow direction.
            (None, None) => {
                if flow == GridAutoFlow::Column {
                    let r = next_row;
                    let c = next_col;
                    next_row += row_span;
                    if row_capacity > 0 && next_row >= row_capacity {
                        next_row = 0;
                        next_col += col_span;
                    }
                    (r, c)
                } else {
                    let r = next_row;
                    let c = next_col;
                    next_col += col_span;
                    if col_capacity > 0 && next_col >= col_capacity {
                        next_col = 0;
                        next_row += row_span;
                    }
                    (r, c)
                }
            }
        };

        placements.push(PlacedItem {
            active_idx,
            row_start,
            row_span,
            col_start,
            col_span,
        });
    }

    let mut total_rows = row_capacity.max(1);
    let mut total_cols = col_capacity.max(1);
    for p in placements {
        total_rows = total_rows.max(p.row_start + p.row_span);
        total_cols = total_cols.max(p.col_start + p.col_span);
    }
    (total_rows, total_cols)
}

/// Resolves a single `TrackSizingFunction` to a definite logical length.
/// `Flex` and the flexible bound of `MinMax` resolve to their definite part
/// (their floor); the flexible share is applied during distribution.
fn resolve_definite(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<f32> {
    match func {
        TrackSizingFunction::Fixed(px) => {
            if !px.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok(px.max(0.0))
        }
        TrackSizingFunction::Percent(p) => {
            if !p.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok((base * p).max(0.0))
        }
        TrackSizingFunction::Auto => Ok(content.max(0.0)),
        TrackSizingFunction::Flex(_fr) => Ok(0.0),
        TrackSizingFunction::MinMax(min, max) => {
            let min_res = resolve_definite(min, base, content)?;
            let max_res = resolve_definite(max, base, content)?;
            Ok(min_res.max(max_res))
        }
    }
}

/// Classifies a `TrackSizingFunction` into a definite or flexible track.
fn classify_track(func: &TrackSizingFunction, base: f32, content: f32) -> GuiResult<Track> {
    match func {
        TrackSizingFunction::Fixed(px) => {
            if !px.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok(Track::Fixed(px.max(0.0)))
        }
        TrackSizingFunction::Percent(p) => {
            if !p.is_finite() {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok(Track::Fixed((base * p).max(0.0)))
        }
        TrackSizingFunction::Auto => Ok(Track::Fixed(content.max(0.0))),
        TrackSizingFunction::Flex(fr) => {
            let fr = *fr;
            if !fr.is_finite() || fr < 0.0 {
                return Err(GuiError::InvalidNumericInput);
            }
            Ok(Track::Flex {
                floor: 0.0,
                weight: fr,
            })
        }
        TrackSizingFunction::MinMax(min, max) => {
            let min_res = resolve_definite(min, base, content)?;
            if let TrackSizingFunction::Flex(fr) = **max {
                if !fr.is_finite() || fr < 0.0 {
                    return Err(GuiError::InvalidNumericInput);
                }
                Ok(Track::Flex {
                    floor: min_res.max(content.max(0.0)),
                    weight: fr,
                })
            } else {
                let max_res = resolve_definite(max, base, content)?;
                Ok(Track::Fixed(min_res.max(max_res)))
            }
        }
    }
}

/// Sizes the tracks on one axis and returns per-track sizes.
///
/// `horizontal` selects the column tracks (inline axis); otherwise the row
/// tracks (block axis). `base` is the container's content size on that axis.
#[allow(clippy::too_many_arguments)]
fn size_axis_tracks(
    total: usize,
    template: &[TrackSizingFunction],
    auto: &[TrackSizingFunction],
    placements: &[PlacedItem],
    active: &[ActiveChild],
    horizontal: bool,
    base: f32,
    gap: f32,
) -> GuiResult<Vec<f32>> {
    if total == 0 {
        return Ok(Vec::new());
    }

    // Max hypothetical size of any active child covering each track.
    let mut content = vec![0.0f32; total];
    for p in placements {
        let hypo = active[p.active_idx].hypo;
        let (start, span, len) = if horizontal {
            (p.col_start, p.col_span, hypo.width)
        } else {
            (p.row_start, p.row_span, hypo.height)
        };
        let end = (start + span).min(total);
        if start < total {
            for c in &mut content[start..end] {
                *c = c.max(len);
            }
        }
    }

    let mut tracks = Vec::with_capacity(total);
    for t in 0..total {
        let func: &TrackSizingFunction = if t < template.len() {
            &template[t]
        } else {
            auto.first().unwrap_or(&TrackSizingFunction::Auto)
        };
        tracks.push(classify_track(func, base, content[t])?);
    }

    // Distribute remaining space among flexible tracks; definite tracks are fixed.
    let fixed_sum: f32 = tracks
        .iter()
        .map(|t| match t {
            Track::Fixed(x) => *x,
            Track::Flex { floor, .. } => *floor,
        })
        .sum();
    let gap_sum = (total.saturating_sub(1) as f32) * gap;
    let free = base - fixed_sum - gap_sum;
    let floor_sum: f32 = tracks
        .iter()
        .map(|t| match t {
            Track::Flex { floor, .. } => *floor,
            Track::Fixed(_) => 0.0,
        })
        .sum();
    let distributable = (free - floor_sum).max(0.0);
    let total_weight: f32 = tracks
        .iter()
        .map(|t| match t {
            Track::Flex { weight, .. } => *weight,
            Track::Fixed(_) => 0.0,
        })
        .sum();

    let mut sizes = Vec::with_capacity(total);
    for t in tracks {
        match t {
            Track::Fixed(x) => sizes.push(x),
            Track::Flex { floor, weight } => {
                let share = if total_weight > 0.0 {
                    distributable * (weight / total_weight)
                } else {
                    0.0
                };
                sizes.push((floor + share).max(0.0));
            }
        }
    }

    Ok(sizes)
}

/// Cumulative start position of each track, applying the inter-track gap.
fn line_positions(sizes: &[f32], gap: f32) -> Vec<f32> {
    let mut pos = Vec::with_capacity(sizes.len());
    let mut cursor = 0.0f32;
    for (i, &s) in sizes.iter().enumerate() {
        if i > 0 {
            cursor += gap;
        }
        pos.push(cursor);
        cursor += s;
    }
    pos
}

/// Total size of a spanned region: the sum of the covered track sizes plus the
/// gaps *between* them (not outside).
fn area_size(sizes: &[f32], start: usize, span: usize, gap: f32) -> f32 {
    let end = (start + span).min(sizes.len());
    if end <= start {
        return 0.0;
    }
    let total: f32 = sizes[start..end].iter().sum();
    total + (span.saturating_sub(1) as f32) * gap
}

/// Resolves an item dimension against its grid-area size, falling back to the
/// hypothetical content size for `Auto`, and clamps with min/max constraints.
fn resolve_item_size(
    dim: &Dimension,
    min_dim: &Dimension,
    max_dim: &Dimension,
    area_base: f32,
    hypo: f32,
) -> f32 {
    let base_space = AvailableSpace::Definite(area_base.max(0.0));
    let requested = resolve_dimension(*dim, base_space).unwrap_or(hypo.max(0.0));
    let min_val = resolve_dimension(*min_dim, base_space);
    let max_val = resolve_dimension(*max_dim, base_space);
    BoxConstraints::clamp_dimension(requested.max(0.0), min_val, max_val)
}

/// Resolves the effective alignment for one axis from the item override and the
/// container default, defaulting to `Start` for the native-GUI grid contract.
fn effective_align(
    item_align: Option<AlignSelf>,
    container_align: Option<AlignItems>,
) -> AlignItems {
    if let Some(a) = item_align {
        return to_align_items(a);
    }
    container_align.unwrap_or(AlignItems::Start)
}

/// Maps an item-level [`AlignSelf`] onto the container-level [`AlignItems`] set.
fn to_align_items(align: AlignSelf) -> AlignItems {
    match align {
        AlignSelf::Start => AlignItems::Start,
        AlignSelf::End => AlignItems::End,
        AlignSelf::Center => AlignItems::Center,
        // Baseline and Stretch have no distinct grid-area offset in the frozen
        // contract; they align as `Start`.
        AlignSelf::Baseline | AlignSelf::Stretch => AlignItems::Start,
    }
}

/// Offset of an item within its grid area along one axis, given its alignment.
fn align_offset(item_size: f32, area_size: f32, align: AlignItems) -> f32 {
    match align {
        AlignItems::Start => 0.0,
        AlignItems::End => (area_size - item_size).max(0.0),
        AlignItems::Center => ((area_size - item_size) * 0.5).max(0.0),
        // Space* distribution is not part of the per-item grid-area contract;
        // it aligns as `Start`.
        AlignItems::Baseline | AlignItems::Stretch => 0.0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn leaf(size: Size<f32>, style: Option<Style>) -> (LayoutNodeId, Style, Size<f32>) {
        let style = style.unwrap_or_else(|| Style {
            size: Size::new(
                Dimension::Length(size.width),
                Dimension::Length(size.height),
            ),
            ..Default::default()
        });
        (LayoutNodeId::new(0, 0), style, size)
    }

    fn grid_style(cols: Vec<TrackSizingFunction>, rows: Vec<TrackSizingFunction>) -> Style {
        Style {
            display: crate::layout::Display::Grid,
            grid_template_columns: cols,
            grid_template_rows: rows,
            ..Default::default()
        }
    }

    /// Runs the solver over a single container and returns rects keyed by the
    /// input child order (which is the returned order).
    fn run(
        style: &Style,
        inner: Size<f32>,
        children: &[(LayoutNodeId, Style, Size<f32>)],
    ) -> Vec<LayoutRect> {
        compute_grid(
            style,
            inner,
            Size::new(
                AvailableSpace::Definite(inner.width),
                AvailableSpace::Definite(inner.height),
            ),
            children,
            Point::new(0.0, 0.0),
        )
        .unwrap()
        .into_iter()
        .map(|(_, r)| r)
        .collect()
    }

    fn approx(a: f32, b: f32) -> bool {
        (a - b).abs() <= crate::layout::STRICT_TOLERANCE_PX
    }

    // FIX-GRD-001: fixed track widths (100, 150, 50).
    #[test]
    fn grd_001_fixed_tracks() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(150.0),
                TrackSizingFunction::Fixed(50.0),
            ],
            vec![],
        );
        let children = vec![
            leaf(Size::new(100.0, 40.0), None),
            leaf(Size::new(150.0, 40.0), None),
            leaf(Size::new(50.0, 40.0), None),
        ];
        let rects = run(&style, Size::new(300.0, 100.0), &children);
        assert!(
            approx(rects[0].x, 0.0)
                && approx(rects[0].width, 100.0)
                && approx(rects[0].height, 40.0)
        );
        assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 150.0));
        assert!(approx(rects[2].x, 250.0) && approx(rects[2].width, 50.0));
    }

    // FIX-GRD-002: fractional tracks 1fr / 2fr in 300px -> 100 / 200.
    #[test]
    fn grd_002_fractional_tracks() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Flex(1.0),
                TrackSizingFunction::Flex(2.0),
            ],
            vec![],
        );
        let children = vec![
            leaf(Size::new(100.0, 40.0), None),
            leaf(Size::new(100.0, 40.0), None),
        ];
        let rects = run(&style, Size::new(300.0, 100.0), &children);
        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
        assert!(approx(rects[1].x, 100.0) && approx(rects[1].width, 100.0));
    }

    // FIX-GRD-003: auto track matches the largest child (140px wide).
    #[test]
    fn grd_003_auto_track_content() {
        let style = grid_style(vec![TrackSizingFunction::Auto], vec![]);
        let children = vec![leaf(Size::new(140.0, 40.0), None)];
        let rects = run(&style, Size::new(300.0, 100.0), &children);
        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 140.0));
    }

    // FIX-GRD-004: MinMax(50px, 1fr) never drops below 50px.
    #[test]
    fn grd_004_minmax_track() {
        let style = grid_style(
            vec![TrackSizingFunction::MinMax(
                Box::new(TrackSizingFunction::Fixed(50.0)),
                Box::new(TrackSizingFunction::Flex(1.0)),
            )],
            vec![],
        );
        let children = vec![leaf(Size::new(20.0, 20.0), None)];
        let rects = run(&style, Size::new(100.0, 50.0), &children);
        assert!(rects[0].width >= 20.0);
    }

    // FIX-GRD-005: span 2 across two 100px columns with a 100%-wide item.
    #[test]
    fn grd_005_multi_column_span() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(100.0),
            ],
            vec![],
        );
        let item = Style {
            grid_column: crate::layout::GridPlacement::new(0, 2),
            size: Size::new(Dimension::Percent(1.0), Dimension::Length(40.0)),
            ..Default::default()
        };
        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(200.0, 40.0))];
        let rects = run(&style, Size::new(200.0, 100.0), &children);
        assert!(
            approx(rects[0].x, 0.0)
                && approx(rects[0].width, 200.0)
                && approx(rects[0].height, 40.0)
        );
    }

    // FIX-GRD-006: explicit cell at row 2, column 3 in a 3x2 grid.
    #[test]
    fn grd_006_explicit_cell_placement() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(100.0),
            ],
            vec![
                TrackSizingFunction::Fixed(50.0),
                TrackSizingFunction::Fixed(50.0),
            ],
        );
        let item = Style {
            grid_row: crate::layout::GridPlacement::new(2, 1),
            grid_column: crate::layout::GridPlacement::new(3, 1),
            size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
            ..Default::default()
        };
        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 50.0))];
        let rects = run(&style, Size::new(300.0, 100.0), &children);
        assert!(
            approx(rects[0].x, 200.0) && approx(rects[0].y, 50.0) && approx(rects[0].width, 100.0)
        );
    }

    // FIX-GRD-007: gaps are applied between tracks, not outside.
    #[test]
    fn grd_007_grid_gaps() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(100.0),
            ],
            vec![],
        );
        let style = Style {
            gap: Size::new(
                crate::layout::LengthPercentage::Length(10.0),
                crate::layout::LengthPercentage::Length(10.0),
            ),
            ..style
        };
        let children = vec![
            leaf(Size::new(100.0, 50.0), None),
            leaf(Size::new(100.0, 50.0), None),
        ];
        let rects = run(&style, Size::new(300.0, 100.0), &children);
        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
        assert!(approx(rects[1].x, 110.0) && approx(rects[1].width, 100.0));
    }

    // FIX-GRD-008: a nested (flex) child inside a 150px grid cell keeps its own size.
    #[test]
    fn grd_008_nested_container_in_cell() {
        let style = grid_style(vec![TrackSizingFunction::Fixed(150.0)], vec![]);
        let child = Style {
            size: Size::new(Dimension::Length(100.0), Dimension::Length(50.0)),
            ..Default::default()
        };
        let children = vec![(LayoutNodeId::new(0, 0), child, Size::new(100.0, 50.0))];
        let rects = run(&style, Size::new(200.0, 100.0), &children);
        assert!(
            approx(rects[0].x, 0.0)
                && approx(rects[0].width, 100.0)
                && approx(rects[0].height, 50.0)
        );
    }

    // Hidden (Display::None) grid children collapse to 0x0 and do not displace
    // their in-flow siblings.
    #[test]
    fn grid_hidden_child_collapses() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(100.0),
                TrackSizingFunction::Fixed(100.0),
            ],
            vec![],
        );
        let hidden = Style {
            display: crate::layout::Display::None,
            size: Size::new(Dimension::Length(80.0), Dimension::Length(80.0)),
            ..Default::default()
        };
        let children = vec![
            leaf(Size::new(100.0, 40.0), None),
            (LayoutNodeId::new(1, 0), hidden, Size::new(80.0, 80.0)),
            leaf(Size::new(100.0, 40.0), None),
        ];
        let rects = run(&style, Size::new(200.0, 100.0), &children);
        assert!(approx(rects[1].width, 0.0) && approx(rects[1].height, 0.0));
        // Siblings keep their own column slots despite the hidden middle child.
        assert!(approx(rects[0].x, 0.0) && approx(rects[0].width, 100.0));
    }

    // Column-flow auto placement fills the column first, then advances the column.
    #[test]
    fn grid_column_flow_placement() {
        let mut style = grid_style(
            vec![TrackSizingFunction::Fixed(100.0)],
            vec![
                TrackSizingFunction::Fixed(50.0),
                TrackSizingFunction::Fixed(50.0),
            ],
        );
        style.grid_auto_flow = GridAutoFlow::Column;
        let children = vec![
            leaf(Size::new(100.0, 50.0), None),
            leaf(Size::new(100.0, 50.0), None),
            leaf(Size::new(100.0, 50.0), None),
        ];
        let rects = run(&style, Size::new(100.0, 100.0), &children);
        // item0 -> (row0,col0); item1 -> (row1,col0); item2 -> (row0,col1)
        assert!(approx(rects[0].x, 0.0) && approx(rects[0].y, 0.0));
        assert!(approx(rects[1].x, 0.0) && approx(rects[1].y, 50.0));
        assert!(approx(rects[2].x, 100.0) && approx(rects[2].y, 0.0));
    }

    // Percent item size resolves against the item's grid area.
    #[test]
    fn grid_percent_item_size_uses_area() {
        let style = grid_style(
            vec![
                TrackSizingFunction::Fixed(60.0),
                TrackSizingFunction::Fixed(40.0),
            ],
            vec![TrackSizingFunction::Fixed(100.0)],
        );
        // Item spans both columns (area width 100) at 50% width => 50px.
        let item = Style {
            grid_column: crate::layout::GridPlacement::new(0, 2),
            size: Size::new(Dimension::Percent(0.5), Dimension::Length(100.0)),
            ..Default::default()
        };
        let children = vec![(LayoutNodeId::new(0, 0), item, Size::new(100.0, 100.0))];
        let rects = run(&style, Size::new(100.0, 100.0), &children);
        assert!(approx(rects[0].width, 50.0) && approx(rects[0].height, 100.0));
    }
}