gpui-deck 0.0.4

Headless GPUI primitives with application-owned presentation.
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
//! A single, multiple, or range date picker composed from Calendar and Popover.

use gpui::{
    Anchor, AnyElement, App, AppContext as _, Context, ElementId, Entity, EventEmitter,
    FocusHandle, IntoElement, Pixels, RenderOnce, SharedString, StyleRefinement, Styled,
    Subscription, Window, prelude::FluentBuilder as _, px,
};

use crate::{
    Button, CalendarState, Popover, PopoverState, StyledExt as _,
    calendar::{CalendarActivation, CalendarSelection},
};

/// Emitted after user activation changes the selection. Single and complete-range
/// selections close the popup before publishing; partial ranges and multiple
/// selections keep the popup open.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DatePickerEvent {
    Change(CalendarSelection),
}

/// Coordinates one Calendar with one non-modal Popover in the same window.
///
/// Calendar exclusively owns the selected value, date arithmetic, and grid
/// navigation. Popover exclusively owns opening, dismissal, and return focus.
/// This composition resolves the current day focus immediately before opening
/// and closes on single-date or completed-range activation. Multiple selection
/// remains open until an explicit close or normal Popover dismissal.
///
/// Keep the matching DatePicker mounted while closed. Render the supplied
/// calendar only inside this picker's content, not in a second simultaneous
/// Calendar. Opening focuses the first selected date, or the retained cursor
/// when empty. Multiple selection retains its cursor if that date is selected.
pub struct DatePickerState {
    calendar: Entity<CalendarState>,
    popover: Entity<PopoverState>,
    focus: FocusHandle,
    _calendar_observation: Subscription,
    _popover_observation: Subscription,
    _activation_subscription: Subscription,
}

impl DatePickerState {
    /// Uses an existing Calendar state, including its week start, disabled-date
    /// predicate, bounds, and initial value.
    pub fn new(
        calendar: &Entity<CalendarState>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let disabled = calendar.read(cx).is_disabled();
        let prepare_calendar = calendar.clone();
        let popover = cx.new(|cx| {
            let mut popover =
                PopoverState::new(cx).with_initial_focus_builder(move |window, cx| {
                    prepare_calendar.update(cx, |calendar, cx| {
                        if !matches!(calendar.selection(), CalendarSelection::Multiple(_))
                            || !calendar.is_selected(calendar.focused_date())
                        {
                            calendar.set_selection(calendar.selection().clone(), window, cx);
                        }
                        calendar.focus_handle().clone()
                    })
                });
            popover.set_disabled(disabled, window, cx);
            popover
        });
        let focus = popover.read(cx).focus_handle().clone();
        let calendar_observation = cx.observe(calendar, |_, _, cx| cx.notify());
        let popover_observation = cx.observe(&popover, |_, _, cx| cx.notify());
        let activation_subscription = cx.subscribe_in(
            calendar,
            window,
            |state, _, event: &CalendarActivation, window, cx| {
                if !state.is_open(cx) || state.is_disabled(cx) {
                    return;
                }
                // Subscribers may open another surface. Finish return focus
                // before notifying them so this popup cannot steal it later.
                if matches!(
                    event.selection,
                    CalendarSelection::Single(_) | CalendarSelection::Range { end: Some(_), .. }
                ) {
                    state.close(window, cx);
                }
                if event.changed {
                    cx.emit(DatePickerEvent::Change(event.selection.clone()));
                }
            },
        );
        Self {
            calendar: calendar.clone(),
            popover,
            focus,
            _calendar_observation: calendar_observation,
            _popover_observation: popover_observation,
            _activation_subscription: activation_subscription,
        }
    }

    /// The shared date state used to render Calendar and its day/month controls.
    pub fn calendar(&self) -> &Entity<CalendarState> {
        &self.calendar
    }

