Skip to main content

arc_ui/inputs/
time_picker.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/time-picker/time-picker.tsx` & `.module.css`
3//!
4//! P4 Component #18: `time-picker`
5//!
6//! - A time dropdown over a fixed tick list (`minuteStep` 1/5/10/15/30 → up to 1440 options):
7//!   - The trigger shows a clock glyph, the formatted value (or placeholder), and a chevron. The
8//!     shown time rolls like a clock face: a later time rises from below with a `2–8px` blur
9//!     sharpen, an earlier one drops from above; reduced motion crossfades.
10//!   - The menu springs open on `spring.snappy` (`y -6 → 0`, `scale .97 → 1`, `fast` opacity)
11//!     and exits `instant` (`y -4`, `scale .98`); Escape closes it.
12//!   - ArrowDown/ArrowUp walk the highlight (wrapping), Enter/Space choose, pointer hover moves
13//!     it; the selected time opens centered in the list and a highlight dot marks it.
14//!   - `format` switches between `12h` ("3:15 PM") and `24h` ("15:15") display.
15//!
16//! Known deviations from upstream:
17//! - No `aria-live` announcement region; the menu scroll centers the selection on the first
18//!   frame instead of a pre-paint scroll.
19//! - The web-only hidden value span and per-option DOM ids are omitted.
20
21use std::{cell::RefCell, rc::Rc};
22
23use arc_motion::{
24    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
25    motion_now,
26};
27use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
28use gpui_kit::{
29    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
30    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
31    TestSupportExt as _, Window,
32    base::{Button as BaseButton, StyledExt as _},
33    canvas, deferred, div, point,
34    prelude::*,
35    px,
36};
37
38use super::field_message::render_field_message;
39
40type TimeChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
41
42const PAD: fn(usize) -> String = |v| format!("{v:02}");
43
44/// Formats `HH:MM` per the display convention (`12h` → "3:15 PM", `24h` → "15:15").
45pub fn time_picker_display(raw: &str, format_24h: bool) -> String {
46    let minutes = time_picker_to_minutes(raw);
47    let hour = minutes / 60;
48    let minute = minutes % 60;
49    if format_24h {
50        format!("{}:{}", PAD(hour), PAD(minute))
51    } else {
52        let shown_hour = hour % 12;
53        let shown_hour = if shown_hour == 0 { 12 } else { shown_hour };
54        format!(
55            "{}:{} {}",
56            shown_hour,
57            PAD(minute),
58            if hour < 12 { "AM" } else { "PM" }
59        )
60    }
61}
62
63/// `HH:MM` → minutes since midnight (`0` for unparseable input).
64pub fn time_picker_to_minutes(value: &str) -> usize {
65    let (h, m) = value.split_once(':').unwrap_or(("x", "x"));
66    match (h.trim().parse::<usize>(), m.trim().parse::<usize>()) {
67        (Ok(h), Ok(m)) if h < 24 && m < 60 => h * 60 + m,
68        _ => 0,
69    }
70}
71
72#[derive(Clone)]
73struct TimePickerInternal {
74    uncontrolled: SharedString,
75    seen_value: Option<SharedString>,
76    open: bool,
77    active_index: usize,
78    direction: i8,
79    changed_at_secs: f64,
80    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
81    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
82    focus_handle: FocusHandle,
83}
84
85impl TimePickerInternal {
86    fn new(default_value: SharedString, cx: &mut App) -> Self {
87        Self {
88            uncontrolled: default_value,
89            seen_value: None,
90            open: false,
91            active_index: 0,
92            direction: 1,
93            changed_at_secs: f64::NEG_INFINITY,
94            trigger_bounds: Rc::new(RefCell::new(None)),
95            menu_bounds: Rc::new(RefCell::new(None)),
96            focus_handle: cx.focus_handle(),
97        }
98    }
99}
100
101fn paint_clock_glyph(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
102    // Circle approximated with a 20-segment polyline stroke.
103    let segments = 20;
104    let radius = 7.0_f32;
105    let mut builder = PathBuilder::stroke(px(1.5));
106    for i in 0..=segments {
107        let angle = i as f32 / segments as f32 * std::f32::consts::TAU;
108        let x = cx + angle.cos() * radius;
109        let y = cy + angle.sin() * radius;
110        let p = point(px(x), px(y));
111        if i == 0 {
112            builder.move_to(p);
113        } else {
114            builder.line_to(p);
115        }
116    }
117    if let Ok(path) = builder.build() {
118        window.paint_path(path, color);
119    }
120    let mut hands = PathBuilder::stroke(px(1.5));
121    hands.move_to(point(px(cx), px(cy)));
122    hands.line_to(point(px(cx), px(cy - 4.0)));
123    if let Ok(path) = hands.build() {
124        window.paint_path(path, color);
125    }
126    let mut minute_hand = PathBuilder::stroke(px(1.5));
127    minute_hand.move_to(point(px(cx), px(cy)));
128    minute_hand.line_to(point(px(cx + 3.0), px(cy)));
129    if let Ok(path) = minute_hand.build() {
130        window.paint_path(path, color);
131    }
132}
133
134fn paint_chevron(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
135    let pts = [(-3.0_f32, -2.0_f32), (0.0, 2.0), (3.0, -2.0)];
136    let mut builder = PathBuilder::stroke(px(1.75));
137    for (i, (lx, ly)) in pts.iter().enumerate() {
138        let p = point(px(cx + lx), px(cy + ly));
139        if i == 0 {
140            builder.move_to(p);
141        } else {
142            builder.line_to(p);
143        }
144    }
145    if let Ok(path) = builder.build() {
146        window.paint_path(path, color);
147    }
148}
149
150/// Arc `TimePicker` — a time dropdown over a fixed minute-step tick list.
151#[derive(IntoElement)]
152pub struct TimePicker {
153    id: ElementId,
154    label: SharedString,
155    value: Option<SharedString>,
156    default_value: SharedString,
157    description: Option<SharedString>,
158    placeholder: SharedString,
159    minute_step: usize,
160    format_24h: bool,
161    disabled: bool,
162    width: Option<Pixels>,
163    on_change: Option<TimeChangeHandler>,
164}
165
166impl TimePicker {
167    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
168        Self {
169            id: id.into(),
170            label: label.into(),
171            value: None,
172            default_value: "09:00".into(),
173            description: None,
174            placeholder: "Select a time".into(),
175            minute_step: 15,
176            format_24h: false,
177            disabled: false,
178            width: None,
179            on_change: None,
180        }
181    }
182
183    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
184        self.value = Some(value.into());
185        self
186    }
187
188    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
189        self.default_value = value.into();
190        self
191    }
192
193    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
194        self.description = Some(description.into());
195        self
196    }
197
198    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
199        self.placeholder = placeholder.into();
200        self
201    }
202
203    /// Minutes between ticks: one of `1`, `5`, `10`, `15`, `30`.
204    pub fn minute_step(mut self, minute_step: usize) -> Self {
205        self.minute_step = minute_step.clamp(1, 30);
206        self
207    }
208
209    /// `true` renders "15:15"; `false` renders "3:15 PM" (upstream `format`).
210    pub fn format_24h(mut self, format_24h: bool) -> Self {
211        self.format_24h = format_24h;
212        self
213    }
214
215    pub fn disabled(mut self, disabled: bool) -> Self {
216        self.disabled = disabled;
217        self
218    }
219
220    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
221        self.width = Some(width.into());
222        self
223    }
224
225    pub fn on_change(
226        mut self,
227        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
228    ) -> Self {
229        self.on_change = Some(Rc::new(handler));
230        self
231    }
232}
233
234impl RenderOnce for TimePicker {
235    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
236        let theme = cx.arc_theme().clone();
237        let colors = theme.colors;
238        let motion = theme.motion;
239        let reduced = is_reduced_motion(cx);
240        let now = motion_now(cx);
241
242        let options: Vec<SharedString> = (0..(1440 / self.minute_step.clamp(1, 1440).max(1)))
243            .map(|index| {
244                let minutes = index * self.minute_step;
245                SharedString::from(format!("{}:{}", PAD(minutes / 60), PAD(minutes % 60)))
246            })
247            .collect();
248
249        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-time-state".into());
250        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
251            TimePickerInternal::new(self.default_value.clone(), cx)
252        });
253
254        // Controlled value sync + roll direction.
255        if let Some(ext) = self.value.clone() {
256            let seen = internal.read(cx).seen_value.clone();
257            if seen.as_ref() != Some(&ext) {
258                internal.update(cx, |s, _| {
259                    let prev = s
260                        .seen_value
261                        .clone()
262                        .unwrap_or_else(|| s.uncontrolled.clone());
263                    s.direction = if time_picker_to_minutes(&ext) >= time_picker_to_minutes(&prev) {
264                        1
265                    } else {
266                        -1
267                    };
268                    s.seen_value = Some(ext.clone());
269                    s.changed_at_secs = now;
270                });
271            }
272        }
273
274        let is_ctrl = self.value.is_some();
275        let selected = self
276            .value
277            .clone()
278            .or_else(|| internal.read(cx).seen_value.clone())
279            .unwrap_or_else(|| internal.read(cx).uncontrolled.clone());
280        let snap_state = internal.read(cx).clone();
281        let open = snap_state.open && !self.disabled;
282        let active_index = snap_state.active_index.min(options.len().saturating_sub(1));
283
284        // Value roll: later times rise from below, earlier ones drop from above.
285        let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
286        let (value_op, value_y) = if src_elapsed >= 0.24 {
287            (1.0_f32, 0.0_f32)
288        } else {
289            window.request_animation_frame();
290            let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
291            let e = if reduced {
292                t
293            } else {
294                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
295            };
296            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
297            let y = if reduced {
298                0.0
299            } else {
300                (snap_state.direction as f32) * 0.35 * f32::from(Typography::TEXT_SM) * (1.0 - e)
301            };
302            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
303        };
304
305        // Menu presence + open/close springs.
306        let menu_presence = ArcPresence::new((self.id.clone(), "tp-presence"), open)
307            .animate_initial(false)
308            .config(ArcPresenceConfig {
309                enter_duration: motion.duration.fast,
310                exit_duration: motion.duration.instant,
311                enter_ease: motion.ease.enter,
312                exit_ease: motion.ease.standard,
313                fade_on_reduced_motion: true,
314            })
315            .sample(window, cx);
316        let p = menu_presence.progress.clamp(0.0, 1.0);
317        let menu_y = if reduced {
318            0.0
319        } else {
320            arc_spring(
321                (self.id.clone(), "tp-y"),
322                if open { 0.0 } else { -4.0 },
323                motion.spring.snappy,
324                window,
325                cx,
326            )
327        };
328
329        let display_fn = |raw: &str| time_picker_display(raw, self.format_24h);
330        let shown = display_fn(&selected);
331
332        // ── Choose plumbing ───────────────────────────────────────────────────────────────────
333        let choose_st = internal.clone();
334        let choose_ch = self.on_change.clone();
335        let choose_is_ctrl = is_ctrl;
336        let choose = move |next: SharedString,
337                           st: &gpui_kit::Entity<TimePickerInternal>,
338                           window: &mut Window,
339                           cx: &mut App| {
340            let now_c = motion_now(cx);
341            let prev = st.read(cx).uncontrolled.clone();
342            st.update(cx, |s, _| {
343                if !choose_is_ctrl {
344                    s.uncontrolled = next.clone();
345                }
346                s.seen_value = Some(next.clone());
347                s.direction = if time_picker_to_minutes(&next) >= time_picker_to_minutes(&prev) {
348                    1
349                } else {
350                    -1
351                };
352                s.changed_at_secs = now_c;
353                s.open = false;
354            });
355            if let Some(handler) = &choose_ch {
356                handler(&next, window, cx);
357            }
358            window.refresh();
359        };
360
361        // ── Trigger ───────────────────────────────────────────────────────────────────────────
362        let muted_color = colors.text_muted;
363        let trigger_hover = colors.surface_muted;
364        let trigger = BaseButton::new(ElementId::NamedChild(
365            self.id.clone().into(),
366            "trigger".into(),
367        ))
368        .accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
369        .disabled(self.disabled)
370        .on_click({
371            let st = internal.clone();
372            let options_len = options.len();
373            let selected_for_open = selected.clone();
374            let disabled_flag = self.disabled;
375            move |_, window, cx| {
376                if disabled_flag {
377                    return;
378                }
379                window.focus(&st.read(cx).focus_handle.clone(), cx);
380                st.update(cx, |s, _| {
381                    s.open = !s.open;
382                    let idx = options_len
383                        .checked_sub(1)
384                        .and_then(|max| {
385                            (0..=max).find(|i| {
386                                // Index of the selected time in the tick list.
387                                let minutes = time_picker_to_minutes(&selected_for_open);
388                                let step = 1440_usize / options_len.max(1);
389                                *i * step == minutes
390                            })
391                        })
392                        .unwrap_or(0);
393                    s.active_index = idx;
394                });
395                window.refresh();
396            }
397        })
398        .w_full()
399        .h(px(38.0))
400        .px(px(10.0))
401        .flex()
402        .flex_row()
403        .items_center()
404        .gap(px(8.0))
405        .rounded(px(10.0))
406        .border_1()
407        .border_color(if self.disabled {
408            colors.border
409        } else {
410            colors.border_strong
411        })
412        .bg(colors.surface)
413        .opacity(if self.disabled { 0.5 } else { 1.0 })
414        .when(!self.disabled, |this| {
415            this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
416        })
417        .child(
418            div().w(px(16.0)).h(px(16.0)).flex_none().child(
419                canvas(
420                    |_, _, _| {},
421                    move |rect, _, window, _| {
422                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
423                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
424                        paint_clock_glyph(cx_pt, cy_pt, muted_color, window);
425                    },
426                )
427                .size_full(),
428            ),
429        )
430        .child(
431            div()
432                .flex_1()
433                .min_w_0()
434                .mt(px(value_y))
435                .opacity(value_op)
436                .text_size(Typography::TEXT_SM)
437                .text_color(if !selected.is_empty() {
438                    colors.foreground
439                } else {
440                    muted_color
441                })
442                .child(SharedString::from(if selected.is_empty() {
443                    self.placeholder.to_string()
444                } else {
445                    shown
446                })),
447        )
448        .child(
449            div().w(px(16.0)).h(px(16.0)).flex_none().child(
450                canvas(
451                    |_, _, _| {},
452                    move |rect, _, window, _| {
453                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
454                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
455                        paint_chevron(cx_pt, cy_pt, muted_color, window);
456                    },
457                )
458                .size_full(),
459            ),
460        );
461
462        // ── Menu (listbox of ticks) ───────────────────────────────────────────────────────────
463        let menu_open = menu_presence.should_render();
464        let menu_el = if menu_open {
465            let st_hover = internal.clone();
466            let choose_hover = choose.clone();
467            let rows: Vec<AnyElement> = options
468                .iter()
469                .enumerate()
470                .map(|(index, option)| {
471                    let is_selected = *option == selected;
472                    let is_active = index == active_index;
473                    let row_fg = if is_active || is_selected {
474                        colors.foreground
475                    } else {
476                        colors.text_secondary
477                    };
478                    let option_for_hover = option.clone();
479                    let option_for_click = option.clone();
480                    let hover_st = st_hover.clone();
481                    let click_st = choose_st.clone();
482                    let click_choose = choose_hover.clone();
483                    div()
484                        .id(ElementId::NamedChild(
485                            self.id.clone().into(),
486                            SharedString::from(format!("option-{index}")),
487                        ))
488                        .test_support()
489                        .role(Role::ListBoxOption)
490                        .aria_selected(is_selected)
491                        .aria_label(SharedString::from(display_fn(option)))
492                        .w_full()
493                        .flex_none()
494                        .h(px(34.0))
495                        .min_h(px(34.0))
496                        .px(px(10.0))
497                        .flex()
498                        .flex_row()
499                        .items_center()
500                        .justify_between()
501                        .rounded(px(8.0))
502                        .text_size(Typography::TEXT_SM)
503                        .text_color(row_fg)
504                        .bg(if is_active {
505                            oklab_mix(colors.foreground, colors.surface_raised, 0.065)
506                        } else {
507                            Hsla::transparent_black()
508                        })
509                        .cursor_pointer()
510                        .on_hover(move |hovered, window, cx| {
511                            if *hovered {
512                                hover_st.update(cx, |s, _| s.active_index = index);
513                                window.refresh();
514                            }
515                            let _ = &option_for_hover;
516                        })
517                        .on_click(move |_, window, cx| {
518                            click_choose(option_for_click.clone(), &click_st, window, cx);
519                        })
520                        .child(SharedString::from(display_fn(option)))
521                        .child(
522                            div()
523                                .size(px(6.0))
524                                .rounded_full()
525                                .bg(colors.control_fill)
526                                .when(!is_selected, |this| this.opacity(0.0)),
527                        )
528                        .into_any_element()
529                })
530                .collect();
531
532            Some(
533                deferred(
534                    div()
535                        .id(ElementId::NamedChild(
536                            self.id.clone().into(),
537                            "listbox".into(),
538                        ))
539                        .test_support()
540                        .role(Role::ListBox)
541                        .aria_label(SharedString::from(format!("{} options", self.label)))
542                        .absolute()
543                        .top_full()
544                        .mt(px(6.0 + menu_y))
545                        .left_0()
546                        .w(px(180.0))
547                        .p(px(6.0))
548                        .rounded(Radii::CONTROL)
549                        .border_1()
550                        .border_color(colors.border)
551                        .bg(colors.surface_raised)
552                        .shadow(Shadows::floating(theme.mode))
553                        .opacity(p)
554                        .overflow_hidden()
555                        .child(canvas(
556                            {
557                                let probe = snap_state.menu_bounds.clone();
558                                move |rect, _, _| {
559                                    *probe.borrow_mut() = Some(rect);
560                                }
561                            },
562                            |_, _, _, _| {},
563                        ))
564                        .child(
565                            div()
566                                .id(ElementId::NamedChild(
567                                    self.id.clone().into(),
568                                    "option-scroll".into(),
569                                ))
570                                .h(px(240.0))
571                                .max_h(px(240.0))
572                                .overflow_y_scroll()
573                                .on_scroll(|_, _, cx| cx.stop_propagation())
574                                .flex()
575                                .flex_col()
576                                .gap(px(2.0))
577                                .children(rows),
578                        ),
579                )
580                .with_priority(25),
581            )
582        } else {
583            None
584        };
585
586        // ── Keyboard ──────────────────────────────────────────────────────────────────────────
587        let key_st = internal.clone();
588        let key_choose = choose.clone();
589        let key_options = options.clone();
590        let key_disabled = self.disabled;
591
592        // Outside dismissal.
593        let dismiss_st = internal.clone();
594        let dismiss_trigger = snap_state.trigger_bounds.clone();
595        let dismiss_menu = snap_state.menu_bounds.clone();
596        let dismiss_canvas = canvas(
597            {
598                let probe = snap_state.trigger_bounds.clone();
599                move |rect, _, _| {
600                    *probe.borrow_mut() = Some(rect);
601                }
602            },
603            move |_, _, window, _| {
604                let st = dismiss_st.clone();
605                let trigger_ref = dismiss_trigger.clone();
606                let menu_ref = dismiss_menu.clone();
607                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
608                    if !phase.bubble() || !st.read(cx).open {
609                        return;
610                    }
611                    let in_trigger = trigger_ref
612                        .borrow()
613                        .is_some_and(|b| b.contains(&event.position));
614                    let in_menu = menu_ref
615                        .borrow()
616                        .is_some_and(|b| b.contains(&event.position));
617                    if !in_trigger && !in_menu {
618                        st.update(cx, |s, _| s.open = false);
619                        window.refresh();
620                    }
621                });
622            },
623        )
624        .absolute()
625        .inset_0();
626
627        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
628
629        div()
630            .id(self.id)
631            .test_support()
632            .when_some(self.width, |this, w| this.w(w))
633            .when(self.width.is_none(), |this| this.w_full())
634            .flex()
635            .flex_col()
636            .gap(Spacing::S2)
637            .when(self.disabled, |this| this.opacity(0.5))
638            .child(
639                div()
640                    .text_size(Typography::TEXT_SM)
641                    .font_medium()
642                    .text_color(colors.foreground)
643                    .child(self.label.clone()),
644            )
645            .child(
646                div()
647                    .relative()
648                    .w_full()
649                    .track_focus(&snap_state.focus_handle.clone())
650                    .child(dismiss_canvas)
651                    .on_key_down(move |event: &KeyDownEvent, window, cx| {
652                        if key_disabled {
653                            return;
654                        }
655                        let key = event.keystroke.key.as_str();
656                        let st_open = key_st.read(cx).open;
657                        match key {
658                            "escape" if st_open => {
659                                key_st.update(cx, |s, _| s.open = false);
660                                window.refresh();
661                            }
662                            "enter" | " " | "space" => {
663                                if st_open {
664                                    let idx = key_st.read(cx).active_index;
665                                    if let Some(option) = key_options.get(idx) {
666                                        key_choose(option.clone(), &key_st, window, cx);
667                                    }
668                                } else {
669                                    key_st.update(cx, |s, _| {
670                                        s.open = true;
671                                    });
672                                    window.refresh();
673                                }
674                            }
675                            "down" | "arrowdown" | "up" | "arrowup" => {
676                                if !st_open {
677                                    key_st.update(cx, |s, _| s.open = true);
678                                    window.refresh();
679                                    return;
680                                }
681                                let len = key_options.len().max(1);
682                                let delta = if key.starts_with("down") || key == "down" {
683                                    1
684                                } else {
685                                    -1
686                                };
687                                key_st.update(cx, |s, _| {
688                                    s.active_index = ((s.active_index as i64 + delta)
689                                        .rem_euclid(len as i64))
690                                        as usize;
691                                });
692                                window.refresh();
693                            }
694                            _ => {}
695                        }
696                    })
697                    .child(trigger)
698                    .when_some(menu_el, |this, el| this.child(el)),
699            )
700            .child(render_field_message(
701                msg_id,
702                self.description,
703                false,
704                window,
705                cx,
706            ))
707    }
708}
709
710#[cfg(test)]
711mod tests {
712    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
713    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
714
715    use super::*;
716
717    #[test]
718    fn time_picker_display_formats_12h_and_24h() {
719        assert_eq!(time_picker_display("15:15", false), "3:15 PM");
720        assert_eq!(time_picker_display("09:00", false), "9:00 AM");
721        assert_eq!(time_picker_display("00:30", false), "12:30 AM");
722        assert_eq!(time_picker_display("15:15", true), "15:15");
723        assert_eq!(time_picker_display("garbage", true), "00:00");
724    }
725
726    #[test]
727    fn time_picker_to_minutes_parses_and_rejects() {
728        assert_eq!(time_picker_to_minutes("15:15"), 915);
729        assert_eq!(time_picker_to_minutes("00:00"), 0);
730        assert_eq!(time_picker_to_minutes("garbage"), 0);
731        assert_eq!(time_picker_to_minutes("25:00"), 0);
732    }
733
734    struct TimeHost {
735        value: Option<SharedString>,
736        events: Rc<RefCell<Vec<String>>>,
737        disabled: bool,
738    }
739
740    impl Render for TimeHost {
741        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
742            let events = self.events.clone();
743            div().w(px(360.0)).p(px(16.0)).child(
744                TimePicker::new("time-test", "Start time")
745                    .minute_step(15)
746                    .format_24h(true)
747                    .disabled(self.disabled)
748                    .when_some(self.value.clone(), |p, v| p.value(v))
749                    .on_change(cx.listener({
750                        let events = events.clone();
751                        move |this, v: &SharedString, _, cx| {
752                            events.borrow_mut().push(v.to_string());
753                            this.value = Some(v.clone());
754                            cx.notify();
755                        }
756                    })),
757            )
758        }
759    }
760
761    fn time_element(name: &str) -> ElementId {
762        ElementId::NamedChild(ElementId::Name("time-test".into()).into(), name.into())
763    }
764
765    #[gpui_kit::test]
766    fn time_picker_opens_walks_and_picks(cx: &mut TestAppContext) {
767        cx.update(|cx| {
768            gpui_kit::init(cx);
769            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
770        });
771
772        let host = TimeHost {
773            value: Some("09:00".into()),
774            events: Rc::new(RefCell::new(Vec::new())),
775            disabled: false,
776        };
777        let events = host.events.clone();
778        let (view, cx) = cx.add_window_view(|_, _| host);
779
780        cx.update(|window, cx| {
781            window.render_frame(cx);
782            // Open via the keyboard (focus lives on the field wrapper).
783            window.click(time_element("trigger"), cx);
784            window.render_frame(cx);
785            let menu = window.find(time_element("listbox"));
786            assert_eq!(menu.role(), Some(Role::ListBox));
787
788            // ArrowDown opens (upstream behavior); the next three walk the highlight; Enter picks.
789            window.press("down", cx);
790            window.press("down", cx);
791            window.press("down", cx);
792            window.press("down", cx);
793            window.press("enter", cx);
794        });
795        // 09:00 → 09:15 → 09:30 → 09:45 → 10:00.
796        assert_eq!(events.borrow().last().map(String::as_str), Some("10:00"));
797
798        // Disabled swallows the open.
799        view.update(cx, |host, cx| {
800            host.disabled = true;
801            host.value = Some("09:00".into());
802            cx.notify();
803        });
804        cx.update(|window, cx| {
805            window.render_frame(cx);
806            window.click(time_element("trigger"), cx);
807            window.render_frame(cx);
808            assert!(window.try_find(time_element("listbox")).is_none());
809        });
810    }
811
812    #[gpui_kit::test]
813    fn time_picker_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
814        cx.update(|cx| {
815            gpui_kit::init(cx);
816            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
817            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
818        });
819
820        let host = TimeHost {
821            value: Some("12:00".into()),
822            events: Rc::new(RefCell::new(Vec::new())),
823            disabled: false,
824        };
825        let events = host.events.clone();
826        let (_view, cx) = cx.add_window_view(|_, _| host);
827
828        cx.update(|window, cx| {
829            window.render_frame(cx);
830            window.click(time_element("trigger"), cx);
831            window.render_frame(cx);
832            window.press("down", cx);
833            window.press("enter", cx);
834        });
835        // First down opens, second down walks one tick: 12:00 -> 12:15.
836        assert_eq!(events.borrow().last().map(String::as_str), Some("12:15"));
837    }
838}