Skip to main content

saorsa_core/widget/
label.rs

1//! Label widget — a single line of styled text.
2
3use crate::buffer::ScreenBuffer;
4use crate::cell::Cell;
5use crate::geometry::Rect;
6use crate::style::Style;
7use unicode_width::UnicodeWidthStr;
8
9use super::Widget;
10
11/// Text alignment.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub enum Alignment {
14    /// Align to the left (default).
15    #[default]
16    Left,
17    /// Center the text.
18    Center,
19    /// Align to the right.
20    Right,
21}
22
23/// A single-line text label widget.
24#[derive(Clone, Debug)]
25pub struct Label {
26    /// The text to display.
27    text: String,
28    /// The style for the text.
29    style: Style,
30    /// Text alignment within the available area.
31    alignment: Alignment,
32}
33
34impl Label {
35    /// Create a new label with the given text.
36    pub fn new(text: impl Into<String>) -> Self {
37        Self {
38            text: text.into(),
39            style: Style::default(),
40            alignment: Alignment::Left,
41        }
42    }
43
44    /// Set the style.
45    #[must_use]
46    pub fn style(mut self, style: Style) -> Self {
47        self.style = style;
48        self
49    }
50
51    /// Set the alignment.
52    #[must_use]
53    pub fn alignment(mut self, alignment: Alignment) -> Self {
54        self.alignment = alignment;
55        self
56    }
57
58    /// Get the text.
59    pub fn text(&self) -> &str {
60        &self.text
61    }
62
63    /// Set new text content.
64    pub fn set_text(&mut self, text: impl Into<String>) {
65        self.text = text.into();
66    }
67}
68
69impl Widget for Label {
70    fn render(&self, area: Rect, buf: &mut ScreenBuffer) {
71        if area.size.width == 0 || area.size.height == 0 {
72            return;
73        }
74
75        let width = usize::from(area.size.width);
76        let text_width = UnicodeWidthStr::width(self.text.as_str());
77
78        // Truncate with ellipsis if needed
79        let display_text = if text_width > width {
80            truncate_with_ellipsis(&self.text, width)
81        } else {
82            self.text.clone()
83        };
84
85        let display_width = UnicodeWidthStr::width(display_text.as_str());
86
87        // Calculate horizontal offset based on alignment
88        let offset = match self.alignment {
89            Alignment::Left => 0,
90            Alignment::Center => (width.saturating_sub(display_width)) / 2,
91            Alignment::Right => width.saturating_sub(display_width),
92        };
93
94        // Write characters to buffer
95        let mut col = 0usize;
96        for ch in display_text.chars() {
97            let ch_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
98            let x = area.position.x + (offset + col) as u16;
99            if x >= area.position.x + area.size.width {
100                break;
101            }
102            buf.set(
103                x,
104                area.position.y,
105                Cell::new(ch.to_string(), self.style.clone()),
106            );
107            col += ch_width;
108        }
109    }
110}
111
112/// Truncate a string to fit within `max_width` columns, adding an ellipsis.
113fn truncate_with_ellipsis(text: &str, max_width: usize) -> String {
114    if max_width == 0 {
115        return String::new();
116    }
117    if max_width == 1 {
118        return "\u{2026}".to_string(); // …
119    }
120
121    let target = max_width - 1; // leave room for ellipsis
122    let mut result = String::new();
123    let mut current_width = 0usize;
124
125    for ch in text.chars() {
126        let ch_width = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
127        if current_width + ch_width > target {
128            break;
129        }
130        result.push(ch);
131        current_width += ch_width;
132    }
133    result.push('\u{2026}'); // …
134    result
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use crate::color::{Color, NamedColor};
141    use crate::geometry::Size;
142
143    #[test]
144    fn label_renders_left_aligned() {
145        let label = Label::new("Hello");
146        let mut buf = ScreenBuffer::new(Size::new(10, 1));
147        label.render(Rect::new(0, 0, 10, 1), &mut buf);
148        assert_eq!(buf.get(0, 0).map(|c| c.grapheme.as_str()), Some("H"));
149        assert_eq!(buf.get(4, 0).map(|c| c.grapheme.as_str()), Some("o"));
150    }
151
152    #[test]
153    fn label_renders_center_aligned() {
154        let label = Label::new("Hi").alignment(Alignment::Center);
155        let mut buf = ScreenBuffer::new(Size::new(10, 1));
156        label.render(Rect::new(0, 0, 10, 1), &mut buf);
157        // "Hi" is 2 wide, centered in 10 → offset 4
158        assert_eq!(buf.get(4, 0).map(|c| c.grapheme.as_str()), Some("H"));
159        assert_eq!(buf.get(5, 0).map(|c| c.grapheme.as_str()), Some("i"));
160    }
161
162    #[test]
163    fn label_renders_right_aligned() {
164        let label = Label::new("Hi").alignment(Alignment::Right);
165        let mut buf = ScreenBuffer::new(Size::new(10, 1));
166        label.render(Rect::new(0, 0, 10, 1), &mut buf);
167        // "Hi" is 2 wide, right-aligned in 10 → offset 8
168        assert_eq!(buf.get(8, 0).map(|c| c.grapheme.as_str()), Some("H"));
169        assert_eq!(buf.get(9, 0).map(|c| c.grapheme.as_str()), Some("i"));
170    }
171
172    #[test]
173    fn label_truncates_with_ellipsis() {
174        let label = Label::new("Hello, World!");
175        let mut buf = ScreenBuffer::new(Size::new(8, 1));
176        label.render(Rect::new(0, 0, 8, 1), &mut buf);
177        // Should truncate to "Hello, \u{2026}" (7 chars + ellipsis)
178        assert_eq!(buf.get(0, 0).map(|c| c.grapheme.as_str()), Some("H"));
179        assert_eq!(buf.get(7, 0).map(|c| c.grapheme.as_str()), Some("\u{2026}"));
180    }
181
182    #[test]
183    fn label_with_style() {
184        let style = Style::new().fg(Color::Named(NamedColor::Red));
185        let label = Label::new("X").style(style.clone());
186        let mut buf = ScreenBuffer::new(Size::new(5, 1));
187        label.render(Rect::new(0, 0, 5, 1), &mut buf);
188        assert_eq!(buf.get(0, 0).map(|c| &c.style), Some(&style));
189    }
190
191    #[test]
192    fn label_empty_area() {
193        let label = Label::new("test");
194        let mut buf = ScreenBuffer::new(Size::new(10, 1));
195        // Should not crash on zero-width area
196        label.render(Rect::new(0, 0, 0, 1), &mut buf);
197    }
198
199    #[test]
200    fn label_set_text() {
201        let mut label = Label::new("before");
202        assert_eq!(label.text(), "before");
203        label.set_text("after");
204        assert_eq!(label.text(), "after");
205    }
206}