crates/tui-core/src/vstack.rs 16.4 KiB raw
1
//! Vertical widget layout container.
2
//!
3
//! `VStack` lays child widgets from top to bottom with optional border,
4
//! horizontal padding, dividers, and fill rows. It is the main primitive for
5
//! stacking small widgets into panels while preserving each child's own render
6
//! logic.
7
8
use super::colors;
9
use super::{Border, Buffer, Cell, Constraint, Label, Length, Rect, Size, Style, Widget};
10
11
/// Default horizontal padding inside a stack border.
12
pub const DEFAULT_PADDING: usize = 1;
13
/// Default divider glyph.
14
pub const DEFAULT_DIVIDER_GLYPH: char = '─';
15
/// Default divider style.
16
pub const DEFAULT_DIVIDER_STYLE: Style = Style::new(super::Color::Unset);
17
18
/// Options for [`VStack`].
19
#[derive(Debug)]
20
pub struct VStackOptions {
21
    /// Optional outer border color.
22
    border: Option<Border>,
23
    /// Horizontal padding inside the outer border.
24
    padding: usize,
25
}
26
27
impl Default for VStackOptions {
28
    fn default() -> Self {
29
        Self {
30
            border: None,
31
            padding: DEFAULT_PADDING,
32
        }
33
    }
34
}
35
36
/// A vertical stack row.
37
#[derive(Debug)]
38
enum Row<'a> {
39
    Widget {
40
        /// Widget rendered in this row.
41
        widget: Box<dyn Widget + 'a>,
42
        /// Optional row height policy.
43
        height: Option<Length>,
44
    },
45
    Divider {
46
        /// Cell repeated across the divider row.
47
        cell: Cell,
48
    },
49
}
50
51
impl Default for Row<'_> {
52
    /// Create the default divider row.
53
    fn default() -> Self {
54
        Self::Divider {
55
            cell: Cell::new(DEFAULT_DIVIDER_GLYPH, DEFAULT_DIVIDER_STYLE),
56
        }
57
    }
58
}
59
60
impl Row<'_> {
61
    /// Return the row's natural width under the given parent constraint.
62
    fn width(&self, c: Constraint) -> usize {
63
        match self {
64
            Self::Widget { widget, .. } => widget.columns(c),
65
            Self::Divider { .. } => c.min.cols,
66
        }
67
    }
68
69
    /// Return the row's natural height before leftover space is distributed.
70
    fn natural_height(&self, c: Constraint) -> usize {
71
        match self {
72
            Self::Widget { widget, height } => match height {
73
                Some(Length::Fixed(rows) | Length::Min(rows)) => *rows,
74
                Some(Length::Fill(_)) => 0,
75
                None => widget.rows(c),
76
            },
77
            Self::Divider { .. } => 1,
78
        }
79
    }
80
81
    /// Return the height policy used when allocating render rows.
82
    fn layout_height(&self, c: Constraint) -> Length {
83
        match self {
84
            Self::Widget { widget, height } => {
85
                height.unwrap_or_else(|| Length::Fixed(widget.rows(c)))
86
            }
87
            Self::Divider { .. } => Length::Fixed(1),
88
        }
89
    }
90
}
91
92
/// Vertical stack of [`Widget`] objects.
93
#[derive(Default, Debug)]
94
pub struct VStack<'a> {
95
    rows: Vec<Row<'a>>,
96
    opts: VStackOptions,
97
}
98
99
impl<'a> VStack<'a> {
100
    /// Add a widget to the stack and return the stack.
101
    pub fn child(mut self, child: impl Widget + 'a) -> Self {
102
        self.push(child);
103
        self
104
    }
105
106
    /// Boxes this stack as a [`Widget`].
107
    pub fn boxed(self) -> Box<dyn Widget + 'a> {
108
        Box::new(self)
109
    }
110
111
    /// Add a widget with an explicit row height policy.
112
    pub fn child_with_height(mut self, child: impl Widget + 'a, height: Length) -> Self {
113
        self.push_with_height(child, height);
114
        self
115
    }
116
117
    /// Add a widget that fills remaining vertical space.
118
    pub fn fill(self, child: impl Widget + 'a) -> Self {
119
        self.child_with_height(child, Length::Fill(1))
120
    }
121
122
    /// Add a blank line to the stack.
123
    pub fn blank(self) -> Self {
124
        self.child(Label::blank())
125
    }
126
127
    /// Add a horizontal divider.
128
    pub fn divider(mut self) -> Self {
129
        self.rows.push(Row::default());
130
        self
131
    }
132
133
    /// Check if this stack is empty.
134
    pub fn is_empty(&self) -> bool {
135
        self.rows.is_empty()
136
    }
