Simplify and speed up `tui-core`

c1c9a66a417ec346d55b26a395c88af27727d2a8
* Make `render` take `&mut self`.
* Cache label metrics.
Alexis Sellier committed ago 1 parent 1968b7e7
crates/diff/src/renderer.rs +3 -3
342 342
343 343
        metas.push(RowMeta::FileTop(file.id));
344 344
        stack.push(file.header_line(child_cols));
345 345
        metas.push(RowMeta::FileHeader(file.id));
346 346
        if !collapsed && !file.hunks.is_empty() {
347 -
            stack = stack.divider_cell(Cell::new(DIVIDER, border.style()));
347 +
            stack = stack.divider_cell(Cell::new(DIVIDER, border.style));
348 348
            metas.push(RowMeta::FileDivider(file.id));
349 349
            for (index, hunk) in file.hunks.iter().enumerate() {
350 350
                if index > 0 {
351 -
                    stack = stack.divider_cell(Cell::new(DIVIDER, border.style()));
351 +
                    stack = stack.divider_cell(Cell::new(DIVIDER, border.style));
352 352
                    metas.push(RowMeta::HunkDivider(file.id));
353 353
                }
354 354
                stack.push(hunk.header_line());
355 355
                metas.push(RowMeta::HunkHeader(file.id, hunk.id));
356 356
                for row in self.hunk_rows(file, hunk, child_cols) {
660 660
        };
661 661
662 662
        Size::new(cols, self.content_rows(cols)).constrain(parent)
663 663
    }
664 664
665 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
665 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
666 666
        Self::render(self, area, buf);
667 667
    }
668 668
}
669 669
670 670
impl RowMeta {
a.rs +0 -0
crates/tui-core/src/aligned.rs +4 -4
40 40
            parent.max.cols.max(child.cols)
41 41
        };
42 42
        Size::new(cols, child.rows).constrain(parent)
43 43
    }
44 44
45 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
45 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
46 46
        let child = self.child.size(Constraint::max(area.size()));
47 47
        let cols = child.cols.min(area.cols);
48 48
        let x = match self.align {
49 49
            Align::Left => area.x,
50 50
            Align::Right => area.x + area.cols.saturating_sub(cols),
61 61
    use super::*;
62 62
    use crate::Line;
63 63
64 64
    #[test]
65 65
    fn left_alignment_pads_to_parent_width() {
66 -
        let aligned = Aligned::new(Line::new("cat"), Align::Left);
66 +
        let mut aligned = Aligned::new(Line::new("cat"), Align::Left);
67 67
68 68
        assert_eq!(aligned.display(Constraint::tight(6)), "cat   \n");
69 69
    }
70 70
71 71
    #[test]
72 72
    fn right_alignment_pads_before_content() {
73 -
        let aligned = Aligned::new(Line::new("cat"), Align::Right);
73 +
        let mut aligned = Aligned::new(Line::new("cat"), Align::Right);
74 74
75 75
        assert_eq!(aligned.display(Constraint::tight(6)), "   cat\n");
76 76
    }
77 77
78 78
    #[test]
79 79
    fn alignment_truncates_content_to_allocated_width() {
80 -
        let aligned = Aligned::new(Line::new("abcdef"), Align::Left);
80 +
        let mut aligned = Aligned::new(Line::new("abcdef"), Align::Left);
81 81
82 82
        assert_eq!(aligned.display(Constraint::tight(4)), "abc…\n");
83 83
    }
84 84
}
crates/tui-core/src/border.rs +5 -12
49 49
}
50 50
51 51
/// A border style.
52 52
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53 53
pub struct Border {
54 -
    style: Style,
55 -
    chars: BorderChars,
54 +
    /// Border style.
55 +
    pub style: Style,
56 +
    /// Border characters.
57 +
    pub chars: BorderChars,
56 58
}
57 59
58 60
impl Border {
59 61
    /// Creates a rounded border from a foreground color.
60 62
    pub const fn new(color: Color) -> Self {
67 69
            style,
68 70
            chars: BorderChars::ROUNDED,
69 71
        }
70 72
    }
71 73
72 -
    /// Returns the border style.
73 -
    pub const fn style(self) -> Style {
74 -
        self.style
75 -
    }
76 -
77 -
    /// Returns the border glyphs.
78 -
    pub const fn chars(self) -> BorderChars {
79 -
        self.chars
80 -
    }
81 -
82 74
    /// Returns a top border line with `cols` inner columns.
