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
use chrono::{Datelike, Duration, Month, Months, NaiveDate, Utc};
use chrono::{Locale, Weekday};
use chronoutil::shift_months;

use std::convert::TryFrom;
use std::mem;

use std::str::FromStr;
use stylist::ast::Sheet;
use stylist::Style;
use yew::MouseEvent;
use yew::{html, Callback, Component, Context, Html, Properties};
use yew_template::template_html;

pub struct Datepicker {
    current_month: NaiveDate,
    locale: Locale,
    selected_date: Option<NaiveDate>,
}

#[derive(Properties, PartialEq)]
pub struct DatepickerProperties {
    pub on_select: Callback<NaiveDate>,
    #[prop_or_default]
    pub locale: Option<Locale>,
}

impl Default for DatepickerProperties {
    fn default() -> Self {
        DatepickerProperties {
            on_select: Default::default(),
            locale: Some(Locale::en_US),
        }
    }
}

pub enum DatepickerMessage {
    CurrentMonthChange(NaiveDate),
    Select(NaiveDate),
}

impl Component for Datepicker {
    type Message = DatepickerMessage;
    type Properties = DatepickerProperties;

    fn create(ctx: &Context<Self>) -> Self {
        let current_date = chrono::offset::Local::now()
            .date_naive()
            .with_day0(0)
            .unwrap();
        let locale = ctx.props().locale.unwrap_or_else(|| Locale::en_US);
        Datepicker {
            current_month: current_date,
            locale,
            selected_date: None,
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            DatepickerMessage::CurrentMonthChange(date) => self.current_month = date,
            DatepickerMessage::Select(selected) => {
                self.selected_date = Some(selected);
                let _ = ctx.props().on_select.emit(selected);
                let in_current_mont_selected = selected.year() == self.current_month.year()
                    && selected.month() == self.current_month.month();
                if !in_current_mont_selected {
                    ctx.link()
                        .send_message(DatepickerMessage::CurrentMonthChange(
                            selected.with_day0(0).unwrap(),
                        ))
                }
            }
        }
        true
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        const STYLE_FILE: &str = include_str!("styles.css");
        let sheet = Sheet::from_str(STYLE_FILE).unwrap();
        let style = Style::new(sheet).unwrap();
        let days_names = self
            .current_week()
            .into_iter()
            .map(|n: NaiveDate| {
                html! {
                   <div class="day">{n.format_localized("%a", self.locale).to_string()}</div>
                }
            })
            .collect::<Html>();
        let columns = html! {
            <>
            <div class="day"></div>
            {days_names}
            </>
        };

        let date = self.current_month.clone();
        let context = ctx.link().clone();
        let onclick = Callback::from(move |_| {
            context.send_message(DatepickerMessage::CurrentMonthChange(shift_months(
                date, -1,
            )));
        });
        let prev = html! {
            <button class="btn" {onclick} type="button">{"<"}</button>
        };

        let context = ctx.link().clone();
        let onclick_next = Callback::from(move |_| {
            context.send_message(DatepickerMessage::CurrentMonthChange(shift_months(date, 1)));
        });
        let next = html! {
            <button class="btn" onclick={onclick_next} type="button">{">"}</button>
        };

        let calendarize = calendarize::calendarize_with_offset(self.current_month, 1);
        let selected_day = self.selected_date;
        let current_month = self.current_month;

        let previous_month = self
            .current_month
            .checked_sub_months(Months::new(1))
            .unwrap();

        let prev_month = calendarize::calendarize_with_offset(previous_month, 1);
        let prev_month_last_week = prev_month.last().unwrap();

        let next_month = self
            .current_month
            .checked_add_months(Months::new(1))
            .unwrap();
        let next_month_calendarize = calendarize::calendarize_with_offset(next_month, 1);
        let next_month_first_week = next_month_calendarize.first().unwrap();

        let weeks_number = calendarize.len();

        let rows = calendarize
            .iter()
            .cloned()
            .enumerate()
            .map(|(week_index, n)| {
                let week_number = week_index + 1;
                let is_first_week = week_index == 0;
                let is_last_week = weeks_number == week_number;
                let cells = n
                    .iter()
                    .cloned()
                    .enumerate()
                    .map(|(day_of_month_index, cl)| {
                        let mut day_class = String::from("day");
                        let context = ctx.link().clone();
                        let current_iter_date: Option<NaiveDate>;

                        let number: String;
                        if cl > 0 {
                            number = cl.to_string();
                            current_iter_date = current_month.with_day(cl);
                        } else {
                            if is_first_week {
                                let prev_month_last_week_day =
                                    prev_month_last_week.get(day_of_month_index).unwrap();
                                number = prev_month_last_week_day.to_string();
                                day_class.push_str(" day--nc-month");
                                current_iter_date =
                                    previous_month.with_day(*prev_month_last_week_day);
                            } else {
                                if is_last_week {
                                    let next_month_day =
                                        next_month_first_week.get(day_of_month_index).unwrap();
                                    number = next_month_day.to_string();
                                    day_class.push_str(" day--nc-month");
                                    current_iter_date = next_month.with_day(*next_month_day);
                                } else {
                                    number = String::new();
                                    current_iter_date = None;
                                }
                            }
                        }
                        match selected_day {
                            None => {}
                            Some(s) => match current_iter_date {
                                None => {}
                                Some(sl) => {
                                    if s == sl {
                                        day_class.push_str(" day--selected");
                                    }
                                }
                            },
                        }
                        let onclick: Callback<MouseEvent> =
                            Callback::from(move |event: MouseEvent| {
                                event.prevent_default();
                                match current_iter_date {
                                    None => {}
                                    Some(s) => {
                                        context.send_message(DatepickerMessage::Select(s));
                                    }
                                }
                            });
                        html! {
                            <a class={day_class} {onclick} href="#">{number}</a>
                        }
                    })
                    .collect::<Html>();
                html! {
                    <>
                    <div>{week_number}</div>
                    {cells}
                    </>
                }
            })
            .collect::<Html>();
        let class = style.get_class_name().to_string();
        let header = format!(
            "{} {}",
            self.current_month_name(),
            self.current_month.year()
        );
        template_html!(
            "src/templates/default.html",
            prev = { prev },
            next = { next },
            columns = { columns },
            rows = { rows },
            class = { class },
            header = { header }
        )
    }
}

