Skip to main content

gpui_material_components/overlay/
snackbar.rs

1mod host;
2mod render;
3
4use std::{rc::Rc, time::Duration};
5
6use gpui::{AnyElement, App, EntityId, Hsla, IntoElement, SharedString, Window};
7use gpui_material_theme::CornerShape;
8
9use crate::SemanticTone;
10
11pub use host::SnackbarHost;
12
13pub(super) type Action = Rc<dyn Fn(&mut Window, &mut App)>;
14pub(super) type Content = Box<dyn Fn(&mut Window, &mut App) -> AnyElement>;
15pub(super) type Completion = Rc<dyn Fn(SnackbarResult, &mut Window, &mut App)>;
16pub(super) type HostRenderer =
17    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    /// The snackbar's action button was activated.
23    ActionPerformed,
24    /// The snackbar timed out, was dismissed by the user, or was dismissed programmatically.
25    Dismissed,
26}
27
28/// An entry in one snackbar host's queue.
29#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
30pub struct SnackbarId {
31    pub(super) host: EntityId,
32    pub(super) sequence: usize,
33}
34
35/// Optional per-region colors. Omitted fields use the window's inverse palette.
36#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct SnackbarColors {
38    /// Background color override for the snackbar container.
39    pub container: Option<Hsla>,
40    /// Foreground color override for the message text.
41    pub content: Option<Hsla>,
42    /// Foreground color override for the action button.
43    pub action: Option<Hsla>,
44    /// Foreground color override for the dismiss button.
45    pub dismiss: Option<Hsla>,
46}
47
48/// Host-owned status and activation elements for a custom layout.
49#[non_exhaustive]
50pub struct SnackbarParts {
51    /// The rendered message element.
52    pub message: AnyElement,
53    /// The optional rendered action control.
54    pub action: Option<AnyElement>,
55    /// The optional rendered dismiss control.
56    pub dismiss: Option<AnyElement>,
57    /// Scale to apply to dimensions in the custom container.
58    pub scale: f32,
59}
60
61/// A message for a window's snackbar queue. The default timeout is four seconds.
62pub struct Snackbar {
63    pub(super) message: SharedString,
64    pub(super) timeout: Option<Duration>,
65    pub(super) action: Option<(SharedString, Action)>,
66    pub(super) message_content: Option<Content>,
67    pub(super) action_content: Option<Content>,
68    pub(super) dismiss_label: Option<SharedString>,
69    pub(super) dismiss_content: Option<(SharedString, Content)>,
70    pub(super) show_dismiss: bool,
71    pub(super) action_on_new_line: bool,
72    pub(super) shape: CornerShape,
73    pub(super) tone: SemanticTone,
74    pub(super) colors: SnackbarColors,
75    pub(super) on_dismiss: Option<Action>,
76    pub(super) on_result: Option<Completion>,
77}
78
79impl Snackbar {
80    /// Creates a snackbar with the given message text and a default four-second timeout.
81    pub fn new(message: impl Into<SharedString>) -> Self {
82        Self {
83            message: message.into(),
84            timeout: Some(Duration::from_secs(4)),
85            action: None,
86            message_content: None,
87            action_content: None,
88            dismiss_label: None,
89            dismiss_content: None,
90            show_dismiss: true,
91            action_on_new_line: false,
92            shape: CornerShape::Radii([4.; 4]),
93            tone: SemanticTone::Default,
94            colors: SnackbarColors::default(),
95            on_dismiss: None,
96            on_result: None,
97        }
98    }
99
100    /// Sets how long the message is visible. `None` waits for explicit dismissal.
101    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
102        self.timeout = timeout;
103        self
104    }
105
106    /// Adds a keyboard-accessible action. By default, messages with an action
107    /// persist. Call `timeout` after this method to set a duration explicitly.
108    pub fn action(
109        mut self,
110        label: impl Into<SharedString>,
111        action: impl Fn(&mut Window, &mut App) + 'static,
112    ) -> Self {
113        self.action = Some((label.into(), Rc::new(action)));
114        self.timeout = None;
115        self
116    }
117
118    /// Returns the plain message used as the status announcement.
119    pub fn message(&self) -> &SharedString {
120        &self.message
121    }
122
123    /// Returns the accessible name of the optional action.
124    pub fn action_label(&self) -> Option<&SharedString> {
125        self.action.as_ref().map(|(label, _)| label)
126    }
127
128    /// Replaces the visible message with repeatable decorative content.
129    pub fn message_content<E: IntoElement>(
130        mut self,
131        content: impl Fn(&mut Window, &mut App) -> E + 'static,
132    ) -> Self {
133        self.message_content = Some(Box::new(move |window, cx| {
134            content(window, cx).into_any_element()
135        }));
136        self
137    }
138
139    /// Replaces the visible content of the named action supplied by [`Self::action`].
140    pub fn action_content<E: IntoElement>(
141        mut self,
142        content: impl Fn(&mut Window, &mut App) -> E + 'static,
143    ) -> Self {
144        self.action_content = Some(Box::new(move |window, cx| {
145            content(window, cx).into_any_element()
146        }));
147        self
148    }
149
150    /// Overrides the accessible name of the default dismiss button (default `"Dismiss message"`).
151    pub fn dismiss_label(mut self, label: impl Into<SharedString>) -> Self {
152        self.dismiss_label = Some(label.into());
153        self
154    }
155
156    /// Supplies the accessible name and decorative content of the close affordance.
157    pub fn dismiss_content<E: IntoElement>(
158        mut self,
159        label: impl Into<SharedString>,
160        content: impl Fn(&mut Window, &mut App) -> E + 'static,
161    ) -> Self {
162        self.dismiss_content = Some((
163            label.into(),
164            Box::new(move |window, cx| content(window, cx).into_any_element()),
165        ));
166        self
167    }
168
169    /// Shows or hides the explicit dismiss button. It is shown by default.
170    pub fn show_dismiss(mut self, show: bool) -> Self {
171        self.show_dismiss = show;
172        self
173    }
174
175    /// Places the action below the message for a long action label.
176    pub fn action_on_new_line(mut self, enabled: bool) -> Self {
177        self.action_on_new_line = enabled;
178        self
179    }
180
181    /// Overrides the corner shape of the snackbar container.
182    pub fn shape(mut self, shape: CornerShape) -> Self {
183        self.shape = shape;
184        self
185    }
186
187    /// Applies a Material 3 semantic tone shortcut.
188    ///
189    /// [`SemanticTone::Default`] keeps the M3 inverse palette; semantic tones
190    /// use `(Container, OnContainer, Role)` while explicit [`Self::colors`]
191    /// overrides still take precedence.
192    pub fn tone(mut self, tone: SemanticTone) -> Self {
193        self.tone = tone;
194        self
195    }
196
197    /// Overrides the snackbar's container, content, action, and dismiss colors.
198    pub fn colors(mut self, colors: SnackbarColors) -> Self {
199        self.colors = colors;
200        self
201    }
202
203    /// Runs on timeout, user dismissal, or explicit dismissal by the caller.
204    pub fn on_dismiss(mut self, dismissed: impl Fn(&mut Window, &mut App) + 'static) -> Self {
205        self.on_dismiss = Some(Rc::new(dismissed));
206        self
207    }
208
209    /// Receives one completion after any action or dismissal callback has run.
210    pub fn on_result(
211        mut self,
212        complete: impl Fn(SnackbarResult, &mut Window, &mut App) + 'static,
213    ) -> Self {
214        self.on_result = Some(Rc::new(complete));
215        self
216    }
217}