Skip to main content

gpui_material_components/overlay/
snackbar.rs

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