crates/tui-core/src/label.rs 5.2 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
        let content = if matches!(ch, '\n' | '\r') {
48
            String::new()
49
        } else {
50
            ch.to_string()
51
        };
52
        Self::raw(content, Style::default())
53
    }
54
55
    /// Creates a blank label.
56
    pub fn blank() -> Self {
57
        Self::raw(String::new(), Style::default())
58
    }
59
60
    /// Returns whether this label is empty.
61
    pub fn is_blank(&self) -> bool {
62
        self.content().is_empty()
63
    }
64
65
    /// Returns unstyled content.
66
    pub fn content(&self) -> &str {
67
        self.paint.content()
68
    }
69
70
    /// Creates a single-space label.
71
    pub fn space() -> Self {
72
        Self::raw(String::from(" "), Style::default())
73
    }
74
75
    /// Color the label's foreground.
76
    pub fn fg(self, color: Color) -> Self {
77
        Self {
78
            paint: self.paint.fg(color),
79
            metrics: self.metrics,
80
        }
81
    }
82
83
    /// Color the label's background.
84
    pub fn bg(self, color: Color) -> Self {
85
        Self {
86
            paint: self.paint.bg(color),
87
            metrics: self.metrics,
88
        }
89
    }
90
91
    /// Styles the label.
92
    pub fn style(self, style: Style) -> Self {
93
        let style = self.paint.style.merge(style);
94
        Self {
95
            paint: self.paint.with_style(style),
96
            metrics: self.metrics,
97
        }
98
    }
99
100
    /// Returns this label with a fill background.
101
    pub fn filled(self, color: Color) -> Filled<Self> {
102
        Filled { item: self, color }
103
    }
104
105
    /// Wraps this label into a line.
106
    pub fn to_line(self) -> Line {
107
        Line::from(self)
108
    }
109
110
    /// Returns whether the label content is printable ASCII.
111
    pub(crate) const fn is_ascii(&self) -> bool {
112
        self.metrics.ascii
113
    }
114
115
    /// Creates a label from content that has already been cleaned.
116
    pub(crate) fn raw(content: String, style: Style) -> Self {
117
        Self {
118
            metrics: LabelMetrics::new(&content),
119
            paint: Paint {
120
                item: content,
121
                style,
122
            },
123
        }
124
    }
125
}
126
127
impl Widget for Label {
128
    fn size(&self, _parent: Constraint) -> Size {
129
        Size::new(self.metrics.width, 1)
130
    }
131
132
    fn render(&mut self, area: crate::Rect, buf: &mut Buffer) {
133
        Line::renders([Line::new(self.clone())], area, buf);
134
    }
135
}
136
137
impl fmt::Display for Label {
138
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139
        fmt::Display::fmt(&self.paint, f)
140
    }
141
}
142
143
impl Text for Label {
144
    type Padded = Self;
145
    type Truncated = Self;
146
147
    fn background(&self) -> Color {
148
        self.paint.style.background
149
    }
150
151
    fn pad(&self, width: usize) -> Self::Padded {
152
        Self::from(self.paint.pad(width))
153
    }
154
155
    fn truncate(&self, width: usize, delim: &str) -> Self::Truncated {
156
        Self::from(self.paint.truncate(width, delim))
157
    }
158
159
    fn width(&self) -> usize {
160
        self.metrics.width
161
    }
162
}
163
164
impl<D: fmt::Display> From<Paint<D>> for Label {
165
    fn from(paint: Paint<D>) -> Self {
166
        Self::raw(clean(format!("{}", paint.item)), paint.style)
167
    }
168
}
169
170
impl From<String> for Label {
171
    fn from(value: String) -> Self {
172
        Self::raw(clean(value), Style::default())
173
    }
174
}
175
176
impl From<&str> for Label {
177
    fn from(value: &str) -> Self {
178
        Self::new(value)
179
    }
180
}
181
182
/// Creates a new label from a [`Paint`] object.
183
pub fn label(s: impl Into<Paint<String>>) -> Label {
184
    Label::from(s.into())
185
}
186
187
/// Removes unsupported label line breaks.
188
fn clean(mut input: String) -> String {
189
    if input.as_bytes().contains(&b'\n') || input.as_bytes().contains(&b'\r') {
190
        input.retain(|c| c != '\n' && c != '\r');
191
    }
192
    input
193
}
194
195
#[cfg(test)]
196
mod tests {
197
    use super::*;
198
199
    #[test]
200
    fn style_merges_with_existing_label_colors() {
201
        let label = Label::new("x")
202
            .fg(Color::White)
203
            .bg(Color::Blue)
204
            .style(Style::default().bold());
205
206
        assert_eq!(label.paint.style().fg_color(), Color::White);
207
        assert_eq!(label.paint.style().bg_color(), Color::Blue);
208
    }
209
}