arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/time-picker/time-picker.tsx` & `.module.css`
//!
//! P4 Component #18: `time-picker`
//!
//! - A time dropdown over a fixed tick list (`minuteStep` 1/5/10/15/30 → up to 1440 options):
//!   - The trigger shows a clock glyph, the formatted value (or placeholder), and a chevron. The
//!     shown time rolls like a clock face: a later time rises from below with a `2–8px` blur
//!     sharpen, an earlier one drops from above; reduced motion crossfades.
//!   - The menu springs open on `spring.snappy` (`y -6 → 0`, `scale .97 → 1`, `fast` opacity)
//!     and exits `instant` (`y -4`, `scale .98`); Escape closes it.
//!   - ArrowDown/ArrowUp walk the highlight (wrapping), Enter/Space choose, pointer hover moves
//!     it; the selected time opens centered in the list and a highlight dot marks it.
//!   - `format` switches between `12h` ("3:15 PM") and `24h` ("15:15") display.
//!
//! Known deviations from upstream:
//! - No `aria-live` announcement region; the menu scroll centers the selection on the first
//!   frame instead of a pre-paint scroll.
//! - The web-only hidden value span and per-option DOM ids are omitted.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{
    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
    motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    canvas, deferred, div, point,
    prelude::*,
    px,
};

use super::field_message::render_field_message;

type TimeChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;

const PAD: fn(usize) -> String = |v| format!("{v:02}");

/// Formats `HH:MM` per the display convention (`12h` → "3:15 PM", `24h` → "15:15").
pub fn time_picker_display(raw: &str, format_24h: bool) -> String {
    let minutes = time_picker_to_minutes(raw);
    let hour = minutes / 60;
    let minute = minutes % 60;
    if format_24h {
        format!("{}:{}", PAD(hour), PAD(minute))
    } else {
        let shown_hour = hour % 12;
        let shown_hour = if shown_hour == 0 { 12 } else { shown_hour };
        format!(
            "{}:{} {}",
            shown_hour,
            PAD(minute),
            if hour < 12 { "AM" } else { "PM" }
        )
    }
}

/// `HH:MM` → minutes since midnight (`0` for unparseable input).
pub fn time_picker_to_minutes(value: &str) -> usize {
    let (h, m) = value.split_once(':').unwrap_or(("x", "x"));
    match (h.trim().parse::<usize>(), m.trim().parse::<usize>()) {
        (Ok(h), Ok(m)) if h < 24 && m < 60 => h * 60 + m,
        _ => 0,
    }
}

#[derive(Clone)]
struct TimePickerInternal {
    uncontrolled: SharedString,
    seen_value: Option<SharedString>,
    open: bool,
    active_index: usize,
    direction: i8,
    changed_at_secs: f64,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl TimePickerInternal {
    fn new(default_value: SharedString, cx: &mut App) -> Self {
        Self {
            uncontrolled: default_value,
            seen_value: None,
            open: false,
            active_index: 0,
            direction: 1,
            changed_at_secs: f64::NEG_INFINITY,
            trigger_bounds: Rc::new(RefCell::new(None)),
            menu_bounds: Rc::new(RefCell::new(None)),
            focus_handle: cx.focus_handle(),
        }
    }
}

fn paint_clock_glyph(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    // Circle approximated with a 20-segment polyline stroke.
    let segments = 20;
    let radius = 7.0_f32;
    let mut builder = PathBuilder::stroke(px(1.5));
    for i in 0..=segments {
        let angle = i as f32 / segments as f32 * std::f32::consts::TAU;
        let x = cx + angle.cos() * radius;
        let y = cy + angle.sin() * radius;
        let p = point(px(x), px(y));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
    let mut hands = PathBuilder::stroke(px(1.5));
    hands.move_to(point(px(cx), px(cy)));
    hands.line_to(point(px(cx), px(cy - 4.0)));
    if let Ok(path) = hands.build() {
        window.paint_path(path, color);
    }
    let mut minute_hand = PathBuilder::stroke(px(1.5));
    minute_hand.move_to(point(px(cx), px(cy)));
    minute_hand.line_to(point(px(cx + 3.0), px(cy)));
    if let Ok(path) = minute_hand.build() {
        window.paint_path(path, color);
    }
}

fn paint_chevron(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    let pts = [(-3.0_f32, -2.0_f32), (0.0, 2.0), (3.0, -2.0)];
    let mut builder = PathBuilder::stroke(px(1.75));
    for (i, (lx, ly)) in pts.iter().enumerate() {
        let p = point(px(cx + lx), px(cy + ly));
        if i == 0 {
            builder.move_to(p);
        } else {
            builder.line_to(p);
        }
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, color);
    }
}

/// Arc `TimePicker` — a time dropdown over a fixed minute-step tick list.
#[derive(IntoElement)]
pub struct TimePicker {
    id: ElementId,
    label: SharedString,
    value: Option<SharedString>,
    default_value: SharedString,
    description: Option<SharedString>,
    placeholder: SharedString,
    minute_step: usize,
    format_24h: bool,
    disabled: bool,
    width: Option<Pixels>,
    on_change: Option<TimeChangeHandler>,
}

impl TimePicker {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: None,
            default_value: "09:00".into(),
            description: None,
            placeholder: "Select a time".into(),
            minute_step: 15,
            format_24h: false,
            disabled: false,
            width: None,
            on_change: None,
        }
    }

    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
        self.default_value = value.into();
        self
    }

    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Minutes between ticks: one of `1`, `5`, `10`, `15`, `30`.
    pub fn minute_step(mut self, minute_step: usize) -> Self {
        self.minute_step = minute_step.clamp(1, 30);
        self
    }

    /// `true` renders "15:15"; `false` renders "3:15 PM" (upstream `format`).
    pub fn format_24h(mut self, format_24h: bool) -> Self {
        self.format_24h = format_24h;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
        self.width = Some(width.into());
        self
    }

    pub fn on_change(
        mut self,
        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for TimePicker {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let options: Vec<SharedString> = (0..(1440 / self.minute_step.clamp(1, 1440).max(1)))
            .map(|index| {
                let minutes = index * self.minute_step;
                SharedString::from(format!("{}:{}", PAD(minutes / 60), PAD(minutes % 60)))
            })
            .collect();

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-time-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            TimePickerInternal::new(self.default_value.clone(), cx)
        });

        // Controlled value sync + roll direction.
        if let Some(ext) = self.value.clone() {
            let seen = internal.read(cx).seen_value.clone();
            if seen.as_ref() != Some(&ext) {
                internal.update(cx, |s, _| {
                    let prev = s
                        .seen_value
                        .clone()
                        .unwrap_or_else(|| s.uncontrolled.clone());
                    s.direction = if time_picker_to_minutes(&ext) >= time_picker_to_minutes(&prev) {
                        1
                    } else {
                        -1
                    };
                    s.seen_value = Some(ext.clone());
                    s.changed_at_secs = now;
                });
            }
        }

        let is_ctrl = self.value.is_some();
        let selected = self
            .value
            .clone()
            .or_else(|| internal.read(cx).seen_value.clone())
            .unwrap_or_else(|| internal.read(cx).uncontrolled.clone());
        let snap_state = internal.read(cx).clone();
        let open = snap_state.open && !self.disabled;
        let active_index = snap_state.active_index.min(options.len().saturating_sub(1));

        // Value roll: later times rise from below, earlier ones drop from above.
        let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
        let (value_op, value_y) = if src_elapsed >= 0.24 {
            (1.0_f32, 0.0_f32)
        } else {
            window.request_animation_frame();
            let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
            let e = if reduced {
                t
            } else {
                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
            };
            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
            let y = if reduced {
                0.0
            } else {
                (snap_state.direction as f32) * 0.35 * f32::from(Typography::TEXT_SM) * (1.0 - e)
            };
            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
        };

        // Menu presence + open/close springs.
        let menu_presence = ArcPresence::new((self.id.clone(), "tp-presence"), open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.fast,
                exit_duration: motion.duration.instant,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);
        let p = menu_presence.progress.clamp(0.0, 1.0);
        let menu_y = if reduced {
            0.0
        } else {
            arc_spring(
                (self.id.clone(), "tp-y"),
                if open { 0.0 } else { -4.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        let display_fn = |raw: &str| time_picker_display(raw, self.format_24h);
        let shown = display_fn(&selected);

        // ── Choose plumbing ───────────────────────────────────────────────────────────────────
        let choose_st = internal.clone();
        let choose_ch = self.on_change.clone();
        let choose_is_ctrl = is_ctrl;
        let choose = move |next: SharedString,
                           st: &gpui_kit::Entity<TimePickerInternal>,
                           window: &mut Window,
                           cx: &mut App| {
            let now_c = motion_now(cx);
            let prev = st.read(cx).uncontrolled.clone();
            st.update(cx, |s, _| {
                if !choose_is_ctrl {
                    s.uncontrolled = next.clone();
                }
                s.seen_value = Some(next.clone());
                s.direction = if time_picker_to_minutes(&next) >= time_picker_to_minutes(&prev) {
                    1
                } else {
                    -1
                };
                s.changed_at_secs = now_c;
                s.open = false;
            });
            if let Some(handler) = &choose_ch {
                handler(&next, window, cx);
            }
            window.refresh();
        };

        // ── Trigger ───────────────────────────────────────────────────────────────────────────
        let muted_color = colors.text_muted;
        let trigger_hover = colors.surface_muted;
        let trigger = BaseButton::new(ElementId::NamedChild(
            self.id.clone().into(),
            "trigger".into(),
        ))
        .accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
        .disabled(self.disabled)
        .on_click({
            let st = internal.clone();
            let options_len = options.len();
            let selected_for_open = selected.clone();
            let disabled_flag = self.disabled;
            move |_, window, cx| {
                if disabled_flag {
                    return;
                }
                window.focus(&st.read(cx).focus_handle.clone(), cx);
                st.update(cx, |s, _| {
                    s.open = !s.open;
                    let idx = options_len
                        .checked_sub(1)
                        .and_then(|max| {
                            (0..=max).find(|i| {
                                // Index of the selected time in the tick list.
                                let minutes = time_picker_to_minutes(&selected_for_open);
                                let step = 1440_usize / options_len.max(1);
                                *i * step == minutes
                            })
                        })
                        .unwrap_or(0);
                    s.active_index = idx;
                });
                window.refresh();
            }
        })
        .w_full()
        .h(px(38.0))
        .px(px(10.0))
        .flex()
        .flex_row()
        .items_center()
        .gap(px(8.0))
        .rounded(px(10.0))
        .border_1()
        .border_color(if self.disabled {
            colors.border
        } else {
            colors.border_strong
        })
        .bg(colors.surface)
        .opacity(if self.disabled { 0.5 } else { 1.0 })
        .when(!self.disabled, |this| {
            this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
        })
        .child(
            div().w(px(16.0)).h(px(16.0)).flex_none().child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_clock_glyph(cx_pt, cy_pt, muted_color, window);
                    },
                )
                .size_full(),
            ),
        )
        .child(
            div()
                .flex_1()
                .min_w_0()
                .mt(px(value_y))
                .opacity(value_op)
                .text_size(Typography::TEXT_SM)
                .text_color(if !selected.is_empty() {
                    colors.foreground
                } else {
                    muted_color
                })
                .child(SharedString::from(if selected.is_empty() {
                    self.placeholder.to_string()
                } else {
                    shown
                })),
        )
        .child(
            div().w(px(16.0)).h(px(16.0)).flex_none().child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_chevron(cx_pt, cy_pt, muted_color, window);
                    },
                )
                .size_full(),
            ),
        );

        // ── Menu (listbox of ticks) ───────────────────────────────────────────────────────────
        let menu_open = menu_presence.should_render();
        let menu_el = if menu_open {
            let st_hover = internal.clone();
            let choose_hover = choose.clone();
            let rows: Vec<AnyElement> = options
                .iter()
                .enumerate()
                .map(|(index, option)| {
                    let is_selected = *option == selected;
                    let is_active = index == active_index;
                    let row_fg = if is_active || is_selected {
                        colors.foreground
                    } else {
                        colors.text_secondary
                    };
                    let option_for_hover = option.clone();
                    let option_for_click = option.clone();
                    let hover_st = st_hover.clone();
                    let click_st = choose_st.clone();
                    let click_choose = choose_hover.clone();
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            SharedString::from(format!("option-{index}")),
                        ))
                        .test_support()
                        .role(Role::ListBoxOption)
                        .aria_selected(is_selected)
                        .aria_label(SharedString::from(display_fn(option)))
                        .w_full()
                        .flex_none()
                        .h(px(34.0))
                        .min_h(px(34.0))
                        .px(px(10.0))
                        .flex()
                        .flex_row()
                        .items_center()
                        .justify_between()
                        .rounded(px(8.0))
                        .text_size(Typography::TEXT_SM)
                        .text_color(row_fg)
                        .bg(if is_active {
                            oklab_mix(colors.foreground, colors.surface_raised, 0.065)
                        } else {
                            Hsla::transparent_black()
                        })
                        .cursor_pointer()
                        .on_hover(move |hovered, window, cx| {
                            if *hovered {
                                hover_st.update(cx, |s, _| s.active_index = index);
                                window.refresh();
                            }
                            let _ = &option_for_hover;
                        })
                        .on_click(move |_, window, cx| {
                            click_choose(option_for_click.clone(), &click_st, window, cx);
                        })
                        .child(SharedString::from(display_fn(option)))
                        .child(
                            div()
                                .size(px(6.0))
                                .rounded_full()
                                .bg(colors.control_fill)
                                .when(!is_selected, |this| this.opacity(0.0)),
                        )
                        .into_any_element()
                })
                .collect();

            Some(
                deferred(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            "listbox".into(),
                        ))
                        .test_support()
                        .role(Role::ListBox)
                        .aria_label(SharedString::from(format!("{} options", self.label)))
                        .absolute()
                        .top_full()
                        .mt(px(6.0 + menu_y))
                        .left_0()
                        .w(px(180.0))
                        .p(px(6.0))
                        .rounded(Radii::CONTROL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(p)
                        .overflow_hidden()
                        .child(canvas(
                            {
                                let probe = snap_state.menu_bounds.clone();
                                move |rect, _, _| {
                                    *probe.borrow_mut() = Some(rect);
                                }
                            },
                            |_, _, _, _| {},
                        ))
                        .child(
                            div()
                                .id(ElementId::NamedChild(
                                    self.id.clone().into(),
                                    "option-scroll".into(),
                                ))
                                .h(px(240.0))
                                .max_h(px(240.0))
                                .overflow_y_scroll()
                                .on_scroll(|_, _, cx| cx.stop_propagation())
                                .flex()
                                .flex_col()
                                .gap(px(2.0))
                                .children(rows),
                        ),
                )
                .with_priority(25),
            )
        } else {
            None
        };

        // ── Keyboard ──────────────────────────────────────────────────────────────────────────
        let key_st = internal.clone();
        let key_choose = choose.clone();
        let key_options = options.clone();
        let key_disabled = self.disabled;

        // Outside dismissal.
        let dismiss_st = internal.clone();
        let dismiss_trigger = snap_state.trigger_bounds.clone();
        let dismiss_menu = snap_state.menu_bounds.clone();
        let dismiss_canvas = canvas(
            {
                let probe = snap_state.trigger_bounds.clone();
                move |rect, _, _| {
                    *probe.borrow_mut() = Some(rect);
                }
            },
            move |_, _, window, _| {
                let st = dismiss_st.clone();
                let trigger_ref = dismiss_trigger.clone();
                let menu_ref = dismiss_menu.clone();
                window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                    if !phase.bubble() || !st.read(cx).open {
                        return;
                    }
                    let in_trigger = trigger_ref
                        .borrow()
                        .is_some_and(|b| b.contains(&event.position));
                    let in_menu = menu_ref
                        .borrow()
                        .is_some_and(|b| b.contains(&event.position));
                    if !in_trigger && !in_menu {
                        st.update(cx, |s, _| s.open = false);
                        window.refresh();
                    }
                });
            },
        )
        .absolute()
        .inset_0();

        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .when(self.disabled, |this| this.opacity(0.5))
            .child(
                div()
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(self.label.clone()),
            )
            .child(
                div()
                    .relative()
                    .w_full()
                    .track_focus(&snap_state.focus_handle.clone())
                    .child(dismiss_canvas)
                    .on_key_down(move |event: &KeyDownEvent, window, cx| {
                        if key_disabled {
                            return;
                        }
                        let key = event.keystroke.key.as_str();
                        let st_open = key_st.read(cx).open;
                        match key {
                            "escape" if st_open => {
                                key_st.update(cx, |s, _| s.open = false);
                                window.refresh();
                            }
                            "enter" | " " | "space" => {
                                if st_open {
                                    let idx = key_st.read(cx).active_index;
                                    if let Some(option) = key_options.get(idx) {
                                        key_choose(option.clone(), &key_st, window, cx);
                                    }
                                } else {
                                    key_st.update(cx, |s, _| {
                                        s.open = true;
                                    });
                                    window.refresh();
                                }
                            }
                            "down" | "arrowdown" | "up" | "arrowup" => {
                                if !st_open {
                                    key_st.update(cx, |s, _| s.open = true);
                                    window.refresh();
                                    return;
                                }
                                let len = key_options.len().max(1);
                                let delta = if key.starts_with("down") || key == "down" {
                                    1
                                } else {
                                    -1
                                };
                                key_st.update(cx, |s, _| {
                                    s.active_index = ((s.active_index as i64 + delta)
                                        .rem_euclid(len as i64))
                                        as usize;
                                });
                                window.refresh();
                            }
                            _ => {}
                        }
                    })
                    .child(trigger)
                    .when_some(menu_el, |this, el| this.child(el)),
            )
            .child(render_field_message(
                msg_id,
                self.description,
                false,
                window,
                cx,
            ))
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn time_picker_display_formats_12h_and_24h() {
        assert_eq!(time_picker_display("15:15", false), "3:15 PM");
        assert_eq!(time_picker_display("09:00", false), "9:00 AM");
        assert_eq!(time_picker_display("00:30", false), "12:30 AM");
        assert_eq!(time_picker_display("15:15", true), "15:15");
        assert_eq!(time_picker_display("garbage", true), "00:00");
    }

    #[test]
    fn time_picker_to_minutes_parses_and_rejects() {
        assert_eq!(time_picker_to_minutes("15:15"), 915);
        assert_eq!(time_picker_to_minutes("00:00"), 0);
        assert_eq!(time_picker_to_minutes("garbage"), 0);
        assert_eq!(time_picker_to_minutes("25:00"), 0);
    }

    struct TimeHost {
        value: Option<SharedString>,
        events: Rc<RefCell<Vec<String>>>,
        disabled: bool,
    }

    impl Render for TimeHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            div().w(px(360.0)).p(px(16.0)).child(
                TimePicker::new("time-test", "Start time")
                    .minute_step(15)
                    .format_24h(true)
                    .disabled(self.disabled)
                    .when_some(self.value.clone(), |p, v| p.value(v))
                    .on_change(cx.listener({
                        let events = events.clone();
                        move |this, v: &SharedString, _, cx| {
                            events.borrow_mut().push(v.to_string());
                            this.value = Some(v.clone());
                            cx.notify();
                        }
                    })),
            )
        }
    }

    fn time_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("time-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn time_picker_opens_walks_and_picks(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = TimeHost {
            value: Some("09:00".into()),
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            // Open via the keyboard (focus lives on the field wrapper).
            window.click(time_element("trigger"), cx);
            window.render_frame(cx);
            let menu = window.find(time_element("listbox"));
            assert_eq!(menu.role(), Some(Role::ListBox));

            // ArrowDown opens (upstream behavior); the next three walk the highlight; Enter picks.
            window.press("down", cx);
            window.press("down", cx);
            window.press("down", cx);
            window.press("down", cx);
            window.press("enter", cx);
        });
        // 09:00 → 09:15 → 09:30 → 09:45 → 10:00.
        assert_eq!(events.borrow().last().map(String::as_str), Some("10:00"));

        // Disabled swallows the open.
        view.update(cx, |host, cx| {
            host.disabled = true;
            host.value = Some("09:00".into());
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(time_element("trigger"), cx);
            window.render_frame(cx);
            assert!(window.try_find(time_element("listbox")).is_none());
        });
    }

    #[gpui_kit::test]
    fn time_picker_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });

        let host = TimeHost {
            value: Some("12:00".into()),
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(time_element("trigger"), cx);
            window.render_frame(cx);
            window.press("down", cx);
            window.press("enter", cx);
        });
        // First down opens, second down walks one tick: 12:00 -> 12:15.
        assert_eq!(events.borrow().last().map(String::as_str), Some("12:15"));
    }
}