A month grid for picking a single date or a date range.
use gpui::{div, prelude::*, Context, Window};
use crate::theme::ActiveTheme;
use crate::ui::calendar::{Calendar, CivilDate, DateRange};
/// Fixed so the preview looks the same every day; pass your app's real date instead.
const TODAY: CivilDate = CivilDate { year: 2026, month: 11, day: 12 };
pub struct CalendarView {
month: CivilDate,
date: Option<CivilDate>,
range_month: CivilDate,
range: DateRange,
}
impl Default for CalendarView {
fn default() -> Self {
Self {
month: TODAY,
date: Some(TODAY),
range_month: TODAY,
range: DateRange::new(Some(TODAY.add_days(4)), Some(TODAY.add_days(10))),
}
}
}
impl Render for CalendarView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let frame = || {
div()
.rounded(theme.radius)
.border_1()
.border_color(theme.border)
.bg(theme.background)
.shadow_sm()
};
div()
.flex()
.items_start()
.gap_6()
.child(
frame().child(
Calendar::new("calendar", self.month)
.today(Some(TODAY))
.selected(self.date)
.on_select(cx.listener(|this, date: &CivilDate, _, cx| {
this.date = Some(*date);
cx.notify();
}))
.on_month_change(cx.listener(|this, month: &CivilDate, _, cx| {
this.month = *month;
cx.notify();
})),
),
)
.child(
frame().child(
Calendar::new("range-calendar", self.range_month)
.today(Some(TODAY))
.range(self.range)
.on_range_change(cx.listener(|this, range: &DateRange, _, cx| {
this.range = *range;
cx.notify();
}))
.on_month_change(cx.listener(|this, month: &CivilDate, _, cx| {
this.range_month = *month;
cx.notify();
})),
),
)
}
}Installation
Copies src/ui/calendar.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/calendar.rs.src/ui/calendar.rs use std::{cell::Cell, rc::Rc, sync::Arc}; use gpui::{ div, prelude::*, px, svg, AnimationExt, App, ElementId, Entity, FontWeight, Hsla, Interpolate, Pixels, SharedString, SpringAnimation, SpringAnimationElement, SpringConfig, Window, }; use crate::theme::ActiveTheme; use crate::icons::{CHEVRON_LEFT, CHEVRON_RIGHT}; const CELL: Pixels = px(32.0); const PADDING: Pixels = px(12.0); /// The calendar's outer width, for sizing a popover or card around it. pub const CALENDAR_WIDTH: Pixels = px(7.0 * 32.0 + 2.0 * 12.0); pub const MONTH_NAMES: [&str; 12] = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Weekday { #[default] Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, } impl Weekday { const ALL: [Weekday; 7] = [ Weekday::Sunday, Weekday::Monday, Weekday::Tuesday, Weekday::Wednesday, Weekday::Thursday, Weekday::Friday, Weekday::Saturday, ]; /// 0 for Sunday through 6 for Saturday. pub fn index(self) -> usize { self as usize } pub fn short_name(self) -> &'static str { ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"][self.index()] } } pub fn is_leap_year(year: i32) -> bool { (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 } /// Returns 0 for a month outside 1..=12. pub fn days_in_month(year: i32, month: u8) -> u8 { match month { 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, 4 | 6 | 9 | 11 => 30, 2 if is_leap_year(year) => 29, 2 => 28, _ => 0, } } /// A day in the proleptic Gregorian calendar, with no time or time zone. Fields are ordered /// year, month, day so the derived ordering is chronological. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CivilDate { pub year: i32, pub month: u8, pub day: u8, } impl CivilDate { /// `None` for dates that don't exist, such as February 30. pub fn new(year: i32, month: u8, day: u8) -> Option<Self> { (day >= 1 && day <= days_in_month(year, month)).then_some(Self { year, month, day }) } /// Days since 1970-01-01, after Howard Hinnant's `days_from_civil`: shifting the year to /// start in March puts the leap day last, so every month before it has a fixed offset. pub fn to_days(self) -> i64 { let month = self.month as i64; let year = self.year as i64 - (month <= 2) as i64; let era = year.div_euclid(400); let year_of_era = year.rem_euclid(400); let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + self.day as i64 - 1; let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; era * 146_097 + day_of_era - 719_468 } /// The inverse of [`CivilDate::to_days`]. pub fn from_days(days: i64) -> Self { let z = days + 719_468; let era = z.div_euclid(146_097); let day_of_era = z.rem_euclid(146_097); let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); let shifted_month = (5 * day_of_year + 2) / 153; let day = day_of_year - (153 * shifted_month + 2) / 5 + 1; let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 }; let year = year_of_era + era * 400 + (month <= 2) as i64; Self { year: year as i32, month: month as u8, day: day as u8, } } pub fn weekday(self) -> Weekday { // 1970-01-01 was a Thursday. Weekday::ALL[(self.to_days() + 4).rem_euclid(7) as usize] } pub fn add_days(self, days: i64) -> Self { Self::from_days(self.to_days() + days) } /// Moves by whole months, clamping the day so January 31 plus one month is February 28/29. pub fn add_months(self, months: i32) -> Self { let index = self.year * 12 + (self.month as i32 - 1) + months; let year = index.div_euclid(12); let month = (index.rem_euclid(12) + 1) as u8; Self { year, month, day: self.day.min(days_in_month(year, month)), } } pub fn first_of_month(self) -> Self { Self { day: 1, ..self } } pub fn same_month(self, other: Self) -> bool { self.year == other.year && self.month == other.month } pub fn month_name(self) -> &'static str { MONTH_NAMES[(self.month.clamp(1, 12) - 1) as usize] } } /// A date range being picked. `end` stays `None` until the second click. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct DateRange { pub start: Option<CivilDate>, pub end: Option<CivilDate>, } impl DateRange { pub fn new(start: Option<CivilDate>, end: Option<CivilDate>) -> Self { Self { start, end } } /// The range after clicking `day`: the first click starts a range, the second closes it /// (swapping ends if needed), and a click on a complete range starts over. pub fn extend(self, day: CivilDate) -> Self { match (self.start, self.end) { (Some(start), None) if day >= start => Self::new(Some(start), Some(day)), (Some(start), None) => Self::new(Some(day), Some(start)), _ => Self::new(Some(day), None), } } pub fn contains(self, day: CivilDate) -> bool { match (self.start, self.end) { (Some(start), Some(end)) => start <= day && day <= end, (Some(start), None) => start == day, _ => false, } } } type DateHandler = Rc<dyn Fn(&CivilDate, &mut Window, &mut App) + 'static>; type RangeHandler = Rc<dyn Fn(&DateRange, &mut Window, &mut App) + 'static>; /// A month grid for picking a single date or a range. The parent view owns the displayed /// month and the selection: `on_month_change` and `on_select` / `on_range_change` ask it to /// update them. Setting `range` switches the calendar to range selection. #[derive(IntoElement)] pub struct Calendar { id: ElementId, month: CivilDate, today: Option<CivilDate>, week_starts_on: Weekday, selected: Option<CivilDate>, range: Option<DateRange>, on_select: Option<DateHandler>, on_range_change: Option<RangeHandler>, on_month_change: Option<DateHandler>, } impl Calendar { /// `month` is any day in the month to show. pub fn new(id: impl Into<ElementId>, month: CivilDate) -> Self { Self { id: id.into(), month: month.first_of_month(), today: None, week_starts_on: Weekday::default(), selected: None, range: None, on_select: None, on_range_change: None, on_month_change: None, } } /// The day to mark as today. Pass it in from your app's clock: the calendar has none of its /// own, because `SystemTime::now()` panics on wasm32-unknown-unknown. pub fn today(mut self, today: Option<CivilDate>) -> Self { self.today = today; self } pub fn week_starts_on(mut self, weekday: Weekday) -> Self { self.week_starts_on = weekday; self } /// The selected day in single selection. pub fn selected(mut self, selected: Option<CivilDate>) -> Self { self.selected = selected; self } /// Receives the clicked day in single selection. pub fn on_select(mut self, handler: impl Fn(&CivilDate, &mut Window, &mut App) + 'static) -> Self { self.on_select = Some(Rc::new(handler)); self } /// The selected range; switches to range selection. pub fn range(mut self, range: DateRange) -> Self { self.range = Some(range); self } /// Receives the *next* range, already extended by the clicked day. pub fn on_range_change( mut self, handler: impl Fn(&DateRange, &mut Window, &mut App) + 'static, ) -> Self { self.on_range_change = Some(Rc::new(handler)); self } /// Receives the first day of the month to show next. pub fn on_month_change( mut self, handler: impl Fn(&CivilDate, &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.theme().clone(); let month = self.month; let calendar_id = Arc::new(self.id.clone()); let clear = gpui::transparent_black(); // Ghost buttons, like shadcn's: the hover background eases in and out. let mut nav_button = |id: &'static str, icon: &'static [u8], target: CivilDate| { let handler = self.on_month_change.clone(); let key = ElementId::NamedChild(calendar_id.clone(), id.into()); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered; let paint = Paint { bg: if hovered { theme.accent } else { clear }, fg: theme.foreground, border: clear, }; let button = div() .id(id) .flex() .flex_none() .items_center() .justify_center() .size(CELL) .rounded(theme.radius) .cursor_pointer() .on_hover(track_hover(&ease)) .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&target, window, cx)) }) .child(svg().data(icon).flex_none().size(px(16.0)).text_color(theme.foreground)); ease_to(button, key, &ease, paint, cx, |this, paint| this.bg(paint.bg)) }; let previous = nav_button("previous-month", CHEVRON_LEFT, month.add_months(-1)); let next = nav_button("next-month", CHEVRON_RIGHT, month.add_months(1)); let header = div() .flex() .items_center() .justify_between() .h(CELL) .child(previous) .child( div() .text_sm() .font_weight(FontWeight::MEDIUM) .child(SharedString::from(format!("{} {}", month.month_name(), month.year))), ) .child(next); let weekdays = div().flex().children((0..7).map(|offset| { let weekday = Weekday::ALL[(self.week_starts_on.index() + offset) % 7]; div() .w(CELL) .flex() .justify_center() .text_xs() .text_color(theme.muted_foreground) .child(weekday.short_name()) })); // Leading days from the previous month fill the first week; only as many weeks are // drawn as the month spans, as react-day-picker does without `fixedWeeks`. let lead = (month.weekday().index() + 7 - self.week_starts_on.index()) % 7; let first_cell = month.add_days(-(lead as i64)); let weeks = (lead + days_in_month(month.year, month.month) as usize).div_ceil(7); let range = self.range; let complete_range = range.and_then(|r| r.start.zip(r.end)); let mut day_cell = |ix: usize| { let day = first_cell.add_days(ix as i64); let outside = !day.same_month(month); let (is_start, is_end, in_range) = match range { Some(range) => ( range.start == Some(day), range.end == Some(day), range.contains(day), ), None => (false, false, false), }; let selected = match range { Some(_) => is_start || is_end, None => self.selected == Some(day), }; let is_today = self.today == Some(day); // The band between range ends: square inside, rounded only where it begins and ends. let band = complete_range.is_some_and(|(start, end)| start != end) && in_range; let on_select = self.on_select.clone(); let on_range_change = self.on_range_change.clone(); let on_month_change = self.on_month_change.clone(); // Keyed by date, so cells of a newly shown month mount fresh instead of fading. let key = ElementId::NamedChild( calendar_id.clone(), format!("day-{}-{}-{}", day.year, day.month, day.day).into(), ); let ease = ease_state(key.clone(), window, cx); let hovered = ease.read(cx).hovered && !selected; // Selection and hover ease like shadcn's day buttons (`transition-all`). let (bg, fg) = if selected { (theme.primary, theme.primary_foreground) } else if hovered { (theme.accent, theme.accent_foreground) } else if band { // The band behind the cell already carries the accent. (clear, theme.accent_foreground) } else if is_today { (theme.accent, theme.accent_foreground) } else if outside { (clear, theme.muted_foreground) } else { (clear, theme.foreground) }; let paint = Paint { bg, fg, border: clear }; let day_button = div() .id(("day", ix)) .size_full() .flex() .items_center() .justify_center() .rounded(theme.radius) .text_sm() .when(is_today || selected, |this| this.font_weight(FontWeight::MEDIUM)) .cursor_pointer() .on_hover(track_hover(&ease)) .on_click(move |_, window, cx| { match range { Some(range) => { if let Some(handler) = &on_range_change { handler(&range.extend(day), window, cx); } } None => { if let Some(handler) = &on_select { handler(&day, window, cx); } } } // Picking a neighbouring month's day brings that month into view. if outside { if let Some(handler) = &on_month_change { handler(&day.first_of_month(), window, cx); } } }) .child(SharedString::from(day.day.to_string())); div() .size(CELL) .flex_none() .when(band, |this| { this.bg(theme.accent) .when(is_start, |this| this.rounded_l(theme.radius)) .when(is_end, |this| this.rounded_r(theme.radius)) }) .child(ease_to(day_button, key, &ease, paint, cx, |this, paint| { this.bg(paint.bg).text_color(paint.fg) })) }; let mut rows = Vec::with_capacity(weeks); for week in 0..weeks { let cells: Vec<_> = (0..7).map(|col| day_cell(week * 7 + col)).collect(); rows.push(div().flex().children(cells)); } let grid = div().flex().flex_col().gap_2().children(rows); div() .id(self.id) .flex() .flex_col() .gap_4() .p(PADDING) .w(CALENDAR_WIDTH) .text_color(theme.foreground) .child(header) .child(div().flex().flex_col().gap_2().child(weekdays).child(grid)) } } /// shadcn's `transition-colors` (150ms) as a critically damped spring: quick, no overshoot. const EASE: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// The colors a control eases between as it is hovered or changes state. #[derive(Clone, Copy, PartialEq)] struct Paint { bg: Hsla, fg: Hsla, border: Hsla, } impl Paint { fn mix(self, to: Self, t: f32) -> Self { Self { bg: mix(self.bg, to.bg, t), fg: mix(self.fg, to.fg, t), border: mix(self.border, to.border, t), } } } /// Blends like CSS: a transparent end only fades the other color in or out, rather than /// passing through a dark gray. fn mix(from: Hsla, to: Hsla, t: f32) -> Hsla { let from = if from.a == 0.0 { to.opacity(0.0) } else { from }; let to = if to.a == 0.0 { from.opacity(0.0) } else { to }; Hsla::interpolate(from, to, t) } /// One control's hover flag and color transition, kept across frames. #[derive(Default)] struct Ease { hovered: bool, /// The colors eased from and to; `None` before the first render. from_to: Option<(Paint, Paint)>, /// Every new target moves the spring on by one, so an interrupted transition keeps its /// velocity; `start` is where the current one began. start: f32, run: f32, /// What the spring painted last and at which position, where the next transition starts. shown: Rc<Cell<Option<(Paint, f32)>>>, } fn ease_state(key: ElementId, window: &mut Window, cx: &mut App) -> Entity<Ease> { window.use_keyed_state(key, cx, |_, _| Ease::default()) } /// An `on_hover` listener that records hover in `ease`, re-rendering only on a change. fn track_hover(ease: &Entity<Ease>) -> impl Fn(&bool, &mut Window, &mut App) + 'static { let ease = ease.clone(); move |hovered, _, cx| { ease.update(cx, |ease, cx| { if ease.hovered != *hovered { ease.hovered = *hovered; cx.notify(); } }) } } /// Paints `element` with colors easing toward `target` from whatever was showing, like a CSS /// color transition. A newly mounted element starts at `target`, so nothing fades in on load. fn ease_to<E: IntoElement + 'static>( element: E, id: ElementId, ease: &Entity<Ease>, target: Paint, cx: &mut App, paint: impl FnOnce(E, Paint) -> E + 'static, ) -> SpringAnimationElement<E> { let (from, start, run, shown) = ease.update(cx, |ease, _| { match ease.from_to { Some((_, to)) if to == target => {} Some((_, to)) => { let (shown, position) = ease.shown.get().unwrap_or((to, ease.run)); ease.from_to = Some((shown, target)); ease.start = position; ease.run += 1.0; } None => ease.from_to = Some((target, target)), } let from = ease.from_to.map_or(target, |(from, _)| from); (from, ease.start, ease.run, ease.shown.clone()) }); element.with_spring(id, SpringAnimation::new(EASE).to(run), move |element, position| { let span = run - start; let t = if span > 0.0 { ((position - start) / span).clamp(0.0, 1.0) } else { 1.0 }; let now = from.mix(target, t); shown.set(Some((now, position))); paint(element, now) }) }Register the module
// src/ui/mod.rs pub mod calendar;
Usage
use crate::ui::calendar::*;API Reference
Weekday
Weekday::SundayWeekday::MondayWeekday::TuesdayWeekday::WednesdayWeekday::ThursdayWeekday::FridayWeekday::SaturdayCivilDate
A day in the proleptic Gregorian calendar, with no time or time zone. Fields are ordered year, month, day so the derived ordering is chronological.
CivilDate::new(year: i32, month: u8, day: u8) -> Option<Self>None for dates that don't exist, such as February 30.
CivilDate::to_days(self) -> i64Days since 1970-01-01, after Howard Hinnant's days_from_civil: shifting the year to start in March puts the leap day last, so every month before it has a fixed offset.
CivilDate::from_days(days: i64) -> SelfThe inverse of [CivilDate::to_days].
CivilDate::weekday(self) -> WeekdayCivilDate::add_days(self, days: i64) -> SelfCivilDate::add_months(self, months: i32) -> SelfMoves by whole months, clamping the day so January 31 plus one month is February 28/29.
CivilDate::first_of_month(self) -> SelfCivilDate::same_month(self, other: Self) -> boolCivilDate::month_name(self) -> &'static strDateRange
A date range being picked. end stays None until the second click.
DateRange::new(start: Option<CivilDate>, end: Option<CivilDate>) -> SelfDateRange::extend(self, day: CivilDate) -> SelfThe range after clicking day: the first click starts a range, the second closes it (swapping ends if needed), and a click on a complete range starts over.
DateRange::contains(self, day: CivilDate) -> boolCalendar
A month grid for picking a single date or a range. The parent view owns the displayed month and the selection: on_month_change and on_select / on_range_change ask it to update them. Setting range switches the calendar to range selection.
Calendar::new(id: impl Into<ElementId>, month: CivilDate) -> Selfmonth is any day in the month to show.
.today(today: Option<CivilDate>)The day to mark as today. Pass it in from your app's clock: the calendar has none of its own, because SystemTime::now() panics on wasm32-unknown-unknown.
.week_starts_on(weekday: Weekday).selected(selected: Option<CivilDate>)The selected day in single selection.
.on_select(handler: impl Fn(&CivilDate, &mut Window, &mut App) + 'static)Receives the clicked day in single selection.
.range(range: DateRange)The selected range; switches to range selection.
.on_range_change(handler: impl Fn(&DateRange, &mut Window, &mut App) + 'static)Receives the *next* range, already extended by the clicked day.
.on_month_change(handler: impl Fn(&CivilDate, &mut Window, &mut App) + 'static)Receives the first day of the month to show next.