use std::rc::Rc;
use arc_motion::{
ArcPresence, ArcPresenceConfig, CubicBezier, DragTracker, PathPoint, PolylinePath, arc_spring,
arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, Hsla, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, assets::IconName,
base::Button as BaseButton, base::StyledExt as _, canvas, div, prelude::*, px,
};
type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
pub const TOAST_MIN_WIDTH: f32 = 220.0;
pub const TOAST_MAX_WIDTH: f32 = 416.0;
pub const TOAST_SWIPE_DISTANCE: f32 = 80.0;
pub const TOAST_SWIPE_VELOCITY: f32 = 480.0;
pub const TOAST_DEFAULT_DURATION_SECS: f64 = 4.5;
const TOAST_THROW_SPRING: SpringSpec = SpringSpec::visual(0.30, 0.0);
pub fn toast_target_width(title: &str, description: Option<&str>) -> f32 {
const CHROME_W: f32 = 16.0 + 30.0 + 12.0 + 12.0 + 32.0 + 14.0 + 2.0 + 8.0;
let measure = |s: &str, char_px: f32| -> f32 {
s.lines()
.map(|line| {
line.chars()
.map(|c| {
if c.is_ascii() {
if c.is_ascii_uppercase() || c == 'W' || c == 'M' {
char_px * 1.12
} else {
char_px
}
} else {
char_px * 1.85
}
})
.sum::<f32>()
})
.fold(0.0_f32, f32::max)
};
let title_w = measure(title, 8.2);
let desc_w = description
.filter(|d| !d.is_empty())
.map(|d| measure(d, 7.6))
.unwrap_or(0.0);
(CHROME_W + title_w.max(desc_w)).clamp(TOAST_MIN_WIDTH, TOAST_MAX_WIDTH)
}
pub fn resolve_toast_swipe_release(
offset_x: f32,
velocity_x: f32,
toast_width: f32,
) -> Option<f32> {
if offset_x.abs() < TOAST_SWIPE_DISTANCE && velocity_x.abs() < TOAST_SWIPE_VELOCITY {
return None;
}
let dir_src = if offset_x.abs() > 1e-3 {
offset_x
} else {
velocity_x
};
let direction = if dir_src >= 0.0 { 1.0 } else { -1.0 };
Some(direction * (toast_width.max(TOAST_MIN_WIDTH) + 48.0))
}
pub fn toast_copy_target_height(description: Option<&str>) -> f32 {
toast_copy_target_height_for_width(description, TOAST_MAX_WIDTH)
}
pub fn toast_copy_target_height_for_width(description: Option<&str>, toast_width: f32) -> f32 {
match description {
None | Some("") => 26.0,
Some(desc) => {
let copy_w = (toast_width - 126.0).max(96.0);
let units_per_line = (copy_w / 7.6).max(12.0);
let char_units: f32 = desc
.chars()
.map(|c| if c.is_ascii() { 1.0 } else { 1.85 })
.sum();
let lines = ((char_units / units_per_line).ceil() as usize).max(1);
26.0 + 4.0 + (lines as f32) * 20.0
}
}
}
fn toast_check_path() -> PolylinePath {
let s = 16.0 / 24.0;
PolylinePath::new(vec![
PathPoint::new(4.0 * s, 12.5 * s),
PathPoint::new(9.0 * s, 17.5 * s),
PathPoint::new(20.0 * s, 6.5 * s),
])
}
#[derive(Clone)]
struct ToastInternal {
last_open_prop: bool,
dismissed: bool,
opened_at_secs: f64,
drag_active: bool,
drag_start_x: f32,
drag_offset_x: f32,
throw_target_x: f32,
release_velocity_x: f32,
tracker: DragTracker,
last_width: f32,
last_morph_key: SharedString,
morph_changed_at_secs: f64,
}
impl ToastInternal {
fn new(open: bool, now: f64) -> Self {
Self {
last_open_prop: open,
dismissed: false,
opened_at_secs: now,
drag_active: false,
drag_start_x: 0.0,
drag_offset_x: 0.0,
throw_target_x: 0.0,
release_velocity_x: 0.0,
tracker: DragTracker::new(0.0),
last_width: TOAST_MAX_WIDTH,
last_morph_key: SharedString::default(),
morph_changed_at_secs: now,
}
}
}
#[derive(IntoElement)]
pub struct Toast {
id: ElementId,
title: SharedString,
description: Option<SharedString>,
open: bool,
duration_secs: f64,
on_open_change: Option<OpenChangeHandler>,
}
impl Toast {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
description: None,
open: true,
duration_secs: TOAST_DEFAULT_DURATION_SECS,
on_open_change: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn open(mut self, open: bool) -> Self {
self.open = open;
self
}
pub fn duration_ms(mut self, ms: u64) -> Self {
self.duration_secs = (ms as f64) / 1000.0;
self
}
pub fn on_open_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_open_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Toast {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-toast-state".into());
let internal =
window.use_keyed_state(state_id, cx, |_, _| ToastInternal::new(self.open, now));
let morph_key = SharedString::from(format!(
"{}\n{}",
self.title,
self.description.as_deref().unwrap_or("")
));
let mut auto_timed_out = false;
internal.update(cx, |s, _| {
if self.open != s.last_open_prop {
s.last_open_prop = self.open;
if self.open {
s.dismissed = false;
s.opened_at_secs = now;
s.drag_active = false;
s.drag_offset_x = 0.0;
s.throw_target_x = 0.0;
s.release_velocity_x = 0.0;
}
}
if s.last_morph_key != morph_key {
if !s.last_morph_key.is_empty() {
s.morph_changed_at_secs = now;
}
s.last_morph_key = morph_key.clone();
}
let currently_visible = self.open && !s.dismissed;
if currently_visible
&& !s.drag_active
&& self.duration_secs > 0.0
&& self.on_open_change.is_some()
{
let elapsed = (now - s.opened_at_secs).max(0.0);
if elapsed >= self.duration_secs {
s.dismissed = true;
s.throw_target_x = 0.0;
auto_timed_out = true;
} else {
window.request_animation_frame();
}
}
});
if auto_timed_out && let Some(cb) = self.on_open_change.clone() {
window.defer(cx, move |window, cx| {
cb(&false, window, cx);
});
}
let snap = internal.read(cx).clone();
let visible = self.open && !snap.dismissed;
let presence = ArcPresence::new((self.id.clone(), "toast-presence"), visible)
.animate_initial(true)
.config(ArcPresenceConfig {
enter_duration: motion.duration.standard,
exit_duration: motion.duration.exit,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
if !presence.should_render() {
return div().id(self.id).into_any_element();
}
let opacity = presence.progress.clamp(0.0, 1.0);
let y_target = if visible { 0.0 } else { 8.0 };
let y_offset = if reduced {
0.0
} else if visible {
arc_spring(
(self.id.clone(), "toast-y"),
y_target,
motion.spring.morph,
window,
cx,
)
} else {
(1.0 - opacity) * 8.0
};
let x_offset = if snap.drag_active {
snap.drag_offset_x
} else if reduced {
0.0
} else if snap.throw_target_x.abs() > 0.5 && !visible {
arc_spring_with_options(
(self.id.clone(), "toast-x"),
snap.throw_target_x,
SpringOptions::new(TOAST_THROW_SPRING)
.with_initial_velocity(snap.release_velocity_x),
window,
cx,
)
.value
} else {
arc_spring_with_options(
(self.id.clone(), "toast-x"),
0.0,
SpringOptions::new(motion.spring.snappy)
.with_initial_velocity(snap.release_velocity_x),
window,
cx,
)
.value
};
let check_progress = if reduced {
1.0
} else {
let elapsed = (now - snap.opened_at_secs - 0.12).max(0.0);
let dur = motion.duration.standard.as_secs_f64();
if elapsed < dur {
window.request_animation_frame();
}
let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let target_w = toast_target_width(self.title.as_ref(), self.description.as_deref());
let animated_w = if reduced {
target_w
} else {
arc_spring_with_options(
(self.id.clone(), "toast-w"),
target_w,
SpringOptions::new(motion.spring.smooth).with_initial_value(target_w),
window,
cx,
)
.value
};
let target_copy_h =
toast_copy_target_height_for_width(self.description.as_deref(), target_w);
let copy_h = if reduced {
target_copy_h
} else {
arc_spring(
(self.id.clone(), "toast-copy-h"),
target_copy_h,
motion.spring.smooth,
window,
cx,
)
};
let swap_progress = if reduced {
1.0
} else {
let elapsed = (now - snap.morph_changed_at_secs).max(0.0);
let dur = motion.duration.standard.as_secs_f64();
if elapsed < dur {
window.request_animation_frame();
}
let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let swap_y = if reduced {
0.0
} else {
(1.0 - swap_progress) * 4.0
};
let card_bg = oklab_mix(colors.surface, colors.background, 0.94);
let badge_border = oklab_mix(colors.success, colors.border, 0.24);
let badge_bg = oklab_mix(colors.success, colors.surface, 0.10);
let icon_fg = Hsla {
a: colors.success.a * opacity,
..colors.success
};
let check_path = toast_check_path();
let int_measure = internal.clone();
let int_drag = internal.clone();
let on_change_drag = self.on_open_change.clone();
let drag_active = snap.drag_active;
let drag_probe = canvas(
move |rect, _, cx| {
int_measure.update(cx, |s, _| {
s.last_width = f32::from(rect.size.width).max(TOAST_MIN_WIDTH);
});
},
move |_, _, window, _| {
if !drag_active {
return;
}
let st_move = int_drag.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let t_now = motion_now(cx);
let cur_x = f32::from(event.position.x);
let cur_y = f32::from(event.position.y);
st_move.update(cx, |s, _| {
if !s.drag_active {
return;
}
if let Some(next_x) = s.tracker.update_x(cur_x, cur_y, t_now, false) {
s.drag_offset_x = next_x;
}
});
window.refresh();
});
let st_up = int_drag.clone();
let cb_up = on_change_drag.clone();
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if !phase.bubble() || event.button != MouseButton::Left {
return;
}
let t_now = motion_now(cx);
let mut dismissed_now = false;
st_up.update(cx, |s, _| {
if !s.drag_active {
return;
}
s.drag_active = false;
let vel_x = s.tracker.release_velocity(t_now);
s.release_velocity_x = vel_x;
if let Some(target_x) =
resolve_toast_swipe_release(s.drag_offset_x, vel_x, s.last_width)
{
s.throw_target_x = target_x;
s.dismissed = true;
dismissed_now = true;
} else {
s.throw_target_x = 0.0;
}
});
if dismissed_now && let Some(cb) = &cb_up {
cb(&false, window, cx);
}
window.refresh();
});
},
)
.absolute()
.inset_0();
let int_down = internal.clone();
let int_close = internal.clone();
let on_change_close = self.on_open_change.clone();
let close_id = ElementId::NamedChild(self.id.clone().into(), "toast-close".into());
div()
.id(self.id)
.test_support()
.role(Role::Status)
.aria_label(self.title.clone())
.relative()
.w(px(animated_w))
.max_w_full()
.ml(px(x_offset))
.mt(px(y_offset))
.opacity(opacity)
.flex()
.flex_row()
.items_start()
.gap(px(12.0))
.pt(px(14.0))
.pr(px(14.0))
.pb(px(14.0))
.pl(px(16.0))
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(card_bg)
.text_color(colors.foreground)
.shadow(Shadows::floating(theme.mode))
.when(!reduced, |this| this.cursor_grab())
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
if reduced {
return;
}
let t_now = motion_now(cx);
let start_x = f32::from(event.position.x);
let start_y = f32::from(event.position.y);
int_down.update(cx, |s, _| {
s.drag_active = true;
s.drag_start_x = start_x - s.drag_offset_x;
s.tracker.begin(start_x, start_y, s.drag_offset_x, t_now);
});
window.refresh();
})
.child(drag_probe)
.child(
div()
.size(px(30.0))
.flex_none()
.rounded(Radii::PILL)
.border_1()
.border_color(badge_border)
.bg(badge_bg)
.flex()
.items_center()
.justify_center()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let sliced = check_path.slice(0.0, check_progress);
if let Some(builder) =
sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(2.25))
&& let Ok(built) = builder.build()
{
window.paint_path(built, icon_fg);
}
},
)
.size(px(16.0)),
),
)
.child(
div()
.flex_1()
.min_w_0()
.min_h(px(copy_h))
.pt(px(5.0))
.flex()
.flex_col()
.gap(px(2.0))
.opacity(swap_progress)
.mt(px(swap_y))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.title),
)
.when_some(self.description, |this, desc| {
this.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(desc),
)
}),
)
.child(
BaseButton::new(close_id)
.accessibility_label("Dismiss notification")
.on_click(move |_, window, cx| {
int_close.update(cx, |s, _| {
s.throw_target_x = 0.0;
s.dismissed = true;
});
if let Some(cb) = &on_change_close {
cb(&false, window, cx);
}
window.refresh();
})
.size(px(32.0))
.flex_none()
.rounded(Radii::PILL)
.flex()
.items_center()
.justify_center()
.text_color(colors.text_muted)
.hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
.cursor_pointer()
.child(IconName::Close),
)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, Spacing, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn swipe_release_and_height_target_behave_as_expected() {
assert_eq!(resolve_toast_swipe_release(32.0, 120.0, 360.0), None);
assert_eq!(resolve_toast_swipe_release(95.0, 60.0, 360.0), Some(408.0));
assert_eq!(
resolve_toast_swipe_release(-24.0, -520.0, 360.0),
Some(-408.0)
);
let h_short = toast_copy_target_height(None);
let h_desc = toast_copy_target_height(Some("Changes have been synced to production."));
let h_long = toast_copy_target_height(Some(
"Your deployment finished across 4 regions and all health checks passed without errors.",
));
assert!(h_desc > h_short);
assert!(h_long > h_desc);
let w_short = toast_target_width("Saved", None);
let w_mid = toast_target_width("Workspace preferences saved", None);
let w_long = toast_target_width(
"Deployment published to production",
Some("All 4 edge regions passed health checks and your live URL is ready."),
);
assert!((w_short - TOAST_MIN_WIDTH).abs() < 1e-3);
assert!(w_mid > w_short && w_mid < TOAST_MAX_WIDTH);
assert!((w_long - TOAST_MAX_WIDTH).abs() < 1e-3);
}
struct Host {
open: Rc<Cell<bool>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let open = self.open.clone();
div().p(Spacing::S6).child(
Toast::new("single-toast", "Project published")
.description("Your live link is ready to share.")
.open(open.get())
.duration_ms(0)
.on_open_change(cx.listener(move |_, is_open: &bool, _, cx| {
open.set(*is_open);
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn toast_dismiss_button_invokes_on_open_change(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let open = Rc::new(Cell::new(true));
let (_view, cx) = cx.add_window_view(|_, _| Host { open: open.clone() });
cx.update(|window, cx| {
window.render_frame(cx);
let close_btn = window.find_by_label("Dismiss notification");
assert_eq!(close_btn.role(), Some(Role::Button));
let pos = close_btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert!(!open.get());
});
}
}