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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
//!
//! Render a month of a calendar.
//! Can be localized with a chrono::Locale.
//!

use crate::_private::NonExhaustive;
use chrono::{Datelike, NaiveDate, Weekday};
use rat_focus::{FocusFlag, HasFocusFlag};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{StatefulWidget, StatefulWidgetRef, Widget};
use std::fmt::{Debug, Formatter};

/// Renders a month.
pub struct Month {
    /// Title style.
    title_style: Style,
    /// Week number style.
    week_style: Style,
    /// Styling for a single date.
    day_style: Box<dyn Fn(NaiveDate) -> Style>,
    /// Start date of the month.
    start_date: NaiveDate,
    /// Locale
    loc: chrono::Locale,
}

/// Composite style for the calendar.
pub struct MonthStyle {
    pub title_style: Style,
    pub week_style: Style,
    pub day_style: Box<dyn Fn(NaiveDate) -> Style>,
    pub non_exhaustive: NonExhaustive,
}

/// Month state.
#[derive(Debug, Clone)]
pub struct MonthState {
    /// Current focus state.
    pub focus: FocusFlag,
    /// Total area.
    pub area: Rect,
    /// Area for the month name.
    pub area_month: Rect,
    /// Area for the days of the month.
    pub area_days: [Rect; 31],
    /// Area for the week numbers.
    pub weeks: [Rect; 6],

    pub non_exhaustive: NonExhaustive,
}

impl Default for MonthStyle {
    fn default() -> Self {
        Self {
            title_style: Default::default(),
            week_style: Default::default(),
            day_style: Box::new(|_| Style::default()),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl MonthState {
    pub fn new() -> Self {
        Self {
            focus: Default::default(),
            area: Default::default(),
            area_month: Default::default(),
            area_days: [Rect::default(); 31],
            weeks: [Rect::default(); 6],
            non_exhaustive: NonExhaustive,
        }
    }

    /// Renders the widget in focused style.
    ///
    /// This flag is not used for event-handling.
    #[inline]
    pub fn set_focused(&mut self, focus: bool) {
        self.focus.focus.set(focus);
    }

    /// Renders the widget in focused style.
    ///
    /// This flag is not used for event-handling.
    #[inline]
    pub fn is_focused(&mut self) -> bool {
        self.focus.focus.get()
    }
}

impl Default for MonthState {
    fn default() -> Self {
        Self {
            focus: Default::default(),
            area: Default::default(),
            area_month: Default::default(),
            area_days: [Rect::default(); 31],
            weeks: [Rect::default(); 6],
            non_exhaustive: NonExhaustive,
        }
    }
}

impl Debug for MonthStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MonthStyle")
            .field("title_style", &self.title_style)
            .field("week_style", &self.week_style)
            .field("day_style", &"... dyn Fn ...")
            .finish()
    }
}

impl Default for Month {
    fn default() -> Self {
        Self {
            title_style: Default::default(),
            week_style: Default::default(),
            day_style: Box::new(|_| Style::default()),
            start_date: Default::default(),
            loc: Default::default(),
        }
    }
}

impl Debug for Month {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Month")
            .field("title_style", &self.title_style)
            .field("week_style", &self.week_style)
            .field("day_style", &"dyn Fn()")
            .field("start_date", &self.start_date)
            .finish()
    }
}

impl Month {
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the starting date.
    #[inline]
    pub fn date(mut self, s: NaiveDate) -> Self {
        self.start_date = s;
        self
    }

    #[inline]
    pub fn locale(mut self, loc: chrono::Locale) -> Self {
        self.loc = loc;
        self
    }

    /// Set the composite style.
    #[inline]
    pub fn style(mut self, s: MonthStyle) -> Self {
        self.title_style = s.title_style;
        self.week_style = s.week_style;
        self.day_style = s.day_style;
        self
    }

    /// Sets a closure that is called to calculate the day style.
    #[inline]
    pub fn day_style(mut self, s: Box<dyn Fn(NaiveDate) -> Style>) -> Self {
        self.day_style = s;
        self
    }

    /// Set the week number style
    #[inline]
    pub fn week_style(mut self, s: impl Into<Style>) -> Self {
        self.week_style = s.into();
        self
    }

