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