Skip to main content

gpui_material_extras/date_time/time/
dialog.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
5    RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Styled as _, WeakEntity,
6    Window, div, px,
7};
8use gpui_material_components::{
9    Button, ButtonVariant, Dialog, DialogAction, DialogCloseReason, DialogColors, DialogProperties,
10};
11use gpui_material_foundation::{color, current_material_theme};
12use gpui_material_theme::{ColorRole, CornerShape};
13use jiff::civil::Time;
14
15use super::{
16    controls::TimePickerPanel,
17    state::TimePickerState,
18    types::{
19        TimeFormat, TimePickerLayout, TimePickerLocale, TimePickerSegment, TimePickerStyle,
20        TimePickerVariant,
21    },
22};
23use crate::date_time::Confirm;
24
25type ActionSlot = Box<dyn FnOnce(DialogAction) -> AnyElement>;
26pub(super) type ModeSlot = Box<dyn FnOnce(TimePickerModeAction) -> AnyElement>;
27type DismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
28type OnClosed = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
29
30/// A request to switch between the current input and picker modes.
31#[derive(Clone)]
32pub struct TimePickerModeAction {
33    state: WeakEntity<TimePickerState>,
34    revision: u64,
35    target: TimePickerVariant,
36    displayed: TimePickerVariant,
37    dialog: bool,
38}
39
40impl TimePickerModeAction {
41    /// Returns the [`TimePickerVariant`] that activating this action will switch to.
42    pub fn target(&self) -> TimePickerVariant {
43        self.target
44    }
45
46    /// Changes mode and moves focus to the active segment of the new editor.
47    pub fn activate(&self, window: &mut Window, cx: &mut App) {
48        let _ = self.state.update(cx, |state, cx| {
49            if state.mode_revision == self.revision && (!self.dialog || state.is_open(cx)) {
50                state.set_mode(self.target, window, cx);
51                if state.mode == self.target && self.target == TimePickerVariant::Input {
52                    state.picker_mode = self.displayed;
53                }
54                state.focus_editor(window, cx);
55            }
56        });
57    }
58}
59
60pub(super) fn mode_action(
61    state: &Entity<TimePickerState>,
62    model: &TimePickerState,
63    displayed: TimePickerVariant,
64    dialog: bool,
65) -> TimePickerModeAction {
66    TimePickerModeAction {
67        state: state.downgrade(),
68        revision: model.mode_revision,
69        target: if displayed == TimePickerVariant::Input {
70            model.picker_mode
71        } else {
72            TimePickerVariant::Input
73        },
74        displayed,
75        dialog,
76    }
77}
78
79/// A Material dialog for an application-owned time picker trigger.
80pub type TimePickerDialog = TimeDialog<false>;
81/// A Material time dialog with vibrant colors and an optional visible title.
82pub type VibrantTimePickerDialog = TimeDialog<true>;
83
84/// Shared dialog composition used by both Material time picker presets.
85#[derive(IntoElement)]
86pub struct TimeDialog<const VIBRANT: bool> {
87    id: ElementId,
88    name: SharedString,
89    state: Entity<TimePickerState>,
90    layout: TimePickerLayout,
91    style: TimePickerStyle,
92    shape: Option<CornerShape>,
93    colors: DialogColors,
94    body: Option<AnyElement>,
95    title: Option<AnyElement>,
96    toggle: Option<ModeSlot>,
97    confirm: Option<ActionSlot>,
98    dismiss: Option<ActionSlot>,
99    show_toggle: bool,
100    show_dismiss: bool,
101    properties: DialogProperties,
102    on_confirm: Option<Confirm<Time>>,
103    on_dismiss_request: Option<DismissRequest>,
104    on_closed: Option<OnClosed>,
105}
106
107impl<const VIBRANT: bool> TimeDialog<VIBRANT> {
108    /// Creates a time picker dialog with an element `id`, accessible `name`, and caller-owned `state`.
109    pub fn new(
110        id: impl Into<ElementId>,
111        name: impl Into<SharedString>,
112        state: &Entity<TimePickerState>,
113    ) -> Self {
114        Self {
115            id: id.into(),
116            name: name.into(),
117            state: state.clone(),
118            layout: TimePickerLayout::Auto,
119            style: TimePickerStyle::default(),
120            shape: None,
121            colors: DialogColors::default(),
122            body: None,
123            title: None,
124            toggle: None,
125            confirm: None,
126            dismiss: None,
127            show_toggle: true,
128            show_dismiss: true,
129            properties: DialogProperties::default(),
130            on_confirm: None,
131            on_dismiss_request: None,
132            on_closed: None,
133        }
134    }
135
136    /// Sets the dial layout orientation. Defaults to [`TimePickerLayout::Auto`].
137    pub fn layout(mut self, layout: TimePickerLayout) -> Self {
138        self.layout = layout;
139        self
140    }
141
142    /// Overrides the panel's appearance and color tokens.
143    pub fn style(mut self, style: TimePickerStyle) -> Self {
144        self.style = style;
145        self
146    }
147
148    /// Overrides the surrounding Material dialog container and action colors.
149    pub fn colors(mut self, colors: DialogColors) -> Self {
150        self.colors = colors;
151        self
152    }
153
154    /// Overrides the dialog container's corner shape.
155    pub fn shape(mut self, shape: CornerShape) -> Self {
156        self.shape = Some(shape);
157        self
158    }
159
160    /// Replaces the default [`TimePickerPanel`] body with a custom element.
161    pub fn body(mut self, body: impl IntoElement) -> Self {
162        self.body = Some(body.into_any_element());
163        self
164    }
165
166    /// Sets custom visible title content while keeping `name` as the accessible dialog title.
167    pub fn title_content(mut self, content: impl IntoElement) -> Self {
168        self.title = Some(content.into_any_element());
169        self
170    }
171
172    /// Customizes the button used to toggle between input and picker modes.
173    pub fn mode_toggle_content<E: IntoElement>(
174        mut self,
175        content: impl FnOnce(TimePickerModeAction) -> E + 'static,
176    ) -> Self {
177        self.toggle = Some(Box::new(move |action| content(action).into_any_element()));
178        self
179    }
180
181    /// Customizes the dialog's confirm action button.
182    pub fn confirm_content<E: IntoElement>(
183        mut self,
184        content: impl FnOnce(DialogAction) -> E + 'static,
185    ) -> Self {
186        self.confirm = Some(Box::new(move |action| content(action).into_any_element()));
187        self
188    }
189
190    /// Customizes the dialog's dismiss action button.
191    pub fn dismiss_content<E: IntoElement>(
192        mut self,
193        content: impl FnOnce(DialogAction) -> E + 'static,
194    ) -> Self {
195        self.dismiss = Some(Box::new(move |action| content(action).into_any_element()));
196        self
197    }
198
199    /// Shows or hides the mode-toggle button in the dialog footer.
200    pub fn show_mode_toggle(mut self, show: bool) -> Self {
201        self.show_toggle = show;
202        self
203    }
204
205    /// Shows or hides the dismiss action button in the dialog footer.
206    pub fn show_dismiss(mut self, show: bool) -> Self {
207        self.show_dismiss = show;
208        self
209    }
210
211    /// Configures escape and outside-click dismissal behavior for the dialog.
212    pub fn properties(mut self, properties: DialogProperties) -> Self {
213        self.properties = properties;
214        self
215    }
216
217    /// Registers a callback invoked with the confirmed [`Time`] when accepted.
218    pub fn on_confirm(mut self, confirm: impl Fn(Time, &mut Window, &mut App) + 'static) -> Self {
219        self.on_confirm = Some(Rc::new(confirm));
220        self
221    }
222
223    /// Registers a gate callback called before dismissing; return `false` to keep the dialog open.
224    pub fn on_dismiss_request(
225        mut self,
226        request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
227    ) -> Self {
228        self.on_dismiss_request = Some(Rc::new(request));
229        self
230    }
231
232    /// Registers a callback invoked after the dialog closes, with the [`DialogCloseReason`].
233    pub fn on_closed(
234        mut self,
235        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
236    ) -> Self {
237        self.on_closed = Some(Rc::new(callback));
238        self
239    }
240}
241
242impl<const VIBRANT: bool> RenderOnce for TimeDialog<VIBRANT> {
243    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
244        let model = self.state.read(cx);
245        let toggle = self.show_toggle.then(|| {
246            let action = mode_action(&self.state, model, model.mode, true);
247            if let Some(custom) = self.toggle {
248                custom(action)
249            } else {
250                Button::new(
251                    (self.id.clone(), "display-mode"),
252                    match action.target() {
253                        TimePickerVariant::Dial => "Show clock",
254                        TimePickerVariant::Input => "Enter time",
255                        TimePickerVariant::Scroll => "Show scroll wheels",
256                    },
257                )
258                .variant(ButtonVariant::Text)
259                .on_activate(move |window, cx| action.activate(window, cx))
260                .into_any_element()
261            }
262        });
263        let body = self.body.unwrap_or_else(|| {
264            TimePickerPanel::new(self.id.clone(), &self.state)
265                .layout(self.layout)
266                .style(self.style)
267                .vibrant(VIBRANT)
268                .into_any_element()
269        });
270        if VIBRANT {
271            let theme = current_material_theme(window, cx);
272            self.colors
273                .container
274                .get_or_insert_with(|| color(theme.colors.color(ColorRole::SurfaceContainer)));
275        }
276        let state = self.state.clone();
277        let dismiss_state = self.state.clone();
278        let close_state = self.state;
279        let confirm = self.on_confirm;
280        let closed = self.on_closed;
281        let dismiss_request = self.on_dismiss_request;
282        let mut dialog = Dialog::new(self.id, &model.dialog, self.name)
283            .show_title(!VIBRANT || self.title.is_some())
284            .colors(self.colors)
285            .properties(self.properties)
286            .show_cancel(self.show_dismiss)
287            .body(
288                div()
289                    .flex()
290                    .flex_col()
291                    .items_center()
292                    .gap(px(8.))
293                    .child(body)
294                    .children(toggle),
295            )
296            .confirm("OK", move |window, cx| {
297                state.update(cx, |state, cx| {
298                    if state.has_composition(window, cx) {
299                        return false;
300                    }
301                    if state.mode != TimePickerVariant::Input {
302                        return true;
303                    }
304                    if let Some(segment) = state.invalid_segment(cx) {
305                        state.input_attempted = true;
306                        state.set_segment(segment, cx);
307                        state.focus_editor(window, cx);
308                        cx.notify();
309                        return false;
310                    }
311                    state.reconcile_input(cx);
312                    true
313                })
314            })
315            .on_dismiss_request(move |reason, window, cx| {
316                if reason == DialogCloseReason::Escape
317                    && dismiss_state.update(cx, |state, cx| state.finish_composition(window, cx))
318                {
319                    return false;
320                }
321                dismiss_request
322                    .as_ref()
323                    .is_none_or(|request| request(reason, window, cx))
324            })
325            .on_closed(move |reason, window, cx| {
326                let value = close_state.update(cx, |state, cx| {
327                    state.dial_dragging = false;
328                    state.discard_composition(window, cx);
329                    state.sync_wheels(cx);
330                    state.value()
331                });
332                if reason == DialogCloseReason::Confirm
333                    && let Some(confirm) = &confirm
334                {
335                    confirm(value, window, cx);
336                }
337                if let Some(closed) = &closed {
338                    closed(reason, window, cx);
339                }
340            });
341        if let Some(shape) = self.shape {
342            dialog = dialog.shape(shape);
343        }
344        if let Some(title) = self.title {
345            dialog = dialog.title_content(title);
346        }
347        if let Some(content) = self.confirm {
348            dialog = dialog.confirm_content(content);
349        }
350        if self.show_dismiss
351            && let Some(content) = self.dismiss
352        {
353            dialog = dialog.dismiss_content(content);
354        }
355        dialog
356    }
357}
358
359struct TimeOptions {
360    value: Time,
361    format: TimeFormat,
362    variant: TimePickerVariant,
363    layout: TimePickerLayout,
364    locale: TimePickerLocale,
365}
366
367/// A button that edits a committed time in a Material dialog.
368#[derive(IntoElement)]
369pub struct TimePicker {
370    id: ElementId,
371    label: SharedString,
372    state: Entity<TimePickerState>,
373    options: TimeOptions,
374    confirm: Option<Confirm<Time>>,
375    style: TimePickerStyle,
376    colors: DialogColors,
377    show_mode_toggle: bool,
378    properties: DialogProperties,
379    on_dismiss_request: Option<DismissRequest>,
380    on_closed: Option<OnClosed>,
381    disabled: bool,
382}
383
384impl TimePicker {
385    /// Creates a triggered time picker bound to `state` with the caller-owned committed `value`.
386    pub fn new(
387        id: impl Into<ElementId>,
388        label: impl Into<SharedString>,
389        state: &Entity<TimePickerState>,
390        value: Time,
391    ) -> Self {
392        Self {
393            id: id.into(),
394            label: label.into(),
395            state: state.clone(),
396            options: TimeOptions {
397                value,
398                format: TimeFormat::default(),
399                variant: TimePickerVariant::default(),
400                layout: TimePickerLayout::default(),
401                locale: TimePickerLocale::default(),
402            },
403            confirm: None,
404            style: TimePickerStyle::default(),
405            colors: DialogColors::default(),
406            show_mode_toggle: true,
407            properties: DialogProperties::default(),
408            on_dismiss_request: None,
409            on_closed: None,
410            disabled: false,
411        }
412    }
413
414    /// Sets the 12-hour or 24-hour clock format used when the trigger opens the dialog.
415    pub fn format(mut self, format: TimeFormat) -> Self {
416        self.options.format = format;
417        self
418    }
419
420    /// Sets the initial editor mode (`Dial`, `Input`, or `Scroll`) applied on open.
421    pub fn variant(mut self, variant: TimePickerVariant) -> Self {
422        self.options.variant = variant;
423        self
424    }
425
426    /// Sets the dial layout orientation.
427    pub fn layout(mut self, layout: TimePickerLayout) -> Self {
428        self.options.layout = layout;
429        self
430    }
431
432    /// Sets the locale formatting, parsing, and labels applied on open.
433    pub fn locale(mut self, locale: TimePickerLocale) -> Self {
434        self.options.locale = locale;
435        self
436    }
437
438    /// Overrides the panel's appearance and color tokens.
439    pub fn style(mut self, style: TimePickerStyle) -> Self {
440        self.style = style;
441        self
442    }
443
444    /// Overrides the dialog container and action colors.
445    pub fn colors(mut self, colors: DialogColors) -> Self {
446        self.colors = colors;
447        self
448    }
449
450    /// Shows or hides the mode-toggle button in the dialog footer.
451    pub fn show_mode_toggle(mut self, show: bool) -> Self {
452        self.show_mode_toggle = show;
453        self
454    }
455
456    /// Configures escape and outside-click dismissal behavior for the dialog.
457    pub fn properties(mut self, properties: DialogProperties) -> Self {
458        self.properties = properties;
459        self
460    }
461
462    /// Registers a gate callback called before dismissing; return `false` to keep the dialog open.
463    pub fn on_dismiss_request(
464        mut self,
465        request: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
466    ) -> Self {
467        self.on_dismiss_request = Some(Rc::new(request));
468        self
469    }
470
471    /// Registers a callback invoked after the dialog closes, with the [`DialogCloseReason`].
472    pub fn on_closed(
473        mut self,
474        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
475    ) -> Self {
476        self.on_closed = Some(Rc::new(callback));
477        self
478    }
479
480    /// Disables the built-in trigger button.
481    pub fn disabled(mut self, disabled: bool) -> Self {
482        self.disabled = disabled;
483        self
484    }
485
486    /// Registers a callback invoked with the confirmed [`Time`] when accepted.
487    pub fn on_confirm(mut self, callback: impl Fn(Time, &mut Window, &mut App) + 'static) -> Self {
488        self.confirm = Some(Rc::new(callback));
489        self
490    }
491}
492
493impl RenderOnce for TimePicker {
494    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
495        let model = self.state.read(cx);
496        let state = self.state.clone();
497        let options = self.options;
498        let layout = options.layout;
499        let trigger = div()
500            .id((self.id.clone(), "trigger-group"))
501            .role(Role::Group)
502            .aria_expanded(model.is_open(cx))
503            .child(
504                Button::new((self.id.clone(), "open"), self.label.clone())
505                    .variant(ButtonVariant::Outlined)
506                    .disabled(self.disabled)
507                    .track_focus(&model.trigger)
508                    .on_activate(move |window, cx| {
509                        state.update(cx, |state, cx| {
510                            if !state.is_open(cx) {
511                                state.trigger.focus(window, cx);
512                                state.set_segment(TimePickerSegment::Hour, cx);
513                                state.picker_mode = TimePickerVariant::Dial;
514                                state.set_mode(options.variant, window, cx);
515                                state.set_format(options.format, window, cx);
516                                state.set_locale(options.locale.clone(), window, cx);
517                                state.open(options.value, window, cx);
518                            }
519                        });
520                    }),
521            );
522        let mut dialog = TimePickerDialog::new(self.id, self.label, &self.state)
523            .layout(layout)
524            .style(self.style)
525            .colors(self.colors)
526            .show_mode_toggle(self.show_mode_toggle)
527            .properties(self.properties);
528        dialog.on_confirm = self.confirm;
529        dialog.on_dismiss_request = self.on_dismiss_request;
530        dialog.on_closed = self.on_closed;
531        div().child(trigger).child(dialog)
532    }
533}