-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathindex.tsx
More file actions
2059 lines (1880 loc) · 60.3 KB
/
index.tsx
File metadata and controls
2059 lines (1880 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { clsx } from "clsx";
import React, { Component, cloneElement } from "react";
import Calendar, { OUTSIDE_CLICK_IGNORE_CLASS } from "./calendar";
import CalendarIcon from "./calendar_icon";
import {
newDate,
isDate,
isBefore,
isAfter,
isEqual,
setTime,
isValid,
getSeconds,
getMinutes,
getHours,
addDays,
addMinutes,
addMonths,
addWeeks,
subDays,
subMonths,
subWeeks,
addYears,
subYears,
isDayDisabled,
isDayInRange,
getEffectiveMinDate,
getEffectiveMaxDate,
parseDate,
parseDateForNavigation,
formatDate,
safeDateFormat,
safeDateRangeFormat,
getHighLightDaysMap,
getYear,
getMonth,
getStartOfWeek,
getEndOfWeek,
registerLocale,
setDefaultLocale,
getDefaultLocale,
DEFAULT_YEAR_ITEM_NUMBER,
isSameDay,
isMonthDisabled,
isYearDisabled,
safeMultipleDatesFormat,
getHolidaysMap,
isDateBefore,
getStartOfDay,
getEndOfDay,
isSameMinute,
toZonedTime,
fromZonedTime,
setDateFnsTzModule,
safeToDate,
type HighlightDate,
type HolidayItem,
type TimeZone,
KeyType,
DATE_RANGE_SEPARATOR,
} from "./date_utils";
import PopperComponent from "./popper_component";
import Portal from "./portal";
import TabLoop from "./tab_loop";
import type { ClickOutsideHandler } from "./click_outside_wrapper";
export { default as CalendarContainer } from "./calendar_container";
export {
registerLocale,
setDefaultLocale,
getDefaultLocale,
setDateFnsTzModule,
};
export {
ReactDatePickerCustomHeaderProps,
ReactDatePickerCustomDayNameProps,
} from "./calendar";
// Compares dates year+month combinations
function hasPreSelectionChanged(
date1?: Date | null,
date2?: Date | null,
): boolean {
if (date1 && date2) {
return (
getMonth(date1) !== getMonth(date2) || getYear(date1) !== getYear(date2)
);
}
return date1 !== date2;
}
/**
* General datepicker component.
*/
const INPUT_ERR_1 = "Date input not valid.";
interface Holiday {
date: string;
holidayName: string;
}
type CalendarProps = React.ComponentPropsWithoutRef<typeof Calendar>;
interface CalendarIconProps extends React.ComponentPropsWithoutRef<
typeof CalendarIcon
> {}
interface PortalProps extends React.ComponentPropsWithoutRef<typeof Portal> {}
interface PopperComponentProps extends React.ComponentPropsWithoutRef<
typeof PopperComponent
> {}
// see https://github.com/microsoft/TypeScript/issues/31501
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type OmitUnion<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
export type DatePickerProps = OmitUnion<
CalendarProps,
| "setOpen"
| "dateFormat"
| "preSelection"
| "onSelect"
| "onClickOutside"
| "highlightDates"
| "holidays"
| "shouldFocusDayInline"
| "monthSelectedIn"
| "onDropdownFocus"
| "onTimeChange"
| "className"
| "container"
| "handleOnKeyDown"
| "handleOnDayKeyDown"
| "isInputFocused"
| "setPreSelection"
| "selectsRange"
| "selectsMultiple"
| "dropdownMode"
> &
Partial<Pick<CalendarIconProps, "icon">> &
OmitUnion<PortalProps, "children" | "portalId"> &
OmitUnion<
PopperComponentProps,
| "className"
| "hidePopper"
| "targetComponent"
| "popperComponent"
| "popperOnKeyDown"
| "showArrow"
> & {
dateFormatCalendar?: CalendarProps["dateFormat"];
calendarClassName?: CalendarProps["className"];
calendarContainer?: CalendarProps["container"];
dropdownMode?: CalendarProps["dropdownMode"];
onKeyDown?: (event: React.KeyboardEvent<HTMLElement>) => void;
popperClassName?: PopperComponentProps["className"];
showPopperArrow?: PopperComponentProps["showArrow"];
popperTargetRef?: React.RefObject<HTMLElement | null>;
open?: boolean;
disabled?: boolean;
readOnly?: boolean;
startOpen?: boolean;
onFocus?: React.FocusEventHandler<HTMLElement>;
onBlur?: React.FocusEventHandler<HTMLElement>;
onClickOutside?: ClickOutsideHandler;
onInputClick?: VoidFunction;
preventOpenOnFocus?: boolean;
closeOnScroll?: boolean | ((event: Event) => boolean);
isClearable?: boolean;
clearButtonTitle?: string;
clearButtonClassName?: string;
ariaLabelClose?: string;
className?: string;
customInput?: Parameters<typeof cloneElement>[0];
dateFormat?: string | string[];
showDateSelect?: boolean;
highlightDates?: (Date | HighlightDate)[];
onCalendarOpen?: VoidFunction;
onCalendarClose?: VoidFunction;
strictParsing?: boolean;
swapRange?: boolean;
onInputError?: (error: { code: 1; msg: string }) => void;
allowSameDay?: boolean;
withPortal?: boolean;
focusSelectedMonth?: boolean;
showIcon?: boolean;
calendarIconClassname?: never;
calendarIconClassName?: string;
toggleCalendarOnIconClick?: boolean;
holidays?: Holiday[];
startDate?: Date | null;
endDate?: Date | null;
selected?: Date | null;
/**
* The IANA timezone identifier (e.g., "America/New_York", "UTC", "Europe/London").
* When set, the datepicker will display dates/times in this timezone and
* the onChange callback will return dates adjusted to this timezone.
*
* Requires the optional peer dependency `date-fns-tz` to be installed:
* ```
* npm install date-fns-tz
* ```
*
* @example
* ```tsx
* <DatePicker
* timeZone="America/New_York"
* selected={selectedDate}
* onChange={(date) => setSelectedDate(date)}
* />
* ```
*/
timeZone?: TimeZone;
value?: string;
customInputRef?: string;
id?: string;
name?: string;
form?: string;
autoFocus?: boolean;
placeholderText?: string;
autoComplete?: string;
title?: string;
required?: boolean;
tabIndex?: number;
ariaDescribedBy?: string;
ariaInvalid?: string;
ariaLabel?: string;
ariaLabelledBy?: string;
ariaRequired?: string;
"aria-describedby"?: string;
"aria-invalid"?: string;
"aria-label"?: string;
"aria-labelledby"?: string;
"aria-required"?: string;
rangeSeparator?: string;
onChangeRaw?: (
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
selectionMeta?: {
date: Date;
formattedDate: string;
},
) => void;
onSelect?: (
date: Date | null,
event?:
| React.MouseEvent<HTMLElement, MouseEvent>
| React.KeyboardEvent<HTMLElement>,
) => void;
} & (
| {
selectsRange?: false | undefined;
selectsMultiple?: false | undefined;
formatMultipleDates?: never;
onChange?: (
date: Date | null,
event?:
| React.MouseEvent<HTMLElement>
| React.KeyboardEvent<HTMLElement>,
) => void;
}
| {
selectsRange: true;
selectsMultiple?: false | undefined;
formatMultipleDates?: never;
onChange?: (
date: [Date | null, Date | null],
event?:
| React.MouseEvent<HTMLElement>
| React.KeyboardEvent<HTMLElement>,
) => void;
}
| {
selectsRange?: false | undefined;
selectsMultiple: true;
formatMultipleDates?: (
dates: Date[],
formatDate: (date: Date) => string,
) => string;
onChange?: (
dates: Date[] | null,
event?:
| React.MouseEvent<HTMLElement>
| React.KeyboardEvent<HTMLElement>,
) => void;
}
);
// Internal types for onChange handlers - used for type assertions within the component
type OnChangeSingle = (
date: Date | null,
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
) => void;
type OnChangeRange = (
date: [Date | null, Date | null],
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
) => void;
type OnChangeMultiple = (
dates: Date[] | null,
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
) => void;
interface DatePickerState {
open: boolean;
wasHidden: boolean;
lastPreSelectChange?:
| typeof PRESELECT_CHANGE_VIA_INPUT
| typeof PRESELECT_CHANGE_VIA_NAVIGATE;
inputValue: string | null;
preventFocus: boolean;
preSelection?: CalendarProps["preSelection"];
shouldFocusDayInline?: CalendarProps["shouldFocusDayInline"];
monthSelectedIn?: CalendarProps["monthSelectedIn"];
focused?: CalendarProps["isInputFocused"];
highlightDates: Required<CalendarProps>["highlightDates"];
isRenderAriaLiveMessage?: boolean;
}
export class DatePicker extends Component<DatePickerProps, DatePickerState> {
static get defaultProps() {
return {
allowSameDay: false,
dateFormat: "MM/dd/yyyy",
dateFormatCalendar: "LLLL yyyy",
disabled: false,
disabledKeyboardNavigation: false,
dropdownMode: "scroll" as const,
preventOpenOnFocus: false,
monthsShown: 1,
outsideClickIgnoreClass: OUTSIDE_CLICK_IGNORE_CLASS,
readOnly: false,
rangeSeparator: DATE_RANGE_SEPARATOR,
withPortal: false,
selectsDisabledDaysInRange: false,
shouldCloseOnSelect: true,
showTimeSelect: false,
showTimeInput: false,
showPreviousMonths: false,
showMonthYearPicker: false,
showFullMonthYearPicker: false,
showTwoColumnMonthYearPicker: false,
showFourColumnMonthYearPicker: false,
showYearPicker: false,
showQuarterYearPicker: false,
showWeekPicker: false,
strictParsing: false,
swapRange: false,
timeIntervals: 30,
timeCaption: "Time",
previousMonthAriaLabel: "Previous Month",
previousMonthButtonLabel: "Previous Month",
nextMonthAriaLabel: "Next Month",
nextMonthButtonLabel: "Next Month",
previousYearAriaLabel: "Previous Year",
previousYearButtonLabel: "Previous Year",
nextYearAriaLabel: "Next Year",
nextYearButtonLabel: "Next Year",
timeInputLabel: "Time",
enableTabLoop: true,
yearItemNumber: DEFAULT_YEAR_ITEM_NUMBER,
focusSelectedMonth: false,
showPopperArrow: true,
excludeScrollbar: true,
customTimeInput: null,
calendarStartDay: undefined,
toggleCalendarOnIconClick: false,
usePointerEvent: false,
};
}
constructor(props: DatePickerProps) {
super(props);
this.state = this.calcInitialState();
this.preventFocusTimeout = undefined;
}
componentDidMount(): void {
window.addEventListener("scroll", this.onScroll, true);
document.addEventListener(
"visibilitychange",
this.setHiddenStateOnVisibilityHidden,
);
}
componentDidUpdate(
prevProps: DatePickerProps,
prevState: DatePickerState,
): void {
// Update preSelection when selected/startDate prop changes to a different month/year.
// This ensures the calendar view updates when dates are programmatically set
// (e.g., via "Today" or "This Week" buttons). (Fix for #3367)
if (
this.props.selectsRange &&
hasPreSelectionChanged(prevProps.startDate, this.props.startDate)
) {
this.setPreSelection(this.props.startDate);
} else if (
hasPreSelectionChanged(prevProps.selected, this.props.selected)
) {
this.setPreSelection(this.props.selected);
}
if (
this.state.monthSelectedIn !== undefined &&
prevProps.monthsShown !== this.props.monthsShown
) {
this.setState({ monthSelectedIn: 0 });
}
// Reset monthSelectedIn when calendar opens for range selection
// This ensures startDate is displayed as the first month when reopening
// (Fix for #5939), but we don't reset during active selection to avoid
// the view jumping when clicking dates in the second calendar (Fix for #5275)
if (
this.props.selectsRange &&
prevState.open === false &&
this.state.open === true &&
this.state.monthSelectedIn !== 0
) {
this.setState({ monthSelectedIn: 0 });
}
if (prevProps.highlightDates !== this.props.highlightDates) {
this.setState({
highlightDates: getHighLightDaysMap(this.props.highlightDates),
});
}
if (
!prevState.focused &&
!isEqual(prevProps.selected, this.props.selected)
) {
this.setState({ inputValue: null });
}
if (prevState.open !== this.state.open) {
if (prevState.open === false && this.state.open === true) {
this.props.onCalendarOpen?.();
}
if (prevState.open === true && this.state.open === false) {
this.props.onCalendarClose?.();
}
}
}
componentWillUnmount(): void {
this.clearPreventFocusTimeout();
window.removeEventListener("scroll", this.onScroll, true);
document.removeEventListener(
"visibilitychange",
this.setHiddenStateOnVisibilityHidden,
);
}
preventFocusTimeout: ReturnType<typeof setTimeout> | undefined;
inputFocusTimeout: ReturnType<typeof setTimeout> | undefined;
calendar: Calendar | null = null;
input: HTMLElement | null = null;
getPreSelection = (): Date => {
const { timeZone } = this.props;
const baseDate = this.props.openToDate
? this.props.openToDate
: this.props.selectsEnd && this.props.startDate
? this.props.startDate
: this.props.selectsStart && this.props.endDate
? this.props.endDate
: newDate();
// Convert to the specified timezone for display
return timeZone ? toZonedTime(baseDate, timeZone) : baseDate;
};
// Convert the date from string format to standard Date format
// Uses parseDate with ISO format to parse as local time, preventing
// dates from shifting in timezones west of UTC. See issue #6105.
modifyHolidays = () =>
this.props.holidays?.reduce<HolidayItem[]>((accumulator, holiday) => {
const date = parseDate(holiday.date, "yyyy-MM-dd", undefined, false);
if (!date) {
return accumulator;
}
return [...accumulator, { ...holiday, date }];
}, []);
calcInitialState = (): DatePickerState => {
const { timeZone } = this.props;
const defaultPreSelection = this.getPreSelection();
const minDate = getEffectiveMinDate(this.props);
const maxDate = getEffectiveMaxDate(this.props);
const boundedPreSelection =
minDate && isBefore(defaultPreSelection, getStartOfDay(minDate))
? minDate
: maxDate && isAfter(defaultPreSelection, getEndOfDay(maxDate))
? maxDate
: defaultPreSelection;
// Convert selected/startDate to zoned time for display if timezone is specified
let initialPreSelection = this.props.selectsRange
? this.props.startDate
: this.props.selected;
if (initialPreSelection && timeZone) {
initialPreSelection = toZonedTime(initialPreSelection, timeZone);
}
return {
open: this.props.startOpen || false,
preventFocus: false,
inputValue: null,
preSelection: initialPreSelection ?? boundedPreSelection,
// transforming highlighted days (perhaps nested array)
// to flat Map for faster access in day.jsx
highlightDates: getHighLightDaysMap(this.props.highlightDates),
focused: false,
// used to focus day in inline version after month has changed, but not on
// initial render
shouldFocusDayInline: false,
isRenderAriaLiveMessage: false,
wasHidden: false,
};
};
getInputValue = (): string => {
const {
locale,
startDate,
endDate,
rangeSeparator,
selected,
selectedDates,
selectsMultiple,
selectsRange,
formatMultipleDates,
value,
timeZone,
} = this.props;
const dateFormat =
this.props.dateFormat ?? DatePicker.defaultProps.dateFormat;
const { inputValue } = this.state;
if (typeof value === "string") {
return value;
} else if (typeof inputValue === "string") {
return inputValue;
} else if (selectsRange) {
return safeDateRangeFormat(startDate, endDate, {
dateFormat,
locale,
rangeSeparator,
timeZone,
});
} else if (selectsMultiple) {
if (formatMultipleDates) {
const formatDateFn = (date: Date) =>
safeDateFormat(date, { dateFormat, locale, timeZone });
return formatMultipleDates(selectedDates ?? [], formatDateFn);
}
return safeMultipleDatesFormat(selectedDates ?? [], {
dateFormat,
locale,
timeZone,
});
}
return safeDateFormat(selected, {
dateFormat,
locale,
timeZone,
});
};
resetHiddenStatus = (): void => {
this.setState({
...this.state,
wasHidden: false,
});
};
setHiddenStatus = (): void => {
this.setState({
...this.state,
wasHidden: true,
});
};
setHiddenStateOnVisibilityHidden = (): void => {
if (document.visibilityState !== "hidden") {
return;
}
this.setHiddenStatus();
};
clearPreventFocusTimeout = () => {
if (this.preventFocusTimeout) {
clearTimeout(this.preventFocusTimeout);
}
};
setFocus = () => {
this.input?.focus?.({ preventScroll: true });
};
setBlur = () => {
this.input?.blur?.();
this.cancelFocusInput();
};
deferBlur = () => {
requestAnimationFrame(() => {
this.setBlur();
});
};
setOpen = (open: boolean, skipSetBlur: boolean = false): void => {
this.setState(
{
open: open,
preSelection:
open && this.state.open
? this.state.preSelection
: this.calcInitialState().preSelection,
lastPreSelectChange: PRESELECT_CHANGE_VIA_NAVIGATE,
},
() => {
if (!open) {
this.setState(
(prev: DatePickerState) => ({
focused: skipSetBlur ? prev.focused : false,
}),
() => {
!skipSetBlur && this.deferBlur();
this.setState({ inputValue: null });
},
);
}
},
);
};
inputOk = (): boolean => isDate(this.state.preSelection);
isCalendarOpen = () =>
this.props.open === undefined
? this.state.open && !this.props.disabled && !this.props.readOnly
: this.props.open;
handleFocus = (event: React.FocusEvent<HTMLElement>): void => {
const isAutoReFocus = this.state.wasHidden;
const isOpenAllowed = isAutoReFocus ? this.state.open : true;
if (isAutoReFocus) {
this.resetHiddenStatus();
}
if (!this.state.preventFocus) {
this.props.onFocus?.(event);
if (
isOpenAllowed &&
!this.props.preventOpenOnFocus &&
!this.props.readOnly
) {
this.setOpen(true);
}
}
this.setState({ focused: true });
};
sendFocusBackToInput = (): void => {
// Clear previous timeout if it exists
if (this.preventFocusTimeout) {
this.clearPreventFocusTimeout();
}
// close the popper and refocus the input
// stop the input from auto opening onFocus
// setFocus to the input
this.setState({ preventFocus: true }, (): void => {
this.preventFocusTimeout = setTimeout((): void => {
this.setFocus();
this.setState({ preventFocus: false });
});
});
};
cancelFocusInput = () => {
clearTimeout(this.inputFocusTimeout);
this.inputFocusTimeout = undefined;
};
deferFocusInput = () => {
this.cancelFocusInput();
this.inputFocusTimeout = setTimeout(() => this.setFocus(), 1);
};
handleDropdownFocus = () => {
this.cancelFocusInput();
};
resetInputValue = () => {
this.setState({
...this.state,
inputValue: null,
});
};
handleBlur = (event: React.FocusEvent<HTMLElement>) => {
if (!this.state.open || this.props.withPortal || this.props.showTimeInput) {
this.props.onBlur?.(event);
}
// If user cleared the input via a mask library (inputValue has no date-like
// characters), clear the selection on blur (fixes issue #5814 with mask inputs)
const { inputValue } = this.state;
if (typeof inputValue === "string" && inputValue.length > 0) {
// Check if input looks like a cleared mask (no alphanumeric characters)
// This distinguishes between:
// - "__/__/____" (cleared mask) → should clear selection
// - "2025-02-45" (invalid date) → should keep previous selection
const hasDateCharacters = /[a-zA-Z0-9]/.test(inputValue);
if (!hasDateCharacters && this.props.selected) {
this.setSelected(null, undefined, true);
}
}
this.resetInputValue();
if (this.state.open && this.props.open === false) {
this.setOpen(false);
}
this.setState({ focused: false });
};
handleCalendarClickOutside = (event: MouseEvent) => {
// Call user's onClickOutside first, allowing them to call preventDefault()
this.props.onClickOutside?.(event);
// Only close if not prevented and not inline
if (!this.props.inline && !event.defaultPrevented) {
this.setOpen(false);
}
if (this.props.withPortal) {
event.preventDefault();
}
};
// handleChange is called when user types in the textbox
handleChange = (
...allArgs: Parameters<Required<DatePickerProps>["onChangeRaw"]>
) => {
const event = allArgs[0];
if (this.props.onChangeRaw) {
this.props.onChangeRaw.apply(this, allArgs);
if (
!event ||
typeof event.isDefaultPrevented !== "function" ||
event.isDefaultPrevented()
) {
return;
}
}
this.setState({
inputValue:
event?.target instanceof HTMLInputElement ? event.target.value : null,
lastPreSelectChange: PRESELECT_CHANGE_VIA_INPUT,
});
const { selectsRange, startDate, endDate } = this.props;
const dateFormat =
this.props.dateFormat ?? DatePicker.defaultProps.dateFormat;
const strictParsing =
this.props.strictParsing ?? DatePicker.defaultProps.strictParsing;
const value =
event?.target instanceof HTMLInputElement ? event.target.value : "";
if (selectsRange) {
const rangeSeparator = this.props.rangeSeparator as string;
const trimmedRangeSeparator = rangeSeparator.trim();
const [valueStart, valueEnd] = value
.split(
dateFormat.includes(trimmedRangeSeparator)
? rangeSeparator
: trimmedRangeSeparator,
2,
)
.map((val) => val.trim());
const startDateNew = parseDate(
valueStart ?? "",
dateFormat,
this.props.locale,
strictParsing,
);
const endDateNew = startDateNew
? parseDate(
valueEnd ?? "",
dateFormat,
this.props.locale,
strictParsing,
)
: null;
const startChanged =
safeToDate(startDate)?.getTime() !== startDateNew?.getTime();
const endChanged =
safeToDate(endDate)?.getTime() !== endDateNew?.getTime();
if (!startChanged && !endChanged) {
return;
}
if (startDateNew && isDayDisabled(startDateNew, this.props)) {
return;
}
if (endDateNew && isDayDisabled(endDateNew, this.props)) {
return;
}
// Update preSelection to keep calendar viewport consistent when reopening
// Use startDate for preSelection to match calcInitialState behavior
if (startDateNew) {
this.setState({ preSelection: startDateNew });
}
this.props.onChange?.([startDateNew, endDateNew], event);
} else {
// not selectsRange
const date = parseDate(
value,
dateFormat,
this.props.locale,
strictParsing,
this.props.selected ?? undefined,
);
// Update selection if either (1) date was successfully parsed, or (2) input field is empty
if (date || !value) {
this.setSelected(date, event, true);
} else if (!this.props.inline) {
// If full date parsing failed but we have partial input,
// try to extract date info for calendar navigation
const navDate = parseDateForNavigation(
value,
this.state.preSelection ?? undefined,
);
// Only update preSelection if navDate is valid and within min/max bounds
if (
navDate &&
(!this.props.minDate || !isBefore(navDate, this.props.minDate)) &&
(!this.props.maxDate || !isAfter(navDate, this.props.maxDate))
) {
this.setState({ preSelection: navDate });
}
}
}
};
handleSelect = (
date: Date,
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
monthSelectedIn?: number,
) => {
if (this.props.readOnly) return;
const { selectsRange, startDate, endDate, locale, swapRange } = this.props;
const dateFormat =
this.props.dateFormat ?? DatePicker.defaultProps.dateFormat;
const isDateSelectionComplete =
!selectsRange ||
(startDate && !endDate && (swapRange || !isDateBefore(date, startDate)));
if (
this.props.shouldCloseOnSelect &&
!this.props.showTimeSelect &&
isDateSelectionComplete
) {
// Preventing onFocus event to fix issue
// https://github.com/Hacker0x01/react-datepicker/issues/628
this.sendFocusBackToInput();
}
if (this.props.onChangeRaw) {
const formattedDate = safeDateFormat(date, {
dateFormat,
locale,
});
this.props.onChangeRaw(event, { date, formattedDate });
}
this.setSelected(date, event, false, monthSelectedIn);
if (this.props.showDateSelect) {
this.setState({ isRenderAriaLiveMessage: true });
}
if (!this.props.shouldCloseOnSelect || this.props.showTimeSelect) {
this.setPreSelection(date);
} else if (isDateSelectionComplete) {
this.setOpen(false);
}
};
// setSelected is called either from handleChange (user typed date into textbox and it was parsed) or handleSelect (user selected date from calendar using mouse or keyboard)
setSelected = (
date: Date | null,
event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,
keepInput?: boolean,
monthSelectedIn?: number,
) => {
const { timeZone } = this.props;
// If timezone is specified, convert the selected date from zoned time to UTC
// This ensures the onChange callback receives a proper UTC Date object
let changedDate = date;
if (changedDate && timeZone) {
changedDate = fromZonedTime(changedDate, timeZone);
}
// Early return if selected year/month/day is disabled
if (this.props.showYearPicker) {
if (
changedDate !== null &&
isYearDisabled(getYear(changedDate), this.props)
) {
return;
}
} else if (this.props.showMonthYearPicker) {
if (changedDate !== null && isMonthDisabled(changedDate, this.props)) {
return;
}
} else {
if (changedDate !== null && isDayDisabled(changedDate, this.props)) {
return;
}
}
const {
onChange,
selectsRange,
startDate,
endDate,
selectsMultiple,
selectedDates,
minTime,
swapRange,
} = this.props;
if (
!isEqual(this.props.selected, changedDate) ||
this.props.allowSameDay ||
selectsRange ||
selectsMultiple
) {
if (changedDate !== null) {
// Preserve previously selected time if only date is currently being changed
if (
this.props.selected &&
(!keepInput ||
(!this.props.showTimeSelect &&
!this.props.showTimeSelectOnly &&
!this.props.showTimeInput))
) {
changedDate = setTime(changedDate, {
hour: getHours(this.props.selected),
minute: getMinutes(this.props.selected),
second: getSeconds(this.props.selected),
});
}
// If minTime is present then set the time to minTime
if (
!keepInput &&
(this.props.showTimeSelect || this.props.showTimeSelectOnly)
) {
if (minTime) {
changedDate = setTime(changedDate, {
hour: minTime.getHours(),
minute: minTime.getMinutes(),
second: minTime.getSeconds(),
});
}
}
if (!this.props.inline) {
this.setState({
preSelection: changedDate,
});
}
if (!this.props.focusSelectedMonth) {
this.setState({ monthSelectedIn: monthSelectedIn });
}
}