Skip to main content

gpui_material_components/overlay/
snackbar.rs

1use std::{cell::Cell, collections::VecDeque, rc::Rc, time::Duration};
2
3use crate::motion::{OverlayMotion, ScaledOverlay};
4use gpui::{
5    App, ClickEvent, Context, InteractiveElement, IntoElement, ParentElement, Render, Role,
6    SharedString, StatefulInteractiveElement, Styled, Task, Window, canvas, div, point,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::TestSupportExt as _;
10use gpui_material_foundation::{Surface, color, window_material_theme};
11use gpui_material_theme::{ColorRole, Direction, Elevation, TypeRole};
12
13type Action = Rc<dyn Fn(&mut Window, &mut App)>;
14
15/// A message for a window's snackbar queue. The default timeout is four seconds.
16pub struct Snackbar {
17    message: SharedString,
18    timeout: Option<Duration>,
19    action: Option<(SharedString, Action)>,
20}
21
22impl Snackbar {
23    pub fn new(message: impl Into<SharedString>) -> Self {
24        Self {
25            message: message.into(),
26            timeout: Some(Duration::from_secs(4)),
27            action: None,
28        }
29    }
30
31    /// Sets how long the message is visible. `None` waits for explicit dismissal.
32    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
33        self.timeout = timeout;
34        self
35    }
36
37    /// Adds a keyboard-accessible action. By default, messages with an action
38    /// persist. Call `timeout` after this method to set a duration explicitly.
39    pub fn action(
40        mut self,
41        label: impl Into<SharedString>,
42        action: impl Fn(&mut Window, &mut App) + 'static,
43    ) -> Self {
44        self.action = Some((label.into(), Rc::new(action)));
45        self.timeout = None;
46        self
47    }
48}
49
50/// One FIFO message queue per host. Mount the entity in the window layout.
51/// A new message leaves keyboard focus wherever it is.
52#[derive(Default)]
53pub struct SnackbarHost {
54    active: Option<(usize, Snackbar)>,
55    exiting: Vec<(usize, Snackbar)>,
56    pending: VecDeque<Snackbar>,
57    next_id: usize,
58    timer: Option<Task<()>>,
59}
60
61impl SnackbarHost {
62    /// Queues the message after any already pending messages.
63    pub fn push(&mut self, snackbar: Snackbar, window: &mut Window, cx: &mut Context<Self>) {
64        self.pending.push_back(snackbar);
65        if self.active.is_none() {
66            self.show_next(window, cx);
67        }
68    }
69
70    /// Dismisses the active message. If any are queued, the next begins its own timeout.
71    pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
72        if let Some((id, _)) = &self.active {
73            self.finish(*id, false, window, cx);
74        }
75    }
76
77    fn show_next(&mut self, window: &mut Window, cx: &mut Context<Self>) {
78        self.active = self.pending.pop_front().map(|message| {
79            self.next_id += 1;
80            (self.next_id, message)
81        });
82        self.timer = self.active.as_ref().and_then(|(id, snackbar)| {
83            let id = *id;
84            let timeout = snackbar.timeout?;
85            Some(cx.spawn_in(window, async move |this, cx| {
86                cx.background_executor().timer(timeout).await;
87                let _ = this.update_in(cx, |this, window, cx| {
88                    this.finish(id, false, window, cx);
89                });
90            }))
91        });
92        cx.notify();
93    }
94
95    fn finish(&mut self, id: usize, run_action: bool, window: &mut Window, cx: &mut Context<Self>) {
96        if self
97            .active
98            .as_ref()
99            .is_none_or(|(current, _)| *current != id)
100        {
101            return;
102        }
103        let entry = self.active.take().unwrap();
104        let action = entry.1.action.as_ref().map(|(_, action)| action.clone());
105        self.exiting.push(entry);
106        self.show_next(window, cx);
107        if let Some(action) = action.filter(|_| run_action) {
108            // The application may enqueue another message from this callback.
109            window.defer(cx, move |window, cx| action(window, cx));
110        }
111    }
112}
113
114impl Render for SnackbarHost {
115    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
116        let host_width = window
117            .use_keyed_state("snackbar-host-width", cx, |_, _| Rc::new(Cell::new(px(0.))))
118            .read(cx)
119            .clone();
120        let width = host_width.get();
121        let mut root = div().relative().w_full().child(
122            canvas(
123                move |bounds, window, _| {
124                    if host_width.replace(bounds.size.width) != bounds.size.width {
125                        window.request_animation_frame();
126                    }
127                },
128                |_, _, _, _| {},
129            )
130            .absolute()
131            .inset_0(),
132        );
133        let mut has_layout = self.active.is_some();
134        self.exiting.retain(|(id, message)| {
135            let Some(motion) = OverlayMotion::sample(&("snackbar", *id).into(), false, window, cx)
136            else {
137                return false;
138            };
139            let content = snackbar_surface(*id, message, motion, width, false, window, cx);
140            let scaled = ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width);
141            let slot = div().when(has_layout, |div| div.absolute().inset_0());
142            root.extend([slot.child(scaled).into_any_element()]);
143            has_layout = true;
144            true
145        });
146        if let Some((id, message)) = &self.active {
147            let motion = OverlayMotion::sample(&("snackbar", *id).into(), true, window, cx)
148                .expect("active snackbar has motion");
149            let content = snackbar_surface(*id, message, motion, width, true, window, cx);
150            root =
151                root.child(ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width));
152        }
153        root
154    }
155}
156
157fn snackbar_surface(
158    id: usize,
159    message: &Snackbar,
160    motion: OverlayMotion,
161    width: gpui::Pixels,
162    active: bool,
163    window: &Window,
164    cx: &mut Context<SnackbarHost>,
165) -> impl IntoElement {
166    let theme = window_material_theme(window, cx);
167    let action_color = color(theme.colors.color(ColorRole::InversePrimary));
168    let rtl = theme.layout.direction == Direction::Rtl;
169    let spacing = motion.px(16.);
170    let control = move |button: gpui_base::Button| {
171        button
172            .min_h(motion.px(48.))
173            .px(spacing * 0.5)
174            .rounded(spacing * 0.375)
175            .text_color(action_color)
176            .font_weight(gpui::FontWeight::MEDIUM)
177            .hover(move |style| {
178                style.bg(action_color.opacity(gpui_material_theme::StateLayer::Hover.opacity()))
179            })
180            .active(move |style| {
181                style.bg(action_color.opacity(gpui_material_theme::StateLayer::Pressed.opacity()))
182            })
183            .focus_visible(move |style| style.border(motion.px(2.)).border_color(action_color))
184    };
185    let passive = move |label: SharedString| {
186        div()
187            .min_h(motion.px(48.))
188            .px(spacing * 0.5)
189            .flex()
190            .items_center()
191            .line_height(gpui::relative(1.))
192            .text_color(action_color)
193            .font_weight(gpui::FontWeight::MEDIUM)
194            .child(label)
195    };
196    let surface = div()
197        .id((if active { "snackbar" } else { "snackbar-exit" }, id))
198        .test_support()
199        .w(width * motion.scale)
200        .opacity(motion.alpha)
201        .child(
202            Surface::new(ColorRole::InverseSurface)
203                .shadow_elevation(Elevation::Level3)
204                .shadow_scale(motion.scale)
205                .flex()
206                .items_center()
207                .min_h(motion.px(48.))
208                .gap(spacing * 0.5)
209                .px(spacing)
210                .rounded(spacing * 0.25)
211                .when(rtl, Styled::flex_row_reverse)
212                .child(
213                    div()
214                        .id(("snackbar-message", id))
215                        .test_support()
216                        .when(active, |label| {
217                            label
218                                .role(Role::Status)
219                                .aria_label(message.message.clone())
220                                .a11y_synthetic_children(|tree| {
221                                    let node = tree.parent_node();
222                                    node.set_live(gpui::accesskit::Live::Polite);
223                                    node.set_live_atomic();
224                                })
225                        })
226                        .min_w_0()
227                        .flex_1()
228                        .py(motion.px(14.))
229                        .child(message.message.clone()),
230                )
231                .when_some(message.action.as_ref(), |surface, (label, _)| {
232                    if active {
233                        surface.child(
234                            div().id("snackbar-action-region").test_support().child(
235                                control(gpui_base::Button::new("snackbar-action"))
236                                    .accessibility_label(label.clone())
237                                    .on_click(cx.listener(
238                                        move |this, _: &ClickEvent, window, cx| {
239                                            this.finish(id, true, window, cx);
240                                        },
241                                    ))
242                                    .child(label.clone()),
243                            ),
244                        )
245                    } else {
246                        surface.child(passive(label.clone()))
247                    }
248                })
249                .when_else(
250                    active,
251                    |surface| {
252                        surface.child(
253                            control(gpui_base::Button::new("snackbar-dismiss"))
254                                .accessibility_label("Dismiss message")
255                                .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
256                                    this.finish(id, false, window, cx);
257                                }))
258                                .child(
259                                    crate::Icon::new(crate::IconName::Close)
260                                        .size(motion.px(24.))
261                                        .color(ColorRole::InverseOnSurface),
262                                ),
263                        )
264                    },
265                    |surface| {
266                        surface.child(
267                            div()
268                                .size(motion.px(48.))
269                                .flex()
270                                .items_center()
271                                .justify_center()
272                                .child(
273                                    crate::Icon::new(crate::IconName::Close)
274                                        .size(motion.px(24.))
275                                        .color(ColorRole::InverseOnSurface),
276                                ),
277                        )
278                    },
279                ),
280        );
281    super::text_style(surface, TypeRole::BodyMedium, motion.scale, window, cx)
282}