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