Skip to main content

fc_ui/capabilities/controls/
calendar.rs

1//! Calendar component - Date selection with month/year navigation.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use crate::capabilities::foundation::theme::use_theme;
8use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
9
10type DateSelectCallback = Rc<dyn Fn(&DateValue, &mut Window, &mut App)>;
11type MonthChangeCallback = Rc<dyn Fn(&DateValue, &mut Window, &mut App)>;
12type DateDisabledPredicate = Rc<dyn Fn(&DateValue) -> bool>;
13
14/// Default English weekday abbreviations
15pub const DEFAULT_WEEKDAYS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
16
17/// Default English month names
18pub const DEFAULT_MONTHS: [&str; 12] = [
19    "January",
20    "February",
21    "March",
22    "April",
23    "May",
24    "June",
25    "July",
26    "August",
27    "September",
28    "October",
29    "November",
30    "December",
31];
32
33/// Localization configuration for the Calendar component
34#[derive(Clone)]
35pub struct CalendarLocale {
36    /// Weekday abbreviations (Sunday to Saturday)
37    pub weekdays: [SharedString; 7],
38    /// Full month names (January to December)
39    pub months: [SharedString; 12],
40}
41
42impl CalendarLocale {
43    /// Create a new locale with custom weekdays and months
44    pub fn new(weekdays: [SharedString; 7], months: [SharedString; 12]) -> Self {
45        Self { weekdays, months }
46    }
47
48    /// English locale (default)
49    pub fn english() -> Self {
50        Self {
51            weekdays: DEFAULT_WEEKDAYS.map(|s| s.into()),
52            months: DEFAULT_MONTHS.map(|s| s.into()),
53        }
54    }
55
56    /// French locale
57    pub fn french() -> Self {
58        Self {
59            weekdays: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"].map(|s| s.into()),
60            months: [
61                "Janvier",
62                "Février",
63                "Mars",
64                "Avril",
65                "Mai",
66                "Juin",
67                "Juillet",
68                "Août",
69                "Septembre",
70                "Octobre",
71                "Novembre",
72                "Décembre",
73            ]
74            .map(|s| s.into()),
75        }
76    }
77
78    /// Spanish locale
79    pub fn spanish() -> Self {
80        Self {
81            weekdays: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sá"].map(|s| s.into()),
82            months: [
83                "Enero",
84                "Febrero",
85                "Marzo",
86                "Abril",
87                "Mayo",
88                "Junio",
89                "Julio",
90                "Agosto",
91                "Septiembre",
92                "Octubre",
93                "Noviembre",
94                "Diciembre",
95            ]
96            .map(|s| s.into()),
97        }
98    }
99
100    /// German locale
101    pub fn german() -> Self {
102        Self {
103            weekdays: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"].map(|s| s.into()),
104            months: [
105                "Januar",
106                "Februar",
107                "März",
108                "April",
109                "Mai",
110                "Juni",
111                "Juli",
112                "August",
113                "September",
114                "Oktober",
115                "November",
116                "Dezember",
117            ]
118            .map(|s| s.into()),
119        }
120    }
121
122    /// Portuguese locale
123    pub fn portuguese() -> Self {
124        Self {
125            weekdays: ["Do", "Se", "Te", "Qa", "Qi", "Sx", "Sá"].map(|s| s.into()),
126            months: [
127                "Janeiro",
128                "Fevereiro",
129                "Março",
130                "Abril",
131                "Maio",
132                "Junho",
133                "Julho",
134                "Agosto",
135                "Setembro",
136                "Outubro",
137                "Novembro",
138                "Dezembro",
139            ]
140            .map(|s| s.into()),
141        }
142    }
143
144    /// Italian locale
145    pub fn italian() -> Self {
146        Self {
147            weekdays: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"].map(|s| s.into()),
148            months: [
149                "Gennaio",
150                "Febbraio",
151                "Marzo",
152                "Aprile",
153                "Maggio",
154                "Giugno",
155                "Luglio",
156                "Agosto",
157                "Settembre",
158                "Ottobre",
159                "Novembre",
160                "Dicembre",
161            ]
162            .map(|s| s.into()),
163        }
164    }
165}
166
167impl Default for CalendarLocale {
168    fn default() -> Self {
169        Self::english()
170    }
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub struct DateValue {
175    pub year: i32,
176    pub month: u32,
177    pub day: u32,
178}
179
180impl DateValue {
181    pub fn new(year: i32, month: u32, day: u32) -> Self {
182        Self { year, month, day }
183    }
184
185    fn days_in_month(&self) -> u32 {
186        match self.month {
187            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
188            4 | 6 | 9 | 11 => 30,
189            2 => {
190                if (self.year % 4 == 0 && self.year % 100 != 0) || (self.year % 400 == 0) {
191                    29
192                } else {
193                    28
194                }
195            }
196            _ => 30,
197        }
198    }
199
200    fn first_day_of_week(&self) -> u32 {
201        let q = 1i32;
202        let m = if self.month < 3 {
203            (self.month + 12) as i32
204        } else {
205            self.month as i32
206        };
207        let y = if self.month < 3 {
208            self.year - 1
209        } else {
210            self.year
211        };
212
213        let h = (q + (13 * (m + 1)) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
214        ((h + 6) % 7) as u32
215    }
216}
217
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub struct DateRange {
220    pub start: DateValue,
221    pub end: DateValue,
222}
223
224/// Days from civil epoch (1970-01-01) to y/m/d — Howard Hinnant's algorithm.
225fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
226    let y = if m <= 2 { y - 1 } else { y };
227    let era = y.div_euclid(400);
228    let yoe = (y - era * 400) as u64;
229    let mp = if m > 2 { m - 3 } else { m + 9 } as u64;
230    let doy = (153 * mp + 2) / 5 + (d - 1) as u64;
231    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
232    era * 146_097 + doe as i64 - 719_468
233}
234
235/// Civil y/m/d from days since civil epoch (1970-01-01) — Howard Hinnant's algorithm.
236fn civil_from_days(z: i64) -> (i64, u32, u32) {
237    let z = z + 719_468;
238    let era = z.div_euclid(146_097);
239    let doe = (z - era * 146_097) as u64;
240    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
241    let y = yoe as i64 + era * 400;
242    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
243    let mp = (5 * doy + 2) / 153;
244    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
245    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
246    (if m <= 2 { y + 1 } else { y }, m, d)
247}
248
249/// Today's date taken from the system clock (UTC-civil date, no local-zone shift).
250pub(crate) fn today() -> DateValue {
251    let days = SystemTime::now()
252        .duration_since(UNIX_EPOCH)
253        .map(|d| (d.as_secs() / 86_400) as i64)
254        .unwrap_or(0);
255    let (year, month, day) = civil_from_days(days);
256    DateValue::new(year as i32, month, day)
257}
258
259/// Whether the date falls on a Saturday or Sunday.
260pub(crate) fn is_weekend(date: &DateValue) -> bool {
261    // Day 0 (1970-01-01) was a Thursday; shift so 0 == Sunday.
262    let weekday = (days_from_civil(date.year as i64, date.month, date.day) + 4).rem_euclid(7);
263    weekday == 0 || weekday == 6
264}
265
266#[derive(IntoElement)]
267pub struct Calendar {
268    current_month: DateValue,
269    selected_date: Option<DateValue>,
270    selected_range: Option<DateRange>,
271    range_start_temp: Option<DateValue>,
272    on_date_select: Option<DateSelectCallback>,
273    on_month_change: Option<MonthChangeCallback>,
274    disabled_dates: Vec<DateValue>,
275    is_date_disabled: Option<DateDisabledPredicate>,
276    locale: CalendarLocale,
277    style: StyleRefinement,
278}
279
280impl Calendar {
281    pub fn new() -> Self {
282        let current_month = today();
283
284        Self {
285            current_month,
286            selected_date: None,
287            selected_range: None,
288            range_start_temp: None,
289            on_date_select: None,
290            on_month_change: None,
291            disabled_dates: Vec::new(),
292            is_date_disabled: None,
293            locale: CalendarLocale::default(),
294            style: StyleRefinement::default(),
295        }
296    }
297
298    pub fn current_month(mut self, date: DateValue) -> Self {
299        self.current_month = date;
300        self
301    }
302
303    pub fn selected_date(mut self, date: DateValue) -> Self {
304        self.selected_date = Some(date);
305        self
306    }
307
308    pub fn locale(mut self, locale: CalendarLocale) -> Self {
309        self.locale = locale;
310        self
311    }
312
313    pub fn on_date_select<F>(mut self, handler: F) -> Self
314    where
315        F: Fn(&DateValue, &mut Window, &mut App) + 'static,
316    {
317        self.on_date_select = Some(Rc::new(handler));
318        self
319    }
320
321    pub fn on_month_change<F>(mut self, handler: F) -> Self
322    where
323        F: Fn(&DateValue, &mut Window, &mut App) + 'static,
324    {
325        self.on_month_change = Some(Rc::new(handler));
326        self
327    }
328
329    pub fn is_date_disabled<F>(mut self, checker: F) -> Self
330    where
331        F: Fn(&DateValue) -> bool + 'static,
332    {
333        self.is_date_disabled = Some(Rc::new(checker));
334        self
335    }
336
337    pub fn disabled_dates(mut self, dates: Vec<DateValue>) -> Self {
338        self.disabled_dates = dates;
339        self
340    }
341
342    pub fn selected_range(mut self, range: Option<DateRange>) -> Self {
343        self.selected_range = range;
344        self
345    }
346
347    pub fn range_start_temp(mut self, date: Option<DateValue>) -> Self {
348        self.range_start_temp = date;
349        self
350    }
351
352    fn is_date_in_range(date: &DateValue, range: &DateRange) -> bool {
353        let date_num = date.year * 10000 + date.month as i32 * 100 + date.day as i32;
354        let start_num =
355            range.start.year * 10000 + range.start.month as i32 * 100 + range.start.day as i32;
356        let end_num = range.end.year * 10000 + range.end.month as i32 * 100 + range.end.day as i32;
357        date_num >= start_num && date_num <= end_num
358    }
359
360    fn prev_month(&self) -> DateValue {
361        if self.current_month.month == 1 {
362            DateValue::new(self.current_month.year - 1, 12, 1)
363        } else {
364            DateValue::new(self.current_month.year, self.current_month.month - 1, 1)
365        }
366    }
367
368    fn next_month(&self) -> DateValue {
369        if self.current_month.month == 12 {
370            DateValue::new(self.current_month.year + 1, 1, 1)
371        } else {
372            DateValue::new(self.current_month.year, self.current_month.month + 1, 1)
373        }
374    }
375}
376
377impl Default for Calendar {
378    fn default() -> Self {
379        Self::new()
380    }
381}
382
383impl Styled for Calendar {
384    fn style(&mut self) -> &mut StyleRefinement {
385        &mut self.style
386    }
387}
388
389impl RenderOnce for Calendar {
390    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
391        let theme = use_theme(cx);
392        let current_month = self.current_month;
393        let selected_date = self.selected_date;
394        let locale = self.locale.clone();
395
396        let prev_month_date = self.prev_month();
397        let next_month_date = self.next_month();
398
399        let on_month_change_handler = self.on_month_change.clone();
400        let month_nav_disabled = on_month_change_handler.is_none();
401        let on_date_select_handler = self.on_date_select;
402        let is_date_disabled_fn = self.is_date_disabled;
403        let disabled_dates = self.disabled_dates;
404        let selected_range = self.selected_range;
405        let range_start_temp = self.range_start_temp;
406
407        let days_in_month = current_month.days_in_month();
408        let first_day_of_week = current_month.first_day_of_week();
409
410        let month_name = if current_month.month >= 1 && current_month.month <= 12 {
411            locale.months[(current_month.month - 1) as usize].clone()
412        } else {
413            "Unknown".into()
414        };
415
416        let user_style = self.style;
417
418        div()
419            .flex()
420            .flex_col()
421            .w(px(280.0))
422            .p(px(16.0))
423            .bg(theme.tokens.background)
424            .child(
425                div()
426                    .flex()
427                    .items_center()
428                    .justify_between()
429                    .mb(px(16.0))
430                    .child({
431                        let handler = on_month_change_handler.clone();
432                        Button::new("prev-month-btn", "‹")
433                            .variant(ButtonVariant::Ghost)
434                            .size(ButtonSize::Sm)
435                            .disabled(month_nav_disabled)
436                            .when_some(handler, |btn, handler| {
437                                btn.on_click(move |_, window, cx| {
438                                    handler(&prev_month_date, window, cx);
439                                })
440                            })
441                    })
442                    .child(
443                        div()
444                            .flex_1()
445                            .text_center()
446                            .text_size(px(14.0))
447                            .font_weight(FontWeight::SEMIBOLD)
448                            .text_color(theme.tokens.foreground)
449                            .child(format!("{} {}", month_name, current_month.year)),
450                    )
451                    .child({
452                        let handler = on_month_change_handler;
453                        Button::new("next-month-btn", "›")
454                            .variant(ButtonVariant::Ghost)
455                            .size(ButtonSize::Sm)
456                            .disabled(month_nav_disabled)
457                            .when_some(handler, |btn, handler| {
458                                btn.on_click(move |_, window, cx| {
459                                    handler(&next_month_date, window, cx);
460                                })
461                            })
462                    }),
463            )
464            .child(
465                div()
466                    .flex()
467                    .mb(px(8.0))
468                    .children(locale.weekdays.iter().map(|day| {
469                        div()
470                            .flex_1()
471                            .text_center()
472                            .text_size(px(12.0))
473                            .font_weight(FontWeight::MEDIUM)
474                            .text_color(theme.tokens.muted_foreground)
475                            .child(day.clone())
476                    })),
477            )
478            .child(div().flex().flex_col().gap(px(4.0)).children({
479                let mut weeks = Vec::new();
480                let mut current_day = 1;
481                let mut day_of_week = 0;
482
483                while current_day <= days_in_month {
484                    let mut week_days = Vec::new();
485
486                    for _ in 0..7 {
487                        if (day_of_week < first_day_of_week && current_day == 1)
488                            || current_day > days_in_month
489                        {
490                            week_days.push(None);
491                        } else {
492                            week_days.push(Some(current_day));
493                            current_day += 1;
494                        }
495                        day_of_week += 1;
496                    }
497
498                    day_of_week = 0;
499                    weeks.push(week_days);
500                }
501
502                let on_date_select_for_weeks = on_date_select_handler.clone();
503                let is_date_disabled_for_weeks = is_date_disabled_fn.clone();
504                let disabled_dates_for_weeks = disabled_dates.clone();
505                weeks.into_iter().map(move |week| {
506                    let on_date_select_for_days = on_date_select_for_weeks.clone();
507                    let is_date_disabled_for_days = is_date_disabled_for_weeks.clone();
508                    let disabled_dates_for_days = disabled_dates_for_weeks.clone();
509                    let range_for_week = selected_range;
510                    let range_start_for_week = range_start_temp;
511                    div()
512                        .flex()
513                        .gap(px(4.0))
514                        .children(week.into_iter().map(move |day_option| {
515                            match day_option {
516                                Some(day) => {
517                                    let date = DateValue::new(
518                                        current_month.year,
519                                        current_month.month,
520                                        day,
521                                    );
522                                    let is_selected = selected_date.is_some_and(|sel| sel == date);
523
524                                    // Check if date is disabled
525                                    let is_disabled = is_date_disabled_for_days
526                                        .as_ref()
527                                        .map(|f| f(&date))
528                                        .unwrap_or_else(|| {
529                                            disabled_dates_for_days.iter().any(|d| d == &date)
530                                        });
531
532                                    // Check if date is in selected range
533                                    let is_in_range = range_for_week
534                                        .map(|r| Calendar::is_date_in_range(&date, &r))
535                                        .unwrap_or(false);
536
537                                    // Check if date is the range start (first click in range mode)
538                                    let is_range_start =
539                                        range_start_for_week.is_some_and(|start| start == date);
540
541                                    // Check if date is a range endpoint
542                                    let is_range_endpoint = range_for_week
543                                        .map(|r| date == r.start || date == r.end)
544                                        .unwrap_or(false);
545
546                                    let handler = if is_disabled {
547                                        None
548                                    } else {
549                                        on_date_select_for_days.clone()
550                                    };
551
552                                    div()
553                                        .flex_1()
554                                        .flex()
555                                        .items_center()
556                                        .justify_center()
557                                        .h(px(36.0))
558                                        .text_size(px(14.0))
559                                        .rounded(theme.tokens.radius_sm)
560                                        // Disabled state styling
561                                        .when(is_disabled, |this: Div| {
562                                            this.text_color(
563                                                theme.tokens.muted_foreground.opacity(0.4),
564                                            )
565                                            .cursor(CursorStyle::OperationNotAllowed)
566                                        })
567                                        // Range middle dates styling (light background)
568                                        .when(
569                                            !is_disabled
570                                                && is_in_range
571                                                && !is_range_endpoint
572                                                && !is_range_start,
573                                            |this: Div| {
574                                                this.bg(theme.tokens.primary.opacity(0.15))
575                                                    .text_color(theme.tokens.foreground)
576                                                    .cursor(CursorStyle::PointingHand)
577                                            },
578                                        )
579                                        // Range endpoints or single selected date styling
580                                        .when(
581                                            !is_disabled
582                                                && (is_range_endpoint
583                                                    || is_selected
584                                                    || is_range_start),
585                                            |this: Div| {
586                                                this.bg(theme.tokens.primary)
587                                                    .text_color(theme.tokens.primary_foreground)
588                                                    .font_weight(FontWeight::MEDIUM)
589                                                    .cursor(CursorStyle::PointingHand)
590                                            },
591                                        )
592                                        // Non-disabled, non-selected, non-range state
593                                        .when(
594                                            !is_disabled
595                                                && !is_selected
596                                                && !is_in_range
597                                                && !is_range_start,
598                                            |this: Div| {
599                                                this.cursor(CursorStyle::PointingHand)
600                                                    .text_color(theme.tokens.foreground)
601                                                    .hover(|style| {
602                                                        style.bg(theme.tokens.muted.opacity(0.5))
603                                                    })
604                                            },
605                                        )
606                                        // Click handler only for non-disabled dates
607                                        .when(handler.is_some(), |this: Div| {
608                                            let handler = handler.unwrap();
609                                            this.on_mouse_down(
610                                                MouseButton::Left,
611                                                move |_, window, cx| {
612                                                    handler(&date, window, cx);
613                                                },
614                                            )
615                                        })
616                                        .child(day.to_string())
617                                        .into_any_element()
618                                }
619                                None => div().flex_1().h(px(36.0)).into_any_element(),
620                            }
621                        }))
622                })
623            }))
624            .map(|this| {
625                let mut div = this;
626                div.style().refine(&user_style);
627                div
628            })
629    }
630}