Skip to main content

freya_components/
calendar.rs

1/// Determines which day the week starts on.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum WeekStart {
4    Sunday,
5    Monday,
6}
7
8use chrono::{
9    Datelike,
10    Local,
11    Month,
12    NaiveDate,
13};
14use freya_core::prelude::*;
15use torin::{
16    content::Content,
17    prelude::Alignment,
18    size::Size,
19};
20
21use crate::{
22    button::Button,
23    get_theme,
24    icons::arrow::ArrowIcon,
25    theming::component_themes::{
26        ButtonColorsThemePartialExt,
27        ButtonLayoutThemePartialExt,
28        CalendarTheme,
29        CalendarThemePartial,
30    },
31};
32
33/// A simple date representation for the calendar.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct CalendarDate {
36    pub year: i32,
37    pub month: u32,
38    pub day: u32,
39}
40
41impl CalendarDate {
42    pub fn new(year: i32, month: u32, day: u32) -> Self {
43        Self { year, month, day }
44    }
45
46    /// Returns the current local date.
47    pub fn now() -> Self {
48        let today = Local::now().date_naive();
49        Self {
50            year: today.year(),
51            month: today.month(),
52            day: today.day(),
53        }
54    }
55
56    /// Returns the number of days in the given month.
57    fn days_in_month(year: i32, month: u32) -> u32 {
58        let next_month = if month == 12 { 1 } else { month + 1 };
59        let next_year = if month == 12 { year + 1 } else { year };
60        NaiveDate::from_ymd_opt(next_year, next_month, 1)
61            .and_then(|d| d.pred_opt())
62            .map(|d| d.day())
63            .unwrap_or(30)
64    }
65
66    /// Returns the day of the week for the first day of the month.
67    fn first_day_of_month(year: i32, month: u32, week_start: WeekStart) -> u32 {
68        NaiveDate::from_ymd_opt(year, month, 1)
69            .map(|d| match week_start {
70                WeekStart::Sunday => d.weekday().num_days_from_sunday(),
71                WeekStart::Monday => d.weekday().num_days_from_monday(),
72            })
73            .unwrap_or(0)
74    }
75
76    /// Returns the full name of the month.
77    fn month_name(month: u32) -> String {
78        Month::try_from(month as u8)
79            .map(|m| m.name().to_string())
80            .unwrap_or_else(|_| "Unknown".to_string())
81    }
82}
83
84/// A calendar component for date selection.
85///
86/// # Example
87///
88/// ```rust
89/// # use freya::prelude::*;
90/// fn app() -> impl IntoElement {
91///     let mut selected = use_state(|| None::<CalendarDate>);
92///     let mut view_date = use_state(|| CalendarDate::new(2025, 1, 1));
93///
94///     Calendar::new()
95///         .selected(selected())
96///         .view_date(view_date())
97///         .on_change(move |date| selected.set(Some(date)))
98///         .on_view_change(move |date| view_date.set(date))
99/// }
100/// # use freya_testing::prelude::*;
101/// # launch_doc(|| {
102/// #   rect().center().expanded().child(app())
103/// # }, "./images/gallery_calendar.png").with_hook(|_| {}).with_scale_factor(0.8).render();
104/// ```
105///
106/// # Preview
107///
108/// ![Calendar Preview][gallery_calendar]
109#[cfg_attr(feature = "docs", doc = embed_doc_image::embed_image!("gallery_calendar", "images/gallery_calendar.png"))]
110#[derive(Clone, PartialEq)]
111pub struct Calendar {
112    pub(crate) theme: Option<CalendarThemePartial>,
113    selected: Option<CalendarDate>,
114    view_date: CalendarDate,
115    week_start: WeekStart,
116    on_change: Option<EventHandler<CalendarDate>>,
117    on_view_change: Option<EventHandler<CalendarDate>>,
118    key: DiffKey,
119}
120
121impl Default for Calendar {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127impl Calendar {
128    pub fn new() -> Self {
129        Self {
130            theme: None,
131            selected: None,
132            view_date: CalendarDate::now(),
133            week_start: WeekStart::Monday,
134            on_change: None,
135            on_view_change: None,
136            key: DiffKey::None,
137        }
138    }
139
140    pub fn selected(mut self, selected: Option<CalendarDate>) -> Self {
141        self.selected = selected;
142        self
143    }
144
145    pub fn view_date(mut self, view_date: CalendarDate) -> Self {
146        self.view_date = view_date;
147        self
148    }
149
150    /// Set which day the week starts on (Sunday or Monday)
151    pub fn week_start(mut self, week_start: WeekStart) -> Self {
152        self.week_start = week_start;
153        self
154    }
155
156    pub fn on_change(mut self, on_change: impl Into<EventHandler<CalendarDate>>) -> Self {
157        self.on_change = Some(on_change.into());
158        self
159    }
160
161    pub fn on_view_change(mut self, on_view_change: impl Into<EventHandler<CalendarDate>>) -> Self {
162        self.on_view_change = Some(on_view_change.into());
163        self
164    }
165}
166
167impl KeyExt for Calendar {
168    fn write_key(&mut self) -> &mut DiffKey {
169        &mut self.key
170    }
171}
172
173impl Component for Calendar {
174    fn render(&self) -> impl IntoElement {
175        let theme = get_theme!(&self.theme, calendar);
176
177        let CalendarTheme {
178            background,
179            day_background,
180            day_hover_background,
181            day_selected_background,
182            color,
183            day_other_month_color,
184            header_color,
185            corner_radius,
186            padding,
187            day_corner_radius,
188            nav_button_hover_background,
189        } = theme;
190
191        let view_year = self.view_date.year;
192        let view_month = self.view_date.month;
193
194        let days_in_month = CalendarDate::days_in_month(view_year, view_month);
195        let first_day = CalendarDate::first_day_of_month(view_year, view_month, self.week_start);
196        let month_name = CalendarDate::month_name(view_month);
197
198        let prev_month = if view_month == 1 { 12 } else { view_month - 1 };
199        let prev_year = if view_month == 1 {
200            view_year - 1
201        } else {
202            view_year
203        };
204        let days_in_prev_month = CalendarDate::days_in_month(prev_year, prev_month);
205
206        let on_change = self.on_change.clone();
207        let on_view_change = self.on_view_change.clone();
208        let selected = self.selected;
209
210        let on_prev = EventHandler::from({
211            let on_view_change = on_view_change.clone();
212            move |_: Event<PressEventData>| {
213                if let Some(handler) = &on_view_change {
214                    let new_month = if view_month == 1 { 12 } else { view_month - 1 };
215                    let new_year = if view_month == 1 {
216                        view_year - 1
217                    } else {
218                        view_year
219                    };
220                    handler.call(CalendarDate::new(new_year, new_month, 1));
221                }
222            }
223        });
224
225        let on_next = EventHandler::from(move |_: Event<PressEventData>| {
226            if let Some(handler) = &on_view_change {
227                let new_month = if view_month == 12 { 1 } else { view_month + 1 };
228                let new_year = if view_month == 12 {
229                    view_year + 1
230                } else {
231                    view_year
232                };
233                handler.call(CalendarDate::new(new_year, new_month, 1));
234            }
235        });
236
237        let nav_button = |on_press: EventHandler<Event<PressEventData>>, rotate| {
238            Button::new()
239                .flat()
240                .width(Size::px(32.))
241                .height(Size::px(32.))
242                .hover_background(nav_button_hover_background)
243                .on_press(on_press)
244                .child(
245                    ArrowIcon::new()
246                        .fill(color)
247                        .width(Size::px(16.))
248                        .height(Size::px(16.))
249                        .rotate(rotate),
250                )
251        };
252
253        let weekday_names = match self.week_start {
254            WeekStart::Sunday => ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
255            WeekStart::Monday => ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
256        };
257
258        let header_cells = weekday_names.iter().map(|day_name| {
259            rect()
260                .width(Size::px(36.))
261                .height(Size::px(36.))
262                .center()
263                .child(label().text(*day_name).color(header_color).font_size(12.))
264                .into()
265        });
266
267        let total_cells = (first_day + days_in_month).div_ceil(7) * 7;
268        let day_cells = (0..total_cells).map(|i| {
269            let current_day = i as i32 - first_day as i32 + 1;
270
271            let (day, day_color, enabled) = if current_day < 1 {
272                let day = (days_in_prev_month as i32 + current_day) as u32;
273                (day, day_other_month_color, false)
274            } else if current_day as u32 > days_in_month {
275                let day = current_day as u32 - days_in_month;
276                (day, day_other_month_color, false)
277            } else {
278                (current_day as u32, color, true)
279            };
280
281            let date = CalendarDate::new(view_year, view_month, current_day as u32);
282            let is_selected = enabled && selected == Some(date);
283            let on_change = on_change.clone();
284
285            let (bg, hover_bg) = if is_selected {
286                (day_selected_background, day_selected_background)
287            } else if enabled {
288                (day_background, day_hover_background)
289            } else {
290                (Color::TRANSPARENT, Color::TRANSPARENT)
291            };
292
293            CalendarDay::new()
294                .key(day)
295                .day(day)
296                .background(bg)
297                .hover_background(hover_bg)
298                .color(day_color)
299                .corner_radius(day_corner_radius)
300                .enabled(enabled)
301                .maybe(enabled, |el| {
302                    el.map(on_change, |el, on_change| {
303                        el.on_press(move |_| on_change.call(date))
304                    })
305                })
306                .into()
307        });
308
309        rect()
310            .background(background)
311            .corner_radius(corner_radius)
312            .padding(padding)
313            .width(Size::px(280.))
314            .child(
315                rect()
316                    .horizontal()
317                    .width(Size::fill())
318                    .padding((0., 0., 8., 0.))
319                    .cross_align(Alignment::center())
320                    .content(Content::flex())
321                    .child(nav_button(on_prev, 90.))
322                    .child(
323                        label()
324                            .width(Size::flex(1.))
325                            .text_align(TextAlign::Center)
326                            .text(format!("{} {}", month_name, view_year))
327                            .color(header_color)
328                            .max_lines(1)
329                            .font_size(16.),
330                    )
331                    .child(nav_button(on_next, -90.)),
332            )
333            .child(
334                rect()
335                    .horizontal()
336                    .content(Content::wrap())
337                    .width(Size::fill())
338                    .children(header_cells)
339                    .children(day_cells),
340            )
341    }
342
343    fn render_key(&self) -> DiffKey {
344        self.key.clone().or(self.default_key())
345    }
346}
347
348#[derive(Clone, PartialEq)]
349struct CalendarDay {
350    day: u32,
351    background: Color,
352    hover_background: Color,
353    color: Color,
354    corner_radius: CornerRadius,
355    on_press: Option<EventHandler<Event<PressEventData>>>,
356    enabled: bool,
357    key: DiffKey,
358}
359
360impl CalendarDay {
361    fn new() -> Self {
362        Self {
363            day: 1,
364            background: Color::TRANSPARENT,
365            hover_background: Color::TRANSPARENT,
366            color: Color::BLACK,
367            corner_radius: CornerRadius::default(),
368            on_press: None,
369            enabled: true,
370            key: DiffKey::None,
371        }
372    }
373
374    fn day(mut self, day: u32) -> Self {
375        self.day = day;
376        self
377    }
378
379    fn background(mut self, background: Color) -> Self {
380        self.background = background;
381        self
382    }
383
384    fn hover_background(mut self, hover_background: Color) -> Self {
385        self.hover_background = hover_background;
386        self
387    }
388
389    fn color(mut self, color: Color) -> Self {
390        self.color = color;
391        self
392    }
393
394    fn corner_radius(mut self, corner_radius: CornerRadius) -> Self {
395        self.corner_radius = corner_radius;
396        self
397    }
398
399    fn on_press(mut self, on_press: impl Into<EventHandler<Event<PressEventData>>>) -> Self {
400        self.on_press = Some(on_press.into());
401        self
402    }
403
404    fn enabled(mut self, enabled: bool) -> Self {
405        self.enabled = enabled;
406        self
407    }
408}
409
410impl KeyExt for CalendarDay {
411    fn write_key(&mut self) -> &mut DiffKey {
412        &mut self.key
413    }
414}
415
416impl Component for CalendarDay {
417    fn render(&self) -> impl IntoElement {
418        Button::new()
419            .flat()
420            .padding(0.)
421            .enabled(self.enabled)
422            .width(Size::px(36.))
423            .height(Size::px(36.))
424            .background(self.background)
425            .hover_background(self.hover_background)
426            .maybe(self.enabled, |el| {
427                el.map(self.on_press.clone(), |el, on_press| el.on_press(on_press))
428            })
429            .child(
430                label()
431                    .text(self.day.to_string())
432                    .color(self.color)
433                    .font_size(14.),
434            )
435    }
436
437    fn render_key(&self) -> DiffKey {
438        self.key.clone().or(self.default_key())
439    }
440}