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    today: civil::Date,
180    number_of_months: usize,
181    disabled_matcher: Option<Rc<Matcher>>,
182}
183
184impl CalendarState {
185    pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
186        let today = jiff::ZonedDateTime::now().date();
187        Self {
188            focus_handle: cx.focus_handle(),
189            view: CalendarView::Day,
190            date: Date::Single(None),
191            current_year: today.year().into(),
192            current_month: today.month() as u8,
193            years: vec![],
194            year_page: 0,
195            today,
196            number_of_months: 1,
197            disabled_matcher: None,
198        }
199        .year_range((i32::from(today.year()) - 50, i32::from(today.year()) + 50))
200    }
201    pub fn disabled_matcher(mut self, matcher: impl Into<Matcher>) -> Self {
202        self.disabled_matcher = Some(Rc::new(matcher.into()));
203        self
204    }
205    pub fn set_disabled_matcher(
206        &mut self,
207        matcher: impl Into<Matcher>,
208        _: &mut Window,
209        _: &mut Context<Self>,
210    ) {
211        self.disabled_matcher = Some(Rc::new(matcher.into()));
212    }
213    pub fn set_disabled_matcher_shared(&mut self, matcher: Option<Rc<Matcher>>) {
214        self.disabled_matcher = matcher;
215    }
216    pub fn disabled_matcher_ref(&self) -> Option<&Matcher> {
217        self.disabled_matcher.as_deref()
218    }
219    pub fn set_date(&mut self, date: impl Into<Date>, _: &mut Window, cx: &mut Context<Self>) {
220        if self.apply_date(date.into()) {
221            cx.notify();
222        }
223    }
224    pub fn apply_date(&mut self, date: Date) -> bool {
225        if self
226            .disabled_matcher
227            .as_ref()
228            .is_some_and(|m| m.is_match(&date))
229        {
230            return false;
231        }
232        self.date = date;
233        if let Some(v) = date.start() {
234            self.current_month = v.month() as u8;
235            self.current_year = v.year().into();
236        }
237        true
238    }
239    pub fn select_date(&mut self, value: civil::Date) -> bool {
240        if self
241            .disabled_matcher
242            .as_ref()
243            .is_some_and(|m| m.matched(&value))
244        {
245            return false;
246        }
247        let next = match self.date {
248            Date::Single(_) => Date::Single(Some(value)),
249            Date::Range(None, None) | Date::Range(None, Some(_)) => Date::Range(Some(value), None),
250            Date::Range(Some(start), None) if value >= start => {
251                Date::Range(Some(start), Some(value))
252            }
253            Date::Range(Some(_), None) | Date::Range(Some(_), Some(_)) => {
254                Date::Range(Some(value), None)
255            }
256        };
257        self.apply_date(next);
258        self.date.is_complete()
259    }
260    /// Activates a day item and emits [`CalendarEvent::Selected`] once the
261    /// controlled value is complete. This is the single pointer/keyboard
262    /// activation path used by the calendar root.
263    pub fn activate_date(&mut self, value: civil::Date, cx: &mut Context<Self>) -> bool {
264        let complete = self.select_date(value);
265        if complete {
266            cx.emit(CalendarEvent::Selected(self.date()));
267        }
268        cx.notify();
269        complete
270    }
271    pub fn date(&self) -> Date {
272        self.date
273    }
274    pub fn set_number_of_months(&mut self, n: usize, _: &mut Window, cx: &mut Context<Self>) {
275        self.number_of_months = n;
276        cx.notify();
277    }
278    pub fn number_of_months(&self) -> usize {
279        self.number_of_months
280    }
281    pub fn year_range(mut self, range: (i32, i32)) -> Self {
282        self.apply_year_range(range);
283        self
284    }
285    pub fn set_year_range(&mut self, range: (i32, i32), cx: &mut Context<Self>) {
286        self.apply_year_range(range);
287        cx.notify();
288    }
289    fn apply_year_range(&mut self, range: (i32, i32)) {
290        self.years = (range.0..range.1)
291            .collect::<Vec<_>>()
292            .chunks(20)
293            .map(<[_]>::to_vec)
294            .collect();
295        self.year_page = self
296            .years
297            .iter()
298            .position(|v| v.contains(&self.current_year))
299            .unwrap_or(0) as i32;
300    }
301    pub fn offset_year_month(&self, offset: usize) -> (i32, u32) {
302        let n = self.current_month as i64 - 1 + offset as i64;
303        (
304            self.current_year + n.div_euclid(12) as i32,
305            n.rem_euclid(12) as u32 + 1,
306        )
307    }
308    pub fn days(&self) -> Vec<Vec<civil::Date>> {
309        self.month_days().into_iter().flatten().collect()
310    }
311    /// Calendar weeks grouped by visible month. This preserves six-week
312    /// months and is the preferred rendering API.
313    pub fn month_days(&self) -> Vec<Vec<Vec<civil::Date>>> {
314        (0..self.number_of_months)
315            .map(|n| {
316                days_in_month(
317                    self.current_year,
318                    self.current_month as u32 + n as u32,
319                    Weekday::Sunday,
320                )
321            })
322            .collect()
323    }
324    pub fn has_prev_year_page(&self) -> bool {
325        self.year_page > 0
326    }
327    pub fn has_next_year_page(&self) -> bool {
328        self.year_page < self.years.len() as i32 - 1
329    }
330    pub fn prev_year_page(&mut self) -> bool {
331        if !self.has_prev_year_page() {
332            false
333        } else {
334            self.year_page -= 1;
335            true
336        }
337    }
338    pub fn next_year_page(&mut self) -> bool {
339        if !self.has_next_year_page() {
340            false
341        } else {
342            self.year_page += 1;
343            true
344        }
345    }
346    pub fn prev_month(&mut self) {
347        if self.current_month == 1 {
348            self.current_year -= 1;
349            self.current_month = 12;
350        } else {
351            self.current_month -= 1;
352        }
353    }
354    pub fn next_month(&mut self) {
355        if self.current_month == 12 {
356            self.current_year += 1;
357            self.current_month = 1;
358        } else {
359            self.current_month += 1;
360        }
361    }
362    pub fn view(&self) -> CalendarView {
363        self.view
364    }
365    pub fn set_view(&mut self, view: CalendarView) {
366        self.view = view;
367    }
368    pub fn current_year(&self) -> i32 {
369        self.current_year
370    }
371    pub fn current_month(&self) -> u8 {
372        self.current_month
373    }
374    pub fn today(&self) -> civil::Date {
375        self.today
376    }
377    pub fn years_on_page(&self) -> &[i32] {
378        self.years
379            .get(self.year_page as usize)
380            .map(Vec::as_slice)
381            .unwrap_or_default()
382    }
383    pub fn select_month(&mut self, month: u8) {
384        self.current_month = month;
385        self.view = CalendarView::Day;
386    }
387    pub fn select_year(&mut self, year: i32) {
388        self.current_year = year;
389        self.view = CalendarView::Day;
390    }
391}
392impl EventEmitter<CalendarEvent> for CalendarState {}
393impl Render for CalendarState {
394    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
395        Empty
396    }
397}
398
399/// The semantic kind of a calendar control rendered by [`Calendar`].
400#[derive(Clone, Copy, Debug, PartialEq, Eq)]
401pub enum CalendarItemKind {
402    Previous,
403    MonthToggle,
404    YearToggle,
405    Next,
406    Weekday,
407    Day,
408    Month,
409    Year,
410}
411
412/// State exposed to a calendar item slot. Applications may use it solely to
413/// decorate the unstyled primitive; all interaction remains owned by base.
414///
415/// The fields are private and reached through the methods below, so that a new
416/// one can be added without breaking the item slots.
417#[derive(Clone, Copy, Debug)]
418pub struct CalendarItemState {
419    kind: CalendarItemKind,
420    active: bool,
421    in_range: bool,
422    muted: bool,
423    disabled: bool,
424    today: bool,
425}
426
427impl CalendarItemState {
428    /// Create a state for `kind`, with every flag off.
429    pub fn new(kind: CalendarItemKind) -> Self {
430        Self {
431            kind,
432            active: false,
433            in_range: false,
434            muted: false,
435            disabled: false,
436            today: false,
437        }
438    }
439
440    pub fn active(mut self, active: bool) -> Self {
441        self.active = active;
442        self
443    }
444
445    /// Set whether the item is between the two ends of a range selection.
446    pub fn in_range(mut self, in_range: bool) -> Self {
447        self.in_range = in_range;
448        self
449    }
450
451    /// Set whether the item is shown as secondary, e.g.: a weekday header or a
452    /// day that belongs to the neighboring month.
453    pub fn muted(mut self, muted: bool) -> Self {
454        self.muted = muted;
455        self
456    }
457
458    pub fn disabled(mut self, disabled: bool) -> Self {
459        self.disabled = disabled;
460        self
461    }
462
463    pub fn today(mut self, today: bool) -> Self {
464        self.today = today;
465        self
466    }
467
468    pub fn kind(&self) -> CalendarItemKind {
469        self.kind
470    }
471
472    pub fn is_active(&self) -> bool {
473        self.active
474    }
475
476    pub fn is_in_range(&self) -> bool {
477        self.in_range
478    }
479
480    pub fn is_muted(&self) -> bool {
481        self.muted
482    }
483
484    pub fn is_disabled(&self) -> bool {
485        self.disabled
486    }
487
488    pub fn is_today(&self) -> bool {
489        self.today
490    }
491}
492
493/// An unstyled, pre-wired calendar item passed to the item slot.
494#[derive(IntoElement)]
495pub struct CalendarItem {
496    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
497    state: CalendarItemState,
498    style: StyleRefinement,
499    children: Vec<AnyElement>,
500}
501
502impl CalendarItem {
503    fn new(id: impl Into<ElementId>, state: CalendarItemState) -> Self {
504        Self {
505            base: div().id(id.into()).test_support(),
506            state,
507            style: StyleRefinement::default(),
508            children: vec![],
509        }
510    }
511    // Keep the default visible label available to assistive technology even
512    // when a presentation assigns a role that does not derive a name from children.
513    fn with_label(self, label: SharedString) -> Self {
514        self.aria_label(label.clone()).child(label)
515    }
516
517    pub fn item_state(&self) -> CalendarItemState {
518        self.state
519    }
520
521    /// Remove the default label so a styled facade can provide custom content.
522    pub fn clear_children(mut self) -> Self {
523        self.children.clear();
524        self
525    }
526}
527impl ParentElement for CalendarItem {
528    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
529        self.children.extend(elements);
530    }
531}
532impl Styled for CalendarItem {
533    fn style(&mut self) -> &mut StyleRefinement {
534        &mut self.style
535    }
536}
537impl InteractiveElement for CalendarItem {
538    fn interactivity(&mut self) -> &mut gpui::Interactivity {
539        self.base.interactivity()
540    }
541
542    fn track_focus(mut self, handle: &gpui::FocusHandle) -> Self {
543        self.base = self.base.track_focus(handle);
544        self
545    }
546}
547impl StatefulInteractiveElement for CalendarItem {}
548impl RenderOnce for CalendarItem {
549    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
550        self.base.children(self.children).refine_style(&self.style)
551    }
552}
553
554type ItemRenderer =
555    Rc<dyn Fn(CalendarItem, CalendarItemState, &mut Window, &mut App) -> AnyElement>;
556type Labeler = Rc<dyn Fn(CalendarItemKind, i32) -> SharedString>;
557
558/// Complete unstyled calendar structure and behavior.
559///
560/// Base owns navigation, view switching, grids, disabled/selection state and
561/// click handling. The UI crate only decorates the pre-wired item slot.
562#[derive(IntoElement)]
563pub struct Calendar {
564    id: ElementId,
565    state: Entity<CalendarState>,
566    number_of_months: usize,
567    first_day_of_week: Weekday,
568    style: StyleRefinement,
569    item: ItemRenderer,
570    label: Labeler,
571}
572
573impl Calendar {
574    pub fn new(id: impl Into<ElementId>, state: &Entity<CalendarState>) -> Self {
575        Self {
576            id: id.into(),
577            state: state.clone(),
578            number_of_months: 1,
579            first_day_of_week: Weekday::Sunday,
580            style: StyleRefinement::default(),
581            item: Rc::new(|item, _, _, _| item.into_any_element()),
582            label: Rc::new(|kind, value| match kind {
583                CalendarItemKind::Previous => "‹".into(),
584                CalendarItemKind::Next => "›".into(),
585                CalendarItemKind::Weekday => value.to_string().into(),
586                _ => value.to_string().into(),
587            }),
588        }
589    }
590    pub fn number_of_months(mut self, count: usize) -> Self {
591        self.number_of_months = count.max(1);
592        self
593    }
594    pub fn first_day_of_week(mut self, day: Weekday) -> Self {
595        self.first_day_of_week = day;
596        self
597    }
598    pub fn item(
599        mut self,
600        render: impl Fn(CalendarItem, CalendarItemState, &mut Window, &mut App) -> AnyElement + 'static,
601    ) -> Self {
602        self.item = Rc::new(render);
603        self
604    }
605    pub fn label(
606        mut self,
607        label: impl Fn(CalendarItemKind, i32) -> SharedString + 'static,
608    ) -> Self {
609        self.label = Rc::new(label);
610        self
611    }
612
613    fn render_item(
614        &self,
615        id: impl Into<ElementId>,
616        state: CalendarItemState,
617        value: i32,
618        window: &mut Window,
619        cx: &mut App,
620    ) -> AnyElement {
621        let label = (self.label)(state.kind(), value);
622        (self.item)(
623            CalendarItem::new(id, state).with_label(label),
624            state,
625            window,
626            cx,
627        )
628    }
629}
630impl Styled for Calendar {
631    fn style(&mut self) -> &mut StyleRefinement {
632        &mut self.style
633    }
634}
635
636impl RenderOnce for Calendar {
637    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
638        let count = self.number_of_months;
639        self.state
640            .update(cx, |s, cx| s.set_number_of_months(count, window, cx));
641        let view = self.state.read(cx).view();
642        let mut header = h_flex()
643            .flex_row_dir(cx)
644            .items_center()
645            .justify_between()
646            .child({
647                let st = CalendarItemState::new(CalendarItemKind::Previous).disabled(
648                    view.is_month()
649                        || (view.is_year() && !self.state.read(cx).has_prev_year_page()),
650                );
651                let mut item =
652                    CalendarItem::new("calendar-prev", st).with_label((self.label)(st.kind(), 0));
653                if !st.is_disabled() {
654                    let entity = self.state.clone();
655                    item = item.on_click(move |_, _window, cx| {
656                        entity.update(cx, |s, cx| {
657                            if s.view().is_day() {
658                                s.prev_month();
659                            } else {
660                                s.prev_year_page();
661                            }
662                            cx.notify();
663                        })
664                    });
665                }
666                (self.item)(item, st, window, cx)
667            });
668        if count == 1 {
669            let (month, year) = {
670                let s = self.state.read(cx);
671                (s.current_month() as i32, s.current_year())
672            };
673            for (kind, value, active) in [
674                (CalendarItemKind::MonthToggle, month, view.is_month()),
675                (CalendarItemKind::YearToggle, year, view.is_year()),
676            ] {
677                let st = CalendarItemState::new(kind).active(active);
678                let entity = self.state.clone();
679                let mut item = CalendarItem::new(format!("calendar-{kind:?}"), st)
680                    .with_label((self.label)(kind, value));
681                item = item.on_click(move |_, _, cx| {
682                    entity.update(cx, |s, cx| {
683                        s.set_view(
684                            if s.view()
685                                == match kind {
686                                    CalendarItemKind::MonthToggle => CalendarView::Month,
687                                    _ => CalendarView::Year,
688                                }
689                            {
690                                CalendarView::Day
691                            } else {
692                                match kind {
693                                    CalendarItemKind::MonthToggle => CalendarView::Month,
694                                    _ => CalendarView::Year,
695                                }
696                            },
697                        );
698                        cx.notify();
699                    })
700                });
701                header = header.child((self.item)(item, st, window, cx));
702            }
703        } else {
704            for offset in 0..count {
705                let (y, m) = self.state.read(cx).offset_year_month(offset);
706                header = header.child(
707                    div().text_sm().font_medium().child(
708                        v_flex()
709                            .items_center()
710                            .child((self.label)(CalendarItemKind::MonthToggle, m as i32))
711                            .child(y.to_string()),
712                    ),
713                );
714            }
715        }
716        header = header.child({
717            let st = CalendarItemState::new(CalendarItemKind::Next).disabled(
718                view.is_month() || (view.is_year() && !self.state.read(cx).has_next_year_page()),
719            );
720            let mut item =
721                CalendarItem::new("calendar-next", st).with_label((self.label)(st.kind(), 0));
722            if !st.is_disabled() {
723                let entity = self.state.clone();
724                item = item.on_click(move |_, _, cx| {
725                    entity.update(cx, |s, cx| {
726                        if s.view().is_day() {
727                            s.next_month()
728                        } else {
729                            s.next_year_page();
730                        }
731                        cx.notify();
732                    })
733                });
734            }
735            (self.item)(item, st, window, cx)
736        });
737
738        let mut body = match picker_grid_layout(view) {
739            None => h_flex().flex_row_dir(cx).justify_around(),
740            Some((columns, horizontal_gap)) => {
741                div().grid().grid_cols(columns).gap_x(px(horizontal_gap))
742            }
743        };
744        if view.is_day() {
745            for offset in 0..count {
746                let (year, month_number) = self.state.read(cx).offset_year_month(offset);
747                let weeks = days_in_month(year, month_number, self.first_day_of_week);
748                let mut month = v_flex();
749                let mut header_row = h_flex().flex_row_dir(cx);
750                for weekday in 0..7 {
751                    let st = CalendarItemState::new(CalendarItemKind::Weekday)
752                        .muted(true)
753                        .disabled(true);
754                    header_row = header_row.child(self.render_item(
755                        format!("weekday-{offset}-{weekday}"),
756                        st,
757                        (weekday + self.first_day_of_week.to_sunday_zero_offset() as i32) % 7,
758                        window,
759                        cx,
760                    ));
761                }
762                month = month.child(header_row);
763                for (week_index, week) in weeks.iter().enumerate() {
764                    let mut week_row = h_flex().flex_row_dir(cx);
765                    for date in week {
766                        let date = *date;
767                        let st = {
768                            let s = self.state.read(cx);
769                            let (_, m) = s.offset_year_month(offset);
770                            let disabled =
771                                s.disabled_matcher_ref().is_some_and(|x| x.matched(&date));
772                            CalendarItemState::new(CalendarItemKind::Day)
773                                .active(s.date().is_active(&date))
774                                .in_range(s.date().is_in_range(&date))
775                                .muted(date.month() as u32 != m || disabled)
776                                .disabled(disabled)
777                                .today(date == s.today())
778                        };
779                        let mut item =
780                            CalendarItem::new(format!("calendar-{date}-{offset}-{week_index}"), st)
781                                .with_label((self.label)(st.kind(), date.day() as i32))
782                                .aria_label(date.to_string());
783                        if !st.is_disabled() {
784                            let entity = self.state.clone();
785                            item = item.on_click(move |_, _, cx| {
786                                entity.update(cx, |s, cx| {
787                                    s.activate_date(date, cx);
788                                })
789                            });
790                        }
791                        week_row = week_row.child((self.item)(item, st, window, cx));
792                    }
793                    month = month.child(week_row);
794                }
795                body = body.child(month);
796            }
797        } else if view.is_month() {
798            let current = self.state.read(cx).current_month();
799            for month in 1..=12u8 {
800                let st = CalendarItemState::new(CalendarItemKind::Month).active(month == current);
801                let entity = self.state.clone();
802                let item = CalendarItem::new(format!("calendar-month-{month}"), st)
803                    .with_label((self.label)(st.kind(), month as i32))
804                    .on_click(move |_, _, cx| {
805                        entity.update(cx, |s, cx| {
806                            s.select_month(month);
807                            cx.notify();
808                        })
809                    });
810                body = body.child((self.item)(item, st, window, cx));
811            }
812        } else {
813            let current = self.state.read(cx).current_year();
814            let years = self.state.read(cx).years_on_page().to_vec();
815            for year in years {
816                let st = CalendarItemState::new(CalendarItemKind::Year).active(year == current);
817                let entity = self.state.clone();
818                let item = CalendarItem::new(format!("calendar-year-{year}"), st)
819                    .with_label((self.label)(st.kind(), year))
820                    .on_click(move |_, _, cx| {
821                        entity.update(cx, |s, cx| {
822                            s.select_year(year);
823                            cx.notify();
824                        })
825                    });
826                body = body.child((self.item)(item, st, window, cx));
827            }
828        }
829        v_flex()
830            .id(self.id)
831            .track_focus(&self.state.read(cx).focus_handle)
832            .child(header)
833            .child(body)
834            .refine_style(&self.style)
835    }
836}
837
838fn days_in_month(year: i32, month: u32, first_day: Weekday) -> Vec<Vec<civil::Date>> {
839    let total = year as i64 * 12 + month as i64 - 1;
840    let year = total.div_euclid(12) as i16;
841    let month = total.rem_euclid(12) as i8 + 1;
842    let first = civil::date(year, month, 1);
843    let offset = first.weekday().since(first_day);
844    let start = first - jiff::Span::new().days(offset);
845    let count = (first.days_in_month() + offset) as usize;
846    start
847        .series(jiff::Span::new().days(1))
848        .take(count.div_ceil(7) * 7)
849        .collect::<Vec<_>>()
850        .chunks(7)
851        .map(<[_]>::to_vec)
852        .collect()
853}
854
855#[cfg(test)]
856mod tests {
857    use std::{cell::RefCell, rc::Rc};
858
859    use gpui::{AppContext as _, Context, Entity, IntoElement, Render, Subscription, Window};
860
861    use super::*;
862
863    #[gpui::test]
864    fn calendar_items_expose_names_in_every_view(cx: &mut gpui::TestAppContext) {
865        use gpui::{Element as _, accesskit};
866        struct Names {
867            calendar: Entity<CalendarState>,
868            labels: Rc<RefCell<Vec<(CalendarItemKind, String)>>>,
869        }
870        impl Render for Names {
871            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
872                let labels = self.labels.clone();
873                labels.borrow_mut().clear();
874                Calendar::new("named-calendar", &self.calendar).item(move |item, state, _, _| {
875                    let mut node = accesskit::Node::new(accesskit::Role::Button);
876                    item.base.write_a11y_info(&mut node);
877                    labels
878                        .borrow_mut()
879                        .push((state.kind(), node.label().unwrap_or("").to_string()));
880                    item.into_any_element()
881                })
882            }
883        }
884        let (view, cx) = cx.add_window_view(|window, cx| Names {
885            calendar: cx.new(|cx| CalendarState::new(window, cx)),
886            labels: Rc::new(RefCell::new(Vec::new())),
887        });
888        for mode in [CalendarView::Day, CalendarView::Month, CalendarView::Year] {
889            cx.update(|window, cx| {
890                view.read(cx).calendar.clone().update(cx, |state, cx| {
891                    state.apply_date(Date::Single(Some(civil::date(2026, 9, 7))));
892                    state.set_view(mode);
893                    cx.notify();
894                });
895                window.draw(cx).clear(cx);
896                let labels = view.read(cx).labels.borrow();
897                assert!(!labels.is_empty());
898                for (kind, label) in labels.iter() {
899                    assert!(!label.is_empty(), "missing name for {kind:?}");
900                }
901                if mode.is_day() {
902                    assert!(labels.iter().any(
903                        |(kind, label)| *kind == CalendarItemKind::Day && label == "2026-09-07"
904                    ));
905                }
906            });
907        }
908    }
909
910    struct EventHarness {
911        calendar: Entity<CalendarState>,
912        events: Rc<RefCell<Vec<Date>>>,
913        _subscription: Option<Subscription>,
914    }
915    impl EventHarness {
916        fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
917            let calendar = cx.new(|cx| CalendarState::new(window, cx));
918            let events = Rc::new(RefCell::new(Vec::new()));
919            let mut this = Self {
920                calendar: calendar.clone(),
921                events: events.clone(),
922                _subscription: None,
923            };
924            this._subscription = Some(cx.subscribe(&calendar, move |_, _, event, _| {
925                let CalendarEvent::Selected(date) = event;
926                events.borrow_mut().push(*date);
927            }));
928            this
929        }
930    }
931    impl Render for EventHarness {
932        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
933            Empty
934        }
935    }
936    fn state(cx: &mut gpui::TestAppContext, date: Date) -> gpui::Entity<CalendarState> {
937        let (state, _) = cx.add_window_view(CalendarState::new);
938        state.update(cx, |state, _| {
939            state.date = date;
940        });
941        state
942    }
943    #[gpui::test]
944    fn range_selection_restarts_and_completes(cx: &mut gpui::TestAppContext) {
945        let s = state(cx, Date::Range(None, None));
946        let a = civil::date(2025, 2, 10);
947        let b = civil::date(2025, 2, 12);
948        s.update(cx, |s, _| {
949            assert!(!s.select_date(a));
950            assert!(s.select_date(b));
951        });
952        assert_eq!(
953            s.read_with(cx, |s, _| s.date()),
954            Date::Range(Some(a), Some(b))
955        );
956        s.update(cx, |s, _| assert!(!s.select_date(a)));
957        assert_eq!(s.read_with(cx, |s, _| s.date()), Date::Range(Some(a), None));
958    }
959    #[gpui::test]
960    fn disabled_date_is_rejected(cx: &mut gpui::TestAppContext) {
961        let s = state(cx, Date::Single(None));
962        s.update(cx, |s, _| {
963            s.disabled_matcher = Some(Rc::new(Matcher::range(
964                Some(civil::date(2025, 1, 1)),
965                Some(civil::date(2025, 1, 31)),
966            )))
967        });
968        s.update(cx, |s, _| assert!(!s.select_date(civil::date(2025, 1, 2))));
969    }
970    #[gpui::test]
971    fn month_navigation_crosses_year(cx: &mut gpui::TestAppContext) {
972        let s = state(cx, Date::Single(Some(civil::date(2025, 1, 1))));
973        s.update(cx, |s, _| {
974            s.apply_date(Date::Single(Some(civil::date(2025, 1, 1))));
975            s.prev_month();
976        });
977        assert_eq!(
978            s.read_with(cx, |s, _| (s.current_year(), s.current_month())),
979            (2024, 12)
980        );
981        s.update(cx, |s, _| s.next_month());
982        assert_eq!(
983            s.read_with(cx, |s, _| (s.current_year(), s.current_month())),
984            (2025, 1)
985        );
986    }
987
988    #[gpui::test]
989    fn six_week_month_is_not_truncated(cx: &mut gpui::TestAppContext) {
990        let s = state(cx, Date::Single(Some(civil::date(2025, 8, 1))));
991        s.update(cx, |s, _| {
992            s.apply_date(Date::Single(Some(civil::date(2025, 8, 1))));
993            assert_eq!(s.month_days().len(), 1);
994            assert_eq!(s.month_days()[0].len(), 6);
995            assert_eq!(s.days().len(), 6);
996            assert_eq!(s.month_days()[0][5][0].day(), 31);
997        });
998    }
999
1000    #[gpui::test]
1001    fn day_month_and_year_views_have_complete_transitions(cx: &mut gpui::TestAppContext) {
1002        let s = state(cx, Date::Single(None));
1003        s.update(cx, |s, _| {
1004            assert_eq!(s.view(), CalendarView::Day);
1005            s.set_view(CalendarView::Month);
1006            s.select_month(11);
1007            assert_eq!((s.view(), s.current_month()), (CalendarView::Day, 11));
1008            s.set_view(CalendarView::Year);
1009            s.select_year(2032);
1010            assert_eq!((s.view(), s.current_year()), (CalendarView::Day, 2032));
1011        });
1012    }
1013
1014    #[test]
1015    fn picker_views_use_stable_grid_layouts() {
1016        assert_eq!(picker_grid_layout(CalendarView::Month), Some((3, 4.)));
1017        assert_eq!(picker_grid_layout(CalendarView::Year), Some((5, 4.)));
1018        assert_eq!(picker_grid_layout(CalendarView::Day), None);
1019    }
1020
1021    #[gpui::test]
1022    fn year_page_navigation_respects_both_bounds(cx: &mut gpui::TestAppContext) {
1023        let s = state(cx, Date::Single(None));
1024        s.update(cx, |s, _| {
1025            s.apply_year_range((2000, 2041));
1026            while s.prev_year_page() {}
1027            assert!(!s.has_prev_year_page());
1028            assert!(!s.prev_year_page());
1029            assert!(s.next_year_page());
1030            while s.next_year_page() {}
1031            assert!(!s.has_next_year_page());
1032            assert!(!s.next_year_page());
1033        });
1034    }
1035
1036    #[gpui::test]
1037    fn activation_emits_only_for_complete_enabled_values(cx: &mut gpui::TestAppContext) {
1038        let (harness, _) = cx.add_window_view(EventHarness::new);
1039        let s = harness.read_with(cx, |h, _| h.calendar.clone());
1040        s.update(cx, |s, _| s.date = Date::Range(None, None));
1041        let start = civil::date(2025, 4, 4);
1042        let end = civil::date(2025, 4, 8);
1043        s.update(cx, |s, cx| {
1044            assert!(!s.activate_date(start, cx));
1045            assert!(s.activate_date(end, cx));
1046            assert_eq!(s.date(), Date::Range(Some(start), Some(end)));
1047            s.set_disabled_matcher_shared(Some(Rc::new(Matcher::custom(move |d| *d == start))));
1048            assert!(!s.activate_date(start, cx));
1049            assert_eq!(s.date(), Date::Range(Some(start), Some(end)));
1050        });
1051        assert_eq!(
1052            harness.read_with(cx, |h, _| h.events.borrow().clone()),
1053            vec![Date::Range(Some(start), Some(end))]
1054        );
1055
1056        s.update(cx, |s, cx| {
1057            s.date = Date::Single(None);
1058            assert!(s.activate_date(end, cx));
1059            assert_eq!(s.date(), Date::Single(Some(end)));
1060        });
1061        assert_eq!(
1062            harness.read_with(cx, |h, _| h.events.borrow().clone()),
1063            vec![Date::Range(Some(start), Some(end)), Date::Single(Some(end))]
1064        );
1065    }
1066}