Skip to main content

xrack_runtime/
calendar.rs

1use crate::{
2    ControlAction, DialogRole, InputRoute, Node, Property, Value, VecModel,
3    picker::{PickerSession, append_picker_dialog},
4};
5use std::{cell::RefCell, collections::BTreeMap, fmt, ops::RangeInclusive};
6
7/// A Gregorian civil date. Validation is independent of time zones and clocks.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
9pub struct Date {
10    pub year: i64,
11    pub month: i64,
12    pub day: i64,
13}
14
15impl Default for Date {
16    fn default() -> Self {
17        Self {
18            year: 1970,
19            month: 1,
20            day: 1,
21        }
22    }
23}
24
25impl fmt::Display for Date {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
28    }
29}
30
31impl Date {
32    pub const MIN: Self = Self {
33        year: 1,
34        month: 1,
35        day: 1,
36    };
37    pub const MAX: Self = Self {
38        year: 9999,
39        month: 12,
40        day: 31,
41    };
42
43    pub fn new(year: i64, month: i64, day: i64) -> Option<Self> {
44        let date = Self { year, month, day };
45        date.valid().then_some(date)
46    }
47
48    /// Parse an ASCII ISO calendar date (YYYY-MM-DD) in the supported years.
49    pub fn parse_iso(text: &str) -> Option<Self> {
50        let bytes = text.as_bytes();
51        if !matches!(bytes, [_, _, _, _, b'-', _, _, b'-', _, _]) {
52            return None;
53        }
54        let number = |digits: &[u8]| {
55            digits.iter().try_fold(0_i64, |value, digit| {
56                digit
57                    .is_ascii_digit()
58                    .then(|| value * 10 + i64::from(digit - b'0'))
59            })
60        };
61        Self::new(
62            number(&bytes[..4])?,
63            number(&bytes[5..7])?,
64            number(&bytes[8..])?,
65        )
66    }
67
68    /// Check the same date restrictions used by calendars and date pickers.
69    pub fn is_selectable(
70        self,
71        minimum: Self,
72        maximum: Self,
73        disabled_weekdays: &VecModel<i64>,
74        disabled_dates: &VecModel<Self>,
75    ) -> bool {
76        self.valid()
77            && DateBounds::new(minimum, maximum)
78                .with_disabled_weekdays(calendar_weekday_mask(disabled_weekdays))
79                .with_disabled_dates(disabled_dates.snapshot())
80                .allows(self)
81    }
82
83    pub fn valid(self) -> bool {
84        (1..=9999).contains(&self.year) && (1..=self.month_length()).contains(&self.day)
85    }
86
87    pub fn first_of_month(self) -> Self {
88        Self { day: 1, ..self }
89    }
90
91    pub fn last_of_month(self) -> Self {
92        Self {
93            day: self.month_length(),
94            ..self
95        }
96    }
97
98    fn month_length(self) -> i64 {
99        match self.month {
100            4 | 6 | 9 | 11 => 30,
101            2 => {
102                28 + i64::from(self.year % 4 == 0 && (self.year % 100 != 0 || self.year % 400 == 0))
103            }
104            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
105            _ => 0,
106        }
107    }
108
109    fn days_before_year(year: i64) -> i64 {
110        let prior = year - 1;
111        prior * 365 + prior / 4 - prior / 100 + prior / 400
112    }
113
114    fn ordinal(self) -> i64 {
115        Self::days_before_year(self.year) + self.day - 1
116            + (1..self.month)
117                .map(|month| Self { month, ..self }.month_length())
118                .sum::<i64>()
119    }
120
121    pub fn add_days(self, days: i64) -> Option<Self> {
122        if !self.valid() {
123            return None;
124        }
125        let ordinal = self.ordinal().checked_add(days)?;
126        if !(0..Self::days_before_year(10_000)).contains(&ordinal) {
127            return None;
128        }
129        let (mut year, mut end) = (1, 10_000);
130        while end - year > 1 {
131            let middle = (year + end) / 2;
132            if Self::days_before_year(middle) <= ordinal {
133                year = middle;
134            } else {
135                end = middle;
136            }
137        }
138        let mut day = ordinal - Self::days_before_year(year) + 1;
139        for month in 1..=12 {
140            let date = Self { year, month, day };
141            let count = date.month_length();
142            if day <= count {
143                return Some(date);
144            }
145            day -= count;
146        }
147        None
148    }
149
150    fn month_number(self) -> i64 {
151        (self.year - 1) * 12 + self.month - 1
152    }
153
154    fn from_month_number(number: i64) -> Self {
155        Self {
156            year: number.div_euclid(12) + 1,
157            month: number.rem_euclid(12) + 1,
158            day: 1,
159        }
160    }
161
162    fn month_span(self, to: Self) -> Option<RangeInclusive<i64>> {
163        (self.valid() && to.valid() && self <= to).then(|| self.month_number()..=to.month_number())
164    }
165
166    /// Return the first day of every month intersecting this inclusive date range.
167    pub fn months_through(self, to: Self) -> VecModel<Self> {
168        VecModel::from(
169            self.month_span(to)
170                .into_iter()
171                .flatten()
172                .map(Self::from_month_number)
173                .collect::<Vec<_>>(),
174        )
175    }
176
177    /// Return the index of the date's month in this range, or -1 if it is absent.
178    pub fn month_index(self, to: Self, date: Self) -> i64 {
179        if date.valid()
180            && let Some(span) = self.month_span(to)
181        {
182            let month = date.month_number();
183            if span.contains(&month) {
184                return month - span.start();
185            }
186        }
187        -1
188    }
189
190    /// Return the first day of the month at the given offset.
191    pub fn add_months(self, months: i64) -> Option<Self> {
192        if !self.valid() {
193            return None;
194        }
195        let index = self.month_number().checked_add(months)?;
196        Self::new(index.div_euclid(12) + 1, index.rem_euclid(12) + 1, 1)
197    }
198
199    /// Shift by whole months, retaining the day or clamping it to the target month's end.
200    pub fn add_months_clamped(self, months: i64) -> Option<Self> {
201        let month = self.add_months(months)?;
202        Some(Self {
203            day: self.day.min(month.month_length()),
204            ..month
205        })
206    }
207
208    /// ISO weekday number, Monday (1) through Sunday (7).
209    pub fn weekday(self) -> Option<i64> {
210        self.valid().then(|| self.ordinal().rem_euclid(7) + 1)
211    }
212
213    /// ISO 8601 week-based year and week number.
214    pub fn iso_week(self) -> Option<(i64, i64)> {
215        if !self.valid() {
216            return None;
217        }
218        let ordinal = self.ordinal();
219        let thursday = ordinal + 3 - ordinal.rem_euclid(7);
220        let year = if thursday < Self::days_before_year(self.year) {
221            self.year - 1
222        } else if thursday >= Self::days_before_year(self.year + 1) {
223            self.year + 1
224        } else {
225            self.year
226        };
227        Some((year, (thursday - Self::days_before_year(year)) / 7 + 1))
228    }
229}
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq)]
232pub enum CalendarAction {
233    Select(Date),
234    Browse(Date),
235    Activate(Date),
236}
237
238/// Apply calendar state before emitting its change notifications.
239#[doc(hidden)]
240pub enum CalendarUpdate {
241    SetDate(Date),
242    SetMonth(Date),
243    DateChanged(Date),
244    MonthChanged(Date),
245    Activated(Date),
246}
247
248#[doc(hidden)]
249pub fn apply_calendar_action(
250    node: &Node,
251    action: CalendarAction,
252    mut update: impl FnMut(CalendarUpdate),
253) -> bool {
254    try_apply_calendar_action(node, action, |change| {
255        update(change);
256        Ok::<_, std::convert::Infallible>(())
257    })
258    .unwrap_or_else(|error| match error {})
259}
260
261#[doc(hidden)]
262pub fn try_apply_calendar_action<E>(
263    node: &Node,
264    action: CalendarAction,
265    mut update: impl FnMut(CalendarUpdate) -> Result<(), E>,
266) -> Result<bool, E> {
267    let calendar = CalendarState::from_node(node);
268    let week_start = (node.kind == "MonthGrid").then(|| node.int("week-start").unwrap_or(1));
269    let Some((date, month)) = calendar.apply(action, week_start) else {
270        return Ok(false);
271    };
272    let date = date.filter(|date| node.date("date") != Some(*date));
273    let month_changed = month != calendar.month;
274    if let Some(date) = date {
275        update(CalendarUpdate::SetDate(date))?;
276    }
277    if month_changed {
278        update(CalendarUpdate::SetMonth(month))?;
279    }
280    if let Some(date) = date {
281        update(CalendarUpdate::DateChanged(date))?;
282    }
283    if month_changed {
284        update(CalendarUpdate::MonthChanged(month))?;
285    }
286    if let CalendarAction::Activate(date) = action {
287        update(CalendarUpdate::Activated(date))?;
288        return Ok(true);
289    }
290    Ok(date.is_some() || month_changed)
291}
292
293#[doc(hidden)]
294pub fn calendar_weekday_mask(weekdays: &VecModel<i64>) -> u8 {
295    weekday_mask(weekdays.snapshot())
296}
297
298fn weekday_mask(weekdays: impl IntoIterator<Item = i64>) -> u8 {
299    weekdays
300        .into_iter()
301        .filter(|day| (1..=7).contains(day))
302        .fold(0, |mask, day| mask | (1 << (day - 1)))
303}
304
305/// Check the calendar bindings that determine how the displayed action is interpreted.
306#[doc(hidden)]
307pub fn try_calendar_input_is_current<E>(
308    node: &Node,
309    input: crate::InputRoute<'_>,
310    mut read: impl FnMut(&str, Date) -> Result<Date, E>,
311    week_start: impl FnOnce() -> Result<i64, E>,
312    disabled_weekdays: impl FnOnce() -> Result<u8, E>,
313    disabled_dates: impl FnOnce() -> Result<Vec<Date>, E>,
314    fixed_month: impl FnOnce() -> Result<bool, E>,
315) -> Result<bool, E> {
316    let selected = node.date("date").unwrap_or_default();
317    input.try_available(|| {
318        let mut exclusions = DateExclusions {
319            weekdays: disabled_weekdays()?,
320            dates: disabled_dates()?,
321        };
322        exclusions.normalize();
323        if exclusions != DateBounds::from_node(node).exclusions || !input.is_current() {
324            return Ok(false);
325        }
326        if node.kind == "MonthGrid" {
327            let mut read_current = |name, default| {
328                let date = read(name, default)?;
329                Ok(input.is_current().then_some(date))
330            };
331            let Some(minimum) = read_current("minimum-date", Date::MIN)? else {
332                return Ok(false);
333            };
334            let Some(maximum) = read_current("maximum-date", Date::MAX)? else {
335                return Ok(false);
336            };
337            let Some(date) = read_current("date", Date::default())? else {
338                return Ok(false);
339            };
340            let Some(month) = read_current("display-month", date)? else {
341                return Ok(false);
342            };
343            let bounds = DateBounds {
344                exclusions,
345                ..DateBounds::new(minimum, maximum)
346            };
347            let live = CalendarState::for_month_grid(date, month, bounds, fixed_month()?);
348            return Ok(live == CalendarState::from_node(node)
349                && week_start()? == node.int("week-start").unwrap_or(1));
350        }
351        for (property, default) in [
352            ("minimum-date", Date::MIN),
353            ("maximum-date", Date::MAX),
354            ("date", Date::default()),
355            ("display-month", selected),
356        ] {
357            if read(property, default)? != node.date(property).unwrap_or(default)
358                || !input.is_current()
359            {
360                return Ok(false);
361            }
362        }
363        Ok(true)
364    })
365}
366
367#[doc(hidden)]
368pub fn calendar_input_is_current(
369    node: &Node,
370    input: crate::InputRoute<'_>,
371    mut read: impl FnMut(&str, Date) -> Date,
372    week_start: impl FnOnce() -> i64,
373    disabled_weekdays: impl FnOnce() -> u8,
374    disabled_dates: impl FnOnce() -> Vec<Date>,
375    fixed_month: impl FnOnce() -> bool,
376) -> bool {
377    try_calendar_input_is_current(
378        node,
379        input,
380        |name, default| Ok::<_, std::convert::Infallible>(read(name, default)),
381        || Ok(week_start()),
382        || Ok(disabled_weekdays()),
383        || Ok(disabled_dates()),
384        || Ok(fixed_month()),
385    )
386    .unwrap_or_else(|error| match error {})
387}
388
389pub fn is_calendar_control(kind: &str) -> bool {
390    matches!(kind, "Calendar" | "MonthGrid")
391}
392
393#[derive(Clone, Debug, PartialEq, Eq)]
394pub struct CalendarState {
395    pub minimum: Date,
396    pub maximum: Date,
397    pub selected: Date,
398    /// First day of the displayed month.
399    pub month: Date,
400    /// A MonthGrid whose viewport belongs to a fixed month in a larger view.
401    pub fixed_month: bool,
402    exclusions: DateExclusions,
403}
404
405#[doc(hidden)]
406#[derive(Clone)]
407pub struct DateBounds {
408    minimum: Date,
409    maximum: Date,
410    exclusions: DateExclusions,
411}
412
413#[derive(Clone, Default, Debug, PartialEq, Eq)]
414struct DateExclusions {
415    weekdays: u8,
416    dates: Vec<Date>,
417}
418
419impl DateExclusions {
420    fn normalize(&mut self) {
421        self.dates.retain(|date| date.valid());
422        self.dates.sort_unstable();
423        self.dates.dedup();
424    }
425
426    fn allows(&self, date: Date) -> bool {
427        let weekday_allowed = if self.weekdays == 0 {
428            date.valid()
429        } else {
430            date.weekday()
431                .is_some_and(|day| self.weekdays & (1 << (day - 1)) == 0)
432        };
433        weekday_allowed && self.dates.binary_search(&date).is_err()
434    }
435}
436
437impl DateBounds {
438    pub fn new(minimum: Date, maximum: Date) -> Self {
439        let minimum = if minimum.valid() { minimum } else { Date::MIN };
440        let maximum = if maximum.valid() { maximum } else { Date::MAX };
441        Self {
442            minimum,
443            maximum: maximum.max(minimum),
444            exclusions: DateExclusions::default(),
445        }
446    }
447
448    pub fn with_disabled_weekdays(mut self, weekdays: u8) -> Self {
449        self.exclusions.weekdays = weekdays;
450        self
451    }
452
453    pub fn with_disabled_dates(mut self, dates: Vec<Date>) -> Self {
454        self.exclusions.dates = dates;
455        self.exclusions.normalize();
456        self
457    }
458
459    fn from_node(node: &Node) -> Self {
460        Self::new(
461            node.date("minimum-date").unwrap_or(Date::MIN),
462            node.date("maximum-date").unwrap_or(Date::MAX),
463        )
464        .with_disabled_weekdays(match node.properties.get("disabled-weekdays") {
465            Some(Value::IntList(weekdays)) => weekday_mask(weekdays.iter().copied()),
466            _ => 0,
467        })
468        .with_disabled_dates(match node.properties.get("disabled-dates") {
469            Some(Value::DateList(dates)) => dates.clone(),
470            _ => Vec::new(),
471        })
472    }
473
474    fn allows(&self, date: Date) -> bool {
475        (self.minimum..=self.maximum).contains(&date) && self.exclusions.allows(date)
476    }
477
478    fn allowable_date(&self, date: Date) -> Option<Date> {
479        let date = self.constrain(date);
480        self.allows(date).then_some(date)
481    }
482
483    fn constrain(&self, date: Date) -> Date {
484        let date = if date.valid() { date } else { Date::default() };
485        date.clamp(self.minimum, self.maximum)
486    }
487}
488
489impl CalendarState {
490    pub fn from_node(node: &Node) -> Self {
491        let date = node.date("date").unwrap_or_default();
492        let month = node.date("display-month");
493        let bounds = DateBounds::from_node(node);
494        if matches!(node.kind, "MonthGrid" | "WeekNumberColumn") {
495            Self::for_month_grid(
496                date,
497                month.unwrap_or(date),
498                bounds,
499                node.kind == "MonthGrid" && node.boolean("fixed-month", false),
500            )
501        } else {
502            Self::with_bounds(date, month, bounds)
503        }
504    }
505
506    #[doc(hidden)]
507    pub fn for_month_grid(date: Date, month: Date, bounds: DateBounds, fixed_month: bool) -> Self {
508        let month = if month.valid() {
509            month
510        } else {
511            Date::default()
512        };
513        Self {
514            minimum: bounds.minimum,
515            maximum: bounds.maximum,
516            selected: bounds.constrain(date),
517            month: month.first_of_month(),
518            fixed_month,
519            exclusions: bounds.exclusions,
520        }
521    }
522
523    fn with_bounds(date: Date, month: Option<Date>, bounds: DateBounds) -> Self {
524        let selected = bounds.constrain(date);
525        let month = bounds
526            .constrain(month.filter(|date| date.valid()).unwrap_or(selected))
527            .first_of_month();
528        Self {
529            minimum: bounds.minimum,
530            maximum: bounds.maximum,
531            selected,
532            month,
533            fixed_month: false,
534            exclusions: bounds.exclusions,
535        }
536    }
537
538    #[doc(hidden)]
539    pub fn apply(
540        &self,
541        action: CalendarAction,
542        grid_week_start: Option<i64>,
543    ) -> Option<(Option<Date>, Date)> {
544        match action {
545            CalendarAction::Select(date) if self.allows(date) => {
546                let month = if grid_week_start.is_some_and(|start| self.shows(date, start)) {
547                    self.month
548                } else {
549                    date.first_of_month()
550                };
551                Some((Some(date), month))
552            }
553            CalendarAction::Activate(date)
554                if self.allows(date)
555                    && grid_week_start.is_some_and(|start| self.shows(date, start)) =>
556            {
557                Some((Some(date), self.month))
558            }
559            CalendarAction::Browse(_) if self.fixed_month => None,
560            CalendarAction::Browse(month) if grid_week_start.is_some() => {
561                (month.valid() && month.day == 1).then_some((None, month))
562            }
563            CalendarAction::Browse(month) if self.allows_month(month) => Some((None, month)),
564            _ => None,
565        }
566    }
567
568    pub fn allows(&self, date: Date) -> bool {
569        self.selection_range().contains(&date) && self.exclusions.allows(date)
570    }
571
572    fn selection_range(&self) -> RangeInclusive<Date> {
573        if self.fixed_month {
574            self.minimum.max(self.month)..=self.maximum.min(self.month.last_of_month())
575        } else {
576            self.minimum..=self.maximum
577        }
578    }
579
580    /// Find the first selectable day at or beyond the requested calendar position.
581    pub fn selectable_from(&self, date: Date, forward: bool) -> Option<Date> {
582        if self.exclusions.weekdays == 0x7f {
583            return None;
584        }
585        let direction = if forward { 1 } else { -1 };
586        let range = self.selection_range();
587        std::iter::successors(Some(date), |day| day.add_days(direction))
588            .take_while(|date| range.contains(date))
589            .find(|date| self.exclusions.allows(*date))
590    }
591
592    pub fn allows_month(&self, month: Date) -> bool {
593        month.valid()
594            && month.day == 1
595            && month <= self.maximum
596            && month.last_of_month() >= self.minimum
597    }
598
599    pub fn adjacent_month(&self, months: i64) -> Option<Date> {
600        self.month
601            .add_months(months)
602            .filter(|&date| self.allows_month(date))
603    }
604
605    pub fn cursor(&self) -> Date {
606        if self.selected.first_of_month() == self.month {
607            self.selected
608        } else {
609            self.month.max(self.minimum)
610        }
611    }
612
613    /// Six complete weeks starting on Monday (1) through Sunday (7).
614    pub fn cells(&self, week_start: i64) -> [Option<Date>; 42] {
615        if !self.month.valid() {
616            return [None; 42];
617        }
618        let offset = self.grid_offset(week_start);
619        std::array::from_fn(|index| self.month.add_days(index as i64 - offset))
620    }
621
622    pub fn shows(&self, date: Date, week_start: i64) -> bool {
623        date.valid()
624            && self.month.valid()
625            && (0..42)
626                .contains(&(date.ordinal() - self.month.ordinal() + self.grid_offset(week_start)))
627    }
628
629    fn grid_offset(&self, week_start: i64) -> i64 {
630        (self.month.ordinal() - (week_start.clamp(1, 7) - 1)).rem_euclid(7)
631    }
632}
633
634/// The visual date interval can be shared without changing how a calendar selects a date.
635#[doc(hidden)]
636#[derive(Clone, Copy)]
637pub struct CalendarHighlight {
638    endpoints: Option<(Date, Date)>,
639    fixed_month: bool,
640}
641
642#[doc(hidden)]
643#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
644pub struct CalendarHighlightDay {
645    pub in_range: bool,
646    pub start: bool,
647    pub end: bool,
648}
649
650impl CalendarHighlight {
651    pub fn from_node(node: &Node, fixed_month: bool) -> Self {
652        let endpoints = node
653            .date("highlight-start")
654            .zip(node.date("highlight-end"))
655            .filter(|(start, end)| start.valid() && end.valid())
656            .map(|(start, end)| (start.min(end), start.max(end)));
657        Self {
658            endpoints,
659            fixed_month,
660        }
661    }
662
663    pub fn day(self, date: Date, in_month: bool) -> CalendarHighlightDay {
664        if let Some((start, end)) = self.endpoints
665            && (in_month || !self.fixed_month)
666            && (start..=end).contains(&date)
667        {
668            CalendarHighlightDay {
669                in_range: true,
670                start: date == start,
671                end: date == end,
672            }
673        } else {
674            CalendarHighlightDay::default()
675        }
676    }
677}
678
679/// Inputs to a visual template for one date in a MonthGrid.
680#[doc(hidden)]
681#[derive(Clone, Copy, Debug, PartialEq, Eq)]
682pub struct CalendarCell {
683    pub date: Date,
684    pub index: i64,
685    pub weekday: i64,
686    pub week: i64,
687    pub week_year: i64,
688    pub selected: bool,
689    pub today: bool,
690    pub in_month: bool,
691    pub enabled: bool,
692    pub in_range: bool,
693    pub range_start: bool,
694    pub range_end: bool,
695}
696
697#[derive(Default)]
698struct CachedCalendarCell {
699    input: Property<CalendarCell>,
700    scene: Property<Node>,
701}
702
703/// Cache the visual bindings of each displayed date independently.
704#[doc(hidden)]
705#[derive(Default)]
706pub struct CalendarCells(RefCell<BTreeMap<Date, CachedCalendarCell>>);
707
708impl CalendarCells {
709    pub fn render(&self, grid: &Node, render_cell: impl Fn(CalendarCell) -> Node) -> Node {
710        self.try_render(grid, |cell| {
711            Ok::<_, std::convert::Infallible>(render_cell(cell))
712        })
713        .unwrap_or_else(|error| match error {})
714    }
715
716    pub fn try_render<E>(
717        &self,
718        grid: &Node,
719        render_cell: impl Fn(CalendarCell) -> Result<Node, E>,
720    ) -> Result<Node, E> {
721        let state = CalendarState::from_node(grid);
722        let start = grid.int("week-start").unwrap_or(1).clamp(1, 7);
723        let today = grid.date("today");
724        let dates = state.cells(start);
725        let highlight = CalendarHighlight::from_node(grid, state.fixed_month);
726        let mut cache = self.0.borrow_mut();
727        cache.retain(|date, _| dates.contains(&Some(*date)));
728        let mut cells = Node::new("CalendarCells", None);
729        cells.children = dates
730            .into_iter()
731            .enumerate()
732            .map(|(index, date)| {
733                let Some(date) = date else {
734                    return Ok(Node::hidden());
735                };
736                let Some((week_year, week)) = date.iso_week() else {
737                    return Ok(Node::hidden());
738                };
739                let in_month = date.first_of_month() == state.month;
740                let mark = highlight.day(date, in_month);
741                let input = CalendarCell {
742                    date,
743                    index: index as i64,
744                    weekday: (start - 1 + index as i64) % 7 + 1,
745                    week,
746                    week_year,
747                    selected: date == state.selected && state.allows(date),
748                    today: Some(date) == today,
749                    in_month,
750                    enabled: state.allows(date),
751                    in_range: mark.in_range,
752                    range_start: mark.start,
753                    range_end: mark.end,
754                };
755                let cached = cache.entry(date).or_default();
756                cached.input.set_if_changed(input);
757                cached
758                    .scene
759                    .try_get(|| render_cell(cached.input.get(|| input)))
760            })
761            .collect::<Result<_, _>>()?;
762        Ok(cells)
763    }
764}
765
766/// Draft date and browsed month share one session without changing the committed date.
767#[doc(hidden)]
768#[derive(Default)]
769pub struct DatePopupState(PickerSession<(Date, Date)>);
770
771impl DatePopupState {
772    #[doc(hidden)]
773    pub fn accepts_input(&self, node: &Node, input: InputRoute<'_>) -> bool {
774        self.0.accepts_input(node, input)
775    }
776
777    pub fn close(&self) {
778        self.0.close();
779    }
780
781    pub fn populate(&self, dialog: &mut Node, date: impl FnOnce() -> Date) {
782        self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(date()))
783            .unwrap_or_else(|error| match error {});
784    }
785
786    pub fn try_populate<E>(
787        &self,
788        dialog: &mut Node,
789        date: impl FnOnce() -> Result<Date, E>,
790    ) -> Result<(), E> {
791        let bounds = DateBounds::from_node(dialog);
792        let Some((date, month)) = self.0.try_begin(dialog, || {
793            let date = bounds.constrain(date()?);
794            Ok((date, date.first_of_month()))
795        })?
796        else {
797            return Ok(());
798        };
799        let state = CalendarState::with_bounds(date, Some(month), bounds);
800        let mut calendar = Node::new("Calendar", None);
801        for key in [
802            "week-start",
803            "disabled-weekdays",
804            "disabled-dates",
805            "weekday-labels",
806            "font",
807            "font-size",
808            "font-family",
809            "font-weight",
810            "font-italic",
811        ] {
812            if let Some(value) = dialog.properties.get(key) {
813                calendar.properties.insert(key, value.clone());
814            }
815        }
816        calendar.properties.insert("date", state.selected.into());
817        calendar
818            .properties
819            .insert("display-month", state.month.into());
820        calendar
821            .properties
822            .insert("minimum-date", state.minimum.into());
823        calendar
824            .properties
825            .insert("maximum-date", state.maximum.into());
826        self.0.stamp(&mut calendar);
827        append_picker_dialog(dialog, calendar, state.allows(state.selected));
828        Ok(())
829    }
830
831    pub fn edit(&self, bounds: DateBounds, node: &Node, action: ControlAction) -> bool {
832        let (Some((date, month)), ControlAction::Calendar(action)) = (self.0.current(node), action)
833        else {
834            return false;
835        };
836        let state = CalendarState::with_bounds(date, Some(month), bounds);
837        if node.kind != "Calendar" || CalendarState::from_node(node) != state {
838            return false;
839        }
840        let Some((selected, month)) = state.apply(action, None) else {
841            return false;
842        };
843        let next = (selected.unwrap_or(state.selected), month);
844        if next == (state.selected, state.month) {
845            return false;
846        }
847        self.0.set(next);
848        true
849    }
850
851    pub fn try_finish_input<E>(
852        &self,
853        dialog: &Node,
854        role: DialogRole,
855        input: InputRoute<'_>,
856        bounds: impl FnOnce() -> Result<DateBounds, E>,
857    ) -> Result<Option<Date>, E> {
858        let draft = self
859            .0
860            .try_finish_input(dialog, role, input, |(date, month)| {
861                Ok(bounds()?.allowable_date(date).map(|date| (date, month)))
862            })?;
863        Ok(draft.map(|(date, _)| date))
864    }
865
866    pub fn finish_input(
867        &self,
868        dialog: &Node,
869        role: DialogRole,
870        input: InputRoute<'_>,
871        bounds: impl FnOnce() -> DateBounds,
872    ) -> Option<Date> {
873        self.try_finish_input(dialog, role, input, || {
874            Ok::<_, std::convert::Infallible>(bounds())
875        })
876        .unwrap_or_else(|error| match error {})
877    }
878
879    pub fn finish(&self, bounds: DateBounds, dialog: &Node) -> Option<Date> {
880        self.finish_with_role(bounds, dialog, DialogRole::Accept)
881    }
882
883    pub fn finish_with_role(
884        &self,
885        bounds: DateBounds,
886        dialog: &Node,
887        role: DialogRole,
888    ) -> Option<Date> {
889        if role == DialogRole::Accept && bounds.allowable_date(self.0.current(dialog)?.0).is_none()
890        {
891            return None;
892        }
893        self.0
894            .finish(dialog, role)
895            .map(|(date, _)| bounds.constrain(date))
896    }
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902
903    #[test]
904    fn gregorian_arithmetic_handles_leap_centuries_and_calendar_limits() {
905        let date = |year, month, day| Date::new(year, month, day).unwrap();
906        assert_eq!(date(1900, 2, 28).add_days(1), Some(date(1900, 3, 1)));
907        assert_eq!(date(2000, 2, 28).add_days(1), Some(date(2000, 2, 29)));
908        assert_eq!(date(2025, 1, 1).add_days(-1), Some(date(2024, 12, 31)));
909        assert_eq!(
910            date(1970, 1, 1).add_days(20_000).unwrap().add_days(-20_000),
911            Some(Date::default())
912        );
913        assert_eq!(Date::MIN.add_days(-1), None);
914        assert_eq!(Date::MAX.add_days(1), None);
915        assert_eq!(Date::MIN.add_days(i64::MAX), None);
916    }
917
918    #[test]
919    fn calendar_template_only_renders_cells_whose_inputs_changed() {
920        use std::cell::Cell;
921        let date = |day| Date::new(2026, 11, day).unwrap();
922        let evaluations = Cell::new(0);
923        let note = Property::default();
924        let cells = CalendarCells::default();
925        let mut grid = Node::new("MonthGrid", None);
926        grid.properties.insert("display-month", date(1).into());
927        grid.properties.insert("date", date(11).into());
928        let render = |grid: &Node| {
929            cells.render(grid, |day| {
930                evaluations.set(evaluations.get() + 1);
931                let mut cell = Node::new("Rectangle", None);
932                if day.date == date(12) {
933                    cell.properties
934                        .insert("accessible-description", note.get(String::new).into());
935                }
936                cell
937            })
938        };
939        assert_eq!(render(&grid).children.len(), 42);
940        assert_eq!(evaluations.get(), 42);
941        grid.properties.insert("date", date(12).into());
942        render(&grid);
943        assert_eq!(evaluations.get(), 44);
944        note.set_if_changed("Review".to_owned());
945        render(&grid);
946        assert_eq!(evaluations.get(), 45);
947    }
948
949    #[test]
950    fn iso_weeks_use_the_thursday_at_new_year() {
951        let week = |year, month, day| Date::new(year, month, day).unwrap().iso_week().unwrap();
952        assert_eq!(week(2018, 12, 31), (2019, 1));
953        assert_eq!(week(2021, 1, 1), (2020, 53));
954        assert_eq!(week(2021, 1, 3), (2020, 53));
955        assert_eq!(week(2021, 1, 4), (2021, 1));
956        assert_eq!(Date::MIN.iso_week(), Some((1, 1)));
957        assert_eq!(Date::MAX.iso_week(), Some((9999, 52)));
958    }
959
960    #[test]
961    fn weekday_policy_snapshots_models_and_skips_days_within_date_bounds() {
962        let date = |day| Date::new(2024, 3, day).unwrap();
963        let weekdays = VecModel::from(vec![6, 7, 6, -1, 8]);
964        let mut node = Node::new("Calendar", None);
965        node.properties.insert("minimum-date", date(1).into());
966        node.properties.insert("maximum-date", date(8).into());
967        node.properties
968            .insert("disabled-weekdays", weekdays.clone().into());
969        let old = node.clone();
970        let state = CalendarState::from_node(&old);
971        assert_eq!(state.selectable_from(date(2), true), Some(date(4)));
972        assert_eq!(state.selectable_from(date(3), false), Some(date(1)));
973        assert_eq!(state.apply(CalendarAction::Select(date(2)), None), None);
974        weekdays.push(1);
975        node.properties
976            .insert("disabled-weekdays", weekdays.clone().into());
977        assert_eq!(
978            CalendarState::from_node(&old).selectable_from(date(2), true),
979            Some(date(4))
980        );
981        assert_eq!(
982            CalendarState::from_node(&node).selectable_from(date(2), true),
983            Some(date(5))
984        );
985        node.properties
986            .insert("disabled-weekdays", Value::IntList((1_i64..=7).collect()));
987        assert_eq!(
988            CalendarState::from_node(&node).selectable_from(date(1), true),
989            None
990        );
991    }
992
993    #[test]
994    fn iso_date_parsing_and_shared_constraints_cover_invalid_dates_and_live_models() {
995        let leap_day = Date::new(2000, 2, 29).unwrap();
996        assert_eq!(Date::parse_iso("2000-02-29"), Some(leap_day));
997        assert_eq!(Date::parse_iso("0001-01-01"), Some(Date::MIN));
998        assert_eq!(Date::parse_iso("9999-12-31"), Some(Date::MAX));
999        for invalid in [
1000            "1900-02-29",
1001            "2024-02-30",
1002            "0000-01-01",
1003            "2024-2-29",
1004            "2024/02/29",
1005            "2024-02-29 ",
1006            "2024-02-29",
1007            "2024-02-2é",
1008        ] {
1009            assert!(Date::parse_iso(invalid).is_none(), "{invalid}");
1010        }
1011        let disabled_weekdays = VecModel::from(vec![6_i64, 7]);
1012        let closed = VecModel::from(vec![leap_day]);
1013        assert!(!leap_day.is_selectable(Date::MIN, Date::MAX, &disabled_weekdays, &closed));
1014        closed.clear();
1015        assert!(leap_day.is_selectable(Date::MIN, Date::MAX, &disabled_weekdays, &closed));
1016        let saturday = Date::new(2000, 3, 4).unwrap();
1017        assert!(!saturday.is_selectable(Date::MIN, Date::MAX, &disabled_weekdays, &closed));
1018        assert!(!leap_day.is_selectable(saturday, Date::MAX, &disabled_weekdays, &closed));
1019    }
1020
1021    #[test]
1022    fn month_ranges_and_indexes_cover_partial_months_without_overflow() {
1023        let date = |year, month, day| Date::new(year, month, day).unwrap();
1024        let from = date(2023, 12, 31);
1025        let to = date(2024, 2, 29);
1026        assert_eq!(
1027            from.months_through(to).snapshot(),
1028            vec![date(2023, 12, 1), date(2024, 1, 1), date(2024, 2, 1)]
1029        );
1030        assert_eq!(from.month_index(to, date(2023, 12, 1)), 0);
1031        assert_eq!(from.month_index(to, to), 2);
1032        assert_eq!(from.month_index(to, date(2024, 3, 1)), -1);
1033        assert!(to.months_through(from).is_empty());
1034        assert_eq!(Date::MIN.month_index(Date::MAX, Date::MAX), 119_987);
1035        let invalid = Date {
1036            year: 1900,
1037            month: 2,
1038            day: 29,
1039        };
1040        assert!(invalid.months_through(to).is_empty());
1041        assert_eq!(from.month_index(to, invalid), -1);
1042    }
1043
1044    #[test]
1045    fn fixed_month_keeps_adjacent_days_visible_but_unselectable() {
1046        let mut node = Node::new("MonthGrid", None);
1047        let month = Date::new(2024, 2, 1).unwrap();
1048        let previous = month.add_days(-1).unwrap();
1049        let next = month.add_months(1).unwrap();
1050        let last = month.last_of_month();
1051        node.properties.insert("display-month", month.into());
1052        node.properties.insert("fixed-month", true.into());
1053        let state = CalendarState::from_node(&node);
1054        assert!(state.shows(previous, 1));
1055        assert!(state.shows(next, 1));
1056        assert!(!state.allows(previous));
1057        assert!(!state.allows(next));
1058        assert_eq!(state.selectable_from(last, true), Some(last));
1059        assert_eq!(state.selectable_from(next, true), None);
1060        assert_eq!(state.apply(CalendarAction::Select(next), Some(1)), None);
1061        assert_eq!(state.apply(CalendarAction::Browse(next), Some(1)), None);
1062        assert_eq!(
1063            state.apply(CalendarAction::Select(last), Some(1)),
1064            Some((Some(last), month))
1065        );
1066    }
1067
1068    #[test]
1069    fn highlights_normalize_reverse_ranges_and_refresh_only_changed_cells() {
1070        use std::cell::Cell;
1071        let date = |day| Date::new(2024, 2, day).unwrap();
1072        let mut grid = Node::new("MonthGrid", None);
1073        grid.properties.insert("display-month", date(1).into());
1074        grid.properties
1075            .insert("disabled-dates", Value::DateList(vec![date(28)]));
1076        let rerendered = Cell::new(0);
1077        let cache = CalendarCells::default();
1078        cache.render(&grid, |_| Node::new("Rectangle", None));
1079        grid.properties.insert("highlight-start", date(29).into());
1080        grid.properties.insert("highlight-end", date(27).into());
1081        cache.render(&grid, |cell| {
1082            rerendered.set(rerendered.get() + 1);
1083            assert!(cell.in_range);
1084            assert_eq!(cell.range_start, cell.date == date(27));
1085            assert_eq!(cell.range_end, cell.date == date(29));
1086            assert_eq!(cell.enabled, cell.date != date(28));
1087            Node::new("Rectangle", None)
1088        });
1089        assert_eq!(rerendered.get(), 3);
1090        let next = Date::new(2024, 3, 1).unwrap();
1091        grid.properties.insert("highlight-start", next.into());
1092        let range = CalendarHighlight::from_node(&grid, true);
1093        assert!(!range.day(next, false).in_range);
1094        assert!(range.day(next, true).end);
1095        grid.properties.remove("highlight-start");
1096        assert!(
1097            !CalendarHighlight::from_node(&grid, false)
1098                .day(date(27), true)
1099                .in_range
1100        );
1101    }
1102
1103    #[test]
1104    fn date_exclusions_skip_a_closure_longer_than_one_week() {
1105        let date = |day| Date::new(2024, 3, day).unwrap();
1106        let mut node = Node::new("Calendar", None);
1107        let mut closures = (1..=10).rev().map(date).collect::<Vec<_>>();
1108        closures.extend([
1109            date(2),
1110            Date {
1111                year: 2024,
1112                month: 2,
1113                day: 30,
1114            },
1115        ]);
1116        node.properties
1117            .insert("disabled-dates", Value::DateList(closures));
1118        node.properties
1119            .insert("disabled-weekdays", Value::IntList(vec![1]));
1120        let state = CalendarState::from_node(&node);
1121        assert_eq!(state.selectable_from(date(1), true), Some(date(12)));
1122        assert!(!state.allows(date(10)));
1123        assert!(!state.allows(date(11)));
1124        assert_eq!(state.apply(CalendarAction::Select(date(10)), None), None);
1125    }
1126
1127    #[test]
1128    fn date_bounds_disable_cells_and_week_start_changes_the_first_column() {
1129        let mut node = Node::new("Calendar", None);
1130        let date = |month, day| Date::new(2024, month, day).unwrap();
1131        node.properties.insert("date", date(2, 29).into());
1132        node.properties.insert("minimum-date", date(2, 20).into());
1133        node.properties.insert("maximum-date", date(3, 5).into());
1134        let calendar = CalendarState::from_node(&node);
1135        assert_eq!(calendar.cells(1)[0], Some(date(1, 29)));
1136        assert_eq!(calendar.cells(7)[0], Some(date(1, 28)));
1137        assert!(calendar.cells(1).contains(&Some(date(2, 29))));
1138        assert!(!calendar.allows(date(2, 19)));
1139        assert!(calendar.allows(date(3, 5)));
1140        assert_eq!(calendar.adjacent_month(-1), None);
1141        assert_eq!(calendar.adjacent_month(1), Some(date(3, 1)));
1142    }
1143}