Skip to main content

gpui_component/
notification.rs

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