137
138
    /// Add multiple widgets to the stack.
139
    pub fn children<I>(mut self, children: I) -> Self
140
    where
141
        I: IntoIterator<Item = Box<dyn Widget + 'a>>,
142
    {
143
        self.rows
144
            .extend(children.into_iter().map(|widget| Row::Widget {
145
                widget,
146
                height: None,
147
            }));
148
        self
149
    }
150
151
    /// Merge with another `VStack`.
152
    pub fn merge(mut self, other: Self) -> Self {
153
        self.rows.extend(other.rows);
154
        self
155
    }
156
157
    /// Set or unset the outer border.
158
    pub fn border(mut self, border: Option<Border>) -> Self {
159
        self.opts.border = border;
160
        self
161
    }
162
163
    /// Set the outer border.
164
    pub fn bordered(self, border: Border) -> Self {
165
        self.border(Some(border))
166
    }
167
168
    /// Set horizontal padding.
169
    pub fn padding(mut self, cols: usize) -> Self {
170
        self.opts.padding = cols;
171
        self
172
    }
173
174
    /// Add a horizontal divider with an explicit cell.
175
    pub fn divider_cell(mut self, cell: Cell) -> Self {
176
        self.rows.push(Row::Divider { cell });
177
        self
178
    }
179
180
    /// Add a widget to the stack.
181
    pub fn push(&mut self, child: impl Widget + 'a) {
182
        self.rows.push(Row::Widget {
183
            widget: Box::new(child),
184
            height: None,
185
        });
186
    }
187
188
    /// Add a widget to the stack with an explicit row height policy.
189
    pub fn push_with_height(&mut self, child: impl Widget + 'a, height: Length) {
190
        self.rows.push(Row::Widget {
191
            widget: Box::new(child),
192
            height: Some(height),
193
        });
194
    }
195
196
    /// Inner size.
197
    #[cfg(test)]
198
    fn inner(&self, c: Constraint) -> Size {
199
        let mut outer = self.outer(c);
200
201
        if self.opts.border.is_some() {
202
            outer.cols = outer.cols.saturating_sub(2);
203
            outer.rows = outer.rows.saturating_sub(2);
204
        }
205
        outer
206
    }
207
208
    /// Outer size (includes borders).
209
    fn outer(&self, c: Constraint) -> Size {
210
        let padding = self.opts.padding * 2;
211
        let mut cols = self
212
            .rows
213
            .iter()
214
            .map(|r| r.width(c))
215
            .max()
216
            .unwrap_or(0)
217
            .saturating_add(padding);
218
        let mut rows = self
219
            .rows
220
            .iter()
221
            .map(|r| r.natural_height(c))
222
            .fold(0usize, usize::saturating_add);
223
224
        // Account for outer borders.
225
        if self.opts.border.is_some() {
226
            cols = cols.saturating_add(2);
227
            rows = rows.saturating_add(2);
228
        }
229
        Size::new(cols, rows).constrain(c)
230
    }
231
}
232
233
impl Widget for VStack<'_> {
234
    fn size(&self, parent: Constraint) -> Size {
235
        self.outer(parent)
236
    }
237
238
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
239
        let padding = self.opts.padding;
240
        let content = if self.opts.border.is_some() {
241
            area.inner(1)
242
        } else {
243
            area
244
        };
245
        let child_cols = content.cols.saturating_sub(padding * 2);
246
        let child_constraint = Constraint::tight(child_cols);
247
        let child_x = content.x + padding.min(content.cols);
248
        let heights = allocate_heights(
249
            content.rows,
250
            &self
251
                .rows
252
                .iter()
253
                .map(|row| row.layout_height(child_constraint))
254
                .collect::<Vec<_>>(),
255
        );
256
        let mut y = content.y;
257
258
        if let Some(border) = self.opts.border {
259
            border.draw(area, buf);
260
        }
261
        for (row, rows) in self.rows.iter_mut().zip(heights) {
262
            match row {
263
                Row::Widget { widget, .. } => {
264
                    if rows > 0 && y < content.bottom() {
265
                        let area = Rect::new(child_x, y, child_cols, rows);
266
                        widget.render(area, buf);
267
                    }
268
                    y += rows;
269
                }
270
                Row::Divider { cell } => {
271
                    let row_y = y;
272
                    y += rows;
273
274
                    if rows == 0 || row_y >= area.bottom() {
275
                        continue;
276
                    }
277
                    if let Some(border) = self.opts.border {
278
                        buf.set_char(area.x, row_y, border.chars.divider_left, border.style);
279
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
280
281
                        if area.cols > 1 {
282
                            buf.set_char(
283
                                area.right().saturating_sub(1),
284
                                row_y,
285
                                border.chars.divider_right,
286
                                border.style,
287
                            );
288
                        }
289
                    } else {
290
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
291
                    }
292
                }
293
            }
294
        }
