crates/tui-core/src/primitive.rs 19.4 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, char_width};
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
    /// Removes the first `width` terminal columns from this line.
267
    pub fn skip(&mut self, width: usize) {
268
        if width == 0 {
269
            return;
270
        }
271
        let mut remaining = width;
272
        let mut items = Vec::with_capacity(self.items.len());
273
        for label in std::mem::take(&mut self.items) {
274
            if remaining == 0 {
275
                items.push(label);
276
                continue;
277
            }
278
            let label_width = label.width();
279
            if label_width <= remaining {
280
                remaining -= label_width;
281
                continue;
282
            }
283
            let mut cols = 0;
284
            let mut boundary = 0;
285
            for (index, ch) in label.content().char_indices() {
286
                cols += char_width(ch);
287
                boundary = index + ch.len_utf8();
288
                if cols >= remaining {
289
                    break;
290
                }
291
            }
292
            items.push(Label::raw(
293
                label.content()[boundary..].to_owned(),
294
                label.paint.style,
295
            ));
296
            remaining = 0;
297
        }
298
        self.items = items;
299
    }
300
301
    /// Returns this line with one leading space and padding to the given width.
302
    pub fn inset(self, width: usize) -> Self {
303
        if width <= 2 {
304
            return self;
305
        }
306
        Line::new(" ").extend(self).padded(width)
307
    }
308
309
    /// Returns the actual column width of this line.
310
    pub fn width(&self) -> usize {
311
        self.items.iter().map(Text::width).sum()
312
    }
313
314
    /// Returns the labels that make up this line.
315
    pub fn labels(&self) -> &[Label] {
316
        &self.items
317
    }
318
319
    /// Returns a display adapter that writes styled text.
320
    pub const fn styled(&self) -> StyledLine<'_> {
321
        StyledLine { line: self }
322
    }
323
324
    /// Creates a line that contains a single space.
325
    pub fn space(mut self) -> Self {
326
        self.items.push(Label::space());
327
        self
328
    }
329
330
    /// Boxes this line as a [`Widget`].
331
    pub fn boxed(self) -> Box<dyn Widget> {
332
        Box::new(self)
333
    }
334
335
    /// Returns a filled line.
336
    pub fn filled(self, color: Color) -> Filled<Self> {
337
        Filled { item: self, color }
338
    }
339
340
    /// Renders line rows into a buffer area.
341
    pub fn renders(lines: impl IntoIterator<Item = Line>, area: Rect, buf: &mut Buffer) {
342
        for (row, mut line) in lines.into_iter().enumerate() {
343
            if row >= area.rows {
344
                break;
345
            }
346
            if line.width() > area.cols {
347
                Line::truncate(&mut line, area.cols, "…");
348
            }
349
            buf.set_line(area.x, area.y + row, &line);
350
        }
351
    }
352
}
353
354
impl IntoIterator for Line {
355
    type Item = Label;
356
    type IntoIter = vec::IntoIter<Label>;
357
358
    fn into_iter(self) -> Self::IntoIter {
359
        self.items.into_iter()
360
    }
361
}
362
363
impl<T: Into<Label>> From<T> for Line {
364
    fn from(value: T) -> Self {
365
        Self::new(value)
366
    }
367
}
368
369
impl From<Vec<Label>> for Line {
370
    fn from(items: Vec<Label>) -> Self {
371
        Self { items }
372
    }
373
}
374
375
impl Widget for Line {
376
    fn size(&self, _parent: Constraint) -> Size {
377
        Size::new(self.width(), 1)
378
    }
379
380
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
381
        Line::renders([self.clone()], area, buf);
382
    }
383
}
384
385
impl Widget for Vec<Line> {
386
    fn size(&self, _parent: Constraint) -> Size {
387
        let width = self.iter().map(Line::width).max().unwrap_or_default();
388
        let height = self.len();
389
390
        Size::new(width, height)
391
    }
392
393
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
394
        Line::renders(self.clone(), area, buf);
395
    }
396
}
397
398
impl fmt::Display for Line {
399
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400
        for item in &self.items {
401
            write!(f, "{item}")?;
402
        }
403
        Ok(())
404
    }
405
}
406
407
impl fmt::Display for StyledLine<'_> {
408
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409
        for item in &self.line.items {
410
            write!(f, "{}", item.paint.styled())?;
411
        }
412
        Ok(())
413
    }
