Skip to main content

gpui_base/
time_field.rs

1use crate::TestSupportExt as _;
2use std::rc::Rc;
3
4use gpui::{
5    AnyElement, App, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable,
6    InteractiveElement, IntoElement, KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent,
7    ParentElement, Render, RenderOnce, Role, SharedString, StatefulInteractiveElement,
8    StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
9};
10use jiff::civil::Time;
11
12use crate::{
13    Decrement, Increment, StyledExt as _,
14    a11y_disabled::A11yDisabledExt as _,
15    actions::{SelectLeft, SelectNextColumn, SelectPrevColumn, SelectRight},
16    input::Delete,
17};
18
19const CONTEXT: &str = "TimeField";
20
21pub(crate) fn init(cx: &mut App) {
22    cx.bind_keys([
23        KeyBinding::new("up", Increment, Some(CONTEXT)),
24        KeyBinding::new("down", Decrement, Some(CONTEXT)),
25        KeyBinding::new("left", SelectLeft, Some(CONTEXT)),
26        KeyBinding::new("right", SelectRight, Some(CONTEXT)),
27        KeyBinding::new("tab", SelectNextColumn, Some(CONTEXT)),
28        KeyBinding::new("shift-tab", SelectPrevColumn, Some(CONTEXT)),
29        KeyBinding::new("backspace", Delete, Some(CONTEXT)),
30        KeyBinding::new("delete", Delete, Some(CONTEXT)),
31    ]);
32}
33
34/// The smallest unit a [`TimeField`] edits.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum TimePrecision {
37    /// Hours and minutes, e.g. `09:30`.
38    #[default]
39    Minute,
40    /// Hours, minutes and seconds, e.g. `09:30:15`.
41    Second,
42}
43
44impl TimePrecision {
45    /// The `strftime` format that displays a time at this precision and cycle.
46    pub fn format(self, hour_cycle: HourCycle) -> &'static str {
47        match (self, hour_cycle) {
48            (Self::Minute, HourCycle::H23) => "%H:%M",
49            (Self::Second, HourCycle::H23) => "%H:%M:%S",
50            (Self::Minute, HourCycle::H12) => "%I:%M %p",
51            (Self::Second, HourCycle::H12) => "%I:%M:%S %p",
52        }
53    }
54
55    /// Drop the components finer than this precision.
56    pub fn truncate(self, time: Time) -> Time {
57        let second = match self {
58            Self::Minute => 0,
59            Self::Second => time.second(),
60        };
61        Time::new(time.hour(), time.minute(), second, 0).unwrap_or(time)
62    }
63}
64
65/// How a [`TimeField`] counts the hours of a day.
66///
67/// The names follow the Unicode `hourCycle` values.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
69pub enum HourCycle {
70    /// A 24-hour clock from `00` to `23`.
71    #[default]
72    H23,
73    /// A 12-hour clock from `12` to `11`, with an AM/PM segment.
74    H12,
75}
76
77/// One editable component of a [`TimeField`].
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub enum TimeSegment {
80    Hour,
81    Minute,
82    Second,
83    /// AM or PM, present with [`HourCycle::H12`].
84    Period,
85}
86
87impl TimeSegment {
88    fn name(self) -> &'static str {
89        match self {
90            Self::Hour => "hour",
91            Self::Minute => "minute",
92            Self::Second => "second",
93            Self::Period => "period",
94        }
95    }
96}
97
98/// A semantic notification from a [`TimeFieldState`].
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub enum TimeFieldEvent {
101    /// Keyboard editing changed the time.
102    Change(Time),
103}
104
105/// The pure editing rules of a [`TimeFieldState`], kept apart from focus so
106/// they can be tested without a window.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108struct SegmentEditor {
109    time: Time,
110    precision: TimePrecision,
111    hour_cycle: HourCycle,
112    segment: TimeSegment,
113    /// The first digit typed into the selected segment, awaiting a second.
114    pending_digit: Option<u32>,
115}
116
117impl SegmentEditor {
118    fn new() -> Self {
119        Self {
120            time: Time::midnight(),
121            precision: TimePrecision::default(),
122            hour_cycle: HourCycle::default(),
123            segment: TimeSegment::Hour,
124            pending_digit: None,
125        }
126    }
127
128    /// The segments shown, in reading order.
129    fn segments(&self) -> &'static [TimeSegment] {
130        use TimeSegment::*;
131        match (self.precision, self.hour_cycle) {
132            (TimePrecision::Minute, HourCycle::H23) => &[Hour, Minute],
133            (TimePrecision::Second, HourCycle::H23) => &[Hour, Minute, Second],
134            (TimePrecision::Minute, HourCycle::H12) => &[Hour, Minute, Period],
135            (TimePrecision::Second, HourCycle::H12) => &[Hour, Minute, Second, Period],
136        }
137    }
138
139    /// The inclusive range a segment's displayed value takes.
140    fn bounds(&self, segment: TimeSegment) -> (u32, u32) {
141        match (segment, self.hour_cycle) {
142            (TimeSegment::Hour, HourCycle::H23) => (0, 23),
143            (TimeSegment::Hour, HourCycle::H12) => (1, 12),
144            (TimeSegment::Minute | TimeSegment::Second, _) => (0, 59),
145            (TimeSegment::Period, _) => (0, 1),
146        }
147    }
148
149    /// The displayed value of a segment: the hour follows the cycle, and the
150    /// period is `0` for AM and `1` for PM.
151    fn value(&self, segment: TimeSegment) -> u32 {
152        let hour = self.time.hour() as u32;
153        match (segment, self.hour_cycle) {
154            (TimeSegment::Hour, HourCycle::H23) => hour,
155            (TimeSegment::Hour, HourCycle::H12) => (hour + 11) % 12 + 1,
156            (TimeSegment::Minute, _) => self.time.minute() as u32,
157            (TimeSegment::Second, _) => self.time.second() as u32,
158            (TimeSegment::Period, _) => hour / 12,
159        }
160    }
161
162    fn label(&self, segment: TimeSegment) -> SharedString {
163        match segment {
164            TimeSegment::Period if self.value(segment) == 0 => "AM".into(),
165            TimeSegment::Period => "PM".into(),
166            _ => format!("{:02}", self.value(segment)).into(),
167        }
168    }
169
170    fn with_value(&self, segment: TimeSegment, value: u32) -> Time {
171        let time = self.time;
172        let hour = time.hour() as u32;
173        let pm_offset = hour / 12 * 12;
174        let (field, value) = match (segment, self.hour_cycle) {
175            (TimeSegment::Hour, HourCycle::H23) => (TimeSegment::Hour, value),
176            // 12 AM is midnight and 12 PM is noon.
177            (TimeSegment::Hour, HourCycle::H12) => (TimeSegment::Hour, value % 12 + pm_offset),
178            (TimeSegment::Period, _) => (TimeSegment::Hour, hour % 12 + value * 12),
179            (field, _) => (field, value),
180        };
181        let Ok(value) = i8::try_from(value) else {
182            return time;
183        };
184        let with = time.with();
185        match field {
186            TimeSegment::Hour | TimeSegment::Period => with.hour(value),
187            TimeSegment::Minute => with.minute(value),
188            TimeSegment::Second => with.second(value),
189        }
190        .build()
191        .unwrap_or(time)
192    }
193
194    fn set_precision(&mut self, precision: TimePrecision) {
195        self.precision = precision;
196        self.time = precision.truncate(self.time);
197        self.reset_segment();
198    }
199
200    fn set_hour_cycle(&mut self, hour_cycle: HourCycle) {
201        self.hour_cycle = hour_cycle;
202        self.reset_segment();
203    }
204
205    fn reset_segment(&mut self) {
206        if !self.segments().contains(&self.segment) {
207            self.segment = TimeSegment::Hour;
208        }
209        self.pending_digit = None;
210    }
211
212    fn set_time(&mut self, time: Time) -> bool {
213        let time = self.precision.truncate(time);
214        if self.time == time {
215            // Keep a half-typed segment when the owner echoes the same value back.
216            return false;
217        }
218        self.time = time;
219        self.pending_digit = None;
220        true
221    }
222
223    fn select_segment(&mut self, segment: TimeSegment) -> bool {
224        if !self.segments().contains(&segment) {
225            return false;
226        }
227        self.segment = segment;
228        self.pending_digit = None;
229        true
230    }
231
232    /// Move the selected segment by `offset`; returns `false` at either end.
233    fn move_segment(&mut self, offset: isize) -> bool {
234        let segments = self.segments();
235        let ix = segments
236            .iter()
237            .position(|segment| *segment == self.segment)
238            .unwrap_or(0);
239        let Some(next) = ix
240            .checked_add_signed(offset)
241            .and_then(|ix| segments.get(ix))
242        else {
243            return false;
244        };
245        self.select_segment(*next)
246    }
247
248    /// Step the selected segment by `delta`, wrapping within the segment.
249    fn step(&mut self, delta: i32) -> bool {
250        self.pending_digit = None;
251        let (min, max) = self.bounds(self.segment);
252        let span = (max - min + 1) as i32;
253        let value = (self.value(self.segment) as i32 - min as i32 + delta).rem_euclid(span);
254        self.replace_segment(value as u32 + min)
255    }
256
257    fn input_digit(&mut self, digit: u32) -> bool {
258        if self.segment == TimeSegment::Period {
259            return false;
260        }
261        let (min, max) = self.bounds(self.segment);
262        let (value, complete) = match self.pending_digit.take() {
263            Some(first) if (min..=max).contains(&(first * 10 + digit)) => {
264                (first * 10 + digit, true)
265            }
266            // The two digits cannot form a valid value, so the new digit starts over.
267            _ => (digit, digit * 10 > max),
268        };
269        if !complete {
270            self.pending_digit = Some(digit);
271        }
272        let changed = self.replace_segment(value);
273        if complete {
274            self.move_segment(1);
275        }
276        changed
277    }
278
279    /// Type `a` or `p` into the period segment.
280    fn input_period(&mut self, pm: bool) -> bool {
281        if self.segment != TimeSegment::Period {
282            return false;
283        }
284        self.replace_segment(pm as u32)
285    }
286
287    /// Reset the selected segment to its first value: zero, or `12` / AM on a
288    /// 12-hour clock.
289    fn clear_segment(&mut self) -> bool {
290        self.pending_digit = None;
291        self.replace_segment(0)
292    }
293
294    fn replace_segment(&mut self, value: u32) -> bool {
295        let time = self.with_value(self.segment, value);
296        let changed = time != self.time;
297        self.time = time;
298        changed
299    }
300}
301
302/// Retained editing behavior for a segmented time field.
303///
304/// The field is one Tab stop. Inside it, one segment is selected at a time:
305/// Up/Down step the selected segment and wrap within it (no carry into the
306/// next unit), Left/Right and Tab/Shift-Tab move between segments, digits are
307/// typed with a two-digit buffer that advances to the next segment once no
308/// further digit could fit, `a`/`p` set the AM/PM segment, and
309/// Backspace/Delete reset the segment.
310///
311/// The owner supplies the value with [`TimeFieldState::set_time`], which does
312/// not emit; user edits emit [`TimeFieldEvent::Change`].
313pub struct TimeFieldState {
314    focus_handle: FocusHandle,
315    editor: SegmentEditor,
316}
317
318impl TimeFieldState {
319    pub fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
320        Self {
321            focus_handle: cx.focus_handle().tab_stop(true),
322            editor: SegmentEditor::new(),
323        }
324    }
325
326    /// Set the precision, default: [`TimePrecision::Minute`].
327    pub fn precision(mut self, precision: TimePrecision) -> Self {
328        self.editor.set_precision(precision);
329        self
330    }
331
332    pub fn set_precision(
333        &mut self,
334        precision: TimePrecision,
335        _: &mut Window,
336        cx: &mut Context<Self>,
337    ) {
338        if self.editor.precision != precision {
339            self.editor.set_precision(precision);
340            cx.notify();
341        }
342    }
343
344    /// Set the hour cycle, default: [`HourCycle::H23`].
345    pub fn hour_cycle(mut self, hour_cycle: HourCycle) -> Self {
346        self.editor.set_hour_cycle(hour_cycle);
347        self
348    }
349
350    pub fn set_hour_cycle(
351        &mut self,
352        hour_cycle: HourCycle,
353        _: &mut Window,
354        cx: &mut Context<Self>,
355    ) {
356        if self.editor.hour_cycle != hour_cycle {
357            self.editor.set_hour_cycle(hour_cycle);
358            cx.notify();
359        }
360    }
361
362    pub fn time(&self) -> Time {
363        self.editor.time
364    }
365
366    /// Replace the time without emitting [`TimeFieldEvent::Change`].
367    pub fn set_time(&mut self, time: Time, _: &mut Window, cx: &mut Context<Self>) {
368        if self.editor.set_time(time) {
369            cx.notify();
370        }
371    }
372
373    /// The segment that keyboard editing applies to.
374    pub fn selected_segment(&self) -> TimeSegment {
375        self.editor.segment
376    }
377
378    pub fn focus(&self, window: &mut Window, cx: &mut App) {
379        self.focus_handle.focus(window, cx);
380    }
381
382    fn edit(&mut self, cx: &mut Context<Self>, edit: impl FnOnce(&mut SegmentEditor) -> bool) {
383        if edit(&mut self.editor) {
384            cx.emit(TimeFieldEvent::Change(self.editor.time));
385        }
386        cx.notify();
387    }
388
389    fn on_increment(&mut self, _: &Increment, _: &mut Window, cx: &mut Context<Self>) {
390        self.edit(cx, |editor| editor.step(1));
391    }
392
393    fn on_decrement(&mut self, _: &Decrement, _: &mut Window, cx: &mut Context<Self>) {
394        self.edit(cx, |editor| editor.step(-1));
395    }
396
397    fn on_delete(&mut self, _: &Delete, _: &mut Window, cx: &mut Context<Self>) {
398        self.edit(cx, SegmentEditor::clear_segment);
399    }
400
401    fn on_select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
402        self.editor.move_segment(-1);
403        cx.notify();
404    }
405
406    fn on_select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
407        self.editor.move_segment(1);
408        cx.notify();
409    }
410
411    // Tab walks the segments first and leaves the field only from the last one.
412    fn on_next_column(&mut self, _: &SelectNextColumn, _: &mut Window, cx: &mut Context<Self>) {
413        if self.editor.move_segment(1) {
414            cx.notify();
415        } else {
416            cx.propagate();
417        }
418    }
419
420    fn on_prev_column(&mut self, _: &SelectPrevColumn, _: &mut Window, cx: &mut Context<Self>) {
421        if self.editor.move_segment(-1) {
422            cx.notify();
423        } else {
424            cx.propagate();
425        }
426    }
427
428    fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
429        let keystroke = &event.keystroke;
430        if keystroke.modifiers.modified() || keystroke.key.chars().count() != 1 {
431            return;
432        }
433        let Some(ch) = keystroke.key.chars().next() else {
434            return;
435        };
436        let edit: Box<dyn FnOnce(&mut SegmentEditor) -> bool> = match ch {
437            '0'..='9' => Box::new(move |editor| editor.input_digit(ch as u32 - '0' as u32)),
438            'a' | 'A' => Box::new(|editor| editor.input_period(false)),
439            'p' | 'P' => Box::new(|editor| editor.input_period(true)),
440            _ => return,
441        };
442        window.prevent_default();
443        cx.stop_propagation();
444        self.edit(cx, edit);
445    }
446
447    fn select_segment(&mut self, segment: TimeSegment, cx: &mut Context<Self>) {
448        self.editor.select_segment(segment);
449        cx.notify();
450    }
451}
452
453impl Focusable for TimeFieldState {
454    fn focus_handle(&self, _: &App) -> FocusHandle {
455        self.focus_handle.clone()
456    }
457}
458impl EventEmitter<TimeFieldEvent> for TimeFieldState {}
459impl Render for TimeFieldState {
460    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
461        Empty
462    }
463}
464
465/// State exposed to a [`TimeField`] segment slot for decoration.
466#[derive(Clone, Copy, Debug)]
467pub struct TimeFieldSegmentState {
468    segment: TimeSegment,
469    value: u32,
470    selected: bool,
471    disabled: bool,
472}
473
474impl TimeFieldSegmentState {
475    pub fn segment(&self) -> TimeSegment {
476        self.segment
477    }
478
479    /// The displayed value: the hour on the configured clock, the minute or
480    /// second, or `0` for AM and `1` for PM.
481    pub fn value(&self) -> u32 {
482        self.value
483    }
484
485    /// Whether keyboard editing applies to this segment: it is the selected
486    /// segment and the field has focus.
487    pub fn is_selected(&self) -> bool {
488        self.selected
489    }
490
491    pub fn is_disabled(&self) -> bool {
492        self.disabled
493    }
494}
495
496type SegmentRenderer =
497    Rc<dyn Fn(TimeFieldSegment, TimeFieldSegmentState, &mut Window, &mut App) -> AnyElement>;
498
499/// An unstyled, pre-wired segment passed to the [`TimeField`] segment slot.
500#[derive(IntoElement)]
501pub struct TimeFieldSegment {
502    base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
503    style: StyleRefinement,
504    children: Vec<AnyElement>,
505}
506
507impl TimeFieldSegment {
508    /// Remove the default label so a styled facade can provide custom content.
509    pub fn clear_children(mut self) -> Self {
510        self.children.clear();
511        self
512    }
513}
514
515impl ParentElement for TimeFieldSegment {
516    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
517        self.children.extend(elements);
518    }
519}
520impl Styled for TimeFieldSegment {
521    fn style(&mut self) -> &mut StyleRefinement {
522        &mut self.style
523    }
524}
525impl InteractiveElement for TimeFieldSegment {
526    fn interactivity(&mut self) -> &mut gpui::Interactivity {
527        self.base.interactivity()
528    }
529}
530impl StatefulInteractiveElement for TimeFieldSegment {}
531impl RenderOnce for TimeFieldSegment {
532    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
533        self.base.children(self.children).refine_style(&self.style)
534    }
535}
536
537/// Unstyled segmented time editor.
538///
539/// Base owns focus, the keyboard model and pointer segment selection; the
540/// presentation lays out and decorates the field with `Styled` and each
541/// segment through [`TimeField::render_segment`]. A `:` separates the numeric
542/// segments unless [`TimeField::separator`] says otherwise; the AM/PM segment
543/// follows without one.
544#[derive(IntoElement)]
545pub struct TimeField {
546    id: ElementId,
547    state: Entity<TimeFieldState>,
548    disabled: bool,
549    style: StyleRefinement,
550    segment: SegmentRenderer,
551    separator: SharedString,
552}
553
554impl TimeField {
555    pub fn new(id: impl Into<ElementId>, state: &Entity<TimeFieldState>) -> Self {
556        Self {
557            id: id.into(),
558            state: state.clone(),
559            disabled: false,
560            style: StyleRefinement::default(),
561            segment: Rc::new(|segment, _, _, _| segment.into_any_element()),
562            separator: SharedString::new_static(":"),
563        }
564    }
565
566    /// What stands between the field's segments (`:` by default), as a caller
567    /// showing a time in its own locale may need.
568    pub fn separator(mut self, separator: impl Into<SharedString>) -> Self {
569        self.separator = separator.into();
570        self
571    }
572
573    pub fn disabled(mut self, disabled: bool) -> Self {
574        self.disabled = disabled;
575        self
576    }
577
578    /// Decorate each segment. The segment already carries its label: two
579    /// digits, or `AM`/`PM`.
580    pub fn render_segment(
581        mut self,
582        render: impl Fn(TimeFieldSegment, TimeFieldSegmentState, &mut Window, &mut App) -> AnyElement
583        + 'static,
584    ) -> Self {
585        self.segment = Rc::new(render);
586        self
587    }
588}
589
590impl Styled for TimeField {
591    fn style(&mut self) -> &mut StyleRefinement {
592        &mut self.style
593    }
594}
595
596impl RenderOnce for TimeField {
597    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
598        let disabled = self.disabled;
599        let state = self.state.read(cx);
600        let focus_handle = state.focus_handle.clone();
601        let focused = focus_handle.is_focused(window);
602        let editor = state.editor;
603        let format = editor.precision.format(editor.hour_cycle);
604
605        let mut root = div()
606            .id(self.id.clone())
607            .test_support()
608            .role(Role::TimeInput)
609            .aria_value(SharedString::from(editor.time.strftime(format).to_string()))
610            .track_focus(&focus_handle.clone().tab_stop(!disabled))
611            .when(!disabled, |this| {
612                this.key_context(CONTEXT)
613                    .on_action(window.listener_for(&self.state, TimeFieldState::on_increment))
614                    .on_action(window.listener_for(&self.state, TimeFieldState::on_decrement))
615                    .on_action(window.listener_for(&self.state, TimeFieldState::on_delete))
616                    .on_action(window.listener_for(&self.state, TimeFieldState::on_select_left))
617                    .on_action(window.listener_for(&self.state, TimeFieldState::on_select_right))
618                    .on_action(window.listener_for(&self.state, TimeFieldState::on_next_column))
619                    .on_action(window.listener_for(&self.state, TimeFieldState::on_prev_column))
620                    .on_key_down(window.listener_for(&self.state, TimeFieldState::on_key_down))
621                    // A press on the field outside any segment focuses it and selects the
622                    // first segment; a press on a segment stops here and selects that one.
623                    .on_mouse_down(MouseButton::Left, {
624                        let state = self.state.clone();
625                        let focus_handle = focus_handle.clone();
626                        move |_: &MouseDownEvent, window, cx| {
627                            focus_handle.focus(window, cx);
628                            state.update(cx, |state, cx| {
629                                let first = state.editor.segments()[0];
630                                state.select_segment(first, cx);
631                            });
632                        }
633                    })
634            });
635
636        for (ix, segment) in editor.segments().iter().copied().enumerate() {
637            if ix > 0 && segment != TimeSegment::Period {
638                root = root.child(div().child(self.separator.clone()));
639            }
640            let segment_state = TimeFieldSegmentState {
641                segment,
642                value: editor.value(segment),
643                selected: focused && segment == editor.segment,
644                disabled,
645            };
646            let mut item = TimeFieldSegment {
647                base: div().id(segment.name()).test_support(),
648                style: StyleRefinement::default(),
649                children: vec![],
650            }
651            .child(editor.label(segment));
652            if !disabled {
653                let state = self.state.clone();
654                let focus_handle = focus_handle.clone();
655                item =
656                    item.on_mouse_down(MouseButton::Left, move |_: &MouseDownEvent, window, cx| {
657                        cx.stop_propagation();
658                        focus_handle.focus(window, cx);
659                        state.update(cx, |state, cx| state.select_segment(segment, cx));
660                    });
661            }
662            root = root.child((self.segment)(item, segment_state, window, cx));
663        }
664
665        root.refine_style(&self.style).a11y_disabled(disabled)
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    fn hms(h: i8, m: i8, s: i8) -> Time {
674        Time::new(h, m, s, 0).unwrap()
675    }
676
677    fn editor(precision: TimePrecision, hour_cycle: HourCycle) -> SegmentEditor {
678        let mut editor = SegmentEditor::new();
679        editor.set_precision(precision);
680        editor.set_hour_cycle(hour_cycle);
681        editor
682    }
683
684    fn type_keys(editor: &mut SegmentEditor, keys: &str) {
685        for ch in keys.chars() {
686            match ch {
687                'a' => editor.input_period(false),
688                'p' => editor.input_period(true),
689                _ => editor.input_digit(ch.to_digit(10).unwrap()),
690            };
691        }
692    }
693
694    #[test]
695    fn typing_fills_segments_and_advances() {
696        let mut editor = editor(TimePrecision::Second, HourCycle::H23);
697        type_keys(&mut editor, "093015");
698        assert_eq!(editor.time, hms(9, 30, 15));
699        // The last segment stays selected once it is complete.
700        assert_eq!(editor.segment, TimeSegment::Second);
701    }
702
703    #[test]
704    fn a_digit_that_cannot_start_two_digits_completes_the_segment() {
705        let mut editor = editor(TimePrecision::Minute, HourCycle::H23);
706        type_keys(&mut editor, "7");
707        assert_eq!(editor.time, hms(7, 0, 0));
708        assert_eq!(editor.segment, TimeSegment::Minute);
709        type_keys(&mut editor, "8");
710        assert_eq!(editor.time, hms(7, 8, 0));
711    }
712
713    #[test]
714    fn an_out_of_range_pair_restarts_from_the_second_digit() {
715        let mut editor = editor(TimePrecision::Minute, HourCycle::H23);
716        // 2 then 5 cannot form 25 hours, so 5 starts a new entry and completes it.
717        type_keys(&mut editor, "25");
718        assert_eq!(editor.time, hms(5, 0, 0));
719        assert_eq!(editor.segment, TimeSegment::Minute);
720    }
721
722    #[test]
723    fn stepping_wraps_without_carry() {
724        let mut editor = editor(TimePrecision::Minute, HourCycle::H23);
725        editor.set_time(hms(23, 59, 0));
726        editor.step(1);
727        assert_eq!(editor.time, hms(0, 59, 0));
728        editor.select_segment(TimeSegment::Minute);
729        editor.step(1);
730        assert_eq!(editor.time, hms(0, 0, 0));
731        editor.step(-1);
732        assert_eq!(editor.time, hms(0, 59, 0));
733    }
734
735    #[test]
736    fn segment_movement_stops_at_the_ends() {
737        let mut editor = editor(TimePrecision::Minute, HourCycle::H23);
738        assert!(!editor.move_segment(-1));
739        assert!(editor.move_segment(1));
740        assert!(!editor.move_segment(1));
741        assert!(!editor.select_segment(TimeSegment::Second));
742        assert!(!editor.select_segment(TimeSegment::Period));
743    }
744
745    #[test]
746    fn precision_truncates_seconds() {
747        let mut editor = editor(TimePrecision::Second, HourCycle::H23);
748        editor.set_time(hms(9, 30, 15));
749        editor.select_segment(TimeSegment::Second);
750        editor.set_precision(TimePrecision::Minute);
751        assert_eq!(editor.time, hms(9, 30, 0));
752        assert_eq!(editor.segment, TimeSegment::Hour);
753    }
754
755    #[test]
756    fn clearing_resets_only_the_selected_segment() {
757        let mut editor = editor(TimePrecision::Minute, HourCycle::H23);
758        editor.set_time(hms(9, 30, 0));
759        editor.select_segment(TimeSegment::Minute);
760        assert!(editor.clear_segment());
761        assert_eq!(editor.time, hms(9, 0, 0));
762    }
763
764    #[test]
765    fn twelve_hour_labels_map_midnight_and_noon_to_twelve() {
766        let mut editor = editor(TimePrecision::Minute, HourCycle::H12);
767        for (hour, label, period) in [
768            (0, "12", "AM"),
769            (9, "09", "AM"),
770            (12, "12", "PM"),
771            (23, "11", "PM"),
772        ] {
773            editor.set_time(hms(hour, 0, 0));
774            assert_eq!(editor.label(TimeSegment::Hour), label);
775            assert_eq!(editor.label(TimeSegment::Period), period);
776        }
777    }
778
779    #[test]
780    fn twelve_hour_typing_keeps_the_period_until_it_is_typed() {
781        let mut editor = editor(TimePrecision::Minute, HourCycle::H12);
782        // "1" may start 10–12, so it waits; "2" makes 12, which is midnight in AM.
783        type_keys(&mut editor, "12");
784        assert_eq!(editor.time, hms(0, 0, 0));
785        type_keys(&mut editor, "30p");
786        assert_eq!(editor.time, hms(12, 30, 0));
787        assert_eq!(editor.segment, TimeSegment::Period);
788        editor.select_segment(TimeSegment::Hour);
789        type_keys(&mut editor, "9");
790        assert_eq!(editor.time, hms(21, 30, 0));
791        // "00" is not an hour on a 12-hour clock.
792        editor.select_segment(TimeSegment::Hour);
793        type_keys(&mut editor, "00");
794        assert_eq!(editor.segment, TimeSegment::Hour);
795    }
796
797    #[test]
798    fn twelve_hour_stepping_wraps_within_the_period() {
799        let mut editor = editor(TimePrecision::Minute, HourCycle::H12);
800        editor.set_time(hms(11, 0, 0));
801        editor.step(1);
802        assert_eq!(editor.time, hms(0, 0, 0), "11 AM steps to 12 AM");
803        editor.select_segment(TimeSegment::Period);
804        editor.step(1);
805        assert_eq!(editor.time, hms(12, 0, 0));
806        editor.step(1);
807        assert_eq!(editor.time, hms(0, 0, 0));
808        assert!(!editor.input_digit(1), "digits do not edit the period");
809    }
810
811    #[gpui::test]
812    fn the_separator_is_a_colon_unless_set(cx: &mut gpui::TestAppContext) {
813        use gpui::AppContext as _;
814
815        let cx = cx.add_empty_window();
816        let state = cx.update(|window, cx| cx.new(|cx| TimeFieldState::new(window, cx)));
817        assert_eq!(TimeField::new("time", &state).separator.as_ref(), ":");
818        assert_eq!(
819            TimeField::new("time", &state)
820                .separator(".")
821                .separator
822                .as_ref(),
823            "."
824        );
825    }
826}