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
use crate::prelude::{
    Button, ButtonType, ButtonVariant, Icon, InputGroup, InputGroupItem, SimpleSelect, TextInput,
    TextInputType,
};
use chrono::{Datelike, Days, Local, Month, Months, NaiveDate, Weekday};
use num_traits::cast::FromPrimitive;
use std::str::FromStr;
use yew::{
    classes, function_component, html, use_callback, use_state_eq, Callback, Html, Properties,
};

#[derive(Clone, PartialEq, Properties)]
pub struct CalendarMonthProperties {
    #[prop_or(Local::now().date_naive())]
    pub date: NaiveDate,
    #[prop_or_default]
    pub onchange: Callback<NaiveDate>,
    #[prop_or_default]
    pub rangestart: Option<NaiveDate>,
    #[prop_or(Weekday::Mon)]
    pub weekday_start: Weekday,
}

// Build a vec (month) which contains vecs (weeks) of a month with the first
// and last day of week, even if they aren't in the same month.
//
// The month is set by `date` and the first day of the week by `weekday_start`.
fn build_calendar(date: NaiveDate, weekday_start: Weekday) -> Vec<Vec<NaiveDate>> {
    const ONE_DAY: Days = Days::new(1);
    let mut ret: Vec<Vec<NaiveDate>> = Vec::new();
    // first day of the week. It's initialized first at the first day of the month
    let mut first_day = date.with_day(1).unwrap();
    let mut day = first_day.week(weekday_start).first_day();
    let mut week: Vec<NaiveDate>;

    while first_day.month() == date.month() {
        week = Vec::new();
        while first_day.week(weekday_start).days().contains(&day) {
            week.push(day);
            day = day + ONE_DAY;
        }

        first_day = first_day.week(weekday_start).last_day() + ONE_DAY;
        ret.push(week);
    }

    ret
}

