Brief notifications that stack in the corner and dismiss themselves.
use gpui::{div, prelude::*};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::toast::{toast, Toast, Toaster};
pub fn toast_demo() -> impl IntoElement {
div()
.child(
Button::new("show-toast", "Show toast")
.variant(ButtonVariant::Outline)
.on_click(|_, _, cx| {
toast(
Toast::new("Event has been created")
.description("Sunday, December 3 at 9:00 AM")
.action("Undo", |_, _, _| println!("undo")),
cx,
);
}),
)
// Render once near the root of your app; it draws over everything else.
.child(Toaster::new())
}Installation
Copies src/ui/toast.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/toast.rs.src/ui/toast.rs use std::{ cell::OnceCell, collections::{HashMap, HashSet}, future::Future, rc::Rc, time::Duration, }; use gpui::{ anchored, deferred, div, point, prelude::*, px, svg, Anchor, AnimationExt, AnyElement, App, ClickEvent, FontWeight, Global, Hsla, Pixels, SharedString, SpringAnimation, SpringConfig, TimedTransformation, Transformation, Window, }; use crate::theme::ActiveTheme; use crate::ui::button::{Button, ButtonSize}; use crate::icons::{CIRCLE_CHECK, INFO, LOADER_CIRCLE, OCTAGON_X, TRIANGLE_ALERT}; const MONO: &str = "Geist Mono"; /// Sonner's default lifetime. const DURATION: Duration = Duration::from_secs(4); /// Older toasts are dropped from view once this many are on screen. const MAX_VISIBLE: usize = 3; /// One turn of the loading icon. const TURN: Duration = Duration::from_millis(1000); /// Sonner moves toasts (in, and along the stack) over 400ms. const ENTER: Duration = Duration::from_millis(400); /// Sonner unmounts a dismissed toast 200ms after it starts leaving. const EXIT: Duration = Duration::from_millis(200); /// Sonner's gap: how far each older toast peeks above the one in front when the stack is /// collapsed, and the space between toasts when it is expanded. const GAP: Pixels = px(14.0); /// Toast width. const WIDTH: Pixels = px(356.0); /// Each older toast in a collapsed stack is this much narrower (sonner scales by 5%). const STEP_SCALE: f32 = 0.05; /// Height assumed for a toast before it has been laid out once. const FALLBACK_HEIGHT: Pixels = px(64.0); /// Critically damped, settling in about 400ms like sonner's `transform 400ms ease`. const STACK_SPRING: SpringConfig = SpringConfig::new(170.0, 26.0, 1.0); /// CSS `ease`, sonner's transition timing. fn ease(t: f32) -> f32 { let (x1, y1, x2, y2) = (0.25, 0.1, 0.25, 1.0); let sample = |a: f32, b: f32, s: f32| { let r = 1.0 - s; 3.0 * r * r * s * a + 3.0 * r * s * s * b + s * s * s }; let t = t.clamp(0.0, 1.0); let (mut lo, mut hi, mut s) = (0.0_f32, 1.0_f32, t); for _ in 0..24 { let x = sample(x1, x2, s); if (x - t).abs() < 1e-4 { break; } if x < t { lo = s; } else { hi = s; } s = (lo + hi) / 2.0; } sample(y1, y2, s) } /// Time on GPUI's clock since the first call. GPUI doesn't export its `Instant`, so moments are /// kept as offsets from one reading. fn clock(cx: &App) -> Duration { type SinceEpoch = Box<dyn Fn(&App) -> Duration>; thread_local! { static SINCE_EPOCH: OnceCell<SinceEpoch> = const { OnceCell::new() }; } SINCE_EPOCH.with(|cell| { let since = cell.get_or_init(|| { let epoch = cx.background_executor().now(); Box::new(move |cx: &App| cx.background_executor().now().saturating_duration_since(epoch)) }); since(cx) }) } /// A toast's eased 0..1 presence. An interrupted run continues from where it is. #[derive(Clone, Copy, Default)] struct Presence { shown: bool, from: f32, since: Duration, } impl Presence { fn value(&self, now: Duration) -> f32 { let target = if self.shown { 1.0 } else { 0.0 }; let span = (target - self.from).abs(); let duration = if self.shown { ENTER } else { EXIT }.as_secs_f32() * span; if span == 0.0 || duration <= 0.0 { return target; } let t = (now.saturating_sub(self.since).as_secs_f32() / duration).min(1.0); self.from + (target - self.from) * ease(t) } /// Returns the value now and whether it is still moving. fn update(&mut self, shown: bool, cx: &App) -> (f32, bool) { let now = clock(cx); if shown != self.shown { self.from = self.value(now); self.shown = shown; self.since = now; } if cx.reduce_motion() { self.from = if shown { 1.0 } else { 0.0 }; } let value = self.value(now); (value, value != if shown { 1.0 } else { 0.0 }) } } /// How far a toast is in or out, and its height when last laid out, which its slot in the /// stack grows and shrinks by so the toasts around it glide instead of jumping. #[derive(Default)] struct ToastMotion { presence: Presence, height: Option<Pixels>, } type ActionHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// The status a toast reports. Every kind but `Default` shows an icon before the title. #[derive(Clone, Copy, Default, PartialEq)] pub enum ToastKind { /// Title and description only. #[default] Default, /// A check mark, for work that finished. Success, /// An "i" in a circle, for neutral news. Info, /// A warning triangle, for something to look at. Warning, /// A crossed octagon, for something that failed. Error, /// A spinning loader, for work still running. See [`toast_promise`]. Loading, } impl ToastKind { fn icon(self, color: Hsla) -> Option<AnyElement> { let data = match self { ToastKind::Default => return None, ToastKind::Success => CIRCLE_CHECK, ToastKind::Info => INFO, ToastKind::Warning => TRIANGLE_ALERT, ToastKind::Error => OCTAGON_X, ToastKind::Loading => LOADER_CIRCLE, }; let icon = svg().data(data).flex_none().size(px(16.0)).text_color(color); Some(if self == ToastKind::Loading { // Spins the painted sprite each frame, so the toast itself isn't re-rendered. icon.with_timed_transformation(TimedTransformation::rotation(TURN, Transformation::default())) .into_any_element() } else { icon.into_any_element() }) } } /// A message for [`toast`]. #[derive(Clone)] pub struct Toast { title: SharedString, description: Option<SharedString>, code: Option<SharedString>, action: Option<(SharedString, ActionHandler)>, kind: ToastKind, } impl Toast { pub fn new(title: impl Into<SharedString>) -> Self { Self { title: title.into(), description: None, code: None, action: None, kind: ToastKind::default(), } } /// Sets the status icon shown before the title. pub fn kind(mut self, kind: ToastKind) -> Self { self.kind = kind; self } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// A block of monospaced text under the description, with its line breaks and /// indentation kept, like shadcn's form demos showing the submitted values as JSON. pub fn code(mut self, code: impl Into<SharedString>) -> Self { self.code = Some(code.into()); self } /// A button on the toast, such as "Undo". Clicking it also dismisses the toast. pub fn action( mut self, label: impl Into<SharedString>, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> Self { self.action = Some((label.into(), Rc::new(handler))); self } } /// Every live toast, shared by whoever calls [`toast`] and the one [`Toaster`] that draws them. #[derive(Default)] struct ToastQueue { toasts: Vec<(usize, Toast)>, next_id: usize, /// Dismissed toasts still animating out; they leave `toasts` once they have. dismissed: HashSet<usize>, motion: HashMap<usize, ToastMotion>, /// The pointer is over the stack, so it fans out into a list (sonner's expanded state). expanded: bool, } impl Global for ToastQueue {} impl ToastQueue { /// Advances every toast's motion and drops the dismissed ones that finished leaving. /// Returns what to draw this frame (id, toast, presence, height) and whether anything moves. #[allow(clippy::type_complexity)] fn frame(&mut self, cx: &App) -> (Vec<(usize, Toast, f32, Option<Pixels>)>, bool) { let live: Vec<usize> = self .toasts .iter() .map(|(id, _)| *id) .filter(|id| !self.dismissed.contains(id)) .collect(); // Older toasts past the limit fold away, and come back when newer ones go. let shown = &live[live.len().saturating_sub(MAX_VISIBLE)..]; let mut rows = Vec::new(); let mut animating = false; let mut finished = Vec::new(); for (id, toast) in &self.toasts { let motion = self.motion.entry(*id).or_default(); let is_shown = shown.contains(id); let (value, moving) = motion.presence.update(is_shown, cx); animating |= moving; if is_shown || moving { rows.push((*id, toast.clone(), value, motion.height)); } else if self.dismissed.contains(id) { finished.push(*id); } } for id in finished { self.toasts.retain(|(toast_id, _)| *toast_id != id); self.dismissed.remove(&id); self.motion.remove(&id); } (rows, animating) } } /// Shows `toast` in the app's [`Toaster`] and dismisses it after four seconds. pub fn toast(toast: Toast, cx: &mut App) { let id = push(toast, cx); dismiss_later(id, cx); } /// Shows `loading` until `task` finishes, then swaps in the toast it resolves to and dismisses /// that after four seconds. `loading` shows a spinner unless it already has a kind; resolve to /// a `Success` or `Error` toast to report how it went. pub fn toast_promise(loading: Toast, task: impl Future<Output = Toast> + 'static, cx: &mut App) { let loading = if loading.kind == ToastKind::Default { loading.kind(ToastKind::Loading) } else { loading }; let id = push(loading, cx); cx.spawn(async move |cx| { let result = task.await; cx.update(|cx| { replace(id, result, cx); dismiss_later(id, cx); }); }) .detach(); } fn push(toast: Toast, cx: &mut App) -> usize { let queue = cx.default_global::<ToastQueue>(); let id = queue.next_id; queue.next_id += 1; queue.toasts.push((id, toast)); // A Global has no observers, so redraw explicitly. cx.refresh_windows(); id } /// Updates a toast in place. Does nothing if it was already dismissed. fn replace(id: usize, toast: Toast, cx: &mut App) { if let Some(queue) = cx.try_global::<ToastQueue>() && queue.toasts.iter().any(|(toast_id, _)| *toast_id == id) && !queue.dismissed.contains(&id) { let queue = cx.global_mut::<ToastQueue>(); if let Some(entry) = queue.toasts.iter_mut().find(|(toast_id, _)| *toast_id == id) { entry.1 = toast; } cx.refresh_windows(); } } fn dismiss_later(id: usize, cx: &mut App) { cx.spawn(async move |cx| { cx.background_executor().timer(DURATION).await; cx.update(|cx| dismiss(id, cx)); }) .detach(); } /// Removes a toast before its timer runs out. It slides and fades out, and the toasts around /// it close the gap. pub fn dismiss(id: usize, cx: &mut App) { if let Some(queue) = cx.try_global::<ToastQueue>() && queue.toasts.iter().any(|(toast_id, _)| *toast_id == id) && !queue.dismissed.contains(&id) { cx.global_mut::<ToastQueue>().dismissed.insert(id); cx.refresh_windows(); } } /// Draws the toasts in the bottom-right corner of the window. Render it once, anywhere. #[derive(IntoElement, Default)] pub struct Toaster; impl Toaster { pub fn new() -> Self { Self } } impl RenderOnce for Toaster { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let (toasts, animating) = if cx.has_global::<ToastQueue>() { cx.update_global::<ToastQueue, _>(|queue, cx| queue.frame(cx)) } else { (Vec::new(), false) }; if animating { window.request_animation_frame(); } // Still up while the last toast animates out. if !toasts.is_empty() { crate::theme::mark_overlay(cx); } let theme = cx.theme(); let viewport = window.viewport_size(); let margin = px(16.0); let expanded = cx.try_global::<ToastQueue>().is_some_and(|queue| queue.expanded); // Newest first: depth 0 is the toast in front. let rows: Vec<_> = toasts.into_iter().rev().enumerate().collect(); let height_of = |height: Option<Pixels>| height.unwrap_or(FALLBACK_HEIGHT); let front_height = rows.first().map_or(FALLBACK_HEIGHT, |(_, row)| height_of(row.3)); // Expanded, each toast sits above every newer one; collapsed, each peeks GAP above the // one in front of it and takes the front toast's height, like sonner. let mut expanded_offsets = Vec::with_capacity(rows.len()); let mut offset = px(0.0); for (_, (_, _, shown, height)) in &rows { expanded_offsets.push(offset); offset += (height_of(*height) + GAP) * shown.clamp(0.0, 1.0); } let stack_height = if expanded { (offset - GAP).max(front_height) } else { front_height + GAP * rows.len().saturating_sub(1).min(MAX_VISIBLE - 1) as f32 }; // Painted oldest first, so the newest toast ends up on top of the deck. let mut rows = rows; rows.reverse(); let stack = div() .id("toaster") // Blocks the page behind the toasts; the cards themselves don't, so hovering any of // them still reaches this stack's hover handler. .occlude() .relative() .w(WIDTH) .h(stack_height) .on_hover(|hovered, window, cx| { if cx.has_global::<ToastQueue>() { cx.global_mut::<ToastQueue>().expanded = *hovered; window.refresh(); } }) .children(rows.into_iter().map(|(depth, (id, toast, shown, height))| { let action = toast.action.map(|(label, handler)| { Button::new(("toast-action", id), label) .size(ButtonSize::Sm) .on_click(move |event, window, cx| { handler(event, window, cx); dismiss(id, cx); }) }); let own_height = height_of(height); let content = div() .flex_1() // Without a zero minimum width, a long description widens the toast // instead of wrapping. .min_w_0() .flex() .items_center() .gap_4() .children(toast.kind.icon(theme.foreground)) .child( div() .flex_1() .min_w_0() .flex() .flex_col() .gap_1() .child(div().font_weight(FontWeight::SEMIBOLD).child(toast.title)) .when_some(toast.description, |this, description| { this.child(div().text_color(theme.muted_foreground).child(description)) }) .when_some(toast.code, |this, code| { this.child( div() .mt_1() .w_full() .p_3() .rounded(theme.radius) .bg(theme.muted) .font_family(MONO) .text_xs() .line_height(px(18.)) .text_color(theme.foreground) .child(code), ) }), ) .children(action) // Older toasts' text hides while the stack is collapsed; their cards peek out. .with_spring( ("toast-reveal", id), SpringAnimation::new(STACK_SPRING).to(expanded || depth == 0), |this, phase| this.opacity(phase.interpolate_clamped(0.0, 1.0)), ); let card = div() .id(("toast", id)) .flex_none() .w_full() .flex() .p_4() .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .text_color(theme.foreground) .text_sm() .shadow_lg() .opacity(shown.clamp(0.0, 1.0)); let depth_f = depth as f32; let target_offset = if expanded { expanded_offsets[depth] } else { GAP * depth_f }; let target_scale = if expanded { 1.0 } else { (1.0 - STEP_SCALE * depth_f).max(0.0) }; let target_height = if expanded || depth == 0 { own_height } else { front_height }; // Enter rises from below by the toast's own height; exit sinks the same way. let rise = own_height * (1.0 - shown.clamp(0.0, 1.0)); // Outer: where the toast sits in the stack. Middle: its width (sonner's scale). // Inner: its height, clipped to the front toast's while collapsed. div() .absolute() .right_0() .bottom_0() .w(WIDTH) .flex() .justify_center() .child( div() .flex() .flex_col() .child( div() .flex() .flex_col() .justify_end() .overflow_hidden() .rounded(theme.radius) .on_children_prepainted(move |bounds, window, cx| { let Some(measured) = bounds.first().map(|bounds| bounds.size.height) else { return; }; if !cx.has_global::<ToastQueue>() { return; } let queue = cx.global_mut::<ToastQueue>(); if let Some(motion) = queue.motion.get_mut(&id) && motion.height != Some(measured) { motion.height = Some(measured); window.refresh(); } }) .child(card.child(content)) .with_spring( ("toast-height", id), SpringAnimation::new(STACK_SPRING).to(target_height), |this, height| this.h(height), ), ) .with_spring( ("toast-scale", id), SpringAnimation::new(STACK_SPRING).to(target_scale), |this, scale| this.w(WIDTH * scale), ), ) .with_spring( ("toast-offset", id), SpringAnimation::new(STACK_SPRING).to(target_offset), move |this, offset| this.bottom(offset - rise), ) })); deferred( anchored() .anchor(Anchor::BottomRight) .position(point(viewport.width - margin, viewport.height - margin)) .child(stack), ) .with_priority(4) } }Register the module
// src/ui/mod.rs pub mod toast;
Usage
use crate::ui::toast::*;Examples
Types
kind adds a status icon: ToastKind::Success, Info, Warning or Error.
use gpui::{div, prelude::*, px};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::toast::{toast, Toast, ToastKind, Toaster};
const KINDS: [(&str, ToastKind, &str); 5] = [
("Default", ToastKind::Default, "Event has been created"),
("Success", ToastKind::Success, "Event has been created"),
("Info", ToastKind::Info, "Be at the area 10 minutes before the event time"),
("Warning", ToastKind::Warning, "Event start time cannot be earlier than 8am"),
("Error", ToastKind::Error, "Event has not been created"),
];
pub fn toast_types() -> impl IntoElement {
div()
.w(px(672.0))
.flex()
.justify_center()
.flex_wrap()
.gap_2()
.children(KINDS.into_iter().enumerate().map(|(ix, (label, kind, title))| {
Button::new(("toast-type", ix), label)
.variant(ButtonVariant::Outline)
.on_click(move |_, _, cx| toast(Toast::new(title).kind(kind), cx))
}))
// Render once near the root of your app; it draws over everything else.
.child(Toaster::new())
}Action
action adds a button to the toast, such as "Undo". Clicking it runs the handler and dismisses the toast.
use gpui::{div, prelude::*, px, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::toast::{toast, Toast, Toaster};
#[derive(Default)]
pub struct ToastAction {
undone: usize,
}
impl Render for ToastAction {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let view = cx.entity().downgrade();
div()
.w(px(672.0))
.flex()
.justify_center()
.items_center()
.gap_4()
.child(
Button::new("toast-action-trigger", "Archive email")
.variant(ButtonVariant::Outline)
.on_click(move |_, _, cx| {
let view = view.clone();
toast(
Toast::new("Email archived").action("Undo", move |_, _, cx| {
// The toast can outlive the view, so hold it weakly.
view.update(cx, |this, cx| {
this.undone += 1;
cx.notify();
})
.ok();
}),
cx,
);
}),
)
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(format!("Undone {} times", self.undone)),
)
.child(Toaster::new())
}
}Promise
toast_promise shows a loading toast while a task runs, then replaces it with the toast the task returns.
use std::time::Duration;
use gpui::{div, prelude::*, px};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::toast::{toast_promise, Toast, ToastKind, Toaster};
pub fn toast_promise_example() -> impl IntoElement {
div()
.w(px(672.0))
.flex()
.justify_center()
.child(
Button::new("toast-promise-trigger", "Create event")
.variant(ButtonVariant::Outline)
.on_click(|_, _, cx| {
// Stands in for real work, such as a network request.
let request = cx.background_executor().timer(Duration::from_secs(2));
toast_promise(
Toast::new("Creating event..."),
async move {
request.await;
Toast::new("Event has been created")
.description("Sunday, December 3 at 9:00 AM")
.kind(ToastKind::Success)
},
cx,
);
}),
)
.child(Toaster::new())
}API Reference
ToastKind
The status a toast reports. Every kind but Default shows an icon before the title.
ToastKind::DefaultTitle and description only.
ToastKind::SuccessA check mark, for work that finished.
ToastKind::InfoAn "i" in a circle, for neutral news.
ToastKind::WarningA warning triangle, for something to look at.
ToastKind::ErrorA crossed octagon, for something that failed.
ToastKind::LoadingA spinning loader, for work still running. See [toast_promise].
Toast
A message for [toast].
Toast::new(title: impl Into<SharedString>) -> Self.kind(kind: ToastKind)Sets the status icon shown before the title.
.description(description: impl Into<SharedString>).code(code: impl Into<SharedString>)A block of monospaced text under the description, with its line breaks and indentation kept, like shadcn's form demos showing the submitted values as JSON.
.action(label: impl Into<SharedString>, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)A button on the toast, such as "Undo". Clicking it also dismisses the toast.
Toaster
Draws the toasts in the bottom-right corner of the window. Render it once, anywhere.
Toaster::new() -> Self