crates/tui-core/src/hstack.rs 6.5 KiB raw
1
//! Horizontal widget layout container.
2
//!
3
//! `HStack` packs child widgets from left to right at their natural widths.
4
//! Spacer slots absorb leftover columns, making it a small primitive for
5
//! toolbar, header, and status-line composition.
6
7
use super::{Buffer, Constraint, Rect, Size, Widget};
8
9
/// One slot in an [`HStack`]: a fixed-width widget or a flexible spacer.
10
#[derive(Default, Debug)]
11
enum Slot<'a> {
12
    /// Widget rendered at its natural width.
13
    Widget(Box<dyn Widget + 'a>),
14
    /// Flexible spacer that absorbs leftover horizontal space.
15
    #[default]
16
    Spacer,
17
}
18
19
/// Horizontal stack of [`Widget`] objects.
20
///
21
/// Each widget child is laid out at its natural width. Spacer slots
22
/// absorb the leftover horizontal space allowed by the parent constraint,
23
/// allowing space-between layouts without manual padding arithmetic.
24
#[derive(Default, Debug)]
25
pub struct HStack<'a> {
26
    /// Slots in left-to-right rendering order.
27
    slots: Vec<Slot<'a>>,
28
}
29
30
impl<'a> HStack<'a> {
31
    /// Add a widget child to the stack.
32
    pub fn child(mut self, child: impl Widget + 'a) -> Self {
33
        self.push(child);
34
        self
35
    }
36
37
    /// Append a widget child to the stack in place.
38
    pub fn push(&mut self, child: impl Widget + 'a) {
39
        self.slots.push(Slot::Widget(Box::new(child)));
40
    }
41
42
    /// Add a flexible spacer that grows to fill leftover horizontal space.
43
    pub fn spacer(mut self) -> Self {
44
        self.slots.push(Slot::Spacer);
45
        self
46
    }
47
}
48
49
impl Widget for HStack<'_> {
50
    fn size(&self, parent: Constraint) -> Size {
51
        let widths = allocate_widths(&self.slots, parent);
52
        let total = widths.iter().copied().fold(0usize, usize::saturating_add);
53
        let height = self
54
            .slots
55
            .iter()
56
            .zip(&widths)
57
            .map(|(slot, &cols)| match slot {
58
                Slot::Widget(e) => e.rows(Constraint::tight(cols.max(1))),
59
                Slot::Spacer => 0,
60
            })
61
            .max()
62
            .unwrap_or(0);
63
64
        Size::new(total, height)
65
    }
66
67
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
68
        let widths = allocate_widths(&self.slots, Constraint::max(area.size()));
69
        let mut x = area.x;
70
71
        for (slot, width) in self.slots.iter_mut().zip(widths) {
72
            if x >= area.right() {
73
                break;
74
            }
75
            let width = width.min(area.right() - x);
76
            if let Slot::Widget(widget) = slot {
77
                widget.render(Rect::new(x, area.y, width, area.rows), buf);
78
            }
79
            x += width;
80
        }
81
    }
