crates/tui-core/src/primitive.rs 18.3 KiB raw
1
//! Core text-line and sizing primitives.
2
//!
3
//! `Constraint`, `Size`, and `Line` are the shared building blocks most widgets
4
//! depend on. This module keeps text-line composition and basic widget sizing
5
//! close together because width-aware rendering needs both.
6
7
use std::fmt;
8
use std::ops::Range;
9
use std::vec;
10
11
use super::cell::Text;
12
use crate::widget::Widget;
13
14
use super::{Buffer, Color, Filled, Label, Rect, Style};
15
16
/// Rendering constraint.
17
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
18
pub struct Constraint {
19
    /// Minimum space the widget can take.
20
    pub min: Size,
21
    /// Maximum space the widget can take.
22
    pub max: Size,
23
}
24
25
impl Default for Constraint {
26
    fn default() -> Self {
27
        Self::UNBOUNDED
28
    }
29
}
30
31
impl Constraint {
32
    /// Can satisfy any size of object.
33
    pub const UNBOUNDED: Self = Self {
34
        min: Size::MIN,
35
        max: Size::MAX,
36
    };
37
38
    /// Creates a new constraint.
39
    pub fn new(min: Size, max: Size) -> Self {
40
        assert!(min.cols <= max.cols && min.rows <= max.rows);
41
42
        Self { min, max }
43
    }
44
45
    /// A constraint with only a maximum size.
46
    pub fn max(max: Size) -> Self {
47
        Self {
48
            min: Size::MIN,
49
            max,
50
        }
51
    }
52
53
    /// A constraint that can only be satisfied by a single column size.
54
    /// The rows are unconstrained.
55
    pub fn tight(cols: usize) -> Self {
56
        Self {
57
            min: Size::new(cols, 1),
58
            max: Size::new(cols, usize::MAX),
59
        }
60
    }
61
62
    /// Returns a finite size that satisfies this constraint.
63
    pub fn bounded_size(self) -> Size {
64
        Size::new(
65
            bounded(self.min.cols, self.max.cols),
66
            bounded(self.min.rows, self.max.rows),
67
        )
68
        .constrain(self)
69
    }
70
}
71
72
/// Chooses a finite bound from a minimum and maximum constraint.
73
fn bounded(min: usize, max: usize) -> usize {
74
    if max == usize::MAX { min } else { max }
75
}
76
77
/// A line of text that has styling and can be displayed.
78
#[derive(Clone, Default, Debug)]
79
pub struct Line {
80
    items: Vec<Label>,
81
}
82
83
/// A line display adapter that writes styled text.
84
pub struct StyledLine<'a> {
85
    line: &'a Line,
