lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
//! Toasts: the static `Toast` and `ToastViewport`, and `ToastProvider` with [`use_toast`].

// cspell:words onfocusin onfocusout

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;

/// Tone of a [`Toast`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastVariant {
    /// Neutral information.
    #[default]
    Default,
    /// Positive outcome.
    Success,
    /// Needs attention.
    Warning,
    /// Error or failure. Announced assertively as an `alert`.
    Destructive,
}

impl ToastVariant {
    /// The class suffix and `data-variant` value.
    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"
        }
    }
}

/// How a toast announces its content to assistive technology.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastAnnounce {
    /// Keep the notification visible without duplicating an application-owned announcement.
    Off,
    /// Announce after the current speech.
    Polite,
    /// Interrupt the current speech for urgent feedback.
    Assertive,
}

impl ToastAnnounce {
    /// The `aria-live` value.
    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",
    }
}

/// Corner or edge of the viewport where toasts stack.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ToastPlacement {
    /// Bottom edge, centered.
    BottomCenter,
    /// Bottom-left corner.
    BottomLeft,
    /// Bottom-right corner.
    #[default]
    BottomRight,
    /// Top edge, centered.
    TopCenter,
    /// Top-left corner.
    TopLeft,
    /// Top-right corner.
    TopRight,
}

impl ToastPlacement {
    /// The `data-placement` value.
    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",
        }
    }
}

