crates/tui-widgets/src/badge.rs 2.6 KiB raw
1
//! Compact text badge widget.
2
3
use rustik_tui_core as tui_core;
4
use tui_core::{Buffer, Constraint, Label, Line, Rect, Size, Style, Widget};
5
6
/// Compact text badge with styled end caps.
7
#[derive(Debug, Clone)]
8
pub struct Badge {
9
    /// Text rendered between the caps.
10
    text: Label,
11
    /// Leading cap.
12
    left: Label,
13
    /// Trailing cap.
14
    right: Label,
15
}
16
17
impl Badge {
18
    /// Creates a badge with powerline-style rounded caps.
19
    pub fn new(text: impl Into<Label>) -> Self {
20
        Self {
21
            text: text.into(),
22
            left: Label::new(""),
23
            right: Label::new(""),
24
        }
25
    }
26
27
    /// Sets the text style.
28
    pub fn style(mut self, style: Style) -> Self {
29
        self.text = self.text.style(style);
30
        self
31
    }
32
33
    /// Sets the cap style.
34
    pub fn cap_style(mut self, style: Style) -> Self {
35
        self.left = self.left.style(style);
36
        self.right = self.right.style(style);
37
        self
38
    }
39
40
    /// Sets the cap labels.
41
    pub fn caps(mut self, left: impl Into<Label>, right: impl Into<Label>) -> Self {
42
        self.left = left.into();
43
        self.right = right.into();
44
        self
45
    }
46
47
    /// Returns the badge width in terminal cells.
48
    pub fn width(&self) -> usize {
49
        self.left.columns(Constraint::UNBOUNDED)
50
            + self.text.columns(Constraint::UNBOUNDED)
51
            + self.right.columns(Constraint::UNBOUNDED)
52
    }
53
54
    /// Returns the badge as a line.
55
    pub fn line(&self) -> Line {
56
        Line::new(self.left.clone())
57
            .item(self.text.clone())
58
            .item(self.right.clone())
59
    }
60
}
61
62
impl Widget for Badge {
63
    fn size(&self, _parent: Constraint) -> Size {
64
        Size::new(self.width(), 1)
65
    }
66
67
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
68
        self.line().render(area, buf);
69
    }
70
}
71
72
impl From<Badge> for Line {
73
    fn from(badge: Badge) -> Self {
74
        badge.line()
75
    }
76
}
77
78
#[cfg(test)]
79
mod tests {
80
    use super::*;
81
    use tui_core::{Color, Style};
82
83
    #[test]
84
    fn badge_renders_caps_and_text() {
85
        let badge = Badge::new("Go")
86
            .cap_style(Style::new(Color::Blue))
87
            .style(Style::new(Color::White).bg(Color::Blue).bold());
88
        let line = badge.line();
89
90
        assert_eq!(line.to_string(), "Go");
91
        assert_eq!(badge.width(), line.width());
92
        assert_eq!(badge.size(Constraint::UNBOUNDED), Size::new(4, 1));
93
    }
94
95
    #[test]
96
    fn badge_supports_custom_caps() {
97
        let badge = Badge::new("A").caps("[", "]");
98
99
        assert_eq!(badge.line().to_string(), "[A]");
100
        assert_eq!(badge.width(), 3);
101
    }
102
}