BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / notification.rs

notification.rs

notification.rs 65.6 KiB Download Raw
1use std::{
2 any::TypeId,
3 borrow::Cow,
4 collections::{HashMap, HashSet},
5 rc::Rc,
6 time::Duration,
7};
8
9use gpui::{
10 Anchor, Animation, AnimationExt, AnyElement, AnyWindowHandle, App, AppContext, ClickEvent,
11 Context, DismissEvent, ElementId, Entity, EventEmitter, FocusHandle, Global,
12 InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, SharedString,
13 StatefulInteractiveElement, StyleRefinement, Styled, Subscription, SystemNotification,
14 SystemNotificationResponse, WeakEntity, Window, WindowId, div, prelude::FluentBuilder, px,
15 relative,
16};
17use gpui_base::{
18 Toast as BaseToast, ToastManager, ToastMotion, ToastOptions, ToastStack, ToastStackState,
19 ToastTransitionStatus,
20};
21
22use crate::{
23 ActiveTheme as _, Edges, Icon, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT,
24 animation::cubic_bezier,
25 button::{Button, ButtonVariants as _},
26 v_flex,
27};
28
29const NOTIFICATION_TRANSITION_DURATION: Duration = Duration::from_millis(400);
30const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);
31const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);
32const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);
33const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);
34struct DismissRequest;
35
36#[derive(Debug, Clone, Copy, Default)]
37pub enum NotificationType {
38 #[default]
39 Info,
40 Success,
41 Warning,
42 Error,
43}
44
45impl NotificationType {
46 fn icon(&self, cx: &App) -> Icon {
47 match self {
48 Self::Info => Icon::new(IconName::Info).text_color(cx.theme().info),
49 Self::Success => Icon::new(IconName::CircleCheck).text_color(cx.theme().success),
50 Self::Warning => Icon::new(IconName::TriangleAlert).text_color(cx.theme().warning),
51 Self::Error => Icon::new(IconName::CircleX).text_color(cx.theme().danger),
52 }
53 }
54}
55
56/// Where a notification is presented: as an in-app toast, in the operating
57/// system's notification center, or both.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub enum NotificationDelivery {
60 /// Show only the in-app toast.
61 #[default]
62 InApp,
63 /// Post only to the OS notification center; no in-app toast is shown.
64 System,
65 /// Show the in-app toast and post to the OS notification center.
66 InAppAndSystem,
67}
68
69impl NotificationDelivery {
70 /// Whether this delivery shows an in-app toast.
71 pub fn includes_in_app(&self) -> bool {
72 matches!(self, Self::InApp | Self::InAppAndSystem)
73 }
74
75 /// Whether this delivery posts to the OS notification center.
76 pub fn includes_system(&self) -> bool {
77 matches!(self, Self::System | Self::InAppAndSystem)
78 }
79}
80
81/// Namespaces the library's system-notification tags away from tags the
82/// application posts itself, so the response handler can tell them apart.
83const SYSTEM_TAG_PREFIX: &str = "gpui-component/notification/";
84
85#[derive(Debug, PartialEq, Clone, Hash, Eq)]
86pub(crate) enum NotificationId {
87 Id(TypeId),
88 IdAndElementId(TypeId, ElementId),
89}
90
91impl NotificationId {
92 /// Stable OS-notification tag for this id within a running binary, so a
93 /// repeat push with the same id replaces the previous system
94 /// notification, mirroring the in-app replace semantics.
95 fn system_tag(&self) -> SharedString {
96 format!("{SYSTEM_TAG_PREFIX}{self:?}").into()
97 }
98}
99
100impl From<TypeId> for NotificationId {
101 fn from(type_id: TypeId) -> Self {
102 Self::Id(type_id)
103 }
104}
105
106impl From<(TypeId, ElementId)> for NotificationId {
107 fn from((type_id, id): (TypeId, ElementId)) -> Self {
108 Self::IdAndElementId(type_id, id)
109 }
110}
111
112/// A notification element.
113pub struct Notification {
114 /// The id is used make the notification unique.
115 /// Then you push a notification with the same id, the previous notification will be replaced.
116 ///
117 /// None means the notification will be added to the end of the list.
118 id: NotificationId,
119 style: StyleRefinement,
120 type_: Option<NotificationType>,
121 title: Option<SharedString>,
122 message: Option<SharedString>,
123 icon: Option<Icon>,
124 placement: Option<Anchor>,
125 delivery: Option<NotificationDelivery>,
126 autohide: bool,
127 action_builder: Option<Rc<dyn Fn(&mut Self, &mut Window, &mut Context<Self>) -> Button>>,
128 content_builder: Option<Rc<dyn Fn(&mut Self, &mut Window, &mut Context<Self>) -> AnyElement>>,
129 on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
130 on_close: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
131 transition_status: ToastTransitionStatus,
132}
133
134impl From<String> for Notification {
135 fn from(s: String) -> Self {
136 Self::new().message(s)
137 }
138}
139
140impl From<SharedString> for Notification {
141 fn from(s: SharedString) -> Self {
142 Self::new().message(s)
143 }
144}
145
146impl From<&str> for Notification {
147 fn from(s: &str) -> Self {
148 Self::new().message(s)
149 }
150}
151
152impl<'a> From<Cow<'a, str>> for Notification {
153 fn from(s: Cow<'a, str>) -> Self {
154 Self::new().message(s)
155 }
156}
157
158impl<T> From<(NotificationType, T)> for Notification
159where
160 T: Into<SharedString>,
161{
162 fn from((type_, content): (NotificationType, T)) -> Self {
163 Self::new().message(content).with_type(type_)
164 }
165}
166
167struct DefaultIdType;
168
169impl Notification {
170 /// Create a new notification.
171 ///
172 /// The default id is a random UUID.
173 pub fn new() -> Self {
174 let id: SharedString = uuid::Uuid::new_v4().to_string().into();
175 let id = (TypeId::of::<DefaultIdType>(), id.into());
176
177 Self {
178 id: id.into(),
179 style: StyleRefinement::default(),
180 title: None,
181 message: None,
182 type_: None,
183 icon: None,
184 placement: None,
185 delivery: None,
186 autohide: true,
187 action_builder: None,
188 content_builder: None,
189 on_click: None,
190 on_close: None,
191 transition_status: ToastTransitionStatus::Starting,
192 }
193 }
194
195 /// Set the message of the notification, default is None.
196 pub fn message(mut self, message: impl Into<SharedString>) -> Self {
197 self.message = Some(message.into());
198 self
199 }
200
201 /// Create an info notification with the given message.
202 pub fn info(message: impl Into<SharedString>) -> Self {
203 Self::new()
204 .message(message)
205 .with_type(NotificationType::Info)
206 }
207
208 /// Create a success notification with the given message.
209 pub fn success(message: impl Into<SharedString>) -> Self {
210 Self::new()
211 .message(message)
212 .with_type(NotificationType::Success)
213 }
214
215 /// Create a warning notification with the given message.
216 pub fn warning(message: impl Into<SharedString>) -> Self {
217 Self::new()
218 .message(message)
219 .with_type(NotificationType::Warning)
220 }
221
222 /// Create an error notification with the given message.
223 pub fn error(message: impl Into<SharedString>) -> Self {
224 Self::new()
225 .message(message)
226 .with_type(NotificationType::Error)
227 }
228
229 /// Set the type for unique identification of the notification.
230 ///
231 /// ```rs
232 /// struct MyNotificationKind;
233 /// let notification = Notification::new().message("Hello").id::<MyNotificationKind>();
234 /// ```
235 pub fn id<T: Sized + 'static>(mut self) -> Self {
236 self.id = TypeId::of::<T>().into();
237 self
238 }
239
240 /// Set the type and id of the notification, used to uniquely identify the notification.
241 pub fn id1<T: Sized + 'static>(mut self, key: impl Into<ElementId>) -> Self {
242 self.id = (TypeId::of::<T>(), key.into()).into();
243 self
244 }
245
246 /// Set the title of the notification, default is None.
247 ///
248 /// If title is None, the notification will not have a title.
249 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
250 self.title = Some(title.into());
251 self
252 }
253
254 /// Set the icon of the notification.
255 ///
256 /// If icon is None, the notification will use the default icon of the type.
257 pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
258 self.icon = Some(icon.into());
259 self
260 }
261
262 /// Set the type of the notification, default is NotificationType::Info.
263 pub fn with_type(mut self, type_: NotificationType) -> Self {
264 self.type_ = Some(type_);
265 self
266 }
267
268 /// Set the placement of the notification, overriding the global
269 /// [`NotificationSettings::placement`].
270 ///
271 /// Notifications are stacked separately for each placement.
272 pub fn placement(mut self, placement: Anchor) -> Self {
273 self.placement = Some(placement);
274 self
275 }
276
277 /// Set where this notification is delivered, overriding the global
278 /// [`NotificationSettings::delivery`].
279 ///
280 /// System delivery uses the OS notification center: the title and message
281 /// become the system notification's title and body (a notification with
282 /// neither is not posted). Pushing again with the same [`Notification::id`]
283 /// replaces the previous system notification. Clicking the system
284 /// notification activates the window, closes the in-app toast (if any),
285 /// and fires [`Notification::on_click`]; with
286 /// [`NotificationDelivery::System`] the toast never exists, so
287 /// [`Notification::on_close`] is never called.
288 ///
289 /// Platform requirements: on macOS the application must run from a bundled
290 /// `.app` in a location the system trusts, such as `/Applications` (posts
291 /// are silently dropped under plain `cargo run`, and the first post
292 /// triggers the authorization prompt); on Windows the application must
293 /// call [`gpui::App::set_app_identity`] early in startup; on Linux a
294 /// notification daemon must be present and retraction is unsupported
295 /// (dismissed notifications age out).
296 pub fn delivery(mut self, delivery: NotificationDelivery) -> Self {
297 self.delivery = Some(delivery);
298 self
299 }
300
301 /// Deliver this notification only to the OS notification center.
302 ///
303 /// Shorthand for [`Notification::delivery`] with
304 /// [`NotificationDelivery::System`]; see there for platform requirements.
305 pub fn system(self) -> Self {
306 self.delivery(NotificationDelivery::System)
307 }
308
309 /// Deliver this notification as an in-app toast and to the OS
310 /// notification center.
311 ///
312 /// Shorthand for [`Notification::delivery`] with
313 /// [`NotificationDelivery::InAppAndSystem`]; see there for platform
314 /// requirements.
315 pub fn in_app_and_system(self) -> Self {
316 self.delivery(NotificationDelivery::InAppAndSystem)
317 }
318
319 /// Set the auto hide of the notification, default is true.
320 pub fn autohide(mut self, autohide: bool) -> Self {
321 self.autohide = autohide;
322 self
323 }
324
325 /// Set the click callback of the notification.
326 pub fn on_click(
327 mut self,
328 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
329 ) -> Self {
330 self.on_click = Some(Rc::new(on_click));
331 self
332 }
333
334 /// Set the close callback of the notification.
335 ///
336 /// Triggered when the notification is closed by any means
337 /// (close button, middle-click, autohide, click handler, or programmatic close).
338 pub fn on_close(mut self, on_close: impl Fn(&mut Window, &mut App) + 'static) -> Self {
339 self.on_close = Some(Rc::new(on_close));
340 self
341 }
342
343 /// Set the action button of the notification.
344 ///
345 /// When an action is set, the notification will not autohide.
346 pub fn action<F>(mut self, action: F) -> Self
347 where
348 F: Fn(&mut Self, &mut Window, &mut Context<Self>) -> Button + 'static,
349 {
350 self.action_builder = Some(Rc::new(action));
351 self.autohide = false;
352 self
353 }
354
355 /// Dismiss the notification.
356 pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
357 let _ = window;
358 cx.emit(DismissRequest);
359 }
360
361 fn begin_close(&mut self, cx: &mut Context<Self>) {
362 if self.transition_status != ToastTransitionStatus::Ending {
363 self.transition_status = ToastTransitionStatus::Ending;
364 cx.notify();
365 }
366 }
367
368 fn complete_enter(&mut self, cx: &mut Context<Self>) {
369 if self.transition_status == ToastTransitionStatus::Starting {
370 self.transition_status = ToastTransitionStatus::Present;
371 cx.notify();
372 }
373 }
374
375 fn complete_close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
376 cx.emit(DismissEvent);
377 if let Some(on_close) = self.on_close.clone() {
378 on_close(window, cx);
379 }
380 }
381
382 /// Set the content of the notification.
383 pub fn content(
384 mut self,
385 content: impl Fn(&mut Self, &mut Window, &mut Context<Self>) -> AnyElement + 'static,
386 ) -> Self {
387 self.content_builder = Some(Rc::new(content));
388 self
389 }
390}
391
392impl EventEmitter<DismissEvent> for Notification {}
393impl EventEmitter<DismissRequest> for Notification {}
394impl FluentBuilder for Notification {}
395impl Styled for Notification {
396 fn style(&mut self) -> &mut StyleRefinement {
397 &mut self.style
398 }
399}
400
401impl Render for Notification {
402 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
403 let content = self
404 .content_builder
405 .clone()
406 .map(|builder| builder(self, window, cx));
407 let action = self
408 .action_builder
409 .clone()
410 .map(|builder| builder(self, window, cx).small().mr_3p5());
411
412 let transition_status = self.transition_status;
413 let closing = transition_status == ToastTransitionStatus::Ending;
414 let icon = match self.type_ {
415 None => self.icon.clone(),
416 Some(type_) => Some(type_.icon(cx)),
417 };
418 let has_icon = icon.is_some();
419 let placement = self.placement.unwrap_or(cx.theme().notification.placement);
420 let toast_elevation = crate::elevation::toast(cx);
421 let resting_shadow = toast_elevation.shadow.clone();
422
423 BaseToast::new("notification")
424 .transition_status(transition_status)
425 .h_flex()
426 .group("")
427 .occlude()
428 .relative()
429 .w_full()
430 .border_1()
431 .border_color(cx.theme().border)
432 .bg(toast_elevation.fill)
433 .rounded(cx.theme().radius_lg)
434 .shadow(resting_shadow)
435 .py_3p5()
436 .px_4()
437 .gap_3()
438 .refine_style(&self.style)
439 .when_some(icon, |this, icon| {
440 this.child(div().absolute().top(px(18.)).left_4().child(icon))
441 })
442 .child(
443 v_flex()
444 .flex_1()
445 .overflow_hidden()
446 .when(has_icon, |this| this.pl_6())
447 .when_some(self.title.clone(), |this, title| {
448 this.child(div().text_sm().font_semibold().child(title))
449 })
450 .when_some(self.message.clone(), |this, message| {
451 this.child(div().text_sm().child(message))
452 })
453 .when_some(content, |this, content| this.child(content)),
454 )
455 .when_some(action, |this, action| this.child(action))
456 .child(
457 div()
458 .absolute()
459 .top_1()
460 .right_1()
461 .invisible()
462 .group_hover("", |this| this.visible())
463 .child(
464 Button::new("close")
465 .icon(IconName::Close)
466 .ghost()
467 .xsmall()
468 .on_click(cx.listener(|this, _, window, cx| {
469 cx.stop_propagation();
470 this.dismiss(window, cx);
471 })),
472 ),
473 )
474 .when_some(self.on_click.clone(), |this, on_click| {
475 this.on_click(cx.listener(move |view, event, window, cx| {
476 view.dismiss(window, cx);
477 on_click(event, window, cx);
478 }))
479 })
480 .on_aux_click(cx.listener(move |view, event: &ClickEvent, window, cx| {
481 if event.is_middle_click() {
482 view.dismiss(window, cx);
483 }
484 }))
485 .with_animation(
486 ElementId::NamedInteger("slide-down".into(), closing as u64),
487 Animation::new(if closing {
488 NOTIFICATION_EXIT_DURATION
489 } else {
490 NOTIFICATION_TRANSITION_DURATION
491 })
492 .with_easing(cubic_bezier(0.25, 0.1, 0.25, 1.)),
493 move |this, delta| {
494 if closing {
495 let opacity = 1. - delta;
496 let that = this
497 .opacity(opacity)
498 .shadow(toast_elevation.shadow_at(opacity.powi(3)));
499 let y_offset = match placement {
500 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => {
501 -delta * NOTIFICATION_TRANSITION_OFFSET
502 }
503 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => {
504 delta * NOTIFICATION_TRANSITION_OFFSET
505 }
506 _ => px(0.),
507 };
508 that.top(y_offset)
509 } else {
510 let y_offset = match placement {
511 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => {
512 -NOTIFICATION_TRANSITION_OFFSET
513 + delta * NOTIFICATION_TRANSITION_OFFSET
514 }
515 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => {
516 NOTIFICATION_TRANSITION_OFFSET
517 - delta * NOTIFICATION_TRANSITION_OFFSET
518 }
519 _ => px(0.),
520 };
521 let opacity = delta;
522 // GPUI paints a drop shadow *under* the card and has no
523 // group compositing, so a card that is still translucent
524 // does not hide its own shadow and it shows through as a
525 // dark slab. Ramping the ink by the cube of the fade
526 // keeps it out of sight until the card can cover it —
527 // where this used to drop the shadow outright past a
528 // threshold, which popped.
529 this.top(px(0.) + y_offset)
530 .opacity(opacity)
531 .shadow(toast_elevation.shadow_at(opacity.powi(3)))
532 }
533 },
534 )
535 }
536}
537
538/// The settings for notifications.
539#[derive(Debug, Clone)]
540pub struct NotificationSettings {
541 /// The placement of the notifications, default: [`Anchor::TopRight`]
542 ///
543 /// A single notification can override this with [`Notification::placement`].
544 pub placement: Anchor,
545 /// The margins of the notification with respect to the window edges.
546 pub margins: Edges<Pixels>,
547 /// The maximum number of notifications to show at once, default: 10
548 pub max_items: usize,
549 /// The width of the notifications, default: 382px
550 pub width: Pixels,
551 /// Where notifications are delivered, default: [`NotificationDelivery::InApp`]
552 ///
553 /// A single notification can override this with [`Notification::delivery`].
554 pub delivery: NotificationDelivery,
555}
556
557impl Default for NotificationSettings {
558 fn default() -> Self {
559 let offset = px(16.);
560 Self {
561 placement: Anchor::TopRight,
562 margins: Edges {
563 top: TITLE_BAR_HEIGHT + offset, // avoid overlap with title bar
564 right: offset,
565 bottom: offset,
566 left: offset,
567 },
568 max_items: 10,
569 width: DEFAULT_NOTIFICATION_WIDTH,
570 delivery: NotificationDelivery::default(),
571 }
572 }
573}
574
575/// Registers the app-global system-notification response handler.
576///
577/// gpui keeps a single such handler (later registrations replace earlier
578/// ones), so gpui-component owns it: applications must not call
579/// [`gpui::App::on_system_notification_response`] after `gpui_component::init`.
580/// Responses to notifications the application posts itself are ignored here.
581pub(crate) fn init(cx: &mut App) {
582 cx.on_system_notification_response(SystemNotificationRegistry::handle_response);
583}
584
585struct SystemNotificationEntry {
586 window: AnyWindowHandle,
587 list: WeakEntity<NotificationList>,
588 id: NotificationId,
589 on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
590}
591
592const MAX_SYSTEM_NOTIFICATION_ENTRIES: usize = 100;
593
594/// App-global map from system-notification tag to the state needed to
595/// dispatch the user's response, ordered oldest-first so overflow prunes the
596/// stalest entries.
597#[derive(Default)]
598struct SystemNotificationRegistry {
599 entries: Vec<(SharedString, SystemNotificationEntry)>,
600}
601
602impl Global for SystemNotificationRegistry {}
603
604impl SystemNotificationRegistry {
605 fn insert(cx: &mut App, tag: SharedString, entry: SystemNotificationEntry) {
606 let entries = &mut cx.default_global::<Self>().entries;
607 entries.retain(|(existing, _)| *existing != tag);
608 entries.push((tag, entry));
609 if entries.len() > MAX_SYSTEM_NOTIFICATION_ENTRIES {
610 let overflow = entries.len() - MAX_SYSTEM_NOTIFICATION_ENTRIES;
611 entries.drain(..overflow);
612 }
613 }
614
615 /// Retract the system notification for `id`, but only if it was posted
616 /// from the given window: another window pushing the same id owns the tag
617 /// now, and this window's local dismiss must not clobber it.
618 fn dismiss(cx: &mut App, id: &NotificationId, window_id: WindowId) {
619 let tag = id.system_tag();
620 let entries = &mut cx.default_global::<Self>().entries;
621 let Some(ix) = entries.iter().position(|(existing, entry)| {
622 *existing == tag && entry.window.window_id() == window_id
623 }) else {
624 return;
625 };
626 entries.remove(ix);
627 cx.dismiss_system_notification(&tag);
628 }
629
630 /// Retract all of the window's system notifications whose id matches the
631 /// given [`TypeId`], regardless of the [`NotificationId`] variant.
632 fn dismiss_by_type(cx: &mut App, type_id: TypeId, window_id: WindowId) {
633 Self::dismiss_matching(cx, window_id, |id| match id {
634 NotificationId::Id(t) | NotificationId::IdAndElementId(t, _) => *t == type_id,
635 });
636 }
637
638 /// Retract all system notifications posted from the given window.
639 fn dismiss_all(cx: &mut App, window_id: WindowId) {
640 Self::dismiss_matching(cx, window_id, |_| true);
641 }
642
643 fn dismiss_matching(
644 cx: &mut App,
645 window_id: WindowId,
646 matches: impl Fn(&NotificationId) -> bool,
647 ) {
648 let entries = &mut cx.default_global::<Self>().entries;
649 let mut tags = Vec::new();
650 entries.retain(|(tag, entry)| {
651 if entry.window.window_id() == window_id && matches(&entry.id) {
652 tags.push(tag.clone());
653 false
654 } else {
655 true
656 }
657 });
658 for tag in tags {
659 cx.dismiss_system_notification(&tag);
660 }
661 }
662
663 fn handle_response(response: SystemNotificationResponse, cx: &mut App) {
664 if !response.tag.starts_with(SYSTEM_TAG_PREFIX) {
665 return;
666 }
667 // Platforms usually remove a clicked notification themselves; retract
668 // explicitly for the ones that keep it in the notification center.
669 cx.dismiss_system_notification(&response.tag);
670 // The prefix already proves the notification is ours, so activate even
671 // when nothing is left to dispatch to: the platform can deliver a
672 // response for a notification posted before the process restarted, and
673 // entries are pruned past `MAX_SYSTEM_NOTIFICATION_ENTRIES`.
674 cx.activate(true);
675 let entries = &mut cx.default_global::<Self>().entries;
676 let Some(ix) = entries.iter().position(|(tag, _)| *tag == response.tag) else {
677 return;
678 };
679 let (_, entry) = entries.remove(ix);
680 // Errs when the window is already closed: the entry is removed and the
681 // application is still brought to the foreground.
682 let _ = entry.window.update(cx, |_, window, cx| {
683 window.activate_window();
684 if let Some(list) = entry.list.upgrade() {
685 // No-op when the toast already closed or was never created
686 // (system-only delivery).
687 list.update(cx, |list, cx| list.close(entry.id.clone(), window, cx));
688 }
689 if let Some(on_click) = entry.on_click {
690 on_click(&ClickEvent::default(), window, cx);
691 }
692 });
693 }
694}
695
696/// Per-placement stack state, created lazily for placements in use.
697struct AnchorStack {
698 state: ToastStackState,
699 focus_handle: FocusHandle,
700}
701
702/// A list of notifications.
703pub struct NotificationList {
704 /// Notifications that will be auto hidden.
705 pub(crate) notifications: ToastManager<NotificationId, Entity<Notification>>,
706 stacks: Vec<(Anchor, AnchorStack)>,
707 focus_handle: FocusHandle,
708 /// Mounted notifications that hide themselves after a timeout.
709 autohide_ids: HashSet<NotificationId>,
710 /// Whether the lifecycle clock is running. The loop clears it as it exits.
711 is_advancing: bool,
712 _subscriptions: HashMap<NotificationId, Subscription>,
713}
714
715impl NotificationList {
716 pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
717 Self {
718 notifications: ToastManager::new(ToastMotion::sonner()),
719 stacks: Vec::new(),
720 focus_handle: cx.focus_handle().tab_stop(true),
721 autohide_ids: HashSet::new(),
722 is_advancing: false,
723 _subscriptions: HashMap::new(),
724 }
725 }
726
727 /// Tick the toast lifecycle while a notification still has time to track.
728 ///
729 /// It advances the transition phases and samples the pause input (stack
730 /// expansion) that reaches the list through no event.
731 /// With nothing mounted, or only persistent notifications at rest, there is
732 /// nothing to do, so the window arms no timer until a push or close.
733 fn start_advancing(&mut self, window: &mut Window, cx: &mut Context<Self>) {
734 if self.is_advancing {
735 return;
736 }
737 self.is_advancing = true;
738 // Detached rather than kept as a `Task`: the loop ends itself, and a
739 // handle on the list would have to be dropped from inside its own future.
740 cx.spawn_in(window, async move |view, cx| {
741 loop {
742 cx.background_executor()
743 .timer(NOTIFICATION_ADVANCE_INTERVAL)
744 .await;
745 let running = view.update_in(cx, |view, window, cx| {
746 view.advance(window, cx);
747 view.is_advancing = view.needs_clock();
748 view.is_advancing
749 });
750 if !matches!(running, Ok(true)) {
751 break;
752 }
753 }
754 })
755 .detach();
756 }
757
758 /// Whether a mounted notification is in transition or counting down to
759 /// autohide. A paused countdown still needs its last sample kept current.
760 fn needs_clock(&self) -> bool {
761 self.notifications
762 .iter()
763 .any(|(id, _, status)| match status {
764 ToastTransitionStatus::Present => self.autohide_ids.contains(id),
765 ToastTransitionStatus::Starting | ToastTransitionStatus::Ending => true,
766 })
767 }
768
769 fn is_expanded(&self) -> bool {
770 self.stacks
771 .iter()
772 .any(|(_, stack)| stack.state.is_expanded())
773 }
774
775 /// Group the visible notifications by their effective placement, pairing
776 /// each group with the element id its stack renders under and preserving
777 /// the display order within each group.
778 fn grouped(
779 &self,
780 cx: &App,
781 ) -> Vec<(
782 Anchor,
783 ElementId,
784 Vec<(NotificationId, Entity<Notification>)>,
785 )> {
786 let settings = &cx.theme().notification;
787 let (max_items, placement) = (settings.max_items, settings.placement);
788
789 let mut groups: Vec<(Anchor, Vec<(NotificationId, Entity<Notification>)>)> = Vec::new();
790 for (id, item, _) in self.notifications.visible(max_items) {
791 let anchor = item.read(cx).placement.unwrap_or(placement);
792 match groups.iter_mut().find(|(a, _)| *a == anchor) {
793 Some((_, items)) => items.push((id.clone(), item.clone())),
794 None => groups.push((anchor, vec![(id.clone(), item.clone())])),
795 }
796 }
797 groups
798 .into_iter()
799 .map(|(anchor, items)| (anchor, Self::stack_id(anchor), items))
800 .collect()
801 }
802
803 /// The element id a placement's stack renders under.
804 ///
805 /// Keyed by the placement itself rather than by position among the mounted
806 /// stacks: a stack whose id changes loses the element state of its whole
807 /// subtree, which replays the enter animation of every notification in it.
808 fn stack_id(anchor: Anchor) -> ElementId {
809 let ix = match anchor {
810 Anchor::TopLeft => 0,
811 Anchor::TopCenter => 1,
812 Anchor::TopRight => 2,
813 Anchor::BottomLeft => 3,
814 Anchor::BottomCenter => 4,
815 Anchor::BottomRight => 5,
816 Anchor::LeftCenter => 6,
817 Anchor::RightCenter => 7,
818 };
819 ("notification-list", ix as usize).into()
820 }
821
822 pub fn push(
823 &mut self,
824 notification: impl Into<Notification>,
825 window: &mut Window,
826 cx: &mut Context<Self>,
827 ) {
828 let notification = notification.into();
829 let delivery = notification
830 .delivery
831 .unwrap_or(cx.theme().notification.delivery);
832 if delivery.includes_system() {
833 Self::push_system(&notification, window, cx);
834 }
835 if !delivery.includes_in_app() {
836 return;
837 }
838
839 let id = notification.id.clone();
840 let autohide = notification.autohide;
841 let window_id = window.window_handle().window_id();
842
843 let notification = cx.new(|_| notification);
844
845 let dismiss_id = id.clone();
846 self._subscriptions.insert(
847 id.clone(),
848 cx.subscribe_in(
849 &notification,
850 window,
851 move |view, _, _: &DismissRequest, window, cx| {
852 if view
853 .notifications
854 .dismiss(&dismiss_id, cx.background_executor().now())
855 {
856 if let Some(note) = view.notifications.get(&dismiss_id) {
857 note.update(cx, |note, cx| note.begin_close(cx));
858 }
859 SystemNotificationRegistry::dismiss(cx, &dismiss_id, window_id);
860 view.start_advancing(window, cx);
861 }
862 },
863 ),
864 );
865 if autohide {
866 self.autohide_ids.insert(id.clone());
867 } else {
868 self.autohide_ids.remove(&id);
869 }
870
871 self.notifications.push(
872 id,
873 notification,
874 ToastOptions {
875 timeout: autohide.then_some(Duration::from_secs(5)),
876 },
877 cx.background_executor().now(),
878 );
879 self.start_advancing(window, cx);
880 cx.notify();
881 }
882
883 /// Post the notification to the OS notification center and register the
884 /// state needed to dispatch the user's response back to this window.
885 fn push_system(notification: &Notification, window: &Window, cx: &mut Context<Self>) {
886 let (title, body) = match (&notification.title, &notification.message) {
887 (Some(title), message) => (title.clone(), message.clone().unwrap_or_default()),
888 (None, Some(message)) => (message.clone(), SharedString::default()),
889 // A content-only notification has nothing textual to show.
890 (None, None) => return,
891 };
892 let tag = notification.id.system_tag();
893 let entry = SystemNotificationEntry {
894 window: window.window_handle(),
895 list: cx.entity().downgrade(),
896 id: notification.id.clone(),
897 on_click: notification.on_click.clone(),
898 };
899 SystemNotificationRegistry::insert(cx, tag.clone(), entry);
900 cx.show_system_notification(SystemNotification {
901 tag,
902 title,
903 body,
904 actions: Vec::new(),
905 });
906 }
907
908 fn advance(&mut self, window: &mut Window, cx: &mut Context<Self>) {
909 let changes = self
910 .notifications
911 .advance(cx.background_executor().now(), self.is_expanded());
912 for id in changes.presented {
913 if let Some(note) = self.notifications.get(&id) {
914 note.update(cx, |note, cx| note.complete_enter(cx));
915 }
916 }
917 for id in changes.ending {
918 if let Some(note) = self.notifications.get(&id) {
919 note.update(cx, |note, cx| note.begin_close(cx));
920 }
921 }
922 for (id, note) in changes.removed {
923 self._subscriptions.remove(&id);
924 self.autohide_ids.remove(&id);
925 note.update(cx, |note, cx| note.complete_close(window, cx));
926 }
927 if changes.changed {
928 cx.notify();
929 }
930 }
931
932 pub(crate) fn close(
933 &mut self,
934 id: impl Into<NotificationId>,
935 window: &mut Window,
936 cx: &mut Context<Self>,
937 ) {
938 let id: NotificationId = id.into();
939 // Unconditional: a system-only notification has no toast to dismiss,
940 // but its system counterpart must still be retracted.
941 SystemNotificationRegistry::dismiss(cx, &id, window.window_handle().window_id());
942 if self
943 .notifications
944 .dismiss(&id, cx.background_executor().now())
945 {
946 if let Some(n) = self.notifications.get(&id) {
947 n.update(cx, |note, cx| note.begin_close(cx))
948 }
949 self.start_advancing(window, cx);
950 }
951 cx.notify();
952 }
953
954 /// Close all notifications whose id matches the given [`TypeId`], regardless of
955 /// whether they were registered via [`Notification::id`] or [`Notification::id1`].
956 pub(crate) fn close_by_type(
957 &mut self,
958 type_id: TypeId,
959 window: &mut Window,
960 cx: &mut Context<Self>,
961 ) {
962 SystemNotificationRegistry::dismiss_by_type(
963 cx,
964 type_id,
965 window.window_handle().window_id(),
966 );
967 let matched: Vec<_> = self
968 .notifications
969 .iter()
970 .filter(|(id, _, _)| match id {
971 NotificationId::Id(t) | NotificationId::IdAndElementId(t, _) => *t == type_id,
972 })
973 .map(|(_, notification, _)| notification)
974 .cloned()
975 .collect();
976 for n in matched {
977 let id = n.read(cx).id.clone();
978 if self
979 .notifications
980 .dismiss(&id, cx.background_executor().now())
981 {
982 n.update(cx, |note, cx| note.begin_close(cx));
983 self.start_advancing(window, cx);
984 }
985 }
986 cx.notify();
987 }
988
989 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
990 SystemNotificationRegistry::dismiss_all(cx, window.window_handle().window_id());
991 for id in self
992 .notifications
993 .dismiss_all(cx.background_executor().now())
994 {
995 if let Some(note) = self.notifications.get(&id) {
996 note.update(cx, |note, cx| note.begin_close(cx));
997 }
998 self.start_advancing(window, cx);
999 }
1000 cx.notify();
1001 }
1002
1003 pub fn notifications(&self) -> Vec<Entity<Notification>> {
1004 self.notifications
1005 .iter()
1006 .map(|(_, value, _)| value.clone())
1007 .collect()
1008 }
1009}
1010
1011impl Render for NotificationList {
1012 fn render(
1013 &mut self,
1014 window: &mut gpui::Window,
1015 cx: &mut gpui::Context<Self>,
1016 ) -> impl IntoElement {
1017 let size = window.viewport_size();
1018 let settings = &cx.theme().notification;
1019 let (placement, margins, width) =
1020 (settings.placement, settings.margins.clone(), settings.width);
1021
1022 let groups = self.grouped(cx);
1023 self.stacks
1024 .retain(|(anchor, _)| groups.iter().any(|(a, _, _)| a == anchor));
1025
1026 let default_focus_handle = self.focus_handle.clone();
1027 let stacks = groups.into_iter().map(|(anchor, stack_id, items)| {
1028 let stack_ix = self
1029 .stacks
1030 .iter()
1031 .position(|(a, _)| *a == anchor)
1032 .unwrap_or_else(|| {
1033 self.stacks.push((
1034 anchor,
1035 AnchorStack {
1036 state: ToastStackState::default(),
1037 focus_handle: if anchor == placement {
1038 default_focus_handle.clone()
1039 } else {
1040 cx.focus_handle().tab_stop(true)
1041 },
1042 },
1043 ));
1044 self.stacks.len() - 1
1045 });
1046 let stack = &self.stacks[stack_ix].1;
1047
1048 items
1049 .into_iter()
1050 .fold(
1051 ToastStack::new(stack_id, stack.state.clone()),
1052 |stack, (id, item)| stack.item(format!("{id:?}"), item),
1053 )
1054 .placement(anchor)
1055 .focus_handle(stack.focus_handle.clone())
1056 .v_flex()
1057 .w(width)
1058 .max_h(size.height)
1059 .absolute()
1060 .map(|this| match anchor {
1061 Anchor::TopLeft => this.top(margins.top).left(margins.left),
1062 Anchor::TopRight => this.top(margins.top).right(margins.right),
1063 Anchor::TopCenter => this.top(margins.top).left(relative(0.5)).ml(-width / 2.),
1064 Anchor::BottomLeft => this.bottom(margins.bottom).left(margins.left),
1065 Anchor::BottomRight => this.bottom(margins.bottom).right(margins.right),
1066 Anchor::BottomCenter => this
1067 .bottom(margins.bottom)
1068 .left(relative(0.5))
1069 .ml(-width / 2.),
1070 Anchor::LeftCenter => this.left(margins.left).top_0().bottom_0().my_auto(),
1071 Anchor::RightCenter => this.right(margins.right).top_0().bottom_0().my_auto(),
1072 })
1073 });
1074
1075 div().size_full().children(stacks)
1076 }
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081 use super::*;
1082 use crate::theme::Theme;
1083 use gpui::{TestAppContext, VisualTestContext};
1084
1085 struct FooKind;
1086 struct BarKind;
1087
1088 struct TestRoot {
1089 list: Entity<NotificationList>,
1090 other_focus: FocusHandle,
1091 }
1092
1093 impl Render for TestRoot {
1094 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1095 div()
1096 .child(self.list.clone())
1097 .child(div().track_focus(&self.other_focus))
1098 }
1099 }
1100
1101 fn ids(list: &Entity<NotificationList>, cx: &mut VisualTestContext) -> Vec<NotificationId> {
1102 list.read_with(cx, |l, cx| {
1103 l.notifications
1104 .iter()
1105 .map(|(_, n, _)| n.read(cx).id.clone())
1106 .collect()
1107 })
1108 }
1109
1110 /// Drive the dismiss animation timer + propagate the resulting `DismissEvent`
1111 /// so that closed notifications are removed from the list.
1112 fn flush_dismiss(cx: &mut VisualTestContext) {
1113 cx.background_executor
1114 .advance_clock(NOTIFICATION_EXIT_DURATION + Duration::from_millis(50));
1115 cx.run_until_parked();
1116 }
1117
1118 #[test]
1119 fn test_notification_builder() {
1120 let note = Notification::new()
1121 .title("title")
1122 .message("message")
1123 .with_type(NotificationType::Success)
1124 .placement(Anchor::BottomLeft)
1125 .delivery(NotificationDelivery::System)
1126 .autohide(false);
1127 assert_eq!(note.title, Some("title".into()));
1128 assert_eq!(note.message, Some("message".into()));
1129 assert!(matches!(note.type_, Some(NotificationType::Success)));
1130 assert_eq!(note.placement, Some(Anchor::BottomLeft));
1131 assert_eq!(note.delivery, Some(NotificationDelivery::System));
1132 assert!(!note.autohide);
1133
1134 assert_eq!(Notification::new().delivery, None);
1135 assert_eq!(
1136 Notification::new().system().delivery,
1137 Some(NotificationDelivery::System)
1138 );
1139 assert_eq!(
1140 Notification::new().in_app_and_system().delivery,
1141 Some(NotificationDelivery::InAppAndSystem)
1142 );
1143 }
1144
1145 #[test]
1146 fn notification_delivery_includes() {
1147 assert!(NotificationDelivery::InApp.includes_in_app());
1148 assert!(!NotificationDelivery::InApp.includes_system());
1149 assert!(!NotificationDelivery::System.includes_in_app());
1150 assert!(NotificationDelivery::System.includes_system());
1151 assert!(NotificationDelivery::InAppAndSystem.includes_in_app());
1152 assert!(NotificationDelivery::InAppAndSystem.includes_system());
1153 }
1154
1155 #[test]
1156 fn system_tag_is_stable_and_namespaced() {
1157 let by_type = NotificationId::from(TypeId::of::<FooKind>());
1158 assert_eq!(by_type.system_tag(), by_type.clone().system_tag());
1159 assert!(by_type.system_tag().starts_with(SYSTEM_TAG_PREFIX));
1160
1161 let key1 = NotificationId::from((TypeId::of::<FooKind>(), ElementId::from(1usize)));
1162 let key2 = NotificationId::from((TypeId::of::<FooKind>(), ElementId::from(2usize)));
1163 assert_ne!(key1.system_tag(), key2.system_tag());
1164 assert_ne!(by_type.system_tag(), key1.system_tag());
1165
1166 // Default (uuid) ids never collide, so they never replace each other.
1167 assert_ne!(
1168 Notification::new().id.system_tag(),
1169 Notification::new().id.system_tag()
1170 );
1171 }
1172
1173 /// A stack's element id must not depend on how many other placements are
1174 /// mounted: a changing id drops the element state of the whole subtree,
1175 /// which replays each notification's enter animation.
1176 #[gpui::test]
1177 fn stack_element_id_survives_other_placements_disappearing(cx: &mut TestAppContext) {
1178 cx.update(|cx| cx.set_global(Theme::default()));
1179 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1180 list: cx.new(|cx| NotificationList::new(window, cx)),
1181 other_focus: cx.focus_handle(),
1182 });
1183 cx.update(|window, _| window.activate_window());
1184 let list = root.read_with(cx, |root, _| root.list.clone());
1185
1186 // The left stack is pushed first, so it owns the lower group index.
1187 list.update_in(cx, |list, window, cx| {
1188 list.push(
1189 Notification::info("left")
1190 .id::<FooKind>()
1191 .placement(Anchor::BottomLeft)
1192 .autohide(false),
1193 window,
1194 cx,
1195 );
1196 list.push(
1197 Notification::info("right").id::<BarKind>().autohide(false),
1198 window,
1199 cx,
1200 );
1201 });
1202
1203 let right_id = |cx: &mut VisualTestContext| {
1204 list.read_with(cx, |list, cx| {
1205 list.grouped(cx)
1206 .into_iter()
1207 .find(|(anchor, _, _)| *anchor == Anchor::TopRight)
1208 .map(|(_, id, _)| id)
1209 .expect("the right stack is mounted")
1210 })
1211 };
1212 let before = right_id(cx);
1213
1214 list.update_in(cx, |list, window, cx| {
1215 list.close(TypeId::of::<FooKind>(), window, cx);
1216 });
1217 flush_dismiss(cx);
1218
1219 assert_eq!(right_id(cx), before);
1220 }
1221
1222 #[gpui::test]
1223 fn per_notification_placement_stacks_by_anchor(cx: &mut TestAppContext) {
1224 cx.update(|cx| cx.set_global(Theme::default()));
1225 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1226 list: cx.new(|cx| NotificationList::new(window, cx)),
1227 other_focus: cx.focus_handle(),
1228 });
1229 cx.update(|window, _| window.activate_window());
1230 let list = root.read_with(cx, |root, _| root.list.clone());
1231
1232 list.update_in(cx, |list, window, cx| {
1233 list.push(
1234 Notification::info("default")
1235 .id::<FooKind>()
1236 .autohide(false),
1237 window,
1238 cx,
1239 );
1240 list.push(
1241 Notification::info("bottom")
1242 .id::<BarKind>()
1243 .placement(Anchor::BottomLeft)
1244 .autohide(false),
1245 window,
1246 cx,
1247 );
1248 });
1249 cx.update(|window, cx| window.draw(cx).clear(cx));
1250
1251 let anchors =
1252 |list: &NotificationList| list.stacks.iter().map(|(a, _)| *a).collect::<Vec<_>>();
1253 assert_eq!(
1254 list.read_with(cx, |list, _| anchors(list)),
1255 [Anchor::TopRight, Anchor::BottomLeft]
1256 );
1257
1258 // Dismissing the overridden notification prunes its stack.
1259 list.update_in(cx, |list, window, cx| {
1260 list.close(TypeId::of::<BarKind>(), window, cx);
1261 });
1262 flush_dismiss(cx);
1263 cx.update(|window, cx| window.draw(cx).clear(cx));
1264 assert_eq!(
1265 list.read_with(cx, |list, _| anchors(list)),
1266 [Anchor::TopRight]
1267 );
1268 }
1269
1270 #[gpui::test]
1271 fn closing_toast_stays_mounted_until_its_transition_finishes(cx: &mut TestAppContext) {
1272 cx.update(|cx| cx.set_global(Theme::default()));
1273 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1274 list: cx.new(|cx| NotificationList::new(window, cx)),
1275 other_focus: cx.focus_handle(),
1276 });
1277 cx.update(|window, _| window.activate_window());
1278 let list = root.read_with(cx, |root, _| root.list.clone());
1279
1280 list.update_in(cx, |list, window, cx| {
1281 list.push(
1282 Notification::info("closing")
1283 .id::<FooKind>()
1284 .autohide(false),
1285 window,
1286 cx,
1287 );
1288 list.close(TypeId::of::<FooKind>(), window, cx);
1289 });
1290
1291 cx.background_executor
1292 .advance_clock(NOTIFICATION_EXIT_DURATION - Duration::from_millis(1));
1293 cx.run_until_parked();
1294 assert_eq!(ids(&list, cx).len(), 1);
1295
1296 cx.background_executor
1297 .advance_clock(Duration::from_millis(1));
1298 cx.run_until_parked();
1299 assert!(ids(&list, cx).is_empty());
1300 }
1301
1302 #[gpui::test]
1303 fn lifecycle_clock_runs_only_while_a_notification_is_mounted(cx: &mut TestAppContext) {
1304 cx.update(|cx| cx.set_global(Theme::default()));
1305 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1306 list: cx.new(|cx| NotificationList::new(window, cx)),
1307 other_focus: cx.focus_handle(),
1308 });
1309 cx.update(|window, _| window.activate_window());
1310 let list = root.read_with(cx, |root, _| root.list.clone());
1311
1312 // A list that has never shown anything arms no timer.
1313 cx.background_executor.advance_clock(Duration::from_secs(1));
1314 cx.run_until_parked();
1315 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1316
1317 list.update_in(cx, |list, window, cx| {
1318 list.push(Notification::info("tick").id::<FooKind>(), window, cx);
1319 });
1320 assert!(list.read_with(cx, |list, _| list.is_advancing));
1321
1322 // Autohide expiry plus the exit transition stops the clock with it.
1323 cx.background_executor
1324 .advance_clock(NOTIFICATION_TRANSITION_DURATION + Duration::from_secs(5));
1325 cx.run_until_parked();
1326 flush_dismiss(cx);
1327 assert!(ids(&list, cx).is_empty());
1328 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1329
1330 // A later notification restarts it.
1331 list.update_in(cx, |list, window, cx| {
1332 list.push(Notification::info("again").id::<BarKind>(), window, cx);
1333 });
1334 assert!(list.read_with(cx, |list, _| list.is_advancing));
1335 cx.background_executor
1336 .advance_clock(NOTIFICATION_TRANSITION_DURATION + Duration::from_secs(5));
1337 cx.run_until_parked();
1338 flush_dismiss(cx);
1339 assert!(ids(&list, cx).is_empty());
1340 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1341 }
1342
1343 #[gpui::test]
1344 fn lifecycle_clock_rests_while_only_persistent_notifications_are_shown(
1345 cx: &mut TestAppContext,
1346 ) {
1347 cx.update(|cx| cx.set_global(Theme::default()));
1348 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1349 list: cx.new(|cx| NotificationList::new(window, cx)),
1350 other_focus: cx.focus_handle(),
1351 });
1352 cx.update(|window, _| window.activate_window());
1353 let list = root.read_with(cx, |root, _| root.list.clone());
1354
1355 list.update_in(cx, |list, window, cx| {
1356 list.push(
1357 Notification::info("first").id::<FooKind>().autohide(false),
1358 window,
1359 cx,
1360 );
1361 list.push(
1362 Notification::info("second").id::<BarKind>().autohide(false),
1363 window,
1364 cx,
1365 );
1366 });
1367 assert!(list.read_with(cx, |list, _| list.is_advancing));
1368
1369 // Once both have entered, nothing is left to time.
1370 cx.background_executor
1371 .advance_clock(NOTIFICATION_TRANSITION_DURATION + NOTIFICATION_ADVANCE_INTERVAL);
1372 cx.run_until_parked();
1373 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1374 assert_eq!(ids(&list, cx).len(), 2);
1375
1376 // A programmatic close restarts the clock to finish the exit.
1377 list.update_in(cx, |list, window, cx| {
1378 list.close(TypeId::of::<FooKind>(), window, cx);
1379 });
1380 assert!(list.read_with(cx, |list, _| list.is_advancing));
1381 flush_dismiss(cx);
1382 assert_eq!(
1383 ids(&list, cx),
1384 [NotificationId::from(TypeId::of::<BarKind>())]
1385 );
1386 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1387
1388 // So does a dismiss requested by the notification itself.
1389 let note = list.read_with(cx, |list, _| list.notifications()[0].clone());
1390 note.update_in(cx, |note, window, cx| note.dismiss(window, cx));
1391 cx.run_until_parked();
1392 assert!(list.read_with(cx, |list, _| list.is_advancing));
1393 flush_dismiss(cx);
1394 assert!(ids(&list, cx).is_empty());
1395 assert!(!list.read_with(cx, |list, _| list.is_advancing));
1396 }
1397
1398 #[gpui::test]
1399 fn inactive_window_does_not_pause_autohide(cx: &mut TestAppContext) {
1400 cx.update(|cx| cx.set_global(Theme::default()));
1401 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1402 list: cx.new(|cx| NotificationList::new(window, cx)),
1403 other_focus: cx.focus_handle(),
1404 });
1405 let list = root.read_with(cx, |root, _| root.list.clone());
1406 list.update_in(cx, |list, window, cx| {
1407 assert!(!window.is_window_active());
1408 list.push(Notification::info("background").id::<FooKind>(), window, cx);
1409 });
1410
1411 cx.background_executor
1412 .advance_clock(NOTIFICATION_TRANSITION_DURATION);
1413 cx.run_until_parked();
1414 let note = list.read_with(cx, |list, _| {
1415 list.notifications
1416 .get(&NotificationId::from(TypeId::of::<FooKind>()))
1417 .unwrap()
1418 .clone()
1419 });
1420 assert_eq!(
1421 note.read_with(cx, |note, _| note.transition_status),
1422 ToastTransitionStatus::Present
1423 );
1424
1425 cx.background_executor
1426 .advance_clock(Duration::from_secs(5) + Duration::from_millis(50));
1427 cx.run_until_parked();
1428 assert_eq!(
1429 note.read_with(cx, |note, _| note.transition_status),
1430 ToastTransitionStatus::Ending
1431 );
1432 }
1433
1434 #[gpui::test]
1435 fn focus_pauses_autohide_and_present_phase_is_projected(cx: &mut TestAppContext) {
1436 cx.update(|cx| cx.set_global(Theme::default()));
1437 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1438 list: cx.new(|cx| NotificationList::new(window, cx)),
1439 other_focus: cx.focus_handle(),
1440 });
1441 let list = root.read_with(cx, |root, _| root.list.clone());
1442 list.update_in(cx, |list, window, cx| {
1443 list.push(Notification::info("paused").id::<FooKind>(), window, cx);
1444 });
1445
1446 cx.background_executor
1447 .advance_clock(NOTIFICATION_TRANSITION_DURATION);
1448 cx.run_until_parked();
1449 let note = list.read_with(cx, |list, _| {
1450 list.notifications
1451 .get(&NotificationId::from(TypeId::of::<FooKind>()))
1452 .unwrap()
1453 .clone()
1454 });
1455 assert_eq!(
1456 note.read_with(cx, |note, _| note.transition_status),
1457 ToastTransitionStatus::Present
1458 );
1459
1460 let list_focus = list.read_with(cx, |list, _| list.focus_handle.clone());
1461 cx.update(|window, cx| {
1462 list_focus.focus(window, cx);
1463 window.draw(cx).clear(cx);
1464 });
1465 cx.background_executor.advance_clock(Duration::from_secs(5));
1466 cx.run_until_parked();
1467 assert_eq!(
1468 note.read_with(cx, |note, _| note.transition_status),
1469 ToastTransitionStatus::Present
1470 );
1471
1472 let other_focus = root.read_with(cx, |root, _| root.other_focus.clone());
1473 cx.update(|window, cx| {
1474 other_focus.focus(window, cx);
1475 window.draw(cx).clear(cx);
1476 });
1477 assert!(!list.read_with(cx, |list, _| list.is_expanded()));
1478 cx.background_executor
1479 .advance_clock(Duration::from_secs(5) + Duration::from_millis(50));
1480 cx.run_until_parked();
1481 assert_eq!(
1482 note.read_with(cx, |note, _| note.transition_status),
1483 ToastTransitionStatus::Ending
1484 );
1485 }
1486
1487 #[gpui::test]
1488 fn close_by_type_removes_id_and_all_id1_of_same_type(cx: &mut TestAppContext) {
1489 cx.update(|cx| cx.set_global(Theme::default()));
1490 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1491 list: cx.new(|cx| NotificationList::new(window, cx)),
1492 other_focus: cx.focus_handle(),
1493 });
1494 let list = root.read_with(cx, |r, _| r.list.clone());
1495
1496 list.update_in(cx, |list, window, cx| {
1497 list.push(
1498 Notification::info("plain").id::<FooKind>().autohide(false),
1499 window,
1500 cx,
1501 );
1502 list.push(
1503 Notification::info("a").id1::<FooKind>(1).autohide(false),
1504 window,
1505 cx,
1506 );
1507 list.push(
1508 Notification::info("b").id1::<FooKind>(2).autohide(false),
1509 window,
1510 cx,
1511 );
1512 list.push(
1513 Notification::info("bar").id::<BarKind>().autohide(false),
1514 window,
1515 cx,
1516 );
1517 });
1518 cx.run_until_parked();
1519 assert_eq!(ids(&list, cx).len(), 4);
1520
1521 list.update_in(cx, |list, window, cx| {
1522 list.close_by_type(TypeId::of::<FooKind>(), window, cx);
1523 });
1524 flush_dismiss(cx);
1525
1526 let remaining = ids(&list, cx);
1527 assert_eq!(
1528 remaining,
1529 vec![NotificationId::Id(TypeId::of::<BarKind>())],
1530 "only the BarKind notification should survive"
1531 );
1532 }
1533
1534 #[gpui::test]
1535 fn close_with_id_and_element_id_removes_only_matching_key(cx: &mut TestAppContext) {
1536 cx.update(|cx| cx.set_global(Theme::default()));
1537 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1538 list: cx.new(|cx| NotificationList::new(window, cx)),
1539 other_focus: cx.focus_handle(),
1540 });
1541 let list = root.read_with(cx, |r, _| r.list.clone());
1542
1543 list.update_in(cx, |list, window, cx| {
1544 list.push(
1545 Notification::info("a").id1::<FooKind>(1).autohide(false),
1546 window,
1547 cx,
1548 );
1549 list.push(
1550 Notification::info("b").id1::<FooKind>(2).autohide(false),
1551 window,
1552 cx,
1553 );
1554 list.push(
1555 Notification::info("plain").id::<FooKind>().autohide(false),
1556 window,
1557 cx,
1558 );
1559 });
1560
1561 list.update_in(cx, |list, window, cx| {
1562 list.close(
1563 (TypeId::of::<FooKind>(), ElementId::from(1usize)),
1564 window,
1565 cx,
1566 );
1567 });
1568 flush_dismiss(cx);
1569
1570 let remaining = ids(&list, cx);
1571 assert_eq!(remaining.len(), 2);
1572 assert!(remaining.contains(&NotificationId::IdAndElementId(
1573 TypeId::of::<FooKind>(),
1574 ElementId::from(2usize),
1575 )));
1576 assert!(remaining.contains(&NotificationId::Id(TypeId::of::<FooKind>())));
1577 }
1578
1579 #[gpui::test]
1580 fn close_with_only_type_id_does_not_match_id1_entries(cx: &mut TestAppContext) {
1581 // The plain `close(TypeId)` form (used by the legacy code path) must keep
1582 // its narrow semantics: it only matches `NotificationId::Id`, not
1583 // `NotificationId::IdAndElementId`. The new `close_by_type` is the broad form.
1584 cx.update(|cx| cx.set_global(Theme::default()));
1585 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1586 list: cx.new(|cx| NotificationList::new(window, cx)),
1587 other_focus: cx.focus_handle(),
1588 });
1589 let list = root.read_with(cx, |r, _| r.list.clone());
1590
1591 list.update_in(cx, |list, window, cx| {
1592 list.push(
1593 Notification::info("a").id1::<FooKind>(1).autohide(false),
1594 window,
1595 cx,
1596 );
1597 });
1598
1599 list.update_in(cx, |list, window, cx| {
1600 list.close(TypeId::of::<FooKind>(), window, cx);
1601 });
1602 flush_dismiss(cx);
1603
1604 assert_eq!(ids(&list, cx).len(), 1, "id1 entry should remain untouched");
1605 }
1606
1607 #[gpui::test]
1608 fn close_by_type_with_no_match_is_noop(cx: &mut TestAppContext) {
1609 cx.update(|cx| cx.set_global(Theme::default()));
1610 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1611 list: cx.new(|cx| NotificationList::new(window, cx)),
1612 other_focus: cx.focus_handle(),
1613 });
1614 let list = root.read_with(cx, |r, _| r.list.clone());
1615
1616 list.update_in(cx, |list, window, cx| {
1617 list.push(
1618 Notification::info("bar").id::<BarKind>().autohide(false),
1619 window,
1620 cx,
1621 );
1622 });
1623
1624 list.update_in(cx, |list, window, cx| {
1625 list.close_by_type(TypeId::of::<FooKind>(), window, cx);
1626 });
1627 flush_dismiss(cx);
1628
1629 assert_eq!(ids(&list, cx).len(), 1);
1630 }
1631
1632 /// Applications may post their own system notifications; a response for
1633 /// one of those must not be retracted or dispatched by the library.
1634 #[gpui::test]
1635 fn response_for_a_foreign_tag_is_ignored(cx: &mut TestAppContext) {
1636 cx.update(|cx| {
1637 init(cx);
1638 cx.set_app_identity("com.example.test", "Test");
1639 });
1640 cx.simulate_system_notification_response(SystemNotificationResponse {
1641 tag: "com.example.app/own-tag".into(),
1642 action_id: None,
1643 });
1644 cx.run_until_parked();
1645 assert!(cx.dismissed_system_notifications().is_empty());
1646 }
1647
1648 #[gpui::test]
1649 fn system_delivery_posts_to_center_without_in_app_toast(cx: &mut TestAppContext) {
1650 cx.update(|cx| {
1651 cx.set_global(Theme::default());
1652 init(cx);
1653 // The test platform drops posts until an identity is set,
1654 // mirroring Windows.
1655 cx.set_app_identity("com.example.test", "Test");
1656 });
1657 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1658 list: cx.new(|cx| NotificationList::new(window, cx)),
1659 other_focus: cx.focus_handle(),
1660 });
1661 let list = root.read_with(cx, |r, _| r.list.clone());
1662
1663 list.update_in(cx, |list, window, cx| {
1664 list.push(
1665 Notification::info("body text")
1666 .title("Title")
1667 .id::<FooKind>()
1668 .delivery(NotificationDelivery::System),
1669 window,
1670 cx,
1671 );
1672 // Message-only: the message becomes the system title.
1673 list.push(
1674 Notification::info("message only")
1675 .id::<BarKind>()
1676 .delivery(NotificationDelivery::System),
1677 window,
1678 cx,
1679 );
1680 });
1681 cx.run_until_parked();
1682
1683 let shown = cx.shown_system_notifications();
1684 assert_eq!(shown.len(), 2);
1685 assert_eq!(
1686 shown[0].tag,
1687 NotificationId::Id(TypeId::of::<FooKind>()).system_tag()
1688 );
1689 assert_eq!(shown[0].title, "Title");
1690 assert_eq!(shown[0].body, "body text");
1691 assert_eq!(shown[1].title, "message only");
1692 assert_eq!(shown[1].body, "");
1693 assert!(ids(&list, cx).is_empty(), "no in-app toast should exist");
1694
1695 // System-only notifications are still retractable through the
1696 // regular close path even though no toast entity exists.
1697 list.update_in(cx, |list, window, cx| {
1698 list.close(TypeId::of::<FooKind>(), window, cx);
1699 });
1700 assert_eq!(
1701 cx.dismissed_system_notifications(),
1702 vec![NotificationId::Id(TypeId::of::<FooKind>()).system_tag()]
1703 );
1704 }
1705
1706 #[gpui::test]
1707 fn system_click_activates_window_closes_toast_and_fires_on_click(cx: &mut TestAppContext) {
1708 cx.update(|cx| {
1709 cx.set_global(Theme::default());
1710 init(cx);
1711 cx.set_app_identity("com.example.test", "Test");
1712 });
1713 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1714 list: cx.new(|cx| NotificationList::new(window, cx)),
1715 other_focus: cx.focus_handle(),
1716 });
1717 let list = root.read_with(cx, |r, _| r.list.clone());
1718
1719 let clicked = Rc::new(std::cell::Cell::new(false));
1720 let on_click_flag = clicked.clone();
1721 list.update_in(cx, |list, window, cx| {
1722 list.push(
1723 Notification::info("message")
1724 .title("Title")
1725 .id::<FooKind>()
1726 .delivery(NotificationDelivery::InAppAndSystem)
1727 .autohide(false)
1728 .on_click(move |_, _, _| on_click_flag.set(true)),
1729 window,
1730 cx,
1731 );
1732 });
1733 cx.run_until_parked();
1734 assert_eq!(ids(&list, cx).len(), 1);
1735 assert_eq!(cx.shown_system_notifications().len(), 1);
1736
1737 cx.simulate_system_notification_response(SystemNotificationResponse {
1738 tag: NotificationId::Id(TypeId::of::<FooKind>()).system_tag(),
1739 action_id: None,
1740 });
1741 cx.run_until_parked();
1742
1743 assert!(clicked.get(), "on_click should fire on system response");
1744 flush_dismiss(cx);
1745 assert!(
1746 ids(&list, cx).is_empty(),
1747 "the in-app counterpart should be closed"
1748 );
1749 }
1750
1751 #[gpui::test]
1752 fn explicit_close_retracts_system_notification_but_autohide_does_not(cx: &mut TestAppContext) {
1753 cx.update(|cx| {
1754 cx.set_global(Theme::default());
1755 init(cx);
1756 cx.set_app_identity("com.example.test", "Test");
1757 });
1758 let (root, cx) = cx.add_window_view(|window, cx| TestRoot {
1759 list: cx.new(|cx| NotificationList::new(window, cx)),
1760 other_focus: cx.focus_handle(),
1761 });
1762 cx.update(|window, _| window.activate_window());
1763 let list = root.read_with(cx, |r, _| r.list.clone());
1764
1765 // Autohide expiry leaves the system notification in the center.
1766 list.update_in(cx, |list, window, cx| {
1767 list.push(
1768 Notification::info("auto")
1769 .id::<FooKind>()
1770 .delivery(NotificationDelivery::InAppAndSystem),
1771 window,
1772 cx,
1773 );
1774 });
1775 cx.run_until_parked();
1776 cx.background_executor.advance_clock(Duration::from_secs(6));
1777 cx.run_until_parked();
1778 flush_dismiss(cx);
1779 assert!(
1780 ids(&list, cx).is_empty(),
1781 "the toast should have autohidden"
1782 );
1783 assert!(
1784 cx.dismissed_system_notifications().is_empty(),
1785 "autohide must not retract the system notification"
1786 );
1787
1788 // An explicit close retracts it.
1789 list.update_in(cx, |list, window, cx| {
1790 list.push(
1791 Notification::info("manual")
1792 .id::<BarKind>()
1793 .delivery(NotificationDelivery::InAppAndSystem)
1794 .autohide(false),
1795 window,
1796 cx,
1797 );
1798 });
1799 cx.run_until_parked();
1800 list.update_in(cx, |list, window, cx| {
1801 list.close(TypeId::of::<BarKind>(), window, cx);
1802 });
1803 flush_dismiss(cx);
1804 assert_eq!(
1805 cx.dismissed_system_notifications(),
1806 vec![NotificationId::Id(TypeId::of::<BarKind>()).system_tag()]
1807 );
1808 }
1809}