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};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CalendarLabels {
pub previous_month: Option<String>,
pub next_month: Option<String>,
pub choose_date: Option<String>,
pub month_names: Option<[String; 12]>,
pub month_short_names: Option<[String; 12]>,
pub weekday_short_names: Option<[String; 7]>,
pub weekday_names: Option<[String; 7]>,
}
struct DateLabelPack {
previous_month: &'static str,
next_month: &'static str,
choose_date: &'static str,
}
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())
}
#[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())
}
pub(crate) fn month_heading(&self, month: CivilDate) -> String {
format!("{} {}", self.month_name(month), month.year())
}
pub(crate) fn day_label(&self, date: CivilDate) -> String {
format!(
"{}, {} {}, {}",
self.weekday_name(date.weekday_index()),
self.month_name(date),
date.day(),
date.year()
)
}
pub(crate) fn short_date(&self, date: CivilDate) -> String {
format!(
"{} {}, {}",
self.month_short_name(date),
date.day(),
date.year()
)
}
}
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())
}
const ROVING_DAY: &str = "roving";
#[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)
}
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)
}
}
#[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,
}
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()
}
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))
}
#[derive(Props, Clone, PartialEq)]
pub struct CalendarProps {
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub default_value: Option<String>,
pub on_value_change: Option<EventHandler<String>>,
#[props(default)]
pub disabled: bool,
#[props(default)]
pub read_only: bool,
#[props(into)]
pub min: Option<String>,
#[props(into)]
pub max: Option<String>,
#[props(into)]
pub month: Option<String>,
#[props(into)]
pub name: Option<String>,
#[props(into)]
pub locale: Option<String>,
pub labels: Option<CalendarLabels>,
#[props(into)]
pub today: Option<String>,
#[props(default)]
pub autofocus: bool,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
#[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();
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()));
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: {
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);
}
}