414
}
415
416
/// Size of terminal content, in columns and rows.
417
#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
418
pub struct Size {
419
    /// Columns occupied.
420
    pub cols: usize,
421
    /// Rows occupied.
422
    pub rows: usize,
423
}
424
425
impl Size {
426
    /// Minimum size.
427
    pub const MIN: Self = Self {
428
        cols: usize::MIN,
429
        rows: usize::MIN,
430
    };
431
    /// Maximum size.
432
    pub const MAX: Self = Self {
433
        cols: usize::MAX,
434
        rows: usize::MAX,
435
    };
436
437
    /// Creates a new [`Size`].
438
    pub const fn new(cols: usize, rows: usize) -> Self {
439
        Self { cols, rows }
440
    }
441
442
    /// Constrain size.
443
    pub fn constrain(self, c: Constraint) -> Self {
444
        Self {
445
            cols: self.cols.clamp(c.min.cols, c.max.cols),
446
            rows: self.rows.clamp(c.min.rows, c.max.rows),
447
        }
448
    }
449
}
450
451
#[cfg(test)]
452
#[allow(clippy::unwrap_used)]
453
mod tests {
454
    use super::*;
455
456
    #[test]
457
    fn test_truncate() {
458
        let line = Line::default().item("banana").item("peach").item("apple");
459
460
        let mut actual = line.clone();
461
        Line::truncate(&mut actual, 9, "…");
462
        assert_eq!(actual.to_string(), "bananape…");
463
464
        let mut actual = line.clone();
465
        Line::truncate(&mut actual, 7, "…");
466
        assert_eq!(actual.to_string(), "banana…");
467
468
        let mut actual = line.clone();
469
        Line::truncate(&mut actual, 1, "…");
470
        assert_eq!(actual.to_string(), "…");
471
472
        let mut actual = line;
473
        Line::truncate(&mut actual, 0, "…");
474
        assert_eq!(actual.to_string(), "");
475
    }
476
477
    #[test]
478
    fn truncate_marks_hidden_text_across_labels() {
479
        let line = Line::default().item("foo").item(",").item(" ").item("bar");
480
481
        let mut actual = line;
482
        Line::truncate(&mut actual, 5, "…");
483
        assert_eq!(actual.to_string(), "foo,…");
484
    }
485
486
    #[test]
487
    fn truncate_omits_marker_for_hidden_trailing_space_across_labels() {
488
        let line = Line::default().item("foo").item("   ");
489
490
        let mut actual = line;
491
        Line::truncate(&mut actual, 5, "…");
492
        assert_eq!(actual.to_string(), "foo ");
493
    }
494
495
    #[test]
496
    fn test_width() {
497
        // Nb. This might not display correctly in some editors or terminals.
498
        let line = Line::new("Radicle Heartwood Protocol & Stack ❤️🪵");
499
        assert_eq!(line.width(), 39, "{line}");
500
        let line = Line::new("❤\u{fe0f}");
501
        assert_eq!(line.width(), 2, "{line}");
502
        let line = Line::new("❤️");
503
        assert_eq!(line.width(), 2, "{line}");
504
    }
505
506
    #[test]
507
    fn test_spaced() {
508
        let line = Line::spaced(["banana", "peach", "apple"].into_iter().map(Label::new));
509
510
        let iterated: Vec<_> = line.into_iter().collect();
511
        assert_eq!(
512
            iterated
513
                .into_iter()
514
                .map(|l| l.to_string())
515
                .collect::<Vec<_>>(),
516
            ["banana", " ", "peach", " ", "apple"]
517
        );
518
    }
519
520
    #[test]
521
    fn spaced_ignores_blank_labels() {
522
        let line = Line::spaced([Label::new("banana"), Label::blank(), Label::new("apple")]);
523
524
        assert_eq!(line.to_string(), "banana apple");
525
    }
526
527
    #[test]
528
    fn overlay_ranges_splits_labels_at_boundaries() {
529
        // Single label "hello world", overlay bg on bytes 0..5 ("hello").
530
        let line = Line::new(Label::new("hello world").fg(Color::Red));
531
        #[allow(clippy::single_range_in_vec_init)]
532
        let overlaid = line.overlay_ranges(&[0..5], Style::default().bg(Color::Blue));
533
        let labels = overlaid.labels();
534
        assert_eq!(labels.len(), 2);
535
        assert_eq!(labels[0].content(), "hello");
536
        assert_eq!(labels[0].paint.style.fg_color(), Color::Red);
537
        assert_eq!(labels[0].paint.style.bg_color(), Color::Blue);
538
        assert_eq!(labels[1].content(), " world");
539
        assert_eq!(labels[1].paint.style.fg_color(), Color::Red);
540
        assert_eq!(labels[1].paint.style.bg_color(), Color::Unset);
541
    }
542
543
    #[test]
544
    fn overlay_ranges_spans_label_boundaries() {
545
        // Range crosses two labels: "ab" + "cd", overlay 1..3 → covers "b"+"c".
546
        let line = Line::default()
547
            .item(Label::new("ab"))
548
            .item(Label::new("cd"));
549
        #[allow(clippy::single_range_in_vec_init)]
550
        let overlaid = line.overlay_ranges(&[1..3], Style::default().bg(Color::Green));
551
        let labels = overlaid.labels();
552
        let text: Vec<_> = labels.iter().map(|l| l.content()).collect();
553
        let bgs: Vec<_> = labels.iter().map(|l| l.paint.style.bg_color()).collect();
554
        assert_eq!(text, ["a", "b", "c", "d"]);
555
        assert_eq!(
556
            bgs,
557
            [Color::Unset, Color::Green, Color::Green, Color::Unset]
558
        );
559
    }
560
561
    #[test]
562
    fn overlay_ranges_empty_returns_unchanged() {
563
        let line = Line::new(Label::new("hello"));
564
        let overlaid = line.overlay_ranges(&[], Style::default().bg(Color::Blue));
565
        assert_eq!(overlaid.labels().len(), 1);
566
        assert_eq!(overlaid.labels()[0].content(), "hello");
567
        assert_eq!(overlaid.labels()[0].paint.style.bg_color(), Color::Unset);
568
    }
569
570
    #[test]
571
    fn line_styled_adapter_formats_label_styles_explicitly() {
572
        let mut line =
573
            Line::new(Label::new("x").fg(Color::Red)).item(Label::new("y").fg(Color::Blue));
574
575
        assert_eq!(line.to_string(), "xy");
576
        assert_eq!(
577
            line.styled().to_string(),
578
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m"
579
        );
580
        assert_eq!(
581
            Widget::display_styled(&mut line, Constraint::UNBOUNDED),
582
            "\x1B[31mx\x1B[0m\x1B[34my\x1B[0m\n"
583
        );
584
    }
585
586
    #[test]
587
    fn line_pad_uses_last_label_background() {
588
        let mut line = Line::new(Label::new("x").bg(Color::Red));
589
590
        Line::pad(&mut line, 3);
591
592
        let labels = line.into_iter().collect::<Vec<_>>();
593
        assert_eq!(labels.len(), 2);
594
        assert_eq!(labels[1].content(), "  ");
595
        assert_eq!(labels[1].background(), Color::Red);
596
    }
597
598
    #[test]
599
    fn line_value_helpers_pad_truncate_and_inset() {
600
        assert_eq!(Line::new("x").padded(3).to_string(), "x  ");
601
        assert_eq!(Line::new("abcdef").truncated(4, "…").to_string(), "abc…");
602
        assert_eq!(Line::new("x").inset(4).to_string(), " x  ");
603
    }
604
605
    #[test]
606
    fn line_boxed_dispatches_widget_methods() {
607
        let line = Line::new("boxed");
608
        let mut boxed = line.boxed();
609
610
        assert_eq!(boxed.size(Constraint::UNBOUNDED), Size::new(5, 1));
611
        assert_eq!(boxed.display(Constraint::UNBOUNDED), "boxed\n");
612
    }
613
614
    #[test]
615
    fn mutable_widget_reference_dispatches_widget_methods() {
616
        let mut line = Line::new("ref");
617
        let reference = &mut line;
618
619
        assert_eq!(reference.size(Constraint::UNBOUNDED), Size::new(3, 1));
620
        assert_eq!(reference.display(Constraint::UNBOUNDED), "ref\n");
621
    }
622
623
    #[test]
624
    fn vec_line_widget_size_uses_widest_line_and_line_count() {
625
        let mut lines = vec![Line::new("short"), Line::new("longer")];
626
627
        assert_eq!(lines.size(Constraint::UNBOUNDED), Size::new(6, 2));
628
        assert_eq!(lines.display(Constraint::UNBOUNDED), "short \nlonger\n");
629
    }
630
631
    #[test]
632
    fn size_and_constraint_helpers_clamp_dimensions() {
633
        let constraint = Constraint::new(Size::new(2, 3), Size::new(5, 7));
634
635
        assert_eq!(Size::new(1, 9).constrain(constraint), Size::new(2, 7));
636
        assert_eq!(
637
            Constraint::max(Size::new(4, 8)),
638
            Constraint {
639
                min: Size::MIN,
640
                max: Size::new(4, 8),
641
            }
642
        );
643
        assert_eq!(
644
            Constraint::tight(6),
645
            Constraint {
646
                min: Size::new(6, 1),
647
                max: Size::new(6, usize::MAX),
648
            }
649
        );
650
    }
651
}