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
//! `Calendar`: a month grid with roving focus, min/max bounds, and keyboard navigation.

use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use dioxus::prelude::*;

use super::dates::{
    CivilDate, MONTH_NAMES, MONTH_SHORT_NAMES, WEEKDAY_NAMES, WEEKDAY_SHORT_NAMES, bounds_valid,
    utc_today,
};
use crate::class::{Glass, compose};
use crate::hooks::{use_controllable, use_unique_id};
use crate::icons::{Icon, lucide};

/// Text the date controls show. Every field is optional; unset fields use the built-in English
/// copy (or the navigation labels of the `locale` language pack).
///
/// Month and weekday names are English by default because JavaScript `Intl` is not available on
/// every Dioxus renderer. Pass all twelve or seven names to localize them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CalendarLabels {
    /// Accessible name of the previous-month button.
    pub previous_month: Option<String>,
    /// Accessible name of the next-month button.
    pub next_month: Option<String>,
    /// Placeholder and dialog name of a `DatePicker`.
    pub choose_date: Option<String>,
    /// Month names, January first, used in the month heading and day labels.
    pub month_names: Option<[String; 12]>,
    /// Short month names, January first, used in the `DatePicker` value.
    pub month_short_names: Option<[String; 12]>,
    /// Column headers, Monday first.
    pub weekday_short_names: Option<[String; 7]>,
    /// Weekday names, Monday first, used in day labels.
    pub weekday_names: Option<[String; 7]>,
}

/// Navigation copy from `resolveLumenDateLabels` in `@santi020k/lumen-core`.
struct DateLabelPack {
    previous_month: &'static str,
    next_month: &'static str,
    choose_date: &'static str,
}

// cspell:words siguiente Elegir fecha Mois précédent suivant Choisir anterior próximo Escolher autofocus
// cspell:words الشهر السابق التالي اختيار تاريخ
const DATE_LABEL_PACKS: [(&str, DateLabelPack); 5] = [
    (
        "en",
        DateLabelPack {
            previous_month: "Previous month",
            next_month: "Next month",
            choose_date: "Choose date",
        },
    ),
    (
        "es",
        DateLabelPack {
            previous_month: "Mes anterior",
            next_month: "Mes siguiente",
            choose_date: "Elegir fecha",
        },
    ),
    (
        "fr",
        DateLabelPack {
            previous_month: "Mois précédent",
            next_month: "Mois suivant",
            choose_date: "Choisir une date",
        },
    ),
    (
        "pt",
        DateLabelPack {
            previous_month: "Mês anterior",
            next_month: "Próximo mês",
            choose_date: "Escolher data",
        },
    ),
    (
        "ar",
        DateLabelPack {
            previous_month: "الشهر السابق",
            next_month: "الشهر التالي",
            choose_date: "اختيار تاريخ",
        },
    ),
];

fn label_pack(locale: Option<&str>) -> &'static DateLabelPack {
    let language: String = locale
        .unwrap_or("en")
        .trim()
        .chars()
        .take_while(char::is_ascii_alphabetic)
        .take(8)
        .collect::<String>()
        .to_ascii_lowercase();

    DATE_LABEL_PACKS
        .iter()
        .find(|(code, _)| *code == language)
        .map_or(&DATE_LABEL_PACKS[0].1, |(_, pack)| pack)
}

fn non_empty(value: Option<&String>) -> Option<&str> {
    value
        .map(String::as_str)
        .filter(|text| !text.trim().is_empty())
}

/// Labels resolved against the locale pack and the English names.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ResolvedDateLabels {
    pub(crate) previous_month: String,
    pub(crate) next_month: String,
    pub(crate) choose_date: String,
    labels: CalendarLabels,
}

impl ResolvedDateLabels {
    pub(crate) fn new(locale: Option<&str>, labels: Option<&CalendarLabels>) -> Self {
        let pack = label_pack(locale);
        let labels = labels.cloned().unwrap_or_default();

        Self {
            previous_month: non_empty(labels.previous_month.as_ref())
                .unwrap_or(pack.previous_month)
                .to_string(),
            next_month: non_empty(labels.next_month.as_ref())
                .unwrap_or(pack.next_month)
                .to_string(),
            choose_date: non_empty(labels.choose_date.as_ref())
                .unwrap_or(pack.choose_date)
                .to_string(),
            labels,
        }
    }

