gpui-material-extras 0.3.2

Optional Material 3 Expressive component families for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
use std::rc::Rc;

use chrono::Timelike;
use gpui::{
    App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Focusable as _,
    SharedString, Window,
};
use gpui_material_components::{DialogState, TextFieldEvent, TextFieldState};

use super::{NaiveTime, ScrollFieldState};

mod dialog;
mod panel;

pub use dialog::{TimePicker, TimePickerDialog, TimePickerModeAction, VibrantTimePickerDialog};
pub use panel::{TimePickerPanel, TimePickerSelectionColors, TimePickerStyle, TimeScroll};

/// Hour display convention for a time picker.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TimeFormat {
    /// 12-hour clock (`1`–`12`) with an AM/PM period selector.
    TwelveHour,
    /// 24-hour clock (`00`–`23`) without a period selector.
    #[default]
    TwentyFourHour,
}

/// Interactive editor mode for a time picker.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TimePickerVariant {
    /// Circular clock dial with clickable and draggable hands.
    #[default]
    Dial,
    /// Direct numeric text fields for hours and minutes.
    Input,
    /// Wrapping vertical scroll wheels for hours and minutes.
    Scroll,
}

/// Orientation of the dial relative to the time header in a time picker.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TimePickerLayout {
    /// Switches to horizontal when the viewport is wide (`>= 600px`) and short (`< 650px`).
    #[default]
    Auto,
    /// Always stacks the time header above the dial.
    Vertical,
    /// Places the time header beside the dial when the viewport is at least `600px` wide.
    Horizontal,
}

type NumberFormatter = Rc<dyn Fn(u32) -> SharedString>;
type NumberParser = Rc<dyn Fn(&str) -> Option<u32>>;

/// Application locale hooks for numbers, period names, separator, and labels.
#[derive(Clone)]
pub struct TimePickerLocale {
    number: NumberFormatter,
    parse: NumberParser,
    am: SharedString,
    pm: SharedString,
    separator: SharedString,
    hour: SharedString,
    minute: SharedString,
    validation_message: SharedString,
}

impl Default for TimePickerLocale {
    fn default() -> Self {
        Self {
            number: Rc::new(|value| super::format_two_digits(value as usize)),
            parse: Rc::new(|text| text.parse().ok()),
            am: SharedString::new_static("AM"),
            pm: SharedString::new_static("PM"),
            separator: SharedString::new_static(":"),
            hour: SharedString::new_static("Hour"),
            minute: SharedString::new_static("Minute"),
            validation_message: SharedString::new_static("Enter a valid time"),
        }
    }
}

impl TimePickerLocale {
    /// Sets custom formatting and parsing functions for hour and minute numerals.
    pub fn numbers(
        mut self,
        format: impl Fn(u32) -> SharedString + 'static,
        parse: impl Fn(&str) -> Option<u32> + 'static,
    ) -> Self {
        self.number = Rc::new(format);
        self.parse = Rc::new(parse);
        self
    }

    /// Sets localized labels for the hour field, minute field, separator, and AM/PM periods.
    pub fn labels(
        mut self,
        hour: impl Into<SharedString>,
        minute: impl Into<SharedString>,
        separator: impl Into<SharedString>,
        am: impl Into<SharedString>,
        pm: impl Into<SharedString>,
    ) -> Self {
        self.hour = hour.into();
        self.minute = minute.into();
        self.separator = separator.into();
        self.am = am.into();
        self.pm = pm.into();
        self
    }

    /// Sets the error message shown when text input cannot be parsed as a valid time.
    pub fn validation_message(mut self, message: impl Into<SharedString>) -> Self {
        self.validation_message = message.into();
        self
    }
}

/// The time component currently targeted for editing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TimePickerSegment {
    /// Editing the hour component.
    #[default]
    Hour,
    /// Editing the minute component.
    Minute,
}

