Skip to main content

bhoo/systems/material/
time_picker.rs

1//! Material / Angular-compatible popover time picker (dropdown slot list or clock dial, 12h or 24h).
2use crate::*;
3
4/// Presentation mode for `Frame::time_picker_with_options`.
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
6pub enum TimePickerMode {
7    #[default]
8    Dropdown,
9    Dial,
10}
11
12/// Configuration for `Frame::time_picker_with_options`.
13#[derive(Clone, Copy, Debug, Default)]
14pub struct TimePickerOptions {
15    pub mode: TimePickerMode,
16    pub use_24h: bool,
17}
18
19/// Caller-owned state for `Frame::time_picker` and `Frame::time_picker_with_options`.
20pub struct TimePickerState {
21    pub selected: usize,
22    pub overlay: OverlayState,
23    pub anchor: Rect,
24    pub list: ListState,
25    pub scrollbar: ScrollbarDragState,
26    pub step_minutes: u16,
27}
28
29impl Default for TimePickerState {
30    fn default() -> Self {
31        Self {
32            selected: 18, // 9:00 AM
33            overlay: OverlayState::default(),
34            anchor: Rect::default(),
35            list: ListState { offset: 0.0, selected: Some(18) },
36            scrollbar: ScrollbarDragState::default(),
37            step_minutes: 30,
38        }
39    }
40}
41
42impl TimePickerState {
43    pub fn slot_count(&self) -> usize {
44        let step = self.step_minutes.clamp(1, 720) as usize;
45        (24 * 60) / step
46    }
47
48    pub fn formatted_value(&self) -> String {
49        time_picker_label_step(self.selected, self.step_minutes)
50    }
51
52    pub fn formatted_value_24h(&self) -> String {
53        time_picker_label_24h(self.selected, self.step_minutes)
54    }
55}
56
57/// Format a half-hour time slot (`0..48`) as `H:MM AM/PM`.
58pub fn time_picker_label(index: usize) -> String {
59    time_picker_label_step(index, 30)
60}
61
62/// Format a time slot with a configurable minute interval as `H:MM AM/PM`.
63pub fn time_picker_label_step(index: usize, step_minutes: u16) -> String {
64    let step = step_minutes.clamp(1, 720) as usize;
65    let total_minutes = (index * step) % (24 * 60);
66    let hours = total_minutes / 60;
67    let minutes = total_minutes % 60;
68    let h12 = if hours.is_multiple_of(12) { 12 } else { hours % 12 };
69    let period = if hours < 12 { "AM" } else { "PM" };
70    format!("{h12}:{minutes:02} {period}")
71}
72
73/// Format a time slot with a configurable minute interval in 24-hour `HH:MM` format.
74pub fn time_picker_label_24h(index: usize, step_minutes: u16) -> String {
75    let step = step_minutes.clamp(1, 720) as usize;
76    let total_minutes = (index * step) % (24 * 60);
77    format!("{:02}:{:02}", total_minutes / 60, total_minutes % 60)
78}
79
80impl Frame<'_> {
81    /// Time picker trigger field + scrollable popover slot list (12-hour dropdown default).
82    /// Returns `true` when the selected time slot changed.
83    pub fn time_picker(&mut self, id: u64, label: &str, state: &mut TimePickerState, filled: bool) -> bool {
84        self.time_picker_with_options(id, label, state, filled, TimePickerOptions::default())
85    }
86
87    /// Time picker supporting `Dropdown` slot list or interactive Material `Dial` face in 12h or 24h format.
88    pub fn time_picker_with_options(
89        &mut self,
90        id: u64,
91        label: &str,
92        state: &mut TimePickerState,
93        filled: bool,
94        options: TimePickerOptions,
95    ) -> bool {
96        let count = state.slot_count().max(1);
97        state.selected = state.selected.min(count - 1);
98        let value = if options.use_24h {
99            state.formatted_value_24h()
100        } else {
101            state.formatted_value()
102        };
103        let trigger = self.popup_field(id, label, &value, filled, FieldAffordance::Clock);
104        if trigger.clicked {
105            state.anchor = trigger.bounds;
106            state.overlay.open = !state.overlay.open;
107            state.list.selected = Some(state.selected);
108        }
109        let mut changed = false;
110        state.overlay.kind = OverlayKind::Menu;
111        state.overlay.style = OverlayStyle::AngularTimepicker;
112        state.overlay.dismiss_policy = OverlayDismissPolicy::EscapeOrOutside;
113        let step = state.step_minutes.clamp(1, 720);
114        let (popup_w, popup_h) = match options.mode {
115            TimePickerMode::Dropdown => (state.anchor.width.max(180.0), (count as f32 * 48.0 + 16.0).min(256.0)),
116            TimePickerMode::Dial => (280.0_f32.min(self.viewport().width.max(220.0)), 320.0),
117        };
118        let popup = Rect {
119            x: state.anchor.x,
120            y: state.anchor.y + state.anchor.height + 4.0,
121            width: popup_w,
122            height: popup_h,
123        };
124        let mut overlay = std::mem::take(&mut state.overlay);
125        self.overlay(id.wrapping_add(50), &mut overlay, popup, false, |f, open| {
126            let area = f.available();
127            match options.mode {
128                TimePickerMode::Dropdown => {
129                    let list_area = Rect { width: (area.width - 16.0).max(0.0), ..area };
130                    f.within(list_area, |f| {
131                        let mut picked = None;
132                        let _ = f.virtual_list_rows(
133                            id.wrapping_add(100),
134                            list_area.height,
135                            count,
136                            &mut state.list,
137                            48.0,
138                            |f, index, selected| {
139                                let text = if options.use_24h {
140                                    time_picker_label_24h(index, step)
141                                } else {
142                                    time_picker_label_step(index, step)
143                                };
144                                let r = f.menu_item_with_selection(
145                                    id.wrapping_add(200 + index as u64),
146                                    &text,
147                                    true,
148                                    selected,
149                                    false,
150                                );
151                                if r.clicked {
152                                    picked = Some(index);
153                                }
154                                r
155                            },
156                        );
157                        if let Some(idx) = picked {
158                            state.selected = idx;
159                            state.list.selected = Some(idx);
160                            *open = false;
161                            changed = true;
162                        }
163                    });
164                    let track = Rect {
165                        x: area.x + area.width - 15.0,
166                        y: area.y,
167                        width: 15.0,
168                        height: area.height,
169                    };
170                    let content_h = count as f32 * 48.0 + 16.0;
171                    f.vertical_scrollbar_painted(
172                        id.wrapping_add(150),
173                        track,
174                        &mut state.list.offset,
175                        area.height,
176                        content_h,
177                        &mut state.scrollbar,
178                    );
179                }
180                TimePickerMode::Dial => {
181                    let t = f.theme();
182                    let total_min = (state.selected * step as usize) % (24 * 60);
183                    let cur_hour = total_min / 60;
184                    let cur_min = total_min % 60;
185                    let header_h = 44.0;
186                    let header = Rect { x: area.x + 12.0, y: area.y + 8.0, width: area.width - 24.0, height: header_h };
187                    let display = if options.use_24h {
188                        format!("{cur_hour:02}:{cur_min:02}")
189                    } else {
190                        let h12 = if cur_hour.is_multiple_of(12) { 12 } else { cur_hour % 12 };
191                        format!("{h12}:{cur_min:02} {}", if cur_hour < 12 { "AM" } else { "PM" })
192                    };
193                    f.styled_text(
194                        header,
195                        &display,
196                        t.text,
197                        TextStyle { size: 22.0, weight: 600, align: 0, ..TextStyle::default() },
198                    );
199                    if !options.use_24h {
200                        let toggle_rect = Rect {
201                            x: header.x + header.width - 76.0,
202                            y: header.y + 4.0,
203                            width: 76.0,
204                            height: 36.0,
205                        };
206                        let tr = f.action_at(
207                            id.wrapping_add(160),
208                            toggle_rect,
209                            if cur_hour < 12 { "AM" } else { "PM" },
210                            Options { variant: ButtonVariant::Tonal, ..Options::default() },
211                        );
212                        if tr.clicked {
213                            let new_hour = (cur_hour + 12) % 24;
214                            let new_min = new_hour * 60 + cur_min;
215                            state.selected = (new_min / step as usize).min(count - 1);
216                            changed = true;
217                        }
218                    }
219                    let dial_sz = (area.width - 32.0).min(area.height - header_h - 32.0).max(120.0);
220                    let dial = Rect {
221                        x: area.x + (area.width - dial_sz) * 0.5,
222                        y: area.y + header_h + 16.0,
223                        width: dial_sz,
224                        height: dial_sz,
225                    };
226                    let cx = dial.x + dial_sz * 0.5;
227                    let cy = dial.y + dial_sz * 0.5;
228                    let r_outer = dial_sz * 0.5;
229                    f.paint_rect(dial, r_outer, t.surface_high);
230                    let ring_r = r_outer - 22.0;
231                    let sel_idx = cur_hour % 12;
232                    let sel_angle = (sel_idx as f32 / 12.0) * std::f32::consts::TAU - std::f32::consts::FRAC_PI_2;
233                    let is_inner_24 = options.use_24h && cur_hour >= 12;
234                    let hand_r = if is_inner_24 { ring_r * 0.62 } else { ring_r };
235                    let tip = [cx + hand_r * sel_angle.cos(), cy + hand_r * sel_angle.sin()];
236                    f.paint_line([cx, cy], tip, 2.0, t.primary);
237                    f.paint_rect(Rect { x: cx - 4.0, y: cy - 4.0, width: 8.0, height: 8.0 }, 4.0, t.primary);
238
239                    let total_hours = if options.use_24h { 24 } else { 12 };
240                    for h in 0..total_hours {
241                        let inner = options.use_24h && h >= 12;
242                        let pos_idx = h % 12;
243                        let angle = (pos_idx as f32 / 12.0) * std::f32::consts::TAU - std::f32::consts::FRAC_PI_2;
244                        let rad = if inner { ring_r * 0.62 } else { ring_r };
245                        let hx = cx + rad * angle.cos();
246                        let hy = cy + rad * angle.sin();
247                        let hit_sz = if inner { 28.0 } else { 32.0 };
248                        let cell = Rect { x: hx - hit_sz * 0.5, y: hy - hit_sz * 0.5, width: hit_sz, height: hit_sz };
249                        let is_sel = if options.use_24h { cur_hour == h } else { cur_hour % 12 == h };
250                        let lbl = if options.use_24h {
251                            format!("{h:02}")
252                        } else if h == 0 {
253                            "12".to_owned()
254                        } else {
255                            h.to_string()
256                        };
257                        let r = f.target(id.wrapping_add(300 + h as u64), cell, &lbl, true, Role::Button);
258                        if is_sel {
259                            f.paint_rect(cell, hit_sz * 0.5, t.primary);
260                        }
261                        f.state_layer(r, hit_sz * 0.5, if is_sel { t.on_primary } else { t.text });
262                        f.styled_text(
263                            cell,
264                            &lbl,
265                            if is_sel { t.on_primary } else { t.text },
266                            TextStyle { size: if inner { 11.0 } else { 13.0 }, weight: 500, align: 1, ..TextStyle::default() },
267                        );
268                        if r.clicked {
269                            let new_hour = if options.use_24h {
270                                h
271                            } else if cur_hour >= 12 {
272                                h + 12
273                            } else {
274                                h
275                            };
276                            let new_min = new_hour * 60 + cur_min;
277                            state.selected = (new_min / step as usize).min(count - 1);
278                            state.list.selected = Some(state.selected);
279                            changed = true;
280                        }
281                    }
282                }
283            }
284        });
285        state.overlay = overlay;
286        changed
287    }
288}
289
290#[cfg(test)]
291#[path = "time_picker.spec.rs"]
292mod tests;