Skip to main content

vizia_core/views/
calendar.rs

1use jiff::ToSpan;
2use jiff::civil::{Date, Weekday};
3
4use crate::{
5    icons::{ICON_CHEVRON_LEFT, ICON_CHEVRON_RIGHT},
6    localization::FluentCivilDateTime,
7    prelude::*,
8};
9
10/// A control used to select a date.
11pub struct Calendar {
12    view_date: Signal<Date>,
13    focused_date: Signal<Date>,
14    week_starts_on: Signal<Weekday>,
15    keyboard_help: Signal<String>,
16    keyboard_help_announced: bool,
17    day_cells: Vec<Entity>,
18    on_select: Option<Box<dyn Fn(&mut EventContext, Date)>>,
19}
20
21const MONTHS: [&str; 12] =
22    ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
23
24pub enum CalendarEvent {
25    IncrementMonth,
26    DecrementMonth,
27    SelectMonth(usize),
28
29    IncrementYear,
30    DecrementYear,
31    SelectYear(i32),
32
33    MoveFocusDays(i64),
34    MoveFocusLeft,
35    MoveFocusRight,
36    MoveFocusWeeks(i64),
37    MoveFocusWeekStart,
38    MoveFocusWeekEnd,
39    MoveFocusMonth(i32),
40    MoveFocusYear(i32),
41    ActivateFocusedDate,
42    RegisterDayCell(usize, usize, Entity),
43    AnnounceKeyboardHelp,
44    RefreshLocalization,
45
46    SelectDate(Date),
47}
48
49impl Calendar {
50    fn weekday_from_monday_index(index: u32) -> Weekday {
51        Weekday::from_monday_zero_offset((index % 7) as i8).unwrap()
52    }
53
54    fn weekday_key(weekday: Weekday) -> &'static str {
55        match weekday {
56            Weekday::Monday => "Monday",
57            Weekday::Tuesday => "Tuesday",
58            Weekday::Wednesday => "Wednesday",
59            Weekday::Thursday => "Thursday",
60            Weekday::Friday => "Friday",
61            Weekday::Saturday => "Saturday",
62            Weekday::Sunday => "Sunday",
63        }
64    }
65
66    fn weekday_short_key(weekday: Weekday) -> &'static str {
67        match weekday {
68            Weekday::Monday => "Monday-short",
69            Weekday::Tuesday => "Tuesday-short",
70            Weekday::Wednesday => "Wednesday-short",
71            Weekday::Thursday => "Thursday-short",
72            Weekday::Friday => "Friday-short",
73            Weekday::Saturday => "Saturday-short",
74            Weekday::Sunday => "Sunday-short",
75        }
76    }
77
78    fn first_day_column(first_day: Weekday, week_starts_on: Weekday) -> u32 {
79        let first = i32::from(first_day.to_monday_zero_offset());
80        let start = i32::from(week_starts_on.to_monday_zero_offset());
81        ((7 + first - start) % 7) as u32
82    }
83
84    fn weekday_from_token(token: &str) -> Option<Weekday> {
85        match token.trim().to_ascii_lowercase().as_str() {
86            "monday" => Some(Weekday::Monday),
87            "tuesday" => Some(Weekday::Tuesday),
88            "wednesday" => Some(Weekday::Wednesday),
89            "thursday" => Some(Weekday::Thursday),
90            "friday" => Some(Weekday::Friday),
91            "saturday" => Some(Weekday::Saturday),
92            "sunday" => Some(Weekday::Sunday),
93            _ => None,
94        }
95    }
96
97    fn week_start_from_localization(cx: &impl DataContext) -> Weekday {
98        let val = Localized::new("calendar-week-start").to_string_local(cx);
99        Self::weekday_from_token(&val).unwrap_or(Weekday::Monday)
100    }
101
102    fn set_view_date(&mut self, date: Date) {
103        self.view_date.set(date);
104        self.focused_date.set(date);
105    }
106
107    /// Moves the focus by whole months, clamping the day to the length of the new month.
108    fn shift_month(&mut self, delta: i32) {
109        let date = self.focused_date.get().checked_add(delta.months()).unwrap();
110        self.set_view_date(date);
111    }
112
113    /// Moves the focus by whole years, clamping the day to the length of the new month.
114    fn shift_year(&mut self, delta: i32) {
115        let date = self.focused_date.get().checked_add(delta.years()).unwrap();
116        self.set_view_date(date);
117    }
118
119    // Given a date and a month offset, returns the first day of the month and the number of days in the month
120    fn view_month_info(view_date: &Date, month_offset: i32) -> (Weekday, u32) {
121        let month = view_date.first_of_month().checked_add(month_offset.months()).unwrap();
122
123        (month.weekday(), u32::try_from(month.days_in_month()).unwrap())
124    }
125
126    fn get_day_number(y: u32, x: u32, view_date: &Date, week_starts_on: Weekday) -> (u32, bool) {
127        let (_, days_prev_month) = Self::view_month_info(view_date, -1);
128        let (first_day_this_month, days_this_month) = Self::view_month_info(view_date, 0);
129
130        let fdtm_i = Self::first_day_column(first_day_this_month, week_starts_on);
131
132        if y == 0 {
133            if x < fdtm_i {
134                (days_prev_month - (fdtm_i - x - 1), true)
135            } else {
136                (x - fdtm_i + 1, false)
137            }
138        } else {
139            let day_number = y * 7 + x - fdtm_i + 1;
140            if day_number > days_this_month {
141                (day_number - days_this_month, true)
142            } else {
143                (day_number, false)
144            }
145        }
146    }
147
148    fn get_cell_date(y: u32, x: u32, view_date: &Date, week_starts_on: Weekday) -> (Date, bool) {
149        let (day_number, disabled) = Self::get_day_number(y, x, view_date, week_starts_on);
150
151        let month_offset = match (disabled, y) {
152            (false, _) => 0,
153            (true, 0) => -1,
154            (true, _) => 1,
155        };
156        let month = view_date.first_of_month().checked_add(month_offset.months()).unwrap();
157
158        (month.with().day(i8::try_from(day_number).unwrap()).build().unwrap(), disabled)
159    }
160
161    fn day_cell_index(y: usize, x: usize) -> usize {
162        y * 7 + x
163    }
164
165    fn focused_day_cell_index(&self) -> Option<usize> {
166        let focused_date = self.focused_date.get();
167        let view_date = self.view_date.get();
168
169        if focused_date.first_of_month() != view_date.first_of_month() {
170            return None;
171        }
172
173        let first_day = view_date.first_of_month().weekday();
174        let first_day_col = Self::first_day_column(first_day, self.week_starts_on.get()) as usize;
175        Some(first_day_col + focused_date.day() as usize - 1)
176    }
177
178    fn focus_focused_day(&self, cx: &mut EventContext) {
179        if let Some(index) = self.focused_day_cell_index()
180            && let Some(entity) = self.day_cells.get(index).copied()
181            && !entity.is_null()
182        {
183            cx.with_current(entity, |cx| cx.focus());
184        }
185    }
186
187    fn focus_focused_day_with_visibility(&self, cx: &mut EventContext, focus_visible: bool) {
188        if let Some(index) = self.focused_day_cell_index()
189            && let Some(entity) = self.day_cells.get(index).copied()
190            && !entity.is_null()
191        {
192            cx.with_current(entity, |cx| cx.focus_with_visibility(focus_visible));
193        }
194    }
195
196    fn move_focused_by_days(&mut self, delta_days: i64) {
197        let focused_date = self.focused_date.get();
198        let next_date = focused_date.checked_add(delta_days.days()).unwrap();
199        self.view_date.set(next_date);
200        self.focused_date.set(next_date);
201    }
202
203    fn move_focused_by_months(&mut self, delta_months: i32) {
204        self.shift_month(delta_months);
205    }
206
207    fn move_focused_by_years(&mut self, delta_years: i32) {
208        self.shift_year(delta_years);
209    }
210
211    /// The signed number of days from `date` to the first day of its week.
212    fn days_to_week_start(date: Date, week_starts_on: Weekday) -> i64 {
213        -((7 + i64::from(date.weekday().to_monday_zero_offset())
214            - i64::from(week_starts_on.to_monday_zero_offset()))
215            % 7)
216    }
217
218    /// The signed number of days from `date` to the last day of its week.
219    fn days_to_week_end(date: Date, week_starts_on: Weekday) -> i64 {
220        6 + Self::days_to_week_start(date, week_starts_on)
221    }
222
223    fn focus_is_on_calendar_day(&self, cx: &EventContext) -> bool {
224        let focused = cx.focused();
225        self.day_cells.iter().any(|cell| {
226            !cell.is_null() && (focused == *cell || focused.is_descendant_of(cx.tree, *cell))
227        })
228    }
229
230    /// Create a new [Calendar] view.
231    pub fn new<R, D>(cx: &mut Context, date: R) -> Handle<Self>
232    where
233        R: Res<D> + Clone + 'static,
234        D: Into<Date> + Clone + 'static,
235    {
236        let selected_date: Date = date.get_value(cx).into();
237        let selected_date_signal = date.to_signal(cx);
238        let view_date = Signal::new(selected_date.first_of_month());
239        let focused_date = Signal::new(selected_date);
240        let month_options =
241            Signal::new(MONTHS.iter().map(|m| Localized::new(m)).collect::<Vec<_>>());
242        let month_year_heading_date =
243            view_date.map(|date| FluentCivilDateTime(date.at(0, 0, 0, 0)));
244        let week_starts_on = Signal::new(Self::week_start_from_localization(cx));
245        let keyboard_help = Signal::new(String::new());
246        let selected_month = view_date.map(|date| Some(date.month() as usize - 1));
247        let year_start = i32::from(selected_date.year()) - 50;
248        let year_end = i32::from(selected_date.year()) + 50;
249        let year_options =
250            Signal::new((year_start..=year_end).map(|year| year.to_string()).collect::<Vec<_>>());
251        let selected_year = view_date.map(move |date| {
252            let index = i32::from(date.year()) - year_start;
253            if (0..=(year_end - year_start)).contains(&index) { Some(index as usize) } else { None }
254        });
255
256        Self {
257            view_date,
258            focused_date,
259            week_starts_on,
260            keyboard_help,
261            keyboard_help_announced: false,
262            day_cells: vec![Entity::null(); 42],
263            on_select: None,
264        }
265        .build(cx, move |cx| {
266            let calendar_entity = cx.current();
267            let locale = cx.environment().locale;
268            locale.set_or_bind(cx, move |cx, _| {
269                cx.emit_to(calendar_entity, CalendarEvent::RefreshLocalization);
270            });
271
272            Keymap::from(vec![
273                (
274                    KeyChord::new(Modifiers::empty(), Code::ArrowUp),
275                    KeymapEntry::new("Calendar Focus Previous Week", |cx| {
276                        cx.emit(CalendarEvent::MoveFocusWeeks(-1))
277                    }),
278                ),
279                (
280                    KeyChord::new(Modifiers::empty(), Code::ArrowDown),
281                    KeymapEntry::new("Calendar Focus Next Week", |cx| {
282                        cx.emit(CalendarEvent::MoveFocusWeeks(1))
283                    }),
284                ),
285                (
286                    KeyChord::new(Modifiers::empty(), Code::ArrowLeft),
287                    KeymapEntry::new("Calendar Focus Left Day", |cx| {
288                        cx.emit(CalendarEvent::MoveFocusLeft)
289                    }),
290                ),
291                (
292                    KeyChord::new(Modifiers::empty(), Code::ArrowRight),
293                    KeymapEntry::new("Calendar Focus Right Day", |cx| {
294                        cx.emit(CalendarEvent::MoveFocusRight)
295                    }),
296                ),
297                (
298                    KeyChord::new(Modifiers::empty(), Code::Home),
299                    KeymapEntry::new("Calendar Focus Week Start", |cx| {
300                        cx.emit(CalendarEvent::MoveFocusWeekStart)
301                    }),
302                ),
303                (
304                    KeyChord::new(Modifiers::empty(), Code::End),
305                    KeymapEntry::new("Calendar Focus Week End", |cx| {
306                        cx.emit(CalendarEvent::MoveFocusWeekEnd)
307                    }),
308                ),
309                (
310                    KeyChord::new(Modifiers::empty(), Code::PageUp),
311                    KeymapEntry::new("Calendar Previous Month", |cx| {
312                        cx.emit(CalendarEvent::MoveFocusMonth(-1))
313                    }),
314                ),
315                (
316                    KeyChord::new(Modifiers::empty(), Code::PageDown),
317                    KeymapEntry::new("Calendar Next Month", |cx| {
318                        cx.emit(CalendarEvent::MoveFocusMonth(1))
319                    }),
320                ),
321                (
322                    KeyChord::new(Modifiers::SHIFT, Code::PageUp),
323                    KeymapEntry::new("Calendar Previous Year", |cx| {
324                        cx.emit(CalendarEvent::MoveFocusYear(-1))
325                    }),
326                ),
327                (
328                    KeyChord::new(Modifiers::SHIFT, Code::PageDown),
329                    KeymapEntry::new("Calendar Next Year", |cx| {
330                        cx.emit(CalendarEvent::MoveFocusYear(1))
331                    }),
332                ),
333                (
334                    KeyChord::new(Modifiers::empty(), Code::Space),
335                    KeymapEntry::new("Calendar Activate Date", |cx| {
336                        cx.emit(CalendarEvent::ActivateFocusedDate)
337                    }),
338                ),
339                (
340                    KeyChord::new(Modifiers::empty(), Code::Enter),
341                    KeymapEntry::new("Calendar Activate Date", |cx| {
342                        cx.emit(CalendarEvent::ActivateFocusedDate)
343                    }),
344                ),
345            ])
346            .build(cx);
347
348            HStack::new(cx, move |cx| {
349                Button::new(cx, |cx| Svg::new(cx, ICON_CHEVRON_LEFT))
350                    .on_press(|ex| ex.emit(CalendarEvent::DecrementMonth))
351                    .variant(ButtonVariant::Text)
352                    .name(Localized::new("calendar-previous-month"))
353                    .class("month-nav");
354                HStack::new(cx, move |cx| {
355                    Select::new(cx, month_options, selected_month, true)
356                        .on_select(|ex, index| ex.emit(CalendarEvent::SelectMonth(index)));
357                    Select::new(cx, year_options, selected_year, true).on_select(
358                        move |ex, index| {
359                            ex.emit(CalendarEvent::SelectYear(year_start + index as i32));
360                        },
361                    );
362                })
363                .class("calendar-controls-select");
364
365                Button::new(cx, |cx| Svg::new(cx, ICON_CHEVRON_RIGHT))
366                    .on_press(|ex| ex.emit(CalendarEvent::IncrementMonth))
367                    .variant(ButtonVariant::Text)
368                    .name(Localized::new("calendar-next-month"))
369                    .class("month-nav");
370            })
371            .class("calendar-controls");
372
373            VStack::new(cx, move |cx| {
374                Label::new(
375                    cx,
376                    Localized::new("calendar-month-year-heading")
377                        .arg("date", month_year_heading_date),
378                )
379                .class("calendar-month-year-heading")
380                .role(Role::Label)
381                .display(Display::None)
382                .live(Live::Polite);
383
384                Label::new(cx, keyboard_help)
385                    .class("calendar-keyboard-help")
386                    .role(Role::Label)
387                    .display(Display::None)
388                    .live(Live::Polite);
389
390                // Days of the week
391                HStack::new(cx, |cx| {
392                    for x in 0..7 {
393                        let week_starts_on = cx.data::<Calendar>().week_starts_on;
394                        Label::new(cx, "")
395                            .bind(week_starts_on, move |handle| {
396                                let week_starts_on = week_starts_on.get();
397                                let weekday = Self::weekday_from_monday_index(
398                                    u32::from(
399                                        week_starts_on.to_monday_zero_offset().unsigned_abs(),
400                                    ) + x,
401                                );
402                                handle
403                                    .text(Localized::new(Self::weekday_short_key(weekday)))
404                                    .name(Localized::new(Self::weekday_key(weekday)));
405                            })
406                            .class("calendar-dow")
407                            .role(Role::ColumnHeader);
408                    }
409                })
410                .class("calendar-header")
411                .role(Role::Row);
412
413                // Numbered days in a grid
414                VStack::new(cx, move |cx| {
415                    for y in 0..6 {
416                        HStack::new(cx, |cx| {
417                            for x in 0..7 {
418                                let selected_date = selected_date_signal;
419                                let view_date = cx.data::<Calendar>().view_date;
420                                let focused_date = cx.data::<Calendar>().focused_date;
421                                let week_starts_on = cx.data::<Calendar>().week_starts_on;
422                                Label::new(cx, "").bind(view_date, move |handle| {
423                                    let view_date = view_date.get();
424                                    let selected_date = selected_date;
425                                    let focused_date = focused_date;
426                                    handle.bind(week_starts_on, move |handle| {
427                                        let week_starts_on = week_starts_on.get();
428                                        let (cell_date, disabled) =
429                                            Self::get_cell_date(y, x, &view_date, week_starts_on);
430                                        let day_number = cell_date.day();
431
432                                        handle.bind(selected_date, move |handle| {
433                                            let selected_date: Date = selected_date.get().into();
434                                            handle.bind(focused_date, move |handle| {
435                                                let focused_date = focused_date.get();
436                                                let is_focused = focused_date == cell_date;
437
438                                                handle
439                                                    .text(day_number.to_string())
440                                                    .class("calendar-day")
441                                                    .role(Role::GridCell)
442                                                    .name(
443                                                        Localized::new("calendar-day-cell-name")
444                                                            .arg(
445                                                                "date",
446                                                                FluentCivilDateTime(
447                                                                    cell_date.at(0, 0, 0, 0),
448                                                                ),
449                                                            ),
450                                                    )
451                                                    .disabled(disabled)
452                                                    .navigable(!disabled && is_focused)
453                                                    .toggle_class("calendar-day-disabled", disabled)
454                                                    .toggle_class(
455                                                        "calendar-day-focused",
456                                                        is_focused,
457                                                    )
458                                                    .on_build(move |cx| {
459                                                        cx.emit(CalendarEvent::RegisterDayCell(
460                                                            y as usize,
461                                                            x as usize,
462                                                            cx.current(),
463                                                        ));
464                                                    })
465                                                    .on_focus_in(|ex| {
466                                                        ex.emit(CalendarEvent::AnnounceKeyboardHelp)
467                                                    })
468                                                    .on_press(move |ex| {
469                                                        if !disabled {
470                                                            ex.emit(CalendarEvent::SelectDate(
471                                                                cell_date,
472                                                            ));
473                                                        }
474                                                    })
475                                                    .toggle_class(
476                                                        "calendar-day-selected",
477                                                        !disabled && selected_date == cell_date,
478                                                    )
479                                                    .selected(
480                                                        !disabled && selected_date == cell_date,
481                                                    );
482                                            });
483                                        });
484                                    });
485                                });
486                            }
487                        })
488                        .role(Role::Row);
489                    }
490                })
491                // This shouldn't be needed but apparently grid size isn't propagated up the tree during layout
492                .width(Pixels(32.0 * 7.0))
493                .height(Pixels(32.0 * 6.0));
494            })
495            .class("calendar-body")
496            .role(Role::Grid)
497            .name(
498                Localized::new("calendar-month-year-heading").arg("date", month_year_heading_date),
499            );
500        })
501    }
502}
503
504impl View for Calendar {
505    fn element(&self) -> Option<&'static str> {
506        Some("calendar")
507    }
508
509    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
510        event.map(|e, _| match e {
511            CalendarEvent::IncrementMonth => {
512                self.shift_month(1);
513            }
514
515            CalendarEvent::DecrementMonth => {
516                self.shift_month(-1);
517            }
518
519            CalendarEvent::SelectMonth(month) => {
520                let months = *month as i32 + 1 - i32::from(self.focused_date.get().month());
521                self.shift_month(months);
522            }
523
524            CalendarEvent::IncrementYear => {
525                self.shift_year(1);
526            }
527
528            CalendarEvent::DecrementYear => {
529                self.shift_year(-1);
530            }
531
532            CalendarEvent::SelectYear(year) => {
533                let years = *year - i32::from(self.focused_date.get().year());
534                self.shift_year(years);
535            }
536
537            CalendarEvent::MoveFocusDays(delta) => {
538                if self.focus_is_on_calendar_day(cx) {
539                    self.move_focused_by_days(*delta);
540                    self.focus_focused_day_with_visibility(cx, true);
541                }
542            }
543
544            CalendarEvent::MoveFocusLeft => {
545                if self.focus_is_on_calendar_day(cx) {
546                    let delta = if cx.environment().direction.get() == Direction::RightToLeft {
547                        1
548                    } else {
549                        -1
550                    };
551                    self.move_focused_by_days(delta);
552                    self.focus_focused_day_with_visibility(cx, true);
553                }
554            }
555
556            CalendarEvent::MoveFocusRight => {
557                if self.focus_is_on_calendar_day(cx) {
558                    let delta = if cx.environment().direction.get() == Direction::RightToLeft {
559                        -1
560                    } else {
561                        1
562                    };
563                    self.move_focused_by_days(delta);
564                    self.focus_focused_day_with_visibility(cx, true);
565                }
566            }
567
568            CalendarEvent::MoveFocusWeeks(delta) => {
569                if self.focus_is_on_calendar_day(cx) {
570                    self.move_focused_by_days(*delta * 7);
571                    self.focus_focused_day_with_visibility(cx, true);
572                }
573            }
574
575            CalendarEvent::MoveFocusWeekStart => {
576                if self.focus_is_on_calendar_day(cx) {
577                    let focused_date = self.focused_date.get();
578                    let offset = Self::days_to_week_start(focused_date, self.week_starts_on.get());
579                    self.move_focused_by_days(offset);
580                    self.focus_focused_day_with_visibility(cx, true);
581                }
582            }
583
584            CalendarEvent::MoveFocusWeekEnd => {
585                if self.focus_is_on_calendar_day(cx) {
586                    let focused_date = self.focused_date.get();
587                    let offset = Self::days_to_week_end(focused_date, self.week_starts_on.get());
588                    self.move_focused_by_days(offset);
589                    self.focus_focused_day_with_visibility(cx, true);
590                }
591            }
592
593            CalendarEvent::MoveFocusMonth(delta) => {
594                if self.focus_is_on_calendar_day(cx) {
595                    self.move_focused_by_months(*delta);
596                    self.focus_focused_day_with_visibility(cx, true);
597                }
598            }
599
600            CalendarEvent::MoveFocusYear(delta) => {
601                if self.focus_is_on_calendar_day(cx) {
602                    self.move_focused_by_years(*delta);
603                    self.focus_focused_day_with_visibility(cx, true);
604                }
605            }
606
607            CalendarEvent::ActivateFocusedDate => {
608                if self.focus_is_on_calendar_day(cx) {
609                    let focused_date = self.focused_date.get();
610                    if focused_date.month() == self.view_date.get().month()
611                        && focused_date.year() == self.view_date.get().year()
612                        && let Some(callback) = &self.on_select
613                    {
614                        (callback)(cx, focused_date);
615                    }
616                }
617            }
618
619            CalendarEvent::RegisterDayCell(y, x, entity) => {
620                let index = Self::day_cell_index(*y, *x);
621                if let Some(day_cell) = self.day_cells.get_mut(index) {
622                    *day_cell = *entity;
623                }
624            }
625
626            CalendarEvent::AnnounceKeyboardHelp => {
627                if !self.keyboard_help_announced {
628                    self.keyboard_help
629                        .set(Localized::new("calendar-keyboard-help").to_string_local(cx));
630                    self.keyboard_help_announced = true;
631                }
632            }
633
634            CalendarEvent::RefreshLocalization => {
635                self.week_starts_on.set(Self::week_start_from_localization(cx));
636                self.keyboard_help.set(String::new());
637                self.keyboard_help_announced = false;
638            }
639
640            CalendarEvent::SelectDate(date) => {
641                self.focused_date.set(*date);
642                self.view_date.set(*date);
643                self.focus_focused_day(cx);
644                if let Some(callback) = &self.on_select {
645                    (callback)(cx, *date);
646                }
647            }
648        });
649
650        event.map(|window_event, meta| match window_event {
651            WindowEvent::KeyDown(code, _)
652                if self.focus_is_on_calendar_day(cx)
653                    && matches!(
654                        code,
655                        Code::ArrowUp
656                            | Code::ArrowDown
657                            | Code::ArrowLeft
658                            | Code::ArrowRight
659                            | Code::Home
660                            | Code::End
661                            | Code::PageUp
662                            | Code::PageDown
663                            | Code::Space
664                            | Code::Enter
665                    ) =>
666            {
667                meta.consume();
668            }
669
670            _ => {}
671        });
672    }
673}
674
675impl Handle<'_, Calendar> {
676    /// Set the callback triggered when a date is selected from the [Calendar] view.
677    pub fn on_select<F: 'static + Fn(&mut EventContext, Date)>(self, callback: F) -> Self {
678        self.modify(|calendar: &mut Calendar| calendar.on_select = Some(Box::new(callback)))
679    }
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685
686    fn date(year: i16, month: i8, day: i8) -> Date {
687        Date::new(year, month, day).unwrap()
688    }
689
690    fn calendar(focused: Date, week_starts_on: Weekday) -> Calendar {
691        Calendar {
692            view_date: Signal::new(focused.first_of_month()),
693            focused_date: Signal::new(focused),
694            week_starts_on: Signal::new(week_starts_on),
695            keyboard_help: Signal::new(String::new()),
696            keyboard_help_announced: false,
697            day_cells: vec![Entity::null(); 42],
698            on_select: None,
699        }
700    }
701
702    #[test]
703    fn month_length_handles_leap_years_and_december() {
704        let days = |year, month| Calendar::view_month_info(&date(year, month, 1), 0).1;
705
706        assert_eq!(days(2024, 2), 29);
707        assert_eq!(days(2023, 2), 28);
708        assert_eq!(days(1900, 2), 28);
709        assert_eq!(days(2000, 2), 29);
710        assert_eq!(days(2023, 12), 31);
711        assert_eq!(days(2023, 4), 30);
712    }
713
714    #[test]
715    fn first_day_of_month_is_the_weekday_of_the_first() {
716        let first_day = |year, month| Calendar::view_month_info(&date(year, month, 1), 0).0;
717
718        assert_eq!(first_day(2024, 2), Weekday::Thursday);
719        assert_eq!(first_day(2023, 12), Weekday::Friday);
720        assert_eq!(first_day(2023, 10), Weekday::Sunday);
721        assert_eq!(Calendar::view_month_info(&date(2024, 2, 17), 0), (Weekday::Thursday, 29));
722    }
723
724    #[test]
725    fn first_day_column_counts_from_the_week_start() {
726        assert_eq!(Calendar::first_day_column(Weekday::Thursday, Weekday::Monday), 3);
727        assert_eq!(Calendar::first_day_column(Weekday::Thursday, Weekday::Sunday), 4);
728        assert_eq!(Calendar::first_day_column(Weekday::Sunday, Weekday::Monday), 6);
729        assert_eq!(Calendar::first_day_column(Weekday::Monday, Weekday::Saturday), 2);
730        assert_eq!(Calendar::first_day_column(Weekday::Wednesday, Weekday::Wednesday), 0);
731    }
732
733    #[test]
734    fn view_month_info_wraps_across_years() {
735        assert_eq!(Calendar::view_month_info(&date(2024, 1, 1), -1), (Weekday::Friday, 31));
736        assert_eq!(Calendar::view_month_info(&date(2023, 12, 1), 1), (Weekday::Monday, 31));
737        assert_eq!(Calendar::view_month_info(&date(2024, 3, 1), -1), (Weekday::Thursday, 29));
738    }
739
740    #[test]
741    fn cell_dates_for_a_leap_february_with_a_monday_start() {
742        let view = date(2024, 2, 1);
743        let cell = |y, x| Calendar::get_cell_date(y, x, &view, Weekday::Monday);
744
745        assert_eq!(cell(0, 0), (date(2024, 1, 29), true));
746        assert_eq!(cell(0, 2), (date(2024, 1, 31), true));
747        assert_eq!(cell(0, 3), (date(2024, 2, 1), false));
748        assert_eq!(cell(4, 3), (date(2024, 2, 29), false));
749        assert_eq!(cell(4, 4), (date(2024, 3, 1), true));
750        assert_eq!(cell(5, 6), (date(2024, 3, 10), true));
751    }
752
753    #[test]
754    fn cell_dates_for_a_leap_february_with_a_sunday_start() {
755        let view = date(2024, 2, 1);
756        let cell = |y, x| Calendar::get_cell_date(y, x, &view, Weekday::Sunday);
757
758        assert_eq!(cell(0, 0), (date(2024, 1, 28), true));
759        assert_eq!(cell(0, 4), (date(2024, 2, 1), false));
760        assert_eq!(cell(4, 4), (date(2024, 2, 29), false));
761        assert_eq!(cell(4, 5), (date(2024, 3, 1), true));
762    }
763
764    #[test]
765    fn cell_dates_roll_over_year_boundaries() {
766        let december = date(2023, 12, 1);
767        assert_eq!(
768            Calendar::get_cell_date(5, 6, &december, Weekday::Monday),
769            (date(2024, 1, 7), true)
770        );
771
772        let january = date(2025, 1, 1);
773        assert_eq!(
774            Calendar::get_cell_date(0, 0, &january, Weekday::Monday),
775            (date(2024, 12, 30), true)
776        );
777        assert_eq!(
778            Calendar::get_cell_date(0, 2, &january, Weekday::Monday),
779            (date(2025, 1, 1), false)
780        );
781    }
782
783    #[test]
784    fn shifting_the_month_clamps_the_day_and_wraps_the_year() {
785        let mut calendar = calendar(date(2024, 1, 31), Weekday::Monday);
786
787        calendar.shift_month(1);
788        assert_eq!(calendar.view_date.get(), date(2024, 2, 29));
789        assert_eq!(calendar.focused_date.get(), date(2024, 2, 29));
790
791        calendar.shift_month(-2);
792        assert_eq!(calendar.focused_date.get(), date(2023, 12, 29));
793
794        calendar.shift_month(1);
795        calendar.shift_month(1);
796        assert_eq!(calendar.focused_date.get(), date(2024, 2, 29));
797    }
798
799    #[test]
800    fn shifting_the_year_clamps_leap_days() {
801        let mut calendar = calendar(date(2024, 2, 29), Weekday::Monday);
802
803        calendar.shift_year(1);
804        assert_eq!(calendar.focused_date.get(), date(2025, 2, 28));
805
806        calendar.shift_year(-1);
807        assert_eq!(calendar.focused_date.get(), date(2024, 2, 28));
808    }
809
810    #[test]
811    fn moving_the_focus_by_days_crosses_month_and_year_boundaries() {
812        let mut calendar = calendar(date(2023, 12, 31), Weekday::Monday);
813
814        calendar.move_focused_by_days(1);
815        assert_eq!(calendar.focused_date.get(), date(2024, 1, 1));
816        assert_eq!(calendar.view_date.get(), date(2024, 1, 1));
817
818        calendar.move_focused_by_days(-1);
819        assert_eq!(calendar.focused_date.get(), date(2023, 12, 31));
820
821        calendar.move_focused_by_days(60);
822        assert_eq!(calendar.focused_date.get(), date(2024, 2, 29));
823
824        calendar.move_focused_by_days(-366);
825        assert_eq!(calendar.focused_date.get(), date(2023, 2, 28));
826    }
827
828    #[test]
829    fn moving_the_focus_by_months_and_years_clamps_the_day() {
830        let mut calendar = calendar(date(2024, 3, 31), Weekday::Monday);
831
832        calendar.move_focused_by_months(-1);
833        assert_eq!(calendar.focused_date.get(), date(2024, 2, 29));
834
835        calendar.move_focused_by_years(-1);
836        assert_eq!(calendar.focused_date.get(), date(2023, 2, 28));
837    }
838
839    #[test]
840    fn the_focused_day_cell_follows_the_week_start() {
841        let calendar = calendar(date(2024, 2, 14), Weekday::Monday);
842        assert_eq!(calendar.focused_day_cell_index(), Some(3 + 13));
843
844        calendar.week_starts_on.set(Weekday::Sunday);
845        assert_eq!(calendar.focused_day_cell_index(), Some(4 + 13));
846
847        calendar.view_date.set(date(2024, 3, 1));
848        assert_eq!(calendar.focused_day_cell_index(), None);
849    }
850
851    #[test]
852    fn week_start_and_end_moves_follow_the_week_start() {
853        let weekdays = [
854            Weekday::Monday,
855            Weekday::Tuesday,
856            Weekday::Wednesday,
857            Weekday::Thursday,
858            Weekday::Friday,
859            Weekday::Saturday,
860            Weekday::Sunday,
861        ];
862
863        // 2024-02-12 is a Monday, so the seven dates cover every weekday.
864        for day in 12..=18 {
865            let focused = date(2024, 2, day);
866
867            for week_starts_on in weekdays {
868                // Walk back to the first day of the week, then forward to the day before the next one.
869                let mut start = focused;
870                while start.weekday() != week_starts_on {
871                    start = start.checked_add((-1).days()).unwrap();
872                }
873                let mut end = focused;
874                while end.checked_add(1.day()).unwrap().weekday() != week_starts_on {
875                    end = end.checked_add(1.day()).unwrap();
876                }
877
878                let mut moved = calendar(focused, week_starts_on);
879                moved.move_focused_by_days(Calendar::days_to_week_start(focused, week_starts_on));
880                assert_eq!(
881                    moved.focused_date.get(),
882                    start,
883                    "{focused} starting {week_starts_on:?}"
884                );
885
886                let mut moved = calendar(focused, week_starts_on);
887                moved.move_focused_by_days(Calendar::days_to_week_end(focused, week_starts_on));
888                assert_eq!(moved.focused_date.get(), end, "{focused} starting {week_starts_on:?}");
889            }
890        }
891    }
892
893    #[test]
894    fn week_start_tokens_match_weekday_names_case_insensitively() {
895        assert_eq!(Calendar::weekday_from_token(" Sunday "), Some(Weekday::Sunday));
896        assert_eq!(Calendar::weekday_from_token("monday"), Some(Weekday::Monday));
897        assert_eq!(Calendar::weekday_from_token("someday"), None);
898        assert_eq!(Calendar::weekday_from_monday_index(8), Weekday::Tuesday);
899    }
900}