/// Props for [`Toast`].
#[derive(Props, Clone, PartialEq)]
pub struct ToastProps {
    /// Tone.
    #[props(default)]
    pub variant: ToastVariant,
    /// Announcement mode. Omitted uses the variant's default; explicit `aria_live` takes precedence.
    #[props(into)]
    pub announce: Option<ToastAnnounce>,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Overrides the resolved announcement role: `group`, `status`, or `alert`.
    #[props(into)]
    pub role: Option<String>,
    /// Overrides the live-region politeness: `assertive` for destructive toasts, otherwise
    /// `polite`.
    #[props(into)]
    pub aria_live: Option<String>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<aside>` or global attribute.
    #[props(extends = GlobalAttributes, extends = aside)]
    pub attributes: Vec<Attribute>,
    /// Toast content, usually a `strong` title and a short paragraph.
    pub children: Element,
}

/// A static notification surface. For timed toasts, use [`ToastProvider`] and [`use_toast`].
#[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}
        }
    }
}

/// Props for [`ToastViewport`].
#[derive(Props, Clone, PartialEq)]
pub struct ToastViewportProps {
    /// Where the stack sits.
    #[props(default)]
    pub placement: ToastPlacement,
    /// The most toasts the stack shows. Defaults to 3.
    #[props(default = 3)]
    pub max_count: usize,
    /// Accessible name. Defaults to "Notifications".
    #[props(default = "Notifications".to_string(), into)]
    pub aria_label: String,
    /// Live-region politeness. Defaults to `off`; each toast owns its announcement.
    #[props(default = "off".to_string(), into)]
    pub aria_live: String,
    /// Whether the region is read as a whole. Defaults to `false`.
    #[props(default = "false".to_string(), into)]
    pub aria_atomic: String,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// [`Toast`]s.
    pub children: Element,
}

/// A fixed notification region that stacks static [`Toast`]s. [`ToastProvider`] renders its own.
#[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);

/// The click handler of a [`ToastAction`].
///
/// The toast owns it, so it keeps working after the component that created the toast unmounts.
/// It runs in the [`ToastProvider`]'s scope, so tasks it spawns live as long as the provider.
/// Signals it captures must still be alive when it runs: capture state of a component that
/// outlives the toast, not of one that may unmount first.
#[derive(Clone)]
pub struct ToastActionHandler(Rc<RefCell<dyn FnMut(String)>>);

impl ToastActionHandler {
    /// Wraps a closure that receives the toast id.
    pub fn new(handler: impl FnMut(String) + 'static) -> Self {
        Self(Rc::new(RefCell::new(handler)))
    }

    /// Calls the handler with the toast id. A call made from inside the same handler is skipped.
    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)
    }
}

/// An action button inside a toast.
#[derive(Clone, PartialEq)]
pub struct ToastAction {
    /// Button label.
    pub label: String,
    /// Called with the toast id before the toast is dismissed.
    pub on_click: Option<ToastActionHandler>,
}

impl ToastAction {
    /// An action with a label and a click handler that receives the toast id.
    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)),
        }
    }
}

/// What to show in a toast, passed to [`ToastApi::create`] and [`ToastApi::update`].
#[derive(Clone, Default, PartialEq)]
pub struct ToastDetail {
    /// Heading. Defaults to "Notification".
    pub title: Option<String>,
    /// Supporting text.
    pub description: Option<String>,
    /// Tone. Defaults to [`ToastVariant::Default`].
    pub variant: Option<ToastVariant>,
    /// Announcement mode. Omitted uses the tone's default and preserves the setting on update.
    pub announce: Option<ToastAnnounce>,
    /// Time before the toast dismisses itself. Defaults to 5 seconds; `Duration::ZERO` or
    /// `Duration::MAX` keeps it until dismissed.
    pub duration: Option<Duration>,
    /// A stable id, so a later create or update replaces the same toast.
    pub id: Option<String>,
    /// The most open toasts in this toast's stack.
    pub max: Option<usize>,
    /// Stack placement. Defaults to the provider placement.
    pub placement: Option<ToastPlacement>,
    /// An action button.
    pub action: Option<ToastAction>,
}

impl ToastDetail {
    /// A toast with a title.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: Some(title.into()),
            ..Self::default()
        }
    }

    /// Sets the supporting text.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the tone.
    #[must_use]
    pub fn with_variant(mut self, variant: ToastVariant) -> Self {
        self.variant = Some(variant);
        self
    }

    /// Sets how the notification announces its content.
    #[must_use]
    pub fn with_announce(mut self, announce: ToastAnnounce) -> Self {
        self.announce = Some(announce);
        self
    }

    /// Sets the time before the toast dismisses itself.
    #[must_use]
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Sets the stack placement.
    #[must_use]
    pub fn with_placement(mut self, placement: ToastPlacement) -> Self {
        self.placement = Some(placement);
        self
    }

    /// Sets the action button.
    #[must_use]
    pub fn with_action(mut self, action: ToastAction) -> Self {
        self.action = Some(action);
        self
    }

    /// Sets a stable id.
    #[must_use]
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }
}

/// A toast held by a [`ToastProvider`].
#[derive(Clone, PartialEq)]
pub struct ToastRecord {
    /// Element id, `ui-toast-N` unless the detail set one.
    pub id: String,
    /// Heading.
    pub title: String,
    /// Supporting text.
    pub description: Option<String>,
    /// Tone.
    pub variant: ToastVariant,
    /// Explicit announcement mode, or the tone's default when absent.
    pub announce: Option<ToastAnnounce>,
    /// Time before the toast dismisses itself.
    pub duration: Option<Duration>,
    /// Stack placement.
    pub placement: ToastPlacement,
    /// False while the toast plays its exit before removal.
    pub open: bool,
    /// The most open toasts in this toast's stack.
    pub max: Option<usize>,
    /// Action button.
    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,
    }
}

/// Closes the oldest open toasts of a placement beyond `max`, like `limitToastPlacement`.
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);
}

/// Creates, updates, and dismisses the toasts of the nearest [`ToastProvider`].
///
/// It is `Copy`, so event handlers can capture it.
#[derive(Clone, Copy)]
pub struct ToastApi {
    toasts: Signal<Vec<ToastRecord>>,
    placement: CopyValue<ToastPlacement>,
    max_count: CopyValue<usize>,
    /// The provider's scope, where action handlers run.
    scope: ScopeId,
}

impl ToastApi {
    /// Shows a toast and returns its id. Creating a toast with an existing id replaces it.
    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
    }

    /// Starts closing a toast, or the newest open toast when `id` is `None`.
    pub fn dismiss(&self, id: Option<&str>) {
        let mut toasts = self.toasts;
        apply_dismiss(&mut toasts.write(), id);
    }

    /// Changes a toast and reopens it if it was closing.
    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);
    }

    /// The current toasts, oldest first. Reading subscribes the component.
    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);
    }

    /// Runs a toast action in the provider's scope, so tasks it spawns outlive the toast, which is
    /// removed shortly after the action dismisses it.
    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),
        }
    }
}

/// The toast API of the nearest [`ToastProvider`].
///
/// # Panics
///
/// Panics when no `ToastProvider` wraps the calling component.
pub fn use_toast() -> ToastApi {
    try_use_context::<ToastApi>()
        .unwrap_or_else(|| panic!("use_toast must be used inside a ToastProvider."))
}

/// Props for [`ToastProvider`].
#[derive(Props, Clone, PartialEq)]
pub struct ToastProviderProps {
    /// The most open toasts per stack. Defaults to 5.
    #[props(default = TOAST_MAX)]
    pub max_count: usize,
    /// Default stack placement.
    #[props(default)]
    pub placement: ToastPlacement,
    /// The app. Components inside can call [`use_toast`].
    pub children: Element,
}

/// Provides [`use_toast`] to its children and renders one live region per stack placement.
///
/// Toasts dismiss themselves after their duration, pause while hovered or focused (web and
/// desktop), and close on Escape or their dismiss button.
#[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;

/// Timer state of one provider toast, free of tasks so its transitions are unit-tested. Time is
/// counted in short ticks, so pausing keeps the remaining duration without a wall clock (which
/// the web target lacks).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ToastClock {
    /// False once the toast is dismissed and waits for removal.
    open: bool,
    /// `PAUSE_HOVER` and `PAUSE_FOCUS` bits.
    paused: u8,
    /// Time left before the toast dismisses itself.
    remaining: Duration,
}

impl ToastClock {
    fn new(open: bool, duration: Option<Duration>) -> Self {
        Self {
            open,
            paused: 0,
            remaining: duration.unwrap_or(TOAST_DURATION),
        }
    }

    /// Takes the record's open state and duration. Pause reasons carry over.
    fn reset(&mut self, open: bool, duration: Option<Duration>) {
        self.open = open;
        self.remaining = duration.unwrap_or(TOAST_DURATION);
    }

    /// Whether the countdown runs: the toast is open, has a finite time left, and nothing pauses
    /// it.
    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;
    }

    /// Drops a pause reason and returns whether the countdown starts again. A closed toast never
    /// restarts, because it is waiting for removal.
    fn resume(&mut self, reason: u8) -> bool {
        if self.paused & reason == 0 {
            return false;
        }

        self.paused &= !reason;
        self.counts_down()
    }

    /// Counts `step` down and returns whether the time ran out.
    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();
    }
}

/// The tasks of one provider toast around its [`ToastClock`]. The countdown and the removal are
/// separate tasks: hover and focus pause and resume only the countdown, so they can never cancel
/// the removal of a dismissed toast.
#[derive(Clone, Copy)]
struct ToastTimer {
    clock: CopyValue<ToastClock>,
    countdown: CopyValue<Option<Task>>,
    removal: CopyValue<Option<Task>>,
}

impl ToastTimer {
    /// Follows the record: an open toast counts down, and a closed one is removed after its exit.
    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() {
        // A toast dismissed while hovered: leaving it within the exit delay used to restart the
        // countdown (and cancel the removal), so the closed toast stayed in the list.
        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());

        // Reopening through `update` counts down again.
        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));

        // Zero and `Duration::MAX` keep the toast until it is dismissed.
        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);
    }
}