83 75
    pub fn top(self, cols: usize) -> Line {
84 76
        self.horizontal(
85 77
            self.chars.top_left,
86 78
            self.chars.horizontal,
182 174
}
183 175
184 176
#[cfg(test)]
185 177
mod tests {
186 178
    use super::*;
179 +
    use crate::Buffer;
187 180
188 181
    #[test]
189 182
    fn border_lines_use_shared_glyphs_and_style() {
190 183
        let border = Border::new(Color::Red);
191 184
        let line = border.top(3);
crates/tui-core/src/buffer.rs +73 -4
99 99
            glyph: normalize_char(ch),
100 100
            style,
101 101
        }
102 102
    }
103 103
104 +
    /// Creates a cell from one printable ASCII byte.
105 +
    fn from_printable_ascii(byte: u8, style: Style) -> Self {
106 +
        Self {
107 +
            glyph: if byte == b' ' {
108 +
                CellGlyph::Blank
109 +
            } else {
110 +
                CellGlyph::Ascii(byte)
111 +
            },
112 +
            style,
113 +
        }
114 +
    }
115 +
104 116
    /// Returns the terminal width of this cell's leading glyph.
105 117
    fn width(&self) -> usize {
106 118
        match &self.glyph {
107 119
            CellGlyph::Blank | CellGlyph::Ascii(_) => 1,
108 120
            CellGlyph::Unicode(glyph) => char_width(*glyph),
221 233
        self.set(x, y, Cell::new(glyph, style));
222 234
    }
223 235
224 236
    /// Writes styled text by absolute position.
225 237
    pub fn set_str(&mut self, x: usize, y: usize, text: &str, style: Style) {
238 +
        if text.is_ascii()
239 +
            && text.bytes().all(|byte| !byte.is_ascii_control())
240 +
            && self.area.contains(Point::new(x, y))
241 +
        {
242 +
            self.set_ascii_str(x, y, text, style);
243 +
            return;
244 +
        }
245 +
226 246
        let mut cursor = x;
227 247
        for ch in text.chars() {
228 248
            if cursor >= self.area.right() {
229 249
                break;
230 250
            }
238 258
            self.set(cursor, y, Cell::from_char(ch, style));
239 259
            cursor += width;
240 260
        }
241 261
    }
242 262
263 +
    /// Writes printable ASCII text by absolute position.
264 +
    fn set_ascii_str(&mut self, x: usize, y: usize, text: &str, style: Style) {
265 +
        let visible = text.len().min(self.area.right() - x);
266 +
        if visible == 0 {
267 +
            return;
268 +
        }
269 +
        self.clear_glyph_at(x, y);
270 +
        if x + visible < self.area.right() {
271 +
            self.clear_glyph_at(x + visible, y);
272 +
        }
273 +
274 +
        let start = (y - self.area.y) * self.area.cols + (x - self.area.x);
275 +
        for (offset, byte) in text.bytes().take(visible).enumerate() {
276 +
            let cell = Cell::from_printable_ascii(byte, style);
277 +
            let index = start + offset;
278 +
279 +
            if self.cells[index] != cell {
280 +
                self.cells[index] = cell;
281 +
                self.dirty[index] = true;
282 +
            }
283 +
        }
284 +
    }
285 +
243 286
    /// Writes a label by absolute position.
244 287
    pub fn set_label(&mut self, x: usize, y: usize, label: &Label) {
245 -
        self.set_str(x, y, label.content(), label.paint().style());
288 +
        if label.is_ascii() && self.area.contains(Point::new(x, y)) {
289 +
            self.set_ascii_str(x, y, label.content(), label.paint.style());
290 +
        } else {
291 +
            self.set_str(x, y, label.content(), label.paint.style());
292 +
        }
246 293
    }
247 294
248 295
    /// Writes a styled line by absolute position.
249 296
    pub fn set_line(&mut self, x: usize, y: usize, line: &Line) {
250 297
        let mut cursor = x;
251 298
        for label in line.labels() {
252 299
            self.set_label(cursor, y, label);
253 -
            cursor += label.content().width();
300 +
            cursor += label.width();
254 301
            if cursor >= self.area.right() {
255 302
                break;
256 303
            }
257 304
        }
258 305
    }
311 358
            return Line::blank();
312 359
        }
313 360
        let start = row * self.area.cols;
314 361
        let end = start + self.area.cols;
315 362
        let mut line = Line::blank();
363 +
        let mut content = String::new();
364 +
        let mut style = None;
316 365
317 366
        for cell in &self.cells[start..end] {
318 -
            if !cell.is_continuation() {
319 -
                line.push(Label::from(cell.paint()));
367 +
            if cell.is_continuation() {
368 +
                continue;
320 369
            }
370 +
            let cell_style = cell.style();
371 +
            if style.is_some_and(|style| style != cell_style) && !content.is_empty() {
372 +
                line.push(Label::raw(content, style.unwrap_or_default()));
373 +
                content = String::new();
374 +
            }
375 +
            style = Some(cell_style);
376 +
            content.push_str(&cell.glyph());
377 +
        }
378 +
        if !content.is_empty() {
379 +
            line.push(Label::raw(content, style.unwrap_or_default()));
321 380
        }
322 381
        line
323 382
    }
324 383
325 384
    /// Computes dirty runs using a cell predicate.
511 570
            line.labels()[1].paint().style().fg_color(),
512 571
            crate::Color::Blue
513 572
        );
514 573
    }
515 574
575 +
    #[test]
576 +
    fn ascii_text_clears_wide_glyph_boundaries() {
577 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 6, 1));
578 +
579 +
        buffer.set_str(0, 0, "🍍🍍", Style::default());
580 +
        buffer.set_str(1, 0, "ab", Style::default());
581 +
582 +
        assert_eq!(buffer.line(0), " ab   ");
583 +
    }
584 +
516 585
    #[test]
517 586
    fn new_buffer_starts_dirty_and_reset_clears_dirty_marks() {
518 587
        let mut buffer = Buffer::empty(Rect::new(2, 3, 4, 2));
519 588
        let runs = buffer.dirty_runs();
520 589
crates/tui-core/src/cell.rs +15 -13
137 137
            self.chars().map(char_width).sum()
138 138
        }
139 139
    }
140 140
141 141
    fn truncate(&self, width: usize, delim: &str) -> String {
142 -
        if width >= Text::width(self) {
143 -
            return self.to_owned();
144 -
        }
145 142
        let d = Text::width(delim);
146 -
147 -
        if width < d {
148 -
            return String::new();
149 -
        }
150 143
        let mut cols = 0;
151 -
        let mut boundary = 0;
144 +
        let mut truncation_boundary = 0;
145 +
        let mut truncated = false;
146 +
        let truncation_width = width.saturating_sub(d);
152 147
153 148
        for (index, ch) in self.char_indices() {
154 149
            let c = char_width(ch);
155 -
            if cols + c + d > width {
150 +
            if cols + c > width {
151 +
                truncated = true;
156 152
                break;
157 153
            }
158 154
            cols += c;
159 -
            boundary = index + ch.len_utf8();
155 +
            if cols <= truncation_width {
156 +
                truncation_boundary = index + ch.len_utf8();
157 +
            }
160 158
        }
161 159
162 -
        if self[boundary..].trim().is_empty() {
163 -
            self[..boundary].to_owned()
160 +
        if !truncated {
161 +
            self.to_owned()
162 +
        } else if width < d {
163 +
            String::new()
164 +
        } else if self[truncation_boundary..].trim().is_empty() {
165 +
            self[..truncation_boundary].to_owned()
164 166
        } else {
165 -
            format!("{}{delim}", &self[..boundary])
167 +
            format!("{}{delim}", &self[..truncation_boundary])
166 168
        }
167 169
    }
168 170
169 171
    fn pad(&self, max: usize) -> String {
170 172
        let width = Text::width(self);
crates/tui-core/src/frame.rs +47 -1
28 28
            cursor: None,
29 29
        }
30 30
    }
31 31
32 32
    /// Renders a widget into an area.
33 -
    pub fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
33 +
    pub fn render_widget<W: Widget>(&mut self, mut widget: W, area: Rect) {
34 34
        widget.render(area, self.buffer);
35 35
    }
36 36
37 37
    /// Sets the terminal cursor.
38 38
    pub fn set_cursor_position(&mut self, point: Point) {
39 39
        self.cursor = Some(point);
40 40
    }
41 41
}
42 +
43 +
#[cfg(test)]
44 +
mod tests {
45 +
    use std::cell::Cell;
46 +
47 +
    use super::*;
48 +
    use crate::{Constraint, Size, Style};
49 +
50 +
    #[derive(Debug)]
51 +
    struct LayoutProbe {
52 +
        laid_out: Cell<bool>,
53 +
        area: Cell<Rect>,
54 +
    }
55 +
56 +
    impl Default for LayoutProbe {
57 +
        fn default() -> Self {
58 +
            Self {
59 +
                laid_out: Cell::new(false),
60 +
                area: Cell::new(Rect::default()),
61 +
            }
62 +
        }
63 +
    }
64 +
65 +
    impl Widget for LayoutProbe {
66 +
        fn size(&self, parent: Constraint) -> Size {
67 +
            parent.bounded_size()
68 +
        }
69 +
70 +
        fn render(&mut self, area: Rect, buf: &mut Buffer) {
71 +
            self.laid_out.set(true);
72 +
            self.area.set(area);
73 +
            buf.set_str(area.x, area.y, "R", Style::default());
74 +
        }
75 +
    }
76 +
77 +
    #[test]
78 +
    fn render_widget_renders_into_area() {
79 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 2));
80 +
        let area = Rect::new(1, 1, 2, 1);
