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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/date-picker/date-picker.tsx` & `.module.css`
//!
//! P4 Component #16: `date-picker`
//!
//! - A trigger + popover around the [`Calendar`]:
//!   - The trigger shows a calendar glyph, the formatted value (or placeholder), and a chevron.
//!     Value changes roll per part: a later date rises from below with a `2–8px` blur sharpen,
//!     an earlier one drops from above; unchanged parts stay still; reduced motion crossfades.
//!   - The popover springs open on `spring.snappy` (`y -8 → 0`, `scale .95 → 1`, `fast` opacity)
//!     and exits `0.14s` on `standard` (`y -6`, `scale .97`); Escape closes it.
//!   - Inside: the [`Calendar`] (opening on the current value's month) plus a footer with a
//!     Clear button and a status line whose copy rises with a soft blur on each pick.
//!   - A picked day lets the highlight glide onto it and the footer confirm it, then the
//!     popover returns to the field after `300ms` (reduced motion closes immediately).
//!   - ArrowDown / Enter / Space open; focus lands on the day owning the tab stop so arrows
//!     work at once; closing hands focus back to the trigger.
//!
//! Known deviations from upstream:
//! - The en-US format is fixed (`Nov 19, 2026`); there is no `aria-live` announcement region.

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};
use gpui_kit::{
    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window,
    base::{Button as BaseButton, StyledExt as _},
    canvas, deferred, div,
    prelude::*,
    px,
};

use super::calendar::{Calendar, CalendarDate, calendar_month_start, calendar_to_epoch_days};
use super::field_message::render_field_message;

type DatePickerValueHandler = Rc<dyn Fn(&Option<CalendarDate>, &mut Window, &mut App)>;

/// How long (`300ms`) the popover lingers after a pick so the highlight glides onto it.
pub const DATE_PICKER_CLOSE_DELAY_SECS: f64 = 0.3;

#[derive(Clone)]
struct DatePickerInternal {
    open: bool,
    month: CalendarDate,
    seen_value: Option<Option<CalendarDate>>,
    /// Direction of the last value change (1 = later, -1 = earlier).
    direction: i8,
    changed_at_secs: f64,
    footer_changed_at_secs: f64,
    footer_text: SharedString,
    /// Pending auto-close after a pick (`300ms`).
    close_at: Option<f64>,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    popover_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl DatePickerInternal {
    fn new(initial_month: CalendarDate, cx: &mut App) -> Self {
        Self {
            open: false,
            month: initial_month,
            seen_value: None,
            direction: 1,
            changed_at_secs: f64::NEG_INFINITY,
            footer_changed_at_secs: f64::NEG_INFINITY,
            footer_text: "Choose a day".into(),
            close_at: None,
            trigger_bounds: Rc::new(RefCell::new(None)),
            popover_bounds: Rc::new(RefCell::new(None)),
            focus_handle: cx.focus_handle(),
        }
    }
}

fn paint_calendar_glyph(x: f32, y: f32, color: Hsla, window: &mut Window) {
    use gpui_kit::PathBuilder;
    // A tiny calendar: a body rectangle outline + two binder ticks.
    let mut body = PathBuilder::stroke(px(1.5));
    body.move_to(gpui_kit::point(px(x + 1.0), px(y - 6.0)));
    body.line_to(gpui_kit::point(px(x + 7.0), px(y - 6.0)));
    body.line_to(gpui_kit::point(px(x + 7.0), px(y + 6.0)));
    body.line_to(gpui_kit::point(px(x + 1.0), px(y + 6.0)));
    body.line_to(gpui_kit::point(px(x + 1.0), px(y - 6.0)));
    if let Ok(path) = body.build() {
        window.paint_path(path, color);
    }
    let mut rings = PathBuilder::stroke(px(1.5));
    rings.move_to(gpui_kit::point(px(x + 3.0), px(y - 8.0)));
    rings.line_to(gpui_kit::point(px(x + 3.0), px(y - 4.0)));
    if let Ok(path) = rings.build() {
        window.paint_path(path, color);
    }
    let mut rings2 = PathBuilder::stroke(px(1.5));
    rings2.move_to(gpui_kit::point(px(x + 5.0), px(y - 8.0)));
    rings2.line_to(gpui_kit::point(px(x + 5.0), px(y - 4.0)));
    if let Ok(path) = rings2.build() {
        window.paint_path(path, color);
    }
}

fn paint_chevron(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
    use gpui_kit::PathBuilder;
    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 = gpui_kit::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 `DatePicker` — a trigger + popover wrapping the Arc [`Calendar`].
#[derive(IntoElement)]
pub struct DatePicker {
    id: ElementId,
    label: SharedString,
    value: Option<CalendarDate>,
    default_value: Option<CalendarDate>,
    description: Option<SharedString>,
    placeholder: SharedString,
    min_date: Option<CalendarDate>,
    max_date: Option<CalendarDate>,
    disabled_dates: Option<Rc<dyn Fn(CalendarDate) -> bool>>,
    show_today: bool,
    disabled: bool,
    width: Option<Pixels>,
    on_change: Option<DatePickerValueHandler>,
    #[cfg(test)]
    changed_probe: Option<Rc<RefCell<f64>>>,
}

impl DatePicker {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: None,
            default_value: None,
            description: None,
            placeholder: "Select a date".into(),
            min_date: None,
            max_date: None,
            disabled_dates: None,
            show_today: false,
            disabled: false,
            width: None,
            on_change: None,
            #[cfg(test)]
            changed_probe: None,
        }
    }

    pub fn value(mut self, value: CalendarDate) -> Self {
        self.value = Some(value);
        self
    }

    pub fn default_value(mut self, value: CalendarDate) -> Self {
        self.default_value = Some(value);
        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
    }

    pub fn min_date(mut self, date: CalendarDate) -> Self {
        self.min_date = Some(date);
        self
    }

    pub fn max_date(mut self, date: CalendarDate) -> Self {
        self.max_date = Some(date);
        self
    }

    pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
        self.disabled_dates = Some(Rc::new(matcher));
        self
    }

    /// Adds a Today button to the calendar header.
    pub fn show_today(mut self, show: bool) -> Self {
        self.show_today = show;
        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
    }

    /// Receives the picked date; `None` means the value was cleared.
    pub fn on_change(
        mut self,
        handler: impl Fn(&Option<CalendarDate>, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

/// `Nov 19, 2026` (upstream's `Intl.DateTimeFormat` en-US default).
fn format_date(date: CalendarDate) -> String {
    const MONTHS: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    format!(
        "{}, {}, {}",
        MONTHS[(date.month - 1) as usize],
        date.day,
        date.year
    )
}

impl RenderOnce for DatePicker {
    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 state_id =
            ElementId::NamedChild(self.id.clone().into(), "__arc-datepicker-state".into());
        let initial_month =
            calendar_month_start(self.value.or(self.default_value).unwrap_or(CalendarDate {
                year: 2026,
                month: 11,
                day: 1,
            }));
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            let mut state = DatePickerInternal::new(initial_month, cx);
            // 首次受控值是初始内容,不是用户改值。
            state.seen_value = Some(self.value.or(self.default_value));
            state
        });

        // A picked day lets the highlight glide onto it and the footer confirm it, then the
        // popover returns to the field (immediately under reduced motion).
        if internal.read(cx).open {
            let close_at = internal.read(cx).close_at;
            if let Some(at) = close_at
                && (now >= at || reduced)
            {
                internal.update(cx, |s, _| {
                    s.open = false;
                    s.close_at = None;
                });
            }
        }

        // Controlled value sync + roll direction.
        if let Some(ext) = self.value {
            let seen = internal.read(cx).seen_value;
            if seen != Some(Some(ext)) {
                internal.update(cx, |s, _| {
                    let prev = s.seen_value.flatten();
                    s.direction = match (prev, Some(ext)) {
                        (Some(p), Some(n)) => {
                            if calendar_to_epoch_days(n) >= calendar_to_epoch_days(p) {
                                1
                            } else {
                                -1
                            }
                        }
                        _ => 1,
                    };
                    s.seen_value = Some(Some(ext));
                    s.changed_at_secs = now;
                });
            }
        }

        let is_ctrl = self.value.is_some();
        let value = if is_ctrl {
            self.value
        } else {
            let seen = internal.read(cx).seen_value;
            seen.unwrap_or(self.default_value)
        };
        let snap_state = internal.read(cx).clone();
        #[cfg(test)]
        if let Some(probe) = self.changed_probe.as_ref() {
            *probe.borrow_mut() = snap_state.changed_at_secs;
        }
        let open = snap_state.open && !self.disabled;
        let shown = value
            .map(format_date)
            .unwrap_or_else(|| self.placeholder.to_string());

        // Value roll: parts rise from below (later) or drop from above (earlier).
        let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
        let (value_op, value_y) = if src_elapsed >= 0.24 || value.is_none() {
            (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)
        };

        // Footer status rise.
        let footer_elapsed = (now - snap_state.footer_changed_at_secs).max(0.0);
        let (footer_op, footer_y) = if footer_elapsed >= 0.24 {
            (1.0_f32, 0.0_f32)
        } else {
            window.request_animation_frame();
            let t = (footer_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 {
                0.3 * f32::from(Typography::TEXT_XS) * (1.0 - e)
            };
            ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
        };

        // ── Popover presence + open/close springs ─────────────────────────────────────────────
        let popover_presence = ArcPresence::new((self.id.clone(), "dp-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 = popover_presence.progress.clamp(0.0, 1.0);
        let popover_y = if reduced {
            0.0
        } else {
            arc_spring(
                (self.id.clone(), "dp-y"),
                if open { 0.0 } else { -6.0 },
                motion.spring.snappy,
                window,
                cx,
            )
        };

        // ── Pick plumbing ─────────────────────────────────────────────────────────────────────
        let ch_pick = self.on_change.clone();
        let is_ctrl_pick = is_ctrl;
        let value_pick = value;
        let select_date = move |date: Option<CalendarDate>,
                                st: &gpui_kit::Entity<DatePickerInternal>,
                                window: &mut Window,
                                cx: &mut App| {
            let now_p = motion_now(cx);
            let footer = match date {
                Some(d) => SharedString::from(format!("Selected {}", format_date(d))),
                None => SharedString::from("Choose a day"),
            };
            st.update(cx, |s, _| {
                if !is_ctrl_pick {
                    s.seen_value = Some(date);
                }
                s.changed_at_secs = now_p;
                s.footer_changed_at_secs = now_p;
                s.footer_text = footer;
                if date.is_some() {
                    s.close_at = Some(now_p + DATE_PICKER_CLOSE_DELAY_SECS);
                } else {
                    s.close_at = None;
                }
            });
            if let Some(handler) = &ch_pick {
                handler(&date, window, cx);
            }
            window.refresh();
        };
        let _ = value_pick;

        // ── Trigger ───────────────────────────────────────────────────────────────────────────
        let trigger_bounds_ref = snap_state.trigger_bounds.clone();
        let trigger_probe = canvas(
            {
                let probe = trigger_bounds_ref.clone();
                move |rect, _, _| {
                    *probe.borrow_mut() = Some(rect);
                }
            },
            |_, _, _, _| {},
        )
        .absolute()
        .inset_0();
        let trigger_color = colors.foreground;
        let muted_color = colors.text_muted;
        let trigger_hover = colors.surface_muted;
        let trigger = BaseButton::new(ElementId::NamedChild(
            self.id.clone().into(),
            "trigger".into(),
        ))
        .disabled(self.disabled)
        .accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
        .on_click({
            let st = internal.clone();
            let focus_trigger = snap_state.focus_handle.clone();
            let disabled_flag = self.disabled;
            move |_, window, cx| {
                if disabled_flag {
                    return;
                }
                window.focus(&focus_trigger, cx);
                st.update(cx, |s, _| {
                    s.open = !s.open;
                    s.close_at = None;
                });
                window.refresh();
            }
        })
        .relative()
        .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(trigger_probe)
        .child(
            div().size(px(16.0)).flex_none().child(
                canvas(
                    |_, _, _| {},
                    move |rect, _, window, _| {
                        let x = f32::from(rect.origin.x);
                        let y = f32::from(rect.origin.y + rect.size.height * 0.5);
                        paint_calendar_glyph(x, y, 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 value.is_some() {
                    trigger_color
                } else {
                    muted_color
                })
                .overflow_hidden()
                .whitespace_nowrap()
                .child(SharedString::from(shown)),
        )
        .child(
            div().size(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(),
            ),
        );

        // ── Popover with Calendar + footer ────────────────────────────────────────────────────
        let popover_el = if popover_presence.should_render() {
            let calendar = Calendar::new(
                ElementId::NamedChild(self.id.clone().into(), "calendar".into()),
                self.label.clone(),
            )
            .month(snap_state.month)
            .when_some(value, |c, v| c.value(v))
            .when_some(self.min_date, |c, d| c.min_date(d))
            .when_some(self.max_date, |c, d| c.max_date(d))
            .when_some(self.disabled_dates.clone(), |c, m| {
                c.disabled_dates(move |d| m(d))
            })
            .show_today(self.show_today)
            .on_month_change({
                let st = internal.clone();
                move |month: &CalendarDate, _window: &mut Window, cx: &mut App| {
                    st.update(cx, |s, _| s.month = *month);
                }
            })
            .on_change({
                let st = internal.clone();
                let select = select_date.clone();
                move |date: &CalendarDate, window: &mut Window, cx: &mut App| {
                    let now_c = motion_now(cx);
                    let text = SharedString::from(format!("Selected {}", format_date(*date)));
                    st.update(cx, |s, _| {
                        s.changed_at_secs = now_c;
                        s.footer_changed_at_secs = now_c;
                        s.footer_text = text;
                    });
                    select(Some(*date), &st, window, cx);
                }
            });
            let clear_st = internal.clone();
            let clear_select = select_date.clone();
            let clear_handler =
                move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
                    clear_select(None, &clear_st, window, cx);
                };
            Some(
                deferred(
                    div()
                        .id(ElementId::NamedChild(
                            self.id.clone().into(),
                            "popover".into(),
                        ))
                        .test_support()
                        .role(Role::Dialog)
                        .aria_label(SharedString::from(format!("{} calendar", self.label)))
                        .absolute()
                        .top_full()
                        .mt(px(6.0 + popover_y))
                        .left_0()
                        .w(px(320.0))
                        .p(px(10.0))
                        .rounded(Radii::CONTROL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(p)
                        .on_key_down({
                            let st = internal.clone();
                            move |event: &KeyDownEvent, window, cx| {
                                if event.keystroke.key == "escape" {
                                    st.update(cx, |s, _| s.open = false);
                                    window.refresh();
                                }
                            }
                        })
                        .on_mouse_down(MouseButton::Left, |_, _, _| {})
                        .child(
                            canvas(
                                {
                                    let probe = snap_state.popover_bounds.clone();
                                    move |rect, _, _| {
                                        *probe.borrow_mut() = Some(rect);
                                    }
                                },
                                {
                                    let st = internal.clone();
                                    let trigger_ref = trigger_bounds_ref.clone();
                                    move |popover_rect, _, window, _| {
                                        let st = st.clone();
                                        let trigger_ref = trigger_ref.clone();
                                        window.on_mouse_event(
                                            move |event: &MouseDownEvent, phase, window, cx| {
                                                if !phase.bubble() {
                                                    return;
                                                }
                                                if !st.read(cx).open {
                                                    return;
                                                }
                                                let in_trigger = trigger_ref
                                                    .borrow()
                                                    .is_some_and(|b| b.contains(&event.position));
                                                let in_popover =
                                                    popover_rect.contains(&event.position);
                                                if !in_trigger && !in_popover {
                                                    st.update(cx, |s, _| s.open = false);
                                                    window.refresh();
                                                }
                                            },
                                        );
                                    }
                                },
                            )
                            .absolute()
                            .inset_0(),
                        )
                        .child(calendar)
                        .child(
                            div()
                                .flex()
                                .flex_row()
                                .items_center()
                                .justify_between()
                                .pt(px(8.0))
                                .child(
                                    BaseButton::new(ElementId::NamedChild(
                                        self.id.clone().into(),
                                        "clear-button".into(),
                                    ))
                                    .accessibility_label("Clear date")
                                    .disabled(value.is_none())
                                    .on_click(clear_handler)
                                    .h(px(28.0))
                                    .px(px(10.0))
                                    .rounded(Radii::PILL)
                                    .text_size(Typography::TEXT_XS)
                                    .font_medium()
                                    .text_color(colors.text_secondary)
                                    .when(value.is_some(), |this| {
                                        this.cursor_pointer()
                                            .hover(move |s| s.bg(colors.surface_muted))
                                    })
                                    .child(SharedString::from("Clear")),
                                )
                                .child(
                                    div()
                                        .mt(px(footer_y))
                                        .opacity(footer_op)
                                        .text_size(Typography::TEXT_XS)
                                        .text_color(colors.text_muted)
                                        .child(snap_state.footer_text.clone()),
                                ),
                        ),
                )
                .with_priority(25),
            )
        } else {
            None
        };

        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()
                    .on_key_down({
                        let st = internal.clone();
                        let focus_trigger = snap_state.focus_handle.clone();
                        let disabled_flag = self.disabled;
                        move |event: &KeyDownEvent, window, cx| {
                            if disabled_flag {
                                return;
                            }
                            let key = event.keystroke.key.as_str();
                            let st_open = st.read(cx).open;
                            match key {
                                "down" | "arrowdown" | "enter" | " " | "space" => {
                                    if !st_open {
                                        window.focus(&focus_trigger, cx);
                                        st.update(cx, |s, _| s.open = true);
                                        window.refresh();
                                    }
                                }
                                "escape" if st_open => {
                                    st.update(cx, |s, _| s.open = false);
                                    window.refresh();
                                }
                                _ => {}
                            }
                        }
                    })
                    .child(trigger)
                    .when_some(popover_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::*;
    use crate::inputs::calendar::calendar_date_key;

    #[test]
    fn date_picker_format_matches_intl_en_us_shape() {
        assert_eq!(
            format_date(CalendarDate {
                year: 2026,
                month: 11,
                day: 19
            }),
            "Nov, 19, 2026"
        );
    }

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

    impl Render for PickerHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            div().w(px(420.0)).p(px(16.0)).child(
                DatePicker::new("dp-test", "Start date")
                    .when_some(self.value, |p, v| p.value(v))
                    .disabled(self.disabled)
                    .show_today(false)
                    .on_change(cx.listener({
                        let events = events.clone();
                        move |this, date: &Option<CalendarDate>, _, cx| {
                            match date {
                                Some(d) => events.borrow_mut().push(calendar_date_key(*d)),
                                None => events.borrow_mut().push("cleared".to_string()),
                            }
                            this.value = *date;
                            cx.notify();
                        }
                    })),
            )
        }
    }

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

    fn nested_dp_element(parent: &str, name: &str) -> ElementId {
        ElementId::NamedChild(
            ElementId::NamedChild(ElementId::Name("dp-test".into()).into(), parent.into()).into(),
            name.into(),
        )
    }

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

        let host = PickerHost {
            value: Some(CalendarDate {
                year: 2026,
                month: 11,
                day: 10,
            }),
            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);
            let trigger = window.find(dp_element("trigger"));
            assert_eq!(trigger.role(), Some(Role::Button));

            // Open the popover and pick a day inside it.
            window.click(dp_element("trigger"), cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|window, cx| {
            for _ in 0..5 {
                window.render_frame(cx);
            }
            let popover = window.find(dp_element("popover"));
            assert_eq!(popover.role(), Some(Role::Dialog));
            window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-15")
        );

        // Clear via the footer button — clearing keeps the popover open so the user can pick a new date.
        cx.update(|window, cx| {
            for _ in 0..3 {
                window.render_frame(cx);
            }
            window.click(dp_element("clear-button"), cx);
        });
        assert_eq!(events.borrow().last().map(String::as_str), Some("cleared"));
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|window, cx| {
            for _ in 0..3 {
                window.render_frame(cx);
            }
            assert!(window.try_find(dp_element("popover")).is_some());
            // Picking a concrete day schedules the 300ms close.
            window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-15")
        );
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(400));
        cx.update(|window, cx| {
            window.render_frame(cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(200));
        cx.update(|window, cx| {
            for _ in 0..3 {
                window.render_frame(cx);
            }
            assert!(window.try_find(dp_element("popover")).is_none());
        });

        // Disabled swallows the open.
        view.update(cx, |host, cx| {
            host.disabled = true;
            host.value = Some(CalendarDate {
                year: 2026,
                month: 11,
                day: 10,
            });
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(dp_element("trigger"), cx);
            window.render_frame(cx);
            assert!(window.try_find(dp_element("popover")).is_none());
        });
    }

    #[gpui_kit::test]
    fn date_picker_initial_controlled_value_does_not_roll(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::Allow, cx);
        });
        struct InitialHost {
            day: u32,
            probe: Rc<RefCell<f64>>,
        }
        impl Render for InitialHost {
            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
                let mut picker = DatePicker::new("initial-date", "Date").value(CalendarDate {
                    year: 2026,
                    month: 11,
                    day: self.day,
                });
                picker.changed_probe = Some(self.probe.clone());
                div().w(px(420.0)).child(picker)
            }
        }
        let probe = Rc::new(RefCell::new(0.0));
        let (view, cx) = cx.add_window_view(|_, _| InitialHost {
            day: 10,
            probe: probe.clone(),
        });
        cx.update(|w, cx| {
            w.render_frame(cx);
            assert_eq!(*probe.borrow(), f64::NEG_INFINITY);
        });
        view.update(cx, |v, cx| {
            v.day = 15;
            cx.notify();
        });
        cx.update(|w, cx| {
            w.render_frame(cx);
            assert!(probe.borrow().is_finite(), "真实外部更新仍保留翻滚动效");
        });
    }

    #[gpui_kit::test]
    fn date_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 = PickerHost {
            value: None,
            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(dp_element("trigger"), cx);
            window.render_frame(cx);
            window.click(nested_dp_element("calendar", "day-2026-11-20"), cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-20")
        );
    }
}