Skip to main content

gpui_material_extras/date_time/date/
state.rs

1use std::{cell::RefCell, ops::RangeInclusive, rc::Rc, sync::Arc};
2
3use gpui::{
4    App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Focusable as _,
5    SharedString, WeakFocusHandle, Window,
6};
7use gpui_base::{CalendarState, Date as BaseDate, Matcher};
8use gpui_material_components::{DialogCloseReason, DialogState, TextFieldState};
9use gpui_material_theme::Direction;
10use jiff::{
11    ToSpan as _,
12    civil::{Date, Weekday},
13};
14
15use super::types::{
16    DateFilter, DateFormatter, DatePickerDisplayMode, DatePickerDraft, DatePickerLocale,
17    DatePickerVariant, DateSelection, YearFilter, complete,
18};
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub(super) enum DateError {
22    Invalid,
23    Disabled,
24    Order,
25}
26
27impl DateError {
28    pub(super) fn message(self) -> &'static str {
29        match self {
30            Self::Invalid => "Enter a valid date",
31            Self::Disabled => "Choose an available date",
32            Self::Order => "End date must be on or after start date",
33        }
34    }
35}
36
37#[derive(Clone)]
38pub(super) struct DateLimits {
39    pub(super) bounds: RangeInclusive<Date>,
40    pub(super) disabled: DateFilter,
41    pub(super) disabled_years: YearFilter,
42}
43
44impl DateLimits {
45    pub(super) fn accepts(&self, date: Date) -> bool {
46        self.bounds.contains(&date)
47            && self.accepts_year(i32::from(date.year()))
48            && !(self.disabled)(date)
49    }
50
51    pub(super) fn accepts_year(&self, year: i32) -> bool {
52        (i32::from(self.bounds.start().year())..=i32::from(self.bounds.end().year()))
53            .contains(&year)
54            && !(self.disabled_years)(year)
55    }
56
57    pub(super) fn accepts_draft(&self, draft: BaseDate) -> bool {
58        let start = draft.start();
59        let end = draft.end();
60        start.is_none_or(|date| self.accepts(date))
61            && end.is_none_or(|date| start.is_some_and(|start| start <= date) && self.accepts(date))
62    }
63}
64
65pub(super) fn first_of_month(date: Date) -> Date {
66    date.first_of_month()
67}
68
69pub(super) fn calendar_start(month: Date, first_day: Weekday) -> Date {
70    let offset = (i32::from(month.weekday().to_monday_zero_offset()) + 7
71        - i32::from(first_day.to_monday_zero_offset()))
72        % 7;
73    month.checked_sub(offset.days()).unwrap_or(month)
74}
75
76pub(super) fn parse_selection(
77    start: &str,
78    end: Option<&str>,
79    locale: &DatePickerLocale,
80    limits: &DateLimits,
81) -> Result<DateSelection, DateError> {
82    let parse = |text: &str| {
83        let date = (locale.parse)(text.trim()).ok_or(DateError::Invalid)?;
84        if !limits.accepts(date) {
85            return Err(DateError::Disabled);
86        }
87        Ok(date)
88    };
89    let start = parse(start)?;
90    let Some(end) = end.map(parse).transpose()? else {
91        return Ok(DateSelection::Single(Some(start)));
92    };
93    if start > end {
94        return Err(DateError::Order);
95    }
96    Ok(DateSelection::Range(Some((start, end))))
97}
98
99pub(super) fn parse_docked_range(
100    text: &str,
101    locale: &DatePickerLocale,
102    limits: &DateLimits,
103) -> Option<DateSelection> {
104    text.split_once(" – ")
105        .or_else(|| text.split_once(" - "))
106        .and_then(|(start, end)| parse_selection(start, Some(end), locale, limits).ok())
107}
108
109pub(super) struct MonthCache {
110    month: Date,
111    day_formatter: DateFormatter,
112    month_formatter: DateFormatter,
113    pub(super) month_label: SharedString,
114    pub(super) day_ids: Vec<SharedString>,
115    pub(super) day_labels: Vec<SharedString>,
116}
117
118impl MonthCache {
119    fn matches(&self, month: Date, locale: &DatePickerLocale) -> bool {
120        self.month == month
121            && Rc::ptr_eq(&self.day_formatter, &locale.day)
122            && Rc::ptr_eq(&self.month_formatter, &locale.month)
123    }
124
125    fn build(month: Date, locale: &DatePickerLocale) -> Self {
126        let mut day_ids = Vec::with_capacity(31);
127        let mut day_labels = Vec::with_capacity(31);
128        let mut current = month;
129        while current.month() == month.month() {
130            day_ids.push(SharedString::from(format!("day-{current}")));
131            day_labels.push((locale.day)(current));
132            let Ok(next) = current.tomorrow() else {
133                break;
134            };
135            current = next;
136        }
137        Self {
138            month,
139            day_formatter: locale.day.clone(),
140            month_formatter: locale.month.clone(),
141            month_label: (locale.month)(month),
142            day_ids,
143            day_labels,
144        }
145    }
146}
147
148/// Owns the Base calendar, input editors, and draft focus. The application owns
149/// the value passed to the picker. Every open copies that value into the draft.
150pub struct DatePickerState {
151    pub(super) calendar: Entity<CalendarState>,
152    pub(super) start: Entity<TextFieldState>,
153    pub(super) end: Entity<TextFieldState>,
154    pub(super) anchor: Entity<TextFieldState>,
155    pub(super) anchor_value: Option<SharedString>,
156    pub(super) dialog: Entity<DialogState>,
157    pub(super) trigger: FocusHandle,
158    pub(super) docked: FocusHandle,
159    pub(super) day: FocusHandle,
160    pub(super) cursor: Date,
161    pub(super) docked_open: bool,
162    pub(super) docked_generation: u64,
163    docked_previous: Option<WeakFocusHandle>,
164    docked_reason: Option<DialogCloseReason>,
165    variant: DatePickerVariant,
166    pub(super) locale: DatePickerLocale,
167    pub(super) locale_initialized: bool,
168    month_cache: RefCell<Option<MonthCache>>,
169    initial_month: Option<Date>,
170    pub(super) year_page: Option<i32>,
171    pub(super) input_mode: bool,
172    pub(super) input_attempted: bool,
173    pub(super) limits: DateLimits,
174}
175
176impl DatePickerState {
177    /// Creates a new date picker state with default bounds (`1900-01-01` through `2100-12-31`).
178    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
179        let limits = DateLimits {
180            bounds: Date::constant(1900, 1, 1)..=Date::constant(2100, 12, 31),
181            disabled: Arc::new(|_| false),
182            disabled_years: Arc::new(|_| false),
183        };
184        let calendar = cx.new(|cx| CalendarState::new(window, cx));
185        let cursor = calendar.read(cx).today();
186        let start = cx.new(|cx| TextFieldState::new(window, cx));
187        let end = cx.new(|cx| TextFieldState::new(window, cx));
188        let anchor = cx.new(|cx| TextFieldState::new(window, cx));
189        cx.observe(&anchor, |_, _, cx| cx.notify()).detach();
190        let dialog = cx.new(DialogState::new);
191        cx.observe(&start, |_, _, cx| cx.notify()).detach();
192        cx.observe(&end, |_, _, cx| cx.notify()).detach();
193        cx.observe(&dialog, |_, _, cx| cx.notify()).detach();
194        Self {
195            calendar,
196            start,
197            end,
198            anchor,
199            anchor_value: None,
200            dialog,
201            trigger: cx.focus_handle(),
202            docked: cx.focus_handle(),
203            day: cx.focus_handle(),
204            cursor,
205            docked_open: false,
206            docked_generation: 0,
207            docked_previous: None,
208            docked_reason: None,
209            variant: DatePickerVariant::default(),
210            locale: DatePickerLocale::default(),
211            locale_initialized: false,
212            month_cache: RefCell::new(None),
213            initial_month: None,
214            year_page: None,
215            input_mode: false,
216            input_attempted: false,
217            limits,
218        }
219    }
220
221    /// Restricts the displayed months and selectable dates. A reversed range
222    /// is ordered before it is applied on the next open.
223    pub fn date_bounds(mut self, bounds: RangeInclusive<Date>) -> Self {
224        let (min, max) = bounds.into_inner();
225        self.limits.bounds = min.min(max)..=min.max(max);
226        self.cursor = self
227            .cursor
228            .clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
229        self
230    }
231
232    /// Disables individual days and range endpoints.
233    pub fn disabled_dates(
234        mut self,
235        disabled: impl Fn(Date) -> bool + Send + Sync + 'static,
236    ) -> Self {
237        self.limits.disabled = Arc::new(disabled);
238        self
239    }
240
241    /// Selects which month is initially displayed on each open.
242    pub fn initial_month(mut self, date: Date) -> Self {
243        self.initial_month = Some(date);
244        self.cursor = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
245        self
246    }
247
248    /// Marks every date in matching years unavailable, independently of day filtering.
249    pub fn disabled_years(
250        mut self,
251        disabled: impl Fn(i32) -> bool + Send + Sync + 'static,
252    ) -> Self {
253        self.limits.disabled_years = Arc::new(disabled);
254        self
255    }
256
257    /// Returns the retained focus handle of the built-in picker trigger.
258    pub fn trigger_focus(&self) -> &FocusHandle {
259        &self.trigger
260    }
261
262    /// Returns whether the docked popup or modal dialog is currently open.
263    pub fn is_open(&self, cx: &App) -> bool {
264        self.docked_open || self.dialog.read(cx).is_open()
265    }
266
267    /// Returns the reason the picker was most recently closed, if any.
268    pub fn last_close_reason(&self, cx: &App) -> Option<DialogCloseReason> {
269        if self.variant == DatePickerVariant::Docked {
270            self.docked_reason
271        } else {
272            self.dialog.read(cx).last_close_reason()
273        }
274    }
275
276    /// Updates presentation and cursor without changing the draft.
277    pub fn set_displayed_month(&mut self, date: Date, cx: &mut Context<Self>) {
278        let clamped = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
279        let month_changed = self.show_month(clamped, cx);
280        let changed = self.cursor != clamped || self.year_page.take().is_some() || month_changed;
281        self.cursor = clamped;
282        if changed {
283            cx.notify();
284        }
285    }
286
287    /// Returns the first day of the month currently shown by the calendar cursor.
288    pub fn displayed_month(&self) -> Date {
289        first_of_month(self.cursor)
290    }
291
292    pub(super) fn month_cache(
293        &self,
294        month: Date,
295        locale: &DatePickerLocale,
296    ) -> std::cell::Ref<'_, MonthCache> {
297        {
298            let mut cache = self.month_cache.borrow_mut();
299            if cache
300                .as_ref()
301                .is_none_or(|cached| !cached.matches(month, locale))
302            {
303                *cache = Some(MonthCache::build(month, locale));
304            }
305        }
306        std::cell::Ref::map(self.month_cache.borrow(), |cache| {
307            cache.as_ref().expect("month cache initialized")
308        })
309    }
310
311    /// Reads the current in-progress draft from the active display mode.
312    pub fn draft(&self, cx: &App) -> DatePickerDraft {
313        if self.input_mode {
314            self.input_draft(cx).into()
315        } else {
316            self.calendar.read(cx).date().into()
317        }
318    }
319
320    /// Returns the retained start editor and the end editor for a range draft.
321    pub fn input_editors(
322        &self,
323        cx: &App,
324    ) -> (&Entity<TextFieldState>, Option<&Entity<TextFieldState>>) {
325        let range = !self.calendar.read(cx).date().is_single();
326        (&self.start, range.then_some(&self.end))
327    }
328
329    /// Applies a valid draft, including empty values and a range with only a start.
330    pub fn set_draft(
331        &mut self,
332        draft: DatePickerDraft,
333        window: &mut Window,
334        cx: &mut Context<Self>,
335    ) -> bool {
336        let draft: BaseDate = draft.into();
337        if !self.limits.accepts_draft(draft) {
338            return false;
339        }
340        self.apply_draft(draft, cx);
341        if let Some(active) = draft.start() {
342            self.cursor = active.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
343            self.year_page = None;
344        }
345        self.show_month(self.cursor, cx);
346        self.reset_input(draft, &self.locale, window, cx);
347        self.input_attempted = false;
348        cx.notify();
349        true
350    }
351
352    /// Returns the active display mode (`Calendar` or `Input`).
353    pub fn display_mode(&self) -> DatePickerDisplayMode {
354        if self.input_mode {
355            DatePickerDisplayMode::Input
356        } else {
357            DatePickerDisplayMode::Calendar
358        }
359    }
360
361    /// Changes display mode after any active IME composition has finished.
362    pub fn set_display_mode(
363        &mut self,
364        mode: DatePickerDisplayMode,
365        window: &mut Window,
366        cx: &mut Context<Self>,
367    ) -> bool {
368        let input = mode == DatePickerDisplayMode::Input;
369        if self.input_mode == input {
370            return true;
371        }
372        if self.input_mode && self.input_composing(window, cx) {
373            return false;
374        }
375        self.input_attempted = false;
376        if self.input_mode {
377            let draft = self.input_draft(cx);
378            self.apply_draft(draft, cx);
379            if let Some(day) = draft.start() {
380                self.set_displayed_month(day, cx);
381            }
382        } else {
383            self.reset_input(self.calendar.read(cx).date(), &self.locale, window, cx);
384        }
385        self.input_mode = input;
386        self.year_page = None;
387        if self.is_open(cx) {
388            self.default_focus(cx).focus(window, cx);
389        }
390        cx.notify();
391        true
392    }
393
394    fn default_focus(&self, cx: &App) -> FocusHandle {
395        if self.input_mode {
396            self.start.read(cx).focus_handle(cx)
397        } else {
398            self.day.clone()
399        }
400    }
401
402    pub(super) fn input_composing(&self, window: &mut Window, cx: &mut App) -> bool {
403        [&self.start, &self.end].into_iter().any(|field| {
404            field.update(cx, |field, cx| {
405                field.marked_text_range(window, cx).is_some()
406            })
407        })
408    }
409
410    fn apply_draft(&self, draft: BaseDate, cx: &mut Context<Self>) {
411        let limits = self.limits.clone();
412        self.calendar.update(cx, |calendar, _| {
413            calendar.set_disabled_matcher_shared(Some(Rc::new(Matcher::custom(move |date| {
414                !limits.accepts(*date)
415            }))));
416            calendar.apply_date(draft);
417        });
418    }
419
420    fn show_month(&self, date: Date, cx: &mut Context<Self>) -> bool {
421        self.calendar.update(cx, |calendar, _| {
422            let year = i32::from(date.year());
423            let month = date.month() as u32;
424            let changed = calendar.offset_year_month(0) != (year, month);
425            if changed {
426                calendar.select_year(year);
427                calendar.select_month(month as u8);
428            }
429            changed
430        })
431    }
432
433    /// Opens a picker rendered by a caller-owned trigger and copies the committed value.
434    pub fn open(
435        &mut self,
436        value: DateSelection,
437        variant: DatePickerVariant,
438        locale: &DatePickerLocale,
439        window: &mut Window,
440        cx: &mut Context<Self>,
441    ) {
442        if self.is_open(cx) {
443            return;
444        }
445        self.variant = variant;
446        self.locale = locale.clone();
447        self.locale_initialized = true;
448        let draft = value.draft();
449        let draft = if self.limits.accepts_draft(draft) {
450            draft
451        } else if draft.is_single() {
452            BaseDate::Single(None)
453        } else {
454            BaseDate::Range(None, None)
455        };
456        self.apply_draft(draft, cx);
457        let today = self.calendar.read(cx).today();
458        self.set_displayed_month(self.initial_month.or(draft.start()).unwrap_or(today), cx);
459        self.reset_input(draft, locale, window, cx);
460        self.input_mode = variant == DatePickerVariant::ModalInput;
461        self.input_attempted = false;
462        if variant == DatePickerVariant::Docked {
463            self.docked_previous = window.focused(cx).map(|focus| focus.downgrade());
464            self.docked_open = true;
465            self.docked_generation = self.docked_generation.wrapping_add(1);
466        } else {
467            self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
468        }
469        self.default_focus(cx).focus(window, cx);
470        cx.notify();
471    }
472
473    /// Closes either presentation and restores focus when the picker still owns it.
474    pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
475        if self.docked_open {
476            self.dismiss_docked(DialogCloseReason::Programmatic, window, cx);
477        } else {
478            self.dialog
479                .update(cx, |dialog, cx| dialog.close(window, cx));
480        }
481    }
482
483    pub(super) fn reset_input(
484        &self,
485        draft: BaseDate,
486        locale: &DatePickerLocale,
487        window: &mut Window,
488        cx: &mut Context<Self>,
489    ) {
490        let format = |date: Option<Date>| {
491            date.map_or_else(SharedString::default, |date| (locale.format)(date))
492        };
493        self.start.update(cx, |field, cx| {
494            field.set_value(format(draft.start()), window, cx)
495        });
496        self.end.update(cx, |field, cx| {
497            field.set_value(format(draft.end()), window, cx)
498        });
499    }
500
501    pub(super) fn input_value(
502        &self,
503        locale: &DatePickerLocale,
504        cx: &App,
505    ) -> Result<DateSelection, DateError> {
506        let start = self.start.read(cx).value();
507        let end = self.end.read(cx).value();
508        let range = !self.calendar.read(cx).date().is_single();
509        parse_selection(&start, range.then_some(end.as_ref()), locale, &self.limits)
510    }
511
512    fn input_draft(&self, cx: &App) -> BaseDate {
513        let parse = |field: &Entity<TextFieldState>| {
514            let text = field.read(cx).value();
515            (self.locale.parse)(text.trim()).filter(|date| self.limits.accepts(*date))
516        };
517        let start = parse(&self.start);
518        if self.calendar.read(cx).date().is_single() {
519            return BaseDate::Single(start);
520        }
521        let end = parse(&self.end).filter(|end| start.is_some_and(|start| start <= *end));
522        BaseDate::Range(start, end)
523    }
524
525    pub(super) fn dismiss_docked(
526        &mut self,
527        reason: DialogCloseReason,
528        window: &mut Window,
529        cx: &mut Context<Self>,
530    ) -> bool {
531        if !self.docked_open {
532            return false;
533        }
534        self.docked_open = false;
535        self.docked_reason = Some(reason);
536        let previous = self.docked_previous.take();
537        if self.docked.contains_focused(window, cx) || self.docked.is_focused(window) {
538            if let Some(focus) = previous.and_then(|focus| focus.upgrade()) {
539                focus.focus(window, cx);
540            } else {
541                window.blur(cx);
542            }
543        }
544        cx.notify();
545        true
546    }
547
548    pub(super) fn select_day(
549        &mut self,
550        date: Date,
551        cx: &mut Context<Self>,
552    ) -> Option<DateSelection> {
553        if !self.limits.accepts(date) {
554            return None;
555        }
556        self.cursor = date;
557        let result = self.calendar.update(cx, |calendar, _| {
558            calendar.select_date(date);
559            complete(calendar.date())
560        });
561        // Base owns the range transition. Keep the second endpoint's month
562        // visible when completing a range across two months.
563        self.show_month(date, cx);
564        self.input_attempted = false;
565        cx.notify();
566        result
567    }
568
569    pub(super) fn navigate(
570        &mut self,
571        key: &str,
572        control: bool,
573        direction: Direction,
574        first_day: Weekday,
575        cx: &mut Context<Self>,
576    ) -> bool {
577        let rtl = direction == Direction::Rtl;
578        let offset = (i32::from(self.cursor.weekday().to_monday_zero_offset()) + 7
579            - i32::from(first_day.to_monday_zero_offset()))
580            % 7;
581        let candidate = match key {
582            "left" | "right" => {
583                if (key == "left") != rtl {
584                    self.cursor.yesterday().ok()
585                } else {
586                    self.cursor.tomorrow().ok()
587                }
588            }
589            "up" => self.cursor.checked_sub(7.days()).ok(),
590            "down" => self.cursor.checked_add(7.days()).ok(),
591            "home" => self.cursor.checked_sub(offset.days()).ok(),
592            "end" => self.cursor.checked_add((6 - offset).days()).ok(),
593            "pageup" => self
594                .cursor
595                .checked_sub(if control { 12.months() } else { 1.month() })
596                .ok(),
597            "pagedown" => self
598                .cursor
599                .checked_add(if control { 12.months() } else { 1.month() })
600                .ok(),
601            _ => return false,
602        };
603        if let Some(date) = candidate {
604            let clamped = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
605            let month_changed = self.show_month(clamped, cx);
606            if self.cursor != clamped || month_changed {
607                self.cursor = clamped;
608                cx.notify();
609            }
610        }
611        true
612    }
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    fn parse_dmy(text: &str) -> Option<Date> {
620        let mut parts = text.split('/');
621        let day: i8 = parts.next()?.parse().ok()?;
622        let month: i8 = parts.next()?.parse().ok()?;
623        let year: i16 = parts.next()?.parse().ok()?;
624        if parts.next().is_some() {
625            return None;
626        }
627        Date::new(year, month, day).ok()
628    }
629
630    #[test]
631    fn local_date_parsing_rejects_invalid_disabled_and_reversed_endpoints() {
632        let first = Date::constant(2024, 2, 1);
633        let last = Date::constant(2024, 2, 29);
634        let locale = DatePickerLocale::default().input_format(
635            |date| format!("{:02}/{:02}/{:04}", date.day(), date.month(), date.year()).into(),
636            parse_dmy,
637        );
638        let limits = DateLimits {
639            bounds: first..=last,
640            disabled: Arc::new(|date| date.day() == 10),
641            disabled_years: Arc::new(|_| false),
642        };
643        assert_eq!(
644            parse_selection(" 29/02/2024 ", None, &locale, &limits),
645            Ok(DateSelection::Single(Some(last)))
646        );
647        assert_eq!(
648            parse_selection("30/02/2024", None, &locale, &limits),
649            Err(DateError::Invalid)
650        );
651        assert_eq!(
652            parse_selection("01/03/2024", None, &locale, &limits),
653            Err(DateError::Disabled)
654        );
655        assert_eq!(
656            parse_selection("01/02/2024", Some("10/02/2024"), &locale, &limits),
657            Err(DateError::Disabled)
658        );
659        assert_eq!(
660            parse_selection("29/02/2024", Some("01/02/2024"), &locale, &limits),
661            Err(DateError::Order)
662        );
663        assert_eq!(
664            parse_selection("01/02/2024", Some("29/02/2024"), &locale, &limits),
665            Ok(DateSelection::Range(Some((first, last))))
666        );
667    }
668
669    #[test]
670    fn docked_range_parsing_accepts_ascii_hyphen_and_unicode_en_dash() {
671        let start = Date::constant(2026, 6, 10);
672        let end = Date::constant(2026, 6, 20);
673        let locale = DatePickerLocale::default();
674        let limits = DateLimits {
675            bounds: Date::constant(2026, 1, 1)..=Date::constant(2026, 12, 31),
676            disabled: Arc::new(|_| false),
677            disabled_years: Arc::new(|_| false),
678        };
679        assert_eq!(
680            parse_docked_range("2026-06-10 – 2026-06-20", &locale, &limits),
681            Some(DateSelection::Range(Some((start, end))))
682        );
683        assert_eq!(
684            parse_docked_range("2026-06-10 - 2026-06-20", &locale, &limits),
685            Some(DateSelection::Range(Some((start, end))))
686        );
687        assert_eq!(
688            parse_docked_range("2026-06-20 - 2026-06-10", &locale, &limits),
689            None
690        );
691    }
692
693    #[test]
694    fn jiff_date_bounds_and_default_locale_formatting() {
695        let locale = DatePickerLocale::default();
696        let date = Date::constant(2026, 6, 12);
697        assert_eq!((locale.format)(date).as_ref(), "2026-06-12");
698        assert_eq!((locale.parse)("2026-06-12"), Some(date));
699        assert_eq!((locale.parse)("2026-02-30"), None);
700        assert_eq!((locale.month)(date).as_ref(), "June 2026");
701        assert_eq!((locale.day)(date).as_ref(), "Friday, June 12, 2026");
702        assert_eq!((locale.weekday)(Weekday::Sunday).as_ref(), "Sun");
703        assert_eq!(first_of_month(date), Date::constant(2026, 6, 1));
704        assert_eq!(
705            calendar_start(Date::constant(2026, 6, 1), Weekday::Sunday),
706            Date::constant(2026, 5, 31)
707        );
708        assert_eq!(
709            calendar_start(Date::constant(2026, 6, 1), Weekday::Monday),
710            Date::constant(2026, 6, 1)
711        );
712    }
713
714    #[cfg(feature = "test-support")]
715    #[gpui::test]
716    fn set_draft_syncs_cursor_month_and_date_picker_on_closed_fires(cx: &mut gpui::TestAppContext) {
717        use std::cell::RefCell;
718
719        use gpui::{IntoElement, Render, WindowOptions};
720        use gpui_material_foundation::MaterialRoot;
721        use gpui_material_theme::MaterialTheme;
722
723        use crate::date_time::date::DatePicker;
724
725        struct Fixture {
726            state: Entity<DatePickerState>,
727            closed: Rc<RefCell<Vec<DialogCloseReason>>>,
728        }
729
730        impl Render for Fixture {
731            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
732                let closed = self.closed.clone();
733                DatePicker::new(
734                    "draft-sync-picker",
735                    "Pick date",
736                    &self.state,
737                    DateSelection::Single(Some(Date::constant(2026, 6, 12))),
738                )
739                .variant(DatePickerVariant::Docked)
740                .on_closed(move |reason, _, _| closed.borrow_mut().push(reason))
741            }
742        }
743
744        let closed = Rc::new(RefCell::new(Vec::new()));
745        let mut state = None;
746        let window: gpui::AnyWindowHandle = cx
747            .update(|cx| {
748                MaterialRoot::init(MaterialTheme::default(), cx);
749                gpui_material_components::init_components(cx);
750                cx.set_reduce_motion(true);
751                MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
752                    let picker = cx.new(|cx| {
753                        DatePickerState::new(window, cx)
754                            .date_bounds(Date::constant(2024, 1, 1)..=Date::constant(2028, 12, 31))
755                            .initial_month(Date::constant(2026, 6, 1))
756                    });
757                    state = Some(picker.clone());
758                    cx.new(|cx| {
759                        cx.observe(&picker, |_, _, cx| cx.notify()).detach();
760                        Fixture {
761                            state: picker,
762                            closed: closed.clone(),
763                        }
764                    })
765                })
766                .unwrap()
767            })
768            .into();
769        let state = state.unwrap();
770
771        cx.update_window(window, |_, window, cx| {
772            state.update(cx, |picker, cx| {
773                assert_eq!(picker.displayed_month(), Date::constant(2026, 6, 1));
774                assert!(picker.set_draft(
775                    DatePickerDraft::Single(Some(Date::constant(2027, 10, 15))),
776                    window,
777                    cx,
778                ));
779                assert_eq!(picker.displayed_month(), Date::constant(2027, 10, 1));
780                picker.open(
781                    DateSelection::Single(Some(Date::constant(2026, 6, 12))),
782                    DatePickerVariant::Docked,
783                    &DatePickerLocale::default(),
784                    window,
785                    cx,
786                );
787            });
788            window.draw(cx).clear(cx);
789        })
790        .unwrap();
791        cx.run_until_parked();
792
793        cx.simulate_keystrokes(window, "escape");
794        cx.update_window(window, |_, window, cx| {
795            window.draw(cx).clear(cx);
796            assert!(!state.read(cx).is_open(cx));
797        })
798        .unwrap();
799        assert_eq!(*closed.borrow(), [DialogCloseReason::Escape]);
800    }
801}