    pub fn selection<'a>(&self, cx: &'a App) -> &'a CalendarSelection {
        self.calendar.read(cx).selection()
    }

    pub fn is_open(&self, cx: &App) -> bool {
        self.popover.read(cx).is_open()
    }

    pub fn is_disabled(&self, cx: &App) -> bool {
        self.popover.read(cx).is_disabled()
    }

    /// The stable native Button trigger focus handle.
    pub fn focus_handle(&self) -> &FocusHandle {
        &self.focus
    }

    /// Opens at the selection or retained cursor, using the Calendar focus policy.
    pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.popover.update(cx, |state, cx| state.open(window, cx));
    }

    /// Closes without changing the value. Restores the trigger while the popup
    /// owns focus; outside/Tab dismissal retains the new focus target.
    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.popover.update(cx, |state, cx| state.close(window, cx));
    }

    /// Disables the trigger and calendar, closing an open popup first.
    /// Use this method to coordinate disabled state rather than changing the
    /// nested Calendar independently.
    pub fn set_disabled(&mut self, disabled: bool, window: &mut Window, cx: &mut Context<Self>) {
        self.popover
            .update(cx, |state, cx| state.set_disabled(disabled, window, cx));
        self.calendar
            .update(cx, |state, cx| state.set_disabled(disabled, window, cx));
    }

    /// Replaces the selection mode and value without emitting Change, closing an
    /// open popup first. Invalid, date-disabled, or out-of-bounds selections leave both states
    /// unchanged. An empty selection preserves the Calendar's navigation date.
    pub fn set_selection(
        &mut self,
        selection: CalendarSelection,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let Some(selection) = self.calendar.read(cx).normalized_selection(selection) else {
            return false;
        };
        // Close while Popover still knows its original initial focus. Before
        // first paint, a different month's grid slot is not yet in its tree.
        self.close(window, cx);
        self.calendar
            .update(cx, |state, cx| state.set_selection(selection, window, cx))
    }
}

impl EventEmitter<DatePickerEvent> for DatePickerState {}

/// Reads one typed date for a text field beside a picker.
///
/// Accepts `YYYY-MM-DD` with `-`, `/` or `.` separators, and these
/// case-insensitive English forms relative to `today`: `today`, `tomorrow`,
/// `yesterday`, `in N days` / `in N weeks`, and `N days ago` / `N weeks ago`
/// (singular units too). The library has no clock, so the application supplies
/// `today`. Returns `None` for anything else, including impossible dates. Pass a
/// result to [`DatePickerState::set_selection`], which still applies the
/// Calendar's bounds and disabled-date predicate.
pub fn parse_date_text(text: &str, today: crate::Date) -> Option<crate::Date> {
    let text = text.trim().to_lowercase();
    let words: Vec<&str> = text.split_whitespace().collect();
    let offset = |count: &str, unit: &str| -> Option<jiff::Span> {
        let count: i64 = count.parse().ok()?;
        let days = match unit {
            "day" | "days" => count,
            "week" | "weeks" => count.checked_mul(7)?,
            _ => return None,
        };
        jiff::Span::new().try_days(days).ok()
    };
    match words.as_slice() {
        ["today"] => Some(today),
        ["tomorrow"] => today.tomorrow().ok(),
        ["yesterday"] => today.yesterday().ok(),
        ["in", count, unit] => today.checked_add(offset(count, unit)?).ok(),
        [count, unit, "ago"] => today.checked_sub(offset(count, unit)?).ok(),
        [date] => {
            let parts: Vec<&str> = date.split(['-', '/', '.']).collect();
            let [year, month, day] = parts.as_slice() else {
                return None;
            };
            if year.len() != 4
                || month.is_empty()
                || month.len() > 2
                || day.is_empty()
                || day.len() > 2
            {
                return None;
            }
            crate::Date::new(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?).ok()
        }
        _ => None,
    }
}

/// An unstyled Button trigger and a date-selection popup.
///
/// The application supplies formatted trigger text, the popup surface, month
/// buttons, and the Calendar rendered from [`DatePickerState::calendar`]. Keep
/// using ordinary CalendarDay children; single and complete-range activation
/// close this picker. Partial range and multiple selections remain open.
/// `accessibility_label` names the popup. Name the trigger separately through
/// its builder. Expansion, disabled state, activation, and focus belong to the
/// underlying Popover. Text parsing and trigger formatting belong to the application.
#[derive(IntoElement)]
pub struct DatePicker {
    id: ElementId,
    state: Entity<DatePickerState>,
    trigger: Button,
    content: Option<AnyElement>,
    label: Option<SharedString>,
    anchor: Anchor,
    offset: Pixels,
    style: StyleRefinement,
}

impl DatePicker {
    pub fn new(id: impl Into<ElementId>, state: &Entity<DatePickerState>) -> Self {
        let id = id.into();
        Self {
            trigger: Button::new(id.clone()),
            id,
            state: state.clone(),
            content: None,
            label: None,
            anchor: Anchor::TopLeft,
            offset: px(0.),
            style: StyleRefinement::default(),
        }
    }

