Skip to main content

bhoo/systems/material/
date_picker.rs

1//! Material Design 3 & Angular-compatible calendar, date picker, and date-range picker.
2use crate::*;
3
4/// Active view inside a calendar / date picker.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub enum DatePickerView {
7    #[default]
8    Days,
9    Years,
10    Months,
11}
12
13/// Optional constraints & mode configuration for `Frame::calendar_grid_with_options` and
14/// `Frame::date_picker_with_options`.
15#[derive(Clone, Copy, Debug, Default)]
16pub struct DatePickerOptions {
17    /// When `true`, renders direct text-entry mode instead of the visual calendar grid.
18    pub text_input_mode: bool,
19    /// Optional inclusive minimum selectable date `[year, month, day]`.
20    pub min_date: Option<[i32; 3]>,
21    /// Optional inclusive maximum selectable date `[year, month, day]`.
22    pub max_date: Option<[i32; 3]>,
23}
24
25impl DatePickerOptions {
26    /// Returns `true` if `date` is disabled by `min_date`/`max_date`.
27    pub fn is_disabled(&self, date: [i32; 3]) -> bool {
28        self.min_date.is_some_and(|min| date < min) || self.max_date.is_some_and(|max| date > max)
29    }
30}
31
32/// Caller-owned state for `Frame::calendar_grid`, `Frame::date_picker`, and `Frame::date_range_picker`.
33#[derive(Clone)]
34pub struct DatePickerState {
35    pub year: i32,
36    pub month: i32,
37    pub selected: Option<[i32; 3]>,
38    pub range_end: Option<[i32; 3]>,
39    pub today: [i32; 3],
40    pub focused_day: usize,
41    pub view: DatePickerView,
42    pub picking_end: bool,
43    pub overlay: OverlayState,
44    pub anchor: Rect,
45}
46
47impl Default for DatePickerState {
48    fn default() -> Self {
49        Self {
50            year: 2026,
51            month: 11,
52            selected: Some([2026, 11, 9]),
53            range_end: None,
54            today: [2026, 11, 9],
55            focused_day: 9,
56            view: DatePickerView::Days,
57            picking_end: false,
58            overlay: OverlayState::default(),
59            anchor: Rect::default(),
60        }
61    }
62}
63
64impl DatePickerState {
65    /// Formatted label for the current single date (`M/D/YYYY`).
66    pub fn formatted_date(&self) -> String {
67        match self.selected {
68            Some([y, m, d]) => format!("{m}/{d}/{y}"),
69            None => String::new(),
70        }
71    }
72
73    /// Formatted label for the current date range (`M/D/YYYY – M/D/YYYY`).
74    pub fn formatted_range(&self) -> String {
75        match (self.selected, self.range_end, self.picking_end) {
76            (Some([y1, m1, d1]), Some([y2, m2, d2]), false) => {
77                format!("{m1}/{d1}/{y1} – {m2}/{d2}/{y2}")
78            }
79            (Some([y1, m1, d1]), _, _) => format!("{m1}/{d1}/{y1} –"),
80            _ => String::new(),
81        }
82    }
83}
84
85/// Number of days in a Gregorian `(year, month)` (`month` in `1..=12`).
86pub fn month_days(year: i32, month: i32) -> usize {
87    match month {
88        2 => {
89            if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
90                29
91            } else {
92                28
93            }
94        }
95        4 | 6 | 9 | 11 => 30,
96        _ => 31,
97    }
98}
99
100/// Day of week for a Gregorian date (`0 = Monday .. 6 = Sunday`).
101pub fn weekday(year: i32, month: i32, day: i32) -> usize {
102    let y = year - i32::from(month < 3);
103    let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
104    let m = month.clamp(1, 12) as usize;
105    ((y + y / 4 - y / 100 + y / 400 + t[m - 1] + day + 6).rem_euclid(7)) as usize
106}
107
108fn paint_range_preview(f: &mut Frame<'_>, cell: Rect, inner: Rect, start: bool, end: bool, color: Color) {
109    let x0 = if start { inner.x + inner.width * 0.5 } else { cell.x };
110    let x1 = if end { inner.x + inner.width * 0.5 } else { cell.x + cell.width };
111    let top = inner.y + 1.0;
112    let bottom = inner.y + inner.height;
113    let width = x1 - x0;
114    let count = ((width + 2.0) / 5.0).floor().max(1.0) as usize;
115    let spacing = if count > 1 { (width - 3.0) / (count - 1) as f32 } else { 0.0 };
116    for i in 0..count {
117        for y in [top, bottom] {
118            let x = if end && !start {
119                if y == top { x0 + 5.0 * i as f32 } else { x1 - 3.0 - 5.0 * i as f32 }
120            } else {
121                x0 + spacing * i as f32
122            };
123            let left = x.max(x0);
124            let right = (x + 3.0).min(x1);
125            if right > left {
126                f.paint_rect(Rect { x: left, y, width: right - left, height: 1.0 }, 0.0, color);
127            }
128        }
129    }
130    if end && !start {
131        f.paint_rect(Rect { x: x0, y: bottom, width: 2.0_f32.min(width), height: 1.0 }, 0.0, color);
132    }
133    let radius = (inner.height - 1.0) * 0.5;
134    let cy = inner.y + inner.height * 0.5 + 1.0;
135    for (enabled, cx, base) in [
136        (start, x0, std::f32::consts::FRAC_PI_2),
137        (end, x1, -std::f32::consts::FRAC_PI_2),
138    ] {
139        if enabled && radius > 0.5 {
140            let length = std::f32::consts::PI * radius;
141            let count = (length / 5.0).ceil().max(1.0) as usize;
142            for i in 0..count {
143                let angle = base + 5.0 * i as f32 / radius;
144                f.paint_arc(
145                    Rect {
146                        x: cx - inner.width / 2.0,
147                        y: cy - inner.height / 2.0,
148                        width: inner.width,
149                        height: inner.height,
150                    },
151                    angle,
152                    (3.0 / radius).min(base + std::f32::consts::PI - angle),
153                    1.0,
154                    color,
155                );
156            }
157        }
158    }
159}
160
161impl Frame<'_> {
162    /// Inline Material calendar grid supporting single-date or date-range selection,
163    /// month/year/24-year drilldown, range hover preview, and roving arrow-key navigation.
164    /// Returns `true` when the selected date/range changed.
165    pub fn calendar_grid(&mut self, id: u64, state: &mut DatePickerState, range: bool) -> bool {
166        self.calendar_grid_with_options(id, state, range, DatePickerOptions::default(), |_| false)
167    }
168
169    /// Inline Material calendar grid with optional text-input mode, `min_date`/`max_date` bounds,
170    /// and a caller-supplied `is_disabled` predicate for blacked-out dates.
171    pub fn calendar_grid_with_options(
172        &mut self,
173        id: u64,
174        state: &mut DatePickerState,
175        range: bool,
176        options: DatePickerOptions,
177        is_disabled: impl Fn([i32; 3]) -> bool,
178    ) -> bool {
179        if options.text_input_mode {
180            let value = if range { state.formatted_range() } else { state.formatted_date() };
181            let r = self.text_field(
182                id.wrapping_add(400),
183                if range { "Start – End (M/D/YYYY)" } else { "Date (M/D/YYYY)" },
184                56.0,
185                !value.is_empty(),
186                false,
187                false,
188            );
189            if !value.is_empty() {
190                self.styled_text(
191                    Rect { x: r.bounds.x + 16.0, width: (r.bounds.width - 32.0).max(0.0), ..r.bounds },
192                    &value,
193                    self.theme().text,
194                    TextStyle { size: 16.0, ..TextStyle::default() },
195                );
196            }
197            return false;
198        }
199        const MONTHS: [&str; 12] = [
200            "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
201        ];
202        const DAYS: [&str; 31] = [
203            "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
204            "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
205            "31",
206        ];
207        state.month = state.month.clamp(1, 12);
208        let mut changed = false;
209        let root = self.available();
210        let t = self.theme();
211        let width = (root.width - 16.0).max(0.0);
212        let pitch = (width / 7.0).max(1.0);
213        let margin = width * 0.05;
214        let control_y = root.y + 8.0 + margin;
215        let control_x = root.x + 8.0 + width * (4.714_286 / 100.0) - 16.0;
216        let right = root.x + root.width - (control_x - root.x);
217        let period = format!("{} {}", MONTHS[(state.month - 1) as usize], state.year);
218        let period_width = (self.text_width(&period, TextStyle::LABEL) + 40.0).max(64.0);
219        let period_box = Rect {
220            x: control_x + 8.0,
221            y: control_y,
222            width: period_width,
223            height: 40.0,
224        };
225        let r = self.target(id, period_box, "Choose year and month", true, Role::Button);
226        self.state_layer(r, 20.0, t.on_surface_variant);
227        if r.clicked {
228            state.view = match state.view {
229                DatePickerView::Days => DatePickerView::Years,
230                _ => DatePickerView::Days,
231            };
232        }
233        self.styled_text(
234            period_box,
235            &period,
236            t.on_surface_variant,
237            TextStyle { align: 0, padding: 12.0, ..TextStyle::LABEL },
238        );
239        let x = period_box.x + period_box.width - 16.0;
240        let y = period_box.y + 20.0;
241        for (i, half) in [4.0, 3.0, 2.0, 1.0].into_iter().enumerate() {
242            self.paint_line([x - half, y - 1.5 + i as f32], [x + half, y - 1.5 + i as f32], 1.0, t.on_surface_variant);
243        }
244        for i in 0..2u64 {
245            let b = Rect { x: right - 80.0 + i as f32 * 40.0, y: control_y, width: 40.0, height: 40.0 };
246            let r = self.target(id.wrapping_add(1 + i), b, if i == 0 { "Previous month" } else { "Next month" }, true, Role::Button);
247            self.state_layer(r, 20.0, t.on_surface_variant);
248            let dir = if i == 0 { -1.0 } else { 1.0 };
249            let c = [b.x + 20.0, b.y + 20.0];
250            self.paint_line([c[0] - dir * 2.5, c[1] - 4.0], [c[0] + dir * 1.5, c[1]], 2.0, t.on_surface_variant);
251            self.paint_line([c[0] + dir * 1.5, c[1]], [c[0] - dir * 2.5, c[1] + 4.0], 2.0, t.on_surface_variant);
252            if r.clicked {
253                match state.view {
254                    DatePickerView::Years => state.year += if i == 0 { -24 } else { 24 },
255                    DatePickerView::Months => state.year += if i == 0 { -1 } else { 1 },
256                    DatePickerView::Days => {
257                        state.month += if i == 0 { -1 } else { 1 };
258                        if state.month == 0 {
259                            state.month = 12;
260                            state.year -= 1;
261                        }
262                        if state.month == 13 {
263                            state.month = 1;
264                            state.year += 1;
265                        }
266                        state.focused_day = state.focused_day.clamp(1, month_days(state.year, state.month));
267                    }
268                }
269            }
270        }
271        let body_y = root.y + 8.0 + 2.0 * margin + 40.0;
272        if state.view != DatePickerView::Days {
273            let count = if state.view == DatePickerView::Years { 24 } else { 12 };
274            let cols = 4;
275            let row_height = 52.0;
276            let start = state.year.div_euclid(24) * 24;
277            for (i, month) in MONTHS.iter().cycle().take(count).enumerate() {
278                let b = Rect {
279                    x: root.x + 8.0 + (i % cols) as f32 * width / cols as f32,
280                    y: body_y + (i / cols) as f32 * row_height,
281                    width: width / cols as f32,
282                    height: row_height,
283                };
284                let label = if state.view == DatePickerView::Years {
285                    (start + i as i32).to_string()
286                } else {
287                    (*month).to_owned()
288                };
289                let r = self.target(id.wrapping_add(100 + i as u64), b, &label, true, Role::Button);
290                self.state_layer(r, 26.0, t.on_surface_variant);
291                self.styled_text(b, &label, t.text, TextStyle { size: 14.0, align: 1, ..TextStyle::default() });
292                if r.clicked {
293                    if state.view == DatePickerView::Years {
294                        state.year = start + i as i32;
295                        state.view = DatePickerView::Months;
296                    } else {
297                        state.month = i as i32 + 1;
298                        state.view = DatePickerView::Days;
299                    }
300                }
301            }
302            self.reserve((body_y - root.y) + count.div_ceil(cols) as f32 * row_height);
303            return false;
304        }
305        for (i, label) in ["S", "M", "T", "W", "T", "F", "S"].iter().enumerate() {
306            self.styled_text(
307                Rect { x: root.x + 8.0 + i as f32 * pitch, y: body_y, width: pitch, height: 18.0 },
308                label,
309                t.on_surface_variant,
310                TextStyle { size: 14.0, weight: 500, align: 1, ..TextStyle::default() },
311            );
312        }
313        let days = month_days(state.year, state.month);
314        let offset = (weekday(state.year, state.month, 1) + 1) % 7;
315        let extra = usize::from(offset == 0);
316        let grid_y = body_y + 32.0;
317        let month_label = Rect {
318            x: root.x + 8.0 + 18.0,
319            y: grid_y,
320            width: if offset == 0 { width - 18.0 } else { pitch * offset as f32 - 18.0 },
321            height: pitch,
322        };
323        self.styled_text(
324            month_label,
325            MONTHS[(state.month - 1) as usize],
326            t.text,
327            TextStyle { size: 14.0, weight: 500, ..TextStyle::default() },
328        );
329        let preview_end = if range && state.picking_end && let Some(start_d) = state.selected {
330            (1..=days).find_map(|day| {
331                let index = offset + day - 1;
332                let cell = Rect {
333                    x: root.x + 8.0 + (index % 7) as f32 * pitch,
334                    y: grid_y + (extra + index / 7) as f32 * pitch,
335                    width: pitch,
336                    height: pitch,
337                };
338                let date = [state.year, state.month, day as i32];
339                let allowed = !options.is_disabled(date) && !is_disabled(date);
340                (allowed && date > start_d && self.pointer_in(cell)).then_some(date)
341            })
342        } else {
343            None
344        };
345        state.focused_day = state.focused_day.clamp(1, days);
346        for day in 1..=days {
347            let index = offset + day - 1;
348            let cell = Rect {
349                x: root.x + 8.0 + (index % 7) as f32 * pitch,
350                y: grid_y + (extra + index / 7) as f32 * pitch,
351                width: pitch,
352                height: pitch,
353            };
354            let b = cell.inset(pitch * 0.05);
355            let date = [state.year, state.month, day as i32];
356            let day_enabled = !options.is_disabled(date) && !is_disabled(date);
357            let selected = if range {
358                state.selected == Some(date) || (!state.picking_end && state.range_end == Some(date))
359            } else {
360                state.selected == Some(date)
361            };
362            let r = self.target_roving(id.wrapping_add(200 + day as u64), b, DAYS[day - 1], day_enabled, day == state.focused_day);
363            if let (Some(start_d), Some(end_d)) = (state.selected, preview_end)
364                && date >= start_d
365                && date <= end_d
366            {
367                paint_range_preview(self, cell, b, date == start_d, date == end_d, t.primary);
368            }
369            if range
370                && !state.picking_end
371                && let (Some(s), Some(e)) = (state.selected, state.range_end)
372                && date > s
373                && date < e
374            {
375                self.paint_rect(Rect { y: b.y, height: b.height, ..cell }, 0.0, t.primary_container);
376            }
377            if selected
378                && range
379                && !state.picking_end
380                && let (Some(s), Some(e)) = (state.selected, state.range_end)
381                && s != e
382            {
383                let left = if date == s { b.x + b.width / 2.0 } else { cell.x };
384                let right = if date == e { b.x + b.width / 2.0 } else { cell.x + cell.width };
385                self.paint_rect(
386                    Rect { x: left, y: b.y, width: (right - left).max(0.0), height: b.height },
387                    0.0,
388                    t.primary_container,
389                );
390            }
391            if selected {
392                self.paint_rect(b, b.width / 2.0, if r.enabled { t.primary } else { t.text.opacity(0.12) });
393            } else if date == state.today {
394                self.paint_rect(b, b.width / 2.0, t.text);
395                self.paint_rect(b.inset(1.0), (b.width / 2.0 - 1.0).max(0.0), t.background);
396            }
397            self.state_layer(r, b.width / 2.0, if selected { t.on_primary } else { t.on_surface_variant });
398            self.styled_text(
399                b,
400                DAYS[day - 1],
401                if !r.enabled {
402                    t.text.opacity(0.38)
403                } else if selected {
404                    t.on_primary
405                } else {
406                    t.text
407                },
408                TextStyle { size: 14.0, align: 1, ..TextStyle::default() },
409            );
410            if r.clicked {
411                state.focused_day = day;
412                changed = true;
413                if range {
414                    if state.picking_end && state.selected.is_some_and(|s| date >= s) {
415                        state.range_end = Some(date);
416                        state.picking_end = false;
417                    } else {
418                        state.selected = Some(date);
419                        state.range_end = Some(date);
420                        state.picking_end = true;
421                    }
422                } else {
423                    state.selected = Some(date);
424                }
425            }
426            if r.focused {
427                let mut next = day as i32;
428                if self.pressed_key(Key::Left) { next -= 1; }
429                if self.pressed_key(Key::Right) { next += 1; }
430                if self.pressed_key(Key::Up) { next -= 7; }
431                if self.pressed_key(Key::Down) { next += 7; }
432                if self.pressed_key(Key::Home) { next = 1; }
433                if self.pressed_key(Key::End) { next = days as i32; }
434                next = next.clamp(1, days as i32);
435                if next != day as i32 {
436                    state.focused_day = next as usize;
437                    self.request_focus(id.wrapping_add(200 + next as u64));
438                }
439            }
440        }
441        self.reserve((grid_y - root.y) + (extra + (offset + days).div_ceil(7)) as f32 * pitch);
442        changed
443    }
444
445    /// Dual-month side-by-side calendar range picker displaying `(state.year, state.month)`
446    /// alongside the consecutive following month for cross-month range selection.
447    pub fn date_range_picker_dual(
448        &mut self,
449        id: u64,
450        state: &mut DatePickerState,
451        options: DatePickerOptions,
452        is_disabled: impl Fn([i32; 3]) -> bool + Copy,
453    ) -> bool {
454        let mut changed = false;
455        let (next_year, next_month) = if state.month == 12 {
456            (state.year + 1, 1)
457        } else {
458            (state.year, state.month + 1)
459        };
460        let mut second = DatePickerState {
461            year: next_year,
462            month: next_month,
463            selected: state.selected,
464            range_end: state.range_end,
465            today: state.today,
466            focused_day: 1,
467            view: DatePickerView::Days,
468            picking_end: state.picking_end,
469            overlay: OverlayState::default(),
470            anchor: Rect::default(),
471        };
472        let area = self.available();
473        if area.width >= 520.0 {
474            let half = (area.width - 16.0) * 0.5;
475            let row = self.reserve(340.0);
476            let left_rect = Rect { width: half, ..row };
477            let right_rect = Rect { x: row.x + half + 16.0, width: half, ..row };
478            self.within(left_rect, |f| {
479                if f.calendar_grid_with_options(id, state, true, options, is_disabled) {
480                    changed = true;
481                }
482            });
483            second.selected = state.selected;
484            second.range_end = state.range_end;
485            second.picking_end = state.picking_end;
486            self.within(right_rect, |f| {
487                if f.calendar_grid_with_options(id.wrapping_add(500), &mut second, true, options, is_disabled) {
488                    state.selected = second.selected;
489                    state.range_end = second.range_end;
490                    state.picking_end = second.picking_end;
491                    changed = true;
492                }
493            });
494        } else {
495            changed |= self.calendar_grid_with_options(id, state, true, options, is_disabled);
496            second.selected = state.selected;
497            second.range_end = state.range_end;
498            second.picking_end = state.picking_end;
499            if self.calendar_grid_with_options(id.wrapping_add(500), &mut second, true, options, is_disabled) {
500                state.selected = second.selected;
501                state.range_end = second.range_end;
502                state.picking_end = second.picking_end;
503                changed = true;
504            }
505        }
506        changed
507    }
508
509    /// Date picker field paired with an anchored calendar popup overlay.
510    /// Returns `true` when the selected date changed.
511    pub fn date_picker(&mut self, id: u64, label: &str, state: &mut DatePickerState, filled: bool) -> bool {
512        let display = state.formatted_date();
513        let trigger = self.popup_field(id, label, &display, filled, FieldAffordance::Calendar);
514        if trigger.clicked {
515            state.anchor = trigger.bounds;
516            state.overlay.open = !state.overlay.open;
517            state.view = DatePickerView::Days;
518        }
519        let mut changed = false;
520        state.overlay.kind = OverlayKind::Menu;
521        state.overlay.style = OverlayStyle::AngularDatepicker;
522        state.overlay.dismiss_policy = OverlayDismissPolicy::EscapeOrOutside;
523        let popup = Rect {
524            x: state.anchor.x,
525            y: state.anchor.y + state.anchor.height + 4.0,
526            width: 296.0_f32.min(self.viewport().width.max(200.0)),
527            height: 354.0,
528        };
529        let mut overlay = std::mem::take(&mut state.overlay);
530        self.overlay(id.wrapping_add(50), &mut overlay, popup, false, |f, open| {
531            if f.calendar_grid(id.wrapping_add(100), state, false) {
532                changed = true;
533                *open = false;
534            }
535        });
536        state.overlay = overlay;
537        changed
538    }
539
540    /// Date-range picker field paired with an anchored calendar popup overlay.
541    /// Returns `true` when the selected range changed.
542    pub fn date_range_picker(&mut self, id: u64, label: &str, state: &mut DatePickerState, filled: bool) -> bool {
543        let display = state.formatted_range();
544        let (field_r, icon_r) = self.date_range_field(id, label, &display, filled);
545        if field_r.clicked || icon_r.clicked {
546            state.anchor = field_r.bounds;
547            state.overlay.open = !state.overlay.open;
548            state.view = DatePickerView::Days;
549        }
550        let mut changed = false;
551        state.overlay.kind = OverlayKind::Menu;
552        state.overlay.style = OverlayStyle::AngularDatepicker;
553        state.overlay.dismiss_policy = OverlayDismissPolicy::EscapeOrOutside;
554        let popup = Rect {
555            x: state.anchor.x,
556            y: state.anchor.y + state.anchor.height + 4.0,
557            width: 296.0_f32.min(self.viewport().width.max(200.0)),
558            height: 354.0,
559        };
560        let mut overlay = std::mem::take(&mut state.overlay);
561        self.overlay(id.wrapping_add(50), &mut overlay, popup, false, |f, open| {
562            if f.calendar_grid(id.wrapping_add(100), state, true) {
563                changed = true;
564                if !state.picking_end {
565                    *open = false;
566                }
567            }
568        });
569        state.overlay = overlay;
570        changed
571    }
572}
573
574#[cfg(test)]
575#[path = "date_picker.spec.rs"]
576mod tests;