    fn month_name(&self, date: CivilDate) -> &str {
        let index = (date.month() - 1) as usize;

        self.labels
            .month_names
            .as_ref()
            .map_or(MONTH_NAMES[index], |names| names[index].as_str())
    }

    fn month_short_name(&self, date: CivilDate) -> &str {
        let index = (date.month() - 1) as usize;

        self.labels
            .month_short_names
            .as_ref()
            .map_or(MONTH_SHORT_NAMES[index], |names| names[index].as_str())
    }

    fn weekday_short_name(&self, column: usize) -> &str {
        self.labels
            .weekday_short_names
            .as_ref()
            .map_or(WEEKDAY_SHORT_NAMES[column], |names| names[column].as_str())
    }

    fn weekday_name(&self, column: usize) -> &str {
        self.labels
            .weekday_names
            .as_ref()
            .map_or(WEEKDAY_NAMES[column], |names| names[column].as_str())
    }

    /// `March 2024`, like `Intl.DateTimeFormat('en', { month: 'long', year: 'numeric' })`.
    pub(crate) fn month_heading(&self, month: CivilDate) -> String {
        format!("{} {}", self.month_name(month), month.year())
    }

    /// `Friday, March 1, 2024`, the en-US long date with weekday.
    pub(crate) fn day_label(&self, date: CivilDate) -> String {
        format!(
            "{}, {} {}, {}",
            self.weekday_name(date.weekday_index()),
            self.month_name(date),
            date.day(),
            date.year()
        )
    }

    /// `Mar 1, 2024`, the en-US medium date the `DatePicker` trigger shows.
    pub(crate) fn short_date(&self, date: CivilDate) -> String {
        format!(
            "{} {}, {}",
            self.month_short_name(date),
            date.day(),
            date.year()
        )
    }
}

/// The local date where `eval` can read it (web and desktop), otherwise the UTC date from the
/// system clock, unless the app passes its own `today`.
pub(crate) fn use_calendar_today(today: Option<&str>) -> Option<CivilDate> {
    let mut local = use_signal(utc_today);

    use_effect(move || {
        spawn(async move {
            let script =
                "const d = new Date(); return [d.getFullYear(), d.getMonth() + 1, d.getDate()];";

            if let Ok((year, month, day)) = document::eval(script).join::<(i64, u32, u32)>().await
                && let Some(date) = CivilDate::new(year, month, day)
                && *local.peek() != Some(date)
            {
                local.set(Some(date));
            }
        });
    });

    today.and_then(CivilDate::parse).or(*local.read())
}

/// Pending-focus marker for "whichever day holds roving focus".
const ROVING_DAY: &str = "roving";

/// The bounds a calendar uses: `0001-01-01` to `9999-12-31` unless narrowed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct CalendarBounds {
    pub(crate) disabled: bool,
    pub(crate) min: Option<CivilDate>,
    pub(crate) max: Option<CivilDate>,
}

impl CalendarBounds {
    pub(crate) fn new(disabled: bool, min: Option<&str>, max: Option<&str>) -> Self {
        Self {
            disabled: disabled || !bounds_valid(min, max),
            min: CivilDate::parse(min.unwrap_or("0001-01-01")),
            max: CivilDate::parse(max.unwrap_or("9999-12-31")),
        }
    }

    pub(crate) fn is_unavailable(self, date: CivilDate) -> bool {
        self.disabled
            || self.min.is_some_and(|min| date < min)
            || self.max.is_some_and(|max| date > max)
    }

    /// The day that holds roving focus in `month`, like `getCalendarFocusDate`.
    pub(crate) fn focus_date(
        self,
        month: CivilDate,
        selected: Option<CivilDate>,
        requested: Option<CivilDate>,
        today: Option<CivilDate>,
    ) -> CivilDate {
        let candidates = [requested, selected, today, Some(month)];

        for candidate in candidates.into_iter().flatten() {
            if candidate.same_month(month) && !self.is_unavailable(candidate) {
                return candidate;
            }
        }

        (0..i64::from(month.days_in_month()))
            .map(|offset| month.start_of_month().add_days(offset))
            .find(|date| !self.is_unavailable(*date))
            .unwrap_or(month)
    }
}

