Skip to main content

lumen_dioxus/overlays/
toast.rs

1//! Toasts: the static `Toast` and `ToastViewport`, and `ToastProvider` with [`use_toast`].
2
3// cspell:words onfocusin onfocusout
4
5use std::cell::RefCell;
6use std::rc::Rc;
7use std::sync::atomic::{AtomicUsize, Ordering};
8use std::time::Duration;
9
10use dioxus::core::{Runtime, ScopeId, Task, current_scope_id};
11use dioxus::prelude::*;
12
13use super::shared::surface;
14use crate::class::{Glass, compose};
15use crate::overlay::is_escape;
16use crate::time::sleep;
17
18/// Tone of a [`Toast`].
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ToastVariant {
22    /// Neutral information.
23    #[default]
24    Default,
25    /// Positive outcome.
26    Success,
27    /// Needs attention.
28    Warning,
29    /// Error or failure. Announced assertively as an `alert`.
30    Destructive,
31}
32
33impl ToastVariant {
34    /// The class suffix and `data-variant` value.
35    pub fn as_str(self) -> &'static str {
36        match self {
37            Self::Default => "default",
38            Self::Success => "success",
39            Self::Warning => "warning",
40            Self::Destructive => "destructive",
41        }
42    }
43
44    fn class(self) -> Option<String> {
45        (self != Self::Default).then(|| format!("ui-toast--{}", self.as_str()))
46    }
47
48    fn live(self) -> &'static str {
49        if self == Self::Destructive {
50            "assertive"
51        } else {
52            "polite"
53        }
54    }
55}
56
57/// How a toast announces its content to assistive technology.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum ToastAnnounce {
61    /// Keep the notification visible without duplicating an application-owned announcement.
62    Off,
63    /// Announce after the current speech.
64    Polite,
65    /// Interrupt the current speech for urgent feedback.
66    Assertive,
67}
68
69impl ToastAnnounce {
70    /// The `aria-live` value.
71    pub fn as_str(self) -> &'static str {
72        match self {
73            Self::Off => "off",
74            Self::Polite => "polite",
75            Self::Assertive => "assertive",
76        }
77    }
78}
79
80fn announcement_role(announcement: &str) -> &'static str {
81    match announcement {
82        "off" => "group",
83        "assertive" => "alert",
84        _ => "status",
85    }
86}
87
88/// Corner or edge of the viewport where toasts stack.
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum ToastPlacement {
92    /// Bottom edge, centered.
93    BottomCenter,
94    /// Bottom-left corner.
95    BottomLeft,
96    /// Bottom-right corner.
97    #[default]
98    BottomRight,
99    /// Top edge, centered.
100    TopCenter,
101    /// Top-left corner.
102    TopLeft,
103    /// Top-right corner.
104    TopRight,
105}
106
107impl ToastPlacement {
108    /// The `data-placement` value.
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::BottomCenter => "bottom-center",
112            Self::BottomLeft => "bottom-left",
113            Self::BottomRight => "bottom-right",
114            Self::TopCenter => "top-center",
115            Self::TopLeft => "top-left",
116            Self::TopRight => "top-right",
117        }
118    }
119}
120
121/// Props for [`Toast`].
122#[derive(Props, Clone, PartialEq)]
123pub struct ToastProps {
124    /// Tone.
125    #[props(default)]
126    pub variant: ToastVariant,
127    /// Announcement mode. Omitted uses the variant's default; explicit `aria_live` takes precedence.
128    #[props(into)]
129    pub announce: Option<ToastAnnounce>,
130    /// Glass intensity.
131    #[props(default, into)]
132    pub glass: Glass,
133    /// Overrides the resolved announcement role: `group`, `status`, or `alert`.
134    #[props(into)]
135    pub role: Option<String>,
136    /// Overrides the live-region politeness: `assertive` for destructive toasts, otherwise
137    /// `polite`.
138    #[props(into)]
139    pub aria_live: Option<String>,
140    /// Extra classes appended after the Lumen classes.
141    #[props(into)]
142    pub class: Option<String>,
143    /// Any other `<aside>` or global attribute.
144    #[props(extends = GlobalAttributes, extends = aside)]
145    pub attributes: Vec<Attribute>,
146    /// Toast content, usually a `strong` title and a short paragraph.
147    pub children: Element,
148}
149
150/// A static notification surface. For timed toasts, use [`ToastProvider`] and [`use_toast`].
151#[component]
152pub fn Toast(props: ToastProps) -> Element {
153    let variant = props.variant.class();
154    let glass = props.glass.class("ui-toast");
155    let class = compose([
156        Some("ui-toast"),
157        variant.as_deref(),
158        glass.as_deref(),
159        props.class.as_deref(),
160    ]);
161    let aria_live = props.aria_live.unwrap_or_else(|| {
162        props
163            .announce
164            .map_or(props.variant.live(), ToastAnnounce::as_str)
165            .to_string()
166    });
167    let role = props
168        .role
169        .unwrap_or_else(|| announcement_role(&aria_live).to_string());
170
171    rsx! {
172        aside {
173            aria_live,
174            class,
175            "data-surface": surface(props.glass),
176            "data-ui-toast": "true",
177            "data-variant": props.variant.as_str(),
178            role,
179            ..props.attributes,
180            {props.children}
181        }
182    }
183}
184
185/// Props for [`ToastViewport`].
186#[derive(Props, Clone, PartialEq)]
187pub struct ToastViewportProps {
188    /// Where the stack sits.
189    #[props(default)]
190    pub placement: ToastPlacement,
191    /// The most toasts the stack shows. Defaults to 3.
192    #[props(default = 3)]
193    pub max_count: usize,
194    /// Accessible name. Defaults to "Notifications".
195    #[props(default = "Notifications".to_string(), into)]
196    pub aria_label: String,
197    /// Live-region politeness. Defaults to `off`; each toast owns its announcement.
198    #[props(default = "off".to_string(), into)]
199    pub aria_live: String,
200    /// Whether the region is read as a whole. Defaults to `false`.
201    #[props(default = "false".to_string(), into)]
202    pub aria_atomic: String,
203    /// Extra classes appended after the Lumen class.
204    #[props(into)]
205    pub class: Option<String>,
206    /// Any other `<div>` or global attribute.
207    #[props(extends = GlobalAttributes, extends = div)]
208    pub attributes: Vec<Attribute>,
209    /// [`Toast`]s.
210    pub children: Element,
211}
212
213/// A fixed notification region that stacks static [`Toast`]s. [`ToastProvider`] renders its own.
214#[component]
215pub fn ToastViewport(props: ToastViewportProps) -> Element {
216    let class = compose([Some("ui-tvp"), props.class.as_deref()]);
217
218    rsx! {
219        div {
220            aria_atomic: props.aria_atomic,
221            aria_label: props.aria_label,
222            aria_live: props.aria_live,
223            class,
224            "data-placement": props.placement.as_str(),
225            "data-ui-toast-viewport": "true",
226            "data-ui-toast-max": "{props.max_count}",
227            role: "region",
228            ..props.attributes,
229            {props.children}
230        }
231    }
232}
233
234const TOAST_DURATION: Duration = Duration::from_millis(5000);
235const TOAST_MAX: usize = 5;
236const TOAST_CLOSE_DELAY: Duration = Duration::from_millis(240);
237const TOAST_TICK: Duration = Duration::from_millis(100);
238
239static NEXT_TOAST_ID: AtomicUsize = AtomicUsize::new(0);
240
241/// The click handler of a [`ToastAction`].
242///
243/// The toast owns it, so it keeps working after the component that created the toast unmounts.
244/// It runs in the [`ToastProvider`]'s scope, so tasks it spawns live as long as the provider.
245/// Signals it captures must still be alive when it runs: capture state of a component that
246/// outlives the toast, not of one that may unmount first.
247#[derive(Clone)]
248pub struct ToastActionHandler(Rc<RefCell<dyn FnMut(String)>>);
249
250impl ToastActionHandler {
251    /// Wraps a closure that receives the toast id.
252    pub fn new(handler: impl FnMut(String) + 'static) -> Self {
253        Self(Rc::new(RefCell::new(handler)))
254    }
255
256    /// Calls the handler with the toast id. A call made from inside the same handler is skipped.
257    pub fn call(&self, id: String) {
258        if let Ok(mut handler) = self.0.try_borrow_mut() {
259            handler(id);
260        }
261    }
262}
263
264impl PartialEq for ToastActionHandler {
265    fn eq(&self, other: &Self) -> bool {
266        Rc::ptr_eq(&self.0, &other.0)
267    }
268}
269
270/// An action button inside a toast.
271#[derive(Clone, PartialEq)]
272pub struct ToastAction {
273    /// Button label.
274    pub label: String,
275    /// Called with the toast id before the toast is dismissed.
276    pub on_click: Option<ToastActionHandler>,
277}
278
279impl ToastAction {
280    /// An action with a label and a click handler that receives the toast id.
281    pub fn new(label: impl Into<String>, on_click: impl FnMut(String) + 'static) -> Self {
282        Self {
283            label: label.into(),
284            on_click: Some(ToastActionHandler::new(on_click)),
285        }
286    }
287}
288
289/// What to show in a toast, passed to [`ToastApi::create`] and [`ToastApi::update`].
290#[derive(Clone, Default, PartialEq)]
291pub struct ToastDetail {
292    /// Heading. Defaults to "Notification".
293    pub title: Option<String>,
294    /// Supporting text.
295    pub description: Option<String>,
296    /// Tone. Defaults to [`ToastVariant::Default`].
297    pub variant: Option<ToastVariant>,
298    /// Announcement mode. Omitted uses the tone's default and preserves the setting on update.
299    pub announce: Option<ToastAnnounce>,
300    /// Time before the toast dismisses itself. Defaults to 5 seconds; `Duration::ZERO` or
301    /// `Duration::MAX` keeps it until dismissed.
302    pub duration: Option<Duration>,
303    /// A stable id, so a later create or update replaces the same toast.
304    pub id: Option<String>,
305    /// The most open toasts in this toast's stack.
306    pub max: Option<usize>,
307    /// Stack placement. Defaults to the provider placement.
308    pub placement: Option<ToastPlacement>,
309    /// An action button.
310    pub action: Option<ToastAction>,
311}
312
313impl ToastDetail {
314    /// A toast with a title.
315    pub fn new(title: impl Into<String>) -> Self {
316        Self {
317            title: Some(title.into()),
318            ..Self::default()
319        }
320    }
321
322    /// Sets the supporting text.
323    #[must_use]
324    pub fn with_description(mut self, description: impl Into<String>) -> Self {
325        self.description = Some(description.into());
326        self
327    }
328
329    /// Sets the tone.
330    #[must_use]
331    pub fn with_variant(mut self, variant: ToastVariant) -> Self {
332        self.variant = Some(variant);
333        self
334    }
335
336    /// Sets how the notification announces its content.
337    #[must_use]
338    pub fn with_announce(mut self, announce: ToastAnnounce) -> Self {
339        self.announce = Some(announce);
340        self
341    }
342
343    /// Sets the time before the toast dismisses itself.
344    #[must_use]
345    pub fn with_duration(mut self, duration: Duration) -> Self {
346        self.duration = Some(duration);
347        self
348    }
349
350    /// Sets the stack placement.
351    #[must_use]
352    pub fn with_placement(mut self, placement: ToastPlacement) -> Self {
353        self.placement = Some(placement);
354        self
355    }
356
357    /// Sets the action button.
358    #[must_use]
359    pub fn with_action(mut self, action: ToastAction) -> Self {
360        self.action = Some(action);
361        self
362    }
363
364    /// Sets a stable id.
365    #[must_use]
366    pub fn with_id(mut self, id: impl Into<String>) -> Self {
367        self.id = Some(id.into());
368        self
369    }
370}
371
372/// A toast held by a [`ToastProvider`].
373#[derive(Clone, PartialEq)]
374pub struct ToastRecord {
375    /// Element id, `ui-toast-N` unless the detail set one.
376    pub id: String,
377    /// Heading.
378    pub title: String,
379    /// Supporting text.
380    pub description: Option<String>,
381    /// Tone.
382    pub variant: ToastVariant,
383    /// Explicit announcement mode, or the tone's default when absent.
384    pub announce: Option<ToastAnnounce>,
385    /// Time before the toast dismisses itself.
386    pub duration: Option<Duration>,
387    /// Stack placement.
388    pub placement: ToastPlacement,
389    /// False while the toast plays its exit before removal.
390    pub open: bool,
391    /// The most open toasts in this toast's stack.
392    pub max: Option<usize>,
393    /// Action button.
394    pub action: Option<ToastAction>,
395}
396
397fn create_toast_record(detail: ToastDetail, placement: ToastPlacement) -> ToastRecord {
398    let id = detail
399        .id
400        .filter(|value| !value.is_empty())
401        .unwrap_or_else(|| format!("ui-toast-{}", NEXT_TOAST_ID.fetch_add(1, Ordering::Relaxed)));
402
403    ToastRecord {
404        id,
405        title: detail.title.unwrap_or_else(|| "Notification".to_string()),
406        description: detail.description,
407        variant: detail.variant.unwrap_or_default(),
408        announce: detail.announce,
409        duration: detail.duration,
410        placement: detail.placement.unwrap_or(placement),
411        open: true,
412        max: detail.max,
413        action: detail.action,
414    }
415}
416
417/// Closes the oldest open toasts of a placement beyond `max`, like `limitToastPlacement`.
418fn limit_toast_placement(toasts: &mut [ToastRecord], placement: ToastPlacement, max: usize) {
419    let open = toasts
420        .iter()
421        .filter(|toast| toast.open && toast.placement == placement)
422        .count();
423    let mut excess = open.saturating_sub(max);
424
425    for toast in toasts.iter_mut() {
426        if excess == 0 {
427            break;
428        }
429
430        if toast.open && toast.placement == placement {
431            toast.open = false;
432            excess -= 1;
433        }
434    }
435}
436
437fn apply_create(toasts: &mut Vec<ToastRecord>, record: ToastRecord, max: usize) {
438    let placement = record.placement;
439    toasts.retain(|toast| toast.id != record.id);
440    toasts.push(record);
441    limit_toast_placement(toasts, placement, max);
442}
443
444fn apply_dismiss(toasts: &mut [ToastRecord], id: Option<&str>) {
445    let target = match id {
446        Some(id) => Some(id.to_string()),
447        None => toasts
448            .iter()
449            .rev()
450            .find(|toast| toast.open)
451            .map(|toast| toast.id.clone()),
452    };
453
454    if let Some(target) = target {
455        for toast in toasts.iter_mut().filter(|toast| toast.id == target) {
456            toast.open = false;
457        }
458    }
459}
460
461fn apply_update(toasts: &mut Vec<ToastRecord>, id: &str, detail: ToastDetail, max: usize) {
462    let Some(index) = toasts.iter().position(|toast| toast.id == id) else {
463        return;
464    };
465    let current = toasts[index].clone();
466    let record = ToastRecord {
467        id: id.to_string(),
468        title: detail.title.unwrap_or(current.title),
469        description: detail.description.or(current.description),
470        variant: detail.variant.unwrap_or(current.variant),
471        announce: detail.announce.or(current.announce),
472        duration: detail.duration.or(current.duration),
473        placement: detail.placement.unwrap_or(current.placement),
474        open: true,
475        max: detail.max.or(current.max),
476        action: detail.action.or(current.action),
477    };
478    let limit = record.max.unwrap_or(max);
479    let placement = record.placement;
480
481    if !current.open || placement != current.placement {
482        toasts.remove(index);
483        toasts.push(record);
484    } else {
485        toasts[index] = record;
486    }
487
488    limit_toast_placement(toasts, placement, limit);
489}
490
491/// Creates, updates, and dismisses the toasts of the nearest [`ToastProvider`].
492///
493/// It is `Copy`, so event handlers can capture it.
494#[derive(Clone, Copy)]
495pub struct ToastApi {
496    toasts: Signal<Vec<ToastRecord>>,
497    placement: CopyValue<ToastPlacement>,
498    max_count: CopyValue<usize>,
499    /// The provider's scope, where action handlers run.
500    scope: ScopeId,
501}
502
503impl ToastApi {
504    /// Shows a toast and returns its id. Creating a toast with an existing id replaces it.
505    pub fn create(&self, detail: ToastDetail) -> String {
506        let max = detail.max.unwrap_or(*self.max_count.peek());
507        let record = create_toast_record(detail, *self.placement.peek());
508        let id = record.id.clone();
509        let mut toasts = self.toasts;
510        apply_create(&mut toasts.write(), record, max);
511        id
512    }
513
514    /// Starts closing a toast, or the newest open toast when `id` is `None`.
515    pub fn dismiss(&self, id: Option<&str>) {
516        let mut toasts = self.toasts;
517        apply_dismiss(&mut toasts.write(), id);
518    }
519
520    /// Changes a toast and reopens it if it was closing.
521    pub fn update(&self, id: &str, detail: ToastDetail) {
522        let max = *self.max_count.peek();
523        let mut toasts = self.toasts;
524        apply_update(&mut toasts.write(), id, detail, max);
525    }
526
527    /// The current toasts, oldest first. Reading subscribes the component.
528    pub fn toasts(&self) -> Vec<ToastRecord> {
529        self.toasts.read().clone()
530    }
531
532    fn remove(&self, id: &str) {
533        let mut toasts = self.toasts;
534        toasts.write().retain(|toast| toast.id != id);
535    }
536
537    /// Runs a toast action in the provider's scope, so tasks it spawns outlive the toast, which is
538    /// removed shortly after the action dismisses it.
539    fn run_action(&self, handler: &ToastActionHandler, id: String) {
540        match Runtime::try_current() {
541            Some(runtime) => runtime.in_scope(self.scope, || handler.call(id)),
542            None => handler.call(id),
543        }
544    }
545}
546
547/// The toast API of the nearest [`ToastProvider`].
548///
549/// # Panics
550///
551/// Panics when no `ToastProvider` wraps the calling component.
552pub fn use_toast() -> ToastApi {
553    try_use_context::<ToastApi>()
554        .unwrap_or_else(|| panic!("use_toast must be used inside a ToastProvider."))
555}
556
557/// Props for [`ToastProvider`].
558#[derive(Props, Clone, PartialEq)]
559pub struct ToastProviderProps {
560    /// The most open toasts per stack. Defaults to 5.
561    #[props(default = TOAST_MAX)]
562    pub max_count: usize,
563    /// Default stack placement.
564    #[props(default)]
565    pub placement: ToastPlacement,
566    /// The app. Components inside can call [`use_toast`].
567    pub children: Element,
568}
569
570/// Provides [`use_toast`] to its children and renders one live region per stack placement.
571///
572/// Toasts dismiss themselves after their duration, pause while hovered or focused (web and
573/// desktop), and close on Escape or their dismiss button.
574#[component]
575pub fn ToastProvider(props: ToastProviderProps) -> Element {
576    let api = use_context_provider(|| ToastApi {
577        toasts: Signal::new(Vec::new()),
578        placement: CopyValue::new(props.placement),
579        max_count: CopyValue::new(props.max_count),
580        scope: current_scope_id(),
581    });
582    let (mut placement, mut max_count) = (api.placement, api.max_count);
583    placement.set(props.placement);
584    max_count.set(props.max_count);
585
586    let toasts = api.toasts.read().clone();
587    let mut placements = vec![props.placement];
588
589    for toast in &toasts {
590        if !placements.contains(&toast.placement) {
591            placements.push(toast.placement);
592        }
593    }
594
595    let max = props.max_count;
596
597    rsx! {
598        {props.children}
599        for stack in placements {
600            div {
601                key: "{stack.as_str()}",
602                aria_atomic: "false",
603                aria_label: "Notifications",
604                aria_live: "off",
605                class: "ui-tvp",
606                "data-placement": stack.as_str(),
607                "data-ui-toast-viewport": "true",
608                "data-ui-toast-max": "{max}",
609                role: "region",
610                for toast in toasts.iter().filter(|toast| toast.placement == stack).cloned() {
611                    ToastItem { key: "{toast.id}", record: toast }
612                }
613            }
614        }
615    }
616}
617
618const PAUSE_HOVER: u8 = 1;
619const PAUSE_FOCUS: u8 = 2;
620
621/// Timer state of one provider toast, free of tasks so its transitions are unit-tested. Time is
622/// counted in short ticks, so pausing keeps the remaining duration without a wall clock (which
623/// the web target lacks).
624#[derive(Clone, Copy, Debug, PartialEq, Eq)]
625struct ToastClock {
626    /// False once the toast is dismissed and waits for removal.
627    open: bool,
628    /// `PAUSE_HOVER` and `PAUSE_FOCUS` bits.
629    paused: u8,
630    /// Time left before the toast dismisses itself.
631    remaining: Duration,
632}
633
634impl ToastClock {
635    fn new(open: bool, duration: Option<Duration>) -> Self {
636        Self {
637            open,
638            paused: 0,
639            remaining: duration.unwrap_or(TOAST_DURATION),
640        }
641    }
642
643    /// Takes the record's open state and duration. Pause reasons carry over.
644    fn reset(&mut self, open: bool, duration: Option<Duration>) {
645        self.open = open;
646        self.remaining = duration.unwrap_or(TOAST_DURATION);
647    }
648
649    /// Whether the countdown runs: the toast is open, has a finite time left, and nothing pauses
650    /// it.
651    fn counts_down(self) -> bool {
652        self.open
653            && self.paused == 0
654            && !self.remaining.is_zero()
655            && self.remaining != Duration::MAX
656    }
657
658    fn pause(&mut self, reason: u8) {
659        self.paused |= reason;
660    }
661
662    /// Drops a pause reason and returns whether the countdown starts again. A closed toast never
663    /// restarts, because it is waiting for removal.
664    fn resume(&mut self, reason: u8) -> bool {
665        if self.paused & reason == 0 {
666            return false;
667        }
668
669        self.paused &= !reason;
670        self.counts_down()
671    }
672
673    /// Counts `step` down and returns whether the time ran out.
674    fn elapse(&mut self, step: Duration) -> bool {
675        self.remaining = self.remaining.saturating_sub(step);
676        self.remaining.is_zero()
677    }
678}
679
680fn cancel_task(mut slot: CopyValue<Option<Task>>) {
681    if let Some(task) = slot.write().take() {
682        task.cancel();
683    }
684}
685
686/// The tasks of one provider toast around its [`ToastClock`]. The countdown and the removal are
687/// separate tasks: hover and focus pause and resume only the countdown, so they can never cancel
688/// the removal of a dismissed toast.
689#[derive(Clone, Copy)]
690struct ToastTimer {
691    clock: CopyValue<ToastClock>,
692    countdown: CopyValue<Option<Task>>,
693    removal: CopyValue<Option<Task>>,
694}
695
696impl ToastTimer {
697    /// Follows the record: an open toast counts down, and a closed one is removed after its exit.
698    fn sync(self, api: ToastApi, id: String, open: bool, duration: Option<Duration>) {
699        cancel_task(self.countdown);
700        cancel_task(self.removal);
701        let mut clock = self.clock;
702        clock.write().reset(open, duration);
703
704        if open {
705            self.start(api, id);
706        } else {
707            let task = spawn(async move {
708                sleep(TOAST_CLOSE_DELAY).await;
709                api.remove(&id);
710            });
711            let mut removal = self.removal;
712            removal.set(Some(task));
713        }
714    }
715
716    fn start(self, api: ToastApi, id: String) {
717        cancel_task(self.countdown);
718
719        if !self.clock.peek().counts_down() {
720            return;
721        }
722
723        let mut clock = self.clock;
724        let task = spawn(async move {
725            loop {
726                let step = clock.peek().remaining.min(TOAST_TICK);
727                sleep(step).await;
728
729                if clock.write().elapse(step) {
730                    api.dismiss(Some(&id));
731                    break;
732                }
733            }
734        });
735        let mut countdown = self.countdown;
736        countdown.set(Some(task));
737    }
738
739    fn pause(self, reason: u8) {
740        let mut clock = self.clock;
741        clock.write().pause(reason);
742        cancel_task(self.countdown);
743    }
744
745    fn resume(self, reason: u8, api: ToastApi, id: String) {
746        let mut clock = self.clock;
747        let restart = clock.write().resume(reason);
748
749        if restart {
750            self.start(api, id);
751        }
752    }
753}
754
755#[component]
756fn ToastItem(record: ToastRecord) -> Element {
757    let api = use_toast();
758    let timer = use_hook(|| ToastTimer {
759        clock: CopyValue::new(ToastClock::new(record.open, record.duration)),
760        countdown: CopyValue::new(None),
761        removal: CopyValue::new(None),
762    });
763    let id = record.id.clone();
764
765    use_effect(use_reactive(
766        (&record.open, &record.duration, &id),
767        move |(open, duration, id)| timer.sync(api, id, open, duration),
768    ));
769
770    let variant = record.variant;
771    let announcement = record
772        .announce
773        .map_or(variant.live(), ToastAnnounce::as_str);
774    let class = compose([Some("ui-toast"), variant.class().as_deref()]);
775    let description = record.description.clone().unwrap_or_default();
776    let (leave_id, blur_id, key_id, action_id, dismiss_id) =
777        (id.clone(), id.clone(), id.clone(), id.clone(), id.clone());
778    let action = record
779        .action
780        .clone()
781        .filter(|action| !action.label.is_empty());
782
783    rsx! {
784        aside {
785            aria_live: announcement,
786            class,
787            "data-description": description.clone(),
788            "data-state": if record.open { "open" } else { "closed" },
789            "data-title": record.title.clone(),
790            "data-ui-toast": "true",
791            "data-variant": variant.as_str(),
792            id: id.clone(),
793            role: announcement_role(announcement),
794            onmouseenter: move |_| timer.pause(PAUSE_HOVER),
795            onmouseleave: move |_| timer.resume(PAUSE_HOVER, api, leave_id.clone()),
796            onfocusin: move |_| timer.pause(PAUSE_FOCUS),
797            onfocusout: move |_| timer.resume(PAUSE_FOCUS, api, blur_id.clone()),
798            onkeydown: move |event| {
799                if !event.default_action_enabled() || !is_escape(&event) {
800                    return;
801                }
802
803                event.prevent_default();
804                api.dismiss(Some(&key_id));
805            },
806            div { class: "ui-toast__body",
807                strong { {record.title.clone()} }
808                if !description.is_empty() {
809                    p { {description.clone()} }
810                }
811            }
812            if let Some(action) = action {
813                button {
814                    class: "ui-button ui-button--secondary ui-button--sm ui-toast__action",
815                    r#type: "button",
816                    onclick: move |_| {
817                        if let Some(handler) = &action.on_click {
818                            api.run_action(handler, action_id.clone());
819                        }
820
821                        api.dismiss(Some(&action_id));
822                    },
823                    {action.label.clone()}
824                }
825            }
826            button {
827                aria_label: "Dismiss notification",
828                class: "ui-toast__dismiss",
829                r#type: "button",
830                onclick: move |_| api.dismiss(Some(&dismiss_id)),
831                "Dismiss"
832            }
833        }
834    }
835}
836
837#[cfg(test)]
838mod tests {
839    use std::time::Duration;
840
841    use super::{
842        PAUSE_FOCUS, PAUSE_HOVER, TOAST_TICK, ToastAction, ToastAnnounce, ToastClock, ToastDetail,
843        ToastPlacement, ToastRecord, ToastVariant, apply_create, apply_dismiss, apply_update,
844        create_toast_record, limit_toast_placement,
845    };
846
847    #[test]
848    fn explicit_announcement_survives_content_updates() {
849        let mut toasts = vec![create_toast_record(
850            ToastDetail::new("Saved")
851                .with_id("save")
852                .with_announce(ToastAnnounce::Off),
853            ToastPlacement::BottomRight,
854        )];
855
856        apply_update(
857            &mut toasts,
858            "save",
859            ToastDetail::new("Failed").with_variant(ToastVariant::Destructive),
860            5,
861        );
862        assert_eq!(toasts[0].announce, Some(ToastAnnounce::Off));
863
864        apply_update(
865            &mut toasts,
866            "save",
867            ToastDetail::default().with_announce(ToastAnnounce::Assertive),
868            5,
869        );
870        assert_eq!(toasts[0].announce, Some(ToastAnnounce::Assertive));
871    }
872
873    #[test]
874    fn dismissed_toasts_never_restart_their_countdown() {
875        // A toast dismissed while hovered: leaving it within the exit delay used to restart the
876        // countdown (and cancel the removal), so the closed toast stayed in the list.
877        let mut clock = ToastClock::new(true, Some(Duration::from_secs(5)));
878        assert!(clock.counts_down());
879        clock.pause(PAUSE_HOVER);
880        assert!(!clock.counts_down());
881        clock.reset(false, Some(Duration::from_secs(5)));
882        assert!(!clock.resume(PAUSE_HOVER));
883        clock.pause(PAUSE_FOCUS);
884        assert!(!clock.resume(PAUSE_FOCUS));
885        assert!(!clock.open);
886        assert!(!clock.counts_down());
887
888        // Reopening through `update` counts down again.
889        clock.reset(true, None);
890        assert!(clock.counts_down());
891    }
892
893    #[test]
894    fn the_countdown_resumes_only_when_every_pause_ends() {
895        let mut clock = ToastClock::new(true, None);
896        clock.pause(PAUSE_HOVER);
897        clock.pause(PAUSE_FOCUS);
898        assert!(!clock.resume(PAUSE_HOVER));
899        assert!(
900            !clock.resume(PAUSE_HOVER),
901            "an unset reason changes nothing"
902        );
903        assert!(clock.resume(PAUSE_FOCUS));
904
905        // Zero and `Duration::MAX` keep the toast until it is dismissed.
906        assert!(!ToastClock::new(true, Some(Duration::ZERO)).counts_down());
907        assert!(!ToastClock::new(true, Some(Duration::MAX)).counts_down());
908    }
909
910    #[test]
911    fn elapsing_counts_down_to_zero() {
912        let mut clock = ToastClock::new(true, Some(Duration::from_millis(150)));
913        assert!(!clock.elapse(TOAST_TICK));
914        assert!(clock.elapse(TOAST_TICK));
915        assert_eq!(clock.remaining, Duration::ZERO);
916        assert!(!clock.counts_down());
917    }
918
919    #[test]
920    fn actions_compare_by_handler_identity() {
921        let action = ToastAction::new("Undo", |_| {});
922        assert!(action == action.clone());
923        assert!(action != ToastAction::new("Undo", |_| {}));
924    }
925
926    fn record(id: &str, placement: ToastPlacement) -> ToastRecord {
927        create_toast_record(
928            ToastDetail::new(id).with_id(id).with_placement(placement),
929            placement,
930        )
931    }
932
933    fn open_ids(toasts: &[ToastRecord]) -> Vec<&str> {
934        toasts
935            .iter()
936            .filter(|toast| toast.open)
937            .map(|toast| toast.id.as_str())
938            .collect()
939    }
940
941    #[test]
942    fn records_take_defaults() {
943        let toast = create_toast_record(ToastDetail::default(), ToastPlacement::TopLeft);
944        assert!(toast.id.starts_with("ui-toast-"));
945        assert_eq!(toast.title, "Notification");
946        assert_eq!(toast.variant, ToastVariant::Default);
947        assert_eq!(toast.placement, ToastPlacement::TopLeft);
948        assert!(toast.open);
949        let empty_id =
950            create_toast_record(ToastDetail::default().with_id(""), ToastPlacement::TopLeft);
951        assert!(empty_id.id.starts_with("ui-toast-"));
952    }
953
954    #[test]
955    fn stacks_close_the_oldest_beyond_the_limit() {
956        let mut toasts = Vec::new();
957        for id in ["a", "b", "c"] {
958            apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 2);
959        }
960        apply_create(&mut toasts, record("top", ToastPlacement::TopLeft), 2);
961        assert_eq!(open_ids(&toasts), vec!["b", "c", "top"]);
962
963        limit_toast_placement(&mut toasts, ToastPlacement::BottomRight, 0);
964        assert_eq!(open_ids(&toasts), vec!["top"]);
965    }
966
967    #[test]
968    fn creating_an_existing_id_replaces_it() {
969        let mut toasts = Vec::new();
970        apply_create(&mut toasts, record("a", ToastPlacement::BottomRight), 5);
971        apply_create(&mut toasts, record("b", ToastPlacement::BottomRight), 5);
972        apply_create(&mut toasts, record("a", ToastPlacement::BottomRight), 5);
973        let ids: Vec<&str> = toasts.iter().map(|toast| toast.id.as_str()).collect();
974        assert_eq!(ids, vec!["b", "a"]);
975    }
976
977    #[test]
978    fn dismiss_targets_an_id_or_the_newest_open_toast() {
979        let mut toasts = Vec::new();
980        for id in ["a", "b", "c"] {
981            apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 5);
982        }
983        apply_dismiss(&mut toasts, Some("a"));
984        apply_dismiss(&mut toasts, None);
985        assert_eq!(open_ids(&toasts), vec!["b"]);
986        apply_dismiss(&mut toasts, Some("missing"));
987        assert_eq!(open_ids(&toasts), vec!["b"]);
988    }
989
990    #[test]
991    fn update_reopens_and_moves_closed_toasts() {
992        let mut toasts = Vec::new();
993        for id in ["a", "b"] {
994            apply_create(&mut toasts, record(id, ToastPlacement::BottomRight), 5);
995        }
996        apply_dismiss(&mut toasts, Some("a"));
997        apply_update(
998            &mut toasts,
999            "a",
1000            ToastDetail::default()
1001                .with_description("Retried")
1002                .with_duration(Duration::ZERO),
1003            5,
1004        );
1005        let ids: Vec<&str> = toasts.iter().map(|toast| toast.id.as_str()).collect();
1006        assert_eq!(ids, vec!["b", "a"]);
1007        assert!(toasts[1].open);
1008        assert_eq!(toasts[1].title, "a");
1009        assert_eq!(toasts[1].description.as_deref(), Some("Retried"));
1010        assert_eq!(toasts[1].duration, Some(Duration::ZERO));
1011
1012        apply_update(&mut toasts, "b", ToastDetail::new("Saved"), 5);
1013        assert_eq!(toasts[0].title, "Saved");
1014        apply_update(&mut toasts, "missing", ToastDetail::new("x"), 5);
1015        assert_eq!(toasts.len(), 2);
1016    }
1017}