Skip to main content

tui/components/
panel.rs

1use crate::{Color, FitOptions, Frame, Line, Style, ViewContext};
2use unicode_width::UnicodeWidthStr;
3
4/// Width consumed by left ("│ ") and right (" │") borders.
5pub const BORDER_H_PAD: u16 = 4;
6
7/// A bordered panel for wrapping content blocks with title/footer chrome.
8///
9/// For borderless stacking with cursor tracking, use [`Frame::vstack`](crate::Frame::vstack).
10///
11/// # Example
12///
13/// ```
14/// use tui::{Panel, Line, ViewContext};
15///
16/// let mut panel = Panel::new(tui::Color::Grey)
17///     .title(" Settings ")
18///     .footer("[Enter] Save [Esc] Cancel")
19///     .gap(1);
20///
21/// panel.push(vec![Line::new("Name: Example")]);
22/// panel.push(vec![Line::new("Value: 42")]);
23///
24/// let ctx = ViewContext::new((40, 20));
25/// let frame = panel.render(&ctx);
26/// ```
27pub struct Panel {
28    blocks: Vec<Vec<Line>>,
29    title: Option<String>,
30    footer: Option<String>,
31    border_color: Color,
32    fill_height: Option<usize>,
33    gap: usize,
34}
35
36impl Panel {
37    pub fn new(border_color: Color) -> Self {
38        Self { blocks: Vec::new(), title: None, footer: None, border_color, fill_height: None, gap: 0 }
39    }
40
41    pub fn title(mut self, title: impl Into<String>) -> Self {
42        self.title = Some(title.into());
43        self
44    }
45
46    pub fn footer(mut self, footer: impl Into<String>) -> Self {
47        self.footer = Some(footer.into());
48        self
49    }
50
51    pub fn fill_height(mut self, h: usize) -> Self {
52        self.fill_height = Some(h);
53        self
54    }
55
56    pub fn gap(mut self, lines: usize) -> Self {
57        self.gap = lines;
58        self
59    }
60
61    pub fn push(&mut self, block: Vec<Line>) {
62        self.blocks.push(block);
63    }
64
65    /// Inner content width when borders are active.
66    pub fn inner_width(total_width: u16) -> u16 {
67        total_width.saturating_sub(BORDER_H_PAD)
68    }
69
70    /// Render blocks with borders/chrome.
71    pub fn render(&self, context: &ViewContext) -> Frame {
72        let width = context.size.width as usize;
73        let inner_width = width.saturating_sub(BORDER_H_PAD as usize);
74        let inner_width_u16 = u16::try_from(inner_width).unwrap_or(u16::MAX);
75        let border_style = Style::fg(self.border_color);
76        let border_left = Line::new("│ ".to_string());
77        let border_right = Line::new(" │".to_string());
78
79        let blank_border = || Frame::new(vec![empty_border_line(inner_width)]);
80
81        let title_text = self.title.as_deref().unwrap_or("");
82        let bar_left = "┌─";
83        let bar_right_pad =
84            width.saturating_sub(UnicodeWidthStr::width(bar_left) + UnicodeWidthStr::width(title_text) + 1); // 1 for ┐
85        let title_line = format!("{bar_left}{title_text}{:─>bar_right_pad$}┐", "", bar_right_pad = bar_right_pad);
86        let top_frame = Frame::new(vec![Line::with_style(title_line, border_style)]);
87
88        let mut body_frames: Vec<Frame> = vec![blank_border()];
89        for (i, block) in self.blocks.iter().enumerate() {
90            if i > 0 {
91                for _ in 0..self.gap {
92                    body_frames.push(blank_border());
93                }
94            }
95            body_frames.push(Frame::new(block.clone()).fit(inner_width_u16, FitOptions::wrap().with_fill()).wrap_each(
96                inner_width_u16,
97                &border_left,
98                &border_right,
99            ));
100        }
101        let mut body_frame = Frame::vstack(body_frames);
102
103        if let Some(target_height) = self.fill_height {
104            // Reserve space for top border (1) + footer (0/1) + bottom border (1).
105            let chrome_rows = if self.footer.is_some() { 3 } else { 2 };
106            let target_body = target_height.saturating_sub(chrome_rows);
107            let current = body_frame.lines().len();
108            if current < target_body {
109                let pad: Vec<Frame> = (0..(target_body - current)).map(|_| blank_border()).collect();
110                body_frame = Frame::vstack(std::iter::once(body_frame).chain(pad));
111            }
112        }
113
114        let mut chrome: Vec<Frame> = Vec::with_capacity(2);
115        if let Some(ref footer_text) = self.footer {
116            let footer_pad = inner_width.saturating_sub(UnicodeWidthStr::width(footer_text.as_str()));
117            let footer_line_str = format!("│ {footer_text}{:footer_pad$} │", "", footer_pad = footer_pad);
118            chrome.push(Frame::new(vec![Line::with_style(footer_line_str, border_style)]));
119        }
120        let bottom_inner = width.saturating_sub(2); // └ and ┘
121        let bottom_line = format!("└{:─>bottom_inner$}┘", "", bottom_inner = bottom_inner);
122        chrome.push(Frame::new(vec![Line::with_style(bottom_line, border_style)]));
123
124        let result = Frame::vstack(std::iter::once(top_frame).chain(std::iter::once(body_frame)).chain(chrome));
125
126        if let Some(target_height) = self.fill_height {
127            result.truncate_height(u16::try_from(target_height).unwrap_or(u16::MAX))
128        } else {
129            result
130        }
131    }
132}
133
134fn empty_border_line(inner_width: usize) -> Line {
135    Line::new(format!("│ {:inner_width$} │", "", inner_width = inner_width))
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn title_renders_top_border_with_title_text() {
144        let mut container = Panel::new(Color::Grey).title(" Config ");
145        container.push(vec![Line::new("x")]);
146        let context = ViewContext::new((30, 10));
147        let lines = container.render(&context).into_lines();
148        let top = lines[0].plain_text();
149        assert!(top.starts_with("┌─ Config "), "top: {top}");
150        assert!(top.ends_with('┐'), "top: {top}");
151    }
152
153    #[test]
154    fn footer_renders_footer_and_bottom_border() {
155        let mut container = Panel::new(Color::Grey).footer("[Esc] Close");
156        container.push(vec![Line::new("x")]);
157        let context = ViewContext::new((30, 10));
158        let lines = container.render(&context).into_lines();
159        let last = lines.last().unwrap().plain_text();
160        assert!(last.starts_with('└'), "last: {last}");
161        assert!(last.ends_with('┘'), "last: {last}");
162        let footer = lines[lines.len() - 2].plain_text();
163        assert!(footer.contains("[Esc] Close"), "footer: {footer}");
164    }
165
166    #[test]
167    fn fill_height_pads_with_empty_bordered_rows() {
168        let mut container = Panel::new(Color::Grey).title(" T ").footer("F").fill_height(10);
169        container.push(vec![Line::new("x")]);
170        let context = ViewContext::new((30, 10));
171        let lines = container.render(&context).into_lines();
172        assert_eq!(lines.len(), 10, "should fill to exactly 10 lines");
173    }
174
175    #[test]
176    fn border_color_styles_border_lines() {
177        let mut container = Panel::new(Color::Cyan).title(" T ");
178        container.push(vec![Line::new("x")]);
179        let context = ViewContext::new((30, 10));
180        let lines = container.render(&context).into_lines();
181        // Top border should have Cyan fg
182        let top_span = &lines[0].spans()[0];
183        assert_eq!(top_span.style().fg, Some(Color::Cyan));
184        // Bottom border should have Cyan fg
185        let bottom_span = &lines.last().unwrap().spans()[0];
186        assert_eq!(bottom_span.style().fg, Some(Color::Cyan));
187    }
188
189    #[test]
190    fn bg_color_extends_through_padding() {
191        let bg = Color::DarkBlue;
192        let mut container = Panel::new(Color::Grey);
193        container.push(vec![Line::with_style("hi", Style::default().bg_color(bg))]);
194        let context = ViewContext::new((20, 10));
195        let lines = container.render(&context).into_lines();
196        // Content row (top border + blank + first content = index 2)
197        let content_row = &lines[2];
198        let bg_span =
199            content_row.spans().iter().find(|s| s.style().bg == Some(bg)).expect("should have a span with bg color");
200        assert!(bg_span.text().len() > 2, "bg span should extend through padding, got: {:?}", bg_span.text());
201    }
202
203    #[test]
204    fn bordered_gap_inserts_empty_bordered_lines_between_children() {
205        let mut container = Panel::new(Color::Grey).gap(1);
206        container.push(vec![Line::new("a")]);
207        container.push(vec![Line::new("b")]);
208        let context = ViewContext::new((20, 10));
209        let lines = container.render(&context).into_lines();
210        // top border + blank + "a" + gap_blank + "b" + bottom border = 6
211        assert_eq!(lines.len(), 6);
212        let gap_line = lines[3].plain_text();
213        assert!(gap_line.starts_with('│'), "gap: {gap_line}");
214        assert!(gap_line.ends_with('│'), "gap: {gap_line}");
215    }
216
217    #[test]
218    fn overlong_content_wraps_inside_borders() {
219        let mut container = Panel::new(Color::Grey);
220        container.push(vec![Line::new("abcdefghijklmnop")]);
221        // total width 14 → inner width 10 (14 − BORDER_H_PAD)
222        let context = ViewContext::new((14, 10));
223        let lines = container.render(&context).into_lines();
224
225        // top border + blank + 2 wrapped content rows + bottom border = 5
226        assert_eq!(lines.len(), 5);
227        assert_eq!(lines[2].plain_text(), "│ abcdefghij │");
228        assert_eq!(lines[3].plain_text(), "│ klmnop     │");
229    }
230
231    #[test]
232    fn top_and_bottom_border_have_equal_visual_width() {
233        let mut container = Panel::new(Color::Grey).title(" Config ");
234        container.push(vec![Line::new("x")]);
235        let context = ViewContext::new((40, 10));
236        let lines = container.render(&context).into_lines();
237        let top = lines.first().unwrap().plain_text();
238        let bottom = lines.last().unwrap().plain_text();
239        assert_eq!(
240            UnicodeWidthStr::width(top.as_str()),
241            UnicodeWidthStr::width(bottom.as_str()),
242            "top ({top}) and bottom ({bottom}) border should have equal visual width"
243        );
244    }
245}