BlueGit

ict rusty-teams

Files

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

notification.rs

notification.rs 66.1 KiB Download Raw
1use std::{
2 any::TypeId,
3 borrow::Cow,
4 collections::{HashMap, HashSet},
5 rc::Rc,
6 time::Duration,
7};
8
9use gpui::{
10 Anchor, Animation, AnimationExt, AnyElement, AnyWindowHandle, App, AppContext, ClickEvent,
11 Context, DismissEvent, ElementId, Entity, EventEmitter, FocusHandle, Global,
12 InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, SharedString,
13 StatefulInteractiveElement, StyleRefinement, Styled, Subscription, SystemNotification,
14 SystemNotificationResponse, WeakEntity, Window, WindowId, div, prelude::FluentBuilder, px,
15 relative,
16};
17use gpui_base::{
18 Toast as BaseToast, ToastManager, ToastMotion, ToastOptions, ToastStack, ToastStackState,
19 ToastTransitionStatus,
20};
21
22use crate::fluent::{TOAST_ICON_GAP, TOAST_ICON_SIZE, TOAST_LINE_HEIGHT};
23use crate::{
24 ActiveTheme as _, Edges, Icon, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT,
25 animation::cubic_bezier,
26 button::{Button, ButtonVariants as _},
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 TOAST_PADDING_X: Pixels = px(16.);
35const TOAST_PADDING_Y: Pixels = px(14.);
36const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);
37struct DismissRequest;
38
39#[derive(Debug, Clone, Copy, Default)]
40pub enum NotificationType {
41 #[default]
42 Info,
43 Success,
44 Warning,
45 Error,
46}
47
48impl NotificationType {
49 fn icon(&self, cx: &App) -> Icon {
50 match self {
51 Self::Info => Icon::new(IconName::Info).text_color(cx.theme().info),
52 Self::Success => Icon::new(IconName::CircleCheck).text_color(cx.theme().success),
53 Self::Warning => Icon::new(IconName::TriangleAlert).text_color(cx.theme().warning),
54 Self::Error => Icon::new(IconName::CircleX).text_color(cx.theme().danger),
55 }
56 }
57}
58
59/// Where a notification is presented: as an in-app toast, in the operating
60/// system's notification center, or both.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum NotificationDelivery {
63 /// Show only the in-app toast.
64 #[default]
65 InApp,
66 /// Post only to the OS notification center; no in-app toast is shown.
67 System,
68 /// Show the in-app toast and post to the OS notification center.
69 InAppAndSystem,
70}
71
72impl NotificationDelivery {
73 /// Whether this delivery shows an in-app toast.
74 pub fn includes_in_app(&self) -> bool {
75 matches!(self, Self::InApp | Self::InAppAndSystem)
76 }
77
78 /// Whether this delivery posts to the OS notification center.
79 pub fn includes_system(&self) -> bool {
80 matches!(self, Self::System | Self::InAppAndSystem)
81 }
82}
83
84/// Namespaces the library's system-notification tags away from tags the
85/// application posts itself, so the response handler can tell them apart.
86const SYSTEM_TAG_PREFIX: &str = "gpui-component/notification/";
87
88#[derive(Debug, PartialEq, Clone, Hash, Eq)]
89pub(crate) enum NotificationId {
90 Id(TypeId),
91 IdAndElementId(TypeId, ElementId),
92}
93
94impl NotificationId {
95 /// Stable OS-notification tag for this id within a running binary, so a
96 /// repeat push with the same id replaces the previous system
97 /// notification, mirroring the in-app replace semantics.
98 fn system_tag(&self) -> SharedString {
99 format!("{SYSTEM_TAG_PREFIX}{self:?}").into()
100 }
101}
102
103impl From<TypeId> for NotificationId {
104 fn from(type_id: TypeId) -> Self {
105 Self::Id(type_id)
106 }
107}
108
109impl From<(TypeId, ElementId)> for NotificationId {
110 fn from((type_id, id): (TypeId, ElementId)) -> Self {
111 Self::IdAndElementId(type_id, id)
112 }
113}
114
115/// A notification element.
116pub struct Notification {
117 /// The id is used make the notification unique.
118 /// Then you push a notification with the same id, the previous notification will be replaced.
119 ///
120 /// None means the notification will be added to the end of the list.
121 id: NotificationId,
122 style: StyleRefinement,
123 type_: Option<NotificationType>,
124 title: Option<SharedString>,
125 message: Option<SharedString>,
126 icon: Option<Icon>,
127 placement: Option<Anchor>,
128 delivery: Option<NotificationDelivery>,
129 autohide: bool,
130 action_builder: Option<Rc<dyn Fn(&mut Self, &mut Window, &mut Context<Self>) -> Button>>,
131 content_builder: Option<Rc<dyn Fn(&mut Self, &mut Window, &mut Context<Self>) -> AnyElement>>,
132 on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
133 on_close: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
134 transition_status: ToastTransitionStatus,
135}
136
137impl From<String> for Notification {
138 fn from(s: String) -> Self {
139 Self::new().message(s)
140 }
141}
142
143impl From<SharedString> for Notification {
144 fn from(s: SharedString) -> Self {
145 Self::new().message(s)
146 }
147}
148
149impl From<&str> for Notification {
150 fn from(s: &str) -> Self {
151 Self::new().message(s)
152 }
153}
154
155impl<'a> From<Cow<'a, str>> for Notification {
156 fn from(s: Cow<'a, str>) -> Self {
157 Self::new().message(s)
158 }
159}
160
161impl<T> From<(NotificationType, T)> for Notification
162where
163 T: Into<SharedString>,
164{
165 fn from((type_, content): (NotificationType, T)) -> Self {
166 Self::new().message(content).with_type(type_)
167 }
168}
169
170struct DefaultIdType;
171
172impl Notification {
173 /// Create a new notification.
174 ///
175 /// The default id is a random UUID.
176 pub fn new() -> Self {
177 let id: SharedString = uuid::Uuid::new_v4().to_string().into();
178 let id = (TypeId::of::<DefaultIdType>(), id.into());
179
180 Self {
181 id: id.into(),
182 style: StyleRefinement::default(),
183 title: None,
184 message: None,
185 type_: None,
186 icon: None,
187 placement: None,
188 delivery: None,
189 autohide: true,
190 action_builder: None,
191 content_builder: None,
192 on_click: None,
193 on_close: None,
194 transition_status: ToastTransitionStatus::Starting,
195 }
196 }
197
198 /// Set the message of the notification, default is None.
199 pub fn message(mut self, message: impl Into<SharedString>) -> Self {
200 self.message = Some(message.into());
201 self
202 }
203
204 /// Create an info notification with the given message.
205 pub fn info(message: impl Into<SharedString>) -> Self {
206 Self::new()
207 .message(message)
208 .with_type(NotificationType::Info)
209 }
210
211 /// Create a success notification with the given message.
212 pub fn success(message: impl Into<SharedString>) -> Self {
213 Self::new()
214 .message(message)
215 .with_type(NotificationType::Success)
216 }
217
218 /// Create a warning notification with the given message.
219 pub fn warning(message: impl Into<SharedString>) -> Self {
220 Self::new()
221 .message(message)
222 .with_type(NotificationType::Warning)
223 }
224
225 /// Create an error notification with the given message.
226 pub fn error(message: impl Into<SharedString>) -> Self {
227 Self::new()
228 .message(message)
229 .with_type(NotificationType::Error)
230 }
231
232 /// Set the type for unique identification of the notification.
233 ///
234 /// ```rs
235 /// struct MyNotificationKind;
236 /// let notification = Notification::new().message("Hello").id::<MyNotificationKind>();
237 /// ```
238 pub fn id<T: Sized + 'static>(mut self) -> Self {
239 self.id = TypeId::of::<T>().into();
240 self
241 }
242
243 /// Set the type and id of the notification, used to uniquely identify the notification.
244 pub fn id1<T: Sized + 'static>(mut self, key: impl Into<ElementId>) -> Self {
245 self.id = (TypeId::of::<T>(), key.into()).into();
246 self
247 }
248
249 /// Set the title of the notification, default is None.
250 ///
251 /// If title is None, the notification will not have a title.
252 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
253 self.title = Some(title.into());
254 self
255 }
256
257 /// Set the icon of the notification.
258 ///
259 /// If icon is None, the notification will use the default icon of the type.
260 pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
261 self.icon = Some(icon.into());
262 self
263 }
264
265 /// Set the type of the notification, default is NotificationType::Info.
266 pub fn with_type(mut self, type_: NotificationType) -> Self {
267 self.type_ = Some(type_);
268 self
269 }
270
271 /// Set the placement of the notification, overriding the global
272 /// [`NotificationSettings::placement`].
273 ///
274 /// Notifications are stacked separately for each placement.
275 pub fn placement(mut self, placement: Anchor) -> Self {
276 self.placement = Some(placement);
277 self
278 }
279
280 /// Set where this notification is delivered, overriding the global
281 /// [`NotificationSettings::delivery`].
282 ///
283 /// System delivery uses the OS notification center: the title and message
284 /// become the system notification's title and body (a notification with
285 /// neither is not posted). Pushing again with the same [`Notification::id`]
286 /// replaces the previous system notification. Clicking the system
287 /// notification activates the window, closes the in-app toast (if any),
288 /// and fires [`Notification::on_click`]; with
289 /// [`NotificationDelivery::System`] the toast never exists, so
290 /// [`Notification::on_close`] is never called.
291 ///
292 /// Platform requirements: on macOS the application must run from a bundled
293 /// `.app` in a location the system trusts, such as `/Applications` (posts
294 /// are silently dropped under plain `cargo run`, and the first post
295 /// triggers the authorization prompt); on Windows the application must
296 /// call [`gpui::App::set_app_identity`] early in startup; on Linux a
297 /// notification daemon must be present and retraction is unsupported
298 /// (dismissed notifications age out).
299 pub fn delivery(mut self, delivery: NotificationDelivery) -> Self {
300 self.delivery = Some(delivery);
301 self
302 }
303
304 /// Deliver this notification only to the OS notification center.
305 ///
306 /// Shorthand for [`Notification::delivery`] with
307 /// [`NotificationDelivery::System`]; see there for platform requirements.
308 pub fn system(self) -> Self {
309 self.delivery(NotificationDelivery::System)
310 }
311
312 /// Deliver this notification as an in-app toast and to the OS
313 /// notification center.
314 ///
315 /// Shorthand for [`Notification::delivery`] with
316 /// [`NotificationDelivery::InAppAndSystem`]; see there for platform
317 /// requirements.
318 pub fn in_app_and_system(self) -> Self {
319 self.delivery(NotificationDelivery::InAppAndSystem)
320 }
321
322 /// Set the auto hide of the notification, default is true.
323 pub fn autohide(mut self, autohide: bool) -> Self {
324 self.autohide = autohide;
325 self
326 }
327
328 /// Set the click callback of the notification.
329 pub fn on_click(
330 mut self,
331 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
332 ) -> Self {
333 self.on_click = Some(Rc::new(on_click));
334 self
335 }
336
337 /// Set the close callback of the notification.
338 ///
339 /// Triggered when the notification is closed by any means
340 /// (close button, middle-click, autohide, click handler, or programmatic close).
341 pub fn on_close(mut self, on_close: impl Fn(&mut Window, &mut App) + 'static) -> Self {
342 self.on_close = Some(Rc::new(on_close));
343 self
344 }
345
346 /// Set the action button of the notification.
347 ///
348 /// When an action is set, the notification will not autohide.
349 pub fn action<F>(mut self, action: F) -> Self
350 where
351 F: Fn(&mut Self, &mut Window, &mut Context<Self>) -> Button + 'static,
352 {
353 self.action_builder = Some(Rc::new(action));
354 self.autohide = false;
355 self
356 }
357
358 /// Dismiss the notification.
359 pub fn dismiss(&mut self, window: &mut Window, cx: &mut Context<Self>) {
360 let _ = window;
361 cx.emit(DismissRequest);
362 }
363
364 fn begin_close(&mut self, cx: &mut Context<Self>) {
365 if self.transition_status != ToastTransitionStatus::Ending {
366 self.transition_status = ToastTransitionStatus::Ending;
367 cx.notify();
368 }
369 }
370
371 fn complete_enter(&mut self, cx: &mut Context<Self>) {
372 if self.transition_status == ToastTransitionStatus::Starting {
373 self.transition_status = ToastTransitionStatus::Present;
374 cx.notify();
375 }
376 }
377
378 fn complete_close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
379 cx.emit(DismissEvent);
380 if let Some(on_close) = self.on_close.clone() {
381 on_close(window, cx);
382 }
383 }
384
385 /// Set the content of the notification.
386 pub fn content(
387 mut self,
388 content: impl Fn(&mut Self, &mut Window, &mut Context<Self>) -> AnyElement + 'static,
389 ) -> Self {
390 self.content_builder = Some(Rc::new(content));
391 self
392 }
393}
394
395impl EventEmitter<DismissEvent> for Notification {}
396impl EventEmitter<DismissRequest> for Notification {}
397impl FluentBuilder for Notification {}
398impl Styled for Notification {
399 fn style(&mut self) -> &mut StyleRefinement {
400 &mut self.style
401 }
402}
403
404impl Render for Notification {
405 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
406 let content = self
407 .content_builder
408 .clone()
409 .map(|builder| builder(self, window, cx));
410 let action = self
411 .action_builder
412 .clone()
413 .map(|builder| builder(self, window, cx).small().mr_3p5());
414
415 let transition_status = self.transition_status;
416 let closing = transition_status == ToastTransitionStatus::Ending;
417 let icon = match self.type_ {
418 None => self.icon.clone(),
419 Some(type_) => Some(type_.icon(cx)),
420 };
421 let has_icon = icon.is_some();
422 let placement = self.placement.unwrap_or(cx.theme().notification.placement);
423 let toast_elevation = crate::elevation::toast(cx);
424 let resting_shadow = toast_elevation.shadow.clone();
425
426 BaseToast::new("notification")
427 .transition_status(transition_status)
428 .h_flex()
429 .group("")
430 .occlude()
431 .relative()
432 .w_full()
433 .border_1()
434 .border_color(cx.theme().border)
435 .bg(toast_elevation.fill)
436 .rounded(cx.theme().radius_lg)
437 .shadow(resting_shadow)
438 .py(TOAST_PADDING_Y)
439 .px(TOAST_PADDING_X)
440 .gap_3()
441 .refine_style(&self.style)
442 .when_some(icon, |this, icon| {
443 this.child(
444 div()
445 .absolute()
446 .top(TOAST_PADDING_Y)
447 .left(TOAST_PADDING_X)
448 .h(TOAST_LINE_HEIGHT)
449 .flex()
450 .items_center()
451 .child(icon.with_size(TOAST_ICON_SIZE)),
452 )
453 })
454 .child(
455 v_flex()
456 .flex_1()
457 .overflow_hidden()
458 .line_height(TOAST_LINE_HEIGHT)
459 .when(has_icon, |this| this.pl(TOAST_ICON_SIZE + TOAST_ICON_GAP))
460 .when_some(self.title.clone(), |this, title| {
461 this.child(div().text_sm().font_semibold().child(title))
462 })
463 .when_some(self.message.clone(), |this, message| {
464 this.child(div().text_sm().child(message))
465 })
466 .when_some(content, |this, content| this.child(content)),
467 )
468 .when_some(action, |this, action| this.child(action))
469 .child(
470 div()
471 .absolute()
472 .top_1()
473 .right_1()
474 .invisible()
475 .group_hover("", |this| this.visible())
476 .child(
477 Button::new("close")
478 .icon(IconName::Close)
479 .ghost()
480 .xsmall()
481 .on_click(cx.listener(|this, _, window, cx| {
482 cx.stop_propagation();
483 this.dismiss(window, cx);
484 })),
485 ),
486 )
487 .when_some(self.on_click.clone(), |this, on_click| {
488 this.on_click(cx.listener(move |view, event, window, cx| {
489 view.dismiss(window, cx);
490 on_click(event, window, cx);
491 }))
492 })
493 .on_aux_click(cx.listener(move |view, event: &ClickEvent, window, cx| {
494 if event.is_middle_click() {
495 view.dismiss(window, cx);
496 }
497 }))
498 .with_animation(
499 ElementId::NamedInteger("slide-down".into(), closing as u64),
500 Animation::new(if closing {
501 NOTIFICATION_EXIT_DURATION
502 } else {
503 NOTIFICATION_TRANSITION_DURATION
504 })
505 .with_easing(cubic_bezier(0.25, 0.1, 0.25, 1.)),
506 move |this, delta| {
507 if closing {
508 let opacity = 1. - delta;
509 let that = this
510 .opacity(opacity)
511 .shadow(toast_elevation.shadow_at(opacity.powi(3)));
512 let y_offset = match placement {
513 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => {
514 -delta * NOTIFICATION_TRANSITION_OFFSET
515 }
516 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => {
517 delta * NOTIFICATION_TRANSITION_OFFSET
518 }
519 _ => px(0.),
520 };
521 that.top(y_offset)
522 } else {
523 let y_offset = match placement {
524 Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => {
525 -NOTIFICATION_TRANSITION_OFFSET
526 + delta * NOTIFICATION_TRANSITION_OFFSET
527 }
528 Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => {
529 NOTIFICATION_TRANSITION_OFFSET
530 - delta * NOTIFICATION_TRANSITION_OFFSET
531 }
532 _ => px(0.),
533 };
534 let opacity = delta;
535 // GPUI paints a drop shadow *under* the card and has no
536 // group compositing, so a card that is still translucent
537 // does not hide its own shadow and it shows through as a
538 // dark slab. Ramping the ink by the cube of the fade
539 // keeps it out of sight until the card can cover it —
540 // where this used to drop the shadow outright past a
541 // threshold, which popped.
542 this.top(px(0.) + y_offset)
543 .opacity(opacity)
544 .shadow(toast_elevation.shadow_at(opacity.powi(3)))
545 }
546 },
547 )
548 }
549}
550
551/// The settings for notifications.
552#[derive(Debug, Clone)]
553pub struct NotificationSettings {
554 /// The placement of the notifications, default: [`Anchor::TopRight`]
555 ///
556 /// A single notification can override this with [`Notification::placement`].
557 pub placement: Anchor,
558 /// The margins of the notification with respect to the window edges.
559 pub margins: Edges<Pixels>,
560 /// The maximum number of notifications to show at once, default: 10
561 pub max_items: usize,
562 /// The width of the notifications, default: 382px
563 pub width: Pixels,
564 /// Where notifications are delivered, default: [`NotificationDelivery::InApp`]
565 ///
566 /// A single notification can override this with [`Notification::delivery`].
567 pub delivery: NotificationDelivery,
568}
569
570impl Default for NotificationSettings {
571 fn default() -> Self {
572 let offset = px(16.);
573 Self {
574 placement: Anchor::TopRight,
575 margins: Edges {
576 top: TITLE_BAR_HEIGHT + offset, // avoid overlap with title bar
577 right: offset,
578 bottom: offset,
579 left: offset,
580 },
581 max_items: 10,
582 width: DEFAULT_NOTIFICATION_WIDTH,
583 delivery: NotificationDelivery::default(),
584 }
585 }
586}
587
588/// Registers the app-global system-notification response handler.
589///
590/// gpui keeps a single such handler (later registrations replace earlier
591/// ones), so gpui-component owns it: applications must not call
592/// [`gpui::App::on_system_notification_response`] after `gpui_component::init`.
593/// Responses to notifications the application posts itself are ignored here.
594pub(crate) fn init(cx: &mut App) {
595 cx.on_system_notification_response(SystemNotificationRegistry::handle_response);
596}
597
598struct SystemNotificationEntry {
599 window: AnyWindowHandle,
600 list: WeakEntity<NotificationList>,
601 id: NotificationId,
602 on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
603}
604
605const MAX_SYSTEM_NOTIFICATION_ENTRIES: usize = 100;
606
607/// App-global map from system-notification tag to the state needed to
608/// dispatch the user's response, ordered oldest-first so overflow prunes the
609/// stalest entries.
610#[derive(Default)]
611struct SystemNotificationRegistry {
612 entries: Vec<(SharedString, SystemNotificationEntry)>,
613}
614
615impl Global for SystemNotificationRegistry {}
616
617impl SystemNotificationRegistry {
618 fn insert(cx: &mut App, tag: SharedString, entry: SystemNotificationEntry) {
619 let entries = &mut cx.default_global::<Self>().entries;
620 entries.retain(|(existing, _)| *existing != tag);
621 entries.push((tag, entry));
622 if entries.len() > MAX_SYSTEM_NOTIFICATION_ENTRIES {
623 let overflow = entries.len() - MAX_SYSTEM_NOTIFICATION_ENTRIES;
624 entries.drain(..overflow);
625 }
626 }
627
628 /// Retract the system notification for `id`, but only if it was posted
629 /// from the given window: another window pushing the same id owns the tag
630 /// now, and this window's local dismiss must not clobber it.
631 fn dismiss(cx: &mut App, id: &NotificationId, window_id: WindowId) {
632 let tag = id.system_tag();
633 let entries = &mut cx.default_global::<Self>().entries;
634 let Some(ix) = entries.iter().position(|(existing, entry)| {
635 *existing == tag && entry.window.window_id() == window_id
636 }) else {
637 return;
638 };
639 entries.remove(ix);
640 cx.dismiss_system_notification(&tag);
641 }
642
643 /// Retract all of the window's system notifications whose id matches the
644 /// given [`TypeId`], regardless of the [`NotificationId`] variant.
645 fn dismiss_by_type(cx: &mut App, type_id: TypeId, window_id: WindowId) {
646 Self::dismiss_matching(cx, window_id, |id| match id {
647 NotificationId::Id(t) | NotificationId::IdAndElementId(t, _) => *t == type_id,
648 });
649 }
650
651 /// Retract all system notifications posted from the given window.
652 fn dismiss_all(cx: &mut App, window_id: WindowId) {
653 Self::dismiss_matching(cx, window_id, |_| true);
654 }
655
656 fn dismiss_matching(
657 cx: &mut App,
658 window_id: WindowId,
659 matches: impl Fn(&NotificationId) -> bool,
660 ) {
661 let entries = &mut cx.default_global::<Self>().entries;
662 let mut tags = Vec::new();
663 entries.retain(|(tag, entry)| {
664 if entry.window.window_id() == window_id && matches(&entry.id) {
665 tags.push(tag.clone());
666 false
667 } else {
668 true
669 }
670 });
671 for tag in tags {
672 cx.dismiss_system_notification(&tag);
673 }
674 }
675
676 fn handle_response(response: SystemNotificationResponse, cx: &mut App) {
677 if !response.tag.starts_with(SYSTEM_TAG_PREFIX) {
678 return;
679 }
680 // Platforms usually remove a clicked notification themselves; retract
681 // explicitly for the ones that keep it in the notification center.
682 cx.dismiss_system_notification(&response.tag);
683 // The prefix already proves the notification is ours, so activate even
684 // when nothing is left to dispatch to: the platform can deliver a
685 // response for a notification posted before the process restarted, and
686 // entries are pruned past `MAX_SYSTEM_NOTIFICATION_ENTRIES`.
687 cx.activate(true);
688 let entries = &mut cx.default_global::<Self>().entries;
689 let Some(ix) = entries.iter().position(|(tag, _)| *tag == response.tag) else {
690 return;
691 };
692 let (_, entry) = entries.remove(ix);
693 // Errs when the window is already closed: the entry is removed and the
694 // application is still brought to the foreground.
695 let _ = entry.window.update(cx, |_, window, cx| {
696 window.activate_window();
697 if let Some(list) = entry.list.upgrade() {
698 // No-op when the toast already closed or was never created
699 // (system-only delivery).
700 list.update(cx, |list, cx| list.close(entry.id.clone(), window, cx));
701 }
702 if let Some(on_click) = entry.on_click {
703 on_click(&ClickEvent::default(), window, cx);
704 }
705 });
706 }
707}
708
709/// Per-placement stack state, created lazily for placements in use.
710struct AnchorStack {
711 state: ToastStackState,
712 focus_handle: FocusHandle,
713}
714
715/// A list of notifications.
716pub struct NotificationList {
717 /// Notifications that will be auto hidden.
718 pub(crate) notifications: ToastManager<NotificationId, Entity<Notification>>,
719 stacks: Vec<(Anchor, AnchorStack)>,
720 focus_handle: FocusHandle,
721 /// Mounted notifications that hide themselves after a timeout.
722 autohide_ids: HashSet<NotificationId>,
723 /// Whether the lifecycle clock is running. The loop clears it as it exits.
724 is_advancing: bool,
725 _subscriptions: HashMap<NotificationId, Subscription>,
726}
727
728impl NotificationList {
729 pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
730 Self {
731 notifications: ToastManager::new(ToastMotion::sonner()),
732 stacks: Vec::new(),
733 focus_handle: cx.focus_handle().tab_stop(true),
734 autohide_ids: HashSet::new(),
735 is_advancing: false,
736 _subscriptions: HashMap::new(),
737 }
738 }
739
740 /// Tick the toast lifecycle while a notification still has time to track.
741 ///
742 /// It advances the transition phases and samples the pause input (stack
743 /// expansion) that reaches the list through no event.
744 /// With nothing mounted, or only persistent notifications at rest, there is
745 /// nothing to do, so the window arms no timer until a push or close.
746 fn start_advancing(&mut self, window: &mut Window, cx: &mut Context<Self>) {
747 if self.is_advancing {
748 return;
749 }
750 self.is_advancing = true;
751 // Detached rather than kept as a `Task`: the loop ends itself, and a
752 // handle on the list would have to be dropped from inside its own future.
753 cx.spawn_in(window, async move |view, cx| {
754 loop {
755 cx.background_executor()
756 .timer(NOTIFICATION_ADVANCE_INTERVAL)
757 .await;
758 let running = view.update_in(cx, |view, window, cx| {
759 view.advance(window, cx);
760 view.is_advancing = view.needs_clock();
761 view.is_advancing
762 });
763 if !matches!(running, Ok(true)) {
764 break;
765 }
766 }
767 })
768 .detach();
769 }
770
771 /// Whether a mounted notification is in transition or counting down to
772 /// autohide. A paused countdown still needs its last sample kept current.
773 fn needs_clock(&self) -> bool {
774 self.notifications
775 .iter()
776 .any(|(id, _, status)| match status {
777 ToastTransitionStatus::Present => self.autohide_ids.contains(id),
778 ToastTransitionStatus::Starting | ToastTransitionStatus::Ending => true,
779 })
780 }
781
782 fn is_expanded(&self) -> bool {
783 self.stacks
784 .iter()
785 .any(|(_, stack)| stack.state.is_expanded())
786 }
787
788 /// Group the visible notifications by their effective placement, pairing
789 /// each group with the element id its stack renders under and preserving
790 /// the display order within each group.
791 fn grouped(
792 &self,
793 cx: &App,
794 ) -> Vec<(
795 Anchor,
796 ElementId,
797 Vec<(NotificationId, Entity<Notification>)>,
798 )> {
799 let settings = &cx.theme().notification;
800 let (max_items, placement) = (settings.max_items, settings.placement);
801
802 let mut groups: Vec<(Anchor, Vec<(NotificationId, Entity<Notification>)>)> = Vec::new();
803 for (id, item, _) in self.notifications.visible(max_items) {
804 let anchor = item.read(cx).placement.unwrap_or(placement);
805 match groups.iter_mut().find(|(a, _)| *a == anchor) {
806 Some((_, items)) => items.push((id.clone(), item.clone())),
807 None => groups.push((anchor, vec![(id.clone(), item.clone())])),
808 }
809 }
810 groups
811 .into_iter()
812 .map(|(anchor, items)| (anchor, Self::stack_id(anchor), items))
813 .collect()
814 }
815
816 /// The element id a placement's stack renders under.
817 ///
818 /// Keyed by the placement itself rather than by position among the mounted
819 /// stacks: a stack whose id changes loses the element state of its whole
820 /// subtree, which replays the enter animation of every notification in it.
821 fn stack_id(anchor: Anchor) -> ElementId {
822 let ix = match anchor {
823 Anchor::TopLeft => 0,
824 Anchor::TopCenter => 1,
825 Anchor::TopRight => 2,
826 Anchor::BottomLeft => 3,
827 Anchor::BottomCenter => 4,
828 Anchor::BottomRight => 5,
829 Anchor::LeftCenter => 6,
830 Anchor::RightCenter => 7,
831 };
832 ("notification-list", ix as usize).into()
833 }
834
835 pub fn push(
836 &mut self,
837 notification: impl Into<Notification>,
838 window: &mut Window,
839 cx: &mut Context<Self>,
840 ) {
841 let notification = notification.into();
842 let delivery = notification
843 .delivery
844 .unwrap_or(cx.theme().notification.delivery);
845 if delivery.includes_system() {
846 Self::push_system(&notification, window, cx);
847 }
848 if !delivery.includes_in_app() {
849 return;
850 }
851
852 let id = notification.id.clone();
853 let autohide = notification.autohide;
854 let window_id = window.window_handle().window_id();
855
856 let notification = cx.new(|_| notification);
857
858 let dismiss_id = id.clone();
859 self._subscriptions.insert(
860 id.clone(),
861 cx.subscribe_in(
862 &notification,
863 window,
864 move |view, _, _: &DismissRequest, window, cx| {
865 if view
866 .notifications
867 .dismiss(&dismiss_id, cx.background_executor().now())
868 {
869 if let Some(note) = view.notifications.get(&dismiss_id) {
870 note.update(cx, |note, cx| note.begin_close(cx));
871 }
872 SystemNotificationRegistry::dismiss(cx, &dismiss_id, window_id);
873 view.start_advancing(window, cx);
874 }
875 },
876 ),
877 );
878 if autohide {
879 self.autohide_ids.insert(id.clone());
880 } else {
881 self.autohide_ids.remove(&id);
882 }
883
884 self.notifications.push(
885 id,
886 notification,
887 ToastOptions {
888 timeout: autohide.then_some(Duration::from_secs(5)),
889 },
890 cx.background_executor().now(),
891 );
892 self.start_advancing(window, cx);
893 cx.notify();
894 }
895
896 /// Post the notification to the OS notification center and register the
897 /// state needed to dispatch the user's response back to this window.
898 fn push_system(notification: &Notification, window: &Window, cx: &mut Context<Self>) {
899 let (title, body) = match (&notification.title, &notification.message) {
900 (Some(title), message) => (title.clone(), message.clone().unwrap_or_default()),
901 (None, Some(message)) => (message.clone(), SharedString::default()),
902 // A content-only notification has nothing textual to show.
903 (None, None) => return,
904 };
905 let tag = notification.id.system_tag();
906 let entry = SystemNotificationEntry {
907 window: window.window_handle(),
908 list: cx.entity().downgrade(),
909 id: notification.id.clone(),
910 on_click: notification.on_click.clone(),
911 };
912 SystemNotificationRegistry::insert(cx, tag.clone(), entry);
913 cx.show_system_notification(SystemNotification {
914 tag,
915 title,
916 body,
917 actions: Vec::new(),
918 });
919 }
920
921 fn advance(&mut self, window: &mut Window, cx: &mut Context<Self>) {
922 let changes = self
923 .notifications
924 .advance(cx.background_executor().now(), self.is_expanded());
925 for id in changes.presented {
926 if let Some(note) = self.notifications.get(&id) {
927 note.update(cx, |note, cx| note.complete_enter(cx));
928 }
929 }
930 for id in changes.ending {
931 if let Some(note) = self.notifications.get(&id) {
932 note.update(cx, |note, cx| note.begin_close(cx));
933 }
934 }
935 for (id, note) in changes.removed {
936 self._subscriptions.remove(&id);
937 self.autohide_ids.remove(&id);
938 note.update(cx, |note, cx| note.complete_close(window, cx));
939 }
940 if changes.changed {
941 cx.notify();
942 }
943 }
944
945 pub(crate) fn close(
946 &mut self,
947 id: impl Into<NotificationId>,
948 window: &mut Window,
949 cx: &mut Context<Self>,
950 ) {
951 let id: NotificationId = id.into();
952 // Unconditional: a system-only notification has no toast to dismiss,
953 // but its system counterpart must still be retracted.
954 SystemNotificationRegistry::dismiss(cx, &id, window.window_handle().window_id());
955 if self
956 .notifications
957 .dismiss(&id, cx.background_executor().now())
958 {
959 if let Some(n) = self.notifications.get(&id) {
960 n.update(cx, |note, cx| note.begin_close(cx))
961 }
962 self.start_advancing(window, cx);
963 }
964 cx.notify();
965 }
966
967 /// Close all notifications whose id matches the given [`TypeId`], regardless of
968 /// whether they were registered via [`Notification::id`] or [`Notification::id1`].
969 pub(crate) fn close_by_type(
970 &mut self,
971 type_id: TypeId,
972 window: &mut Window,
973 cx: &mut Context<Self>,
974 ) {
975 SystemNotificationRegistry::dismiss_by_type(
976 cx,
977 type_id,
978 window.window_handle().window_id(),
979 );
980 let matched: Vec<_> = self
981 .notifications
982 .iter()
983 .filter(|(id, _, _)| match id {
984 NotificationId::Id(t) | NotificationId::IdAndElementId(t, _) => *t == type_id,
985 })
986 .map(|(_, notification, _)| notification)
987 .cloned()
988 .collect();
989 for n in matched {
990 let id = n.read(cx).id.clone();
991 if self
992 .notifications
993 .dismiss(&id, cx.background_executor().now())
994 {
995 n.update(cx, |note, cx| note.begin_close(cx));
996 self.start_advancing(window, cx);
997 }
998 }
999 cx.notify();
1000 }
1001
1002 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1003 SystemNotificationRegistry::dismiss_all(cx, window.window_handle().window_id());
1004 for id in self
1005 .notifications
1006 .dismiss_all(cx.background_executor().now())
1007 {
1008 if let Some(note) = self.notifications.get(&id) {
1009 note.update(cx, |note, cx| note.begin_close(cx));
1010 }
1011 self.start_advancing(window, cx);
1012 }
1013 cx.notify();
1014 }
1015
1016 pub fn notifications(&self) -> Vec<Entity<Notification>> {
1017 self.notifications
1018 .iter()
1019 .map(|(_, value, _)| value.clone())
1020 .collect()
1021 }
1022}
1023
1024impl Render for NotificationList {
1025 fn render(
1026 &mut self,
1027 window: &mut gpui::Window,
1028 cx: &mut gpui::Context<Self>,
1029 ) -> impl IntoElement {
1030 let size = window.viewport_size();
1031 let settings = &cx.theme().notification;
1032 let (placement, margins, width) =
1033 (settings.placement, settings.margins.clone(), settings.width);
1034
1035 let groups = self.grouped(cx);
1036 self.stacks
1037 .retain(|(anchor, _)| groups.iter().any(|(a, _, _)| a == anchor));
1038
1039 let default_focus_handle = self.focus_handle.clone();
1040 let stacks = groups.into_iter().map(|(anchor, stack_id, items)| {
1041 let stack_ix = self
1042 .stacks
1043 .iter()
1044 .position(|(a, _)| *a == anchor)
1045 .unwrap_or_else(|| {
1046 self.stacks.push((
1047 anchor,
1048 AnchorStack {
1049 state: ToastStackState::default(),
1050 focus_handle: if anchor == placement {
1051 default_focus_handle.clone()
1052 } else {
1053 cx.focus_handle().tab_stop(true)
1054 },
1055 },
1056 ));
1057 self.stacks.len() - 1
1058 });
1059 let stack = &self.stacks[stack_ix].1;
1060
1061 items
1062 .into_iter()
1063 .fold(
1064 ToastStack::new(stack_id, stack.state.clone()),
1065 |stack, (id, item)| stack.item(format!("{id:?}"), item),
1066 )
1067 .placement(anchor)
1068 .focus_handle(stack.focus_handle.clone())
1069 .v_flex()
1070 .w(width)
1071 .max_h(size.height)
1072 .absolute()
1073 .map(|this| match anchor {
1074 Anchor::TopLeft => this.top(margins.top).left(margins.left),
1075 Anchor::TopRight => this.top(margins.top).right(margins.right),
1076 Anchor::TopCenter => this.top(margins.top).left(relative(0.5)).ml(-width / 2.),
1077 Anchor::BottomLeft => this.bottom(margins.bottom).left(margins.left),
1078 Anchor::BottomRight => this.bottom(margins.bottom).right(margins.right),
1079 Anchor::BottomCenter => this
1080 .bottom(margins.bottom)
1081 .left(relative(0.5))
1082 .ml(-width / 2.),
1083 Anchor::LeftCenter => this.left(margins.left).top_0().bottom_0().my_auto(),
1084 Anchor::RightCenter => this.right(margins.right).top_0().bottom_0().my_auto(),
1085 })
1086 });
1087
1088 div().size_full().children(stacks)
1089 }
1090}
1091
1092#[cfg(test)]
1093mod tests {
1094 use super::*;
1095 use crate::theme::Theme;
1096 use gpui::{TestAppContext, VisualTestContext};
1097
1098 struct FooKind;
1099 struct BarKind;
1100
1101 struct TestRoot {
1102 list: Entity<NotificationList>,
1103 other_focus: FocusHandle,
1104 }
1105
1106 impl Render for TestRoot {
1107 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1108 div()
1109 .child(self.list.clone())
1110 .child(div().track_focus(&self.other_focus))
1111 }
1112 }
1113
1114 fn ids(list: &Entity<NotificationList>, cx: &mut VisualTestContext) -> Vec<NotificationId> {
1115 list.read_with(cx, |l, cx| {
1116 l.notifications
1117 .iter()
1118 .map(|(_, n, _)| n.read(cx).id.clone())
1119 .collect()
1120 })
1121 }
1122
1123 /// Drive the dismiss animation timer + propagate the resulting `DismissEvent`
1124 /// so that closed notifications are removed from the list.
1125 fn flush_dismiss(cx: &mut VisualTestContext) {
1126 cx.background_executor
1127 .advance_clock(NOTIFICATION_EXIT_DURATION + Duration::from_millis(50));
1128 cx.run_until_parked();
1129 }
1130
1131 #[test]
1132 fn test_notification_builder() {
1133 let note = Notification::new()
1134 .title("title")
1135 .message("message")
1136 .with_type(NotificationType::Success)
1137 .placement(Anchor::BottomLeft)
1138 .delivery(NotificationDelivery::System)
1139 .autohide(false);
1140 assert_eq!(note.title, Some("title".into()));
1141 assert_eq!(note.message, Some("message".into()));
1142 assert!(matches!(note.type_, Some(NotificationType::Success)));
1143 assert_eq!(note.placement, Some(Anchor::BottomLeft));
1144 assert_eq!(note.delivery, Some(NotificationDelivery::System));
1145 assert!(!note.autohide);
1146
1147 assert_eq!(Notification::new().delivery, None);
1148 assert_eq!(
1149 Notification::new().system().delivery,
1150 Some(NotificationDelivery::System)
1151 );
1152 assert_eq!(
1153 Notification::new().in_app_and_system().delivery,
1154 Some(NotificationDelivery::InAppAndSystem)
1155 );
1156 }
1157
1158 #[test]
1159 fn notification_delivery_includes() {
1160 assert!(NotificationDelivery::InApp.includes_in_app());
1161 assert!(!NotificationDelivery::InApp.includes_system());
1162 assert!(!NotificationDelivery::System.includes_in_app());
1163 assert!(NotificationDelivery::System.includes_system());
1164 assert!(NotificationDelivery::InAppAndSystem.includes_in_app());
1165 assert!(NotificationDelivery::InAppAndSystem.includes_system());
1166 }
1167
1168 #[test]
1169 fn system_tag_is_stable_and_namespaced() {
1170 let by_type = NotificationId::from(TypeId::of::<FooKind>());
1171 assert_eq!(by_type.system_tag(), by_type.clone().system_tag());
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}