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();
53 let end = draft.end();
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 = 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() {
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(*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 = self.calendar.read(cx).today();
440 self.set_displayed_month(self.initial_month.or(draft.start()).unwrap_or(today), cx);
441 self.reset_input(draft, locale, window, cx);
442 self.input_mode = variant == DatePickerVariant::ModalInput;
443 self.input_attempted = false;
444 if variant == DatePickerVariant::Docked {
445 self.docked_previous = window.focused(cx).map(|focus| focus.downgrade());
446 self.docked_open = true;
447 self.docked_generation = self.docked_generation.wrapping_add(1);
448 } else {
449 self.dialog.update(cx, |dialog, cx| dialog.open(window, cx));
450 }
451 self.default_focus(cx).focus(window, cx);
452 cx.notify();
453 }
454
455 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
457 if self.docked_open {
458 self.dismiss_docked(DialogCloseReason::Programmatic, window, cx);
459 } else {
460 self.dialog
461 .update(cx, |dialog, cx| dialog.close(window, cx));
462 }
463 }
464
465 pub(super) fn reset_input(
466 &self,
467 draft: Date,
468 locale: &DatePickerLocale,
469 window: &mut Window,
470 cx: &mut Context<Self>,
471 ) {
472 let format = |date: Option<NaiveDate>| {
473 date.map_or_else(SharedString::default, |date| (locale.format)(date))
474 };
475 self.start.update(cx, |field, cx| {
476 field.set_value(format(draft.start()), window, cx)
477 });
478 self.end.update(cx, |field, cx| {
479 field.set_value(format(draft.end()), window, cx)
480 });
481 }
482
483 pub(super) fn input_value(
484 &self,
485 locale: &DatePickerLocale,
486 cx: &App,
487 ) -> Result<DateSelection, DateError> {
488 let start = self.start.read(cx).value();
489 let end = self.end.read(cx).value();
490 let range = !self.calendar.read(cx).date().is_single();
491 parse_selection(&start, range.then_some(end.as_ref()), locale, &self.limits)
492 }
493
494 fn input_draft(&self, cx: &App) -> Date {
495 let parse = |field: &Entity<TextFieldState>| {
496 let text = field.read(cx).value();
497 (self.locale.parse)(text.trim()).filter(|date| self.limits.accepts(*date))
498 };
499 let start = parse(&self.start);
500 if self.calendar.read(cx).date().is_single() {
501 return Date::Single(start);
502 }
503 let end = parse(&self.end).filter(|end| start.is_some_and(|start| start <= *end));
504 Date::Range(start, end)
505 }
506
507 pub(super) fn dismiss_docked(
508 &mut self,
509 reason: DialogCloseReason,
510 window: &mut Window,
511 cx: &mut Context<Self>,
512 ) -> bool {
513 if !self.docked_open {
514 return false;
515 }
516 self.docked_open = false;
517 self.docked_reason = Some(reason);
518 let previous = self.docked_previous.take();
519 if self.docked.contains_focused(window, cx) || self.docked.is_focused(window) {
520 if let Some(focus) = previous.and_then(|focus| focus.upgrade()) {
521 focus.focus(window, cx);
522 } else {
523 window.blur(cx);
524 }
525 }
526 cx.notify();
527 true
528 }
529
530 pub(super) fn select_day(
531 &mut self,
532 date: NaiveDate,
533 cx: &mut Context<Self>,
534 ) -> Option<DateSelection> {
535 if !self.limits.accepts(date) {
536 return None;
537 }
538 self.cursor = date;
539 let result = self.calendar.update(cx, |calendar, _| {
540 calendar.select_date(date);
541 complete(calendar.date())
542 });
543 self.show_month(date, cx);
546 self.input_attempted = false;
547 cx.notify();
548 result
549 }
550
551 pub(super) fn navigate(
552 &mut self,
553 key: &str,
554 control: bool,
555 direction: Direction,
556 first_day: Weekday,
557 cx: &mut Context<Self>,
558 ) -> bool {
559 let rtl = direction == Direction::Rtl;
560 let offset = (self.cursor.weekday().num_days_from_monday() + 7
561 - first_day.num_days_from_monday())
562 % 7;
563 let candidate = match key {
564 "left" | "right" => {
565 if (key == "left") != rtl {
566 self.cursor.pred_opt()
567 } else {
568 self.cursor.succ_opt()
569 }
570 }
571 "up" => self.cursor.checked_sub_days(Days::new(7)),
572 "down" => self.cursor.checked_add_days(Days::new(7)),
573 "home" => self.cursor.checked_sub_days(Days::new(u64::from(offset))),
574 "end" => self
575 .cursor
576 .checked_add_days(Days::new(u64::from(6 - offset))),
577 "pageup" => self
578 .cursor
579 .checked_sub_months(Months::new(if control { 12 } else { 1 })),
580 "pagedown" => self
581 .cursor
582 .checked_add_months(Months::new(if control { 12 } else { 1 })),
583 _ => return false,
584 };
585 if let Some(date) = candidate {
586 let clamped = date.clamp(*self.limits.bounds.start(), *self.limits.bounds.end());
587 let month_changed = self.show_month(clamped, cx);
588 if self.cursor != clamped || month_changed {
589 self.cursor = clamped;
590 cx.notify();
591 }
592 }
593 true
594 }
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600
601 #[test]
602 fn local_date_parsing_rejects_invalid_disabled_and_reversed_endpoints() {
603 let first = NaiveDate::from_ymd_opt(2024, 2, 1).unwrap();
604 let last = NaiveDate::from_ymd_opt(2024, 2, 29).unwrap();
605 let locale = DatePickerLocale::default().input_format(
606 |date| date.format("%d/%m/%Y").to_string().into(),
607 |text| NaiveDate::parse_from_str(text, "%d/%m/%Y").ok(),
608 );
609 let limits = DateLimits {
610 bounds: first..=last,
611 disabled: Arc::new(|date| date.day() == 10),
612 disabled_years: Arc::new(|_| false),
613 };
614 assert_eq!(
615 parse_selection(" 29/02/2024 ", None, &locale, &limits),
616 Ok(DateSelection::Single(Some(last)))
617 );
618 assert_eq!(
619 parse_selection("30/02/2024", None, &locale, &limits),
620 Err(DateError::Invalid)
621 );
622 assert_eq!(
623 parse_selection("01/03/2024", None, &locale, &limits),
624 Err(DateError::Disabled)
625 );
626 assert_eq!(
627 parse_selection("01/02/2024", Some("10/02/2024"), &locale, &limits),
628 Err(DateError::Disabled)
629 );
630 assert_eq!(
631 parse_selection("29/02/2024", Some("01/02/2024"), &locale, &limits),
632 Err(DateError::Order)
633 );
634 assert_eq!(
635 parse_selection("01/02/2024", Some("29/02/2024"), &locale, &limits),
636 Ok(DateSelection::Range(Some((first, last))))
637 );
638 }
639}