1use gpui::{
4 AnyElement, App, Context, ElementId, Entity, EntityId, EventEmitter, FocusHandle,
5 InteractiveElement, Interactivity, IntoElement, KeyBinding, ParentElement, RenderOnce, Role,
6 SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Window,
7 actions, canvas, div, prelude::FluentBuilder as _,
8};
9use jiff::ToSpan as _;
10pub use jiff::civil::{Date, Weekday};
11
12use crate::{
13 Button, ButtonStyles, Direction, TestSupportExt as _,
14 a11y_disabled::A11yDisabledExt as _,
15 actions::{
16 SelectDown, SelectFirst, SelectLast, SelectLeft, SelectPageDown, SelectPageUp, SelectRight,
17 SelectUp,
18 },
19};
20
21actions!(calendar, [PreviousYear, NextYear]);
22
23const CONTEXT: &str = "Calendar";
24const DAY_COUNT: usize = 42;
25const MAX_YEAR: i16 = 9998;
28
29pub(crate) fn init(cx: &mut App) {
30 cx.bind_keys([
31 KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
32 KeyBinding::new("right", SelectRight, Some(CONTEXT)),
33 KeyBinding::new("up", SelectUp, Some(CONTEXT)),
34 KeyBinding::new("down", SelectDown, Some(CONTEXT)),
35 KeyBinding::new("home", SelectFirst, Some(CONTEXT)),
36 KeyBinding::new("end", SelectLast, Some(CONTEXT)),
37 KeyBinding::new("pageup", SelectPageUp, Some(CONTEXT)),
38 KeyBinding::new("pagedown", SelectPageDown, Some(CONTEXT)),
39 KeyBinding::new("shift-pageup", PreviousYear, Some(CONTEXT)),
40 KeyBinding::new("shift-pagedown", NextYear, Some(CONTEXT)),
41 ]);
42}
43
44#[derive(Clone, Debug, Eq, PartialEq)]
51pub enum CalendarSelection {
52 Single(Option<Date>),
53 Multiple(Vec<Date>),
54 Range {
55 start: Option<Date>,
56 end: Option<Date>,
57 },
58}
59
60impl CalendarSelection {
61 pub fn first_date(&self) -> Option<Date> {
63 match self {
64 Self::Single(date) => *date,
65 Self::Multiple(dates) => dates.iter().copied().min(),
66 Self::Range { start, .. } => *start,
67 }
68 }
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
73pub enum CalendarEvent {
74 Change(CalendarSelection),
75}
76
77#[derive(Clone)]
80pub(crate) struct CalendarActivation {
81 pub(crate) selection: CalendarSelection,
82 pub(crate) changed: bool,
83}
84
85pub struct CalendarState {
97 month: Date,
98 cursor: Date,
99 selection: CalendarSelection,
100 minimum: Date,
101 maximum: Date,
102 first_weekday: Weekday,
103 disabled_dates: Option<Box<dyn Fn(Date) -> bool>>,
104 disabled: bool,
105 direction: Direction,
106 focus: [FocusHandle; DAY_COUNT],
107 focus_subscriptions: Vec<Subscription>,
108 reveal: Option<Date>,
109}
110
111impl CalendarState {
112 pub fn new(initial_date: Date, cx: &mut Context<Self>) -> Self {
117 assert!(
118 (1..=MAX_YEAR).contains(&initial_date.year()),
119 "Calendar dates must be in years 1..=9998"
120 );
121 Self {
122 month: initial_date.first_of_month(),
123 cursor: initial_date,
124 selection: CalendarSelection::Single(None),
125 minimum: Date::constant(1, 1, 1),
126 maximum: Date::constant(MAX_YEAR, 12, 31),
127 first_weekday: Weekday::Monday,
128 disabled_dates: None,
129 disabled: false,
130 direction: Direction::Ltr,
131 focus: std::array::from_fn(|_| cx.focus_handle()),
132 focus_subscriptions: Vec::new(),
133 reveal: None,
134 }
135 }
136
137 pub fn bounds(mut self, minimum: Date, maximum: Date) -> Self {
144 assert!(
145 minimum <= maximum && minimum.year() >= 1 && maximum.year() <= MAX_YEAR,
146 "Calendar bounds must be ordered and within years 1..=9998"
147 );
148 self.minimum = minimum;
149 self.maximum = maximum;
150 self.cursor = self.cursor.clamp(minimum, maximum);
151 self.month = self.cursor.first_of_month();
152 self.selection = match self.selection {
153 CalendarSelection::Single(date) => {
154 CalendarSelection::Single(date.filter(|date| (minimum..=maximum).contains(date)))
155 }
156 CalendarSelection::Multiple(dates) => CalendarSelection::Multiple(
157 dates
158 .into_iter()
159 .filter(|date| (minimum..=maximum).contains(date))
160 .collect(),
161 ),
162 CalendarSelection::Range { start, end } => {
163 if start.is_some_and(|date| !(minimum..=maximum).contains(&date))
164 || end.is_some_and(|date| !(minimum..=maximum).contains(&date))
165 {
166 CalendarSelection::Range {
167 start: None,
168 end: None,
169 }
170 } else {
171 CalendarSelection::Range { start, end }
172 }
173 }
174 };
175 self
176 }
177
178 pub fn week_starts_on(mut self, weekday: Weekday) -> Self {
181 self.first_weekday = weekday;
182 self
183 }
184
185 pub fn disabled_dates(mut self, predicate: impl Fn(Date) -> bool + 'static) -> Self {
193 self.disabled_dates = Some(Box::new(predicate));
194 self.selection = match self.selection.clone() {
195 CalendarSelection::Single(date) => {
196 CalendarSelection::Single(date.filter(|date| self.date_is_selectable(*date)))
197 }
198 CalendarSelection::Multiple(dates) => CalendarSelection::Multiple(
199 dates
200 .into_iter()
201 .filter(|date| self.date_is_selectable(*date))
202 .collect(),
203 ),
204 selection @ CalendarSelection::Range { .. } => self
205 .normalized_selection(selection)
206 .unwrap_or(CalendarSelection::Range {
207 start: None,
208 end: None,
209 }),
210 };
211 self
212 }
213
214 pub fn default_selection(mut self, selection: CalendarSelection) -> Self {
222 self.selection = self
223 .normalized_selection(selection)
224 .expect("Calendar default_selection must be ordered and selectable inside its bounds");
225 if let Some(date) = self.selection.first_date() {
226 self.cursor = date;
227 self.month = date.first_of_month();
228 }
229 self
230 }
231
232 pub fn focused_date(&self) -> Date {
233 self.cursor
234 }
235
236 pub fn selection(&self) -> &CalendarSelection {
237 &self.selection
238 }
239
240 pub fn is_selected(&self, date: Date) -> bool {
242 match &self.selection {
243 CalendarSelection::Single(selected) => *selected == Some(date),
244 CalendarSelection::Multiple(dates) => dates.binary_search(&date).is_ok(),
245 CalendarSelection::Range {
246 start: Some(start),
247 end,
248 } => (*start..=end.unwrap_or(*start)).contains(&date),
249 CalendarSelection::Range { start: None, .. } => false,
250 }
251 }
252
253 pub fn month(&self) -> Date {
255 self.month
256 }
257
258 pub fn minimum(&self) -> Date {
259 self.minimum
260 }
261
262 pub fn maximum(&self) -> Date {
263 self.maximum
264 }
265
266 pub fn first_weekday(&self) -> Weekday {
267 self.first_weekday
268 }
269
270 pub fn weekdays(&self) -> [Weekday; 7] {
272 let mut weekday = self.first_weekday;
273 std::array::from_fn(|_| {
274 let current = weekday;
275 weekday = weekday.next();
276 current
277 })
278 }
279
280 pub fn is_disabled(&self) -> bool {
281 self.disabled
282 }
283
284 pub fn is_date_disabled(&self, date: Date) -> bool {
285 self.disabled || !self.date_is_selectable(date)
286 }
287
288 pub fn days(&self) -> [Date; DAY_COUNT] {
292 let first = self.grid_start();
293 std::array::from_fn(|index| first + (index as i64).days())
294 }
295
296 pub fn focus_handle(&self) -> &FocusHandle {
299 &self.focus[self.index_of(self.cursor)]
300 }
301
302 pub fn can_previous_month(&self) -> bool {
303 !self.disabled && self.month() > self.minimum.first_of_month()
304 }
305
306 pub fn can_next_month(&self) -> bool {
307 !self.disabled && self.month() < self.maximum.first_of_month()
308 }
309
310 pub fn previous_month(&mut self, window: &mut Window, cx: &mut Context<Self>) {
313 if self.can_previous_month() {
314 self.display_month(self.month - 1.month(), window, cx);
315 }
316 }
317
318 pub fn next_month(&mut self, window: &mut Window, cx: &mut Context<Self>) {
321 if self.can_next_month() {
322 self.display_month(self.month + 1.month(), window, cx);
323 }
324 }
325
326 pub fn display_month(&mut self, month: Date, window: &mut Window, cx: &mut Context<Self>) {
331 if self.disabled {
332 return;
333 }
334 let date = month
335 .with()
336 .day(self.cursor.day().min(month.days_in_month()))
337 .build()
338 .expect("the day is clamped to the month's length");
339 self.set_cursor(date, self.focused_index(window).is_some(), window, cx);
340 }
341
342 pub fn set_selection(
347 &mut self,
348 selection: CalendarSelection,
349 window: &mut Window,
350 cx: &mut Context<Self>,
351 ) -> bool {
352 let Some(selection) = self.normalized_selection(selection) else {
353 return false;
354 };
355 let changed = self.selection != selection;
356 self.selection = selection;
357 if let Some(date) = self.selection.first_date() {
358 let focused = self.focused_index(window).is_some();
359 self.set_cursor(date, focused, window, cx);
360 }
361 if changed {
362 cx.notify();
363 window.refresh();
364 }
365 true
366 }
367
368 pub(crate) fn normalized_selection(
369 &self,
370 selection: CalendarSelection,
371 ) -> Option<CalendarSelection> {
372 let selectable = |date: &Date| self.date_is_selectable(*date);
373 match selection {
374 CalendarSelection::Single(date) => (!date.is_some_and(|date| !selectable(&date)))
375 .then_some(CalendarSelection::Single(date)),
376 CalendarSelection::Multiple(mut dates) => {
377 if !dates.iter().all(selectable) {
378 return None;
379 }
380 dates.sort_unstable();
381 dates.dedup();
382 Some(CalendarSelection::Multiple(dates))
383 }
384 CalendarSelection::Range { start, end } => {
385 if start.is_some_and(|date| !selectable(&date))
386 || end.is_some_and(|date| !selectable(&date))
387 || matches!((start, end), (None, Some(_)))
388 || matches!((start, end), (Some(start), Some(end)) if start > end)
389 {
390 return None;
391 }
392 Some(CalendarSelection::Range { start, end })
393 }
394 }
395 }
396
397 pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
400 if self.disabled != disabled {
401 self.disabled = disabled;
402 cx.notify();
403 window.refresh();
404 }
405 }
406
407 fn grid_start(&self) -> Date {
408 let first = self.month();
409 first - i64::from(self.weekday_offset(first)).days()
410 }
411
412 fn weekday_offset(&self, date: Date) -> i8 {
413 self.first_weekday.until(date.weekday())
414 }
415
416 fn date_is_selectable(&self, date: Date) -> bool {
417 (self.minimum..=self.maximum).contains(&date)
418 && !self
419 .disabled_dates
420 .as_ref()
421 .is_some_and(|predicate| predicate(date))
422 }
423
424 fn index_of(&self, date: Date) -> usize {
425 let index = i64::from((date - self.grid_start()).get_days());
426 assert!(
427 (0..DAY_COUNT as i64).contains(&index),
428 "CalendarDay date must belong to CalendarState::days()"
429 );
430 index as usize
431 }
432
433 fn focused_index(&self, window: &Window) -> Option<usize> {
434 self.focus.iter().position(|focus| focus.is_focused(window))
435 }
436
437 fn bind_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
438 if !self.focus_subscriptions.is_empty() {
439 return;
440 }
441 self.focus_subscriptions = self
442 .focus
443 .iter()
444 .enumerate()
445 .map(|(index, focus)| {
446 cx.on_focus(focus, window, move |_, window, cx| {
447 cx.defer_in(window, move |state, window, cx| {
448 if state.focus[index].is_focused(window) {
449 let date = state.days()[index];
450 if !state.disabled && (state.minimum..=state.maximum).contains(&date) {
451 state.cursor = date;
455 state.reveal = Some(date);
456 cx.notify();
457 window.refresh();
458 }
459 }
460 });
461 })
462 })
463 .collect();
464 }
465
466 fn set_cursor(&mut self, date: Date, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
467 let date = date.clamp(self.minimum, self.maximum);
468 let month = date.first_of_month();
469 let changed = self.cursor != date || self.month != month;
470 self.cursor = date;
471 self.month = month;
472 if focus {
473 if changed || !self.focus_handle().is_focused(window) {
474 self.reveal = Some(date);
475 }
476 self.focus_handle().focus(window, cx);
477 }
478 if changed {
479 cx.notify();
480 window.refresh();
481 }
482 }
483
484 fn select(&mut self, date: Date, window: &mut Window, cx: &mut Context<Self>) {
485 if self.is_date_disabled(date) {
486 return;
487 }
488 self.set_cursor(date, true, window, cx);
489 let selection = match &self.selection {
490 CalendarSelection::Single(_) => CalendarSelection::Single(Some(date)),
491 CalendarSelection::Multiple(dates) => {
492 let mut dates = dates.clone();
493 match dates.binary_search(&date) {
494 Ok(index) => {
495 dates.remove(index);
496 }
497 Err(index) => dates.insert(index, date),
498 }
499 CalendarSelection::Multiple(dates)
500 }
501 CalendarSelection::Range {
502 start: Some(start),
503 end: None,
504 } => CalendarSelection::Range {
505 start: Some((*start).min(date)),
506 end: Some((*start).max(date)),
507 },
508 CalendarSelection::Range { .. } => CalendarSelection::Range {
509 start: Some(date),
510 end: None,
511 },
512 };
513 let changed = self.selection != selection;
514 if changed {
515 self.selection = selection;
516 cx.emit(CalendarEvent::Change(self.selection.clone()));
517 cx.notify();
518 window.refresh();
519 }
520 cx.emit(CalendarActivation {
521 selection: self.selection.clone(),
522 changed,
523 });
524 }
525
526 fn move_days(&mut self, days: i64, window: &mut Window, cx: &mut Context<Self>) {
527 let date = self.cursor + days.days();
529 self.set_cursor(date, true, window, cx);
530 }
531
532 fn move_months(&mut self, months: i32, window: &mut Window, cx: &mut Context<Self>) {
533 let date = self.cursor + months.months();
535 self.set_cursor(date, self.focused_index(window).is_some(), window, cx);
536 }
537
538 fn handles_navigation(&self, window: &Window, cx: &mut Context<Self>) -> bool {
539 if self.disabled || self.focused_index(window).is_none() {
540 cx.propagate();
541 false
542 } else {
543 true
544 }
545 }
546}
547
548impl EventEmitter<CalendarEvent> for CalendarState {}
549impl EventEmitter<CalendarActivation> for CalendarState {}
550
551#[derive(IntoElement)]
565pub struct Calendar {
566 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
567 state: Entity<CalendarState>,
568 label: Option<SharedString>,
569 direction: Option<Direction>,
570}
571
572impl Calendar {
573 pub fn new(id: impl Into<ElementId>, state: &Entity<CalendarState>) -> Self {
574 Self {
575 base: div().id(id).test_support(),
576 state: state.clone(),
577 label: None,
578 direction: None,
579 }
580 }
581
582 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
583 self.label = Some(label.into());
584 self
585 }
586
587 pub fn direction(mut self, direction: Direction) -> Self {
590 self.direction = Some(direction);
591 self
592 }
593}
594
595impl Styled for Calendar {
596 fn style(&mut self) -> &mut StyleRefinement {
597 self.base.style()
598 }
599}
600
601impl ParentElement for Calendar {
602 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
603 self.base.extend(elements);
604 }
605}
606
607impl InteractiveElement for Calendar {
608 fn interactivity(&mut self) -> &mut Interactivity {
609 self.base.interactivity()
610 }
611}
612
613impl StatefulInteractiveElement for Calendar {}
614
615impl RenderOnce for Calendar {
616 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
617 let direction = self.direction.unwrap_or_else(|| Direction::current(cx));
618 self.state.update(cx, |state, cx| {
619 state.direction = direction;
620 state.bind_focus(window, cx);
621 });
622 let disabled = self.state.read(cx).disabled;
623 let multiselectable = !matches!(
624 self.state.read(cx).selection(),
625 CalendarSelection::Single(_)
626 );
627 let left = self.state.clone();
628 let right = self.state.clone();
629 let up = self.state.clone();
630 let down = self.state.clone();
631 let first = self.state.clone();
632 let last = self.state.clone();
633 let previous = self.state.clone();
634 let next = self.state.clone();
635 let previous_year = self.state.clone();
636 let next_year = self.state;
637 self.base
638 .role(Role::Grid)
639 .aria_row_count(7)
640 .aria_column_count(7)
641 .key_context(CONTEXT)
642 .when_some(self.label, |this, label| this.aria_label(label))
643 .on_action(move |_: &SelectLeft, window, cx| {
644 left.update(cx, |state, cx| {
645 if state.handles_navigation(window, cx) {
646 state.move_days(if direction.is_rtl() { 1 } else { -1 }, window, cx);
647 }
648 });
649 })
650 .on_action(move |_: &SelectRight, window, cx| {
651 right.update(cx, |state, cx| {
652 if state.handles_navigation(window, cx) {
653 state.move_days(if direction.is_rtl() { -1 } else { 1 }, window, cx);
654 }
655 });
656 })
657 .on_action(move |_: &SelectUp, window, cx| {
658 up.update(cx, |state, cx| {
659 if state.handles_navigation(window, cx) {
660 state.move_days(-7, window, cx);
661 }
662 });
663 })
664 .on_action(move |_: &SelectDown, window, cx| {
665 down.update(cx, |state, cx| {
666 if state.handles_navigation(window, cx) {
667 state.move_days(7, window, cx);
668 }
669 });
670 })
671 .on_action(move |_: &SelectFirst, window, cx| {
672 first.update(cx, |state, cx| {
673 if state.handles_navigation(window, cx) {
674 state.move_days(-(state.weekday_offset(state.cursor) as i64), window, cx);
675 }
676 });
677 })
678 .on_action(move |_: &SelectLast, window, cx| {
679 last.update(cx, |state, cx| {
680 if state.handles_navigation(window, cx) {
681 state.move_days(6 - state.weekday_offset(state.cursor) as i64, window, cx);
682 }
683 });
684 })
685 .on_action(move |_: &SelectPageUp, window, cx| {
686 previous.update(cx, |state, cx| {
687 if state.handles_navigation(window, cx) {
688 state.move_months(-1, window, cx);
689 }
690 });
691 })
692 .on_action(move |_: &SelectPageDown, window, cx| {
693 next.update(cx, |state, cx| {
694 if state.handles_navigation(window, cx) {
695 state.move_months(1, window, cx);
696 }
697 });
698 })
699 .on_action(move |_: &PreviousYear, window, cx| {
700 previous_year.update(cx, |state, cx| {
701 if state.handles_navigation(window, cx) {
702 state.move_months(-12, window, cx);
703 }
704 });
705 })
706 .on_action(move |_: &NextYear, window, cx| {
707 next_year.update(cx, |state, cx| {
708 if state.handles_navigation(window, cx) {
709 state.move_months(12, window, cx);
710 }
711 });
712 })
713 .a11y_selection(disabled, multiselectable)
714 }
715}
716
717fn day_id(state: EntityId, date: Date) -> ElementId {
718 (ElementId::from(("calendar-day", state)), date.to_string()).into()
719}
720
721#[derive(IntoElement)]
726pub struct CalendarDay {
727 button: Button,
728 state: Entity<CalendarState>,
729 date: Date,
730 label: Option<SharedString>,
731}
732
733impl CalendarDay {
734 pub fn new(state: &Entity<CalendarState>, date: Date) -> Self {
736 Self {
737 button: Button::new(day_id(state.entity_id(), date)),
738 state: state.clone(),
739 date,
740 label: None,
741 }
742 }
743
744 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
745 self.label = Some(label.into());
746 self
747 }
748
749 pub fn styles(mut self, build: impl FnOnce(ButtonStyles) -> ButtonStyles) -> Self {
750 self.button = self.button.styles(build);
751 self
752 }
753}
754
755impl Styled for CalendarDay {
756 fn style(&mut self) -> &mut StyleRefinement {
757 self.button.style()
758 }
759}
760
761impl ParentElement for CalendarDay {
762 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
763 self.button.extend(elements);
764 }
765}
766
767impl InteractiveElement for CalendarDay {
768 fn interactivity(&mut self) -> &mut Interactivity {
769 self.button.interactivity()
770 }
771
772 crate::button::forward_hover_styles!(button);
773}
774
775impl StatefulInteractiveElement for CalendarDay {
776 crate::button::forward_active_styles!(button);
777}
778
779impl RenderOnce for CalendarDay {
780 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
781 let model = self.state.read(cx);
782 let index = model.index_of(self.date);
783 let disabled = model.is_date_disabled(self.date);
784 let disabled_focusable =
785 !model.disabled && (model.minimum..=model.maximum).contains(&self.date);
786 let selected = model.is_selected(self.date);
787 let focus = model.focus[index].clone();
788 let tab_stop = model.cursor == self.date;
789 let column = if model.direction.is_rtl() {
790 6 - index % 7
791 } else {
792 index % 7
793 };
794 let date = self.date;
795 let reveal_state = self.state.clone();
796 let state = self.state;
797 self.button
798 .role(Role::GridCell)
799 .accessibility_label(self.label.unwrap_or_else(|| date.to_string().into()))
800 .aria_selected(selected)
801 .aria_row_index(index / 7 + 1)
802 .aria_column_index(column)
803 .selected(selected)
804 .disabled(disabled)
805 .focus_when_disabled(disabled_focusable)
806 .track_focus(&focus)
807 .tab_stop(tab_stop)
808 .when(tab_stop, |button| {
809 button.child(
810 canvas(
813 move |bounds, window, cx| {
814 reveal_state.update(cx, |state, _| {
815 if state.reveal == Some(date) {
816 state.reveal = None;
817 if state.cursor == date
818 && state.focus_handle().is_focused(window)
819 {
820 window.request_autoscroll(bounds);
821 }
822 }
823 });
824 },
825 |_, _, _, _| {},
826 )
827 .absolute()
828 .top_0()
829 .left_0()
830 .size_full(),
831 )
832 })
833 .on_click(move |_, window, cx| {
834 state.update(cx, |state, cx| state.select(date, window, cx));
835 })
836 .render(window, cx)
837 }
838}
839
840#[cfg(test)]
841mod tests {
842 use std::{cell::RefCell, rc::Rc};
843
844 use gpui::{
845 AppContext as _, Element as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, MouseButton,
846 MouseDownEvent, MouseUpEvent, Render, TestAppContext, VisualTestContext, accesskit, px,
847 };
848
849 use super::*;
850 use crate::{DirectionProvider, Root};
851
852 struct Harness {
853 state: Entity<CalendarState>,
854 before: FocusHandle,
855 after: FocusHandle,
856 direction: Direction,
857 calendar_direction: Option<Direction>,
858 _subscription: Subscription,
859 }
860
861 impl Render for Harness {
862 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
863 let days = self.state.read(cx).days();
864 let weekdays = self.state.read(cx).weekdays();
865 let direction = self.calendar_direction.unwrap_or(self.direction);
866 DirectionProvider::new(self.direction).child(
867 div()
868 .w(px(280.))
869 .flex()
870 .flex_col()
871 .child(
872 Button::new("before")
873 .track_focus(&self.before)
874 .h(px(32.))
875 .child("Before"),
876 )
877 .child(
878 Calendar::new("calendar", &self.state)
879 .when_some(self.calendar_direction, |calendar, direction| {
880 calendar.direction(direction)
881 })
882 .accessibility_label("Recording date")
883 .flex()
884 .flex_col()
885 .child(
886 direction
887 .row(div().id("weekdays").role(Role::Row))
888 .children(weekdays.into_iter().enumerate().map(
889 |(index, label)| {
890 div()
891 .id(("weekday", index))
892 .role(Role::ColumnHeader)
893 .aria_column_index(if direction.is_rtl() {
894 6 - index
895 } else {
896 index
897 })
898 .w(px(40.))
899 .h(px(24.))
900 .child(short_weekday(label))
901 },
902 )),
903 )
904 .children(days.chunks(7).enumerate().map(|(index, week)| {
905 direction
906 .row(div().id(("week", index)).role(Role::Row))
907 .children(week.iter().map(|&date| {
908 CalendarDay::new(&self.state, date)
909 .debug_selector(move || format!("date-{date}"))
910 .w(px(40.))
911 .h(px(32.))
912 .child(date.day().to_string())
913 }))
914 })),
915 )
916 .child(
917 Button::new("after")
918 .track_focus(&self.after)
919 .h(px(32.))
920 .child("After"),
921 ),
922 )
923 }
924 }
925
926 type Changes = Rc<RefCell<Vec<CalendarSelection>>>;
927
928 fn short_weekday(day: Weekday) -> &'static str {
930 match day {
931 Weekday::Monday => "Mon",
932 Weekday::Tuesday => "Tue",
933 Weekday::Wednesday => "Wed",
934 Weekday::Thursday => "Thu",
935 Weekday::Friday => "Fri",
936 Weekday::Saturday => "Sat",
937 Weekday::Sunday => "Sun",
938 }
939 }
940
941 fn date(year: i16, month: i8, day: i8) -> Date {
942 Date::new(year, month, day).unwrap()
943 }
944
945 fn harness(
946 cx: &mut TestAppContext,
947 initial: Date,
948 bounds: Option<(Date, Date)>,
949 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
950 configured_harness(cx, initial, bounds, |state| state)
951 }
952
953 fn configured_harness(
954 cx: &mut TestAppContext,
955 initial: Date,
956 bounds: Option<(Date, Date)>,
957 configure: impl FnOnce(CalendarState) -> CalendarState + 'static,
958 ) -> (&mut VisualTestContext, Entity<Harness>, Changes) {
959 cx.update(crate::init);
960 let (root, cx) = cx.add_window_view(move |window, cx| {
961 let content = cx.new(|cx| {
962 let state = cx.new(|cx| {
963 let state = CalendarState::new(initial, cx)
964 .default_selection(CalendarSelection::Single(Some(initial)));
965 let state = if let Some((minimum, maximum)) = bounds {
966 state.bounds(minimum, maximum)
967 } else {
968 state
969 };
970 configure(state)
971 });
972 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
973 Harness {
974 state,
975 before: cx.focus_handle().tab_stop(true),
976 after: cx.focus_handle().tab_stop(true),
977 direction: Direction::Ltr,
978 calendar_direction: None,
979 _subscription: subscription,
980 }
981 });
982 Root::new(content, window, cx)
983 });
984 let view = root
985 .read_with(cx, |root, _| root.view().clone())
986 .downcast::<Harness>()
987 .unwrap();
988 let changes = Rc::new(RefCell::new(Vec::new()));
989 cx.update(|window, cx| {
990 let state = view.read(cx).state.clone();
991 let changes = changes.clone();
992 cx.subscribe(&state, move |_, event: &CalendarEvent, _| {
993 let CalendarEvent::Change(selection) = event;
994 changes.borrow_mut().push(selection.clone());
995 })
996 .detach();
997 window.activate_window();
998 view.read(cx).before.clone().focus(window, cx);
999 window.draw(cx).clear(cx);
1000 });
1001 cx.run_until_parked();
1002 (cx, view, changes)
1003 }
1004
1005 fn draw(cx: &mut VisualTestContext) {
1006 cx.update(|window, cx| window.draw(cx).clear(cx));
1007 }
1008
1009 fn press(cx: &mut VisualTestContext, key: &str) {
1010 let keystroke =
1011 cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
1012 cx.simulate_event(KeyDownEvent {
1013 keystroke: keystroke.clone(),
1014 is_held: false,
1015 prefer_character_input: false,
1016 });
1017 cx.simulate_event(KeyUpEvent { keystroke });
1018 draw(cx);
1019 }
1020
1021 fn assert_cursor(
1022 cx: &mut VisualTestContext,
1023 view: &Entity<Harness>,
1024 expected: Date,
1025 selected: Option<Date>,
1026 ) {
1027 cx.update(|window, cx| {
1028 let state = view.read(cx).state.read(cx);
1029 assert_eq!(state.focused_date(), expected);
1030 assert_eq!(state.month(), expected.first_of_month());
1031 assert_eq!(state.selection(), &CalendarSelection::Single(selected));
1032 assert!(state.focus_handle().is_focused(window));
1033 });
1034 }
1035
1036 #[gpui::test]
1037 fn navigation_crosses_months_and_leap_years_without_committing(cx: &mut TestAppContext) {
1038 let initial = date(2024, 1, 31);
1039 let (cx, view, changes) = harness(cx, initial, None);
1040 cx.simulate_keystrokes("tab right");
1041 draw(cx);
1042 assert_cursor(cx, &view, date(2024, 2, 1), Some(initial));
1043 assert!(changes.borrow().is_empty());
1044 press(cx, "enter");
1045 press(cx, "space");
1046 assert_eq!(
1047 *changes.borrow(),
1048 [CalendarSelection::Single(Some(date(2024, 2, 1)))]
1049 );
1050
1051 cx.update(|window, cx| {
1052 let state = view.read(cx).state.clone();
1053 state.update(cx, |state, cx| {
1054 assert!(state.set_selection(CalendarSelection::Single(Some(initial)), window, cx));
1055 });
1056 });
1057 draw(cx);
1058 for (key, expected) in [
1059 ("pagedown", date(2024, 2, 29)),
1060 ("shift-pagedown", date(2025, 2, 28)),
1061 ("home", date(2025, 2, 24)),
1062 ("end", date(2025, 3, 2)),
1063 ("up", date(2025, 2, 23)),
1064 ("down", date(2025, 3, 2)),
1065 ] {
1066 press(cx, key);
1067 assert_cursor(cx, &view, expected, Some(initial));
1068 }
1069 assert_eq!(
1070 *changes.borrow(),
1071 [CalendarSelection::Single(Some(date(2024, 2, 1)))]
1072 );
1073
1074 let adjacent = cx.debug_bounds("date-2025-02-24").unwrap().center();
1075 cx.simulate_event(MouseDownEvent {
1076 button: MouseButton::Left,
1077 position: adjacent,
1078 click_count: 1,
1079 ..Default::default()
1080 });
1081 draw(cx);
1082 cx.run_until_parked();
1083 draw(cx);
1084 cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).month(), date(2025, 3, 1)));
1085 assert_eq!(
1086 cx.debug_bounds("date-2025-02-24").unwrap().center(),
1087 adjacent
1088 );
1089 cx.simulate_event(MouseUpEvent {
1090 button: MouseButton::Left,
1091 position: adjacent,
1092 click_count: 1,
1093 ..Default::default()
1094 });
1095 draw(cx);
1096 assert_cursor(cx, &view, date(2025, 2, 24), Some(date(2025, 2, 24)));
1097 assert_eq!(
1098 *changes.borrow(),
1099 [date(2024, 2, 1), date(2025, 2, 24)].map(|date| CalendarSelection::Single(Some(date)))
1100 );
1101 cx.simulate_keystrokes("tab");
1102 draw(cx);
1103 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
1104 cx.simulate_keystrokes("shift-tab");
1105 draw(cx);
1106 assert_cursor(cx, &view, date(2025, 2, 24), Some(date(2025, 2, 24)));
1107
1108 cx.update(|window, cx| {
1110 let before = view.read(cx).before.clone();
1111 before.focus(window, cx);
1112 let state = view.read(cx).state.clone();
1113 state.update(cx, |state, cx| state.next_month(window, cx));
1114 assert!(before.is_focused(window));
1115 assert_eq!(state.read(cx).month(), date(2025, 3, 1));
1116 });
1117 }
1118
1119 #[gpui::test]
1120 fn jumping_to_a_month_clamps_the_cursor_and_preserves_selection(cx: &mut TestAppContext) {
1121 let initial = date(2023, 12, 31);
1122 let minimum = date(2023, 10, 20);
1123 let maximum = date(2030, 4, 9);
1124 let (cx, view, changes) = harness(cx, initial, Some((minimum, maximum)));
1125 cx.simulate_keystrokes("tab");
1126 let state = view.read_with(cx, |view, _| view.state.clone());
1127 for (month, expected) in [
1128 (date(2028, 2, 1), date(2028, 2, 29)),
1129 (date(2100, 12, 31), maximum),
1130 (date(2000, 1, 1), minimum),
1131 ] {
1132 cx.update(|window, cx| {
1133 state.update(cx, |state, cx| state.display_month(month, window, cx))
1134 });
1135 draw(cx);
1136 assert_cursor(cx, &view, expected, Some(initial));
1137 }
1138 assert!(changes.borrow().is_empty());
1139 }
1140
1141 #[gpui::test]
1142 fn bounds_disabled_state_and_native_grid_metadata_follow_the_same_dates(
1143 cx: &mut TestAppContext,
1144 ) {
1145 let minimum = date(2026, 11, 9);
1146 let maximum = date(2026, 11, 20);
1147 let (cx, view, changes) = harness(cx, minimum, Some((minimum, maximum)));
1148 cx.simulate_keystrokes("tab left up home");
1149 draw(cx);
1150 assert_cursor(cx, &view, minimum, Some(minimum));
1151 let disabled = cx.debug_bounds("date-2026-11-08").unwrap().center();
1152 cx.simulate_click(disabled, Modifiers::default());
1153 draw(cx);
1154 assert_cursor(cx, &view, minimum, Some(minimum));
1155 cx.simulate_keystrokes("end down");
1156 draw(cx);
1157 assert_cursor(cx, &view, maximum, Some(minimum));
1158 press(cx, "pagedown");
1159 assert_cursor(cx, &view, maximum, Some(minimum));
1160 assert!(changes.borrow().is_empty());
1161
1162 cx.update(|window, cx| {
1163 let state = view.read(cx).state.clone();
1164 assert!(!state.read(cx).can_previous_month());
1165 assert!(!state.read(cx).can_next_month());
1166 let grid = Calendar::new("native-calendar", &state)
1167 .accessibility_label("November 2026")
1168 .render(window, cx)
1169 .into_element();
1170 let mut node = accesskit::Node::new(grid.a11y_role().unwrap());
1171 grid.write_a11y_info(&mut node);
1172 assert_eq!(node.role(), Role::Grid);
1173 assert_eq!(node.label(), Some("November 2026"));
1174 assert_eq!(node.row_count(), Some(7));
1175 assert_eq!(node.column_count(), Some(7));
1176 assert!(!node.is_multiselectable());
1177 for (date, disabled, selected, row, column) in [
1178 (date(2026, 11, 8), true, false, 2, 6),
1179 (minimum, false, true, 3, 0),
1180 ] {
1181 let day = CalendarDay::new(&state, date)
1182 .render(window, cx)
1183 .into_element();
1184 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1185 day.write_a11y_info(&mut node);
1186 assert_eq!(node.role(), Role::GridCell);
1187 assert_eq!(node.label(), Some(date.to_string().as_str()));
1188 assert_eq!(node.is_disabled(), disabled);
1189 assert_eq!(node.is_selected(), Some(selected));
1190 assert_eq!(node.row_index(), Some(row));
1191 assert_eq!(node.column_index(), Some(column));
1192 }
1193 state.update(cx, |state, cx| {
1194 assert!(!state.set_selection(
1195 CalendarSelection::Single(Some(date(2026, 11, 21))),
1196 window,
1197 cx
1198 ));
1199 state.set_disabled(true, window, cx);
1200 });
1201 });
1202 draw(cx);
1203 press(cx, "enter");
1204 cx.simulate_keystrokes("left tab");
1205 draw(cx);
1206 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
1207 cx.simulate_keystrokes("shift-tab");
1208 draw(cx);
1209 cx.update(|window, cx| {
1210 assert!(view.read(cx).before.is_focused(window));
1211 let state = view.read(cx).state.clone();
1212 state.update(cx, |state, cx| {
1213 assert!(state.set_selection(CalendarSelection::Single(None), window, cx));
1214 state.set_disabled(false, window, cx);
1215 });
1216 });
1217 draw(cx);
1218 cx.simulate_keystrokes("tab");
1219 draw(cx);
1220 assert_cursor(cx, &view, maximum, None);
1221 press(cx, "space");
1222 assert_eq!(
1223 *changes.borrow(),
1224 [CalendarSelection::Single(Some(maximum))]
1225 );
1226 }
1227
1228 #[gpui::test]
1229 fn range_selection_completes_reverses_restarts_and_marks_every_inclusive_day(
1230 cx: &mut TestAppContext,
1231 ) {
1232 let initial = date(2024, 1, 31);
1233 let (cx, view, changes) =
1234 harness(cx, initial, Some((date(2024, 1, 20), date(2024, 3, 10))));
1235 let range = |start, end| CalendarSelection::Range { start, end };
1236 cx.update(|window, cx| {
1237 let state = view.read(cx).state.clone();
1238 assert!(state.update(cx, |state, cx| state.set_selection(
1239 range(None, None),
1240 window,
1241 cx
1242 )));
1243 });
1244 draw(cx);
1245 cx.simulate_keystrokes("tab");
1246 press(cx, "enter");
1247 cx.simulate_keystrokes("right right right");
1248 draw(cx);
1249 cx.update(|_, cx| {
1250 let state = view.read(cx).state.read(cx);
1251 assert_eq!(state.focused_date(), date(2024, 2, 3));
1252 assert_eq!(state.selection(), &range(Some(initial), None));
1253 });
1254 press(cx, "enter");
1255 cx.update(|window, cx| {
1256 let state = view.read(cx).state.clone();
1257 let grid = Calendar::new("range-native-calendar", &state)
1258 .render(window, cx)
1259 .into_element();
1260 let mut node = accesskit::Node::new(grid.a11y_role().unwrap());
1261 grid.write_a11y_info(&mut node);
1262 assert!(node.is_multiselectable());
1263 for (date, selected) in [
1264 (date(2024, 1, 30), false),
1265 (initial, true),
1266 (date(2024, 2, 1), true),
1267 (date(2024, 2, 2), true),
1268 (date(2024, 2, 3), true),
1269 (date(2024, 2, 4), false),
1270 ] {
1271 let day = CalendarDay::new(&state, date)
1272 .render(window, cx)
1273 .into_element();
1274 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1275 day.write_a11y_info(&mut node);
1276 assert_eq!(node.is_selected(), Some(selected));
1277 }
1278 });
1279 press(cx, "left");
1280 press(cx, "enter");
1281 cx.simulate_keystrokes("left left");
1282 press(cx, "space");
1283 cx.update(|_, cx| {
1284 assert_eq!(
1285 view.read(cx).state.read(cx).selection(),
1286 &range(Some(initial), Some(date(2024, 2, 2)))
1287 )
1288 });
1289 press(cx, "enter");
1290 press(cx, "space");
1291 cx.update(|window, cx| {
1292 let state = view.read(cx).state.clone();
1293 assert_eq!(
1294 state.read(cx).selection(),
1295 &range(Some(initial), Some(initial))
1296 );
1297 for invalid in [
1298 range(None, Some(initial)),
1299 range(Some(initial), Some(date(2024, 1, 30))),
1300 range(Some(initial), Some(date(2024, 3, 11))),
1301 ] {
1302 assert!(!state.update(cx, |state, cx| state.set_selection(invalid, window, cx)));
1303 }
1304 assert_eq!(
1305 state.read(cx).selection(),
1306 &range(Some(initial), Some(initial))
1307 );
1308 });
1309 assert_eq!(
1310 *changes.borrow(),
1311 [
1312 range(Some(initial), None),
1313 range(Some(initial), Some(date(2024, 2, 3))),
1314 range(Some(date(2024, 2, 2)), None),
1315 range(Some(initial), Some(date(2024, 2, 2))),
1316 range(Some(initial), None),
1317 range(Some(initial), Some(initial)),
1318 ]
1319 );
1320 }
1321
1322 #[gpui::test]
1323 fn multiple_dates_toggle_in_order_without_changing_selection_during_navigation(
1324 cx: &mut TestAppContext,
1325 ) {
1326 let first = date(2026, 11, 10);
1327 let second = date(2026, 11, 11);
1328 let third = date(2026, 11, 12);
1329 let (cx, view, changes) = harness(cx, first, Some((date(2026, 11, 9), date(2026, 11, 20))));
1330 cx.update(|window, cx| {
1331 let state = view.read(cx).state.clone();
1332 state.update(cx, |state, cx| {
1333 assert!(state.set_selection(
1334 CalendarSelection::Multiple(vec![third, first, third]),
1335 window,
1336 cx
1337 ));
1338 assert_eq!(
1339 state.selection(),
1340 &CalendarSelection::Multiple(vec![first, third])
1341 );
1342 assert_eq!(state.selection().first_date(), Some(first));
1343 });
1344 });
1345 draw(cx);
1346 cx.simulate_keystrokes("tab right");
1347 draw(cx);
1348 assert!(changes.borrow().is_empty());
1349 press(cx, "enter");
1350 let point = cx.debug_bounds("date-2026-11-10").unwrap().center();
1351 cx.simulate_click(point, Modifiers::default());
1352 draw(cx);
1353 cx.update(|window, cx| {
1354 let state = view.read(cx).state.clone();
1355 assert_eq!(
1356 state.read(cx).selection(),
1357 &CalendarSelection::Multiple(vec![second, third])
1358 );
1359 let grid = Calendar::new("multiple-native-calendar", &state)
1360 .render(window, cx)
1361 .into_element();
1362 let mut node = accesskit::Node::new(grid.a11y_role().unwrap());
1363 grid.write_a11y_info(&mut node);
1364 assert!(node.is_multiselectable());
1365 for (date, selected) in [(first, false), (second, true), (third, true)] {
1366 let day = CalendarDay::new(&state, date)
1367 .render(window, cx)
1368 .into_element();
1369 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1370 day.write_a11y_info(&mut node);
1371 assert_eq!(node.is_selected(), Some(selected));
1372 }
1373 state.update(cx, |state, cx| {
1374 assert!(!state.set_selection(
1375 CalendarSelection::Multiple(vec![date(2026, 11, 21)]),
1376 window,
1377 cx
1378 ));
1379 state.set_disabled(true, window, cx);
1380 });
1381 });
1382 draw(cx);
1383 press(cx, "space");
1384 assert_eq!(
1385 *changes.borrow(),
1386 [
1387 CalendarSelection::Multiple(vec![first, second, third]),
1388 CalendarSelection::Multiple(vec![second, third]),
1389 ]
1390 );
1391 }
1392
1393 #[gpui::test]
1394 fn sunday_first_disabled_dates_remain_discoverable_without_activation(cx: &mut TestAppContext) {
1395 let initial = date(2026, 11, 11);
1396 let (cx, view, changes) = configured_harness(cx, initial, None, |state| {
1397 state
1398 .week_starts_on(Weekday::Sunday)
1399 .disabled_dates(|date| {
1400 matches!(date.weekday(), Weekday::Saturday | Weekday::Sunday)
1401 })
1402 });
1403 cx.update(|_, cx| {
1404 let state = view.read(cx).state.read(cx);
1405 assert_eq!(state.first_weekday(), Weekday::Sunday);
1406 assert_eq!(state.days()[0], date(2026, 11, 1));
1407 assert_eq!(state.days()[41], date(2026, 12, 12));
1408 assert_eq!(
1409 state.weekdays(),
1410 [
1411 Weekday::Sunday,
1412 Weekday::Monday,
1413 Weekday::Tuesday,
1414 Weekday::Wednesday,
1415 Weekday::Thursday,
1416 Weekday::Friday,
1417 Weekday::Saturday
1418 ]
1419 );
1420 });
1421 cx.simulate_keystrokes("tab home");
1422 draw(cx);
1423 assert_cursor(cx, &view, date(2026, 11, 8), Some(initial));
1424 press(cx, "enter");
1425 press(cx, "end");
1426 assert_cursor(cx, &view, date(2026, 11, 14), Some(initial));
1427 press(cx, "space");
1428 let disabled = cx.debug_bounds("date-2026-11-08").unwrap().center();
1429 cx.simulate_click(disabled, Modifiers::default());
1430 draw(cx);
1431 assert_cursor(cx, &view, date(2026, 11, 14), Some(initial));
1432 cx.simulate_keystrokes("tab");
1433 draw(cx);
1434 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
1435 cx.simulate_keystrokes("shift-tab");
1436 draw(cx);
1437 assert_cursor(cx, &view, date(2026, 11, 14), Some(initial));
1438 assert!(changes.borrow().is_empty());
1439 cx.update(|window, cx| {
1440 let state = view.read(cx).state.clone();
1441 let day = CalendarDay::new(&state, date(2026, 11, 14))
1442 .render(window, cx)
1443 .into_element();
1444 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1445 day.write_a11y_info(&mut node);
1446 assert!(node.is_disabled());
1447 assert_eq!(node.column_index(), Some(6));
1448 assert_eq!(node.row_index(), Some(2));
1449 state.update(cx, |state, cx| {
1450 for selection in [
1451 CalendarSelection::Single(Some(date(2026, 11, 14))),
1452 CalendarSelection::Multiple(vec![initial, date(2026, 11, 14)]),
1453 CalendarSelection::Range {
1454 start: Some(initial),
1455 end: Some(date(2026, 11, 14)),
1456 },
1457 ] {
1458 assert!(!state.set_selection(selection, window, cx));
1459 assert_eq!(state.selection(), &CalendarSelection::Single(Some(initial)));
1460 }
1461 let range = CalendarSelection::Range {
1462 start: Some(date(2026, 11, 13)),
1463 end: Some(date(2026, 11, 16)),
1464 };
1465 assert!(state.set_selection(range, window, cx));
1466 assert!(state.is_selected(date(2026, 11, 14)));
1467 assert!(state.is_selected(date(2026, 11, 15)));
1468 });
1469 });
1470 draw(cx);
1471 let enabled = cx.debug_bounds("date-2026-11-12").unwrap().center();
1472 cx.simulate_click(enabled, Modifiers::default());
1473 draw(cx);
1474 cx.update(|_, cx| {
1475 assert_eq!(
1476 view.read(cx).state.read(cx).selection(),
1477 &CalendarSelection::Range {
1478 start: Some(date(2026, 11, 12)),
1479 end: None
1480 }
1481 )
1482 });
1483 assert_eq!(changes.borrow().len(), 1);
1484 }
1485
1486 #[gpui::test]
1487 fn disabled_date_configuration_filters_retained_values(cx: &mut TestAppContext) {
1488 let enabled = date(2026, 11, 13);
1489 let disabled = date(2026, 11, 14);
1490 cx.update(|cx| {
1491 for (selection, expected) in [
1492 (
1493 CalendarSelection::Single(Some(disabled)),
1494 CalendarSelection::Single(None),
1495 ),
1496 (
1497 CalendarSelection::Multiple(vec![disabled, enabled]),
1498 CalendarSelection::Multiple(vec![enabled]),
1499 ),
1500 (
1501 CalendarSelection::Range {
1502 start: Some(enabled),
1503 end: Some(disabled),
1504 },
1505 CalendarSelection::Range {
1506 start: None,
1507 end: None,
1508 },
1509 ),
1510 ] {
1511 let state = cx.new(|cx| {
1512 CalendarState::new(enabled, cx)
1513 .default_selection(selection)
1514 .disabled_dates(move |date| date == disabled)
1515 });
1516 assert_eq!(state.read(cx).selection(), &expected);
1517 }
1518 });
1519 }
1520
1521 #[gpui::test]
1522 fn grids_at_the_supported_range_edges_stay_within_jiff_dates(cx: &mut TestAppContext) {
1523 cx.update(|cx| {
1524 let last = cx.new(|cx| CalendarState::new(date(MAX_YEAR, 12, 31), cx));
1525 let days = last.read(cx).days();
1526 assert_eq!(last.read(cx).maximum(), date(MAX_YEAR, 12, 31));
1527 assert_eq!(days[DAY_COUNT - 1].year(), MAX_YEAR + 1);
1528 assert!(days.contains(&date(MAX_YEAR, 12, 31)));
1529
1530 let first =
1532 cx.new(|cx| CalendarState::new(date(1, 1, 1), cx).week_starts_on(Weekday::Sunday));
1533 let days = first.read(cx).days();
1534 assert_eq!(days[0].year(), 0);
1535 assert!(days.contains(&date(1, 1, 1)));
1536 });
1537 }
1538
1539 #[gpui::test]
1540 #[should_panic(expected = "Calendar dates must be in years 1..=9998")]
1541 fn dates_past_the_supported_range_are_rejected(cx: &mut TestAppContext) {
1542 cx.update(|cx| {
1543 cx.new(|cx| CalendarState::new(date(MAX_YEAR + 1, 1, 1), cx));
1544 });
1545 }
1546
1547 #[gpui::test]
1548 fn all_dates_disabled_keeps_one_tab_stop_until_whole_calendar_is_disabled(
1549 cx: &mut TestAppContext,
1550 ) {
1551 let initial = date(2026, 11, 11);
1552 let (cx, view, changes) =
1553 configured_harness(cx, initial, None, |state| state.disabled_dates(|_| true));
1554 cx.simulate_keystrokes("tab right enter");
1555 draw(cx);
1556 assert_cursor(cx, &view, date(2026, 11, 12), None);
1557 cx.simulate_keystrokes("tab");
1558 draw(cx);
1559 cx.update(|window, cx| {
1560 assert!(view.read(cx).after.is_focused(window));
1561 let state = view.read(cx).state.clone();
1562 state.update(cx, |state, cx| state.set_disabled(true, window, cx));
1563 });
1564 draw(cx);
1565 cx.simulate_keystrokes("shift-tab");
1566 draw(cx);
1567 cx.update(|window, cx| assert!(view.read(cx).before.is_focused(window)));
1568 assert!(changes.borrow().is_empty());
1569 }
1570
1571 #[gpui::test]
1572 fn inherited_rtl_mirrors_arrows_and_native_columns_and_allows_override(
1573 cx: &mut TestAppContext,
1574 ) {
1575 let initial = date(2026, 11, 11);
1576 let (cx, view, changes) = harness(cx, initial, None);
1577 view.update(cx, |view, cx| {
1578 view.direction = Direction::Rtl;
1579 cx.notify();
1580 });
1581 draw(cx);
1582 cx.simulate_keystrokes("tab left");
1583 draw(cx);
1584 assert_cursor(cx, &view, date(2026, 11, 12), Some(initial));
1585 press(cx, "right");
1586 assert_cursor(cx, &view, initial, Some(initial));
1587 let wednesday = cx.debug_bounds("date-2026-11-11").unwrap();
1588 let thursday = cx.debug_bounds("date-2026-11-12").unwrap();
1589 assert!(thursday.left() < wednesday.left());
1590 cx.update(|window, cx| {
1591 let state = view.read(cx).state.clone();
1592 let day = CalendarDay::new(&state, initial)
1593 .render(window, cx)
1594 .into_element();
1595 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1596 day.write_a11y_info(&mut node);
1597 assert_eq!(node.column_index(), Some(4));
1598 });
1599 view.update(cx, |view, cx| {
1600 view.calendar_direction = Some(Direction::Ltr);
1601 cx.notify();
1602 });
1603 draw(cx);
1604 press(cx, "right");
1605 assert_cursor(cx, &view, date(2026, 11, 12), Some(initial));
1606 let wednesday = cx.debug_bounds("date-2026-11-11").unwrap();
1607 let thursday = cx.debug_bounds("date-2026-11-12").unwrap();
1608 assert!(thursday.left() > wednesday.left());
1609 cx.update(|window, cx| {
1610 let state = view.read(cx).state.clone();
1611 let day = CalendarDay::new(&state, initial)
1612 .render(window, cx)
1613 .into_element();
1614 let mut node = accesskit::Node::new(day.a11y_role().unwrap());
1615 day.write_a11y_info(&mut node);
1616 assert_eq!(node.column_index(), Some(2));
1617 });
1618 assert!(changes.borrow().is_empty());
1619 }
1620}