1use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6use crate::capabilities::controls::calendar::{
7 is_weekend, today, Calendar, CalendarLocale, DateRange, DateValue,
8};
9use crate::capabilities::foundation::theme::use_theme;
10use crate::capabilities::overlays::popover::{Popover, PopoverContent};
11use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
12use crate::capabilities::primitives::icon::Icon;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
16pub enum DateFormat {
17 #[default]
19 IsoDate,
20 UsDate,
22 EuDate,
24 LongDate,
26}
27
28impl DateFormat {
29 pub fn format(&self, date: &DateValue, locale: &CalendarLocale) -> String {
31 match self {
32 DateFormat::IsoDate => {
33 format!("{:04}-{:02}-{:02}", date.year, date.month, date.day)
34 }
35 DateFormat::UsDate => {
36 format!("{:02}/{:02}/{:04}", date.month, date.day, date.year)
37 }
38 DateFormat::EuDate => {
39 format!("{:02}/{:02}/{:04}", date.day, date.month, date.year)
40 }
41 DateFormat::LongDate => {
42 let month_name = if date.month >= 1 && date.month <= 12 {
43 locale.months[(date.month - 1) as usize].clone()
44 } else {
45 "Unknown".into()
46 };
47 format!("{} {:02}, {:04}", month_name, date.day, date.year)
48 }
49 }
50 }
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum DateSelectionMode {
56 Single,
58 Range,
60}
61
62pub struct DatePickerState {
64 pub selected_date: Option<DateValue>,
65 pub selected_range: Option<DateRange>,
66 pub range_start_temp: Option<DateValue>, pub selection_mode: DateSelectionMode,
68 pub is_open: bool,
69 pub viewing_month: DateValue,
70 focus_handle: FocusHandle,
71}
72
73impl DatePickerState {
74 pub fn new(cx: &mut App) -> Self {
75 let today = today();
76 Self {
77 selected_date: None,
78 selected_range: None,
79 range_start_temp: None,
80 selection_mode: DateSelectionMode::Single,
81 is_open: false,
82 viewing_month: today,
83 focus_handle: cx.focus_handle(),
84 }
85 }
86
87 pub fn new_with_date(date: DateValue, cx: &mut App) -> Self {
88 Self {
89 selected_date: Some(date),
90 selected_range: None,
91 range_start_temp: None,
92 selection_mode: DateSelectionMode::Single,
93 is_open: false,
94 viewing_month: date,
95 focus_handle: cx.focus_handle(),
96 }
97 }
98
99 pub fn new_with_mode(mode: DateSelectionMode, cx: &mut App) -> Self {
100 let today = today();
101 Self {
102 selected_date: None,
103 selected_range: None,
104 range_start_temp: None,
105 selection_mode: mode,
106 is_open: false,
107 viewing_month: today,
108 focus_handle: cx.focus_handle(),
109 }
110 }
111
112 pub fn select_date(&mut self, date: DateValue, _cx: &mut App) {
113 match self.selection_mode {
114 DateSelectionMode::Single => {
115 self.selected_date = Some(date);
116 self.viewing_month = date;
117 }
118 DateSelectionMode::Range => {
119 if let Some(start) = self.range_start_temp {
120 let (range_start, range_end) = if date.year < start.year
122 || (date.year == start.year && date.month < start.month)
123 || (date.year == start.year
124 && date.month == start.month
125 && date.day < start.day)
126 {
127 (date, start)
128 } else {
129 (start, date)
130 };
131 self.selected_range = Some(DateRange {
132 start: range_start,
133 end: range_end,
134 });
135 self.range_start_temp = None;
136 } else {
137 self.range_start_temp = Some(date);
139 self.selected_range = None;
140 }
141 self.viewing_month = date;
142 }
143 }
144 }
145
146 pub fn set_selection_mode(&mut self, mode: DateSelectionMode, _cx: &mut App) {
147 self.selection_mode = mode;
148 self.selected_date = None;
150 self.selected_range = None;
151 self.range_start_temp = None;
152 }
153
154 pub fn clear_date(&mut self, _cx: &mut App) {
155 self.selected_date = None;
156 self.selected_range = None;
157 self.range_start_temp = None;
158 }
159
160 pub fn set_viewing_month(&mut self, date: DateValue, _cx: &mut App) {
161 self.viewing_month = date;
162 }
163
164 pub fn toggle_open(&mut self, _cx: &mut App) {
165 self.is_open = !self.is_open;
166 }
167
168 pub fn close(&mut self, _cx: &mut App) {
169 self.is_open = false;
170 }
171
172 pub fn open(&mut self, _cx: &mut App) {
173 self.is_open = true;
174 }
175
176 pub fn jump_to_today(&mut self, _cx: &mut App) {
177 self.viewing_month = today();
178 }
179}
180
181impl Focusable for DatePickerState {
182 fn focus_handle(&self, _cx: &App) -> FocusHandle {
183 self.focus_handle.clone()
184 }
185}
186
187impl EventEmitter<DismissEvent> for DatePickerState {}
188
189actions!(
190 date_picker,
191 [ClosePicker, SelectToday, NextMonth, PrevMonth]
192);
193
194pub fn init(cx: &mut App) {
196 if !crate::capabilities::foundation::initialization::begin(cx, "date-picker") {
197 return;
198 }
199 cx.bind_keys([
200 KeyBinding::new("escape", ClosePicker, Some("DatePicker")),
201 KeyBinding::new("cmd-t", SelectToday, Some("DatePicker")),
202 KeyBinding::new("cmd-]", NextMonth, Some("DatePicker")),
203 KeyBinding::new("cmd-[", PrevMonth, Some("DatePicker")),
204 ]);
205}
206
207#[derive(IntoElement)]
209pub struct DatePicker {
210 state: Entity<DatePickerState>,
211 placeholder: SharedString,
212 format: DateFormat,
213 min_date: Option<DateValue>,
214 max_date: Option<DateValue>,
215 disabled_dates: Vec<DateValue>,
216 disable_weekends: bool,
217 disabled: bool,
218 clearable: bool,
219 show_today_button: bool,
220 on_select: Option<Rc<dyn Fn(&DateValue, &mut Window, &mut App)>>,
221 on_clear: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
222 locale: CalendarLocale,
223 style: StyleRefinement,
224}
225
226impl DatePicker {
227 pub fn new(state: Entity<DatePickerState>) -> Self {
228 Self {
229 state,
230 placeholder: "Select date...".into(),
231 format: DateFormat::default(),
232 min_date: None,
233 max_date: None,
234 disabled_dates: Vec::new(),
235 disable_weekends: false,
236 disabled: false,
237 clearable: true,
238 show_today_button: true,
239 on_select: None,
240 on_clear: None,
241 locale: CalendarLocale::default(),
242 style: StyleRefinement::default(),
243 }
244 }
245
246 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
248 self.placeholder = placeholder.into();
249 self
250 }
251
252 pub fn format(mut self, format: DateFormat) -> Self {
254 self.format = format;
255 self
256 }
257
258 pub fn min_date(mut self, date: DateValue) -> Self {
260 self.min_date = Some(date);
261 self
262 }
263
264 pub fn max_date(mut self, date: DateValue) -> Self {
266 self.max_date = Some(date);
267 self
268 }
269
270 pub fn disabled_date(mut self, date: DateValue) -> Self {
272 self.disabled_dates.push(date);
273 self
274 }
275
276 pub fn disabled_dates(mut self, dates: Vec<DateValue>) -> Self {
278 self.disabled_dates = dates;
279 self
280 }
281
282 pub fn disable_weekends(mut self) -> Self {
284 self.disable_weekends = true;
285 self
286 }
287
288 pub fn disabled(mut self, disabled: bool) -> Self {
290 self.disabled = disabled;
291 self
292 }
293
294 pub fn clearable(mut self, clearable: bool) -> Self {
296 self.clearable = clearable;
297 self
298 }
299
300 pub fn show_today_button(mut self, show: bool) -> Self {
302 self.show_today_button = show;
303 self
304 }
305
306 pub fn on_select<F>(mut self, handler: F) -> Self
308 where
309 F: Fn(&DateValue, &mut Window, &mut App) + 'static,
310 {
311 self.on_select = Some(Rc::new(handler));
312 self
313 }
314
315 pub fn on_clear<F>(mut self, handler: F) -> Self
317 where
318 F: Fn(&mut Window, &mut App) + 'static,
319 {
320 self.on_clear = Some(Rc::new(handler));
321 self
322 }
323
324 pub fn locale(mut self, locale: CalendarLocale) -> Self {
326 self.locale = locale;
327 self
328 }
329}
330
331impl Styled for DatePicker {
332 fn style(&mut self) -> &mut StyleRefinement {
333 &mut self.style
334 }
335}
336
337impl RenderOnce for DatePicker {
338 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
339 let theme = use_theme(cx);
340 let state_entity = self.state.clone();
341 let state = self.state.read(cx);
342
343 let selected_date = state.selected_date;
344 let _viewing_month = state.viewing_month;
345 let locale = self.locale.clone();
346 let format = self.format;
347 let disabled = self.disabled;
348 let clearable = self.clearable;
349 let show_today_button = self.show_today_button;
350
351 let display_text = if let Some(date) = selected_date {
352 format.format(&date, &locale)
353 } else {
354 self.placeholder.to_string()
355 };
356
357 let has_value = selected_date.is_some();
358 let text_color = if has_value {
359 theme.tokens.foreground
360 } else {
361 theme.tokens.muted_foreground
362 };
363
364 let state_for_clear = state_entity.clone();
365 let state_for_calendar = state_entity.clone();
366 let state_for_today = state_entity.clone();
367 let on_select_handler = self.on_select.clone();
368 let on_clear_handler = self.on_clear.clone();
369 let min_date = self.min_date;
370 let max_date = self.max_date;
371 let disabled_dates = self.disabled_dates.clone();
372 let disable_weekends = self.disable_weekends;
373
374 let user_style = self.style;
375
376 let popover_id = ElementId::Name(
377 format!("date-picker-popover-{}", state_entity.entity_id().as_u64()).into(),
378 );
379
380 Popover::new(popover_id.clone())
381 .trigger(
382 div()
383 .flex()
384 .items_center()
385 .justify_between()
386 .w_full()
387 .h(px(40.0))
388 .px(px(12.0))
389 .gap(px(8.0))
390 .bg(theme.tokens.background)
391 .border_1()
392 .border_color(theme.tokens.input)
393 .rounded(theme.tokens.radius_md)
394 .when(!disabled, |div| {
395 div.cursor(CursorStyle::PointingHand)
396 .hover(|style| style.border_color(theme.tokens.ring))
397 })
398 .when(disabled, |div| {
399 div.cursor(CursorStyle::OperationNotAllowed).opacity(0.5)
400 })
401 .child(
402 div()
403 .flex_1()
404 .text_size(px(14.0))
405 .text_color(text_color)
406 .child(display_text),
407 )
408 .child(
409 div()
410 .flex()
411 .gap(px(4.0))
412 .when(clearable && has_value && !disabled, |parent_div| {
413 let on_clear = on_clear_handler.clone();
414 let muted_bg = theme.tokens.muted;
415 let muted_fg = theme.tokens.muted_foreground;
416 parent_div.child(
417 div()
418 .p(px(2.0))
419 .rounded(px(4.0))
420 .cursor_pointer()
421 .hover(move |style| style.bg(muted_bg))
422 .on_mouse_down(
423 MouseButton::Left,
424 move |_event: &MouseDownEvent, window, cx| {
425 cx.stop_propagation();
426 state_for_clear.update(cx, |state, cx| {
427 state.clear_date(cx);
428 });
429 if let Some(handler) = on_clear.as_ref() {
430 handler(window, cx);
431 }
432 },
433 )
434 .child(Icon::new("x").size(px(16.0)).color(muted_fg)),
435 )
436 })
437 .child(
438 Icon::new("calendar")
439 .size(px(16.0))
440 .color(theme.tokens.muted_foreground),
441 ),
442 ),
443 )
444 .content(move |window: &mut Window, app_cx: &mut App| {
445 let state_ref = state_for_calendar.clone();
446 let on_select_ref = on_select_handler.clone();
447 let locale_ref = locale.clone();
448 let disabled_dates_ref = disabled_dates.clone();
449 let state_today_ref = state_for_today.clone();
450
451 app_cx.new(move |cx| {
452 PopoverContent::new(
453 window,
454 cx,
455 move |_window, popover_cx: &mut Context<PopoverContent>| {
456 let theme = use_theme(popover_cx);
457 let state = state_ref.read(popover_cx);
458 let viewing_month = state.viewing_month;
459 let selected_date = state.selected_date;
460 let selected_range = state.selected_range;
461 let range_start_temp = state.range_start_temp;
462
463 let state_for_select = state_ref.clone();
464 let state_for_month = state_ref.clone();
465 let on_select = on_select_ref.clone();
466 let locale_clone = locale_ref.clone();
467 let min_date_clone = min_date;
468 let max_date_clone = max_date;
469 let disabled_dates_clone = disabled_dates_ref.clone();
470 let state_today = state_today_ref.clone();
471 let border_color = theme.tokens.border;
472
473 let popover_entity = popover_cx.entity().clone();
475
476 div()
477 .flex()
478 .flex_col()
479 .gap(px(8.0))
480 .child({
481 Calendar::new()
482 .current_month(viewing_month)
483 .when_some(selected_date, |cal, date| {
484 cal.selected_date(date)
485 })
486 .selected_range(selected_range)
487 .range_start_temp(range_start_temp)
488 .locale(locale_clone.clone())
489 .is_date_disabled({
490 let min = min_date_clone;
491 let max = max_date_clone;
492 let disabled = disabled_dates_clone.clone();
493 move |date: &DateValue| {
494 let is_before_min = if let Some(min) = min {
495 date.year < min.year
496 || (date.year == min.year
497 && date.month < min.month)
498 || (date.year == min.year
499 && date.month == min.month
500 && date.day < min.day)
501 } else {
502 false
503 };
504
505 let is_after_max = if let Some(max) = max {
506 date.year > max.year
507 || (date.year == max.year
508 && date.month > max.month)
509 || (date.year == max.year
510 && date.month == max.month
511 && date.day > max.day)
512 } else {
513 false
514 };
515
516 let is_in_disabled_list =
517 disabled.iter().any(|d| d == date);
518 is_before_min
519 || is_after_max
520 || is_in_disabled_list
521 || (disable_weekends && is_weekend(date))
522 }
523 })
524 .on_date_select({
525 let popover_for_dismiss = popover_entity.clone();
526 let on_select_for_date = on_select.clone();
527 move |date, window, app_cx| {
528 let is_before_min =
529 if let Some(min) = min_date_clone {
530 date.year < min.year
531 || (date.year == min.year
532 && date.month < min.month)
533 || (date.year == min.year
534 && date.month == min.month
535 && date.day < min.day)
536 } else {
537 false
538 };
539
540 let is_after_max = if let Some(max) = max_date_clone
541 {
542 date.year > max.year
543 || (date.year == max.year
544 && date.month > max.month)
545 || (date.year == max.year
546 && date.month == max.month
547 && date.day > max.day)
548 } else {
549 false
550 };
551
552 let is_in_disabled_list =
553 disabled_dates_clone.iter().any(|d| d == date);
554 let is_disabled = is_before_min
555 || is_after_max
556 || is_in_disabled_list
557 || (disable_weekends && is_weekend(date));
558
559 if !is_disabled {
560 let should_close = state_for_select
562 .read(app_cx)
563 .selection_mode
564 == DateSelectionMode::Single
565 || state_for_select
566 .read(app_cx)
567 .range_start_temp
568 .is_some(); state_for_select.update(app_cx, |state, cx| {
572 state.select_date(*date, cx);
573 if should_close {
574 state.close(cx);
575 }
576 cx.notify(); });
578
579 if should_close {
581 if let Some(handler) =
582 on_select_for_date.as_ref()
583 {
584 handler(date, window, app_cx);
585 }
586
587 popover_for_dismiss.update(
589 app_cx,
590 |_, cx| {
591 cx.emit(DismissEvent);
592 },
593 );
594 }
595 }
596 }
597 })
598 .on_month_change(move |date, _window, app_cx| {
599 state_for_month.update(app_cx, |state, cx| {
600 state.set_viewing_month(*date, cx);
601 cx.notify(); });
603 })
604 })
605 .when(show_today_button, |parent_div| {
606 let popover_for_today = popover_entity.clone();
607 let on_select_for_today = on_select.clone();
608 parent_div.child(
609 div()
610 .flex()
611 .justify_center()
612 .pt(px(8.0))
613 .border_t_1()
614 .border_color(border_color)
615 .child(
616 Button::new("today-btn", "Today")
617 .variant(ButtonVariant::Outline)
618 .size(ButtonSize::Sm)
619 .on_click(move |_, window, app_cx| {
620 let today = today();
621 state_today.update(app_cx, |state, cx| {
622 state.select_date(today, cx);
623 state.close(cx);
624 cx.notify(); });
626
627 if let Some(handler) =
629 on_select_for_today.as_ref()
630 {
631 handler(&today, window, app_cx);
632 }
633
634 popover_for_today.update(
636 app_cx,
637 |_, cx| {
638 cx.emit(DismissEvent);
639 },
640 );
641 }),
642 ),
643 )
644 })
645 .into_any_element()
646 },
647 )
648 })
649 })
650 .map(|this| {
651 let mut popover = this;
652 popover.style().refine(&user_style);
653 popover
654 })
655 }
656}