Skip to main content

gpui_component/time/
calendar.rs

1use chrono::Weekday;
2use gpui::{
3    App, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, RenderOnce,
4    SharedString, StyleRefinement, Styled, Window, prelude::FluentBuilder as _, px,
5};
6use rust_i18n::t;
7
8use crate::{ActiveTheme, Icon, IconName, Sizable, Size, StyledExt as _};
9
10use gpui_base::{Calendar as BaseCalendar, CalendarItemKind, LayoutDirection};
11pub use gpui_base::{CalendarEvent, CalendarState, Date, Matcher};
12
13fn month_name(month: i32) -> SharedString {
14    match month {
15        1 => t!("Calendar.month.January"),
16        2 => t!("Calendar.month.February"),
17        3 => t!("Calendar.month.March"),
18        4 => t!("Calendar.month.April"),
19        5 => t!("Calendar.month.May"),
20        6 => t!("Calendar.month.June"),
21        7 => t!("Calendar.month.July"),
22        8 => t!("Calendar.month.August"),
23        9 => t!("Calendar.month.September"),
24        10 => t!("Calendar.month.October"),
25        11 => t!("Calendar.month.November"),
26        12 => t!("Calendar.month.December"),
27        _ => "".into(),
28    }
29    .into()
30}
31
32fn uses_compact_text(kind: CalendarItemKind) -> bool {
33    kind == CalendarItemKind::Month
34}
35
36/// Styled facade for the complete behavior and structure in `gpui-base`.
37#[derive(IntoElement)]
38pub struct Calendar {
39    id: ElementId,
40    size: Size,
41    state: Entity<CalendarState>,
42    style: StyleRefinement,
43    number_of_months: usize,
44    first_day_of_week: Weekday,
45}
46
47impl Calendar {
48    pub fn new(state: &Entity<CalendarState>) -> Self {
49        Self {
50            id: ("calendar", state.entity_id()).into(),
51            size: Size::default(),
52            state: state.clone(),
53            style: StyleRefinement::default(),
54            number_of_months: 1,
55            first_day_of_week: Weekday::Sun,
56        }
57    }
58    pub fn number_of_months(mut self, count: usize) -> Self {
59        self.number_of_months = count;
60        self
61    }
62    /// Set the first day of the week for the calendar.
63    pub fn first_day_of_week(mut self, day: Weekday) -> Self {
64        self.first_day_of_week = day;
65        self
66    }
67}
68impl Sizable for Calendar {
69    fn with_size(mut self, size: impl Into<Size>) -> Self {
70        self.size = size.into();
71        self
72    }
73}
74impl Styled for Calendar {
75    fn style(&mut self) -> &mut StyleRefinement {
76        &mut self.style
77    }
78}
79
80impl RenderOnce for Calendar {
81    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
82        let size = self.size;
83        let month_count = self.number_of_months.max(1) as f32;
84        BaseCalendar::new(self.id, &self.state)
85            .number_of_months(self.number_of_months)
86            .first_day_of_week(self.first_day_of_week)
87            .label(|kind, value| match kind {
88                CalendarItemKind::Previous => "‹".into(),
89                CalendarItemKind::Next => "›".into(),
90                CalendarItemKind::MonthToggle | CalendarItemKind::Month => month_name(value),
91                CalendarItemKind::Weekday => match value {
92                    0 => t!("Calendar.week.0"),
93                    1 => t!("Calendar.week.1"),
94                    2 => t!("Calendar.week.2"),
95                    3 => t!("Calendar.week.3"),
96                    4 => t!("Calendar.week.4"),
97                    5 => t!("Calendar.week.5"),
98                    _ => t!("Calendar.week.6"),
99                }
100                .into(),
101                _ => value.to_string().into(),
102            })
103            .item(move |item, state, _, cx| {
104                let item = match state.kind() {
105                    // Previous points toward the start edge: the right in RTL.
106                    CalendarItemKind::Previous => item
107                        .clear_children()
108                        .child(Icon::new(start_chevron(cx)).size_4()),
109                    CalendarItemKind::Next => item
110                        .clear_children()
111                        .child(Icon::new(end_chevron(cx)).size_4()),
112                    _ => item,
113                };
114                item.map(|this| match size {
115                    Size::Small => this.size_7().rounded(cx.theme().radius / 2.),
116                    Size::Large => this.size_10().rounded(cx.theme().radius * 2.),
117                    _ => this.size_8().rounded(cx.theme().radius),
118                })
119                .flex()
120                .items_center()
121                .justify_center()
122                .when(
123                    state.kind() != CalendarItemKind::Weekday,
124                    |this| match size {
125                        Size::Small => this.text_xs(),
126                        _ => this.text_sm(),
127                    },
128                )
129                .when(state.kind() == CalendarItemKind::Weekday, |this| {
130                    this.text_xs()
131                        .font_normal()
132                        .text_color(cx.theme().muted_foreground)
133                })
134                .when(uses_compact_text(state.kind()), |this| this.text_xs())
135                .when(
136                    matches!(
137                        state.kind(),
138                        CalendarItemKind::MonthToggle | CalendarItemKind::YearToggle
139                    ),
140                    |this| this.text_sm().font_medium(),
141                )
142                .when(
143                    matches!(
144                        state.kind(),
145                        CalendarItemKind::Month | CalendarItemKind::MonthToggle
146                    ),
147                    |this| {
148                        this.when(state.kind() == CalendarItemKind::Month, |this| {
149                            this.w_full().my_1()
150                        })
151                        .when(state.kind() == CalendarItemKind::MonthToggle, |this| {
152                            this.w_auto().px_2()
153                        })
154                    },
155                )
156                .when(
157                    matches!(
158                        state.kind(),
159                        CalendarItemKind::Year | CalendarItemKind::YearToggle
160                    ),
161                    |this| {
162                        this.when(state.kind() == CalendarItemKind::Year, |this| {
163                            this.w_full().my_1()
164                        })
165                        .when(state.kind() == CalendarItemKind::YearToggle, |this| {
166                            this.w_auto().px_2()
167                        })
168                    },
169                )
170                .when(state.is_muted(), |this| {
171                    this.text_color(cx.theme().muted_foreground)
172                        .when(state.is_disabled(), |this| this.opacity(0.5))
173                })
174                .when(state.is_in_range(), |this| {
175                    this.bg(cx.theme().accent)
176                        .text_color(cx.theme().accent_foreground)
177                })
178                .when(
179                    !state.is_active()
180                        && !state.is_disabled()
181                        && state.kind() != CalendarItemKind::Weekday,
182                    |this| {
183                        this.hover(|this| {
184                            this.bg(cx.theme().tokens.secondary_hover)
185                                .text_color(cx.theme().foreground)
186                        })
187                    },
188                )
189                .when(state.is_active(), |this| {
190                    this.bg(cx.theme().tokens.primary)
191                        .text_color(cx.theme().primary_foreground)
192                })
193                .when(state.is_today() && !state.is_active(), |this| {
194                    this.bg(cx.theme().accent)
195                        .text_color(cx.theme().accent_foreground)
196                })
197                .into_any_element()
198            })
199            .border_1()
200            .border_color(cx.theme().border)
201            .rounded(cx.theme().radius_lg)
202            .p_3()
203            .gap_0p5()
204            .map(|this| match size {
205                Size::Small => this.w(px(220.) * month_count),
206                Size::Large => this.w(px(304.) * month_count),
207                _ => this.w(px(248.) * month_count),
208            })
209            .refine_style(&self.style)
210    }
211}
212
213fn start_chevron(cx: &App) -> IconName {
214    if LayoutDirection::global(cx).is_rtl() {
215        IconName::ChevronRight
216    } else {
217        IconName::ChevronLeft
218    }
219}
220
221fn end_chevron(cx: &App) -> IconName {
222    if LayoutDirection::global(cx).is_rtl() {
223        IconName::ChevronLeft
224    } else {
225        IconName::ChevronRight
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::{CalendarItemKind, Date, uses_compact_text};
232    use chrono::NaiveDate;
233
234    #[test]
235    fn date_display_is_stable() {
236        assert_eq!(
237            Date::Single(Some(NaiveDate::from_ymd_opt(2024, 8, 3).unwrap())).to_string(),
238            "2024-08-03"
239        );
240        assert_eq!(Date::Single(None).to_string(), "nil");
241    }
242
243    #[test]
244    fn only_month_options_use_compact_text() {
245        assert!(uses_compact_text(CalendarItemKind::Month));
246        assert!(!uses_compact_text(CalendarItemKind::MonthToggle));
247        assert!(!uses_compact_text(CalendarItemKind::Day));
248    }
249}