leptos_use/
use_calendar.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use crate::core::MaybeRwSignal;
use chrono::*;
use default_struct_builder::DefaultBuilder;
use leptos::prelude::*;
use std::ops::Deref;

/// Create bare-bone calendar data to use in your component.
/// See [`UseCalendarOptions`] for options and [`UseCalendarReturn`] for return values.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_calendar)
///
/// ## Usage
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos_use::{use_calendar, UseCalendarReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let UseCalendarReturn {
///     dates,
///     weekdays,
///     previous_month,
///     today,
///     next_month
/// } = use_calendar();
/// #
/// # view! {
/// # }
/// # }
/// ```
///
/// Use [`use_calendar_with_options`] to change the initial date and first day of the week.
///
/// ```
/// # use leptos::prelude::*;
/// # use chrono::NaiveDate;
/// # use leptos_use::{use_calendar_with_options, UseCalendarReturn, UseCalendarOptions};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let initial_date = RwSignal::new(
///     Some(NaiveDate::from_ymd_opt(2022, 1, 1).unwrap())
/// );
///
/// let options = UseCalendarOptions::default()
///     .first_day_of_the_week(6)
///     .initial_date(initial_date);
///
/// let UseCalendarReturn {
///     dates,
///     weekdays,
///     previous_month,
///     today,
///     next_month
/// } = use_calendar_with_options(options);
/// #
/// # view! {
/// # }
/// # }
/// ```
///
///
/// ## Server-Side Rendering
///
/// Not tested yet.
// #[doc(cfg(feature = "use_calendar"))]
pub fn use_calendar() -> UseCalendarReturn<
    impl Fn() + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
> {
    use_calendar_with_options(UseCalendarOptions::default())
}

/// Version of [`use_calendar`] that takes a [`UseCalendarOptions`]. See [`use_calendar`] for how to use.
// #[doc(cfg(feature = "use_calendar"))]
pub fn use_calendar_with_options(
    options: UseCalendarOptions,
) -> UseCalendarReturn<
    impl Fn() + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
    impl Fn() + Clone + Send + Sync,
> {
    let UseCalendarOptions {
        initial_date: date,
        first_day_of_the_week,
    } = options;
    let (date, _set_date) = date.into_signal();

    let show_date = RwSignal::new(date.get_untracked().unwrap_or(Local::now().date_naive()));
    Effect::new(move |_| {
        if let Some(selected_date) = date.get() {
            let show_date_data = show_date.get_untracked();
            if selected_date.year() != show_date_data.year()
                || selected_date.month() != show_date_data.month()
            {
                show_date.set(selected_date);
            }
        }
    });

    let dates = Memo::new(move |_| {
        let show_date = show_date.get();
        let show_date_month = show_date.month();
        let mut dates = vec![];

        let mut current_date = show_date;
        let mut current_weekday_number = None::<u32>;
        loop {
            let date = current_date - Days::new(1);
            if date.month() != show_date_month {
                if current_weekday_number.is_none() {
                    current_weekday_number = Some(
                        current_date.weekday().days_since(
                            Weekday::try_from(first_day_of_the_week.get() as u8)
                                .unwrap_or(Weekday::Mon),
                        ),
                    );
                }
                let weekday_number = current_weekday_number.unwrap();
                if weekday_number == 0 {
                    break;
                }
                current_weekday_number = Some(weekday_number - 1);

                dates.push(CalendarDate::Previous(date));
            } else {
                dates.push(CalendarDate::Current(date));
            }
            current_date = date;
        }
        dates.reverse();
        dates.push(CalendarDate::Current(show_date));
        current_date = show_date;
        current_weekday_number = None;
        loop {
            let date = current_date + Days::new(1);
            if date.month() != show_date_month {
                if current_weekday_number.is_none() {
                    current_weekday_number = Some(
                        current_date.weekday().days_since(
                            Weekday::try_from(first_day_of_the_week.get() as u8)
                                .unwrap_or(Weekday::Mon),
                        ),
                    );
                }
                let weekday_number = current_weekday_number.unwrap();
                if weekday_number == 6 {
                    break;
                }
                current_weekday_number = Some(weekday_number + 1);
                dates.push(CalendarDate::Next(date));
            } else {
                dates.push(CalendarDate::Current(date));
            }
            current_date = date;
        }
        dates
    });

    let weekdays = Memo::<Vec<usize>>::new(move |_| {
        if Weekday::try_from(first_day_of_the_week.get() as u8).is_ok() {
            let first_weekdays = first_day_of_the_week.get()..7;
            let last_weekdays = 0..first_day_of_the_week.get();
            first_weekdays.chain(last_weekdays).collect()
        } else {
            (0..7).collect()
        }
    });

    UseCalendarReturn {
        previous_month: move || {
            show_date.update(|date| {
                *date = *date - Months::new(1);
            });
        },
        today: move || {
            show_date.set(Local::now().date_naive());
        },
        next_month: move || {
            show_date.update(|date| {
                *date = *date + Months::new(1);
            });
        },
        weekdays: weekdays.into(),
        dates: dates.into(),
    }
}

/// Options for [`use_calendar_with_options`].
// #[doc(cfg(feature = "use_calendar"))]
#[derive(DefaultBuilder)]
pub struct UseCalendarOptions {
    /// Date being used to initialize the calendar month to be displayed.
    /// Optional [`chrono::NaiveDate`](https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html). Defaults to [`chrono::Local::now()`](https://docs.rs/chrono/latest/chrono/struct.Local.html#method.now).
    #[builder(into)]
    pub initial_date: MaybeRwSignal<Option<NaiveDate>>,
    /// First day of the week as a number from 0 to 6. Defaults to 0 (Monday).
    #[builder(into)]
    pub first_day_of_the_week: Signal<usize>,
}

impl Default for UseCalendarOptions {
    fn default() -> Self {
        Self {
            initial_date: Some(Local::now().date_naive()).into(),
            first_day_of_the_week: 0.into(),
        }
    }
}

/// Return type of [`use_calendar`].
// #[doc(cfg(feature = "use_calendar"))]
pub struct UseCalendarReturn<PreviousMonthFn, TodayFn, NextMonthFn>
where
    PreviousMonthFn: Fn() + Clone + Send + Sync,
    TodayFn: Fn() + Clone + Send + Sync,
    NextMonthFn: Fn() + Clone + Send + Sync,
{
    /// A function to go to the previous month.
    pub previous_month: PreviousMonthFn,
    /// A function to go to the current month.
    pub today: TodayFn,
    /// A function to go to the next month.
    pub next_month: NextMonthFn,
    /// The first day of the week as a number from 0 to 6.
    pub weekdays: Signal<Vec<usize>>,
    /// A `Vec` of [`CalendarDate`]s representing the dates in the current month.
    pub dates: Signal<Vec<CalendarDate>>,
}

/// Utility enum to represent a calendar date. Implements [`Deref`] to [`chrono::NaiveDate`](https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html).
#[derive(Clone, Copy, PartialEq)]
pub enum CalendarDate {
    Previous(NaiveDate),
    Current(NaiveDate),
    Next(NaiveDate),
}

impl CalendarDate {
    pub fn is_other_month(&self) -> bool {
        match self {
            CalendarDate::Previous(_) | CalendarDate::Next(_) => true,
            CalendarDate::Current(_) => false,
        }
    }
    pub fn is_today(&self) -> bool {
        let date = self.deref();
        let now_date = Local::now().date_naive();
        &now_date == date
    }

    pub fn is_selected(&self, selected_date: &NaiveDate) -> bool {
        self.deref() == selected_date
    }

    pub fn is_before(&self, date: &NaiveDate) -> bool {
        self.deref() < date
    }

    pub fn is_between(&self, start_date: &NaiveDate, end_date: &NaiveDate) -> bool {
        let date = self.deref();
        date >= start_date && date <= end_date
    }

    pub fn is_between_current_month(&self, start_date: &NaiveDate, end_date: &NaiveDate) -> bool {
        match self {
            CalendarDate::Current(date) => date >= start_date && date <= end_date,
            CalendarDate::Next(date) => date > start_date && date <= end_date,
            CalendarDate::Previous(date) => date >= start_date && date < end_date,
        }
    }

    pub fn is_after(&self, date: &NaiveDate) -> bool {
        self.deref() > date
    }

    pub fn is_first_day_of_month(&self) -> bool {
        let date = self.deref();
        if let Some(prev_date) = date.pred_opt() {
            date.month() != prev_date.month()
        } else {
            true
        }
    }

    pub fn is_last_day_of_month(&self) -> bool {
        let date = self.deref();
        if let Some(next_date) = date.succ_opt() {
            date.month() != next_date.month()
        } else {
            true
        }
    }
}

impl Deref for CalendarDate {
    type Target = NaiveDate;

    fn deref(&self) -> &Self::Target {
        match self {
            CalendarDate::Previous(date)
            | CalendarDate::Current(date)
            | CalendarDate::Next(date) => date,
        }
    }
}