    pub fn trigger(mut self, build: impl FnOnce(Button) -> Button) -> Self {
        self.trigger = build(self.trigger);
        self
    }

    pub fn content(mut self, content: impl IntoElement) -> Self {
        self.content = Some(content.into_any_element());
        self
    }

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

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

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

impl Styled for DatePicker {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for DatePicker {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        Popover::new(self.id, &self.state.read(cx).popover)
            .trigger(|_| self.trigger)
            .when_some(self.content, |popover, content| popover.content(content))
            .when_some(self.label, |popover, label| {
                popover.accessibility_label(label)
            })
            .anchor(self.anchor)
            .offset(self.offset)
            .refine_style(&self.style)
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use gpui::{
        InteractiveElement as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
        ParentElement as _, Render, Role, StatefulInteractiveElement as _, TestAppContext,
        VisualTestContext, div,
    };

    use super::*;
    use crate::{Calendar, CalendarDay, Date, Root};

    struct Harness {
        calendar: Entity<CalendarState>,
        picker: Entity<DatePickerState>,
        before: FocusHandle,
        after: FocusHandle,
        show_picker: bool,
        redirect_change: bool,
        changes: Rc<RefCell<Vec<CalendarSelection>>>,
        _subscriptions: Vec<Subscription>,
    }

    impl Render for Harness {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let days = self.calendar.read(cx).days();
            let calendar = Calendar::new("calendar", &self.calendar)
                .accessibility_label("Date")
                .flex()
                .flex_col()
                .child(
                    div().id("weekdays").role(Role::Row).flex().children(
                        ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
                            .into_iter()
                            .enumerate()
                            .map(|(index, label)| {
                                div()
                                    .id(("weekday", index))
                                    .role(Role::ColumnHeader)
                                    .aria_column_index(index)
                                    .w(px(40.))
                                    .h(px(24.))
                                    .child(label)
                            }),
                    ),
                )
                .children(days.chunks(7).enumerate().map(|(index, week)| {
                    div()
                        .id(("week", index))
                        .role(Role::Row)
                        .flex()
                        .children(week.iter().map(|&date| {
                            CalendarDay::new(&self.calendar, date)
                                .debug_selector(move || format!("date-{date}"))
                                .w(px(40.))
                                .h(px(28.))
                                .child(date.day().to_string())
                        }))
                }));
            div()
                .w(px(680.))
                .flex()
                .flex_col()
                .gap(px(8.))
                .child(
                    Button::new("before")
                        .debug_selector(|| "before".into())
                        .track_focus(&self.before)
                        .w(px(120.))
                        .h(px(32.))
                        .child("Before"),
                )
                .when(self.show_picker, |base| {
                    base.child(
                        DatePicker::new("picker", &self.picker)
                            .accessibility_label("Choose a date")
                            .w(px(180.))
                            .offset(px(4.))
                            .trigger(|button| {
                                button
                                    .debug_selector(|| "picker".into())
                                    .accessibility_label("Recording date")
                                    .h(px(32.))
                                    .child("Pick a date")
                            })
                            .content(div().w(px(280.)).child(calendar)),
                    )
                })
                .child(
                    Button::new("after")
                        .debug_selector(|| "after".into())
                        .track_focus(&self.after)
                        .ml(px(400.))
                        .w(px(120.))
                        .h(px(32.))
                        .child("After"),
                )
        }
    }

    fn date(year: i16, month: i8, day: i8) -> Date {
        Date::new(year, month, day).unwrap()
    }

    fn harness(cx: &mut TestAppContext) -> (&mut VisualTestContext, Entity<Harness>) {
        configured_harness(cx, |calendar| calendar)
    }

