1use std::{ops::Deref as _, str::FromStr as _};
2
3use chrono::{Datelike as _, NaiveDate};
4use gpui_es_fluent::localize_message;
5use gpui_kit::component::{
6 ActiveTheme as _, Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _,
7 ThemeStyled as _,
8 button::{Button, ButtonVariants as _},
9 h_flex,
10};
11use gpui_kit::{
12 App, AppContext as _, ClickEvent, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle,
13 Focusable, InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Render,
14 RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled,
15 Subscription, Window, anchored, deferred, div, prelude::FluentBuilder as _, px,
16};
17use icu_calendar::{Date as IcuDate, Gregorian};
18use icu_datetime::{FixedCalendarDateTimeFormatter, fieldsets};
19use icu_locale_core::Locale;
20use jiff::civil::Date as JiffDate;
21
22use crate::calendar::{Calendar, CalendarEvent, CalendarState, Date as CalendarDate};
23use crate::i18n::DatePickerText;
24#[cfg(feature = "component-shape")]
25use gpui_form_runtime::shape::ValueChange;
26
27mod formatting;
28mod state;
29
30pub use formatting::parse_form_date;
31use formatting::*;
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
35pub enum DateDisplayStyle {
36 Short,
37 #[default]
38 Medium,
39 Long,
40}
41
42#[derive(Clone)]
44pub enum DatePickerEvent {
45 Change(Option<JiffDate>),
46}
47
48#[derive(Clone)]
50pub enum DateRangePickerEvent {
51 Change(Option<JiffDate>, Option<JiffDate>),
52}
53
54pub struct DatePickerState {
56 focus_handle: FocusHandle,
57 date: Option<JiffDate>,
58 open: bool,
59 calendar: Entity<CalendarState>,
60 display_locale: Option<Locale>,
61 display_style: DateDisplayStyle,
62 _subscriptions: Vec<Subscription>,
63}
64
65#[cfg(feature = "component-shape")]
66impl gpui_form_runtime::shape::GpuiComponentStateValueBinding<chrono::NaiveDate>
67 for DatePickerState
68{
69 type Event = DatePickerEvent;
70
71 fn seed_value_binding_state(
72 state: &mut Self,
73 value: Option<&chrono::NaiveDate>,
74 window: &mut Window,
75 cx: &mut Context<'_, Self>,
76 ) {
77 let date = value.and_then(|value| value.to_string().parse::<JiffDate>().ok());
78 state.set_date(date, window, cx);
79 }
80
81 fn value_change(_state: &Self, event: &Self::Event) -> ValueChange<chrono::NaiveDate> {
82 match event {
83 DatePickerEvent::Change(Some(date)) => parse_form_date::<chrono::NaiveDate>(*date)
84 .map_or(ValueChange::Unchanged, ValueChange::Set),
85 DatePickerEvent::Change(None) => ValueChange::Clear,
86 }
87 }
88}
89
90impl Focusable for DatePickerState {
91 fn focus_handle(&self, _: &App) -> FocusHandle {
92 self.focus_handle.clone()
93 }
94}
95
96impl EventEmitter<DatePickerEvent> for DatePickerState {}
97
98pub struct DateRangePickerState {
100 focus_handle: FocusHandle,
101 start_date: Option<JiffDate>,
102 end_date: Option<JiffDate>,
103 open: bool,
104 calendar: Entity<CalendarState>,
105 display_locale: Option<Locale>,
106 display_style: DateDisplayStyle,
107 _subscriptions: Vec<Subscription>,
108}
109
110#[cfg(feature = "component-shape")]
111impl
112 gpui_form_runtime::shape::GpuiComponentStateValueBinding<(chrono::NaiveDate, chrono::NaiveDate)>
113 for DateRangePickerState
114{
115 type Event = DateRangePickerEvent;
116
117 fn seed_value_binding_state(
118 state: &mut Self,
119 value: Option<&(chrono::NaiveDate, chrono::NaiveDate)>,
120 window: &mut Window,
121 cx: &mut Context<'_, Self>,
122 ) {
123 state.set_range(
124 value.and_then(|(start, _)| jiff_date_from_chrono(*start)),
125 value.and_then(|(_, end)| jiff_date_from_chrono(*end)),
126 window,
127 cx,
128 );
129 }
130
131 fn value_change(
132 _state: &Self,
133 event: &Self::Event,
134 ) -> ValueChange<(chrono::NaiveDate, chrono::NaiveDate)> {
135 match event {
136 DateRangePickerEvent::Change(Some(start), Some(end)) => {
137 jiff_date_range_from_chrono(*start, *end)
138 .map_or(ValueChange::Unchanged, ValueChange::Set)
139 },
140 DateRangePickerEvent::Change(_, _) => ValueChange::Clear,
141 }
142 }
143}
144
145impl Focusable for DateRangePickerState {
146 fn focus_handle(&self, _: &App) -> FocusHandle {
147 self.focus_handle.clone()
148 }
149}
150
151impl EventEmitter<DateRangePickerEvent> for DateRangePickerState {}
152
153impl Render for DatePickerState {
154 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
155 Empty
156 }
157}
158
159impl Render for DateRangePickerState {
160 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
161 Empty
162 }
163}
164
165#[cfg_attr(
167 feature = "component-shape",
168 derive(component_shape_gpui::GpuiComponentShape)
169)]
170#[cfg_attr(
171 feature = "component-shape",
172 gpui_component_shape(
173 state = DatePickerState,
174 value = chrono::NaiveDate,
175 field_suffix = "date_picker",
176 value_binding
177 )
178)]
179#[derive(IntoElement)]
180pub struct DatePicker {
181 id: ElementId,
182 style: StyleRefinement,
183 state: Entity<DatePickerState>,
184 cleanable: bool,
185 placeholder: Option<SharedString>,
186 size: Size,
187 number_of_months: usize,
188 appearance: bool,
189 disabled: bool,
190}
191
192#[cfg(feature = "component-shape")]
193impl gpui_form_runtime::shape::GpuiFormComponentShapePolicy for DatePicker {
194 type ValueStoragePolicy = gpui_form_runtime::shape::RequiredValueStorage;
195}
196
197#[cfg_attr(
199 feature = "component-shape",
200 derive(component_shape_gpui::GpuiComponentShape)
201)]
202#[cfg_attr(
203 feature = "component-shape",
204 gpui_component_shape(
205 state = DateRangePickerState,
206 value = (chrono::NaiveDate, chrono::NaiveDate),
207 field_suffix = "date_range_picker",
208 value_binding
209 )
210)]
211#[derive(IntoElement)]
212pub struct DateRangePicker {
213 id: ElementId,
214 style: StyleRefinement,
215 state: Entity<DateRangePickerState>,
216 cleanable: bool,
217 placeholder: Option<SharedString>,
218 size: Size,
219 number_of_months: usize,
220 appearance: bool,
221 disabled: bool,
222}
223
224#[cfg(feature = "component-shape")]
225impl gpui_form_runtime::shape::GpuiFormComponentShapePolicy for DateRangePicker {
226 type ValueStoragePolicy = gpui_form_runtime::shape::RequiredValueStorage;
227}
228
229impl Sizable for DatePicker {
230 fn with_size(mut self, size: impl Into<Size>) -> Self {
231 self.size = size.into();
232 self
233 }
234}
235
236impl Sizable for DateRangePicker {
237 fn with_size(mut self, size: impl Into<Size>) -> Self {
238 self.size = size.into();
239 self
240 }
241}
242
243impl Focusable for DatePicker {
244 fn focus_handle(&self, cx: &App) -> FocusHandle {
245 self.state.focus_handle(cx)
246 }
247}
248
249impl Focusable for DateRangePicker {
250 fn focus_handle(&self, cx: &App) -> FocusHandle {
251 self.state.focus_handle(cx)
252 }
253}
254
255impl Styled for DatePicker {
256 fn style(&mut self) -> &mut StyleRefinement {
257 &mut self.style
258 }
259}
260
261impl Styled for DateRangePicker {
262 fn style(&mut self) -> &mut StyleRefinement {
263 &mut self.style
264 }
265}
266
267impl Disableable for DatePicker {
268 fn disabled(mut self, disabled: bool) -> Self {
269 self.disabled = disabled;
270 self
271 }
272}
273
274impl Disableable for DateRangePicker {
275 fn disabled(mut self, disabled: bool) -> Self {
276 self.disabled = disabled;
277 self
278 }
279}
280
281impl DatePicker {
282 pub fn new(state: &Entity<DatePickerState>) -> Self {
284 Self {
285 id: ("date-picker", state.entity_id()).into(),
286 state: state.clone(),
287 cleanable: false,
288 placeholder: None,
289 size: Size::default(),
290 style: StyleRefinement::default(),
291 number_of_months: 2,
292 appearance: true,
293 disabled: false,
294 }
295 }
296
297 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
299 self.placeholder = Some(placeholder.into());
300 self
301 }
302
303 pub fn cleanable(mut self, cleanable: bool) -> Self {
305 self.cleanable = cleanable;
306 self
307 }
308
309 pub fn number_of_months(mut self, number_of_months: usize) -> Self {
311 self.number_of_months = number_of_months;
312 self
313 }
314
315 pub fn appearance(mut self, appearance: bool) -> Self {
317 self.appearance = appearance;
318 self
319 }
320}
321
322impl DateRangePicker {
323 pub fn new(state: &Entity<DateRangePickerState>) -> Self {
325 Self {
326 id: ("date-range-picker", state.entity_id()).into(),
327 state: state.clone(),
328 cleanable: false,
329 placeholder: None,
330 size: Size::default(),
331 style: StyleRefinement::default(),
332 number_of_months: 2,
333 appearance: true,
334 disabled: false,
335 }
336 }
337
338 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
340 self.placeholder = Some(placeholder.into());
341 self
342 }
343
344 pub fn cleanable(mut self, cleanable: bool) -> Self {
346 self.cleanable = cleanable;
347 self
348 }
349
350 pub fn number_of_months(mut self, number_of_months: usize) -> Self {
352 self.number_of_months = number_of_months;
353 self
354 }
355
356 pub fn appearance(mut self, appearance: bool) -> Self {
358 self.appearance = appearance;
359 self
360 }
361}
362
363impl RenderOnce for DatePicker {
364 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
365 let is_focused = self.focus_handle(cx).contains_focused(window, cx);
366 let state = self.state.read(cx);
367 let show_clean = self.cleanable && state.date.is_some();
368 let placeholder = self
369 .placeholder
370 .clone()
371 .unwrap_or_else(|| localize_message(cx, &DatePickerText::SelectDate).into());
372 let locale = state.display_locale.clone().unwrap_or_else(active_locale);
373 let display_title = state
374 .date
375 .and_then(|date| format_display_date(date, &locale, state.display_style))
376 .unwrap_or_else(|| placeholder.clone());
377
378 div()
379 .id(self.id.clone())
380 .track_focus(&self.focus_handle(cx).tab_stop(true))
381 .flex_none()
382 .w_full()
383 .relative()
384 .input_text_size(self.size)
385 .refine_style(&self.style)
386 .child(
387 div()
388 .id("date-picker-input")
389 .relative()
390 .flex()
391 .items_center()
392 .justify_between()
393 .when(self.appearance, |this| {
394 this.bg(cx.theme().background)
395 .text_color(cx.theme().foreground)
396 .when(self.disabled, |this| this.opacity(0.5))
397 .border_1()
398 .border_color(cx.theme().input)
399 .rounded(cx.theme().radius)
400 .when(cx.theme().shadow, |this| this.shadow_xs())
401 .when(is_focused, |this| this.border_color(cx.theme().ring))
402 })
403 .when(is_focused && self.appearance && !self.disabled, |this| {
404 this.focus_ring_style(window, cx)
405 })
406 .overflow_hidden()
407 .input_text_size(self.size)
408 .input_size(self.size)
409 .when(!self.disabled, |this| {
410 this.on_click(
411 window.listener_for(&self.state, DatePickerState::toggle_calendar),
412 )
413 })
414 .child(
415 h_flex()
416 .w_full()
417 .items_center()
418 .justify_between()
419 .gap_1()
420 .child(
421 div()
422 .w_full()
423 .overflow_hidden()
424 .when(state.date.is_none(), |this| {
425 this.text_color(cx.theme().muted_foreground)
426 })
427 .child(display_title),
428 )
429 .when(!self.disabled, |this| {
430 this.when(show_clean, |this| {
431 this.child(
432 Button::new(("clear-date", self.state.entity_id()))
433 .small()
434 .ghost()
435 .icon(IconName::Close)
436 .on_click(
437 window.listener_for(
438 &self.state,
439 DatePickerState::clean,
440 ),
441 ),
442 )
443 })
444 .when(!show_clean, |this| {
445 this.child(
446 Icon::new(IconName::Calendar)
447 .xsmall()
448 .text_color(cx.theme().muted_foreground),
449 )
450 })
451 }),
452 ),
453 )
454 .when(state.open, |this| {
455 this.child(
456 deferred(
457 anchored().snap_to_window_with_margin(px(8.)).child(
458 div()
459 .occlude()
460 .mt_1p5()
461 .p_3()
462 .border_1()
463 .border_color(cx.theme().border)
464 .shadow_lg()
465 .rounded((cx.theme().radius * 2.).min(px(8.)))
466 .bg(cx.theme().popover)
467 .text_color(cx.theme().popover_foreground)
468 .on_mouse_up_out(
469 MouseButton::Left,
470 window.listener_for(&self.state, |state, _, window, cx| {
471 state.close_calendar(window, cx);
472 }),
473 )
474 .child(
475 Calendar::new(&state.calendar)
476 .display_locale(locale.clone())
477 .number_of_months(self.number_of_months)
478 .border_0()
479 .rounded_none()
480 .p_0()
481 .with_size(self.size),
482 ),
483 ),
484 )
485 .with_priority(2),
486 )
487 })
488 }
489}
490
491impl RenderOnce for DateRangePicker {
492 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
493 let is_focused = self.focus_handle(cx).contains_focused(window, cx);
494 let state = self.state.read(cx);
495 let show_clean = self.cleanable && (state.start_date.is_some() || state.end_date.is_some());
496 let placeholder = self
497 .placeholder
498 .clone()
499 .unwrap_or_else(|| localize_message(cx, &DatePickerText::SelectDate).into());
500 let locale = state.display_locale.clone().unwrap_or_else(active_locale);
501 let display_title = format_display_range(
502 state.start_date,
503 state.end_date,
504 &locale,
505 state.display_style,
506 )
507 .unwrap_or_else(|| placeholder.clone());
508
509 div()
510 .id(self.id.clone())
511 .track_focus(&self.focus_handle(cx).tab_stop(true))
512 .flex_none()
513 .w_full()
514 .relative()
515 .input_text_size(self.size)
516 .refine_style(&self.style)
517 .child(
518 div()
519 .id("date-range-picker-input")
520 .relative()
521 .flex()
522 .items_center()
523 .justify_between()
524 .when(self.appearance, |this| {
525 this.bg(cx.theme().background)
526 .text_color(cx.theme().foreground)
527 .when(self.disabled, |this| this.opacity(0.5))
528 .border_1()
529 .border_color(cx.theme().input)
530 .rounded(cx.theme().radius)
531 .when(cx.theme().shadow, |this| this.shadow_xs())
532 .when(is_focused, |this| this.border_color(cx.theme().ring))
533 })
534 .when(is_focused && self.appearance && !self.disabled, |this| {
535 this.focus_ring_style(window, cx)
536 })
537 .overflow_hidden()
538 .input_text_size(self.size)
539 .input_size(self.size)
540 .when(!self.disabled, |this| {
541 this.on_click(
542 window.listener_for(&self.state, DateRangePickerState::toggle_calendar),
543 )
544 })
545 .child(
546 h_flex()
547 .w_full()
548 .items_center()
549 .justify_between()
550 .gap_1()
551 .child(
552 div()
553 .w_full()
554 .overflow_hidden()
555 .when(
556 state.start_date.is_none() && state.end_date.is_none(),
557 |this| this.text_color(cx.theme().muted_foreground),
558 )
559 .child(display_title),
560 )
561 .when(!self.disabled, |this| {
562 this.when(show_clean, |this| {
563 this.child(
564 Button::new(("clear-date-range", self.state.entity_id()))
565 .small()
566 .ghost()
567 .icon(IconName::Close)
568 .on_click(window.listener_for(
569 &self.state,
570 DateRangePickerState::clean,
571 )),
572 )
573 })
574 .when(!show_clean, |this| {
575 this.child(
576 Icon::new(IconName::Calendar)
577 .xsmall()
578 .text_color(cx.theme().muted_foreground),
579 )
580 })
581 }),
582 ),
583 )
584 .when(state.open, |this| {
585 this.child(
586 deferred(
587 anchored().snap_to_window_with_margin(px(8.)).child(
588 div()
589 .occlude()
590 .mt_1p5()
591 .p_3()
592 .border_1()
593 .border_color(cx.theme().border)
594 .shadow_lg()
595 .rounded((cx.theme().radius * 2.).min(px(8.)))
596 .bg(cx.theme().popover)
597 .text_color(cx.theme().popover_foreground)
598 .on_mouse_up_out(
599 MouseButton::Left,
600 window.listener_for(&self.state, |state, _, window, cx| {
601 state.close_calendar(window, cx);
602 }),
603 )
604 .child(
605 Calendar::new(&state.calendar)
606 .display_locale(locale.clone())
607 .number_of_months(self.number_of_months)
608 .border_0()
609 .rounded_none()
610 .p_0()
611 .with_size(self.size),
612 ),
613 ),
614 )
615 .with_priority(2),
616 )
617 })
618 }
619}
620
621#[cfg(test)]
622mod tests;