Skip to main content

gpui_material_extras/date_time/
time.rs

1use std::rc::Rc;
2
3use chrono::Timelike;
4use gpui::{
5    App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Focusable as _,
6    SharedString, Window,
7};
8use gpui_material_components::{DialogState, TextFieldEvent, TextFieldState};
9
10use super::{NaiveTime, ScrollFieldState};
11
12mod dialog;
13mod panel;
14
15pub use dialog::{TimePicker, TimePickerDialog, TimePickerModeAction, VibrantTimePickerDialog};
16pub use panel::{TimePickerPanel, TimePickerSelectionColors, TimePickerStyle, TimeScroll};
17
18/// Hour display convention for a time picker.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub enum TimeFormat {
21    /// 12-hour clock (`1`–`12`) with an AM/PM period selector.
22    TwelveHour,
23    /// 24-hour clock (`00`–`23`) without a period selector.
24    #[default]
25    TwentyFourHour,
26}
27
28/// Interactive editor mode for a time picker.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum TimePickerVariant {
31    /// Circular clock dial with clickable and draggable hands.
32    #[default]
33    Dial,
34    /// Direct numeric text fields for hours and minutes.
35    Input,
36    /// Wrapping vertical scroll wheels for hours and minutes.
37    Scroll,
38}
39
40/// Orientation of the dial relative to the time header in a time picker.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub enum TimePickerLayout {
43    /// Switches to horizontal when the viewport is wide (`>= 600px`) and short (`< 650px`).
44    #[default]
45    Auto,
46    /// Always stacks the time header above the dial.
47    Vertical,
48    /// Places the time header beside the dial when the viewport is at least `600px` wide.
49    Horizontal,
50}
51
52type NumberFormatter = Rc<dyn Fn(u32) -> SharedString>;
53type NumberParser = Rc<dyn Fn(&str) -> Option<u32>>;
54
55/// Application locale hooks for numbers, period names, separator, and labels.
56#[derive(Clone)]
57pub struct TimePickerLocale {
58    number: NumberFormatter,
59    parse: NumberParser,
60    am: SharedString,
61    pm: SharedString,
62    separator: SharedString,
63    hour: SharedString,
64    minute: SharedString,
65    validation_message: SharedString,
66}
67
68impl Default for TimePickerLocale {
69    fn default() -> Self {
70        Self {
71            number: Rc::new(|value| super::format_two_digits(value as usize)),
72            parse: Rc::new(|text| text.parse().ok()),
73            am: SharedString::new_static("AM"),
74            pm: SharedString::new_static("PM"),
75            separator: SharedString::new_static(":"),
76            hour: SharedString::new_static("Hour"),
77            minute: SharedString::new_static("Minute"),
78            validation_message: SharedString::new_static("Enter a valid time"),
79        }
80    }
81}
82
83impl TimePickerLocale {
84    /// Sets custom formatting and parsing functions for hour and minute numerals.
85    pub fn numbers(
86        mut self,
87        format: impl Fn(u32) -> SharedString + 'static,
88        parse: impl Fn(&str) -> Option<u32> + 'static,
89    ) -> Self {
90        self.number = Rc::new(format);
91        self.parse = Rc::new(parse);
92        self
93    }
94
95    /// Sets localized labels for the hour field, minute field, separator, and AM/PM periods.
96    pub fn labels(
97        mut self,
98        hour: impl Into<SharedString>,
99        minute: impl Into<SharedString>,
100        separator: impl Into<SharedString>,
101        am: impl Into<SharedString>,
102        pm: impl Into<SharedString>,
103    ) -> Self {
104        self.hour = hour.into();
105        self.minute = minute.into();
106        self.separator = separator.into();
107        self.am = am.into();
108        self.pm = pm.into();
109        self
110    }
111
112    /// Sets the error message shown when text input cannot be parsed as a valid time.
113    pub fn validation_message(mut self, message: impl Into<SharedString>) -> Self {
114        self.validation_message = message.into();
115        self
116    }
117}
118
119/// The time component currently targeted for editing.
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
121pub enum TimePickerSegment {
122    /// Editing the hour component.
123    #[default]
124    Hour,
125    /// Editing the minute component.
126    Minute,
127}
128
129fn display_hour(time: NaiveTime, format: TimeFormat) -> u32 {
130    if format == TimeFormat::TwelveHour {
131        time.hour12().1
132    } else {
133        time.hour()
134    }
135}
136
137fn parse_segment(
138    locale: &TimePickerLocale,
139    segment: TimePickerSegment,
140    text: &str,
141    format: TimeFormat,
142    pm: bool,
143) -> Option<u32> {
144    let value = (locale.parse)(text.trim())?;
145    match (segment, format) {
146        (TimePickerSegment::Hour, TimeFormat::TwelveHour) if (1..=12).contains(&value) => {
147            Some(value % 12 + u32::from(pm) * 12)
148        }
149        (TimePickerSegment::Hour, TimeFormat::TwentyFourHour) if value < 24 => Some(value),
150        (TimePickerSegment::Minute, _) if value < 60 => Some(value),
151        _ => None,
152    }
153}
154
155fn format_time(time: NaiveTime, format: TimeFormat, locale: &TimePickerLocale) -> SharedString {
156    let hour = (locale.number)(display_hour(time, format));
157    let minute = (locale.number)(time.minute());
158    let suffix = if format == TimeFormat::TwelveHour {
159        format!(
160            " {}",
161            if time.hour() < 12 {
162                &locale.am
163            } else {
164                &locale.pm
165            }
166        )
167    } else {
168        String::new()
169    };
170    format!("{hour}{}{minute}{suffix}", locale.separator).into()
171}
172
173/// Owns one editable time, its input fields, selection wheels, and dialog session.
174pub struct TimePickerState {
175    draft: NaiveTime,
176    segment: TimePickerSegment,
177    mode: TimePickerVariant,
178    picker_mode: TimePickerVariant,
179    format: TimeFormat,
180    locale: TimePickerLocale,
181    input_attempted: bool,
182    mode_revision: u64,
183    hour: Entity<TextFieldState>,
184    minute: Entity<TextFieldState>,
185    hours: Entity<ScrollFieldState>,
186    minutes: Entity<ScrollFieldState>,
187    dialog: Entity<DialogState>,
188    trigger: FocusHandle,
189    panel: FocusHandle,
190    dial: FocusHandle,
191}
192
193impl TimePickerState {
194    /// Creates a time picker state initialized to `00:00` in 24-hour dial mode.
195    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
196        let hour = cx.new(|cx| TextFieldState::new(window, cx));
197        let minute = cx.new(|cx| TextFieldState::new(window, cx));
198        let hours = cx.new(|cx| ScrollFieldState::new(24, 0, cx));
199        let minutes = cx.new(|cx| ScrollFieldState::new(60, 0, cx));
200        let dialog = cx.new(DialogState::new);
201        for (segment, editor, wheel) in [
202            (TimePickerSegment::Hour, &hour, &hours),
203            (TimePickerSegment::Minute, &minute, &minutes),
204        ] {
205            cx.subscribe_in(editor, window, move |state, editor, event, window, cx| {
206                if matches!(event, TextFieldEvent::Change) && !has_marked_text(editor, window, cx) {
207                    let text = editor.read(cx).value();
208                    state.apply_input(segment, &text, cx);
209                }
210            })
211            .detach();
212            cx.observe_in(wheel, window, move |state, wheel, window, cx| {
213                let wheel = wheel.read(cx);
214                if !wheel.is_scroll_in_progress()
215                    && let Some(index) = wheel.selected_option()
216                    && index != state.wheel_index(segment)
217                {
218                    let mut value = index as u32;
219                    if segment == TimePickerSegment::Hour && state.format == TimeFormat::TwelveHour
220                    {
221                        value = (value + 1) % 12 + state.hour() / 12 * 12;
222                    }
223                    if !state
224                        .segment_focus(state.segment, TimePickerVariant::Scroll, cx)
225                        .is_focused(window)
226                    {
227                        state.set_segment(segment, cx);
228                    }
229                    state.update_draft(segment, value);
230                    state.sync_field(segment, window, cx);
231                    cx.notify();
232                }
233            })
234            .detach();
235            for focus in [
236                editor.read(cx).focus_handle(cx),
237                wheel.read(cx).focus_handle().clone(),
238            ] {
239                cx.on_focus(&focus, window, move |state, _, cx| {
240                    state.set_segment(segment, cx)
241                })
242                .detach();
243            }
244        }
245        cx.observe(&dialog, |_, _, cx| cx.notify()).detach();
246        let state = Self {
247            draft: NaiveTime::default(),
248            segment: TimePickerSegment::Hour,
249            mode: TimePickerVariant::Dial,
250            picker_mode: TimePickerVariant::Dial,
251            format: TimeFormat::TwentyFourHour,
252            locale: TimePickerLocale::default(),
253            input_attempted: false,
254            mode_revision: 0,
255            hour,
256            minute,
257            hours,
258            minutes,
259            dialog,
260            trigger: cx.focus_handle(),
261            panel: cx.focus_handle(),
262            dial: cx.focus_handle(),
263        };
264        state.sync_fields(window, cx);
265        state
266    }
267
268    /// The latest valid draft, at minute precision.
269    pub fn value(&self) -> NaiveTime {
270        self.draft
271    }
272
273    /// Returns the draft hour in 24-hour format (`0`–`23`).
274    pub fn hour(&self) -> u32 {
275        self.draft.hour()
276    }
277
278    /// Returns the draft minute (`0`–`59`).
279    pub fn minute(&self) -> u32 {
280        self.draft.minute()
281    }
282
283    /// Returns `true` when the draft hour is `12` or later.
284    pub fn is_pm(&self) -> bool {
285        self.hour() >= 12
286    }
287
288    /// Returns the currently active editing segment ([`TimePickerSegment::Hour`] or [`TimePickerSegment::Minute`]).
289    pub fn segment(&self) -> TimePickerSegment {
290        self.segment
291    }
292
293    /// Returns the active editor mode ([`TimePickerVariant`]).
294    pub fn mode(&self) -> TimePickerVariant {
295        self.mode
296    }
297
298    /// Returns the active 12-hour or 24-hour [`TimeFormat`].
299    pub fn format(&self) -> TimeFormat {
300        self.format
301    }
302
303    /// Returns the raw text currently in the hour input field.
304    pub fn hour_input(&self, cx: &App) -> SharedString {
305        self.hour.read(cx).value()
306    }
307
308    /// Returns the raw text currently in the minute input field.
309    pub fn minute_input(&self, cx: &App) -> SharedString {
310        self.minute.read(cx).value()
311    }
312
313    /// Replaces the text in the hour input field and updates the draft if valid.
314    pub fn set_hour_input(
315        &mut self,
316        text: impl Into<SharedString>,
317        window: &mut Window,
318        cx: &mut Context<Self>,
319    ) {
320        self.set_input(TimePickerSegment::Hour, text.into(), window, cx);
321    }
322
323    /// Replaces the text in the minute input field and updates the draft if valid.
324    pub fn set_minute_input(
325        &mut self,
326        text: impl Into<SharedString>,
327        window: &mut Window,
328        cx: &mut Context<Self>,
329    ) {
330        self.set_input(TimePickerSegment::Minute, text.into(), window, cx);
331    }
332
333    /// Returns whether the hour input field currently parses as a valid hour for the active format.
334    pub fn is_hour_input_valid(&self, cx: &App) -> bool {
335        self.valid_input(TimePickerSegment::Hour, cx)
336    }
337
338    /// Returns whether the minute input field currently parses as a valid minute (`0`–`59`).
339    pub fn is_minute_input_valid(&self, cx: &App) -> bool {
340        self.valid_input(TimePickerSegment::Minute, cx)
341    }
342
343    /// Returns whether both hour and minute input fields currently contain valid values.
344    pub fn is_input_valid(&self, cx: &App) -> bool {
345        self.invalid_segment(cx).is_none()
346    }
347
348    /// Returns whether the picker's modal dialog is currently open.
349    pub fn is_open(&self, cx: &App) -> bool {
350        self.dialog.read(cx).is_open()
351    }
352
353    /// Returns the retained focus handle of the built-in picker trigger.
354    pub fn trigger_focus(&self) -> &FocusHandle {
355        &self.trigger
356    }
357
358    /// Replaces the editable draft and cancels outstanding wheel motion.
359    pub fn set_value(&mut self, value: NaiveTime, window: &mut Window, cx: &mut Context<Self>) {
360        let next = NaiveTime::from_hms_opt(value.hour(), value.minute(), 0).unwrap();
361        let draft_changed = self.draft != next;
362        let attempted_changed = self.input_attempted;
363        self.draft = next;
364        self.input_attempted = false;
365        let fields_changed = self.sync_fields(window, cx);
366        let wheels_changed = self.sync_wheels(cx);
367        if draft_changed || attempted_changed || fields_changed || wheels_changed {
368            cx.notify();
369        }
370    }
371
372    /// Sets a 24-hour value. Returns whether the supplied hour was valid.
373    pub fn set_hour(&mut self, hour: u32, window: &mut Window, cx: &mut Context<Self>) -> bool {
374        self.set_part(TimePickerSegment::Hour, hour, window, cx)
375    }
376
377    /// Sets a minute in 0–59. Returns whether the supplied minute was valid.
378    pub fn set_minute(&mut self, minute: u32, window: &mut Window, cx: &mut Context<Self>) -> bool {
379        self.set_part(TimePickerSegment::Minute, minute, window, cx)
380    }
381
382    /// Switches the active editing segment between hours and minutes.
383    pub fn set_segment(&mut self, segment: TimePickerSegment, cx: &mut Context<Self>) {
384        if segment != self.segment {
385            self.segment = segment;
386            cx.notify();
387        }
388    }
389
390    /// Retains the active segment across mode changes. Reconciles editors with the last valid time.
391    pub fn set_mode(
392        &mut self,
393        mode: TimePickerVariant,
394        window: &mut Window,
395        cx: &mut Context<Self>,
396    ) {
397        if mode != self.mode && !self.has_composition(window, cx) {
398            if self.mode == TimePickerVariant::Input {
399                self.reconcile_input(cx);
400            }
401            let restore_focus = self.panel.contains_focused(window, cx);
402            self.mode = mode;
403            self.mode_revision = self.mode_revision.wrapping_add(1);
404            if mode != TimePickerVariant::Input {
405                self.picker_mode = mode;
406            }
407            self.input_attempted = false;
408            self.sync_fields(window, cx);
409            self.sync_wheels(cx);
410            if restore_focus {
411                self.focus_editor(window, cx);
412            }
413            cx.notify();
414        }
415    }
416
417    /// Switches between 12-hour and 24-hour display formats and resynchronizes editors and wheels.
418    pub fn set_format(&mut self, format: TimeFormat, window: &mut Window, cx: &mut Context<Self>) {
419        if format != self.format {
420            self.format = format;
421            self.input_attempted = false;
422            self.sync_fields(window, cx);
423            self.sync_wheels(cx);
424            cx.notify();
425        }
426    }
427
428    /// Replaces the locale hooks and reformats the hour and minute input fields.
429    pub fn set_locale(
430        &mut self,
431        locale: TimePickerLocale,
432        window: &mut Window,
433        cx: &mut Context<Self>,
434    ) {
435        self.locale = locale;
436        self.input_attempted = false;
437        self.sync_fields(window, cx);
438        cx.notify();
439    }
440
441    /// Opens a new editing session initialized from the application's value.
442    pub fn open(&mut self, value: NaiveTime, window: &mut Window, cx: &mut Context<Self>) {
443        if !self.is_open(cx) {
444            self.mode_revision = self.mode_revision.wrapping_add(1);
445            self.set_value(value, window, cx);
446            self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
447            self.focus_editor(window, cx);
448        }
449    }
450
451    /// Closes this session programmatically through the Material dialog.
452    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
453        if self.is_open(cx) {
454            self.discard_composition(window, cx);
455            self.sync_wheels(cx);
456            self.dialog
457                .update(cx, |dialog, cx| dialog.close(window, cx));
458        }
459    }
460
461    fn has_composition(&self, window: &mut Window, cx: &mut App) -> bool {
462        [&self.hour, &self.minute]
463            .into_iter()
464            .any(|field| has_marked_text(field, window, cx))
465    }
466
467    fn finish_composition(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
468        let mut composed = false;
469        for editor in [&self.hour, &self.minute] {
470            composed |= editor.update(cx, |editor, cx| {
471                if editor.marked_text_range(window, cx).is_none() {
472                    return false;
473                }
474                editor.unmark_text(window, cx);
475                true
476            });
477        }
478        if composed {
479            self.reconcile_input(cx);
480        }
481        composed
482    }
483
484    fn discard_composition(&self, window: &mut Window, cx: &mut Context<Self>) {
485        if self.has_composition(window, cx) {
486            self.sync_fields(window, cx);
487        }
488    }
489
490    fn reconcile_input(&mut self, cx: &mut Context<Self>) {
491        for segment in [TimePickerSegment::Hour, TimePickerSegment::Minute] {
492            let text = self.field(segment).read(cx).value();
493            if let Some(value) = self.parse_segment(segment, &text) {
494                self.update_draft(segment, value);
495                self.sync_wheel(segment, cx);
496            }
497        }
498        cx.notify();
499    }
500
501    fn parse_segment(&self, segment: TimePickerSegment, text: &str) -> Option<u32> {
502        parse_segment(&self.locale, segment, text, self.format, self.is_pm())
503    }
504
505    fn valid_input(&self, segment: TimePickerSegment, cx: &App) -> bool {
506        self.parse_segment(segment, &self.field(segment).read(cx).value())
507            .is_some()
508    }
509
510    fn invalid_segment(&self, cx: &App) -> Option<TimePickerSegment> {
511        [TimePickerSegment::Hour, TimePickerSegment::Minute]
512            .into_iter()
513            .find(|&segment| !self.valid_input(segment, cx))
514    }
515
516    fn apply_input(&mut self, segment: TimePickerSegment, text: &str, cx: &mut Context<Self>) {
517        if let Some(value) = self.parse_segment(segment, text) {
518            self.update_draft(segment, value);
519            self.sync_wheel(segment, cx);
520        }
521        cx.notify();
522    }
523
524    fn set_input(
525        &mut self,
526        segment: TimePickerSegment,
527        text: SharedString,
528        window: &mut Window,
529        cx: &mut Context<Self>,
530    ) {
531        self.field(segment)
532            .update(cx, |field, cx| field.set_value(text.clone(), window, cx));
533        self.apply_input(segment, &text, cx);
534    }
535
536    fn field(&self, segment: TimePickerSegment) -> &Entity<TextFieldState> {
537        match segment {
538            TimePickerSegment::Hour => &self.hour,
539            TimePickerSegment::Minute => &self.minute,
540        }
541    }
542
543    fn wheel(&self, segment: TimePickerSegment) -> &Entity<ScrollFieldState> {
544        match segment {
545            TimePickerSegment::Hour => &self.hours,
546            TimePickerSegment::Minute => &self.minutes,
547        }
548    }
549
550    fn wheel_index(&self, segment: TimePickerSegment) -> usize {
551        match segment {
552            TimePickerSegment::Hour => {
553                let hour = display_hour(self.draft, self.format) as usize;
554                hour - usize::from(self.format == TimeFormat::TwelveHour)
555            }
556            TimePickerSegment::Minute => self.minute() as usize,
557        }
558    }
559
560    fn sync_field(
561        &self,
562        segment: TimePickerSegment,
563        window: &mut Window,
564        cx: &mut Context<Self>,
565    ) -> bool {
566        let number = match segment {
567            TimePickerSegment::Hour => display_hour(self.draft, self.format),
568            TimePickerSegment::Minute => self.minute(),
569        };
570        let text = (self.locale.number)(number);
571        let field = self.field(segment);
572        if field.read(cx).value() != text || has_marked_text(field, window, cx) {
573            field.update(cx, |field, cx| field.set_value(text, window, cx));
574            true
575        } else {
576            false
577        }
578    }
579
580    fn sync_fields(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
581        self.sync_field(TimePickerSegment::Hour, window, cx)
582            | self.sync_field(TimePickerSegment::Minute, window, cx)
583    }
584
585    fn sync_wheel(&self, segment: TimePickerSegment, cx: &mut Context<Self>) -> bool {
586        let count = match (segment, self.format) {
587            (TimePickerSegment::Hour, TimeFormat::TwelveHour) => 12,
588            (TimePickerSegment::Hour, TimeFormat::TwentyFourHour) => 24,
589            (TimePickerSegment::Minute, _) => 60,
590        };
591        let index = self.wheel_index(segment);
592        self.wheel(segment).update(cx, |wheel, cx| {
593            wheel.set_item_count(count, cx);
594            if wheel.target_option() != Some(index) || wheel.is_scroll_in_progress() {
595                wheel.scroll_to_option(index, cx);
596                true
597            } else {
598                false
599            }
600        })
601    }
602
603    fn sync_wheels(&self, cx: &mut Context<Self>) -> bool {
604        self.sync_wheel(TimePickerSegment::Hour, cx)
605            | self.sync_wheel(TimePickerSegment::Minute, cx)
606    }
607
608    fn update_draft(&mut self, segment: TimePickerSegment, value: u32) -> bool {
609        let time = match segment {
610            TimePickerSegment::Hour => self.draft.with_hour(value),
611            TimePickerSegment::Minute => self.draft.with_minute(value),
612        };
613        if let Some(time) = time {
614            self.draft = time;
615        }
616        time.is_some()
617    }
618
619    fn set_part(
620        &mut self,
621        segment: TimePickerSegment,
622        value: u32,
623        window: &mut Window,
624        cx: &mut Context<Self>,
625    ) -> bool {
626        let previous = self.draft;
627        if !self.update_draft(segment, value) {
628            return false;
629        }
630        let field_changed = self.sync_field(segment, window, cx);
631        let wheel_changed = self.sync_wheel(segment, cx);
632        if self.draft != previous || field_changed || wheel_changed {
633            cx.notify();
634        }
635        true
636    }
637
638    fn segment_focus(
639        &self,
640        segment: TimePickerSegment,
641        mode: TimePickerVariant,
642        cx: &App,
643    ) -> FocusHandle {
644        match mode {
645            TimePickerVariant::Dial => self.dial.clone(),
646            TimePickerVariant::Input => self.field(segment).read(cx).focus_handle(cx),
647            TimePickerVariant::Scroll => self.wheel(segment).read(cx).focus_handle().clone(),
648        }
649    }
650
651    fn editor_focus(&self, mode: TimePickerVariant, cx: &App) -> FocusHandle {
652        self.segment_focus(self.segment, mode, cx)
653    }
654
655    fn focus_editor(&self, window: &mut Window, cx: &mut App) {
656        self.editor_focus(self.mode, cx).focus(window, cx);
657    }
658
659    fn select(&mut self, value: u32, advance: bool, window: &mut Window, cx: &mut Context<Self>) {
660        let segment = self.segment;
661        let value = if segment == TimePickerSegment::Hour && self.format == TimeFormat::TwelveHour {
662            value % 12 + self.hour() / 12 * 12
663        } else {
664            value
665        };
666        if self.set_part(segment, value, window, cx)
667            && advance
668            && segment == TimePickerSegment::Hour
669        {
670            self.set_segment(TimePickerSegment::Minute, cx);
671        }
672    }
673}
674
675fn has_marked_text(field: &Entity<TextFieldState>, window: &mut Window, cx: &mut App) -> bool {
676    field.update(cx, |editor, cx| {
677        editor.marked_text_range(window, cx).is_some()
678    })
679}
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684
685    #[test]
686    fn local_time_parsing_handles_midnight_noon_and_boundaries() {
687        let locale = TimePickerLocale::default();
688        let parse_hour = |text, pm| {
689            parse_segment(
690                &locale,
691                TimePickerSegment::Hour,
692                text,
693                TimeFormat::TwelveHour,
694                pm,
695            )
696        };
697        assert_eq!(parse_hour("12", false), Some(0));
698        assert_eq!(parse_hour("12", true), Some(12));
699        assert_eq!(parse_hour("11", true), Some(23));
700        assert_eq!(parse_hour("00", false), None);
701        assert_eq!(
702            parse_segment(
703                &locale,
704                TimePickerSegment::Minute,
705                "60",
706                TimeFormat::TwelveHour,
707                false
708            ),
709            None
710        );
711        assert_eq!(
712            parse_segment(
713                &locale,
714                TimePickerSegment::Hour,
715                "24",
716                TimeFormat::TwentyFourHour,
717                false
718            ),
719            None
720        );
721    }
722    #[cfg(feature = "test-support")]
723    #[gpui::test]
724    fn time_dialog_waits_for_ime_then_confirms_the_unmarked_value(cx: &mut gpui::TestAppContext) {
725        use std::cell::{Cell, RefCell};
726
727        use gpui::{IntoElement, Render, WindowOptions, div};
728        use gpui_material_components::DialogAction;
729        use gpui_material_foundation::MaterialRoot;
730        use gpui_material_theme::MaterialTheme;
731
732        struct Fixture {
733            state: Entity<TimePickerState>,
734            change_mode: Rc<RefCell<Option<TimePickerModeAction>>>,
735            confirm: Rc<RefCell<Option<DialogAction>>>,
736            accepted: Rc<Cell<Option<NaiveTime>>>,
737        }
738
739        impl Render for Fixture {
740            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
741                let change_mode = self.change_mode.clone();
742                let confirm = self.confirm.clone();
743                let accepted = self.accepted.clone();
744                TimePickerDialog::new("ime-clock", "Input composition", &self.state)
745                    .mode_toggle_content(move |action| {
746                        change_mode.replace(Some(action));
747                        div()
748                    })
749                    .confirm_content(move |action| {
750                        confirm.replace(Some(action));
751                        div()
752                    })
753                    .on_confirm(move |time, _, _| accepted.set(Some(time)))
754            }
755        }
756
757        let mode = Rc::new(RefCell::new(None));
758        let confirm = Rc::new(RefCell::new(None));
759        let accepted = Rc::new(Cell::new(None));
760        let mut state = None;
761        let window = cx
762            .update(|cx| {
763                MaterialRoot::init(MaterialTheme::default(), cx);
764                gpui_material_components::init_components(cx);
765                cx.set_reduce_motion(true);
766                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
767                    let picker = cx.new(|cx| {
768                        let mut picker = TimePickerState::new(window, cx);
769                        picker.set_mode(TimePickerVariant::Input, window, cx);
770                        picker
771                    });
772                    state = Some(picker.clone());
773                    cx.new(|cx| {
774                        cx.observe(&picker, |_, _, cx| cx.notify()).detach();
775                        Fixture {
776                            state: picker,
777                            change_mode: mode.clone(),
778                            confirm: confirm.clone(),
779                            accepted: accepted.clone(),
780                        }
781                    })
782                })
783                .unwrap()
784            })
785            .into();
786        let state = state.unwrap();
787        let initial = NaiveTime::from_hms_opt(15, 25, 0).unwrap();
788        cx.update_window(window, |_, window, cx| {
789            state.update(cx, |state, cx| state.open(initial, window, cx));
790            window.draw(cx).clear(cx);
791        })
792        .unwrap();
793        cx.run_until_parked();
794        let change_mode = mode.borrow().clone().unwrap();
795        let apply = confirm.borrow().clone().unwrap();
796
797        cx.update_window(window, |_, window, cx| {
798            let editor = state.read(cx).hour.clone();
799            editor.update(cx, |editor, cx| {
800                editor.replace_and_mark_text_in_range(Some(0..2), "19", Some(1..1), window, cx);
801            });
802            change_mode.activate(window, cx);
803            apply.activate(window, cx);
804            let model = state.read(cx);
805            assert_eq!(model.mode(), TimePickerVariant::Input);
806            assert_eq!(model.value(), initial);
807            assert_eq!(model.hour_input(cx).as_ref(), "19");
808            assert!(model.is_open(cx));
809            assert!(accepted.get().is_none());
810        })
811        .unwrap();
812
813        cx.simulate_keystrokes(window, "escape");
814        cx.update_window(window, |_, window, cx| {
815            let model = state.read(cx);
816            let editor = model.hour.clone();
817            assert!(model.is_open(cx));
818            assert!(accepted.get().is_none());
819            editor.update(cx, |editor, cx| {
820                assert!(editor.marked_text_range(window, cx).is_none());
821                editor.replace_and_mark_text_in_range(Some(0..2), "21", Some(1..1), window, cx);
822                editor.unmark_text(window, cx);
823            });
824            apply.activate(window, cx);
825            assert_eq!(accepted.get(), NaiveTime::from_hms_opt(21, 25, 0));
826            assert!(!state.read(cx).is_open(cx));
827
828            state.update(cx, |state, cx| state.open(initial, window, cx));
829            let editor = state.read(cx).hour.clone();
830            editor.update(cx, |editor, cx| {
831                editor.replace_and_mark_text_in_range(Some(0..2), "22", Some(1..1), window, cx);
832            });
833            state.update(cx, |state, cx| state.close(window, cx));
834            assert!(!state.read(cx).is_open(cx));
835            assert_eq!(state.read(cx).value(), initial);
836            assert_eq!(state.read(cx).hour_input(cx).as_ref(), "15");
837        })
838        .unwrap();
839    }
840}