295
    }
296
}
297
298
/// Allocates row heights without growing fixed rows when no fill row exists.
299
fn allocate_heights(total: usize, lengths: &[Length]) -> Vec<usize> {
300
    let base = lengths
301
        .iter()
302
        .map(|length| match *length {
303
            Length::Fixed(rows) | Length::Min(rows) => rows,
304
            Length::Fill(_) => 0,
305
        })
306
        .sum::<usize>();
307
    let fill = lengths
308
        .iter()
309
        .map(|length| match *length {
310
            Length::Fill(weight) => weight.max(1) as usize,
311
            _ => 0,
312
        })
313
        .sum::<usize>();
314
    let remaining = total.saturating_sub(base);
315
    let mut used = 0usize;
316
    let mut remaining_fill = fill;
317
    let mut used_fill = 0usize;
318
319
    lengths
320
        .iter()
321
        .map(|length| {
322
            let rows = match *length {
323
                Length::Fixed(rows) | Length::Min(rows) => rows,
324
                Length::Fill(weight) if fill > 0 => {
325
                    let weight = weight.max(1) as usize;
326
                    let rows = if remaining_fill == weight {
327
                        remaining.saturating_sub(used_fill)
328
                    } else {
329
                        remaining * weight / fill
330
                    };
331
                    remaining_fill = remaining_fill.saturating_sub(weight);
332
                    used_fill += rows;
333
                    rows
334
                }
335
                Length::Fill(_) => 0,
336
            }
337
            .min(total.saturating_sub(used));
338
            used += rows;
339
            rows
340
        })
341
        .collect()
342
}
343
344
/// Simple bordered vstack.
345
pub fn bordered<'a>(child: impl Widget + 'a) -> VStack<'a> {
346
    VStack::default()
347
        .border(Some(Border::new(colors::FAINT)))
348
        .child(child)
349
}
350
351
#[cfg(test)]
352
mod tests {
353
    use super::*;
354
    use crate::{Buffer, Color, Line};
355
356
    #[derive(Debug)]
357
    struct Expanding;
358
359
    impl Widget for Expanding {
360
        fn size(&self, parent: Constraint) -> Size {
361
            parent.max
362
        }
363
364
        fn render(&mut self, _area: Rect, _buf: &mut Buffer) {}
365
    }
366
367
    #[test]
368
    fn test_vstack() {
369
        let mut v = VStack::default()
370
            .border(Some(Border::new(Color::Unset)))
371
            .padding(1);
372
373
        v.push(Line::new("banana"));
374
        v.push(Line::new("apple"));
375
        v.push(Line::new("abricot"));
376
377
        let constraint = Constraint::default();
378
        let outer = v.outer(constraint);
379
        assert_eq!(outer.cols, 11);
380
        assert_eq!(outer.rows, 5);
381
382
        let inner = v.inner(constraint);
383
        assert_eq!(inner.cols, 9);
384
        assert_eq!(inner.rows, 3);
385
386
        assert_eq!(
387
            v.display(constraint),
388
            r"
389
╭─────────╮
390
│ banana  │
391
│ apple   │
392
│ abricot │
393
╰─────────╯
394
"
395
            .trim_start()
396
        );
397
    }
398
399
    #[test]
400
    fn test_vstack_maximize() {
401
        let mut v = VStack::default()
402
            .border(Some(Border::new(Color::Unset)))
403
            .padding(1);
404
405
        v.push(Line::new("banana"));
406
        v.push(Line::new("apple"));
407
        v.push(Line::new("abricot"));
408
409
        let constraint = Constraint {
410
            min: Size::new(14, 0),
411
            max: Size::new(14, usize::MAX),
412
        };
413
        let outer = v.outer(constraint);
414
        assert_eq!(outer.cols, 14);
415
        assert_eq!(outer.rows, 5);
416
417
        let inner = v.inner(constraint);
418
        assert_eq!(inner.cols, 12);
419
        assert_eq!(inner.rows, 3);
420
421
        assert_eq!(
422
            v.display(constraint),
423
            r"
424
╭────────────╮
425
│ banana     │
426
│ apple      │
427
│ abricot    │
428
╰────────────╯
429
"
430
            .trim_start()
431
        );
432
    }
433
434
    #[test]
435
    fn empty_vstack_has_padding_width_and_no_rows() {
436
        let mut v = VStack::default();
437
438
        assert!(v.is_empty());
439
        assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(2, 0));
440
        assert_eq!(v.display(Constraint::UNBOUNDED), "");
441
    }