86
}
87
88
impl Line {
89
    /// Creates a new line.
90
    pub fn new(item: impl Into<Label>) -> Self {
91
        Self {
92
            items: vec![item.into()],
93
        }
94
    }
95
96
    /// Creates a blank line.
97
    pub fn blank() -> Self {
98
        Self::default()
99
    }
100
101
    /// Returns a styled line by styling all its labels.
102
    pub fn style(self, style: Style) -> Line {
103
        Self {
104
            items: self
105
                .items
106
                .into_iter()
107
                .map(|l| {
108
                    let style = l.paint.style().merge(style);
109
                    l.style(style)
110
                })
111
                .collect(),
112
        }
113
    }
114
115
    /// Returns this line with `style` overlaid on the byte ranges in `ranges`.
116
    ///
117
    /// Labels are split at range boundaries; in-range sub-labels are styled as
118
    /// `style.merge(original)` (see [`Style::merge`]), and out-of-range parts
119
    /// keep their original style. Byte indices are counted across the line's
120
    /// labels in order.
121
    ///
122
    /// `ranges` must be sorted and disjoint. Indices that fall outside any
123
    /// label are ignored.
124
    pub fn overlay_ranges(self, ranges: &[Range<usize>], style: Style) -> Self {
125
        if ranges.is_empty() {
126
            return self;
127
        }
128
        let mut out: Vec<Label> = Vec::new();
129
        let mut ranges = ranges.iter().peekable();
130
        let mut cursor: usize = 0;
131
132
        for label in self.items {
133
            let content = label.content();
134
            if content.is_empty() {
135
                out.push(label);
136
                continue;
137
            }
138
            let label_start = cursor;
139
            let label_end = cursor + content.len();
140
            cursor = label_end;
141
142
            let mut pos = label_start;
143
            while pos < label_end {
144
                while ranges.peek().is_some_and(|range| range.end <= pos) {
145
                    ranges.next();
146
                }
147
                let (next, in_range) = match ranges.peek() {
148
                    Some(range) if range.start <= pos => (range.end.min(label_end), true),
149
                    Some(range) => (range.start.min(label_end), false),
150
                    None => (label_end, false),
151
                };
152
                let sub_start = pos - label_start;
153
                let sub_end = next - label_start;
154
155
                if let Some(text) = content.get(sub_start..sub_end) {
156
                    let sub_style = if in_range {
157
                        style.merge(label.paint.style)
158
                    } else {
159
                        label.paint.style
160
                    };
161
                    out.push(Label::raw(text.to_owned(), sub_style));
162
                }
163
                pos = next;
164
            }
165
        }
166
        Self { items: out }
167
    }
168
169
    /// Returns a line with a single space between the given labels.
170
    // TODO: Use [`Iterator::intersperse`] when MSRV is updated.
171
    pub fn spaced(items: impl IntoIterator<Item = Label>) -> Self {
172
        let items = items.into_iter();
173
        let mut line = Self {
174
            items: Vec::with_capacity(items.size_hint().1.unwrap_or_default().saturating_mul(2)),
175
        };
176
177
        // Don't create spaces around empty labels.
178
        for item in items.filter(|i| !i.is_blank()) {
179
            line.push(item);
180
            line.push(Label::space());
181
        }
182
        line.items.pop();
183
        line
184
    }
185
186
    /// Adds an item to this line.
187
    pub fn item(mut self, item: impl Into<Label>) -> Self {
188
        self.push(item);
189
        self
190
    }
191
192
    /// Adds multiple items to this line.
193
    pub fn extend(mut self, items: impl IntoIterator<Item = Label>) -> Self {
194
        self.items.extend(items);
195
        self
196
    }
197
198
    /// Adds an item to this line.
199
    pub fn push(&mut self, item: impl Into<Label>) {
200
        self.items.push(item.into());
201
    }
202
203
    /// Pad this line to occupy the given width.
204
    pub fn pad(&mut self, width: usize) {
205
        let w = self.width();
206
207
        if width > w {
208
            let pad = width - w;
209
            let bg = self.items.last().map_or(Color::Unset, Label::background);
210
            self.items.push(Label::new(" ".repeat(pad).as_str()).bg(bg));
211
        }
212
    }
213
214
    /// Returns this line padded to occupy the given width.
215
    pub fn padded(mut self, width: usize) -> Self {
216
        Line::pad(&mut self, width);
217
        self
218
    }
219
220
    /// Truncate this line to the given width.
221
    pub fn truncate(&mut self, width: usize, delim: &str) {
222
        let delim_width = delim.width();
223
        let mut hidden_text = false;
224
225
        while self.width() > width {
226
            let total = self.width();
227
228
            if total - self.items.last().map_or(0, Text::width) > width {
229
                if let Some(item) = self.items.pop() {
230
                    hidden_text |= !item.content().trim().is_empty();
231
                }
232
            } else if let Some(item) = self.items.last_mut() {
233
                let original = item.clone();
234
                *item = item.truncate(width - (total - Text::width(item)), delim);
235
236
                if !item.content().ends_with(delim) {
237
                    let hidden = original
238
                        .content()
239
                        .strip_prefix(item.content())
240
                        .unwrap_or_else(|| original.content());
241
                    hidden_text |= !hidden.trim().is_empty();
242
                }
243
            }
244
        }
245
246
        if delim.is_empty()
247
            || delim_width > width
248
            || !hidden_text
249
            || self
250
                .items
251
                .last()
252
                .is_some_and(|item| item.content().ends_with(delim))
253
        {
254
            return;
255
        }
256
        Line::truncate(self, width - delim_width, "");
257
        self.push(Label::new(delim));
258
    }
259
260
    /// Returns this line truncated to the given width.
261
    pub fn truncated(mut self, width: usize, delim: &str) -> Self {
262
        Line::truncate(&mut self, width, delim);
263
        self
264
    }
265
266
    /// Returns this line with one leading space and padding to the given width.
267
    pub fn inset(self, width: usize) -> Self {
268
        if width <= 2 {
269
            return self;
270
        }
271
        Line::new(" ").extend(self).padded(width)
272
    }
273
274
    /// Returns the actual column width of this line.
275
    pub fn width(&self) -> usize {
276
        self.items.iter().map(Text::width).sum()
277
    }
278
279
    /// Returns the labels that make up this line.
280
    pub fn labels(&self) -> &[Label] {
281
        &self.items
282
    }
283
284
    /// Returns a display adapter that writes styled text.
285
    pub const fn styled(&self) -> StyledLine<'_> {
286
        StyledLine { line: self }
287
    }
