Skip to main content

ftui_layout/
grid.rs

1#![forbid(unsafe_code)]
2
3//! 2D Grid layout system for dashboard-style positioning.
4//!
5//! Grid provides constraint-based 2D positioning with support for:
6//! - Row and column constraints
7//! - Cell spanning (colspan, rowspan)
8//! - Named areas for semantic layout references
9//! - Gap configuration
10//!
11//! # Example
12//!
13//! ```
14//! use ftui_layout::grid::Grid;
15//! use ftui_layout::Constraint;
16//! use ftui_core::geometry::Rect;
17//!
18//! // Create a 3x2 grid (3 rows, 2 columns)
19//! let grid = Grid::new()
20//!     .rows([
21//!         Constraint::Fixed(3),      // Header
22//!         Constraint::Min(10),       // Content
23//!         Constraint::Fixed(1),      // Footer
24//!     ])
25//!     .columns([
26//!         Constraint::Percentage(30.0),  // Sidebar
27//!         Constraint::Min(20),            // Main
28//!     ])
29//!     .row_gap(1)
30//!     .col_gap(2);
31//!
32//! let area = Rect::new(0, 0, 80, 24);
33//! let layout = grid.split(area);
34//!
35//! // Access cell by (row, col)
36//! let header_left = layout.cell(0, 0);
37//! let content_main = layout.cell(1, 1);
38//! ```
39
40use crate::{Constraint, Sizes};
41use ftui_core::geometry::Rect;
42use std::collections::HashMap;
43
44/// A 2D grid layout container.
45#[derive(Debug, Clone, Default)]
46pub struct Grid {
47    /// Row constraints (height of each row).
48    row_constraints: Vec<Constraint>,
49    /// Column constraints (width of each column).
50    col_constraints: Vec<Constraint>,
51    /// Gap between rows.
52    row_gap: u16,
53    /// Gap between columns.
54    col_gap: u16,
55    /// Named areas mapping to (row, col, rowspan, colspan).
56    named_areas: HashMap<String, GridArea>,
57    /// Overflow behavior for content exceeding the grid bounds.
58    overflow: crate::OverflowBehavior,
59}
60
61/// Definition of a named grid area.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct GridArea {
64    /// Starting row (0-indexed).
65    pub row: usize,
66    /// Starting column (0-indexed).
67    pub col: usize,
68    /// Number of rows this area spans.
69    pub rowspan: usize,
70    /// Number of columns this area spans.
71    pub colspan: usize,
72}
73
74impl GridArea {
75    /// Create a single-cell area.
76    #[inline]
77    #[must_use]
78    pub fn cell(row: usize, col: usize) -> Self {
79        Self {
80            row,
81            col,
82            rowspan: 1,
83            colspan: 1,
84        }
85    }
86
87    /// Create a spanning area.
88    #[inline]
89    #[must_use]
90    pub fn span(row: usize, col: usize, rowspan: usize, colspan: usize) -> Self {
91        Self {
92            row,
93            col,
94            rowspan: rowspan.max(1),
95            colspan: colspan.max(1),
96        }
97    }
98}
99
100/// Result of solving a grid layout.
101#[derive(Debug, Clone)]
102pub struct GridLayout {
103    /// Row heights.
104    row_heights: Sizes,
105    /// Column widths.
106    col_widths: Sizes,
107    /// Row Y positions (cumulative with gaps).
108    row_positions: Sizes,
109    /// Column X positions (cumulative with gaps).
110    col_positions: Sizes,
111    /// Named areas from the grid definition.
112    named_areas: HashMap<String, GridArea>,
113    /// Gap between rows.
114    row_gap: u16,
115    /// Gap between columns.
116    col_gap: u16,
117    /// The bounding area of the grid.
118    bounds: Rect,
119}
120
121impl Grid {
122    /// Create a new empty grid.
123    #[inline]
124    #[must_use]
125    pub fn new() -> Self {
126        Self::default()
127    }
128
129    /// Set the row constraints.
130    #[must_use]
131    pub fn rows(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
132        self.row_constraints = constraints.into_iter().collect();
133        self
134    }
135
136    /// Set the column constraints.
137    #[must_use]
138    pub fn columns(mut self, constraints: impl IntoIterator<Item = Constraint>) -> Self {
139        self.col_constraints = constraints.into_iter().collect();
140        self
141    }
142
143    /// Set the gap between rows.
144    #[must_use]
145    pub fn row_gap(mut self, gap: u16) -> Self {
146        self.row_gap = gap;
147        self
148    }
149
150    /// Set the gap between columns.
151    #[must_use]
152    pub fn col_gap(mut self, gap: u16) -> Self {
153        self.col_gap = gap;
154        self
155    }
156
157    /// Set uniform gap for both rows and columns.
158    #[must_use]
159    pub fn gap(self, gap: u16) -> Self {
160        self.row_gap(gap).col_gap(gap)
161    }
162
163    /// Define a named area in the grid.
164    ///
165    /// Named areas allow semantic access to grid regions:
166    /// ```ignore
167    /// let grid = Grid::new()
168    ///     .rows([Constraint::Fixed(3), Constraint::Min(10)])
169    ///     .columns([Constraint::Fixed(20), Constraint::Min(40)])
170    ///     .area("sidebar", GridArea::span(0, 0, 2, 1))  // Left column, both rows
171    ///     .area("content", GridArea::cell(0, 1))        // Top right
172    ///     .area("footer", GridArea::cell(1, 1));        // Bottom right
173    /// ```
174    #[must_use]
175    pub fn area(mut self, name: impl Into<String>, area: GridArea) -> Self {
176        self.named_areas.insert(name.into(), area);
177        self
178    }
179
180    /// Set the overflow behavior for this grid.
181    #[must_use]
182    pub fn overflow(mut self, overflow: crate::OverflowBehavior) -> Self {
183        self.overflow = overflow;
184        self
185    }
186
187    /// Get the current overflow behavior.
188    #[must_use]
189    pub fn overflow_behavior(&self) -> crate::OverflowBehavior {
190        self.overflow
191    }
192
193    /// Get the number of rows.
194    #[inline]
195    pub fn num_rows(&self) -> usize {
196        self.row_constraints.len()
197    }
198
199    /// Get the number of columns.
200    #[inline]
201    pub fn num_cols(&self) -> usize {
202        self.col_constraints.len()
203    }
204
205    /// Split the given area according to the grid configuration.
206    pub fn split(&self, area: Rect) -> GridLayout {
207        let num_rows = self.row_constraints.len();
208        let num_cols = self.col_constraints.len();
209
210        if num_rows == 0 || num_cols == 0 || area.is_empty() {
211            return GridLayout {
212                row_heights: smallvec::smallvec![0; num_rows],
213                col_widths: smallvec::smallvec![0; num_cols],
214                row_positions: smallvec::smallvec![area.y; num_rows],
215                col_positions: smallvec::smallvec![area.x; num_cols],
216                named_areas: self.named_areas.clone(),
217                row_gap: 0,
218                col_gap: 0,
219                bounds: area,
220            };
221        }
222
223        // Calculate total gaps
224        let total_row_gap = if num_rows > 1 {
225            let gaps = (num_rows - 1) as u64;
226            (gaps * self.row_gap as u64).min(u16::MAX as u64) as u16
227        } else {
228            0
229        };
230        let total_col_gap = if num_cols > 1 {
231            let gaps = (num_cols - 1) as u64;
232            (gaps * self.col_gap as u64).min(u16::MAX as u64) as u16
233        } else {
234            0
235        };
236
237        // Available space after gaps
238        let available_height = area.height.saturating_sub(total_row_gap);
239        let available_width = area.width.saturating_sub(total_col_gap);
240
241        // Solve constraints
242        let row_heights = crate::solve_constraints(&self.row_constraints, available_height);
243        let col_widths = crate::solve_constraints(&self.col_constraints, available_width);
244
245        // Calculate positions
246        let row_positions = self.calculate_positions(&row_heights, area.y, self.row_gap);
247        let col_positions = self.calculate_positions(&col_widths, area.x, self.col_gap);
248
249        GridLayout {
250            row_heights,
251            col_widths,
252            row_positions,
253            col_positions,
254            named_areas: self.named_areas.clone(),
255            row_gap: self.row_gap,
256            col_gap: self.col_gap,
257            bounds: area,
258        }
259    }
260
261    /// Calculate cumulative positions from sizes.
262    fn calculate_positions(&self, sizes: &[u16], start: u16, gap: u16) -> Sizes {
263        let mut positions = Sizes::with_capacity(sizes.len());
264        let mut pos = start;
265
266        for (i, &size) in sizes.iter().enumerate() {
267            positions.push(pos);
268            pos = pos.saturating_add(size);
269            if i < sizes.len() - 1 {
270                pos = pos.saturating_add(gap);
271            }
272        }
273
274        positions
275    }
276}
277
278impl GridLayout {
279    /// Get the rectangle for a specific cell.
280    ///
281    /// Returns an empty Rect if coordinates are out of bounds.
282    #[inline]
283    pub fn cell(&self, row: usize, col: usize) -> Rect {
284        self.span(row, col, 1, 1)
285    }
286
287    /// Get the rectangle for a spanning region.
288    ///
289    /// The region starts at (row, col) and spans rowspan rows and colspan columns.
290    pub fn span(&self, row: usize, col: usize, rowspan: usize, colspan: usize) -> Rect {
291        let rowspan = rowspan.max(1);
292        let colspan = colspan.max(1);
293
294        // Bounds check
295        if row >= self.row_heights.len() || col >= self.col_widths.len() {
296            return Rect::default();
297        }
298
299        // Saturating: `usize::MAX` reads naturally as "to the last row", and
300        // the plain sum overflowed (a panic in debug, an empty rect in
301        // release).
302        let end_row = row.saturating_add(rowspan).min(self.row_heights.len());
303        let end_col = col.saturating_add(colspan).min(self.col_widths.len());
304
305        // Get starting position
306        let x = self.col_positions[col];
307        let y = self.row_positions[row];
308
309        // Calculate total width (sum of widths + gaps between spanned columns)
310        let mut width: u16 = 0;
311        for c in col..end_col {
312            width = width.saturating_add(self.col_widths[c]);
313        }
314        // Add gaps between columns (not after last)
315        if end_col > col + 1 {
316            let gap_count = (end_col - col - 1) as u16;
317            width = width.saturating_add(self.col_gap.saturating_mul(gap_count));
318        }
319
320        // Calculate total height (sum of heights + gaps between spanned rows)
321        let mut height: u16 = 0;
322        for r in row..end_row {
323            height = height.saturating_add(self.row_heights[r]);
324        }
325        if end_row > row + 1 {
326            let gap_count = (end_row - row - 1) as u16;
327            height = height.saturating_add(self.row_gap.saturating_mul(gap_count));
328        }
329
330        Rect::new(x, y, width, height).intersection(&self.bounds)
331    }
332
333    /// Get the rectangle for a named area.
334    ///
335    /// Returns None if the area name is not defined.
336    pub fn area(&self, name: &str) -> Option<Rect> {
337        self.named_areas
338            .get(name)
339            .map(|a| self.span(a.row, a.col, a.rowspan, a.colspan))
340    }
341
342    /// Get the number of rows in this layout.
343    #[inline]
344    pub fn num_rows(&self) -> usize {
345        self.row_heights.len()
346    }
347
348    /// Get the number of columns in this layout.
349    #[inline]
350    pub fn num_cols(&self) -> usize {
351        self.col_widths.len()
352    }
353
354    /// Get the height of a specific row.
355    #[inline]
356    pub fn row_height(&self, row: usize) -> u16 {
357        self.row_heights.get(row).copied().unwrap_or(0)
358    }
359
360    /// Get the width of a specific column.
361    #[inline]
362    pub fn col_width(&self, col: usize) -> u16 {
363        self.col_widths.get(col).copied().unwrap_or(0)
364    }
365
366    /// Iterate over all cells, yielding (row, col, Rect).
367    pub fn iter_cells(&self) -> impl Iterator<Item = (usize, usize, Rect)> + '_ {
368        let num_rows = self.num_rows();
369        let num_cols = self.num_cols();
370        (0..num_rows)
371            .flat_map(move |row| (0..num_cols).map(move |col| (row, col, self.cell(row, col))))
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[test]
380    fn empty_grid() {
381        let grid = Grid::new();
382        let layout = grid.split(Rect::new(0, 0, 100, 50));
383        assert_eq!(layout.num_rows(), 0);
384        assert_eq!(layout.num_cols(), 0);
385    }
386
387    #[test]
388    fn simple_2x2_grid() {
389        let grid = Grid::new()
390            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
391            .columns([Constraint::Fixed(20), Constraint::Fixed(20)]);
392
393        let layout = grid.split(Rect::new(0, 0, 100, 50));
394
395        assert_eq!(layout.num_rows(), 2);
396        assert_eq!(layout.num_cols(), 2);
397
398        // Check each cell
399        assert_eq!(layout.cell(0, 0), Rect::new(0, 0, 20, 10));
400        assert_eq!(layout.cell(0, 1), Rect::new(20, 0, 20, 10));
401        assert_eq!(layout.cell(1, 0), Rect::new(0, 10, 20, 10));
402        assert_eq!(layout.cell(1, 1), Rect::new(20, 10, 20, 10));
403    }
404
405    #[test]
406    fn grid_with_gaps() {
407        let grid = Grid::new()
408            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
409            .columns([Constraint::Fixed(20), Constraint::Fixed(20)])
410            .row_gap(2)
411            .col_gap(5);
412
413        let layout = grid.split(Rect::new(0, 0, 100, 50));
414
415        // First row, first col
416        assert_eq!(layout.cell(0, 0), Rect::new(0, 0, 20, 10));
417        // First row, second col (after col_gap of 5)
418        assert_eq!(layout.cell(0, 1), Rect::new(25, 0, 20, 10));
419        // Second row, first col (after row_gap of 2)
420        assert_eq!(layout.cell(1, 0), Rect::new(0, 12, 20, 10));
421        // Second row, second col
422        assert_eq!(layout.cell(1, 1), Rect::new(25, 12, 20, 10));
423    }
424
425    #[test]
426    fn percentage_constraints() {
427        let grid = Grid::new()
428            .rows([Constraint::Percentage(50.0), Constraint::Percentage(50.0)])
429            .columns([Constraint::Percentage(30.0), Constraint::Percentage(70.0)]);
430
431        let layout = grid.split(Rect::new(0, 0, 100, 50));
432
433        assert_eq!(layout.row_height(0), 25);
434        assert_eq!(layout.row_height(1), 25);
435        assert_eq!(layout.col_width(0), 30);
436        assert_eq!(layout.col_width(1), 70);
437    }
438
439    #[test]
440    fn min_constraints_fill_space() {
441        let grid = Grid::new()
442            .rows([Constraint::Fixed(10), Constraint::Min(5)])
443            .columns([Constraint::Fixed(20), Constraint::Min(10)]);
444
445        let layout = grid.split(Rect::new(0, 0, 100, 50));
446
447        // Min should expand to fill remaining space
448        assert_eq!(layout.row_height(0), 10);
449        assert_eq!(layout.row_height(1), 40); // 50 - 10 = 40
450        assert_eq!(layout.col_width(0), 20);
451        assert_eq!(layout.col_width(1), 80); // 100 - 20 = 80
452    }
453
454    #[test]
455    fn grid_span_clamps_out_of_bounds() {
456        let grid = Grid::new()
457            .rows([Constraint::Fixed(4), Constraint::Fixed(6)])
458            .columns([Constraint::Fixed(8), Constraint::Fixed(12)]);
459
460        let layout = grid.split(Rect::new(0, 0, 40, 20));
461        let span = layout.span(1, 1, 5, 5);
462
463        assert_eq!(span, Rect::new(8, 4, 12, 6));
464    }
465
466    #[test]
467    fn grid_span_to_the_end_with_usize_max() {
468        // `row + rowspan` overflowed: a panic in debug, an empty rect in
469        // release.
470        let grid = Grid::new()
471            .rows([Constraint::Fixed(4), Constraint::Fixed(6)])
472            .columns([Constraint::Fixed(8), Constraint::Fixed(12)]);
473        let layout = grid.split(Rect::new(0, 0, 40, 20));
474
475        assert_eq!(layout.span(1, 0, usize::MAX, 1), Rect::new(0, 4, 8, 6));
476        assert_eq!(
477            layout.span(0, 1, usize::MAX, usize::MAX),
478            Rect::new(8, 0, 12, 10)
479        );
480    }
481
482    #[test]
483    fn grid_span_includes_gaps_between_tracks() {
484        let grid = Grid::new()
485            .rows([Constraint::Fixed(3)])
486            .columns([
487                Constraint::Fixed(2),
488                Constraint::Fixed(2),
489                Constraint::Fixed(2),
490            ])
491            .col_gap(1);
492
493        let layout = grid.split(Rect::new(0, 0, 20, 10));
494        let span = layout.span(0, 0, 1, 3);
495
496        assert_eq!(span.width, 8); // 2 + 1 + 2 + 1 + 2
497        assert_eq!(span.height, 3);
498    }
499
500    #[test]
501    fn grid_tiny_area_with_gaps_produces_zero_tracks() {
502        let grid = Grid::new()
503            .rows([Constraint::Fixed(1), Constraint::Fixed(1)])
504            .columns([Constraint::Fixed(1), Constraint::Fixed(1)])
505            .row_gap(2)
506            .col_gap(2);
507
508        let layout = grid.split(Rect::new(0, 0, 1, 1));
509        assert_eq!(layout.row_height(0), 0);
510        assert_eq!(layout.row_height(1), 0);
511        assert_eq!(layout.col_width(0), 0);
512        assert_eq!(layout.col_width(1), 0);
513    }
514
515    #[test]
516    fn cell_spanning() {
517        let grid = Grid::new()
518            .rows([
519                Constraint::Fixed(10),
520                Constraint::Fixed(10),
521                Constraint::Fixed(10),
522            ])
523            .columns([
524                Constraint::Fixed(20),
525                Constraint::Fixed(20),
526                Constraint::Fixed(20),
527            ]);
528
529        let layout = grid.split(Rect::new(0, 0, 100, 50));
530
531        // Single cell
532        assert_eq!(layout.span(0, 0, 1, 1), Rect::new(0, 0, 20, 10));
533
534        // Horizontal span (2 columns)
535        assert_eq!(layout.span(0, 0, 1, 2), Rect::new(0, 0, 40, 10));
536
537        // Vertical span (2 rows)
538        assert_eq!(layout.span(0, 0, 2, 1), Rect::new(0, 0, 20, 20));
539
540        // 2x2 block
541        assert_eq!(layout.span(0, 0, 2, 2), Rect::new(0, 0, 40, 20));
542    }
543
544    #[test]
545    fn cell_spanning_with_gaps() {
546        let grid = Grid::new()
547            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
548            .columns([Constraint::Fixed(20), Constraint::Fixed(20)])
549            .row_gap(2)
550            .col_gap(5);
551
552        let layout = grid.split(Rect::new(0, 0, 100, 50));
553
554        // 2x2 span should include the gaps
555        let full = layout.span(0, 0, 2, 2);
556        // Width: 20 + 5 (gap) + 20 = 45
557        // Height: 10 + 2 (gap) + 10 = 22
558        assert_eq!(full.width, 45);
559        assert_eq!(full.height, 22);
560    }
561
562    #[test]
563    fn named_areas() {
564        let grid = Grid::new()
565            .rows([
566                Constraint::Fixed(5),
567                Constraint::Min(10),
568                Constraint::Fixed(3),
569            ])
570            .columns([Constraint::Fixed(20), Constraint::Min(30)])
571            .area("header", GridArea::span(0, 0, 1, 2))
572            .area("sidebar", GridArea::span(1, 0, 2, 1))
573            .area("content", GridArea::cell(1, 1))
574            .area("footer", GridArea::cell(2, 1));
575
576        let layout = grid.split(Rect::new(0, 0, 80, 30));
577
578        // Header spans both columns
579        let header = layout.area("header").unwrap();
580        assert_eq!(header.y, 0);
581        assert_eq!(header.height, 5);
582
583        // Sidebar spans rows 1 and 2
584        let sidebar = layout.area("sidebar").unwrap();
585        assert_eq!(sidebar.x, 0);
586        assert_eq!(sidebar.width, 20);
587
588        // Content is in the middle
589        let content = layout.area("content").unwrap();
590        assert_eq!(content.x, 20);
591        assert_eq!(content.y, 5);
592
593        // Footer is at the bottom right
594        let footer = layout.area("footer").unwrap();
595        assert_eq!(
596            footer.y,
597            layout.area("content").unwrap().y + layout.area("content").unwrap().height
598        );
599    }
600
601    #[test]
602    fn out_of_bounds_returns_empty() {
603        let grid = Grid::new()
604            .rows([Constraint::Fixed(10)])
605            .columns([Constraint::Fixed(20)]);
606
607        let layout = grid.split(Rect::new(0, 0, 100, 50));
608
609        // Out of bounds
610        assert_eq!(layout.cell(5, 5), Rect::default());
611        assert_eq!(layout.cell(0, 5), Rect::default());
612        assert_eq!(layout.cell(5, 0), Rect::default());
613    }
614
615    #[test]
616    fn iter_cells() {
617        let grid = Grid::new()
618            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
619            .columns([Constraint::Fixed(20), Constraint::Fixed(20)]);
620
621        let layout = grid.split(Rect::new(0, 0, 100, 50));
622
623        let cells: Vec<_> = layout.iter_cells().collect();
624        assert_eq!(cells.len(), 4);
625        assert_eq!(cells[0], (0, 0, Rect::new(0, 0, 20, 10)));
626        assert_eq!(cells[1], (0, 1, Rect::new(20, 0, 20, 10)));
627        assert_eq!(cells[2], (1, 0, Rect::new(0, 10, 20, 10)));
628        assert_eq!(cells[3], (1, 1, Rect::new(20, 10, 20, 10)));
629    }
630
631    #[test]
632    fn undefined_area_returns_none() {
633        let grid = Grid::new()
634            .rows([Constraint::Fixed(10)])
635            .columns([Constraint::Fixed(20)]);
636
637        let layout = grid.split(Rect::new(0, 0, 100, 50));
638
639        assert!(layout.area("nonexistent").is_none());
640    }
641
642    #[test]
643    fn empty_area_produces_empty_cells() {
644        let grid = Grid::new()
645            .rows([Constraint::Fixed(10)])
646            .columns([Constraint::Fixed(20)]);
647
648        let layout = grid.split(Rect::new(0, 0, 0, 0));
649
650        assert_eq!(layout.cell(0, 0), Rect::new(0, 0, 0, 0));
651    }
652
653    #[test]
654    fn offset_area() {
655        let grid = Grid::new()
656            .rows([Constraint::Fixed(10)])
657            .columns([Constraint::Fixed(20)]);
658
659        let layout = grid.split(Rect::new(10, 5, 100, 50));
660
661        // Cell should be offset by the area origin
662        assert_eq!(layout.cell(0, 0), Rect::new(10, 5, 20, 10));
663    }
664
665    #[test]
666    fn ratio_constraints() {
667        let grid = Grid::new()
668            .rows([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)])
669            .columns([Constraint::Fixed(30)]);
670
671        let layout = grid.split(Rect::new(0, 0, 30, 30));
672
673        // 1:2 ratio should give roughly 10:20 split
674        assert_eq!(layout.row_height(0), 10);
675        assert_eq!(layout.row_height(1), 20);
676    }
677
678    #[test]
679    fn max_constraints() {
680        // Test that Max(N) clamps the size to at most N
681        let grid = Grid::new()
682            .rows([Constraint::Max(5), Constraint::Fixed(20)])
683            .columns([Constraint::Fixed(30)]);
684
685        let layout = grid.split(Rect::new(0, 0, 30, 30));
686
687        // Max(5) should get at most 5, but the remaining 5 (from 30-20=10 available)
688        // is distributed to Max, giving 5 which is then clamped to 5
689        assert!(layout.row_height(0) <= 5);
690        // Fixed gets its exact size
691        assert_eq!(layout.row_height(1), 20);
692    }
693
694    #[test]
695    fn fixed_constraints_exceed_available_clamped() {
696        let grid = Grid::new()
697            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
698            .columns([Constraint::Fixed(7), Constraint::Fixed(7)]);
699
700        let layout = grid.split(Rect::new(0, 0, 10, 15));
701
702        assert_eq!(layout.row_height(0), 10);
703        assert_eq!(layout.row_height(1), 5);
704        assert_eq!(layout.col_width(0), 7);
705        assert_eq!(layout.col_width(1), 3);
706    }
707
708    #[test]
709    fn ratio_constraints_calculate_strictly() {
710        let grid = Grid::new()
711            .rows([Constraint::Fixed(1)])
712            .columns([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
713
714        let layout = grid.split(Rect::new(0, 0, 5, 1));
715
716        // 5 * 1/3 = 1
717        // 5 * 2/3 = 3
718        // Total allocated = 4. Remaining = 1.
719        // Ratio is no longer a grow constraint, so it doesn't consume the remainder.
720        assert_eq!(layout.col_width(0), 1);
721        assert_eq!(layout.col_width(1), 3);
722    }
723
724    // --- Additional Grid tests ---
725
726    #[test]
727    fn uniform_gap_sets_both() {
728        let grid = Grid::new()
729            .rows([Constraint::Fixed(10), Constraint::Fixed(10)])
730            .columns([Constraint::Fixed(20), Constraint::Fixed(20)])
731            .gap(3);
732
733        let layout = grid.split(Rect::new(0, 0, 100, 50));
734
735        // Both row_gap and col_gap should be 3
736        assert_eq!(layout.cell(0, 1).x, 23); // 20 + 3
737        assert_eq!(layout.cell(1, 0).y, 13); // 10 + 3
738    }
739
740    #[test]
741    fn grid_area_cell_is_1x1_span() {
742        let a = GridArea::cell(2, 3);
743        assert_eq!(a.row, 2);
744        assert_eq!(a.col, 3);
745        assert_eq!(a.rowspan, 1);
746        assert_eq!(a.colspan, 1);
747    }
748
749    #[test]
750    fn grid_area_span_clamps_zero() {
751        // Zero spans should be clamped to 1
752        let a = GridArea::span(0, 0, 0, 0);
753        assert_eq!(a.rowspan, 1);
754        assert_eq!(a.colspan, 1);
755    }
756
757    #[test]
758    fn grid_num_rows_cols() {
759        let grid = Grid::new()
760            .rows([
761                Constraint::Fixed(5),
762                Constraint::Fixed(5),
763                Constraint::Fixed(5),
764            ])
765            .columns([Constraint::Fixed(10), Constraint::Fixed(10)]);
766        assert_eq!(grid.num_rows(), 3);
767        assert_eq!(grid.num_cols(), 2);
768    }
769
770    #[test]
771    fn grid_row_height_col_width_out_of_bounds() {
772        let grid = Grid::new()
773            .rows([Constraint::Fixed(10)])
774            .columns([Constraint::Fixed(20)]);
775        let layout = grid.split(Rect::new(0, 0, 100, 50));
776        assert_eq!(layout.row_height(0), 10);
777        assert_eq!(layout.row_height(99), 0); // Out of bounds returns 0
778        assert_eq!(layout.col_width(0), 20);
779        assert_eq!(layout.col_width(99), 0); // Out of bounds returns 0
780    }
781
782    #[test]
783    fn grid_span_clamped_to_bounds() {
784        let grid = Grid::new()
785            .rows([Constraint::Fixed(10)])
786            .columns([Constraint::Fixed(20)]);
787        let layout = grid.split(Rect::new(0, 0, 100, 50));
788
789        // Spanning beyond grid dimensions should clamp
790        let r = layout.span(0, 0, 5, 5);
791        // Should get the single cell (1x1 grid)
792        assert_eq!(r, Rect::new(0, 0, 20, 10));
793    }
794
795    #[test]
796    fn grid_with_all_constraint_types() {
797        let grid = Grid::new()
798            .rows([
799                Constraint::Fixed(5),
800                Constraint::Percentage(20.0),
801                Constraint::Min(3),
802                Constraint::Max(10),
803                Constraint::Ratio(1, 4),
804            ])
805            .columns([Constraint::Fixed(30)]);
806
807        let layout = grid.split(Rect::new(0, 0, 30, 50));
808
809        // All rows should have non-negative heights
810        let total: u16 = (0..layout.num_rows()).map(|r| layout.row_height(r)).sum();
811        assert!(total <= 50);
812    }
813
814    // Property-like invariant tests
815    #[test]
816    fn invariant_total_size_within_bounds() {
817        for (width, height) in [(50, 30), (100, 50), (80, 24)] {
818            let grid = Grid::new()
819                .rows([
820                    Constraint::Fixed(10),
821                    Constraint::Min(5),
822                    Constraint::Percentage(20.0),
823                ])
824                .columns([
825                    Constraint::Fixed(15),
826                    Constraint::Min(10),
827                    Constraint::Ratio(1, 2),
828                ]);
829
830            let layout = grid.split(Rect::new(0, 0, width, height));
831
832            let total_height: u16 = (0..layout.num_rows()).map(|r| layout.row_height(r)).sum();
833            let total_width: u16 = (0..layout.num_cols()).map(|c| layout.col_width(c)).sum();
834
835            assert!(
836                total_height <= height,
837                "Total height {} exceeds available {}",
838                total_height,
839                height
840            );
841            assert!(
842                total_width <= width,
843                "Total width {} exceeds available {}",
844                total_width,
845                width
846            );
847        }
848    }
849
850    #[test]
851    fn invariant_cells_within_area() {
852        let area = Rect::new(10, 20, 80, 60);
853        let grid = Grid::new()
854            .rows([
855                Constraint::Fixed(15),
856                Constraint::Min(10),
857                Constraint::Fixed(15),
858            ])
859            .columns([
860                Constraint::Fixed(20),
861                Constraint::Min(20),
862                Constraint::Fixed(20),
863            ])
864            .row_gap(2)
865            .col_gap(3);
866
867        let layout = grid.split(area);
868
869        for (row, col, cell) in layout.iter_cells() {
870            assert!(
871                cell.x >= area.x,
872                "Cell ({},{}) x {} < area x {}",
873                row,
874                col,
875                cell.x,
876                area.x
877            );
878            assert!(
879                cell.y >= area.y,
880                "Cell ({},{}) y {} < area y {}",
881                row,
882                col,
883                cell.y,
884                area.y
885            );
886            assert!(
887                cell.right() <= area.right(),
888                "Cell ({},{}) right {} > area right {}",
889                row,
890                col,
891                cell.right(),
892                area.right()
893            );
894            assert!(
895                cell.bottom() <= area.bottom(),
896                "Cell ({},{}) bottom {} > area bottom {}",
897                row,
898                col,
899                cell.bottom(),
900                area.bottom()
901            );
902        }
903    }
904
905    #[test]
906    fn grid_layout_span_clamps_zero() {
907        let grid = Grid::new()
908            .rows([Constraint::Fixed(10)])
909            .columns([Constraint::Fixed(20)]);
910        let layout = grid.split(Rect::new(0, 0, 100, 50));
911
912        // span(..., 0, 0) should be clamped to 1x1 (the cell itself)
913        let r = layout.span(0, 0, 0, 0);
914        assert_eq!(r, layout.cell(0, 0));
915        assert_eq!(r.width, 20);
916        assert_eq!(r.height, 10);
917    }
918}