1use std::{cell::RefCell, ops::RangeInclusive, rc::Rc, sync::Arc};
2
3use chrono::{Datelike, Days, Months};
4use gpui::{
5 App, AppContext as _, Context, Entity, EntityInputHandler as _, FocusHandle, Focusable as _,
6 SharedString, WeakFocusHandle, Window,
7};
8use gpui_base::{CalendarState, Date, Matcher};
9use gpui_material_components::{DialogCloseReason, DialogState, TextFieldState};
10use gpui_material_theme::Direction;
11
12use super::{
13 DateFilter, DateFormatter, DatePickerDisplayMode, DatePickerDraft, DatePickerLocale,
14 DatePickerVariant, DateSelection, NaiveDate, Weekday, YearFilter, complete,
15};
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub(super) enum DateError {
19 Invalid,
20 Disabled,
21 Order,
22}
23
24impl DateError {
25 pub(super) fn message(self) -> &'static str {
26 match self {
27 Self::Invalid => "Enter a valid date",
28 Self::Disabled => "Choose an available date",
29 Self::Order => "End date must be on or after start date",
30 }
31 }
32}
33
34#[derive(Clone)]
35pub(super) struct DateLimits {
36 pub(super) bounds: RangeInclusive<NaiveDate>,
37 pub(super) disabled: DateFilter,
38 pub(super) disabled_years: YearFilter,
39}
40
41impl DateLimits {
42 pub(super) fn accepts(&self, date: NaiveDate) -> bool {
43 self.bounds.contains(&date) && self.accepts_year(date.year()) && !(self.disabled)(date)
44 }
45
46 pub(super) fn accepts_year(&self, year: i32) -> bool {
47 (self.bounds.start().year()..=self.bounds.end().year()).contains(&year)
48 && !(self.disabled_years)(year)
49 }
50
51 pub(super) fn accepts_draft(&self, draft: Date) -> bool {
52 let start = draft.start().map(super::from_base_date);
53 let end = draft.end().map(super::from_base_date);
54 start.is_none_or(|date| self.accepts(date))
55 && end.is_none_or(|date| start.is_some_and(|start| start <= date) && self.accepts(date))
56 }
57}
58
59pub(super) fn first_of_month(date: NaiveDate) -> NaiveDate {
60 date.with_day(1).expect("every month has a first day")
61}
62
63pub(super) fn calendar_start(month: NaiveDate, first_day: Weekday) -> NaiveDate {
64 let offset =
65 (month.weekday().num_days_from_monday() + 7 - first_day.num_days_from_monday()) % 7;
66 month
67 .checked_sub_days(Days::new(u64::from(offset)))
68 .unwrap_or(month)
69}
70
71pub(super) fn parse_selection(
72 start: &str,
73 end: Option<&str>,
74 locale: &DatePickerLocale,
75 limits: &DateLimits,
76) -> Result<DateSelection, DateError> {
77 let parse = |text: &str| {
78 let date = (locale.parse)(text.trim()).ok_or(DateError::Invalid)?;
79 if !limits.accepts(date) {
80 return Err(DateError::Disabled);
81 }
82 Ok(date)
83 };
84 let start = parse(start)?;
85 let Some(end) = end.map(parse).transpose()? else {
86 return Ok(DateSelection::Single(Some(start)));
87 };
88 if start > end {
89 return Err(DateError::Order);
90 }
91 Ok(DateSelection::Range(Some((start, end))))
92}
93
94pub(super) struct MonthCache {
95 month: NaiveDate,
96 day_formatter: DateFormatter,
97 month_formatter: DateFormatter,
98 pub(super) month_label: SharedString,
99 pub(super) day_ids: Vec<SharedString>,
100 pub(super) day_labels: Vec<SharedString>,
101}
102
103impl MonthCache {
104 fn matches(&self, month: NaiveDate, locale: &DatePickerLocale) -> bool {
105 self.month == month
106 && Rc::ptr_eq(&self.day_formatter, &locale.day)
107 && Rc::ptr_eq(&self.month_formatter, &locale.month)
108 }
109
110 fn build(month: NaiveDate, locale: &DatePickerLocale) -> Self {
111 let mut day_ids = Vec::with_capacity(31);
112 let mut day_labels = Vec::with_capacity(31);
113 let mut current = month;
114 while current.month() == month.month() {
115 day_ids.push(SharedString::from(format!("day-{current}")));
116 day_labels.push((locale.day)(current));
117 let Some(next) = current.succ_opt() else {
118 break;
119 };
120 current = next;
121 }
122 Self {
123 month,
124 day_formatter: locale.day.clone(),
125 month_formatter: locale.month.clone(),
126 month_label: (locale.month)(month),
127 day_ids,
128 day_labels,
129 }
130 }
131}
132
133pub struct DatePickerState {
136 pub(super) calendar: Entity<CalendarState>,
137 pub(super) start: Entity<TextFieldState>,
138 pub(super) end: Entity<TextFieldState>,
139 pub(super) anchor: Entity<TextFieldState>,
140 pub(super) anchor_value: Option<SharedString>,
141 pub(super) dialog: Entity<DialogState>,
142 pub(super) trigger: FocusHandle,
143 pub(super) docked: FocusHandle,
144 pub(super) day: FocusHandle,
145 pub(super) cursor: NaiveDate,
146 pub(super) docked_open: bool,
147 pub(super) docked_generation: u64,
148 docked_previous: Option<WeakFocusHandle>,
149 docked_reason: Option<DialogCloseReason>,
150 variant: DatePickerVariant,
151 pub(super) locale: DatePickerLocale,
152 pub(super) locale_initialized: bool,
153 month_cache: RefCell<Option<MonthCache>>,
154 initial_month: Option<NaiveDate>,
155 pub(super) year_page: Option<i32>,
156 pub(super) input_mode: bool,
157 pub(super) input_attempted: bool,
158 pub(super) limits: DateLimits,
159}
160
161impl DatePickerState {
162 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
164 let limits = DateLimits {
165 bounds: NaiveDate::from_ymd_opt(1900, 1, 1).unwrap()
166 ..=NaiveDate::from_ymd_opt(2100, 12, 31).unwrap(),
167 disabled: Arc::new(|_| false),
168 disabled_years: Arc::new(|_| false),
169 };
170 let calendar = cx.new(|cx| CalendarState::new(window, cx));
171 let cursor = super::from_base_date(calendar.read(cx).today());
172 let start = cx.new(|cx| TextFieldState::new(window, cx));
173 let end = cx.new(|cx| TextFieldState::new(window, cx));
174 let anchor = cx.new(|cx| TextFieldState::new(window, cx));
175 cx.observe(&anchor, |_, _, cx| cx.notify()).detach();
176 let dialog = cx.new(DialogState::new);
177 cx.observe(&start, |_, _, cx| cx.notify()).detach();
178 cx.observe(&end, |_, _, cx| cx.notify()).detach();
179 cx.observe(&dialog, |_, _, cx| cx.notify()).detach();
180 Self {
181 calendar,
182 start,
183 end,
184 anchor,
185 anchor_value: None,
186 dialog,
187 trigger: cx.focus_handle(),
188 docked: cx.focus_handle(),
189 day: cx.focus_handle(),
190 cursor,
191 docked_open: false,
192 docked_generation: 0,
193 docked_previous: None,
194 docked_reason: None,
195 variant: DatePickerVariant::default(),
196 locale: DatePickerLocale::default(),
197 locale_initialized: false,
198 month_cache: RefCell::new(None),
199 initial_month: None,
200 year_page: None,
201 input_mode: false,
202 input_attempted: false,
203 limits,
204 }
205 }
206
207 pub fn date_bounds(mut self, bounds: RangeInclusive<NaiveDate>) -> Self {
210 let (min, max) = bounds.into_inner();
211 self.limits.bounds = min.min(max)..=min.max(max);
212 self.cursor = self
213 .cursor
214 .clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
215 self
216 }
217
218 pub fn disabled_dates(
220 mut self,
221 disabled: impl Fn(NaiveDate) -> bool + Send + Sync + 'static,
222 ) -> Self {
223 self.limits.disabled = Arc::new(disabled);
224 self
225 }
226
227 pub fn initial_month(mut self, date: NaiveDate) -> Self {
229 self.initial_month = Some(date);
230 self.cursor = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
231 self
232 }
233
234 pub fn disabled_years(
236 mut self,
237 disabled: impl Fn(i32) -> bool + Send + Sync + 'static,
238 ) -> Self {
239 self.limits.disabled_years = Arc::new(disabled);
240 self
241 }
242
243 pub fn trigger_focus(&self) -> &FocusHandle {
245 &self.trigger
246 }
247
248 pub fn is_open(&self, cx: &App) -> bool {
250 self.docked_open || self.dialog.read(cx).is_open()
251 }
252
253 pub fn last_close_reason(&self, cx: &App) -> Option<DialogCloseReason> {
255 if self.variant == DatePickerVariant::Docked {
256 self.docked_reason
257 } else {
258 self.dialog.read(cx).last_close_reason()
259 }
260 }
261
262 pub fn set_displayed_month(&mut self, date: NaiveDate, cx: &mut Context<Self>) {
264 let clamped = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
265 let month_changed = self.show_month(clamped, cx);
266 let changed = self.cursor != clamped || self.year_page.take().is_some() || month_changed;
267 self.cursor = clamped;
268 if changed {
269 cx.notify();
270 }
271 }
272
273 pub fn displayed_month(&self) -> NaiveDate {
275 first_of_month(self.cursor)
276 }
277
278 pub(super) fn month_cache(
279 &self,
280 month: NaiveDate,
281 locale: &DatePickerLocale,
282 ) -> std::cell::Ref<'_, MonthCache> {
283 {
284 let mut cache = self.month_cache.borrow_mut();
285 if cache
286 .as_ref()
287 .is_none_or(|cached| !cached.matches(month, locale))
288 {
289 *cache = Some(MonthCache::build(month, locale));
290 }
291 }
292 std::cell::Ref::map(self.month_cache.borrow(), |cache| {
293 cache.as_ref().expect("month cache initialized")
294 })
295 }
296
297 pub fn draft(&self, cx: &App) -> DatePickerDraft {
299 if self.input_mode {
300 self.input_draft(cx).into()
301 } else {
302 self.calendar.read(cx).date().into()
303 }
304 }
305
306 pub fn input_editors(
308 &self,
309 cx: &App,
310 ) -> (&Entity<TextFieldState>, Option<&Entity<TextFieldState>>) {
311 let range = !self.calendar.read(cx).date().is_single();
312 (&self.start, range.then_some(&self.end))
313 }
314
315 pub fn set_draft(
317 &mut self,
318 draft: DatePickerDraft,
319 window: &mut Window,
320 cx: &mut Context<Self>,
321 ) -> bool {
322 let draft = draft.into();
323 if !self.limits.accepts_draft(draft) {
324 return false;
325 }
326 self.apply_draft(draft, cx);
327 self.show_month(self.cursor, cx);
328 self.reset_input(draft, &self.locale, window, cx);
329 self.input_attempted = false;
330 cx.notify();
331 true
332 }
333
334 pub fn display_mode(&self) -> DatePickerDisplayMode {
336 if self.input_mode {
337 DatePickerDisplayMode::Input
338 } else {
339 DatePickerDisplayMode::Calendar
340 }
341 }
342
343 pub fn set_display_mode(
345 &mut self,
346 mode: DatePickerDisplayMode,
347 window: &mut Window,
348 cx: &mut Context<Self>,
349 ) -> bool {
350 let input = mode == DatePickerDisplayMode::Input;
351 if self.input_mode == input {
352 return true;
353 }
354 if self.input_mode && self.input_composing(window, cx) {
355 return false;
356 }
357 self.input_attempted = false;
358 if self.input_mode {
359 let draft = self.input_draft(cx);
360 self.apply_draft(draft, cx);
361 if let Some(day) = draft.start().map(super::from_base_date) {
362 self.set_displayed_month(day, cx);
363 }
364 } else {
365 self.reset_input(self.calendar.read(cx).date(), &self.locale, window, cx);
366 }
367 self.input_mode = input;
368 self.year_page = None;
369 if self.is_open(cx) {
370 self.default_focus(cx).focus(window, cx);
371 }
372 cx.notify();
373 true
374 }
375
376 fn default_focus(&self, cx: &App) -> FocusHandle {
377 if self.input_mode {
378 self.start.read(cx).focus_handle(cx)
379 } else {
380 self.day.clone()
381 }
382 }
383
384 pub(super) fn input_composing(&self, window: &mut Window, cx: &mut App) -> bool {
385 [&self.start, &self.end].into_iter().any(|field| {
386 field.update(cx, |field, cx| {
387 field.marked_text_range(window, cx).is_some()
388 })
389 })
390 }
391
392 fn apply_draft(&self, draft: Date, cx: &mut Context<Self>) {
393 let limits = self.limits.clone();
394 self.calendar.update(cx, |calendar, _| {
395 calendar.set_disabled_matcher_shared(Some(Rc::new(Matcher::custom(move |date| {
396 !limits.accepts(super::from_base_date(*date))
397 }))));
398 calendar.apply_date(draft);
399 });
400 }
401
402 fn show_month(&self, date: NaiveDate, cx: &mut Context<Self>) -> bool {
403 self.calendar.update(cx, |calendar, _| {
404 let year = date.year();
405 let month = date.month();
406 let changed = calendar.offset_year_month(0) != (year, month);
407 if changed {
408 calendar.select_year(year);
409 calendar.select_month(month as u8);
410 }
411 changed
412 })
413 }
414
415 pub fn open(
417 &mut self,
418 value: DateSelection,
419 variant: DatePickerVariant,
420 locale: &DatePickerLocale,
421 window: &mut Window,
422 cx: &mut Context<Self>,
423 ) {
424 if self.is_open(cx) {
425 return;
426 }
427 self.variant = variant;
428 self.locale = locale.clone();
429 self.locale_initialized = true;
430 let draft = value.draft();
431 let draft = if self.limits.accepts_draft(draft) {
432 draft
433 } else if draft.is_single() {
434 Date::Single(None)
435 } else {
436 Date::Range(None, None)
437 };
438 self.apply_draft(draft, cx);
439 let today = super::from_base_date(self.calendar.read(cx).today());
440 self.set_displayed_month(
441 self.initial_month
442 .or(draft.start().map(super::from_base_date))
443 .unwrap_or(today),
444 cx,
445 );
446 self.reset_input(draft, locale, window, cx);
447 self.input_mode = variant == DatePickerVariant::ModalInput;
448 self.input_attempted = false;
449 if variant == DatePickerVariant::Docked {
450 self.docked_previous = window.focused(cx).map(|focus| focus.downgrade());
451 self.docked_open = true;
452 self.docked_generation = self.docked_generation.wrapping_add(1);
453 } else {
454 self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
455 }
456 self.default_focus(cx).focus(window, cx);
457 cx.notify();
458 }
459
460 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
462 if self.docked_open {
463 self.dismiss_docked(DialogCloseReason::Programmatic, window, cx);
464 } else {
465 self.dialog
466 .update(cx, |dialog, cx| dialog.close(window, cx));
467 }
468 }
469
470 pub(super) fn reset_input(
471 &self,
472 draft: Date,
473 locale: &DatePickerLocale,
474 window: &mut Window,
475 cx: &mut Context<Self>,
476 ) {
477 let format = |date: Option<NaiveDate>| {
478 date.map_or_else(SharedString::default, |date| (locale.format)(date))
479 };
480 self.start.update(cx, |field, cx| {
481 field.set_value(format(draft.start().map(super::from_base_date)), window, cx)
482 });
483 self.end.update(cx, |field, cx| {
484 field.set_value(format(draft.end().map(super::from_base_date)), window, cx)
485 });
486 }
487
488 pub(super) fn input_value(
489 &self,
490 locale: &DatePickerLocale,
491 cx: &App,
492 ) -> Result<DateSelection, DateError> {
493 let start = self.start.read(cx).value();
494 let end = self.end.read(cx).value();
495 let range = !self.calendar.read(cx).date().is_single();
496 parse_selection(&start, range.then_some(end.as_ref()), locale, &self.limits)
497 }
498
499 fn input_draft(&self, cx: &App) -> Date {
500 let parse = |field: &Entity<TextFieldState>| {
501 let text = field.read(cx).value();
502 (self.locale.parse)(text.trim()).filter(|date| self.limits.accepts(*date))
503 };
504 let start = parse(&self.start);
505 if self.calendar.read(cx).date().is_single() {
506 return Date::Single(start.and_then(super::to_base_date));
507 }
508 let end = parse(&self.end).filter(|end| start.is_some_and(|start| start <= *end));
509 Date::Range(
510 start.and_then(super::to_base_date),
511 end.and_then(super::to_base_date),
512 )
513 }
514
515 pub(super) fn dismiss_docked(
516 &mut self,
517 reason: DialogCloseReason,
518 window: &mut Window,
519 cx: &mut Context<Self>,
520 ) -> bool {
521 if !self.docked_open {
522 return false;
523 }
524 self.docked_open = false;
525 self.docked_reason = Some(reason);
526 let previous = self.docked_previous.take();
527 if self.docked.contains_focused(window, cx) || self.docked.is_focused(window) {
528 if let Some(focus) = previous.and_then(|focus| focus.upgrade()) {
529 focus.focus(window, cx);
530 } else {
531 window.blur(cx);
532 }
533 }
534 cx.notify();
535 true
536 }
537
538 pub(super) fn select_day(
539 &mut self,
540 date: NaiveDate,
541 cx: &mut Context<Self>,
542 ) -> Option<DateSelection> {
543 if !self.limits.accepts(date) {
544 return None;
545 }
546 self.cursor = date;
547 let result = self.calendar.update(cx, |calendar, _| {
548 if let Some(base_date) = super::to_base_date(date) {
549 calendar.select_date(base_date);
550 }
551 complete(calendar.date())
552 });
553 self.show_month(date, cx);
556 self.input_attempted = false;
557 cx.notify();
558 result
559 }
560
561 pub(super) fn navigate(
562 &mut self,
563 key: &str,
564 control: bool,
565 direction: Direction,
566 first_day: Weekday,
567 cx: &mut Context<Self>,
568 ) -> bool {
569 let rtl = direction == Direction::Rtl;
570 let offset = (self.cursor.weekday().num_days_from_monday() + 7
571 - first_day.num_days_from_monday())
572 % 7;
573 let candidate = match key {
574 "left" | "right" => {
575 if (key == "left") != rtl {
576 self.cursor.pred_opt()
577 } else {
578 self.cursor.succ_opt()
579 }
580 }
581 "up" => self.cursor.checked_sub_days(Days::new(7)),
582 "down" => self.cursor.checked_add_days(Days::new(7)),
583 "home" => self.cursor.checked_sub_days(Days::new(u64::from(offset))),
584 "end" => self
585 .cursor
586 .checked_add_days(Days::new(u64::from(6 - offset))),
587 "pageup" => self
588 .cursor
589 .checked_sub_months(Months::new(if control { 12 } else { 1 })),
590 "pagedown" => self
591 .cursor
592 .checked_add_months(Months::new(if control { 12 } else { 1 })),
593 _ => return false,
594 };
595 if let Some(date) = candidate {
596 let clamped = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
597 let month_changed = self.show_month(clamped, cx);
598 if self.cursor != clamped || month_changed {
599 self.cursor = clamped;
600 cx.notify();
601 }
602 }
603 true
604 }
605}
606
607#[cfg(test)]
608mod tests {
609 use super::*;
610
611 #[test]
612 fn local_date_parsing_rejects_invalid_disabled_and_reversed_endpoints() {
613 let first = NaiveDate::from_ymd_opt(2024, 2, 1).unwrap();
614 let last = NaiveDate::from_ymd_opt(2024, 2, 29).unwrap();
615 let locale = DatePickerLocale::default().input_format(
616 |date| date.format("%d/%m/%Y").to_string().into(),
617 |text| NaiveDate::parse_from_str(text, "%d/%m/%Y").ok(),
618 );
619 let limits = DateLimits {
620 bounds: first..=last,
621 disabled: Arc::new(|date| date.day() == 10),
622 disabled_years: Arc::new(|_| false),
623 };
624 assert_eq!(
625 parse_selection(" 29/02/2024 ", None, &locale, &limits),
626 Ok(DateSelection::Single(Some(last)))
627 );
628 assert_eq!(
629 parse_selection("30/02/2024", None, &locale, &limits),
630 Err(DateError::Invalid)
631 );
632 assert_eq!(
633 parse_selection("01/03/2024", None, &locale, &limits),
634 Err(DateError::Disabled)
635 );
636 assert_eq!(
637 parse_selection("01/02/2024", Some("10/02/2024"), &locale, &limits),
638 Err(DateError::Disabled)
639 );
640 assert_eq!(
641 parse_selection("29/02/2024", Some("01/02/2024"), &locale, &limits),
642 Err(DateError::Order)
643 );
644 assert_eq!(
645 parse_selection("01/02/2024", Some("29/02/2024"), &locale, &limits),
646 Ok(DateSelection::Range(Some((first, last))))
647 );
648 }
649}