//! Single styled text segment. //! //! `Label` is the smallest styled text unit used by [`Line`](crate::Line) and //! text widgets. It combines string content with paint/style metadata while //! still supporting width-aware truncation and padding. use std::fmt; use super::{Buffer, Color, Constraint, Filled, Line, Paint, Size, Style, Widget, cell::Text}; /// A styled string that does not contain any `'\n'` and implements [`Widget`] and [`Text`]. #[derive(Clone, Default, Debug)] pub struct Label { /// Styled label content. pub paint: Paint, /// Cached text metrics. metrics: LabelMetrics, } /// Cached metrics for label content. #[derive(Clone, Copy, Debug, Default)] struct LabelMetrics { /// Display width in terminal cells. width: usize, /// Whether the content can use the buffer's printable-ASCII fast path. ascii: bool, } impl LabelMetrics { /// Computes metrics for label content. fn new(content: &str) -> Self { Self { width: content.width(), ascii: content.is_ascii() && content.bytes().all(|byte| !byte.is_ascii_control()), } } } impl Label { /// Creates a new label. pub fn new(s: &str) -> Self { Self::raw(clean(s.to_owned()), Style::default()) } /// Creates a new label from one character. pub fn from_char(ch: char) -> Self { let content = if matches!(ch, '\n' | '\r') { String::new() } else { ch.to_string() }; Self::raw(content, Style::default()) } /// Creates a blank label. pub fn blank() -> Self { Self::raw(String::new(), Style::default()) } /// Returns whether this label is empty. pub fn is_blank(&self) -> bool { self.content().is_empty() } /// Returns unstyled content. pub fn content(&self) -> &str { self.paint.content() } /// Creates a single-space label. pub fn space() -> Self { Self::raw(String::from(" "), Style::default()) } /// Color the label's foreground. pub fn fg(self, color: Color) -> Self { Self { paint: self.paint.fg(color), metrics: self.metrics, } } /// Color the label's background. pub fn bg(self, color: Color) -> Self { Self { paint: self.paint.bg(color), metrics: self.metrics, } } /// Styles the label. pub fn style(self, style: Style) -> Self { let style = self.paint.style.merge(style); Self { paint: self.paint.with_style(style), metrics: self.metrics, } } /// Returns this label with a fill background. pub fn filled(self, color: Color) -> Filled { Filled { item: self, color } } /// Wraps this label into a line. pub fn to_line(self) -> Line { Line::from(self) } /// Returns whether the label content is printable ASCII. pub(crate) const fn is_ascii(&self) -> bool { self.metrics.ascii } /// Creates a label from content that has already been cleaned. pub(crate) fn raw(content: String, style: Style) -> Self { Self { metrics: LabelMetrics::new(&content), paint: Paint { item: content, style, }, } } } impl Widget for Label { fn size(&self, _parent: Constraint) -> Size { Size::new(self.metrics.width, 1) } fn render(&mut self, area: crate::Rect, buf: &mut Buffer) { Line::renders([Line::new(self.clone())], area, buf); } } impl fmt::Display for Label { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.paint, f) } } impl Text for Label { type Padded = Self; type Truncated = Self; fn background(&self) -> Color { self.paint.style.background } fn pad(&self, width: usize) -> Self::Padded { Self::from(self.paint.pad(width)) } fn truncate(&self, width: usize, delim: &str) -> Self::Truncated { Self::from(self.paint.truncate(width, delim)) } fn width(&self) -> usize { self.metrics.width } } impl From> for Label { fn from(paint: Paint) -> Self { Self::raw(clean(format!("{}", paint.item)), paint.style) } } impl From for Label { fn from(value: String) -> Self { Self::raw(clean(value), Style::default()) } } impl From<&str> for Label { fn from(value: &str) -> Self { Self::new(value) } } /// Creates a new label from a [`Paint`] object. pub fn label(s: impl Into>) -> Label { Label::from(s.into()) } /// Removes unsupported label line breaks. fn clean(mut input: String) -> String { if input.as_bytes().contains(&b'\n') || input.as_bytes().contains(&b'\r') { input.retain(|c| c != '\n' && c != '\r'); } input } #[cfg(test)] mod tests { use super::*; #[test] fn style_merges_with_existing_label_colors() { let label = Label::new("x") .fg(Color::White) .bg(Color::Blue) .style(Style::default().bold()); assert_eq!(label.paint.style().fg_color(), Color::White); assert_eq!(label.paint.style().bg_color(), Color::Blue); } }