//! Vertical widget layout container. //! //! `VStack` lays child widgets from top to bottom with optional border, //! horizontal padding, dividers, and fill rows. It is the main primitive for //! stacking small widgets into panels while preserving each child's own render //! logic. use super::colors; use super::{Border, Buffer, Cell, Constraint, Label, Length, Rect, Size, Style, Widget}; /// Default horizontal padding inside a stack border. pub const DEFAULT_PADDING: usize = 1; /// Default divider glyph. pub const DEFAULT_DIVIDER_GLYPH: char = '─'; /// Default divider style. pub const DEFAULT_DIVIDER_STYLE: Style = Style::new(super::Color::Unset); /// Options for [`VStack`]. #[derive(Debug)] pub struct VStackOptions { /// Optional outer border color. border: Option, /// Horizontal padding inside the outer border. padding: usize, } impl Default for VStackOptions { fn default() -> Self { Self { border: None, padding: DEFAULT_PADDING, } } } /// A vertical stack row. #[derive(Debug)] enum Row<'a> { Widget { /// Widget rendered in this row. widget: Box, /// Optional row height policy. height: Option, }, Divider { /// Cell repeated across the divider row. cell: Cell, }, } impl Default for Row<'_> { /// Create the default divider row. fn default() -> Self { Self::Divider { cell: Cell::new(DEFAULT_DIVIDER_GLYPH, DEFAULT_DIVIDER_STYLE), } } } impl Row<'_> { /// Return the row's natural width under the given parent constraint. fn width(&self, c: Constraint) -> usize { match self { Self::Widget { widget, .. } => widget.columns(c), Self::Divider { .. } => c.min.cols, } } /// Return the row's natural height before leftover space is distributed. fn natural_height(&self, c: Constraint) -> usize { match self { Self::Widget { widget, height } => match height { Some(Length::Fixed(rows) | Length::Min(rows)) => *rows, Some(Length::Fill(_)) => 0, None => widget.rows(c), }, Self::Divider { .. } => 1, } } /// Return the height policy used when allocating render rows. fn layout_height(&self, c: Constraint) -> Length { match self { Self::Widget { widget, height } => { height.unwrap_or_else(|| Length::Fixed(widget.rows(c))) } Self::Divider { .. } => Length::Fixed(1), } } } /// Vertical stack of [`Widget`] objects. #[derive(Default, Debug)] pub struct VStack<'a> { rows: Vec>, opts: VStackOptions, } impl<'a> VStack<'a> { /// Add a widget to the stack and return the stack. pub fn child(mut self, child: impl Widget + 'a) -> Self { self.push(child); self } /// Boxes this stack as a [`Widget`]. pub fn boxed(self) -> Box { Box::new(self) } /// Add a widget with an explicit row height policy. pub fn child_with_height(mut self, child: impl Widget + 'a, height: Length) -> Self { self.push_with_height(child, height); self } /// Add a widget that fills remaining vertical space. pub fn fill(self, child: impl Widget + 'a) -> Self { self.child_with_height(child, Length::Fill(1)) } /// Add a blank line to the stack. pub fn blank(self) -> Self { self.child(Label::blank()) } /// Add a horizontal divider. pub fn divider(mut self) -> Self { self.rows.push(Row::default()); self } /// Check if this stack is empty. pub fn is_empty(&self) -> bool { self.rows.is_empty() } /// Add multiple widgets to the stack. pub fn children(mut self, children: I) -> Self where I: IntoIterator>, { self.rows .extend(children.into_iter().map(|widget| Row::Widget { widget, height: None, })); self } /// Merge with another `VStack`. pub fn merge(mut self, other: Self) -> Self { self.rows.extend(other.rows); self } /// Set or unset the outer border. pub fn border(mut self, border: Option) -> Self { self.opts.border = border; self } /// Set the outer border. pub fn bordered(self, border: Border) -> Self { self.border(Some(border)) } /// Set horizontal padding. pub fn padding(mut self, cols: usize) -> Self { self.opts.padding = cols; self } /// Add a horizontal divider with an explicit cell. pub fn divider_cell(mut self, cell: Cell) -> Self { self.rows.push(Row::Divider { cell }); self } /// Add a widget to the stack. pub fn push(&mut self, child: impl Widget + 'a) { self.rows.push(Row::Widget { widget: Box::new(child), height: None, }); } /// Add a widget to the stack with an explicit row height policy. pub fn push_with_height(&mut self, child: impl Widget + 'a, height: Length) { self.rows.push(Row::Widget { widget: Box::new(child), height: Some(height), }); } /// Inner size. #[cfg(test)] fn inner(&self, c: Constraint) -> Size { let mut outer = self.outer(c); if self.opts.border.is_some() { outer.cols = outer.cols.saturating_sub(2); outer.rows = outer.rows.saturating_sub(2); } outer } /// Outer size (includes borders). fn outer(&self, c: Constraint) -> Size { let padding = self.opts.padding * 2; let mut cols = self .rows .iter() .map(|r| r.width(c)) .max() .unwrap_or(0) .saturating_add(padding); let mut rows = self .rows .iter() .map(|r| r.natural_height(c)) .fold(0usize, usize::saturating_add); // Account for outer borders. if self.opts.border.is_some() { cols = cols.saturating_add(2); rows = rows.saturating_add(2); } Size::new(cols, rows).constrain(c) } } impl Widget for VStack<'_> { fn size(&self, parent: Constraint) -> Size { self.outer(parent) } fn render(&mut self, area: Rect, buf: &mut Buffer) { let padding = self.opts.padding; let content = if self.opts.border.is_some() { area.inner(1) } else { area }; let child_cols = content.cols.saturating_sub(padding * 2); let child_constraint = Constraint::tight(child_cols); let child_x = content.x + padding.min(content.cols); let heights = allocate_heights( content.rows, &self .rows .iter() .map(|row| row.layout_height(child_constraint)) .collect::>(), ); let mut y = content.y; if let Some(border) = self.opts.border { border.draw(area, buf); } for (row, rows) in self.rows.iter_mut().zip(heights) { match row { Row::Widget { widget, .. } => { if rows > 0 && y < content.bottom() { let area = Rect::new(child_x, y, child_cols, rows); widget.render(area, buf); } y += rows; } Row::Divider { cell } => { let row_y = y; y += rows; if rows == 0 || row_y >= area.bottom() { continue; } if let Some(border) = self.opts.border { buf.set_char(area.x, row_y, border.chars.divider_left, border.style); buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone()); if area.cols > 1 { buf.set_char( area.right().saturating_sub(1), row_y, border.chars.divider_right, border.style, ); } } else { buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone()); } } } } } } /// Allocates row heights without growing fixed rows when no fill row exists. fn allocate_heights(total: usize, lengths: &[Length]) -> Vec { let base = lengths .iter() .map(|length| match *length { Length::Fixed(rows) | Length::Min(rows) => rows, Length::Fill(_) => 0, }) .sum::(); let fill = lengths .iter() .map(|length| match *length { Length::Fill(weight) => weight.max(1) as usize, _ => 0, }) .sum::(); let remaining = total.saturating_sub(base); let mut used = 0usize; let mut remaining_fill = fill; let mut used_fill = 0usize; lengths .iter() .map(|length| { let rows = match *length { Length::Fixed(rows) | Length::Min(rows) => rows, Length::Fill(weight) if fill > 0 => { let weight = weight.max(1) as usize; let rows = if remaining_fill == weight { remaining.saturating_sub(used_fill) } else { remaining * weight / fill }; remaining_fill = remaining_fill.saturating_sub(weight); used_fill += rows; rows } Length::Fill(_) => 0, } .min(total.saturating_sub(used)); used += rows; rows }) .collect() } /// Simple bordered vstack. pub fn bordered<'a>(child: impl Widget + 'a) -> VStack<'a> { VStack::default() .border(Some(Border::new(colors::FAINT))) .child(child) } #[cfg(test)] mod tests { use super::*; use crate::{Buffer, Color, Line}; #[derive(Debug)] struct Expanding; impl Widget for Expanding { fn size(&self, parent: Constraint) -> Size { parent.max } fn render(&mut self, _area: Rect, _buf: &mut Buffer) {} } #[test] fn test_vstack() { let mut v = VStack::default() .border(Some(Border::new(Color::Unset))) .padding(1); v.push(Line::new("banana")); v.push(Line::new("apple")); v.push(Line::new("abricot")); let constraint = Constraint::default(); let outer = v.outer(constraint); assert_eq!(outer.cols, 11); assert_eq!(outer.rows, 5); let inner = v.inner(constraint); assert_eq!(inner.cols, 9); assert_eq!(inner.rows, 3); assert_eq!( v.display(constraint), r" ╭─────────╮ │ banana │ │ apple │ │ abricot │ ╰─────────╯ " .trim_start() ); } #[test] fn test_vstack_maximize() { let mut v = VStack::default() .border(Some(Border::new(Color::Unset))) .padding(1); v.push(Line::new("banana")); v.push(Line::new("apple")); v.push(Line::new("abricot")); let constraint = Constraint { min: Size::new(14, 0), max: Size::new(14, usize::MAX), }; let outer = v.outer(constraint); assert_eq!(outer.cols, 14); assert_eq!(outer.rows, 5); let inner = v.inner(constraint); assert_eq!(inner.cols, 12); assert_eq!(inner.rows, 3); assert_eq!( v.display(constraint), r" ╭────────────╮ │ banana │ │ apple │ │ abricot │ ╰────────────╯ " .trim_start() ); } #[test] fn empty_vstack_has_padding_width_and_no_rows() { let mut v = VStack::default(); assert!(v.is_empty()); assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(2, 0)); assert_eq!(v.display(Constraint::UNBOUNDED), ""); } #[test] fn unbordered_vstack_renders_widgets_and_plain_divider() { let mut v = VStack::default() .padding(0) .child(Line::new("top")) .divider() .child(Line::new("bottom")); assert!(!v.is_empty()); assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(6, 3)); assert_eq!(v.display(Constraint::UNBOUNDED), "top \n──────\nbottom\n"); } #[test] fn bordered_divider_keeps_border_and_fill_styles_separate() { let mut v = VStack::default() .border(Some(Border::new(Color::Blue))) .padding(0) .child(Line::new("top")) .divider_cell(Cell::new('┄', Style::new(Color::Red))) .child(Line::new("bottom")); let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED))); v.render(buffer.area(), &mut buffer); assert_eq!( buffer.lines(), vec!["╭──────╮", "│top │", "├┄┄┄┄┄┄┤", "│bottom│", "╰──────╯"] ); assert_eq!( buffer.get(0, 2).map(|cell| cell.style().fg_color()), Some(Color::Blue) ); assert_eq!( buffer.get(1, 2).map(|cell| cell.style().fg_color()), Some(Color::Red) ); assert_eq!( buffer.get(7, 2).map(|cell| cell.style().fg_color()), Some(Color::Blue) ); } #[test] fn blank_adds_empty_widget_row() { let mut v = VStack::default() .padding(0) .child(Line::new("top")) .blank() .child(Line::new("bottom")); assert_eq!(v.display(Constraint::UNBOUNDED), "top \n \nbottom\n"); } #[test] fn children_appends_boxed_widgets() { let children = vec![Line::new("one").boxed(), Line::new("two").boxed()]; let mut v = VStack::default().padding(0).children(children); assert_eq!(v.display(Constraint::UNBOUNDED), "one\ntwo\n"); } #[test] fn fill_child_absorbs_remaining_height() { let mut stack = VStack::default() .padding(0) .child(Line::new("top")) .fill(crate::Fill::new('.', crate::Style::default())); let constraint = Constraint::new(Size::new(5, 4), Size::new(5, 4)); assert_eq!(stack.display(constraint), "top \n.....\n.....\n.....\n"); } #[test] fn unbounded_expanding_child_does_not_overflow_natural_width() { let stack = VStack::default() .border(Some(Border::new(Color::Unset))) .fill(Expanding); assert_eq!(stack.size(Constraint::UNBOUNDED), Size::new(usize::MAX, 2)); } #[test] fn merge_preserves_row_order() { let left = VStack::default().padding(0).child(Line::new("left")); let right = VStack::default().padding(0).child(Line::new("right")); assert_eq!( left.merge(right).display(Constraint::UNBOUNDED), "left \nright\n" ); } #[test] fn boxed_vstack_dispatches_widget_methods() { let mut boxed = VStack::default() .padding(0) .child(Line::new("boxed")) .boxed(); assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1)); assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n"); } #[test] fn bordered_helper_wraps_child_with_faint_border() { let mut v = bordered(Line::new("x")).padding(0); let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED))); v.render(buffer.area(), &mut buffer); assert_eq!(buffer.lines(), vec!["╭─╮", "│x│", "╰─╯"]); assert_eq!( buffer.get(0, 0).map(|cell| cell.style().fg_color()), Some(colors::FAINT) ); assert_eq!( buffer.get(0, 1).map(|cell| cell.style().fg_color()), Some(colors::FAINT) ); assert_eq!( buffer.get(2, 2).map(|cell| cell.style().fg_color()), Some(colors::FAINT) ); } }