Skip to main content

gpui_material_extras/date_time/
date.rs

1use std::{cell::Cell, rc::Rc, sync::Arc};
2
3use gpui::{
4    Anchor, AnyElement, App, Bounds, ElementId, Entity, EntityInputHandler as _, FocusHandle,
5    Focusable as _, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, Pixels,
6    RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Styled as _, Window, canvas,
7    div, prelude::FluentBuilder as _, px,
8};
9use gpui_base::{Date, Popup, TestSupportExt as _};
10use gpui_material_components::{
11    Button, ButtonVariant, Dialog, DialogAction, DialogCloseReason, DialogColors, DialogProperties,
12    DialogVariant, Icon, IconButton, IconName, Text, TextField, TextFieldColors, TextFieldState,
13    TextFieldVariant,
14};
15use gpui_material_foundation::{Surface, ThemeScope, current_material_theme, logical_anchor};
16use gpui_material_theme::{ColorRole, Elevation, TypeRole};
17
18use super::{Confirm, NaiveDate, Weekday, status};
19
20mod calendar;
21mod state;
22
23pub use state::DatePickerState;
24use state::parse_selection;
25
26/// A committed picker value. The empty variants preserve the selection kind.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum DateSelection {
29    /// A single-date selection, or `None` when cleared.
30    Single(Option<NaiveDate>),
31    /// An inclusive start-and-end date range, or `None` when cleared.
32    Range(Option<(NaiveDate, NaiveDate)>),
33}
34
35impl DateSelection {
36    fn draft(self) -> Date {
37        match self {
38            Self::Single(value) => Date::Single(value),
39            Self::Range(Some((start, end))) => Date::Range(Some(start), Some(end)),
40            Self::Range(None) => Date::Range(None, None),
41        }
42    }
43}
44
45fn complete(draft: Date) -> Option<DateSelection> {
46    match draft {
47        Date::Single(Some(date)) => Some(DateSelection::Single(Some(date))),
48        Date::Range(Some(start), Some(end)) if start <= end => {
49            Some(DateSelection::Range(Some((start, end))))
50        }
51        _ => None,
52    }
53}
54
55/// Presentation style of a [`DatePicker`].
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57pub enum DatePickerVariant {
58    /// Anchors an inline text field with a popup calendar beneath it.
59    Docked,
60    /// Opens a centered modal dialog starting in calendar mode.
61    #[default]
62    Modal,
63    /// Opens a centered modal dialog starting in text-input mode.
64    ModalInput,
65    /// Uses a full-screen dialog in compact windows.
66    FullScreen,
67}
68
69/// A draft can retain the first endpoint before the second is chosen.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum DatePickerDraft {
72    /// Draft for a single-date picker.
73    Single(Option<NaiveDate>),
74    /// Draft for a date-range picker with optional start and end endpoints.
75    Range(Option<NaiveDate>, Option<NaiveDate>),
76}
77
78impl DatePickerDraft {
79    /// Returns a complete candidate selection, when the draft has all its dates.
80    pub fn selection(self) -> Option<DateSelection> {
81        complete(self.into())
82    }
83}
84
85impl From<DateSelection> for DatePickerDraft {
86    fn from(value: DateSelection) -> Self {
87        value.draft().into()
88    }
89}
90
91impl From<Date> for DatePickerDraft {
92    fn from(date: Date) -> Self {
93        match date {
94            Date::Single(value) => Self::Single(value),
95            Date::Range(start, end) => Self::Range(start, end),
96        }
97    }
98}
99
100impl From<DatePickerDraft> for Date {
101    fn from(draft: DatePickerDraft) -> Self {
102        match draft {
103            DatePickerDraft::Single(value) => Self::Single(value),
104            DatePickerDraft::Range(start, end) => Self::Range(start, end),
105        }
106    }
107}
108
109/// The visible editor in a date picker.
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub enum DatePickerDisplayMode {
112    /// Interactive month grid and year selector.
113    #[default]
114    Calendar,
115    /// Direct text-field date entry.
116    Input,
117}
118
119/// Local date picker and editor colors. Unset values use the active Material theme.
120#[derive(Clone, Copy, Debug, Default)]
121pub struct DatePickerColors {
122    /// Background color of the picker surface or dialog container.
123    pub container: Option<Hsla>,
124    /// Text color of the picker title.
125    pub title: Option<Hsla>,
126    /// Text color of the selected-date headline.
127    pub headline: Option<Hsla>,
128    /// Text color of weekday column headers.
129    pub weekday: Option<Hsla>,
130    /// Text color of month and year subheadings.
131    pub subheading: Option<Hsla>,
132    /// Icon and label color of month/year navigation controls.
133    pub navigation: Option<Hsla>,
134    /// Text color of unselected year items.
135    pub year: Option<Hsla>,
136    /// Text color of the current calendar year item.
137    pub current_year: Option<Hsla>,
138    /// Text color of disabled year items.
139    pub disabled_year: Option<Hsla>,
140    /// Text color of the selected year item.
141    pub selected_year: Option<Hsla>,
142    /// Container fill color behind the selected year item.
143    pub selected_year_container: Option<Hsla>,
144    /// Text color of a selected year item that is disabled.
145    pub disabled_selected_year: Option<Hsla>,
146    /// Container fill color behind a disabled selected year item.
147    pub disabled_selected_year_container: Option<Hsla>,
148    /// Text color of unselected enabled day cells.
149    pub day: Option<Hsla>,
150    /// Text color of disabled day cells.
151    pub disabled_day: Option<Hsla>,
152    /// Text color of selected day endpoints.
153    pub selected_day: Option<Hsla>,
154    /// Container fill color behind selected day endpoints.
155    pub selected_day_container: Option<Hsla>,
156    /// Text color of a selected day that is disabled.
157    pub disabled_selected_day: Option<Hsla>,
158    /// Container fill color behind a disabled selected day.
159    pub disabled_selected_day_container: Option<Hsla>,
160    /// Text color of today's date when not selected.
161    pub today: Option<Hsla>,
162    /// Outline color drawn around today's date.
163    pub today_outline: Option<Hsla>,
164    /// Text color of intermediate days inside a selected range.
165    pub range_day: Option<Hsla>,
166    /// Background fill color connecting intermediate days in a selected range.
167    pub range_container: Option<Hsla>,
168    /// Focus ring outline color for keyboard navigation.
169    pub focus_outline: Option<Hsla>,
170    /// Color overrides applied to the date text input fields.
171    pub input: Option<TextFieldColors>,
172}
173
174type DateFormatter = Rc<dyn Fn(NaiveDate) -> SharedString>;
175type DateParser = Rc<dyn Fn(&str) -> Option<NaiveDate>>;
176type WeekdayFormatter = Rc<dyn Fn(Weekday) -> SharedString>;
177type DateFilter = Arc<dyn Fn(NaiveDate) -> bool + Send + Sync>;
178type YearFilter = Arc<dyn Fn(i32) -> bool + Send + Sync>;
179type OnClose = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App)>;
180type DismissRequest = Rc<dyn Fn(DialogCloseReason, &mut Window, &mut App) -> bool>;
181type CustomAnchor = Box<dyn FnOnce(TextField) -> AnyElement>;
182type CustomAction = Box<dyn FnOnce(DialogAction) -> AnyElement>;
183
184/// Formatting and parsing belong to the application locale. Default editing
185/// uses an ISO pattern and the calendar uses English headings.
186#[derive(Clone)]
187pub struct DatePickerLocale {
188    first_day: Weekday,
189    day: DateFormatter,
190    month: DateFormatter,
191    weekday: WeekdayFormatter,
192    format: DateFormatter,
193    parse: DateParser,
194}
195
196thread_local! {
197    static DEFAULT_DATE_LOCALE: DatePickerLocale = DatePickerLocale {
198        first_day: Weekday::Sun,
199        day: Rc::new(|date| date.format("%A, %B %-d, %Y").to_string().into()),
200        month: Rc::new(|date| date.format("%B %Y").to_string().into()),
201        weekday: Rc::new(|day| day.to_string().into()),
202        format: Rc::new(|date| date.format("%Y-%m-%d").to_string().into()),
203        parse: Rc::new(|text| NaiveDate::parse_from_str(text, "%Y-%m-%d").ok()),
204    };
205}
206
207impl Default for DatePickerLocale {
208    fn default() -> Self {
209        DEFAULT_DATE_LOCALE.with(Clone::clone)
210    }
211}
212
213impl DatePickerLocale {
214    fn same_hooks(&self, other: &Self) -> bool {
215        self.first_day == other.first_day
216            && Rc::ptr_eq(&self.day, &other.day)
217            && Rc::ptr_eq(&self.month, &other.month)
218            && Rc::ptr_eq(&self.weekday, &other.weekday)
219            && Rc::ptr_eq(&self.format, &other.format)
220            && Rc::ptr_eq(&self.parse, &other.parse)
221    }
222
223    /// Sets the first day of the week shown in the calendar grid. Defaults to [`Weekday::Sun`].
224    pub fn first_day(mut self, day: Weekday) -> Self {
225        self.first_day = day;
226        self
227    }
228
229    /// Formats the initial editable text and parses a finished edit.
230    pub fn input_format(
231        mut self,
232        format: impl Fn(NaiveDate) -> SharedString + 'static,
233        parse: impl Fn(&str) -> Option<NaiveDate> + 'static,
234    ) -> Self {
235        self.format = Rc::new(format);
236        self.parse = Rc::new(parse);
237        self
238    }
239
240    /// Sets the spoken date format independently of editable text.
241    pub fn accessible_date_format(
242        mut self,
243        format: impl Fn(NaiveDate) -> SharedString + 'static,
244    ) -> Self {
245        self.day = Rc::new(format);
246        self
247    }
248
249    /// Formats day accessibility names, month headings, and weekday labels.
250    pub fn calendar_format(
251        mut self,
252        day: impl Fn(NaiveDate) -> SharedString + 'static,
253        month: impl Fn(NaiveDate) -> SharedString + 'static,
254        weekday: impl Fn(Weekday) -> SharedString + 'static,
255    ) -> Self {
256        self.day = Rc::new(day);
257        self.month = Rc::new(month);
258        self.weekday = Rc::new(weekday);
259        self
260    }
261}
262
263#[derive(Clone)]
264struct DatePickerOptions {
265    value: DateSelection,
266    variant: DatePickerVariant,
267    locale: DatePickerLocale,
268    focus_target: Option<FocusHandle>,
269}
270
271#[derive(Clone, Copy, Eq, PartialEq)]
272enum Presentation {
273    Triggered,
274    Panel,
275    Dialog,
276}
277
278#[derive(Clone)]
279struct DockedActions {
280    state: Entity<DatePickerState>,
281    generation: u64,
282    properties: DialogProperties,
283    confirm: Option<Confirm<DateSelection>>,
284    request: Option<DismissRequest>,
285    closed: Option<OnClose>,
286}
287
288impl DockedActions {
289    fn current(&self, cx: &App) -> bool {
290        let state = self.state.read(cx);
291        state.docked_open && state.docked_generation == self.generation
292    }
293
294    fn dismiss(&self, reason: DialogCloseReason, window: &mut Window, cx: &mut App) {
295        let enabled = match reason {
296            DialogCloseReason::Escape => self.properties.dismiss_on_escape,
297            DialogCloseReason::OutsideClick => self.properties.dismiss_on_outside_click,
298            _ => true,
299        };
300        if enabled
301            && self.current(cx)
302            && self
303                .request
304                .as_ref()
305                .is_none_or(|callback| callback(reason, window, cx))
306        {
307            self.finish(reason, None, window, cx);
308        }
309    }
310
311    fn finish(
312        &self,
313        reason: DialogCloseReason,
314        value: Option<DateSelection>,
315        window: &mut Window,
316        cx: &mut App,
317    ) {
318        if self.current(cx) {
319            self.state
320                .update(cx, |model, cx| model.dismiss_docked(reason, window, cx));
321            if let (Some(value), Some(confirm)) = (value, &self.confirm) {
322                confirm(value, window, cx);
323            }
324            if let Some(closed) = &self.closed {
325                closed(reason, window, cx);
326            }
327        }
328    }
329}
330
331/// A single or range date picker with a trigger, a standalone panel, or a modal dialog.
332#[derive(IntoElement)]
333pub struct DatePicker {
334    id: ElementId,
335    label: SharedString,
336    state: Entity<DatePickerState>,
337    options: DatePickerOptions,
338    presentation: Presentation,
339    anchor: Option<CustomAnchor>,
340    show_mode_toggle: bool,
341    title: Option<AnyElement>,
342    headline: Option<AnyElement>,
343    confirm_content: Option<CustomAction>,
344    dismiss_content: Option<CustomAction>,
345    confirm: Option<Confirm<DateSelection>>,
346    properties: DialogProperties,
347    request: Option<DismissRequest>,
348    closed: Option<OnClose>,
349    colors: DatePickerColors,
350    disabled: bool,
351}
352
353impl DatePicker {
354    /// Creates a triggered date picker bound to `state` with the caller-owned committed `value`.
355    ///
356    /// Defaults to [`DatePickerVariant::Modal`], [`DatePickerLocale::default()`], and the mode
357    /// toggle visible.
358    pub fn new(
359        id: impl Into<ElementId>,
360        label: impl Into<SharedString>,
361        state: &Entity<DatePickerState>,
362        value: DateSelection,
363    ) -> Self {
364        Self {
365            id: id.into(),
366            label: label.into(),
367            state: state.clone(),
368            options: DatePickerOptions {
369                value,
370                variant: DatePickerVariant::default(),
371                locale: DatePickerLocale::default(),
372                focus_target: None,
373            },
374            presentation: Presentation::Triggered,
375            anchor: None,
376            show_mode_toggle: true,
377            title: None,
378            headline: None,
379            confirm_content: None,
380            dismiss_content: None,
381            confirm: None,
382            properties: DialogProperties::default(),
383            request: None,
384            closed: None,
385            colors: DatePickerColors::default(),
386            disabled: false,
387        }
388    }
389
390    /// Embeds the retained draft and display mode directly in another layout.
391    pub fn panel(
392        id: impl Into<ElementId>,
393        label: impl Into<SharedString>,
394        state: &Entity<DatePickerState>,
395    ) -> Self {
396        Self {
397            presentation: Presentation::Panel,
398            ..Self::new(id, label, state, DateSelection::Single(None))
399        }
400    }
401
402    /// Renders a modal opened by a caller-owned control with `DatePickerState::open`.
403    pub fn dialog(
404        id: impl Into<ElementId>,
405        label: impl Into<SharedString>,
406        state: &Entity<DatePickerState>,
407        value: DateSelection,
408    ) -> Self {
409        Self {
410            presentation: Presentation::Dialog,
411            ..Self::new(id, label, state, value)
412        }
413    }
414
415    /// Sets the picker presentation variant.
416    pub fn variant(mut self, variant: DatePickerVariant) -> Self {
417        self.options.variant = variant;
418        self
419    }
420
421    /// Sets the locale formatting, parsing, and first-day-of-week rules.
422    pub fn locale(mut self, locale: DatePickerLocale) -> Self {
423        self.options.locale = locale;
424        self
425    }
426
427    /// Chooses the initial focus when the built-in control opens the picker.
428    pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
429        self.options.focus_target = Some(focus.clone());
430        self
431    }
432
433    /// Wraps/customizes the retained docked editor and supplied trailing trigger.
434    pub fn docked_anchor<E: IntoElement>(
435        mut self,
436        render: impl FnOnce(TextField) -> E + 'static,
437    ) -> Self {
438        self.anchor = Some(Box::new(move |field| render(field).into_any_element()));
439        self
440    }
441
442    /// Shows or hides the button that toggles between calendar and text-input display modes.
443    pub fn show_mode_toggle(mut self, show: bool) -> Self {
444        self.show_mode_toggle = show;
445        self
446    }
447
448    /// Replaces the visible title while preserving the accessible picker label.
449    pub fn title_content(mut self, element: impl IntoElement) -> Self {
450        self.title = Some(element.into_any_element());
451        self
452    }
453
454    /// Replaces the selection headline while preserving its date announcement.
455    pub fn headline_content(mut self, element: impl IntoElement) -> Self {
456        self.headline = Some(element.into_any_element());
457        self
458    }
459
460    /// Customizes the confirm action control rendered in modal or docked dialogs.
461    pub fn confirm_content<E: IntoElement>(
462        mut self,
463        build: impl FnOnce(DialogAction) -> E + 'static,
464    ) -> Self {
465        self.confirm_content = Some(Box::new(move |confirm| build(confirm).into_any_element()));
466        self
467    }
468
469    /// Customizes the dismiss action control rendered in modal or docked dialogs.
470    pub fn dismiss_content<E: IntoElement>(
471        mut self,
472        build: impl FnOnce(DialogAction) -> E + 'static,
473    ) -> Self {
474        self.dismiss_content = Some(Box::new(move |dismiss| build(dismiss).into_any_element()));
475        self
476    }
477
478    /// Registers a callback invoked with the committed [`DateSelection`] when confirmed.
479    pub fn on_confirm(
480        mut self,
481        callback: impl Fn(DateSelection, &mut Window, &mut App) + 'static,
482    ) -> Self {
483        self.confirm = Some(Rc::new(callback));
484        self
485    }
486
487    /// Configures escape and outside-click dismissal behavior for modal and docked popups.
488    pub fn properties(mut self, properties: DialogProperties) -> Self {
489        self.properties = properties;
490        self
491    }
492
493    /// Registers a gate callback called before dismissing; return `false` to keep the picker open.
494    pub fn on_dismiss_request(
495        mut self,
496        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
497    ) -> Self {
498        self.request = Some(Rc::new(callback));
499        self
500    }
501
502    /// Registers a callback invoked after the picker closes, with the [`DialogCloseReason`].
503    pub fn on_close(
504        mut self,
505        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
506    ) -> Self {
507        self.closed = Some(Rc::new(callback));
508        self
509    }
510
511    /// Overrides the picker's local color palette.
512    pub fn colors(mut self, colors: DatePickerColors) -> Self {
513        self.colors = colors;
514        self
515    }
516
517    /// Disables the built-in trigger control.
518    pub fn disabled(mut self, disabled: bool) -> Self {
519        self.disabled = disabled;
520        self
521    }
522}
523
524fn selection_label(draft: Date, formatter: &DateFormatter) -> SharedString {
525    match (draft.start(), draft.end()) {
526        (Some(start), Some(end)) => format!("{} – {}", formatter(start), formatter(end)).into(),
527        (Some(start), _) => formatter(start),
528        _ if draft.is_single() => "No date selected".into(),
529        _ => "No date range selected".into(),
530    }
531}
532
533impl RenderOnce for DatePicker {
534    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
535        let docked = self.options.variant == DatePickerVariant::Docked
536            && self.presentation == Presentation::Triggered;
537        let (needs_locale_sync, open) = {
538            let model = self.state.read(cx);
539            let open = if self.presentation == Presentation::Panel {
540                true
541            } else if docked {
542                model.docked_open
543            } else {
544                model.dialog.read(cx).is_open()
545            };
546            let needs_locale_sync = !model.locale_initialized
547                || (open && !model.locale.same_hooks(&self.options.locale));
548            (needs_locale_sync, open)
549        };
550        if needs_locale_sync {
551            self.state.update(cx, |state, cx| {
552                state.locale = self.options.locale.clone();
553                if !state.locale_initialized {
554                    state.locale_initialized = true;
555                    if self.presentation == Presentation::Panel {
556                        let draft = state.calendar.read(cx).date();
557                        state.reset_input(draft, &self.options.locale, window, cx);
558                    }
559                }
560            });
561        }
562        let width = (window.viewport_size().width - px(96.)).clamp(px(70.), px(336.));
563        if self.presentation == Presentation::Panel {
564            let body = self.body(width, None, true, window, cx);
565            return Surface::new(ColorRole::SurfaceContainerHigh)
566                .when_some(self.colors.container, Surface::container_color)
567                .child(
568                    div()
569                        .id(self.id)
570                        .role(Role::Group)
571                        .aria_label(self.label)
572                        .child(body),
573                )
574                .into_any_element();
575        }
576
577        let model = self.state.read(cx);
578        let scope = model.docked.clone();
579        let overlay = model.dialog.clone();
580        let docked_actions = DockedActions {
581            state: self.state.clone(),
582            generation: model.docked_generation,
583            properties: self.properties,
584            confirm: self.confirm.clone(),
585            request: self.request.clone(),
586            closed: self.closed.clone(),
587        };
588
589        let trigger = (self.presentation == Presentation::Triggered)
590            .then(|| self.trigger(docked, open, docked_actions.clone(), window, cx));
591        if docked {
592            let (trigger, bounds) = trigger.expect("docked pickers have an anchor");
593            return self.render_docked(trigger, bounds, open, scope, docked_actions, window, cx);
594        }
595
596        self.render_dialog(trigger, overlay, open, width, window, cx)
597    }
598}
599
600type AnchorBounds = Rc<Cell<Option<Bounds<Pixels>>>>;
601
602impl DatePicker {
603    #[allow(clippy::too_many_arguments)]
604    fn render_docked(
605        mut self,
606        trigger: AnyElement,
607        bounds: AnchorBounds,
608        open: bool,
609        scope: FocusHandle,
610        docked_actions: DockedActions,
611        window: &mut Window,
612        cx: &mut App,
613    ) -> AnyElement {
614        let direction = current_material_theme(window, cx).layout.direction;
615        let mut popup = Popup::new(self.id.clone(), trigger)
616            .anchor(logical_anchor(Anchor::TopLeft, direction))
617            .offset(px(4.));
618        if open {
619            let width = (window.viewport_size().width - px(16.)).clamp(px(1.), px(360.));
620            let close_key = docked_actions.clone();
621            let close_outside = docked_actions.clone();
622            let body = self.body(
623                (width - px(24.)).max(px(1.)),
624                Some(docked_actions),
625                true,
626                window,
627                cx,
628            );
629            let panel = div()
630                .id((self.id.clone(), "docked"))
631                .test_support()
632                .role(Role::Dialog)
633                .aria_label(self.label)
634                .track_focus(&scope)
635                .tab_group()
636                .occlude()
637                .max_h((window.viewport_size().height - px(16.)).max(px(1.)))
638                .overflow_y_scroll()
639                .on_mouse_down_out(move |event, window, cx| {
640                    if bounds
641                        .get()
642                        .is_none_or(|bounds| !bounds.contains(&event.position))
643                    {
644                        close_outside.dismiss(DialogCloseReason::OutsideClick, window, cx);
645                    }
646                })
647                .on_key_down(move |event, window, cx| {
648                    if event.keystroke.key == "escape" {
649                        close_key.dismiss(DialogCloseReason::Escape, window, cx);
650                        cx.stop_propagation();
651                    }
652                })
653                .child(
654                    Surface::new(ColorRole::SurfaceContainerHigh)
655                        .when_some(self.colors.container, Surface::container_color)
656                        .w(width)
657                        .rounded(px(16.))
658                        .shadow_elevation(Elevation::Level3)
659                        .p(px(12.))
660                        .child(body),
661                );
662            popup = popup.content(ThemeScope::inherit(panel, window, cx));
663        }
664        popup.into_any_element()
665    }
666
667    fn render_dialog(
668        mut self,
669        trigger: Option<(AnyElement, AnchorBounds)>,
670        overlay: Entity<gpui_material_components::DialogState>,
671        open: bool,
672        width: Pixels,
673        window: &mut Window,
674        cx: &mut App,
675    ) -> AnyElement {
676        let body = if open {
677            self.body(width, None, false, window, cx)
678        } else {
679            div().into_any_element()
680        };
681        let state = self.state.clone();
682        let request_state = self.state;
683        let locale = self.options.locale;
684        let callback = self.confirm;
685        let request = self.request;
686        let mut dialog = Dialog::new(self.id, &overlay, self.label)
687            .variant(if self.options.variant == DatePickerVariant::FullScreen {
688                DialogVariant::FullScreen
689            } else {
690                DialogVariant::Basic
691            })
692            .properties(self.properties)
693            .colors(DialogColors {
694                container: self.colors.container,
695                title: self.colors.title,
696                ..DialogColors::default()
697            })
698            .when_some(self.title, Dialog::title_content)
699            .body(body)
700            .on_dismiss_request(move |reason, window, cx| {
701                let composing = reason == DialogCloseReason::Escape
702                    && request_state.update(cx, |state, cx| {
703                        state.input_mode && state.input_composing(window, cx)
704                    });
705                !composing
706                    && request
707                        .as_ref()
708                        .is_none_or(|request| request(reason, window, cx))
709            })
710            .confirm("OK", move |window, cx| {
711                let value = state.update(cx, |model, cx| {
712                    if model.input_mode && model.input_composing(window, cx) {
713                        return None;
714                    }
715                    let value = if model.input_mode {
716                        model.input_value(&locale, cx).ok()
717                    } else {
718                        complete(model.calendar.read(cx).date())
719                    };
720                    if value.is_none() {
721                        model.input_attempted = true;
722                        cx.notify();
723                    }
724                    value
725                });
726                if let (Some(value), Some(callback)) = (value, &callback) {
727                    callback(value, window, cx);
728                }
729                value.is_some()
730            });
731        if let Some(build) = self.confirm_content {
732            dialog = dialog.confirm_content(build);
733        }
734        if let Some(build) = self.dismiss_content {
735            dialog = dialog.dismiss_content(build);
736        }
737        if let Some(closed) = self.closed {
738            dialog = dialog.on_close(move |reason, window, cx| closed(reason, window, cx));
739        }
740        div()
741            .children(trigger.map(|(trigger, _)| trigger))
742            .child(dialog)
743            .into_any_element()
744    }
745
746    fn trigger(
747        &mut self,
748        docked: bool,
749        open: bool,
750        docked_actions: DockedActions,
751        window: &mut Window,
752        cx: &mut App,
753    ) -> (AnyElement, AnchorBounds) {
754        let model = self.state.read(cx);
755        let focus = model.trigger.clone();
756        let editor = model.anchor.clone();
757        let state = self.state.clone();
758        let options = self.options.clone();
759        let typed_actions = docked_actions.clone();
760        let disabled = self.disabled;
761        let toggle = move |window: &mut Window, cx: &mut App| {
762            if disabled {
763                return;
764            }
765            if docked && state.read(cx).docked_open {
766                docked_actions.dismiss(DialogCloseReason::Cancel, window, cx);
767            } else {
768                focus.focus(window, cx);
769                state.update(cx, |state, cx| {
770                    state.open(options.value, options.variant, &options.locale, window, cx);
771                    if let Some(focus) = &options.focus_target {
772                        focus.focus(window, cx);
773                    }
774                });
775            }
776        };
777        let bounds = Rc::new(Cell::new(None));
778        let capture = bounds.clone();
779        let group = div()
780            .id((self.id.clone(), "trigger-group"))
781            .relative()
782            .role(Role::Group)
783            .aria_expanded(open)
784            .child(
785                canvas(
786                    move |bounds, _, _| capture.set(Some(bounds)),
787                    |_, _, _, _| {},
788                )
789                .absolute()
790                .inset_0(),
791            );
792        let control_id = (self.id.clone(), "open");
793        let focus = self.state.read(cx).trigger.clone();
794        if let Some(anchor) = self.anchor.take().filter(|_| docked) {
795            let locale = self.options.locale.clone();
796            let value = self.options.value;
797            let formatted = if value.draft().start().is_none() {
798                SharedString::default()
799            } else {
800                selection_label(value.draft(), &locale.format)
801            };
802            if self.state.read(cx).anchor_value.as_ref() != Some(&formatted) {
803                self.state.update(cx, |state, cx| {
804                    let synchronized = state.anchor.update(cx, |editor, cx| {
805                        if editor.marked_text_range(window, cx).is_some() {
806                            return false;
807                        }
808                        editor.set_value(formatted.clone(), window, cx);
809                        true
810                    });
811                    if synchronized {
812                        state.anchor_value = Some(formatted);
813                    }
814                });
815            }
816            let handle = editor.read(cx).focus_handle(cx);
817            let state = self.state.clone();
818            let commit = self.confirm.clone();
819            let trailing = IconButton::new(
820                control_id,
821                "Open calendar",
822                Icon::new(IconName::ArrowDropDown),
823            )
824            .disabled(disabled)
825            .track_focus(&focus)
826            .on_activate(toggle);
827            let field = TextField::new((self.id.clone(), "anchor"), self.label.clone(), &editor)
828                .variant(TextFieldVariant::Outlined)
829                .when_some(self.colors.input, TextField::colors)
830                .trailing(trailing);
831            let element = group
832                .on_key_down(move |event, window, cx| {
833                    if disabled || event.keystroke.key != "enter" || !handle.is_focused(window) {
834                        return;
835                    }
836                    let text = editor.update(cx, |editor, cx| {
837                        editor
838                            .marked_text_range(window, cx)
839                            .is_none()
840                            .then(|| editor.value())
841                    });
842                    let Some(text) = text else {
843                        return;
844                    };
845                    let model = state.read(cx);
846                    let selection = if value.draft().is_single() {
847                        parse_selection(&text, None, &locale, &model.limits).ok()
848                    } else {
849                        text.split_once(" – ").and_then(|(start, end)| {
850                            parse_selection(start, Some(end), &locale, &model.limits).ok()
851                        })
852                    };
853                    if let Some(selection) = selection {
854                        state.update(cx, |state, cx| {
855                            state.set_draft(selection.draft().into(), window, cx);
856                        });
857                        if typed_actions.current(cx) {
858                            typed_actions.finish(
859                                DialogCloseReason::Confirm,
860                                Some(selection),
861                                window,
862                                cx,
863                            );
864                        } else if let Some(commit) = &commit {
865                            commit(selection, window, cx);
866                        }
867                        cx.stop_propagation();
868                    }
869                })
870                .child(anchor(field))
871                .into_any_element();
872            (element, bounds)
873        } else {
874            let element = group
875                .child(
876                    Button::new(control_id, self.label.clone())
877                        .variant(ButtonVariant::Outlined)
878                        .disabled(disabled)
879                        .track_focus(&focus)
880                        .on_activate(toggle),
881                )
882                .into_any_element();
883            (element, bounds)
884        }
885    }
886
887    fn body(
888        &mut self,
889        width: Pixels,
890        docked: Option<DockedActions>,
891        inline_title: bool,
892        window: &Window,
893        cx: &App,
894    ) -> AnyElement {
895        let model = self.state.read(cx);
896        let input = model.input_mode;
897        let draft = Date::from(model.draft(cx));
898        let locale = &self.options.locale;
899        let value = selection_label(draft, &locale.format);
900        let spoken = selection_label(draft, &locale.day);
901        let heading = div()
902            .id((self.id.clone(), "headline"))
903            .test_support()
904            .role(Role::Status)
905            .aria_label(spoken)
906            .a11y_synthetic_children(|tree| {
907                tree.parent_node().set_live(gpui::accesskit::Live::Polite)
908            })
909            .when_some(self.colors.headline, gpui::Styled::text_color)
910            .child(self.headline.take().unwrap_or_else(|| {
911                Text::new(value)
912                    .id("date-headline-text")
913                    .role(TypeRole::TitleMedium)
914                    .into_any_element()
915            }));
916        let title = inline_title.then(|| self.title.take()).flatten();
917        let attempted = model.input_attempted;
918        let body = if input {
919            self.input_fields(cx)
920        } else {
921            calendar::calendar(
922                &self.id,
923                self.state.clone(),
924                locale.clone(),
925                docked.clone(),
926                (self.colors, width),
927                window,
928                cx,
929            )
930        };
931        let state = self.state.clone();
932        let mode = if input {
933            DatePickerDisplayMode::Calendar
934        } else {
935            DatePickerDisplayMode::Input
936        };
937        let toggle = (self.show_mode_toggle && docked.is_none()).then(|| {
938            Button::new(
939                (self.id.clone(), "display-mode"),
940                if input { "Show calendar" } else { "Enter date" },
941            )
942            .variant(ButtonVariant::Text)
943            .on_activate(move |window, cx| {
944                state.update(cx, |state, cx| {
945                    state.set_display_mode(mode, window, cx);
946                });
947            })
948        });
949        div()
950            .flex()
951            .flex_col()
952            .gap(px(8.))
953            .children(title.map(|title| {
954                div()
955                    .when_some(self.colors.title, gpui::Styled::text_color)
956                    .child(title)
957            }))
958            .child(heading)
959            .child(body)
960            .children(toggle)
961            .children(
962                (!input && attempted && complete(draft).is_none())
963                    .then(|| status("Select a date before confirming".into(), true)),
964            )
965            .into_any_element()
966    }
967
968    fn input_fields(&self, cx: &App) -> AnyElement {
969        let model = self.state.read(cx);
970        let range = !model.calendar.read(cx).date().is_single();
971        let result = model.input_value(&self.options.locale, cx);
972        let field = |id, name, state: &Entity<TextFieldState>| {
973            TextField::new((self.id.clone(), id), name, state)
974                .variant(TextFieldVariant::Outlined)
975                .when_some(self.colors.input, TextField::colors)
976        };
977        div()
978            .flex()
979            .flex_col()
980            .gap(px(12.))
981            .child(field(
982                "start",
983                if range { "Start date" } else { "Date" },
984                &model.start,
985            ))
986            .when(range, |column| {
987                column.child(field("end", "End date", &model.end))
988            })
989            .when_some(
990                result.err().filter(|_| model.input_attempted),
991                |column, error| column.child(status(error.message().into(), true)),
992            )
993            .into_any_element()
994    }
995}