Skip to main content

gpui_material_extras/date_time/time/
controls.rs

1use std::rc::Rc;
2
3use gpui::{
4    AccessibleAction, AnyElement, App, ElementId, Entity, InteractiveElement as _, IntoElement,
5    ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
6    Styled as _, Window, div, prelude::FluentBuilder as _, px,
7};
8use gpui_base::Button as BaseButton;
9use gpui_material_components::{Text, TextField, TextFieldVariant};
10use gpui_material_foundation::{color, current_material_theme};
11use gpui_material_theme::{ColorRole, Direction, TypeRole};
12
13use super::{
14    dial::dial,
15    dialog::{ModeSlot, TimePickerModeAction, mode_action},
16    state::TimePickerState,
17    types::{
18        Presentation, TimeFormat, TimePickerLayout, TimePickerSegment, TimePickerStyle,
19        TimePickerVariant, display_hour,
20    },
21};
22use crate::date_time::{ScrollField, status};
23
24/// An independently mountable Material time-editing panel.
25#[derive(IntoElement)]
26pub struct TimePickerPanel {
27    id: ElementId,
28    state: Entity<TimePickerState>,
29    variant: Option<TimePickerVariant>,
30    layout: TimePickerLayout,
31    presentation: Presentation,
32    toggle: Option<ModeSlot>,
33}
34
35impl TimePickerPanel {
36    /// Creates a panel that follows `state.mode()` dynamically.
37    pub fn new(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
38        Self {
39            id: id.into(),
40            state: state.clone(),
41            variant: None,
42            layout: TimePickerLayout::Auto,
43            presentation: Presentation {
44                style: TimePickerStyle::default(),
45                vibrant: false,
46            },
47            toggle: None,
48        }
49    }
50
51    /// Creates a panel pinned to [`TimePickerVariant::Dial`].
52    pub fn dial(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
53        Self::new(id, state).fixed(TimePickerVariant::Dial)
54    }
55
56    /// Creates a panel pinned to [`TimePickerVariant::Input`].
57    pub fn input(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
58        Self::new(id, state).fixed(TimePickerVariant::Input)
59    }
60
61    fn fixed(mut self, variant: TimePickerVariant) -> Self {
62        self.variant = Some(variant);
63        self
64    }
65
66    /// Sets the dial layout orientation. Defaults to [`TimePickerLayout::Auto`].
67    pub fn layout(mut self, layout: TimePickerLayout) -> Self {
68        self.layout = layout;
69        self
70    }
71
72    /// Overrides the panel's appearance and color tokens.
73    pub fn style(mut self, style: TimePickerStyle) -> Self {
74        self.presentation.style = style;
75        self
76    }
77
78    /// Enables or disables the expressive vibrant styling preset.
79    pub fn vibrant(mut self, vibrant: bool) -> Self {
80        self.presentation.vibrant = vibrant;
81        self
82    }
83
84    /// Renders a custom mode-toggle control inside the panel.
85    pub fn mode_toggle_content<E: IntoElement>(
86        mut self,
87        content: impl FnOnce(TimePickerModeAction) -> E + 'static,
88    ) -> Self {
89        self.toggle = Some(Box::new(move |action| content(action).into_any_element()));
90        self
91    }
92}
93
94impl RenderOnce for TimePickerPanel {
95    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
96        let model = self.state.read(cx);
97        let mode = self.variant.unwrap_or(model.mode);
98        let appearance = self.presentation;
99        let controls = match mode {
100            TimePickerVariant::Dial => time_selector(&self.id, &self.state, appearance, window, cx),
101            TimePickerVariant::Input => time_input(&self.id, &self.state, appearance, window, cx),
102            TimePickerVariant::Scroll => time_scroll(&self.id, model, appearance),
103        };
104        let period = (model.format == TimeFormat::TwelveHour)
105            .then(|| period_selector(&self.id, &self.state, appearance, window, cx));
106        let horizontal = mode == TimePickerVariant::Dial
107            && window.viewport_size().width >= px(600.)
108            && match self.layout {
109                TimePickerLayout::Vertical => false,
110                TimePickerLayout::Horizontal => true,
111                TimePickerLayout::Auto => window.viewport_size().height < px(650.),
112            };
113        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
114        let toggle = self
115            .toggle
116            .map(|content| content(mode_action(&self.state, model, mode, false)));
117        div()
118            .id((self.id.clone(), "panel"))
119            .track_focus(&model.panel)
120            .flex()
121            .gap(px(12.))
122            .items_center()
123            .when(!horizontal, gpui::Styled::flex_col)
124            .when(horizontal && rtl, gpui::Styled::flex_row_reverse)
125            .when_some(appearance.style.container, |body, container| {
126                body.bg(container)
127            })
128            .child(
129                div()
130                    .min_w_0()
131                    .w(px(216.))
132                    .max_w_full()
133                    .flex()
134                    .flex_col()
135                    .gap(px(8.))
136                    .child(controls)
137                    .children(period)
138                    .children(toggle),
139            )
140            .children(
141                (mode == TimePickerVariant::Dial)
142                    .then(|| dial(&self.id, &self.state, appearance, window, cx)),
143            )
144    }
145}
146
147/// An uncontained vibrant panel with separate, wrapping hour and minute wheels.
148#[derive(IntoElement)]
149pub struct TimeScroll(TimePickerPanel);
150
151impl TimeScroll {
152    /// Creates a vibrant scroll-wheel time panel bound to `state`.
153    pub fn new(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
154        Self(
155            TimePickerPanel::new(id, state)
156                .fixed(TimePickerVariant::Scroll)
157                .vibrant(true),
158        )
159    }
160
161    /// Overrides the panel's appearance and color tokens.
162    pub fn style(mut self, style: TimePickerStyle) -> Self {
163        self.0 = self.0.style(style);
164        self
165    }
166
167    /// Renders a custom mode-toggle control inside the scroll panel.
168    pub fn mode_toggle_content<E: IntoElement>(
169        mut self,
170        content: impl FnOnce(TimePickerModeAction) -> E + 'static,
171    ) -> Self {
172        self.0 = self.0.mode_toggle_content(content);
173        self
174    }
175}
176
177impl RenderOnce for TimeScroll {
178    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
179        self.0
180    }
181}
182
183fn time_input(
184    id: &ElementId,
185    state: &Entity<TimePickerState>,
186    appearance: Presentation,
187    window: &Window,
188    cx: &App,
189) -> AnyElement {
190    let model = state.read(cx);
191    let state = state.clone();
192    let theme = current_material_theme(window, cx);
193    let colors = appearance.input_colors(&theme);
194    let field = |segment, label: &SharedString, part| {
195        let editor = model.field(segment);
196        let invalid = model.input_attempted
197            && model
198                .parse_segment(segment, &editor.read(cx).value())
199                .is_none();
200        let control = TextField::new((id.clone(), part), label.clone(), editor)
201            .variant(TextFieldVariant::Outlined)
202            .colors(colors)
203            .invalid(invalid)
204            .when_some(
205                appearance
206                    .style
207                    .time_field_shape
208                    .or_else(|| appearance.vibrant.then(|| appearance.selector_shape())),
209                |field, shape| field.shape(shape),
210            );
211        div().flex_1().min_w_0().child(control)
212    };
213    div()
214        .capture_action(move |_: &gpui_base::input::Escape, window, cx| {
215            if state.update(cx, |state, cx| state.finish_composition(window, cx)) {
216                cx.stop_propagation();
217            }
218        })
219        .flex()
220        .flex_col()
221        .gap(px(8.))
222        .child(
223            // Numeric HH:MM fields stay left-to-right under RTL per M3 & Unicode BiDi.
224            div()
225                .flex()
226                .items_start()
227                .gap(px(12.))
228                .w_full()
229                .child(field(TimePickerSegment::Hour, &model.locale.hour, "hour"))
230                .child(field(
231                    TimePickerSegment::Minute,
232                    &model.locale.minute,
233                    "minute",
234                )),
235        )
236        .when(
237            model.input_attempted && !model.is_input_valid(cx),
238            |column| column.child(status(model.locale.validation_message.clone(), true)),
239        )
240        .into_any_element()
241}
242
243fn time_scroll(id: &ElementId, model: &TimePickerState, appearance: Presentation) -> AnyElement {
244    let wheel = |segment, name: &SharedString, part| {
245        let offset = usize::from(
246            segment == TimePickerSegment::Hour && model.format == TimeFormat::TwelveHour,
247        );
248        let describe = model.locale.number.clone();
249        let display = describe.clone();
250        let scroll = ScrollField::new((id.clone(), part), name.clone(), model.wheel(segment))
251            .colors(appearance.style.scroll)
252            .time_field(appearance.style.time_field_shape, offset)
253            .value_description(move |index| describe((index + offset) as u32))
254            .item_content(move |index, selected, _| {
255                Text::new(display((index + offset) as u32))
256                    .role(if selected {
257                        TypeRole::DisplayLarge
258                    } else {
259                        TypeRole::DisplayMedium
260                    })
261                    .emphasized(selected)
262            });
263        div().flex_1().min_w_0().child(scroll)
264    };
265    // Numeric HH:MM wheels stay left-to-right under RTL per M3 & Unicode BiDi.
266    div()
267        .flex()
268        .w_full()
269        .gap(px(4.))
270        .child(wheel(
271            TimePickerSegment::Hour,
272            &model.locale.hour,
273            "hour-scroll",
274        ))
275        .child(wheel(
276            TimePickerSegment::Minute,
277            &model.locale.minute,
278            "minute-scroll",
279        ))
280        .into_any_element()
281}
282
283fn time_selector(
284    id: &ElementId,
285    state: &Entity<TimePickerState>,
286    appearance: Presentation,
287    window: &Window,
288    cx: &App,
289) -> AnyElement {
290    let model = state.read(cx);
291    let (format, locale) = (model.format, &model.locale);
292    let theme = current_material_theme(window, cx);
293    let tone = |role| color(theme.colors.color(role));
294    let palette = appearance.style.time_selector;
295    let [tl, tr, br, bl] = appearance
296        .selector_shape()
297        .radii(96., 80., theme.layout.direction)
298        .map(px);
299    let segment = |part, label: &SharedString, value| {
300        let selected = part == model.segment;
301        let state = state.clone();
302        let text = (locale.number)(value);
303        let action = Rc::new(move |window: &mut Window, cx: &mut App| {
304            state.update(cx, |state, cx| {
305                state.set_segment(part, cx);
306                state.dial.focus(window, cx);
307            });
308        });
309        let click = action.clone();
310        BaseButton::new((
311            id.clone(),
312            if part == TimePickerSegment::Hour {
313                "select-hour"
314            } else {
315                "select-minute"
316            },
317        ))
318        .role(Role::RadioButton)
319        .aria_toggled(if selected {
320            gpui::Toggled::True
321        } else {
322            gpui::Toggled::False
323        })
324        .accessibility_label(format!("{label} {text}"))
325        .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
326            action(window, cx)
327        })
328        .on_click(move |_, window, cx| click(window, cx))
329        .w(px(96.))
330        .h(px(80.))
331        .max_w_full()
332        .min_w_0()
333        .flex_shrink(1.)
334        .rounded_tl(tl)
335        .rounded_tr(tr)
336        .rounded_br(br)
337        .rounded_bl(bl)
338        .bg(if appearance.vibrant {
339            (if selected {
340                palette.selected_container
341            } else {
342                palette.container
343            })
344            .unwrap_or_else(|| tone(ColorRole::SurfaceContainerLowest))
345        } else if selected {
346            palette
347                .selected_container
348                .unwrap_or_else(|| tone(ColorRole::PrimaryContainer))
349        } else {
350            palette
351                .container
352                .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHighest))
353        })
354        .text_color(if selected {
355            palette.selected_content.unwrap_or_else(|| {
356                tone(if appearance.vibrant {
357                    ColorRole::Primary
358                } else {
359                    ColorRole::OnPrimaryContainer
360                })
361            })
362        } else {
363            palette
364                .content
365                .unwrap_or_else(|| tone(ColorRole::OnSurface))
366        })
367        .when(appearance.vibrant && selected, |button| {
368            button.border_2().border_color(tone(ColorRole::Primary))
369        })
370        .child(Text::new(text).role(TypeRole::DisplayMedium))
371    };
372    // Numeric HH:MM selector stays left-to-right under RTL per M3 & Unicode BiDi.
373    div()
374        .flex()
375        .items_center()
376        .justify_center()
377        .gap(px(4.))
378        .child(segment(
379            TimePickerSegment::Hour,
380            &locale.hour,
381            display_hour(model.draft, format),
382        ))
383        .child(Text::new(locale.separator.clone()).role(TypeRole::DisplayMedium))
384        .child(segment(
385            TimePickerSegment::Minute,
386            &locale.minute,
387            model.minute(),
388        ))
389        .into_any_element()
390}
391
392fn period_selector(
393    id: &ElementId,
394    state: &Entity<TimePickerState>,
395    appearance: Presentation,
396    window: &Window,
397    cx: &App,
398) -> AnyElement {
399    let model = state.read(cx);
400    let locale = &model.locale;
401    let theme = current_material_theme(window, cx);
402    let rtl = theme.layout.direction == Direction::Rtl;
403    let tone = |role| color(theme.colors.color(role));
404    let palette = appearance.style.period_selector;
405    let [tl, tr, br, bl] = appearance
406        .period_shape()
407        .radii(108., 38., theme.layout.direction)
408        .map(px);
409    let button = |pm, label: SharedString| {
410        let selected = model.is_pm() == pm;
411        let state = state.clone();
412        let activate = Rc::new(move |_: &mut Window, cx: &mut App| {
413            state.update(cx, |state, cx| {
414                let next_hour = state.draft.hour() % 12 + if pm { 12 } else { 0 };
415                let next = state
416                    .draft
417                    .with()
418                    .hour(next_hour)
419                    .build()
420                    .expect("hour in 0..24 is always valid");
421                if state.draft != next {
422                    state.draft = next;
423                    cx.notify();
424                }
425            });
426        });
427        let click = activate.clone();
428        BaseButton::new((id.clone(), if pm { "pm" } else { "am" }))
429            .role(Role::RadioButton)
430            .aria_toggled(if selected {
431                gpui::Toggled::True
432            } else {
433                gpui::Toggled::False
434            })
435            .accessibility_label(label.clone())
436            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
437                activate(window, cx)
438            })
439            .on_click(move |_, window, cx| click(window, cx))
440            .flex_1()
441            .h(px(38.))
442            .rounded_tl(tl)
443            .rounded_tr(tr)
444            .rounded_br(br)
445            .rounded_bl(bl)
446            .when_some(
447                if selected {
448                    Some(palette.selected_container.unwrap_or_else(|| {
449                        tone(if appearance.vibrant {
450                            ColorRole::PrimaryContainer
451                        } else {
452                            ColorRole::TertiaryContainer
453                        })
454                    }))
455                } else {
456                    palette.container.or_else(|| {
457                        appearance
458                            .vibrant
459                            .then(|| tone(ColorRole::SurfaceContainerLowest))
460                    })
461                },
462                |button, container| button.bg(container),
463            )
464            .text_color(if selected {
465                palette.selected_content.unwrap_or_else(|| {
466                    tone(if appearance.vibrant {
467                        ColorRole::OnPrimaryContainer
468                    } else {
469                        ColorRole::OnTertiaryContainer
470                    })
471                })
472            } else {
473                palette
474                    .content
475                    .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant))
476            })
477            .child(Text::new(label).role(TypeRole::TitleMedium))
478    };
479    div()
480        .flex()
481        .w_full()
482        .rounded_tl(tl)
483        .rounded_tr(tr)
484        .rounded_br(br)
485        .rounded_bl(bl)
486        .border_1()
487        .border_color(
488            appearance
489                .style
490                .period_selector_border
491                .unwrap_or_else(|| tone(ColorRole::Outline)),
492        )
493        .when(rtl, gpui::Styled::flex_row_reverse)
494        .child(button(false, locale.am.clone()))
495        .child(button(true, locale.pm.clone()))
496        .into_any_element()
497}
498
499#[cfg(all(test, feature = "test-support"))]
500mod tests {
501    use gpui::{AppContext as _, Context, Hsla, Render, WindowOptions, rgb};
502    use gpui_material_foundation::MaterialRoot;
503    use gpui_material_theme::{Direction, MaterialTheme};
504
505    use super::{super::types::TimePickerSelectionColors, *};
506
507    #[gpui::test]
508    fn rtl_keeps_hh_mm_selector_left_to_right(cx: &mut gpui::TestAppContext) {
509        const HOUR_COLOR: u32 = 0x112233;
510        const MINUTE_COLOR: u32 = 0x445566;
511
512        struct Fixture {
513            state: Entity<TimePickerState>,
514        }
515
516        impl Render for Fixture {
517            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
518                TimePickerPanel::dial("rtl-dial", &self.state).style(TimePickerStyle {
519                    time_selector: TimePickerSelectionColors {
520                        selected_container: Some(rgb(HOUR_COLOR).into()),
521                        container: Some(rgb(MINUTE_COLOR).into()),
522                        ..Default::default()
523                    },
524                    ..Default::default()
525                })
526            }
527        }
528
529        let window: gpui::AnyWindowHandle = cx
530            .update(|cx| {
531                let mut theme = MaterialTheme::default();
532                theme.layout.direction = Direction::Rtl;
533                MaterialRoot::init(theme, cx);
534                gpui_material_components::init_components(cx);
535                cx.set_reduce_motion(true);
536                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
537                    let picker = cx.new(|cx| TimePickerState::new(window, cx));
538                    cx.new(|_| Fixture { state: picker })
539                })
540                .unwrap()
541            })
542            .into();
543
544        cx.update_window(window, |_, window, cx| {
545            window.draw(cx).clear(cx);
546            let hour_fill: Hsla = rgb(HOUR_COLOR).into();
547            let minute_fill: Hsla = rgb(MINUTE_COLOR).into();
548            let quads = window.painted_quads();
549            let hour_left = quads
550                .iter()
551                .find(|quad| quad.background == hour_fill.into())
552                .expect("hour selector quad")
553                .bounds
554                .left();
555            let minute_left = quads
556                .iter()
557                .find(|quad| quad.background == minute_fill.into())
558                .expect("minute selector quad")
559                .bounds
560                .left();
561            assert!(
562                hour_left < minute_left,
563                "expected hour ({hour_left:?}) left of minute ({minute_left:?}) under RTL"
564            );
565        })
566        .unwrap();
567    }
568}