81 +
        let mut frame = Frame::new(buffer.area(), &mut buffer);
82 +
83 +
        frame.render_widget(LayoutProbe::default(), area);
84 +
85 +
        assert_eq!(buffer.lines(), vec!["    ", " R  "]);
86 +
    }
87 +
}
crates/tui-core/src/hstack.rs +10 -10
62 62
            .unwrap_or(0);
63 63
64 64
        Size::new(total, height)
65 65
    }
66 66
67 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
67 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
68 68
        let widths = allocate_widths(&self.slots, Constraint::max(area.size()));
69 69
        let mut x = area.x;
70 70
71 -
        for (slot, width) in self.slots.iter().zip(widths) {
71 +
        for (slot, width) in self.slots.iter_mut().zip(widths) {
72 72
            if x >= area.right() {
73 73
                break;
74 74
            }
75 75
            let width = width.min(area.right() - x);
76 76
            if let Slot::Widget(widget) = slot {
133 133
    impl Widget for Expanding {
134 134
        fn size(&self, parent: Constraint) -> Size {
135 135
            parent.max
136 136
        }
137 137
138 -
        fn render(&self, _area: Rect, _buf: &mut Buffer) {}
138 +
        fn render(&mut self, _area: Rect, _buf: &mut Buffer) {}
139 139
    }
140 140
141 141
    #[test]
142 142
    fn empty_stack_uses_no_space() {
143 -
        let stack = HStack::default();
143 +
        let mut stack = HStack::default();
144 144
145 145
        assert_eq!(stack.size(Constraint::tight(8)), Size::new(0, 0));
146 146
        assert!(stack.display(Constraint::tight(8)).is_empty());
147 147
    }
148 148
149 149
    #[test]
150 150
    fn natural_widths_sum_for_widget_children() {
151 -
        let stack = HStack::default()
151 +
        let mut stack = HStack::default()
152 152
            .child(Line::new("abcdef"))
153 153
            .child(Line::new("ghij"));
154 154
155 155
        assert_eq!(stack.size(Constraint::tight(80)), Size::new(10, 1));
156 156
        assert_eq!(
170 170
        );
171 171
    }
172 172
173 173
    #[test]
174 174
    fn spacer_absorbs_leftover_horizontal_space() {
175 -
        let stack = HStack::default()
175 +
        let mut stack = HStack::default()
176 176
            .child(Line::new("L"))
177 177
            .spacer()
178 178
            .child(Line::new("R"));
179 179
180 180
        assert_eq!(stack.display(Constraint::tight(6)), "L    R\n");
181 181
    }
182 182
183 183
    #[test]
184 184
    fn multiple_spacers_split_remainder_evenly() {
185 -
        let stack = HStack::default()
185 +
        let mut stack = HStack::default()
186 186
            .child(Line::new("a"))
187 187
            .spacer()
188 188
            .child(Line::new("b"))
189 189
            .spacer()
190 190
            .child(Line::new("c"));
192 192
        assert_eq!(stack.display(Constraint::tight(7)), "a  b  c\n");
193 193
    }
194 194
195 195
    #[test]
196 196
    fn spacer_falls_back_to_one_column_when_unbounded() {
197 -
        let stack = HStack::default()
197 +
        let mut stack = HStack::default()
198 198
            .child(Line::new("L"))
199 199
            .spacer()
200 200
            .child(Line::new("R"));
201 201
202 202
        assert_eq!(stack.display(Constraint::UNBOUNDED), "L R\n");
203 203
    }
204 204
205 205
    #[test]
206 206
    fn column_rows_pad_to_column_width_when_neighbors_have_more_lines() {
207 -
        let stack = HStack::default()
207 +
        let mut stack = HStack::default()
208 208
            .child(vec![Line::new("aa"), Line::new("bb")])
209 209
            .child(Line::new("cc"));
210 210
211 211
        assert_eq!(stack.display(Constraint::tight(10)), "aacc\nbb  \n");
212 212
    }
213 213
214 214
    #[test]
215 215
    fn lines_zip_columns_for_multi_row_children() {
216 -
        let stack = HStack::default()
216 +
        let mut stack = HStack::default()
217 217
            .child(vec![Line::new("aa"), Line::new("bb")])
218 218
            .child(Line::new("cc"));
219 219
220 220
        let lines = stack
221 221
            .lines(Constraint::tight(10))
crates/tui-core/src/label.rs +67 -39
4 4
//! text widgets. It combines string content with paint/style metadata while
5 5
//! still supporting width-aware truncation and padding.
6 6
7 7
use std::fmt;
8 8
9 -
use super::{Color, Constraint, Filled, Line, Paint, Size, Style, Widget, cell::Text};
9 +
use super::{Buffer, Color, Constraint, Filled, Line, Paint, Size, Style, Widget, cell::Text};
10 10
11 11
/// A styled string that does not contain any `'\n'` and implements [`Widget`] and [`Text`].
12 12
#[derive(Clone, Default, Debug)]
13 -
pub struct Label(Paint<String>);
13 +
pub struct Label {
14 +
    /// Styled label content.
15 +
    pub paint: Paint<String>,
16 +
    /// Cached text metrics.
17 +
    metrics: LabelMetrics,
18 +
}
19 +
20 +
/// Cached metrics for label content.
21 +
#[derive(Clone, Copy, Debug, Default)]
22 +
struct LabelMetrics {
23 +
    /// Display width in terminal cells.
24 +
    width: usize,
25 +
    /// Whether the content can use the buffer's printable-ASCII fast path.
26 +
    ascii: bool,
27 +
}
28 +
29 +
impl LabelMetrics {
30 +
    /// Computes metrics for label content.
31 +
    fn new(content: &str) -> Self {
32 +
        Self {
33 +
            width: content.width(),
34 +
            ascii: content.is_ascii() && content.bytes().all(|byte| !byte.is_ascii_control()),
35 +
        }
36 +
    }
37 +
}
14 38
15 39
impl Label {
16 40
    /// Creates a new label.
17 41
    pub fn new(s: &str) -> Self {
18 -
        Self(Paint::new(clean(s.to_owned())))
42 +
        Self::raw(clean(s.to_owned()), Style::default())
19 43
    }
20 44
21 45
    /// Creates a blank label.
22 46
    pub fn blank() -> Self {
23 -
        Self(Paint::default())
47 +
        Self::raw(String::new(), Style::default())
24 48
    }
25 49
26 50
    /// Returns whether this label is empty.
27 51
    pub fn is_blank(&self) -> bool {
28 52
        self.content().is_empty()
29 53
    }
30 54
31 55
    /// Returns unstyled content.
32 56
    pub fn content(&self) -> &str {
33 -
        self.0.content()
57 +
        self.paint.content()
34 58
    }
35 59
36 60
    /// Creates a single-space label.
37 61
    pub fn space() -> Self {
38 -
        Self(Paint::new(" ".to_owned()))
39 -
    }
40 -
41 -
    /// Boxes the label.
42 -
    pub fn boxed(self) -> Box<dyn Widget> {
43 -
        Box::new(self)
62 +
        Self::raw(String::from(" "), Style::default())
44 63
    }
45 64
46 65
    /// Color the label's foreground.
47 66
    pub fn fg(self, color: Color) -> Self {
48 -
        Self(self.0.fg(color))
67 +
        Self {
68 +
            paint: self.paint.fg(color),
69 +
            metrics: self.metrics,
70 +
        }
49 71
    }
50 72
51 73
    /// Color the label's background.
52 74
    pub fn bg(self, color: Color) -> Self {
53 -
        Self(self.0.bg(color))
75 +
        Self {
76 +
            paint: self.paint.bg(color),
77 +
            metrics: self.metrics,
78 +
        }
54 79
    }
55 80
56 81
    /// Styles the label.
57 82
    pub fn style(self, style: Style) -> Self {
58 -
        Self(self.0.with_style(style))
59 -
    }
60 -
61 -
    /// Returns the inner paint object.
62 -
    pub fn paint(&self) -> &Paint<String> {
63 -
        &self.0
83 +
        Self {
84 +
            paint: self.paint.with_style(style),
85 +
            metrics: self.metrics,
86 +
        }
64 87
    }
65 88
66 89
    /// Returns this label with a fill background.
67 90
    pub fn filled(self, color: Color) -> Filled<Self> {
68 91
        Filled { item: self, color }
70 93
71 94
    /// Wraps this label into a line.
72 95
    pub fn to_line(self) -> Line {
73 96
        Line::from(self)
74 97
    }
75 -
}
76 98
77 -
impl Widget for Label {
78 -
    fn size(&self, _parent: Constraint) -> Size {
79 -
        Size::new(self.0.width(), 1)
99 +
    /// Returns whether the label content is printable ASCII.
100 +
    pub(crate) const fn is_ascii(&self) -> bool {
101 +
        self.metrics.ascii
80 102
    }
81 103
82 -
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
83 -
        Line::renders([Line::new(self.clone())], area, buf);
104 +
    /// Creates a label from content that has already been cleaned.
105 +
    pub(crate) fn raw(content: String, style: Style) -> Self {
106 +
        Self {
107 +
            metrics: LabelMetrics::new(&content),
108 +
            paint: Paint {
109 +
                item: content,
110 +
                style,
111 +
            },
112 +
        }
84 113
    }
114 +
}
85 115
86 -
    fn lines(&self, _parent: Constraint) -> Vec<Line> {
87 -
        vec![Line::new(self.clone())]
116 +
impl Widget for Label {
117 +
    fn size(&self, _parent: Constraint) -> Size {
118 +
        Size::new(self.metrics.width, 1)
88 119
    }
89 120
90 -
    fn to_line(&self, _parent: Constraint) -> Line {
91 -
        Line::new(self.clone())
121 +
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
122 +
        Line::renders([Line::new(self.clone())], area, buf);
92 123
    }
93 124
}
94 125
95 126
impl fmt::Display for Label {
96 127
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 -
        fmt::Display::fmt(&self.0, f)
128 +
        fmt::Display::fmt(&self.paint, f)
98 129
    }
99 130
}
100 131
101 132
impl Text for Label {
102 133
    type Padded = Self;
103 134
    type Truncated = Self;
104 135
105 136
    fn background(&self) -> Color {
106 -
        self.paint().style.background
137 +
        self.paint.style.background
107 138
    }
108 139
109 140
    fn pad(&self, width: usize) -> Self::Padded {
110 -
        Self(self.0.pad(width))
141 +
        Self::from(self.paint.pad(width))
111 142
    }
112 143
113 144
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
114 -
        Self(self.0.truncate(width, delim))
145 +
        Self::from(self.paint.truncate(width, delim))
115 146
    }
116 147
117 148
    fn width(&self) -> usize {
118 -
        Text::width(&self.0)
149 +
        self.metrics.width
119 150
    }
120 151
}
121 152
122 153
impl<D: fmt::Display> From<Paint<D>> for Label {
123 154
    fn from(paint: Paint<D>) -> Self {
124 -
        Self(Paint {
125 -
            item: clean(format!("{}", paint.item)),
126 -
            style: paint.style,
127 -
        })
155 +
        Self::raw(clean(format!("{}", paint.item)), paint.style)
128 156
    }
129 157
}
130 158
131 159
impl From<String> for Label {
132 160
    fn from(value: String) -> Self {
133 -
        Self(Paint::new(clean(value)))
161 +
        Self::raw(clean(value), Style::default())
134 162
    }
135 163
}
136 164
137 165
impl From<&str> for Label {
138 166
    fn from(value: &str) -> Self {
crates/tui-core/src/primitive.rs +12 -23
102 102
        Self {
103 103
            items: self
104 104
                .items
105 105
                .into_iter()
106 106
                .map(|l| {
107 -
                    let style = l.paint().style().merge(style);
107 +
                    let style = l.paint.style().merge(style);
108 108
                    l.style(style)
109 109
                })
110 110
                .collect(),
111 111
        }
112 112
    }
259 259
impl Widget for Line {
260 260
    fn size(&self, _parent: Constraint) -> Size {
261 261
        Size::new(self.width(), 1)
262 262
    }
263 263
264 -
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
264 +
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
265 265
        Line::renders([self.clone()], area, buf);
266 266
    }
267 -
268 -
    fn lines(&self, _parent: Constraint) -> Vec<Line> {
269 -
        vec![self.clone()]
270 -
    }
271 -
272 -
    fn to_line(&self, _parent: Constraint) -> Line {
273 -
        self.clone()
274 -
    }
275 267
}
276 268
277 269
impl Widget for Vec<Line> {
278 270
    fn size(&self, _parent: Constraint) -> Size {
279 271
        let width = self.iter().map(Line::width).max().unwrap_or_default();
280 272
        let height = self.len();
281 273
282 274
        Size::new(width, height)
283 275
    }
284 276
285 -
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
277 +
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
286 278
        Line::renders(self.clone(), area, buf);
287 279
    }
288 -
289 -
    fn lines(&self, _parent: Constraint) -> Vec<Line> {
290 -
        self.clone()
291 -
    }
292 280
}
293 281
294 282
impl fmt::Display for Line {
295 283
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 284
        for item in &self.items {
301 289
}
302 290
303 291
impl fmt::Display for StyledLine<'_> {
304 292
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 293
        for item in &self.line.items {
306 -
            write!(f, "{}", item.paint().styled())?;
294 +
            write!(f, "{}", item.paint.styled())?;
307 295
        }
308 296
        Ok(())
309 297
    }
310 298
}
311 299
402 390
        assert_eq!(line.to_string(), "banana apple");
403 391
    }
404 392
405 393
    #[test]
406 394
    fn line_styled_adapter_formats_label_styles_explicitly() {
407 -
        let line = Line::new(Label::new("x").fg(Color::Red)).item(Label::new("y").fg(Color::Blue));
395 +
        let mut line =
396 +
            Line::new(Label::new("x").fg(Color::Red)).item(Label::new("y").fg(Color::Blue));
408 397
409 398
        assert_eq!(line.to_string(), "xy");
410 399
        assert_eq!(
411 400
            line.styled().to_string(),
412 401
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m"
413 402
        );
414 403
        assert_eq!(
415 -
            Widget::display_styled(&line, Constraint::UNBOUNDED),
404 +
            Widget::display_styled(&mut line, Constraint::UNBOUNDED),
416 405
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m\n"
417 406
        );
418 407
    }
419 408
420 409
    #[test]
437 426
    }
438 427
439 428
    #[test]
440 429
    fn line_boxed_dispatches_widget_methods() {
441 430
        let line = Line::new("boxed");
442 -
        let boxed = line.boxed();
431 +
        let mut boxed = line.boxed();
443 432
444 433
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
445 434
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
446 435
    }
447 436
448 437
    #[test]
449 -
    fn widget_reference_dispatches_widget_methods() {
450 -
        let line = Line::new("ref");
451 -
        let reference = &line;
438 +
    fn mutable_widget_reference_dispatches_widget_methods() {
439 +
        let mut line = Line::new("ref");
440 +
        let reference = &mut line;
452 441
453 442
        assert_eq!(reference.size(Constraint::UNBOUNDED), Size::new(3, 1));
454 443
        assert_eq!(reference.display(Constraint::UNBOUNDED), "ref\n");
455 444
    }
456 445
457 446
    #[test]
458 447
    fn vec_line_widget_size_uses_widest_line_and_line_count() {
459 -
        let lines = vec![Line::new("short"), Line::new("longer")];
448 +
        let mut lines = vec![Line::new("short"), Line::new("longer")];
460 449
461 450
        assert_eq!(lines.size(Constraint::UNBOUNDED), Size::new(6, 2));
462 451
        assert_eq!(lines.display(Constraint::UNBOUNDED), "short \nlonger\n");
463 452
    }
464 453
crates/tui-core/src/table.rs +4 -4
34 34
//! spider mite ladybug
35 35
//! ```
36 36
use std::fmt;
37 37
38 38
use super::cell::Text;
39 -
use super::{Border, Constraint, Line, Size, Style, Widget, colors};
39 +
use super::{Border, Buffer, Constraint, Line, Size, Style, Widget, colors};
40 40
41 41
/// Rendering options for a table.
42 42
#[derive(Debug)]
43 43
pub struct TableOptions {
44 44
    /// Whether the table should be allowed to overflow.
124 124
{
125 125
    fn size(&self, parent: Constraint) -> Size {
126 126
        Table::size(self, parent)
127 127
    }
128 128
129 -
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
129 +
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
130 130
        let size = area.size();
131 131
        Line::renders(self.lines(Constraint::new(size, size)), area, buf);
132 132
    }
133 133
134 -
    fn lines(&self, parent: Constraint) -> Vec<Line> {
134 +
    fn lines(&mut self, parent: Constraint) -> Vec<Line> {
135 135
        Table::lines(self, parent)
136 136
    }
137 137
}
138 138
139 139
impl<const W: usize, T: Text> Table<W, T>
563 563
        );
564 564
    }
565 565
566 566
    #[test]
567 567
    fn from_iterator_tracks_column_widths() {
568 -
        let t = [["a", "beta"], ["alpha", "b"]]
568 +
        let mut t = [["a", "beta"], ["alpha", "b"]]
569 569
            .into_iter()
570 570
            .collect::<Table<2, _>>();
571 571
572 572
        assert_eq!(t.display(Constraint::UNBOUNDED), "a     beta\nalpha b   \n");
573 573
    }
crates/tui-core/src/textarea.rs +3 -4
2 2
//!
3 3
//! `TextArea` stores plain text plus body style and exposes wrapped lines for a
4 4
//! target width. It is useful both as a widget and as a line producer for
5 5
//! scrollable previews.
6 6
7 -
use super::{Constraint, Line, Paint, Size, Widget, cell::Text};
7 +
use super::{Buffer, Constraint, Line, Paint, Size, Widget, cell::Text};
8 8
9 9
/// Default text wrap width.
10 10
pub const DEFAULT_WRAP: usize = 80;
11 11
/// Soft tab replacement for '\t'.
12 12
pub const SOFT_TAB: &str = "  ";
84 84
        let rows = self.lines().count();
85 85
86 86
        Size::new(cols, rows)
87 87
    }
