Skip to main content

gpui_material_extras/date_time/
date.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement,
5    ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Window,
6    div, prelude::FluentBuilder as _, px,
7};
8use gpui_material_components::{DialogAction, DialogCloseReason, DialogProperties, TextField};
9use gpui_material_foundation::Surface;
10use gpui_material_theme::ColorRole;
11
12use super::Confirm;
13
14mod calendar;
15mod dialog;
16mod docked;
17mod state;
18mod types;
19
20pub use state::DatePickerState;
21pub use types::{
22    DatePickerColors, DatePickerDisplayMode, DatePickerDraft, DatePickerLocale, DatePickerVariant,
23    DateSelection,
24};
25
26use types::{
27    CustomAction, CustomAnchor, DatePickerOptions, DismissRequest, DockedActions, OnClose,
28    Presentation,
29};
30
31/// A single or range date picker with a trigger, a standalone panel, or a modal dialog.
32#[derive(IntoElement)]
33pub struct DatePicker {
34    id: ElementId,
35    label: SharedString,
36    state: Entity<DatePickerState>,
37    options: DatePickerOptions,
38    presentation: Presentation,
39    anchor: Option<CustomAnchor>,
40    show_mode_toggle: bool,
41    title: Option<AnyElement>,
42    headline: Option<AnyElement>,
43    confirm_content: Option<CustomAction>,
44    dismiss_content: Option<CustomAction>,
45    confirm: Option<Confirm<DateSelection>>,
46    properties: DialogProperties,
47    request: Option<DismissRequest>,
48    closed: Option<OnClose>,
49    colors: DatePickerColors,
50    disabled: bool,
51}
52
53impl DatePicker {
54    /// Creates a triggered date picker bound to `state` with the caller-owned committed `value`.
55    ///
56    /// Defaults to [`DatePickerVariant::Modal`], [`DatePickerLocale::default()`], and the mode
57    /// toggle visible.
58    pub fn new(
59        id: impl Into<ElementId>,
60        label: impl Into<SharedString>,
61        state: &Entity<DatePickerState>,
62        value: DateSelection,
63    ) -> Self {
64        Self {
65            id: id.into(),
66            label: label.into(),
67            state: state.clone(),
68            options: DatePickerOptions {
69                value,
70                variant: DatePickerVariant::default(),
71                locale: DatePickerLocale::default(),
72                focus_target: None,
73            },
74            presentation: Presentation::Triggered,
75            anchor: None,
76            show_mode_toggle: true,
77            title: None,
78            headline: None,
79            confirm_content: None,
80            dismiss_content: None,
81            confirm: None,
82            properties: DialogProperties::default(),
83            request: None,
84            closed: None,
85            colors: DatePickerColors::default(),
86            disabled: false,
87        }
88    }
89
90    /// Embeds the retained draft and display mode directly in another layout.
91    pub fn panel(
92        id: impl Into<ElementId>,
93        label: impl Into<SharedString>,
94        state: &Entity<DatePickerState>,
95    ) -> Self {
96        Self {
97            presentation: Presentation::Panel,
98            ..Self::new(id, label, state, DateSelection::Single(None))
99        }
100    }
101
102    /// Renders a modal opened by a caller-owned control with `DatePickerState::open`.
103    pub fn dialog(
104        id: impl Into<ElementId>,
105        label: impl Into<SharedString>,
106        state: &Entity<DatePickerState>,
107        value: DateSelection,
108    ) -> Self {
109        Self {
110            presentation: Presentation::Dialog,
111            ..Self::new(id, label, state, value)
112        }
113    }
114
115    /// Sets the picker presentation variant.
116    pub fn variant(mut self, variant: DatePickerVariant) -> Self {
117        self.options.variant = variant;
118        self
119    }
120
121    /// Sets the locale formatting, parsing, and first-day-of-week rules.
122    pub fn locale(mut self, locale: DatePickerLocale) -> Self {
123        self.options.locale = locale;
124        self
125    }
126
127    /// Chooses the initial focus when the built-in control opens the picker.
128    pub fn focus_target(mut self, focus: &FocusHandle) -> Self {
129        self.options.focus_target = Some(focus.clone());
130        self
131    }
132
133    /// Wraps/customizes the retained docked editor and supplied trailing trigger.
134    pub fn docked_anchor<E: IntoElement>(
135        mut self,
136        render: impl FnOnce(TextField) -> E + 'static,
137    ) -> Self {
138        self.anchor = Some(Box::new(move |field| render(field).into_any_element()));
139        self
140    }
141
142    /// Shows or hides the button that toggles between calendar and text-input display modes.
143    pub fn show_mode_toggle(mut self, show: bool) -> Self {
144        self.show_mode_toggle = show;
145        self
146    }
147
148    /// Replaces the visible title while preserving the accessible picker label.
149    pub fn title_content(mut self, element: impl IntoElement) -> Self {
150        self.title = Some(element.into_any_element());
151        self
152    }
153
154    /// Replaces the selection headline while preserving its date announcement.
155    pub fn headline_content(mut self, element: impl IntoElement) -> Self {
156        self.headline = Some(element.into_any_element());
157        self
158    }
159
160    /// Customizes the confirm action control rendered in modal or docked dialogs.
161    pub fn confirm_content<E: IntoElement>(
162        mut self,
163        build: impl FnOnce(DialogAction) -> E + 'static,
164    ) -> Self {
165        self.confirm_content = Some(Box::new(move |confirm| build(confirm).into_any_element()));
166        self
167    }
168
169    /// Customizes the dismiss action control rendered in modal or docked dialogs.
170    pub fn dismiss_content<E: IntoElement>(
171        mut self,
172        build: impl FnOnce(DialogAction) -> E + 'static,
173    ) -> Self {
174        self.dismiss_content = Some(Box::new(move |dismiss| build(dismiss).into_any_element()));
175        self
176    }
177
178    /// Registers a callback invoked with the committed [`DateSelection`] when confirmed.
179    pub fn on_confirm(
180        mut self,
181        callback: impl Fn(DateSelection, &mut Window, &mut App) + 'static,
182    ) -> Self {
183        self.confirm = Some(Rc::new(callback));
184        self
185    }
186
187    /// Configures escape and outside-click dismissal behavior for modal and docked popups.
188    pub fn properties(mut self, properties: DialogProperties) -> Self {
189        self.properties = properties;
190        self
191    }
192
193    /// Registers a gate callback called before dismissing; return `false` to keep the picker open.
194    pub fn on_dismiss_request(
195        mut self,
196        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) -> bool + 'static,
197    ) -> Self {
198        self.request = Some(Rc::new(callback));
199        self
200    }
201
202    /// Registers a callback invoked after the picker closes, with the [`DialogCloseReason`].
203    pub fn on_closed(
204        mut self,
205        callback: impl Fn(DialogCloseReason, &mut Window, &mut App) + 'static,
206    ) -> Self {
207        self.closed = Some(Rc::new(callback));
208        self
209    }
210
211    /// Overrides the picker's local color palette.
212    pub fn colors(mut self, colors: DatePickerColors) -> Self {
213        self.colors = colors;
214        self
215    }
216
217    /// Disables the built-in trigger control.
218    pub fn disabled(mut self, disabled: bool) -> Self {
219        self.disabled = disabled;
220        self
221    }
222}
223
224impl RenderOnce for DatePicker {
225    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
226        let docked = self.options.variant == DatePickerVariant::Docked
227            && self.presentation == Presentation::Triggered;
228        let (needs_locale_init, open) = {
229            let model = self.state.read(cx);
230            let open = if self.presentation == Presentation::Panel {
231                true
232            } else if docked {
233                model.docked_open
234            } else {
235                model.dialog.read(cx).is_open()
236            };
237            (!model.locale_initialized, open)
238        };
239        if needs_locale_init {
240            self.state.update(cx, |state, cx| {
241                state.locale = self.options.locale.clone();
242                state.locale_initialized = true;
243                if self.presentation == Presentation::Panel {
244                    let draft = state.calendar.read(cx).date();
245                    state.reset_input(draft, &self.options.locale, window, cx);
246                }
247            });
248        }
249        let width = (window.viewport_size().width - px(96.)).clamp(px(70.), px(336.));
250        if self.presentation == Presentation::Panel {
251            let body = self.body(width, None, true, window, cx);
252            return Surface::new(ColorRole::SurfaceContainerHigh)
253                .when_some(self.colors.container, Surface::container_color)
254                .child(
255                    div()
256                        .id(self.id)
257                        .role(Role::Group)
258                        .aria_label(self.label)
259                        .child(body),
260                )
261                .into_any_element();
262        }
263
264        let model = self.state.read(cx);
265        let scope = model.docked.clone();
266        let overlay = model.dialog.clone();
267        let docked_actions = DockedActions {
268            state: self.state.clone(),
269            generation: model.docked_generation,
270            properties: self.properties,
271            confirm: self.confirm.clone(),
272            request: self.request.clone(),
273            closed: self.closed.clone(),
274        };
275
276        let trigger = (self.presentation == Presentation::Triggered)
277            .then(|| self.trigger(docked, open, docked_actions.clone(), window, cx));
278        if docked {
279            let (trigger, bounds) = trigger.expect("docked pickers have an anchor");
280            return self.render_docked(trigger, bounds, open, scope, docked_actions, window, cx);
281        }
282
283        self.render_dialog(trigger, overlay, open, width, window, cx)
284    }
285}