    /// Set the month-name style.
    #[inline]
    pub fn title_style(mut self, s: impl Into<Style>) -> Self {
        self.title_style = s.into();
        self
    }

    /// Required width for the widget.
    #[inline]
    pub fn width(&self) -> usize {
        8 * 3
    }

    /// Required height for the widget. Varies.
    #[inline]
    pub fn height(&self) -> usize {
        let mut r = 0;
        let mut day = self.start_date;
        let month = day.month();

        // i'm sure you can calculate this better.
        for wd in [
            Weekday::Mon,
            Weekday::Tue,
            Weekday::Wed,
            Weekday::Thu,
            Weekday::Fri,
            Weekday::Sat,
            Weekday::Sun,
        ] {
            if day.weekday() == wd {
                day += chrono::Duration::try_days(1).expect("days");
            }
        }
        r += 1;
        while month == day.month() {
            day += chrono::Duration::try_days(7).expect("days");
            r += 1;
        }

        r
    }
}

impl StatefulWidgetRef for Month {
    type State = MonthState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(self, area, buf, state);
    }
}

impl StatefulWidget for Month {
    type State = MonthState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(&self, area, buf, state);
    }
}

fn render_ref(widget: &Month, area: Rect, buf: &mut Buffer, state: &mut MonthState) {
    let mut day = widget.start_date;
    let month = widget.start_date.month();

    state.area = area;

    let mut w = 0;
    let mut x = area.x;
    let mut y = area.y;

    let day_style = widget.day_style.as_ref();

    let mut w_month = Text::default();

    let w_title = Line::styled(
        day.format_localized("%B", widget.loc).to_string(),
        widget.title_style,
    );
    state.area_month = Rect::new(x, y, w_title.width() as u16, 1);
    w_month.lines.push(w_title);
    y += 1;

    // first line may omit a few days
    let mut w_week = Line::default();
    let w_weeknum =
        Span::from(day.format_localized("%U", widget.loc).to_string()).style(widget.week_style);
    state.weeks[w] = Rect::new(x, y, w_weeknum.width() as u16, 1);
    w_week.spans.push(w_weeknum);
    w_week.spans.push(" ".into());
    x += 3;

    for wd in [
        Weekday::Mon,
        Weekday::Tue,
        Weekday::Wed,
        Weekday::Thu,
        Weekday::Fri,
        Weekday::Sat,
        Weekday::Sun,
    ] {
        if day.weekday() != wd {
            w_week.spans.push("   ".into());
            x += 3;
        } else {
            let w_date = Span::from(day.format_localized("%e", widget.loc).to_string())
                .style(day_style(day));
            state.area_days[day.day0() as usize] = Rect::new(x, y, w_date.width() as u16, 1);
            w_week.spans.push(w_date);
            w_week.spans.push(" ".into());
            x += 3;

            day += chrono::Duration::try_days(1).expect("days");
        }
    }
    w_month.lines.push(w_week);

    y += 1;
    x = area.x;
    w += 1;

    while month == day.month() {
        let mut w_week = Line::default();
        let w_weeknum =
            Span::from(day.format_localized("%U", widget.loc).to_string()).style(widget.week_style);
        state.weeks[w] = Rect::new(x, y, w_weeknum.width() as u16, 1);
        w_week.spans.push(w_weeknum);
        w_week.spans.push(" ".into());
        x += 3;

        for _ in 0..7 {
            if day.month() == month {
                let w_date = Span::from(day.format_localized("%e", widget.loc).to_string())
                    .style(day_style(day));
                state.area_days[day.day0() as usize] = Rect::new(x, y, w_date.width() as u16, 1);
                w_week.spans.push(w_date);
                w_week.spans.push(" ".into());
                x += 3;

                day += chrono::Duration::try_days(1).expect("days");
            } else {
                w_week.spans.push("   ".into());
                x += 3;
            }
        }
        w_month.lines.push(w_week);

        y += 1;
        x = area.x;
        w += 1;
    }

    w_month.render(area, buf);
}

impl HasFocusFlag for MonthState {
    #[inline]
    fn focus(&self) -> &FocusFlag {
        &self.focus
    }

    #[inline]
    fn area(&self) -> Rect {
        self.area
    }
}