fn display_hour(time: NaiveTime, format: TimeFormat) -> u32 {
    if format == TimeFormat::TwelveHour {
        time.hour12().1
    } else {
        time.hour()
    }
}

fn parse_segment(
    locale: &TimePickerLocale,
    segment: TimePickerSegment,
    text: &str,
    format: TimeFormat,
    pm: bool,
) -> Option<u32> {
    let value = (locale.parse)(text.trim())?;
    match (segment, format) {
        (TimePickerSegment::Hour, TimeFormat::TwelveHour) if (1..=12).contains(&value) => {
            Some(value % 12 + u32::from(pm) * 12)
        }
        (TimePickerSegment::Hour, TimeFormat::TwentyFourHour) if value < 24 => Some(value),
        (TimePickerSegment::Minute, _) if value < 60 => Some(value),
        _ => None,
    }
}

fn format_time(time: NaiveTime, format: TimeFormat, locale: &TimePickerLocale) -> SharedString {
    let hour = (locale.number)(display_hour(time, format));
    let minute = (locale.number)(time.minute());
    let suffix = if format == TimeFormat::TwelveHour {
        format!(
            " {}",
            if time.hour() < 12 {
                &locale.am
            } else {
                &locale.pm
            }
        )
    } else {
        String::new()
    };
    format!("{hour}{}{minute}{suffix}", locale.separator).into()
}

/// Owns one editable time, its input fields, selection wheels, and dialog session.
pub struct TimePickerState {
    draft: NaiveTime,
    segment: TimePickerSegment,
    mode: TimePickerVariant,
    picker_mode: TimePickerVariant,
    format: TimeFormat,
    locale: TimePickerLocale,
    input_attempted: bool,
    mode_revision: u64,
    hour: Entity<TextFieldState>,
    minute: Entity<TextFieldState>,
    hours: Entity<ScrollFieldState>,
    minutes: Entity<ScrollFieldState>,
    dialog: Entity<DialogState>,
    trigger: FocusHandle,
    panel: FocusHandle,
    dial: FocusHandle,
}

