1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ToastVariant {
22 #[default]
24 Default,
25 Success,
27 Warning,
29 Destructive,
31}
32
33impl ToastVariant {
34 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum ToastAnnounce {
61 Off,
63 Polite,
65 Assertive,
67}
68
69impl ToastAnnounce {
70 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum ToastPlacement {
92 BottomCenter,
94 BottomLeft,
96 #[default]
98 BottomRight,
99 TopCenter,
101 TopLeft,
103 TopRight,
105}
106
107impl ToastPlacement {
108 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#[derive(Props, Clone, PartialEq)]
123pub struct ToastProps {
124 #[props(default)]
126 pub variant: ToastVariant,
127 #[props(into)]
129 pub announce: Option<ToastAnnounce>,
130 #[props(default, into)]
132 pub glass: Glass,
133 #[props(into)]
135 pub role: Option<String>,
136 #[props(into)]
139 pub aria_live: Option<String>,
140 #[props(into)]
142 pub class: Option<String>,
143 #[props(extends = GlobalAttributes, extends = aside)]
145 pub attributes: Vec<Attribute>,
146 pub children: Element,
148}
149
150#[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#[derive(Props, Clone, PartialEq)]
187pub struct ToastViewportProps {
188 #[props(default)]
190 pub placement: ToastPlacement,
191 #[props(default = 3)]
193 pub max_count: usize,
194 #[props(default = "Notifications".to_string(), into)]
196 pub aria_label: String,
197 #[props(default = "off".to_string(), into)]
199 pub aria_live: String,
200 #[props(default = "false".to_string(), into)]
202 pub aria_atomic: String,
203 #[props(into)]
205 pub class: Option<String>,
206 #[props(extends = GlobalAttributes, extends = div)]
208 pub attributes: Vec<Attribute>,
209 pub children: Element,
211}
212
213#[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#[derive(Clone)]
248pub struct ToastActionHandler(Rc<RefCell<dyn FnMut(String)>>);
249
250impl ToastActionHandler {
251 pub fn new(handler: impl FnMut(String) + 'static) -> Self {
253 Self(Rc::new(RefCell::new(handler)))
254 }
255
256 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#[derive(Clone, PartialEq)]
272pub struct ToastAction {
273 pub label: String,
275 pub on_click: Option<ToastActionHandler>,
277}
278
279impl ToastAction {
280 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#[derive(Clone, Default, PartialEq)]
291pub struct ToastDetail {
292 pub title: Option<String>,
294 pub description: Option<String>,
296 pub variant: Option<ToastVariant>,
298 pub announce: Option<ToastAnnounce>,
300 pub duration: Option<Duration>,
303 pub id: Option<String>,
305 pub max: Option<usize>,
307 pub placement: Option<ToastPlacement>,
309 pub action: Option<ToastAction>,
311}
312
313impl ToastDetail {
314 pub fn new(title: impl Into<String>) -> Self {
316 Self {
317 title: Some(title.into()),
318 ..Self::default()
319 }
320 }
321
322 #[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 #[must_use]
331 pub fn with_variant(mut self, variant: ToastVariant) -> Self {
332 self.variant = Some(variant);
333 self
334 }
335
336 #[must_use]
338 pub fn with_announce(mut self, announce: ToastAnnounce) -> Self {
339 self.announce = Some(announce);
340 self
341 }
342
343 #[must_use]
345 pub fn with_duration(mut self, duration: Duration) -> Self {
346 self.duration = Some(duration);
347 self
348 }
349
350 #[must_use]
352 pub fn with_placement(mut self, placement: ToastPlacement) -> Self {
353 self.placement = Some(placement);
354 self
355 }
356
357 #[must_use]
359 pub fn with_action(mut self, action: ToastAction) -> Self {
360 self.action = Some(action);
361 self
362 }
363
364 #[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#[derive(Clone, PartialEq)]
374pub struct ToastRecord {
375 pub id: String,
377 pub title: String,
379 pub description: Option<String>,
381 pub variant: ToastVariant,
383 pub announce: Option<ToastAnnounce>,
385 pub duration: Option<Duration>,
387 pub placement: ToastPlacement,
389 pub open: bool,
391 pub max: Option<usize>,
393 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
417fn 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#[derive(Clone, Copy)]
495pub struct ToastApi {
496 toasts: Signal<Vec<ToastRecord>>,
497 placement: CopyValue<ToastPlacement>,
498 max_count: CopyValue<usize>,
499 scope: ScopeId,
501}
502
503impl ToastApi {
504 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 pub fn dismiss(&self, id: Option<&str>) {
516 let mut toasts = self.toasts;
517 apply_dismiss(&mut toasts.write(), id);
518 }
519
520 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 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 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
547pub 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#[derive(Props, Clone, PartialEq)]
559pub struct ToastProviderProps {
560 #[props(default = TOAST_MAX)]
562 pub max_count: usize,
563 #[props(default)]
565 pub placement: ToastPlacement,
566 pub children: Element,
568}
569
570#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
625struct ToastClock {
626 open: bool,
628 paused: u8,
630 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 fn reset(&mut self, open: bool, duration: Option<Duration>) {
645 self.open = open;
646 self.remaining = duration.unwrap_or(TOAST_DURATION);
647 }
648
649 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 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 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#[derive(Clone, Copy)]
690struct ToastTimer {
691 clock: CopyValue<ToastClock>,
692 countdown: CopyValue<Option<Task>>,
693 removal: CopyValue<Option<Task>>,
694}
695
696impl ToastTimer {
697 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 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 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 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}