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