#[function_component(CalendarView)]
pub fn calendar(props: &CalendarMonthProperties) -> Html {
    // the date which is selected by user
    let date = use_state_eq(|| props.date);
    // the date which is showed when the user changes month or year without selecting a new date
    let show_date = use_state_eq(|| props.date);
    // an array which contains the week of the selected date
    let weeks = build_calendar(*show_date, props.weekday_start);
    // the month of the selected date, used for selector
    let month = use_state_eq(|| Month::from_u32(props.date.month()).unwrap());

    let callback_month_select = use_callback(
        (show_date.clone(), month.clone()),
        move |new_month: String, (show_date, month)| {
            if let Ok(m) = new_month.parse::<Month>() {
                if let Some(d) = NaiveDate::from_ymd_opt(
                    show_date.year(),
                    m.number_from_month(),
                    show_date.day(),
                ) {
                    show_date.set(d);
                    month.set(m);
                }
            }
        },
    );

    let callback_years = use_callback(show_date.clone(), move |new_year: String, show_date| {
        if let Ok(y) = i32::from_str(&new_year) {
            if let Some(d) = NaiveDate::from_ymd_opt(y, show_date.month(), show_date.day()) {
                show_date.set(d)
            }
        }
    });

    let callback_prev = use_callback(
        (show_date.clone(), month.clone()),
        move |_, (show_date, month)| {
            if let Some(d) = show_date.checked_sub_months(Months::new(1)) {
                show_date.set(d);
                month.set(month.pred());
            }
        },
    );

    let callback_next = use_callback(
        (show_date.clone(), month.clone()),
        move |_, (show_date, month)| {
            if let Some(d) = show_date.checked_add_months(Months::new(1)) {
                show_date.set(d);
                month.set(month.succ());
            }
        },
    );

    html! {
        <div class="pf-v5-c-calendar-month">
            <div class="pf-v5-c-calendar-month__header">
                <div class="pf-v5-c-calendar-month__header-nav-control pf-m-prev-month">
                    <Button
                        variant={ButtonVariant::Plain}
                        aria_label="Previous month"
                        onclick={callback_prev}
                    >
                    {Icon::AngleLeft.as_html()}
                    </Button>
                </div>
                <InputGroup>
                    <InputGroupItem>
                        <div class="pf-v5-c-calendar-month__header-month">
                            <SimpleSelect<String>
                                entries={vec![
                                    String::from(Month::January.name()),
                                    String::from(Month::February.name()),
                                    String::from(Month::March.name()),
                                    String::from(Month::April.name()),
                                    String::from(Month::May.name()),
                                    String::from(Month::June.name()),
                                    String::from(Month::July.name()),
                                    String::from(Month::August.name()),
                                    String::from(Month::September.name()),
                                    String::from(Month::October.name()),
                                    String::from(Month::November.name()),
                                    String::from(Month::December.name())
                                ]}
                                selected={String::from(month.name())}
                                onselect={callback_month_select}
                            />
                        </div>
                    </InputGroupItem>
                    <InputGroupItem>
                        <div class="pf-v5-c-calendar-month__header-year">
                            <TextInput
                                value={show_date.year().to_string()}
                                r#type={TextInputType::Number}
                                onchange={callback_years}
                            >
                            </TextInput>
                        </div>
                    </InputGroupItem>
                </InputGroup>
                <div class="pf-v5-c-calendar-month__header-nav-control pf-m-next-month">
                    <Button
                        variant={ButtonVariant::Plain}
                        aria_label="Next month"
                        onclick={callback_next}
                    >
                    {Icon::AngleRight.as_html()}
                    </Button>
                </div>
            </div>
            <table class="pf-v5-c-calendar-month__calendar">
                <thead class="pf-v5-c-calendar-month__days">
                    <tr class="pf-v5-c-calendar-month__days-row">
                    {
                        weeks[0].clone().into_iter().map(|day| {
                            html!{
                                <th class="pf-v5-c-calendar-month__day">
                                    <span class="pf-v5-screen-reader">{day.weekday().to_string()}</span>
                                    <span aria-hidden="true">{day.weekday().to_string()}</span>
                                </th>
                            }
                        }).collect::<Html>()
                    }
                    </tr>
                </thead>
                <tbody class="pf-v5-c-calendar-month__dates">
                {
                    weeks.into_iter().map(|week| {
                        html!{
                            <>
                            <tr class="pf-v5-c-calendar-month__dates-row">
                            {
                            week.into_iter().map(|day| {
                                let callback_date = {
                                    let date = date.clone();
                                    let month = month.clone();
                                    let show_date = show_date.clone();
                                    let onchange = props.onchange.clone();
                                    move |day: NaiveDate| {
                                        Callback::from(move |_| {
                                            let new = NaiveDate::from_ymd_opt(day.year(), day.month(), day.day()).unwrap();
                                            date.set(new);
                                            show_date.set(new);
                                            month.set(Month::from_u32(day.month()).unwrap());
                                            onchange.emit(new);
                                        })
                                    }
                                };

                                let mut classes = classes!("pf-v5-c-calendar-month__dates-cell");

                                if day == *date {
                                    classes.extend(classes!("pf-m-selected"));
                                }

                                if day.month() != show_date.month() {
                                    classes.extend(classes!("pf-m-adjacent-month"));
                                }

                                let before_range = if let Some(range_start) = props.rangestart {
                                    if day < range_start {
                                        classes.extend(classes!("pf-m-disabled"));
                                    }

                                    if day == range_start {
                                        classes.extend(classes!("pf-m-start-range"));
                                        classes.extend(classes!("pf-m-selected"));
                                    }

                                    if day >= range_start && day <= *date {
                                        classes.extend(classes!("pf-m-in-range"));
                                    }

                                    if day == *date {
                                        classes.extend(classes!("pf-m-end-range"));
                                    }

                                    day < range_start
                                } else { false };

                                html!{
                                    <>
                                    <td class={classes}>
                                        <Button
                                            class="pf-v5-c-calendar-month__date"
                                            r#type={ButtonType::Button}
                                            variant={if before_range {
                                                ButtonVariant::Plain
                                            } else {
                                                ButtonVariant::None
                                            }}
                                            onclick={callback_date(day)}
                                            disabled={before_range}
                                        >
                                        {day.day()}
                                        </Button>
                                    </td>
                                    </>
                                }
                            }).collect::<Html>()
                            }
                            </tr>
                            </>
                        }
                    }).collect::<Html>()
                }
                </tbody>
            </table>
        </div>
    }
}