Skip to main content

fc_ui/capabilities/overlays/
toast.rs

1//! Toast notification component with auto-dismiss.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use smol::Timer;
5use std::time::Duration;
6
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::motion::animations::easings;
9use crate::capabilities::primitives::icon::Icon;
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub enum ToastVariant {
13    Default,
14    Success,
15    Warning,
16    Error,
17}
18
19#[derive(Copy, Clone, Debug, PartialEq, Eq)]
20pub enum ToastPosition {
21    TopLeft,
22    TopCenter,
23    TopRight,
24    BottomLeft,
25    BottomCenter,
26    BottomRight,
27}
28
29#[derive(Clone, Debug)]
30pub struct ToastItem {
31    pub id: u64,
32    pub title: SharedString,
33    pub description: Option<SharedString>,
34    pub variant: ToastVariant,
35    pub duration: Option<Duration>,
36    pub style: StyleRefinement,
37}
38
39impl ToastItem {
40    /// The passed `id` is a placeholder: `ToastManager` assigns its own
41    /// incrementing id when the toast is added.
42    pub fn new(id: u64, title: impl Into<SharedString>) -> Self {
43        Self {
44            id,
45            title: title.into(),
46            description: None,
47            variant: ToastVariant::Default,
48            duration: Some(Duration::from_secs(5)),
49            style: StyleRefinement::default(),
50        }
51    }
52
53    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
54        self.description = Some(description.into());
55        self
56    }
57
58    pub fn variant(mut self, variant: ToastVariant) -> Self {
59        self.variant = variant;
60        self
61    }
62
63    pub fn duration(mut self, duration: Duration) -> Self {
64        self.duration = Some(duration);
65        self
66    }
67
68    pub fn persistent(mut self) -> Self {
69        self.duration = None;
70        self
71    }
72}
73
74impl Styled for ToastItem {
75    fn style(&mut self) -> &mut StyleRefinement {
76        &mut self.style
77    }
78}
79
80pub struct ToastManager {
81    toasts: Vec<ToastItem>,
82    position: ToastPosition,
83    max_toasts: usize,
84    dismissing: std::collections::HashSet<u64>,
85    next_id: u64,
86}
87
88impl ToastManager {
89    pub fn new(_cx: &mut Context<Self>) -> Self {
90        Self {
91            toasts: vec![],
92            position: ToastPosition::BottomRight,
93            max_toasts: 5,
94            dismissing: std::collections::HashSet::new(),
95            next_id: 0,
96        }
97    }
98
99    pub fn position(mut self, position: ToastPosition) -> Self {
100        self.position = position;
101        self
102    }
103
104    pub fn max_toasts(mut self, max: usize) -> Self {
105        self.max_toasts = max;
106        self
107    }
108
109    fn push_toast(&mut self, mut toast: ToastItem, cx: &mut Context<Self>) -> u64 {
110        if self.toasts.len() >= self.max_toasts {
111            self.toasts.remove(0);
112        }
113
114        toast.id = self.next_id;
115        self.next_id = self.next_id.wrapping_add(1);
116
117        let id = toast.id;
118        self.toasts.push(toast);
119        cx.notify();
120        id
121    }
122
123    /// Add a toast and return the ID assigned by the manager.
124    pub fn add_toast(
125        &mut self,
126        toast: ToastItem,
127        window: &mut Window,
128        cx: &mut Context<Self>,
129    ) -> u64 {
130        let duration = toast.duration;
131        let id = self.push_toast(toast, cx);
132
133        if let Some(duration) = duration {
134            cx.spawn_in(window, async move |this, cx| {
135                Timer::after(duration).await;
136                let _ = this.update(cx, |this, cx| {
137                    this.dismissing.insert(id);
138                    cx.notify();
139                });
140                Timer::after(Duration::from_millis(250)).await;
141                let _ = this.update(cx, |this, cx| {
142                    this.dismiss_toast(id, cx);
143                });
144            })
145            .detach();
146        }
147
148        id
149    }
150
151    /// Add a persistent toast and return the ID assigned by the manager.
152    pub fn add_toast_no_dismiss(&mut self, toast: ToastItem, cx: &mut Context<Self>) -> u64 {
153        self.push_toast(toast, cx)
154    }
155
156    pub fn dismiss_toast(&mut self, id: u64, cx: &mut Context<Self>) {
157        self.toasts.retain(|t| t.id != id);
158        self.dismissing.remove(&id);
159        cx.notify();
160    }
161
162    pub fn dismiss_toast_animated(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
163        if self.dismissing.contains(&id) {
164            return;
165        }
166        self.dismissing.insert(id);
167        cx.notify();
168
169        cx.spawn_in(window, async move |this, cx| {
170            Timer::after(Duration::from_millis(250)).await;
171            let _ = this.update(cx, |this, cx| {
172                this.dismiss_toast(id, cx);
173            });
174        })
175        .detach();
176    }
177
178    pub fn is_dismissing(&self, id: u64) -> bool {
179        self.dismissing.contains(&id)
180    }
181
182    pub fn clear_all(&mut self, cx: &mut Context<Self>) {
183        self.toasts.clear();
184        cx.notify();
185    }
186}
187
188impl Render for ToastManager {
189    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
190        let theme = use_theme(cx);
191
192        if self.toasts.is_empty() {
193            return div().into_any_element();
194        }
195
196        let (v_pos, h_pos, v_anchor, items_order) = match self.position {
197            ToastPosition::TopLeft => ("top", "left", "flex_col", false),
198            ToastPosition::TopCenter => ("top", "center", "flex_col", false),
199            ToastPosition::TopRight => ("top", "right", "flex_col", false),
200            ToastPosition::BottomLeft => ("bottom", "left", "flex_col_reverse", true),
201            ToastPosition::BottomCenter => ("bottom", "center", "flex_col_reverse", true),
202            ToastPosition::BottomRight => ("bottom", "right", "flex_col_reverse", true),
203        };
204
205        let mut container = div()
206            .absolute()
207            .flex()
208            .gap(px(12.0))
209            .p(px(16.0))
210            .max_w(px(420.0));
211
212        container = match v_pos {
213            "top" => container.top_0(),
214            "bottom" => container.bottom_0(),
215            _ => container,
216        };
217
218        container = match h_pos {
219            "left" => container.left_0(),
220            "right" => container.right_0(),
221            "center" => container.left_0().right_0().mx_auto(),
222            _ => container,
223        };
224
225        container = match v_anchor {
226            "flex_col" => container.flex_col(),
227            "flex_col_reverse" => container.flex_col_reverse(),
228            _ => container,
229        };
230
231        let mut toasts_to_show = self.toasts.clone();
232        if items_order {
233            toasts_to_show.reverse();
234        }
235
236        container
237            .children(
238                toasts_to_show
239                    .into_iter()
240                    .map(|toast| {
241                        let (bg_color, border_color, icon, icon_color) = match toast.variant {
242                            ToastVariant::Default => (
243                                theme.tokens.card,
244                                theme.tokens.border,
245                                "info",
246                                theme.tokens.foreground,
247                            ),
248                            ToastVariant::Success => (
249                                theme.tokens.card,
250                                theme.tokens.border,
251                                "circle-check",
252                                gpui::hsla(142.0 / 360.0, 0.71, 0.45, 1.0), // green-500
253                            ),
254                            ToastVariant::Warning => (
255                                theme.tokens.card,
256                                theme.tokens.border,
257                                "circle-alert",
258                                gpui::hsla(48.0 / 360.0, 0.96, 0.53, 1.0), // yellow-500
259                            ),
260                            ToastVariant::Error => (
261                                theme.tokens.destructive.opacity(0.1),
262                                theme.tokens.destructive,
263                                "x-circle",
264                                theme.tokens.destructive,
265                            ),
266                        };
267
268                        let user_style = toast.style.clone();
269                        let toast_id = toast.id;
270                        let is_dismissing = self.dismissing.contains(&toast_id);
271
272                        div()
273                            .id(("toast", toast_id))
274                            .flex()
275                            .items_start()
276                            .gap(px(12.0))
277                            .w_full()
278                            .min_w(px(300.0))
279                            .bg(bg_color)
280                            .border_1()
281                            .border_color(border_color)
282                            .rounded(theme.tokens.radius_md)
283                            .p(px(16.0))
284                            .shadow_lg()
285                            .map(|this| {
286                                let mut div = this;
287                                div.style().refine(&user_style);
288                                div
289                            })
290                            .child(Icon::new(icon).size(px(20.0)).color(icon_color))
291                            .child(
292                                div()
293                                    .flex()
294                                    .flex_col()
295                                    .gap(px(4.0))
296                                    .flex_1()
297                                    .child(
298                                        div()
299                                            .text_size(px(14.0))
300                                            .font_family(theme.tokens.font_family.clone())
301                                            .font_weight(FontWeight::SEMIBOLD)
302                                            .text_color(theme.tokens.foreground)
303                                            .line_height(relative(1.4))
304                                            .child(toast.title),
305                                    )
306                                    .when_some(toast.description, |this, desc| {
307                                        this.child(
308                                            div()
309                                                .text_size(px(13.0))
310                                                .font_family(theme.tokens.font_family.clone())
311                                                .text_color(theme.tokens.muted_foreground)
312                                                .line_height(relative(1.4))
313                                                .child(desc),
314                                        )
315                                    }),
316                            )
317                            .child(
318                                div()
319                                    .w(px(20.0))
320                                    .h(px(20.0))
321                                    .flex()
322                                    .items_center()
323                                    .justify_center()
324                                    .rounded(theme.tokens.radius_sm)
325                                    .cursor(CursorStyle::PointingHand)
326                                    .text_color(theme.tokens.muted_foreground)
327                                    .text_size(px(16.0))
328                                    .font_family(theme.tokens.font_family.clone())
329                                    .hover(|style| style.bg(theme.tokens.accent))
330                                    .on_mouse_down(
331                                        MouseButton::Left,
332                                        cx.listener(move |this, _, window, cx| {
333                                            this.dismiss_toast_animated(toast.id, window, cx);
334                                        }),
335                                    )
336                                    .child("×"),
337                            )
338                            .with_animation(
339                                ElementId::NamedInteger(
340                                    if is_dismissing {
341                                        "toast-exit"
342                                    } else {
343                                        "toast-enter"
344                                    }
345                                    .into(),
346                                    toast_id,
347                                ),
348                                Animation::new(Duration::from_millis(if is_dismissing {
349                                    250
350                                } else {
351                                    300
352                                }))
353                                .with_easing(if is_dismissing {
354                                    easings::ease_in_cubic as fn(f32) -> f32
355                                } else {
356                                    easings::ease_out_cubic as fn(f32) -> f32
357                                }),
358                                move |el, delta| {
359                                    if is_dismissing {
360                                        el.opacity(1.0 - delta).mt(px(8.0 * delta))
361                                    } else {
362                                        el.opacity(delta).mt(px(8.0 * (1.0 - delta)))
363                                    }
364                                },
365                            )
366                    })
367                    .collect::<Vec<_>>(),
368            )
369            .into_any_element()
370    }
371}
372
373impl EventEmitter<()> for ToastManager {}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use gpui::{Empty, TestApp};
379
380    #[gpui::test]
381    fn manager_returns_ids_that_can_be_dismissed() {
382        let mut app = TestApp::new();
383        let mut window = app.open_window(|_, _| Empty);
384        let manager = app.update(|cx| cx.new(ToastManager::new));
385
386        let id = window.update(|_, window, cx| {
387            manager.update(cx, |manager, cx| {
388                manager.add_toast(ToastItem::new(999, "toast").persistent(), window, cx)
389            })
390        });
391
392        app.read(|cx| {
393            assert_eq!(manager.read(cx).toasts[0].id, id);
394        });
395
396        app.update(|cx| {
397            manager.update(cx, |manager, cx| manager.dismiss_toast(id, cx));
398        });
399        app.read(|cx| assert!(manager.read(cx).toasts.is_empty()));
400    }
401}