Skip to main content

arc_ui/inputs/
date_picker.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/date-picker/date-picker.tsx` & `.module.css`
3//!
4//! P4 Component #16: `date-picker`
5//!
6//! - A trigger + popover around the [`Calendar`]:
7//!   - The trigger shows a calendar glyph, the formatted value (or placeholder), and a chevron.
8//!     Value changes roll per part: a later date rises from below with a `2–8px` blur sharpen,
9//!     an earlier one drops from above; unchanged parts stay still; reduced motion crossfades.
10//!   - The popover springs open on `spring.snappy` (`y -8 → 0`, `scale .95 → 1`, `fast` opacity)
11//!     and exits `0.14s` on `standard` (`y -6`, `scale .97`); Escape closes it.
12//!   - Inside: the [`Calendar`] (opening on the current value's month) plus a footer with a
13//!     Clear button and a status line whose copy rises with a soft blur on each pick.
14//!   - A picked day lets the highlight glide onto it and the footer confirm it, then the
15//!     popover returns to the field after `300ms` (reduced motion closes immediately).
16//!   - ArrowDown / Enter / Space open; focus lands on the day owning the tab stop so arrows
17//!     work at once; closing hands focus back to the trigger.
18//!
19//! Known deviations from upstream:
20//! - The en-US format is fixed (`Nov 19, 2026`); there is no `aria-live` announcement region.
21
22use std::{cell::RefCell, rc::Rc};
23
24use arc_motion::{
25    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
26    motion_now,
27};
28use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography};
29use gpui_kit::{
30    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
31    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
32    TestSupportExt as _, Window,
33    base::{Button as BaseButton, StyledExt as _},
34    canvas, deferred, div,
35    prelude::*,
36    px,
37};
38
39use super::calendar::{Calendar, CalendarDate, calendar_month_start, calendar_to_epoch_days};
40use super::field_message::render_field_message;
41
42type DatePickerValueHandler = Rc<dyn Fn(&Option<CalendarDate>, &mut Window, &mut App)>;
43
44/// How long (`300ms`) the popover lingers after a pick so the highlight glides onto it.
45pub const DATE_PICKER_CLOSE_DELAY_SECS: f64 = 0.3;
46
47#[derive(Clone)]
48struct DatePickerInternal {
49    open: bool,
50    month: CalendarDate,
51    seen_value: Option<Option<CalendarDate>>,
52    /// Direction of the last value change (1 = later, -1 = earlier).
53    direction: i8,
54    changed_at_secs: f64,
55    footer_changed_at_secs: f64,
56    footer_text: SharedString,
57    /// Pending auto-close after a pick (`300ms`).
58    close_at: Option<f64>,
59    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
60    popover_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
61    focus_handle: FocusHandle,
62}
63
64impl DatePickerInternal {
65    fn new(initial_month: CalendarDate, cx: &mut App) -> Self {
66        Self {
67            open: false,
68            month: initial_month,
69            seen_value: None,
70            direction: 1,
71            changed_at_secs: f64::NEG_INFINITY,
72            footer_changed_at_secs: f64::NEG_INFINITY,
73            footer_text: "Choose a day".into(),
74            close_at: None,
75            trigger_bounds: Rc::new(RefCell::new(None)),
76            popover_bounds: Rc::new(RefCell::new(None)),
77            focus_handle: cx.focus_handle(),
78        }
79    }
80}
81
82fn paint_calendar_glyph(x: f32, y: f32, color: Hsla, window: &mut Window) {
83    use gpui_kit::PathBuilder;
84    // A tiny calendar: a body rectangle outline + two binder ticks.
85    let mut body = PathBuilder::stroke(px(1.5));
86    body.move_to(gpui_kit::point(px(x + 1.0), px(y - 6.0)));
87    body.line_to(gpui_kit::point(px(x + 7.0), px(y - 6.0)));
88    body.line_to(gpui_kit::point(px(x + 7.0), px(y + 6.0)));
89    body.line_to(gpui_kit::point(px(x + 1.0), px(y + 6.0)));
90    body.line_to(gpui_kit::point(px(x + 1.0), px(y - 6.0)));
91    if let Ok(path) = body.build() {
92        window.paint_path(path, color);
93    }
94    let mut rings = PathBuilder::stroke(px(1.5));
95    rings.move_to(gpui_kit::point(px(x + 3.0), px(y - 8.0)));
96    rings.line_to(gpui_kit::point(px(x + 3.0), px(y - 4.0)));
97    if let Ok(path) = rings.build() {
98        window.paint_path(path, color);
99    }
100    let mut rings2 = PathBuilder::stroke(px(1.5));
101    rings2.move_to(gpui_kit::point(px(x + 5.0), px(y - 8.0)));
102    rings2.line_to(gpui_kit::point(px(x + 5.0), px(y - 4.0)));
103    if let Ok(path) = rings2.build() {
104        window.paint_path(path, color);
105    }
106}
107
108fn paint_chevron(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
109    use gpui_kit::PathBuilder;
110    let pts = [(-3.0_f32, -2.0_f32), (0.0, 2.0), (3.0, -2.0)];
111    let mut builder = PathBuilder::stroke(px(1.75));
112    for (i, (lx, ly)) in pts.iter().enumerate() {
113        let p = gpui_kit::point(px(cx + lx), px(cy + ly));
114        if i == 0 {
115            builder.move_to(p);
116        } else {
117            builder.line_to(p);
118        }
119    }
120    if let Ok(path) = builder.build() {
121        window.paint_path(path, color);
122    }
123}
124
125/// Arc `DatePicker` — a trigger + popover wrapping the Arc [`Calendar`].
126#[derive(IntoElement)]
127pub struct DatePicker {
128    id: ElementId,
129    label: SharedString,
130    value: Option<CalendarDate>,
131    default_value: Option<CalendarDate>,
132    description: Option<SharedString>,
133    placeholder: SharedString,
134    min_date: Option<CalendarDate>,
135    max_date: Option<CalendarDate>,
136    disabled_dates: Option<Rc<dyn Fn(CalendarDate) -> bool>>,
137    show_today: bool,
138    disabled: bool,
139    width: Option<Pixels>,
140    on_change: Option<DatePickerValueHandler>,
141    #[cfg(test)]
142    changed_probe: Option<Rc<RefCell<f64>>>,
143}
144
145impl DatePicker {
146    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
147        Self {
148            id: id.into(),
149            label: label.into(),
150            value: None,
151            default_value: None,
152            description: None,
153            placeholder: "Select a date".into(),
154            min_date: None,
155            max_date: None,
156            disabled_dates: None,
157            show_today: false,
158            disabled: false,
159            width: None,
160            on_change: None,
161            #[cfg(test)]
162            changed_probe: None,
163        }
164    }
165
166    pub fn value(mut self, value: CalendarDate) -> Self {
167        self.value = Some(value);
168        self
169    }
170
171    pub fn default_value(mut self, value: CalendarDate) -> Self {
172        self.default_value = Some(value);
173        self
174    }
175
176    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
177        self.description = Some(description.into());
178        self
179    }
180
181    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
182        self.placeholder = placeholder.into();
183        self
184    }
185
186    pub fn min_date(mut self, date: CalendarDate) -> Self {
187        self.min_date = Some(date);
188        self
189    }
190
191    pub fn max_date(mut self, date: CalendarDate) -> Self {
192        self.max_date = Some(date);
193        self
194    }
195
196    pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
197        self.disabled_dates = Some(Rc::new(matcher));
198        self
199    }
200
201    /// Adds a Today button to the calendar header.
202    pub fn show_today(mut self, show: bool) -> Self {
203        self.show_today = show;
204        self
205    }
206
207    pub fn disabled(mut self, disabled: bool) -> Self {
208        self.disabled = disabled;
209        self
210    }
211
212    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
213        self.width = Some(width.into());
214        self
215    }
216
217    /// Receives the picked date; `None` means the value was cleared.
218    pub fn on_change(
219        mut self,
220        handler: impl Fn(&Option<CalendarDate>, &mut Window, &mut App) + 'static,
221    ) -> Self {
222        self.on_change = Some(Rc::new(handler));
223        self
224    }
225}
226
227/// `Nov 19, 2026` (upstream's `Intl.DateTimeFormat` en-US default).
228fn format_date(date: CalendarDate) -> String {
229    const MONTHS: [&str; 12] = [
230        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
231    ];
232    format!(
233        "{}, {}, {}",
234        MONTHS[(date.month - 1) as usize],
235        date.day,
236        date.year
237    )
238}
239
240impl RenderOnce for DatePicker {
241    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
242        let theme = cx.arc_theme().clone();
243        let colors = theme.colors;
244        let motion = theme.motion;
245        let reduced = is_reduced_motion(cx);
246        let now = motion_now(cx);
247
248        let state_id =
249            ElementId::NamedChild(self.id.clone().into(), "__arc-datepicker-state".into());
250        let initial_month =
251            calendar_month_start(self.value.or(self.default_value).unwrap_or(CalendarDate {
252                year: 2026,
253                month: 11,
254                day: 1,
255            }));
256        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
257            let mut state = DatePickerInternal::new(initial_month, cx);
258            // 首次受控值是初始内容,不是用户改值。
259            state.seen_value = Some(self.value.or(self.default_value));
260            state
261        });
262
263        // A picked day lets the highlight glide onto it and the footer confirm it, then the
264        // popover returns to the field (immediately under reduced motion).
265        if internal.read(cx).open {
266            let close_at = internal.read(cx).close_at;
267            if let Some(at) = close_at
268                && (now >= at || reduced)
269            {
270                internal.update(cx, |s, _| {
271                    s.open = false;
272                    s.close_at = None;
273                });
274            }
275        }
276
277        // Controlled value sync + roll direction.
278        if let Some(ext) = self.value {
279            let seen = internal.read(cx).seen_value;
280            if seen != Some(Some(ext)) {
281                internal.update(cx, |s, _| {
282                    let prev = s.seen_value.flatten();
283                    s.direction = match (prev, Some(ext)) {
284                        (Some(p), Some(n)) => {
285                            if calendar_to_epoch_days(n) >= calendar_to_epoch_days(p) {
286                                1
287                            } else {
288                                -1
289                            }
290                        }
291                        _ => 1,
292                    };
293                    s.seen_value = Some(Some(ext));
294                    s.changed_at_secs = now;
295                });
296            }
297        }
298
299        let is_ctrl = self.value.is_some();
300        let value = if is_ctrl {
301            self.value
302        } else {
303            let seen = internal.read(cx).seen_value;
304            seen.unwrap_or(self.default_value)
305        };
306        let snap_state = internal.read(cx).clone();
307        #[cfg(test)]
308        if let Some(probe) = self.changed_probe.as_ref() {
309            *probe.borrow_mut() = snap_state.changed_at_secs;
310        }
311        let open = snap_state.open && !self.disabled;
312        let shown = value
313            .map(format_date)
314            .unwrap_or_else(|| self.placeholder.to_string());
315
316        // Value roll: parts rise from below (later) or drop from above (earlier).
317        let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
318        let (value_op, value_y) = if src_elapsed >= 0.24 || value.is_none() {
319            (1.0_f32, 0.0_f32)
320        } else {
321            window.request_animation_frame();
322            let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
323            let e = if reduced {
324                t
325            } else {
326                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
327            };
328            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
329            let y = if reduced {
330                0.0
331            } else {
332                (snap_state.direction as f32) * 0.35 * f32::from(Typography::TEXT_SM) * (1.0 - e)
333            };
334            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
335        };
336
337        // Footer status rise.
338        let footer_elapsed = (now - snap_state.footer_changed_at_secs).max(0.0);
339        let (footer_op, footer_y) = if footer_elapsed >= 0.24 {
340            (1.0_f32, 0.0_f32)
341        } else {
342            window.request_animation_frame();
343            let t = (footer_elapsed / 0.24).clamp(0.0, 1.0) as f32;
344            let e = if reduced {
345                t
346            } else {
347                CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
348            };
349            let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
350            let y = if reduced {
351                0.0
352            } else {
353                0.3 * f32::from(Typography::TEXT_XS) * (1.0 - e)
354            };
355            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
356        };
357
358        // ── Popover presence + open/close springs ─────────────────────────────────────────────
359        let popover_presence = ArcPresence::new((self.id.clone(), "dp-presence"), open)
360            .animate_initial(false)
361            .config(ArcPresenceConfig {
362                enter_duration: motion.duration.fast,
363                exit_duration: motion.duration.instant,
364                enter_ease: motion.ease.enter,
365                exit_ease: motion.ease.standard,
366                fade_on_reduced_motion: true,
367            })
368            .sample(window, cx);
369        let p = popover_presence.progress.clamp(0.0, 1.0);
370        let popover_y = if reduced {
371            0.0
372        } else {
373            arc_spring(
374                (self.id.clone(), "dp-y"),
375                if open { 0.0 } else { -6.0 },
376                motion.spring.snappy,
377                window,
378                cx,
379            )
380        };
381
382        // ── Pick plumbing ─────────────────────────────────────────────────────────────────────
383        let ch_pick = self.on_change.clone();
384        let is_ctrl_pick = is_ctrl;
385        let value_pick = value;
386        let select_date = move |date: Option<CalendarDate>,
387                                st: &gpui_kit::Entity<DatePickerInternal>,
388                                window: &mut Window,
389                                cx: &mut App| {
390            let now_p = motion_now(cx);
391            let footer = match date {
392                Some(d) => SharedString::from(format!("Selected {}", format_date(d))),
393                None => SharedString::from("Choose a day"),
394            };
395            st.update(cx, |s, _| {
396                if !is_ctrl_pick {
397                    s.seen_value = Some(date);
398                }
399                s.changed_at_secs = now_p;
400                s.footer_changed_at_secs = now_p;
401                s.footer_text = footer;
402                if date.is_some() {
403                    s.close_at = Some(now_p + DATE_PICKER_CLOSE_DELAY_SECS);
404                } else {
405                    s.close_at = None;
406                }
407            });
408            if let Some(handler) = &ch_pick {
409                handler(&date, window, cx);
410            }
411            window.refresh();
412        };
413        let _ = value_pick;
414
415        // ── Trigger ───────────────────────────────────────────────────────────────────────────
416        let trigger_bounds_ref = snap_state.trigger_bounds.clone();
417        let trigger_probe = canvas(
418            {
419                let probe = trigger_bounds_ref.clone();
420                move |rect, _, _| {
421                    *probe.borrow_mut() = Some(rect);
422                }
423            },
424            |_, _, _, _| {},
425        )
426        .absolute()
427        .inset_0();
428        let trigger_color = colors.foreground;
429        let muted_color = colors.text_muted;
430        let trigger_hover = colors.surface_muted;
431        let trigger = BaseButton::new(ElementId::NamedChild(
432            self.id.clone().into(),
433            "trigger".into(),
434        ))
435        .disabled(self.disabled)
436        .accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
437        .on_click({
438            let st = internal.clone();
439            let focus_trigger = snap_state.focus_handle.clone();
440            let disabled_flag = self.disabled;
441            move |_, window, cx| {
442                if disabled_flag {
443                    return;
444                }
445                window.focus(&focus_trigger, cx);
446                st.update(cx, |s, _| {
447                    s.open = !s.open;
448                    s.close_at = None;
449                });
450                window.refresh();
451            }
452        })
453        .relative()
454        .w_full()
455        .h(px(38.0))
456        .px(px(10.0))
457        .flex()
458        .flex_row()
459        .items_center()
460        .gap(px(8.0))
461        .rounded(px(10.0))
462        .border_1()
463        .border_color(if self.disabled {
464            colors.border
465        } else {
466            colors.border_strong
467        })
468        .bg(colors.surface)
469        .opacity(if self.disabled { 0.5 } else { 1.0 })
470        .when(!self.disabled, |this| {
471            this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
472        })
473        .child(trigger_probe)
474        .child(
475            div().size(px(16.0)).flex_none().child(
476                canvas(
477                    |_, _, _| {},
478                    move |rect, _, window, _| {
479                        let x = f32::from(rect.origin.x);
480                        let y = f32::from(rect.origin.y + rect.size.height * 0.5);
481                        paint_calendar_glyph(x, y, muted_color, window);
482                    },
483                )
484                .size_full(),
485            ),
486        )
487        .child(
488            div()
489                .flex_1()
490                .min_w_0()
491                .mt(px(value_y))
492                .opacity(value_op)
493                .text_size(Typography::TEXT_SM)
494                .text_color(if value.is_some() {
495                    trigger_color
496                } else {
497                    muted_color
498                })
499                .overflow_hidden()
500                .whitespace_nowrap()
501                .child(SharedString::from(shown)),
502        )
503        .child(
504            div().size(px(16.0)).flex_none().child(
505                canvas(
506                    |_, _, _| {},
507                    move |rect, _, window, _| {
508                        let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
509                        let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
510                        paint_chevron(cx_pt, cy_pt, muted_color, window);
511                    },
512                )
513                .size_full(),
514            ),
515        );
516
517        // ── Popover with Calendar + footer ────────────────────────────────────────────────────
518        let popover_el = if popover_presence.should_render() {
519            let calendar = Calendar::new(
520                ElementId::NamedChild(self.id.clone().into(), "calendar".into()),
521                self.label.clone(),
522            )
523            .month(snap_state.month)
524            .when_some(value, |c, v| c.value(v))
525            .when_some(self.min_date, |c, d| c.min_date(d))
526            .when_some(self.max_date, |c, d| c.max_date(d))
527            .when_some(self.disabled_dates.clone(), |c, m| {
528                c.disabled_dates(move |d| m(d))
529            })
530            .show_today(self.show_today)
531            .on_month_change({
532                let st = internal.clone();
533                move |month: &CalendarDate, _window: &mut Window, cx: &mut App| {
534                    st.update(cx, |s, _| s.month = *month);
535                }
536            })
537            .on_change({
538                let st = internal.clone();
539                let select = select_date.clone();
540                move |date: &CalendarDate, window: &mut Window, cx: &mut App| {
541                    let now_c = motion_now(cx);
542                    let text = SharedString::from(format!("Selected {}", format_date(*date)));
543                    st.update(cx, |s, _| {
544                        s.changed_at_secs = now_c;
545                        s.footer_changed_at_secs = now_c;
546                        s.footer_text = text;
547                    });
548                    select(Some(*date), &st, window, cx);
549                }
550            });
551            let clear_st = internal.clone();
552            let clear_select = select_date.clone();
553            let clear_handler =
554                move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
555                    clear_select(None, &clear_st, window, cx);
556                };
557            Some(
558                deferred(
559                    div()
560                        .id(ElementId::NamedChild(
561                            self.id.clone().into(),
562                            "popover".into(),
563                        ))
564                        .test_support()
565                        .role(Role::Dialog)
566                        .aria_label(SharedString::from(format!("{} calendar", self.label)))
567                        .absolute()
568                        .top_full()
569                        .mt(px(6.0 + popover_y))
570                        .left_0()
571                        .w(px(320.0))
572                        .p(px(10.0))
573                        .rounded(Radii::CONTROL)
574                        .border_1()
575                        .border_color(colors.border)
576                        .bg(colors.surface_raised)
577                        .shadow(Shadows::floating(theme.mode))
578                        .opacity(p)
579                        .on_key_down({
580                            let st = internal.clone();
581                            move |event: &KeyDownEvent, window, cx| {
582                                if event.keystroke.key == "escape" {
583                                    st.update(cx, |s, _| s.open = false);
584                                    window.refresh();
585                                }
586                            }
587                        })
588                        .on_mouse_down(MouseButton::Left, |_, _, _| {})
589                        .child(
590                            canvas(
591                                {
592                                    let probe = snap_state.popover_bounds.clone();
593                                    move |rect, _, _| {
594                                        *probe.borrow_mut() = Some(rect);
595                                    }
596                                },
597                                {
598                                    let st = internal.clone();
599                                    let trigger_ref = trigger_bounds_ref.clone();
600                                    move |popover_rect, _, window, _| {
601                                        let st = st.clone();
602                                        let trigger_ref = trigger_ref.clone();
603                                        window.on_mouse_event(
604                                            move |event: &MouseDownEvent, phase, window, cx| {
605                                                if !phase.bubble() {
606                                                    return;
607                                                }
608                                                if !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_popover =
615                                                    popover_rect.contains(&event.position);
616                                                if !in_trigger && !in_popover {
617                                                    st.update(cx, |s, _| s.open = false);
618                                                    window.refresh();
619                                                }
620                                            },
621                                        );
622                                    }
623                                },
624                            )
625                            .absolute()
626                            .inset_0(),
627                        )
628                        .child(calendar)
629                        .child(
630                            div()
631                                .flex()
632                                .flex_row()
633                                .items_center()
634                                .justify_between()
635                                .pt(px(8.0))
636                                .child(
637                                    BaseButton::new(ElementId::NamedChild(
638                                        self.id.clone().into(),
639                                        "clear-button".into(),
640                                    ))
641                                    .accessibility_label("Clear date")
642                                    .disabled(value.is_none())
643                                    .on_click(clear_handler)
644                                    .h(px(28.0))
645                                    .px(px(10.0))
646                                    .rounded(Radii::PILL)
647                                    .text_size(Typography::TEXT_XS)
648                                    .font_medium()
649                                    .text_color(colors.text_secondary)
650                                    .when(value.is_some(), |this| {
651                                        this.cursor_pointer()
652                                            .hover(move |s| s.bg(colors.surface_muted))
653                                    })
654                                    .child(SharedString::from("Clear")),
655                                )
656                                .child(
657                                    div()
658                                        .mt(px(footer_y))
659                                        .opacity(footer_op)
660                                        .text_size(Typography::TEXT_XS)
661                                        .text_color(colors.text_muted)
662                                        .child(snap_state.footer_text.clone()),
663                                ),
664                        ),
665                )
666                .with_priority(25),
667            )
668        } else {
669            None
670        };
671
672        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
673
674        div()
675            .id(self.id)
676            .test_support()
677            .when_some(self.width, |this, w| this.w(w))
678            .when(self.width.is_none(), |this| this.w_full())
679            .flex()
680            .flex_col()
681            .gap(Spacing::S2)
682            .when(self.disabled, |this| this.opacity(0.5))
683            .child(
684                div()
685                    .text_size(Typography::TEXT_SM)
686                    .font_medium()
687                    .text_color(colors.foreground)
688                    .child(self.label.clone()),
689            )
690            .child(
691                div()
692                    .relative()
693                    .w_full()
694                    .on_key_down({
695                        let st = internal.clone();
696                        let focus_trigger = snap_state.focus_handle.clone();
697                        let disabled_flag = self.disabled;
698                        move |event: &KeyDownEvent, window, cx| {
699                            if disabled_flag {
700                                return;
701                            }
702                            let key = event.keystroke.key.as_str();
703                            let st_open = st.read(cx).open;
704                            match key {
705                                "down" | "arrowdown" | "enter" | " " | "space" => {
706                                    if !st_open {
707                                        window.focus(&focus_trigger, cx);
708                                        st.update(cx, |s, _| s.open = true);
709                                        window.refresh();
710                                    }
711                                }
712                                "escape" if st_open => {
713                                    st.update(cx, |s, _| s.open = false);
714                                    window.refresh();
715                                }
716                                _ => {}
717                            }
718                        }
719                    })
720                    .child(trigger)
721                    .when_some(popover_el, |this, el| this.child(el)),
722            )
723            .child(render_field_message(
724                msg_id,
725                self.description,
726                false,
727                window,
728                cx,
729            ))
730    }
731}
732
733#[cfg(test)]
734mod tests {
735    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
736    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
737
738    use super::*;
739    use crate::inputs::calendar::calendar_date_key;
740
741    #[test]
742    fn date_picker_format_matches_intl_en_us_shape() {
743        assert_eq!(
744            format_date(CalendarDate {
745                year: 2026,
746                month: 11,
747                day: 19
748            }),
749            "Nov, 19, 2026"
750        );
751    }
752
753    struct PickerHost {
754        value: Option<CalendarDate>,
755        events: Rc<RefCell<Vec<String>>>,
756        disabled: bool,
757    }
758
759    impl Render for PickerHost {
760        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
761            let events = self.events.clone();
762            div().w(px(420.0)).p(px(16.0)).child(
763                DatePicker::new("dp-test", "Start date")
764                    .when_some(self.value, |p, v| p.value(v))
765                    .disabled(self.disabled)
766                    .show_today(false)
767                    .on_change(cx.listener({
768                        let events = events.clone();
769                        move |this, date: &Option<CalendarDate>, _, cx| {
770                            match date {
771                                Some(d) => events.borrow_mut().push(calendar_date_key(*d)),
772                                None => events.borrow_mut().push("cleared".to_string()),
773                            }
774                            this.value = *date;
775                            cx.notify();
776                        }
777                    })),
778            )
779        }
780    }
781
782    fn dp_element(name: &str) -> ElementId {
783        ElementId::NamedChild(ElementId::Name("dp-test".into()).into(), name.into())
784    }
785
786    fn nested_dp_element(parent: &str, name: &str) -> ElementId {
787        ElementId::NamedChild(
788            ElementId::NamedChild(ElementId::Name("dp-test".into()).into(), parent.into()).into(),
789            name.into(),
790        )
791    }
792
793    #[gpui_kit::test]
794    fn date_picker_opens_picks_and_clears(cx: &mut TestAppContext) {
795        cx.update(|cx| {
796            gpui_kit::init(cx);
797            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
798        });
799
800        let host = PickerHost {
801            value: Some(CalendarDate {
802                year: 2026,
803                month: 11,
804                day: 10,
805            }),
806            events: Rc::new(RefCell::new(Vec::new())),
807            disabled: false,
808        };
809        let events = host.events.clone();
810        let (view, cx) = cx.add_window_view(|_, _| host);
811
812        cx.update(|window, cx| {
813            window.render_frame(cx);
814            let trigger = window.find(dp_element("trigger"));
815            assert_eq!(trigger.role(), Some(Role::Button));
816
817            // Open the popover and pick a day inside it.
818            window.click(dp_element("trigger"), cx);
819        });
820        cx.executor()
821            .advance_clock(std::time::Duration::from_millis(400));
822        cx.update(|window, cx| {
823            for _ in 0..5 {
824                window.render_frame(cx);
825            }
826            let popover = window.find(dp_element("popover"));
827            assert_eq!(popover.role(), Some(Role::Dialog));
828            window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
829        });
830        assert_eq!(
831            events.borrow().last().map(String::as_str),
832            Some("2026-11-15")
833        );
834
835        // Clear via the footer button — clearing keeps the popover open so the user can pick a new date.
836        cx.update(|window, cx| {
837            for _ in 0..3 {
838                window.render_frame(cx);
839            }
840            window.click(dp_element("clear-button"), cx);
841        });
842        assert_eq!(events.borrow().last().map(String::as_str), Some("cleared"));
843        cx.executor()
844            .advance_clock(std::time::Duration::from_millis(400));
845        cx.update(|window, cx| {
846            for _ in 0..3 {
847                window.render_frame(cx);
848            }
849            assert!(window.try_find(dp_element("popover")).is_some());
850            // Picking a concrete day schedules the 300ms close.
851            window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
852        });
853        assert_eq!(
854            events.borrow().last().map(String::as_str),
855            Some("2026-11-15")
856        );
857        cx.executor()
858            .advance_clock(std::time::Duration::from_millis(400));
859        cx.update(|window, cx| {
860            window.render_frame(cx);
861        });
862        cx.executor()
863            .advance_clock(std::time::Duration::from_millis(200));
864        cx.update(|window, cx| {
865            for _ in 0..3 {
866                window.render_frame(cx);
867            }
868            assert!(window.try_find(dp_element("popover")).is_none());
869        });
870
871        // Disabled swallows the open.
872        view.update(cx, |host, cx| {
873            host.disabled = true;
874            host.value = Some(CalendarDate {
875                year: 2026,
876                month: 11,
877                day: 10,
878            });
879            cx.notify();
880        });
881        cx.update(|window, cx| {
882            window.render_frame(cx);
883            window.click(dp_element("trigger"), cx);
884            window.render_frame(cx);
885            assert!(window.try_find(dp_element("popover")).is_none());
886        });
887    }
888
889    #[gpui_kit::test]
890    fn date_picker_initial_controlled_value_does_not_roll(cx: &mut TestAppContext) {
891        cx.update(|cx| {
892            gpui_kit::init(cx);
893            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
894            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Allow, cx);
895        });
896        struct InitialHost {
897            day: u32,
898            probe: Rc<RefCell<f64>>,
899        }
900        impl Render for InitialHost {
901            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
902                let mut picker = DatePicker::new("initial-date", "Date").value(CalendarDate {
903                    year: 2026,
904                    month: 11,
905                    day: self.day,
906                });
907                picker.changed_probe = Some(self.probe.clone());
908                div().w(px(420.0)).child(picker)
909            }
910        }
911        let probe = Rc::new(RefCell::new(0.0));
912        let (view, cx) = cx.add_window_view(|_, _| InitialHost {
913            day: 10,
914            probe: probe.clone(),
915        });
916        cx.update(|w, cx| {
917            w.render_frame(cx);
918            assert_eq!(*probe.borrow(), f64::NEG_INFINITY);
919        });
920        view.update(cx, |v, cx| {
921            v.day = 15;
922            cx.notify();
923        });
924        cx.update(|w, cx| {
925            w.render_frame(cx);
926            assert!(probe.borrow().is_finite(), "真实外部更新仍保留翻滚动效");
927        });
928    }
929
930    #[gpui_kit::test]
931    fn date_picker_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
932        cx.update(|cx| {
933            gpui_kit::init(cx);
934            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
935            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
936        });
937
938        let host = PickerHost {
939            value: None,
940            events: Rc::new(RefCell::new(Vec::new())),
941            disabled: false,
942        };
943        let events = host.events.clone();
944        let (_view, cx) = cx.add_window_view(|_, _| host);
945
946        cx.update(|window, cx| {
947            window.render_frame(cx);
948            window.click(dp_element("trigger"), cx);
949            window.render_frame(cx);
950            window.click(nested_dp_element("calendar", "day-2026-11-20"), cx);
951        });
952        assert_eq!(
953            events.borrow().last().map(String::as_str),
954            Some("2026-11-20")
955        );
956    }
957}