Skip to main content

fc_ui/capabilities/primitives/
alert.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::icon::Icon;
3use crate::capabilities::primitives::icon_source::IconSource;
4use gpui::{prelude::FluentBuilder as _, *};
5use std::rc::Rc;
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8static NEXT_ALERT_ID: AtomicUsize = AtomicUsize::new(0);
9
10#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
11pub enum AlertVariant {
12    #[default]
13    Info,
14    Success,
15    Warning,
16    Error,
17}
18
19impl AlertVariant {
20    fn default_icon(&self) -> &'static str {
21        match self {
22            AlertVariant::Info => "info",
23            AlertVariant::Success => "circle-check",
24            AlertVariant::Warning => "triangle-alert",
25            AlertVariant::Error => "circle-alert",
26        }
27    }
28}
29
30#[derive(IntoElement)]
31pub struct Alert {
32    variant: AlertVariant,
33    title: Option<SharedString>,
34    description: Option<SharedString>,
35    icon: Option<IconSource>,
36    show_icon: bool,
37    dismissible: bool,
38    on_dismiss: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
39    action: Option<(SharedString, Rc<dyn Fn(&mut Window, &mut App)>)>,
40    instance_id: usize,
41    style: StyleRefinement,
42}
43
44impl Alert {
45    pub fn new() -> Self {
46        Self {
47            variant: AlertVariant::default(),
48            title: None,
49            description: None,
50            icon: None,
51            show_icon: true,
52            dismissible: false,
53            on_dismiss: None,
54            action: None,
55            instance_id: NEXT_ALERT_ID.fetch_add(1, Ordering::Relaxed),
56            style: StyleRefinement::default(),
57        }
58    }
59
60    pub fn info() -> Self {
61        Self::new().variant(AlertVariant::Info)
62    }
63
64    pub fn success() -> Self {
65        Self::new().variant(AlertVariant::Success)
66    }
67
68    pub fn warning() -> Self {
69        Self::new().variant(AlertVariant::Warning)
70    }
71
72    pub fn error() -> Self {
73        Self::new().variant(AlertVariant::Error)
74    }
75
76    pub fn variant(mut self, variant: AlertVariant) -> Self {
77        self.variant = variant;
78        self
79    }
80
81    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
82        self.title = Some(title.into());
83        self
84    }
85
86    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
87        self.description = Some(description.into());
88        self
89    }
90
91    pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
92        self.icon = Some(icon.into());
93        self
94    }
95
96    pub fn show_icon(mut self, show: bool) -> Self {
97        self.show_icon = show;
98        self
99    }
100
101    pub fn dismissible(mut self, dismissible: bool) -> Self {
102        self.dismissible = dismissible;
103        self
104    }
105
106    pub fn on_dismiss(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
107        self.on_dismiss = Some(Rc::new(handler));
108        self.dismissible = true;
109        self
110    }
111
112    pub fn action(
113        mut self,
114        label: impl Into<SharedString>,
115        handler: impl Fn(&mut Window, &mut App) + 'static,
116    ) -> Self {
117        self.action = Some((label.into(), Rc::new(handler)));
118        self
119    }
120
121    fn get_colors(
122        &self,
123        theme: &crate::capabilities::foundation::theme::Theme,
124    ) -> (Hsla, Hsla, Hsla) {
125        match self.variant {
126            AlertVariant::Info => (
127                theme.tokens.primary.opacity(0.1),
128                theme.tokens.primary,
129                theme.tokens.primary,
130            ),
131            AlertVariant::Success => {
132                let success_color: Hsla = rgb(0x22c55e).into();
133                (success_color.opacity(0.1), success_color, success_color)
134            }
135            AlertVariant::Warning => {
136                let warning_color: Hsla = rgb(0xf59e0b).into();
137                (warning_color.opacity(0.1), warning_color, warning_color)
138            }
139            AlertVariant::Error => (
140                theme.tokens.destructive.opacity(0.1),
141                theme.tokens.destructive,
142                theme.tokens.destructive,
143            ),
144        }
145    }
146}
147
148impl Default for Alert {
149    fn default() -> Self {
150        Self::new()
151    }
152}
153
154impl Styled for Alert {
155    fn style(&mut self) -> &mut StyleRefinement {
156        &mut self.style
157    }
158}
159
160impl RenderOnce for Alert {
161    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
162        let theme = use_theme(cx);
163        let (bg_color, border_color, accent_color) = self.get_colors(&theme);
164        let user_style = self.style;
165
166        let icon_source = self
167            .icon
168            .unwrap_or_else(|| IconSource::Named(self.variant.default_icon().into()));
169
170        let has_content = self.title.is_some() || self.description.is_some();
171
172        div()
173            .flex()
174            .w_full()
175            .p(px(16.0))
176            .rounded(theme.tokens.radius_md)
177            .bg(bg_color)
178            .border_1()
179            .border_color(border_color.opacity(0.3))
180            .gap(px(12.0))
181            .when(self.show_icon, |this| {
182                this.child(
183                    div()
184                        .flex_shrink_0()
185                        .pt(px(2.0))
186                        .child(Icon::new(icon_source).size(px(20.0)).color(accent_color)),
187                )
188            })
189            .when(has_content, |this| {
190                this.child(
191                    div()
192                        .flex()
193                        .flex_col()
194                        .flex_1()
195                        .gap(px(4.0))
196                        .when_some(self.title.clone(), |this, title| {
197                            this.child(
198                                div()
199                                    .text_sm()
200                                    .font_weight(FontWeight::SEMIBOLD)
201                                    .text_color(theme.tokens.foreground)
202                                    .child(title),
203                            )
204                        })
205                        .when_some(self.description.clone(), |this, desc| {
206                            this.child(
207                                div()
208                                    .text_sm()
209                                    .text_color(theme.tokens.muted_foreground)
210                                    .child(desc),
211                            )
212                        })
213                        .when_some(self.action.clone(), |this, (label, handler)| {
214                            this.child(
215                                div().mt(px(8.0)).child(
216                                    div()
217                                        .id(("alert-action", self.instance_id))
218                                        .role(Role::Button)
219                                        .aria_label(label.clone())
220                                        .text_sm()
221                                        .font_weight(FontWeight::MEDIUM)
222                                        .text_color(accent_color)
223                                        .cursor(CursorStyle::PointingHand)
224                                        .hover(|style| style.opacity(0.8))
225                                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
226                                            (handler)(window, cx);
227                                        })
228                                        .child(label),
229                                ),
230                            )
231                        }),
232                )
233            })
234            .when(self.dismissible, |this| {
235                let dismiss_handler = self.on_dismiss.clone();
236                this.child(
237                    div()
238                        .flex_shrink_0()
239                        .id(("alert-dismiss", self.instance_id))
240                        .role(Role::Button)
241                        .aria_label("Dismiss")
242                        .cursor(CursorStyle::PointingHand)
243                        .rounded(theme.tokens.radius_sm)
244                        .p(px(4.0))
245                        .hover(|style| style.bg(theme.tokens.muted.opacity(0.5)))
246                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
247                            if let Some(ref handler) = dismiss_handler {
248                                (handler)(window, cx);
249                            }
250                        })
251                        .child(
252                            Icon::new("x")
253                                .size(px(16.0))
254                                .color(theme.tokens.muted_foreground),
255                        ),
256                )
257            })
258            .map(|this| {
259                let mut div = this;
260                div.style().refine(&user_style);
261                div
262            })
263    }
264}
265
266pub fn alert() -> Alert {
267    Alert::new()
268}