impl TimePickerState {
    /// Creates a time picker state initialized to `00:00` in 24-hour dial mode.
    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
        let hour = cx.new(|cx| TextFieldState::new(window, cx));
        let minute = cx.new(|cx| TextFieldState::new(window, cx));
        let hours = cx.new(|cx| ScrollFieldState::new(24, 0, cx));
        let minutes = cx.new(|cx| ScrollFieldState::new(60, 0, cx));
        let dialog = cx.new(DialogState::new);
        for (segment, editor, wheel) in [
            (TimePickerSegment::Hour, &hour, &hours),
            (TimePickerSegment::Minute, &minute, &minutes),
        ] {
            cx.subscribe_in(editor, window, move |state, editor, event, window, cx| {
                if matches!(event, TextFieldEvent::Change) && !has_marked_text(editor, window, cx) {
                    let text = editor.read(cx).value();
                    state.apply_input(segment, &text, cx);
                }
            })
            .detach();
            cx.observe_in(wheel, window, move |state, wheel, window, cx| {
                let wheel = wheel.read(cx);
                if !wheel.is_scroll_in_progress()
                    && let Some(index) = wheel.selected_option()
                    && index != state.wheel_index(segment)
                {
                    let mut value = index as u32;
                    if segment == TimePickerSegment::Hour && state.format == TimeFormat::TwelveHour
                    {
                        value = (value + 1) % 12 + state.hour() / 12 * 12;
                    }
                    if !state
                        .segment_focus(state.segment, TimePickerVariant::Scroll, cx)
                        .is_focused(window)
                    {
                        state.set_segment(segment, cx);
                    }
                    state.update_draft(segment, value);
                    state.sync_field(segment, window, cx);
                    cx.notify();
                }
            })
            .detach();
            for focus in [
                editor.read(cx).focus_handle(cx),
                wheel.read(cx).focus_handle().clone(),
            ] {
                cx.on_focus(&focus, window, move |state, _, cx| {
                    state.set_segment(segment, cx)
                })
                .detach();
            }
        }
        cx.observe(&dialog, |_, _, cx| cx.notify()).detach();
        let state = Self {
            draft: NaiveTime::default(),
            segment: TimePickerSegment::Hour,
            mode: TimePickerVariant::Dial,
            picker_mode: TimePickerVariant::Dial,
            format: TimeFormat::TwentyFourHour,
            locale: TimePickerLocale::default(),
            input_attempted: false,
            mode_revision: 0,
            hour,
            minute,
            hours,
            minutes,
            dialog,
            trigger: cx.focus_handle(),
            panel: cx.focus_handle(),
            dial: cx.focus_handle(),
        };
        state.sync_fields(window, cx);
        state
    }

    /// The latest valid draft, at minute precision.
    pub fn value(&self) -> NaiveTime {
        self.draft
    }

    /// Returns the draft hour in 24-hour format (`0`–`23`).
    pub fn hour(&self) -> u32 {
        self.draft.hour()
    }

    /// Returns the draft minute (`0`–`59`).
    pub fn minute(&self) -> u32 {
        self.draft.minute()
    }

    /// Returns `true` when the draft hour is `12` or later.
    pub fn is_pm(&self) -> bool {
        self.hour() >= 12
    }

    /// Returns the currently active editing segment ([`TimePickerSegment::Hour`] or [`TimePickerSegment::Minute`]).
    pub fn segment(&self) -> TimePickerSegment {
        self.segment
    }

    /// Returns the active editor mode ([`TimePickerVariant`]).
    pub fn mode(&self) -> TimePickerVariant {
        self.mode
    }

    /// Returns the active 12-hour or 24-hour [`TimeFormat`].
    pub fn format(&self) -> TimeFormat {
        self.format
    }

    /// Returns the raw text currently in the hour input field.
    pub fn hour_input(&self, cx: &App) -> SharedString {
        self.hour.read(cx).value()
    }

    /// Returns the raw text currently in the minute input field.
    pub fn minute_input(&self, cx: &App) -> SharedString {
        self.minute.read(cx).value()
    }

    /// Replaces the text in the hour input field and updates the draft if valid.
    pub fn set_hour_input(
        &mut self,
        text: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.set_input(TimePickerSegment::Hour, text.into(), window, cx);
    }

    /// Replaces the text in the minute input field and updates the draft if valid.
    pub fn set_minute_input(
        &mut self,
        text: impl Into<SharedString>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.set_input(TimePickerSegment::Minute, text.into(), window, cx);
    }

    /// Returns whether the hour input field currently parses as a valid hour for the active format.
    pub fn is_hour_input_valid(&self, cx: &App) -> bool {
        self.valid_input(TimePickerSegment::Hour, cx)
    }

    /// Returns whether the minute input field currently parses as a valid minute (`0`–`59`).
    pub fn is_minute_input_valid(&self, cx: &App) -> bool {
        self.valid_input(TimePickerSegment::Minute, cx)
    }

    /// Returns whether both hour and minute input fields currently contain valid values.
    pub fn is_input_valid(&self, cx: &App) -> bool {
        self.invalid_segment(cx).is_none()
    }

    /// Returns whether the picker's modal dialog is currently open.
    pub fn is_open(&self, cx: &App) -> bool {
        self.dialog.read(cx).is_open()
    }

    /// Returns the retained focus handle of the built-in picker trigger.
    pub fn trigger_focus(&self) -> &FocusHandle {
        &self.trigger
    }

    /// Replaces the editable draft and cancels outstanding wheel motion.
    pub fn set_value(&mut self, value: NaiveTime, window: &mut Window, cx: &mut Context<Self>) {
        let next = NaiveTime::from_hms_opt(value.hour(), value.minute(), 0).unwrap();
        let draft_changed = self.draft != next;
        let attempted_changed = self.input_attempted;
        self.draft = next;
        self.input_attempted = false;
        let fields_changed = self.sync_fields(window, cx);
        let wheels_changed = self.sync_wheels(cx);
        if draft_changed || attempted_changed || fields_changed || wheels_changed {
            cx.notify();
        }
    }

    /// Sets a 24-hour value. Returns whether the supplied hour was valid.
    pub fn set_hour(&mut self, hour: u32, window: &mut Window, cx: &mut Context<Self>) -> bool {
        self.set_part(TimePickerSegment::Hour, hour, window, cx)
    }

    /// Sets a minute in 0–59. Returns whether the supplied minute was valid.
    pub fn set_minute(&mut self, minute: u32, window: &mut Window, cx: &mut Context<Self>) -> bool {
        self.set_part(TimePickerSegment::Minute, minute, window, cx)
    }

    /// Switches the active editing segment between hours and minutes.
    pub fn set_segment(&mut self, segment: TimePickerSegment, cx: &mut Context<Self>) {
        if segment != self.segment {
            self.segment = segment;
            cx.notify();
        }
    }

    /// Retains the active segment across mode changes. Reconciles editors with the last valid time.
    pub fn set_mode(
        &mut self,
        mode: TimePickerVariant,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if mode != self.mode && !self.has_composition(window, cx) {
            if self.mode == TimePickerVariant::Input {
                self.reconcile_input(cx);
            }
            let restore_focus = self.panel.contains_focused(window, cx);
            self.mode = mode;
            self.mode_revision = self.mode_revision.wrapping_add(1);
            if mode != TimePickerVariant::Input {
                self.picker_mode = mode;
            }
            self.input_attempted = false;
            self.sync_fields(window, cx);
            self.sync_wheels(cx);
            if restore_focus {
                self.focus_editor(window, cx);
            }
            cx.notify();
        }
    }

    /// Switches between 12-hour and 24-hour display formats and resynchronizes editors and wheels.
    pub fn set_format(&mut self, format: TimeFormat, window: &mut Window, cx: &mut Context<Self>) {
        if format != self.format {
            self.format = format;
            self.input_attempted = false;
            self.sync_fields(window, cx);
            self.sync_wheels(cx);
            cx.notify();
        }
    }

    /// Replaces the locale hooks and reformats the hour and minute input fields.
    pub fn set_locale(
        &mut self,
        locale: TimePickerLocale,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.locale = locale;
        self.input_attempted = false;
        self.sync_fields(window, cx);
        cx.notify();
    }

    /// Opens a new editing session initialized from the application's value.
    pub fn open(&mut self, value: NaiveTime, window: &mut Window, cx: &mut Context<Self>) {
        if !self.is_open(cx) {
            self.mode_revision = self.mode_revision.wrapping_add(1);
            self.set_value(value, window, cx);
            self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
            self.focus_editor(window, cx);
        }
    }

    /// Closes this session programmatically through the Material dialog.
    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.is_open(cx) {
            self.discard_composition(window, cx);
            self.sync_wheels(cx);
            self.dialog
                .update(cx, |dialog, cx| dialog.close(window, cx));
        }
    }

    fn has_composition(&self, window: &mut Window, cx: &mut App) -> bool {
        [&self.hour, &self.minute]
            .into_iter()
            .any(|field| has_marked_text(field, window, cx))
    }

    fn finish_composition(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let mut composed = false;
        for editor in [&self.hour, &self.minute] {
            composed |= editor.update(cx, |editor, cx| {
                if editor.marked_text_range(window, cx).is_none() {
                    return false;
                }
                editor.unmark_text(window, cx);
                true
            });
        }
        if composed {
            self.reconcile_input(cx);
        }
        composed
    }

    fn discard_composition(&self, window: &mut Window, cx: &mut Context<Self>) {
        if self.has_composition(window, cx) {
            self.sync_fields(window, cx);
        }
    }

    fn reconcile_input(&mut self, cx: &mut Context<Self>) {
        for segment in [TimePickerSegment::Hour, TimePickerSegment::Minute] {
            let text = self.field(segment).read(cx).value();
            if let Some(value) = self.parse_segment(segment, &text) {
                self.update_draft(segment, value);
                self.sync_wheel(segment, cx);
            }
        }
        cx.notify();
    }

    fn parse_segment(&self, segment: TimePickerSegment, text: &str) -> Option<u32> {
        parse_segment(&self.locale, segment, text, self.format, self.is_pm())
    }

    fn valid_input(&self, segment: TimePickerSegment, cx: &App) -> bool {
        self.parse_segment(segment, &self.field(segment).read(cx).value())
            .is_some()
    }

    fn invalid_segment(&self, cx: &App) -> Option<TimePickerSegment> {
        [TimePickerSegment::Hour, TimePickerSegment::Minute]
            .into_iter()
            .find(|&segment| !self.valid_input(segment, cx))
    }

    fn apply_input(&mut self, segment: TimePickerSegment, text: &str, cx: &mut Context<Self>) {
        if let Some(value) = self.parse_segment(segment, text) {
            self.update_draft(segment, value);
            self.sync_wheel(segment, cx);
        }
        cx.notify();
    }

    fn set_input(
        &mut self,
        segment: TimePickerSegment,
        text: SharedString,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.field(segment)
            .update(cx, |field, cx| field.set_value(text.clone(), window, cx));
        self.apply_input(segment, &text, cx);
    }

    fn field(&self, segment: TimePickerSegment) -> &Entity<TextFieldState> {
        match segment {
            TimePickerSegment::Hour => &self.hour,
            TimePickerSegment::Minute => &self.minute,
        }
    }

    fn wheel(&self, segment: TimePickerSegment) -> &Entity<ScrollFieldState> {
        match segment {
            TimePickerSegment::Hour => &self.hours,
            TimePickerSegment::Minute => &self.minutes,
        }
    }

    fn wheel_index(&self, segment: TimePickerSegment) -> usize {
        match segment {
            TimePickerSegment::Hour => {
                let hour = display_hour(self.draft, self.format) as usize;
                hour - usize::from(self.format == TimeFormat::TwelveHour)
            }
            TimePickerSegment::Minute => self.minute() as usize,
        }
    }

    fn sync_field(
        &self,
        segment: TimePickerSegment,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let number = match segment {
            TimePickerSegment::Hour => display_hour(self.draft, self.format),
            TimePickerSegment::Minute => self.minute(),
        };
        let text = (self.locale.number)(number);
        let field = self.field(segment);
        if field.read(cx).value() != text || has_marked_text(field, window, cx) {
            field.update(cx, |field, cx| field.set_value(text, window, cx));
            true
        } else {
            false
        }
    }

    fn sync_fields(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        self.sync_field(TimePickerSegment::Hour, window, cx)
            | self.sync_field(TimePickerSegment::Minute, window, cx)
    }

    fn sync_wheel(&self, segment: TimePickerSegment, cx: &mut Context<Self>) -> bool {
        let count = match (segment, self.format) {
            (TimePickerSegment::Hour, TimeFormat::TwelveHour) => 12,
            (TimePickerSegment::Hour, TimeFormat::TwentyFourHour) => 24,
            (TimePickerSegment::Minute, _) => 60,
        };
        let index = self.wheel_index(segment);
        self.wheel(segment).update(cx, |wheel, cx| {
            wheel.set_item_count(count, cx);
            if wheel.target_option() != Some(index) || wheel.is_scroll_in_progress() {
                wheel.scroll_to_option(index, cx);
                true
            } else {
                false
            }
        })
    }

    fn sync_wheels(&self, cx: &mut Context<Self>) -> bool {
        self.sync_wheel(TimePickerSegment::Hour, cx)
            | self.sync_wheel(TimePickerSegment::Minute, cx)
    }

    fn update_draft(&mut self, segment: TimePickerSegment, value: u32) -> bool {
        let time = match segment {
            TimePickerSegment::Hour => self.draft.with_hour(value),
            TimePickerSegment::Minute => self.draft.with_minute(value),
        };
        if let Some(time) = time {
            self.draft = time;
        }
        time.is_some()
    }

    fn set_part(
        &mut self,
        segment: TimePickerSegment,
        value: u32,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let previous = self.draft;
        if !self.update_draft(segment, value) {
            return false;
        }
        let field_changed = self.sync_field(segment, window, cx);
        let wheel_changed = self.sync_wheel(segment, cx);
        if self.draft != previous || field_changed || wheel_changed {
            cx.notify();
        }
        true
    }

    fn segment_focus(
        &self,
        segment: TimePickerSegment,
        mode: TimePickerVariant,
        cx: &App,
    ) -> FocusHandle {
        match mode {
            TimePickerVariant::Dial => self.dial.clone(),
            TimePickerVariant::Input => self.field(segment).read(cx).focus_handle(cx),
            TimePickerVariant::Scroll => self.wheel(segment).read(cx).focus_handle().clone(),
        }
    }

    fn editor_focus(&self, mode: TimePickerVariant, cx: &App) -> FocusHandle {
        self.segment_focus(self.segment, mode, cx)
    }

    fn focus_editor(&self, window: &mut Window, cx: &mut App) {
        self.editor_focus(self.mode, cx).focus(window, cx);
    }

    fn select(&mut self, value: u32, advance: bool, window: &mut Window, cx: &mut Context<Self>) {
        let segment = self.segment;
        let value = if segment == TimePickerSegment::Hour && self.format == TimeFormat::TwelveHour {
            value % 12 + self.hour() / 12 * 12
        } else {
            value
        };
        if self.set_part(segment, value, window, cx)
            && advance
            && segment == TimePickerSegment::Hour
        {
            self.set_segment(TimePickerSegment::Minute, cx);
        }
    }
}

