-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathCalendar.tsx
More file actions
969 lines (871 loc) · 28.8 KB
/
Copy pathCalendar.tsx
File metadata and controls
969 lines (871 loc) · 28.8 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
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
/**
* @file Calendar.tsx
* @input Uses React useState, useMemo, useCallback, hooks
* @output Exports Calendar component and related types
* @position Core implementation; forwards DOM ref and exposes navigation via
* handleRef
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Calendar/Calendar.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Calendar/Calendar.test.tsx (tests for new/changed behavior)
* - /packages/core/src/Calendar/index.ts (exports if types change)
* - /apps/storybook/stories/Calendar.stories.tsx (storybook stories)
* - /packages/cli/templates/blocks/components/Calendar/ (showcase blocks)
*/
import {
useState,
useMemo,
useCallback,
useEffect,
useImperativeHandle,
} from 'react';
import type {BaseProps} from '../BaseProps';
import * as stylex from '@stylexjs/stylex';
import {Button} from '../Button';
import {Icon} from '../Icon';
import {useGridFocus} from '../hooks';
import {
useCalendarDays,
useCalendarConstraints,
type CalendarDay,
} from './hooks';
import {
calendarStyles,
monthGridStyles,
dayCellStyles,
dayCellTheme,
} from './styles';
import {
type PlainDate,
plainDateFromISO,
plainDateToISO,
plainDateToDate,
plainDateToday,
plainDateSetFirstOfMonth,
plainDateAddMonths,
plainDateAddDays,
plainDateIsBefore,
plainDateIsEqual,
plainDateGetWeekNumber,
plainDateFormat,
DATE_FORMAT_WITH_WEEKDAY,
DATE_FORMAT_MONTH_YEAR,
} from '../utils/plainDate';
import {mergeProps} from '../utils';
import {
computeDayCellState,
computeRangeRounding,
computePreviewRounding,
isEndpoint,
} from './dayCellUtils';
// =============================================================================
// Types
// =============================================================================
export type {
ISODateString,
DayOfWeek,
DayOfWeekName,
DateRange,
} from '../utils/dateTypes';
import type {
ISODateString,
DayOfWeek,
DayOfWeekName,
DateRange,
} from '../utils/dateTypes';
import {normalizeDayOfWeek} from '../utils/dateTypes';
import {themeProps} from '../utils/themeProps';
/** Imperative handle for Calendar handleRef */
export interface CalendarHandle {
/** Navigate the calendar to show the month containing the given date */
navigateTo: (date: ISODateString) => void;
}
// ─── Base Props (shared across all modes) ─────────────────────
interface CalendarBaseProps extends Omit<
BaseProps<HTMLDivElement>,
'onChange' | 'defaultValue'
> {
/** Ref forwarded to the calendar root element. */
ref?: React.Ref<HTMLDivElement>;
/** Imperative handle ref for calendar navigation. */
handleRef?: React.Ref<CalendarHandle>;
/** Number of months to display (default: 1) */
numberOfMonths?: 1 | 2;
/** Minimum selectable date in ISO format */
min?: ISODateString;
/** Maximum selectable date in ISO format */
max?: ISODateString;
/**
* Custom date constraint functions. Date is disabled if ANY function returns false.
* Use for complex rules like "weekdays only" or "no holidays".
*/
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
/**
* Controlled focus date (which month is visible).
* If not provided, defaults to selected date or today.
*/
focusDate?: ISODateString;
/** Callback when visible month changes via navigation */
onFocusDateChange?: (focusDate: ISODateString) => void;
/**
* Show days from adjacent months (grayed out).
* Default: true
*/
hasOutsideDays?: boolean;
/**
* Show ISO week numbers in a side column.
* Default: false
*/
hasWeekNumbers?: boolean;
/**
* Use variable rows per month vs. fixed 6-row grid.
* Default: false (fixed 6 rows for consistent height)
*/
hasVariableRowCount?: boolean;
/**
* First day of week. Accepts a number (0 = Sunday … 6 = Saturday) or a
* three-letter day name ('sun'–'sat', case-insensitive) for readability.
* Default: 0 (Sunday)
*/
weekStartsOn?: DayOfWeek | DayOfWeekName;
}
// ─── Mode-specific Props (discriminated union) ────────────────
interface CalendarSingleProps extends CalendarBaseProps {
/** Selection mode */
mode?: 'single';
/** Selected date in ISO format (YYYY-MM-DD) */
value?: ISODateString;
/** Default value for uncontrolled mode */
defaultValue?: ISODateString;
/** Callback when date is selected */
onChange?: (value: ISODateString, valueAsDate: Date) => void;
}
interface CalendarRangeProps extends CalendarBaseProps {
/** Selection mode */
mode: 'range';
/** Selected date range */
value?: DateRange;
/** Default value for uncontrolled mode */
defaultValue?: DateRange;
/** Callback when range is selected */
onChange?: (value: DateRange) => void;
}
export type CalendarProps = CalendarSingleProps | CalendarRangeProps;
// =============================================================================
// Main Component
// =============================================================================
/**
* A calendar component for selecting dates or date ranges.
*
* @example
* ```
* <Calendar value={selectedDate} onChange={setSelectedDate} />
* ```
*/
export function Calendar({ref, ...props}: CalendarProps) {
const {
handleRef,
mode = 'single',
value,
defaultValue,
onChange,
numberOfMonths = 1,
min,
max,
dateConstraints,
focusDate: focusDateProp,
onFocusDateChange,
hasOutsideDays = true,
hasWeekNumbers = false,
hasVariableRowCount = false,
weekStartsOn: weekStartsOnProp = 0,
xstyle,
className,
style,
...rest
} = props;
// Normalize `weekStartsOn` (number or three-letter day name) to a numeric
// DayOfWeek so all downstream date math keeps working with an index.
const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);
// Today's date (memoized)
const today = useMemo(() => plainDateToday(), []);
// Internal state for uncontrolled mode
const [internalValue, setInternalValue] = useState<
ISODateString | DateRange | undefined
>(defaultValue);
// Range selection in progress (first click made, waiting for second)
const [rangeSelectionStart, setRangeSelectionStart] =
useState<ISODateString | null>(null);
// Hovered date for range preview
const [hoveredDate, setHoveredDate] = useState<ISODateString | null>(null);
// Pending focus target after month navigation
const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
// Determine effective value
const effectiveValue = value !== undefined ? value : internalValue;
// Focus date state (which month is visible)
const [internalFocusDate, setInternalFocusDate] = useState<PlainDate>(() => {
if (focusDateProp) {
return plainDateFromISO(focusDateProp);
}
if (effectiveValue) {
if (typeof effectiveValue === 'string') {
return plainDateFromISO(effectiveValue);
} else {
return plainDateFromISO(effectiveValue.start);
}
}
return plainDateToday();
});
// Use controlled focusDate if callback is provided, otherwise use internal state
const isControlledFocus =
focusDateProp !== undefined && onFocusDateChange !== undefined;
const focusDate = isControlledFocus
? plainDateFromISO(focusDateProp)
: internalFocusDate;
// Expose imperative handle for external navigation
useImperativeHandle(
handleRef,
() => ({
navigateTo: (date: ISODateString) => {
if (isControlledFocus) {
onFocusDateChange?.(date);
} else {
setInternalFocusDate(plainDateFromISO(date));
}
},
}),
[isControlledFocus, onFocusDateChange],
);
// Base month (first day of focus month)
const baseMonth = useMemo(() => {
return plainDateSetFirstOfMonth(focusDate);
}, [focusDate]);
// Generate visible months
const visibleMonths = useMemo(() => {
return Array.from({length: numberOfMonths}, (_, i) => {
return plainDateAddMonths(baseMonth, i);
});
}, [baseMonth, numberOfMonths]);
// Format month header
const monthYearLabel = useMemo(() => {
if (numberOfMonths === 1) {
return plainDateFormat(visibleMonths[0], DATE_FORMAT_MONTH_YEAR);
}
return visibleMonths
.map(m => plainDateFormat(m, DATE_FORMAT_MONTH_YEAR))
.join(' – ');
}, [visibleMonths, numberOfMonths]);
// Determine if prev/next navigation is possible based on min/max
const canNavigatePrevious = useMemo(() => {
if (!min) {
return true;
}
const minDate = plainDateFromISO(min);
// Can't go back if min is in the current focus month
return (
minDate.year < baseMonth.year ||
(minDate.year === baseMonth.year && minDate.month < baseMonth.month)
);
}, [min, baseMonth]);
const canNavigateNext = useMemo(() => {
if (!max) {
return true;
}
const maxDate = plainDateFromISO(max);
// Check against the last visible month, not just baseMonth
const lastVisibleMonth = plainDateAddMonths(baseMonth, numberOfMonths - 1);
return (
maxDate.year > lastVisibleMonth.year ||
(maxDate.year === lastVisibleMonth.year &&
maxDate.month > lastVisibleMonth.month)
);
}, [max, baseMonth, numberOfMonths]);
// Navigation handlers
const navigateMonth = useCallback(
(delta: number, focusedDate?: ISODateString, offset?: number) => {
const newPd = plainDateAddMonths(baseMonth, delta);
const newISO = plainDateToISO(newPd);
// Calculate target focus date if a focused date was provided
if (focusedDate) {
const currentPd = plainDateFromISO(focusedDate);
const daysToMove = offset ?? 7;
const targetPd = plainDateAddDays(currentPd, delta * daysToMove);
setPendingFocus(plainDateToISO(targetPd));
}
if (onFocusDateChange) {
onFocusDateChange(newISO);
} else {
setInternalFocusDate(newPd);
}
},
[baseMonth, onFocusDateChange],
);
// Escape key handler to cancel range selection
const handleCalendarKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (
mode === 'range' &&
rangeSelectionStart !== null &&
e.key === 'Escape'
) {
setRangeSelectionStart(null);
e.preventDefault();
e.stopPropagation();
}
},
[mode, rangeSelectionStart],
);
// Day click handler
const handleDayClick = useCallback(
(date: PlainDate) => {
const iso = plainDateToISO(date);
if (mode === 'single') {
setInternalValue(iso);
(onChange as CalendarSingleProps['onChange'])?.(
iso,
plainDateToDate(date),
);
} else {
// Range mode
if (rangeSelectionStart === null) {
// First click - start the range
setRangeSelectionStart(iso);
} else {
// Second click - complete the range
const startPd = plainDateFromISO(rangeSelectionStart);
let start: ISODateString;
let end: ISODateString;
// Ensure start <= end
if (plainDateIsBefore(date, startPd)) {
start = iso;
end = rangeSelectionStart;
} else {
start = rangeSelectionStart;
end = iso;
}
const range: DateRange = {start, end};
setInternalValue(range);
setRangeSelectionStart(null);
(onChange as CalendarRangeProps['onChange'])?.(range);
}
}
},
[mode, onChange, rangeSelectionStart],
);
return (
<div
ref={ref}
{...mergeProps(
themeProps('calendar', {mode}),
stylex.props(calendarStyles.calendar, xstyle),
className,
style,
)}
onKeyDown={handleCalendarKeyDown}
{...rest}>
{/* Header with navigation */}
<div {...stylex.props(calendarStyles.header)}>
<Button
label="Previous month"
variant="ghost"
icon={<Icon icon="chevronLeft" size="sm" color="inherit" />}
onClick={() => navigateMonth(-1)}
isDisabled={!canNavigatePrevious}
isIconOnly
/>
<span {...stylex.props(calendarStyles.monthYearLabel)}>
{monthYearLabel}
</span>
<Button
label="Next month"
variant="ghost"
icon={<Icon icon="chevronRight" size="sm" color="inherit" />}
onClick={() => navigateMonth(1)}
isDisabled={!canNavigateNext}
isIconOnly
/>
</div>
{/* Month grids */}
<div {...stylex.props(calendarStyles.monthsContainer)}>
{visibleMonths.map(month => (
<MonthGrid
key={`${month.year}-${month.month}`}
month={month}
value={effectiveValue}
mode={mode}
rangeSelectionStart={rangeSelectionStart}
hoveredDate={hoveredDate}
min={min}
max={max}
dateConstraints={dateConstraints}
hasOutsideDays={hasOutsideDays}
hasWeekNumbers={hasWeekNumbers}
hasVariableRowCount={hasVariableRowCount}
weekStartsOn={weekStartsOn}
onDayClick={handleDayClick}
onDayHover={date =>
setHoveredDate(date ? plainDateToISO(date) : null)
}
today={today}
onNavigatePrevious={(focusedDate, offset) =>
navigateMonth(-1, focusedDate, offset)
}
onNavigateNext={(focusedDate, offset) =>
navigateMonth(1, focusedDate, offset)
}
pendingFocus={pendingFocus}
onPendingFocusHandled={() => setPendingFocus(null)}
/>
))}
</div>
</div>
);
}
Calendar.displayName = 'Calendar';
// =============================================================================
// MonthGrid (Private)
// =============================================================================
interface MonthGridProps {
month: PlainDate;
value: ISODateString | DateRange | undefined;
mode: 'single' | 'range';
rangeSelectionStart: ISODateString | null;
hoveredDate: ISODateString | null;
min?: ISODateString;
max?: ISODateString;
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
hasOutsideDays: boolean;
hasWeekNumbers: boolean;
hasVariableRowCount: boolean;
weekStartsOn: DayOfWeek;
onDayClick: (date: PlainDate) => void;
onDayHover: (date: PlainDate | null) => void;
today: PlainDate;
onNavigatePrevious?: (focusedDate: ISODateString, offset: number) => void;
onNavigateNext?: (focusedDate: ISODateString, offset: number) => void;
pendingFocus?: ISODateString | null;
onPendingFocusHandled?: () => void;
}
function MonthGrid({
month,
value,
mode,
rangeSelectionStart,
hoveredDate,
min,
max,
dateConstraints,
hasOutsideDays,
hasWeekNumbers,
hasVariableRowCount,
weekStartsOn,
onDayClick,
onDayHover,
today,
onNavigatePrevious,
onNavigateNext,
pendingFocus,
onPendingFocusHandled,
}: MonthGridProps) {
const year = month.year;
// Use hooks for days generation and constraints
const {days, weeks, dayNames} = useCalendarDays({
year,
month: month.month,
weekStartsOn,
hasVariableRowCount,
});
const {isDateDisabled} = useCalendarConstraints({
min,
max,
dateConstraints,
});
// Parse selected date for roving tabindex priority
const selectedDateForTabindex = useMemo(() => {
if (mode === 'single' && value && typeof value === 'string') {
return plainDateFromISO(value);
}
return null;
}, [mode, value]);
// Seed the initial roving tab stop for this month. useGridFocus owns the
// live tab stop (see `hasRovingTabIndex` below) — it honors an existing
// `tabindex="0"` and repairs/moves it thereafter — so this only decides
// which day button starts tabbable. Priority: selected date (if visible and
// enabled) > today (if visible and enabled) > first enabled in-month day.
const seedTabbableIso = useMemo((): ISODateString | null => {
if (selectedDateForTabindex) {
const isSelectedInMonth =
selectedDateForTabindex.year === year &&
selectedDateForTabindex.month === month.month;
if (isSelectedInMonth && !isDateDisabled(selectedDateForTabindex)) {
return plainDateToISO(selectedDateForTabindex);
}
}
const isTodayInMonth = today.year === year && today.month === month.month;
if (isTodayInMonth && !isDateDisabled(today)) {
return plainDateToISO(today);
}
for (const day of days) {
if (!day.isOutside && !isDateDisabled(day.date)) {
return day.iso;
}
}
return null;
}, [days, today, year, month.month, isDateDisabled, selectedDateForTabindex]);
// Helper to get the focused date from the currently focused element.
// Reads the machine-readable `data-date` (ISO) attribute rather than parsing
// the human-readable `aria-label` with `new Date()`, which is locale/format
// dependent and returns Invalid Date in non-English locales (e.g. fr-FR,
// ja-JP), silently swallowing month-boundary arrow navigation (complex-4).
const getFocusedDate = useCallback((): ISODateString | null => {
const activeElement = document.activeElement as HTMLElement | null;
if (!activeElement) {
return null;
}
const iso = activeElement.getAttribute('data-date');
if (!iso) {
return null;
}
return iso as ISODateString;
}, []);
// Handle navigation to previous month
const handleNavigatePrevious = useCallback(
(_column: number, offset: number) => {
const focusedDate = getFocusedDate();
if (focusedDate) {
onNavigatePrevious?.(focusedDate, offset);
}
},
[getFocusedDate, onNavigatePrevious],
);
// Handle navigation to next month
const handleNavigateNext = useCallback(
(_column: number, offset: number) => {
const focusedDate = getFocusedDate();
if (focusedDate) {
onNavigateNext?.(focusedDate, offset);
}
},
[getFocusedDate, onNavigateNext],
);
// Handle PageUp/PageDown
const handlePageUp = useCallback(() => {
const focusedDate = getFocusedDate();
if (focusedDate) {
onNavigatePrevious?.(focusedDate, 7);
}
}, [getFocusedDate, onNavigatePrevious]);
const handlePageDown = useCallback(() => {
const focusedDate = getFocusedDate();
if (focusedDate) {
onNavigateNext?.(focusedDate, 7);
}
}, [getFocusedDate, onNavigateNext]);
// Grid focus navigation.
//
// The hook enumerates ALL grid cells (every `role="gridcell"`, including
// disabled days and empty placeholder cells) so the true 7-column geometry is
// preserved. `isCellFocusable` / `getFocusTarget` tell the hook which cells
// can take focus (those containing an enabled day button) and where to send
// focus (the day button inside the cell). Arrow keys move to the target
// row/column and, if that cell is disabled, continue in the same direction to
// the next enabled cell.
const {
gridRef,
handleKeyDown: handleGridKeyDown,
handleFocus: handleGridFocus,
} = useGridFocus<HTMLDivElement>({
columns: 7,
cellSelector: '[role="gridcell"]',
isCellFocusable: cell =>
cell.querySelector('button:not([disabled])') !== null,
getFocusTarget: cell => cell.querySelector<HTMLElement>('button'),
hasRovingTabIndex: true,
onNavigateBefore: handleNavigatePrevious,
onNavigateAfter: handleNavigateNext,
onPageUp: handlePageUp,
onPageDown: handlePageDown,
});
// Handle pending focus after month navigation
useEffect(() => {
if (!pendingFocus || !gridRef.current) {
return;
}
const buttons = gridRef.current.querySelectorAll<HTMLElement>(
'button:not([disabled])',
);
const targetPd = plainDateFromISO(pendingFocus);
const targetIso = plainDateToISO(targetPd);
let targetButton: HTMLElement | null = null;
for (const button of buttons) {
if (button.getAttribute('data-date') === targetIso) {
targetButton = button;
break;
}
}
if (!targetButton && buttons.length > 0) {
targetButton = buttons[0];
}
targetButton?.focus();
onPendingFocusHandled?.();
}, [pendingFocus, gridRef, onPendingFocusHandled]);
// Parse selection
let selectedDate: PlainDate | null = null;
let rangeStart: PlainDate | null = null;
let rangeEnd: PlainDate | null = null;
if (mode === 'single' && value && typeof value === 'string') {
selectedDate = plainDateFromISO(value);
} else if (mode === 'range' && value && typeof value === 'object') {
const range = value;
rangeStart = plainDateFromISO(range.start);
rangeEnd = plainDateFromISO(range.end);
}
// Handle in-progress range selection
if (rangeSelectionStart) {
rangeStart = plainDateFromISO(rangeSelectionStart);
rangeEnd = rangeStart;
}
// Calculate preview range when hovering during range selection
let previewStart: PlainDate | null = null;
let previewEnd: PlainDate | null = null;
if (mode === 'range' && rangeSelectionStart && hoveredDate) {
const startPd = plainDateFromISO(rangeSelectionStart);
const hoverPd = plainDateFromISO(hoveredDate);
if (!plainDateIsEqual(startPd, hoverPd)) {
if (plainDateIsBefore(hoverPd, startPd)) {
previewStart = hoverPd;
previewEnd = startPd;
} else {
previewStart = startPd;
previewEnd = hoverPd;
}
}
}
// Month label for announcements
const monthLabel = useMemo(() => {
return plainDateFormat(month, DATE_FORMAT_MONTH_YEAR);
}, [month]);
return (
<div {...stylex.props(monthGridStyles.monthGrid)}>
{/* Days grid (APG grid: header row of columnheaders + week rows) */}
<div
ref={gridRef}
role="grid"
aria-label={monthLabel}
onKeyDown={handleGridKeyDown}
onFocus={handleGridFocus}
{...stylex.props(
monthGridStyles.daysGrid,
hasWeekNumbers && monthGridStyles.daysGridWithNumbers,
)}>
{/* Day names header row (columnheaders live inside the grid). Uses the
same display:contents row so its cells align to the grid columns. */}
<div role="row" {...stylex.props(monthGridStyles.weekRow)}>
{hasWeekNumbers && (
<div
{...stylex.props(
monthGridStyles.dayName,
monthGridStyles.weekNumberHeader,
)}
/>
)}
{dayNames.map(name => (
<div
key={name}
role="columnheader"
{...stylex.props(monthGridStyles.dayName)}>
{name}
</div>
))}
</div>
{weeks.map(week => {
const weekDate = week.find(d => !d.isOutside)?.date || week[0].date;
const weekNum = plainDateGetWeekNumber(weekDate);
return (
<div
key={plainDateToISO(weekDate)}
role="row"
{...stylex.props(monthGridStyles.weekRow)}>
{hasWeekNumbers && (
<div
role="rowheader"
{...stylex.props(monthGridStyles.weekNumber)}>
{weekNum}
</div>
)}
{week.map((day, dayIndex) => (
<DayCell
key={day.iso}
day={day}
dayIndex={dayIndex}
mode={mode}
selectedDate={selectedDate}
rangeStart={rangeStart}
rangeEnd={rangeEnd}
previewStart={previewStart}
previewEnd={previewEnd}
today={today}
hasOutsideDays={hasOutsideDays}
isDisabled={isDateDisabled(day.date)}
isTabbable={day.iso === seedTabbableIso}
onDayClick={onDayClick}
onDayHover={onDayHover}
/>
))}
</div>
);
})}
</div>
</div>
);
}
// =============================================================================
// DayCell (Private)
// =============================================================================
interface DayCellProps {
day: CalendarDay;
dayIndex: number;
mode: 'single' | 'range';
selectedDate: PlainDate | null;
rangeStart: PlainDate | null;
rangeEnd: PlainDate | null;
previewStart: PlainDate | null;
previewEnd: PlainDate | null;
today: PlainDate;
hasOutsideDays: boolean;
isDisabled: boolean;
/**
* Whether this day seeds the initial roving tab stop. useGridFocus
* (`hasRovingTabIndex`) owns the live tab stop thereafter — it honors an
* existing `tabindex="0"` and repairs/moves it on navigation and focus.
*/
isTabbable: boolean;
onDayClick: (date: PlainDate) => void;
onDayHover: (date: PlainDate | null) => void;
}
function DayCell({
day,
dayIndex,
mode,
selectedDate,
rangeStart,
rangeEnd,
previewStart,
previewEnd,
today,
hasOutsideDays,
isDisabled,
isTabbable: isTabbableDay,
onDayClick,
onDayHover,
}: DayCellProps) {
const {date, isOutside, dayNumber} = day;
if (isOutside && !hasOutsideDays) {
// Empty placeholder cell — still a gridcell so the grid geometry stays a
// clean 7-per-row set for keyboard navigation.
return <div role="gridcell" {...stylex.props(dayCellStyles.cell)} />;
}
const state = computeDayCellState({
date,
dayIndex,
mode,
selectedDate,
rangeStart,
rangeEnd,
previewStart,
previewEnd,
today,
isDisabled,
isOutside,
});
const endpoint = isEndpoint(state);
const rangeRounding = computeRangeRounding(state);
const previewRounding = computePreviewRounding(state);
return (
<div role="gridcell" {...stylex.props(dayCellStyles.cell)}>
{/* Range background */}
{state.isInRange && (
<div
{...stylex.props(
dayCellStyles.rangeBg,
dayCellTheme.rangeBg,
rangeRounding.roundLeft && dayCellStyles.rangeBgRadiusLeft,
rangeRounding.roundRight && dayCellStyles.rangeBgRadiusRight,
state.isRangeStart && dayCellStyles.rangeInsetLeft,
state.isRangeStart &&
rangeRounding.roundRight &&
dayCellStyles.rangeInsetRight,
state.isRangeEnd && dayCellStyles.rangeInsetRight,
state.isRangeStart &&
rangeRounding.roundLeft &&
dayCellStyles.rangeInsetLeft,
)}
/>
)}
{/* Preview range background */}
{state.isInPreview && (
<div
{...stylex.props(
dayCellStyles.previewBg,
dayCellTheme.previewBg,
previewRounding.roundLeft && dayCellStyles.previewBgRadiusLeft,
previewRounding.roundRight && dayCellStyles.previewBgRadiusRight,
state.isPreviewStart && dayCellStyles.previewStart,
state.isPreviewEnd && dayCellStyles.previewEnd,
)}
/>
)}
{/* Day button */}
<button
type="button"
data-date={day.iso}
aria-label={plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY)}
aria-selected={state.isSelected || state.isInRange || undefined}
aria-disabled={state.effectivelyDisabled || undefined}
disabled={isDisabled}
// Initial roving tab-stop seed; useGridFocus owns it after mount.
tabIndex={isTabbableDay ? 0 : -1}
onClick={() => !state.effectivelyDisabled && onDayClick(date)}
onMouseEnter={() => !state.effectivelyDisabled && onDayHover(date)}
onMouseLeave={() => onDayHover(null)}
{...mergeProps(
themeProps('calendar-day', {
selected: endpoint ? 'selected' : null,
today: state.isToday ? 'today' : null,
disabled: state.effectivelyDisabled ? 'disabled' : null,
'in-range': state.isInRange ? 'in-range' : null,
}),
stylex.props(
dayCellStyles.day,
dayCellTheme.day,
isOutside && dayCellStyles.dayOutside,
isOutside && dayCellTheme.dayOutside,
state.isToday &&
!state.isSelected &&
!state.isInRange &&
dayCellStyles.dayToday,
state.isToday &&
!state.isSelected &&
!state.isInRange &&
dayCellTheme.dayToday,
state.isToday &&
!state.isSelected &&
state.isInRange &&
dayCellStyles.dayTodayInRange,
state.isToday &&
!state.isSelected &&
state.isInRange &&
dayCellTheme.dayTodayInRange,
endpoint && dayCellStyles.daySelected,
endpoint && dayCellTheme.daySelected,
state.effectivelyDisabled && dayCellStyles.dayDisabled,
state.effectivelyDisabled && dayCellTheme.dayDisabled,
),
)}>
{dayNumber}
</button>
</div>
);
}