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