Skip to main content

tinyharness_ui/tui/
layout.rs

1// ── Constraint-based layout engine ──────────────────────────────────────────
2//
3// Splits rectangular areas into sub-areas based on constraints.
4// Inspired by ratatui's layout system but implemented from scratch.
5
6/// A rectangular area on the screen.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub struct Rect {
9    pub x: u16,
10    pub y: u16,
11    pub width: u16,
12    pub height: u16,
13}
14
15impl Rect {
16    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
17        Self {
18            x,
19            y,
20            width,
21            height,
22        }
23    }
24
25    /// The area (width * height) of this rectangle.
26    pub fn area(&self) -> u32 {
27        (self.width as u32) * (self.height as u32)
28    }
29
30    /// Returns true if this rectangle has zero area.
31    pub fn is_empty(&self) -> bool {
32        self.width == 0 || self.height == 0
33    }
34
35    /// Check if a point is inside this rectangle.
36    pub fn contains(&self, x: u16, y: u16) -> bool {
37        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
38    }
39
40    /// Clamp this rectangle to fit within another rectangle.
41    pub fn clamp_to(&self, other: Rect) -> Rect {
42        let x = self.x.max(other.x);
43        let y = self.y.max(other.y);
44        let max_x = (self.x + self.width).min(other.x + other.width);
45        let max_y = (self.y + self.height).min(other.y + other.height);
46        Rect {
47            x,
48            y,
49            width: max_x.saturating_sub(x),
50            height: max_y.saturating_sub(y),
51        }
52    }
53
54    /// The right edge (x + width).
55    pub fn right(&self) -> u16 {
56        self.x + self.width
57    }
58
59    /// The bottom edge (y + height).
60    pub fn bottom(&self) -> u16 {
61        self.y + self.height
62    }
63
64    /// Shrink the rectangle by the given amount on all sides.
65    pub fn shrink(&self, amount: u16) -> Rect {
66        Rect {
67            x: self.x + amount,
68            y: self.y + amount,
69            width: self.width.saturating_sub(amount * 2),
70            height: self.height.saturating_sub(amount * 2),
71        }
72    }
73
74    /// The inner area, shrunk by 1 cell on each side (for borders).
75    pub fn inner(&self) -> Rect {
76        self.shrink(1)
77    }
78
79    /// Split the rectangle horizontally (top/bottom) at the given row offset.
80    pub fn split_horizontally(&self, at: u16) -> (Rect, Rect) {
81        let top_height = at.min(self.height);
82        let bottom_height = self.height.saturating_sub(top_height);
83        (
84            Rect::new(self.x, self.y, self.width, top_height),
85            Rect::new(self.x, self.y + top_height, self.width, bottom_height),
86        )
87    }
88
89    /// Split the rectangle vertically (left/right) at the given column offset.
90    pub fn split_vertically(&self, at: u16) -> (Rect, Rect) {
91        let left_width = at.min(self.width);
92        let right_width = self.width.saturating_sub(left_width);
93        (
94            Rect::new(self.x, self.y, left_width, self.height),
95            Rect::new(self.x + left_width, self.y, right_width, self.height),
96        )
97    }
98}
99
100/// Layout direction.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub enum Direction {
103    /// Stack areas horizontally (left to right).
104    Horizontal,
105    /// Stack areas vertically (top to bottom).
106    Vertical,
107}
108
109/// A constraint for laying out areas.
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub enum Constraint {
112    /// Fixed size in cells.
113    Length(u16),
114    /// Percentage of the available space (0–100).
115    Percentage(u16),
116    /// At least this many cells.
117    Min(u16),
118    /// At most this many cells.
119    Max(u16),
120}
121
122/// A layout specification.
123///
124/// Splits a rectangle into sub-rectangles based on constraints and direction.
125pub struct Layout {
126    pub direction: Direction,
127    pub constraints: Vec<Constraint>,
128    /// Gap between areas in cells (0 = no gap).
129    pub gap: u16,
130}
131
132impl Layout {
133    pub fn new(direction: Direction) -> Self {
134        Self {
135            direction,
136            constraints: Vec::new(),
137            gap: 0,
138        }
139    }
140
141    pub fn constraints(mut self, constraints: Vec<Constraint>) -> Self {
142        self.constraints = constraints;
143        self
144    }
145
146    pub fn gap(mut self, gap: u16) -> Self {
147        self.gap = gap;
148        self
149    }
150
151    /// Split the given area into sub-rectangles based on the constraints.
152    ///
153    /// The algorithm:
154    /// 1. Calculate the total available space (minus gaps).
155    /// 2. Resolve each constraint into a desired size.
156    /// 3. Distribute remaining space to `Min`/`Percentage` constraints.
157    /// 4. Return the list of rectangles.
158    pub fn split(self, area: Rect) -> Vec<Rect> {
159        if self.constraints.is_empty() || area.is_empty() {
160            return vec![];
161        }
162
163        let n = self.constraints.len();
164        let total_gap = self.gap as u32 * n.saturating_sub(1) as u32;
165
166        match self.direction {
167            Direction::Vertical => self.split_vertical(area, total_gap),
168            Direction::Horizontal => self.split_horizontal(area, total_gap),
169        }
170    }
171
172    fn split_vertical(&self, area: Rect, total_gap: u32) -> Vec<Rect> {
173        let available = area.height as u32;
174        let available_after_gap = available.saturating_sub(total_gap);
175        let sizes = self.resolve_sizes(available_after_gap, area.height);
176
177        let mut rects = Vec::with_capacity(sizes.len());
178        let mut y = area.y;
179        for (i, &size) in sizes.iter().enumerate() {
180            let height = size.min(area.y + area.height - y);
181            if height == 0 {
182                break;
183            }
184            rects.push(Rect::new(area.x, y, area.width, height));
185            y += height;
186            if i + 1 < sizes.len() {
187                y += self.gap;
188            }
189        }
190        rects
191    }
192
193    fn split_horizontal(&self, area: Rect, total_gap: u32) -> Vec<Rect> {
194        let available = area.width as u32;
195        let available_after_gap = available.saturating_sub(total_gap);
196        let sizes = self.resolve_sizes(available_after_gap, area.width);
197
198        let mut rects = Vec::with_capacity(sizes.len());
199        let mut x = area.x;
200        for (i, &size) in sizes.iter().enumerate() {
201            let width = size.min(area.x + area.width - x);
202            if width == 0 {
203                break;
204            }
205            rects.push(Rect::new(x, area.y, width, area.height));
206            x += width;
207            if i + 1 < sizes.len() {
208                x += self.gap;
209            }
210        }
211        rects
212    }
213
214    /// Resolve constraints into actual sizes given available space.
215    fn resolve_sizes(&self, available: u32, _total: u16) -> Vec<u16> {
216        let n = self.constraints.len();
217        let mut sizes = vec![0u16; n];
218        let mut remaining = available;
219
220        // First pass: resolve Length and Max constraints
221        for (i, constraint) in self.constraints.iter().enumerate() {
222            match constraint {
223                Constraint::Length(len) => {
224                    let resolved = (*len as u32).min(remaining);
225                    sizes[i] = resolved as u16;
226                    remaining = remaining.saturating_sub(resolved);
227                }
228                Constraint::Max(max) => {
229                    let resolved = (*max as u32).min(remaining);
230                    sizes[i] = resolved as u16;
231                    remaining = remaining.saturating_sub(resolved);
232                }
233                _ => {}
234            }
235        }
236
237        // Second pass: resolve Percentage constraints based on the total
238        // available space (before Length/Max), not the remaining space.
239        // This matches how TUI frameworks like ratatui handle percentages:
240        // percentages are of the total, not of what's left after fixed items.
241        let percentage_base = available;
242        for (i, constraint) in self.constraints.iter().enumerate() {
243            if let Constraint::Percentage(pct) = constraint {
244                let resolved = (percentage_base * *pct as u32 / 100).min(remaining);
245                sizes[i] = resolved as u16;
246                remaining = remaining.saturating_sub(resolved);
247            }
248        }
249
250        // Third pass: resolve Min constraints from remaining space
251        for (i, constraint) in self.constraints.iter().enumerate() {
252            if let Constraint::Min(min) = constraint {
253                let resolved = (*min as u32).min(remaining);
254                sizes[i] = sizes[i].max(resolved as u16);
255                remaining = remaining.saturating_sub(resolved);
256            }
257        }
258
259        // Distribute any remaining space to zero-sized areas
260        if remaining > 0 {
261            let zero_count = sizes.iter().filter(|&&s| s == 0).count() as u32;
262            if zero_count > 0 {
263                let per_area = remaining / zero_count.max(1);
264                for size in sizes.iter_mut() {
265                    if *size == 0 {
266                        *size = per_area as u16;
267                        remaining = remaining.saturating_sub(per_area);
268                    }
269                }
270            }
271        }
272
273        sizes
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn test_rect_new() {
283        let r = Rect::new(1, 2, 30, 10);
284        assert_eq!(r.x, 1);
285        assert_eq!(r.y, 2);
286        assert_eq!(r.width, 30);
287        assert_eq!(r.height, 10);
288    }
289
290    #[test]
291    fn test_rect_area() {
292        let r = Rect::new(0, 0, 30, 10);
293        assert_eq!(r.area(), 300);
294    }
295
296    #[test]
297    fn test_rect_is_empty() {
298        assert!(Rect::new(0, 0, 0, 10).is_empty());
299        assert!(Rect::new(0, 0, 10, 0).is_empty());
300        assert!(!Rect::new(0, 0, 10, 10).is_empty());
301    }
302
303    #[test]
304    fn test_rect_contains() {
305        let r = Rect::new(5, 5, 10, 10);
306        assert!(r.contains(5, 5));
307        assert!(r.contains(14, 14));
308        assert!(!r.contains(4, 5));
309        assert!(!r.contains(15, 5));
310        assert!(!r.contains(5, 15));
311    }
312
313    #[test]
314    fn test_rect_shrink() {
315        let r = Rect::new(0, 0, 10, 10).shrink(1);
316        assert_eq!(r.x, 1);
317        assert_eq!(r.y, 1);
318        assert_eq!(r.width, 8);
319        assert_eq!(r.height, 8);
320    }
321
322    #[test]
323    fn test_rect_inner() {
324        let r = Rect::new(0, 0, 10, 10).inner();
325        assert_eq!(r.x, 1);
326        assert_eq!(r.y, 1);
327        assert_eq!(r.width, 8);
328        assert_eq!(r.height, 8);
329    }
330
331    #[test]
332    fn test_rect_split_horizontally() {
333        let r = Rect::new(0, 0, 80, 24);
334        let (top, bottom) = r.split_horizontally(6);
335        assert_eq!(top, Rect::new(0, 0, 80, 6));
336        assert_eq!(bottom, Rect::new(0, 6, 80, 18));
337    }
338
339    #[test]
340    fn test_rect_split_vertically() {
341        let r = Rect::new(0, 0, 80, 24);
342        let (left, right) = r.split_vertically(60);
343        assert_eq!(left, Rect::new(0, 0, 60, 24));
344        assert_eq!(right, Rect::new(60, 0, 20, 24));
345    }
346
347    #[test]
348    fn test_layout_vertical_fixed() {
349        let layout = Layout::new(Direction::Vertical).constraints(vec![
350            Constraint::Length(1),
351            Constraint::Length(20),
352            Constraint::Length(3),
353        ]);
354        let area = Rect::new(0, 0, 80, 24);
355        let rects = layout.split(area);
356
357        assert_eq!(rects.len(), 3);
358        assert_eq!(rects[0], Rect::new(0, 0, 80, 1)); // status bar
359        assert_eq!(rects[1], Rect::new(0, 1, 80, 20)); // main area
360        assert_eq!(rects[2], Rect::new(0, 21, 80, 3)); // input bar
361    }
362
363    #[test]
364    fn test_layout_horizontal_percentage() {
365        let layout = Layout::new(Direction::Horizontal)
366            .constraints(vec![Constraint::Percentage(70), Constraint::Percentage(30)]);
367        let area = Rect::new(0, 0, 100, 24);
368        let rects = layout.split(area);
369
370        assert_eq!(rects.len(), 2);
371        assert_eq!(rects[0].width, 70);
372        assert_eq!(rects[1].width, 30);
373    }
374
375    #[test]
376    fn test_layout_with_gap() {
377        let layout = Layout::new(Direction::Horizontal)
378            .constraints(vec![Constraint::Length(60), Constraint::Length(30)])
379            .gap(1);
380        let area = Rect::new(0, 0, 91, 24);
381        let rects = layout.split(area);
382
383        assert_eq!(rects.len(), 2);
384        assert_eq!(rects[0], Rect::new(0, 0, 60, 24));
385        assert_eq!(rects[1], Rect::new(61, 0, 30, 24));
386    }
387
388    #[test]
389    fn test_layout_nested() {
390        // Simulate the TinyHarness TUI layout:
391        // Top:    status bar (1 row)
392        // Middle: conversation (70%) + sidebar (30%)
393        // Bottom: input bar (3 rows)
394
395        let full = Rect::new(0, 0, 80, 24);
396        let main_layout = Layout::new(Direction::Vertical).constraints(vec![
397            Constraint::Length(1), // status bar
398            Constraint::Min(0),    // main area (takes remaining)
399            Constraint::Length(3), // input bar
400        ]);
401        let rects = main_layout.split(full);
402
403        assert_eq!(rects[0].height, 1); // status bar
404        assert_eq!(rects[2].height, 3); // input bar
405        assert_eq!(rects[1].height, 20); // main area
406
407        // Split main area horizontally (80 columns wide)
408        // 70% of 80 = 56, 30% of 80 = 24
409        let side_layout = Layout::new(Direction::Horizontal)
410            .constraints(vec![Constraint::Percentage(70), Constraint::Percentage(30)]);
411        let side_rects = side_layout.split(rects[1]);
412
413        assert_eq!(side_rects[0].width, 56); // 70% of 80
414        assert_eq!(side_rects[1].width, 24); // 30% of 80
415    }
416
417    #[test]
418    fn test_layout_empty_constraints() {
419        let layout = Layout::new(Direction::Vertical).constraints(vec![]);
420        let area = Rect::new(0, 0, 80, 24);
421        let rects = layout.split(area);
422        assert!(rects.is_empty());
423    }
424
425    #[test]
426    fn test_layout_empty_area() {
427        let layout = Layout::new(Direction::Vertical).constraints(vec![Constraint::Length(10)]);
428        let area = Rect::new(0, 0, 0, 0);
429        let rects = layout.split(area);
430        assert!(rects.is_empty());
431    }
432}