82
}
83
84
/// Allocates a column width to every slot, distributing leftover into spacers.
85
fn allocate_widths(slots: &[Slot<'_>], parent: Constraint) -> Vec<usize> {
86
    let max_cols = parent.max.cols;
87
    let mut widths = Vec::with_capacity(slots.len());
88
    let mut natural_total = 0usize;
89
    let mut spacer_count = 0usize;
90
91
    for slot in slots {
92
        match slot {
93
            Slot::Widget(e) => {
94
                let w = e.columns(Constraint::UNBOUNDED);
95
                widths.push(w);
96
                natural_total = natural_total.saturating_add(w);
97
            }
98
            Slot::Spacer => {
99
                widths.push(0);
100
                spacer_count += 1;
101
            }
102
        }
103
    }
104
105
    if spacer_count == 0 {
106
        return widths;
107
    }
108
    let remaining = if max_cols == usize::MAX {
109
        spacer_count
110
    } else {
111
        max_cols.saturating_sub(natural_total).max(spacer_count)
112
    };
113
    let per = remaining / spacer_count;
114
    let extra = remaining % spacer_count;
115
    let mut k = 0;
116
    for (i, slot) in slots.iter().enumerate() {
117
        if matches!(slot, Slot::Spacer) {
118
            widths[i] = per + usize::from(k < extra);
119
            k += 1;
120
        }
121
    }
122
    widths
123
}
124
125
#[cfg(test)]
126
mod tests {
127
    use super::*;
128
    use crate::Line;
129
130
    #[derive(Debug)]
131
    struct Expanding;
132
133
    impl Widget for Expanding {
134
        fn size(&self, parent: Constraint) -> Size {
135
            parent.max
136
        }
137
138
        fn render(&mut self, _area: Rect, _buf: &mut Buffer) {}
139
    }
140
141
    #[test]
142
    fn empty_stack_uses_no_space() {
143
        let mut stack = HStack::default();
144
145
        assert_eq!(stack.size(Constraint::tight(8)), Size::new(0, 0));
146
        assert!(stack.display(Constraint::tight(8)).is_empty());
147
    }
148
149
    #[test]
150
    fn natural_widths_sum_for_widget_children() {
151
        let mut stack = HStack::default()
152
            .child(Line::new("abcdef"))
153
            .child(Line::new("ghij"));
154
155
        assert_eq!(stack.size(Constraint::tight(80)), Size::new(10, 1));
156
        assert_eq!(
157
            stack.display(Constraint::tight(80)),
158
            "abcdefghij\n",
159
            "widgets pack at their natural widths"
160
        );
161
    }
162
163
    #[test]
164
    fn unbounded_expanding_children_do_not_overflow_natural_width() {
165
        let stack = HStack::default().child(Expanding).child(Expanding);
166
167
        assert_eq!(
168
            stack.size(Constraint::UNBOUNDED),
169
            Size::new(usize::MAX, usize::MAX)
170
        );
171
    }
172
173
    #[test]
174
    fn spacer_absorbs_leftover_horizontal_space() {
175
        let mut stack = HStack::default()
176
            .child(Line::new("L"))
177
            .spacer()
178
            .child(Line::new("R"));
179
180
        assert_eq!(stack.display(Constraint::tight(6)), "L    R\n");
181
    }
182
183
    #[test]
184
    fn multiple_spacers_split_remainder_evenly() {
185
        let mut stack = HStack::default()
186
            .child(Line::new("a"))
187
            .spacer()
188
            .child(Line::new("b"))
189
            .spacer()
190
            .child(Line::new("c"));
191
192
        assert_eq!(stack.display(Constraint::tight(7)), "a  b  c\n");
193
    }
194
195
    #[test]
196
    fn spacer_falls_back_to_one_column_when_unbounded() {
197
        let mut stack = HStack::default()
198
            .child(Line::new("L"))
199
            .spacer()
200
            .child(Line::new("R"));
201
202
        assert_eq!(stack.display(Constraint::UNBOUNDED), "L R\n");
203
    }
204
205
    #[test]
206
    fn column_rows_pad_to_column_width_when_neighbors_have_more_lines() {
207
        let mut stack = HStack::default()
208
            .child(vec![Line::new("aa"), Line::new("bb")])
209
            .child(Line::new("cc"));
210
211
        assert_eq!(stack.display(Constraint::tight(10)), "aacc\nbb  \n");
212
    }
213
214
    #[test]
215
    fn lines_zip_columns_for_multi_row_children() {
216
        let mut stack = HStack::default()
217
            .child(vec![Line::new("aa"), Line::new("bb")])
218
            .child(Line::new("cc"));
219
220
        let lines = stack
221
            .lines(Constraint::tight(10))
222
            .into_iter()
223
            .map(|line| line.to_string())
224
            .collect::<Vec<_>>();
225
226
        assert_eq!(lines, vec!["aacc", "bb  "]);
227
    }
228
}