Skip to main content

gpui_component/
badge.rs

1use gpui::{
2    AnyElement, App, Hsla, IntoElement, ParentElement, RenderOnce, StyleRefinement, Styled, Window,
3    div, prelude::FluentBuilder, px, relative,
4};
5use gpui_base::LogicalStyledExt as _;
6
7use crate::{ActiveTheme, Icon, Sizable, Size, StyledExt, ThemeStyled as _, h_flex, white};
8
9#[derive(Default, Clone)]
10enum BadgeVariant {
11    #[default]
12    Number,
13    Dot,
14    Icon(Box<Icon>),
15}
16
17#[allow(unused)]
18impl BadgeVariant {
19    #[inline]
20    fn is_icon(&self) -> bool {
21        matches!(self, BadgeVariant::Icon(_))
22    }
23
24    #[inline]
25    fn is_number(&self) -> bool {
26        matches!(self, BadgeVariant::Number)
27    }
28}
29
30/// A badge for displaying a count, dot, or icon on an element.
31#[derive(IntoElement)]
32pub struct Badge {
33    style: StyleRefinement,
34    count: usize,
35    max: usize,
36    variant: BadgeVariant,
37    children: Vec<AnyElement>,
38    color: Option<Hsla>,
39    size: Size,
40}
41
42impl Badge {
43    /// Create a new badge.
44    pub fn new() -> Self {
45        Self {
46            style: StyleRefinement::default(),
47            count: 0,
48            max: 99,
49            variant: Default::default(),
50            color: None,
51            children: Vec::new(),
52            size: Size::default(),
53        }
54    }
55
56    /// Set to use [`BadgeVariant::Dot`] to show a dot.
57    pub fn dot(mut self) -> Self {
58        self.variant = BadgeVariant::Dot;
59        self
60    }
61
62    /// Set to use [`BadgeVariant::Number`] to show a count.
63    ///
64    /// If count is 0, the badge will be hidden.
65    pub fn count(mut self, count: usize) -> Self {
66        self.count = count;
67        self
68    }
69
70    /// Set to use [`BadgeVariant::Icon`] to show an icon.
71    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
72        self.variant = BadgeVariant::Icon(Box::new(icon.into()));
73        self
74    }
75
76    /// Set the maximum count to show (Only if [`BadgeVariant::Number`] is used).
77    pub fn max(mut self, max: usize) -> Self {
78        self.max = max;
79        self
80    }
81
82    /// Set the color (background) of the badge.
83    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
84        self.color = Some(color.into());
85        self
86    }
87}
88
89impl ParentElement for Badge {
90    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
91        self.children.extend(elements);
92    }
93}
94
95impl Sizable for Badge {
96    fn with_size(mut self, size: impl Into<Size>) -> Self {
97        self.size = size.into();
98        self
99    }
100}
101
102impl RenderOnce for Badge {
103    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
104        let visible = match self.variant {
105            BadgeVariant::Number => self.count > 0,
106            BadgeVariant::Dot | BadgeVariant::Icon(_) => true,
107        };
108
109        let (size, text_size) = match self.size {
110            Size::Large => (px(24.), px(14.)),
111            Size::Medium | Size::Size(_) => (px(16.), px(10.)),
112            Size::Small | Size::XSmall => (px(10.), px(8.)),
113        };
114
115        div()
116            .relative()
117            .refine_style(&self.style)
118            .children(self.children)
119            .when(visible, |this| {
120                this.child(
121                    h_flex()
122                        .absolute()
123                        .justify_center()
124                        .items_center()
125                        .rounded_full_style(cx)
126                        .bg(self.color.unwrap_or(cx.theme().red))
127                        .text_color(white())
128                        .text_size(text_size)
129                        .map(|this| match self.variant {
130                            BadgeVariant::Dot => this.top_0().inset_e(px(0.), cx).size(px(6.)),
131                            BadgeVariant::Number => {
132                                let count = if self.count > self.max {
133                                    format!("{}+", self.max)
134                                } else {
135                                    self.count.to_string()
136                                };
137
138                                let (top, left) = match self.size {
139                                    Size::Large => (px(2.), -px(count.len() as f32)),
140                                    Size::Medium | Size::Size(_) => {
141                                        (-px(3.), -px(3.) * count.len())
142                                    }
143                                    Size::Small | Size::XSmall => (-px(4.), -px(4.) * count.len()),
144                                };
145
146                                this.top(top)
147                                    .inset_e(left, cx)
148                                    .py_0p5()
149                                    .px_0p5()
150                                    .min_w_3p5()
151                                    .text_size(px(10.))
152                                    .line_height(relative(1.))
153                                    .child(count)
154                            }
155                            BadgeVariant::Icon(icon) => this
156                                .inset_e(px(0.), cx)
157                                .bottom_0()
158                                .size(size)
159                                .border_1()
160                                .border_color(cx.theme().background)
161                                .child(*icon),
162                        }),
163                )
164            })
165    }
166}