1use std::collections::VecDeque;
48
49use iced::futures::channel::mpsc;
50use iced::futures::{Stream, StreamExt, stream};
51use iced::keyboard::key::Named;
52use iced::time::{Duration, Instant};
53use iced::widget::{self, column, container, mouse_area, row, stack, text};
54use iced::{
55 Alignment, Background, Border, Color, Element, Length, Padding, Shadow, Subscription, Theme,
56 Vector,
57};
58
59use crate::after_touch::after_touch;
60use crate::hit_slop::hit_slop;
61use crate::icon::{Glyph, themed};
62use crate::keys::{self, Chord, Keymap};
63use crate::primitives::button::{self, Size};
64use crate::primitives::icon_button::icon_button;
65use crate::solid::solid;
66use crate::theme::{Tokens, fade, mix, radius, space, text_size};
67
68pub const CHANNEL_CAPACITY: usize = 32;
70pub const BATCH_SIZE: usize = 16;
72pub const DEFAULT_DURATION: Duration = Duration::from_secs(5);
74pub const ACTION_DURATION: Duration = Duration::from_secs(10);
77pub const DEFAULT_LIMIT: usize = 3;
79pub const TICK: Duration = Duration::from_millis(250);
81
82pub const MAX_WIDTH: f32 = 356.0;
85pub const INSET: f32 = space::LG;
87
88pub type Sender = mpsc::Sender<Toast>;
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
93pub enum Variant {
94 #[default]
95 Default,
96 Success,
97 Destructive,
98}
99
100impl Variant {
101 pub const ALL: [Variant; 3] = [Variant::Default, Variant::Success, Variant::Destructive];
102
103 fn glyph(self) -> Option<Glyph> {
104 match self {
105 Variant::Default => None,
106 Variant::Success => Some(crate::lucide!(CircleCheck)),
107 Variant::Destructive => Some(crate::lucide!(CircleX)),
108 }
109 }
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
114pub enum Position {
115 TopLeft,
116 TopCenter,
117 TopRight,
118 BottomLeft,
119 BottomCenter,
120 #[default]
121 BottomRight,
122}
123
124impl Position {
125 pub const ALL: [Position; 6] = [
126 Position::TopLeft,
127 Position::TopCenter,
128 Position::TopRight,
129 Position::BottomLeft,
130 Position::BottomCenter,
131 Position::BottomRight,
132 ];
133
134 fn alignment(self) -> (Alignment, Alignment) {
135 match self {
136 Position::TopLeft => (Alignment::Start, Alignment::Start),
137 Position::TopCenter => (Alignment::Center, Alignment::Start),
138 Position::TopRight => (Alignment::End, Alignment::Start),
139 Position::BottomLeft => (Alignment::Start, Alignment::End),
140 Position::BottomCenter => (Alignment::Center, Alignment::End),
141 Position::BottomRight => (Alignment::End, Alignment::End),
142 }
143 }
144}
145
146#[derive(Debug, Clone, PartialEq)]
148pub struct Toast {
149 pub title: String,
150 pub description: Option<String>,
151 pub variant: Variant,
152 pub action: Option<String>,
154 pub duration: Option<Duration>,
156}
157
158pub fn toast(title: impl Into<String>) -> Toast {
160 Toast {
161 title: title.into(),
162 description: None,
163 variant: Variant::default(),
164 action: None,
165 duration: Some(DEFAULT_DURATION),
166 }
167}
168
169impl Toast {
170 pub fn description(mut self, description: impl Into<String>) -> Self {
171 self.description = Some(description.into());
172 self
173 }
174
175 pub fn variant(mut self, variant: Variant) -> Self {
176 self.variant = variant;
177 self
178 }
179
180 pub fn action(mut self, label: impl Into<String>) -> Self {
184 self.action = Some(label.into());
185 self
186 }
187
188 pub fn duration(mut self, duration: Duration) -> Self {
190 self.duration = Some(duration);
191 self
192 }
193
194 pub fn persistent(mut self) -> Self {
196 self.duration = None;
197 self
198 }
199
200 pub fn lifetime(&self) -> Option<Duration> {
204 let duration = self.duration?;
205 if self.action.is_some() {
206 return Some(duration.max(ACTION_DURATION));
207 }
208 Some(duration)
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
214pub struct Id(u64);
215
216#[derive(Debug, Clone)]
218pub enum Event {
219 Ready(Sender),
221 Received(Vec<Toast>),
223 Dismiss(Id),
224 Action(Id),
225 Tick(Instant),
226 Pause,
229 Resume,
231}
232
233#[derive(Debug, Clone)]
236pub enum Output<A = ()> {
237 Ready(Sender),
238 Action(Id, Toast),
240 Payload(A),
243}
244
245#[derive(Debug, Clone)]
246struct Entry<A> {
247 id: Id,
248 toast: Toast,
249 payload: Option<A>,
250 expires_at: Option<Instant>,
251}
252
253#[derive(Debug, Clone)]
267pub struct State<A = ()> {
268 entries: VecDeque<Entry<A>>,
269 next_id: u64,
270 limit: usize,
271 paused: bool,
272 last_tick: Option<Instant>,
273}
274
275impl<A> Default for State<A> {
276 fn default() -> Self {
277 Self {
278 entries: VecDeque::new(),
279 next_id: 0,
280 limit: DEFAULT_LIMIT,
281 paused: false,
282 last_tick: None,
283 }
284 }
285}
286
287impl State {
288 pub fn new() -> Self {
289 Self::default()
290 }
291}
292
293impl<A> State<A> {
294 pub fn with_limit(mut self, limit: usize) -> Self {
296 self.limit = limit.max(1);
297 self
298 }
299
300 pub fn limit(&self) -> usize {
301 self.limit
302 }
303
304 pub fn push(&mut self, toast: Toast) -> Id {
306 self.enqueue(toast, None)
307 }
308
309 pub fn push_with(&mut self, toast: Toast, payload: A) -> Id {
312 self.enqueue(toast, Some(payload))
313 }
314
315 fn enqueue(&mut self, toast: Toast, payload: Option<A>) -> Id {
316 let id = Id(self.next_id);
317 self.next_id += 1;
318 let entry = Entry {
319 id,
320 toast,
321 payload,
322 expires_at: None,
323 };
324 if entry.toast.action.is_some() {
325 self.insert_ahead(entry);
326 } else {
327 self.entries.push_back(entry);
328 }
329 id
330 }
331
332 fn insert_ahead(&mut self, entry: Entry<A>) {
335 let limit = self.limit;
336 if self.entries.len() < limit {
337 self.entries.push_back(entry);
338 return;
339 }
340 let newest_plain = (0..limit)
341 .rev()
342 .find(|&index| self.entries[index].toast.action.is_none());
343 let Some(index) = newest_plain else {
344 let after_actions = self
345 .entries
346 .iter()
347 .rposition(|entry| entry.toast.action.is_some())
348 .map_or(0, |index| index + 1);
349 self.entries.insert(after_actions, entry);
350 return;
351 };
352 let Some(mut displaced) = self.entries.remove(index) else {
353 return;
354 };
355 displaced.expires_at = None;
356 self.entries.insert(limit - 1, entry);
357 self.entries.insert(limit, displaced);
358 }
359
360 pub fn dismiss(&mut self, id: Id) -> Option<Toast> {
362 self.remove(id).map(|entry| entry.toast)
363 }
364
365 fn remove(&mut self, id: Id) -> Option<Entry<A>> {
366 let index = self.entries.iter().position(|entry| entry.id == id)?;
367 let entry = self.entries.remove(index);
368 self.settle();
369 entry
370 }
371
372 fn settle(&mut self) {
374 if self.entries.is_empty() {
375 self.paused = false;
376 }
377 }
378
379 pub fn tick(&mut self, now: Instant) -> Vec<Id> {
383 let last = self.last_tick.replace(now);
384 if self.paused
385 && let Some(last) = last
386 {
387 let paused_for = now.saturating_duration_since(last);
388 for entry in &mut self.entries {
389 entry.expires_at = entry.expires_at.map(|at| at + paused_for);
390 }
391 }
392
393 let mut expired = Vec::new();
394 self.entries.retain(|entry| {
395 let alive = entry.expires_at.is_none_or(|at| at > now);
396 if !alive {
397 expired.push(entry.id);
398 }
399 alive
400 });
401 self.settle();
402
403 let limit = self.limit;
404 for entry in self.entries.iter_mut().take(limit) {
405 if entry.expires_at.is_none() {
406 entry.expires_at = entry.toast.lifetime().map(|duration| now + duration);
407 }
408 }
409 expired
410 }
411
412 pub fn is_paused(&self) -> bool {
415 self.paused
416 }
417
418 pub fn update(&mut self, event: Event) -> Option<Output<A>> {
419 match event {
420 Event::Ready(sender) => Some(Output::Ready(sender)),
421 Event::Received(batch) => {
422 for toast in batch {
423 let _ = self.push(toast);
424 }
425 None
426 }
427 Event::Dismiss(id) => {
428 let _ = self.dismiss(id);
429 None
430 }
431 Event::Action(id) => {
432 let entry = self.remove(id)?;
433 Some(match entry.payload {
434 Some(payload) => Output::Payload(payload),
435 None => Output::Action(id, entry.toast),
436 })
437 }
438 Event::Tick(now) => {
439 let _ = self.tick(now);
440 None
441 }
442 Event::Pause => {
443 self.paused = true;
444 None
445 }
446 Event::Resume => {
447 self.paused = false;
448 None
449 }
450 }
451 }
452
453 pub fn visible(&self) -> impl Iterator<Item = (Id, &Toast)> {
456 self.entries
457 .iter()
458 .take(self.limit)
459 .map(|entry| (entry.id, &entry.toast))
460 }
461
462 pub fn waiting(&self) -> usize {
464 self.entries.len().saturating_sub(self.limit)
465 }
466
467 pub fn len(&self) -> usize {
468 self.entries.len()
469 }
470
471 pub fn is_empty(&self) -> bool {
472 self.entries.is_empty()
473 }
474
475 pub fn needs_tick(&self) -> bool {
477 self.visible().any(|(_, toast)| toast.lifetime().is_some())
478 }
479
480 pub fn ids(&self) -> impl Iterator<Item = Id> {
482 self.entries.iter().map(|entry| entry.id)
483 }
484}
485
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
488pub enum Action {
489 DismissLatest,
490 DismissAll,
491 ActivateLatest,
492}
493
494impl Action {
495 pub fn events<A>(self, state: &State<A>) -> Vec<Event> {
498 match self {
499 Action::DismissLatest => state
500 .visible()
501 .map(|(id, _)| id)
502 .max()
503 .map(Event::Dismiss)
504 .into_iter()
505 .collect(),
506 Action::DismissAll => state.ids().map(Event::Dismiss).collect(),
507 Action::ActivateLatest => state
508 .visible()
509 .filter(|(_, toast)| toast.action.is_some())
510 .map(|(id, _)| id)
511 .max()
512 .map(Event::Action)
513 .into_iter()
514 .collect(),
515 }
516 }
517}
518
519impl keys::Action for Action {
520 const ALL: &'static [Self] = &[
521 Action::DismissLatest,
522 Action::DismissAll,
523 Action::ActivateLatest,
524 ];
525
526 fn defaults() -> Keymap<Self> {
527 default_keymap()
528 }
529
530 fn name(self) -> &'static str {
531 match self {
532 Action::DismissLatest => "DismissLatest",
533 Action::DismissAll => "DismissAll",
534 Action::ActivateLatest => "ActivateLatest",
535 }
536 }
537
538 fn description(self) -> &'static str {
539 match self {
540 Action::DismissLatest => "Closes the newest visible toast.",
541 Action::DismissAll => "Closes every toast, including those waiting their turn.",
542 Action::ActivateLatest => {
543 "Presses the action button, such as Undo, of the newest visible toast that has one."
544 }
545 }
546 }
547}
548
549pub fn default_keymap() -> Keymap<Action> {
560 Keymap::new()
561 .bind(Chord::named(Named::Escape), Action::DismissLatest)
562 .bind(Chord::named(Named::Escape).shift(), Action::DismissAll)
563 .bind(Chord::character('z').alt(), Action::ActivateLatest)
564}
565
566pub fn subscription() -> Subscription<Event> {
568 Subscription::run(stream)
569}
570
571pub fn stream() -> impl Stream<Item = Event> {
573 let (sender, receiver) = mpsc::channel(CHANNEL_CAPACITY);
574 stream::once(async move { Event::Ready(sender) }).chain(batches(receiver).map(Event::Received))
575}
576
577pub fn batches<T>(receiver: impl Stream<Item = T>) -> impl Stream<Item = Vec<T>> {
579 receiver.ready_chunks(BATCH_SIZE)
580}
581
582pub fn timer<A>(state: &State<A>) -> Subscription<Event> {
584 if !state.needs_tick() {
585 return Subscription::none();
586 }
587 crate::ticker::every(TICK).map(Event::Tick)
588}
589
590pub fn close_button_id(id: Id) -> widget::Id {
592 widget::Id::from(format!("iced-cube-toast-close-{}", id.0))
593}
594
595pub struct Toasts<'a, Message, A = ()> {
597 state: &'a State<A>,
598 content: Element<'a, Message>,
599 position: Position,
600 inset: Padding,
601 max_width: f32,
602 on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
603}
604
605pub fn toasts<'a, Message, A>(
608 state: &'a State<A>,
609 content: impl Into<Element<'a, Message>>,
610) -> Toasts<'a, Message, A> {
611 Toasts {
612 state,
613 content: content.into(),
614 position: Position::default(),
615 inset: Padding::from(INSET),
616 max_width: MAX_WIDTH,
617 on_event: None,
618 }
619}
620
621impl<Message, A: std::fmt::Debug> std::fmt::Debug for Toasts<'_, Message, A> {
622 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623 f.debug_struct("Toasts")
624 .field("state", self.state)
625 .field("position", &self.position)
626 .field("inset", &self.inset)
627 .field("max_width", &self.max_width)
628 .finish_non_exhaustive()
629 }
630}
631
632impl<'a, Message, A> Toasts<'a, Message, A> {
633 pub fn position(mut self, position: Position) -> Self {
634 self.position = position;
635 self
636 }
637
638 pub fn inset(mut self, inset: impl Into<Padding>) -> Self {
642 self.inset = inset.into();
643 self
644 }
645
646 pub fn max_width(mut self, max_width: f32) -> Self {
650 self.max_width = max_width.max(0.0);
651 self
652 }
653
654 pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
655 self.on_event = Some(Box::new(on_event));
656 self
657 }
658}
659
660impl<'a, Message: Clone + 'a, A> From<Toasts<'a, Message, A>> for Element<'a, Message> {
661 fn from(toasts: Toasts<'a, Message, A>) -> Self {
662 let Toasts {
663 state,
664 content,
665 position,
666 inset,
667 max_width,
668 on_event,
669 } = toasts;
670 let emit = |event: Event| on_event.as_ref().map(|on_event| on_event(event));
671
672 let cards = state.visible().map(|(id, toast)| card(id, toast, &emit));
673
674 let cards = column(cards)
675 .spacing(space::SM)
676 .width(Length::Fill)
677 .max_width(max_width);
678 let cards: Element<'a, Message> = match (emit(Event::Pause), emit(Event::Resume)) {
681 (Some(pause), Some(resume)) => {
682 after_touch(mouse_area(cards).on_enter(pause).on_exit(resume))
683 }
684 _ => cards.into(),
685 };
686
687 let (align_x, align_y) = position.alignment();
688 let layer = container(cards)
689 .padding(inset)
690 .width(Length::Fill)
691 .height(Length::Fill)
692 .align_x(align_x)
693 .align_y(align_y);
694
695 stack![content, layer]
698 .width(Length::Fill)
699 .height(Length::Fill)
700 .into()
701 }
702}
703
704fn card<'a, Message: Clone + 'a>(
705 id: Id,
706 toast: &'a Toast,
707 emit: &impl Fn(Event) -> Option<Message>,
708) -> Element<'a, Message> {
709 let variant = toast.variant;
710
711 let mut body = column![
712 text(&toast.title)
713 .size(text_size::SM)
714 .font(crate::theme::semibold())
715 ]
716 .spacing(2)
717 .width(Length::Fill);
718 if let Some(description) = &toast.description {
719 body = body.push(
720 text(description)
721 .size(text_size::SM)
722 .style(move |theme: &Theme| text::Style {
723 color: Some(Tokens::of(theme).muted_foreground),
724 }),
725 );
726 }
727
728 let mut content = row![].spacing(space::MD).align_y(Alignment::Center);
729 if let Some(glyph) = variant.glyph() {
730 content = content.push(themed(glyph, 18.0, 1.0, move |theme| {
731 accent(&Tokens::of(theme), variant)
732 }));
733 }
734 content = content.push(body);
735 if let Some(label) = &toast.action {
736 content = content.push(hit_slop(
737 button::button(label.as_str())
738 .variant(button::Variant::Outline)
739 .size(Size::Sm)
740 .on_press_maybe(emit(Event::Action(id))),
741 HIT_SLOP,
742 ));
743 }
744 content = content.push(
745 container(hit_slop(
746 icon_button(crate::lucide!(X))
747 .label("Dismiss")
748 .tooltip(None)
749 .size(Size::Sm)
750 .on_press_maybe(emit(Event::Dismiss(id))),
751 HIT_SLOP,
752 ))
753 .id(close_button_id(id)),
754 );
755
756 let card = solid(
757 container(content)
758 .padding([space::MD, space::LG])
759 .width(Length::Fill)
760 .style(move |theme| style(&Tokens::of(theme), variant)),
761 );
762 #[cfg(feature = "icedwright")]
763 let card = {
764 use icedwright_probe::{Semantic, role, semantic};
765
766 fn finish<'a, Message: 'a, R: role::RoleKind>(
767 annotated: Semantic<'a, Message, Theme, iced::Renderer, R>,
768 toast: &'a Toast,
769 ) -> Element<'a, Message> {
770 let annotated = annotated
771 .name(toast.title.as_str())
772 .component("iced_cube::toast");
773 match &toast.description {
774 Some(description) => annotated.description(description.as_str()).into(),
775 None => annotated.into(),
776 }
777 }
778
779 match variant {
780 Variant::Destructive => finish(semantic(card).role(role::Alert), toast),
781 Variant::Default | Variant::Success => finish(semantic(card).role(role::Status), toast),
782 }
783 };
784 card
785}
786
787const HIT_SLOP: Padding = Padding {
790 top: 8.0,
791 bottom: 8.0,
792 left: space::MD / 2.0,
793 right: space::MD / 2.0,
794};
795
796pub fn accent(tokens: &Tokens, variant: Variant) -> Color {
798 match variant {
799 Variant::Default => tokens.foreground,
800 Variant::Success => tokens.success,
801 Variant::Destructive => tokens.destructive,
802 }
803}
804
805pub fn style(tokens: &Tokens, variant: Variant) -> container::Style {
807 let (background, border) = match variant {
808 Variant::Default => (tokens.background, tokens.border),
809 Variant::Success | Variant::Destructive => {
810 let accent = accent(tokens, variant);
811 (
812 mix(tokens.background, accent, 0.08),
813 mix(tokens.border, accent, 0.45),
814 )
815 }
816 };
817 let shadow_alpha = if tokens.is_dark { 0.5 } else { 0.12 };
818
819 container::Style {
820 background: Some(Background::Color(background)),
821 text_color: Some(tokens.foreground),
822 border: Border {
823 color: border,
824 width: 1.0,
825 radius: radius::LG.into(),
826 },
827 shadow: Shadow {
828 color: fade(Color::BLACK, shadow_alpha),
829 offset: Vector::new(0.0, 4.0),
830 blur_radius: 12.0,
831 },
832 snap: true,
833 }
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839 use crate::theme::{dark, light};
840 use futures::SinkExt;
841 use futures::executor::block_on;
842
843 fn titles(state: &State) -> Vec<&str> {
844 state
845 .visible()
846 .map(|(_, toast)| toast.title.as_str())
847 .collect()
848 }
849
850 #[test]
851 fn builder_defaults() {
852 let t = toast("Saved");
853 assert_eq!(t.title, "Saved");
854 assert_eq!(t.variant, Variant::Default);
855 assert_eq!(t.duration, Some(DEFAULT_DURATION));
856 assert!(t.description.is_none());
857 assert!(t.action.is_none());
858 assert!(toast("Sticky").persistent().duration.is_none());
859 }
860
861 #[test]
862 fn layer_defaults_keep_the_corner_and_options_override_them() {
863 let state: State = State::new();
864 let layer: Toasts<'_, (), ()> = toasts(&state, text("Content"));
865 assert_eq!(layer.position, Position::BottomRight);
866 assert_eq!(layer.inset, Padding::from(INSET));
867 assert_eq!(layer.max_width, MAX_WIDTH);
868 let layer: Toasts<'_, (), ()> = toasts(&state, text("Content"))
869 .inset(Padding::from(16).bottom(96))
870 .max_width(-1.0);
871 assert_eq!(layer.inset.bottom, 96.0);
872 assert_eq!(layer.max_width, 0.0);
873 }
874
875 #[test]
876 fn queue_keeps_arrival_order_and_unique_ids() {
877 let mut state = State::new();
878 let a = state.push(toast("a"));
879 let b = state.push(toast("b"));
880 let _ = state.update(Event::Received(vec![toast("c"), toast("d")]));
881
882 assert_ne!(a, b);
883 assert_eq!(state.len(), 4);
884 assert_eq!(titles(&state), ["a", "b", "c"]);
885 assert_eq!(state.waiting(), 1);
886 }
887
888 #[test]
889 fn limit_caps_visible_toasts_and_is_at_least_one() {
890 let mut state = State::new().with_limit(2);
891 for title in ["a", "b", "c"] {
892 let _ = state.push(toast(title));
893 }
894 assert_eq!(titles(&state), ["a", "b"]);
895 assert_eq!(State::new().with_limit(0).limit(), 1);
896 }
897
898 #[test]
899 fn toasts_expire_using_injected_time() {
900 let start = Instant::now();
901 let mut state = State::new();
902 let id = state.push(toast("a").duration(Duration::from_secs(2)));
903
904 assert!(state.tick(start).is_empty());
905 assert!(state.tick(start + Duration::from_millis(1999)).is_empty());
906 assert_eq!(state.tick(start + Duration::from_secs(2)), vec![id]);
907 assert!(state.is_empty());
908 }
909
910 #[test]
911 fn waiting_toasts_start_counting_when_shown() {
912 let start = Instant::now();
913 let mut state = State::new().with_limit(1);
914 let _ = state.push(toast("a").duration(Duration::from_secs(1)));
915 let _ = state.push(toast("b").duration(Duration::from_secs(1)));
916
917 let _ = state.tick(start);
918 let _ = state.tick(start + Duration::from_secs(1));
919 assert_eq!(titles(&state), ["b"]);
920
921 assert!(state.tick(start + Duration::from_millis(1500)).is_empty());
923 assert_eq!(state.tick(start + Duration::from_secs(2)).len(), 1);
924 }
925
926 #[test]
927 fn persistent_toasts_never_expire_and_need_no_timer() {
928 let start = Instant::now();
929 let mut state = State::new();
930 let _ = state.push(toast("a").persistent());
931 assert!(!state.needs_tick());
932
933 let _ = state.tick(start + Duration::from_secs(3600));
934 assert_eq!(state.len(), 1);
935 }
936
937 #[test]
938 fn empty_state_needs_no_timer() {
939 let mut state = State::new();
940 assert!(!state.needs_tick());
941 let _ = state.push(toast("a"));
942 assert!(state.needs_tick());
943 }
944
945 #[test]
946 fn dismiss_and_action_remove_the_toast() {
947 let mut state = State::new();
948 let a = state.push(toast("a"));
949 let b = state.push(toast("b").action("Undo"));
950
951 assert!(state.update(Event::Dismiss(a)).is_none());
952 let Some(Output::Action(id, toast)) = state.update(Event::Action(b)) else {
953 panic!("expected an action output");
954 };
955 assert_eq!(id, b);
956 assert_eq!(toast.action.as_deref(), Some("Undo"));
957 assert!(state.is_empty());
958 assert!(state.update(Event::Action(b)).is_none());
959 }
960
961 #[derive(Debug, Clone, PartialEq)]
962 enum Undo {
963 Restore(&'static str),
964 }
965
966 #[test]
967 fn an_action_hands_back_the_payload_it_was_queued_with() {
968 let mut state: State<Undo> = State::default();
969 let plain = state.push(toast("Saved").action("View"));
970 let undo = state.push_with(toast("Archived").action("Undo"), Undo::Restore("inbox"));
971 assert_eq!(state.len(), 2);
972
973 let Some(Output::Payload(payload)) = state.update(Event::Action(undo)) else {
974 panic!("expected the payload");
975 };
976 assert_eq!(payload, Undo::Restore("inbox"));
977 assert!(matches!(
978 state.update(Event::Action(plain)),
979 Some(Output::Action(id, _)) if id == plain
980 ));
981 assert!(state.is_empty());
982 }
983
984 #[test]
985 fn dismissing_drops_the_payload() {
986 let mut state: State<Undo> = State::default();
987 let undo = state.push_with(toast("Archived").action("Undo"), Undo::Restore("inbox"));
988 assert!(state.update(Event::Dismiss(undo)).is_none());
989 assert!(state.update(Event::Action(undo)).is_none());
990 let expired = state.push_with(
991 toast("Archived").duration(Duration::from_secs(1)),
992 Undo::Restore("inbox"),
993 );
994 let start = Instant::now();
995 let _ = state.tick(start);
996 assert_eq!(state.tick(start + Duration::from_secs(1)), vec![expired]);
997 assert!(state.update(Event::Action(expired)).is_none());
998 }
999
1000 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1001 let chord: Chord = chord.parse().unwrap();
1002 keymap.resolve(chord.key(), chord.modifiers())
1003 }
1004
1005 #[test]
1006 fn default_keymap_and_overrides() {
1007 let keymap = default_keymap();
1008 assert_eq!(press(&keymap, "Escape"), Some(Action::DismissLatest));
1009 assert_eq!(press(&keymap, "Shift+Escape"), Some(Action::DismissAll));
1010 assert_eq!(press(&keymap, "Alt+Z"), Some(Action::ActivateLatest));
1011 assert_eq!(press(&keymap, "Ctrl+Escape"), None);
1012 assert_eq!(press(&keymap, "Z"), None);
1013 for action in <Action as keys::Action>::ALL {
1014 assert!(!keymap.chords(action).is_empty(), "{action:?}");
1015 assert!(keys::Action::description(*action).ends_with('.'));
1016 }
1017
1018 let custom = keymap
1019 .unbind(&"Shift+Escape".parse().unwrap())
1020 .bind("Ctrl+Shift+X".parse().unwrap(), Action::DismissAll);
1021 assert_eq!(press(&custom, "Shift+Escape"), None);
1022 assert_eq!(press(&custom, "ctrl+shift+x"), Some(Action::DismissAll));
1023 }
1024
1025 #[test]
1026 fn dismiss_latest_closes_the_newest_visible_toast() {
1027 let mut state = State::new().with_limit(2);
1028 let _ = state.push(toast("a"));
1029 let b = state.push(toast("b"));
1030 let _ = state.push(toast("c"));
1031
1032 let events = Action::DismissLatest.events(&state);
1033 assert!(matches!(events.as_slice(), [Event::Dismiss(id)] if *id == b));
1034 for event in events {
1035 let _ = state.update(event);
1036 }
1037 assert_eq!(titles(&state), ["a", "c"]);
1038 assert!(Action::DismissLatest.events(&State::new()).is_empty());
1039 }
1040
1041 #[test]
1042 fn action_toasts_last_at_least_the_action_duration() {
1043 assert_eq!(toast("a").action("Undo").lifetime(), Some(ACTION_DURATION));
1044 let long = Duration::from_secs(30);
1045 assert_eq!(
1046 toast("a").action("Undo").duration(long).lifetime(),
1047 Some(long)
1048 );
1049 assert_eq!(toast("a").action("Undo").persistent().lifetime(), None);
1050 assert_eq!(toast("a").lifetime(), Some(DEFAULT_DURATION));
1051
1052 let start = Instant::now();
1053 let mut state = State::new();
1054 let _ = state.push(toast("Deleted").action("Undo"));
1055 let _ = state.tick(start);
1056 assert!(state.tick(start + DEFAULT_DURATION).is_empty());
1057 assert_eq!(state.tick(start + ACTION_DURATION).len(), 1);
1058 }
1059
1060 #[test]
1061 fn an_action_toast_takes_the_place_of_the_newest_plain_one() {
1062 let start = Instant::now();
1063 let mut state = State::new();
1064 for title in ["a", "b", "c", "d"] {
1065 let _ = state.push(toast(title));
1066 }
1067 let _ = state.tick(start);
1068 let _ = state.push(toast("Undo me").action("Undo"));
1069 assert_eq!(titles(&state), ["a", "b", "Undo me"]);
1070 assert_eq!(state.waiting(), 2);
1071
1072 let _ = state.tick(start + Duration::from_secs(1));
1074 let _ = state.tick(start + DEFAULT_DURATION);
1075 assert_eq!(titles(&state), ["Undo me", "c", "d"]);
1076 assert!(state.tick(start + Duration::from_secs(9)).is_empty());
1077 assert_eq!(state.tick(start + DEFAULT_DURATION * 2).len(), 2);
1078 }
1079
1080 #[test]
1081 fn action_toasts_wait_ahead_of_plain_ones_when_every_visible_toast_has_an_action() {
1082 let mut state = State::new().with_limit(2);
1083 let _ = state.push(toast("plain"));
1084 let _ = state.push(toast("one").action("Undo"));
1085 let _ = state.push(toast("two").action("Undo"));
1086 assert_eq!(titles(&state), ["one", "two"]);
1087 let _ = state.push(toast("three").action("Undo"));
1088 let order: Vec<_> = state
1089 .entries
1090 .iter()
1091 .map(|entry| entry.toast.title.as_str())
1092 .collect();
1093 assert_eq!(order, ["one", "two", "three", "plain"]);
1094 }
1095
1096 #[test]
1097 fn a_plain_toast_with_room_just_joins_the_end() {
1098 let mut state = State::new();
1099 let _ = state.push(toast("one").action("Undo"));
1100 let _ = state.push(toast("plain"));
1101 let _ = state.push(toast("two").action("Undo"));
1102 assert_eq!(titles(&state), ["one", "plain", "two"]);
1103 }
1104
1105 #[test]
1106 fn hovering_pauses_every_countdown() {
1107 let start = Instant::now();
1108 let mut state = State::new();
1109 let id = state.push(toast("a").duration(Duration::from_secs(2)));
1110 let _ = state.tick(start);
1111
1112 let _ = state.update(Event::Pause);
1113 assert!(state.is_paused());
1114 assert!(state.needs_tick());
1115 assert!(state.tick(start + Duration::from_secs(1)).is_empty());
1116 assert!(state.tick(start + Duration::from_secs(10)).is_empty());
1117
1118 let _ = state.update(Event::Resume);
1119 assert!(!state.is_paused());
1120 let resumed = start + Duration::from_secs(10);
1122 assert!(state.tick(resumed + Duration::from_millis(1900)).is_empty());
1123 assert_eq!(state.tick(resumed + Duration::from_secs(2)), vec![id]);
1124 }
1125
1126 #[test]
1127 fn the_pause_ends_when_the_last_toast_closes() {
1128 let mut state = State::new();
1129 let id = state.push(toast("a"));
1130 let _ = state.update(Event::Pause);
1131 let _ = state.dismiss(id);
1132 assert!(!state.is_paused());
1133 }
1134
1135 #[test]
1136 fn activate_latest_presses_the_newest_visible_action() {
1137 let mut state: State<Undo> = State::default();
1138 assert!(Action::ActivateLatest.events(&state).is_empty());
1139 let _ = state.push(toast("plain"));
1140 assert!(Action::ActivateLatest.events(&state).is_empty());
1141
1142 let _ = state.push_with(toast("first").action("Undo"), Undo::Restore("a"));
1143 let second = state.push_with(toast("second").action("Undo"), Undo::Restore("b"));
1144 let _ = state.push(toast("newer plain"));
1145 let events = Action::ActivateLatest.events(&state);
1146 assert!(matches!(events.as_slice(), [Event::Action(id)] if *id == second));
1147
1148 let outputs: Vec<_> = events
1149 .into_iter()
1150 .filter_map(|event| state.update(event))
1151 .collect();
1152 assert!(matches!(
1153 outputs.as_slice(),
1154 [Output::Payload(Undo::Restore("b"))]
1155 ));
1156 }
1157
1158 #[test]
1159 fn dismiss_all_includes_waiting_toasts() {
1160 let mut state = State::new().with_limit(1);
1161 for title in ["a", "b", "c"] {
1162 let _ = state.push(toast(title));
1163 }
1164 let events = Action::DismissAll.events(&state);
1165 assert_eq!(events.len(), 3);
1166 for event in events {
1167 let _ = state.update(event);
1168 }
1169 assert!(state.is_empty());
1170 assert!(Action::DismissAll.events(&state).is_empty());
1171 }
1172
1173 #[test]
1174 fn ready_hands_the_sender_back() {
1175 let (sender, _receiver) = mpsc::channel(1);
1176 let output = State::new().update(Event::Ready(sender));
1177 assert!(matches!(output, Some(Output::Ready(_))));
1178 }
1179
1180 #[test]
1181 fn stream_emits_ready_first_then_batches() {
1182 let mut events = Box::pin(stream());
1183 let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
1184 panic!("first event must be Ready");
1185 };
1186
1187 block_on(async {
1188 for title in ["a", "b", "c"] {
1189 sender.send(toast(title)).await.ok();
1190 }
1191 });
1192 let Some(Event::Received(batch)) = block_on(events.next()) else {
1193 panic!("expected a batch");
1194 };
1195 let titles: Vec<_> = batch.iter().map(|toast| toast.title.as_str()).collect();
1196 assert_eq!(titles, ["a", "b", "c"]);
1197 }
1198
1199 #[test]
1200 fn batches_split_bursts_at_batch_size() {
1201 let items = stream::iter(0..BATCH_SIZE + 3);
1202 let sizes: Vec<_> = block_on(batches(items).map(|batch| batch.len()).collect());
1203 assert_eq!(sizes, [BATCH_SIZE, 3]);
1204 }
1205
1206 #[test]
1207 fn default_style_uses_background_and_border_tokens() {
1208 for theme in [light(), dark()] {
1209 let tokens = Tokens::of(&theme);
1210 let style = style(&tokens, Variant::Default);
1211 assert_eq!(style.background, Some(Background::Color(tokens.background)));
1212 assert_eq!(style.border.color, tokens.border);
1213 assert_eq!(style.text_color, Some(tokens.foreground));
1214 }
1215 }
1216
1217 #[test]
1218 fn variants_are_tinted_differently_in_both_themes() {
1219 for theme in [light(), dark()] {
1220 let tokens = Tokens::of(&theme);
1221 let styles = Variant::ALL.map(|variant| style(&tokens, variant).border.color);
1222 assert_ne!(styles[0], styles[1]);
1223 assert_ne!(styles[1], styles[2]);
1224 assert_eq!(accent(&tokens, Variant::Destructive), tokens.destructive);
1225 assert_eq!(accent(&tokens, Variant::Success), tokens.success);
1226 }
1227 }
1228
1229 #[test]
1230 fn dark_shadow_is_stronger() {
1231 let light = style(&Tokens::of(&light()), Variant::Default)
1232 .shadow
1233 .color
1234 .a;
1235 let dark = style(&Tokens::of(&dark()), Variant::Default).shadow.color.a;
1236 assert!(dark > light);
1237 }
1238}