Skip to main content

gpui_base/
calendar.rs

1use crate::TestSupportExt as _;
2use std::rc::Rc;
3
4use crate::{LogicalStyledExt as _, h_flex, styled::StyledExt as _, v_flex};
5use gpui::{
6    AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle,
7    InteractiveElement, IntoElement, ParentElement, Render, RenderOnce, SharedString,
8    StatefulInteractiveElement, StyleRefinement, Styled, Window, div, px,
9};
10use jiff::civil::{self, Weekday};
11
12/// A controlled calendar value.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Date {
15    Single(Option<civil::Date>),
16    Range(Option<civil::Date>, Option<civil::Date>),
17}
18
19impl std::fmt::Display for Date {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        match self {
22            Self::Single(Some(date)) => write!(f, "{date}"),
23            Self::Single(None) | Self::Range(None, None) => write!(f, "nil"),
24            Self::Range(Some(start), Some(end)) => write!(f, "{start} - {end}"),
25            Self::Range(Some(start), None) => write!(f, "{start} - nil"),
26            Self::Range(None, Some(end)) => write!(f, "nil - {end}"),
27        }
28    }
29}
30
31impl From<civil::Date> for Date {
32    fn from(value: civil::Date) -> Self {
33        Self::Single(Some(value))
34    }
35}
36impl From<(civil::Date, civil::Date)> for Date {
37    fn from((start, end): (civil::Date, civil::Date)) -> Self {
38        Self::Range(Some(start), Some(end))
39    }
40}
41
42impl Date {
43    pub fn is_some(&self) -> bool {
44        matches!(self, Self::Single(Some(_)) | Self::Range(Some(_), _))
45    }
46    pub fn is_complete(&self) -> bool {
47        matches!(self, Self::Single(Some(_)) | Self::Range(Some(_), Some(_)))
48    }
49    pub fn start(&self) -> Option<civil::Date> {
50        match self {
51            Self::Single(Some(v)) | Self::Range(Some(v), _) => Some(*v),
52            _ => None,
53        }
54    }
55    pub fn end(&self) -> Option<civil::Date> {
56        match self {
57            Self::Range(_, Some(v)) => Some(*v),
58            _ => None,
59        }
60    }
61    pub fn format(&self, format: &str) -> Option<SharedString> {
62        match self {
63            Self::Single(Some(v)) => Some(v.strftime(format).to_string().into()),
64            Self::Range(Some(a), Some(b)) => {
65                Some(format!("{} - {}", a.strftime(format), b.strftime(format)).into())
66            }
67            _ => None,
68        }
69    }
70    pub fn is_active(&self, value: &civil::Date) -> bool {
71        match self {
72            Self::Single(v) => *v == Some(*value),
73            Self::Range(a, b) => *a == Some(*value) || *b == Some(*value),
74        }
75    }
76    pub fn is_single(&self) -> bool {
77        matches!(self, Self::Single(_))
78    }
79    pub fn is_in_range(&self, value: &civil::Date) -> bool {
80        matches!(self, Self::Range(Some(a), Some(b)) if value >= a && value <= b)
81    }
82}
83
84pub struct IntervalMatcher {
85    before: Option<civil::Date>,
86    after: Option<civil::Date>,
87}
88pub struct RangeMatcher {
89    from: Option<civil::Date>,
90    to: Option<civil::Date>,
91}
92pub enum Matcher {
93    DayOfWeek(Vec<u32>),
94    Interval(IntervalMatcher),
95    Range(RangeMatcher),
96    Custom(Box<dyn Fn(&civil::Date) -> bool + Send + Sync>),
97}
98impl From<Vec<u32>> for Matcher {
99    fn from(v: Vec<u32>) -> Self {
100        Self::DayOfWeek(v)
101    }
102}
103impl<F: Fn(&civil::Date) -> bool + Send + Sync + 'static> From<F> for Matcher {
104    fn from(v: F) -> Self {
105        Self::Custom(Box::new(v))
106    }
107}
108impl Matcher {
109    pub fn interval(before: Option<civil::Date>, after: Option<civil::Date>) -> Self {
110        Self::Interval(IntervalMatcher { before, after })
111    }
112    pub fn range(from: Option<civil::Date>, to: Option<civil::Date>) -> Self {
113        Self::Range(RangeMatcher { from, to })
114    }
115    pub fn custom<F: Fn(&civil::Date) -> bool + Send + Sync + 'static>(f: F) -> Self {
116        Self::Custom(Box::new(f))
117    }
118    pub fn is_match(&self, date: &Date) -> bool {
119        match date {
120            Date::Single(Some(v)) => self.matched(v),
121            Date::Range(Some(a), Some(b)) => self.matched(a) || self.matched(b),
122            _ => false,
123        }
124    }
125    pub fn matched(&self, date: &civil::Date) -> bool {
126        match self {
127            Self::DayOfWeek(days) => {
128                days.contains(&(date.weekday().to_sunday_zero_offset() as u32))
129            }
130            Self::Interval(v) => {
131                v.before.is_some_and(|x| date < &x) || v.after.is_some_and(|x| date > &x)
132            }
133            Self::Range(v) => {
134                !v.from.is_some_and(|x| date < &x) && !v.to.is_some_and(|x| date > &x)
135            }
136            Self::Custom(f) => f(date),
137        }
138    }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum CalendarView {
143    Day,
144    Month,
145    Year,
146}
147impl CalendarView {
148    pub fn is_day(self) -> bool {
149        self == Self::Day
150    }
151    pub fn is_month(self) -> bool {
152        self == Self::Month
153    }
154    pub fn is_year(self) -> bool {
155        self == Self::Year
156    }
157}
158
159fn picker_grid_layout(view: CalendarView) -> Option<(u16, f32)> {
160    match view {
161        CalendarView::Day => None,
162        CalendarView::Month => Some((3, 4.)),
163        CalendarView::Year => Some((5, 4.)),
164    }
165}
166
167pub enum CalendarEvent {
168    Selected(Date),
169}
170
171pub struct CalendarState {
172    pub focus_handle: FocusHandle,
173    view: CalendarView,
174    date: Date,
175    current_year: i32,
176    current_month: u8,
177    years: Vec<Vec<i32>>,
178    year_page: i32,
179    number_of_months: usize,
180    disabled_matcher: Option<Rc<Matcher>>,
181    /// Day the keyboard cursor sits on (single tab stop, ARIA grid style).
182    focused_day: Option<civil::Date>,
183}
184
185impl CalendarState {
186    pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
187        let today = jiff::ZonedDateTime::now().date();
188        Self {
189            focus_handle: cx.focus_handle(),
190            view: CalendarView::Day,
191            date: Date::Single(None),
192            current_year: today.year().into(),
193            current_month: today.month() as u8,
194            years: vec![],
195            year_page: 0,
196            number_of_months: 1,
197            disabled_matcher: None,
198            focused_day: None,
199        }
200        .year_range((i32::from(today.year()) - 50, i32::from(today.year()) + 50))
201    }
202    pub fn disabled_matcher(mut self, matcher: impl Into<Matcher>) -> Self {
203        self.disabled_matcher = Some(Rc::new(matcher.into()));
204        self
205    }
206    pub fn set_disabled_matcher(
207        &mut self,
208        matcher: impl Into<Matcher>,
209        _: &mut Window,
210        _: &mut Context<Self>,
211    ) {
212        self.disabled_matcher = Some(Rc::new(matcher.into()));
213    }
214    pub fn set_disabled_matcher_shared(&mut self, matcher: Option<Rc<Matcher>>) {
215        self.disabled_matcher = matcher;
216    }
217    pub fn disabled_matcher_ref(&self) -> Option<&Matcher> {
218        self.disabled_matcher.as_deref()
219    }
220    pub fn set_date(&mut self, date: impl Into<Date>, _: &mut Window, cx: &mut Context<Self>) {
221        if self.apply_date(date.into()) {
222            cx.notify();
223        }
224    }
225    pub fn apply_date(&mut self, date: Date) -> bool {
226        if self
227            .disabled_matcher
228            .as_ref()
229            .is_some_and(|m| m.is_match(&date))
230        {
231            return false;
232        }
233        self.date = date;
234        if let Some(v) = date.start() {
235            self.current_month = v.month() as u8;
236            self.current_year = v.year().into();
237        }
238        true
239    }
240    pub fn select_date(&mut self, value: civil::Date) -> bool {
241        if self
242            .disabled_matcher
243            .as_ref()
244            .is_some_and(|m| m.matched(&value))
245        {
246            return false;
247        }
248        let next = match self.date {
249            Date::Single(_) => Date::Single(Some(value)),
250            Date::Range(None, None) | Date::Range(None, Some(_)) => Date::Range(Some(value), None),
251            Date::Range(Some(start), None) if value >= start => {
252                Date::Range(Some(start), Some(value))
253            }
254            Date::Range(Some(_), None) | Date::Range(Some(_), Some(_)) => {
255                Date::Range(Some(value), None)
256            }
257        };
258        self.apply_date(next);
259        self.date.is_complete()
260    }
261    /// Activates a day item and emits [`CalendarEvent::Selected`] once the
262    /// controlled value is complete. This is the single pointer/keyboard
263    /// activation path used by the calendar root.
264    pub fn activate_date(&mut self, value: civil::Date, cx: &mut Context<Self>) -> bool {
265        let complete = self.select_date(value);
266        if complete {
267            cx.emit(CalendarEvent::Selected(self.date()));
268        }
269        cx.notify();
270        complete
271    }
272    pub fn date(&self) -> Date {
273        self.date
274    }
275    pub fn set_number_of_months(&mut self, n: usize, _: &mut Window, cx: &mut Context<Self>) {
276        self.number_of_months = n;
277        cx.notify();
278    }
279    pub fn number_of_months(&self) -> usize {
280        self.number_of_months
281    }
282    pub fn year_range(mut self, range: (i32, i32)) -> Self {
283        self.apply_year_range(range);
284        self
285    }
286    pub fn set_year_range(&mut self, range: (i32, i32), cx: &mut Context<Self>) {
287        self.apply_year_range(range);
288        cx.notify();
289    }
290    fn apply_year_range(&mut self, range: (i32, i32)) {
291        self.years = (range.0..range.1)
292            .collect::<Vec<_>>()
293            .chunks(20)
294            .map(<[_]>::to_vec)
295            .collect();
296        self.year_page = self
297            .years
298            .iter()
299            .position(|v| v.contains(&self.current_year))
300            .unwrap_or(0) as i32;
301    }
302    pub fn offset_year_month(&self, offset: usize) -> (i32, u32) {
303        let n = self.current_month as i64 - 1 + offset as i64;
304        (
305            self.current_year + n.div_euclid(12) as i32,
306            n.rem_euclid(12) as u32 + 1,
307        )
308    }
309    pub fn days(&self) -> Vec<Vec<civil::Date>> {
310        self.month_days().into_iter().flatten().collect()
311    }
312    /// Calendar weeks grouped by visible month. This preserves six-week
313    /// months and is the preferred rendering API.
314    pub fn month_days(&self) -> Vec<Vec<Vec<civil::Date>>> {
315        (0..self.number_of_months)
316            .map(|n| {
317                days_in_month(
318                    self.current_year,
319                    self.current_month as u32 + n as u32,
320                    Weekday::Sunday,
321                )
322            })
323            .collect()
324    }
325    pub fn has_prev_year_page(&self) -> bool {
326        self.year_page > 0
327    }
328    pub fn has_next_year_page(&self) -> bool {
329        self.year_page < self.years.len() as i32 - 1
330    }
331    pub fn prev_year_page(&mut self) -> bool {
332        if !self.has_prev_year_page() {
333            false
334        } else {
335            self.year_page -= 1;
336            true
337        }
338    }
339    pub fn next_year_page(&mut self) -> bool {
340        if !self.has_next_year_page() {
341            false
342        } else {
343            self.year_page += 1;
344            true
345        }
346    }
347    pub fn prev_month(&mut self) {
348        if self.current_month == 1 {
349            self.current_year -= 1;
350            self.current_month = 12;
351        } else {
352            self.current_month -= 1;
353        }
354    }
355    pub fn next_month(&mut self) {
356        if self.current_month == 12 {
357            self.current_year += 1;
358            self.current_month = 1;
359        } else {
360            self.current_month += 1;
361        }
362    }
363    pub fn view(&self) -> CalendarView {
364        self.view
365    }
366    pub fn set_view(&mut self, view: CalendarView) {
367        self.view = view;
368    }
369    pub fn current_year(&self) -> i32 {
370        self.current_year
371    }
372    pub fn current_month(&self) -> u8 {
373        self.current_month
374    }
375    /// Today's date on the system clock, read on each call so that a
376    /// state kept open across midnight marks the new day.
377    pub fn today(&self) -> civil::Date {
378        jiff::ZonedDateTime::now().date()
379    }
380    pub fn years_on_page(&self) -> &[i32] {
381        self.years
382            .get(self.year_page as usize)
383            .map(Vec::as_slice)
384            .unwrap_or_default()
385    }
386    pub fn select_month(&mut self, month: u8) {
387        self.current_month = month;
388        self.view = CalendarView::Day;
389    }
390    pub fn select_year(&mut self, year: i32) {
391        self.current_year = year;
392        self.view = CalendarView::Day;
393    }
394}
395impl CalendarState {
396    /// The day the keyboard acts on: the moved-to day, else the selected
397    /// day, else today, else the first of the visible month.
398    fn keyboard_day(&self) -> civil::Date {
399        let first = civil::Date::new(self.current_year as i16, self.current_month as i8, 1)
400            .unwrap_or_else(|_| self.today());
401        let visible = |d: &civil::Date| {
402            let n = (d.year() as i32 - self.current_year) * 12 + d.month() as i32
403                - self.current_month as i32;
404            n >= 0 && (n as usize) < self.number_of_months.max(1)
405        };
406        self.focused_day
407            .or(self.date.start())
408            .or_else(|| Some(self.today()))
409            .filter(visible)
410            .unwrap_or(first)
411    }
412
413    /// Moves the keyboard day and pages the view so it stays visible.
414    fn focus_day(&mut self, day: civil::Date) {
415        self.focused_day = Some(day);
416        let n = (day.year() as i32 - self.current_year) * 12 + day.month() as i32
417            - self.current_month as i32;
418        if n < 0 || n as usize >= self.number_of_months.max(1) {
419            self.current_year = day.year().into();
420            self.current_month = day.month() as u8;
421        }
422    }
423
424    /// Handles the WAI-ARIA date picker keys in the day view. Returns
425    /// whether the key was consumed.
426    fn handle_key(
427        &mut self,
428        key: &str,
429        shift: bool,
430        first_day: Weekday,
431        cx: &mut Context<Self>,
432    ) -> bool {
433        if !self.view.is_day() {
434            return false;
435        }
436        let day = self.keyboard_day();
437        let months = |n: i32| jiff::Span::new().months(n);
438        let target = match key {
439            "left" => day.yesterday().ok(),
440            "right" => day.tomorrow().ok(),
441            "up" => day.checked_sub(jiff::Span::new().days(7)).ok(),
442            "down" => day.checked_add(jiff::Span::new().days(7)).ok(),
443            "home" => {
444                let back = (day.weekday().to_sunday_zero_offset() as i64
445                    - first_day.to_sunday_zero_offset() as i64)
446                    .rem_euclid(7);
447                day.checked_sub(jiff::Span::new().days(back)).ok()
448            }
449            "end" => {
450                let back = (day.weekday().to_sunday_zero_offset() as i64
451                    - first_day.to_sunday_zero_offset() as i64)
452                    .rem_euclid(7);
453                day.checked_add(jiff::Span::new().days(6 - back)).ok()
454            }
455            "pageup" => day
456                .checked_sub(if shift { months(12) } else { months(1) })
457                .ok(),
458            "pagedown" => day
459                .checked_add(if shift { months(12) } else { months(1) })
460                .ok(),
461            "enter" | "space" => {
462                self.focused_day = Some(day);
463                self.activate_date(day, cx);
464                return true;
465            }
466            _ => return false,
467        };
468        let Some(target) = target else { return false };
469        self.focus_day(target);
470        cx.notify();
471        true
472    }
473}
474
475impl EventEmitter<CalendarEvent> for CalendarState {}
476impl Render for CalendarState {
477    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
478        Empty
479    }
480}
481
482/// The semantic kind of a calendar control rendered by [`Calendar`].
483#[derive(Clone, Copy, Debug, PartialEq, Eq)]
484pub enum CalendarItemKind {
485    Previous,
486    MonthToggle,
487    YearToggle,
488    Next,
489    Weekday,
490    Day,
491    Month,
492    Year,
493}
494
495/// State exposed to a calendar item slot. Applications may use it solely to
496/// decorate the unstyled primitive; all interaction remains owned by base.
497///
498/// The fields are private and reached through the methods below, so that a new
499/// one can be added without breaking the item slots.
500#[derive(Clone, Copy, Debug)]
501pub struct CalendarItemState {
502    kind: CalendarItemKind,
503    active: bool,
504    in_range: bool,
505    muted: bool,
506    disabled: bool,
507    today: bool,
508}
509
510impl CalendarItemState {
511    /// Create a state for `kind`, with every flag off.
512    pub fn new(kind: CalendarItemKind) -> Self {
513        Self {
514            kind,
515            active: false,
516            in_range: false,
517            muted: false,
518            disabled: false,
519            today: false,
520        }
521    }
522
523    pub fn active(mut self, active: bool) -> Self {
524        self.active = active;
525        self
526    }
527
528    /// Set whether the item is between the two ends of a range selection.
529    pub fn in_range(mut self, in_range: bool) -> Self {
530        self.in_range = in_range;
531        self
532    }
533
534    /// Set whether the item is shown as secondary, e.g.: a weekday header or a
535    /// day that belongs to the neighboring month.
536    pub fn muted(mut self, muted: bool) -> Self {
537        self.muted = muted;
538        self
539    }
540
541    pub fn disabled(mut self, disabled: bool) -> Self {
542        self.disabled = disabled;
543        self
544    }
545
546    pub fn today(mut self, today: bool) -> Self {
547        self.today = today;
548        self
549    }
550
551    pub fn kind(&self) -> CalendarItemKind {
552        self.kind
553    }
554
555    pub fn is_active(&self) -> bool {
556        self.active
557    }
558
559    pub fn is_in_range(&self) -> bool {
560        self.in_range
561    }
562
563    pub fn is_muted(&self) -> bool {
564        self.muted
565    }
566
567    pub fn is_disabled(&self) -> bool {
568        self.disabled
569    }
570
571    pub fn is_today(&self) -> bool {
572        self.today
573    }
574}
575
576/// An unstyled, pre-wired calendar item passed to the item slot.
577#[derive(IntoElement)]
578pub struct CalendarItem {
579    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
580    state: CalendarItemState,
581    style: StyleRefinement,
582    children: Vec<AnyElement>,
583}
584
585impl CalendarItem {
586    fn new(id: impl Into<ElementId>, state: CalendarItemState) -> Self {
587        Self {
588            base: div().id(id.into()).test_support(),
589            state,
590            style: StyleRefinement::default(),
591            children: vec![],
592        }
593    }
594    // Keep the default visible label available to assistive technology even
595    // when a presentation assigns a role that does not derive a name from children.
596    fn with_label(self, label: SharedString) -> Self {
597        self.aria_label(label.clone()).child(label)
598    }
599
600    pub fn item_state(&self) -> CalendarItemState {
601        self.state
602    }
603
604    /// Remove the default label so a styled facade can provide custom content.
605    pub fn clear_children(mut self) -> Self {
606        self.children.clear();
607        self
608    }
609}
610impl ParentElement for CalendarItem {
611    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
612        self.children.extend(elements);
613    }
614}
615impl Styled for CalendarItem {
616    fn style(&mut self) -> &mut StyleRefinement {
617        &mut self.style
618    }
619}
620impl InteractiveElement for CalendarItem {
621    fn interactivity(&mut self) -> &mut gpui::Interactivity {
622        self.base.interactivity()
623    }
624
625    fn track_focus(mut self, handle: &gpui::FocusHandle) -> Self {
626        self.base = self.base.track_focus(handle);
627        self
628    }
629}
630impl StatefulInteractiveElement for CalendarItem {}
631impl RenderOnce for CalendarItem {
632    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
633        self.base.children(self.children).refine_style(&self.style)
634    }
635}
636
637type ItemRenderer =
638    Rc<dyn Fn(CalendarItem, CalendarItemState, &mut Window, &mut App) -> AnyElement>;
639type Labeler = Rc<dyn Fn(CalendarItemKind, i32) -> SharedString>;
640
641/// Complete unstyled calendar structure and behavior.
642///
643/// Base owns navigation, view switching, grids, disabled/selection state and
644/// click handling. The UI crate only decorates the pre-wired item slot.
645#[derive(IntoElement)]
646pub struct Calendar {
647    id: ElementId,
648    state: Entity<CalendarState>,
649    number_of_months: usize,
650    first_day_of_week: Weekday,
651    style: StyleRefinement,
652    item: ItemRenderer,
653    label: Labeler,
654}
655
656impl Calendar {
657    pub fn new(id: impl Into<ElementId>, state: &Entity<CalendarState>) -> Self {
658        Self {
659            id: id.into(),
660            state: state.clone(),
661            number_of_months: 1,
662            first_day_of_week: Weekday::Sunday,
663            style: StyleRefinement::default(),
664            item: Rc::new(|item, _, _, _| item.into_any_element()),
665            label: Rc::new(|kind, value| match kind {
666                CalendarItemKind::Previous => "‹".into(),
667                CalendarItemKind::Next => "›".into(),
668                CalendarItemKind::Weekday => value.to_string().into(),
669                _ => value.to_string().into(),
670            }),
671        }
672    }
673    pub fn number_of_months(mut self, count: usize) -> Self {
674        self.number_of_months = count.max(1);
675        self
676    }
677    pub fn first_day_of_week(mut self, day: Weekday) -> Self {
678        self.first_day_of_week = day;
679        self
680    }
681    pub fn item(
682        mut self,
683        render: impl Fn(CalendarItem, CalendarItemState, &mut Window, &mut App) -> AnyElement + 'static,
684    ) -> Self {
685        self.item = Rc::new(render);
686        self
687    }
688    pub fn label(
689        mut self,
690        label: impl Fn(CalendarItemKind, i32) -> SharedString + 'static,
691    ) -> Self {
692        self.label = Rc::new(label);
693        self
694    }
695
696    fn render_item(
697        &self,
698        id: impl Into<ElementId>,
699        state: CalendarItemState,
700        value: i32,
701        window: &mut Window,
702        cx: &mut App,
703    ) -> AnyElement {
704        let label = (self.label)(state.kind(), value);
705        (self.item)(
706            CalendarItem::new(id, state).with_label(label),
707            state,
708            window,
709            cx,
710        )
711    }
712}
713impl Styled for Calendar {
714    fn style(&mut self) -> &mut StyleRefinement {
715        &mut self.style
716    }
717}
718
719impl RenderOnce for Calendar {
720    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
721        let count = self.number_of_months;
722        self.state
723            .update(cx, |s, cx| s.set_number_of_months(count, window, cx));
724        let view = self.state.read(cx).view();
725        let mut header = h_flex()
726            .flex_row_dir(cx)
727            .items_center()
728            .justify_between()
729            .child({
730                let st = CalendarItemState::new(CalendarItemKind::Previous).disabled(
731                    view.is_month()
732                        || (view.is_year() && !self.state.read(cx).has_prev_year_page()),
733                );
734                let mut item =
735                    CalendarItem::new("calendar-prev", st).with_label((self.label)(st.kind(), 0));
736                if !st.is_disabled() {
737                    let entity = self.state.clone();
738                    item = item.on_click(move |_, _window, cx| {
739                        entity.update(cx, |s, cx| {
740                            if s.view().is_day() {
741                                s.prev_month();
742                            } else {
743                                s.prev_year_page();
744                            }
745                            cx.notify();
746                        })
747                    });
748                }
749                (self.item)(item, st, window, cx)
750            });
751        if count == 1 {
752            let (month, year) = {
753                let s = self.state.read(cx);
754                (s.current_month() as i32, s.current_year())
755            };
756            for (kind, value, active) in [
757                (CalendarItemKind::MonthToggle, month, view.is_month()),
758                (CalendarItemKind::YearToggle, year, view.is_year()),
759            ] {
760                let st = CalendarItemState::new(kind).active(active);
761                let entity = self.state.clone();
762                let mut item = CalendarItem::new(format!("calendar-{kind:?}"), st)
763                    .with_label((self.label)(kind, value));
764                item = item.on_click(move |_, _, cx| {
765                    entity.update(cx, |s, cx| {
766                        s.set_view(
767                            if s.view()
768                                == match kind {
769                                    CalendarItemKind::MonthToggle => CalendarView::Month,
770                                    _ => CalendarView::Year,
771                                }
772                            {
773                                CalendarView::Day
774                            } else {
775                                match kind {
776                                    CalendarItemKind::MonthToggle => CalendarView::Month,
777                                    _ => CalendarView::Year,
778                                }
779                            },
780                        );
781                        cx.notify();
782                    })
783                });
784                header = header.child((self.item)(item, st, window, cx));
785            }
786        } else {
787            for offset in 0..count {
788                let (y, m) = self.state.read(cx).offset_year_month(offset);
789                header = header.child(
790                    div().text_sm().font_medium().child(
791                        v_flex()
792                            .items_center()
793                            .child((self.label)(CalendarItemKind::MonthToggle, m as i32))
794                            .child(y.to_string()),
795                    ),
796                );
797            }
798        }
799        header = header.child({
800            let st = CalendarItemState::new(CalendarItemKind::Next).disabled(
801                view.is_month() || (view.is_year() && !self.state.read(cx).has_next_year_page()),
802            );
803            let mut item =
804                CalendarItem::new("calendar-next", st).with_label((self.label)(st.kind(), 0));
805            if !st.is_disabled() {
806                let entity = self.state.clone();
807                item = item.on_click(move |_, _, cx| {
808                    entity.update(cx, |s, cx| {
809                        if s.view().is_day() {
810                            s.next_month()
811                        } else {
812                            s.next_year_page();
813                        }
814                        cx.notify();
815                    })
816                });
817            }
818            (self.item)(item, st, window, cx)
819        });
820
821        let mut body = match picker_grid_layout(view) {
822            None => h_flex().flex_row_dir(cx).justify_around(),
823            Some((columns, horizontal_gap)) => {
824                div().grid().grid_cols(columns).gap_x(px(horizontal_gap))
825            }
826        };
827        if view.is_day() {
828            for offset in 0..count {
829                let (year, month_number) = self.state.read(cx).offset_year_month(offset);
830                let weeks = days_in_month(year, month_number, self.first_day_of_week);
831                let mut month = v_flex();
832                let mut header_row = h_flex().flex_row_dir(cx);
833                for weekday in 0..7 {
834                    let st = CalendarItemState::new(CalendarItemKind::Weekday)
835                        .muted(true)
836                        .disabled(true);
837                    header_row = header_row.child(self.render_item(
838                        format!("weekday-{offset}-{weekday}"),
839                        st,
840                        (weekday + self.first_day_of_week.to_sunday_zero_offset() as i32) % 7,
841                        window,
842                        cx,
843                    ));
844                }
845                month = month.child(header_row);
846                let today = self.state.read(cx).today();
847                for (week_index, week) in weeks.iter().enumerate() {
848                    let mut week_row = h_flex().flex_row_dir(cx);
849                    for date in week {
850                        let date = *date;
851                        let st = {
852                            let s = self.state.read(cx);
853                            let (_, m) = s.offset_year_month(offset);
854                            let disabled =
855                                s.disabled_matcher_ref().is_some_and(|x| x.matched(&date));
856                            CalendarItemState::new(CalendarItemKind::Day)
857                                .active(s.date().is_active(&date))
858                                .in_range(s.date().is_in_range(&date))
859                                .muted(date.month() as u32 != m || disabled)
860                                .disabled(disabled)
861                                .today(date == today)
862                        };
863                        let mut item =
864                            CalendarItem::new(format!("calendar-{date}-{offset}-{week_index}"), st)
865                                .with_label((self.label)(st.kind(), date.day() as i32))
866                                .aria_label(date.to_string());
867                        if !st.is_disabled() {
868                            let entity = self.state.clone();
869                            item = item.on_click(move |_, _, cx| {
870                                entity.update(cx, |s, cx| {
871                                    s.activate_date(date, cx);
872                                })
873                            });
874                        }
875                        week_row = week_row.child((self.item)(item, st, window, cx));
876                    }
877                    month = month.child(week_row);
878                }
879                body = body.child(month);
880            }
881        } else if view.is_month() {
882            let current = self.state.read(cx).current_month();
883            for month in 1..=12u8 {
884                let st = CalendarItemState::new(CalendarItemKind::Month).active(month == current);
885                let entity = self.state.clone();
886                let item = CalendarItem::new(format!("calendar-month-{month}"), st)
887                    .with_label((self.label)(st.kind(), month as i32))
888                    .on_click(move |_, _, cx| {
889                        entity.update(cx, |s, cx| {
890                            s.select_month(month);
891                            cx.notify();
892                        })
893                    });
894                body = body.child((self.item)(item, st, window, cx));
895            }
896        } else {
897            let current = self.state.read(cx).current_year();
898            let years = self.state.read(cx).years_on_page().to_vec();
899            for year in years {
900                let st = CalendarItemState::new(CalendarItemKind::Year).active(year == current);
901                let entity = self.state.clone();
902                let item = CalendarItem::new(format!("calendar-year-{year}"), st)
903                    .with_label((self.label)(st.kind(), year))
904                    .on_click(move |_, _, cx| {
905                        entity.update(cx, |s, cx| {
906                            s.select_year(year);
907                            cx.notify();
908                        })
909                    });
910                body = body.child((self.item)(item, st, window, cx));
911            }
912        }
913        let entity = self.state.clone();
914        let first_day = self.first_day_of_week;
915        v_flex()
916            .id(self.id)
917            .track_focus(&self.state.read(cx).focus_handle)
918            .on_key_down(move |event, window, cx| {
919                let modifiers = event.keystroke.modifiers;
920                if window.default_prevented()
921                    || event.keystroke.is_ime_in_progress()
922                    || modifiers.control
923                    || modifiers.alt
924                    || modifiers.platform
925                {
926                    return;
927                }
928                let key = event.keystroke.key.clone();
929                let handled = entity.update(cx, |s, cx| {
930                    s.handle_key(&key, modifiers.shift, first_day, cx)
931                });
932                if handled {
933                    window.prevent_default();
934                    cx.stop_propagation();
935                }
936            })
937            .child(header)
938            .child(body)
939            .refine_style(&self.style)
940    }
941}
942
943fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec<Vec<civil::Date>> {
944    let total = year as i64 * 12 + month as i64 - 1;
945    let year = total.div_euclid(12) as i16;
946    let month = total.rem_euclid(12) as i8 + 1;
947    let first = civil::date(year, month, 1);
948    let offset = first.weekday().since(first_day);
949    let start = first - jiff::Span::new().days(offset);
950    let count = (first.days_in_month() + offset) as usize;
951    start
952        .series(jiff::Span::new().days(1))
953        .take(count.div_ceil(7) * 7)
954        .collect::<Vec<_>>()
955        .chunks(7)
956        .map(<[_]>::to_vec)
957        .collect()
958}
959
960#[cfg(test)]
961mod tests {
962    use std::{cell::RefCell, rc::Rc};
963
964    use gpui::{AppContext as _, Context, Entity, IntoElement, Render, Subscription, Window};
965
966    use super::*;
967
968    #[gpui::test]
969    fn calendar_keyboard_moves_pages_and_selects(cx: &mut gpui::TestAppContext) {
970        let (state, cx) = cx.add_window_view(|window, cx| CalendarState::new(window, cx));
971        cx.update(|_, cx| {
972            state.update(cx, |s, cx| {
973                s.apply_date(Date::Single(Some(civil::date(2026, 1, 30))));
974                let first = Weekday::Sunday;
975                assert!(s.handle_key("right", false, first, cx));
976                assert!(s.handle_key("right", false, first, cx));
977                assert_eq!(s.keyboard_day(), civil::date(2026, 2, 1));
978                assert_eq!((s.current_year(), s.current_month()), (2026, 2));
979                assert!(s.handle_key("up", false, first, cx));
980                assert_eq!(s.keyboard_day(), civil::date(2026, 1, 25));
981                assert!(s.handle_key("pagedown", false, first, cx));
982                assert_eq!(s.keyboard_day(), civil::date(2026, 2, 25));
983                assert!(s.handle_key("pageup", true, first, cx));
984                assert_eq!(s.keyboard_day(), civil::date(2025, 2, 25));
985                assert!(s.handle_key("home", false, first, cx));
986                assert_eq!(s.keyboard_day().weekday(), Weekday::Sunday);
987                assert!(s.handle_key("end", false, first, cx));
988                assert_eq!(s.keyboard_day().weekday(), Weekday::Saturday);
989                let day = s.keyboard_day();
990                assert!(s.handle_key("enter", false, first, cx));
991                assert_eq!(s.date(), Date::Single(Some(day)));
992                assert!(!s.handle_key("a", false, first, cx));
993                s.set_view(CalendarView::Month);
994                assert!(!s.handle_key("right", false, first, cx));
995            })
996        });
997    }
998
999    #[gpui::test]
1000    fn calendar_items_expose_names_in_every_view(cx: &mut gpui::TestAppContext) {
1001        use gpui::{Element as _, accesskit};
1002        struct Names {
1003            calendar: Entity<CalendarState>,
1004            labels: Rc<RefCell<Vec<(CalendarItemKind, String)>>>,
1005        }
1006        impl Render for Names {
1007            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1008                let labels = self.labels.clone();
1009                labels.borrow_mut().clear();
1010                Calendar::new("named-calendar", &self.calendar).item(move |item, state, _, _| {
1011                    let mut node = accesskit::Node::new(accesskit::Role::Button);
1012                    item.base.write_a11y_info(&mut node);
1013                    labels
1014                        .borrow_mut()
1015                        .push((state.kind(), node.label().unwrap_or("").to_string()));
1016                    item.into_any_element()
1017                })
1018            }
1019        }
1020        let (view, cx) = cx.add_window_view(|window, cx| Names {
1021            calendar: cx.new(|cx| CalendarState::new(window, cx)),
1022            labels: Rc::new(RefCell::new(Vec::new())),
1023        });
1024        for mode in [CalendarView::Day, CalendarView::Month, CalendarView::Year] {
1025            cx.update(|window, cx| {
1026                view.read(cx).calendar.clone().update(cx, |state, cx| {
1027                    state.apply_date(Date::Single(Some(civil::date(2026, 9, 7))));
1028                    state.set_view(mode);
1029                    cx.notify();
1030                });
1031                window.draw(cx).clear(cx);
1032                let labels = view.read(cx).labels.borrow();
1033                assert!(!labels.is_empty());
1034                for (kind, label) in labels.iter() {
1035                    assert!(!label.is_empty(), "missing name for {kind:?}");
1036                }
1037                if mode.is_day() {
1038                    assert!(labels.iter().any(
1039                        |(kind, label)| *kind == CalendarItemKind::Day && label == "2026-09-07"
1040                    ));
1041                }
1042            });
1043        }
1044    }
1045
1046    struct EventHarness {
1047        calendar: Entity<CalendarState>,
1048        events: Rc<RefCell<Vec<Date>>>,
1049        _subscription: Option<Subscription>,
1050    }
1051    impl EventHarness {
1052        fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053            let calendar = cx.new(|cx| CalendarState::new(window, cx));
1054            let events = Rc::new(RefCell::new(Vec::new()));
1055            let mut this = Self {
1056                calendar: calendar.clone(),
1057                events: events.clone(),
1058                _subscription: None,
1059            };
1060            this._subscription = Some(cx.subscribe(&calendar, move |_, _, event, _| {
1061                let CalendarEvent::Selected(date) = event;
1062                events.borrow_mut().push(*date);
1063            }));
1064            this
1065        }
1066    }
1067    impl Render for EventHarness {
1068        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1069            Empty
1070        }
1071    }
1072    fn state(cx: &mut gpui::TestAppContext, date: Date) -> gpui::Entity<CalendarState> {
1073        let (state, _) = cx.add_window_view(CalendarState::new);
1074        state.update(cx, |state, _| {
1075            state.date = date;
1076        });
1077        state
1078    }
1079    #[gpui::test]
1080    fn today_follows_the_system_clock(cx: &mut gpui::TestAppContext) {
1081        let (state, cx) = cx.add_window_view(CalendarState::new);
1082        // `today` is read from the clock rather than stored when the state is
1083        // created, so a calendar kept open past midnight marks the new day.
1084        let before = jiff::ZonedDateTime::now().date();
1085        let today = state.read_with(cx, |s, _| s.today());
1086        let after = jiff::ZonedDateTime::now().date();
1087        assert!(today == before || today == after);
1088    }
1089
1090    #[gpui::test]
1091    fn range_selection_restarts_and_completes(cx: &mut gpui::TestAppContext) {
1092        let s = state(cx, Date::Range(None, None));
1093        let a = civil::date(2025, 2, 10);
1094        let b = civil::date(2025, 2, 12);
1095        s.update(cx, |s, _| {
1096            assert!(!s.select_date(a));
1097            assert!(s.select_date(b));
1098        });
1099        assert_eq!(
1100            s.read_with(cx, |s, _| s.date()),
1101            Date::Range(Some(a), Some(b))
1102        );
1103        s.update(cx, |s, _| assert!(!s.select_date(a)));
1104        assert_eq!(s.read_with(cx, |s, _| s.date()), Date::Range(Some(a), None));
1105    }
1106    #[gpui::test]
1107    fn disabled_date_is_rejected(cx: &mut gpui::TestAppContext) {
1108        let s = state(cx, Date::Single(None));
1109        s.update(cx, |s, _| {
1110            s.disabled_matcher = Some(Rc::new(Matcher::range(
1111                Some(civil::date(2025, 1, 1)),
1112                Some(civil::date(2025, 1, 31)),
1113            )))
1114        });
1115        s.update(cx, |s, _| assert!(!s.select_date(civil::date(2025, 1, 2))));
1116    }
1117    #[gpui::test]
1118    fn month_navigation_crosses_year(cx: &mut gpui::TestAppContext) {
1119        let s = state(cx, Date::Single(Some(civil::date(2025, 1, 1))));
1120        s.update(cx, |s, _| {
1121            s.apply_date(Date::Single(Some(civil::date(2025, 1, 1))));
1122            s.prev_month();
1123        });
1124        assert_eq!(
1125            s.read_with(cx, |s, _| (s.current_year(), s.current_month())),
1126            (2024, 12)
1127        );
1128        s.update(cx, |s, _| s.next_month());
1129        assert_eq!(
1130            s.read_with(cx, |s, _| (s.current_year(), s.current_month())),
1131            (2025, 1)
1132        );
1133    }
1134
1135    #[gpui::test]
1136    fn six_week_month_is_not_truncated(cx: &mut gpui::TestAppContext) {
1137        let s = state(cx, Date::Single(Some(civil::date(2025, 8, 1))));
1138        s.update(cx, |s, _| {
1139            s.apply_date(Date::Single(Some(civil::date(2025, 8, 1))));
1140            assert_eq!(s.month_days().len(), 1);
1141            assert_eq!(s.month_days()[0].len(), 6);
1142            assert_eq!(s.days().len(), 6);
1143            assert_eq!(s.month_days()[0][5][0].day(), 31);
1144        });
1145    }
1146
1147    #[gpui::test]
1148    fn day_month_and_year_views_have_complete_transitions(cx: &mut gpui::TestAppContext) {
1149        let s = state(cx, Date::Single(None));
1150        s.update(cx, |s, _| {
1151            assert_eq!(s.view(), CalendarView::Day);
1152            s.set_view(CalendarView::Month);
1153            s.select_month(11);
1154            assert_eq!((s.view(), s.current_month()), (CalendarView::Day, 11));
1155            s.set_view(CalendarView::Year);
1156            s.select_year(2032);
1157            assert_eq!((s.view(), s.current_year()), (CalendarView::Day, 2032));
1158        });
1159    }
1160
1161    #[test]
1162    fn picker_views_use_stable_grid_layouts() {
1163        assert_eq!(picker_grid_layout(CalendarView::Month), Some((3, 4.)));
1164        assert_eq!(picker_grid_layout(CalendarView::Year), Some((5, 4.)));
1165        assert_eq!(picker_grid_layout(CalendarView::Day), None);
1166    }
1167
1168    #[gpui::test]
1169    fn year_page_navigation_respects_both_bounds(cx: &mut gpui::TestAppContext) {
1170        let s = state(cx, Date::Single(None));
1171        s.update(cx, |s, _| {
1172            s.apply_year_range((2000, 2041));
1173            while s.prev_year_page() {}
1174            assert!(!s.has_prev_year_page());
1175            assert!(!s.prev_year_page());
1176            assert!(s.next_year_page());
1177            while s.next_year_page() {}
1178            assert!(!s.has_next_year_page());
1179            assert!(!s.next_year_page());
1180        });
1181    }
1182
1183    #[gpui::test]
1184    fn activation_emits_only_for_complete_enabled_values(cx: &mut gpui::TestAppContext) {
1185        let (harness, _) = cx.add_window_view(EventHarness::new);
1186        let s = harness.read_with(cx, |h, _| h.calendar.clone());
1187        s.update(cx, |s, _| s.date = Date::Range(None, None));
1188        let start = civil::date(2025, 4, 4);
1189        let end = civil::date(2025, 4, 8);
1190        s.update(cx, |s, cx| {
1191            assert!(!s.activate_date(start, cx));
1192            assert!(s.activate_date(end, cx));
1193            assert_eq!(s.date(), Date::Range(Some(start), Some(end)));
1194            s.set_disabled_matcher_shared(Some(Rc::new(Matcher::custom(move |d| *d == start))));
1195            assert!(!s.activate_date(start, cx));
1196            assert_eq!(s.date(), Date::Range(Some(start), Some(end)));
1197        });
1198        assert_eq!(
1199            harness.read_with(cx, |h, _| h.events.borrow().clone()),
1200            vec![Date::Range(Some(start), Some(end))]
1201        );
1202
1203        s.update(cx, |s, cx| {
1204            s.date = Date::Single(None);
1205            assert!(s.activate_date(end, cx));
1206            assert_eq!(s.date(), Date::Single(Some(end)));
1207        });
1208        assert_eq!(
1209            harness.read_with(cx, |h, _| h.events.borrow().clone()),
1210            vec![Date::Range(Some(start), Some(end)), Date::Single(Some(end))]
1211        );
1212    }
1213}