Skip to main content

iced_cube/feedback/
badge.rs

1//! Short status or category markers.
2
3use iced::widget::{container, row, text};
4use iced::{Alignment, Background, Border, Color, Element, Padding, Shadow};
5
6use crate::icon::{Glyph, themed};
7use crate::natural::natural;
8use crate::theme::{Tokens, on, radius, text_size};
9
10const ICON_SIZE: f32 = 12.0;
11
12/// Visual emphasis of a badge.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum Variant {
15    #[default]
16    Default,
17    Secondary,
18    Outline,
19    Destructive,
20    Success,
21    Warning,
22}
23
24impl Variant {
25    pub const ALL: [Variant; 6] = [
26        Variant::Default,
27        Variant::Secondary,
28        Variant::Outline,
29        Variant::Destructive,
30        Variant::Success,
31        Variant::Warning,
32    ];
33}
34
35/// A badge builder. Convert it into an [`Element`] to render.
36#[derive(Debug)]
37pub struct Badge<'a> {
38    label: text::Fragment<'a>,
39    icon: Option<Glyph>,
40    variant: Variant,
41}
42
43/// Creates a badge with a text label.
44pub fn badge<'a>(label: impl text::IntoFragment<'a>) -> Badge<'a> {
45    Badge {
46        label: label.into_fragment(),
47        icon: None,
48        variant: Variant::default(),
49    }
50}
51
52impl Badge<'_> {
53    pub fn variant(mut self, variant: Variant) -> Self {
54        self.variant = variant;
55        self
56    }
57
58    /// Adds an icon before the label.
59    pub fn icon(mut self, glyph: Glyph) -> Self {
60        self.icon = Some(glyph);
61        self
62    }
63}
64
65impl<'a, Message: 'a> From<Badge<'a>> for Element<'a, Message> {
66    fn from(badge: Badge<'a>) -> Self {
67        let variant = badge.variant;
68        #[cfg(feature = "icedwright")]
69        let name = badge.label.clone();
70
71        let mut content = row![].spacing(4).align_y(Alignment::Center);
72        if let Some(glyph) = badge.icon {
73            content = content.push(themed(glyph, ICON_SIZE, 1.0, move |theme| {
74                colours(&Tokens::of(theme), variant).foreground
75            }));
76        }
77        content = content.push(
78            text(badge.label)
79                .size(text_size::XS)
80                .wrapping(text::Wrapping::None),
81        );
82
83        let element = natural(
84            container(content)
85                .padding(Padding::from([2.0, 10.0]))
86                .style(move |theme| style(&Tokens::of(theme), variant)),
87        );
88        #[cfg(feature = "icedwright")]
89        let element = icedwright_probe::semantic(element)
90            .role(icedwright_probe::role::Status)
91            .name(name)
92            .component("iced_cube::badge")
93            .into();
94        element
95    }
96}
97
98/// Background, foreground and border colours for a variant.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct Colours {
101    pub background: Option<Color>,
102    pub foreground: Color,
103    pub border: Option<Color>,
104}
105
106/// Resolves the colours of a variant.
107pub fn colours(tokens: &Tokens, variant: Variant) -> Colours {
108    let filled = |background: Color, foreground: Color| Colours {
109        background: Some(background),
110        foreground,
111        border: None,
112    };
113
114    match variant {
115        Variant::Default => filled(tokens.primary, tokens.primary_foreground),
116        Variant::Secondary => filled(tokens.secondary, tokens.secondary_foreground),
117        Variant::Outline => Colours {
118            background: None,
119            foreground: tokens.foreground,
120            border: Some(tokens.border),
121        },
122        Variant::Destructive => filled(tokens.destructive, tokens.destructive_foreground),
123        Variant::Success => filled(tokens.success, on(tokens.success)),
124        Variant::Warning => filled(tokens.warning, on(tokens.warning)),
125    }
126}
127
128/// The container style for a variant.
129pub fn style(tokens: &Tokens, variant: Variant) -> container::Style {
130    let colours = colours(tokens, variant);
131    container::Style {
132        text_color: Some(colours.foreground),
133        background: colours.background.map(Background::Color),
134        border: Border {
135            color: colours.border.unwrap_or(Color::TRANSPARENT),
136            width: if colours.border.is_some() { 1.0 } else { 0.0 },
137            radius: radius::FULL.into(),
138        },
139        shadow: Shadow::default(),
140        snap: true,
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use crate::theme::{dark, light};
148
149    #[test]
150    fn default_builder_is_default_variant_without_icon() {
151        let b = badge("New");
152        assert_eq!(b.variant, Variant::Default);
153        assert!(b.icon.is_none());
154    }
155
156    #[test]
157    fn icon_and_variant_are_kept() {
158        let b = badge("Live")
159            .icon(crate::lucide!(CircleDot))
160            .variant(Variant::Success);
161        assert_eq!(b.variant, Variant::Success);
162        assert_eq!(b.icon.map(Glyph::name), Some("circle-dot"));
163    }
164
165    #[test]
166    fn only_outline_has_a_border_and_no_fill() {
167        for theme in [light(), dark()] {
168            let tokens = Tokens::of(&theme);
169            for variant in Variant::ALL {
170                let style = style(&tokens, variant);
171                let outline = variant == Variant::Outline;
172                assert_eq!(style.border.width > 0.0, outline, "{variant:?}");
173                assert_eq!(style.background.is_none(), outline, "{variant:?}");
174            }
175        }
176    }
177
178    #[test]
179    fn foreground_differs_from_background_in_every_variant() {
180        for theme in [light(), dark()] {
181            let tokens = Tokens::of(&theme);
182            for variant in Variant::ALL {
183                let colours = colours(&tokens, variant);
184                let behind = colours.background.unwrap_or(tokens.background);
185                assert_ne!(colours.foreground, behind, "{variant:?}");
186            }
187        }
188    }
189
190    #[test]
191    fn status_variants_use_status_tokens() {
192        for theme in [light(), dark()] {
193            let tokens = Tokens::of(&theme);
194            assert_eq!(
195                colours(&tokens, Variant::Success).background,
196                Some(tokens.success)
197            );
198            assert_eq!(
199                colours(&tokens, Variant::Warning).background,
200                Some(tokens.warning)
201            );
202            assert_eq!(
203                colours(&tokens, Variant::Destructive).background,
204                Some(tokens.destructive)
205            );
206        }
207    }
208
209    #[test]
210    fn badges_are_pills() {
211        let tokens = Tokens::of(&light());
212        for variant in Variant::ALL {
213            assert_eq!(style(&tokens, variant).border.radius, radius::FULL.into());
214        }
215    }
216}