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    AnyElement, App, ClickEvent, Context, EntityId, FocusHandle, Hsla, InteractiveElement,
6    IntoElement, KeyDownEvent, ParentElement, Render, Role, SharedString,
7    StatefulInteractiveElement, Styled, Task, WeakFocusHandle, Window, canvas, div, point,
8    prelude::FluentBuilder, px,
9};
10use gpui_base::TestSupportExt as _;
11use gpui_material_foundation::{color, current_material_theme, elevation_shadows};
12use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, TypeRole};
13
14type Action = Rc<dyn Fn(&mut Window, &mut App)>;
15type Content = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
16type Completion = Rc<dyn Fn(SnackbarResult, &mut Window, &mut App)>;
17type HostRenderer = Box<dyn Fn(&Snackbar, SnackbarParts, &mut Window, &mut App) -> AnyElement>;
18
19/// How a current snackbar left its host's queue.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum SnackbarResult {
22    ActionPerformed,
23    Dismissed,
24}
25
26/// An entry in one snackbar host's queue.
27#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
28pub struct SnackbarId {
29    host: EntityId,
30    sequence: usize,
31}
32
33/// Optional per-region colors. Omitted fields use the window's inverse palette.
34#[derive(Clone, Copy, Debug, Default, PartialEq)]
35pub struct SnackbarColors {
36    pub container: Option<Hsla>,
37    pub content: Option<Hsla>,
38    pub action: Option<Hsla>,
39    pub dismiss: Option<Hsla>,
40}
41
42/// Host-owned status and activation elements for a custom layout.
43#[non_exhaustive]
44pub struct SnackbarParts {
45    pub message: AnyElement,
46    pub action: Option<AnyElement>,
47    pub dismiss: Option<AnyElement>,
48    /// Scale to apply to dimensions in the custom container.
49    pub scale: f32,
50}
51
52/// A message for a window's snackbar queue. The default timeout is four seconds.
53pub struct Snackbar {
54    message: SharedString,
55    timeout: Option<Duration>,
56    action: Option<(SharedString, Action)>,
57    message_content: Option<Content>,
58    action_content: Option<Content>,
59    dismiss_content: Option<(SharedString, Content)>,
60    show_dismiss: bool,
61    action_on_new_line: bool,
62    shape: CornerShape,
63    colors: SnackbarColors,
64    on_dismiss: Option<Action>,
65    on_result: Option<Completion>,
66}
67
68impl Snackbar {
69    pub fn new(message: impl Into<SharedString>) -> Self {
70        Self {
71            message: message.into(),
72            timeout: Some(Duration::from_secs(4)),
73            action: None,
74            message_content: None,
75            action_content: None,
76            dismiss_content: None,
77            show_dismiss: true,
78            action_on_new_line: false,
79            shape: CornerShape::Radii([4.; 4]),
80            colors: SnackbarColors::default(),
81            on_dismiss: None,
82            on_result: None,
83        }
84    }
85
86    /// Sets how long the message is visible. `None` waits for explicit dismissal.
87    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
88        self.timeout = timeout;
89        self
90    }
91
92    /// Adds a keyboard-accessible action. By default, messages with an action
93    /// persist. Call `timeout` after this method to set a duration explicitly.
94    pub fn action(
95        mut self,
96        label: impl Into<SharedString>,
97        action: impl Fn(&mut Window, &mut App) + 'static,
98    ) -> Self {
99        self.action = Some((label.into(), Rc::new(action)));
100        self.timeout = None;
101        self
102    }
103
104    /// Returns the plain message used as the status announcement.
105    pub fn message(&self) -> &SharedString {
106        &self.message
107    }
108
109    /// Returns the accessible name of the optional action.
110    pub fn action_label(&self) -> Option<&SharedString> {
111        self.action.as_ref().map(|(label, _)| label)
112    }
113
114    /// Replaces the visible message with repeatable decorative content.
115    pub fn message_content<E: IntoElement>(
116        mut self,
117        content: impl Fn(&mut Window, &mut App) -> E + 'static,
118    ) -> Self {
119        self.message_content = Some(Box::new(move |window, cx| {
120            content(window, cx).into_any_element()
121        }));
122        self
123    }
124
125    /// Replaces the visible content of the named action supplied by [`Self::action`].
126    pub fn action_content<E: IntoElement>(
127        mut self,
128        content: impl Fn(&mut Window, &mut App) -> E + 'static,
129    ) -> Self {
130        self.action_content = Some(Box::new(move |window, cx| {
131            content(window, cx).into_any_element()
132        }));
133        self
134    }
135
136    /// Supplies the accessible name and decorative content of the close affordance.
137    pub fn dismiss_content<E: IntoElement>(
138        mut self,
139        label: impl Into<SharedString>,
140        content: impl Fn(&mut Window, &mut App) -> E + 'static,
141    ) -> Self {
142        self.dismiss_content = Some((
143            label.into(),
144            Box::new(move |window, cx| content(window, cx).into_any_element()),
145        ));
146        self
147    }
148
149    /// Shows or hides the explicit dismiss button. It is shown by default.
150    pub fn show_dismiss(mut self, show: bool) -> Self {
151        self.show_dismiss = show;
152        self
153    }
154
155    /// Places the action below the message for a long action label.
156    pub fn action_on_new_line(mut self, enabled: bool) -> Self {
157        self.action_on_new_line = enabled;
158        self
159    }
160
161    pub fn shape(mut self, shape: CornerShape) -> Self {
162        self.shape = shape;
163        self
164    }
165
166    pub fn colors(mut self, colors: SnackbarColors) -> Self {
167        self.colors = colors;
168        self
169    }
170
171    /// Runs on timeout, user dismissal, or explicit dismissal by the caller.
172    pub fn on_dismiss(mut self, dismissed: impl Fn(&mut Window, &mut App) + 'static) -> Self {
173        self.on_dismiss = Some(Rc::new(dismissed));
174        self
175    }
176
177    /// Receives one completion after any action or dismissal callback has run.
178    pub fn on_result(
179        mut self,
180        complete: impl Fn(SnackbarResult, &mut Window, &mut App) + 'static,
181    ) -> Self {
182        self.on_result = Some(Rc::new(complete));
183        self
184    }
185}
186
187struct Entry {
188    id: SnackbarId,
189    message: Snackbar,
190    controls: [FocusHandle; 2],
191    return_focus: Option<WeakFocusHandle>,
192}
193
194/// One FIFO message queue per host. Mount the entity in the window layout.
195/// A new message leaves keyboard focus wherever it is.
196#[derive(Default)]
197pub struct SnackbarHost {
198    active: Option<Entry>,
199    exiting: Vec<Entry>,
200    pending: VecDeque<(SnackbarId, Snackbar)>,
201    next_id: usize,
202    timer: Option<Task<()>>,
203    renderer: Option<HostRenderer>,
204}
205
206impl SnackbarHost {
207    /// Uses a custom container and layout for the host-owned message and controls.
208    pub fn renderer<E: IntoElement>(
209        mut self,
210        render: impl Fn(&Snackbar, SnackbarParts, &mut Window, &mut App) -> E + 'static,
211    ) -> Self {
212        self.renderer = Some(Box::new(move |message, parts, window, cx| {
213            render(message, parts, window, cx).into_any_element()
214        }));
215        self
216    }
217
218    /// Queues the message after any already pending messages.
219    pub fn push(&mut self, snackbar: Snackbar, window: &mut Window, cx: &mut Context<Self>) {
220        self.enqueue(snackbar, window, cx);
221    }
222
223    /// Queues the message and returns an opaque identity scoped to this host.
224    pub fn enqueue(
225        &mut self,
226        snackbar: Snackbar,
227        window: &mut Window,
228        cx: &mut Context<Self>,
229    ) -> SnackbarId {
230        self.next_id += 1;
231        let id = SnackbarId {
232            host: cx.entity_id(),
233            sequence: self.next_id,
234        };
235        self.pending.push_back((id, snackbar));
236        if self.active.is_none() {
237            self.show_next(window, cx);
238        }
239        id
240    }
241
242    /// Returns the active entry. Pending and exiting entries are excluded.
243    pub fn current(&self) -> Option<(SnackbarId, &Snackbar)> {
244        self.active.as_ref().map(|entry| (entry.id, &entry.message))
245    }
246
247    /// Dismisses the active message. If any are queued, the next begins its own timeout.
248    pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
249        if let Some((id, _)) = self.current() {
250            self.dismiss_message(id, window, cx);
251        }
252    }
253
254    /// Dismisses the entry if it is still current.
255    pub fn dismiss_message(
256        &mut self,
257        id: SnackbarId,
258        window: &mut Window,
259        cx: &mut Context<Self>,
260    ) -> bool {
261        self.finish(id, SnackbarResult::Dismissed, window, cx)
262    }
263
264    /// Performs the entry's action if it is current and has an action.
265    pub fn perform_action(
266        &mut self,
267        id: SnackbarId,
268        window: &mut Window,
269        cx: &mut Context<Self>,
270    ) -> bool {
271        self.finish(id, SnackbarResult::ActionPerformed, window, cx)
272    }
273
274    fn show_next(&mut self, window: &mut Window, cx: &mut Context<Self>) {
275        self.active = self.pending.pop_front().map(|(id, message)| Entry {
276            id,
277            message,
278            controls: [cx.focus_handle(), cx.focus_handle()],
279            return_focus: window.focused(cx).map(|focus| focus.downgrade()),
280        });
281        self.timer = self.active.as_ref().and_then(|entry| {
282            let id = entry.id;
283            let timeout = entry.message.timeout?;
284            Some(cx.spawn_in(window, async move |this, cx| {
285                cx.background_executor().timer(timeout).await;
286                let _ = this.update_in(cx, |this, window, cx| {
287                    this.dismiss_message(id, window, cx);
288                });
289            }))
290        });
291        cx.notify();
292    }
293
294    fn finish(
295        &mut self,
296        id: SnackbarId,
297        result: SnackbarResult,
298        window: &mut Window,
299        cx: &mut Context<Self>,
300    ) -> bool {
301        let Some(active) = self.active.as_ref().filter(|entry| entry.id == id) else {
302            return false;
303        };
304        let callback = match result {
305            SnackbarResult::ActionPerformed => {
306                let Some((_, callback)) = &active.message.action else {
307                    return false;
308                };
309                Some(callback.clone())
310            }
311            SnackbarResult::Dismissed => active.message.on_dismiss.clone(),
312        };
313        let mut entry = self.active.take().expect("current entry checked above");
314        let complete = entry.message.on_result.take();
315        if entry.controls.iter().any(|focus| focus.is_focused(window)) {
316            if let Some(restore) = entry.return_focus.take().and_then(|focus| focus.upgrade()) {
317                restore.focus(window, cx);
318            } else {
319                window.blur(cx);
320            }
321        }
322        self.exiting.push(entry);
323        self.show_next(window, cx);
324        if callback.is_some() || complete.is_some() {
325            window.defer(cx, move |window, cx| {
326                if let Some(callback) = callback {
327                    callback(window, cx);
328                }
329                if let Some(complete) = complete {
330                    complete(result, window, cx);
331                }
332            });
333        }
334        true
335    }
336}
337
338impl Render for SnackbarHost {
339    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
340        let host_width = window
341            .use_keyed_state("snackbar-host-width", cx, |_, _| Rc::new(Cell::new(px(0.))))
342            .read(cx)
343            .clone();
344        let width = host_width.get();
345        let mut root = div().relative().w_full().child(
346            canvas(
347                move |bounds, window, _| {
348                    if host_width.replace(bounds.size.width) != bounds.size.width {
349                        window.request_animation_frame();
350                    }
351                },
352                |_, _, _, _| {},
353            )
354            .absolute()
355            .inset_0(),
356        );
357        let mut has_layout = self.active.is_some();
358        let renderer = self.renderer.as_ref();
359        self.exiting.retain(|entry| {
360            let Some(motion) =
361                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), false, window, cx)
362            else {
363                return false;
364            };
365            let content = snackbar_surface(entry, motion, width, false, renderer, window, cx);
366            let scaled = ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width);
367            let slot = div().when(has_layout, |div| div.absolute().inset_0());
368            root.extend([slot.child(scaled).into_any_element()]);
369            has_layout = true;
370            true
371        });
372        if let Some(entry) = &self.active {
373            let motion =
374                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), true, window, cx)
375                    .expect("active snackbar has motion");
376            let content = snackbar_surface(entry, motion, width, true, renderer, window, cx);
377            root =
378                root.child(ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width));
379        }
380        root
381    }
382}
383
384fn snackbar_surface(
385    entry: &Entry,
386    motion: OverlayMotion,
387    width: gpui::Pixels,
388    active: bool,
389    renderer: Option<&HostRenderer>,
390    window: &mut Window,
391    cx: &mut Context<SnackbarHost>,
392) -> impl IntoElement {
393    let id = entry.id;
394    let serial = id.sequence;
395    let message = &entry.message;
396    let theme = current_material_theme(window, cx);
397    let tone = |role| color(theme.colors.color(role));
398    let inverse_primary = tone(ColorRole::InversePrimary);
399    let inverse_on_surface = tone(ColorRole::InverseOnSurface);
400    let content_color = message.colors.content.unwrap_or(inverse_on_surface);
401    let action_color = message.colors.action.unwrap_or(inverse_primary);
402    let dismiss_color = message.colors.dismiss.unwrap_or(inverse_on_surface);
403    let dismiss_feedback = message.colors.dismiss.unwrap_or(inverse_primary);
404    let spacing = motion.px(16.);
405    let message_content = message.message_content.as_ref().map_or_else(
406        || message.message.clone().into_any_element(),
407        |content| content(window, cx),
408    );
409    let message_part = div()
410        .id(("snackbar-message", serial))
411        .test_support()
412        .when(active, |label| {
413            label
414                .role(Role::Status)
415                .aria_label(message.message.clone())
416                .a11y_synthetic_children(|tree| {
417                    let node = tree.parent_node();
418                    node.set_live(gpui::accesskit::Live::Polite);
419                    node.set_live_atomic();
420                })
421        })
422        .min_w_0()
423        .flex_1()
424        .py(motion.px(14.))
425        .text_color(content_color)
426        .child(message_content)
427        .into_any_element();
428
429    let render_control = |index,
430                          id_name,
431                          label,
432                          content,
433                          foreground: Hsla,
434                          feedback: Hsla,
435                          result,
436                          cx: &Context<SnackbarHost>| {
437        if active {
438            gpui_base::Button::new(id_name)
439                .min_h(motion.px(48.))
440                .px(spacing * 0.5)
441                .rounded(spacing * 0.375)
442                .text_color(foreground)
443                .font_weight(gpui::FontWeight::MEDIUM)
444                .hover(move |style| {
445                    style.bg(feedback.opacity(gpui_material_theme::StateLayer::Hover.opacity()))
446                })
447                .active(move |style| {
448                    style.bg(feedback.opacity(gpui_material_theme::StateLayer::Pressed.opacity()))
449                })
450                .focus_visible(move |style| style.border(motion.px(2.)).border_color(feedback))
451                .track_focus(&entry.controls[index])
452                .accessibility_label(label)
453                .on_click(cx.listener(move |host, _: &ClickEvent, window, cx| {
454                    host.finish(id, result, window, cx);
455                }))
456                .child(content)
457                .into_any_element()
458        } else {
459            div()
460                .min_h(motion.px(48.))
461                .px(spacing * 0.5)
462                .flex()
463                .items_center()
464                .line_height(gpui::relative(1.))
465                .text_color(foreground)
466                .font_weight(gpui::FontWeight::MEDIUM)
467                .child(content)
468                .into_any_element()
469        }
470    };
471    let action_part = message.action_label().map(|label| {
472        let content = message.action_content.as_ref().map_or_else(
473            || label.clone().into_any_element(),
474            |content| content(window, cx),
475        );
476        let control = render_control(
477            0,
478            "snackbar-action",
479            label.clone(),
480            content,
481            action_color,
482            action_color,
483            SnackbarResult::ActionPerformed,
484            cx,
485        );
486        if active {
487            div()
488                .id("snackbar-action-region")
489                .test_support()
490                .child(control)
491                .into_any_element()
492        } else {
493            control
494        }
495    });
496    let dismiss_part = message.show_dismiss.then(|| {
497        let (label, content) = message.dismiss_content.as_ref().map_or_else(
498            || {
499                (
500                    "Dismiss message".into(),
501                    crate::Icon::new(crate::IconName::Close)
502                        .size(motion.px(24.))
503                        .into_any_element(),
504                )
505            },
506            |(label, content)| (label.clone(), content(window, cx)),
507        );
508        render_control(
509            1,
510            "snackbar-dismiss",
511            label,
512            content,
513            dismiss_color,
514            dismiss_feedback,
515            SnackbarResult::Dismissed,
516            cx,
517        )
518    });
519    let parts = SnackbarParts {
520        message: message_part,
521        action: action_part,
522        dismiss: dismiss_part,
523        scale: motion.scale,
524    };
525    let rendered = match renderer {
526        Some(render) => render(message, parts, window, cx),
527        None => default_layout(message, parts, motion, window, cx).into_any_element(),
528    };
529    let surface = div()
530        .id((if active { "snackbar" } else { "snackbar-exit" }, serial))
531        .test_support()
532        .w(width * motion.scale)
533        .opacity(motion.alpha)
534        .when(active, |surface| {
535            surface.capture_key_down(cx.listener(move |host, event: &KeyDownEvent, window, cx| {
536                if event.keystroke.key == "escape" && host.dismiss_message(id, window, cx) {
537                    cx.stop_propagation();
538                }
539            }))
540        })
541        .child(rendered);
542    super::text_style(surface, TypeRole::BodyMedium, motion.scale, window, cx)
543}
544
545fn default_layout(
546    message: &Snackbar,
547    parts: SnackbarParts,
548    motion: OverlayMotion,
549    window: &Window,
550    cx: &App,
551) -> gpui::Div {
552    let SnackbarParts {
553        message: content,
554        action,
555        dismiss,
556        ..
557    } = parts;
558    let theme = current_material_theme(window, cx);
559    let direction = theme.layout.direction;
560    let rtl = direction == Direction::Rtl;
561    let tone = |role| color(theme.colors.color(role));
562    let spacing = motion.px(16.);
563    let mut surface = div()
564        .bg(message
565            .colors
566            .container
567            .unwrap_or_else(|| tone(ColorRole::InverseSurface)))
568        .shadow(elevation_shadows(
569            Elevation::Level3.dp(),
570            motion.scale,
571            tone(ColorRole::Shadow),
572        ))
573        .flex()
574        .min_h(motion.px(48.))
575        .gap(spacing * 0.5)
576        .px(spacing)
577        .when(rtl, Styled::flex_row_reverse);
578    if message.shape == CornerShape::Full {
579        surface = surface.rounded_full();
580    } else {
581        // GPUI further clamps these radii against the actual laid-out quad.
582        let [top_left, top_right, bottom_right, bottom_left] =
583            message.shape.radii(f32::MAX / 2., f32::MAX / 2., direction);
584        let radii = &mut surface.style().corner_radii;
585        radii.top_left = Some(motion.px(top_left).into());
586        radii.top_right = Some(motion.px(top_right).into());
587        radii.bottom_right = Some(motion.px(bottom_right).into());
588        radii.bottom_left = Some(motion.px(bottom_left).into());
589    }
590    match (message.action_on_new_line, action) {
591        (true, Some(action)) => surface
592            .flex_col()
593            .items_stretch()
594            .gap_0()
595            .child(content)
596            .child(
597                div()
598                    .flex()
599                    .items_center()
600                    .justify_end()
601                    .gap(spacing * 0.5)
602                    .when(rtl, Styled::flex_row_reverse)
603                    .child(action)
604                    .children(dismiss),
605            ),
606        (_, action) => surface
607            .items_center()
608            .child(content)
609            .children(action)
610            .children(dismiss),
611    }
612}