442
443
    #[test]
444
    fn unbordered_vstack_renders_widgets_and_plain_divider() {
445
        let mut v = VStack::default()
446
            .padding(0)
447
            .child(Line::new("top"))
448
            .divider()
449
            .child(Line::new("bottom"));
450
451
        assert!(!v.is_empty());
452
        assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(6, 3));
453
        assert_eq!(v.display(Constraint::UNBOUNDED), "top   \n──────\nbottom\n");
454
    }
455
456
    #[test]
457
    fn bordered_divider_keeps_border_and_fill_styles_separate() {
458
        let mut v = VStack::default()
459
            .border(Some(Border::new(Color::Blue)))
460
            .padding(0)
461
            .child(Line::new("top"))
462
            .divider_cell(Cell::new('┄', Style::new(Color::Red)))
463
            .child(Line::new("bottom"));
464
        let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED)));
465
466
        v.render(buffer.area(), &mut buffer);
467
468
        assert_eq!(
469
            buffer.lines(),
470
            vec!["╭──────╮", "│top   │", "├┄┄┄┄┄┄┤", "│bottom│", "╰──────╯"]
471
        );
472
        assert_eq!(
473
            buffer.get(0, 2).map(|cell| cell.style().fg_color()),
474
            Some(Color::Blue)
475
        );
476
        assert_eq!(
477
            buffer.get(1, 2).map(|cell| cell.style().fg_color()),
478
            Some(Color::Red)
479
        );
480
        assert_eq!(
481
            buffer.get(7, 2).map(|cell| cell.style().fg_color()),
482
            Some(Color::Blue)
483
        );
484
    }
485
486
    #[test]
487
    fn blank_adds_empty_widget_row() {
488
        let mut v = VStack::default()
489
            .padding(0)
490
            .child(Line::new("top"))
491
            .blank()
492
            .child(Line::new("bottom"));
493
494
        assert_eq!(v.display(Constraint::UNBOUNDED), "top   \n      \nbottom\n");
495
    }
496
497
    #[test]
498
    fn children_appends_boxed_widgets() {
499
        let children = vec![Line::new("one").boxed(), Line::new("two").boxed()];
500
        let mut v = VStack::default().padding(0).children(children);
501
502
        assert_eq!(v.display(Constraint::UNBOUNDED), "one\ntwo\n");
503
    }
504
505
    #[test]
506
    fn fill_child_absorbs_remaining_height() {
507
        let mut stack = VStack::default()
508
            .padding(0)
509
            .child(Line::new("top"))
510
            .fill(crate::Fill::new('.', crate::Style::default()));
511
        let constraint = Constraint::new(Size::new(5, 4), Size::new(5, 4));
512
513
        assert_eq!(stack.display(constraint), "top  \n.....\n.....\n.....\n");
514
    }
515
516
    #[test]
517
    fn unbounded_expanding_child_does_not_overflow_natural_width() {
518
        let stack = VStack::default()
519
            .border(Some(Border::new(Color::Unset)))
520
            .fill(Expanding);
521
522
        assert_eq!(stack.size(Constraint::UNBOUNDED), Size::new(usize::MAX, 2));
523
    }
524
525
    #[test]
526
    fn merge_preserves_row_order() {
527
        let left = VStack::default().padding(0).child(Line::new("left"));
528
        let right = VStack::default().padding(0).child(Line::new("right"));
529
530
        assert_eq!(
531
            left.merge(right).display(Constraint::UNBOUNDED),
532
            "left \nright\n"
533
        );
534
    }
535
536
    #[test]
537
    fn boxed_vstack_dispatches_widget_methods() {
538
        let mut boxed = VStack::default()
539
            .padding(0)
540
            .child(Line::new("boxed"))
541
            .boxed();
542
543
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
544
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
545
    }
546
547
    #[test]
548
    fn bordered_helper_wraps_child_with_faint_border() {
549
        let mut v = bordered(Line::new("x")).padding(0);
550
        let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED)));
551
552
        v.render(buffer.area(), &mut buffer);
553
554
        assert_eq!(buffer.lines(), vec!["╭─╮", "│x│", "╰─╯"]);
555
        assert_eq!(
556
            buffer.get(0, 0).map(|cell| cell.style().fg_color()),
557
            Some(colors::FAINT)
558
        );
559
        assert_eq!(
560
            buffer.get(0, 1).map(|cell| cell.style().fg_color()),
561
            Some(colors::FAINT)
562
        );
563
        assert_eq!(
564
            buffer.get(2, 2).map(|cell| cell.style().fg_color()),
565
            Some(colors::FAINT)
566
        );
567
    }
568
}