Skip to main content

gpui_base/
toast.rs

1use crate::TestSupportExt as _;
2#[cfg(not(target_family = "wasm"))]
3use std::time::Instant;
4use std::{cell::RefCell, collections::VecDeque, rc::Rc, time::Duration};
5#[cfg(target_family = "wasm")]
6use web_time::Instant;
7
8use gpui::{
9    Anchor, AnyElement, App, Div, ElementId, FocusHandle, InteractiveElement, Interactivity,
10    IntoElement, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role, Stateful,
11    StatefulInteractiveElement, StyleRefinement, Styled, Window, canvas, div,
12    prelude::FluentBuilder as _, px,
13};
14
15use crate::motion::{Spring, spring};
16
17/// Motion tokens used by an unstyled toast stack.
18#[derive(Clone, Copy, Debug)]
19pub struct ToastMotion {
20    /// Time scale of the stack's motion.
21    ///
22    /// This is read as two different quantities, because the stack sequences
23    /// one thing and interpolates another. [`ToastManager`] treats it as a
24    /// deadline: a toast is present once it has elapsed. The layout treats it
25    /// as a spring response, which is the scale the reflow is felt at rather
26    /// than the moment it stops — a toast arriving still nudges the stack for
27    /// a little longer than this.
28    pub duration: Duration,
29    /// Duration before an ending toast is unmounted.
30    pub exit_duration: Duration,
31    /// Visible distance between collapsed toast layers.
32    pub collapsed_peek: Pixels,
33    /// Distance between expanded toast items.
34    pub expanded_gap: Pixels,
35    /// Fractional width reduction for each collapsed layer.
36    pub collapsed_scale_step: f32,
37    /// Number of layers visible while the stack is collapsed.
38    pub collapsed_visible: usize,
39}
40
41impl ToastMotion {
42    /// Create motion matching the shadcn/Sonner toaster.
43    pub fn sonner() -> Self {
44        Self {
45            duration: Duration::from_millis(400),
46            exit_duration: Duration::from_millis(200),
47            collapsed_peek: px(14.),
48            expanded_gap: px(14.),
49            collapsed_scale_step: 0.05,
50            collapsed_visible: 3,
51        }
52    }
53}
54
55impl Default for ToastMotion {
56    fn default() -> Self {
57        Self::sonner()
58    }
59}
60
61/// Persistent private layout state used by [`ToastStack`].
62#[derive(Clone, Debug, Default)]
63pub struct ToastStackState {
64    heights: Rc<RefCell<std::collections::HashMap<ElementId, Pixels>>>,
65    width: Rc<std::cell::Cell<Pixels>>,
66    hovered: Rc<std::cell::Cell<bool>>,
67    focused: Rc<std::cell::Cell<bool>>,
68}
69
70impl ToastStackState {
71    /// Return whether interaction has expanded the stack.
72    pub fn is_expanded(&self) -> bool {
73        self.hovered.get() || self.focused.get()
74    }
75}
76
77/// Options applied when a toast enters a [`ToastManager`].
78#[derive(Clone, Copy, Debug, Default)]
79pub struct ToastOptions {
80    /// Active time before automatic dismissal; `None` disables auto-hide.
81    pub timeout: Option<Duration>,
82}
83
84#[derive(Debug)]
85struct ManagedToast<I, T> {
86    id: I,
87    value: T,
88    status: ToastTransitionStatus,
89    timeout_remaining: Option<Duration>,
90    transition_elapsed: Duration,
91    last_advance: Instant,
92}
93
94/// Changes produced when a toast manager advances its lifecycle clock.
95#[derive(Debug)]
96pub struct ToastAdvance<I, T> {
97    /// Whether a mounted toast changed phase or membership.
98    pub changed: bool,
99    /// Toast ids whose entry transition completed.
100    pub presented: Vec<I>,
101    /// Toast ids that entered their ending transition.
102    pub ending: Vec<I>,
103    /// Toast values removed after their ending transition completed.
104    pub removed: Vec<(I, T)>,
105}
106
107/// Ordered toast storage, lifecycle, auto-hide, limits, and exit coordination.
108#[derive(Debug)]
109pub struct ToastManager<I, T> {
110    entries: VecDeque<ManagedToast<I, T>>,
111    transition_duration: Duration,
112    exit_duration: Duration,
113}
114
115impl<I, T> ToastManager<I, T> {
116    /// Create a manager using the supplied motion duration for enter and exit.
117    pub fn new(motion: ToastMotion) -> Self {
118        Self {
119            entries: VecDeque::new(),
120            transition_duration: motion.duration,
121            exit_duration: motion.exit_duration,
122        }
123    }
124
125    /// Return the number of mounted toasts, including ending toasts.
126    pub fn len(&self) -> usize {
127        self.entries.len()
128    }
129
130    /// Return whether no toast is mounted.
131    pub fn is_empty(&self) -> bool {
132        self.entries.is_empty()
133    }
134
135    /// Iterate over mounted toast ids, values, and phases in display order.
136    pub fn iter(&self) -> impl DoubleEndedIterator<Item = (&I, &T, ToastTransitionStatus)> {
137        self.entries
138            .iter()
139            .map(|entry| (&entry.id, &entry.value, entry.status))
140    }
141
142    /// Iterate over newest visible active toasts plus ending toasts.
143    pub fn visible(&self, limit: usize) -> impl Iterator<Item = (&I, &T, ToastTransitionStatus)> {
144        let first = self
145            .entries
146            .iter()
147            .filter(|entry| entry.status != ToastTransitionStatus::Ending)
148            .count()
149            .saturating_sub(limit);
150        let mut active_index = 0usize;
151        self.entries.iter().filter_map(move |entry| {
152            let visible = if entry.status == ToastTransitionStatus::Ending {
153                true
154            } else {
155                let keep = active_index >= first;
156                active_index += 1;
157                keep
158            };
159            visible.then_some((&entry.id, &entry.value, entry.status))
160        })
161    }
162
163    /// Return a mounted toast value by id.
164    pub fn get(&self, id: &I) -> Option<&T>
165    where
166        I: Eq,
167    {
168        self.entries
169            .iter()
170            .find_map(|entry| (&entry.id == id).then_some(&entry.value))
171    }
172}
173
174impl<I: Clone + Eq, T> ToastManager<I, T> {
175    /// Add a newest toast, replacing an existing toast with the same id.
176    pub fn push(&mut self, id: I, value: T, options: ToastOptions, now: Instant) -> Option<T> {
177        let replaced = self
178            .entries
179            .iter()
180            .position(|entry| entry.id == id)
181            .and_then(|index| self.entries.remove(index))
182            .map(|entry| entry.value);
183        self.entries.push_back(ManagedToast {
184            id,
185            value,
186            status: ToastTransitionStatus::Starting,
187            timeout_remaining: options.timeout,
188            transition_elapsed: Duration::ZERO,
189            last_advance: now,
190        });
191        replaced
192    }
193
194    /// Begin a toast's exit transition, returning whether its state changed.
195    pub fn dismiss(&mut self, id: &I, now: Instant) -> bool {
196        let Some(entry) = self.entries.iter_mut().find(|entry| &entry.id == id) else {
197            return false;
198        };
199        if entry.status == ToastTransitionStatus::Ending {
200            return false;
201        }
202        entry.status = ToastTransitionStatus::Ending;
203        entry.transition_elapsed = Duration::ZERO;
204        entry.last_advance = now;
205        true
206    }
207
208    /// Begin the exit transition for every active toast.
209    pub fn dismiss_all(&mut self, now: Instant) -> Vec<I> {
210        let mut changed = Vec::new();
211        for entry in &mut self.entries {
212            if entry.status != ToastTransitionStatus::Ending {
213                entry.status = ToastTransitionStatus::Ending;
214                entry.transition_elapsed = Duration::ZERO;
215                entry.last_advance = now;
216                changed.push(entry.id.clone());
217            }
218        }
219        changed
220    }
221
222    /// Advance lifecycle time; active timers pause while `paused` is true.
223    pub fn advance(&mut self, now: Instant, paused: bool) -> ToastAdvance<I, T> {
224        let mut ending = Vec::new();
225        let mut presented = Vec::new();
226        let mut changed = false;
227        for entry in &mut self.entries {
228            let delta = now.saturating_duration_since(entry.last_advance);
229            entry.last_advance = now;
230            match entry.status {
231                ToastTransitionStatus::Starting => {
232                    entry.transition_elapsed += delta;
233                    if entry.transition_elapsed >= self.transition_duration {
234                        entry.status = ToastTransitionStatus::Present;
235                        entry.transition_elapsed = Duration::ZERO;
236                        presented.push(entry.id.clone());
237                        changed = true;
238                    }
239                }
240                ToastTransitionStatus::Present if !paused => {
241                    if let Some(remaining) = &mut entry.timeout_remaining {
242                        *remaining = remaining.saturating_sub(delta);
243                        if remaining.is_zero() {
244                            entry.status = ToastTransitionStatus::Ending;
245                            entry.transition_elapsed = Duration::ZERO;
246                            ending.push(entry.id.clone());
247                            changed = true;
248                        }
249                    }
250                }
251                ToastTransitionStatus::Ending => entry.transition_elapsed += delta,
252                ToastTransitionStatus::Present => {}
253            }
254        }
255        let mut removed = Vec::new();
256        let mut index = 0;
257        while index < self.entries.len() {
258            if self.entries[index].status == ToastTransitionStatus::Ending
259                && self.entries[index].transition_elapsed >= self.exit_duration
260            {
261                let entry = self.entries.remove(index).expect("toast index is valid");
262                removed.push((entry.id, entry.value));
263                changed = true;
264            } else {
265                index += 1;
266            }
267        }
268        ToastAdvance {
269            changed,
270            presented,
271            ending,
272            removed,
273        }
274    }
275}
276
277/// A deep toast-stack element that owns measurement, overlap, and expansion motion.
278#[derive(IntoElement)]
279pub struct ToastStack {
280    id: ElementId,
281    base: crate::ObservedElement<Stateful<Div>>,
282    style: StyleRefinement,
283    state: ToastStackState,
284    motion: ToastMotion,
285    placement: Anchor,
286    focus_handle: Option<FocusHandle>,
287    children: Vec<(ElementId, AnyElement)>,
288}
289
290impl ToastStack {
291    /// Create a toast stack with Base UI-compatible motion.
292    pub fn new(id: impl Into<ElementId>, state: ToastStackState) -> Self {
293        let id = id.into();
294        Self {
295            base: div().id(id.clone()).test_support(),
296            id,
297            style: StyleRefinement::default(),
298            state,
299            motion: ToastMotion::sonner(),
300            placement: Anchor::TopRight,
301            focus_handle: None,
302            children: Vec::new(),
303        }
304    }
305
306    /// Add a stably keyed toast item to the stack.
307    pub fn item(mut self, id: impl Into<ElementId>, child: impl IntoElement) -> Self {
308        self.children.push((id.into(), child.into_any_element()));
309        self
310    }
311
312    /// Set the stack motion tokens.
313    pub fn motion(mut self, motion: ToastMotion) -> Self {
314        self.motion = motion;
315        self
316    }
317
318    /// Set the viewport edge used to anchor stack geometry.
319    pub fn placement(mut self, placement: Anchor) -> Self {
320        self.placement = placement;
321        self
322    }
323
324    /// Set the focus scope that expands the stack and pauses auto-hide timers.
325    pub fn focus_handle(mut self, focus_handle: FocusHandle) -> Self {
326        self.focus_handle = Some(focus_handle);
327        self
328    }
329}
330
331impl Styled for ToastStack {
332    fn style(&mut self) -> &mut StyleRefinement {
333        &mut self.style
334    }
335}
336
337impl ParentElement for ToastStack {
338    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
339        self.children
340            .extend(children.into_iter().enumerate().map(|(index, child)| {
341                (
342                    ElementId::NamedInteger("toast-stack-child".into(), index as u64),
343                    child,
344                )
345            }));
346    }
347}
348
349impl InteractiveElement for ToastStack {
350    fn interactivity(&mut self) -> &mut Interactivity {
351        self.base.interactivity()
352    }
353
354    fn track_focus(mut self, handle: &gpui::FocusHandle) -> Self {
355        self.base = self.base.track_focus(handle);
356        self
357    }
358}
359
360impl StatefulInteractiveElement for ToastStack {}
361
362fn stack_geometry(
363    heights: &[Pixels],
364    gap: Pixels,
365    peek: Pixels,
366    anchored_bottom: bool,
367) -> (Pixels, Pixels, Vec<(Pixels, Pixels)>) {
368    let count = heights.len();
369    let expanded_height = heights
370        .iter()
371        .copied()
372        .fold(px(0.), |sum, height| sum + height)
373        + gap * count.saturating_sub(1) as f32;
374    let front_height = heights.last().copied().unwrap_or(px(0.));
375    let collapsed_height = heights
376        .iter()
377        .enumerate()
378        .map(|(index, height)| {
379            let rank = count - 1 - index;
380            *height + peek * rank as f32
381        })
382        .fold(
383            front_height + peek * count.saturating_sub(1) as f32,
384            Pixels::max,
385        );
386    let offsets = heights
387        .iter()
388        .enumerate()
389        .map(|(index, height)| {
390            let rank = count - 1 - index;
391            let newer_height = heights[(index + 1)..]
392                .iter()
393                .copied()
394                .fold(px(0.), |sum, height| sum + height);
395            let expanded = if anchored_bottom {
396                expanded_height - newer_height - gap * rank as f32 - *height
397            } else {
398                newer_height + gap * rank as f32
399            };
400            let collapsed = if anchored_bottom {
401                collapsed_height - *height - peek * rank as f32
402            } else {
403                peek * rank as f32
404            };
405            (collapsed, expanded)
406        })
407        .collect();
408    (collapsed_height, expanded_height, offsets)
409}
410
411impl RenderOnce for ToastStack {
412    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
413        let focused = self
414            .focus_handle
415            .as_ref()
416            .is_some_and(|handle| handle.contains_focused(window, cx));
417        self.state.focused.set(focused);
418        let expanded = self.state.is_expanded();
419        let keys = self
420            .children
421            .iter()
422            .map(|(id, _)| id.clone())
423            .collect::<Vec<_>>();
424        self.state
425            .heights
426            .borrow_mut()
427            .retain(|id, _| keys.contains(id));
428        let measured_by_id = self.state.heights.borrow().clone();
429        let heights = keys
430            .iter()
431            .map(|id| measured_by_id.get(id).copied().unwrap_or(px(0.)))
432            .collect::<Vec<_>>();
433        let measured = self.state.heights.clone();
434        let peek = self.motion.collapsed_peek;
435        let gap = self.motion.expanded_gap;
436        let scale_step = self.motion.collapsed_scale_step;
437        let collapsed_visible = self.motion.collapsed_visible.max(1);
438        let stack_width = self.state.width.get();
439        let count = self.children.len();
440        let anchored_bottom = matches!(
441            self.placement,
442            Anchor::BottomLeft | Anchor::BottomCenter | Anchor::BottomRight
443        );
444        let (collapsed_height, expanded_height, offsets) = stack_geometry(
445            &heights[..count.min(heights.len())],
446            gap,
447            peek,
448            anchored_bottom,
449        );
450        // The whole stack reflows every time a toast arrives or leaves, so each
451        // layer is sprung: one retargeted mid-move carries its velocity into the
452        // new layout instead of restarting. Critically damped, because a height
453        // or an opacity that overshoots its target reads as a glitch. Geometry
454        // settles in pixels, so its tolerance is coarser than the fade's.
455        //
456        // A bottom-anchored item's position is composed from two of these — the
457        // stack height and the item's own offset — and the stack height only
458        // acquires its real target once the new toast has been measured in
459        // prepaint, a frame after the offsets know theirs. Two springs sharing a
460        // config stay proportional to each other only while they also share a
461        // start, so that one frame of skew lets the composed position pass its
462        // settled value by a fraction of a pixel before arriving. Both springs
463        // snap on settling, so it is a transient, not a resting error.
464        let geometry = Spring::new(self.motion.duration).with_epsilon(0.1);
465        let fade = Spring::new(self.motion.duration);
466        let stack_height = spring(
467            (self.id.clone(), "height"),
468            if expanded {
469                expanded_height
470            } else {
471                collapsed_height
472            },
473            geometry,
474            window,
475            cx,
476        );
477        let items = self
478            .children
479            .into_iter()
480            .enumerate()
481            .map(move |(index, (item_id, child))| {
482                let (collapsed_offset, expanded_offset) =
483                    offsets.get(index).copied().unwrap_or((px(0.), px(0.)));
484                let measured = measured.clone();
485                let measured_id = item_id.clone();
486                let rank = count.saturating_sub(1 + index);
487                let target_offset = if expanded {
488                    expanded_offset
489                } else {
490                    collapsed_offset
491                };
492                let offset = spring(
493                    (item_id.clone(), "offset"),
494                    target_offset,
495                    geometry,
496                    window,
497                    cx,
498                );
499                let target_inset = if expanded {
500                    px(0.)
501                } else {
502                    stack_width * (scale_step * rank.min(collapsed_visible - 1) as f32 / 2.)
503                };
504                let inset = spring(
505                    (item_id.clone(), "inset"),
506                    target_inset,
507                    geometry,
508                    window,
509                    cx,
510                );
511                let opacity = spring(
512                    (item_id.clone(), "visibility"),
513                    if expanded || rank < collapsed_visible {
514                        1.
515                    } else {
516                        0.
517                    },
518                    fade,
519                    window,
520                    cx,
521                );
522                crate::ElementExt::on_prepaint(
523                    div()
524                        .id(item_id.clone())
525                        .absolute()
526                        .top_0()
527                        .left_0()
528                        .right_0()
529                        .top(offset)
530                        .left(inset)
531                        .right(inset)
532                        .opacity(opacity)
533                        .when(!expanded && rank >= collapsed_visible, |this| {
534                            this.invisible()
535                        }),
536                    move |bounds, _, cx| {
537                        let mut heights = measured.borrow_mut();
538                        if heights.get(&measured_id).copied() != Some(bounds.size.height) {
539                            heights.insert(measured_id.clone(), bounds.size.height);
540                            cx.refresh_windows();
541                        }
542                    },
543                )
544                .child(child)
545            });
546
547        let hovered_state = self.state.hovered.clone();
548        let measured_width = self.state.width.clone();
549        self.base
550            .relative()
551            .h(stack_height)
552            .when_some(self.focus_handle, |this, handle| this.track_focus(&handle))
553            .child(
554                canvas(
555                    |_, _, _| {},
556                    move |mut bounds, _, window, cx| {
557                        if measured_width.replace(bounds.size.width) != bounds.size.width {
558                            cx.refresh_windows();
559                        }
560                        if !expanded {
561                            if anchored_bottom {
562                                bounds.origin.y += stack_height - collapsed_height;
563                            }
564                            bounds.size.height = collapsed_height;
565                        }
566                        let hovered_state = hovered_state.clone();
567                        window.on_mouse_event(move |event: &MouseMoveEvent, _, _, cx| {
568                            let hovered = bounds.contains(&event.position);
569                            if hovered_state.replace(hovered) != hovered {
570                                cx.refresh_windows();
571                            }
572                        });
573                    },
574                )
575                .absolute()
576                .size_full(),
577            )
578            .children(items)
579            .refine_style(&self.style)
580    }
581}
582
583/// The lifecycle phase exposed by a toast root to application-owned presentation.
584#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
585pub enum ToastTransitionStatus {
586    /// The toast has just been added and may run its enter transition.
587    #[default]
588    Starting,
589    /// The toast is fully present.
590    Present,
591    /// The toast is closing and remains mounted until its exit transition completes.
592    Ending,
593}
594
595/// An unstyled semantic toast root. Applications own all presentation and motion.
596#[derive(IntoElement)]
597pub struct Toast {
598    base: crate::ObservedElement<Stateful<Div>>,
599    style: StyleRefinement,
600    transition_status: ToastTransitionStatus,
601    children: Vec<AnyElement>,
602}
603
604impl Toast {
605    /// Create an unstyled semantic toast in the starting transition phase.
606    pub fn new(id: impl Into<ElementId>) -> Self {
607        Self {
608            base: div().id(id).test_support(),
609            style: StyleRefinement::default(),
610            transition_status: ToastTransitionStatus::Starting,
611            children: Vec::new(),
612        }
613    }
614
615    /// Set the lifecycle phase used by application-owned toast presentation.
616    pub fn transition_status(mut self, status: ToastTransitionStatus) -> Self {
617        self.transition_status = status;
618        self
619    }
620
621    /// Return the lifecycle phase used by application-owned toast presentation.
622    pub fn status(&self) -> ToastTransitionStatus {
623        self.transition_status
624    }
625}
626
627impl Styled for Toast {
628    fn style(&mut self) -> &mut StyleRefinement {
629        &mut self.style
630    }
631}
632
633impl ParentElement for Toast {
634    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
635        self.children.extend(children);
636    }
637}
638
639impl InteractiveElement for Toast {
640    fn interactivity(&mut self) -> &mut Interactivity {
641        self.base.interactivity()
642    }
643
644    fn track_focus(mut self, handle: &gpui::FocusHandle) -> Self {
645        self.base = self.base.track_focus(handle);
646        self
647    }
648}
649
650impl StatefulInteractiveElement for Toast {}
651
652impl RenderOnce for Toast {
653    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
654        self.base
655            .role(Role::Alert)
656            .children(self.children)
657            .refine_style(&self.style)
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664    use gpui::{Element as _, accesskit, point};
665
666    #[test]
667    fn manager_pauses_timeout_and_removes_only_after_exit() {
668        let motion = ToastMotion::sonner();
669        let start = Instant::now();
670        let mut manager = ToastManager::new(motion);
671        manager.push(
672            "a",
673            1,
674            ToastOptions {
675                timeout: Some(Duration::from_secs(5)),
676            },
677            start,
678        );
679        manager.advance(start + motion.duration, false);
680        manager.advance(start + motion.duration + Duration::from_secs(4), true);
681        assert_eq!(
682            manager.iter().next().unwrap().2,
683            ToastTransitionStatus::Present
684        );
685        let ending = manager.advance(start + motion.duration + Duration::from_secs(9), false);
686        assert_eq!(ending.ending, vec!["a"]);
687        assert!(ending.removed.is_empty());
688        let removed = manager.advance(
689            start + motion.duration + motion.exit_duration + Duration::from_secs(9),
690            false,
691        );
692        assert_eq!(removed.removed, vec![("a", 1)]);
693    }
694
695    #[test]
696    fn manager_limit_keeps_ending_toasts_mounted() {
697        let now = Instant::now();
698        let mut manager = ToastManager::new(ToastMotion::sonner());
699        for id in ["a", "b", "c"] {
700            manager.push(id, id, ToastOptions::default(), now);
701        }
702        manager.dismiss(&"a", now);
703        assert_eq!(
704            manager.visible(1).map(|(id, _, _)| *id).collect::<Vec<_>>(),
705            vec!["a", "c"]
706        );
707    }
708
709    #[test]
710    fn manager_replaces_duplicate_ids_as_the_newest_toast() {
711        let now = Instant::now();
712        let mut manager = ToastManager::new(ToastMotion::sonner());
713        manager.push("a", 1, ToastOptions::default(), now);
714        manager.push("b", 2, ToastOptions::default(), now);
715        assert_eq!(manager.push("a", 3, ToastOptions::default(), now), Some(1));
716        assert_eq!(
717            manager
718                .iter()
719                .map(|(id, value, _)| (*id, *value))
720                .collect::<Vec<_>>(),
721            vec![("b", 2), ("a", 3)]
722        );
723    }
724
725    #[test]
726    fn manager_resets_clock_when_reused_after_becoming_empty() {
727        let motion = ToastMotion::sonner();
728        let start = Instant::now();
729        let mut manager = ToastManager::new(motion);
730        manager.push("old", 1, ToastOptions::default(), start);
731        manager.dismiss(&"old", start);
732        manager.advance(start + motion.exit_duration, false);
733        let later = start + Duration::from_secs(60);
734        manager.push("new", 2, ToastOptions::default(), later);
735        manager.advance(later + Duration::from_millis(50), false);
736        assert_eq!(
737            manager.iter().next().unwrap().2,
738            ToastTransitionStatus::Starting
739        );
740    }
741
742    #[test]
743    fn newly_pushed_toast_does_not_inherit_existing_entry_clock() {
744        let motion = ToastMotion::sonner();
745        let start = Instant::now();
746        let mut manager = ToastManager::new(motion);
747        manager.push("old", 1, ToastOptions::default(), start);
748        let later = start + Duration::from_secs(60);
749        manager.push("new", 2, ToastOptions::default(), later);
750        manager.advance(later + Duration::from_millis(50), false);
751        assert_eq!(
752            manager
753                .iter()
754                .find(|(id, _, _)| **id == "new")
755                .map(|(_, _, status)| status),
756            Some(ToastTransitionStatus::Starting)
757        );
758    }
759
760    #[test]
761    fn stack_geometry_anchors_newest_item_and_supports_variable_heights() {
762        let heights = [px(40.), px(60.), px(80.)];
763        let (collapsed, expanded, top) = stack_geometry(&heights, px(12.), px(12.), false);
764        assert_eq!(collapsed, px(104.));
765        assert_eq!(expanded, px(204.));
766        assert_eq!(
767            top,
768            vec![(px(24.), px(164.)), (px(12.), px(92.)), (px(0.), px(0.))]
769        );
770
771        let (_, _, bottom) = stack_geometry(&heights, px(12.), px(12.), true);
772        assert_eq!(
773            bottom,
774            vec![(px(40.), px(0.)), (px(32.), px(52.)), (px(24.), px(124.))]
775        );
776
777        let tall_behind = [px(180.), px(60.)];
778        let (collapsed, _, top) = stack_geometry(&tall_behind, px(14.), px(14.), false);
779        assert_eq!(collapsed, px(194.));
780        assert_eq!(top[0].0, px(14.));
781        assert!(top[0].0 + tall_behind[0] <= collapsed);
782        assert_eq!(top[0].0 - top[1].0, px(14.));
783
784        let (_, _, bottom) = stack_geometry(&tall_behind, px(14.), px(14.), true);
785        assert!(bottom[0].0 >= px(0.));
786        assert!(bottom[0].0 + tall_behind[0] <= collapsed);
787        assert_eq!(
788            (bottom[1].0 + tall_behind[1]) - (bottom[0].0 + tall_behind[0]),
789            px(14.)
790        );
791    }
792
793    #[gpui::test]
794    fn toast_exposes_alert_semantics(cx: &mut gpui::TestAppContext) {
795        let window = cx.add_empty_window();
796        window.update(|window, cx| {
797            let mut node = accesskit::Node::new(Role::Alert);
798            Toast::new("toast")
799                .render(window, cx)
800                .into_element()
801                .write_a11y_info(&mut node);
802            assert_eq!(node.role(), Role::Alert);
803        });
804    }
805
806    #[gpui::test]
807    fn stack_bootstraps_measurement_without_zero_height_clipping(cx: &mut gpui::TestAppContext) {
808        struct Harness {
809            state: ToastStackState,
810        }
811        impl gpui::Render for Harness {
812            fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
813                ToastStack::new("stack", self.state.clone())
814                    .w(px(300.))
815                    .item("first", div().h(px(80.)).child("Visible"))
816            }
817        }
818
819        let (view, cx) = cx.add_window_view(|_, _| Harness {
820            state: ToastStackState::default(),
821        });
822        cx.update(|window, cx| window.draw(cx).clear(cx));
823        view.read_with(cx, |view, _| {
824            assert_eq!(
825                view.state
826                    .heights
827                    .borrow()
828                    .get(&ElementId::from("first"))
829                    .copied(),
830                Some(px(80.))
831            );
832        });
833    }
834
835    #[gpui::test]
836    fn stack_expands_for_hover_and_focus(cx: &mut gpui::TestAppContext) {
837        struct Harness {
838            state: ToastStackState,
839            focus: FocusHandle,
840        }
841        impl gpui::Render for Harness {
842            fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
843                ToastStack::new("stack", self.state.clone())
844                    .focus_handle(self.focus.clone())
845                    .w(px(300.))
846                    .item("first", div().h(px(80.)))
847            }
848        }
849
850        let (view, cx) = cx.add_window_view(|_, cx| Harness {
851            state: ToastStackState::default(),
852            focus: cx.focus_handle().tab_stop(true),
853        });
854        cx.update(|window, cx| window.draw(cx).clear(cx));
855
856        cx.simulate_mouse_move(point(px(10.), px(10.)), None, gpui::Modifiers::default());
857        cx.update(|window, cx| window.draw(cx).clear(cx));
858        view.read_with(cx, |view, _| assert!(view.state.is_expanded()));
859
860        cx.simulate_mouse_move(point(px(400.), px(400.)), None, gpui::Modifiers::default());
861        cx.update(|window, cx| window.draw(cx).clear(cx));
862        view.read_with(cx, |view, _| assert!(!view.state.is_expanded()));
863
864        cx.simulate_mouse_move(point(px(10.), px(10.)), None, gpui::Modifiers::default());
865        cx.update(|window, cx| window.draw(cx).clear(cx));
866        view.read_with(cx, |view, _| assert!(view.state.is_expanded()));
867
868        cx.simulate_mouse_move(point(px(400.), px(400.)), None, gpui::Modifiers::default());
869        cx.update(|window, cx| window.draw(cx).clear(cx));
870        view.read_with(cx, |view, _| assert!(!view.state.is_expanded()));
871
872        let focus = view.read_with(cx, |view, _| view.focus.clone());
873        cx.update(|window, cx| {
874            focus.focus(window, cx);
875            window.draw(cx).clear(cx);
876        });
877        view.read_with(cx, |view, _| assert!(view.state.is_expanded()));
878    }
879
880    #[gpui::test]
881    fn keyed_stack_reflow_moves_from_the_current_visual_position(cx: &mut gpui::TestAppContext) {
882        struct Harness {
883            state: ToastStackState,
884            show_second: bool,
885        }
886        impl gpui::Render for Harness {
887            fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
888                ToastStack::new("stack", self.state.clone())
889                    .w(px(300.))
890                    .item(
891                        "first",
892                        div().debug_selector(|| "first-toast".into()).h(px(40.)),
893                    )
894                    .when(self.show_second, |stack| {
895                        stack.item(
896                            "second",
897                            div().debug_selector(|| "second-toast".into()).h(px(80.)),
898                        )
899                    })
900            }
901        }
902
903        let (view, cx) = cx.add_window_view(|_, _| Harness {
904            state: ToastStackState::default(),
905            show_second: false,
906        });
907        cx.update(|window, cx| {
908            window.draw(cx).clear(cx);
909            window.draw(cx).clear(cx);
910        });
911        let initial_y = cx.debug_bounds("first-toast").unwrap().origin.y;
912
913        view.update(cx, |view, cx| {
914            view.show_second = true;
915            cx.notify();
916        });
917        cx.run_until_parked();
918        let first_reflow_y = cx.debug_bounds("first-toast").unwrap().origin.y;
919        assert_eq!(first_reflow_y, initial_y);
920
921        cx.executor().advance_clock(Duration::from_millis(200));
922        cx.update(|window, cx| window.draw(cx).clear(cx));
923        let middle_y = cx.debug_bounds("first-toast").unwrap().origin.y;
924        assert!(middle_y > initial_y);
925        assert!(middle_y < initial_y + px(14.));
926
927        cx.executor().advance_clock(Duration::from_millis(200));
928        cx.update(|window, cx| window.draw(cx).clear(cx));
929        assert_eq!(
930            cx.debug_bounds("first-toast").unwrap().origin.y,
931            initial_y + px(14.)
932        );
933        assert!(
934            cx.debug_bounds("first-toast").unwrap().size.width
935                < cx.debug_bounds("second-toast").unwrap().size.width
936        );
937    }
938
939    #[gpui::test]
940    fn bottom_stack_reflow_moves_up_without_an_opposite_direction_jump(
941        cx: &mut gpui::TestAppContext,
942    ) {
943        struct Harness {
944            state: ToastStackState,
945            show_second: bool,
946        }
947        impl gpui::Render for Harness {
948            fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
949                div().relative().size(px(300.)).child(
950                    ToastStack::new("bottom-stack", self.state.clone())
951                        .placement(Anchor::BottomRight)
952                        .absolute()
953                        .bottom_0()
954                        .w(px(300.))
955                        .item(
956                            "bottom-first",
957                            div()
958                                .debug_selector(|| "bottom-first-toast".into())
959                                .h(px(40.)),
960                        )
961                        .when(self.show_second, |stack| {
962                            stack.item("bottom-second", div().h(px(80.)))
963                        }),
964                )
965            }
966        }
967
968        let (view, cx) = cx.add_window_view(|_, _| Harness {
969            state: ToastStackState::default(),
970            show_second: false,
971        });
972        cx.update(|window, cx| {
973            window.draw(cx).clear(cx);
974            window.draw(cx).clear(cx);
975        });
976        // A bottom-anchored item's position is composed from two springs — the
977        // stack height and the item's own offset — and the stack height only
978        // acquires its real target once the toast has been measured in prepaint.
979        // Both the baseline and the final reading are taken settled, so neither
980        // carries the fraction of a pixel that separates them mid-flight.
981        cx.executor().advance_clock(Duration::from_secs(1));
982        cx.update(|window, cx| window.draw(cx).clear(cx));
983        let initial_y = cx.debug_bounds("bottom-first-toast").unwrap().origin.y;
984
985        view.update(cx, |view, cx| {
986            view.show_second = true;
987            cx.notify();
988        });
989        cx.run_until_parked();
990        assert_eq!(
991            cx.debug_bounds("bottom-first-toast").unwrap().origin.y,
992            initial_y
993        );
994
995        cx.executor().advance_clock(Duration::from_millis(200));
996        cx.update(|window, cx| window.draw(cx).clear(cx));
997        let middle_y = cx.debug_bounds("bottom-first-toast").unwrap().origin.y;
998        assert!(middle_y < initial_y);
999        assert!(
1000            middle_y >= initial_y - px(14.),
1001            "middle={middle_y:?}, initial={initial_y:?}"
1002        );
1003
1004        cx.executor().advance_clock(Duration::from_secs(1));
1005        cx.update(|window, cx| window.draw(cx).clear(cx));
1006        assert_eq!(
1007            cx.debug_bounds("bottom-first-toast").unwrap().origin.y,
1008            initial_y - px(14.)
1009        );
1010    }
1011}