crates/tui-core/src/label.rs 5.5 KiB raw
1
//! Single styled text segment.
2
//!
3
//! `Label` is the smallest styled text unit used by [`Line`](crate::Line) and
4
//! text widgets. It combines string content with paint/style metadata while
5
//! still supporting width-aware truncation and padding.
6
7
use std::fmt;
8
9
use super::{Buffer, Color, Constraint, Filled, Line, Paint, Size, Style, Widget, cell::Text};
10
11
/// A styled string that does not contain any `'\n'` and implements [`Widget`] and [`Text`].
12
#[derive(Clone, Default, Debug)]
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
}
38
39
impl Label {
40
    /// Creates a new label.
41
    pub fn new(s: &str) -> Self {
42
        Self::raw(clean(s.to_owned()), Style::default())
43
    }
44
45
    /// Creates a new label from one character.
46
    pub fn from_char(ch: char) -> Self {
47
        Self::from(ch.to_string())
48
    }
49
50
    /// Creates a blank label.
51
    pub fn blank() -> Self {
52
        Self::raw(String::new(), Style::default())
53
    }
54
55
    /// Returns whether this label is empty.
56
    pub fn is_blank(&self) -> bool {
57
        self.content().is_empty()
58
    }
59
60
    /// Returns unstyled content.
61
    pub fn content(&self) -> &str {
62
        self.paint.content()
63
    }
64
65
    /// Creates a single-space label.
66
    pub fn space() -> Self {
67
        Self::raw(String::from(" "), Style::default())
68
    }
69
70
    /// Color the label's foreground.
71
    pub fn fg(self, color: Color) -> Self {
72
        Self {
73
            paint: self.paint.fg(color),
74
            metrics: self.metrics,
75
        }
76
    }
77
78
    /// Color the label's background.
79
    pub fn bg(self, color: Color) -> Self {
80
        Self {
81
            paint: self.paint.bg(color),
82
            metrics: self.metrics,
83
        }
84
    }
85
86
    /// Styles the label.
87
    pub fn style(self, style: Style) -> Self {
88
        let style = self.paint.style.merge(style);
89
        Self {
90
            paint: self.paint.with_style(style),
91
            metrics: self.metrics,
92
        }
93
    }
94
95
    /// Returns this label with a fill background.
96
    pub fn filled(self, color: Color) -> Filled<Self> {
97
        Filled { item: self, color }
98
    }
99
100
    /// Wraps this label into a line.
101
    pub fn to_line(self) -> Line {
102
        Line::from(self)
103
    }
104
105
    /// Returns whether the label content is printable ASCII.
106
    pub(crate) const fn is_ascii(&self) -> bool {
107
        self.metrics.ascii
108
    }
109
110
    /// Creates a label from content that has already been cleaned.
111
    pub(crate) fn raw(content: String, style: Style) -> Self {
112
        Self {
113
            metrics: LabelMetrics::new(&content),
114
            paint: Paint {
115
                item: content,
116
                style,
117
            },
118
        }
119
    }
120
}
121
122
impl Widget for Label {
123
    fn size(&self, _parent: Constraint) -> Size {
124
        Size::new(self.metrics.width, 1)
125
    }
126
127
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
128
        Line::renders([Line::new(self.clone())], area, buf);
129
    }
130
}
131
132
impl fmt::Display for Label {
133
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134
        fmt::Display::fmt(&self.paint, f)
135
    }
136
}
137
138
impl Text for Label {
139
    type Padded = Self;
140
    type Truncated = Self;
141
142
    fn background(&self) -> Color {
143
        self.paint.style.background
144
    }
145
146
    fn pad(&self, width: usize) -> Self::Padded {
147
        Self::from(self.paint.pad(width))
148
    }
149
150
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
151
        Self::from(self.paint.truncate(width, delim))
152
    }
153
154
    fn width(&self) -> usize {
155
        self.metrics.width
156
    }
157
}
158
159
impl<D: fmt::Display> From<Paint<D>> for Label {
160
    fn from(paint: Paint<D>) -> Self {
161
        Self::raw(clean(format!("{}", paint.item)), paint.style)
162
    }
163
}
164
165
impl From<String> for Label {
166
    fn from(value: String) -> Self {
167
        Self::raw(clean(value), Style::default())
168
    }
169
}
170
171
impl From<&str> for Label {
172
    fn from(value: &str) -> Self {
173
        Self::new(value)
174
    }
175
}
176
177
/// Creates a new label from a [`Paint`] object.
178
pub fn label(s: impl Into<Paint<String>>) -> Label {
179
    Label::from(s.into())
180
}
181
182
/// Escapes control characters that a terminal could interpret.
183
fn clean(input: String) -> String {
184
    if !input.chars().any(|ch| ch.is_control() && ch != '\t') {
185
        return input;
186
    }
187
    let mut cleaned = String::with_capacity(input.len());
188
    for ch in input.chars() {
189
        if ch.is_control() && ch != '\t' {
190
            cleaned.extend(ch.escape_default());
191
        } else {
192
            cleaned.push(ch);
193
        }
194
    }
195
    cleaned
196
}
197
198
#[cfg(test)]
199
mod tests {
200
    use super::*;
201
202
    #[test]
203
    fn style_merges_with_existing_label_colors() {
204
        let label = Label::new("x")
205
            .fg(Color::White)
206
            .bg(Color::Blue)
207
            .style(Style::default().bold());
208
209
        assert_eq!(label.paint.style().fg_color(), Color::White);
210
        assert_eq!(label.paint.style().bg_color(), Color::Blue);
211
    }
212
213
    #[test]
214
    fn control_characters_are_visible() {
215
        let label = Label::new("tab\tline\nescape\x1b");
216
217
        assert_eq!(label.content(), "tab\tline\\nescape\\u{1b}");
218
    }
219
}