use std::{cell::RefCell, rc::Rc};
use arc_motion::{
arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
base::StyledExt as _, canvas, div, prelude::*, px,
};
type CalendarDateHandler = Rc<dyn Fn(&CalendarDate, &mut Window, &mut App)>;
type CalendarMonthChange =
Rc<dyn Fn(CalendarDate, &gpui_kit::Entity<CalendarInternal>, &mut Window, &mut App)>;
pub const fn calendar_strip_spring() -> SpringSpec {
SpringSpec::visual(0.36, 0.0)
}
const WEEKDAY_LABELS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
const MONTH_NAMES: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CalendarDate {
pub year: i32,
pub month: u32,
pub day: u32,
}
pub fn calendar_days_in_month(year: i32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
29
} else {
28
}
}
_ => 30,
}
}
pub fn calendar_to_epoch_days(date: CalendarDate) -> i64 {
let y = date.year as i64 - if date.month <= 2 { 1 } else { 0 };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let m = date.month as i64;
let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + date.day as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
pub fn calendar_from_epoch_days(days: i64) -> CalendarDate {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = mp + if mp < 10 { 3 } else { -9 };
CalendarDate {
year: (y + if m <= 2 { 1 } else { 0 }) as i32,
month: m as u32,
day: d as u32,
}
}
pub fn calendar_weekday(date: CalendarDate) -> u32 {
let days = calendar_to_epoch_days(date);
(((days % 7) + 11) % 7) as u32
}
pub fn calendar_add_months(date: CalendarDate, amount: i32) -> CalendarDate {
let total = date.year * 12 + (date.month as i32 - 1) + amount;
let year = total.div_euclid(12);
let month = (total.rem_euclid(12) + 1) as u32;
let day = date.day.min(calendar_days_in_month(year, month));
CalendarDate { year, month, day }
}
pub fn calendar_add_days(date: CalendarDate, amount: i64) -> CalendarDate {
calendar_from_epoch_days(calendar_to_epoch_days(date) + amount)
}
pub fn calendar_month_start(date: CalendarDate) -> CalendarDate {
CalendarDate {
year: date.year,
month: date.month,
day: 1,
}
}
pub fn calendar_same_day(a: CalendarDate, b: CalendarDate) -> bool {
a.year == b.year && a.month == b.month && a.day == b.day
}
pub fn calendar_same_month(a: CalendarDate, b: CalendarDate) -> bool {
a.year == b.year && a.month == b.month
}
pub fn calendar_date_key(date: CalendarDate) -> String {
format!("{:04}-{:02}-{:02}", date.year, date.month, date.day)
}
pub fn calendar_month_label(date: CalendarDate) -> String {
format!("{} {}", MONTH_NAMES[(date.month - 1) as usize], date.year)
}
pub fn calendar_weeks(month: CalendarDate) -> Vec<[CalendarDate; 7]> {
let first = calendar_month_start(month);
let start = calendar_add_days(first, -(calendar_weekday(first) as i64));
(0..6)
.map(|week| {
let base = calendar_add_days(start, week * 7);
core::array::from_fn(|day| calendar_add_days(base, day as i64))
})
.collect()
}
fn calendar_month_index(date: CalendarDate) -> i64 {
date.year as i64 * 12 + date.month as i64 - 1
}
fn calendar_from_index(index: i64) -> CalendarDate {
let year = index.div_euclid(12);
let month = (index.rem_euclid(12) + 1) as u32;
CalendarDate {
year: year as i32,
month,
day: 1,
}
}
#[derive(Clone)]
struct CalendarInternal {
uncontrolled_month: Option<CalendarDate>,
uncontrolled_value: Option<CalendarDate>,
focused_date: Option<CalendarDate>,
seen_value: Option<CalendarDate>,
strip_seed: Option<f32>,
viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl CalendarInternal {
fn new(cx: &mut App) -> Self {
Self {
uncontrolled_month: None,
uncontrolled_value: None,
focused_date: None,
seen_value: None,
strip_seed: None,
viewport_bounds: Rc::new(RefCell::new(None)),
focus_handle: cx.focus_handle(),
}
}
}
#[derive(IntoElement)]
pub struct Calendar {
id: ElementId,
label: SharedString,
value: Option<CalendarDate>,
default_value: Option<CalendarDate>,
month: Option<CalendarDate>,
min_date: Option<CalendarDate>,
max_date: Option<CalendarDate>,
disabled_dates: Option<Rc<dyn Fn(CalendarDate) -> bool>>,
show_today: bool,
disabled: bool,
width: Option<Pixels>,
on_change: Option<CalendarDateHandler>,
on_month_change: Option<CalendarDateHandler>,
}
impl Calendar {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
default_value: None,
month: None,
min_date: None,
max_date: None,
disabled_dates: None,
show_today: false,
disabled: false,
width: None,
on_change: None,
on_month_change: None,
}
}
pub fn value(mut self, value: CalendarDate) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, value: CalendarDate) -> Self {
self.default_value = Some(value);
self
}
pub fn month(mut self, month: CalendarDate) -> Self {
self.month = Some(month);
self
}
pub fn min_date(mut self, date: CalendarDate) -> Self {
self.min_date = Some(date);
self
}
pub fn max_date(mut self, date: CalendarDate) -> Self {
self.max_date = Some(date);
self
}
pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
self.disabled_dates = Some(Rc::new(matcher));
self
}
pub fn show_today(mut self, show: bool) -> Self {
self.show_today = show;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_change(
mut self,
handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
pub fn on_month_change(
mut self,
handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
) -> Self {
self.on_month_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for Calendar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let today = {
self.value.or(self.default_value).unwrap_or(CalendarDate {
year: 2026,
month: 11,
day: 27,
})
};
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-calendar-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
let seed_value = self.value.or(self.default_value);
let mut st = CalendarInternal::new(cx);
st.uncontrolled_value = seed_value;
st.uncontrolled_month = seed_value.map(calendar_month_start);
st
});
if let Some(ext) = self.value {
let seen = internal.read(cx).seen_value;
if seen != Some(ext) {
internal.update(cx, |s, _| {
s.seen_value = Some(ext);
if s.uncontrolled_value != Some(ext) {
s.uncontrolled_value = Some(ext);
}
if s.uncontrolled_month.is_none() {
s.uncontrolled_month = Some(calendar_month_start(ext));
}
});
}
}
let is_ctrl_value = self.value.is_some();
let is_ctrl_month = self.month.is_some();
let month = self
.month
.map(calendar_month_start)
.or_else(|| internal.read(cx).uncontrolled_month)
.unwrap_or_else(|| calendar_month_start(today));
let value = if is_ctrl_value {
self.value
} else {
internal.read(cx).uncontrolled_value
};
let min_bound = self.min_date;
let max_bound = self.max_date;
let matcher = self.disabled_dates.clone();
let is_disabled = move |date: CalendarDate| -> bool {
(min_bound.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
|| (max_bound
.is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
|| matcher.as_ref().is_some_and(|f| f(date))
};
let target = calendar_month_index(month);
let snap_state = internal.read(cx).clone();
let strip_seed = snap_state.strip_seed;
let strip_opts = match strip_seed {
Some(seed) if (seed - target as f32).abs() > 1.5 => {
let start = target as f32 - (target as f32 - seed).signum();
internal.update(cx, |s, _| s.strip_seed = None);
SpringOptions::new(calendar_strip_spring())
.with_initial_value(start)
.with_rest_thresholds(0.002, 0.02)
}
_ => SpringOptions::new(calendar_strip_spring()).with_rest_thresholds(0.002, 0.02),
};
let position = arc_spring_with_options(
(self.id.clone(), "strip"),
target as f32,
strip_opts,
window,
cx,
)
.value;
let moving = (position - target as f32).abs() > 0.002;
if moving {
window.request_animation_frame();
}
let pane_lo = (position as i64).min(target);
let pane_hi = (position as i64).max(target);
let pane_indexes: Vec<i64> = [pane_lo, target, pane_hi]
.into_iter()
.collect::<std::collections::BTreeSet<i64>>()
.into_iter()
.collect();
let _ = now;
let st_change = internal.clone();
let ch_change = self.on_change.clone();
let cm_change = self.on_month_change.clone();
let is_ctrl_m = is_ctrl_month;
#[allow(clippy::type_complexity)]
let change_month: CalendarMonthChange = Rc::new(
move |next: CalendarDate,
st: &gpui_kit::Entity<CalendarInternal>,
window: &mut Window,
cx: &mut App| {
let normalized = calendar_month_start(next);
let prev = st.read(cx).uncontrolled_month;
let seed_moved = prev
.map(|p| (calendar_month_index(normalized) - calendar_month_index(p)).abs() > 2)
.unwrap_or(false);
st.update(cx, |s, _| {
if !is_ctrl_m {
s.uncontrolled_month = Some(normalized);
}
if seed_moved {
s.strip_seed = prev.map(|p| calendar_month_index(p) as f32);
}
});
if let Some(handler) = &cm_change {
handler(&normalized, window, cx);
}
},
);
let _ = &st_change;
let _ = &ch_change;
let disc_value = value;
let disc_of = move |pane_month: CalendarDate| -> Option<(usize, f32, f32)> {
let v = disc_value?;
let grid_start = calendar_add_days(
calendar_month_start(pane_month),
-(calendar_weekday(calendar_month_start(pane_month)) as i64),
);
let index = calendar_to_epoch_days(v) - calendar_to_epoch_days(grid_start);
if !(0..42).contains(&index) {
return None;
}
Some((index as usize, index as f32 % 7.0, (index / 7) as f32))
};
let prev_disabled = self.min_date.is_some_and(|m| {
calendar_month_index(calendar_add_months(month, -1))
< calendar_month_index(calendar_month_start(m))
});
let next_disabled = self.max_date.is_some_and(|m| {
calendar_month_index(calendar_add_months(month, 1))
> calendar_month_index(calendar_month_start(m))
});
let today_selectable = !is_disabled(today);
let today_idle =
calendar_same_month(month, today) && (!today_selectable || value == Some(today));
let nav_color = colors.text_secondary;
let disabled_flag = self.disabled;
let show_today_flag = self.show_today;
let prev_disabled_flag = prev_disabled;
let next_disabled_flag = next_disabled;
let today_idle_flag = today_idle;
let today_selectable_flag = today_selectable;
let month_for_nav = month;
let header = div()
.flex()
.flex_row()
.items_center()
.justify_between()
.mb(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(SharedString::from(calendar_month_label(month))),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(2.0))
.when(show_today_flag, |this| {
this.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"today-button".into(),
))
.test_support()
.aria_label(SharedString::from(format!(
"Today, {}",
calendar_date_key(today)
)))
.text_size(Typography::TEXT_XS)
.font_medium()
.px(px(8.0))
.h(px(26.0))
.flex()
.items_center()
.rounded(Radii::PILL)
.text_color(
if today_idle_flag || disabled_flag || !today_selectable_flag {
colors.text_muted
} else {
colors.foreground
},
)
.when(
!today_idle_flag && !disabled_flag && today_selectable_flag,
|this| {
this.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
},
)
.on_click({
let st = internal.clone();
let ch = self.on_change.clone();
let cm = change_month.clone();
let is_ctrl_v = is_ctrl_value;
let idle = today_idle_flag;
let off = disabled_flag || !today_selectable_flag;
let month_here = month_for_nav;
move |_, window, cx| {
if idle || off {
return;
}
st.update(cx, |s, _| {
if !is_ctrl_v {
s.uncontrolled_value = Some(today);
}
s.focused_date = Some(today);
});
if !calendar_same_month(month_here, today) {
cm(today, &st, window, cx);
}
if let Some(handler) = &ch {
handler(&today, window, cx);
}
window.refresh();
}
})
.child(SharedString::from("Today")),
)
})
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"prev-month".into(),
))
.test_support()
.aria_label("Previous month")
.w(px(26.0))
.h(px(26.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.text_color(if prev_disabled_flag || disabled_flag {
colors.text_muted
} else {
nav_color
})
.when(!prev_disabled_flag && !disabled_flag, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
})
.on_click({
let st = internal.clone();
let cm = change_month.clone();
let off = prev_disabled_flag || disabled_flag;
let month_here = month_for_nav;
move |_, window, cx| {
if off {
return;
}
let prev = calendar_add_months(month_here, -1);
cm(prev, &st, window, cx);
window.refresh();
}
})
.child(
div()
.text_size(Typography::TEXT_SM)
.child(SharedString::from("‹")),
),
)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"next-month".into(),
))
.test_support()
.aria_label("Next month")
.w(px(26.0))
.h(px(26.0))
.flex()
.items_center()
.justify_center()
.rounded(Radii::PILL)
.text_color(if next_disabled_flag || disabled_flag {
colors.text_muted
} else {
nav_color
})
.when(!next_disabled_flag && !disabled_flag, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
})
.on_click({
let st = internal.clone();
let cm = change_month.clone();
let off = next_disabled_flag || disabled_flag;
let month_here = month_for_nav;
move |_, window, cx| {
if off {
return;
}
let next = calendar_add_months(month_here, 1);
cm(next, &st, window, cx);
window.refresh();
}
})
.child(
div()
.text_size(Typography::TEXT_SM)
.child(SharedString::from("›")),
),
),
);
let viewport_width = snap_state
.viewport_bounds
.borrow()
.map_or(280.0_f32, |b| f32::from(b.size.width).max(1.0));
let strip_offset_px = -(position - target as f32) * viewport_width;
let pane_id = self.id.clone();
let pane_focus = snap_state.focus_handle.clone();
let pane_internal = internal.clone();
let pane_on_change = self.on_change.clone();
let pane_disabled = self.disabled;
let pane_is_ctrl_value = is_ctrl_value;
let mut render_pane = move |pane_month: CalendarDate, present: bool| -> AnyElement {
let disc = disc_of(pane_month);
let pane_key = calendar_date_key(pane_month);
let (disc_op, disc_scale, disc_col, disc_row) = if let Some((_, col, row)) = disc {
let col_s = if reduced || moving {
col
} else {
arc_spring(
(
pane_id.clone(),
SharedString::from(format!("disc-col-{pane_key}")),
),
col,
motion.spring.morph,
window,
cx,
)
};
let row_s = if reduced || moving {
row
} else {
arc_spring(
(
pane_id.clone(),
SharedString::from(format!("disc-row-{pane_key}")),
),
row,
motion.spring.morph,
window,
cx,
)
};
(1.0_f32, 1.0_f32, col_s, row_s)
} else {
(0.0, 0.6, 0.0, 0.0)
};
let mut week_els: Vec<AnyElement> = Vec::with_capacity(6);
for week in calendar_weeks(pane_month) {
let mut day_els: Vec<AnyElement> = Vec::with_capacity(7);
for date in week {
let key = calendar_date_key(date);
let selected = value.is_some_and(|v| calendar_same_day(v, date));
let is_today = calendar_same_day(date, today);
let disabled_here = is_disabled(date);
let outside = !calendar_same_month(date, pane_month);
let day_fg = if disabled_here || outside {
colors.text_muted
} else if selected {
colors.surface
} else if is_today {
colors.control_fill
} else {
colors.foreground
};
let bg = if selected {
Some(colors.control_fill)
} else if is_today {
Some(oklab_mix(colors.control_fill, colors.surface, 0.10))
} else {
None
};
let cell_size = viewport_width / 7.0;
day_els.push(
div()
.id(ElementId::NamedChild(
pane_id.clone().into(),
SharedString::from(format!("day-{key}")),
))
.test_support()
.when(present, |this| {
this.role(Role::GridCell)
.aria_selected(selected)
.aria_label(SharedString::from(key.clone()))
})
.w(px(cell_size - 4.0))
.h(px(34.0))
.m(px(2.0))
.flex()
.items_center()
.justify_center()
.rounded(px(10.0))
.text_size(Typography::TEXT_XS)
.text_color(day_fg)
.when_some(bg, |this, bg| this.bg(bg))
.when(!disabled_here && present && !self.disabled, |this| {
this.cursor_pointer().when(!selected, |this| {
this.hover(move |s| {
s.bg(oklab_mix(colors.foreground, colors.surface, 0.08))
})
})
})
.on_click({
let st = pane_internal.clone();
let pane_focus_for_click = pane_focus.clone();
let ch = pane_on_change.clone();
let is_ctrl_v = pane_is_ctrl_value;
let disabled_d = disabled_here;
let off = pane_disabled;
move |_, window, cx| {
if disabled_d || !present || off {
return;
}
st.update(cx, |s, _| {
if !is_ctrl_v {
s.uncontrolled_value = Some(date);
}
s.focused_date = Some(date);
});
window.focus(&pane_focus_for_click, cx);
if let Some(handler) = &ch {
handler(&date, window, cx);
}
window.refresh();
}
})
.child(SharedString::from(date.day.to_string()))
.into_any_element(),
);
}
week_els.push(div().flex().flex_row().children(day_els).into_any_element());
}
let disc_el = if disc.is_some() || disc_op > 0.01 {
let cell_w = viewport_width / 7.0;
Some(
div()
.absolute()
.left(px(2.0 + disc_col * cell_w))
.top(px(2.0 + disc_row * 38.0))
.w(px(cell_w - 4.0))
.h(px(cell_w - 4.0))
.h(px(34.0))
.rounded(px(10.0))
.bg(colors.control_fill)
.opacity(disc_op * disc_scale),
)
} else {
None
};
div()
.relative()
.w(px(viewport_width))
.flex_none()
.opacity(if present { 1.0 } else { 0.4 })
.when_some(disc_el, |this, el| this.child(el))
.child(
div()
.relative()
.flex()
.flex_col()
.gap(px(2.0))
.children(week_els),
)
.into_any_element()
};
let pane_els: Vec<AnyElement> = pane_indexes
.iter()
.map(|&index| {
let offset_px = (index as f32 - position) * viewport_width;
div()
.absolute()
.left_0()
.top_0()
.ml(px(offset_px))
.child(render_pane(calendar_from_index(index), index == target))
.into_any_element()
})
.collect();
let st_key = internal.clone();
let ch_key = self.on_change.clone();
let cm_key = change_month.clone();
let focus_key = snap_state.focus_handle.clone();
let is_ctrl_vk = is_ctrl_value;
let grid_disabled = self.disabled;
let grid_month = month;
let disabled_matcher = self.disabled_dates.clone();
let min_d = self.min_date;
let max_d = self.max_date;
let is_disabled_fn = move |date: CalendarDate| -> bool {
(min_d.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
|| (max_d.is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
|| disabled_matcher.as_ref().is_some_and(|f| f(date))
};
let grid = div()
.id(ElementId::NamedChild(self.id.clone().into(), "grid".into()))
.test_support()
.role(Role::Grid)
.aria_label(SharedString::from(calendar_month_label(month)))
.track_focus(&focus_key)
.relative()
.overflow_hidden()
.h(px(2.0 + 6.0 * 38.0))
.on_mouse_down(MouseButton::Left, {
let focus_grid = focus_key.clone();
move |_, window, cx| {
window.focus(&focus_grid, cx);
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if grid_disabled {
return;
}
let key = event.keystroke.key.as_str();
let shift = event.keystroke.modifiers.shift;
let from = st_key.read(cx).focused_date.or(value).unwrap_or(today);
let (next, step_dir): (CalendarDate, i64) = match key {
"enter" | " " | "space" => {
if !is_disabled_fn(from) {
st_key.update(cx, |s, _| {
if !is_ctrl_vk {
s.uncontrolled_value = Some(from);
}
});
if let Some(handler) = &ch_key {
handler(&from, window, cx);
}
}
window.refresh();
return;
}
"left" | "arrowleft" => (calendar_add_days(from, -1), -1),
"right" | "arrowright" => (calendar_add_days(from, 1), 1),
"up" | "arrowup" => (calendar_add_days(from, -7), -1),
"down" | "arrowdown" => (calendar_add_days(from, 7), 1),
"home" => (calendar_add_days(from, -(calendar_weekday(from) as i64)), 1),
"end" => (
calendar_add_days(from, 6 - calendar_weekday(from) as i64),
-1,
),
"pageup" => (calendar_add_months(from, if shift { -12 } else { -1 }), -1),
"pagedown" => (calendar_add_months(from, if shift { 12 } else { 1 }), 1),
_ => return,
};
let mut clamped = next;
if let Some(m) = min_d
&& calendar_to_epoch_days(clamped) < calendar_to_epoch_days(m)
{
clamped = m;
}
if let Some(m) = max_d
&& calendar_to_epoch_days(clamped) > calendar_to_epoch_days(m)
{
clamped = m;
}
let mut final_date = clamped;
for _ in 0..42 {
if !is_disabled_fn(final_date) {
break;
}
final_date = calendar_add_days(final_date, step_dir);
}
if is_disabled_fn(final_date) || calendar_same_day(final_date, from) {
return;
}
st_key.update(cx, |s, _| {
s.focused_date = Some(final_date);
});
if !calendar_same_month(final_date, grid_month) {
cm_key(final_date, &st_key, window, cx);
}
window.refresh();
})
.child(canvas(
{
let vp_ref = snap_state.viewport_bounds.clone();
move |rect, _, _| {
*vp_ref.borrow_mut() = Some(rect);
}
},
|_, _, _, _| {},
))
.child(
div().absolute().inset_0().child(
div()
.absolute()
.left(px(strip_offset_px))
.top_0()
.flex()
.flex_row()
.children(pane_els),
),
);
let weekdays_row = div()
.flex()
.flex_row()
.mb(px(2.0))
.children(WEEKDAY_LABELS.iter().map(|label| {
div()
.flex_1()
.text_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(SharedString::from(*label))
.into_any_element()
}));
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.when(self.disabled, |this| this.opacity(0.5))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.mb(Spacing::S1)
.child(self.label.clone()),
)
.child(header)
.child(weekdays_row)
.child(grid)
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
const D: fn(i32, u32, u32) -> CalendarDate =
|year, month, day| CalendarDate { year, month, day };
#[test]
fn calendar_civil_math_round_trips_and_clamps_months() {
assert_eq!(calendar_days_in_month(2026, 2), 28);
assert_eq!(calendar_days_in_month(2024, 2), 29);
let d = D(2026, 11, 27);
assert_eq!(calendar_from_epoch_days(calendar_to_epoch_days(d)), d);
assert_eq!(calendar_weekday(d), 5);
let shifted = calendar_add_months(D(2026, 1, 31), 1);
assert_eq!(shifted, D(2026, 2, 28));
assert_eq!(calendar_add_days(D(2026, 11, 30), 1), D(2026, 12, 1));
let weeks = calendar_weeks(D(2026, 11, 15));
assert_eq!(calendar_weekday(weeks[0][0]), 0);
assert_eq!(
calendar_to_epoch_days(weeks[5][6]) - calendar_to_epoch_days(weeks[0][0]),
41
);
}
#[test]
fn calendar_month_labels_and_keys_format() {
assert_eq!(calendar_month_label(D(2026, 11, 1)), "November 2026");
assert_eq!(calendar_date_key(D(2026, 11, 5)), "2026-11-05");
assert_eq!(calendar_month_index(D(2026, 11, 27)), 2026 * 12 + 10);
}
struct CalendarHost {
value: Option<CalendarDate>,
events: Rc<RefCell<Vec<String>>>,
disabled: bool,
}
impl Render for CalendarHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
div().w(px(320.0)).p(px(16.0)).child(
Calendar::new("cal-test", "Start date")
.value(self.value.unwrap_or(D(2026, 11, 10)))
.disabled(self.disabled)
.on_change(cx.listener({
let events = events.clone();
move |this, date: &CalendarDate, _, cx| {
events.borrow_mut().push(calendar_date_key(*date));
this.value = Some(*date);
cx.notify();
}
})),
)
}
}
fn cal_element(name: &str) -> ElementId {
ElementId::NamedChild(ElementId::Name("cal-test".into()).into(), name.into())
}
#[gpui_kit::test]
fn calendar_picks_days_and_navigates_months_by_keyboard(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let host = CalendarHost {
value: Some(D(2026, 11, 10)),
events: Rc::new(RefCell::new(Vec::new())),
disabled: false,
};
let events = host.events.clone();
let (view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
let grid = window.find(cal_element("grid"));
assert_eq!(grid.role(), Some(Role::Grid));
window.click(cal_element("day-2026-11-15"), cx);
});
assert_eq!(
events.borrow().last().map(String::as_str),
Some("2026-11-15")
);
cx.update(|window, cx| {
window.click(cal_element("grid"), cx);
window.press("right", cx);
window.press("enter", cx);
});
assert_eq!(
events.borrow().last().map(String::as_str),
Some("2026-11-19")
);
cx.update(|window, cx| {
if let Some(el) = window.try_find(cal_element("next-month")) {
let b = el.bounds();
eprintln!(
"NEXT bounds=({},{}) size=({},{})",
f32::from(b.origin.x),
f32::from(b.origin.y),
f32::from(b.size.width),
f32::from(b.size.height)
);
} else {
eprintln!("NEXT missing");
}
window.press("pagedown", cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(600));
cx.update(|window, cx| {
for _ in 0..5 {
window.render_frame(cx);
}
window.press("enter", cx);
});
assert_eq!(
events.borrow().last().map(String::as_str),
Some("2026-12-19")
);
view.update(cx, |host, cx| {
host.disabled = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.click(cal_element("day-2026-12-05"), cx);
window.press("right", cx);
});
assert_eq!(
events.borrow().last().map(String::as_str),
Some("2026-12-19")
);
}
#[gpui_kit::test]
fn calendar_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let host = CalendarHost {
value: Some(D(2026, 11, 10)),
events: Rc::new(RefCell::new(Vec::new())),
disabled: false,
};
let events = host.events.clone();
let (_view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
window.click(cal_element("day-2026-11-20"), cx);
});
assert_eq!(
events.borrow().last().map(String::as_str),
Some("2026-11-20")
);
}
}