Skip to main content

rustik_tui_core/
widget.rs

1//! Core widget trait and generic widget wrappers.
2//!
3//! [`Widget`] is the object-safe rendering contract used throughout the crate.
4//! This module also provides simple wrappers such as `Clear`, `Fill`, and
5//! `Block` that are broadly useful and do not belong to a more specific
6//! layout or text module.
7
8use std::fmt;
9use std::fmt::Write as _;
10use std::ops::{Deref, DerefMut};
11
12use crate::layout::Rect;
13use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Size, Style};
14
15/// Something that can render into a [`Buffer`].
16pub trait Widget: fmt::Debug + Send {
17    /// Returns the widget size under a parent constraint.
18    fn size(&self, parent: Constraint) -> Size;
19
20    /// Renders the widget into an area.
21    fn render(&mut self, area: Rect, buf: &mut Buffer);
22
23    /// Returns the number of columns occupied by this widget.
24    fn columns(&self, parent: Constraint) -> usize {
25        self.size(parent).cols
26    }
27
28    /// Returns the number of rows occupied by this widget.
29    fn rows(&self, parent: Constraint) -> usize {
30        self.size(parent).rows
31    }
32
33    /// Renders this widget into a fresh buffer sized from the given constraints.
34    fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
35        let size = self.size(constraints);
36        let area = Rect::from_size(size);
37        let mut buffer = Buffer::empty(area);
38
39        self.render(area, &mut buffer);
40
41        buffer
42    }
43
44    /// Returns this widget rendered as styled lines, one per row.
45    ///
46    /// The default implementation renders into a private buffer and reads each
47    /// row back as a styled [`Line`].
48    fn lines(&mut self, constraints: Constraint) -> Vec<Line> {
49        let buffer = self.to_buffer(constraints);
50        let rows = buffer.area().rows;
51
52        (0..rows).map(|row| buffer.styled_line(row)).collect()
53    }
54
55    /// Returns the first rendered row of this widget, or a blank line.
56    ///
57    /// Convenience for callers that compose single-row widgets and want a
58    /// `Line` rather than a one-element `Vec<Line>`.
59    fn to_line(&mut self, constraints: Constraint) -> Line {
60        self.lines(constraints)
61            .into_iter()
62            .next()
63            .unwrap_or_default()
64    }
65
66    /// Returns a plain string representation of this widget.
67    #[must_use]
68    fn display(&mut self, constraints: Constraint) -> String {
69        let buffer = self.to_buffer(constraints);
70        let mut out = String::new();
71
72        for line in buffer.lines() {
73            out.push_str(&line);
74            out.push('\n');
75        }
76        out
77    }
78
79    /// Returns a string representation with terminal styling escapes.
80    #[must_use]
81    fn display_styled(&mut self, constraints: Constraint) -> String {
82        let buffer = self.to_buffer(constraints);
83        let area = buffer.area();
84        let mut out = String::new();
85
86        for y in area.y..area.bottom() {
87            for x in area.x..area.right() {
88                let Some(cell) = buffer.get(x, y) else {
89                    continue;
90                };
91                if !cell.is_continuation() {
92                    let _ = write!(out, "{}", cell.paint().styled());
93                }
94            }
95            out.push('\n');
96        }
97        out
98    }
99}
100
101impl Widget for Box<dyn Widget + '_> {
102    fn size(&self, parent: Constraint) -> Size {
103        self.deref().size(parent)
104    }
105
106    fn render(&mut self, area: Rect, buf: &mut Buffer) {
107        self.deref_mut().render(area, buf);
108    }
109}
110
111impl<T: Widget + ?Sized> Widget for &mut T {
112    fn size(&self, parent: Constraint) -> Size {
113        (**self).size(parent)
114    }
115
116    fn render(&mut self, area: Rect, buf: &mut Buffer) {
117        (**self).render(area, buf);
118    }
119}
120
121/// Clears an area.
122#[derive(Debug, Clone, Copy, Default)]
123pub struct Clear;
124
125impl Widget for Clear {
126    fn size(&self, parent: Constraint) -> Size {
127        parent.bounded_size()
128    }
129
130    fn render(&mut self, area: Rect, buf: &mut Buffer) {
131        buf.fill(area, crate::buffer::Cell::blank());
132    }
133}
134
135/// Fills an area with one glyph and style.
136#[derive(Debug, Clone)]
137pub struct Fill {
138    /// Fill cell.
139    cell: Cell,
140}
141
142impl Fill {
143    /// Creates a fill widget from one character and style.
144    pub fn new(ch: char, style: Style) -> Self {
145        Self {
146            cell: Cell::new(ch, style),
147        }
148    }
149
150    /// Creates a fill widget from a cell.
151    pub fn cell(cell: Cell) -> Self {
152        Self { cell }
153    }
154}
155
156impl Widget for Fill {
157    fn size(&self, parent: Constraint) -> Size {
158        parent.bounded_size()
159    }
160
161    fn render(&mut self, area: Rect, buf: &mut Buffer) {
162        buf.fill(area, self.cell.clone());
163    }
164}
165
166/// Bordered widget wrapper.
167#[derive(Debug, Clone)]
168pub struct Block<W> {
169    child: W,
170    border: Option<Border>,
171    title: Option<Line>,
172}
173
174impl<W> Block<W> {
175    /// Creates a block around a child.
176    pub fn new(child: W) -> Self {
177        Self {
178            child,
179            border: None,
180            title: None,
181        }
182    }
183
184    /// Sets the border color.
185    pub fn border(mut self, color: Color) -> Self {
186        self.border = Some(Border::new(color));
187        self
188    }
189
190    /// Sets the border style.
191    pub fn border_style(mut self, border: Border) -> Self {
192        self.border = Some(border);
193        self
194    }
195
196    /// Sets the title.
197    pub fn title(mut self, title: impl Into<Line>) -> Self {
198        self.title = Some(title.into());
199        self
200    }
201}
202
203impl<W: Widget> Widget for Block<W> {
204    fn size(&self, parent: Constraint) -> Size {
205        let mut size = self.child.size(parent);
206        if self.border.is_some() {
207            size.cols = size.cols.saturating_add(2);
208            size.rows = size.rows.saturating_add(2);
209        }
210        size.constrain(parent)
211    }
212
213    fn render(&mut self, area: Rect, buf: &mut Buffer) {
214        if area.is_empty() {
215            return;
216        }
217        let Some(border) = self.border else {
218            self.child.render(area, buf);
219            return;
220        };
221        border.draw(area, buf);
222
223        if let Some(title) = self.title.clone()
224            && area.cols > 4
225        {
226            let title = title.truncated(area.cols.saturating_sub(4), "…");
227            buf.set_line(area.x + 2, area.y, &title);
228        }
229        self.child.render(area.inner(1), buf);
230    }
231}
232
233impl From<Paint<String>> for Fill {
234    fn from(paint: Paint<String>) -> Self {
235        Self::cell(Cell::from_glyph(paint.content(), paint.style()))
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use crate::{Constraint, Label};
243
244    #[test]
245    fn line_widgets_render_into_buffer() {
246        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2));
247
248        Label::new("hello").render(buffer.area(), &mut buffer);
249
250        assert_eq!(buffer.lines(), vec!["hello ", "      "]);
251        assert_eq!(Label::new("hello").size(Constraint::UNBOUNDED).cols, 5);
252    }
253
254    #[test]
255    fn widget_display_renders_through_buffer() {
256        let display = Fill::new('x', Style::default()).display(Constraint::tight(4));
257
258        assert_eq!(display, "xxxx\n");
259    }
260
261    #[test]
262    fn block_draws_border_and_child() {
263        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 3));
264
265        Block::new(Label::new("x"))
266            .border(Color::Unset)
267            .title("t")
268            .render(buffer.area(), &mut buffer);
269
270        assert_eq!(buffer.lines(), vec!["╭─t────╮", "│x     │", "╰──────╯"]);
271    }
272
273    #[test]
274    fn clear_and_fill_widgets_cover_their_area() {
275        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
276
277        Fill::new('x', Style::default()).render(buffer.area(), &mut buffer);
278        Clear.render(Rect::new(1, 0, 3, 1), &mut buffer);
279
280        assert_eq!(buffer.lines(), vec!["x   x", "xxxxx"]);
281    }
282
283    #[test]
284    fn block_without_border_renders_child_directly() {
285        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1));
286
287        Block::new(Label::new("abc")).render(buffer.area(), &mut buffer);
288
289        assert_eq!(buffer.lines(), vec!["abc  "]);
290    }
291
292    #[test]
293    fn block_handles_degenerate_border_areas() {
294        let mut one = Buffer::empty(Rect::new(0, 0, 1, 1));
295        let mut row = Buffer::empty(Rect::new(0, 0, 4, 1));
296        let mut column = Buffer::empty(Rect::new(0, 0, 1, 3));
297
298        Block::new(Label::new("x"))
299            .border(Color::Unset)
300            .render(one.area(), &mut one);
301        Block::new(Label::new("x"))
302            .border(Color::Unset)
303            .render(row.area(), &mut row);
304        Block::new(Label::new("x"))
305            .border(Color::Unset)
306            .render(column.area(), &mut column);
307
308        assert_eq!(one.lines(), vec!["╭"]);
309        assert_eq!(row.lines(), vec!["╭──╮"]);
310        assert_eq!(column.lines(), vec!["╭", "│", "╰"]);
311    }
312
313    #[test]
314    fn line_widget_truncates_to_area_width_and_height() {
315        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
316
317        vec![Line::new("abcdef"), Line::new("hidden")].render(buffer.area(), &mut buffer);
318
319        assert_eq!(buffer.lines(), vec!["abc…"]);
320    }
321}