    fn configured_harness(
        cx: &mut TestAppContext,
        configure: impl FnOnce(CalendarState) -> CalendarState + 'static,
    ) -> (&mut VisualTestContext, Entity<Harness>) {
        cx.update(crate::init);
        let (root, cx) = cx.add_window_view(move |window, cx| {
            let content = cx.new(|cx| {
                let calendar = cx.new(|cx| {
                    configure(
                        CalendarState::new(date(2024, 1, 31), cx)
                            .bounds(date(2024, 1, 1), date(2026, 12, 31))
                            .default_selection(CalendarSelection::Single(Some(date(2024, 1, 31)))),
                    )
                });
                let picker = cx.new(|cx| DatePickerState::new(&calendar, window, cx));
                let subscriptions = vec![
                    cx.observe(&picker, |_, _, cx| cx.notify()),
                    cx.subscribe_in(
                        &picker,
                        window,
                        |this: &mut Harness, picker, event, window, cx| {
                            let DatePickerEvent::Change(selection) = event;
                            let finished = matches!(
                                selection,
                                CalendarSelection::Single(_)
                                    | CalendarSelection::Range { end: Some(_), .. }
                            );
                            assert_eq!(picker.read(cx).is_open(cx), !finished);
                            this.changes.borrow_mut().push(selection.clone());
                            if this.redirect_change {
                                this.after.focus(window, cx);
                            }
                        },
                    ),
                ];
                Harness {
                    calendar,
                    picker,
                    before: cx.focus_handle(),
                    after: cx.focus_handle(),
                    show_picker: true,
                    redirect_change: false,
                    changes: Rc::new(RefCell::new(Vec::new())),
                    _subscriptions: subscriptions,
                }
            });
            Root::new(content, window, cx)
        });
        let view = root
            .read_with(cx, |root, _| root.view().clone())
            .downcast::<Harness>()
            .unwrap();
        cx.update(|window, cx| {
            window.activate_window();
            view.read(cx).before.clone().focus(window, cx);
        });
        settle(cx);
        (cx, view)
    }

    fn settle(cx: &mut VisualTestContext) {
        cx.update(|window, cx| window.draw(cx).clear(cx));
        cx.run_until_parked();
        cx.update(|window, cx| window.draw(cx).clear(cx));
    }

    fn press(cx: &mut VisualTestContext, key: &str) {
        let keystroke =
            cx.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
        cx.simulate_event(KeyDownEvent {
            keystroke: keystroke.clone(),
            is_held: false,
            prefer_character_input: false,
        });
        cx.simulate_event(KeyUpEvent { keystroke });
        settle(cx);
    }

