1use std::{cell::RefCell, rc::Rc};
28
29use arc_motion::{
30 arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
31};
32use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
33use gpui_kit::{
34 AnyElement, App, Bounds, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
35 ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
36 base::StyledExt as _, canvas, div, prelude::*, px,
37};
38
39type CalendarDateHandler = Rc<dyn Fn(&CalendarDate, &mut Window, &mut App)>;
40type CalendarMonthChange =
41 Rc<dyn Fn(CalendarDate, &gpui_kit::Entity<CalendarInternal>, &mut Window, &mut App)>;
42
43pub const fn calendar_strip_spring() -> SpringSpec {
45 SpringSpec::visual(0.36, 0.0)
46}
47
48const WEEKDAY_LABELS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
49const MONTH_NAMES: [&str; 12] = [
50 "January",
51 "February",
52 "March",
53 "April",
54 "May",
55 "June",
56 "July",
57 "August",
58 "September",
59 "October",
60 "November",
61 "December",
62];
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
66pub struct CalendarDate {
67 pub year: i32,
68 pub month: u32,
69 pub day: u32,
70}
71
72pub fn calendar_days_in_month(year: i32, month: u32) -> u32 {
73 match month {
74 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
75 4 | 6 | 9 | 11 => 30,
76 2 => {
77 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
78 29
79 } else {
80 28
81 }
82 }
83 _ => 30,
84 }
85}
86
87pub fn calendar_to_epoch_days(date: CalendarDate) -> i64 {
89 let y = date.year as i64 - if date.month <= 2 { 1 } else { 0 };
90 let era = if y >= 0 { y } else { y - 399 } / 400;
91 let yoe = y - era * 400;
92 let m = date.month as i64;
93 let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + date.day as i64 - 1;
94 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
95 era * 146_097 + doe - 719_468
96}
97
98pub fn calendar_from_epoch_days(days: i64) -> CalendarDate {
99 let z = days + 719_468;
100 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
101 let doe = z - era * 146_097;
102 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
103 let y = yoe + era * 400;
104 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
105 let mp = (5 * doy + 2) / 153;
106 let d = doy - (153 * mp + 2) / 5 + 1;
107 let m = mp + if mp < 10 { 3 } else { -9 };
108 CalendarDate {
109 year: (y + if m <= 2 { 1 } else { 0 }) as i32,
110 month: m as u32,
111 day: d as u32,
112 }
113}
114
115pub fn calendar_weekday(date: CalendarDate) -> u32 {
117 let days = calendar_to_epoch_days(date);
118 (((days % 7) + 11) % 7) as u32
119}
120
121pub fn calendar_add_months(date: CalendarDate, amount: i32) -> CalendarDate {
123 let total = date.year * 12 + (date.month as i32 - 1) + amount;
124 let year = total.div_euclid(12);
125 let month = (total.rem_euclid(12) + 1) as u32;
126 let day = date.day.min(calendar_days_in_month(year, month));
127 CalendarDate { year, month, day }
128}
129
130pub fn calendar_add_days(date: CalendarDate, amount: i64) -> CalendarDate {
131 calendar_from_epoch_days(calendar_to_epoch_days(date) + amount)
132}
133
134pub fn calendar_month_start(date: CalendarDate) -> CalendarDate {
135 CalendarDate {
136 year: date.year,
137 month: date.month,
138 day: 1,
139 }
140}
141
142pub fn calendar_same_day(a: CalendarDate, b: CalendarDate) -> bool {
143 a.year == b.year && a.month == b.month && a.day == b.day
144}
145
146pub fn calendar_same_month(a: CalendarDate, b: CalendarDate) -> bool {
147 a.year == b.year && a.month == b.month
148}
149
150pub fn calendar_date_key(date: CalendarDate) -> String {
152 format!("{:04}-{:02}-{:02}", date.year, date.month, date.day)
153}
154
155pub fn calendar_month_label(date: CalendarDate) -> String {
156 format!("{} {}", MONTH_NAMES[(date.month - 1) as usize], date.year)
157}
158
159pub fn calendar_weeks(month: CalendarDate) -> Vec<[CalendarDate; 7]> {
161 let first = calendar_month_start(month);
162 let start = calendar_add_days(first, -(calendar_weekday(first) as i64));
163 (0..6)
164 .map(|week| {
165 let base = calendar_add_days(start, week * 7);
166 core::array::from_fn(|day| calendar_add_days(base, day as i64))
167 })
168 .collect()
169}
170
171fn calendar_month_index(date: CalendarDate) -> i64 {
172 date.year as i64 * 12 + date.month as i64 - 1
173}
174
175fn calendar_from_index(index: i64) -> CalendarDate {
176 let year = index.div_euclid(12);
177 let month = (index.rem_euclid(12) + 1) as u32;
178 CalendarDate {
179 year: year as i32,
180 month,
181 day: 1,
182 }
183}
184
185#[derive(Clone)]
186struct CalendarInternal {
187 uncontrolled_month: Option<CalendarDate>,
188 uncontrolled_value: Option<CalendarDate>,
189 focused_date: Option<CalendarDate>,
190 seen_value: Option<CalendarDate>,
191 strip_seed: Option<f32>,
193 viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
194 focus_handle: FocusHandle,
195}
196
197impl CalendarInternal {
198 fn new(cx: &mut App) -> Self {
199 Self {
200 uncontrolled_month: None,
201 uncontrolled_value: None,
202 focused_date: None,
203 seen_value: None,
204 strip_seed: None,
205 viewport_bounds: Rc::new(RefCell::new(None)),
206 focus_handle: cx.focus_handle(),
207 }
208 }
209}
210
211#[derive(IntoElement)]
214pub struct Calendar {
215 id: ElementId,
216 label: SharedString,
217 value: Option<CalendarDate>,
218 default_value: Option<CalendarDate>,
219 month: Option<CalendarDate>,
220 min_date: Option<CalendarDate>,
221 max_date: Option<CalendarDate>,
222 disabled_dates: Option<Rc<dyn Fn(CalendarDate) -> bool>>,
223 show_today: bool,
224 disabled: bool,
225 width: Option<Pixels>,
226 on_change: Option<CalendarDateHandler>,
227 on_month_change: Option<CalendarDateHandler>,
228}
229
230impl Calendar {
231 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
232 Self {
233 id: id.into(),
234 label: label.into(),
235 value: None,
236 default_value: None,
237 month: None,
238 min_date: None,
239 max_date: None,
240 disabled_dates: None,
241 show_today: false,
242 disabled: false,
243 width: None,
244 on_change: None,
245 on_month_change: None,
246 }
247 }
248
249 pub fn value(mut self, value: CalendarDate) -> Self {
250 self.value = Some(value);
251 self
252 }
253
254 pub fn default_value(mut self, value: CalendarDate) -> Self {
255 self.default_value = Some(value);
256 self
257 }
258
259 pub fn month(mut self, month: CalendarDate) -> Self {
260 self.month = Some(month);
261 self
262 }
263
264 pub fn min_date(mut self, date: CalendarDate) -> Self {
265 self.min_date = Some(date);
266 self
267 }
268
269 pub fn max_date(mut self, date: CalendarDate) -> Self {
270 self.max_date = Some(date);
271 self
272 }
273
274 pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
276 self.disabled_dates = Some(Rc::new(matcher));
277 self
278 }
279
280 pub fn show_today(mut self, show: bool) -> Self {
282 self.show_today = show;
283 self
284 }
285
286 pub fn disabled(mut self, disabled: bool) -> Self {
287 self.disabled = disabled;
288 self
289 }
290
291 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
292 self.width = Some(width.into());
293 self
294 }
295
296 pub fn on_change(
297 mut self,
298 handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
299 ) -> Self {
300 self.on_change = Some(Rc::new(handler));
301 self
302 }
303
304 pub fn on_month_change(
305 mut self,
306 handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
307 ) -> Self {
308 self.on_month_change = Some(Rc::new(handler));
309 self
310 }
311}
312
313impl RenderOnce for Calendar {
314 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
315 let theme = cx.arc_theme().clone();
316 let colors = theme.colors;
317 let motion = theme.motion;
318 let reduced = is_reduced_motion(cx);
319 let now = motion_now(cx);
320
321 let today = {
322 self.value.or(self.default_value).unwrap_or(CalendarDate {
325 year: 2026,
326 month: 11,
327 day: 27,
328 })
329 };
330
331 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-calendar-state".into());
332 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
333 let seed_value = self.value.or(self.default_value);
334 let mut st = CalendarInternal::new(cx);
335 st.uncontrolled_value = seed_value;
336 st.uncontrolled_month = seed_value.map(calendar_month_start);
337 st
338 });
339
340 if let Some(ext) = self.value {
342 let seen = internal.read(cx).seen_value;
343 if seen != Some(ext) {
344 internal.update(cx, |s, _| {
345 s.seen_value = Some(ext);
346 if s.uncontrolled_value != Some(ext) {
347 s.uncontrolled_value = Some(ext);
348 }
349 if s.uncontrolled_month.is_none() {
350 s.uncontrolled_month = Some(calendar_month_start(ext));
351 }
352 });
353 }
354 }
355
356 let is_ctrl_value = self.value.is_some();
357 let is_ctrl_month = self.month.is_some();
358 let month = self
359 .month
360 .map(calendar_month_start)
361 .or_else(|| internal.read(cx).uncontrolled_month)
362 .unwrap_or_else(|| calendar_month_start(today));
363 let value = if is_ctrl_value {
364 self.value
365 } else {
366 internal.read(cx).uncontrolled_value
367 };
368
369 let min_bound = self.min_date;
370 let max_bound = self.max_date;
371 let matcher = self.disabled_dates.clone();
372 let is_disabled = move |date: CalendarDate| -> bool {
373 (min_bound.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
374 || (max_bound
375 .is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
376 || matcher.as_ref().is_some_and(|f| f(date))
377 };
378
379 let target = calendar_month_index(month);
380 let snap_state = internal.read(cx).clone();
381 let strip_seed = snap_state.strip_seed;
382 let strip_opts = match strip_seed {
383 Some(seed) if (seed - target as f32).abs() > 1.5 => {
384 let start = target as f32 - (target as f32 - seed).signum();
386 internal.update(cx, |s, _| s.strip_seed = None);
387 SpringOptions::new(calendar_strip_spring())
388 .with_initial_value(start)
389 .with_rest_thresholds(0.002, 0.02)
390 }
391 _ => SpringOptions::new(calendar_strip_spring()).with_rest_thresholds(0.002, 0.02),
392 };
393 let position = arc_spring_with_options(
394 (self.id.clone(), "strip"),
395 target as f32,
396 strip_opts,
397 window,
398 cx,
399 )
400 .value;
401 let moving = (position - target as f32).abs() > 0.002;
402 if moving {
403 window.request_animation_frame();
404 }
405 let pane_lo = (position as i64).min(target);
406 let pane_hi = (position as i64).max(target);
407 let pane_indexes: Vec<i64> = [pane_lo, target, pane_hi]
408 .into_iter()
409 .collect::<std::collections::BTreeSet<i64>>()
410 .into_iter()
411 .collect();
412
413 let _ = now;
414
415 let st_change = internal.clone();
417 let ch_change = self.on_change.clone();
418 let cm_change = self.on_month_change.clone();
419 let is_ctrl_m = is_ctrl_month;
420 #[allow(clippy::type_complexity)]
421 let change_month: CalendarMonthChange = Rc::new(
422 move |next: CalendarDate,
423 st: &gpui_kit::Entity<CalendarInternal>,
424 window: &mut Window,
425 cx: &mut App| {
426 let normalized = calendar_month_start(next);
427 let prev = st.read(cx).uncontrolled_month;
428 let seed_moved = prev
429 .map(|p| (calendar_month_index(normalized) - calendar_month_index(p)).abs() > 2)
430 .unwrap_or(false);
431 st.update(cx, |s, _| {
432 if !is_ctrl_m {
433 s.uncontrolled_month = Some(normalized);
434 }
435 if seed_moved {
436 s.strip_seed = prev.map(|p| calendar_month_index(p) as f32);
437 }
438 });
439 if let Some(handler) = &cm_change {
440 handler(&normalized, window, cx);
441 }
442 },
443 );
444 let _ = &st_change;
445 let _ = &ch_change;
446
447 let disc_value = value;
449 let disc_of = move |pane_month: CalendarDate| -> Option<(usize, f32, f32)> {
450 let v = disc_value?;
451 let grid_start = calendar_add_days(
452 calendar_month_start(pane_month),
453 -(calendar_weekday(calendar_month_start(pane_month)) as i64),
454 );
455 let index = calendar_to_epoch_days(v) - calendar_to_epoch_days(grid_start);
456 if !(0..42).contains(&index) {
457 return None;
458 }
459 Some((index as usize, index as f32 % 7.0, (index / 7) as f32))
460 };
461
462 let prev_disabled = self.min_date.is_some_and(|m| {
464 calendar_month_index(calendar_add_months(month, -1))
465 < calendar_month_index(calendar_month_start(m))
466 });
467 let next_disabled = self.max_date.is_some_and(|m| {
468 calendar_month_index(calendar_add_months(month, 1))
469 > calendar_month_index(calendar_month_start(m))
470 });
471 let today_selectable = !is_disabled(today);
472 let today_idle =
473 calendar_same_month(month, today) && (!today_selectable || value == Some(today));
474
475 let nav_color = colors.text_secondary;
476 let disabled_flag = self.disabled;
477 let show_today_flag = self.show_today;
478 let prev_disabled_flag = prev_disabled;
479 let next_disabled_flag = next_disabled;
480 let today_idle_flag = today_idle;
481 let today_selectable_flag = today_selectable;
482 let month_for_nav = month;
483 let header = div()
484 .flex()
485 .flex_row()
486 .items_center()
487 .justify_between()
488 .mb(Spacing::S2)
489 .child(
490 div()
491 .text_size(Typography::TEXT_SM)
492 .font_medium()
493 .text_color(colors.foreground)
494 .child(SharedString::from(calendar_month_label(month))),
495 )
496 .child(
497 div()
498 .flex()
499 .flex_row()
500 .items_center()
501 .gap(px(2.0))
502 .when(show_today_flag, |this| {
503 this.child(
504 div()
505 .id(ElementId::NamedChild(
506 self.id.clone().into(),
507 "today-button".into(),
508 ))
509 .test_support()
510 .aria_label(SharedString::from(format!(
511 "Today, {}",
512 calendar_date_key(today)
513 )))
514 .text_size(Typography::TEXT_XS)
515 .font_medium()
516 .px(px(8.0))
517 .h(px(26.0))
518 .flex()
519 .items_center()
520 .rounded(Radii::PILL)
521 .text_color(
522 if today_idle_flag || disabled_flag || !today_selectable_flag {
523 colors.text_muted
524 } else {
525 colors.foreground
526 },
527 )
528 .when(
529 !today_idle_flag && !disabled_flag && today_selectable_flag,
530 |this| {
531 this.cursor_pointer()
532 .hover(move |s| s.bg(colors.surface_muted))
533 },
534 )
535 .on_click({
536 let st = internal.clone();
537 let ch = self.on_change.clone();
538 let cm = change_month.clone();
539 let is_ctrl_v = is_ctrl_value;
540 let idle = today_idle_flag;
541 let off = disabled_flag || !today_selectable_flag;
542 let month_here = month_for_nav;
543 move |_, window, cx| {
544 if idle || off {
545 return;
546 }
547 st.update(cx, |s, _| {
548 if !is_ctrl_v {
549 s.uncontrolled_value = Some(today);
550 }
551 s.focused_date = Some(today);
552 });
553 if !calendar_same_month(month_here, today) {
554 cm(today, &st, window, cx);
555 }
556 if let Some(handler) = &ch {
557 handler(&today, window, cx);
558 }
559 window.refresh();
560 }
561 })
562 .child(SharedString::from("Today")),
563 )
564 })
565 .child(
566 div()
567 .id(ElementId::NamedChild(
568 self.id.clone().into(),
569 "prev-month".into(),
570 ))
571 .test_support()
572 .aria_label("Previous month")
573 .w(px(26.0))
574 .h(px(26.0))
575 .flex()
576 .items_center()
577 .justify_center()
578 .rounded(Radii::PILL)
579 .text_color(if prev_disabled_flag || disabled_flag {
580 colors.text_muted
581 } else {
582 nav_color
583 })
584 .when(!prev_disabled_flag && !disabled_flag, |this| {
585 this.cursor_pointer()
586 .hover(move |s| s.bg(colors.surface_muted))
587 })
588 .on_click({
589 let st = internal.clone();
590 let cm = change_month.clone();
591 let off = prev_disabled_flag || disabled_flag;
592 let month_here = month_for_nav;
593 move |_, window, cx| {
594 if off {
595 return;
596 }
597 let prev = calendar_add_months(month_here, -1);
598 cm(prev, &st, window, cx);
599 window.refresh();
600 }
601 })
602 .child(
603 div()
604 .text_size(Typography::TEXT_SM)
605 .child(SharedString::from("‹")),
606 ),
607 )
608 .child(
609 div()
610 .id(ElementId::NamedChild(
611 self.id.clone().into(),
612 "next-month".into(),
613 ))
614 .test_support()
615 .aria_label("Next month")
616 .w(px(26.0))
617 .h(px(26.0))
618 .flex()
619 .items_center()
620 .justify_center()
621 .rounded(Radii::PILL)
622 .text_color(if next_disabled_flag || disabled_flag {
623 colors.text_muted
624 } else {
625 nav_color
626 })
627 .when(!next_disabled_flag && !disabled_flag, |this| {
628 this.cursor_pointer()
629 .hover(move |s| s.bg(colors.surface_muted))
630 })
631 .on_click({
632 let st = internal.clone();
633 let cm = change_month.clone();
634 let off = next_disabled_flag || disabled_flag;
635 let month_here = month_for_nav;
636 move |_, window, cx| {
637 if off {
638 return;
639 }
640 let next = calendar_add_months(month_here, 1);
641 cm(next, &st, window, cx);
642 window.refresh();
643 }
644 })
645 .child(
646 div()
647 .text_size(Typography::TEXT_SM)
648 .child(SharedString::from("›")),
649 ),
650 ),
651 );
652
653 let viewport_width = snap_state
655 .viewport_bounds
656 .borrow()
657 .map_or(280.0_f32, |b| f32::from(b.size.width).max(1.0));
658 let strip_offset_px = -(position - target as f32) * viewport_width;
659
660 let pane_id = self.id.clone();
661 let pane_focus = snap_state.focus_handle.clone();
662 let pane_internal = internal.clone();
663 let pane_on_change = self.on_change.clone();
664 let pane_disabled = self.disabled;
665 let pane_is_ctrl_value = is_ctrl_value;
666 let mut render_pane = move |pane_month: CalendarDate, present: bool| -> AnyElement {
667 let disc = disc_of(pane_month);
668 let pane_key = calendar_date_key(pane_month);
669 let (disc_op, disc_scale, disc_col, disc_row) = if let Some((_, col, row)) = disc {
671 let col_s = if reduced || moving {
672 col
673 } else {
674 arc_spring(
675 (
676 pane_id.clone(),
677 SharedString::from(format!("disc-col-{pane_key}")),
678 ),
679 col,
680 motion.spring.morph,
681 window,
682 cx,
683 )
684 };
685 let row_s = if reduced || moving {
686 row
687 } else {
688 arc_spring(
689 (
690 pane_id.clone(),
691 SharedString::from(format!("disc-row-{pane_key}")),
692 ),
693 row,
694 motion.spring.morph,
695 window,
696 cx,
697 )
698 };
699 (1.0_f32, 1.0_f32, col_s, row_s)
700 } else {
701 (0.0, 0.6, 0.0, 0.0)
702 };
703
704 let mut week_els: Vec<AnyElement> = Vec::with_capacity(6);
705 for week in calendar_weeks(pane_month) {
706 let mut day_els: Vec<AnyElement> = Vec::with_capacity(7);
707 for date in week {
708 let key = calendar_date_key(date);
709 let selected = value.is_some_and(|v| calendar_same_day(v, date));
710 let is_today = calendar_same_day(date, today);
711 let disabled_here = is_disabled(date);
712 let outside = !calendar_same_month(date, pane_month);
713 let day_fg = if disabled_here || outside {
714 colors.text_muted
715 } else if selected {
716 colors.surface
717 } else if is_today {
718 colors.control_fill
719 } else {
720 colors.foreground
721 };
722 let bg = if selected {
723 Some(colors.control_fill)
724 } else if is_today {
725 Some(oklab_mix(colors.control_fill, colors.surface, 0.10))
726 } else {
727 None
728 };
729 let cell_size = viewport_width / 7.0;
730 day_els.push(
731 div()
732 .id(ElementId::NamedChild(
733 pane_id.clone().into(),
734 SharedString::from(format!("day-{key}")),
735 ))
736 .test_support()
737 .when(present, |this| {
738 this.role(Role::GridCell)
739 .aria_selected(selected)
740 .aria_label(SharedString::from(key.clone()))
741 })
742 .w(px(cell_size - 4.0))
743 .h(px(34.0))
744 .m(px(2.0))
745 .flex()
746 .items_center()
747 .justify_center()
748 .rounded(px(10.0))
749 .text_size(Typography::TEXT_XS)
750 .text_color(day_fg)
751 .when_some(bg, |this, bg| this.bg(bg))
752 .when(!disabled_here && present && !self.disabled, |this| {
753 this.cursor_pointer().when(!selected, |this| {
754 this.hover(move |s| {
755 s.bg(oklab_mix(colors.foreground, colors.surface, 0.08))
756 })
757 })
758 })
759 .on_click({
760 let st = pane_internal.clone();
761 let pane_focus_for_click = pane_focus.clone();
762 let ch = pane_on_change.clone();
763 let is_ctrl_v = pane_is_ctrl_value;
764 let disabled_d = disabled_here;
765 let off = pane_disabled;
766 move |_, window, cx| {
767 if disabled_d || !present || off {
768 return;
769 }
770 st.update(cx, |s, _| {
771 if !is_ctrl_v {
772 s.uncontrolled_value = Some(date);
773 }
774 s.focused_date = Some(date);
775 });
776 window.focus(&pane_focus_for_click, cx);
777 if let Some(handler) = &ch {
778 handler(&date, window, cx);
779 }
780 window.refresh();
781 }
782 })
783 .child(SharedString::from(date.day.to_string()))
784 .into_any_element(),
785 );
786 }
787 week_els.push(div().flex().flex_row().children(day_els).into_any_element());
788 }
789
790 let disc_el = if disc.is_some() || disc_op > 0.01 {
791 let cell_w = viewport_width / 7.0;
792 Some(
793 div()
794 .absolute()
795 .left(px(2.0 + disc_col * cell_w))
796 .top(px(2.0 + disc_row * 38.0))
797 .w(px(cell_w - 4.0))
798 .h(px(cell_w - 4.0))
799 .h(px(34.0))
800 .rounded(px(10.0))
801 .bg(colors.control_fill)
802 .opacity(disc_op * disc_scale),
803 )
804 } else {
805 None
806 };
807
808 div()
809 .relative()
810 .w(px(viewport_width))
811 .flex_none()
812 .opacity(if present { 1.0 } else { 0.4 })
813 .when_some(disc_el, |this, el| this.child(el))
814 .child(
815 div()
816 .relative()
817 .flex()
818 .flex_col()
819 .gap(px(2.0))
820 .children(week_els),
821 )
822 .into_any_element()
823 };
824
825 let pane_els: Vec<AnyElement> = pane_indexes
826 .iter()
827 .map(|&index| {
828 let offset_px = (index as f32 - position) * viewport_width;
829 div()
830 .absolute()
831 .left_0()
832 .top_0()
833 .ml(px(offset_px))
834 .child(render_pane(calendar_from_index(index), index == target))
835 .into_any_element()
836 })
837 .collect();
838
839 let st_key = internal.clone();
841 let ch_key = self.on_change.clone();
842 let cm_key = change_month.clone();
843 let focus_key = snap_state.focus_handle.clone();
844 let is_ctrl_vk = is_ctrl_value;
845 let grid_disabled = self.disabled;
846 let grid_month = month;
847 let disabled_matcher = self.disabled_dates.clone();
848 let min_d = self.min_date;
849 let max_d = self.max_date;
850 let is_disabled_fn = move |date: CalendarDate| -> bool {
851 (min_d.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
852 || (max_d.is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
853 || disabled_matcher.as_ref().is_some_and(|f| f(date))
854 };
855
856 let grid = div()
857 .id(ElementId::NamedChild(self.id.clone().into(), "grid".into()))
858 .test_support()
859 .role(Role::Grid)
860 .aria_label(SharedString::from(calendar_month_label(month)))
861 .track_focus(&focus_key)
862 .relative()
863 .overflow_hidden()
864 .h(px(2.0 + 6.0 * 38.0))
865 .on_mouse_down(MouseButton::Left, {
866 let focus_grid = focus_key.clone();
867 move |_, window, cx| {
868 window.focus(&focus_grid, cx);
869 }
870 })
871 .on_key_down(move |event: &KeyDownEvent, window, cx| {
872 if grid_disabled {
873 return;
874 }
875 let key = event.keystroke.key.as_str();
876 let shift = event.keystroke.modifiers.shift;
877 let from = st_key.read(cx).focused_date.or(value).unwrap_or(today);
878 let (next, step_dir): (CalendarDate, i64) = match key {
879 "enter" | " " | "space" => {
880 if !is_disabled_fn(from) {
881 st_key.update(cx, |s, _| {
882 if !is_ctrl_vk {
883 s.uncontrolled_value = Some(from);
884 }
885 });
886 if let Some(handler) = &ch_key {
887 handler(&from, window, cx);
888 }
889 }
890 window.refresh();
891 return;
892 }
893 "left" | "arrowleft" => (calendar_add_days(from, -1), -1),
894 "right" | "arrowright" => (calendar_add_days(from, 1), 1),
895 "up" | "arrowup" => (calendar_add_days(from, -7), -1),
896 "down" | "arrowdown" => (calendar_add_days(from, 7), 1),
897 "home" => (calendar_add_days(from, -(calendar_weekday(from) as i64)), 1),
898 "end" => (
899 calendar_add_days(from, 6 - calendar_weekday(from) as i64),
900 -1,
901 ),
902 "pageup" => (calendar_add_months(from, if shift { -12 } else { -1 }), -1),
903 "pagedown" => (calendar_add_months(from, if shift { 12 } else { 1 }), 1),
904 _ => return,
905 };
906 let mut clamped = next;
908 if let Some(m) = min_d
909 && calendar_to_epoch_days(clamped) < calendar_to_epoch_days(m)
910 {
911 clamped = m;
912 }
913 if let Some(m) = max_d
914 && calendar_to_epoch_days(clamped) > calendar_to_epoch_days(m)
915 {
916 clamped = m;
917 }
918 let mut final_date = clamped;
919 for _ in 0..42 {
920 if !is_disabled_fn(final_date) {
921 break;
922 }
923 final_date = calendar_add_days(final_date, step_dir);
924 }
925 if is_disabled_fn(final_date) || calendar_same_day(final_date, from) {
926 return;
927 }
928 st_key.update(cx, |s, _| {
929 s.focused_date = Some(final_date);
930 });
931 if !calendar_same_month(final_date, grid_month) {
932 cm_key(final_date, &st_key, window, cx);
933 }
934 window.refresh();
935 })
936 .child(canvas(
937 {
938 let vp_ref = snap_state.viewport_bounds.clone();
939 move |rect, _, _| {
940 *vp_ref.borrow_mut() = Some(rect);
941 }
942 },
943 |_, _, _, _| {},
944 ))
945 .child(
946 div().absolute().inset_0().child(
947 div()
948 .absolute()
949 .left(px(strip_offset_px))
950 .top_0()
951 .flex()
952 .flex_row()
953 .children(pane_els),
954 ),
955 );
956
957 let weekdays_row = div()
959 .flex()
960 .flex_row()
961 .mb(px(2.0))
962 .children(WEEKDAY_LABELS.iter().map(|label| {
963 div()
964 .flex_1()
965 .text_center()
966 .text_size(Typography::TEXT_XS)
967 .text_color(colors.text_muted)
968 .child(SharedString::from(*label))
969 .into_any_element()
970 }));
971
972 div()
973 .id(self.id)
974 .test_support()
975 .when_some(self.width, |this, w| this.w(w))
976 .when(self.width.is_none(), |this| this.w_full())
977 .flex()
978 .flex_col()
979 .when(self.disabled, |this| this.opacity(0.5))
980 .child(
981 div()
982 .text_size(Typography::TEXT_XS)
983 .text_color(colors.text_muted)
984 .mb(Spacing::S1)
985 .child(self.label.clone()),
986 )
987 .child(header)
988 .child(weekdays_row)
989 .child(grid)
990 }
991}
992
993#[cfg(test)]
994mod tests {
995 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
996 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
997
998 use super::*;
999
1000 const D: fn(i32, u32, u32) -> CalendarDate =
1001 |year, month, day| CalendarDate { year, month, day };
1002
1003 #[test]
1004 fn calendar_civil_math_round_trips_and_clamps_months() {
1005 assert_eq!(calendar_days_in_month(2026, 2), 28);
1006 assert_eq!(calendar_days_in_month(2024, 2), 29);
1007 let d = D(2026, 11, 27);
1009 assert_eq!(calendar_from_epoch_days(calendar_to_epoch_days(d)), d);
1010 assert_eq!(calendar_weekday(d), 5);
1012 let shifted = calendar_add_months(D(2026, 1, 31), 1);
1014 assert_eq!(shifted, D(2026, 2, 28));
1015 assert_eq!(calendar_add_days(D(2026, 11, 30), 1), D(2026, 12, 1));
1017 let weeks = calendar_weeks(D(2026, 11, 15));
1019 assert_eq!(calendar_weekday(weeks[0][0]), 0);
1020 assert_eq!(
1021 calendar_to_epoch_days(weeks[5][6]) - calendar_to_epoch_days(weeks[0][0]),
1022 41
1023 );
1024 }
1025
1026 #[test]
1027 fn calendar_month_labels_and_keys_format() {
1028 assert_eq!(calendar_month_label(D(2026, 11, 1)), "November 2026");
1029 assert_eq!(calendar_date_key(D(2026, 11, 5)), "2026-11-05");
1030 assert_eq!(calendar_month_index(D(2026, 11, 27)), 2026 * 12 + 10);
1031 }
1032
1033 struct CalendarHost {
1034 value: Option<CalendarDate>,
1035 events: Rc<RefCell<Vec<String>>>,
1036 disabled: bool,
1037 }
1038
1039 impl Render for CalendarHost {
1040 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1041 let events = self.events.clone();
1042 div().w(px(320.0)).p(px(16.0)).child(
1043 Calendar::new("cal-test", "Start date")
1044 .value(self.value.unwrap_or(D(2026, 11, 10)))
1045 .disabled(self.disabled)
1046 .on_change(cx.listener({
1047 let events = events.clone();
1048 move |this, date: &CalendarDate, _, cx| {
1049 events.borrow_mut().push(calendar_date_key(*date));
1050 this.value = Some(*date);
1051 cx.notify();
1052 }
1053 })),
1054 )
1055 }
1056 }
1057
1058 fn cal_element(name: &str) -> ElementId {
1059 ElementId::NamedChild(ElementId::Name("cal-test".into()).into(), name.into())
1060 }
1061
1062 #[gpui_kit::test]
1063 fn calendar_picks_days_and_navigates_months_by_keyboard(cx: &mut TestAppContext) {
1064 cx.update(|cx| {
1065 gpui_kit::init(cx);
1066 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1067 });
1068
1069 let host = CalendarHost {
1070 value: Some(D(2026, 11, 10)),
1071 events: Rc::new(RefCell::new(Vec::new())),
1072 disabled: false,
1073 };
1074 let events = host.events.clone();
1075 let (view, cx) = cx.add_window_view(|_, _| host);
1076
1077 cx.update(|window, cx| {
1078 window.render_frame(cx);
1079 let grid = window.find(cal_element("grid"));
1080 assert_eq!(grid.role(), Some(Role::Grid));
1081
1082 window.click(cal_element("day-2026-11-15"), cx);
1084 });
1085 assert_eq!(
1086 events.borrow().last().map(String::as_str),
1087 Some("2026-11-15")
1088 );
1089
1090 cx.update(|window, cx| {
1091 window.click(cal_element("grid"), cx);
1094 window.press("right", cx);
1095 window.press("enter", cx);
1096 });
1097 assert_eq!(
1098 events.borrow().last().map(String::as_str),
1099 Some("2026-11-19")
1100 );
1101
1102 cx.update(|window, cx| {
1103 if let Some(el) = window.try_find(cal_element("next-month")) {
1105 let b = el.bounds();
1106 eprintln!(
1107 "NEXT bounds=({},{}) size=({},{})",
1108 f32::from(b.origin.x),
1109 f32::from(b.origin.y),
1110 f32::from(b.size.width),
1111 f32::from(b.size.height)
1112 );
1113 } else {
1114 eprintln!("NEXT missing");
1115 }
1116 window.press("pagedown", cx);
1118 });
1119 cx.executor()
1120 .advance_clock(std::time::Duration::from_millis(600));
1121 cx.update(|window, cx| {
1122 for _ in 0..5 {
1123 window.render_frame(cx);
1124 }
1125 window.press("enter", cx);
1126 });
1127 assert_eq!(
1128 events.borrow().last().map(String::as_str),
1129 Some("2026-12-19")
1130 );
1131
1132 view.update(cx, |host, cx| {
1134 host.disabled = true;
1135 cx.notify();
1136 });
1137 cx.update(|window, cx| {
1138 window.render_frame(cx);
1139 window.click(cal_element("day-2026-12-05"), cx);
1140 window.press("right", cx);
1141 });
1142 assert_eq!(
1143 events.borrow().last().map(String::as_str),
1144 Some("2026-12-19")
1145 );
1146 }
1147
1148 #[gpui_kit::test]
1149 fn calendar_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
1150 cx.update(|cx| {
1151 gpui_kit::init(cx);
1152 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1153 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
1154 });
1155
1156 let host = CalendarHost {
1157 value: Some(D(2026, 11, 10)),
1158 events: Rc::new(RefCell::new(Vec::new())),
1159 disabled: false,
1160 };
1161 let events = host.events.clone();
1162 let (_view, cx) = cx.add_window_view(|_, _| host);
1163
1164 cx.update(|window, cx| {
1165 window.render_frame(cx);
1166 window.click(cal_element("day-2026-11-20"), cx);
1167 });
1168 assert_eq!(
1169 events.borrow().last().map(String::as_str),
1170 Some("2026-11-20")
1171 );
1172 }
1173}