use std::{collections::HashMap, rc::Rc, time::Duration};
use arc_motion::{
BlurFallback, DragTracker, arc_spring_with_options, arc_transition, is_reduced_motion,
motion_now, project_deceleration, rubber_band, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcLocale as _, ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography,
};
use gpui_kit::{
App, ElementId, Entity, FocusHandle, IntoElement, KeyDownEvent, MouseButton, MouseMoveEvent,
MouseUpEvent, ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window, assets::IconName, canvas, div, point, prelude::*, px,
};
const PEEK: f32 = 14.0;
const GAP: f32 = 12.0;
const STEP: f32 = 0.05;
const SWIPE_FADE: f32 = 280.0;
pub const TOAST_STACK_MIN_WIDTH: f32 = 200.0;
pub const TOAST_STACK_MAX_WIDTH: f32 = 420.0;
const DEFAULT_TOAST_HEIGHT: f32 = 64.0;
const DESCRIPTION_EXTRA_HEIGHT: f32 = 22.0;
const THROW_SPRING: SpringSpec = SpringSpec::visual(0.32, 0.0);
fn estimate_copy_line_width(text: &str, char_px: f32) -> f32 {
text.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)
}
pub fn toast_stack_item_width(
title: &str,
description: Option<&str>,
action_label: Option<&str>,
) -> f32 {
const BASE_CHROME_W: f32 = 16.0 + 18.0 + 12.0 + 12.0 + 28.0 + 12.0 + 2.0 + 12.0;
let title_w = estimate_copy_line_width(title, 8.2);
let desc_w = description
.filter(|d| !d.is_empty())
.map(|d| estimate_copy_line_width(d, 7.6))
.unwrap_or(0.0);
let action_w = action_label
.filter(|l| !l.is_empty())
.map(|l| 12.0 + 24.0 + estimate_copy_line_width(l, 8.0))
.unwrap_or(0.0);
(BASE_CHROME_W + title_w.max(desc_w) + action_w)
.clamp(TOAST_STACK_MIN_WIDTH, TOAST_STACK_MAX_WIDTH)
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToastType {
Success,
#[default]
Info,
Warning,
Error,
Loading,
}
impl ToastType {
pub const fn sr_label(self) -> &'static str {
match self {
Self::Success => "Success",
Self::Info => "Info",
Self::Warning => "Warning",
Self::Error => "Error",
Self::Loading => "In progress",
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ToastPosition {
#[default]
BottomRight,
BottomCenter,
BottomLeft,
}
type ActionCallback = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone)]
pub struct ToastAction {
pub label: SharedString,
pub on_click: ActionCallback,
}
impl ToastAction {
pub fn new(
label: impl Into<SharedString>,
on_click: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
Self {
label: label.into(),
on_click: Rc::new(on_click),
}
}
}
#[derive(Clone)]
pub struct ToastOptions {
pub id: Option<SharedString>,
pub kind: ToastType,
pub title: SharedString,
pub description: Option<SharedString>,
pub action: Option<ToastAction>,
pub duration: Option<Option<Duration>>,
}
impl ToastOptions {
pub fn new(title: impl Into<SharedString>) -> Self {
Self {
id: None,
kind: ToastType::Info,
title: title.into(),
description: None,
action: None,
duration: None,
}
}
pub fn id(mut self, id: impl Into<SharedString>) -> Self {
self.id = Some(id.into());
self
}
pub fn kind(mut self, kind: ToastType) -> Self {
self.kind = kind;
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn action(mut self, action: ToastAction) -> Self {
self.action = Some(action);
self
}
pub fn duration(mut self, duration: Option<Duration>) -> Self {
self.duration = Some(duration);
self
}
}
#[derive(Clone, Default)]
pub struct ToastPatch {
pub kind: Option<ToastType>,
pub title: Option<SharedString>,
pub description: Option<Option<SharedString>>,
pub action: Option<Option<ToastAction>>,
pub duration: Option<Option<Duration>>,
}
#[derive(Clone)]
pub struct ToastRecord {
pub id: SharedString,
pub kind: ToastType,
pub title: SharedString,
pub description: Option<SharedString>,
pub action: Option<ToastAction>,
pub duration: Option<Duration>,
pub remaining_secs: Option<f64>,
pub seq: u64,
pub version: u64,
pub entered_at_secs: f64,
pub updated_at_secs: f64,
}
impl ToastRecord {
pub fn estimated_width(&self) -> f32 {
toast_stack_item_width(
self.title.as_ref(),
self.description.as_deref(),
self.action.as_ref().map(|a| a.label.as_ref()),
)
}
pub fn estimated_height(&self) -> f32 {
self.estimated_height_for_width(self.estimated_width())
}
pub fn estimated_height_for_width(&self, card_width: f32) -> f32 {
let action_w = self
.action
.as_ref()
.map(|a| 12.0 + 24.0 + estimate_copy_line_width(a.label.as_ref(), 8.0))
.unwrap_or(0.0);
let copy_w = (card_width - 102.0 - action_w).max(88.0);
let title_lines =
((estimate_copy_line_width(self.title.as_ref(), 8.2) / copy_w).ceil() as usize).max(1);
let title_extra = title_lines.saturating_sub(1) as f32 * 20.0;
let desc_extra = self
.description
.as_deref()
.filter(|d| !d.is_empty())
.map(|desc| {
let desc_w = estimate_copy_line_width(desc, 7.6);
let lines = ((desc_w / copy_w).ceil() as usize).max(1);
DESCRIPTION_EXTRA_HEIGHT + lines.saturating_sub(1) as f32 * 18.0
})
.unwrap_or(0.0);
DEFAULT_TOAST_HEIGHT + title_extra + desc_extra
}
}
#[derive(Clone)]
struct ExitingToast {
record: ToastRecord,
last_target: StackTarget,
exited_at_secs: f64,
swiped: bool,
throw_velocity: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StackTarget {
pub y: f32,
pub scale: f32,
pub height: f32,
pub opacity: f32,
pub content_opacity: f32,
}
pub fn layout_stack(
toasts: &[ToastRecord],
heights: &HashMap<SharedString, f32>,
expanded: bool,
visible_toasts: usize,
) -> (Vec<StackTarget>, f32) {
let height_of = |t: &ToastRecord| -> f32 {
heights
.get(&t.id)
.copied()
.unwrap_or_else(|| t.estimated_height())
};
let front = toasts.first().map_or(0.0, height_of);
let mut tops = Vec::with_capacity(toasts.len() + 1);
tops.push(0.0_f32);
for (idx, item) in toasts.iter().enumerate() {
let prev = tops[idx];
let add = if idx < visible_toasts {
height_of(item) + GAP
} else {
0.0
};
tops.push(prev + add);
}
let targets: Vec<StackTarget> = toasts
.iter()
.enumerate()
.map(|(index, item)| {
let visible = index < visible_toasts;
let depth = index.min(visible_toasts) as f32;
if expanded {
StackTarget {
y: -tops[index],
scale: 1.0,
height: height_of(item),
opacity: if visible { 1.0 } else { 0.0 },
content_opacity: 1.0,
}
} else {
StackTarget {
y: -PEEK * depth,
scale: 1.0 - STEP * depth,
height: if index == 0 { height_of(item) } else { front },
opacity: if visible { 1.0 } else { 0.0 },
content_opacity: if index == 0 { 1.0 } else { 0.0 },
}
}
})
.collect();
let list_height = if toasts.is_empty() {
0.0
} else if expanded {
(tops[toasts.len()] - GAP).max(0.0)
} else {
front + PEEK * (toasts.len().min(visible_toasts).saturating_sub(1) as f32)
};
(targets, list_height)
}
fn default_duration_for(kind: ToastType, base: Duration) -> Option<Duration> {
match kind {
ToastType::Loading => None,
ToastType::Warning | ToastType::Error => Some(base.mul_f64(1.6)),
ToastType::Success | ToastType::Info => Some(base),
}
}
pub struct ToastStackStore {
base_duration: Duration,
limit: usize,
seq: u64,
toasts: Vec<ToastRecord>,
exiting: Vec<ExitingToast>,
heights: HashMap<SharedString, f32>,
last_tick_secs: Option<f64>,
}
impl Default for ToastStackStore {
fn default() -> Self {
Self::new(Duration::from_millis(5000), 12)
}
}
impl ToastStackStore {
pub fn new(base_duration: Duration, limit: usize) -> Self {
Self {
base_duration,
limit: limit.max(1),
seq: 0,
toasts: Vec::new(),
exiting: Vec::new(),
heights: HashMap::new(),
last_tick_secs: None,
}
}
pub fn count(&self) -> usize {
self.toasts.len()
}
pub fn toasts(&self) -> &[ToastRecord] {
&self.toasts
}
pub fn toast(&mut self, options: ToastOptions, now_secs: f64) -> SharedString {
if let Some(id) = &options.id
&& self.toasts.iter().any(|t| &t.id == id)
{
let id_clone = id.clone();
self.update(
&id_clone,
ToastPatch {
kind: Some(options.kind),
title: Some(options.title),
description: Some(options.description),
action: Some(options.action),
duration: options.duration,
},
now_secs,
);
return id_clone;
}
self.seq += 1;
let id = options
.id
.unwrap_or_else(|| SharedString::from(format!("toast-{}", self.seq)));
let duration = options
.duration
.unwrap_or_else(|| default_duration_for(options.kind, self.base_duration));
let record = ToastRecord {
id: id.clone(),
kind: options.kind,
title: options.title,
description: options.description,
action: options.action,
duration,
remaining_secs: duration.map(|d| d.as_secs_f64()),
seq: self.seq,
version: 0,
entered_at_secs: now_secs,
updated_at_secs: now_secs,
};
self.toasts.insert(0, record);
self.toasts.truncate(self.limit);
id
}
pub fn update(&mut self, id: &str, patch: ToastPatch, now_secs: f64) {
let Some(record) = self.toasts.iter_mut().find(|t| t.id.as_ref() == id) else {
return;
};
if let Some(kind) = patch.kind {
record.kind = kind;
}
if let Some(title) = patch.title {
record.title = title;
}
if let Some(description) = patch.description {
record.description = description;
}
if let Some(action) = patch.action {
record.action = action;
}
record.duration = patch
.duration
.unwrap_or_else(|| default_duration_for(record.kind, self.base_duration));
record.remaining_secs = record.duration.map(|d| d.as_secs_f64());
record.version += 1;
record.updated_at_secs = now_secs;
}
pub fn dismiss(&mut self, id: &str, now_secs: f64) {
self.dismiss_with_swipe(id, now_secs, false, 0.0, false, 3);
}
fn dismiss_with_swipe(
&mut self,
id: &str,
now_secs: f64,
swiped: bool,
throw_velocity: f32,
expanded: bool,
visible_toasts: usize,
) {
let (targets, _) = layout_stack(&self.toasts, &self.heights, expanded, visible_toasts);
let Some(pos) = self.toasts.iter().position(|t| t.id.as_ref() == id) else {
return;
};
let record = self.toasts.remove(pos);
let target = targets[pos];
self.exiting.push(ExitingToast {
record,
last_target: target,
exited_at_secs: now_secs,
swiped,
throw_velocity,
});
}
pub fn dismiss_all(&mut self, now_secs: f64) {
let ids: Vec<SharedString> = self.toasts.iter().map(|t| t.id.clone()).collect();
for id in ids {
self.dismiss(id.as_ref(), now_secs);
}
}
pub fn invoke_action(
store: &Entity<Self>,
id: &SharedString,
window: &mut Window,
cx: &mut App,
) {
let found = {
let s = store.read(cx);
s.toasts
.iter()
.find(|t| &t.id == id)
.and_then(|t| t.action.clone().map(|a| (t.version, a)))
};
let Some((version_before, action)) = found else {
return;
};
(action.on_click)(id, window, cx);
let still_same_version = store
.read(cx)
.toasts
.iter()
.find(|t| &t.id == id)
.is_some_and(|t| t.version == version_before);
if still_same_version {
let now = motion_now(cx);
store.update(cx, |s, _| s.dismiss(id.as_ref(), now));
}
}
pub fn tick(&mut self, now_secs: f64, paused: bool, exit_duration_secs: f64) -> bool {
let dt = self
.last_tick_secs
.map_or(0.0, |prev| (now_secs - prev).max(0.0));
self.last_tick_secs = Some(now_secs);
if !paused && dt > 0.0 {
let mut expired = Vec::new();
for toast in &mut self.toasts {
if let Some(rem) = &mut toast.remaining_secs {
*rem -= dt;
if *rem <= 0.0 {
expired.push(toast.id.clone());
}
}
}
for id in expired {
self.dismiss(id.as_ref(), now_secs);
}
}
self.exiting.retain(|ex| {
let max_exit = if ex.swiped { 0.24 } else { exit_duration_secs };
(now_secs - ex.exited_at_secs) < max_exit
});
let has_timed = !paused && self.toasts.iter().any(|t| t.remaining_secs.is_some());
let has_loading = self.toasts.iter().any(|t| t.kind == ToastType::Loading);
has_timed || !self.exiting.is_empty() || has_loading
}
}
#[derive(Clone)]
struct ToastViewState {
hovered: bool,
focused: bool,
dragging_id: Option<SharedString>,
drag_x: HashMap<SharedString, f32>,
drag_tracker: DragTracker,
focus_handle: FocusHandle,
}
impl ToastViewState {
fn new(focus_handle: FocusHandle) -> Self {
Self {
hovered: false,
focused: false,
dragging_id: None,
drag_x: HashMap::new(),
drag_tracker: DragTracker::new(6.0),
focus_handle,
}
}
}
#[derive(IntoElement)]
pub struct ToastStack {
id: ElementId,
store: Entity<ToastStackStore>,
label: SharedString,
position: ToastPosition,
contained: bool,
visible_toasts: usize,
hotkey: bool,
}
impl ToastStack {
pub fn new(id: impl Into<ElementId>, store: Entity<ToastStackStore>) -> Self {
Self {
id: id.into(),
store,
label: "Notifications".into(),
position: ToastPosition::BottomRight,
contained: false,
visible_toasts: 3,
hotkey: true,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn position(mut self, position: ToastPosition) -> Self {
self.position = position;
self
}
pub fn contained(mut self, contained: bool) -> Self {
self.contained = contained;
self
}
pub fn visible_toasts(mut self, visible_toasts: usize) -> Self {
self.visible_toasts = visible_toasts.max(1);
self
}
pub fn hotkey(mut self, hotkey: bool) -> Self {
self.hotkey = hotkey;
self
}
}
impl RenderOnce for ToastStack {
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 view_state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-toast-stack-view".into());
let view_state = window.use_keyed_state(view_state_id, cx, |_, cx| {
ToastViewState::new(cx.focus_handle())
});
let view_snap = view_state.read(cx).clone();
let count = self.store.read(cx).count();
let expanded = count > 0 && (view_snap.hovered || view_snap.focused);
let paused = expanded || view_snap.dragging_id.is_some();
let exit_secs = motion.duration.exit.as_secs_f64();
let keep_ticking = self.store.update(cx, |s, _| s.tick(now, paused, exit_secs));
if keep_ticking {
window.request_animation_frame();
}
let (toasts, exiting, heights) = {
let s = self.store.read(cx);
(s.toasts.clone(), s.exiting.clone(), s.heights.clone())
};
if toasts.is_empty() && exiting.is_empty() {
return div().id(self.id);
}
let target_stack_width = toasts
.iter()
.take(self.visible_toasts)
.map(ToastRecord::estimated_width)
.chain(exiting.iter().map(|ex| ex.record.estimated_width()))
.fold(TOAST_STACK_MIN_WIDTH, f32::max);
let animated_stack_width = if reduced {
target_stack_width
} else {
arc_spring_with_options(
(self.id.clone(), "list-width"),
target_stack_width,
SpringOptions::new(motion.spring.smooth).with_initial_value(target_stack_width),
window,
cx,
)
.value
};
let (targets, list_height) = layout_stack(&toasts, &heights, expanded, self.visible_toasts);
let animated_list_height = arc_spring_with_options(
(self.id.clone(), "list-height"),
list_height,
SpringOptions::new(motion.spring.smooth),
window,
cx,
)
.value;
let default_label = if self.label == "Notifications" {
SharedString::from(cx.arc_locale().ui_strings().notifications)
} else {
self.label.clone()
};
let region_label: SharedString = if self.hotkey {
SharedString::from(format!("{default_label} (Alt+T)"))
} else {
default_label
};
let view_hover = view_state.clone();
let view_key = view_state.clone();
let store_key = self.store.clone();
let hotkey_enabled = self.hotkey;
let focus_handle = view_snap.focus_handle.clone();
let dragging_id = view_snap.dragging_id.clone();
let view_move = view_state.clone();
let view_up = view_state.clone();
let store_up = self.store.clone();
let visible_toasts = self.visible_toasts;
let drag_toast_width = animated_stack_width.max(TOAST_STACK_MIN_WIDTH);
let drag_capture_canvas = canvas(
|_, _, _| {},
move |_, _, window, _| {
if let Some(active_drag_id) = dragging_id.clone() {
let vm = view_move.clone();
let drag_id_m = active_drag_id.clone();
window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
let now_m = motion_now(cx);
vm.update(cx, |v, _| {
if v.dragging_id.as_ref() != Some(&drag_id_m) {
return;
}
if let Some(raw) = v.drag_tracker.update_x(
f32::from(event.position.x),
f32::from(event.position.y),
now_m,
true,
) {
let clamped = if raw >= 0.0 {
raw
} else {
-rubber_band(-raw, drag_toast_width)
};
v.drag_x.insert(drag_id_m.clone(), clamped);
}
});
window.refresh();
});
let vu = view_up.clone();
let su = store_up.clone();
let drag_id_u = active_drag_id;
window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
if !phase.bubble() || event.button != MouseButton::Left {
return;
}
let now_u = motion_now(cx);
let (offset, velocity) = vu.update(cx, |v, _| {
if v.dragging_id.as_ref() != Some(&drag_id_u) {
return (0.0, 0.0);
}
v.dragging_id = None;
let off = v.drag_x.remove(&drag_id_u).unwrap_or(0.0);
let vel = v.drag_tracker.release_velocity(now_u);
(off, vel)
});
if offset > 0.0
&& velocity > -200.0
&& offset + project_deceleration(velocity) > drag_toast_width * 0.4
{
su.update(cx, |s, _| {
s.dismiss_with_swipe(
drag_id_u.as_ref(),
now_u,
true,
velocity.max(0.0),
expanded,
visible_toasts,
);
});
}
window.refresh();
});
}
},
)
.absolute()
.inset_0();
let mut list = div()
.id(ElementId::NamedChild(self.id.clone().into(), "list".into()))
.test_support()
.track_focus(&focus_handle)
.role(Role::Region)
.aria_label(region_label)
.relative()
.w(px(animated_stack_width))
.h(px(animated_list_height.max(1.0)))
.on_hover(move |hovered, window, cx| {
view_hover.update(cx, |v, _| v.hovered = *hovered);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" {
let now_k = motion_now(cx);
store_key.update(cx, |s, _| {
if let Some(front) = s.toasts.first().map(|t| t.id.clone()) {
s.dismiss(front.as_ref(), now_k);
}
});
window.refresh();
} else if hotkey_enabled
&& event.keystroke.modifiers.alt
&& !event.keystroke.modifiers.control
&& !event.keystroke.modifiers.platform
&& event.keystroke.key.eq_ignore_ascii_case("t")
{
view_key.update(cx, |v, _| v.focused = true);
window.refresh();
}
})
.child(drag_capture_canvas);
for (index, toast) in toasts.iter().enumerate().rev() {
let target = targets[index];
let front = index == 0;
let hidden = index >= self.visible_toasts;
let spring_spec = if expanded {
motion.spring.morph
} else {
motion.spring.smooth
};
let y = arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("y-{}", toast.id)),
),
target.y,
SpringOptions::new(spring_spec).with_initial_value(target.y + target.height),
window,
cx,
)
.value;
let scale = arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("s-{}", toast.id)),
),
target.scale,
SpringOptions::new(spring_spec),
window,
cx,
)
.value;
let height = arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("h-{}", toast.id)),
),
target.height,
SpringOptions::new(spring_spec),
window,
cx,
)
.value;
let is_dragging_this = view_snap.dragging_id.as_ref() == Some(&toast.id);
let drag_x_target = view_snap.drag_x.get(&toast.id).copied().unwrap_or(0.0);
let x = arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("x-{}", toast.id)),
),
drag_x_target,
SpringOptions::new(motion.spring.snappy).with_travel(!is_dragging_this),
window,
cx,
)
.value;
let swipe_fade = if x > 0.0 {
1.0 - (x / SWIPE_FADE).min(1.0) * 0.75
} else {
1.0
};
let enter_t = ((now - toast.entered_at_secs) / motion.duration.standard.as_secs_f64())
.clamp(0.0, 1.0) as f32;
let enter_op = if reduced {
1.0
} else {
arc_motion::CubicBezier::from_spec(motion.ease.enter).sample(enter_t)
};
if enter_t < 1.0 && !reduced {
window.request_animation_frame();
}
let base_op = arc_transition(
(
self.id.clone(),
SharedString::from(format!("op-{}", toast.id)),
),
target.opacity,
motion.duration.fast,
motion.ease.standard,
window,
cx,
);
let content_op = arc_transition(
(
self.id.clone(),
SharedString::from(format!("cop-{}", toast.id)),
),
target.content_opacity,
motion.duration.fast,
motion.ease.standard,
window,
cx,
);
let card_opacity = (base_op * enter_op * swipe_fade).clamp(0.0, 1.0);
let swap_t = ((now - toast.updated_at_secs) / motion.duration.standard.as_secs_f64())
.clamp(0.0, 1.0) as f32;
let swap_blur = if toast.version > 0 && swap_t < 1.0 {
window.request_animation_frame();
BlurFallback::evaluate(px((1.0 - swap_t) * f32::from(motion.blur.soft)), reduced)
} else {
BlurFallback::evaluate(px(0.0), reduced)
};
let card_bg = if !front && !expanded {
colors.surface_muted
} else {
colors.surface_raised
};
let card_shadow = if front || expanded {
Shadows::floating(theme.mode)
} else {
Shadows::raised(theme.mode)
};
let scaled_w = animated_stack_width * scale;
let inset_x = (animated_stack_width - scaled_w) * 0.5;
let bottom_offset = -y;
let tid = toast.id.clone();
let store_dismiss = self.store.clone();
let tid_dismiss = tid.clone();
let store_action = self.store.clone();
let tid_action = tid.clone();
let view_down = view_state.clone();
let tid_down = tid.clone();
let icon_color = match toast.kind {
ToastType::Success => colors.success,
ToastType::Info => colors.info,
ToastType::Warning => colors.warning,
ToastType::Error => colors.danger,
ToastType::Loading => colors.text_muted,
};
let icon_el = match toast.kind {
ToastType::Success => div()
.text_color(icon_color)
.child(IconName::CircleCheck)
.into_any_element(),
ToastType::Info => div()
.text_color(icon_color)
.child(IconName::Info)
.into_any_element(),
ToastType::Warning => div()
.text_color(icon_color)
.child(IconName::TriangleAlert)
.into_any_element(),
ToastType::Error => div()
.text_color(icon_color)
.child(IconName::CircleX)
.into_any_element(),
ToastType::Loading => {
let spin_angle = if reduced {
0.0
} else {
((now / 0.8) % 1.0) as f32 * std::f32::consts::TAU
};
let spinner_color = icon_color;
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_p = f32::from(rect.origin.x) + f32::from(rect.size.width) * 0.5;
let cy_p = f32::from(rect.origin.y) + f32::from(rect.size.height) * 0.5;
let r = 6.5_f32;
let mut builder = PathBuilder::stroke(px(1.75));
let segs = 18usize;
let sweep = std::f32::consts::TAU * 0.75;
for i in 0..=segs {
let a = spin_angle + sweep * (i as f32 / segs as f32);
let pt = point(px(cx_p + r * a.cos()), px(cy_p + r * a.sin()));
if i == 0 {
builder.move_to(pt);
} else {
builder.line_to(pt);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, spinner_color);
}
},
)
.w(px(18.0))
.h(px(18.0))
.into_any_element()
}
};
let card_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("card-{}", toast.id)),
);
let close_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("close-{}", toast.id)),
);
let action_id = ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("action-{}", toast.id)),
);
let card = div()
.id(card_id)
.test_support()
.absolute()
.left(px(inset_x + x))
.bottom(px(bottom_offset))
.w(px(scaled_w))
.h(px(height.max(44.0)))
.overflow_hidden()
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(card_bg)
.shadow(card_shadow)
.opacity(card_opacity)
.when(is_dragging_this, |this| {
this.cursor(gpui_kit::CursorStyle::ClosedHand)
})
.on_mouse_down(MouseButton::Left, move |event, window, cx| {
if hidden {
return;
}
let now_d = motion_now(cx);
view_down.update(cx, |v, _| {
v.dragging_id = Some(tid_down.clone());
let origin = v.drag_x.get(&tid_down).copied().unwrap_or(0.0);
v.drag_tracker.begin(
f32::from(event.position.x),
f32::from(event.position.y),
origin,
now_d,
);
});
window.refresh();
})
.child(
div()
.w_full()
.flex()
.flex_row()
.items_start()
.gap(Spacing::S3)
.pt(Spacing::S3)
.pb(Spacing::S3)
.pl(Spacing::S4)
.pr(Spacing::S3)
.opacity((content_op * swap_blur.opacity_multiplier).clamp(0.0, 1.0))
.mt(swap_blur.offset_y)
.child(
div()
.flex_none()
.w(px(18.0))
.h(px(20.0))
.flex()
.items_center()
.justify_center()
.child(icon_el),
)
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(toast.title.clone())
.when_some(toast.description.clone(), |this, desc| {
this.child(
div()
.mt(px(2.0))
.text_color(colors.text_secondary)
.child(desc),
)
}),
)
.when_some(toast.action.clone(), |this, action| {
let hover_bg = colors.surface_muted;
let hover_border = colors.border_strong;
this.child(
div()
.id(action_id)
.test_support()
.flex_none()
.h(px(28.0))
.px(Spacing::S3)
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.hover(move |s| s.bg(hover_bg).border_color(hover_border))
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| {
cx.stop_propagation();
})
.on_click(move |_, window, cx| {
ToastStackStore::invoke_action(
&store_action,
&tid_action,
window,
cx,
);
window.refresh();
})
.child(action.label),
)
})
.child({
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
let dismiss_label = cx.arc_locale().ui_strings().dismiss_notification;
div()
.id(close_id)
.test_support()
.role(Role::Button)
.aria_label(dismiss_label)
.flex_none()
.w(px(28.0))
.h(px(28.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.text_color(colors.text_muted)
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
.cursor_pointer()
.on_mouse_down(MouseButton::Left, |_, _, cx| {
cx.stop_propagation();
})
.on_click(move |_, window, cx| {
let now_c = motion_now(cx);
store_dismiss.update(cx, |s, _| {
s.dismiss(tid_dismiss.as_ref(), now_c);
});
window.refresh();
})
.child(IconName::Close)
}),
);
list = list.child(card);
}
for ex in &exiting {
let elapsed = (now - ex.exited_at_secs).max(0.0);
let exit_dur = if ex.swiped { 0.22 } else { exit_secs };
let t = (elapsed / exit_dur).clamp(0.0, 1.0) as f32;
let op = (1.0 - t).clamp(0.0, 1.0);
let (dx, dy, scale) = if reduced {
(0.0, ex.last_target.y, ex.last_target.scale)
} else if ex.swiped {
let throw_x = arc_motion::SpringSolver::new(
THROW_SPRING.as_physical(),
0.0,
f64::from(animated_stack_width + 40.0),
f64::from(ex.throw_velocity),
)
.sample(elapsed)
.value;
(throw_x, ex.last_target.y, ex.last_target.scale)
} else {
(
0.0,
ex.last_target.y + 10.0 * t,
ex.last_target.scale * (1.0 - 0.04 * t),
)
};
let scaled_w = animated_stack_width * scale;
let inset_x = (animated_stack_width - scaled_w) * 0.5;
let ex_icon_color = match ex.record.kind {
ToastType::Success => colors.success,
ToastType::Info => colors.info,
ToastType::Warning => colors.warning,
ToastType::Error => colors.danger,
ToastType::Loading => colors.text_muted,
};
let ex_icon = match ex.record.kind {
ToastType::Success => IconName::CircleCheck,
ToastType::Info | ToastType::Loading => IconName::Info,
ToastType::Warning => IconName::TriangleAlert,
ToastType::Error => IconName::CircleX,
};
list = list.child(
div()
.absolute()
.left(px(inset_x + dx))
.bottom(px(-dy))
.w(px(scaled_w))
.h(px(ex.last_target.height.max(44.0)))
.overflow_hidden()
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::raised(theme.mode))
.opacity(op)
.flex()
.flex_row()
.items_start()
.gap(Spacing::S3)
.pt(Spacing::S3)
.pb(Spacing::S3)
.pl(Spacing::S4)
.pr(Spacing::S3)
.child(div().flex_none().text_color(ex_icon_color).child(ex_icon))
.child(
div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(ex.record.title.clone())
.when_some(ex.record.description.clone(), |this, desc| {
this.child(
div()
.mt(px(2.0))
.text_color(colors.text_secondary)
.child(desc),
)
}),
),
);
}
let inset = if self.contained {
Spacing::S4
} else {
Spacing::S6
};
let mut viewport = div()
.id(self.id)
.absolute()
.bottom(inset)
.flex()
.justify_center();
viewport = match self.position {
ToastPosition::BottomRight => viewport.right(inset),
ToastPosition::BottomLeft => viewport.left(inset),
ToastPosition::BottomCenter => viewport.left_0().right_0(),
};
viewport.child(list)
}
}
#[cfg(test)]
mod tests {
use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
use gpui_kit::{
AppContext as _, Context, Render, TestAppContext, div, px, test::TestWindowExt as _,
};
use super::*;
struct ToastHost {
store: Entity<ToastStackStore>,
}
impl Render for ToastHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().relative().w(px(640.0)).h(px(420.0)).child(
ToastStack::new("demo-toasts", self.store.clone())
.contained(true)
.visible_toasts(3),
)
}
}
#[test]
fn layout_stack_collapsed_and_expanded_geometry_match_arc() {
let mut store = ToastStackStore::default();
store.toast(ToastOptions::new("First"), 0.0);
store.toast(ToastOptions::new("Second").description("Detail"), 1.0);
store.toast(ToastOptions::new("Third"), 2.0);
store.toast(ToastOptions::new("Fourth"), 3.0);
let heights = HashMap::new();
let (collapsed, collapsed_h) = layout_stack(store.toasts(), &heights, false, 3);
assert_eq!(collapsed.len(), 4);
assert_eq!(collapsed[0].y, 0.0);
assert_eq!(collapsed[0].scale, 1.0);
assert_eq!(collapsed[0].content_opacity, 1.0);
assert_eq!(collapsed[1].y, -PEEK);
assert!((collapsed[1].scale - 0.95).abs() < 1e-5);
assert_eq!(collapsed[1].content_opacity, 0.0);
assert_eq!(collapsed[2].y, -2.0 * PEEK);
assert!((collapsed[2].scale - 0.90).abs() < 1e-5);
assert_eq!(collapsed[3].opacity, 0.0);
assert_eq!(collapsed_h, DEFAULT_TOAST_HEIGHT + 2.0 * PEEK);
let (expanded, expanded_h) = layout_stack(store.toasts(), &heights, true, 3);
assert_eq!(expanded[0].y, 0.0);
assert_eq!(expanded[1].scale, 1.0);
assert_eq!(expanded[1].content_opacity, 1.0);
assert!(expanded[1].y < -DEFAULT_TOAST_HEIGHT);
assert!(expanded_h > collapsed_h);
}
#[test]
fn toast_stack_item_width_adapts_to_copy_and_action() {
let w_short = toast_stack_item_width("已保存", None, None);
let w_mid = toast_stack_item_width("会话已归档", None, Some("撤销"));
let w_long = toast_stack_item_width(
"不能连接到自身或构成环路",
Some("请重新选择目标输入端口,确保工作流拓扑保持有向无环图。"),
None,
);
assert!((w_short - TOAST_STACK_MIN_WIDTH).abs() < 1e-3);
assert!(w_mid > w_short && w_mid < TOAST_STACK_MAX_WIDTH);
assert!((w_long - TOAST_STACK_MAX_WIDTH).abs() < 1e-3);
}
#[gpui_kit::test]
fn toast_stack_enqueue_update_dismiss_and_timer_pause(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Green, cx);
});
let store = cx.new(|_| ToastStackStore::new(Duration::from_millis(2000), 12));
let (_view, cx) = cx.add_window_view(|_, _| ToastHost {
store: store.clone(),
});
let id = cx.update(|_, cx| {
store.update(cx, |s, _| {
s.toast(
ToastOptions::new("Uploading file…").kind(ToastType::Loading),
0.0,
)
})
});
cx.update(|window, cx| {
window.render_frame(cx);
assert_eq!(store.read(cx).count(), 1);
assert!(store.read(cx).toasts()[0].remaining_secs.is_none());
store.update(cx, |s, _| {
s.update(
id.as_ref(),
ToastPatch {
kind: Some(ToastType::Success),
title: Some("Uploaded".into()),
..Default::default()
},
1.0,
);
});
window.render_frame(cx);
let t = &store.read(cx).toasts()[0];
assert_eq!(t.kind, ToastType::Success);
assert_eq!(t.version, 1);
assert!(t.remaining_secs.is_some());
let close_id = ElementId::NamedChild(
ElementId::from("demo-toasts").into(),
SharedString::from(format!("close-{id}")),
);
window.click(close_id, cx);
assert_eq!(store.read(cx).count(), 0);
});
}
#[test]
fn toast_stack_expand_morph_curve_matches_motion_within_5_percent() {
let spec = ArcMotionTokens::DEFAULT.spring.morph;
let solver = SpringSolver::new(spec, -14.0, -76.0, 0.0);
let omega0 = std::f64::consts::TAU / (0.42 * 1.2);
let mut actual = CurveTrace::new("toast-stack", "item_y");
let mut expected = CurveTrace::new("toast-stack", "item_y");
for frame in 0..=45 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let ref_y = -76.0 - (-omega0 * t).exp() * (-62.0 + omega0 * -62.0 * t);
expected.push(t_ms, ref_y);
actual.push(t_ms, f64::from(solver.sample(t).value));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "ToastStack morph curve error {err:.3}% >= 5%");
}
}