crates/tui-core/src/widget.rs 11.0 KiB raw
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
8
use std::fmt;
9
use std::fmt::Write as _;
10
use std::ops::{Deref, DerefMut};
11
12
use crate::layout::Rect;
13
use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Point, Size, Style};
14
15
/// Something that can render into a [`Buffer`].
16
pub 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
101
/// Something that renders with caller-owned state.
102
pub trait StatefulWidget: fmt::Debug + Send {
103
    /// State kept by the caller between render calls.
104
    type State;
105
106
    /// Returns the widget size under a parent constraint.
107
    fn size(&self, parent: Constraint) -> Size;
108
109
    /// Renders the widget into an area with caller-owned state.
110
    fn render_with_state(
111
        &mut self,
112
        area: Rect,
113
        buf: &mut Buffer,
114
        state: &mut Self::State,
115
    ) -> RenderResult;
116
}
117
118
/// Result produced by one stateful widget render pass.
119
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
120
pub struct RenderResult {
121
    /// Requested terminal cursor position after rendering.
122
    pub cursor: Option<Point>,
123
}
124
125
impl Widget for Box<dyn Widget + '_> {
126
    fn size(&self, parent: Constraint) -> Size {
127
        self.deref().size(parent)
128
    }
129
130
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
131
        self.deref_mut().render(area, buf);
132
    }
133
}
134
135
impl<T: Widget + ?Sized> Widget for &mut T {
136
    fn size(&self, parent: Constraint) -> Size {
137
        (**self).size(parent)
138
    }
139
140
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
141
        (**self).render(area, buf);
142
    }
143
}
144
145
impl<T: StatefulWidget + ?Sized> StatefulWidget for &mut T {
146
    type State = T::State;
147
148
    fn size(&self, parent: Constraint) -> Size {
149
        (**self).size(parent)
150
    }
151
152
    fn render_with_state(
153
        &mut self,
154
        area: Rect,
155
        buf: &mut Buffer,
156
        state: &mut Self::State,
157
    ) -> RenderResult {
158
        (**self).render_with_state(area, buf, state)
159
    }
160
}
161
162
/// Clears an area.
163
#[derive(Debug, Clone, Copy, Default)]
164
pub struct Clear;
165
166
impl Widget for Clear {
167
    fn size(&self, parent: Constraint) -> Size {
168
        parent.bounded_size()
169
    }
170
171
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
172
        buf.fill(area, crate::buffer::Cell::blank());
173
    }
174
}
175
176
/// Fills an area with one glyph and style.
177
#[derive(Debug, Clone)]
178
pub struct Fill {
179
    /// Fill cell.
180
    cell: Cell,
181
}
182
183
impl Fill {
184
    /// Creates a fill widget from one character and style.
185
    pub fn new(ch: char, style: Style) -> Self {
186
        Self {
187
            cell: Cell::new(ch, style),
188
        }
189
    }
190
191
    /// Creates a fill widget from a cell.
192
    pub fn cell(cell: Cell) -> Self {
193
        Self { cell }
194
    }
195
}
196
197
impl Widget for Fill {
198
    fn size(&self, parent: Constraint) -> Size {
199
        parent.bounded_size()
200
    }
201
202
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
203
        buf.fill(area, self.cell.clone());
204
    }
205
}
206
207
/// Bordered widget wrapper.
208
#[derive(Debug, Clone)]
209
pub struct Block<W> {
210
    child: W,
211
    border: Option<Border>,
212
    title: Option<Line>,
213
}
214
215
impl<W> Block<W> {
216
    /// Creates a block around a child.
217
    pub fn new(child: W) -> Self {
218
        Self {
219
            child,
220
            border: None,
221
            title: None,
222
        }
223
    }
224
225
    /// Sets the border color.
226
    pub fn border(mut self, color: Color) -> Self {
227
        self.border = Some(Border::new(color));
228
        self
229
    }
230
231
    /// Sets the border style.
232
    pub fn border_style(mut self, border: Border) -> Self {
233
        self.border = Some(border);
234
        self
235
    }
236
237
    /// Sets the title.
238
    pub fn title(mut self, title: impl Into<Line>) -> Self {
239
        self.title = Some(title.into());
240
        self
241
    }
242
243
    /// Grows a child size by the border, then constrains it to the parent.
244
    fn outer_size(&self, mut size: Size, parent: Constraint) -> Size {
245
        if self.border.is_some() {
246
            size.cols = size.cols.saturating_add(2);
247
            size.rows = size.rows.saturating_add(2);
248
        }
249
        size.constrain(parent)
250
    }
251
252
    /// Draws the border and title, returning the area left for the child.
253
    ///
254
    /// Returns `None` when `area` is empty so the caller renders nothing.
255
    fn frame(&self, area: Rect, buf: &mut Buffer) -> Option<Rect> {
256
        if area.is_empty() {
257
            return None;
258
        }
259
        let Some(border) = self.border else {
260
            return Some(area);
261
        };
262
        border.draw(area, buf);
263
264
        if let Some(title) = self.title.clone()
265
            && area.cols > 4
266
        {
267
            let title = title.truncated(area.cols.saturating_sub(4), "…");
268
            buf.set_line(area.x + 2, area.y, &title);
269
        }
270
        Some(area.inner(1))
271
    }
272
}
273
274
impl<W: Widget> Widget for Block<W> {
275
    fn size(&self, parent: Constraint) -> Size {
276
        self.outer_size(self.child.size(parent), parent)
277
    }
278
279
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
280
        if let Some(inner) = self.frame(area, buf) {
281
            self.child.render(inner, buf);
282
        }
283
    }