impl Datepicker {
    fn current_week(&self) -> Vec<NaiveDate> {
        let current = Utc::now().date_naive();
        let week = current.week(Weekday::Mon);
        let first_day = week.first_day();
        let last_day = week.last_day();
        let mut result = Vec::new();
        for day in NaiveDateRange(first_day, last_day) {
            result.push(day);
        }
        result
    }
    fn current_month_name(&self) -> String {
        match self.locale {
            Locale::ru_RU => {
                let month = Month::try_from(self.current_month.month() as u8).unwrap();
                self.russian_month_name(month).to_string()
            }
            _ => self
                .current_month
                .format_localized("%B", self.locale)
                .to_string(),
        }
    }
    fn russian_month_name(&self, month: Month) -> &'static str {
        match month {
            Month::January => "Январь",
            Month::February => "Февраль",
            Month::March => "Март",
            Month::April => "Апрель",
            Month::May => "Май",
            Month::June => "Июнь",
            Month::July => "Июль",
            Month::August => "Август",
            Month::September => "Сентябрь",
            Month::October => "Октябрь",
            Month::November => "Ноябрь",
            Month::December => "Декабрь",
        }
    }
}

struct NaiveDateRange(NaiveDate, NaiveDate);

impl Iterator for NaiveDateRange {
    type Item = NaiveDate;
    fn next(&mut self) -> Option<Self::Item> {
        if self.0 <= self.1 {
            let next = self.0 + Duration::days(1);
            Some(mem::replace(&mut self.0, next))
        } else {
            None
        }
    }
}