288
289
    /// Creates a line that contains a single space.
290
    pub fn space(mut self) -> Self {
291
        self.items.push(Label::space());
292
        self
293
    }
294
295
    /// Boxes this line as a [`Widget`].
296
    pub fn boxed(self) -> Box<dyn Widget> {
297
        Box::new(self)
298
    }
299
300
    /// Returns a filled line.
301
    pub fn filled(self, color: Color) -> Filled<Self> {
302
        Filled { item: self, color }
303
    }
304
305
    /// Renders line rows into a buffer area.
306
    pub fn renders(lines: impl IntoIterator<Item = Line>, area: Rect, buf: &mut Buffer) {
307
        for (row, mut line) in lines.into_iter().enumerate() {
308
            if row >= area.rows {
309
                break;
310
            }
311
            if line.width() > area.cols {
312
                Line::truncate(&mut line, area.cols, "…");
313
            }
314
            buf.set_line(area.x, area.y + row, &line);
315
        }
316
    }
317
}
318
319
impl IntoIterator for Line {
320
    type Item = Label;
321
    type IntoIter = vec::IntoIter<Label>;
322
323
    fn into_iter(self) -> Self::IntoIter {
324
        self.items.into_iter()
325
    }
326
}
327
328
impl<T: Into<Label>> From<T> for Line {
329
    fn from(value: T) -> Self {
330
        Self::new(value)
331
    }
332
}
333
334
impl From<Vec<Label>> for Line {
335
    fn from(items: Vec<Label>) -> Self {
336
        Self { items }
337
    }
338
}
339
340
impl Widget for Line {
341
    fn size(&self, _parent: Constraint) -> Size {
342
        Size::new(self.width(), 1)
343
    }
344
345
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
346
        Line::renders([self.clone()], area, buf);
347
    }
348
}
349
350
impl Widget for Vec<Line> {
351
    fn size(&self, _parent: Constraint) -> Size {
352
        let width = self.iter().map(Line::width).max().unwrap_or_default();
353
        let height = self.len();
354
355
        Size::new(width, height)
356
    }
357
358
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
359
        Line::renders(self.clone(), area, buf);
360
    }
361
}
362
363
impl fmt::Display for Line {
364
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365
        for item in &self.items {
366
            write!(f, "{item}")?;
367
        }
368
        Ok(())
369
    }
370
}
371
372
impl fmt::Display for StyledLine<'_> {
373
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374
        for item in &self.line.items {
375
            write!(f, "{}", item.paint.styled())?;
376
        }
377
        Ok(())
378
    }
