Skip to main content

gpui_component/
notification.rs

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