Skip to main content

xrack_runtime/
calendar.rs

1use crate::{
2    ControlAction, DialogRole, InputRoute, Node, Property,
3    picker::{PickerSession, append_picker_dialog},
4};
5use std::{cell::RefCell, collections::BTreeMap, fmt};
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    pub fn valid(self) -> bool {
49        (1..=9999).contains(&self.year) && (1..=self.month_length()).contains(&self.day)
50    }
51
52    pub fn first_of_month(self) -> Self {
53        Self { day: 1, ..self }
54    }
55
56    pub fn last_of_month(self) -> Self {
57        Self {
58            day: self.month_length(),
59            ..self
60        }
61    }
62
63    fn month_length(self) -> i64 {
64        match self.month {
65            4 | 6 | 9 | 11 => 30,
66            2 => {
67                28 + i64::from(self.year % 4 == 0 && (self.year % 100 != 0 || self.year % 400 == 0))
68            }
69            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
70            _ => 0,
71        }
72    }
73
74    fn days_before_year(year: i64) -> i64 {
75        let prior = year - 1;
76        prior * 365 + prior / 4 - prior / 100 + prior / 400
77    }
78
79    fn ordinal(self) -> i64 {
80        Self::days_before_year(self.year) + self.day - 1
81            + (1..self.month)
82                .map(|month| Self { month, ..self }.month_length())
83                .sum::<i64>()
84    }
85
86    pub fn add_days(self, days: i64) -> Option<Self> {
87        if !self.valid() {
88            return None;
89        }
90        let ordinal = self.ordinal().checked_add(days)?;
91        if !(0..Self::days_before_year(10_000)).contains(&ordinal) {
92            return None;
93        }
94        let (mut year, mut end) = (1, 10_000);
95        while end - year > 1 {
96            let middle = (year + end) / 2;
97            if Self::days_before_year(middle) <= ordinal {
98                year = middle;
99            } else {
100                end = middle;
101            }
102        }
103        let mut day = ordinal - Self::days_before_year(year) + 1;
104        for month in 1..=12 {
105            let date = Self { year, month, day };
106            let count = date.month_length();
107            if day <= count {
108                return Some(date);
109            }
110            day -= count;
111        }
112        None
113    }
114
115    /// Return the first day of the month at the given offset.
116    pub fn add_months(self, months: i64) -> Option<Self> {
117        if !self.valid() {
118            return None;
119        }
120        let index = ((self.year - 1) * 12 + self.month - 1).checked_add(months)?;
121        Self::new(index.div_euclid(12) + 1, index.rem_euclid(12) + 1, 1)
122    }
123
124    /// Shift by whole months, retaining the day or clamping it to the target month's end.
125    pub fn add_months_clamped(self, months: i64) -> Option<Self> {
126        let month = self.add_months(months)?;
127        Some(Self {
128            day: self.day.min(month.month_length()),
129            ..month
130        })
131    }
132
133    /// ISO weekday number, Monday (1) through Sunday (7).
134    pub fn weekday(self) -> Option<i64> {
135        self.valid().then(|| self.ordinal().rem_euclid(7) + 1)
136    }
137
138    /// ISO 8601 week-based year and week number.
139    pub fn iso_week(self) -> Option<(i64, i64)> {
140        if !self.valid() {
141            return None;
142        }
143        let ordinal = self.ordinal();
144        let thursday = ordinal + 3 - ordinal.rem_euclid(7);
145        let year = if thursday < Self::days_before_year(self.year) {
146            self.year - 1
147        } else if thursday >= Self::days_before_year(self.year + 1) {
148            self.year + 1
149        } else {
150            self.year
151        };
152        Some((year, (thursday - Self::days_before_year(year)) / 7 + 1))
153    }
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum CalendarAction {
158    Select(Date),
159    Browse(Date),
160    Activate(Date),
161}
162
163/// Apply calendar state before emitting its change notifications.
164#[doc(hidden)]
165pub enum CalendarUpdate {
166    SetDate(Date),
167    SetMonth(Date),
168    DateChanged(Date),
169    MonthChanged(Date),
170    Activated(Date),
171}
172
173#[doc(hidden)]
174pub fn apply_calendar_action(
175    node: &Node,
176    action: CalendarAction,
177    mut update: impl FnMut(CalendarUpdate),
178) -> bool {
179    try_apply_calendar_action(node, action, |change| {
180        update(change);
181        Ok::<_, std::convert::Infallible>(())
182    })
183    .unwrap_or_else(|error| match error {})
184}
185
186#[doc(hidden)]
187pub fn try_apply_calendar_action<E>(
188    node: &Node,
189    action: CalendarAction,
190    mut update: impl FnMut(CalendarUpdate) -> Result<(), E>,
191) -> Result<bool, E> {
192    let calendar = CalendarState::from_node(node);
193    let week_start = (node.kind == "MonthGrid").then(|| node.int("week-start").unwrap_or(1));
194    let Some((date, month)) = calendar.apply(action, week_start) else {
195        return Ok(false);
196    };
197    let date = date.filter(|date| node.date("date") != Some(*date));
198    let month_changed = month != calendar.month;
199    if let Some(date) = date {
200        update(CalendarUpdate::SetDate(date))?;
201    }
202    if month_changed {
203        update(CalendarUpdate::SetMonth(month))?;
204    }
205    if let Some(date) = date {
206        update(CalendarUpdate::DateChanged(date))?;
207    }
208    if month_changed {
209        update(CalendarUpdate::MonthChanged(month))?;
210    }
211    if let CalendarAction::Activate(date) = action {
212        update(CalendarUpdate::Activated(date))?;
213        return Ok(true);
214    }
215    Ok(date.is_some() || month_changed)
216}
217
218/// Check the calendar bindings that determine how the displayed action is interpreted.
219#[doc(hidden)]
220pub fn try_calendar_input_is_current<E>(
221    node: &Node,
222    input: crate::InputRoute<'_>,
223    mut read: impl FnMut(&str, Date) -> Result<Date, E>,
224    week_start: impl FnOnce() -> Result<i64, E>,
225) -> Result<bool, E> {
226    let selected = node.date("date").unwrap_or_default();
227    input.try_available(|| {
228        if node.kind == "MonthGrid" {
229            let mut read_current = |name, default| {
230                let date = read(name, default)?;
231                Ok(input.is_current().then_some(date))
232            };
233            let Some(minimum) = read_current("minimum-date", Date::MIN)? else {
234                return Ok(false);
235            };
236            let Some(maximum) = read_current("maximum-date", Date::MAX)? else {
237                return Ok(false);
238            };
239            let Some(date) = read_current("date", Date::default())? else {
240                return Ok(false);
241            };
242            let Some(month) = read_current("display-month", date)? else {
243                return Ok(false);
244            };
245            let live =
246                CalendarState::for_month_grid(date, month, DateBounds::new(minimum, maximum));
247            return Ok(live == CalendarState::from_node(node)
248                && week_start()? == node.int("week-start").unwrap_or(1));
249        }
250        for (property, default) in [
251            ("minimum-date", Date::MIN),
252            ("maximum-date", Date::MAX),
253            ("date", Date::default()),
254            ("display-month", selected),
255        ] {
256            if read(property, default)? != node.date(property).unwrap_or(default)
257                || !input.is_current()
258            {
259                return Ok(false);
260            }
261        }
262        Ok(true)
263    })
264}
265
266#[doc(hidden)]
267pub fn calendar_input_is_current(
268    node: &Node,
269    input: crate::InputRoute<'_>,
270    mut read: impl FnMut(&str, Date) -> Date,
271    week_start: impl FnOnce() -> i64,
272) -> bool {
273    try_calendar_input_is_current(
274        node,
275        input,
276        |name, default| Ok::<_, std::convert::Infallible>(read(name, default)),
277        || Ok(week_start()),
278    )
279    .unwrap_or_else(|error| match error {})
280}
281
282pub fn is_calendar_control(kind: &str) -> bool {
283    matches!(kind, "Calendar" | "MonthGrid")
284}
285
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287pub struct CalendarState {
288    pub minimum: Date,
289    pub maximum: Date,
290    pub selected: Date,
291    /// First day of the displayed month.
292    pub month: Date,
293}
294
295#[doc(hidden)]
296#[derive(Clone, Copy)]
297pub struct DateBounds {
298    minimum: Date,
299    maximum: Date,
300}
301
302impl DateBounds {
303    pub fn new(minimum: Date, maximum: Date) -> Self {
304        let minimum = if minimum.valid() { minimum } else { Date::MIN };
305        let maximum = if maximum.valid() { maximum } else { Date::MAX };
306        Self {
307            minimum,
308            maximum: maximum.max(minimum),
309        }
310    }
311
312    fn from_node(node: &Node) -> Self {
313        Self::new(
314            node.date("minimum-date").unwrap_or(Date::MIN),
315            node.date("maximum-date").unwrap_or(Date::MAX),
316        )
317    }
318
319    fn constrain(self, date: Date) -> Date {
320        let date = if date.valid() { date } else { Date::default() };
321        date.clamp(self.minimum, self.maximum)
322    }
323}
324
325impl CalendarState {
326    pub fn from_node(node: &Node) -> Self {
327        let date = node.date("date").unwrap_or_default();
328        let month = node.date("display-month");
329        let bounds = DateBounds::from_node(node);
330        if matches!(node.kind, "MonthGrid" | "WeekNumberColumn") {
331            Self::for_month_grid(date, month.unwrap_or(date), bounds)
332        } else {
333            Self::with_bounds(date, month, bounds)
334        }
335    }
336
337    #[doc(hidden)]
338    pub fn for_month_grid(date: Date, month: Date, bounds: DateBounds) -> Self {
339        let month = if month.valid() {
340            month
341        } else {
342            Date::default()
343        };
344        Self {
345            minimum: bounds.minimum,
346            maximum: bounds.maximum,
347            selected: bounds.constrain(date),
348            month: month.first_of_month(),
349        }
350    }
351
352    fn with_bounds(date: Date, month: Option<Date>, bounds: DateBounds) -> Self {
353        let selected = bounds.constrain(date);
354        let month = bounds
355            .constrain(month.filter(|date| date.valid()).unwrap_or(selected))
356            .first_of_month();
357        Self {
358            minimum: bounds.minimum,
359            maximum: bounds.maximum,
360            selected,
361            month,
362        }
363    }
364
365    #[doc(hidden)]
366    pub fn apply(
367        self,
368        action: CalendarAction,
369        grid_week_start: Option<i64>,
370    ) -> Option<(Option<Date>, Date)> {
371        match action {
372            CalendarAction::Select(date) if self.allows(date) => {
373                let month = if grid_week_start.is_some_and(|start| self.shows(date, start)) {
374                    self.month
375                } else {
376                    date.first_of_month()
377                };
378                Some((Some(date), month))
379            }
380            CalendarAction::Activate(date)
381                if self.allows(date)
382                    && grid_week_start.is_some_and(|start| self.shows(date, start)) =>
383            {
384                Some((Some(date), self.month))
385            }
386            CalendarAction::Browse(month) if grid_week_start.is_some() => {
387                (month.valid() && month.day == 1).then_some((None, month))
388            }
389            CalendarAction::Browse(month) if self.allows_month(month) => Some((None, month)),
390            _ => None,
391        }
392    }
393
394    pub fn allows(self, date: Date) -> bool {
395        date.valid() && (self.minimum..=self.maximum).contains(&date)
396    }
397
398    pub fn allows_month(self, month: Date) -> bool {
399        month.valid()
400            && month.day == 1
401            && month <= self.maximum
402            && month.last_of_month() >= self.minimum
403    }
404
405    pub fn adjacent_month(self, months: i64) -> Option<Date> {
406        self.month
407            .add_months(months)
408            .filter(|&date| self.allows_month(date))
409    }
410
411    pub fn cursor(self) -> Date {
412        if self.selected.first_of_month() == self.month {
413            self.selected
414        } else {
415            self.month.max(self.minimum)
416        }
417    }
418
419    /// Six complete weeks starting on Monday (1) through Sunday (7).
420    pub fn cells(self, week_start: i64) -> [Option<Date>; 42] {
421        if !self.month.valid() {
422            return [None; 42];
423        }
424        let offset = self.grid_offset(week_start);
425        std::array::from_fn(|index| self.month.add_days(index as i64 - offset))
426    }
427
428    pub fn shows(self, date: Date, week_start: i64) -> bool {
429        date.valid()
430            && self.month.valid()
431            && (0..42)
432                .contains(&(date.ordinal() - self.month.ordinal() + self.grid_offset(week_start)))
433    }
434
435    fn grid_offset(self, week_start: i64) -> i64 {
436        (self.month.ordinal() - (week_start.clamp(1, 7) - 1)).rem_euclid(7)
437    }
438}
439
440/// Inputs to a visual template for one date in a MonthGrid.
441#[doc(hidden)]
442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
443pub struct CalendarCell {
444    pub date: Date,
445    pub index: i64,
446    pub weekday: i64,
447    pub week: i64,
448    pub week_year: i64,
449    pub selected: bool,
450    pub today: bool,
451    pub in_month: bool,
452    pub enabled: bool,
453}
454
455#[derive(Default)]
456struct CachedCalendarCell {
457    input: Property<CalendarCell>,
458    scene: Property<Node>,
459}
460
461/// Cache the visual bindings of each displayed date independently.
462#[doc(hidden)]
463#[derive(Default)]
464pub struct CalendarCells(RefCell<BTreeMap<Date, CachedCalendarCell>>);
465
466impl CalendarCells {
467    pub fn render(&self, grid: &Node, render_cell: impl Fn(CalendarCell) -> Node) -> Node {
468        self.try_render(grid, |cell| {
469            Ok::<_, std::convert::Infallible>(render_cell(cell))
470        })
471        .unwrap_or_else(|error| match error {})
472    }
473
474    pub fn try_render<E>(
475        &self,
476        grid: &Node,
477        render_cell: impl Fn(CalendarCell) -> Result<Node, E>,
478    ) -> Result<Node, E> {
479        let state = CalendarState::from_node(grid);
480        let start = grid.int("week-start").unwrap_or(1).clamp(1, 7);
481        let today = grid.date("today");
482        let dates = state.cells(start);
483        let mut cache = self.0.borrow_mut();
484        cache.retain(|date, _| dates.contains(&Some(*date)));
485        let mut cells = Node::new("CalendarCells", None);
486        cells.children = dates
487            .into_iter()
488            .enumerate()
489            .map(|(index, date)| {
490                let Some(date) = date else {
491                    return Ok(Node::hidden());
492                };
493                let (week_year, week) =
494                    date.iso_week().expect("calendar cells contain valid dates");
495                let input = CalendarCell {
496                    date,
497                    index: index as i64,
498                    weekday: (start - 1 + index as i64) % 7 + 1,
499                    week,
500                    week_year,
501                    selected: date == state.selected,
502                    today: Some(date) == today,
503                    in_month: date.first_of_month() == state.month,
504                    enabled: state.allows(date),
505                };
506                let cached = cache.entry(date).or_default();
507                cached.input.set_if_changed(input);
508                cached
509                    .scene
510                    .try_get(|| render_cell(cached.input.get(|| input)))
511            })
512            .collect::<Result<_, _>>()?;
513        Ok(cells)
514    }
515}
516
517/// Draft date and browsed month share one session without changing the committed date.
518#[doc(hidden)]
519#[derive(Default)]
520pub struct DatePopupState(PickerSession<(Date, Date)>);
521
522impl DatePopupState {
523    #[doc(hidden)]
524    pub fn accepts_input(&self, node: &Node, input: InputRoute<'_>) -> bool {
525        self.0.accepts_input(node, input)
526    }
527
528    pub fn close(&self) {
529        self.0.close();
530    }
531
532    pub fn populate(&self, dialog: &mut Node, date: impl FnOnce() -> Date) {
533        self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(date()))
534            .unwrap_or_else(|error| match error {});
535    }
536
537    pub fn try_populate<E>(
538        &self,
539        dialog: &mut Node,
540        date: impl FnOnce() -> Result<Date, E>,
541    ) -> Result<(), E> {
542        let bounds = DateBounds::from_node(dialog);
543        let Some((date, month)) = self.0.try_begin(dialog, || {
544            let date = bounds.constrain(date()?);
545            Ok((date, date.first_of_month()))
546        })?
547        else {
548            return Ok(());
549        };
550        let state = CalendarState::with_bounds(date, Some(month), bounds);
551        let mut calendar = Node::new("Calendar", None);
552        for key in [
553            "week-start",
554            "weekday-labels",
555            "font",
556            "font-size",
557            "font-family",
558            "font-weight",
559            "font-italic",
560        ] {
561            if let Some(value) = dialog.properties.get(key) {
562                calendar.properties.insert(key, value.clone());
563            }
564        }
565        calendar.properties.insert("date", state.selected.into());
566        calendar
567            .properties
568            .insert("display-month", state.month.into());
569        calendar
570            .properties
571            .insert("minimum-date", state.minimum.into());
572        calendar
573            .properties
574            .insert("maximum-date", state.maximum.into());
575        self.0.stamp(&mut calendar);
576        append_picker_dialog(dialog, calendar);
577        Ok(())
578    }
579
580    pub fn edit(&self, bounds: DateBounds, node: &Node, action: ControlAction) -> bool {
581        let (Some((date, month)), ControlAction::Calendar(action)) = (self.0.current(node), action)
582        else {
583            return false;
584        };
585        let state = CalendarState::with_bounds(date, Some(month), bounds);
586        if node.kind != "Calendar" || CalendarState::from_node(node) != state {
587            return false;
588        }
589        let Some((selected, month)) = state.apply(action, None) else {
590            return false;
591        };
592        let next = (selected.unwrap_or(state.selected), month);
593        if next == (state.selected, state.month) {
594            return false;
595        }
596        self.0.set(next);
597        true
598    }
599
600    pub fn try_finish_input<E>(
601        &self,
602        dialog: &Node,
603        role: DialogRole,
604        input: InputRoute<'_>,
605        bounds: impl FnOnce() -> Result<DateBounds, E>,
606    ) -> Result<Option<Date>, E> {
607        let draft = self
608            .0
609            .try_finish_input(dialog, role, input, |(date, month)| {
610                Ok(Some((bounds()?.constrain(date), month)))
611            })?;
612        Ok(draft.map(|(date, _)| date))
613    }
614
615    pub fn finish_input(
616        &self,
617        dialog: &Node,
618        role: DialogRole,
619        input: InputRoute<'_>,
620        bounds: impl FnOnce() -> DateBounds,
621    ) -> Option<Date> {
622        self.try_finish_input(dialog, role, input, || {
623            Ok::<_, std::convert::Infallible>(bounds())
624        })
625        .unwrap_or_else(|error| match error {})
626    }
627
628    pub fn finish(&self, bounds: DateBounds, dialog: &Node) -> Option<Date> {
629        self.finish_with_role(bounds, dialog, DialogRole::Accept)
630    }
631
632    pub fn finish_with_role(
633        &self,
634        bounds: DateBounds,
635        dialog: &Node,
636        role: DialogRole,
637    ) -> Option<Date> {
638        self.0
639            .finish(dialog, role)
640            .map(|(date, _)| bounds.constrain(date))
641    }
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    #[test]
649    fn gregorian_arithmetic_handles_leap_centuries_and_calendar_limits() {
650        let date = |year, month, day| Date::new(year, month, day).unwrap();
651        assert_eq!(date(1900, 2, 28).add_days(1), Some(date(1900, 3, 1)));
652        assert_eq!(date(2000, 2, 28).add_days(1), Some(date(2000, 2, 29)));
653        assert_eq!(date(2025, 1, 1).add_days(-1), Some(date(2024, 12, 31)));
654        assert_eq!(
655            date(1970, 1, 1).add_days(20_000).unwrap().add_days(-20_000),
656            Some(Date::default())
657        );
658        assert_eq!(Date::MIN.add_days(-1), None);
659        assert_eq!(Date::MAX.add_days(1), None);
660        assert_eq!(Date::MIN.add_days(i64::MAX), None);
661    }
662
663    #[test]
664    fn calendar_template_only_renders_cells_whose_inputs_changed() {
665        use std::cell::Cell;
666        let date = |day| Date::new(2026, 11, day).unwrap();
667        let evaluations = Cell::new(0);
668        let note = Property::default();
669        let cells = CalendarCells::default();
670        let mut grid = Node::new("MonthGrid", None);
671        grid.properties.insert("display-month", date(1).into());
672        grid.properties.insert("date", date(11).into());
673        let render = |grid: &Node| {
674            cells.render(grid, |day| {
675                evaluations.set(evaluations.get() + 1);
676                let mut cell = Node::new("Rectangle", None);
677                if day.date == date(12) {
678                    cell.properties
679                        .insert("accessible-description", note.get(String::new).into());
680                }
681                cell
682            })
683        };
684        assert_eq!(render(&grid).children.len(), 42);
685        assert_eq!(evaluations.get(), 42);
686        grid.properties.insert("date", date(12).into());
687        render(&grid);
688        assert_eq!(evaluations.get(), 44);
689        note.set_if_changed("Review".to_owned());
690        render(&grid);
691        assert_eq!(evaluations.get(), 45);
692    }
693
694    #[test]
695    fn iso_weeks_use_the_thursday_at_new_year() {
696        let week = |year, month, day| Date::new(year, month, day).unwrap().iso_week().unwrap();
697        assert_eq!(week(2018, 12, 31), (2019, 1));
698        assert_eq!(week(2021, 1, 1), (2020, 53));
699        assert_eq!(week(2021, 1, 3), (2020, 53));
700        assert_eq!(week(2021, 1, 4), (2021, 1));
701        assert_eq!(Date::MIN.iso_week(), Some((1, 1)));
702        assert_eq!(Date::MAX.iso_week(), Some((9999, 52)));
703    }
704
705    #[test]
706    fn date_bounds_disable_cells_and_week_start_changes_the_first_column() {
707        let mut node = Node::new("Calendar", None);
708        let date = |month, day| Date::new(2024, month, day).unwrap();
709        node.properties.insert("date", date(2, 29).into());
710        node.properties.insert("minimum-date", date(2, 20).into());
711        node.properties.insert("maximum-date", date(3, 5).into());
712        let calendar = CalendarState::from_node(&node);
713        assert_eq!(calendar.cells(1)[0], Some(date(1, 29)));
714        assert_eq!(calendar.cells(7)[0], Some(date(1, 28)));
715        assert!(calendar.cells(1).contains(&Some(date(2, 29))));
716        assert!(!calendar.allows(date(2, 19)));
717        assert!(calendar.allows(date(3, 5)));
718        assert_eq!(calendar.adjacent_month(-1), None);
719        assert_eq!(calendar.adjacent_month(1), Some(date(3, 1)));
720    }
721}