    fn assert_open_at(cx: &mut VisualTestContext, view: &Entity<Harness>, date: Date) {
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(view.picker.read(cx).is_open(cx));
            let calendar = view.calendar.read(cx);
            assert_eq!(calendar.focused_date(), date);
            assert_eq!(calendar.month(), date.first_of_month());
            assert!(calendar.focus_handle().is_focused(window));
        });
    }

    #[gpui::test]
    fn opening_resolves_the_selected_day_and_every_activation_finishes_the_popup(
        cx: &mut TestAppContext,
    ) {
        let (cx, view) = harness(cx);
        press(cx, "tab");
        press(cx, "enter");
        assert_open_at(cx, &view, date(2024, 1, 31));
        press(cx, "pagedown");
        assert_open_at(cx, &view, date(2024, 2, 29));
        press(cx, "escape");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert_eq!(
                view.picker.read(cx).selection(cx),
                &CalendarSelection::Single(Some(date(2024, 1, 31)))
            );
            assert!(view.picker.read(cx).focus_handle().is_focused(window));
        });
        press(cx, "space");
        assert_open_at(cx, &view, date(2024, 1, 31));
        press(cx, "right");
        press(cx, "enter");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert_eq!(
                *view.changes.borrow(),
                [CalendarSelection::Single(Some(date(2024, 2, 1)))]
            );
            assert!(view.picker.read(cx).focus_handle().is_focused(window));
        });

        press(cx, "enter");
        assert_open_at(cx, &view, date(2024, 2, 1));
        press(cx, "space");
        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
        press(cx, "enter");
        let point = cx.debug_bounds("date-2024-02-01").unwrap().center();
        cx.simulate_click(point, Modifiers::default());
        settle(cx);
        cx.update(|_, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert_eq!(
                *view.changes.borrow(),
                [CalendarSelection::Single(Some(date(2024, 2, 1)))]
            );
        });

        view.update(cx, |view, _| view.redirect_change = true);
        press(cx, "enter");
        press(cx, "right");
        press(cx, "enter");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert_eq!(
                *view.changes.borrow(),
                [date(2024, 2, 1), date(2024, 2, 2)]
                    .map(|date| CalendarSelection::Single(Some(date)))
            );
            assert!(
                view.after.is_focused(window),
                "Change subscribers retain their new focus"
            );
        });
    }

    #[gpui::test]
    fn dismissal_disabled_and_unselected_reopening_preserve_their_owners(cx: &mut TestAppContext) {
        let (cx, view) = harness(cx);
        // Resolve and return focus even before the Calendar has ever mounted.
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| {
                picker.open(window, cx);
                picker.close(window, cx);
                assert!(picker.focus_handle().is_focused(window));
                picker.open(window, cx);
                assert!(picker.set_selection(
                    CalendarSelection::Single(Some(date(2024, 2, 20))),
                    window,
                    cx
                ));
                assert!(!picker.is_open(cx));
                assert!(picker.focus_handle().is_focused(window));
            });
        });
        settle(cx);
        press(cx, "enter");
        press(cx, "tab");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert!(view.after.is_focused(window));
        });
        press(cx, "shift-tab");
        press(cx, "space");
        let before = cx.debug_bounds("before").unwrap().center();
        cx.simulate_click(before, Modifiers::default());
        settle(cx);
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert!(view.before.is_focused(window));
            assert!(view.changes.borrow().is_empty());
        });

        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| {
                assert!(picker.set_selection(
                    CalendarSelection::Single(Some(date(2024, 2, 20))),
                    window,
                    cx
                ));
                assert!(!picker.set_selection(
                    CalendarSelection::Single(Some(date(2023, 12, 31))),
                    window,
                    cx
                ));
                assert_eq!(
                    picker.selection(cx),
                    &CalendarSelection::Single(Some(date(2024, 2, 20)))
                );
                assert!(picker.set_selection(CalendarSelection::Single(None), window, cx));
                picker.open(window, cx);
            });
        });
        settle(cx);
        assert_open_at(cx, &view, date(2024, 2, 20));
        press(cx, "pagedown");
        press(cx, "escape");
        press(cx, "enter");
        assert_open_at(cx, &view, date(2024, 3, 20));
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| picker.set_disabled(true, window, cx));
            assert!(picker.read(cx).is_disabled(cx));
            assert!(!picker.read(cx).is_open(cx));
            assert!(picker.read(cx).focus_handle().is_focused(window));
            assert!(view.read(cx).calendar.read(cx).is_disabled());
        });
        settle(cx);
        press(cx, "enter");
        press(cx, "tab");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert!(view.after.is_focused(window));
            assert!(view.changes.borrow().is_empty());
        });

        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| {
                picker.set_disabled(false, window, cx);
                picker.open(window, cx);
            });
        });
        settle(cx);
        view.update(cx, |view, cx| {
            view.show_picker = false;
            cx.notify();
        });
        settle(cx);
        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
    }

    #[gpui::test]
    fn range_picker_retains_partial_selection_and_closes_only_when_complete(
        cx: &mut TestAppContext,
    ) {
        let (cx, view) = harness(cx);
        let start = date(2024, 1, 31);
        let end = date(2024, 2, 2);
        let range = |start, end| CalendarSelection::Range { start, end };
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| {
                assert!(picker.set_selection(range(None, None), window, cx));
                picker.open(window, cx);
            });
        });
        settle(cx);
        press(cx, "enter");
        assert_open_at(cx, &view, start);
        press(cx, "right");
        press(cx, "escape");
        press(cx, "enter");
        assert_open_at(cx, &view, start);
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            assert!(!picker.update(cx, |picker, cx| {
                picker.set_selection(range(None, Some(end)), window, cx)
            }));
            assert!(picker.read(cx).is_open(cx));
            assert_eq!(picker.read(cx).selection(cx), &range(Some(start), None));
        });
        press(cx, "right");
        press(cx, "right");
        press(cx, "space");
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.read(cx);
            assert!(!picker.is_open(cx));
            assert!(picker.focus_handle().is_focused(window));
            assert_eq!(picker.selection(cx), &range(Some(start), Some(end)));
        });
        press(cx, "enter");
        assert_open_at(cx, &view, start);
        press(cx, "enter");
        assert_open_at(cx, &view, start);
        press(cx, "space");
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            assert!(!picker.read(cx).is_open(cx));
            assert_eq!(
                picker.read(cx).selection(cx),
                &range(Some(start), Some(start))
            );
            assert_eq!(
                *view.read(cx).changes.borrow(),
                [
                    range(Some(start), None),
                    range(Some(start), Some(end)),
                    range(Some(start), None),
                    range(Some(start), Some(start)),
                ]
            );
            picker.update(cx, |picker, cx| {
                picker.open(window, cx);
                assert!(picker.set_selection(range(Some(start), Some(end)), window, cx));
                assert!(!picker.is_open(cx));
                assert!(picker.focus_handle().is_focused(window));
            });
        });
    }

    #[gpui::test]
    fn multiple_picker_keeps_toggling_until_dismissal_and_reopens_at_selected_focus(
        cx: &mut TestAppContext,
    ) {
        let (cx, view) = harness(cx);
        let first = date(2024, 1, 31);
        let second = date(2024, 2, 1);
        let third = date(2024, 2, 2);
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| {
                assert!(picker.set_selection(CalendarSelection::Multiple(vec![first]), window, cx));
                picker.open(window, cx);
            });
        });
        settle(cx);
        press(cx, "right");
        press(cx, "enter");
        assert_open_at(cx, &view, second);
        press(cx, "left");
        press(cx, "space");
        assert_open_at(cx, &view, first);
        press(cx, "escape");
        press(cx, "enter");
        assert_open_at(cx, &view, second);
        press(cx, "right");
        press(cx, "enter");
        press(cx, "escape");
        press(cx, "enter");
        assert_open_at(cx, &view, third);
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            picker.update(cx, |picker, cx| picker.set_disabled(true, window, cx));
            assert!(!picker.read(cx).is_open(cx));
            assert_eq!(
                picker.read(cx).selection(cx),
                &CalendarSelection::Multiple(vec![second, third])
            );
            assert_eq!(
                *view.read(cx).changes.borrow(),
                [
                    CalendarSelection::Multiple(vec![first, second]),
                    CalendarSelection::Multiple(vec![second]),
                    CalendarSelection::Multiple(vec![second, third]),
                ]
            );
        });
        settle(cx);
        press(cx, "space");
        cx.update(|_, cx| assert!(!view.read(cx).picker.read(cx).is_open(cx)));
    }

    #[gpui::test]
    fn disabled_date_activation_and_programmatic_rejection_keep_the_popup_open(
        cx: &mut TestAppContext,
    ) {
        let disabled = date(2024, 2, 1);
        let (cx, view) = configured_harness(cx, move |calendar| {
            calendar.disabled_dates(move |date| date == disabled)
        });
        press(cx, "tab");
        press(cx, "enter");
        press(cx, "right");
        assert_open_at(cx, &view, disabled);
        press(cx, "enter");
        assert_open_at(cx, &view, disabled);
        cx.update(|window, cx| {
            let picker = view.read(cx).picker.clone();
            assert!(!picker.update(cx, |picker, cx| picker.set_selection(
                CalendarSelection::Single(Some(disabled)),
                window,
                cx
            )));
            assert!(view.read(cx).changes.borrow().is_empty());
        });
        settle(cx);
        assert_open_at(cx, &view, disabled);
        press(cx, "right");
        press(cx, "enter");
        cx.update(|window, cx| {
            let view = view.read(cx);
            assert!(!view.picker.read(cx).is_open(cx));
            assert!(view.picker.read(cx).focus_handle().is_focused(window));
            assert_eq!(
                *view.changes.borrow(),
                [CalendarSelection::Single(Some(date(2024, 2, 2)))]
            );
        });
    }

    #[test]
    fn typed_dates_accept_iso_and_relative_english_forms() {
        let today = Date::constant(2026, 11, 20);
        let date = |y, m, d| Date::new(y, m, d).ok();
        for (text, expected) in [
            ("2026-12-01", date(2026, 12, 1)),
            (" 2026/1/5 ", date(2026, 1, 5)),
            ("2026.02.28", date(2026, 2, 28)),
            ("Today", Some(today)),
            ("tomorrow", date(2026, 11, 21)),
            ("yesterday", date(2026, 11, 19)),
            ("in 2 days", date(2026, 11, 22)),
            ("In 1 week", date(2026, 11, 27)),
            ("3 days ago", date(2026, 11, 17)),
            ("2 weeks ago", date(2026, 11, 6)),
            ("2026-02-30", None),
            ("26-02-03", None),
            ("in two days", None),
            ("next friday", None),
            ("", None),
        ] {
            assert_eq!(parse_date_text(text, today), expected, "{text:?}");
        }
    }
}