284
}
285
286
impl<W: StatefulWidget> StatefulWidget for Block<W> {
287
    type State = W::State;
288
289
    fn size(&self, parent: Constraint) -> Size {
290
        self.outer_size(self.child.size(parent), parent)
291
    }
292
293
    fn render_with_state(
294
        &mut self,
295
        area: Rect,
296
        buf: &mut Buffer,
297
        state: &mut Self::State,
298
    ) -> RenderResult {
299
        if let Some(inner) = self.frame(area, buf) {
300
            self.child.render_with_state(inner, buf, state)
301
        } else {
302
            RenderResult::default()
303
        }
304
    }
305
}
306
307
impl From<Paint<String>> for Fill {
308
    fn from(paint: Paint<String>) -> Self {
309
        Self::cell(Cell::from_glyph(paint.content(), paint.style()))
310
    }
311
}
312
313
#[cfg(test)]
314
mod tests {
315
    use super::*;
316
    use crate::{Constraint, Label};
317
318
    #[test]
319
    fn line_widgets_render_into_buffer() {
320
        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 2));
321
322
        Label::new("hello").render(buffer.area(), &mut buffer);
323
324
        assert_eq!(buffer.lines(), vec!["hello ", "      "]);
325
        assert_eq!(Label::new("hello").size(Constraint::UNBOUNDED).cols, 5);
326
    }
327
328
    #[test]
329
    fn widget_display_renders_through_buffer() {
330
        let display = Fill::new('x', Style::default()).display(Constraint::tight(4));
331
332
        assert_eq!(display, "xxxx\n");
333
    }
334
335
    #[test]
336
    fn block_draws_border_and_child() {
337
        let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 3));
338
339
        Block::new(Label::new("x"))
340
            .border(Color::Unset)
341
            .title("t")
342
            .render(buffer.area(), &mut buffer);
343
344
        assert_eq!(buffer.lines(), vec!["╭─t────╮", "│x     │", "╰──────╯"]);
345
    }
346
347
    #[test]
348
    fn clear_and_fill_widgets_cover_their_area() {
349
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
350
351
        Fill::new('x', Style::default()).render(buffer.area(), &mut buffer);
352
        Clear.render(Rect::new(1, 0, 3, 1), &mut buffer);
353
354
        assert_eq!(buffer.lines(), vec!["x   x", "xxxxx"]);
355
    }
356
357
    #[test]
358
    fn block_without_border_renders_child_directly() {
359
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 1));
360
361
        Block::new(Label::new("abc")).render(buffer.area(), &mut buffer);
362
363
        assert_eq!(buffer.lines(), vec!["abc  "]);
364
    }
365
366
    #[test]
367
    fn block_handles_degenerate_border_areas() {
368
        let mut one = Buffer::empty(Rect::new(0, 0, 1, 1));
369
        let mut row = Buffer::empty(Rect::new(0, 0, 4, 1));
370
        let mut column = Buffer::empty(Rect::new(0, 0, 1, 3));
371
372
        Block::new(Label::new("x"))
373
            .border(Color::Unset)
374
            .render(one.area(), &mut one);
375
        Block::new(Label::new("x"))
376
            .border(Color::Unset)
377
            .render(row.area(), &mut row);
378
        Block::new(Label::new("x"))
379
            .border(Color::Unset)
380
            .render(column.area(), &mut column);
381
382
        assert_eq!(one.lines(), vec!["╭"]);
383
        assert_eq!(row.lines(), vec!["╭──╮"]);
384
        assert_eq!(column.lines(), vec!["╭", "│", "╰"]);
385
    }
386
387
    #[test]
388
    fn line_widget_truncates_to_area_width_and_height() {
389
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
390
391
        vec![Line::new("abcdef"), Line::new("hidden")].render(buffer.area(), &mut buffer);
392
393
        assert_eq!(buffer.lines(), vec!["abc…"]);
394
    }
395
}