379
}
380
381
/// Size of terminal content, in columns and rows.
382
#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
383
pub struct Size {
384
    /// Columns occupied.
385
    pub cols: usize,
386
    /// Rows occupied.
387
    pub rows: usize,
388
}
389
390
impl Size {
391
    /// Minimum size.
392
    pub const MIN: Self = Self {
393
        cols: usize::MIN,
394
        rows: usize::MIN,
395
    };
396
    /// Maximum size.
397
    pub const MAX: Self = Self {
398
        cols: usize::MAX,
399
        rows: usize::MAX,
400
    };
401
402
    /// Creates a new [`Size`].
403
    pub const fn new(cols: usize, rows: usize) -> Self {
404
        Self { cols, rows }
405
    }
406
407
    /// Constrain size.
408
    pub fn constrain(self, c: Constraint) -> Self {
409
        Self {
410
            cols: self.cols.clamp(c.min.cols, c.max.cols),
411
            rows: self.rows.clamp(c.min.rows, c.max.rows),
412
        }
413
    }
414
}
415
416
#[cfg(test)]
417
#[allow(clippy::unwrap_used)]
418
mod tests {
419
    use super::*;
420
421
    #[test]
422
    fn test_truncate() {
423
        let line = Line::default().item("banana").item("peach").item("apple");
424
425
        let mut actual = line.clone();
426
        Line::truncate(&mut actual, 9, "…");
427
        assert_eq!(actual.to_string(), "bananape…");
428
429
        let mut actual = line.clone();
430
        Line::truncate(&mut actual, 7, "…");
431
        assert_eq!(actual.to_string(), "banana…");
432
433
        let mut actual = line.clone();
434
        Line::truncate(&mut actual, 1, "…");
435
        assert_eq!(actual.to_string(), "…");
436
437
        let mut actual = line;
438
        Line::truncate(&mut actual, 0, "…");
439
        assert_eq!(actual.to_string(), "");
440
    }
441
442
    #[test]
443
    fn truncate_marks_hidden_text_across_labels() {
444
        let line = Line::default().item("foo").item(",").item(" ").item("bar");
445
446
        let mut actual = line;
447
        Line::truncate(&mut actual, 5, "…");
448
        assert_eq!(actual.to_string(), "foo,…");
449
    }
450
451
    #[test]
452
    fn truncate_omits_marker_for_hidden_trailing_space_across_labels() {
453
        let line = Line::default().item("foo").item("   ");
454
455
        let mut actual = line;
456
        Line::truncate(&mut actual, 5, "…");
457
        assert_eq!(actual.to_string(), "foo ");
458
    }
459
460
    #[test]
461
    fn test_width() {
462
        // Nb. This might not display correctly in some editors or terminals.
463
        let line = Line::new("Radicle Heartwood Protocol & Stack ❤️🪵");
464
        assert_eq!(line.width(), 39, "{line}");
465
        let line = Line::new("❤\u{fe0f}");
466
        assert_eq!(line.width(), 2, "{line}");
467
        let line = Line::new("❤️");
468
        assert_eq!(line.width(), 2, "{line}");
469
    }
470
471
    #[test]
472
    fn test_spaced() {
473
        let line = Line::spaced(["banana", "peach", "apple"].into_iter().map(Label::new));
474
475
        let iterated: Vec<_> = line.into_iter().collect();
476
        assert_eq!(
477
            iterated
478
                .into_iter()
479
                .map(|l| l.to_string())
480
                .collect::<Vec<_>>(),
481
            ["banana", " ", "peach", " ", "apple"]
482
        );
483
    }
484
485
    #[test]
486
    fn spaced_ignores_blank_labels() {
487
        let line = Line::spaced([Label::new("banana"), Label::blank(), Label::new("apple")]);
488
489
        assert_eq!(line.to_string(), "banana apple");
490
    }
491
492
    #[test]
493
    fn overlay_ranges_splits_labels_at_boundaries() {
494
        // Single label "hello world", overlay bg on bytes 0..5 ("hello").
495
        let line = Line::new(Label::new("hello world").fg(Color::Red));
496
        #[allow(clippy::single_range_in_vec_init)]
497
        let overlaid = line.overlay_ranges(&[0..5], Style::default().bg(Color::Blue));
498
        let labels = overlaid.labels();
499
        assert_eq!(labels.len(), 2);
500
        assert_eq!(labels[0].content(), "hello");
501
        assert_eq!(labels[0].paint.style.fg_color(), Color::Red);
502
        assert_eq!(labels[0].paint.style.bg_color(), Color::Blue);
503
        assert_eq!(labels[1].content(), " world");
504
        assert_eq!(labels[1].paint.style.fg_color(), Color::Red);
505
        assert_eq!(labels[1].paint.style.bg_color(), Color::Unset);
506
    }
507
508
    #[test]
509
    fn overlay_ranges_spans_label_boundaries() {
510
        // Range crosses two labels: "ab" + "cd", overlay 1..3 → covers "b"+"c".
511
        let line = Line::default()
512
            .item(Label::new("ab"))
513
            .item(Label::new("cd"));
514
        #[allow(clippy::single_range_in_vec_init)]
515
        let overlaid = line.overlay_ranges(&[1..3], Style::default().bg(Color::Green));
516
        let labels = overlaid.labels();
517
        let text: Vec<_> = labels.iter().map(|l| l.content()).collect();
518
        let bgs: Vec<_> = labels.iter().map(|l| l.paint.style.bg_color()).collect();
519
        assert_eq!(text, ["a", "b", "c", "d"]);
520
        assert_eq!(
521
            bgs,
522
            [Color::Unset, Color::Green, Color::Green, Color::Unset]
523
        );
524
    }
525
526
    #[test]
527
    fn overlay_ranges_empty_returns_unchanged() {
528
        let line = Line::new(Label::new("hello"));
529
        let overlaid = line.overlay_ranges(&[], Style::default().bg(Color::Blue));
530
        assert_eq!(overlaid.labels().len(), 1);
531
        assert_eq!(overlaid.labels()[0].content(), "hello");
532
        assert_eq!(overlaid.labels()[0].paint.style.bg_color(), Color::Unset);
533
    }
534
535
    #[test]
536
    fn line_styled_adapter_formats_label_styles_explicitly() {
537
        let mut line =
538
            Line::new(Label::new("x").fg(Color::Red)).item(Label::new("y").fg(Color::Blue));
539
540
        assert_eq!(line.to_string(), "xy");
541
        assert_eq!(
542
            line.styled().to_string(),
543
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m"
544
        );
545
        assert_eq!(
546
            Widget::display_styled(&mut line, Constraint::UNBOUNDED),
547
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m\n"
548
        );
549
    }
550
551
    #[test]
552
    fn line_pad_uses_last_label_background() {
553
        let mut line = Line::new(Label::new("x").bg(Color::Red));
554
555
        Line::pad(&mut line, 3);
556
557
        let labels = line.into_iter().collect::<Vec<_>>();
558
        assert_eq!(labels.len(), 2);
559
        assert_eq!(labels[1].content(), "  ");
560
        assert_eq!(labels[1].background(), Color::Red);
561
    }
562
563
    #[test]
564
    fn line_value_helpers_pad_truncate_and_inset() {
565
        assert_eq!(Line::new("x").padded(3).to_string(), "x  ");
566
        assert_eq!(Line::new("abcdef").truncated(4, "…").to_string(), "abc…");
567
        assert_eq!(Line::new("x").inset(4).to_string(), " x  ");
568
    }
569
570
    #[test]
571
    fn line_boxed_dispatches_widget_methods() {
572
        let line = Line::new("boxed");
573
        let mut boxed = line.boxed();
574
575
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
576
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
577
    }
578
579
    #[test]
580
    fn mutable_widget_reference_dispatches_widget_methods() {
581
        let mut line = Line::new("ref");
582
        let reference = &mut line;
583
584
        assert_eq!(reference.size(Constraint::UNBOUNDED), Size::new(3, 1));
585
        assert_eq!(reference.display(Constraint::UNBOUNDED), "ref\n");
586
    }
587
588
    #[test]
589
    fn vec_line_widget_size_uses_widest_line_and_line_count() {
590
        let mut lines = vec![Line::new("short"), Line::new("longer")];
591
592
        assert_eq!(lines.size(Constraint::UNBOUNDED), Size::new(6, 2));
593
        assert_eq!(lines.display(Constraint::UNBOUNDED), "short \nlonger\n");
594
    }
595
596
    #[test]
597
    fn size_and_constraint_helpers_clamp_dimensions() {
598
        let constraint = Constraint::new(Size::new(2, 3), Size::new(5, 7));
599
600
        assert_eq!(Size::new(1, 9).constrain(constraint), Size::new(2, 7));
601
        assert_eq!(
602
            Constraint::max(Size::new(4, 8)),
603
            Constraint {
604
                min: Size::MIN,
605
                max: Size::new(4, 8),
606
            }
607
        );
608
        assert_eq!(
609
            Constraint::tight(6),
610
            Constraint {
611
                min: Size::new(6, 1),
612
                max: Size::new(6, usize::MAX),
613
            }
614
        );
615
    }
616
}