1use std::time::Duration;
4
5use gpui::{
6 AnyElement, App, AppContext as _, Bounds, Context, Element, ElementId, Entity, EventEmitter,
7 FocusHandle, GlobalElementId, HoverListenerMode, InspectorElementId, InteractiveElement as _,
8 IntoElement, KeyBinding, LayoutId, ParentElement, Pixels, RenderOnce, Role, SharedString,
9 StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, WeakFocusHandle,
10 Window, accesskit, div, prelude::FluentBuilder as _,
11};
12use web_time::Instant;
13
14use crate::{Button, StyledExt as _, TestSupportExt as _, actions::Cancel};
15
16pub(crate) fn init(cx: &mut App) {
17 cx.bind_keys([KeyBinding::new("escape", Cancel, Some("Toast"))]);
18}
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum ToastDismissReason {
22 Timeout,
23 CloseButton,
24 Escape,
25 Imperative,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum ToastEvent {
30 Opened,
31 Dismissed(ToastDismissReason),
32}
33
34pub struct ToastState {
42 focus: FocusHandle,
43 previous_focus: Option<WeakFocusHandle>,
44 duration: Duration,
45 remaining: Duration,
46 running_since: Option<Instant>,
47 timer: Option<Task<()>>,
48 open: bool,
49 mounted: bool,
50 hovered: bool,
51 focused: bool,
52 _subscriptions: Vec<Subscription>,
53}
54
55impl ToastState {
56 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
59 let focus = cx.focus_handle().tab_stop(false);
60 let subscriptions = vec![
61 cx.on_focus_in(&focus, window, |state, _, cx| {
62 state.focused = true;
63 state.pause(cx);
64 }),
65 cx.on_focus_out(&focus, window, |state, _, window, cx| {
66 state.focused = false;
67 state.resume(window, cx);
68 }),
69 cx.observe_window_activation(window, |state, window, cx| {
70 if window.is_window_active() {
71 state.resume(window, cx);
72 } else {
73 state.pause(cx);
74 }
75 }),
76 ];
77 let duration = Duration::from_secs(5);
78 Self {
79 focus,
80 previous_focus: None,
81 duration,
82 remaining: duration,
83 running_since: None,
84 timer: None,
85 open: false,
86 mounted: false,
87 hovered: false,
88 focused: false,
89 _subscriptions: subscriptions,
90 }
91 }
92
93 pub fn with_duration(mut self, duration: Duration) -> Self {
95 assert!(!duration.is_zero(), "Toast duration must be nonzero");
96 self.duration = duration;
97 self.remaining = duration;
98 self
99 }
100
101 pub fn is_open(&self) -> bool {
102 self.open
103 }
104
105 pub fn focus_handle(&self) -> &FocusHandle {
109 &self.focus
110 }
111
112 pub fn show(&mut self, window: &mut Window, cx: &mut Context<Self>) {
114 self.timer = None;
115 self.running_since = None;
116 self.remaining = self.duration;
117 if !self.open {
118 self.previous_focus = window.focused(cx).map(|focus| focus.downgrade());
119 self.open = true;
120 cx.emit(ToastEvent::Opened);
121 }
122 self.resume(window, cx);
123 cx.notify();
124 window.refresh();
125 }
126
127 pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
128 self.dismiss_with_reason(ToastDismissReason::Imperative, window, cx);
129 }
130
131 fn owns_focus(&self, window: &Window, cx: &App) -> bool {
132 self.focus.is_focused(window) || self.focus.contains_focused(window, cx)
133 }
134
135 fn pause(&mut self, cx: &mut Context<Self>) {
136 self.timer = None;
137 if let Some(started) = self.running_since.take() {
138 self.remaining = self
139 .remaining
140 .saturating_sub(cx.background_executor().now().duration_since(started));
141 }
142 }
143
144 fn resume(&mut self, window: &mut Window, cx: &mut Context<Self>) {
145 if !self.open
146 || !self.mounted
147 || self.hovered
148 || self.focused
149 || self.owns_focus(window, cx)
150 || !window.is_window_active()
151 || self.timer.is_some()
152 {
153 return;
154 }
155 self.running_since = Some(cx.background_executor().now());
156 let remaining = self.remaining;
157 self.timer = Some(cx.spawn_in(window, async move |state, cx| {
158 cx.background_executor().timer(remaining).await;
159 let _ = state.update_in(cx, |state, window, cx| {
160 state.timer = None;
161 state.running_since = None;
162 state.remaining = Duration::ZERO;
163 if state.hovered || state.focused || state.owns_focus(window, cx) {
164 return;
165 }
166 state.dismiss_with_reason(ToastDismissReason::Timeout, window, cx);
167 });
168 }));
169 }
170
171 fn hover(&mut self, hovered: bool, window: &mut Window, cx: &mut Context<Self>) {
172 self.hovered = hovered;
173 if hovered {
174 self.pause(cx);
175 } else {
176 self.resume(window, cx);
177 }
178 }
179
180 fn dismiss_with_reason(
181 &mut self,
182 reason: ToastDismissReason,
183 window: &mut Window,
184 cx: &mut Context<Self>,
185 ) {
186 self.timer = None;
187 self.running_since = None;
188 if !self.open {
189 return;
190 }
191 self.open = false;
192 let owns_focus = self.owns_focus(window, cx);
193 let restore = self.previous_focus.take().and_then(|focus| focus.upgrade());
194 self.hovered = false;
195 self.focused = false;
196 if owns_focus {
197 if let Some(focus) = restore {
198 focus.focus(window, cx);
199 } else {
200 window.blur(cx);
201 }
202 }
203 cx.emit(ToastEvent::Dismissed(reason));
204 cx.notify();
205 window.refresh();
206 }
207}
208
209impl EventEmitter<ToastEvent> for ToastState {}
210
211struct ToastMount {
212 _release: Subscription,
213}
214
215struct ToastLive<E> {
218 inner: E,
219 live: Option<accesskit::Live>,
220}
221
222impl<E: Element> IntoElement for ToastLive<E> {
223 type Element = Self;
224
225 fn into_element(self) -> Self {
226 self
227 }
228}
229
230impl<E: Element> Element for ToastLive<E> {
231 type RequestLayoutState = E::RequestLayoutState;
232 type PrepaintState = E::PrepaintState;
233
234 fn id(&self) -> Option<ElementId> {
235 self.inner.id()
236 }
237
238 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
239 self.inner.source_location()
240 }
241
242 fn request_layout(
243 &mut self,
244 id: Option<&GlobalElementId>,
245 inspector: Option<&InspectorElementId>,
246 window: &mut Window,
247 cx: &mut App,
248 ) -> (LayoutId, Self::RequestLayoutState) {
249 self.inner.request_layout(id, inspector, window, cx)
250 }
251
252 fn prepaint(
253 &mut self,
254 id: Option<&GlobalElementId>,
255 inspector: Option<&InspectorElementId>,
256 bounds: Bounds<Pixels>,
257 layout: &mut Self::RequestLayoutState,
258 window: &mut Window,
259 cx: &mut App,
260 ) -> Self::PrepaintState {
261 self.inner
262 .prepaint(id, inspector, bounds, layout, window, cx)
263 }
264
265 fn paint(
266 &mut self,
267 id: Option<&GlobalElementId>,
268 inspector: Option<&InspectorElementId>,
269 bounds: Bounds<Pixels>,
270 layout: &mut Self::RequestLayoutState,
271 prepaint: &mut Self::PrepaintState,
272 window: &mut Window,
273 cx: &mut App,
274 ) {
275 self.inner
276 .paint(id, inspector, bounds, layout, prepaint, window, cx);
277 }
278
279 fn a11y_role(&self) -> Option<Role> {
280 self.inner.a11y_role()
281 }
282
283 fn write_a11y_info(&self, node: &mut accesskit::Node) {
284 self.inner.write_a11y_info(node);
285 if let Some(live) = self.live {
286 node.set_live(live);
287 node.set_live_atomic();
288 }
289 }
290
291 fn a11y_synthetic_children(
292 &mut self,
293 prepaint: &mut Self::PrepaintState,
294 builder: &mut gpui::A11ySubtreeBuilder,
295 ) {
296 Element::a11y_synthetic_children(&mut self.inner, prepaint, builder);
297 }
298}
299
300#[derive(IntoElement)]
306pub struct Toast {
307 id: ElementId,
308 state: Entity<ToastState>,
309 style: StyleRefinement,
310 children: Vec<AnyElement>,
311 label: Option<SharedString>,
312 urgent: bool,
313}
314
315impl Toast {
316 pub fn new(id: impl Into<ElementId>, state: &Entity<ToastState>) -> Self {
317 Self {
318 id: id.into(),
319 state: state.clone(),
320 style: StyleRefinement::default(),
321 children: Vec::new(),
322 label: None,
323 urgent: false,
324 }
325 }
326
327 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
330 self.label = Some(label.into());
331 self
332 }
333
334 pub fn urgent(mut self, urgent: bool) -> Self {
335 self.urgent = urgent;
336 self
337 }
338}
339
340impl Styled for Toast {
341 fn style(&mut self) -> &mut StyleRefinement {
342 &mut self.style
343 }
344}
345
346impl ParentElement for Toast {
347 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
348 self.children.extend(children);
349 }
350}
351
352impl RenderOnce for Toast {
353 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
354 let weak = self.state.downgrade();
355 let owner_window = window.window_handle();
356 window.with_element_namespace(self.id.clone(), |window| {
357 window.use_keyed_state(("toast-mount", self.state.entity_id()), cx, |_, cx| {
358 ToastMount {
359 _release: cx.on_release(move |_, cx| {
360 let _ = owner_window.update(cx, |_, window, cx| {
361 let _ = weak.update(cx, |state, cx| {
362 state.mounted = false;
363 state.previous_focus = None;
365 state.dismiss(window, cx);
366 });
367 });
368 }),
369 }
370 })
371 });
372 self.state.update(cx, |state, cx| {
373 state.mounted = true;
374 state.resume(window, cx);
375 });
376 let model = self.state.read(cx);
377 let base = div().id(self.id).test_support();
378 if !model.open {
379 return ToastLive {
380 inner: base,
381 live: None,
382 };
383 }
384 let focus = model.focus.clone();
385 let hover = self.state.clone();
386 let dismiss = self.state;
387 let surface = base
388 .role(if self.urgent {
389 Role::Alert
390 } else {
391 Role::Status
392 })
393 .when_some(self.label, |this, label| {
394 this.aria_label(label.clone()).aria_value(label)
395 })
396 .key_context("Toast")
397 .track_focus(&focus)
398 .hover_listener_mode(HoverListenerMode::InputModalityIndependent)
399 .on_hover(move |hovered, window, cx| {
400 hover.update(cx, |state, cx| state.hover(*hovered, window, cx));
401 })
402 .on_action(move |_: &Cancel, window, cx| {
403 dismiss.update(cx, |state, cx| {
404 state.dismiss_with_reason(ToastDismissReason::Escape, window, cx);
405 });
406 })
407 .children(self.children)
408 .refine_style(&self.style);
409 ToastLive {
410 inner: surface,
411 live: Some(if self.urgent {
412 accesskit::Live::Assertive
413 } else {
414 accesskit::Live::Polite
415 }),
416 }
417 }
418}
419
420#[derive(IntoElement)]
422pub struct ToastClose {
423 button: Button,
424}
425
426impl ToastClose {
427 pub fn new(id: impl Into<ElementId>, state: &Entity<ToastState>) -> Self {
428 let state = state.clone();
429 Self {
430 button: Button::new(id)
431 .accessibility_label("Dismiss notification")
432 .on_click(move |_, window, cx| {
433 state.update(cx, |state, cx| {
434 state.dismiss_with_reason(ToastDismissReason::CloseButton, window, cx);
435 });
436 }),
437 }
438 }
439
440 pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
441 self.button = build(self.button);
442 self
443 }
444}
445
446impl RenderOnce for ToastClose {
447 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
448 self.button
449 }
450}
451
452#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
454pub struct ToastKey(u64);
455
456impl From<ToastKey> for ElementId {
457 fn from(key: ToastKey) -> Self {
458 ElementId::NamedInteger("toast".into(), key.0)
459 }
460}
461
462struct ToasterEntry<T> {
463 key: ToastKey,
464 value: T,
465 state: Entity<ToastState>,
466 _subscription: Subscription,
467}
468
469pub struct ToasterState<T> {
477 entries: Vec<ToasterEntry<T>>,
478 visible: usize,
479 duration: Duration,
480 next: u64,
481}
482
483impl<T: 'static> ToasterState<T> {
484 pub fn new() -> Self {
486 Self {
487 entries: Vec::new(),
488 visible: 3,
489 duration: Duration::from_secs(5),
490 next: 0,
491 }
492 }
493
494 pub fn visible_limit(mut self, visible: usize) -> Self {
496 assert!(visible > 0, "Toaster must show at least one notification");
497 self.visible = visible;
498 self
499 }
500
501 pub fn with_duration(mut self, duration: Duration) -> Self {
503 assert!(!duration.is_zero(), "Toast duration must be nonzero");
504 self.duration = duration;
505 self
506 }
507
508 pub fn push(&mut self, value: T, window: &mut Window, cx: &mut Context<Self>) -> ToastKey {
510 let key = ToastKey(self.next);
511 self.next += 1;
512 let duration = self.duration;
513 let state = cx.new(|cx| ToastState::new(window, cx).with_duration(duration));
514 let subscription = cx.subscribe(&state, move |this, _, event: &ToastEvent, cx| {
515 if matches!(event, ToastEvent::Dismissed(_)) {
516 this.entries.retain(|entry| entry.key != key);
517 cx.notify();
518 }
519 });
520 state.update(cx, |state, cx| state.show(window, cx));
521 self.entries.push(ToasterEntry {
522 key,
523 value,
524 state,
525 _subscription: subscription,
526 });
527 cx.notify();
528 key
529 }
530
531 pub fn replace(
535 &mut self,
536 key: ToastKey,
537 value: T,
538 window: &mut Window,
539 cx: &mut Context<Self>,
540 ) -> bool {
541 let Some(entry) = self.entries.iter_mut().find(|entry| entry.key == key) else {
542 return false;
543 };
544 entry.value = value;
545 entry.state.update(cx, |state, cx| state.show(window, cx));
546 cx.notify();
547 true
548 }
549
550 pub fn dismiss(&mut self, key: ToastKey, window: &mut Window, cx: &mut Context<Self>) {
551 if let Some(entry) = self.entries.iter().find(|entry| entry.key == key) {
552 entry
553 .state
554 .update(cx, |state, cx| state.dismiss(window, cx));
555 }
556 }
557
558 pub fn dismiss_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
559 for entry in &self.entries {
560 entry
561 .state
562 .update(cx, |state, cx| state.dismiss(window, cx));
563 }
564 }
565
566 pub fn len(&self) -> usize {
568 self.entries.len()
569 }
570
571 pub fn is_empty(&self) -> bool {
572 self.entries.is_empty()
573 }
574
575 pub fn visible(&self) -> impl Iterator<Item = (ToastKey, &T, &Entity<ToastState>)> {
577 self.entries
578 .iter()
579 .rev()
580 .take(self.visible)
581 .map(|entry| (entry.key, &entry.value, &entry.state))
582 }
583
584 pub fn focus_latest(&mut self, window: &mut Window, cx: &mut Context<Self>) {
587 if let Some(entry) = self.entries.last() {
588 entry.state.read(cx).focus.clone().focus(window, cx);
589 }
590 }
591}
592
593impl<T: 'static> Default for ToasterState<T> {
594 fn default() -> Self {
595 Self::new()
596 }
597}
598
599type RenderToast<T> = Box<dyn Fn(ToastKey, &T, &Entity<ToastState>) -> Toast>;
600
601#[derive(IntoElement)]
604pub struct Toaster<T: 'static> {
605 id: ElementId,
606 state: Entity<ToasterState<T>>,
607 label: SharedString,
608 render: RenderToast<T>,
609 style: StyleRefinement,
610}
611
612impl<T: 'static> Toaster<T> {
613 pub fn new(
615 id: impl Into<ElementId>,
616 state: &Entity<ToasterState<T>>,
617 render: impl Fn(ToastKey, &T, &Entity<ToastState>) -> Toast + 'static,
618 ) -> Self {
619 Self {
620 id: id.into(),
621 state: state.clone(),
622 label: "Notifications".into(),
623 render: Box::new(render),
624 style: StyleRefinement::default(),
625 }
626 }
627
628 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
629 self.label = label.into();
630 self
631 }
632}
633
634impl<T: 'static> Styled for Toaster<T> {
635 fn style(&mut self) -> &mut StyleRefinement {
636 &mut self.style
637 }
638}
639
640impl<T: 'static> RenderOnce for Toaster<T> {
641 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
642 let toasts: Vec<_> = self
643 .state
644 .read(cx)
645 .visible()
646 .map(|(key, value, state)| (self.render)(key, value, state))
647 .collect();
648 div()
649 .id(self.id)
650 .test_support()
651 .role(Role::Group)
652 .aria_label(self.label)
653 .flex()
654 .flex_col()
655 .children(toasts)
656 .refine_style(&self.style)
657 }
658}
659
660#[cfg(test)]
661mod tests {
662 use gpui::{Modifiers, Render, TestAppContext, VisualTestContext, point, px};
663
664 use super::*;
665
666 struct Harness {
667 state: Entity<ToastState>,
668 trigger: FocusHandle,
669 close: FocusHandle,
670 urgent: bool,
671 show_host: bool,
672 _subscription: Subscription,
673 }
674
675 impl Render for Harness {
676 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
677 if !self.show_host {
678 return div().into_any_element();
679 }
680 let close = self.close.clone();
681 let surface = Toast::new("notice", &self.state)
682 .accessibility_label("Saved locally")
683 .urgent(self.urgent)
684 .w(px(240.))
685 .h(px(60.))
686 .child("Saved locally")
687 .child(
688 ToastClose::new("close-notice", &self.state)
689 .trigger(|button| button.track_focus(&close).child("Dismiss")),
690 )
691 .render(window, cx)
692 .into_element();
693 if self.state.read(cx).is_open() {
694 let role = if self.urgent {
695 Role::Alert
696 } else {
697 Role::Status
698 };
699 let mut node = accesskit::Node::new(role);
700 surface.write_a11y_info(&mut node);
701 assert_eq!(surface.a11y_role(), Some(role));
702 assert_eq!(node.label(), Some("Saved locally"));
703 assert_eq!(node.value(), Some("Saved locally"));
704 assert_eq!(
705 node.live(),
706 Some(if self.urgent {
707 accesskit::Live::Assertive
708 } else {
709 accesskit::Live::Polite
710 })
711 );
712 assert!(node.is_live_atomic());
713 }
714 div()
715 .size_full()
716 .flex()
717 .flex_col()
718 .child(
719 Button::new("trigger")
720 .track_focus(&self.trigger)
721 .h(px(30.))
722 .child("Show"),
723 )
724 .child(
725 div()
726 .debug_selector(|| "notice".into())
727 .w(px(240.))
728 .h(px(60.))
729 .child(surface),
730 )
731 .into_any_element()
732 }
733 }
734
735 #[gpui::test]
736 fn lifetime_pauses_for_hover_and_focus_and_dismissal_restores_focus(cx: &mut TestAppContext) {
737 cx.update(crate::init);
738 let (root, cx) = cx.add_window_view(|window, cx| {
739 let view = cx.new(|cx| {
740 let state =
741 cx.new(|cx| ToastState::new(window, cx).with_duration(Duration::from_secs(4)));
742 Harness {
743 _subscription: cx.observe(&state, |_, _, cx| cx.notify()),
744 state,
745 trigger: cx.focus_handle(),
746 close: cx.focus_handle(),
747 urgent: false,
748 show_host: true,
749 }
750 });
751 crate::Root::new(view, window, cx)
752 });
753 let view = root
754 .read_with(cx, |root, _| root.view().clone())
755 .downcast::<Harness>()
756 .unwrap();
757 cx.update(|window, cx| {
758 window.activate_window();
759 view.read(cx).trigger.clone().focus(window, cx);
760 let state = view.read(cx).state.clone();
761 state.update(cx, |state, cx| state.show(window, cx));
762 window.draw(cx).clear(cx);
763 });
764 cx.run_until_parked();
765 cx.executor().advance_clock(Duration::from_secs(1));
766 let notice = cx.debug_bounds("notice").unwrap().center();
767 cx.simulate_mouse_move(notice, None, Modifiers::default());
768 cx.run_until_parked();
769 cx.executor().advance_clock(Duration::from_secs(8));
770 cx.run_until_parked();
771 cx.update(|_, cx| assert!(view.read(cx).state.read(cx).is_open()));
772 cx.simulate_mouse_move(point(px(600.), px(400.)), None, Modifiers::default());
773 cx.run_until_parked();
774 cx.executor().advance_clock(Duration::from_secs(2));
775 cx.run_until_parked();
776 cx.update(|window, cx| {
777 assert!(view.read(cx).state.read(cx).is_open());
778 view.read(cx).close.clone().focus(window, cx);
779 view.update(cx, |view, cx| {
780 view.urgent = true;
781 cx.notify();
782 });
783 window.draw(cx).clear(cx);
784 });
785 cx.run_until_parked();
786 cx.executor().advance_clock(Duration::from_secs(8));
787 cx.run_until_parked();
788 cx.update(|_, cx| assert!(view.read(cx).state.read(cx).is_open()));
789 cx.simulate_keystrokes("escape");
790 cx.run_until_parked();
791 cx.update(|window, cx| {
792 assert!(!view.read(cx).state.read(cx).is_open());
793 assert!(view.read(cx).trigger.is_focused(window));
794 let state = view.read(cx).state.clone();
795 state.update(cx, |state, cx| state.show(window, cx));
796 window.draw(cx).clear(cx);
797 });
798 cx.run_until_parked();
799 cx.executor().advance_clock(Duration::from_secs(4));
800 cx.run_until_parked();
801 cx.update(|window, cx| {
802 assert!(!view.read(cx).state.read(cx).is_open());
803 assert!(view.read(cx).trigger.is_focused(window));
804 });
805 let replaced = cx.update(|window, cx| {
806 let previous = view.read(cx).state.clone();
807 previous.update(cx, |state, cx| state.show(window, cx));
808 window.draw(cx).clear(cx);
809 let replacement =
810 cx.new(|cx| ToastState::new(window, cx).with_duration(Duration::from_secs(4)));
811 replacement.update(cx, |state, cx| state.show(window, cx));
812 view.update(cx, |view, cx| {
813 view._subscription = cx.observe(&replacement, |_, _, cx| cx.notify());
814 view.state = replacement;
815 cx.notify();
816 });
817 window.draw(cx).clear(cx);
818 previous
819 });
820 cx.run_until_parked();
821 cx.update(|_, cx| {
822 assert!(
823 !replaced.read(cx).is_open(),
824 "replacing the state at the same UI ID must release the old notification"
825 );
826 assert!(view.read(cx).state.read(cx).is_open());
827 });
828 cx.update(|window, cx| {
829 let state = view.read(cx).state.clone();
830 state.update(cx, |state, cx| state.show(window, cx));
831 state.read(cx).focus.clone().focus(window, cx);
832 window.draw(cx).clear(cx);
833 view.update(cx, |view, cx| {
834 view.show_host = false;
835 cx.notify();
836 });
837 window.draw(cx).clear(cx);
838 });
839 cx.run_until_parked();
840 cx.update(|window, cx| {
841 assert!(!view.read(cx).state.read(cx).is_open());
842 assert!(
843 !view.read(cx).trigger.is_focused(window),
844 "unmounting a notification must not focus its hidden trigger"
845 );
846 });
847 }
848
849 struct StackHarness {
850 toaster: Entity<ToasterState<&'static str>>,
851 trigger: FocusHandle,
852 _subscription: Subscription,
853 }
854
855 impl Render for StackHarness {
856 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
857 div()
858 .size_full()
859 .flex()
860 .flex_col()
861 .child(
862 Button::new("trigger")
863 .track_focus(&self.trigger)
864 .h(px(30.))
865 .child("Show"),
866 )
867 .child(
868 Toaster::new("stack", &self.toaster, |key, message, state| {
869 Toast::new(key, state)
870 .accessibility_label(*message)
871 .h(px(40.))
872 .child(*message)
873 .child(
874 ToastClose::new((ElementId::from(key), "close"), state)
875 .trigger(|button| button.child("Dismiss")),
876 )
877 })
878 .w(px(240.)),
879 )
880 }
881 }
882
883 #[gpui::test]
884 fn toaster_limits_mounted_toasts_and_queues_older_ones(cx: &mut TestAppContext) {
885 cx.update(crate::init);
886 let (root, cx) = cx.add_window_view(|window, cx| {
887 let view = cx.new(|cx| {
888 let toaster = cx.new(|_| {
889 ToasterState::new()
890 .visible_limit(3)
891 .with_duration(Duration::from_secs(4))
892 });
893 StackHarness {
894 _subscription: cx.observe(&toaster, |_, _, cx| cx.notify()),
895 toaster,
896 trigger: cx.focus_handle(),
897 }
898 });
899 crate::Root::new(view, window, cx)
900 });
901 let view = root
902 .read_with(cx, |root, _| root.view().clone())
903 .downcast::<StackHarness>()
904 .unwrap();
905 let toaster = cx.update(|_, cx| view.read(cx).toaster.clone());
906 let draw = |cx: &mut VisualTestContext| {
907 cx.update(|window, cx| window.draw(cx).clear(cx));
908 cx.run_until_parked();
909 };
910 let messages = |cx: &mut VisualTestContext| {
911 cx.update(|_, cx| {
912 toaster
913 .read(cx)
914 .visible()
915 .map(|(_, message, _)| *message)
916 .collect::<Vec<_>>()
917 })
918 };
919 let first = cx.update(|window, cx| {
920 window.activate_window();
921 view.read(cx).trigger.clone().focus(window, cx);
922 toaster.update(cx, |toaster, cx| {
923 let first = toaster.push("One", window, cx);
924 for message in ["Two", "Three", "Four"] {
925 toaster.push(message, window, cx);
926 }
927 first
928 })
929 });
930 draw(cx);
931 assert_eq!(messages(cx), ["Four", "Three", "Two"]);
932 cx.update(|window, cx| {
933 assert_eq!(toaster.read(cx).len(), 4);
934 assert!(
935 view.read(cx).trigger.is_focused(window),
936 "showing never takes focus"
937 );
938 let region = crate::test_support::find(window, &[], &"stack".into()).unwrap();
939 assert_eq!(region.role(), Some(Role::Group));
940 assert_eq!(region.label(), Some("Notifications"));
941 assert!(crate::test_support::find(window, &[], &first.into()).is_none());
942 });
943
944 cx.executor().advance_clock(Duration::from_secs(4));
946 cx.run_until_parked();
947 draw(cx);
948 assert_eq!(messages(cx), ["One"]);
949 cx.executor().advance_clock(Duration::from_secs(3));
950 cx.run_until_parked();
951 cx.update(|window, cx| {
952 toaster.update(cx, |toaster, cx| {
953 assert!(toaster.replace(first, "One finished", window, cx));
954 })
955 });
956 draw(cx);
957 cx.executor().advance_clock(Duration::from_secs(3));
958 cx.run_until_parked();
959 assert_eq!(
960 messages(cx),
961 ["One finished"],
962 "replacing restarts its lifetime"
963 );
964 cx.executor().advance_clock(Duration::from_secs(1));
965 cx.run_until_parked();
966 cx.update(|window, cx| {
967 assert!(toaster.read(cx).is_empty());
968 toaster.update(cx, |toaster, cx| {
969 assert!(!toaster.replace(first, "Gone", window, cx));
970 toaster.push("Five", window, cx);
971 });
972 });
973 draw(cx);
974
975 cx.update(|window, cx| toaster.update(cx, |toaster, cx| toaster.focus_latest(window, cx)));
977 draw(cx);
978 cx.simulate_keystrokes("escape");
979 cx.run_until_parked();
980 cx.update(|window, cx| {
981 assert!(toaster.read(cx).is_empty());
982 assert!(view.read(cx).trigger.is_focused(window));
983 toaster.update(cx, |toaster, cx| {
984 toaster.push("Six", window, cx);
985 toaster.push("Seven", window, cx);
986 toaster.dismiss_all(window, cx);
987 });
988 });
989 cx.run_until_parked();
990 cx.update(|_, cx| assert!(toaster.read(cx).is_empty()));
991 }
992}