Skip to main content

gpui_material_components/overlay/snackbar/
host.rs

1use std::{cell::Cell, collections::VecDeque, rc::Rc};
2
3use gpui::{
4    App, Context, FocusHandle, IntoElement, ParentElement, Render, SharedString, Styled,
5    Subscription, Task, WeakFocusHandle, Window, canvas, div, point, prelude::FluentBuilder, px,
6};
7use gpui_material_foundation::{OverlayMotion, ScaledOverlay};
8
9use super::super::modal::ZLayer;
10use super::render::snackbar_surface;
11use super::{HostRenderer, Snackbar, SnackbarId, SnackbarParts, SnackbarResult};
12
13const MAX_WIDTH: gpui::Pixels = px(672.);
14const MAX_EXITING: usize = 4;
15
16pub(super) struct Entry {
17    pub(super) id: SnackbarId,
18    pub(super) message: Snackbar,
19    pub(super) controls: [FocusHandle; 2],
20    return_focus: Option<WeakFocusHandle>,
21}
22
23/// One FIFO message queue per host. Mount the entity in the window layout.
24/// A new message leaves keyboard focus wherever it is.
25#[derive(Default)]
26pub struct SnackbarHost {
27    pub(super) active: Option<Entry>,
28    exiting: Vec<Entry>,
29    pending: VecDeque<(SnackbarId, Snackbar)>,
30    next_id: usize,
31    timer: Option<Task<()>>,
32    hovered: bool,
33    focused: bool,
34    last_external_focus: Option<WeakFocusHandle>,
35    _focus_subscriptions: Vec<Subscription>,
36    renderer: Option<HostRenderer>,
37}
38
39impl SnackbarHost {
40    /// Unified overlay z-layer priority for snackbars.
41    #[allow(dead_code)]
42    pub(crate) const Z_LAYER: ZLayer = ZLayer::SNACKBAR;
43
44    /// Uses a custom container and layout for the host-owned message and controls.
45    pub fn renderer<E: IntoElement>(
46        mut self,
47        render: impl Fn(&Snackbar, SnackbarParts, &mut Window, &mut App) -> E + 'static,
48    ) -> Self {
49        self.renderer = Some(Box::new(move |message, parts, window, cx| {
50            render(message, parts, window, cx).into_any_element()
51        }));
52        self
53    }
54
55    /// Queues the message after any already pending messages.
56    pub fn push(&mut self, snackbar: Snackbar, window: &mut Window, cx: &mut Context<Self>) {
57        self.enqueue(snackbar, window, cx);
58    }
59
60    /// Queues a plain message snackbar and returns its opaque identity.
61    pub fn push_message(
62        &mut self,
63        message: impl Into<SharedString>,
64        window: &mut Window,
65        cx: &mut Context<Self>,
66    ) -> SnackbarId {
67        self.enqueue(Snackbar::new(message), window, cx)
68    }
69
70    /// Dismisses the currently active snackbar (if any, firing its dismissal
71    /// completion cleanly) and immediately presents the new snackbar ahead of
72    /// any pending entries.
73    pub fn replace(
74        &mut self,
75        snackbar: Snackbar,
76        window: &mut Window,
77        cx: &mut Context<Self>,
78    ) -> SnackbarId {
79        self.next_id += 1;
80        let id = SnackbarId {
81            host: cx.entity_id(),
82            sequence: self.next_id,
83        };
84        self.pending.push_front((id, snackbar));
85        if let Some((active_id, _)) = self.current() {
86            self.finish(active_id, SnackbarResult::Dismissed, window, cx);
87        } else {
88            self.show_next(window, cx);
89        }
90        id
91    }
92
93    /// Queues the message and returns an opaque identity scoped to this host.
94    pub fn enqueue(
95        &mut self,
96        snackbar: Snackbar,
97        window: &mut Window,
98        cx: &mut Context<Self>,
99    ) -> SnackbarId {
100        self.next_id += 1;
101        let id = SnackbarId {
102            host: cx.entity_id(),
103            sequence: self.next_id,
104        };
105        self.pending.push_back((id, snackbar));
106        if self.active.is_none() {
107            self.show_next(window, cx);
108        } else {
109            cx.notify();
110        }
111        id
112    }
113
114    /// Returns the active entry. Pending and exiting entries are excluded.
115    pub fn current(&self) -> Option<(SnackbarId, &Snackbar)> {
116        self.active.as_ref().map(|entry| (entry.id, &entry.message))
117    }
118
119    /// Returns the number of queued snackbars waiting behind the active entry.
120    pub fn pending_len(&self) -> usize {
121        self.pending.len()
122    }
123
124    /// Discards all queued snackbars waiting behind the active entry without
125    /// disturbing the currently visible snackbar.
126    pub fn clear_queue(&mut self, cx: &mut Context<Self>) {
127        if !self.pending.is_empty() {
128            self.pending.clear();
129            cx.notify();
130        }
131    }
132
133    /// Dismisses the active message. If any are queued, the next begins its own timeout.
134    pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
135        if let Some((id, _)) = self.current() {
136            self.dismiss_message(id, window, cx);
137        }
138    }
139
140    /// Dismisses the entry if it is still current.
141    pub fn dismiss_message(
142        &mut self,
143        id: SnackbarId,
144        window: &mut Window,
145        cx: &mut Context<Self>,
146    ) -> bool {
147        self.finish(id, SnackbarResult::Dismissed, window, cx)
148    }
149
150    /// Performs the entry's action if it is current and has an action.
151    pub fn perform_action(
152        &mut self,
153        id: SnackbarId,
154        window: &mut Window,
155        cx: &mut Context<Self>,
156    ) -> bool {
157        self.finish(id, SnackbarResult::ActionPerformed, window, cx)
158    }
159
160    fn show_next(&mut self, window: &mut Window, cx: &mut Context<Self>) {
161        self.hovered = false;
162        self.focused = false;
163        self._focus_subscriptions.clear();
164        self.timer = None;
165        self.last_external_focus = window.focused(cx).map(|focus| focus.downgrade());
166        self.active = self.pending.pop_front().map(|(id, message)| Entry {
167            id,
168            message,
169            controls: [cx.focus_handle(), cx.focus_handle()],
170            return_focus: None,
171        });
172        if let Some(entry) = &self.active {
173            let controls = entry.controls.clone();
174            for handle in &controls {
175                let enter = cx.weak_entity();
176                let leave = enter.clone();
177                self._focus_subscriptions.push(window.on_focus_in(
178                    handle,
179                    cx,
180                    move |window, cx| {
181                        let _ = enter.update(cx, |host, cx| host.refresh_focus(window, cx));
182                    },
183                ));
184                self._focus_subscriptions.push(window.on_focus_out(
185                    handle,
186                    cx,
187                    move |_, window, cx| {
188                        let _ = leave.update(cx, |host, cx| host.refresh_focus(window, cx));
189                    },
190                ));
191            }
192        }
193        self.sync_timer(window, cx);
194        cx.notify();
195    }
196
197    pub(super) fn set_hovered(
198        &mut self,
199        hovered: bool,
200        window: &mut Window,
201        cx: &mut Context<Self>,
202    ) {
203        if self.hovered != hovered {
204            self.hovered = hovered;
205            self.sync_timer(window, cx);
206        }
207    }
208
209    fn refresh_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
210        let focused = self
211            .active
212            .as_ref()
213            .is_some_and(|entry| entry.controls.iter().any(|focus| focus.is_focused(window)));
214        if self.focused != focused {
215            self.focused = focused;
216            if let Some(entry) = &mut self.active {
217                if focused {
218                    // Only capture return focus when focus actually enters the snackbar.
219                    entry.return_focus = self.last_external_focus.clone();
220                } else {
221                    entry.return_focus = None;
222                }
223            }
224            self.sync_timer(window, cx);
225        }
226    }
227
228    fn sync_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
229        if self.hovered || self.focused {
230            self.timer = None;
231            return;
232        }
233        if self.timer.is_some() {
234            return;
235        }
236        self.timer = self.active.as_ref().and_then(|entry| {
237            let id = entry.id;
238            let timeout = entry.message.timeout?;
239            Some(cx.spawn_in(window, async move |this, cx| {
240                cx.background_executor().timer(timeout).await;
241                let _ = this.update_in(cx, |this, window, cx| {
242                    this.dismiss_message(id, window, cx);
243                });
244            }))
245        });
246    }
247
248    pub(super) fn finish(
249        &mut self,
250        id: SnackbarId,
251        result: SnackbarResult,
252        window: &mut Window,
253        cx: &mut Context<Self>,
254    ) -> bool {
255        let Some(active) = self.active.as_ref().filter(|entry| entry.id == id) else {
256            return false;
257        };
258        let callback = match result {
259            SnackbarResult::ActionPerformed => {
260                let Some((_, callback)) = &active.message.action else {
261                    return false;
262                };
263                Some(callback.clone())
264            }
265            SnackbarResult::Dismissed => active.message.on_dismiss.clone(),
266        };
267        let mut entry = self.active.take().expect("current entry checked above");
268        let complete = entry.message.on_result.take();
269        if entry.controls.iter().any(|focus| focus.is_focused(window)) {
270            if let Some(restore) = entry.return_focus.take().and_then(|focus| focus.upgrade()) {
271                restore.focus(window, cx);
272            } else {
273                window.blur(cx);
274            }
275        }
276        if !cx.reduce_motion() {
277            if self.exiting.len() >= MAX_EXITING {
278                self.exiting.remove(0);
279            }
280            self.exiting.push(entry);
281        }
282        self.show_next(window, cx);
283        if callback.is_some() || complete.is_some() {
284            window.defer(cx, move |window, cx| {
285                if let Some(callback) = callback {
286                    callback(window, cx);
287                }
288                if let Some(complete) = complete {
289                    complete(result, window, cx);
290                }
291            });
292        }
293        true
294    }
295}
296
297impl Render for SnackbarHost {
298    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
299        if !self.focused
300            && let Some(focused) = window.focused(cx)
301            && self
302                .active
303                .as_ref()
304                .is_none_or(|entry| !entry.controls.iter().any(|handle| handle == &focused))
305        {
306            self.last_external_focus = Some(focused.downgrade());
307        }
308        let host_width = window
309            .use_keyed_state(("snackbar-host-width", cx.entity_id()), cx, |_, _| {
310                Rc::new(Cell::new(px(0.)))
311            })
312            .read(cx)
313            .clone();
314        let measured_width = host_width.get();
315        let width = if measured_width > px(0.) {
316            measured_width
317        } else {
318            (window.viewport_size().width - px(32.)).clamp(px(0.), MAX_WIDTH)
319        };
320        let mut root = div().relative().w_full().child(
321            canvas(
322                move |bounds, window, _| {
323                    if host_width.replace(bounds.size.width) != bounds.size.width {
324                        window.request_animation_frame();
325                    }
326                },
327                |_, _, _, _| {},
328            )
329            .absolute()
330            .inset_0(),
331        );
332        let mut has_layout = self.active.is_some();
333        let renderer = self.renderer.as_ref();
334        self.exiting.retain(|entry| {
335            let Some(motion) =
336                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), false, window, cx)
337            else {
338                return false;
339            };
340            let content = snackbar_surface(entry, motion, width, false, renderer, window, cx);
341            let scaled = ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width);
342            let slot = div().when(has_layout, |div| div.absolute().inset_0());
343            root.extend([slot.child(scaled).into_any_element()]);
344            has_layout = true;
345            true
346        });
347        if let Some(entry) = &self.active {
348            let motion =
349                OverlayMotion::sample(&("snackbar", entry.id.sequence).into(), true, window, cx)
350                    .expect("active snackbar has motion");
351            let content = snackbar_surface(entry, motion, width, true, renderer, window, cx);
352            root =
353                root.child(ScaledOverlay::new(content, motion, |_| point(0.5, 0.5)).width(width));
354        }
355        root
356    }
357}