Skip to main content

gpui_deck/
date_picker.rs

1//! A single, multiple, or range date picker composed from Calendar and Popover.
2
3use gpui::{
4    Anchor, AnyElement, App, AppContext as _, Context, ElementId, Entity, EventEmitter,
5    FocusHandle, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement, Styled,
6    Subscription, Window, prelude::FluentBuilder as _, px,
7};
8
9use crate::{
10    Button, CalendarState, Popover, PopoverState, StyledExt as _,
11    calendar::{CalendarActivation, CalendarSelection},
12};
13
14/// Emitted after user activation changes the selection. Single and complete-range
15/// selections close the popup before publishing; partial ranges and multiple
16/// selections keep the popup open.
17#[derive(Clone, Debug, Eq, PartialEq)]
18pub enum DatePickerEvent {
19    Change(CalendarSelection),
20}
21
22/// Coordinates one Calendar with one non-modal Popover in the same window.
23///
24/// Calendar exclusively owns the selected value, date arithmetic, and grid
25/// navigation. Popover exclusively owns opening, dismissal, and return focus.
26/// This composition resolves the current day focus immediately before opening
27/// and closes on single-date or completed-range activation. Multiple selection
28/// remains open until an explicit close or normal Popover dismissal.
29///
30/// Keep the matching DatePicker mounted while closed. Render the supplied
31/// calendar only inside this picker's content, not in a second simultaneous
32/// Calendar. Opening focuses the first selected date, or the retained cursor
33/// when empty. Multiple selection retains its cursor if that date is selected.
34pub struct DatePickerState {
35    calendar: Entity<CalendarState>,
36    popover: Entity<PopoverState>,
37    focus: FocusHandle,
38    _calendar_observation: Subscription,
39    _popover_observation: Subscription,
40    _activation_subscription: Subscription,
41}
42
43impl DatePickerState {
44    /// Uses an existing Calendar state, including its week start, disabled-date
45    /// predicate, bounds, and initial value.
46    pub fn new(
47        calendar: &Entity<CalendarState>,
48        window: &mut Window,
49        cx: &mut Context<Self>,
50    ) -> Self {
51        let disabled = calendar.read(cx).is_disabled();
52        let prepare_calendar = calendar.clone();
53        let popover = cx.new(|cx| {
54            let mut popover =
55                PopoverState::new(cx).with_initial_focus_builder(move |window, cx| {
56                    prepare_calendar.update(cx, |calendar, cx| {
57                        if !matches!(calendar.selection(), CalendarSelection::Multiple(_))
58                            || !calendar.is_selected(calendar.focused_date())
59                        {
60                            calendar.set_selection(calendar.selection().clone(), window, cx);
61                        }
62                        calendar.focus_handle().clone()
63                    })
64                });
65            popover.set_disabled(disabled, window, cx);
66            popover
67        });
68        let focus = popover.read(cx).focus_handle().clone();
69        let calendar_observation = cx.observe(calendar, |_, _, cx| cx.notify());
70        let popover_observation = cx.observe(&popover, |_, _, cx| cx.notify());
71        let activation_subscription = cx.subscribe_in(
72            calendar,
73            window,
74            |state, _, event: &CalendarActivation, window, cx| {
75                if !state.is_open(cx) || state.is_disabled(cx) {
76                    return;
77                }
78                // Subscribers may open another surface. Finish return focus
79                // before notifying them so this popup cannot steal it later.
80                if matches!(
81                    event.selection,
82                    CalendarSelection::Single(_) | CalendarSelection::Range { end: Some(_), .. }
83                ) {
84                    state.close(window, cx);
85                }
86                if event.changed {
87                    cx.emit(DatePickerEvent::Change(event.selection.clone()));
88                }
89            },
90        );
91        Self {
92            calendar: calendar.clone(),
93            popover,
94            focus,
95            _calendar_observation: calendar_observation,
96            _popover_observation: popover_observation,
97            _activation_subscription: activation_subscription,
98        }
99    }
100
101    /// The shared date state used to render Calendar and its day/month controls.
102    pub fn calendar(&self) -> &Entity<CalendarState> {
103        &self.calendar
104    }
105
106    pub fn selection<'a>(&self, cx: &'a App) -> &'a CalendarSelection {
107        self.calendar.read(cx).selection()
108    }
109
110    pub fn is_open(&self, cx: &App) -> bool {
111        self.popover.read(cx).is_open()
112    }
113
114    pub fn is_disabled(&self, cx: &App) -> bool {
115        self.popover.read(cx).is_disabled()
116    }
117
118    /// The stable native Button trigger focus handle.
119    pub fn focus_handle(&self) -> &FocusHandle {
120        &self.focus
121    }
122
123    /// Opens at the selection or retained cursor, using the Calendar focus policy.
124    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
125        self.popover.update(cx, |state, cx| state.open(window, cx));
126    }
127
128    /// Closes without changing the value. Restores the trigger while the popup
129    /// owns focus; outside/Tab dismissal retains the new focus target.
130    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
131        self.popover.update(cx, |state, cx| state.close(window, cx));
132    }
133
134    /// Disables the trigger and calendar, closing an open popup first.
135    /// Use this method to coordinate disabled state rather than changing the
136    /// nested Calendar independently.
137    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
138        self.popover
139            .update(cx, |state, cx| state.set_disabled(disabled, window, cx));
140        self.calendar
141            .update(cx, |state, cx| state.set_disabled(disabled, window, cx));
142    }
143
144    /// Replaces the selection mode and value without emitting Change, closing an
145    /// open popup first. Invalid, date-disabled, or out-of-bounds selections leave both states
146    /// unchanged. An empty selection preserves the Calendar's navigation date.
147    pub fn set_selection(
148        &mut self,
149        selection: CalendarSelection,
150        window: &mut Window,
151        cx: &mut Context<Self>,
152    ) -> bool {
153        let Some(selection) = self.calendar.read(cx).normalized_selection(selection) else {
154            return false;
155        };
156        // Close while Popover still knows its original initial focus. Before
157        // first paint, a different month's grid slot is not yet in its tree.
158        self.close(window, cx);
159        self.calendar
160            .update(cx, |state, cx| state.set_selection(selection, window, cx))
161    }
162}
163
164impl EventEmitter<DatePickerEvent> for DatePickerState {}
165
166/// Reads one typed date for a text field beside a picker.
167///
168/// Accepts `YYYY-MM-DD` with `-`, `/` or `.` separators, and these
169/// case-insensitive English forms relative to `today`: `today`, `tomorrow`,
170/// `yesterday`, `in N days` / `in N weeks`, and `N days ago` / `N weeks ago`
171/// (singular units too). The library has no clock, so the application supplies
172/// `today`. Returns `None` for anything else, including impossible dates. Pass a
173/// result to [`DatePickerState::set_selection`], which still applies the
174/// Calendar's bounds and disabled-date predicate.
175pub fn parse_date_text(text: &str, today: crate::Date) -> Option<crate::Date> {
176    let text = text.trim().to_lowercase();
177    let words: Vec<&str> = text.split_whitespace().collect();
178    let offset = |count: &str, unit: &str| -> Option<jiff::Span> {
179        let count: i64 = count.parse().ok()?;
180        let days = match unit {
181            "day" | "days" => count,
182            "week" | "weeks" => count.checked_mul(7)?,
183            _ => return None,
184        };
185        jiff::Span::new().try_days(days).ok()
186    };
187    match words.as_slice() {
188        ["today"] => Some(today),
189        ["tomorrow"] => today.tomorrow().ok(),
190        ["yesterday"] => today.yesterday().ok(),
191        ["in", count, unit] => today.checked_add(offset(count, unit)?).ok(),
192        [count, unit, "ago"] => today.checked_sub(offset(count, unit)?).ok(),
193        [date] => {
194            let parts: Vec<&str> = date.split(['-', '/', '.']).collect();
195            let [year, month, day] = parts.as_slice() else {
196                return None;
197            };
198            if year.len() != 4
199                || month.is_empty()
200                || month.len() > 2
201                || day.is_empty()
202                || day.len() > 2
203            {
204                return None;
205            }
206            crate::Date::new(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?).ok()
207        }
208        _ => None,
209    }
210}
211
212/// An unstyled Button trigger and a date-selection popup.
213///
214/// The application supplies formatted trigger text, the popup surface, month
215/// buttons, and the Calendar rendered from [`DatePickerState::calendar`]. Keep
216/// using ordinary CalendarDay children; single and complete-range activation
217/// close this picker. Partial range and multiple selections remain open.
218/// `accessibility_label` names the popup. Name the trigger separately through
219/// its builder. Expansion, disabled state, activation, and focus belong to the
220/// underlying Popover. Text parsing and trigger formatting belong to the application.
221#[derive(IntoElement)]
222pub struct DatePicker {
223    id: ElementId,
224    state: Entity<DatePickerState>,
225    trigger: Button,
226    content: Option<AnyElement>,
227    label: Option<SharedString>,
228    anchor: Anchor,
229    offset: Pixels,
230    style: StyleRefinement,
231}
232
233impl DatePicker {
234    pub fn new(id: impl Into<ElementId>, state: &Entity<DatePickerState>) -> Self {
235        let id = id.into();
236        Self {
237            trigger: Button::new(id.clone()),
238            id,
239            state: state.clone(),
240            content: None,
241            label: None,
242            anchor: Anchor::TopLeft,
243            offset: px(0.),
244            style: StyleRefinement::default(),
245        }
246    }
247
248    pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
249        self.trigger = build(self.trigger);
250        self
251    }
252
253    pub fn content(mut self, content: impl IntoElement) -> Self {
254        self.content = Some(content.into_any_element());
255        self
256    }
257
258    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
259        self.label = Some(label.into());
260        self
261    }
262
263    pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
264        self.anchor = anchor.into();
265        self
266    }
267
268    pub fn offset(mut self, offset: Pixels) -> Self {
269        self.offset = offset;
270        self
271    }
272}
273
274impl Styled for DatePicker {
275    fn style(&mut self) -> &mut StyleRefinement {
276        &mut self.style
277    }
278}
279
280impl RenderOnce for DatePicker {
281    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
282        Popover::new(self.id, &self.state.read(cx).popover)
283            .trigger(|_| self.trigger)
284            .when_some(self.content, |popover, content| popover.content(content))
285            .when_some(self.label, |popover, label| {
286                popover.accessibility_label(label)
287            })
288            .anchor(self.anchor)
289            .offset(self.offset)
290            .refine_style(&self.style)
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use std::{cell::RefCell, rc::Rc};
297
298    use gpui::{
299        InteractiveElement as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
300        ParentElement as _, Render, Role, StatefulInteractiveElement as _, TestAppContext,
301        VisualTestContext, div,
302    };
303
304    use super::*;
305    use crate::{Calendar, CalendarDay, Date, Root};
306
307    struct Harness {
308        calendar: Entity<CalendarState>,
309        picker: Entity<DatePickerState>,
310        before: FocusHandle,
311        after: FocusHandle,
312        show_picker: bool,
313        redirect_change: bool,
314        changes: Rc<RefCell<Vec<CalendarSelection>>>,
315        _subscriptions: Vec<Subscription>,
316    }
317
318    impl Render for Harness {
319        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
320            let days = self.calendar.read(cx).days();
321            let calendar = Calendar::new("calendar", &self.calendar)
322                .accessibility_label("Date")
323                .flex()
324                .flex_col()
325                .child(
326                    div().id("weekdays").role(Role::Row).flex().children(
327                        ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
328                            .into_iter()
329                            .enumerate()
330                            .map(|(index, label)| {
331                                div()
332                                    .id(("weekday", index))
333                                    .role(Role::ColumnHeader)
334                                    .aria_column_index(index)
335                                    .w(px(40.))
336                                    .h(px(24.))
337                                    .child(label)
338                            }),
339                    ),
340                )
341                .children(days.chunks(7).enumerate().map(|(index, week)| {
342                    div()
343                        .id(("week", index))
344                        .role(Role::Row)
345                        .flex()
346                        .children(week.iter().map(|&date| {
347                            CalendarDay::new(&self.calendar, date)
348                                .debug_selector(move || format!("date-{date}"))
349                                .w(px(40.))
350                                .h(px(28.))
351                                .child(date.day().to_string())
352                        }))
353                }));
354            div()
355                .w(px(680.))
356                .flex()
357                .flex_col()
358                .gap(px(8.))
359                .child(
360                    Button::new("before")
361                        .debug_selector(|| "before".into())
362                        .track_focus(&self.before)
363                        .w(px(120.))
364                        .h(px(32.))
365                        .child("Before"),
366                )
367                .when(self.show_picker, |base| {
368                    base.child(
369                        DatePicker::new("picker", &self.picker)
370                            .accessibility_label("Choose a date")
371                            .w(px(180.))
372                            .offset(px(4.))
373                            .trigger(|button| {
374                                button
375                                    .debug_selector(|| "picker".into())
376                                    .accessibility_label("Recording date")
377                                    .h(px(32.))
378                                    .child("Pick a date")
379                            })
380                            .content(div().w(px(280.)).child(calendar)),
381                    )
382                })
383                .child(
384                    Button::new("after")
385                        .debug_selector(|| "after".into())
386                        .track_focus(&self.after)
387                        .ml(px(400.))
388                        .w(px(120.))
389                        .h(px(32.))
390                        .child("After"),
391                )
392        }
393    }
394
395    fn date(year: i16, month: i8, day: i8) -> Date {
396        Date::new(year, month, day).unwrap()
397    }
398
399    fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>) {
400        configured_harness(cx, |calendar| calendar)
401    }
402
403    fn configured_harness(
404        cx: &mut TestAppContext,
405        configure: impl FnOnce(CalendarState) -> CalendarState + 'static,
406    ) -> (&mut VisualTestContext, Entity<Harness>) {
407        cx.update(crate::init);
408        let (root, cx) = cx.add_window_view(move |window, cx| {
409            let content = cx.new(|cx| {
410                let calendar = cx.new(|cx| {
411                    configure(
412                        CalendarState::new(date(2024, 1, 31), cx)
413                            .bounds(date(2024, 1, 1), date(2026, 12, 31))
414                            .default_selection(CalendarSelection::Single(Some(date(2024, 1, 31)))),
415                    )
416                });
417                let picker = cx.new(|cx| DatePickerState::new(&calendar, window, cx));
418                let subscriptions = vec![
419                    cx.observe(&picker, |_, _, cx| cx.notify()),
420                    cx.subscribe_in(
421                        &picker,
422                        window,
423                        |this: &mut Harness, picker, event, window, cx| {
424                            let DatePickerEvent::Change(selection) = event;
425                            let finished = matches!(
426                                selection,
427                                CalendarSelection::Single(_)
428                                    | CalendarSelection::Range { end: Some(_), .. }
429                            );
430                            assert_eq!(picker.read(cx).is_open(cx), !finished);
431                            this.changes.borrow_mut().push(selection.clone());
432                            if this.redirect_change {
433                                this.after.focus(window, cx);
434                            }
435                        },
436                    ),
437                ];
438                Harness {
439                    calendar,
440                    picker,
441                    before: cx.focus_handle(),
442                    after: cx.focus_handle(),
443                    show_picker: true,
444                    redirect_change: false,
445                    changes: Rc::new(RefCell::new(Vec::new())),
446                    _subscriptions: subscriptions,
447                }
448            });
449            Root::new(content, window, cx)
450        });
451        let view = root
452            .read_with(cx, |root, _| root.view().clone())
453            .downcast::<Harness>()
454            .unwrap();
455        cx.update(|window, cx| {
456            window.activate_window();
457            view.read(cx).before.clone().focus(window, cx);
458        });
459        settle(cx);
460        (cx, view)
461    }
462
463    fn settle(cx: &mut VisualTestContext) {
464        cx.update(|window, cx| window.draw(cx).clear(cx));
465        cx.run_until_parked();
466        cx.update(|window, cx| window.draw(cx).clear(cx));
467    }
468
469    fn press(cx: &mut VisualTestContext, key: &str) {
470        let keystroke =
471            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
472        cx.simulate_event(KeyDownEvent {
473            keystroke: keystroke.clone(),
474            is_held: false,
475            prefer_character_input: false,
476        });
477        cx.simulate_event(KeyUpEvent { keystroke });
478        settle(cx);
479    }
480
481    fn assert_open_at(cx: &mut VisualTestContext, view: &Entity<Harness>, date: Date) {
482        cx.update(|window, cx| {
483            let view = view.read(cx);
484            assert!(view.picker.read(cx).is_open(cx));
485            let calendar = view.calendar.read(cx);
486            assert_eq!(calendar.focused_date(), date);
487            assert_eq!(calendar.month(), date.first_of_month());
488            assert!(calendar.focus_handle().is_focused(window));
489        });
490    }
491
492    #[gpui::test]
493    fn opening_resolves_the_selected_day_and_every_activation_finishes_the_popup(
494        cx: &mut TestAppContext,
495    ) {
496        let (cx, view) = harness(cx);
497        press(cx, "tab");
498        press(cx, "enter");
499        assert_open_at(cx, &view, date(2024, 1, 31));
500        press(cx, "pagedown");
501        assert_open_at(cx, &view, date(2024, 2, 29));
502        press(cx, "escape");
503        cx.update(|window, cx| {
504            let view = view.read(cx);
505            assert!(!view.picker.read(cx).is_open(cx));
506            assert_eq!(
507                view.picker.read(cx).selection(cx),
508                &CalendarSelection::Single(Some(date(2024, 1, 31)))
509            );
510            assert!(view.picker.read(cx).focus_handle().is_focused(window));
511        });
512        press(cx, "space");
513        assert_open_at(cx, &view, date(2024, 1, 31));
514        press(cx, "right");
515        press(cx, "enter");
516        cx.update(|window, cx| {
517            let view = view.read(cx);
518            assert!(!view.picker.read(cx).is_open(cx));
519            assert_eq!(
520                *view.changes.borrow(),
521                [CalendarSelection::Single(Some(date(2024, 2, 1)))]
522            );
523            assert!(view.picker.read(cx).focus_handle().is_focused(window));
524        });
525
526        press(cx, "enter");
527        assert_open_at(cx, &view, date(2024, 2, 1));
528        press(cx, "space");
529        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
530        press(cx, "enter");
531        let point = cx.debug_bounds("date-2024-02-01").unwrap().center();
532        cx.simulate_click(point, Modifiers::default());
533        settle(cx);
534        cx.update(|_, cx| {
535            let view = view.read(cx);
536            assert!(!view.picker.read(cx).is_open(cx));
537            assert_eq!(
538                *view.changes.borrow(),
539                [CalendarSelection::Single(Some(date(2024, 2, 1)))]
540            );
541        });
542
543        view.update(cx, |view, _| view.redirect_change = true);
544        press(cx, "enter");
545        press(cx, "right");
546        press(cx, "enter");
547        cx.update(|window, cx| {
548            let view = view.read(cx);
549            assert!(!view.picker.read(cx).is_open(cx));
550            assert_eq!(
551                *view.changes.borrow(),
552                [date(2024, 2, 1), date(2024, 2, 2)]
553                    .map(|date| CalendarSelection::Single(Some(date)))
554            );
555            assert!(
556                view.after.is_focused(window),
557                "Change subscribers retain their new focus"
558            );
559        });
560    }
561
562    #[gpui::test]
563    fn dismissal_disabled_and_unselected_reopening_preserve_their_owners(cx: &mut TestAppContext) {
564        let (cx, view) = harness(cx);
565        // Resolve and return focus even before the Calendar has ever mounted.
566        cx.update(|window, cx| {
567            let picker = view.read(cx).picker.clone();
568            picker.update(cx, |picker, cx| {
569                picker.open(window, cx);
570                picker.close(window, cx);
571                assert!(picker.focus_handle().is_focused(window));
572                picker.open(window, cx);
573                assert!(picker.set_selection(
574                    CalendarSelection::Single(Some(date(2024, 2, 20))),
575                    window,
576                    cx
577                ));
578                assert!(!picker.is_open(cx));
579                assert!(picker.focus_handle().is_focused(window));
580            });
581        });
582        settle(cx);
583        press(cx, "enter");
584        press(cx, "tab");
585        cx.update(|window, cx| {
586            let view = view.read(cx);
587            assert!(!view.picker.read(cx).is_open(cx));
588            assert!(view.after.is_focused(window));
589        });
590        press(cx, "shift-tab");
591        press(cx, "space");
592        let before = cx.debug_bounds("before").unwrap().center();
593        cx.simulate_click(before, Modifiers::default());
594        settle(cx);
595        cx.update(|window, cx| {
596            let view = view.read(cx);
597            assert!(!view.picker.read(cx).is_open(cx));
598            assert!(view.before.is_focused(window));
599            assert!(view.changes.borrow().is_empty());
600        });
601
602        cx.update(|window, cx| {
603            let picker = view.read(cx).picker.clone();
604            picker.update(cx, |picker, cx| {
605                assert!(picker.set_selection(
606                    CalendarSelection::Single(Some(date(2024, 2, 20))),
607                    window,
608                    cx
609                ));
610                assert!(!picker.set_selection(
611                    CalendarSelection::Single(Some(date(2023, 12, 31))),
612                    window,
613                    cx
614                ));
615                assert_eq!(
616                    picker.selection(cx),
617                    &CalendarSelection::Single(Some(date(2024, 2, 20)))
618                );
619                assert!(picker.set_selection(CalendarSelection::Single(None), window, cx));
620                picker.open(window, cx);
621            });
622        });
623        settle(cx);
624        assert_open_at(cx, &view, date(2024, 2, 20));
625        press(cx, "pagedown");
626        press(cx, "escape");
627        press(cx, "enter");
628        assert_open_at(cx, &view, date(2024, 3, 20));
629        cx.update(|window, cx| {
630            let picker = view.read(cx).picker.clone();
631            picker.update(cx, |picker, cx| picker.set_disabled(true, window, cx));
632            assert!(picker.read(cx).is_disabled(cx));
633            assert!(!picker.read(cx).is_open(cx));
634            assert!(picker.read(cx).focus_handle().is_focused(window));
635            assert!(view.read(cx).calendar.read(cx).is_disabled());
636        });
637        settle(cx);
638        press(cx, "enter");
639        press(cx, "tab");
640        cx.update(|window, cx| {
641            let view = view.read(cx);
642            assert!(!view.picker.read(cx).is_open(cx));
643            assert!(view.after.is_focused(window));
644            assert!(view.changes.borrow().is_empty());
645        });
646
647        cx.update(|window, cx| {
648            let picker = view.read(cx).picker.clone();
649            picker.update(cx, |picker, cx| {
650                picker.set_disabled(false, window, cx);
651                picker.open(window, cx);
652            });
653        });
654        settle(cx);
655        view.update(cx, |view, cx| {
656            view.show_picker = false;
657            cx.notify();
658        });
659        settle(cx);
660        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
661    }
662
663    #[gpui::test]
664    fn range_picker_retains_partial_selection_and_closes_only_when_complete(
665        cx: &mut TestAppContext,
666    ) {
667        let (cx, view) = harness(cx);
668        let start = date(2024, 1, 31);
669        let end = date(2024, 2, 2);
670        let range = |start, end| CalendarSelection::Range { start, end };
671        cx.update(|window, cx| {
672            let picker = view.read(cx).picker.clone();
673            picker.update(cx, |picker, cx| {
674                assert!(picker.set_selection(range(None, None), window, cx));
675                picker.open(window, cx);
676            });
677        });
678        settle(cx);
679        press(cx, "enter");
680        assert_open_at(cx, &view, start);
681        press(cx, "right");
682        press(cx, "escape");
683        press(cx, "enter");
684        assert_open_at(cx, &view, start);
685        cx.update(|window, cx| {
686            let picker = view.read(cx).picker.clone();
687            assert!(!picker.update(cx, |picker, cx| {
688                picker.set_selection(range(None, Some(end)), window, cx)
689            }));
690            assert!(picker.read(cx).is_open(cx));
691            assert_eq!(picker.read(cx).selection(cx), &range(Some(start), None));
692        });
693        press(cx, "right");
694        press(cx, "right");
695        press(cx, "space");
696        cx.update(|window, cx| {
697            let picker = view.read(cx).picker.read(cx);
698            assert!(!picker.is_open(cx));
699            assert!(picker.focus_handle().is_focused(window));
700            assert_eq!(picker.selection(cx), &range(Some(start), Some(end)));
701        });
702        press(cx, "enter");
703        assert_open_at(cx, &view, start);
704        press(cx, "enter");
705        assert_open_at(cx, &view, start);
706        press(cx, "space");
707        cx.update(|window, cx| {
708            let picker = view.read(cx).picker.clone();
709            assert!(!picker.read(cx).is_open(cx));
710            assert_eq!(
711                picker.read(cx).selection(cx),
712                &range(Some(start), Some(start))
713            );
714            assert_eq!(
715                *view.read(cx).changes.borrow(),
716                [
717                    range(Some(start), None),
718                    range(Some(start), Some(end)),
719                    range(Some(start), None),
720                    range(Some(start), Some(start)),
721                ]
722            );
723            picker.update(cx, |picker, cx| {
724                picker.open(window, cx);
725                assert!(picker.set_selection(range(Some(start), Some(end)), window, cx));
726                assert!(!picker.is_open(cx));
727                assert!(picker.focus_handle().is_focused(window));
728            });
729        });
730    }
731
732    #[gpui::test]
733    fn multiple_picker_keeps_toggling_until_dismissal_and_reopens_at_selected_focus(
734        cx: &mut TestAppContext,
735    ) {
736        let (cx, view) = harness(cx);
737        let first = date(2024, 1, 31);
738        let second = date(2024, 2, 1);
739        let third = date(2024, 2, 2);
740        cx.update(|window, cx| {
741            let picker = view.read(cx).picker.clone();
742            picker.update(cx, |picker, cx| {
743                assert!(picker.set_selection(CalendarSelection::Multiple(vec![first]), window, cx));
744                picker.open(window, cx);
745            });
746        });
747        settle(cx);
748        press(cx, "right");
749        press(cx, "enter");
750        assert_open_at(cx, &view, second);
751        press(cx, "left");
752        press(cx, "space");
753        assert_open_at(cx, &view, first);
754        press(cx, "escape");
755        press(cx, "enter");
756        assert_open_at(cx, &view, second);
757        press(cx, "right");
758        press(cx, "enter");
759        press(cx, "escape");
760        press(cx, "enter");
761        assert_open_at(cx, &view, third);
762        cx.update(|window, cx| {
763            let picker = view.read(cx).picker.clone();
764            picker.update(cx, |picker, cx| picker.set_disabled(true, window, cx));
765            assert!(!picker.read(cx).is_open(cx));
766            assert_eq!(
767                picker.read(cx).selection(cx),
768                &CalendarSelection::Multiple(vec![second, third])
769            );
770            assert_eq!(
771                *view.read(cx).changes.borrow(),
772                [
773                    CalendarSelection::Multiple(vec![first, second]),
774                    CalendarSelection::Multiple(vec![second]),
775                    CalendarSelection::Multiple(vec![second, third]),
776                ]
777            );
778        });
779        settle(cx);
780        press(cx, "space");
781        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
782    }
783
784    #[gpui::test]
785    fn disabled_date_activation_and_programmatic_rejection_keep_the_popup_open(
786        cx: &mut TestAppContext,
787    ) {
788        let disabled = date(2024, 2, 1);
789        let (cx, view) = configured_harness(cx, move |calendar| {
790            calendar.disabled_dates(move |date| date == disabled)
791        });
792        press(cx, "tab");
793        press(cx, "enter");
794        press(cx, "right");
795        assert_open_at(cx, &view, disabled);
796        press(cx, "enter");
797        assert_open_at(cx, &view, disabled);
798        cx.update(|window, cx| {
799            let picker = view.read(cx).picker.clone();
800            assert!(!picker.update(cx, |picker, cx| picker.set_selection(
801                CalendarSelection::Single(Some(disabled)),
802                window,
803                cx
804            )));
805            assert!(view.read(cx).changes.borrow().is_empty());
806        });
807        settle(cx);
808        assert_open_at(cx, &view, disabled);
809        press(cx, "right");
810        press(cx, "enter");
811        cx.update(|window, cx| {
812            let view = view.read(cx);
813            assert!(!view.picker.read(cx).is_open(cx));
814            assert!(view.picker.read(cx).focus_handle().is_focused(window));
815            assert_eq!(
816                *view.changes.borrow(),
817                [CalendarSelection::Single(Some(date(2024, 2, 2)))]
818            );
819        });
820    }
821
822    #[test]
823    fn typed_dates_accept_iso_and_relative_english_forms() {
824        let today = Date::constant(2026, 11, 20);
825        let date = |y, m, d| Date::new(y, m, d).ok();
826        for (text, expected) in [
827            ("2026-12-01", date(2026, 12, 1)),
828            (" 2026/1/5 ", date(2026, 1, 5)),
829            ("2026.02.28", date(2026, 2, 28)),
830            ("Today", Some(today)),
831            ("tomorrow", date(2026, 11, 21)),
832            ("yesterday", date(2026, 11, 19)),
833            ("in 2 days", date(2026, 11, 22)),
834            ("In 1 week", date(2026, 11, 27)),
835            ("3 days ago", date(2026, 11, 17)),
836            ("2 weeks ago", date(2026, 11, 6)),
837            ("2026-02-30", None),
838            ("26-02-03", None),
839            ("in two days", None),
840            ("next friday", None),
841            ("", None),
842        ] {
843            assert_eq!(parse_date_text(text, today), expected, "{text:?}");
844        }
845    }
846}