Skip to main content

xrack_runtime/
calendar.rs

1use crate::{
2    ControlAction, 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    /// ISO 8601 week-based year and week number.
125    pub fn iso_week(self) -> Option<(i64, i64)> {
126        if !self.valid() {
127            return None;
128        }
129        let ordinal = self.ordinal();
130        let thursday = ordinal + 3 - ordinal.rem_euclid(7);
131        let year = if thursday < Self::days_before_year(self.year) {
132            self.year - 1
133        } else if thursday >= Self::days_before_year(self.year + 1) {
134            self.year + 1
135        } else {
136            self.year
137        };
138        Some((year, (thursday - Self::days_before_year(year)) / 7 + 1))
139    }
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub enum CalendarAction {
144    Select(Date),
145    Browse(Date),
146    Activate(Date),
147}
148
149pub fn is_calendar_control(kind: &str) -> bool {
150    matches!(kind, "Calendar" | "MonthGrid")
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct CalendarState {
155    pub minimum: Date,
156    pub maximum: Date,
157    pub selected: Date,
158    /// First day of the displayed month.
159    pub month: Date,
160}
161
162#[doc(hidden)]
163#[derive(Clone, Copy)]
164pub struct DateBounds {
165    minimum: Date,
166    maximum: Date,
167}
168
169impl DateBounds {
170    pub fn new(minimum: Date, maximum: Date) -> Self {
171        let minimum = if minimum.valid() { minimum } else { Date::MIN };
172        let maximum = if maximum.valid() { maximum } else { Date::MAX };
173        Self {
174            minimum,
175            maximum: maximum.max(minimum),
176        }
177    }
178
179    fn from_node(node: &Node) -> Self {
180        Self::new(
181            node.date("minimum-date").unwrap_or(Date::MIN),
182            node.date("maximum-date").unwrap_or(Date::MAX),
183        )
184    }
185
186    fn constrain(self, date: Date) -> Date {
187        let date = if date.valid() { date } else { Date::default() };
188        date.clamp(self.minimum, self.maximum)
189    }
190}
191
192impl CalendarState {
193    pub fn from_node(node: &Node) -> Self {
194        let date = node.date("date").unwrap_or_default();
195        let month = node.date("display-month");
196        let bounds = DateBounds::from_node(node);
197        if matches!(node.kind, "MonthGrid" | "WeekNumberColumn") {
198            Self::for_month_grid(date, month.unwrap_or(date), bounds)
199        } else {
200            Self::with_bounds(date, month, bounds)
201        }
202    }
203
204    #[doc(hidden)]
205    pub fn for_month_grid(date: Date, month: Date, bounds: DateBounds) -> Self {
206        let month = if month.valid() {
207            month
208        } else {
209            Date::default()
210        };
211        Self {
212            minimum: bounds.minimum,
213            maximum: bounds.maximum,
214            selected: bounds.constrain(date),
215            month: month.first_of_month(),
216        }
217    }
218
219    fn with_bounds(date: Date, month: Option<Date>, bounds: DateBounds) -> Self {
220        let selected = bounds.constrain(date);
221        let month = bounds
222            .constrain(month.filter(|date| date.valid()).unwrap_or(selected))
223            .first_of_month();
224        Self {
225            minimum: bounds.minimum,
226            maximum: bounds.maximum,
227            selected,
228            month,
229        }
230    }
231
232    pub fn allows(self, date: Date) -> bool {
233        date.valid() && (self.minimum..=self.maximum).contains(&date)
234    }
235
236    pub fn allows_month(self, month: Date) -> bool {
237        month.valid()
238            && month.day == 1
239            && month <= self.maximum
240            && month.last_of_month() >= self.minimum
241    }
242
243    pub fn adjacent_month(self, months: i64) -> Option<Date> {
244        self.month
245            .add_months(months)
246            .filter(|&date| self.allows_month(date))
247    }
248
249    pub fn cursor(self) -> Date {
250        if self.selected.first_of_month() == self.month {
251            self.selected
252        } else {
253            self.month.max(self.minimum)
254        }
255    }
256
257    /// Six complete weeks starting on Monday (1) through Sunday (7).
258    pub fn cells(self, week_start: i64) -> [Option<Date>; 42] {
259        if !self.month.valid() {
260            return [None; 42];
261        }
262        let offset = self.grid_offset(week_start);
263        std::array::from_fn(|index| self.month.add_days(index as i64 - offset))
264    }
265
266    pub fn shows(self, date: Date, week_start: i64) -> bool {
267        date.valid()
268            && self.month.valid()
269            && (0..42)
270                .contains(&(date.ordinal() - self.month.ordinal() + self.grid_offset(week_start)))
271    }
272
273    fn grid_offset(self, week_start: i64) -> i64 {
274        (self.month.ordinal() - (week_start.clamp(1, 7) - 1)).rem_euclid(7)
275    }
276}
277
278/// Inputs to a visual template for one date in a MonthGrid.
279#[doc(hidden)]
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
281pub struct CalendarCell {
282    pub date: Date,
283    pub index: i64,
284    pub weekday: i64,
285    pub week: i64,
286    pub week_year: i64,
287    pub selected: bool,
288    pub today: bool,
289    pub in_month: bool,
290    pub enabled: bool,
291}
292
293#[derive(Default)]
294struct CachedCalendarCell {
295    input: Property<CalendarCell>,
296    scene: Property<Node>,
297}
298
299/// Cache the visual bindings of each displayed date independently.
300#[doc(hidden)]
301#[derive(Default)]
302pub struct CalendarCells(RefCell<BTreeMap<Date, CachedCalendarCell>>);
303
304impl CalendarCells {
305    pub fn render(&self, grid: &Node, render_cell: impl Fn(CalendarCell) -> Node) -> Node {
306        let state = CalendarState::from_node(grid);
307        let start = grid.int("week-start").unwrap_or(1).clamp(1, 7);
308        let today = grid.date("today");
309        let dates = state.cells(start);
310        let mut cache = self.0.borrow_mut();
311        cache.retain(|date, _| dates.contains(&Some(*date)));
312        let mut cells = Node::new("CalendarCells", None);
313        cells.children = dates
314            .into_iter()
315            .enumerate()
316            .map(|(index, date)| {
317                let Some(date) = date else {
318                    return Node::hidden();
319                };
320                let (week_year, week) =
321                    date.iso_week().expect("calendar cells contain valid dates");
322                let input = CalendarCell {
323                    date,
324                    index: index as i64,
325                    weekday: (start - 1 + index as i64) % 7 + 1,
326                    week,
327                    week_year,
328                    selected: date == state.selected,
329                    today: Some(date) == today,
330                    in_month: date.first_of_month() == state.month,
331                    enabled: state.allows(date),
332                };
333                let cached = cache.entry(date).or_default();
334                cached.input.set_if_changed(input);
335                cached.scene.get(|| render_cell(cached.input.get(|| input)))
336            })
337            .collect();
338        cells
339    }
340}
341
342/// Draft date and browsed month share one session without changing the committed date.
343#[doc(hidden)]
344#[derive(Default)]
345pub struct DatePopupState(PickerSession<(Date, Date)>);
346
347impl DatePopupState {
348    pub fn close(&self) {
349        self.0.close();
350    }
351
352    pub fn populate(&self, dialog: &mut Node, date: impl FnOnce() -> Date) {
353        let bounds = DateBounds::from_node(dialog);
354        let Some((date, month)) = self.0.begin(dialog, || {
355            let date = bounds.constrain(date());
356            (date, date.first_of_month())
357        }) else {
358            return;
359        };
360        let state = CalendarState::with_bounds(date, Some(month), bounds);
361        let mut calendar = Node::new("Calendar", None);
362        for key in [
363            "week-start",
364            "weekday-labels",
365            "font",
366            "font-size",
367            "font-family",
368            "font-weight",
369            "font-italic",
370        ] {
371            if let Some(value) = dialog.properties.get(key) {
372                calendar.properties.insert(key, value.clone());
373            }
374        }
375        calendar.properties.insert("date", state.selected.into());
376        calendar
377            .properties
378            .insert("display-month", state.month.into());
379        calendar
380            .properties
381            .insert("minimum-date", state.minimum.into());
382        calendar
383            .properties
384            .insert("maximum-date", state.maximum.into());
385        self.0.stamp(&mut calendar);
386        append_picker_dialog(dialog, calendar);
387    }
388
389    pub fn edit(&self, bounds: DateBounds, node: &Node, action: ControlAction) -> bool {
390        let (Some((date, month)), ControlAction::Calendar(action)) = (self.0.current(node), action)
391        else {
392            return false;
393        };
394        let state = CalendarState::with_bounds(date, Some(month), bounds);
395        if node.kind != "Calendar" || CalendarState::from_node(node) != state {
396            return false;
397        }
398        let next = match action {
399            CalendarAction::Select(date) if state.allows(date) => (date, date.first_of_month()),
400            CalendarAction::Browse(month) if state.allows_month(month) => (state.selected, month),
401            _ => return false,
402        };
403        if next == (state.selected, state.month) {
404            return false;
405        }
406        self.0.set(next);
407        true
408    }
409
410    pub fn finish(&self, bounds: DateBounds, dialog: &Node) -> Option<Date> {
411        self.0
412            .finish(dialog)
413            .map(|(date, _)| bounds.constrain(date))
414    }
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    #[test]
422    fn gregorian_arithmetic_handles_leap_centuries_and_calendar_limits() {
423        let date = |year, month, day| Date::new(year, month, day).unwrap();
424        assert_eq!(date(1900, 2, 28).add_days(1), Some(date(1900, 3, 1)));
425        assert_eq!(date(2000, 2, 28).add_days(1), Some(date(2000, 2, 29)));
426        assert_eq!(date(2025, 1, 1).add_days(-1), Some(date(2024, 12, 31)));
427        assert_eq!(
428            date(1970, 1, 1).add_days(20_000).unwrap().add_days(-20_000),
429            Some(Date::default())
430        );
431        assert_eq!(Date::MIN.add_days(-1), None);
432        assert_eq!(Date::MAX.add_days(1), None);
433        assert_eq!(Date::MIN.add_days(i64::MAX), None);
434    }
435
436    #[test]
437    fn calendar_template_only_renders_cells_whose_inputs_changed() {
438        use std::cell::Cell;
439        let date = |day| Date::new(2026, 11, day).unwrap();
440        let evaluations = Cell::new(0);
441        let note = Property::default();
442        let cells = CalendarCells::default();
443        let mut grid = Node::new("MonthGrid", None);
444        grid.properties.insert("display-month", date(1).into());
445        grid.properties.insert("date", date(11).into());
446        let render = |grid: &Node| {
447            cells.render(grid, |day| {
448                evaluations.set(evaluations.get() + 1);
449                let mut cell = Node::new("Rectangle", None);
450                if day.date == date(12) {
451                    cell.properties
452                        .insert("accessible-description", note.get(String::new).into());
453                }
454                cell
455            })
456        };
457        assert_eq!(render(&grid).children.len(), 42);
458        assert_eq!(evaluations.get(), 42);
459        grid.properties.insert("date", date(12).into());
460        render(&grid);
461        assert_eq!(evaluations.get(), 44);
462        note.set_if_changed("Review".to_owned());
463        render(&grid);
464        assert_eq!(evaluations.get(), 45);
465    }
466
467    #[test]
468    fn iso_weeks_use_the_thursday_at_new_year() {
469        let week = |year, month, day| Date::new(year, month, day).unwrap().iso_week().unwrap();
470        assert_eq!(week(2018, 12, 31), (2019, 1));
471        assert_eq!(week(2021, 1, 1), (2020, 53));
472        assert_eq!(week(2021, 1, 3), (2020, 53));
473        assert_eq!(week(2021, 1, 4), (2021, 1));
474        assert_eq!(Date::MIN.iso_week(), Some((1, 1)));
475        assert_eq!(Date::MAX.iso_week(), Some((9999, 52)));
476    }
477
478    #[test]
479    fn date_bounds_disable_cells_and_week_start_changes_the_first_column() {
480        let mut node = Node::new("Calendar", None);
481        let date = |month, day| Date::new(2024, month, day).unwrap();
482        node.properties.insert("date", date(2, 29).into());
483        node.properties.insert("minimum-date", date(2, 20).into());
484        node.properties.insert("maximum-date", date(3, 5).into());
485        let calendar = CalendarState::from_node(&node);
486        assert_eq!(calendar.cells(1)[0], Some(date(1, 29)));
487        assert_eq!(calendar.cells(7)[0], Some(date(1, 28)));
488        assert!(calendar.cells(1).contains(&Some(date(2, 29))));
489        assert!(!calendar.allows(date(2, 19)));
490        assert!(calendar.allows(date(3, 5)));
491        assert_eq!(calendar.adjacent_month(-1), None);
492        assert_eq!(calendar.adjacent_month(1), Some(date(3, 1)));
493    }
494}