//! Horizontal widget layout container. //! //! `HStack` packs child widgets from left to right at their natural widths. //! Spacer slots absorb leftover columns, making it a small primitive for //! toolbar, header, and status-line composition. use super::{Buffer, Constraint, Rect, Size, Widget}; /// One slot in an [`HStack`]: a fixed-width widget or a flexible spacer. #[derive(Default, Debug)] enum Slot<'a> { /// Widget rendered at its natural width. Widget(Box), /// Flexible spacer that absorbs leftover horizontal space. #[default] Spacer, } /// Horizontal stack of [`Widget`] objects. /// /// Each widget child is laid out at its natural width. Spacer slots /// absorb the leftover horizontal space allowed by the parent constraint, /// allowing space-between layouts without manual padding arithmetic. #[derive(Default, Debug)] pub struct HStack<'a> { /// Slots in left-to-right rendering order. slots: Vec>, } impl<'a> HStack<'a> { /// Add a widget child to the stack. pub fn child(mut self, child: impl Widget + 'a) -> Self { self.push(child); self } /// Append a widget child to the stack in place. pub fn push(&mut self, child: impl Widget + 'a) { self.slots.push(Slot::Widget(Box::new(child))); } /// Add a flexible spacer that grows to fill leftover horizontal space. pub fn spacer(mut self) -> Self { self.slots.push(Slot::Spacer); self } } impl Widget for HStack<'_> { fn size(&self, parent: Constraint) -> Size { let widths = allocate_widths(&self.slots, parent); let total = widths.iter().copied().fold(0usize, usize::saturating_add); let height = self .slots .iter() .zip(&widths) .map(|(slot, &cols)| match slot { Slot::Widget(e) => e.rows(Constraint::tight(cols.max(1))), Slot::Spacer => 0, }) .max() .unwrap_or(0); Size::new(total, height) } fn render(&mut self, area: Rect, buf: &mut Buffer) { let widths = allocate_widths(&self.slots, Constraint::max(area.size())); let mut x = area.x; for (slot, width) in self.slots.iter_mut().zip(widths) { if x >= area.right() { break; } let width = width.min(area.right() - x); if let Slot::Widget(widget) = slot { widget.render(Rect::new(x, area.y, width, area.rows), buf); } x += width; } } } /// Allocates a column width to every slot, distributing leftover into spacers. fn allocate_widths(slots: &[Slot<'_>], parent: Constraint) -> Vec { let max_cols = parent.max.cols; let mut widths = Vec::with_capacity(slots.len()); let mut natural_total = 0usize; let mut spacer_count = 0usize; for slot in slots { match slot { Slot::Widget(e) => { let w = e.columns(Constraint::UNBOUNDED); widths.push(w); natural_total = natural_total.saturating_add(w); } Slot::Spacer => { widths.push(0); spacer_count += 1; } } } if spacer_count == 0 { return widths; } let remaining = if max_cols == usize::MAX { spacer_count } else { max_cols.saturating_sub(natural_total).max(spacer_count) }; let per = remaining / spacer_count; let extra = remaining % spacer_count; let mut k = 0; for (i, slot) in slots.iter().enumerate() { if matches!(slot, Slot::Spacer) { widths[i] = per + usize::from(k < extra); k += 1; } } widths } #[cfg(test)] mod tests { use super::*; use crate::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 empty_stack_uses_no_space() { let mut stack = HStack::default(); assert_eq!(stack.size(Constraint::tight(8)), Size::new(0, 0)); assert!(stack.display(Constraint::tight(8)).is_empty()); } #[test] fn natural_widths_sum_for_widget_children() { let mut stack = HStack::default() .child(Line::new("abcdef")) .child(Line::new("ghij")); assert_eq!(stack.size(Constraint::tight(80)), Size::new(10, 1)); assert_eq!( stack.display(Constraint::tight(80)), "abcdefghij\n", "widgets pack at their natural widths" ); } #[test] fn unbounded_expanding_children_do_not_overflow_natural_width() { let stack = HStack::default().child(Expanding).child(Expanding); assert_eq!( stack.size(Constraint::UNBOUNDED), Size::new(usize::MAX, usize::MAX) ); } #[test] fn spacer_absorbs_leftover_horizontal_space() { let mut stack = HStack::default() .child(Line::new("L")) .spacer() .child(Line::new("R")); assert_eq!(stack.display(Constraint::tight(6)), "L R\n"); } #[test] fn multiple_spacers_split_remainder_evenly() { let mut stack = HStack::default() .child(Line::new("a")) .spacer() .child(Line::new("b")) .spacer() .child(Line::new("c")); assert_eq!(stack.display(Constraint::tight(7)), "a b c\n"); } #[test] fn spacer_falls_back_to_one_column_when_unbounded() { let mut stack = HStack::default() .child(Line::new("L")) .spacer() .child(Line::new("R")); assert_eq!(stack.display(Constraint::UNBOUNDED), "L R\n"); } #[test] fn column_rows_pad_to_column_width_when_neighbors_have_more_lines() { let mut stack = HStack::default() .child(vec![Line::new("aa"), Line::new("bb")]) .child(Line::new("cc")); assert_eq!(stack.display(Constraint::tight(10)), "aacc\nbb \n"); } #[test] fn lines_zip_columns_for_multi_row_children() { let mut stack = HStack::default() .child(vec![Line::new("aa"), Line::new("bb")]) .child(Line::new("cc")); let lines = stack .lines(Constraint::tight(10)) .into_iter() .map(|line| line.to_string()) .collect::>(); assert_eq!(lines, vec!["aacc", "bb "]); } }