Skip to main content

arc_ui/feedback/
toast.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/toast/toast.tsx` & `.module.css`
3//!
4//! P3 Component #17: `toast`
5//!
6//! - Single standalone notification card (`width: min(100%, 26rem / 416px)`) with a 30×30px
7//!   success badge that draws its checkmark stroke after a `120ms` delay (`ease.enter`),
8//!   a height-morphing copy frame (`spring.smooth`) that crossfades title/description swaps,
9//!   and a 32×32px close button (`scale(0.96)` on press).
10//! - Rises from `+16px` (`scale: 0.96 -> 1.0`) along `motion.spring.morph`.
11//! - Bidirectional horizontal swipe-to-dismiss: dragging left or right past `80px` or `480 px/s`
12//!   throws the toast off-screen (`direction * (width + 48)`) with release velocity on a
13//!   `SpringSpec::visual(0.30, 0.0)` spring while fading out over `duration.exit`; shorter swipes
14//!   snap back home on `motion.spring.snappy` preserving release velocity.
15//! - Auto-dismiss timer (`duration`, default `4500ms`, `0` disables auto-dismiss).
16
17use std::rc::Rc;
18
19use arc_motion::{
20    ArcPresence, ArcPresenceConfig, CubicBezier, DragTracker, PathPoint, PolylinePath, arc_spring,
21    arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
22};
23use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, SpringSpec, Typography, oklab_mix};
24use gpui_kit::{
25    App, ElementId, Hsla, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement,
26    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
27    base::Button as BaseButton, base::StyledExt as _, canvas, div, prelude::*, px,
28};
29
30type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
31
32/// Minimum width of a standalone [`Toast`] so short copy still breathes comfortably.
33pub const TOAST_MIN_WIDTH: f32 = 220.0;
34
35/// Maximum width of a standalone [`Toast`] (`26rem = 416px`).
36pub const TOAST_MAX_WIDTH: f32 = 416.0;
37
38/// Horizontal swipe distance threshold (`80px`) that triggers a throw dismissal.
39pub const TOAST_SWIPE_DISTANCE: f32 = 80.0;
40
41/// Horizontal swipe speed threshold (`480 px/s`) that triggers a throw dismissal.
42pub const TOAST_SWIPE_VELOCITY: f32 = 480.0;
43
44/// Default auto-dismiss duration in seconds (`4500ms`).
45pub const TOAST_DEFAULT_DURATION_SECS: f64 = 4.5;
46
47const TOAST_THROW_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
48
49/// Estimates the preferred pixel width of a standalone [`Toast`] from its `title` and optional
50/// `description`, clamped between [`TOAST_MIN_WIDTH`] and [`TOAST_MAX_WIDTH`] so short toasts hug
51/// their copy instead of stretching to a fixed full width while long copy wraps cleanly at `416px`.
52pub fn toast_target_width(title: &str, description: Option<&str>) -> f32 {
53    // 16px left pad + 30px badge + 12px gap + 12px gap + 32px close + 14px right pad + 2px border
54    const CHROME_W: f32 = 16.0 + 30.0 + 12.0 + 12.0 + 32.0 + 14.0 + 2.0 + 8.0;
55    let measure = |s: &str, char_px: f32| -> f32 {
56        s.lines()
57            .map(|line| {
58                line.chars()
59                    .map(|c| {
60                        if c.is_ascii() {
61                            if c.is_ascii_uppercase() || c == 'W' || c == 'M' {
62                                char_px * 1.12
63                            } else {
64                                char_px
65                            }
66                        } else {
67                            char_px * 1.85
68                        }
69                    })
70                    .sum::<f32>()
71            })
72            .fold(0.0_f32, f32::max)
73    };
74    let title_w = measure(title, 8.2);
75    let desc_w = description
76        .filter(|d| !d.is_empty())
77        .map(|d| measure(d, 7.6))
78        .unwrap_or(0.0);
79    (CHROME_W + title_w.max(desc_w)).clamp(TOAST_MIN_WIDTH, TOAST_MAX_WIDTH)
80}
81
82/// Resolves whether a horizontal drag release should throw-dismiss the toast (`Some(target_x)`)
83/// or snap back to center (`None`).
84pub fn resolve_toast_swipe_release(
85    offset_x: f32,
86    velocity_x: f32,
87    toast_width: f32,
88) -> Option<f32> {
89    if offset_x.abs() < TOAST_SWIPE_DISTANCE && velocity_x.abs() < TOAST_SWIPE_VELOCITY {
90        return None;
91    }
92    let dir_src = if offset_x.abs() > 1e-3 {
93        offset_x
94    } else {
95        velocity_x
96    };
97    let direction = if dir_src >= 0.0 { 1.0 } else { -1.0 };
98    Some(direction * (toast_width.max(TOAST_MIN_WIDTH) + 48.0))
99}
100
101/// Estimates the copy column height in pixels from `title` and `description` so the `HeightFrame`
102/// springs smoothly on `motion.spring.smooth` when copy grows or shrinks.
103pub fn toast_copy_target_height(description: Option<&str>) -> f32 {
104    toast_copy_target_height_for_width(description, TOAST_MAX_WIDTH)
105}
106
107/// Estimates the copy column height given the resolved toast outer width.
108pub fn toast_copy_target_height_for_width(description: Option<&str>, toast_width: f32) -> f32 {
109    match description {
110        None | Some("") => 26.0,
111        Some(desc) => {
112            let copy_w = (toast_width - 126.0).max(96.0);
113            let units_per_line = (copy_w / 7.6).max(12.0);
114            let char_units: f32 = desc
115                .chars()
116                .map(|c| if c.is_ascii() { 1.0 } else { 1.85 })
117                .sum();
118            let lines = ((char_units / units_per_line).ceil() as usize).max(1);
119            26.0 + 4.0 + (lines as f32) * 20.0
120        }
121    }
122}
123
124fn toast_check_path() -> PolylinePath {
125    let s = 16.0 / 24.0;
126    PolylinePath::new(vec![
127        PathPoint::new(4.0 * s, 12.5 * s),
128        PathPoint::new(9.0 * s, 17.5 * s),
129        PathPoint::new(20.0 * s, 6.5 * s),
130    ])
131}
132
133#[derive(Clone)]
134struct ToastInternal {
135    last_open_prop: bool,
136    dismissed: bool,
137    opened_at_secs: f64,
138    drag_active: bool,
139    drag_start_x: f32,
140    drag_offset_x: f32,
141    throw_target_x: f32,
142    release_velocity_x: f32,
143    tracker: DragTracker,
144    last_width: f32,
145    last_morph_key: SharedString,
146    morph_changed_at_secs: f64,
147}
148
149impl ToastInternal {
150    fn new(open: bool, now: f64) -> Self {
151        Self {
152            last_open_prop: open,
153            dismissed: false,
154            opened_at_secs: now,
155            drag_active: false,
156            drag_start_x: 0.0,
157            drag_offset_x: 0.0,
158            throw_target_x: 0.0,
159            release_velocity_x: 0.0,
160            tracker: DragTracker::new(0.0),
161            last_width: TOAST_MAX_WIDTH,
162            last_morph_key: SharedString::default(),
163            morph_changed_at_secs: now,
164        }
165    }
166}
167
168/// Arc standalone `Toast`: single status notification card with a drawn checkmark badge,
169/// smooth height-morphing text frame, auto-dismiss timer, and bidirectional swipe-to-throw dismissal.
170#[derive(IntoElement)]
171pub struct Toast {
172    id: ElementId,
173    title: SharedString,
174    description: Option<SharedString>,
175    open: bool,
176    duration_secs: f64,
177    on_open_change: Option<OpenChangeHandler>,
178}
179
180impl Toast {
181    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
182        Self {
183            id: id.into(),
184            title: title.into(),
185            description: None,
186            open: true,
187            duration_secs: TOAST_DEFAULT_DURATION_SECS,
188            on_open_change: None,
189        }
190    }
191
192    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
193        self.description = Some(description.into());
194        self
195    }
196
197    pub fn open(mut self, open: bool) -> Self {
198        self.open = open;
199        self
200    }
201
202    /// Sets auto-dismiss timeout in milliseconds (`0` disables auto-dismiss).
203    pub fn duration_ms(mut self, ms: u64) -> Self {
204        self.duration_secs = (ms as f64) / 1000.0;
205        self
206    }
207
208    pub fn on_open_change(
209        mut self,
210        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
211    ) -> Self {
212        self.on_open_change = Some(Rc::new(handler));
213        self
214    }
215}
216
217impl RenderOnce for Toast {
218    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
219        let theme = cx.arc_theme().clone();
220        let colors = theme.colors;
221        let motion = theme.motion;
222        let reduced = is_reduced_motion(cx);
223        let now = motion_now(cx);
224
225        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-toast-state".into());
226        let internal =
227            window.use_keyed_state(state_id, cx, |_, _| ToastInternal::new(self.open, now));
228
229        let morph_key = SharedString::from(format!(
230            "{}\n{}",
231            self.title,
232            self.description.as_deref().unwrap_or("")
233        ));
234
235        let mut auto_timed_out = false;
236        internal.update(cx, |s, _| {
237            if self.open != s.last_open_prop {
238                s.last_open_prop = self.open;
239                if self.open {
240                    s.dismissed = false;
241                    s.opened_at_secs = now;
242                    s.drag_active = false;
243                    s.drag_offset_x = 0.0;
244                    s.throw_target_x = 0.0;
245                    s.release_velocity_x = 0.0;
246                }
247            }
248            if s.last_morph_key != morph_key {
249                if !s.last_morph_key.is_empty() {
250                    s.morph_changed_at_secs = now;
251                }
252                s.last_morph_key = morph_key.clone();
253            }
254            let currently_visible = self.open && !s.dismissed;
255            if currently_visible
256                && !s.drag_active
257                && self.duration_secs > 0.0
258                && self.on_open_change.is_some()
259            {
260                let elapsed = (now - s.opened_at_secs).max(0.0);
261                if elapsed >= self.duration_secs {
262                    s.dismissed = true;
263                    s.throw_target_x = 0.0;
264                    auto_timed_out = true;
265                } else {
266                    window.request_animation_frame();
267                }
268            }
269        });
270
271        if auto_timed_out && let Some(cb) = self.on_open_change.clone() {
272            window.defer(cx, move |window, cx| {
273                cb(&false, window, cx);
274            });
275        }
276
277        let snap = internal.read(cx).clone();
278        let visible = self.open && !snap.dismissed;
279
280        let presence = ArcPresence::new((self.id.clone(), "toast-presence"), visible)
281            .animate_initial(true)
282            .config(ArcPresenceConfig {
283                enter_duration: motion.duration.standard,
284                exit_duration: motion.duration.exit,
285                enter_ease: motion.ease.enter,
286                exit_ease: motion.ease.standard,
287                fade_on_reduced_motion: true,
288            })
289            .sample(window, cx);
290
291        if !presence.should_render() {
292            return div().id(self.id).into_any_element();
293        }
294
295        let opacity = presence.progress.clamp(0.0, 1.0);
296        let y_target = if visible { 0.0 } else { 8.0 };
297        let y_offset = if reduced {
298            0.0
299        } else if visible {
300            arc_spring(
301                (self.id.clone(), "toast-y"),
302                y_target,
303                motion.spring.morph,
304                window,
305                cx,
306            )
307        } else {
308            (1.0 - opacity) * 8.0
309        };
310
311        let x_offset = if snap.drag_active {
312            snap.drag_offset_x
313        } else if reduced {
314            0.0
315        } else if snap.throw_target_x.abs() > 0.5 && !visible {
316            arc_spring_with_options(
317                (self.id.clone(), "toast-x"),
318                snap.throw_target_x,
319                SpringOptions::new(TOAST_THROW_SPRING)
320                    .with_initial_velocity(snap.release_velocity_x),
321                window,
322                cx,
323            )
324            .value
325        } else {
326            arc_spring_with_options(
327                (self.id.clone(), "toast-x"),
328                0.0,
329                SpringOptions::new(motion.spring.snappy)
330                    .with_initial_velocity(snap.release_velocity_x),
331                window,
332                cx,
333            )
334            .value
335        };
336
337        // Drawn checkmark progress (120ms delay, standard duration, ease.enter)
338        let check_progress = if reduced {
339            1.0
340        } else {
341            let elapsed = (now - snap.opened_at_secs - 0.12).max(0.0);
342            let dur = motion.duration.standard.as_secs_f64();
343            if elapsed < dur {
344                window.request_animation_frame();
345            }
346            let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
347            CubicBezier::from_spec(motion.ease.enter).sample(t)
348        };
349
350        // Dynamic width & HeightFrame smooth springs + swap text crossfade
351        let target_w = toast_target_width(self.title.as_ref(), self.description.as_deref());
352        let animated_w = if reduced {
353            target_w
354        } else {
355            arc_spring_with_options(
356                (self.id.clone(), "toast-w"),
357                target_w,
358                SpringOptions::new(motion.spring.smooth).with_initial_value(target_w),
359                window,
360                cx,
361            )
362            .value
363        };
364        let target_copy_h =
365            toast_copy_target_height_for_width(self.description.as_deref(), target_w);
366        let copy_h = if reduced {
367            target_copy_h
368        } else {
369            arc_spring(
370                (self.id.clone(), "toast-copy-h"),
371                target_copy_h,
372                motion.spring.smooth,
373                window,
374                cx,
375            )
376        };
377
378        let swap_progress = if reduced {
379            1.0
380        } else {
381            let elapsed = (now - snap.morph_changed_at_secs).max(0.0);
382            let dur = motion.duration.standard.as_secs_f64();
383            if elapsed < dur {
384                window.request_animation_frame();
385            }
386            let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
387            CubicBezier::from_spec(motion.ease.enter).sample(t)
388        };
389        let swap_y = if reduced {
390            0.0
391        } else {
392            (1.0 - swap_progress) * 4.0
393        };
394
395        let card_bg = oklab_mix(colors.surface, colors.background, 0.94);
396        let badge_border = oklab_mix(colors.success, colors.border, 0.24);
397        let badge_bg = oklab_mix(colors.success, colors.surface, 0.10);
398        let icon_fg = Hsla {
399            a: colors.success.a * opacity,
400            ..colors.success
401        };
402        let check_path = toast_check_path();
403
404        let int_measure = internal.clone();
405        let int_drag = internal.clone();
406        let on_change_drag = self.on_open_change.clone();
407        let drag_active = snap.drag_active;
408
409        let drag_probe = canvas(
410            move |rect, _, cx| {
411                int_measure.update(cx, |s, _| {
412                    s.last_width = f32::from(rect.size.width).max(TOAST_MIN_WIDTH);
413                });
414            },
415            move |_, _, window, _| {
416                if !drag_active {
417                    return;
418                }
419                let st_move = int_drag.clone();
420                window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
421                    if !phase.bubble() {
422                        return;
423                    }
424                    let t_now = motion_now(cx);
425                    let cur_x = f32::from(event.position.x);
426                    let cur_y = f32::from(event.position.y);
427                    st_move.update(cx, |s, _| {
428                        if !s.drag_active {
429                            return;
430                        }
431                        if let Some(next_x) = s.tracker.update_x(cur_x, cur_y, t_now, false) {
432                            s.drag_offset_x = next_x;
433                        }
434                    });
435                    window.refresh();
436                });
437
438                let st_up = int_drag.clone();
439                let cb_up = on_change_drag.clone();
440                window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
441                    if !phase.bubble() || event.button != MouseButton::Left {
442                        return;
443                    }
444                    let t_now = motion_now(cx);
445                    let mut dismissed_now = false;
446                    st_up.update(cx, |s, _| {
447                        if !s.drag_active {
448                            return;
449                        }
450                        s.drag_active = false;
451                        let vel_x = s.tracker.release_velocity(t_now);
452                        s.release_velocity_x = vel_x;
453                        if let Some(target_x) =
454                            resolve_toast_swipe_release(s.drag_offset_x, vel_x, s.last_width)
455                        {
456                            s.throw_target_x = target_x;
457                            s.dismissed = true;
458                            dismissed_now = true;
459                        } else {
460                            s.throw_target_x = 0.0;
461                        }
462                    });
463                    if dismissed_now && let Some(cb) = &cb_up {
464                        cb(&false, window, cx);
465                    }
466                    window.refresh();
467                });
468            },
469        )
470        .absolute()
471        .inset_0();
472
473        let int_down = internal.clone();
474        let int_close = internal.clone();
475        let on_change_close = self.on_open_change.clone();
476        let close_id = ElementId::NamedChild(self.id.clone().into(), "toast-close".into());
477
478        div()
479            .id(self.id)
480            .test_support()
481            .role(Role::Status)
482            .aria_label(self.title.clone())
483            .relative()
484            .w(px(animated_w))
485            .max_w_full()
486            .ml(px(x_offset))
487            .mt(px(y_offset))
488            .opacity(opacity)
489            .flex()
490            .flex_row()
491            .items_start()
492            .gap(px(12.0))
493            .pt(px(14.0))
494            .pr(px(14.0))
495            .pb(px(14.0))
496            .pl(px(16.0))
497            .rounded(Radii::PANEL)
498            .border_1()
499            .border_color(colors.border)
500            .bg(card_bg)
501            .text_color(colors.foreground)
502            .shadow(Shadows::floating(theme.mode))
503            .when(!reduced, |this| this.cursor_grab())
504            .on_mouse_down(MouseButton::Left, move |event, window, cx| {
505                if reduced {
506                    return;
507                }
508                let t_now = motion_now(cx);
509                let start_x = f32::from(event.position.x);
510                let start_y = f32::from(event.position.y);
511                int_down.update(cx, |s, _| {
512                    s.drag_active = true;
513                    s.drag_start_x = start_x - s.drag_offset_x;
514                    s.tracker.begin(start_x, start_y, s.drag_offset_x, t_now);
515                });
516                window.refresh();
517            })
518            .child(drag_probe)
519            .child(
520                div()
521                    .size(px(30.0))
522                    .flex_none()
523                    .rounded(Radii::PILL)
524                    .border_1()
525                    .border_color(badge_border)
526                    .bg(badge_bg)
527                    .flex()
528                    .items_center()
529                    .justify_center()
530                    .child(
531                        canvas(
532                            |_, _, _| {},
533                            move |rect, _, window, _| {
534                                let sliced = check_path.slice(0.0, check_progress);
535                                if let Some(builder) =
536                                    sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(2.25))
537                                    && let Ok(built) = builder.build()
538                                {
539                                    window.paint_path(built, icon_fg);
540                                }
541                            },
542                        )
543                        .size(px(16.0)),
544                    ),
545            )
546            .child(
547                div()
548                    .flex_1()
549                    .min_w_0()
550                    .min_h(px(copy_h))
551                    .pt(px(5.0))
552                    .flex()
553                    .flex_col()
554                    .gap(px(2.0))
555                    .opacity(swap_progress)
556                    .mt(px(swap_y))
557                    .child(
558                        div()
559                            .text_size(Typography::TEXT_SM)
560                            .font_medium()
561                            .text_color(colors.foreground)
562                            .child(self.title),
563                    )
564                    .when_some(self.description, |this, desc| {
565                        this.child(
566                            div()
567                                .text_size(Typography::TEXT_SM)
568                                .text_color(colors.text_secondary)
569                                .child(desc),
570                        )
571                    }),
572            )
573            .child(
574                BaseButton::new(close_id)
575                    .accessibility_label("Dismiss notification")
576                    .on_click(move |_, window, cx| {
577                        int_close.update(cx, |s, _| {
578                            s.throw_target_x = 0.0;
579                            s.dismissed = true;
580                        });
581                        if let Some(cb) = &on_change_close {
582                            cb(&false, window, cx);
583                        }
584                        window.refresh();
585                    })
586                    .size(px(32.0))
587                    .flex_none()
588                    .rounded(Radii::PILL)
589                    .flex()
590                    .items_center()
591                    .justify_center()
592                    .text_color(colors.text_muted)
593                    .hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
594                    .cursor_pointer()
595                    .child(IconName::Close),
596            )
597            .into_any_element()
598    }
599}
600
601#[cfg(test)]
602mod tests {
603    use std::{cell::Cell, rc::Rc};
604
605    use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
606    use gpui_kit::{
607        Context, MouseButton, Render, Role, TestAppContext, div,
608        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
609    };
610
611    use super::*;
612
613    #[test]
614    fn swipe_release_and_height_target_behave_as_expected() {
615        // Short and slow swipe snaps back
616        assert_eq!(resolve_toast_swipe_release(32.0, 120.0, 360.0), None);
617        // Past 80px throws right
618        assert_eq!(resolve_toast_swipe_release(95.0, 60.0, 360.0), Some(408.0));
619        // Fast left flick throws left
620        assert_eq!(
621            resolve_toast_swipe_release(-24.0, -520.0, 360.0),
622            Some(-408.0)
623        );
624
625        let h_short = toast_copy_target_height(None);
626        let h_desc = toast_copy_target_height(Some("Changes have been synced to production."));
627        let h_long = toast_copy_target_height(Some(
628            "Your deployment finished across 4 regions and all health checks passed without errors.",
629        ));
630        assert!(h_desc > h_short);
631        assert!(h_long > h_desc);
632
633        // Dynamic width scales with copy length within [TOAST_MIN_WIDTH, TOAST_MAX_WIDTH]
634        let w_short = toast_target_width("Saved", None);
635        let w_mid = toast_target_width("Workspace preferences saved", None);
636        let w_long = toast_target_width(
637            "Deployment published to production",
638            Some("All 4 edge regions passed health checks and your live URL is ready."),
639        );
640        assert!((w_short - TOAST_MIN_WIDTH).abs() < 1e-3);
641        assert!(w_mid > w_short && w_mid < TOAST_MAX_WIDTH);
642        assert!((w_long - TOAST_MAX_WIDTH).abs() < 1e-3);
643    }
644
645    struct Host {
646        open: Rc<Cell<bool>>,
647    }
648
649    impl Render for Host {
650        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
651            let open = self.open.clone();
652            div().p(Spacing::S6).child(
653                Toast::new("single-toast", "Project published")
654                    .description("Your live link is ready to share.")
655                    .open(open.get())
656                    .duration_ms(0)
657                    .on_open_change(cx.listener(move |_, is_open: &bool, _, cx| {
658                        open.set(*is_open);
659                        cx.notify();
660                    })),
661            )
662        }
663    }
664
665    #[gpui_kit::test]
666    fn toast_dismiss_button_invokes_on_open_change(cx: &mut TestAppContext) {
667        cx.update(|cx| {
668            gpui_kit::init(cx);
669            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
670        });
671        let open = Rc::new(Cell::new(true));
672        let (_view, cx) = cx.add_window_view(|_, _| Host { open: open.clone() });
673
674        cx.update(|window, cx| {
675            window.render_frame(cx);
676            let close_btn = window.find_by_label("Dismiss notification");
677            assert_eq!(close_btn.role(), Some(Role::Button));
678            let pos = close_btn.bounds().center();
679            window.pointer_down(pos, MouseButton::Left, cx);
680            window.pointer_up(pos, MouseButton::Left, cx);
681            assert!(!open.get());
682        });
683    }
684}