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