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