/// One cell of the six-week grid. The flags mirror lumen-react's `CalendarDay` fields, which are
/// independent of each other.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CalendarCell {
    pub(crate) date: CivilDate,
    pub(crate) iso: String,
    pub(crate) disabled: bool,
    pub(crate) outside: bool,
    pub(crate) selected: bool,
    pub(crate) today: bool,
    pub(crate) focusable: bool,
}

/// The 6x7 Monday-first grid for `month`.
pub(crate) fn calendar_weeks(
    month: CivilDate,
    bounds: CalendarBounds,
    selected: Option<CivilDate>,
    focus: CivilDate,
    today: Option<CivilDate>,
) -> Vec<Vec<CalendarCell>> {
    let first = month.grid_start();

    (0..6_i64)
        .map(|row| {
            (0..7_i64)
                .map(|column| {
                    let date = first.add_days(row * 7 + column);
                    let disabled = bounds.is_unavailable(date);

                    CalendarCell {
                        date,
                        iso: date.to_string(),
                        disabled,
                        outside: !date.same_month(month),
                        selected: selected == Some(date),
                        today: today == Some(date),
                        focusable: !disabled && date == focus,
                    }
                })
                .collect()
        })
        .collect()
}

/// The day a navigation key moves focus to from `current`, like the `useCalendar` key map.
pub(crate) fn calendar_key_target(current: CivilDate, key: &Key) -> Option<CivilDate> {
    let column = i64::try_from(current.weekday_index()).unwrap_or(0);

    let offset = match key {
        Key::ArrowDown => 7,
        Key::ArrowUp => -7,
        Key::ArrowLeft => -1,
        Key::ArrowRight => 1,
        Key::Home => -column,
        Key::End => 6 - column,
        Key::PageDown => return Some(current.add_months(1)),
        Key::PageUp => return Some(current.add_months(-1)),
        _ => return None,
    };

    Some(current.add_days(offset))
}

/// Props for [`Calendar`].
#[derive(Props, Clone, PartialEq)]
pub struct CalendarProps {
    /// Controlled selected date (`YYYY-MM-DD`). Invalid dates select nothing.
    #[props(into)]
    pub value: Option<String>,
    /// Initially selected date when uncontrolled.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the newly selected date.
    pub on_value_change: Option<EventHandler<String>>,
    /// Disables every day and the month buttons.
    #[props(default)]
    pub disabled: bool,
    /// Keeps navigation but blocks selection.
    #[props(default)]
    pub read_only: bool,
    /// Earliest selectable date (`YYYY-MM-DD`).
    #[props(into)]
    pub min: Option<String>,
    /// Latest selectable date (`YYYY-MM-DD`).
    #[props(into)]
    pub max: Option<String>,
    /// Pins the visible month (`YYYY-MM`).
    #[props(into)]
    pub month: Option<String>,
    /// Form field name of the hidden input that submits the value.
    #[props(into)]
    pub name: Option<String>,
    /// Language of the navigation labels: `en`, `es`, `fr`, `pt`, or `ar`. Month and weekday
    /// names stay English unless `labels` provides them.
    #[props(into)]
    pub locale: Option<String>,
    /// Label overrides.
    pub labels: Option<CalendarLabels>,
    /// Overrides today's date (`YYYY-MM-DD`), which otherwise comes from the platform.
    #[props(into)]
    pub today: Option<String>,
    /// Moves focus to the focusable day when the calendar mounts, as a `DatePicker` dialog does.
    #[props(default)]
    pub autofocus: bool,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
}