fn has_marked_text(field: &Entity<TextFieldState>, window: &mut Window, cx: &mut App) -> bool {
    field.update(cx, |editor, cx| {
        editor.marked_text_range(window, cx).is_some()
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn local_time_parsing_handles_midnight_noon_and_boundaries() {
        let locale = TimePickerLocale::default();
        let parse_hour = |text, pm| {
            parse_segment(
                &locale,
                TimePickerSegment::Hour,
                text,
                TimeFormat::TwelveHour,
                pm,
            )
        };
        assert_eq!(parse_hour("12", false), Some(0));
        assert_eq!(parse_hour("12", true), Some(12));
        assert_eq!(parse_hour("11", true), Some(23));
        assert_eq!(parse_hour("00", false), None);
        assert_eq!(
            parse_segment(
                &locale,
                TimePickerSegment::Minute,
                "60",
                TimeFormat::TwelveHour,
                false
            ),
            None
        );
        assert_eq!(
            parse_segment(
                &locale,
                TimePickerSegment::Hour,
                "24",
                TimeFormat::TwentyFourHour,
                false
            ),
            None
        );
    }
    #[cfg(feature = "test-support")]
    #[gpui::test]
    fn time_dialog_waits_for_ime_then_confirms_the_unmarked_value(cx: &mut gpui::TestAppContext) {
        use std::cell::{Cell, RefCell};

        use gpui::{IntoElement, Render, WindowOptions, div};
        use gpui_material_components::DialogAction;
        use gpui_material_foundation::MaterialRoot;
        use gpui_material_theme::MaterialTheme;

        struct Fixture {
            state: Entity<TimePickerState>,
            change_mode: Rc<RefCell<Option<TimePickerModeAction>>>,
            confirm: Rc<RefCell<Option<DialogAction>>>,
            accepted: Rc<Cell<Option<NaiveTime>>>,
        }

        impl Render for Fixture {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                let change_mode = self.change_mode.clone();
                let confirm = self.confirm.clone();
                let accepted = self.accepted.clone();
                TimePickerDialog::new("ime-clock", "Input composition", &self.state)
                    .mode_toggle_content(move |action| {
                        change_mode.replace(Some(action));
                        div()
                    })
                    .confirm_content(move |action| {
                        confirm.replace(Some(action));
                        div()
                    })
                    .on_confirm(move |time, _, _| accepted.set(Some(time)))
            }
        }

        let mode = Rc::new(RefCell::new(None));
        let confirm = Rc::new(RefCell::new(None));
        let accepted = Rc::new(Cell::new(None));
        let mut state = None;
        let window = cx
            .update(|cx| {
                MaterialRoot::init(MaterialTheme::default(), cx);
                gpui_material_components::init_components(cx);
                cx.set_reduce_motion(true);
                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
                    let picker = cx.new(|cx| {
                        let mut picker = TimePickerState::new(window, cx);
                        picker.set_mode(TimePickerVariant::Input, window, cx);
                        picker
                    });
                    state = Some(picker.clone());
                    cx.new(|cx| {
                        cx.observe(&picker, |_, _, cx| cx.notify()).detach();
                        Fixture {
                            state: picker,
                            change_mode: mode.clone(),
                            confirm: confirm.clone(),
                            accepted: accepted.clone(),
                        }
                    })
                })
                .unwrap()
            })
            .into();
        let state = state.unwrap();
        let initial = NaiveTime::from_hms_opt(15, 25, 0).unwrap();
        cx.update_window(window, |_, window, cx| {
            state.update(cx, |state, cx| state.open(initial, window, cx));
            window.draw(cx).clear(cx);
        })
        .unwrap();
        cx.run_until_parked();
        let change_mode = mode.borrow().clone().unwrap();
        let apply = confirm.borrow().clone().unwrap();

        cx.update_window(window, |_, window, cx| {
            let editor = state.read(cx).hour.clone();
            editor.update(cx, |editor, cx| {
                editor.replace_and_mark_text_in_range(Some(0..2), "19", Some(1..1), window, cx);
            });
            change_mode.activate(window, cx);
            apply.activate(window, cx);
            let model = state.read(cx);
            assert_eq!(model.mode(), TimePickerVariant::Input);
            assert_eq!(model.value(), initial);
            assert_eq!(model.hour_input(cx).as_ref(), "19");
            assert!(model.is_open(cx));
            assert!(accepted.get().is_none());
        })
        .unwrap();

        cx.simulate_keystrokes(window, "escape");
        cx.update_window(window, |_, window, cx| {
            let model = state.read(cx);
            let editor = model.hour.clone();
            assert!(model.is_open(cx));
            assert!(accepted.get().is_none());
            editor.update(cx, |editor, cx| {
                assert!(editor.marked_text_range(window, cx).is_none());
                editor.replace_and_mark_text_in_range(Some(0..2), "21", Some(1..1), window, cx);
                editor.unmark_text(window, cx);
            });
            apply.activate(window, cx);
            assert_eq!(accepted.get(), NaiveTime::from_hms_opt(21, 25, 0));
            assert!(!state.read(cx).is_open(cx));

            state.update(cx, |state, cx| state.open(initial, window, cx));
            let editor = state.read(cx).hour.clone();
            editor.update(cx, |editor, cx| {
                editor.replace_and_mark_text_in_range(Some(0..2), "22", Some(1..1), window, cx);
            });
            state.update(cx, |state, cx| state.close(window, cx));
            assert!(!state.read(cx).is_open(cx));
            assert_eq!(state.read(cx).value(), initial);
            assert_eq!(state.read(cx).hour_input(cx).as_ref(), "15");
        })
        .unwrap();
    }
}