88 88
89 -
    fn render(&self, area: crate::Rect, buf: &mut crate::Buffer) {
89 +
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
90 90
        Line::renders(
91 -
            self.lines()
92 -
                .map(|l| Line::new(Paint::new(l).with_style(self.body.style))),
91 +
            TextArea::lines(self).map(|l| Line::new(Paint::new(l).with_style(self.body.style))),
93 92
            area,
94 93
            buf,
95 94
        );
96 95
    }
97 96
}
crates/tui-core/src/vstack.rs +17 -21
181 181
            widget: Box::new(child),
182 182
            height: Some(height),
183 183
        });
184 184
    }
185 185
186 -
    /// Box this widget.
187 -
    pub fn boxed(self) -> Box<dyn Widget + 'a> {
188 -
        Box::new(self)
189 -
    }
190 -
191 186
    /// Inner size.
192 187
    #[cfg(test)]
193 188
    fn inner(&self, c: Constraint) -> Size {
194 189
        let mut outer = self.outer(c);
195 190
228 223
impl Widget for VStack<'_> {
229 224
    fn size(&self, parent: Constraint) -> Size {
230 225
        self.outer(parent)
231 226
    }
232 227
233 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
228 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
234 229
        let padding = self.opts.padding;
235 230
        let content = if self.opts.border.is_some() {
236 231
            area.inner(1)
237 232
        } else {
238 233
            area
251 246
        let mut y = content.y;
252 247
253 248
        if let Some(border) = self.opts.border {
254 249
            border.draw(area, buf);
255 250
        }
256 -
        for (row, rows) in self.rows.iter().zip(heights) {
251 +
        for (row, rows) in self.rows.iter_mut().zip(heights) {
257 252
            match row {
258 253
                Row::Widget { widget, .. } => {
259 254
                    if rows > 0 && y < content.bottom() {
260 255
                        let area = Rect::new(child_x, y, child_cols, rows);
261 256
                        widget.render(area, buf);
263 258
                    y += rows;
264 259
                }
265 260
                Row::Divider { cell } => {
266 261
                    let row_y = y;
267 262
                    y += rows;
263 +
268 264
                    if rows == 0 || row_y >= area.bottom() {
269 265
                        continue;
270 266
                    }
271 267
                    if let Some(border) = self.opts.border {
272 -
                        let chars = border.chars();
273 -
                        buf.set_glyph(area.x, row_y, chars.divider_left, border.style());
268 +
                        buf.set_glyph(area.x, row_y, border.chars.divider_left, border.style);
274 269
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
270 +
275 271
                        if area.cols > 1 {
276 272
                            buf.set_glyph(
277 273
                                area.right().saturating_sub(1),
278 274
                                row_y,
279 -
                                chars.divider_right,
280 -
                                border.style(),
275 +
                                border.chars.divider_right,
276 +
                                border.style,
281 277
                            );
282 278
                        }
283 279
                    } else {
284 280
                        buf.fill(Rect::new(content.x, row_y, content.cols, 1), cell.clone());
285 281
                    }
343 339
}
344 340
345 341
#[cfg(test)]
346 342
mod tests {
347 343
    use super::*;
348 -
    use crate::{Color, Line};
344 +
    use crate::{Buffer, Color, Line};
349 345
350 346
    #[derive(Debug)]
351 347
    struct Expanding;
352 348
353 349
    impl Widget for Expanding {
354 350
        fn size(&self, parent: Constraint) -> Size {
355 351
            parent.max
356 352
        }
357 353
358 -
        fn render(&self, _area: Rect, _buf: &mut Buffer) {}
354 +
        fn render(&mut self, _area: Rect, _buf: &mut Buffer) {}
359 355
    }
360 356
361 357
    #[test]
362 358
    fn test_vstack() {
363 359
        let mut v = VStack::default()
425 421
        );
426 422
    }
427 423
428 424
    #[test]
429 425
    fn empty_vstack_has_padding_width_and_no_rows() {
430 -
        let v = VStack::default();
426 +
        let mut v = VStack::default();
431 427
432 428
        assert!(v.is_empty());
433 429
        assert_eq!(v.size(Constraint::UNBOUNDED), Size::new(2, 0));
434 430
        assert_eq!(v.display(Constraint::UNBOUNDED), "");
435 431
    }
436 432
437 433
    #[test]
438 434
    fn unbordered_vstack_renders_widgets_and_plain_divider() {
439 -
        let v = VStack::default()
435 +
        let mut v = VStack::default()
440 436
            .padding(0)
441 437
            .child(Line::new("top"))
442 438
            .divider()
443 439
            .child(Line::new("bottom"));
444 440
447 443
        assert_eq!(v.display(Constraint::UNBOUNDED), "top   \n──────\nbottom\n");
448 444
    }
449 445
450 446
    #[test]
451 447
    fn bordered_divider_keeps_border_and_fill_styles_separate() {
452 -
        let v = VStack::default()
448 +
        let mut v = VStack::default()
453 449
            .border(Some(Border::new(Color::Blue)))
454 450
            .padding(0)
455 451
            .child(Line::new("top"))
456 452
            .divider_cell(Cell::new("┄", Style::new(Color::Red)))
457 453
            .child(Line::new("bottom"));
477 473
        );
478 474
    }
479 475
480 476
    #[test]
481 477
    fn blank_adds_empty_widget_row() {
482 -
        let v = VStack::default()
478 +
        let mut v = VStack::default()
483 479
            .padding(0)
484 480
            .child(Line::new("top"))
485 481
            .blank()
486 482
            .child(Line::new("bottom"));
487 483
489 485
    }
490 486
491 487
    #[test]
492 488
    fn children_appends_boxed_widgets() {
493 489
        let children = vec![Line::new("one").boxed(), Line::new("two").boxed()];
494 -
        let v = VStack::default().padding(0).children(children);
490 +
        let mut v = VStack::default().padding(0).children(children);
495 491
496 492
        assert_eq!(v.display(Constraint::UNBOUNDED), "one\ntwo\n");
497 493
    }
498 494
499 495
    #[test]
500 496
    fn fill_child_absorbs_remaining_height() {
501 -
        let stack = VStack::default()
497 +
        let mut stack = VStack::default()
502 498
            .padding(0)
503 499
            .child(Line::new("top"))
504 500
            .fill(crate::Fill::new(".", crate::Style::default()));
505 501
        let constraint = Constraint::new(Size::new(5, 4), Size::new(5, 4));
506 502
527 523
        );
528 524
    }
529 525
530 526
    #[test]
531 527
    fn boxed_vstack_dispatches_widget_methods() {
532 -
        let boxed = VStack::default()
528 +
        let mut boxed = VStack::default()
533 529
            .padding(0)
534 530
            .child(Line::new("boxed"))
535 531
            .boxed();
536 532
537 533
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
538 534
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
539 535
    }
540 536
541 537
    #[test]
542 538
    fn bordered_helper_wraps_child_with_faint_border() {
543 -
        let v = bordered(Line::new("x")).padding(0);
539 +
        let mut v = bordered(Line::new("x")).padding(0);
544 540
        let mut buffer = Buffer::empty(Rect::from_size(v.size(Constraint::UNBOUNDED)));
545 541
546 542
        v.render(buffer.area(), &mut buffer);
547 543
548 544
        assert_eq!(buffer.lines(), vec!["╭─╮", "│x│", "╰─╯"]);
crates/tui-core/src/widget.rs +17 -18
5 5
//! `Block` that are broadly useful and do not belong to a more specific
6 6
//! layout or text module.
7 7
8 8
use std::fmt;
9 9
use std::fmt::Write as _;
10 -
use std::ops::Deref;
10 +
use std::ops::{Deref, DerefMut};
11 11
12 12
use crate::layout::Rect;
13 13
use crate::{Border, Buffer, Cell, Color, Constraint, Line, Paint, Size, Style};
14 14
15 15
/// Something that can render into a [`Buffer`].
16 16
pub trait Widget: fmt::Debug + Send {
17 17
    /// Returns the widget size under a parent constraint.
18 18
    fn size(&self, parent: Constraint) -> Size;
19 19
20 20
    /// Renders the widget into an area.
21 -
    fn render(&self, area: Rect, buf: &mut Buffer);
21 +
    fn render(&mut self, area: Rect, buf: &mut Buffer);
22 22
23 23
    /// Returns the number of columns occupied by this widget.
24 24
    fn columns(&self, parent: Constraint) -> usize {
25 25
        self.size(parent).cols
26 26
    }
29 29
    fn rows(&self, parent: Constraint) -> usize {
30 30
        self.size(parent).rows
31 31
    }
32 32
33 33
    /// Renders this widget into a fresh buffer sized from the given constraints.
34 -
    fn to_buffer(&self, constraints: Constraint) -> Buffer {
34 +
    fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
35 35
        let size = self.size(constraints);
36 36
        let area = Rect::from_size(size);
37 37
        let mut buffer = Buffer::empty(area);
38 38
39 39
        self.render(area, &mut buffer);
42 42
    }
43 43
44 44
    /// Returns this widget rendered as styled lines, one per row.
45 45
    ///
46 46
    /// The default implementation renders into a private buffer and reads each
47 -
    /// row back as a styled [`Line`]. Composite widgets that already produce
48 -
    /// row-shaped output should override this to skip the buffer round-trip.
49 -
    fn lines(&self, constraints: Constraint) -> Vec<Line> {
47 +
    /// row back as a styled [`Line`].
48 +
    fn lines(&mut self, constraints: Constraint) -> Vec<Line> {
50 49
        let buffer = self.to_buffer(constraints);
51 50
        let rows = buffer.area().rows;
52 51
53 52
        (0..rows).map(|row| buffer.styled_line(row)).collect()
54 53
    }
55 54
56 55
    /// Returns the first rendered row of this widget, or a blank line.
57 56
    ///
58 57
    /// Convenience for callers that compose single-row widgets and want a
59 58
    /// `Line` rather than a one-element `Vec<Line>`.
60 -
    fn to_line(&self, constraints: Constraint) -> Line {
59 +
    fn to_line(&mut self, constraints: Constraint) -> Line {
61 60
        self.lines(constraints)
62 61
            .into_iter()
63 62
            .next()
64 63
            .unwrap_or_default()
65 64
    }
66 65
67 66
    /// Returns a plain string representation of this widget.
68 67
    #[must_use]
69 -
    fn display(&self, constraints: Constraint) -> String {
68 +
    fn display(&mut self, constraints: Constraint) -> String {
70 69
        let buffer = self.to_buffer(constraints);
71 70
        let mut out = String::new();
72 71
73 72
        for line in buffer.lines() {
74 73
            out.push_str(&line);
77 76
        out
78 77
    }
79 78
80 79
    /// Returns a string representation with terminal styling escapes.
81 80
    #[must_use]
82 -
    fn display_styled(&self, constraints: Constraint) -> String {
81 +
    fn display_styled(&mut self, constraints: Constraint) -> String {
83 82
        let buffer = self.to_buffer(constraints);
84 83
        let area = buffer.area();
85 84
        let mut out = String::new();
86 85
87 86
        for y in area.y..area.bottom() {
102 101
impl Widget for Box<dyn Widget + '_> {
103 102
    fn size(&self, parent: Constraint) -> Size {
104 103
        self.deref().size(parent)
105 104
    }
106 105
107 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
108 -
        self.deref().render(area, buf);
106 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
107 +
        self.deref_mut().render(area, buf);
109 108
    }
110 109
}
111 110
112 -
impl<T: Widget + Sync + ?Sized> Widget for &T {
111 +
impl<T: Widget + ?Sized> Widget for &mut T {
113 112
    fn size(&self, parent: Constraint) -> Size {
114 -
        (*self).size(parent)
113 +
        (**self).size(parent)
115 114
    }
116 115
117 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
118 -
        (*self).render(area, buf);
116 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
117 +
        (**self).render(area, buf);
119 118
    }
120 119
}
121 120
122 121
/// Clears an area.
123 122
#[derive(Debug, Clone, Copy, Default)]
126 125
impl Widget for Clear {
127 126
    fn size(&self, parent: Constraint) -> Size {
128 127
        parent.bounded_size()
129 128
    }
130 129
131 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
130 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
132 131
        buf.fill(area, crate::buffer::Cell::blank());
133 132
    }
134 133
}
135 134
136 135
/// Fills an area with one glyph and style.
157 156
impl Widget for Fill {
158 157
    fn size(&self, parent: Constraint) -> Size {
159 158
        parent.bounded_size()
160 159
    }
161 160
162 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
161 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
163 162
        buf.fill(area, self.cell.clone());
164 163
    }
165 164
}
166 165
167 166
/// Bordered widget wrapper.
209 208
            size.rows = size.rows.saturating_add(2);
210 209
        }
211 210
        size.constrain(parent)
212 211
    }
213 212
214 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
213 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
215 214
        if area.is_empty() {
216 215
            return;
217 216
        }
218 217
        let Some(border) = self.border else {
219 218
            self.child.render(area, buf);
crates/tui-termion/src/term.rs +5 -2
57 57
        None
58 58
    }
59 59
}
60 60
61 61
/// Prints a widget to stdout.
62 -
pub fn print<W: Widget + ?Sized>(widget: &W) {
62 +
pub fn print<W: Widget + ?Sized>(widget: &mut W) {
63 63
    let constraint = stdout_constraint().unwrap_or_default();
64 64
65 65
    write_to_stdout(widget, constraint).ok();
66 66
}
67 67
68 68
/// Writes a widget to stdout under the given constraint.
69 -
pub fn write_to_stdout<W: Widget + ?Sized>(widget: &W, constraints: Constraint) -> io::Result<()> {
69 +
pub fn write_to_stdout<W: Widget + ?Sized>(
70 +
    widget: &mut W,
71 +
    constraints: Constraint,
72 +
) -> io::Result<()> {
70 73
    let mut stdout = io::stdout();
71 74
    for line in widget.display(constraints).lines() {
72 75
        writeln!(stdout, "{}", line.trim_end())?;
73 76
    }
74 77
    Ok(())
crates/tui-widgets/src/list.rs +25 -19
155 155
    /// Sets the vertical scrollbar style.
156 156
    pub fn scrollbar(mut self, style: ScrollbarStyle) -> Self {
157 157
        self.scrollbar = style;
158 158
        self
159 159
    }
160 -
}
161 -
162 -
impl Widget for List {
163 -
    fn size(&self, parent: Constraint) -> Size {
164 -
        Size::new(parent.max.cols, parent.max.rows).constrain(parent)
165 -
    }
166 160
167 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
168 -
        if area.is_empty() {
169 -
            return;
170 -
        }
161 +
    /// Returns the scroll view for non-empty list rows.
162 +
    fn scroll_view(&self, area: Rect) -> Option<ScrollView> {
171 163
        if self.lines.is_empty() {
172 -
            if let Some(line) = self.empty.clone() {
173 -
                let x = area.x + 1.min(area.cols);
174 -
                let y = area.y + 1.min(area.rows.saturating_sub(1));
175 -
                buf.set_line(x, y, &line.padded(area.right().saturating_sub(x)));
176 -
            }
177 -
            return;
164 +
            return None;
178 165
        }
179 166
180 167
        let selection = self.selected.map(Selection::at).unwrap_or_default();
181 168
        let view = if let Some(offset) = self.offset {
182 169
            View::new(offset, self.lines.len(), area.rows)
202 189
                        line.clone()
203 190
                    }
204 191
                })
205 192
                .collect()
206 193
        };
207 -
        let scroll = ScrollView::new(area, view.offset, rows).scrollbar(self.scrollbar.clone());
208 194
209 -
        scroll.render(area, buf);
195 +
        Some(ScrollView::new(area, view.offset, rows).scrollbar(self.scrollbar.clone()))
196 +
    }
197 +
}
198 +
199 +
impl Widget for List {
200 +
    fn size(&self, parent: Constraint) -> Size {
201 +
        Size::new(parent.max.cols, parent.max.rows).constrain(parent)
202 +
    }
203 +
204 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
205 +
        if area.is_empty() {
206 +
            return;
207 +
        }
208 +
        if let Some(mut scroll) = self.scroll_view(area) {
209 +
            scroll.render(area, buf);
210 +
        } else if let Some(line) = self.empty.clone() {
211 +
            let x = area.x + 1.min(area.cols);
212 +
            let y = area.y + 1.min(area.rows.saturating_sub(1));
213 +
            buf.set_line(x, y, &line.padded(area.right().saturating_sub(x)));
214 +
        }
210 215
    }
211 216
}
212 217
213 218
#[cfg(test)]
214 219
mod tests {
215 220
    use super::*;
221 +
    use tui_core::Buffer;
216 222
217 223
    #[test]
218 224
    fn selection_moves_with_clamped_bounds() {
219 225
        let mut selection = Selection::new();
220 226
227 233
        assert!(!selection.move_by(1, 0));
228 234
    }
229 235
230 236
    #[test]
231 237
    fn list_keeps_selection_visible_and_styles_row() {
232 -
        let list = List::new(["zero", "one", "two", "three"].into_iter().map(Line::new))
238 +
        let mut list = List::new(["zero", "one", "two", "three"].into_iter().map(Line::new))
233 239
            .selected(3)
234 240
            .placement(Placement::Minimal);
235 241
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 2));
236 242
237 243
        list.render(buffer.area(), &mut buffer);
crates/tui-widgets/src/scrollbar.rs +4 -4
104 104
            parent.max.rows
105 105
        };
106 106
        Size::new(1, rows).constrain(parent)
107 107
    }
108 108
109 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
109 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
110 110
        if area.is_empty() {
111 111
            return;
112 112
        }
113 113
        let thumb = self.thumb_range(area.rows);
114 114
133 133
134 134
#[cfg(test)]
135 135
mod tests {
136 136
    use super::*;
137 137
    use rustik_tui_core as tui_core;
138 -
    use tui_core::{Color, Style};
138 +
    use tui_core::{Buffer, Color, Style};
139 139
140 140
    #[test]
141 141
    fn thumb_range_is_empty_when_content_fits() {
142 142
        let scrollbar = Scrollbar::new(View::new(0, 3, 5));
143 143
159 159
    fn scrollbar_renders_track_and_thumb_glyphs() {
160 160
        let style = ScrollbarStyle::new(
161 161
            Cell::new("·", Style::new(Color::Unset)),
162 162
            Cell::new("█", Style::new(Color::Unset)),
163 163
        );
164 -
        let scrollbar = Scrollbar::new(View::new(40, 100, 20)).style(style);
164 +
        let mut scrollbar = Scrollbar::new(View::new(40, 100, 20)).style(style);
165 165
        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 5));
166 166
167 167
        scrollbar.render(buffer.area(), &mut buffer);
168 168
169 169
        assert_eq!(buffer.lines(), vec!["·", "·", "█", "·", "·"]);
173 173
    fn scrollbar_keeps_track_and_thumb_styles_separate() {
174 174
        let style = ScrollbarStyle::new(
175 175
            Cell::new("·", Style::new(Color::Fixed(236))),
176 176
            Cell::new("█", Style::new(Color::White)),
177 177
        );
178 -
        let scrollbar = Scrollbar::new(View::new(2, 10, 4)).style(style);
178 +
        let mut scrollbar = Scrollbar::new(View::new(2, 10, 4)).style(style);
179 179
        let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 4));
180 180
181 181
        scrollbar.render(buffer.area(), &mut buffer);
182 182
183 183
        assert_eq!(buffer.lines(), vec!["·", "█", "·", "·"]);
crates/tui-widgets/src/scrollview.rs +5 -5
132 132
impl Widget for ScrollView {
133 133
    fn size(&self, parent: Constraint) -> Size {
134 134
        Size::new(parent.max.cols, parent.max.rows).constrain(parent)
135 135
    }
136 136
137 -
    fn render(&self, area: Rect, buf: &mut Buffer) {
137 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
138 138
        if area.is_empty() {
139 139
            return;
140 140
        }
141 141
        let (text_area, scrollbar_area) = self.areas(area);
142 142
        let sticky_rows = self.sticky.len().min(text_area.rows);
167 167
}
168 168
169 169
#[cfg(test)]
170 170
mod tests {
171 171
    use super::*;
172 -
    use rustik_tui_core::{Cell, Color, Style};
172 +
    use rustik_tui_core::{Buffer, Cell, Color, Style};
173 173
174 174
    #[test]
175 175
    fn scrollbar_column_shows_track_only_when_content_fits() {
176 -
        let view = ScrollView::from_lines([Line::new("hello")]);
176 +
        let mut view = ScrollView::from_lines([Line::new("hello")]);
177 177
        let mut buffer = Buffer::empty(Rect::new(0, 0, 7, 2));
178 178
179 179
        view.render(buffer.area(), &mut buffer);
180 180
181 181
        // 6-col body + 1-col scrollbar; non-scrollable view paints track only.
185 185
    #[test]
186 186
    fn sticky_rows_pin_to_top_above_scrolled_body() {
187 187
        let lines = (0..6)
188 188
            .map(|i| Line::new(format!("row{i}")))
189 189
            .collect::<Vec<_>>();
190 -
        let view = ScrollView::from_lines(lines)
190 +
        let mut view = ScrollView::from_lines(lines)
191 191
            .offset(2)
192 192
            .sticky([Line::new("HEAD")]);
193 193
        let mut buffer = Buffer::empty(Rect::new(0, 0, 5, 3));
194 194
195 195
        view.render(buffer.area(), &mut buffer);
202 202
        let style = ScrollbarStyle::new(
203 203
            Cell::new("|", Style::new(Color::Unset)),
204 204
            Cell::new("#", Style::new(Color::Unset)),
205 205
        );
206 206
        let area = Rect::new(0, 0, 4, 2);
207 -
        let view = ScrollView::new(area, 1, |cols| {
207 +
        let mut view = ScrollView::new(area, 1, |cols| {
208 208
            (0..3)
209 209
                .map(|row| Line::new(format!("{row}:{cols}")))
210 210
                .collect()
211 211
        })
212 212
        .scrollbar(style);
crates/tui-widgets/src/viewport.rs +1 -0
320 320
}
321 321
322 322
#[cfg(test)]
323 323
mod tests {
324 324
    use super::*;
325 +
    use tui_core::Buffer;
325 326
326 327
    #[test]
327 328
    fn view_clamps_offset_and_reports_visible_range() {
328 329
        let view = View::new(8, 10, 4);
329 330
crates/tui/benches/render.rs +1 -1
13 13
    TableOptions, VStack, Widget,
14 14
};
15 15
16 16
const WORKLOAD: &str = "render";
17 17
const AREA: Rect = Rect::new(0, 0, 640, 480);
18 -
const DEFAULT_FRAMES: usize = 2_000;
18 +
const DEFAULT_FRAMES: usize = 500;
19 19
const LIST_ROWS: usize = 2_048;
20 20
const TABLE_ROWS: usize = 320;
21 21
const LOG_ROWS: usize = 4_096;
22 22
23 23
const ACTIVE_BORDER: Color = Color::Blue;