use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use dioxus::core::{Runtime, ScopeId, Task, current_scope_id};
use dioxus::prelude::*;
use super::shared::surface;
use crate::class::{Glass, compose};
use crate::overlay::is_escape;
use crate::time::sleep;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastVariant {
#[default]
Default,
Success,
Warning,
Destructive,
}
impl ToastVariant {
pub fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Success => "success",
Self::Warning => "warning",
Self::Destructive => "destructive",
}
}
fn class(self) -> Option<String> {
(self != Self::Default).then(|| format!("ui-toast--{}", self.as_str()))
}
fn live(self) -> &'static str {
if self == Self::Destructive {
"assertive"
} else {
"polite"
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastAnnounce {
Off,
Polite,
Assertive,
}
impl ToastAnnounce {
pub fn as_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::Polite => "polite",
Self::Assertive => "assertive",
}
}
}
fn announcement_role(announcement: &str) -> &'static str {
match announcement {
"off" => "group",
"assertive" => "alert",
_ => "status",
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastPlacement {
BottomCenter,
BottomLeft,
#[default]
BottomRight,
TopCenter,
TopLeft,
TopRight,
}
impl ToastPlacement {
pub fn as_str(self) -> &'static str {
match self {
Self::BottomCenter => "bottom-center",
Self::BottomLeft => "bottom-left",
Self::BottomRight => "bottom-right",
Self::TopCenter => "top-center",
Self::TopLeft => "top-left",
Self::TopRight => "top-right",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct ToastProps {
#[props(default)]
pub variant: ToastVariant,
#[props(into)]
pub announce: Option<ToastAnnounce>,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub role: Option<String>,
#[props(into)]
pub aria_live: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = aside)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Toast(props: ToastProps) -> Element {
let variant = props.variant.class();
let glass = props.glass.class("ui-toast");
let class = compose([
Some("ui-toast"),
variant.as_deref(),
glass.as_deref(),
props.class.as_deref(),
]);
let aria_live = props.aria_live.unwrap_or_else(|| {
props
.announce
.map_or(props.variant.live(), ToastAnnounce::as_str)
.to_string()
});
let role = props
.role
.unwrap_or_else(|| announcement_role(&aria_live).to_string());
rsx! {
aside {
aria_live,
class,
"data-surface": surface(props.glass),
"data-ui-toast": "true",
"data-variant": props.variant.as_str(),
role,
..props.attributes,
{props.children}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct ToastViewportProps {
#[props(default)]
pub placement: ToastPlacement,
#[props(default = 3)]
pub max_count: usize,
#[props(default = "Notifications".to_string(), into)]
pub aria_label: String,
#[props(default = "off".to_string(), into)]
pub aria_live: String,
#[props(default = "false".to_string(), into)]
pub aria_atomic: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn ToastViewport(props: ToastViewportProps) -> Element {
let class = compose([Some("ui-tvp"), props.class.as_deref()]);
rsx! {
div {
aria_atomic: props.aria_atomic,
aria_label: props.aria_label,
aria_live: props.aria_live,
class,
"data-placement": props.placement.as_str(),
"data-ui-toast-viewport": "true",
"data-ui-toast-max": "{props.max_count}",
role: "region",
..props.attributes,
{props.children}
}
}
}
const TOAST_DURATION: Duration = Duration::from_millis(5000);
const TOAST_MAX: usize = 5;
const TOAST_CLOSE_DELAY: Duration = Duration::from_millis(240);
const TOAST_TICK: Duration = Duration::from_millis(100);
static NEXT_TOAST_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Clone)]
pub struct ToastActionHandler(Rc<RefCell<dyn FnMut(String)>>);
impl ToastActionHandler {
pub fn new(handler: impl FnMut(String) + 'static) -> Self {
Self(Rc::new(RefCell::new(handler)))
}
pub fn call(&self, id: String) {
if let Ok(mut handler) = self.0.try_borrow_mut() {
handler(id);
}
}
}
impl PartialEq for ToastActionHandler {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone, PartialEq)]
pub struct ToastAction {
pub label: String,
pub on_click: Option<ToastActionHandler>,
}
impl ToastAction {
pub fn new(label: impl Into<String>, on_click: impl FnMut(String) + 'static) -> Self {
Self {
label: label.into(),
on_click: Some(ToastActionHandler::new(on_click)),
}
}
}
#[derive(Clone, Default, PartialEq)]
pub struct ToastDetail {
pub title: Option<String>,
pub description: Option<String>,
pub variant: Option<ToastVariant>,
pub announce: Option<ToastAnnounce>,
pub duration: Option<Duration>,
pub id: Option<String>,
pub max: Option<usize>,
pub placement: Option<ToastPlacement>,
pub action: Option<ToastAction>,
}
impl ToastDetail {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: Some(title.into()),
..Self::default()
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_variant(mut self, variant: ToastVariant) -> Self {
self.variant = Some(variant);
self
}
#[must_use]
pub fn with_announce(mut self, announce: ToastAnnounce) -> Self {
self.announce = Some(announce);
self
}
#[must_use]
pub fn with_duration(mut self, duration: Duration) -> Self {
self.duration = Some(duration);
self
}
#[must_use]
pub fn with_placement(mut self, placement: ToastPlacement) -> Self {
self.placement = Some(placement);
self
}
#[must_use]
pub fn with_action(mut self, action: ToastAction) -> Self {
self.action = Some(action);
self
}
#[must_use]
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
}
#[derive(Clone, PartialEq)]
pub struct ToastRecord {
pub id: String,
pub title: String,
pub description: Option<String>,
pub variant: ToastVariant,
pub announce: Option<ToastAnnounce>,
pub duration: Option<Duration>,
pub placement: ToastPlacement,
pub open: bool,
pub max: Option<usize>,
pub action: Option<ToastAction>,
}
fn create_toast_record(detail: ToastDetail, placement: ToastPlacement) -> ToastRecord {
let id = detail
.id
.filter(|value| !value.is_empty())
.unwrap_or_else(|| format!("ui-toast-{}", NEXT_TOAST_ID.fetch_add(1, Ordering::Relaxed)));
ToastRecord {
id,
title: detail.title.unwrap_or_else(|| "Notification".to_string()),
description: detail.description,
variant: detail.variant.unwrap_or_default(),
announce: detail.announce,
duration: detail.duration,
placement: detail.placement.unwrap_or(placement),
open: true,
max: detail.max,
action: detail.action,
}
}
fn limit_toast_placement(toasts: &mut [ToastRecord], placement: ToastPlacement, max: usize) {
let open = toasts
.iter()
.filter(|toast| toast.open && toast.placement == placement)
.count();
let mut excess = open.saturating_sub(max);
for toast in toasts.iter_mut() {
if excess == 0 {
break;
}
if toast.open && toast.placement == placement {
toast.open = false;
excess -= 1;
}
}
}
fn apply_create(toasts: &mut Vec<ToastRecord>, record: ToastRecord, max: usize) {
let placement = record.placement;
toasts.retain(|toast| toast.id != record.id);
toasts.push(record);
limit_toast_placement(toasts, placement, max);
}
fn apply_dismiss(toasts: &mut [ToastRecord], id: Option<&str>) {
let target = match id {
Some(id) => Some(id.to_string()),
None => toasts
.iter()
.rev()
.find(|toast| toast.open)
.map(|toast| toast.id.clone()),
};
if let Some(target) = target {
for toast in toasts.iter_mut().filter(|toast| toast.id == target) {
toast.open = false;
}
}
}
fn apply_update(toasts: &mut Vec<ToastRecord>, id: &str, detail: ToastDetail, max: usize) {
let Some(index) = toasts.iter().position(|toast| toast.id == id) else {
return;
};
let current = toasts[index].clone();
let record = ToastRecord {
id: id.to_string(),
title: detail.title.unwrap_or(current.title),
description: detail.description.or(current.description),
variant: detail.variant.unwrap_or(current.variant),
announce: detail.announce.or(current.announce),
duration: detail.duration.or(current.duration),
placement: detail.placement.unwrap_or(current.placement),
open: true,
max: detail.max.or(current.max),
action: detail.action.or(current.action),
};
let limit = record.max.unwrap_or(max);
let placement = record.placement;
if !current.open || placement != current.placement {
toasts.remove(index);
toasts.push(record);
} else {
toasts[index] = record;
}
limit_toast_placement(toasts, placement, limit);
}
#[derive(Clone, Copy)]
pub struct ToastApi {
toasts: Signal<Vec<ToastRecord>>,
placement: CopyValue<ToastPlacement>,
max_count: CopyValue<usize>,
scope: ScopeId,
}
impl ToastApi {
pub fn create(&self, detail: ToastDetail) -> String {
let max = detail.max.unwrap_or(*self.max_count.peek());
let record = create_toast_record(detail, *self.placement.peek());
let id = record.id.clone();
let mut toasts = self.toasts;
apply_create(&mut toasts.write(), record, max);
id
}
pub fn dismiss(&self, id: Option<&str>) {
let mut toasts = self.toasts;
apply_dismiss(&mut toasts.write(), id);
}
pub fn update(&self, id: &str, detail: ToastDetail) {
let max = *self.max_count.peek();
let mut toasts = self.toasts;
apply_update(&mut toasts.write(), id, detail, max);
}
pub fn toasts(&self) -> Vec<ToastRecord> {
self.toasts.read().clone()
}
fn remove(&self, id: &str) {
let mut toasts = self.toasts;
toasts.write().retain(|toast| toast.id != id);
}
fn run_action(&self, handler: &ToastActionHandler, id: String) {
match Runtime::try_current() {
Some(runtime) => runtime.in_scope(self.scope, || handler.call(id)),
None => handler.call(id),
}
}
}
pub fn use_toast() -> ToastApi {
try_use_context::<ToastApi>()
.unwrap_or_else(|| panic!("use_toast must be used inside a ToastProvider."))
}
#[derive(Props, Clone, PartialEq)]
pub struct ToastProviderProps {
#[props(default = TOAST_MAX)]
pub max_count: usize,
#[props(default)]
pub placement: ToastPlacement,
pub children: Element,
}
#[component]
pub fn ToastProvider(props: ToastProviderProps) -> Element {
let api = use_context_provider(|| ToastApi {
toasts: Signal::new(Vec::new()),
placement: CopyValue::new(props.placement),
max_count: CopyValue::new(props.max_count),
scope: current_scope_id(),
});
let (mut placement, mut max_count) = (api.placement, api.max_count);
placement.set(props.placement);
max_count.set(props.max_count);
let toasts = api.toasts.read().clone();
let mut placements = vec![props.placement];
for toast in &toasts {
if !placements.contains(&toast.placement) {
placements.push(toast.placement);
}
}
let max = props.max_count;
rsx! {
{props.children}
for stack in placements {
div {
key: "{stack.as_str()}",
aria_atomic: "false",
aria_label: "Notifications",
aria_live: "off",
class: "ui-tvp",
"data-placement": stack.as_str(),
"data-ui-toast-viewport": "true",
"data-ui-toast-max": "{max}",
role: "region",
for toast in toasts.iter().filter(|toast| toast.placement == stack).cloned() {
ToastItem { key: "{toast.id}", record: toast }
}
}
}
}
}
const PAUSE_HOVER: u8 = 1;
const PAUSE_FOCUS: u8 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ToastClock {
open: bool,
paused: u8,
remaining: Duration,
}
impl ToastClock {
fn new(open: bool, duration: Option<Duration>) -> Self {
Self {
open,
paused: 0,
remaining: duration.unwrap_or(TOAST_DURATION),
}
}
fn reset(&mut self, open: bool, duration: Option<Duration>) {
self.open = open;
self.remaining = duration.unwrap_or(TOAST_DURATION);
}
fn counts_down(self) -> bool {
self.open
&& self.paused == 0
&& !self.remaining.is_zero()
&& self.remaining != Duration::MAX
}
fn pause(&mut self, reason: u8) {
self.paused |= reason;
}
fn resume(&mut self, reason: u8) -> bool {
if self.paused & reason == 0 {
return false;
}
self.paused &= !reason;
self.counts_down()
}
fn elapse(&mut self, step: Duration) -> bool {
self.remaining = self.remaining.saturating_sub(step);
self.remaining.is_zero()
}
}
fn cancel_task(mut slot: CopyValue<Option<Task>>) {
if let Some(task) = slot.write().take() {
task.cancel();
}
}
#[derive(Clone, Copy)]
struct ToastTimer {
clock: CopyValue<ToastClock>,
countdown: CopyValue<Option<Task>>,
removal: CopyValue<Option<Task>>,
}
impl ToastTimer {
fn sync(self, api: ToastApi, id: String, open: bool, duration: Option<Duration>) {
cancel_task(self.countdown);
cancel_task(self.removal);
let mut clock = self.clock;
clock.write().reset(open, duration);
if open {
self.start(api, id);
} else {
let task = spawn(async move {
sleep(TOAST_CLOSE_DELAY).await;
api.remove(&id);
});
let mut removal = self.removal;
removal.set(Some(task));
}
}
fn start(self, api: ToastApi, id: String) {
cancel_task(self.countdown);
if !self.clock.peek().counts_down() {
return;
}
let mut clock = self.clock;
let task = spawn(async move {
loop {
let step = clock.peek().remaining.min(TOAST_TICK);
sleep(step).await;
if clock.write().elapse(step) {
api.dismiss(Some(&id));
break;
}
}
});
let mut countdown = self.countdown;
countdown.set(Some(task));
}
fn pause(self, reason: u8) {
let mut clock = self.clock;
clock.write().pause(reason);
cancel_task(self.countdown);
}
fn resume(self, reason: u8, api: ToastApi, id: String) {
let mut clock = self.clock;
let restart = clock.write().resume(reason);
if restart {
self.start(api, id);
}
}
}
#[component]
fn ToastItem(record: ToastRecord) -> Element {
let api = use_toast();
let timer = use_hook(|| ToastTimer {
clock: CopyValue::new(ToastClock::new(record.open, record.duration)),
countdown: CopyValue::new(None),
removal: CopyValue::new(None),
});
let id = record.id.clone();
use_effect(use_reactive(
(&record.open, &record.duration, &id),
move |(open, duration, id)| timer.sync(api, id, open, duration),
));
let variant = record.variant;
let announcement = record
.announce
.map_or(variant.live(), ToastAnnounce::as_str);
let class = compose([Some("ui-toast"), variant.class().as_deref()]);
let description = record.description.clone().unwrap_or_default();
let (leave_id, blur_id, key_id, action_id, dismiss_id) =
(id.clone(), id.clone(), id.clone(), id.clone(), id.clone());
let action = record
.action
.clone()
.filter(|action| !action.label.is_empty());
rsx! {
aside {
aria_live: announcement,
class,
"data-description": description.clone(),
"data-state": if record.open { "open" } else { "closed" },
"data-title": record.title.clone(),
"data-ui-toast": "true",
"data-variant": variant.as_str(),
id: id.clone(),
role: announcement_role(announcement),
onmouseenter: move |_| timer.pause(PAUSE_HOVER),
onmouseleave: move |_| timer.resume(PAUSE_HOVER, api, leave_id.clone()),
onfocusin: move |_| timer.pause(PAUSE_FOCUS),
onfocusout: move |_| timer.resume(PAUSE_FOCUS, api, blur_id.clone()),
onkeydown: move |event| {
if !event.default_action_enabled() || !is_escape(&event) {
return;
}
event.prevent_default();
api.dismiss(Some(&key_id));
},
div { class: "ui-toast__body",
strong { {record.title.clone()} }
if !description.is_empty() {
p { {description.clone()} }
}
}
if let Some(action) = action {
button {
class: "ui-button ui-button--secondary ui-button--sm ui-toast__action",
r#type: "button",
onclick: move |_| {
if let Some(handler) = &action.on_click {
api.run_action(handler, action_id.clone());
}
api.dismiss(Some(&action_id));
},
{action.label.clone()}
}
}
button {
aria_label: "Dismiss notification",
class: "ui-toast__dismiss",
r#type: "button",
onclick: move |_| api.dismiss(Some(&dismiss_id)),
"Dismiss"
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{
PAUSE_FOCUS, PAUSE_HOVER, TOAST_TICK, ToastAction, ToastAnnounce, ToastClock, ToastDetail,
ToastPlacement, ToastRecord, ToastVariant, apply_create, apply_dismiss, apply_update,
create_toast_record, limit_toast_placement,
};
#[test]
fn explicit_announcement_survives_content_updates() {
let mut toasts = vec![create_toast_record(
ToastDetail::new("Saved")
.with_id("save")
.with_announce(ToastAnnounce::Off),
ToastPlacement::BottomRight,
)];
apply_update(
&mut toasts,
"save",
ToastDetail::new("Failed").with_variant(ToastVariant::Destructive),
5,
);
assert_eq!(toasts[0].announce, Some(ToastAnnounce::Off));
apply_update(
&mut toasts,
"save",
ToastDetail::default().with_announce(ToastAnnounce::Assertive),
5,
);
assert_eq!(toasts[0].announce, Some(ToastAnnounce::Assertive));
}
#[test]
fn dismissed_toasts_never_restart_their_countdown() {
let mut clock = ToastClock::new(true, Some(Duration::from_secs(5)));
assert!(clock.counts_down());
clock.pause(PAUSE_HOVER);
assert!(!clock.counts_down());
clock.reset(false, Some(Duration::from_secs(5)));
assert!(!clock.resume(PAUSE_HOVER));
clock.pause(PAUSE_FOCUS);
assert!(!clock.resume(PAUSE_FOCUS));
assert!(!clock.open);
assert!(!clock.counts_down());
clock.reset(true, None);
assert!(clock.counts_down());
}
#[test]
fn the_countdown_resumes_only_when_every_pause_ends() {
let mut clock = ToastClock::new(true, None);
clock.pause(PAUSE_HOVER);
clock.pause(PAUSE_FOCUS);
assert!(!clock.resume(PAUSE_HOVER));
assert!(
!clock.resume(PAUSE_HOVER),
"an unset reason changes nothing"
);
assert!(clock.resume(PAUSE_FOCUS));
assert!(!ToastClock::new(true, Some(Duration::ZERO)).counts_down());
assert!(!ToastClock::new(true, Some(Duration::MAX)).counts_down());
}
#[test]
fn elapsing_counts_down_to_zero() {
let mut clock = ToastClock::new(true, Some(Duration::from_millis(150)));
assert!(!clock.elapse(TOAST_TICK));
assert!(clock.elapse(TOAST_TICK));
assert_eq!(clock.remaining, Duration::ZERO);
assert!(!clock.counts_down());
}
#[test]
fn actions_compare_by_handler_identity() {
let action = ToastAction::new("Undo", |_| {});
assert!(action == action.clone());
assert!(action != ToastAction::new("Undo", |_| {}));
}
fn record(id: &str, placement: ToastPlacement) -> ToastRecord {
create_toast_record(
ToastDetail::new(id).with_id(id).with_placement(placement),
placement,
)
}
fn open_ids(toasts: &[ToastRecord]) -> Vec<&str> {
toasts
.iter()
.filter(|toast| toast.open)
.map(|toast| toast.id.as_str())
.collect()
}
#[test]
fn records_take_defaults() {
let toast = create_toast_record(ToastDetail::default(), ToastPlacement::TopLeft);
assert!(toast.id.starts_with("ui-toast-"));
assert_eq!(toast.title, "Notification");
assert_eq!(toast.variant, ToastVariant::Default);
assert_eq!(toast.placement, ToastPlacement::TopLeft);
assert!(toast.open);
let empty_id =
create_toast_record(ToastDetail::default().with_id(""), ToastPlacement::TopLeft);
assert!(empty_id.id.starts_with("ui-toast-"));
}
#[test]
fn stacks_close_the_oldest_beyond_the_limit() {
let mut toasts = Vec::new();
for id in ["a", "b", "c"] {
apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 2);
}
apply_create(&mut toasts, record("top", ToastPlacement::TopLeft), 2);
assert_eq!(open_ids(&toasts), vec!["b", "c", "top"]);
limit_toast_placement(&mut toasts, ToastPlacement::BottomRight, 0);
assert_eq!(open_ids(&toasts), vec!["top"]);
}
#[test]
fn creating_an_existing_id_replaces_it() {
let mut toasts = Vec::new();
apply_create(&mut toasts, record("a", ToastPlacement::BottomRight), 5);
apply_create(&mut toasts, record("b", ToastPlacement::BottomRight), 5);
apply_create(&mut toasts, record("a", ToastPlacement::BottomRight), 5);
let ids: Vec<&str> = toasts.iter().map(|toast| toast.id.as_str()).collect();
assert_eq!(ids, vec!["b", "a"]);
}
#[test]
fn dismiss_targets_an_id_or_the_newest_open_toast() {
let mut toasts = Vec::new();
for id in ["a", "b", "c"] {
apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 5);
}
apply_dismiss(&mut toasts, Some("a"));
apply_dismiss(&mut toasts, None);
assert_eq!(open_ids(&toasts), vec!["b"]);
apply_dismiss(&mut toasts, Some("missing"));
assert_eq!(open_ids(&toasts), vec!["b"]);
}
#[test]
fn update_reopens_and_moves_closed_toasts() {
let mut toasts = Vec::new();
for id in ["a", "b"] {
apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 5);
}
apply_dismiss(&mut toasts, Some("a"));
apply_update(
&mut toasts,
"a",
ToastDetail::default()
.with_description("Retried")
.with_duration(Duration::ZERO),
5,
);
let ids: Vec<&str> = toasts.iter().map(|toast| toast.id.as_str()).collect();
assert_eq!(ids, vec!["b", "a"]);
assert!(toasts[1].open);
assert_eq!(toasts[1].title, "a");
assert_eq!(toasts[1].description.as_deref(), Some("Retried"));
assert_eq!(toasts[1].duration, Some(Duration::ZERO));
apply_update(&mut toasts, "b", ToastDetail::new("Saved"), 5);
assert_eq!(toasts[0].title, "Saved");
apply_update(&mut toasts, "missing", ToastDetail::new("x"), 5);
assert_eq!(toasts.len(), 2);
}
}