1use std::collections::{HashMap, HashSet};
4use std::rc::Rc;
5
6use dioxus::prelude::*;
7
8use super::dates::{
9 CivilDate, MONTH_NAMES, MONTH_SHORT_NAMES, WEEKDAY_NAMES, WEEKDAY_SHORT_NAMES, bounds_valid,
10 utc_today,
11};
12use crate::class::{Glass, compose};
13use crate::hooks::{use_controllable, use_unique_id};
14use crate::icons::{Icon, lucide};
15
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
22pub struct CalendarLabels {
23 pub previous_month: Option<String>,
25 pub next_month: Option<String>,
27 pub choose_date: Option<String>,
29 pub month_names: Option<[String; 12]>,
31 pub month_short_names: Option<[String; 12]>,
33 pub weekday_short_names: Option<[String; 7]>,
35 pub weekday_names: Option<[String; 7]>,
37}
38
39struct DateLabelPack {
41 previous_month: &'static str,
42 next_month: &'static str,
43 choose_date: &'static str,
44}
45
46const DATE_LABEL_PACKS: [(&str, DateLabelPack); 5] = [
49 (
50 "en",
51 DateLabelPack {
52 previous_month: "Previous month",
53 next_month: "Next month",
54 choose_date: "Choose date",
55 },
56 ),
57 (
58 "es",
59 DateLabelPack {
60 previous_month: "Mes anterior",
61 next_month: "Mes siguiente",
62 choose_date: "Elegir fecha",
63 },
64 ),
65 (
66 "fr",
67 DateLabelPack {
68 previous_month: "Mois précédent",
69 next_month: "Mois suivant",
70 choose_date: "Choisir une date",
71 },
72 ),
73 (
74 "pt",
75 DateLabelPack {
76 previous_month: "Mês anterior",
77 next_month: "Próximo mês",
78 choose_date: "Escolher data",
79 },
80 ),
81 (
82 "ar",
83 DateLabelPack {
84 previous_month: "الشهر السابق",
85 next_month: "الشهر التالي",
86 choose_date: "اختيار تاريخ",
87 },
88 ),
89];
90
91fn label_pack(locale: Option<&str>) -> &'static DateLabelPack {
92 let language: String = locale
93 .unwrap_or("en")
94 .trim()
95 .chars()
96 .take_while(char::is_ascii_alphabetic)
97 .take(8)
98 .collect::<String>()
99 .to_ascii_lowercase();
100
101 DATE_LABEL_PACKS
102 .iter()
103 .find(|(code, _)| *code == language)
104 .map_or(&DATE_LABEL_PACKS[0].1, |(_, pack)| pack)
105}
106
107fn non_empty(value: Option<&String>) -> Option<&str> {
108 value
109 .map(String::as_str)
110 .filter(|text| !text.trim().is_empty())
111}
112
113#[derive(Clone, Debug, PartialEq)]
115pub(crate) struct ResolvedDateLabels {
116 pub(crate) previous_month: String,
117 pub(crate) next_month: String,
118 pub(crate) choose_date: String,
119 labels: CalendarLabels,
120}
121
122impl ResolvedDateLabels {
123 pub(crate) fn new(locale: Option<&str>, labels: Option<&CalendarLabels>) -> Self {
124 let pack = label_pack(locale);
125 let labels = labels.cloned().unwrap_or_default();
126
127 Self {
128 previous_month: non_empty(labels.previous_month.as_ref())
129 .unwrap_or(pack.previous_month)
130 .to_string(),
131 next_month: non_empty(labels.next_month.as_ref())
132 .unwrap_or(pack.next_month)
133 .to_string(),
134 choose_date: non_empty(labels.choose_date.as_ref())
135 .unwrap_or(pack.choose_date)
136 .to_string(),
137 labels,
138 }
139 }
140
141 fn month_name(&self, date: CivilDate) -> &str {
142 let index = (date.month() - 1) as usize;
143
144 self.labels
145 .month_names
146 .as_ref()
147 .map_or(MONTH_NAMES[index], |names| names[index].as_str())
148 }
149
150 fn month_short_name(&self, date: CivilDate) -> &str {
151 let index = (date.month() - 1) as usize;
152
153 self.labels
154 .month_short_names
155 .as_ref()
156 .map_or(MONTH_SHORT_NAMES[index], |names| names[index].as_str())
157 }
158
159 fn weekday_short_name(&self, column: usize) -> &str {
160 self.labels
161 .weekday_short_names
162 .as_ref()
163 .map_or(WEEKDAY_SHORT_NAMES[column], |names| names[column].as_str())
164 }
165
166 fn weekday_name(&self, column: usize) -> &str {
167 self.labels
168 .weekday_names
169 .as_ref()
170 .map_or(WEEKDAY_NAMES[column], |names| names[column].as_str())
171 }
172
173 pub(crate) fn month_heading(&self, month: CivilDate) -> String {
175 format!("{} {}", self.month_name(month), month.year())
176 }
177
178 pub(crate) fn day_label(&self, date: CivilDate) -> String {
180 format!(
181 "{}, {} {}, {}",
182 self.weekday_name(date.weekday_index()),
183 self.month_name(date),
184 date.day(),
185 date.year()
186 )
187 }
188
189 pub(crate) fn short_date(&self, date: CivilDate) -> String {
191 format!(
192 "{} {}, {}",
193 self.month_short_name(date),
194 date.day(),
195 date.year()
196 )
197 }
198}
199
200pub(crate) fn use_calendar_today(today: Option<&str>) -> Option<CivilDate> {
203 let mut local = use_signal(utc_today);
204
205 use_effect(move || {
206 spawn(async move {
207 let script =
208 "const d = new Date(); return [d.getFullYear(), d.getMonth() + 1, d.getDate()];";
209
210 if let Ok((year, month, day)) = document::eval(script).join::<(i64, u32, u32)>().await
211 && let Some(date) = CivilDate::new(year, month, day)
212 && *local.peek() != Some(date)
213 {
214 local.set(Some(date));
215 }
216 });
217 });
218
219 today.and_then(CivilDate::parse).or(*local.read())
220}
221
222const ROVING_DAY: &str = "roving";
224
225#[derive(Clone, Copy, Debug, PartialEq, Eq)]
227pub(crate) struct CalendarBounds {
228 pub(crate) disabled: bool,
229 pub(crate) min: Option<CivilDate>,
230 pub(crate) max: Option<CivilDate>,
231}
232
233impl CalendarBounds {
234 pub(crate) fn new(disabled: bool, min: Option<&str>, max: Option<&str>) -> Self {
235 Self {
236 disabled: disabled || !bounds_valid(min, max),
237 min: CivilDate::parse(min.unwrap_or("0001-01-01")),
238 max: CivilDate::parse(max.unwrap_or("9999-12-31")),
239 }
240 }
241
242 pub(crate) fn is_unavailable(self, date: CivilDate) -> bool {
243 self.disabled
244 || self.min.is_some_and(|min| date < min)
245 || self.max.is_some_and(|max| date > max)
246 }
247
248 pub(crate) fn focus_date(
250 self,
251 month: CivilDate,
252 selected: Option<CivilDate>,
253 requested: Option<CivilDate>,
254 today: Option<CivilDate>,
255 ) -> CivilDate {
256 let candidates = [requested, selected, today, Some(month)];
257
258 for candidate in candidates.into_iter().flatten() {
259 if candidate.same_month(month) && !self.is_unavailable(candidate) {
260 return candidate;
261 }
262 }
263
264 (0..i64::from(month.days_in_month()))
265 .map(|offset| month.start_of_month().add_days(offset))
266 .find(|date| !self.is_unavailable(*date))
267 .unwrap_or(month)
268 }
269}
270
271#[allow(clippy::struct_excessive_bools)]
274#[derive(Clone, Debug, PartialEq)]
275pub(crate) struct CalendarCell {
276 pub(crate) date: CivilDate,
277 pub(crate) iso: String,
278 pub(crate) disabled: bool,
279 pub(crate) outside: bool,
280 pub(crate) selected: bool,
281 pub(crate) today: bool,
282 pub(crate) focusable: bool,
283}
284
285pub(crate) fn calendar_weeks(
287 month: CivilDate,
288 bounds: CalendarBounds,
289 selected: Option<CivilDate>,
290 focus: CivilDate,
291 today: Option<CivilDate>,
292) -> Vec<Vec<CalendarCell>> {
293 let first = month.grid_start();
294
295 (0..6_i64)
296 .map(|row| {
297 (0..7_i64)
298 .map(|column| {
299 let date = first.add_days(row * 7 + column);
300 let disabled = bounds.is_unavailable(date);
301
302 CalendarCell {
303 date,
304 iso: date.to_string(),
305 disabled,
306 outside: !date.same_month(month),
307 selected: selected == Some(date),
308 today: today == Some(date),
309 focusable: !disabled && date == focus,
310 }
311 })
312 .collect()
313 })
314 .collect()
315}
316
317pub(crate) fn calendar_key_target(current: CivilDate, key: &Key) -> Option<CivilDate> {
319 let column = i64::try_from(current.weekday_index()).unwrap_or(0);
320
321 let offset = match key {
322 Key::ArrowDown => 7,
323 Key::ArrowUp => -7,
324 Key::ArrowLeft => -1,
325 Key::ArrowRight => 1,
326 Key::Home => -column,
327 Key::End => 6 - column,
328 Key::PageDown => return Some(current.add_months(1)),
329 Key::PageUp => return Some(current.add_months(-1)),
330 _ => return None,
331 };
332
333 Some(current.add_days(offset))
334}
335
336#[derive(Props, Clone, PartialEq)]
338pub struct CalendarProps {
339 #[props(into)]
341 pub value: Option<String>,
342 #[props(into)]
344 pub default_value: Option<String>,
345 pub on_value_change: Option<EventHandler<String>>,
347 #[props(default)]
349 pub disabled: bool,
350 #[props(default)]
352 pub read_only: bool,
353 #[props(into)]
355 pub min: Option<String>,
356 #[props(into)]
358 pub max: Option<String>,
359 #[props(into)]
361 pub month: Option<String>,
362 #[props(into)]
364 pub name: Option<String>,
365 #[props(into)]
368 pub locale: Option<String>,
369 pub labels: Option<CalendarLabels>,
371 #[props(into)]
373 pub today: Option<String>,
374 #[props(default)]
376 pub autofocus: bool,
377 #[props(default, into)]
379 pub glass: Glass,
380 #[props(into)]
382 pub class: Option<String>,
383 #[props(extends = GlobalAttributes, extends = div)]
385 pub attributes: Vec<Attribute>,
386}
387
388#[component]
393pub fn Calendar(props: CalendarProps) -> Element {
394 let bounds = CalendarBounds::new(props.disabled, props.min.as_deref(), props.max.as_deref());
395 let read_only = props.read_only;
396 let unique = use_unique_id();
397 let label_id = format!("ui-calendar-{unique}-label");
398 let today = use_calendar_today(props.today.as_deref());
399
400 let controlled = props
401 .value
402 .as_ref()
403 .map(|value| CivilDate::parse(value).map_or_else(String::new, |date| date.to_string()));
404 let value = use_controllable(
405 controlled,
406 || {
407 props
408 .default_value
409 .as_deref()
410 .and_then(CivilDate::parse)
411 .map_or_else(String::new, |date| date.to_string())
412 },
413 props.on_value_change,
414 );
415 let selected_value = value.get();
416 let selected = CivilDate::parse(&selected_value);
417
418 let initial_month = props
419 .month
420 .as_deref()
421 .and_then(CivilDate::parse_month)
422 .or_else(|| selected.map(CivilDate::start_of_month))
423 .or_else(|| today.map(CivilDate::start_of_month));
424 let mut visible_value = use_signal(|| initial_month.map(CivilDate::month_key));
425 let visible_source = props.month.clone().or_else(|| visible_value.read().clone());
426 let visible = visible_source
427 .as_deref()
428 .and_then(CivilDate::parse_month)
429 .or(initial_month)
430 .unwrap_or_else(|| CivilDate::from_unix_seconds(0));
431
432 let mut focus_value = use_signal(|| None::<String>);
433 let focus = bounds.focus_date(
434 visible,
435 selected,
436 focus_value().as_deref().and_then(CivilDate::parse),
437 today,
438 );
439 let weeks = calendar_weeks(visible, bounds, selected, focus, today);
440 let labels = ResolvedDateLabels::new(props.locale.as_deref(), props.labels.as_ref());
441 let heading = labels.month_heading(visible);
442 let weekdays: Vec<String> = (0..7)
443 .map(|column| labels.weekday_short_name(column).to_string())
444 .collect();
445
446 let mut cells = use_hook(|| CopyValue::new(HashMap::<String, Rc<MountedData>>::new()));
451 {
452 let rendered: HashSet<&str> = weeks
453 .iter()
454 .flatten()
455 .map(|cell| cell.iso.as_str())
456 .collect();
457 cells
458 .write()
459 .retain(|iso, _| rendered.contains(iso.as_str()));
460 }
461 let mut pending_focus = use_signal(|| props.autofocus.then(|| ROVING_DAY.to_string()));
462
463 let mut move_focus = move |date: CivilDate| {
464 let next = date.clamp_to(bounds.min, bounds.max);
465 let iso = next.to_string();
466 visible_value.set(Some(next.month_key()));
467 focus_value.set(Some(iso.clone()));
468
469 if let Some(cell) = cells.peek().get(&iso).cloned() {
470 spawn(async move {
471 let _ = cell.set_focus(true).await;
472 });
473 }
474
475 pending_focus.set(Some(iso));
476 };
477
478 let mut select = move |date: CivilDate| {
479 if bounds.disabled || read_only {
480 return;
481 }
482
483 let next = date.clamp_to(bounds.min, bounds.max);
484
485 if bounds.is_unavailable(next) {
486 return;
487 }
488
489 visible_value.set(Some(next.month_key()));
490 focus_value.set(Some(next.to_string()));
491 value.select(next.to_string());
493 };
494
495 let previous_last_day = visible.add_days(-1);
496 let next_first_day = visible.add_months(1);
497 let previous_disabled =
498 bounds.disabled || bounds.min.is_some_and(|min| previous_last_day < min);
499 let next_disabled = bounds.disabled || bounds.max.is_some_and(|max| next_first_day > max);
500
501 let mut show_month = move |month: CivilDate| {
502 visible_value.set(Some(month.month_key()));
503 focus_value.set(Some(
504 bounds.focus_date(month, selected, None, today).to_string(),
505 ));
506 };
507
508 let glass = props.glass.class("ui-calendar");
509 let class = compose([
510 Some("ui-calendar"),
511 glass.as_deref(),
512 props.class.as_deref(),
513 ]);
514 let glass_on = props.glass != Glass::Off;
515
516 rsx! {
517 div {
518 aria_disabled: bounds.disabled.then_some("true"),
519 class,
520 "data-disabled": bounds.disabled.then_some("true"),
521 "data-ui-calendar": "true",
522 "data-ui-calendar-initial-month": initial_month.map(CivilDate::month_key),
523 "data-ui-owner": "dioxus",
524 "data-ui-calendar-max": bounds.max.map(|date| date.to_string()),
525 "data-ui-calendar-min": bounds.min.map(|date| date.to_string()),
526 "data-ui-calendar-month": visible.month_key(),
527 "data-ui-calendar-value": (!selected_value.is_empty()).then(|| selected_value.clone()),
528 "data-ui-glass-track": glass_on.then_some("true"),
529 ..props.attributes,
530 input {
531 "data-ui-calendar-input": "true",
532 disabled: bounds.disabled,
533 name: props.name,
534 r#type: "hidden",
535 value: selected_value.clone(),
536 }
537 div { class: "ui-calendar__header",
538 button {
539 aria_label: labels.previous_month.clone(),
540 class: "ui-calendar__nav",
541 "data-ui-calendar-prev": "true",
542 disabled: previous_disabled,
543 r#type: "button",
544 onclick: move |_| {
545 if !previous_disabled {
546 show_month(visible.add_months(-1).start_of_month());
547 }
548 },
549 Icon { icon: &lucide::CHEVRON_LEFT }
550 }
551 strong {
552 class: "ui-calendar__label",
553 "data-ui-calendar-label": "true",
554 id: label_id.clone(),
555 "{heading}"
556 }
557 button {
558 aria_label: labels.next_month.clone(),
559 class: "ui-calendar__nav",
560 "data-ui-calendar-next": "true",
561 disabled: next_disabled,
562 r#type: "button",
563 onclick: move |_| {
564 if !next_disabled {
565 show_month(visible.add_months(1).start_of_month());
566 }
567 },
568 Icon { icon: &lucide::CHEVRON_RIGHT }
569 }
570 }
571 table {
572 aria_labelledby: label_id,
573 aria_readonly: read_only.then_some("true"),
574 class: "ui-calendar__grid",
575 "data-ui-calendar-grid": "true",
576 role: "grid",
577 thead {
578 tr {
579 for weekday in weekdays {
580 th { key: "{weekday}", scope: "col", "{weekday}" }
581 }
582 }
583 }
584 tbody {
585 for week in weeks {
586 tr { key: "{week[0].iso}",
587 for cell in week {
588 td {
589 key: "{cell.iso}",
590 aria_disabled: cell.disabled.then_some("true"),
591 aria_label: labels.day_label(cell.date),
592 aria_selected: if cell.selected { "true" } else { "false" },
593 "data-date": cell.iso.clone(),
594 "data-outside": cell.outside.then_some("true"),
595 "data-selected": cell.selected.then_some("true"),
596 "data-today": cell.today.then_some("true"),
597 "data-ui-calendar-day": "true",
598 role: "gridcell",
599 tabindex: if cell.focusable { "0" } else { "-1" },
600 onclick: {
601 let date = cell.date;
602 let disabled = cell.disabled;
603 move |_| {
604 if !disabled {
605 select(date);
606 }
607 }
608 },
609 onkeydown: {
610 let date = if bounds.is_unavailable(focus) { cell.date } else { focus };
613 let disabled = cell.disabled && date == cell.date;
614 move |event: KeyboardEvent| {
615 if disabled {
616 return;
617 }
618
619 let key = event.key();
620
621 if key == Key::Enter || key == Key::Character(" ".to_string()) {
622 event.prevent_default();
623 select(date);
624 return;
625 }
626
627 if let Some(target) = calendar_key_target(date, &key) {
628 event.prevent_default();
629 move_focus(target);
630 }
631 }
632 },
633 onmounted: {
634 let iso = cell.iso.clone();
635 let focusable = cell.focusable;
636 move |event: MountedEvent| {
637 let node = event.data();
638 cells.write().insert(iso.clone(), node.clone());
639 let pending = pending_focus.peek().clone();
640
641 if pending.as_deref() == Some(iso.as_str())
642 || (focusable && pending.as_deref() == Some(ROVING_DAY))
643 {
644 pending_focus.set(None);
645 spawn(async move {
646 let _ = node.set_focus(true).await;
647 });
648 }
649 }
650 },
651 "{cell.date.day()}"
652 }
653 }
654 }
655 }
656 }
657 }
658 }
659 }
660}
661
662#[cfg(test)]
663mod tests {
664 use super::{CalendarBounds, ResolvedDateLabels, calendar_key_target, calendar_weeks};
665 use crate::pickers::dates::CivilDate;
666 use dioxus::prelude::Key;
667
668 fn date(value: &str) -> CivilDate {
669 CivilDate::parse(value).expect("valid test date")
670 }
671
672 #[test]
673 fn labels_follow_en_us_formats() {
674 let labels = ResolvedDateLabels::new(None, None);
675 assert_eq!(labels.month_heading(date("2024-03-01")), "March 2024");
676 assert_eq!(
677 labels.day_label(date("2024-03-01")),
678 "Friday, March 1, 2024"
679 );
680 assert_eq!(labels.short_date(date("2024-09-15")), "Sep 15, 2024");
681 assert_eq!(labels.previous_month, "Previous month");
682 assert_eq!(
683 ResolvedDateLabels::new(Some("es-CO"), None).next_month,
684 "Mes siguiente"
685 );
686 assert_eq!(
687 ResolvedDateLabels::new(Some("zz"), None).choose_date,
688 "Choose date"
689 );
690 }
691
692 #[test]
693 fn grid_marks_outside_selected_and_focus() {
694 let bounds = CalendarBounds::new(false, Some("2024-03-05"), None);
695 let month = date("2024-03-01");
696 let focus = bounds.focus_date(month, None, None, None);
697 assert_eq!(focus.to_string(), "2024-03-05");
698
699 let weeks = calendar_weeks(month, bounds, Some(date("2024-03-12")), focus, None);
700 assert_eq!(weeks.len(), 6);
701 assert_eq!(weeks[0][0].iso, "2024-02-26");
702 assert!(weeks[0][0].outside && weeks[0][0].disabled);
703 let selected: Vec<_> = weeks
704 .iter()
705 .flatten()
706 .filter(|cell| cell.selected)
707 .collect();
708 assert_eq!(selected.len(), 1);
709 assert_eq!(selected[0].iso, "2024-03-12");
710 let focusable: Vec<_> = weeks
711 .iter()
712 .flatten()
713 .filter(|cell| cell.focusable)
714 .collect();
715 assert_eq!(focusable.len(), 1);
716 assert_eq!(focusable[0].iso, "2024-03-05");
717 }
718
719 #[test]
720 fn invalid_bounds_disable_the_calendar() {
721 assert!(CalendarBounds::new(false, Some("2024-05-01"), Some("2024-04-01")).disabled);
722 assert!(CalendarBounds::new(false, Some("bad"), None).disabled);
723 let disabled = CalendarBounds::new(true, None, None);
724 assert_eq!(
725 disabled
726 .focus_date(date("2024-03-01"), None, None, None)
727 .to_string(),
728 "2024-03-01"
729 );
730 }
731
732 #[test]
733 fn keys_move_by_day_week_and_month() {
734 let friday = date("2024-03-01");
735 let target = |key: Key| calendar_key_target(friday, &key).map(|day| day.to_string());
736 assert_eq!(target(Key::ArrowRight).as_deref(), Some("2024-03-02"));
737 assert_eq!(target(Key::ArrowLeft).as_deref(), Some("2024-02-29"));
738 assert_eq!(target(Key::ArrowDown).as_deref(), Some("2024-03-08"));
739 assert_eq!(target(Key::ArrowUp).as_deref(), Some("2024-02-23"));
740 assert_eq!(target(Key::Home).as_deref(), Some("2024-02-26"));
741 assert_eq!(target(Key::End).as_deref(), Some("2024-03-03"));
742 assert_eq!(target(Key::PageDown).as_deref(), Some("2024-04-01"));
743 assert_eq!(
744 calendar_key_target(date("2024-01-31"), &Key::PageDown).map(|day| day.to_string()),
745 Some("2024-02-29".to_string())
746 );
747 assert_eq!(target(Key::Tab), None);
748 }
749}