Skip to main content

vtcode_ui/design/
panel.rs

1//! Base panel widget primitive.
2//!
3//! `Panel` renders standardized chrome (borders, titles) and returns the inner
4//! area for child widgets. It is decoupled from any specific session or styling
5//! type via the [`PanelStyleProvider`] trait.
6
7use ratatui::{
8    buffer::Buffer,
9    layout::Rect,
10    style::{Modifier, Style},
11    symbols::border,
12    widgets::{Block, Widget},
13};
14
15use crate::design::layout::LayoutMode;
16use vtcode_commons::terminal_capabilities::BoxGlyphTier;
17
18/// Chrome for terminals that cannot render Unicode box drawing.
19///
20/// Ratatui's `BorderType::Plain` still draws `┌─┐│└┘`, so the ASCII rung of the
21/// capability ladder needs its own set: the point of detecting a non-Unicode
22/// terminal is to avoid mojibake, not to pick a different Unicode style.
23pub(crate) const ASCII_BORDER_SET: border::Set<'static> = border::Set {
24    top_left: "+",
25    top_right: "+",
26    bottom_left: "+",
27    bottom_right: "+",
28    vertical_left: "|",
29    vertical_right: "|",
30    horizontal_top: "-",
31    horizontal_bottom: "-",
32};
33
34/// Panel chrome for a capability tier.
35pub(crate) fn border_set_for_tier(tier: BoxGlyphTier) -> border::Set<'static> {
36    match tier {
37        BoxGlyphTier::RichUnicode => ratatui::widgets::BorderType::HeavyDoubleDashed.to_border_set(),
38        BoxGlyphTier::Unicode => ratatui::widgets::BorderType::Rounded.to_border_set(),
39        BoxGlyphTier::Ascii => ASCII_BORDER_SET,
40    }
41}
42
43/// The canonical panel chrome for this terminal.
44///
45/// Reads the capability verdict once per process, so a bordered panel costs no
46/// per-frame environment probing.
47pub(crate) fn canonical_border_set() -> border::Set<'static> {
48    border_set_for_tier(vtcode_commons::terminal_capabilities::box_glyph_tier())
49}
50
51/// Degrade a preferred set to ASCII when the terminal cannot render Unicode.
52///
53/// Chrome that keeps a fixed Unicode style calls this instead of hard-coding a
54/// border set, so no surface draws mojibake on a non-Unicode terminal.
55pub(crate) fn border_set_with_fallback(preferred: border::Set<'static>) -> border::Set<'static> {
56    match vtcode_commons::terminal_capabilities::box_glyph_tier() {
57        BoxGlyphTier::Ascii => ASCII_BORDER_SET,
58        _ => preferred,
59    }
60}
61
62/// Trait for providing panel styles. Decouples `Panel` from any specific
63/// session or theme type.
64///
65/// Implementors provide the three core styles needed to render a panel:
66/// - `default_style`: the base style for the panel background
67/// - `accent_style`: the style for active/focused borders
68/// - `border_style`: the style for inactive borders
69pub trait PanelStyleProvider {
70    /// Base style for the panel background.
71    fn default_style(&self) -> Style;
72
73    /// Style for active/focused borders and titles.
74    fn accent_style(&self) -> Style;
75
76    /// Style for inactive borders.
77    fn border_style(&self) -> Style;
78}
79
80/// A consistent panel wrapper that applies standardized chrome (borders, titles).
81///
82/// This widget ensures visual consistency across all panels in the UI by
83/// providing a unified border and title style based on the active theme.
84///
85/// # Example
86/// ```ignore
87/// let inner = Panel::new(&styles)
88///     .title("Transcript")
89///     .active(true)
90///     .mode(layout_mode)
91///     .border_set(border::ROUNDED)
92///     .render_and_get_inner(area, buf);
93/// // Render child widget into `inner`
94/// ```
95pub(crate) struct Panel<'a, S: PanelStyleProvider> {
96    styles: &'a S,
97    title: Option<&'a str>,
98    active: bool,
99    mode: LayoutMode,
100    border_set: Option<border::Set<'static>>,
101}
102
103impl<'a, S: PanelStyleProvider> Panel<'a, S> {
104    /// Create a new panel with required style reference.
105    pub(crate) fn new(styles: &'a S) -> Self {
106        Self {
107            styles,
108            title: None,
109            active: false,
110            mode: LayoutMode::Standard,
111            border_set: None,
112        }
113    }
114
115    /// Set the panel title (displayed in the border).
116    #[must_use]
117    pub(crate) fn title(mut self, title: &'a str) -> Self {
118        self.title = Some(title);
119        self
120    }
121
122    /// Mark the panel as active (highlighted border).
123    #[must_use]
124    pub(crate) fn active(mut self, active: bool) -> Self {
125        self.active = active;
126        self
127    }
128
129    /// Set the layout mode (affects border visibility).
130    #[must_use]
131    pub(crate) fn mode(mut self, mode: LayoutMode) -> Self {
132        self.mode = mode;
133        self
134    }
135
136    /// Override the border set.
137    #[must_use]
138    pub(crate) fn border_set(mut self, border_set: border::Set<'static>) -> Self {
139        self.border_set = Some(border_set);
140        self
141    }
142
143    /// Render the panel and return the inner area for child widgets.
144    pub(crate) fn render_and_get_inner(self, area: Rect, buf: &mut Buffer) -> Rect {
145        if area.is_empty() {
146            return area;
147        }
148        if !self.mode.show_borders() {
149            return area;
150        }
151
152        let border_style = if self.active {
153            self.styles.accent_style()
154        } else {
155            self.styles.border_style()
156        };
157
158        let border_set = self.border_set.unwrap_or(border::PLAIN);
159
160        let mut block = Block::bordered()
161            .border_set(border_set)
162            .style(self.styles.default_style())
163            .border_style(border_style);
164
165        if self.mode.show_titles()
166            && let Some(title) = self.title
167        {
168            let title_style = if self.active {
169                self.styles.accent_style().add_modifier(Modifier::BOLD)
170            } else {
171                self.styles.default_style().add_modifier(Modifier::BOLD)
172            };
173            block = block.title(title).title_style(title_style);
174        }
175
176        let inner = block.inner(area);
177        block.render(area, buf);
178        inner
179    }
180}
181
182/// Extended style methods for panels and visual hierarchy.
183pub trait PanelStyles {
184    /// Style for muted/secondary content.
185    fn muted_style(&self) -> Style;
186
187    /// Style for panel titles.
188    fn title_style(&self) -> Style;
189
190    /// Style for active/focused borders.
191    fn border_active_style(&self) -> Style;
192
193    /// Style for dividers between sections.
194    fn divider_style(&self) -> Style;
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    struct MockStyles {
202        default: Style,
203        accent: Style,
204        border: Style,
205    }
206
207    impl MockStyles {
208        fn new() -> Self {
209            Self {
210                default: Style::default(),
211                accent: Style::default().fg(ratatui::style::Color::Cyan),
212                border: Style::default().fg(ratatui::style::Color::Gray),
213            }
214        }
215    }
216
217    impl PanelStyleProvider for MockStyles {
218        fn default_style(&self) -> Style {
219            self.default
220        }
221        fn accent_style(&self) -> Style {
222            self.accent
223        }
224        fn border_style(&self) -> Style {
225            self.border
226        }
227    }
228
229    #[test]
230    fn zero_area_returns_unchanged_without_painting() {
231        let styles = MockStyles::new();
232        let area = Rect::new(5, 5, 0, 0);
233        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
234        let before = buf.clone();
235        let inner = Panel::new(&styles)
236            .mode(LayoutMode::Standard)
237            .render_and_get_inner(area, &mut buf);
238        assert_eq!(inner, area);
239        assert_eq!(buf, before, "zero-area panel must not touch the buffer");
240    }
241
242    #[test]
243    fn compact_mode_returns_full_area() {
244        let styles = MockStyles::new();
245        let area = Rect::new(0, 0, 40, 10);
246        let mut buf = Buffer::empty(area);
247        let inner = Panel::new(&styles)
248            .mode(LayoutMode::Compact)
249            .render_and_get_inner(area, &mut buf);
250        assert_eq!(inner, area);
251    }
252
253    #[test]
254    fn standard_mode_returns_smaller_inner_area() {
255        let styles = MockStyles::new();
256        let area = Rect::new(0, 0, 80, 24);
257        let mut buf = Buffer::empty(area);
258        let inner = Panel::new(&styles)
259            .mode(LayoutMode::Standard)
260            .render_and_get_inner(area, &mut buf);
261        // Borders reduce inner area by 1 on each side
262        assert_eq!(inner.x, area.x + 1);
263        assert_eq!(inner.y, area.y + 1);
264        assert_eq!(inner.width, area.width - 2);
265        assert_eq!(inner.height, area.height - 2);
266    }
267
268    #[test]
269    fn wide_mode_with_title() {
270        let styles = MockStyles::new();
271        let area = Rect::new(0, 0, 120, 30);
272        let mut buf = Buffer::empty(area);
273        let inner = Panel::new(&styles)
274            .title("Test Panel")
275            .active(true)
276            .mode(LayoutMode::Wide)
277            .render_and_get_inner(area, &mut buf);
278        assert_eq!(inner.x, area.x + 1);
279        assert_eq!(inner.y, area.y + 1);
280        assert_eq!(inner.width, area.width - 2);
281        assert_eq!(inner.height, area.height - 2);
282    }
283
284    #[test]
285    fn ascii_tier_renders_ascii_chrome_end_to_end() {
286        // The tier constant is not the contract; the painted buffer is.
287        let styles = MockStyles::new();
288        let area = Rect::new(0, 0, 12, 4);
289        let mut buf = Buffer::empty(area);
290
291        let inner = Panel::new(&styles)
292            .mode(LayoutMode::Standard)
293            .border_set(border_set_for_tier(BoxGlyphTier::Ascii))
294            .render_and_get_inner(area, &mut buf);
295
296        let rendered: String = (0..area.height)
297            .flat_map(|y| (0..area.width).map(move |x| (x, y)))
298            .map(|(x, y)| buf[(x, y)].symbol().to_string())
299            .collect();
300        assert!(rendered.is_ascii(), "the ASCII tier must paint only ASCII chrome, got: {rendered:?}");
301        assert_eq!(buf[(0, 0)].symbol(), "+", "top-left corner should be an ASCII plus");
302        assert_eq!(buf[(0, 1)].symbol(), "|", "left edge should be an ASCII pipe");
303        assert_eq!(inner, Rect::new(1, 1, 10, 2), "inner area must still be the bordered box");
304    }
305
306    #[test]
307    fn active_panel_uses_accent_style() {
308        let styles = MockStyles::new();
309        let area = Rect::new(0, 0, 80, 24);
310        let mut buf = Buffer::empty(area);
311        // Should not panic and should render with accent style
312        Panel::new(&styles)
313            .active(true)
314            .mode(LayoutMode::Standard)
315            .render_and_get_inner(area, &mut buf);
316    }
317}