1use 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
44pub 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: i8,
54 changed_at_secs: f64,
55 footer_changed_at_secs: f64,
56 footer_text: SharedString,
57 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 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#[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}
142
143impl DatePicker {
144 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
145 Self {
146 id: id.into(),
147 label: label.into(),
148 value: None,
149 default_value: None,
150 description: None,
151 placeholder: "Select a date".into(),
152 min_date: None,
153 max_date: None,
154 disabled_dates: None,
155 show_today: false,
156 disabled: false,
157 width: None,
158 on_change: None,
159 }
160 }
161
162 pub fn value(mut self, value: CalendarDate) -> Self {
163 self.value = Some(value);
164 self
165 }
166
167 pub fn default_value(mut self, value: CalendarDate) -> Self {
168 self.default_value = Some(value);
169 self
170 }
171
172 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
173 self.description = Some(description.into());
174 self
175 }
176
177 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
178 self.placeholder = placeholder.into();
179 self
180 }
181
182 pub fn min_date(mut self, date: CalendarDate) -> Self {
183 self.min_date = Some(date);
184 self
185 }
186
187 pub fn max_date(mut self, date: CalendarDate) -> Self {
188 self.max_date = Some(date);
189 self
190 }
191
192 pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
193 self.disabled_dates = Some(Rc::new(matcher));
194 self
195 }
196
197 pub fn show_today(mut self, show: bool) -> Self {
199 self.show_today = show;
200 self
201 }
202
203 pub fn disabled(mut self, disabled: bool) -> Self {
204 self.disabled = disabled;
205 self
206 }
207
208 pub fn width(mut self, width: impl Into<Pixels>) -> Self {
209 self.width = Some(width.into());
210 self
211 }
212
213 pub fn on_change(
215 mut self,
216 handler: impl Fn(&Option<CalendarDate>, &mut Window, &mut App) + 'static,
217 ) -> Self {
218 self.on_change = Some(Rc::new(handler));
219 self
220 }
221}
222
223fn format_date(date: CalendarDate) -> String {
225 const MONTHS: [&str; 12] = [
226 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
227 ];
228 format!(
229 "{}, {}, {}",
230 MONTHS[(date.month - 1) as usize],
231 date.day,
232 date.year
233 )
234}
235
236impl RenderOnce for DatePicker {
237 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
238 let theme = cx.arc_theme().clone();
239 let colors = theme.colors;
240 let motion = theme.motion;
241 let reduced = is_reduced_motion(cx);
242 let now = motion_now(cx);
243
244 let state_id =
245 ElementId::NamedChild(self.id.clone().into(), "__arc-datepicker-state".into());
246 let initial_month =
247 calendar_month_start(self.value.or(self.default_value).unwrap_or(CalendarDate {
248 year: 2026,
249 month: 11,
250 day: 1,
251 }));
252 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
253 DatePickerInternal::new(initial_month, cx)
254 });
255
256 if internal.read(cx).open {
259 let close_at = internal.read(cx).close_at;
260 if let Some(at) = close_at
261 && (now >= at || reduced)
262 {
263 internal.update(cx, |s, _| {
264 s.open = false;
265 s.close_at = None;
266 });
267 }
268 }
269
270 if let Some(ext) = self.value {
272 let seen = internal.read(cx).seen_value;
273 if seen != Some(Some(ext)) {
274 internal.update(cx, |s, _| {
275 let prev = s.seen_value.flatten();
276 s.direction = match (prev, Some(ext)) {
277 (Some(p), Some(n)) => {
278 if calendar_to_epoch_days(n) >= calendar_to_epoch_days(p) {
279 1
280 } else {
281 -1
282 }
283 }
284 _ => 1,
285 };
286 s.seen_value = Some(Some(ext));
287 s.changed_at_secs = now;
288 });
289 }
290 }
291
292 let is_ctrl = self.value.is_some();
293 let value = if is_ctrl {
294 self.value
295 } else {
296 let seen = internal.read(cx).seen_value;
297 seen.unwrap_or(self.default_value)
298 };
299 let snap_state = internal.read(cx).clone();
300 let open = snap_state.open && !self.disabled;
301 let shown = value
302 .map(format_date)
303 .unwrap_or_else(|| self.placeholder.to_string());
304
305 let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
307 let (value_op, value_y) = if src_elapsed >= 0.24 || value.is_none() {
308 (1.0_f32, 0.0_f32)
309 } else {
310 window.request_animation_frame();
311 let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
312 let e = if reduced {
313 t
314 } else {
315 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
316 };
317 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
318 let y = if reduced {
319 0.0
320 } else {
321 (snap_state.direction as f32) * 0.35 * f32::from(Typography::TEXT_SM) * (1.0 - e)
322 };
323 ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
324 };
325
326 let footer_elapsed = (now - snap_state.footer_changed_at_secs).max(0.0);
328 let (footer_op, footer_y) = if footer_elapsed >= 0.24 {
329 (1.0_f32, 0.0_f32)
330 } else {
331 window.request_animation_frame();
332 let t = (footer_elapsed / 0.24).clamp(0.0, 1.0) as f32;
333 let e = if reduced {
334 t
335 } else {
336 CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
337 };
338 let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
339 let y = if reduced {
340 0.0
341 } else {
342 0.3 * f32::from(Typography::TEXT_XS) * (1.0 - e)
343 };
344 ((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
345 };
346
347 let popover_presence = ArcPresence::new((self.id.clone(), "dp-presence"), open)
349 .animate_initial(false)
350 .config(ArcPresenceConfig {
351 enter_duration: motion.duration.fast,
352 exit_duration: motion.duration.instant,
353 enter_ease: motion.ease.enter,
354 exit_ease: motion.ease.standard,
355 fade_on_reduced_motion: true,
356 })
357 .sample(window, cx);
358 let p = popover_presence.progress.clamp(0.0, 1.0);
359 let popover_y = if reduced {
360 0.0
361 } else {
362 arc_spring(
363 (self.id.clone(), "dp-y"),
364 if open { 0.0 } else { -6.0 },
365 motion.spring.snappy,
366 window,
367 cx,
368 )
369 };
370
371 let ch_pick = self.on_change.clone();
373 let is_ctrl_pick = is_ctrl;
374 let value_pick = value;
375 let select_date = move |date: Option<CalendarDate>,
376 st: &gpui_kit::Entity<DatePickerInternal>,
377 window: &mut Window,
378 cx: &mut App| {
379 let now_p = motion_now(cx);
380 let footer = match date {
381 Some(d) => SharedString::from(format!("Selected {}", format_date(d))),
382 None => SharedString::from("Choose a day"),
383 };
384 st.update(cx, |s, _| {
385 if !is_ctrl_pick {
386 s.seen_value = Some(date);
387 }
388 s.changed_at_secs = now_p;
389 s.footer_changed_at_secs = now_p;
390 s.footer_text = footer;
391 if date.is_some() {
392 s.close_at = Some(now_p + DATE_PICKER_CLOSE_DELAY_SECS);
393 } else {
394 s.close_at = None;
395 }
396 });
397 if let Some(handler) = &ch_pick {
398 handler(&date, window, cx);
399 }
400 window.refresh();
401 };
402 let _ = value_pick;
403
404 let trigger_bounds_ref = snap_state.trigger_bounds.clone();
406 let trigger_probe = canvas(
407 {
408 let probe = trigger_bounds_ref.clone();
409 move |rect, _, _| {
410 *probe.borrow_mut() = Some(rect);
411 }
412 },
413 |_, _, _, _| {},
414 )
415 .absolute()
416 .inset_0();
417 let trigger_color = colors.foreground;
418 let muted_color = colors.text_muted;
419 let trigger_hover = colors.surface_muted;
420 let trigger = BaseButton::new(ElementId::NamedChild(
421 self.id.clone().into(),
422 "trigger".into(),
423 ))
424 .disabled(self.disabled)
425 .accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
426 .on_click({
427 let st = internal.clone();
428 let focus_trigger = snap_state.focus_handle.clone();
429 let disabled_flag = self.disabled;
430 move |_, window, cx| {
431 if disabled_flag {
432 return;
433 }
434 window.focus(&focus_trigger, cx);
435 st.update(cx, |s, _| {
436 s.open = !s.open;
437 s.close_at = None;
438 });
439 window.refresh();
440 }
441 })
442 .relative()
443 .w_full()
444 .h(px(38.0))
445 .px(px(10.0))
446 .flex()
447 .flex_row()
448 .items_center()
449 .gap(px(8.0))
450 .rounded(px(10.0))
451 .border_1()
452 .border_color(if self.disabled {
453 colors.border
454 } else {
455 colors.border_strong
456 })
457 .bg(colors.surface)
458 .opacity(if self.disabled { 0.5 } else { 1.0 })
459 .when(!self.disabled, |this| {
460 this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
461 })
462 .child(trigger_probe)
463 .child(
464 div().size(px(16.0)).flex_none().child(
465 canvas(
466 |_, _, _| {},
467 move |rect, _, window, _| {
468 let x = f32::from(rect.origin.x);
469 let y = f32::from(rect.origin.y + rect.size.height * 0.5);
470 paint_calendar_glyph(x, y, muted_color, window);
471 },
472 )
473 .size_full(),
474 ),
475 )
476 .child(
477 div()
478 .flex_1()
479 .min_w_0()
480 .mt(px(value_y))
481 .opacity(value_op)
482 .text_size(Typography::TEXT_SM)
483 .text_color(if value.is_some() {
484 trigger_color
485 } else {
486 muted_color
487 })
488 .overflow_hidden()
489 .whitespace_nowrap()
490 .child(SharedString::from(shown)),
491 )
492 .child(
493 div().size(px(16.0)).flex_none().child(
494 canvas(
495 |_, _, _| {},
496 move |rect, _, window, _| {
497 let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
498 let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
499 paint_chevron(cx_pt, cy_pt, muted_color, window);
500 },
501 )
502 .size_full(),
503 ),
504 );
505
506 let popover_el = if popover_presence.should_render() {
508 let calendar = Calendar::new(
509 ElementId::NamedChild(self.id.clone().into(), "calendar".into()),
510 self.label.clone(),
511 )
512 .month(snap_state.month)
513 .when_some(value, |c, v| c.value(v))
514 .when_some(self.min_date, |c, d| c.min_date(d))
515 .when_some(self.max_date, |c, d| c.max_date(d))
516 .when_some(self.disabled_dates.clone(), |c, m| {
517 c.disabled_dates(move |d| m(d))
518 })
519 .show_today(self.show_today)
520 .on_month_change({
521 let st = internal.clone();
522 move |month: &CalendarDate, _window: &mut Window, cx: &mut App| {
523 st.update(cx, |s, _| s.month = *month);
524 }
525 })
526 .on_change({
527 let st = internal.clone();
528 let select = select_date.clone();
529 move |date: &CalendarDate, window: &mut Window, cx: &mut App| {
530 let now_c = motion_now(cx);
531 let text = SharedString::from(format!("Selected {}", format_date(*date)));
532 st.update(cx, |s, _| {
533 s.changed_at_secs = now_c;
534 s.footer_changed_at_secs = now_c;
535 s.footer_text = text;
536 });
537 select(Some(*date), &st, window, cx);
538 }
539 });
540 let clear_st = internal.clone();
541 let clear_select = select_date.clone();
542 let clear_handler =
543 move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
544 clear_select(None, &clear_st, window, cx);
545 };
546 Some(
547 deferred(
548 div()
549 .id(ElementId::NamedChild(
550 self.id.clone().into(),
551 "popover".into(),
552 ))
553 .test_support()
554 .role(Role::Dialog)
555 .aria_label(SharedString::from(format!("{} calendar", self.label)))
556 .absolute()
557 .top_full()
558 .mt(px(6.0 + popover_y))
559 .left_0()
560 .w(px(320.0))
561 .p(px(10.0))
562 .rounded(Radii::CONTROL)
563 .border_1()
564 .border_color(colors.border)
565 .bg(colors.surface_raised)
566 .shadow(Shadows::floating(theme.mode))
567 .opacity(p)
568 .on_key_down({
569 let st = internal.clone();
570 move |event: &KeyDownEvent, window, cx| {
571 if event.keystroke.key == "escape" {
572 st.update(cx, |s, _| s.open = false);
573 window.refresh();
574 }
575 }
576 })
577 .on_mouse_down(MouseButton::Left, |_, _, _| {})
578 .child(
579 canvas(
580 {
581 let probe = snap_state.popover_bounds.clone();
582 move |rect, _, _| {
583 *probe.borrow_mut() = Some(rect);
584 }
585 },
586 {
587 let st = internal.clone();
588 let trigger_ref = trigger_bounds_ref.clone();
589 move |popover_rect, _, window, _| {
590 let st = st.clone();
591 let trigger_ref = trigger_ref.clone();
592 window.on_mouse_event(
593 move |event: &MouseDownEvent, phase, window, cx| {
594 if !phase.bubble() {
595 return;
596 }
597 if !st.read(cx).open {
598 return;
599 }
600 let in_trigger = trigger_ref
601 .borrow()
602 .is_some_and(|b| b.contains(&event.position));
603 let in_popover =
604 popover_rect.contains(&event.position);
605 if !in_trigger && !in_popover {
606 st.update(cx, |s, _| s.open = false);
607 window.refresh();
608 }
609 },
610 );
611 }
612 },
613 )
614 .absolute()
615 .inset_0(),
616 )
617 .child(calendar)
618 .child(
619 div()
620 .flex()
621 .flex_row()
622 .items_center()
623 .justify_between()
624 .pt(px(8.0))
625 .child(
626 BaseButton::new(ElementId::NamedChild(
627 self.id.clone().into(),
628 "clear-button".into(),
629 ))
630 .accessibility_label("Clear date")
631 .disabled(value.is_none())
632 .on_click(clear_handler)
633 .h(px(28.0))
634 .px(px(10.0))
635 .rounded(Radii::PILL)
636 .text_size(Typography::TEXT_XS)
637 .font_medium()
638 .text_color(colors.text_secondary)
639 .when(value.is_some(), |this| {
640 this.cursor_pointer()
641 .hover(move |s| s.bg(colors.surface_muted))
642 })
643 .child(SharedString::from("Clear")),
644 )
645 .child(
646 div()
647 .mt(px(footer_y))
648 .opacity(footer_op)
649 .text_size(Typography::TEXT_XS)
650 .text_color(colors.text_muted)
651 .child(snap_state.footer_text.clone()),
652 ),
653 ),
654 )
655 .with_priority(25),
656 )
657 } else {
658 None
659 };
660
661 let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
662
663 div()
664 .id(self.id)
665 .test_support()
666 .when_some(self.width, |this, w| this.w(w))
667 .when(self.width.is_none(), |this| this.w_full())
668 .flex()
669 .flex_col()
670 .gap(Spacing::S2)
671 .when(self.disabled, |this| this.opacity(0.5))
672 .child(
673 div()
674 .text_size(Typography::TEXT_SM)
675 .font_medium()
676 .text_color(colors.foreground)
677 .child(self.label.clone()),
678 )
679 .child(
680 div()
681 .relative()
682 .w_full()
683 .on_key_down({
684 let st = internal.clone();
685 let focus_trigger = snap_state.focus_handle.clone();
686 let disabled_flag = self.disabled;
687 move |event: &KeyDownEvent, window, cx| {
688 if disabled_flag {
689 return;
690 }
691 let key = event.keystroke.key.as_str();
692 let st_open = st.read(cx).open;
693 match key {
694 "down" | "arrowdown" | "enter" | " " | "space" => {
695 if !st_open {
696 window.focus(&focus_trigger, cx);
697 st.update(cx, |s, _| s.open = true);
698 window.refresh();
699 }
700 }
701 "escape" if st_open => {
702 st.update(cx, |s, _| s.open = false);
703 window.refresh();
704 }
705 _ => {}
706 }
707 }
708 })
709 .child(trigger)
710 .when_some(popover_el, |this, el| this.child(el)),
711 )
712 .child(render_field_message(
713 msg_id,
714 self.description,
715 false,
716 window,
717 cx,
718 ))
719 }
720}
721
722#[cfg(test)]
723mod tests {
724 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
725 use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
726
727 use super::*;
728 use crate::inputs::calendar::calendar_date_key;
729
730 #[test]
731 fn date_picker_format_matches_intl_en_us_shape() {
732 assert_eq!(
733 format_date(CalendarDate {
734 year: 2026,
735 month: 11,
736 day: 19
737 }),
738 "Nov, 19, 2026"
739 );
740 }
741
742 struct PickerHost {
743 value: Option<CalendarDate>,
744 events: Rc<RefCell<Vec<String>>>,
745 disabled: bool,
746 }
747
748 impl Render for PickerHost {
749 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
750 let events = self.events.clone();
751 div().w(px(420.0)).p(px(16.0)).child(
752 DatePicker::new("dp-test", "Start date")
753 .when_some(self.value, |p, v| p.value(v))
754 .disabled(self.disabled)
755 .show_today(false)
756 .on_change(cx.listener({
757 let events = events.clone();
758 move |this, date: &Option<CalendarDate>, _, cx| {
759 match date {
760 Some(d) => events.borrow_mut().push(calendar_date_key(*d)),
761 None => events.borrow_mut().push("cleared".to_string()),
762 }
763 this.value = *date;
764 cx.notify();
765 }
766 })),
767 )
768 }
769 }
770
771 fn dp_element(name: &str) -> ElementId {
772 ElementId::NamedChild(ElementId::Name("dp-test".into()).into(), name.into())
773 }
774
775 fn nested_dp_element(parent: &str, name: &str) -> ElementId {
776 ElementId::NamedChild(
777 ElementId::NamedChild(ElementId::Name("dp-test".into()).into(), parent.into()).into(),
778 name.into(),
779 )
780 }
781
782 #[gpui_kit::test]
783 fn date_picker_opens_picks_and_clears(cx: &mut TestAppContext) {
784 cx.update(|cx| {
785 gpui_kit::init(cx);
786 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
787 });
788
789 let host = PickerHost {
790 value: Some(CalendarDate {
791 year: 2026,
792 month: 11,
793 day: 10,
794 }),
795 events: Rc::new(RefCell::new(Vec::new())),
796 disabled: false,
797 };
798 let events = host.events.clone();
799 let (view, cx) = cx.add_window_view(|_, _| host);
800
801 cx.update(|window, cx| {
802 window.render_frame(cx);
803 let trigger = window.find(dp_element("trigger"));
804 assert_eq!(trigger.role(), Some(Role::Button));
805
806 window.click(dp_element("trigger"), cx);
808 });
809 cx.executor()
810 .advance_clock(std::time::Duration::from_millis(400));
811 cx.update(|window, cx| {
812 for _ in 0..5 {
813 window.render_frame(cx);
814 }
815 let popover = window.find(dp_element("popover"));
816 assert_eq!(popover.role(), Some(Role::Dialog));
817 window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
818 });
819 assert_eq!(
820 events.borrow().last().map(String::as_str),
821 Some("2026-11-15")
822 );
823
824 cx.update(|window, cx| {
826 for _ in 0..3 {
827 window.render_frame(cx);
828 }
829 window.click(dp_element("clear-button"), cx);
830 });
831 assert_eq!(events.borrow().last().map(String::as_str), Some("cleared"));
832 cx.executor()
833 .advance_clock(std::time::Duration::from_millis(400));
834 cx.update(|window, cx| {
835 for _ in 0..3 {
836 window.render_frame(cx);
837 }
838 assert!(window.try_find(dp_element("popover")).is_some());
839 window.click(nested_dp_element("calendar", "day-2026-11-15"), cx);
841 });
842 assert_eq!(
843 events.borrow().last().map(String::as_str),
844 Some("2026-11-15")
845 );
846 cx.executor()
847 .advance_clock(std::time::Duration::from_millis(400));
848 cx.update(|window, cx| {
849 window.render_frame(cx);
850 });
851 cx.executor()
852 .advance_clock(std::time::Duration::from_millis(200));
853 cx.update(|window, cx| {
854 for _ in 0..3 {
855 window.render_frame(cx);
856 }
857 assert!(window.try_find(dp_element("popover")).is_none());
858 });
859
860 view.update(cx, |host, cx| {
862 host.disabled = true;
863 host.value = Some(CalendarDate {
864 year: 2026,
865 month: 11,
866 day: 10,
867 });
868 cx.notify();
869 });
870 cx.update(|window, cx| {
871 window.render_frame(cx);
872 window.click(dp_element("trigger"), cx);
873 window.render_frame(cx);
874 assert!(window.try_find(dp_element("popover")).is_none());
875 });
876 }
877
878 #[gpui_kit::test]
879 fn date_picker_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
880 cx.update(|cx| {
881 gpui_kit::init(cx);
882 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
883 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
884 });
885
886 let host = PickerHost {
887 value: None,
888 events: Rc::new(RefCell::new(Vec::new())),
889 disabled: false,
890 };
891 let events = host.events.clone();
892 let (_view, cx) = cx.add_window_view(|_, _| host);
893
894 cx.update(|window, cx| {
895 window.render_frame(cx);
896 window.click(dp_element("trigger"), cx);
897 window.render_frame(cx);
898 window.click(nested_dp_element("calendar", "day-2026-11-20"), cx);
899 });
900 assert_eq!(
901 events.borrow().last().map(String::as_str),
902 Some("2026-11-20")
903 );
904 }
905}