-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathCalendar.tsx
More file actions
410 lines (371 loc) · 14.2 KB
/
Calendar.tsx
File metadata and controls
410 lines (371 loc) · 14.2 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
import React, {
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
forwardRef,
} from 'react';
import {addMonths, subMonths, endOfMonth} from 'date-fns';
import {
ArrowUpIcon,
ArrowDownIcon,
ArrowLeftIcon,
ArrowRightIcon,
} from '@radix-ui/react-icons';
import Input from '../../components/Input';
import Dropdown from '../../components/Dropdown';
import {DayOfWeek, CalendarDirection, HTMLInputTypes} from '../../types';
import {CalendarMonth} from './CalendarMonth';
import {
getMonthOptions,
formatYear,
parseYear,
isDateInRange,
isSameDay,
} from './helpers';
export type CalendarHandle = {
focusDate: (date?: Date) => void;
setVisibleDate: (date: Date) => void;
};
type CalendarProps = {
onSelectionChange: (selectionStart: Date, selectionEnd?: Date) => void;
selectionStart?: Date;
selectionEnd?: Date;
highlightStart?: Date;
highlightEnd?: Date;
initialVisibleDate?: Date;
minDateAllowed?: Date;
maxDateAllowed?: Date;
disabledDates?: Date[];
firstDayOfWeek?: DayOfWeek;
showOutsideDays?: boolean;
monthFormat?: string;
calendarOrientation?: 'vertical' | 'horizontal';
numberOfMonthsShown?: number;
daySize?: number;
direction?: CalendarDirection;
};
type CalendarPropsWithRef = CalendarProps & {
forwardedRef?: React.Ref<CalendarHandle>;
};
const CalendarComponent = ({
initialVisibleDate = new Date(),
onSelectionChange,
selectionStart,
selectionEnd,
highlightStart,
highlightEnd,
minDateAllowed,
maxDateAllowed,
disabledDates,
firstDayOfWeek,
showOutsideDays,
monthFormat,
calendarOrientation,
numberOfMonthsShown = 1,
daySize,
direction = CalendarDirection.LeftToRight,
forwardedRef,
}: CalendarPropsWithRef) => {
const [activeYear, setActiveYear] = useState(() =>
initialVisibleDate.getFullYear()
);
const [activeMonth, setActiveMonth] = useState(() =>
initialVisibleDate.getMonth()
);
const [firstCalendarMonth, setFirstCalendarMonth] = useState(() => {
// Start by displaying calendar months centered around the initial date
const halfRange = Math.floor((numberOfMonthsShown - 1) / 2);
return subMonths(initialVisibleDate, halfRange);
});
const [focusedDate, setFocusedDate] = useState<Date>();
const [highlightedDates, setHighlightedDates] = useState<[Date, Date]>();
const calendarContainerRef = useRef(document.createElement('div'));
const scrollAccumulatorRef = useRef(0);
const prevFocusedDateRef = useRef(focusedDate);
const displayYear = useMemo(() => {
const formatted = formatYear(activeYear, monthFormat);
return parseInt(formatted, 10);
}, [activeYear, monthFormat]);
useImperativeHandle(forwardedRef, () => ({
focusDate: (date = new Date(activeYear, activeMonth, 1)) => {
setFocusedDate(date);
},
setVisibleDate: (date: Date) => {
setActiveMonth(date.getMonth());
setActiveYear(date.getFullYear());
},
}));
const isMonthVisible = useCallback(
(date: Date) => {
const visibleStart = firstCalendarMonth;
const visibleEnd = endOfMonth(
addMonths(visibleStart, numberOfMonthsShown - 1)
);
return isDateInRange(date, visibleStart, visibleEnd);
},
[firstCalendarMonth, numberOfMonthsShown]
);
// Updates the calendar whenever the active month & year change
useEffect(() => {
const activeDate = new Date(activeYear, activeMonth, 1);
// Don't change calendar if the active month is already visible
if (isMonthVisible(activeDate)) {
return;
}
setFirstCalendarMonth(
activeDate < firstCalendarMonth
? activeDate // Moved backward: show activeDate as first month
: subMonths(activeDate, numberOfMonthsShown - 1) // Moved forward: show activeDate as last month
);
}, [activeMonth, activeYear, isMonthVisible]);
useEffect(() => {
// Syncs activeMonth/activeYear to focusedDate when focusedDate changes
if (!focusedDate) {
return;
}
if (focusedDate.getTime() === prevFocusedDateRef.current?.getTime()) {
return;
}
prevFocusedDateRef.current = focusedDate;
if (!isMonthVisible(focusedDate)) {
setActiveMonth(focusedDate.getMonth());
setActiveYear(focusedDate.getFullYear());
}
}, [focusedDate, isMonthVisible]);
useEffect(() => {
if (highlightStart && highlightEnd) {
setHighlightedDates([highlightStart, highlightEnd]);
} else if (highlightStart) {
setHighlightedDates([highlightStart, highlightStart]);
} else {
setHighlightedDates(undefined);
}
}, [highlightStart, highlightEnd]);
useEffect(() => {
if (selectionStart && selectionEnd) {
setHighlightedDates([selectionStart, selectionEnd]);
}
}, [selectionStart, selectionEnd]);
const selectedDates = useMemo((): Date[] => {
return [selectionStart, selectionEnd].filter(
(d): d is Date => d !== undefined
);
}, [selectionStart, selectionEnd]);
const handleSelectionStart = useCallback(
(date: Date) => {
if (!selectionStart || selectionEnd) {
// No selection yet, or previous selection is complete → start new selection
setHighlightedDates(undefined);
onSelectionChange(date, undefined);
}
},
[selectionStart, selectionEnd, onSelectionChange]
);
const handleSelectionEnd = useCallback(
(date: Date) => {
// Complete the selection with an end date
if (selectionStart && !selectionEnd) {
// Incomplete selection exists (range picker mid-selection)
onSelectionChange(selectionStart, date);
} else {
// Complete selection exists or a single date was chosen
onSelectionChange(date, date);
}
},
[selectionStart, selectionEnd, onSelectionChange]
);
const handleDaysHighlighted = useCallback(
(date: Date) => {
if (selectionStart && selectionEnd) {
setHighlightedDates([selectionStart, selectionEnd]);
} else if (selectionStart && !selectionEnd) {
setHighlightedDates([selectionStart, date]);
} else {
setHighlightedDates([date, date]);
}
},
[selectionStart, selectionEnd]
);
const handleDayFocused = useCallback(
(date: Date) => {
setFocusedDate(date);
// When navigating with keyboard during range selection,
// highlight the range from start to focused date
if (selectionStart && !selectionEnd) {
setHighlightedDates([selectionStart, date]);
}
},
[selectionStart, selectionEnd]
);
const monthOptions = useMemo(
() =>
getMonthOptions(
activeYear,
monthFormat,
minDateAllowed,
maxDateAllowed
),
[activeYear, monthFormat, minDateAllowed, maxDateAllowed]
);
const changeMonthBy = useCallback(
(months: number) => {
const currentDate = new Date(activeYear, activeMonth, 1);
// In RTL mode, directions are reversed
const actualMonths =
direction === CalendarDirection.RightToLeft ? -months : months;
const newMonthStart = addMonths(currentDate, actualMonths);
if (isDateInRange(newMonthStart, minDateAllowed, maxDateAllowed)) {
setActiveYear(newMonthStart.getFullYear());
setActiveMonth(newMonthStart.getMonth());
setFirstCalendarMonth(newMonthStart);
}
},
[activeYear, activeMonth, minDateAllowed, maxDateAllowed, direction]
);
const handleWheel = useCallback(
(e: WheelEvent) => {
e.preventDefault();
// Accumulate scroll delta until threshold is reached, then change the active month
// This respects OS scroll speed settings and works well with trackpads
const threshold = 100; // Adjust this to control sensitivity
scrollAccumulatorRef.current += e.deltaY;
if (Math.abs(scrollAccumulatorRef.current) >= threshold) {
const offset = scrollAccumulatorRef.current > 0 ? 1 : -1;
changeMonthBy(offset);
scrollAccumulatorRef.current = 0; // Reset accumulator after month change
}
},
[changeMonthBy]
);
useEffect(() => {
// Add listener with passive: false to allow preventDefault
calendarContainerRef.current.addEventListener('wheel', handleWheel, {
passive: false,
});
return () => {
calendarContainerRef.current?.removeEventListener(
'wheel',
handleWheel
);
};
}, [handleWheel]);
const canChangeMonthBy = useCallback(
(months: number) => {
const currentDate = new Date(activeYear, activeMonth, 1);
const targetMonth = addMonths(currentDate, months);
return isDateInRange(targetMonth, minDateAllowed, maxDateAllowed);
},
[activeYear, activeMonth, minDateAllowed, maxDateAllowed]
);
const isVertical = calendarOrientation === 'vertical';
const PreviousMonthIcon = isVertical ? ArrowUpIcon : ArrowLeftIcon;
const NextMonthIcon = isVertical ? ArrowDownIcon : ArrowRightIcon;
return (
<div
className="dash-datepicker-calendar-wrapper"
style={{'--day-size': `${daySize}px`} as React.CSSProperties}
>
<div className="dash-datepicker-controls">
<button
type="button"
className="dash-datepicker-month-nav"
onClick={() => changeMonthBy(-1)}
disabled={!canChangeMonthBy(-1)}
aria-label="Previous month"
>
<PreviousMonthIcon />
</button>
<div style={{display: 'grid'}}>
{/* Render all the month names invisibly so that the longest month name is what determines the width of the month picker, regardless of which language is used */}
{monthOptions.map((opt, i) => (
<div
key={i}
className="dash-datepicker-month-sizer"
aria-hidden="true"
>
{opt.label}
</div>
))}
<Dropdown
options={monthOptions}
value={activeMonth}
clearable={false}
maxHeight={250}
searchable={false}
setProps={({value}) => {
if (Number.isInteger(value)) {
setActiveMonth(value as number);
}
}}
/>
</div>
<Input
type={HTMLInputTypes.number}
debounce={0.5}
value={displayYear}
min={minDateAllowed?.getFullYear()}
max={maxDateAllowed?.getFullYear()}
setProps={({value}) => {
const parsed = parseYear(String(value));
if (parsed !== undefined) {
setActiveYear(parsed);
}
}}
/>
<button
type="button"
className="dash-datepicker-month-nav"
onClick={() => changeMonthBy(1)}
disabled={!canChangeMonthBy(1)}
aria-label="Next month"
>
<NextMonthIcon />
</button>
</div>
<div
className="dash-datepicker-calendar-container"
ref={calendarContainerRef}
dir={direction}
style={{
flexDirection:
calendarOrientation === 'vertical' ? 'column' : 'row',
}}
>
{Array.from({length: numberOfMonthsShown}, (_, i) => {
const monthDate = addMonths(firstCalendarMonth, i);
return (
<CalendarMonth
key={i}
year={monthDate.getFullYear()}
month={monthDate.getMonth()}
minDateAllowed={minDateAllowed}
maxDateAllowed={maxDateAllowed}
disabledDates={disabledDates}
dateFocused={focusedDate}
onDayFocused={handleDayFocused}
selectedDates={selectedDates}
onSelectionStart={handleSelectionStart}
onSelectionEnd={handleSelectionEnd}
highlightedDatesRange={highlightedDates}
onDaysHighlighted={handleDaysHighlighted}
firstDayOfWeek={firstDayOfWeek}
showOutsideDays={showOutsideDays}
daySize={daySize}
monthFormat={monthFormat}
showMonthHeader={numberOfMonthsShown > 1}
direction={direction}
/>
);
})}
</div>
</div>
);
};
const Calendar = forwardRef<CalendarHandle, CalendarProps>((props, ref) => {
return <CalendarComponent {...props} forwardedRef={ref} />;
});
Calendar.displayName = 'Calendar';
export default Calendar;