/// A month grid for picking one date, following the WAI-ARIA date grid pattern.
///
/// Arrow keys move by day and week, Home and End jump within the week, Page Up and Page Down
/// change the month, and Enter or Space selects. Days outside `min` and `max` are unavailable.
#[component]
pub fn Calendar(props: CalendarProps) -> Element {
    let bounds = CalendarBounds::new(props.disabled, props.min.as_deref(), props.max.as_deref());
    let read_only = props.read_only;
    let unique = use_unique_id();
    let label_id = format!("ui-calendar-{unique}-label");
    let today = use_calendar_today(props.today.as_deref());

    let controlled = props
        .value
        .as_ref()
        .map(|value| CivilDate::parse(value).map_or_else(String::new, |date| date.to_string()));
    let value = use_controllable(
        controlled,
        || {
            props
                .default_value
                .as_deref()
                .and_then(CivilDate::parse)
                .map_or_else(String::new, |date| date.to_string())
        },
        props.on_value_change,
    );
    let selected_value = value.get();
    let selected = CivilDate::parse(&selected_value);

    let initial_month = props
        .month
        .as_deref()
        .and_then(CivilDate::parse_month)
        .or_else(|| selected.map(CivilDate::start_of_month))
        .or_else(|| today.map(CivilDate::start_of_month));
    let mut visible_value = use_signal(|| initial_month.map(CivilDate::month_key));
    let visible_source = props.month.clone().or_else(|| visible_value.read().clone());
    let visible = visible_source
        .as_deref()
        .and_then(CivilDate::parse_month)
        .or(initial_month)
        .unwrap_or_else(|| CivilDate::from_unix_seconds(0));

    let mut focus_value = use_signal(|| None::<String>);
    let focus = bounds.focus_date(
        visible,
        selected,
        focus_value().as_deref().and_then(CivilDate::parse),
        today,
    );
    let weeks = calendar_weeks(visible, bounds, selected, focus, today);
    let labels = ResolvedDateLabels::new(props.locale.as_deref(), props.labels.as_ref());
    let heading = labels.month_heading(visible);
    let weekdays: Vec<String> = (0..7)
        .map(|column| labels.weekday_short_name(column).to_string())
        .collect();

    // Mounted day cells by date, so keys can focus a rendered day at once. Only days of the
    // rendered grid are kept: cells of other months unmount, and their nodes must not be focused
    // or kept while paging through months. Cells that stay keep their entry, because a day that
    // stays in the grid is moved, not mounted again.
    let mut cells = use_hook(|| CopyValue::new(HashMap::<String, Rc<MountedData>>::new()));
    {
        let rendered: HashSet<&str> = weeks
            .iter()
            .flatten()
            .map(|cell| cell.iso.as_str())
            .collect();
        cells
            .write()
            .retain(|iso, _| rendered.contains(iso.as_str()));
    }
    let mut pending_focus = use_signal(|| props.autofocus.then(|| ROVING_DAY.to_string()));

    let mut move_focus = move |date: CivilDate| {
        let next = date.clamp_to(bounds.min, bounds.max);
        let iso = next.to_string();
        visible_value.set(Some(next.month_key()));
        focus_value.set(Some(iso.clone()));

        if let Some(cell) = cells.peek().get(&iso).cloned() {
            spawn(async move {
                let _ = cell.set_focus(true).await;
            });
        }

        pending_focus.set(Some(iso));
    };

    let mut select = move |date: CivilDate| {
        if bounds.disabled || read_only {
            return;
        }

        let next = date.clamp_to(bounds.min, bounds.max);

        if bounds.is_unavailable(next) {
            return;
        }

        visible_value.set(Some(next.month_key()));
        focus_value.set(Some(next.to_string()));
        // Picking the selected day still reports it, like lumen-react, so a `DatePicker` closes.
        value.select(next.to_string());
    };

    let previous_last_day = visible.add_days(-1);
    let next_first_day = visible.add_months(1);
    let previous_disabled =
        bounds.disabled || bounds.min.is_some_and(|min| previous_last_day < min);
    let next_disabled = bounds.disabled || bounds.max.is_some_and(|max| next_first_day > max);

    let mut show_month = move |month: CivilDate| {
        visible_value.set(Some(month.month_key()));
        focus_value.set(Some(
            bounds.focus_date(month, selected, None, today).to_string(),
        ));
    };

    let glass = props.glass.class("ui-calendar");
    let class = compose([
        Some("ui-calendar"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);
    let glass_on = props.glass != Glass::Off;

    rsx! {
        div {
            aria_disabled: bounds.disabled.then_some("true"),
            class,
            "data-disabled": bounds.disabled.then_some("true"),
            "data-ui-calendar": "true",
            "data-ui-calendar-initial-month": initial_month.map(CivilDate::month_key),
            "data-ui-owner": "dioxus",
            "data-ui-calendar-max": bounds.max.map(|date| date.to_string()),
            "data-ui-calendar-min": bounds.min.map(|date| date.to_string()),
            "data-ui-calendar-month": visible.month_key(),
            "data-ui-calendar-value": (!selected_value.is_empty()).then(|| selected_value.clone()),
            "data-ui-glass-track": glass_on.then_some("true"),
            ..props.attributes,
            input {
                "data-ui-calendar-input": "true",
                disabled: bounds.disabled,
                name: props.name,
                r#type: "hidden",
                value: selected_value.clone(),
            }
            div { class: "ui-calendar__header",
                button {
                    aria_label: labels.previous_month.clone(),
                    class: "ui-calendar__nav",
                    "data-ui-calendar-prev": "true",
                    disabled: previous_disabled,
                    r#type: "button",
                    onclick: move |_| {
                        if !previous_disabled {
                            show_month(visible.add_months(-1).start_of_month());
                        }
                    },
                    Icon { icon: &lucide::CHEVRON_LEFT }
                }
                strong {
                    class: "ui-calendar__label",
                    "data-ui-calendar-label": "true",
                    id: label_id.clone(),
                    "{heading}"
                }
                button {
                    aria_label: labels.next_month.clone(),
                    class: "ui-calendar__nav",
                    "data-ui-calendar-next": "true",
                    disabled: next_disabled,
                    r#type: "button",
                    onclick: move |_| {
                        if !next_disabled {
                            show_month(visible.add_months(1).start_of_month());
                        }
                    },
                    Icon { icon: &lucide::CHEVRON_RIGHT }
                }
            }
            table {
                aria_labelledby: label_id,
                aria_readonly: read_only.then_some("true"),
                class: "ui-calendar__grid",
                "data-ui-calendar-grid": "true",
                role: "grid",
                thead {
                    tr {
                        for weekday in weekdays {
                            th { key: "{weekday}", scope: "col", "{weekday}" }
                        }
                    }
                }
                tbody {
                    for week in weeks {
                        tr { key: "{week[0].iso}",
                            for cell in week {
                                td {
                                    key: "{cell.iso}",
                                    aria_disabled: cell.disabled.then_some("true"),
                                    aria_label: labels.day_label(cell.date),
                                    aria_selected: if cell.selected { "true" } else { "false" },
                                    "data-date": cell.iso.clone(),
                                    "data-outside": cell.outside.then_some("true"),
                                    "data-selected": cell.selected.then_some("true"),
                                    "data-today": cell.today.then_some("true"),
                                    "data-ui-calendar-day": "true",
                                    role: "gridcell",
                                    tabindex: if cell.focusable { "0" } else { "-1" },
                                    onclick: {
                                        let date = cell.date;
                                        let disabled = cell.disabled;
                                        move |_| {
                                            if !disabled {
                                                select(date);
                                            }
                                        }
                                    },
                                    onkeydown: {
                                        // Keys act on the roving day: Dioxus Native cannot move
                                        // DOM focus, so the focused cell may lag behind it.
                                        let date = if bounds.is_unavailable(focus) { cell.date } else { focus };
                                        let disabled = cell.disabled && date == cell.date;
                                        move |event: KeyboardEvent| {
                                            if disabled {
                                                return;
                                            }

                                            let key = event.key();

                                            if key == Key::Enter || key == Key::Character(" ".to_string()) {
                                                event.prevent_default();
                                                select(date);
                                                return;
                                            }

                                            if let Some(target) = calendar_key_target(date, &key) {
                                                event.prevent_default();
                                                move_focus(target);
                                            }
                                        }
                                    },
                                    onmounted: {
                                        let iso = cell.iso.clone();
                                        let focusable = cell.focusable;
                                        move |event: MountedEvent| {
                                            let node = event.data();
                                            cells.write().insert(iso.clone(), node.clone());
                                            let pending = pending_focus.peek().clone();

                                            if pending.as_deref() == Some(iso.as_str())
                                                || (focusable && pending.as_deref() == Some(ROVING_DAY))
                                            {
                                                pending_focus.set(None);
                                                spawn(async move {
                                                    let _ = node.set_focus(true).await;
                                                });
                                            }
                                        }
                                    },
                                    "{cell.date.day()}"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CalendarBounds, ResolvedDateLabels, calendar_key_target, calendar_weeks};
    use crate::pickers::dates::CivilDate;
    use dioxus::prelude::Key;

    fn date(value: &str) -> CivilDate {
        CivilDate::parse(value).expect("valid test date")
    }

    #[test]
    fn labels_follow_en_us_formats() {
        let labels = ResolvedDateLabels::new(None, None);
        assert_eq!(labels.month_heading(date("2024-03-01")), "March 2024");
        assert_eq!(
            labels.day_label(date("2024-03-01")),
            "Friday, March 1, 2024"
        );
        assert_eq!(labels.short_date(date("2024-09-15")), "Sep 15, 2024");
        assert_eq!(labels.previous_month, "Previous month");
        assert_eq!(
            ResolvedDateLabels::new(Some("es-CO"), None).next_month,
            "Mes siguiente"
        );
        assert_eq!(
            ResolvedDateLabels::new(Some("zz"), None).choose_date,
            "Choose date"
        );
    }

    #[test]
    fn grid_marks_outside_selected_and_focus() {
        let bounds = CalendarBounds::new(false, Some("2024-03-05"), None);
        let month = date("2024-03-01");
        let focus = bounds.focus_date(month, None, None, None);
        assert_eq!(focus.to_string(), "2024-03-05");

        let weeks = calendar_weeks(month, bounds, Some(date("2024-03-12")), focus, None);
        assert_eq!(weeks.len(), 6);
        assert_eq!(weeks[0][0].iso, "2024-02-26");
        assert!(weeks[0][0].outside && weeks[0][0].disabled);
        let selected: Vec<_> = weeks
            .iter()
            .flatten()
            .filter(|cell| cell.selected)
            .collect();
        assert_eq!(selected.len(), 1);
        assert_eq!(selected[0].iso, "2024-03-12");
        let focusable: Vec<_> = weeks
            .iter()
            .flatten()
            .filter(|cell| cell.focusable)
            .collect();
        assert_eq!(focusable.len(), 1);
        assert_eq!(focusable[0].iso, "2024-03-05");
    }

    #[test]
    fn invalid_bounds_disable_the_calendar() {
        assert!(CalendarBounds::new(false, Some("2024-05-01"), Some("2024-04-01")).disabled);
        assert!(CalendarBounds::new(false, Some("bad"), None).disabled);
        let disabled = CalendarBounds::new(true, None, None);
        assert_eq!(
            disabled
                .focus_date(date("2024-03-01"), None, None, None)
                .to_string(),
            "2024-03-01"
        );
    }

    #[test]
    fn keys_move_by_day_week_and_month() {
        let friday = date("2024-03-01");
        let target = |key: Key| calendar_key_target(friday, &key).map(|day| day.to_string());
        assert_eq!(target(Key::ArrowRight).as_deref(), Some("2024-03-02"));
        assert_eq!(target(Key::ArrowLeft).as_deref(), Some("2024-02-29"));
        assert_eq!(target(Key::ArrowDown).as_deref(), Some("2024-03-08"));
        assert_eq!(target(Key::ArrowUp).as_deref(), Some("2024-02-23"));
        assert_eq!(target(Key::Home).as_deref(), Some("2024-02-26"));
        assert_eq!(target(Key::End).as_deref(), Some("2024-03-03"));
        assert_eq!(target(Key::PageDown).as_deref(), Some("2024-04-01"));
        assert_eq!(
            calendar_key_target(date("2024-01-31"), &Key::PageDown).map(|day| day.to_string()),
            Some("2024-02-29".to_string())
        );
        assert_eq!(target(Key::Tab), None);
    }
}