Skip to main content

arc_ui/feedback/
toast_stack.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/toast-stack/toast-stack.tsx` & `.module.css`
3//!
4//! P1 Sample Component #4: `toast-stack`
5//!
6//! - Scoped `ToastStackStore` entity (`toast`, `update`, `dismiss`, `dismiss_all`, `run_action`,
7//!   `tick_timers`) supporting in-place morph updates (`version` bump, action auto-dismiss unless
8//!   updated, `warning`/`error` 1.6× duration, `loading` infinite duration).
9//! - Stacked geometry: newest toast at front, older visible toasts tucked behind (`PEEK = 14px`,
10//!   `STEP = 0.05` top-edge scale), fanning out cleanly on hover/focus (`GAP = 12px`) with
11//!   `motion.spring.morph` / `motion.spring.smooth`.
12//! - Presence exit animation (sink + scale 0.96 + fade over `duration.exit` or right-swipe throw
13//!   with deceleration projection `project_deceleration` and left-pull `rubber_band` resistance).
14//! - Rotating loading spinner arc (`800ms` linear loop, static under `reduce_motion`).
15//! - Accessibility: `Role::Region`, Escape dismissal, Alt+T hotkey focus, close button `aria_label`.
16
17use std::{collections::HashMap, rc::Rc, time::Duration};
18
19use arc_motion::{
20    BlurFallback, DragTracker, arc_spring_with_options, arc_transition, is_reduced_motion,
21    motion_now, project_deceleration, rubber_band, spring::SpringOptions,
22};
23use arc_tokens::{
24    ActiveArcLocale as _, ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography,
25};
26use gpui_kit::{
27    App, ElementId, Entity, FocusHandle, IntoElement, KeyDownEvent, MouseButton, MouseMoveEvent,
28    MouseUpEvent, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled,
29    TestSupportExt as _, Window, assets::IconName, canvas, div, point, prelude::*, px,
30};
31
32const PEEK: f32 = 14.0;
33const GAP: f32 = 12.0;
34const STEP: f32 = 0.05;
35const SWIPE_FADE: f32 = 280.0;
36/// Minimum toast card width in [`ToastStack`] so short copy stays comfortable.
37pub const TOAST_STACK_MIN_WIDTH: f32 = 200.0;
38/// Maximum toast card width in [`ToastStack`] before long copy wraps cleanly.
39pub const TOAST_STACK_MAX_WIDTH: f32 = 420.0;
40const DEFAULT_TOAST_HEIGHT: f32 = 64.0;
41const DESCRIPTION_EXTRA_HEIGHT: f32 = 22.0;
42const THROW_SPRING: SpringSpec = SpringSpec::visual(0.32, 0.0);
43
44fn estimate_copy_line_width(text: &str, char_px: f32) -> f32 {
45    text.lines()
46        .map(|line| {
47            line.chars()
48                .map(|c| {
49                    if c.is_ascii() {
50                        if c.is_ascii_uppercase() || c == 'W' || c == 'M' {
51                            char_px * 1.12
52                        } else {
53                            char_px
54                        }
55                    } else {
56                        char_px * 1.85
57                    }
58                })
59                .sum::<f32>()
60        })
61        .fold(0.0_f32, f32::max)
62}
63
64/// Estimates the adaptive pixel width for a single toast record inside [`ToastStack`]
65/// from its title, optional description, and optional action button label, clamped within
66/// `[TOAST_STACK_MIN_WIDTH, TOAST_STACK_MAX_WIDTH]`.
67pub fn toast_stack_item_width(
68    title: &str,
69    description: Option<&str>,
70    action_label: Option<&str>,
71) -> f32 {
72    // 16px left pad + 18px icon + 12px gap + 12px gap + 28px close + 12px right pad + 2px border + breathing buffer
73    const BASE_CHROME_W: f32 = 16.0 + 18.0 + 12.0 + 12.0 + 28.0 + 12.0 + 2.0 + 12.0;
74    let title_w = estimate_copy_line_width(title, 8.2);
75    let desc_w = description
76        .filter(|d| !d.is_empty())
77        .map(|d| estimate_copy_line_width(d, 7.6))
78        .unwrap_or(0.0);
79    let action_w = action_label
80        .filter(|l| !l.is_empty())
81        .map(|l| 12.0 + 24.0 + estimate_copy_line_width(l, 8.0))
82        .unwrap_or(0.0);
83    (BASE_CHROME_W + title_w.max(desc_w) + action_w)
84        .clamp(TOAST_STACK_MIN_WIDTH, TOAST_STACK_MAX_WIDTH)
85}
86
87/// Visual & semantic toast variant matching Arc's `ToastType`.
88#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
89pub enum ToastType {
90    Success,
91    #[default]
92    Info,
93    Warning,
94    Error,
95    Loading,
96}
97
98impl ToastType {
99    pub const fn sr_label(self) -> &'static str {
100        match self {
101            Self::Success => "Success",
102            Self::Info => "Info",
103            Self::Warning => "Warning",
104            Self::Error => "Error",
105            Self::Loading => "In progress",
106        }
107    }
108}
109
110/// Viewport corner/edge placement for [`ToastStack`].
111#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
112pub enum ToastPosition {
113    #[default]
114    BottomRight,
115    BottomCenter,
116    BottomLeft,
117}
118
119type ActionCallback = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
120
121/// Optional action button inside a toast card.
122#[derive(Clone)]
123pub struct ToastAction {
124    pub label: SharedString,
125    pub on_click: ActionCallback,
126}
127
128impl ToastAction {
129    pub fn new(
130        label: impl Into<SharedString>,
131        on_click: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
132    ) -> Self {
133        Self {
134            label: label.into(),
135            on_click: Rc::new(on_click),
136        }
137    }
138}
139
140/// Builder options for enqueueing a toast via [`ToastStackStore::toast`].
141#[derive(Clone)]
142pub struct ToastOptions {
143    pub id: Option<SharedString>,
144    pub kind: ToastType,
145    pub title: SharedString,
146    pub description: Option<SharedString>,
147    pub action: Option<ToastAction>,
148    /// `Some(None)` = infinite (sticky), `Some(Some(d))` = explicit duration, `None` = default by type.
149    pub duration: Option<Option<Duration>>,
150}
151
152impl ToastOptions {
153    pub fn new(title: impl Into<SharedString>) -> Self {
154        Self {
155            id: None,
156            kind: ToastType::Info,
157            title: title.into(),
158            description: None,
159            action: None,
160            duration: None,
161        }
162    }
163
164    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
165        self.id = Some(id.into());
166        self
167    }
168
169    pub fn kind(mut self, kind: ToastType) -> Self {
170        self.kind = kind;
171        self
172    }
173
174    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
175        self.description = Some(description.into());
176        self
177    }
178
179    pub fn action(mut self, action: ToastAction) -> Self {
180        self.action = Some(action);
181        self
182    }
183
184    pub fn duration(mut self, duration: Option<Duration>) -> Self {
185        self.duration = Some(duration);
186        self
187    }
188}
189
190/// Patch for in-place morph updates via [`ToastStackStore::update`].
191#[derive(Clone, Default)]
192pub struct ToastPatch {
193    pub kind: Option<ToastType>,
194    pub title: Option<SharedString>,
195    pub description: Option<Option<SharedString>>,
196    pub action: Option<Option<ToastAction>>,
197    pub duration: Option<Option<Duration>>,
198}
199
200/// Stored toast record.
201#[derive(Clone)]
202pub struct ToastRecord {
203    pub id: SharedString,
204    pub kind: ToastType,
205    pub title: SharedString,
206    pub description: Option<SharedString>,
207    pub action: Option<ToastAction>,
208    pub duration: Option<Duration>,
209    pub remaining_secs: Option<f64>,
210    pub seq: u64,
211    pub version: u64,
212    pub entered_at_secs: f64,
213    pub updated_at_secs: f64,
214}
215
216impl ToastRecord {
217    pub fn estimated_width(&self) -> f32 {
218        toast_stack_item_width(
219            self.title.as_ref(),
220            self.description.as_deref(),
221            self.action.as_ref().map(|a| a.label.as_ref()),
222        )
223    }
224
225    pub fn estimated_height(&self) -> f32 {
226        self.estimated_height_for_width(self.estimated_width())
227    }
228
229    pub fn estimated_height_for_width(&self, card_width: f32) -> f32 {
230        let action_w = self
231            .action
232            .as_ref()
233            .map(|a| 12.0 + 24.0 + estimate_copy_line_width(a.label.as_ref(), 8.0))
234            .unwrap_or(0.0);
235        let copy_w = (card_width - 102.0 - action_w).max(88.0);
236        let title_lines =
237            ((estimate_copy_line_width(self.title.as_ref(), 8.2) / copy_w).ceil() as usize).max(1);
238        let title_extra = title_lines.saturating_sub(1) as f32 * 20.0;
239        let desc_extra = self
240            .description
241            .as_deref()
242            .filter(|d| !d.is_empty())
243            .map(|desc| {
244                let desc_w = estimate_copy_line_width(desc, 7.6);
245                let lines = ((desc_w / copy_w).ceil() as usize).max(1);
246                DESCRIPTION_EXTRA_HEIGHT + lines.saturating_sub(1) as f32 * 18.0
247            })
248            .unwrap_or(0.0);
249        DEFAULT_TOAST_HEIGHT + title_extra + desc_extra
250    }
251}
252
253/// Exiting toast retained until its exit animation finishes.
254#[derive(Clone)]
255struct ExitingToast {
256    record: ToastRecord,
257    last_target: StackTarget,
258    exited_at_secs: f64,
259    swiped: bool,
260    throw_velocity: f32,
261}
262
263/// Computed geometric target for one toast in the stack (`layoutStack` in `toast-stack.tsx`).
264#[derive(Clone, Copy, Debug, PartialEq)]
265pub struct StackTarget {
266    pub y: f32,
267    pub scale: f32,
268    pub height: f32,
269    pub opacity: f32,
270    pub content_opacity: f32,
271}
272
273/// Computes exact stacked / expanded target positions, scales, heights, and container height
274/// matching `layoutStack` in `toast-stack.tsx` lines 111-123.
275pub fn layout_stack(
276    toasts: &[ToastRecord],
277    heights: &HashMap<SharedString, f32>,
278    expanded: bool,
279    visible_toasts: usize,
280) -> (Vec<StackTarget>, f32) {
281    let height_of = |t: &ToastRecord| -> f32 {
282        heights
283            .get(&t.id)
284            .copied()
285            .unwrap_or_else(|| t.estimated_height())
286    };
287    let front = toasts.first().map_or(0.0, height_of);
288
289    let mut tops = Vec::with_capacity(toasts.len() + 1);
290    tops.push(0.0_f32);
291    for (idx, item) in toasts.iter().enumerate() {
292        let prev = tops[idx];
293        let add = if idx < visible_toasts {
294            height_of(item) + GAP
295        } else {
296            0.0
297        };
298        tops.push(prev + add);
299    }
300
301    let targets: Vec<StackTarget> = toasts
302        .iter()
303        .enumerate()
304        .map(|(index, item)| {
305            let visible = index < visible_toasts;
306            let depth = index.min(visible_toasts) as f32;
307            if expanded {
308                StackTarget {
309                    y: -tops[index],
310                    scale: 1.0,
311                    height: height_of(item),
312                    opacity: if visible { 1.0 } else { 0.0 },
313                    content_opacity: 1.0,
314                }
315            } else {
316                StackTarget {
317                    y: -PEEK * depth,
318                    scale: 1.0 - STEP * depth,
319                    height: if index == 0 { height_of(item) } else { front },
320                    opacity: if visible { 1.0 } else { 0.0 },
321                    content_opacity: if index == 0 { 1.0 } else { 0.0 },
322                }
323            }
324        })
325        .collect();
326
327    let list_height = if toasts.is_empty() {
328        0.0
329    } else if expanded {
330        (tops[toasts.len()] - GAP).max(0.0)
331    } else {
332        front + PEEK * (toasts.len().min(visible_toasts).saturating_sub(1) as f32)
333    };
334
335    (targets, list_height)
336}
337
338fn default_duration_for(kind: ToastType, base: Duration) -> Option<Duration> {
339    match kind {
340        ToastType::Loading => None,
341        ToastType::Warning | ToastType::Error => Some(base.mul_f64(1.6)),
342        ToastType::Success | ToastType::Info => Some(base),
343    }
344}
345
346/// Scoped toast queue store (GPUI `Entity`, equivalent to `<ToastStackProvider>` + `useToastStack()`).
347pub struct ToastStackStore {
348    base_duration: Duration,
349    limit: usize,
350    seq: u64,
351    toasts: Vec<ToastRecord>,
352    exiting: Vec<ExitingToast>,
353    heights: HashMap<SharedString, f32>,
354    last_tick_secs: Option<f64>,
355}
356
357impl Default for ToastStackStore {
358    fn default() -> Self {
359        Self::new(Duration::from_millis(5000), 12)
360    }
361}
362
363impl ToastStackStore {
364    pub fn new(base_duration: Duration, limit: usize) -> Self {
365        Self {
366            base_duration,
367            limit: limit.max(1),
368            seq: 0,
369            toasts: Vec::new(),
370            exiting: Vec::new(),
371            heights: HashMap::new(),
372            last_tick_secs: None,
373        }
374    }
375
376    pub fn count(&self) -> usize {
377        self.toasts.len()
378    }
379
380    pub fn toasts(&self) -> &[ToastRecord] {
381        &self.toasts
382    }
383
384    /// Shows a toast (or updates in place if `id` already exists) and returns its id.
385    pub fn toast(&mut self, options: ToastOptions, now_secs: f64) -> SharedString {
386        if let Some(id) = &options.id
387            && self.toasts.iter().any(|t| &t.id == id)
388        {
389            let id_clone = id.clone();
390            self.update(
391                &id_clone,
392                ToastPatch {
393                    kind: Some(options.kind),
394                    title: Some(options.title),
395                    description: Some(options.description),
396                    action: Some(options.action),
397                    duration: options.duration,
398                },
399                now_secs,
400            );
401            return id_clone;
402        }
403
404        self.seq += 1;
405        let id = options
406            .id
407            .unwrap_or_else(|| SharedString::from(format!("toast-{}", self.seq)));
408        let duration = options
409            .duration
410            .unwrap_or_else(|| default_duration_for(options.kind, self.base_duration));
411        let record = ToastRecord {
412            id: id.clone(),
413            kind: options.kind,
414            title: options.title,
415            description: options.description,
416            action: options.action,
417            duration,
418            remaining_secs: duration.map(|d| d.as_secs_f64()),
419            seq: self.seq,
420            version: 0,
421            entered_at_secs: now_secs,
422            updated_at_secs: now_secs,
423        };
424        self.toasts.insert(0, record);
425        self.toasts.truncate(self.limit);
426        id
427    }
428
429    /// Morphs an existing toast in place, bumping `version` and restarting its timer.
430    pub fn update(&mut self, id: &str, patch: ToastPatch, now_secs: f64) {
431        let Some(record) = self.toasts.iter_mut().find(|t| t.id.as_ref() == id) else {
432            return;
433        };
434        if let Some(kind) = patch.kind {
435            record.kind = kind;
436        }
437        if let Some(title) = patch.title {
438            record.title = title;
439        }
440        if let Some(description) = patch.description {
441            record.description = description;
442        }
443        if let Some(action) = patch.action {
444            record.action = action;
445        }
446        record.duration = patch
447            .duration
448            .unwrap_or_else(|| default_duration_for(record.kind, self.base_duration));
449        record.remaining_secs = record.duration.map(|d| d.as_secs_f64());
450        record.version += 1;
451        record.updated_at_secs = now_secs;
452    }
453
454    /// Dismisses a toast by id, moving it into the exiting queue for presence exit animation.
455    pub fn dismiss(&mut self, id: &str, now_secs: f64) {
456        self.dismiss_with_swipe(id, now_secs, false, 0.0, false, 3);
457    }
458
459    fn dismiss_with_swipe(
460        &mut self,
461        id: &str,
462        now_secs: f64,
463        swiped: bool,
464        throw_velocity: f32,
465        expanded: bool,
466        visible_toasts: usize,
467    ) {
468        let (targets, _) = layout_stack(&self.toasts, &self.heights, expanded, visible_toasts);
469        let Some(pos) = self.toasts.iter().position(|t| t.id.as_ref() == id) else {
470            return;
471        };
472        let record = self.toasts.remove(pos);
473        let target = targets[pos];
474        self.exiting.push(ExitingToast {
475            record,
476            last_target: target,
477            exited_at_secs: now_secs,
478            swiped,
479            throw_velocity,
480        });
481    }
482
483    pub fn dismiss_all(&mut self, now_secs: f64) {
484        let ids: Vec<SharedString> = self.toasts.iter().map(|t| t.id.clone()).collect();
485        for id in ids {
486            self.dismiss(id.as_ref(), now_secs);
487        }
488    }
489
490    /// Invokes a toast's action safely WITHOUT holding a mutable lease on `store`,
491    /// preventing re-entrant `Entity::update` panics when an action handler updates
492    /// or morphs the toast in place (e.g. Undo -> Restored). Auto-dismisses the toast
493    /// afterward only if the handler did not update its version.
494    pub fn invoke_action(
495        store: &Entity<Self>,
496        id: &SharedString,
497        window: &mut Window,
498        cx: &mut App,
499    ) {
500        let found = {
501            let s = store.read(cx);
502            s.toasts
503                .iter()
504                .find(|t| &t.id == id)
505                .and_then(|t| t.action.clone().map(|a| (t.version, a)))
506        };
507        let Some((version_before, action)) = found else {
508            return;
509        };
510        (action.on_click)(id, window, cx);
511        let still_same_version = store
512            .read(cx)
513            .toasts
514            .iter()
515            .find(|t| &t.id == id)
516            .is_some_and(|t| t.version == version_before);
517        if still_same_version {
518            let now = motion_now(cx);
519            store.update(cx, |s, _| s.dismiss(id.as_ref(), now));
520        }
521    }
522
523    /// Advances auto-dismiss countdown timers (paused while hovered/focused/dragging) and prunes
524    /// completed exiting toasts. Returns `true` if any timer or exit animation is still active.
525    pub fn tick(&mut self, now_secs: f64, paused: bool, exit_duration_secs: f64) -> bool {
526        let dt = self
527            .last_tick_secs
528            .map_or(0.0, |prev| (now_secs - prev).max(0.0));
529        self.last_tick_secs = Some(now_secs);
530
531        if !paused && dt > 0.0 {
532            let mut expired = Vec::new();
533            for toast in &mut self.toasts {
534                if let Some(rem) = &mut toast.remaining_secs {
535                    *rem -= dt;
536                    if *rem <= 0.0 {
537                        expired.push(toast.id.clone());
538                    }
539                }
540            }
541            for id in expired {
542                self.dismiss(id.as_ref(), now_secs);
543            }
544        }
545
546        self.exiting.retain(|ex| {
547            let max_exit = if ex.swiped { 0.24 } else { exit_duration_secs };
548            (now_secs - ex.exited_at_secs) < max_exit
549        });
550
551        let has_timed = !paused && self.toasts.iter().any(|t| t.remaining_secs.is_some());
552        let has_loading = self.toasts.iter().any(|t| t.kind == ToastType::Loading);
553        has_timed || !self.exiting.is_empty() || has_loading
554    }
555}
556
557#[derive(Clone)]
558struct ToastViewState {
559    hovered: bool,
560    focused: bool,
561    dragging_id: Option<SharedString>,
562    drag_x: HashMap<SharedString, f32>,
563    drag_tracker: DragTracker,
564    focus_handle: FocusHandle,
565}
566
567impl ToastViewState {
568    fn new(focus_handle: FocusHandle) -> Self {
569        Self {
570            hovered: false,
571            focused: false,
572            dragging_id: None,
573            drag_x: HashMap::new(),
574            drag_tracker: DragTracker::new(6.0),
575            focus_handle,
576        }
577    }
578}
579
580/// Arc `ToastStack` viewport rendering stacked, expandable, swipe-to-dismiss toasts.
581#[derive(IntoElement)]
582pub struct ToastStack {
583    id: ElementId,
584    store: Entity<ToastStackStore>,
585    label: SharedString,
586    position: ToastPosition,
587    contained: bool,
588    visible_toasts: usize,
589    hotkey: bool,
590}
591
592impl ToastStack {
593    pub fn new(id: impl Into<ElementId>, store: Entity<ToastStackStore>) -> Self {
594        Self {
595            id: id.into(),
596            store,
597            label: "Notifications".into(),
598            position: ToastPosition::BottomRight,
599            contained: false,
600            visible_toasts: 3,
601            hotkey: true,
602        }
603    }
604
605    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
606        self.label = label.into();
607        self
608    }
609
610    pub fn position(mut self, position: ToastPosition) -> Self {
611        self.position = position;
612        self
613    }
614
615    pub fn contained(mut self, contained: bool) -> Self {
616        self.contained = contained;
617        self
618    }
619
620    pub fn visible_toasts(mut self, visible_toasts: usize) -> Self {
621        self.visible_toasts = visible_toasts.max(1);
622        self
623    }
624
625    pub fn hotkey(mut self, hotkey: bool) -> Self {
626        self.hotkey = hotkey;
627        self
628    }
629}
630
631impl RenderOnce for ToastStack {
632    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
633        let theme = cx.arc_theme().clone();
634        let colors = theme.colors;
635        let motion = theme.motion;
636        let reduced = is_reduced_motion(cx);
637        let now = motion_now(cx);
638
639        let view_state_id =
640            ElementId::NamedChild(self.id.clone().into(), "__arc-toast-stack-view".into());
641        let view_state = window.use_keyed_state(view_state_id, cx, |_, cx| {
642            ToastViewState::new(cx.focus_handle())
643        });
644
645        let view_snap = view_state.read(cx).clone();
646        let count = self.store.read(cx).count();
647        let expanded = count > 0 && (view_snap.hovered || view_snap.focused);
648        let paused = expanded || view_snap.dragging_id.is_some();
649
650        let exit_secs = motion.duration.exit.as_secs_f64();
651        let keep_ticking = self.store.update(cx, |s, _| s.tick(now, paused, exit_secs));
652        if keep_ticking {
653            window.request_animation_frame();
654        }
655
656        let (toasts, exiting, heights) = {
657            let s = self.store.read(cx);
658            (s.toasts.clone(), s.exiting.clone(), s.heights.clone())
659        };
660
661        if toasts.is_empty() && exiting.is_empty() {
662            return div().id(self.id);
663        }
664
665        let target_stack_width = toasts
666            .iter()
667            .take(self.visible_toasts)
668            .map(ToastRecord::estimated_width)
669            .chain(exiting.iter().map(|ex| ex.record.estimated_width()))
670            .fold(TOAST_STACK_MIN_WIDTH, f32::max);
671        let animated_stack_width = if reduced {
672            target_stack_width
673        } else {
674            arc_spring_with_options(
675                (self.id.clone(), "list-width"),
676                target_stack_width,
677                SpringOptions::new(motion.spring.smooth).with_initial_value(target_stack_width),
678                window,
679                cx,
680            )
681            .value
682        };
683        let (targets, list_height) = layout_stack(&toasts, &heights, expanded, self.visible_toasts);
684        let animated_list_height = arc_spring_with_options(
685            (self.id.clone(), "list-height"),
686            list_height,
687            SpringOptions::new(motion.spring.smooth),
688            window,
689            cx,
690        )
691        .value;
692
693        let default_label = if self.label == "Notifications" {
694            SharedString::from(cx.arc_locale().ui_strings().notifications)
695        } else {
696            self.label.clone()
697        };
698        let region_label: SharedString = if self.hotkey {
699            SharedString::from(format!("{default_label} (Alt+T)"))
700        } else {
701            default_label
702        };
703
704        let view_hover = view_state.clone();
705        let view_key = view_state.clone();
706        let store_key = self.store.clone();
707        let hotkey_enabled = self.hotkey;
708        let focus_handle = view_snap.focus_handle.clone();
709
710        // Window-level pointer capture during horizontal swipe-to-dismiss drag.
711        let dragging_id = view_snap.dragging_id.clone();
712        let view_move = view_state.clone();
713        let view_up = view_state.clone();
714        let store_up = self.store.clone();
715        let visible_toasts = self.visible_toasts;
716        let drag_toast_width = animated_stack_width.max(TOAST_STACK_MIN_WIDTH);
717
718        let drag_capture_canvas = canvas(
719            |_, _, _| {},
720            move |_, _, window, _| {
721                if let Some(active_drag_id) = dragging_id.clone() {
722                    let vm = view_move.clone();
723                    let drag_id_m = active_drag_id.clone();
724                    window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
725                        if !phase.bubble() {
726                            return;
727                        }
728                        let now_m = motion_now(cx);
729                        vm.update(cx, |v, _| {
730                            if v.dragging_id.as_ref() != Some(&drag_id_m) {
731                                return;
732                            }
733                            if let Some(raw) = v.drag_tracker.update_x(
734                                f32::from(event.position.x),
735                                f32::from(event.position.y),
736                                now_m,
737                                true,
738                            ) {
739                                let clamped = if raw >= 0.0 {
740                                    raw
741                                } else {
742                                    -rubber_band(-raw, drag_toast_width)
743                                };
744                                v.drag_x.insert(drag_id_m.clone(), clamped);
745                            }
746                        });
747                        window.refresh();
748                    });
749
750                    let vu = view_up.clone();
751                    let su = store_up.clone();
752                    let drag_id_u = active_drag_id;
753                    window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
754                        if !phase.bubble() || event.button != MouseButton::Left {
755                            return;
756                        }
757                        let now_u = motion_now(cx);
758                        let (offset, velocity) = vu.update(cx, |v, _| {
759                            if v.dragging_id.as_ref() != Some(&drag_id_u) {
760                                return (0.0, 0.0);
761                            }
762                            v.dragging_id = None;
763                            let off = v.drag_x.remove(&drag_id_u).unwrap_or(0.0);
764                            let vel = v.drag_tracker.release_velocity(now_u);
765                            (off, vel)
766                        });
767                        if offset > 0.0
768                            && velocity > -200.0
769                            && offset + project_deceleration(velocity) > drag_toast_width * 0.4
770                        {
771                            su.update(cx, |s, _| {
772                                s.dismiss_with_swipe(
773                                    drag_id_u.as_ref(),
774                                    now_u,
775                                    true,
776                                    velocity.max(0.0),
777                                    expanded,
778                                    visible_toasts,
779                                );
780                            });
781                        }
782                        window.refresh();
783                    });
784                }
785            },
786        )
787        .absolute()
788        .inset_0();
789
790        let mut list = div()
791            .id(ElementId::NamedChild(self.id.clone().into(), "list".into()))
792            .test_support()
793            .track_focus(&focus_handle)
794            .role(Role::Region)
795            .aria_label(region_label)
796            .relative()
797            .w(px(animated_stack_width))
798            .h(px(animated_list_height.max(1.0)))
799            .on_hover(move |hovered, window, cx| {
800                view_hover.update(cx, |v, _| v.hovered = *hovered);
801                window.refresh();
802            })
803            .on_key_down(move |event: &KeyDownEvent, window, cx| {
804                if event.keystroke.key == "escape" {
805                    let now_k = motion_now(cx);
806                    store_key.update(cx, |s, _| {
807                        if let Some(front) = s.toasts.first().map(|t| t.id.clone()) {
808                            s.dismiss(front.as_ref(), now_k);
809                        }
810                    });
811                    window.refresh();
812                } else if hotkey_enabled
813                    && event.keystroke.modifiers.alt
814                    && !event.keystroke.modifiers.control
815                    && !event.keystroke.modifiers.platform
816                    && event.keystroke.key.eq_ignore_ascii_case("t")
817                {
818                    view_key.update(cx, |v, _| v.focused = true);
819                    window.refresh();
820                }
821            })
822            .child(drag_capture_canvas);
823
824        // Render active toasts back-to-front so front toast (index 0) paints on top.
825        for (index, toast) in toasts.iter().enumerate().rev() {
826            let target = targets[index];
827            let front = index == 0;
828            let hidden = index >= self.visible_toasts;
829            let spring_spec = if expanded {
830                motion.spring.morph
831            } else {
832                motion.spring.smooth
833            };
834
835            // Seed newly mounted toasts below the bottom edge (`target.y + target.height`)
836            // so they smoothly rise into the stack, matching `toast-stack.tsx` line 253.
837            let y = arc_spring_with_options(
838                (
839                    self.id.clone(),
840                    SharedString::from(format!("y-{}", toast.id)),
841                ),
842                target.y,
843                SpringOptions::new(spring_spec).with_initial_value(target.y + target.height),
844                window,
845                cx,
846            )
847            .value;
848            let scale = arc_spring_with_options(
849                (
850                    self.id.clone(),
851                    SharedString::from(format!("s-{}", toast.id)),
852                ),
853                target.scale,
854                SpringOptions::new(spring_spec),
855                window,
856                cx,
857            )
858            .value;
859            let height = arc_spring_with_options(
860                (
861                    self.id.clone(),
862                    SharedString::from(format!("h-{}", toast.id)),
863                ),
864                target.height,
865                SpringOptions::new(spring_spec),
866                window,
867                cx,
868            )
869            .value;
870
871            let is_dragging_this = view_snap.dragging_id.as_ref() == Some(&toast.id);
872            let drag_x_target = view_snap.drag_x.get(&toast.id).copied().unwrap_or(0.0);
873            let x = arc_spring_with_options(
874                (
875                    self.id.clone(),
876                    SharedString::from(format!("x-{}", toast.id)),
877                ),
878                drag_x_target,
879                SpringOptions::new(motion.spring.snappy).with_travel(!is_dragging_this),
880                window,
881                cx,
882            )
883            .value;
884            let swipe_fade = if x > 0.0 {
885                1.0 - (x / SWIPE_FADE).min(1.0) * 0.75
886            } else {
887                1.0
888            };
889
890            let enter_t = ((now - toast.entered_at_secs) / motion.duration.standard.as_secs_f64())
891                .clamp(0.0, 1.0) as f32;
892            let enter_op = if reduced {
893                1.0
894            } else {
895                arc_motion::CubicBezier::from_spec(motion.ease.enter).sample(enter_t)
896            };
897            if enter_t < 1.0 && !reduced {
898                window.request_animation_frame();
899            }
900
901            let base_op = arc_transition(
902                (
903                    self.id.clone(),
904                    SharedString::from(format!("op-{}", toast.id)),
905                ),
906                target.opacity,
907                motion.duration.fast,
908                motion.ease.standard,
909                window,
910                cx,
911            );
912            let content_op = arc_transition(
913                (
914                    self.id.clone(),
915                    SharedString::from(format!("cop-{}", toast.id)),
916                ),
917                target.content_opacity,
918                motion.duration.fast,
919                motion.ease.standard,
920                window,
921                cx,
922            );
923            let card_opacity = (base_op * enter_op * swipe_fade).clamp(0.0, 1.0);
924
925            // Brief text/icon morph blur fallback when updated in place.
926            let swap_t = ((now - toast.updated_at_secs) / motion.duration.standard.as_secs_f64())
927                .clamp(0.0, 1.0) as f32;
928            let swap_blur = if toast.version > 0 && swap_t < 1.0 {
929                window.request_animation_frame();
930                BlurFallback::evaluate(px((1.0 - swap_t) * f32::from(motion.blur.soft)), reduced)
931            } else {
932                BlurFallback::evaluate(px(0.0), reduced)
933            };
934
935            let card_bg = if !front && !expanded {
936                colors.surface_muted
937            } else {
938                colors.surface_raised
939            };
940            let card_shadow = if front || expanded {
941                Shadows::floating(theme.mode)
942            } else {
943                Shadows::raised(theme.mode)
944            };
945
946            // Top-center scaling geometry (`transform-origin: 50% 0`).
947            let scaled_w = animated_stack_width * scale;
948            let inset_x = (animated_stack_width - scaled_w) * 0.5;
949            let bottom_offset = -y;
950
951            let tid = toast.id.clone();
952            let store_dismiss = self.store.clone();
953            let tid_dismiss = tid.clone();
954            let store_action = self.store.clone();
955            let tid_action = tid.clone();
956            let view_down = view_state.clone();
957            let tid_down = tid.clone();
958
959            let icon_color = match toast.kind {
960                ToastType::Success => colors.success,
961                ToastType::Info => colors.info,
962                ToastType::Warning => colors.warning,
963                ToastType::Error => colors.danger,
964                ToastType::Loading => colors.text_muted,
965            };
966
967            let icon_el = match toast.kind {
968                ToastType::Success => div()
969                    .text_color(icon_color)
970                    .child(IconName::CircleCheck)
971                    .into_any_element(),
972                ToastType::Info => div()
973                    .text_color(icon_color)
974                    .child(IconName::Info)
975                    .into_any_element(),
976                ToastType::Warning => div()
977                    .text_color(icon_color)
978                    .child(IconName::TriangleAlert)
979                    .into_any_element(),
980                ToastType::Error => div()
981                    .text_color(icon_color)
982                    .child(IconName::CircleX)
983                    .into_any_element(),
984                ToastType::Loading => {
985                    let spin_angle = if reduced {
986                        0.0
987                    } else {
988                        ((now / 0.8) % 1.0) as f32 * std::f32::consts::TAU
989                    };
990                    let spinner_color = icon_color;
991                    canvas(
992                        |_, _, _| {},
993                        move |rect, _, window, _| {
994                            let cx_p = f32::from(rect.origin.x) + f32::from(rect.size.width) * 0.5;
995                            let cy_p = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
996                            let r = 6.5_f32;
997                            let mut builder = PathBuilder::stroke(px(1.75));
998                            let segs = 18usize;
999                            let sweep = std::f32::consts::TAU * 0.75;
1000                            for i in 0..=segs {
1001                                let a = spin_angle + sweep * (i as f32 / segs as f32);
1002                                let pt = point(px(cx_p + r * a.cos()), px(cy_p + r * a.sin()));
1003                                if i == 0 {
1004                                    builder.move_to(pt);
1005                                } else {
1006                                    builder.line_to(pt);
1007                                }
1008                            }
1009                            if let Ok(path) = builder.build() {
1010                                window.paint_path(path, spinner_color);
1011                            }
1012                        },
1013                    )
1014                    .w(px(18.0))
1015                    .h(px(18.0))
1016                    .into_any_element()
1017                }
1018            };
1019
1020            let card_id = ElementId::NamedChild(
1021                self.id.clone().into(),
1022                SharedString::from(format!("card-{}", toast.id)),
1023            );
1024            let close_id = ElementId::NamedChild(
1025                self.id.clone().into(),
1026                SharedString::from(format!("close-{}", toast.id)),
1027            );
1028            let action_id = ElementId::NamedChild(
1029                self.id.clone().into(),
1030                SharedString::from(format!("action-{}", toast.id)),
1031            );
1032
1033            let card = div()
1034                .id(card_id)
1035                .test_support()
1036                .absolute()
1037                .left(px(inset_x + x))
1038                .bottom(px(bottom_offset))
1039                .w(px(scaled_w))
1040                .h(px(height.max(44.0)))
1041                .overflow_hidden()
1042                .rounded(Radii::PANEL)
1043                .border_1()
1044                .border_color(colors.border)
1045                .bg(card_bg)
1046                .shadow(card_shadow)
1047                .opacity(card_opacity)
1048                .when(is_dragging_this, |this| {
1049                    this.cursor(gpui_kit::CursorStyle::ClosedHand)
1050                })
1051                .on_mouse_down(MouseButton::Left, move |event, window, cx| {
1052                    if hidden {
1053                        return;
1054                    }
1055                    let now_d = motion_now(cx);
1056                    view_down.update(cx, |v, _| {
1057                        v.dragging_id = Some(tid_down.clone());
1058                        let origin = v.drag_x.get(&tid_down).copied().unwrap_or(0.0);
1059                        v.drag_tracker.begin(
1060                            f32::from(event.position.x),
1061                            f32::from(event.position.y),
1062                            origin,
1063                            now_d,
1064                        );
1065                    });
1066                    window.refresh();
1067                })
1068                .child(
1069                    div()
1070                        .w_full()
1071                        .flex()
1072                        .flex_row()
1073                        .items_start()
1074                        .gap(Spacing::S3)
1075                        .pt(Spacing::S3)
1076                        .pb(Spacing::S3)
1077                        .pl(Spacing::S4)
1078                        .pr(Spacing::S3)
1079                        .opacity((content_op * swap_blur.opacity_multiplier).clamp(0.0, 1.0))
1080                        .mt(swap_blur.offset_y)
1081                        .child(
1082                            div()
1083                                .flex_none()
1084                                .w(px(18.0))
1085                                .h(px(20.0))
1086                                .flex()
1087                                .items_center()
1088                                .justify_center()
1089                                .child(icon_el),
1090                        )
1091                        .child(
1092                            div()
1093                                .flex_1()
1094                                .min_w_0()
1095                                .flex()
1096                                .flex_col()
1097                                .text_size(Typography::TEXT_SM)
1098                                .text_color(colors.foreground)
1099                                .child(toast.title.clone())
1100                                .when_some(toast.description.clone(), |this, desc| {
1101                                    this.child(
1102                                        div()
1103                                            .mt(px(2.0))
1104                                            .text_color(colors.text_secondary)
1105                                            .child(desc),
1106                                    )
1107                                }),
1108                        )
1109                        .when_some(toast.action.clone(), |this, action| {
1110                            let hover_bg = colors.surface_muted;
1111                            let hover_border = colors.border_strong;
1112                            this.child(
1113                                div()
1114                                    .id(action_id)
1115                                    .test_support()
1116                                    .flex_none()
1117                                    .h(px(28.0))
1118                                    .px(Spacing::S3)
1119                                    .flex()
1120                                    .items_center()
1121                                    .justify_center()
1122                                    .rounded(Radii::PILL)
1123                                    .border_1()
1124                                    .border_color(colors.border)
1125                                    .bg(colors.surface)
1126                                    .hover(move |s| s.bg(hover_bg).border_color(hover_border))
1127                                    .text_size(Typography::TEXT_SM)
1128                                    .text_color(colors.foreground)
1129                                    .cursor_pointer()
1130                                    .on_mouse_down(MouseButton::Left, |_, _, cx| {
1131                                        cx.stop_propagation();
1132                                    })
1133                                    .on_click(move |_, window, cx| {
1134                                        ToastStackStore::invoke_action(
1135                                            &store_action,
1136                                            &tid_action,
1137                                            window,
1138                                            cx,
1139                                        );
1140                                        window.refresh();
1141                                    })
1142                                    .child(action.label),
1143                            )
1144                        })
1145                        .child({
1146                            let hover_bg = colors.surface_muted;
1147                            let hover_fg = colors.foreground;
1148                            let dismiss_label = cx.arc_locale().ui_strings().dismiss_notification;
1149                            div()
1150                                .id(close_id)
1151                                .test_support()
1152                                .role(Role::Button)
1153                                .aria_label(dismiss_label)
1154                                .flex_none()
1155                                .w(px(28.0))
1156                                .h(px(28.0))
1157                                .flex()
1158                                .items_center()
1159                                .justify_center()
1160                                .rounded(Radii::PILL)
1161                                .text_color(colors.text_muted)
1162                                .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
1163                                .cursor_pointer()
1164                                .on_mouse_down(MouseButton::Left, |_, _, cx| {
1165                                    cx.stop_propagation();
1166                                })
1167                                .on_click(move |_, window, cx| {
1168                                    let now_c = motion_now(cx);
1169                                    store_dismiss.update(cx, |s, _| {
1170                                        s.dismiss(tid_dismiss.as_ref(), now_c);
1171                                    });
1172                                    window.refresh();
1173                                })
1174                                .child(IconName::Close)
1175                        }),
1176                );
1177
1178            list = list.child(card);
1179        }
1180
1181        // Render exiting toasts smoothly fading/sinking or throwing off-screen.
1182        for ex in &exiting {
1183            let elapsed = (now - ex.exited_at_secs).max(0.0);
1184            let exit_dur = if ex.swiped { 0.22 } else { exit_secs };
1185            let t = (elapsed / exit_dur).clamp(0.0, 1.0) as f32;
1186            let op = (1.0 - t).clamp(0.0, 1.0);
1187            let (dx, dy, scale) = if reduced {
1188                (0.0, ex.last_target.y, ex.last_target.scale)
1189            } else if ex.swiped {
1190                let throw_x = arc_motion::SpringSolver::new(
1191                    THROW_SPRING.as_physical(),
1192                    0.0,
1193                    f64::from(animated_stack_width + 40.0),
1194                    f64::from(ex.throw_velocity),
1195                )
1196                .sample(elapsed)
1197                .value;
1198                (throw_x, ex.last_target.y, ex.last_target.scale)
1199            } else {
1200                (
1201                    0.0,
1202                    ex.last_target.y + 10.0 * t,
1203                    ex.last_target.scale * (1.0 - 0.04 * t),
1204                )
1205            };
1206
1207            let scaled_w = animated_stack_width * scale;
1208            let inset_x = (animated_stack_width - scaled_w) * 0.5;
1209            let ex_icon_color = match ex.record.kind {
1210                ToastType::Success => colors.success,
1211                ToastType::Info => colors.info,
1212                ToastType::Warning => colors.warning,
1213                ToastType::Error => colors.danger,
1214                ToastType::Loading => colors.text_muted,
1215            };
1216            let ex_icon = match ex.record.kind {
1217                ToastType::Success => IconName::CircleCheck,
1218                ToastType::Info | ToastType::Loading => IconName::Info,
1219                ToastType::Warning => IconName::TriangleAlert,
1220                ToastType::Error => IconName::CircleX,
1221            };
1222            list = list.child(
1223                div()
1224                    .absolute()
1225                    .left(px(inset_x + dx))
1226                    .bottom(px(-dy))
1227                    .w(px(scaled_w))
1228                    .h(px(ex.last_target.height.max(44.0)))
1229                    .overflow_hidden()
1230                    .rounded(Radii::PANEL)
1231                    .border_1()
1232                    .border_color(colors.border)
1233                    .bg(colors.surface_raised)
1234                    .shadow(Shadows::raised(theme.mode))
1235                    .opacity(op)
1236                    .flex()
1237                    .flex_row()
1238                    .items_start()
1239                    .gap(Spacing::S3)
1240                    .pt(Spacing::S3)
1241                    .pb(Spacing::S3)
1242                    .pl(Spacing::S4)
1243                    .pr(Spacing::S3)
1244                    .child(div().flex_none().text_color(ex_icon_color).child(ex_icon))
1245                    .child(
1246                        div()
1247                            .flex_1()
1248                            .min_w_0()
1249                            .flex()
1250                            .flex_col()
1251                            .text_size(Typography::TEXT_SM)
1252                            .text_color(colors.foreground)
1253                            .child(ex.record.title.clone())
1254                            .when_some(ex.record.description.clone(), |this, desc| {
1255                                this.child(
1256                                    div()
1257                                        .mt(px(2.0))
1258                                        .text_color(colors.text_secondary)
1259                                        .child(desc),
1260                                )
1261                            }),
1262                    ),
1263            );
1264        }
1265
1266        let inset = if self.contained {
1267            Spacing::S4
1268        } else {
1269            Spacing::S6
1270        };
1271
1272        let mut viewport = div()
1273            .id(self.id)
1274            .absolute()
1275            .bottom(inset)
1276            .flex()
1277            .justify_center();
1278
1279        viewport = match self.position {
1280            ToastPosition::BottomRight => viewport.right(inset),
1281            ToastPosition::BottomLeft => viewport.left(inset),
1282            ToastPosition::BottomCenter => viewport.left_0().right_0(),
1283        };
1284
1285        viewport.child(list)
1286    }
1287}
1288
1289#[cfg(test)]
1290mod tests {
1291    use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
1292    use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
1293    use gpui_kit::{
1294        AppContext as _, Context, Render, TestAppContext, div, px, test::TestWindowExt as _,
1295    };
1296
1297    use super::*;
1298
1299    struct ToastHost {
1300        store: Entity<ToastStackStore>,
1301    }
1302
1303    impl Render for ToastHost {
1304        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1305            div().relative().w(px(640.0)).h(px(420.0)).child(
1306                ToastStack::new("demo-toasts", self.store.clone())
1307                    .contained(true)
1308                    .visible_toasts(3),
1309            )
1310        }
1311    }
1312
1313    #[test]
1314    fn layout_stack_collapsed_and_expanded_geometry_match_arc() {
1315        let mut store = ToastStackStore::default();
1316        store.toast(ToastOptions::new("First"), 0.0);
1317        store.toast(ToastOptions::new("Second").description("Detail"), 1.0);
1318        store.toast(ToastOptions::new("Third"), 2.0);
1319        store.toast(ToastOptions::new("Fourth"), 3.0);
1320
1321        let heights = HashMap::new();
1322        let (collapsed, collapsed_h) = layout_stack(store.toasts(), &heights, false, 3);
1323        assert_eq!(collapsed.len(), 4);
1324        assert_eq!(collapsed[0].y, 0.0);
1325        assert_eq!(collapsed[0].scale, 1.0);
1326        assert_eq!(collapsed[0].content_opacity, 1.0);
1327        assert_eq!(collapsed[1].y, -PEEK);
1328        assert!((collapsed[1].scale - 0.95).abs() < 1e-5);
1329        assert_eq!(collapsed[1].content_opacity, 0.0);
1330        assert_eq!(collapsed[2].y, -2.0 * PEEK);
1331        assert!((collapsed[2].scale - 0.90).abs() < 1e-5);
1332        assert_eq!(collapsed[3].opacity, 0.0);
1333        assert_eq!(collapsed_h, DEFAULT_TOAST_HEIGHT + 2.0 * PEEK);
1334
1335        let (expanded, expanded_h) = layout_stack(store.toasts(), &heights, true, 3);
1336        assert_eq!(expanded[0].y, 0.0);
1337        assert_eq!(expanded[1].scale, 1.0);
1338        assert_eq!(expanded[1].content_opacity, 1.0);
1339        assert!(expanded[1].y < -DEFAULT_TOAST_HEIGHT);
1340        assert!(expanded_h > collapsed_h);
1341    }
1342
1343    #[test]
1344    fn toast_stack_item_width_adapts_to_copy_and_action() {
1345        let w_short = toast_stack_item_width("已保存", None, None);
1346        let w_mid = toast_stack_item_width("会话已归档", None, Some("撤销"));
1347        let w_long = toast_stack_item_width(
1348            "不能连接到自身或构成环路",
1349            Some("请重新选择目标输入端口,确保工作流拓扑保持有向无环图。"),
1350            None,
1351        );
1352        assert!((w_short - TOAST_STACK_MIN_WIDTH).abs() < 1e-3);
1353        assert!(w_mid > w_short && w_mid < TOAST_STACK_MAX_WIDTH);
1354        assert!((w_long - TOAST_STACK_MAX_WIDTH).abs() < 1e-3);
1355    }
1356
1357    #[gpui_kit::test]
1358    fn toast_stack_enqueue_update_dismiss_and_timer_pause(cx: &mut TestAppContext) {
1359        cx.update(|cx| {
1360            gpui_kit::init(cx);
1361            install_arc_theme(ThemeMode::Light, Accent::Green, cx);
1362        });
1363        let store = cx.new(|_| ToastStackStore::new(Duration::from_millis(2000), 12));
1364        let (_view, cx) = cx.add_window_view(|_, _| ToastHost {
1365            store: store.clone(),
1366        });
1367
1368        let id = cx.update(|_, cx| {
1369            store.update(cx, |s, _| {
1370                s.toast(
1371                    ToastOptions::new("Uploading file…").kind(ToastType::Loading),
1372                    0.0,
1373                )
1374            })
1375        });
1376
1377        cx.update(|window, cx| {
1378            window.render_frame(cx);
1379            assert_eq!(store.read(cx).count(), 1);
1380            // Loading toast has infinite duration (never auto-dismisses)
1381            assert!(store.read(cx).toasts()[0].remaining_secs.is_none());
1382
1383            // Morph in place to Success -> restarts timer and bumps version
1384            store.update(cx, |s, _| {
1385                s.update(
1386                    id.as_ref(),
1387                    ToastPatch {
1388                        kind: Some(ToastType::Success),
1389                        title: Some("Uploaded".into()),
1390                        ..Default::default()
1391                    },
1392                    1.0,
1393                );
1394            });
1395            window.render_frame(cx);
1396            let t = &store.read(cx).toasts()[0];
1397            assert_eq!(t.kind, ToastType::Success);
1398            assert_eq!(t.version, 1);
1399            assert!(t.remaining_secs.is_some());
1400
1401            // Click close button to dismiss
1402            let close_id = ElementId::NamedChild(
1403                ElementId::from("demo-toasts").into(),
1404                SharedString::from(format!("close-{id}")),
1405            );
1406            window.click(close_id, cx);
1407            assert_eq!(store.read(cx).count(), 0);
1408        });
1409    }
1410
1411    #[test]
1412    fn toast_stack_expand_morph_curve_matches_motion_within_5_percent() {
1413        let spec = ArcMotionTokens::DEFAULT.spring.morph;
1414        let solver = SpringSolver::new(spec, -14.0, -76.0, 0.0);
1415        let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
1416        let mut actual = CurveTrace::new("toast-stack", "item_y");
1417        let mut expected = CurveTrace::new("toast-stack", "item_y");
1418        for frame in 0..=45 {
1419            let t_ms = frame as f64 * 16.0;
1420            let t = t_ms / 1000.0;
1421            let ref_y = -76.0 - (-omega0 * t).exp() * (-62.0 + omega0 * -62.0 * t);
1422            expected.push(t_ms, ref_y);
1423            actual.push(t_ms, f64::from(solver.sample(t).value));
1424        }
1425        let err = max_curve_error_pct(&actual, &expected);
1426        assert!(err < 5.0, "ToastStack morph curve error {err:.3}% >= 5%");
1427    }
1428}