import { useState, useCallback, useEffect, useId, useRef, KeyboardEvent } from 'react'; import { useIntl } from 'react-intl'; import { formatDate } from '@transferwise/formatting'; import { MonthFormat } from '../common'; import { useDirection } from '../common/hooks'; import { isWithinRange, moveToWithinRange, returnDateView } from '../common/DateUtils'; import { clampToDayViewBoundary, isDateDisabled, hasDisabledDatesInMonth } from './_helpers'; import { LONG_DAY_FORMAT } from './Calendar.constants'; import { InlinePrompt } from '../Prompt/InlinePrompt'; import type { DateChangeMeta, DisabledRules } from './Calendar.types'; import DayCalendar from './DayCalendar'; import { getStartOfDay } from './GetStartOfDay'; import messages from './Calendar.messages'; import MonthCalendar from './MonthCalendar'; import YearCalendar from './YearCalendar'; export interface CalendarProps { /** The currently selected date, or `null` for no selection. */ value: Date | null; /** Earliest selectable date (inclusive). Dates before this are interactive but not selectable, and show a boundary prompt. */ min?: Date | null; /** Latest selectable date (inclusive). Dates after this are interactive but not selectable, and show a boundary prompt. */ max?: Date | null; /** Month name format in the header. Defaults to `'long'` (e.g. "January"). */ monthFormat?: `${MonthFormat}`; /** Placeholder text shown in the month/year cells when no date is selected. */ placeholder?: string; /** Rules for disabling specific weekdays, individual dates, or date ranges. The required `reason` is shown in an inline prompt and linked to disabled cells via `aria-describedby` for screen reader accessibility. */ disabledRules?: DisabledRules; /** Called whenever the focused date changes — including disabled and out-of-range dates. `meta.isEnabled` is `false` when the date is not selectable. */ onDateFocus?: (date: Date | null, meta: DateChangeMeta) => void; /** Called when a date is confirmed (click or Enter). Only fires for enabled dates. */ onChange?: (date: Date | null) => void; } /** * Temporary toggle — set `true` to restore strict min/max keyboard clamping. * @see https://transferwise.atlassian.net/browse/DS-8518 */ const STRICT_KEYBOARD_CLAMPING = false; /** * Inline calendar for selecting a single date. Powers [DateLookup](?path=/docs/forms-datelookup--docs). */ const Calendar = ({ value, min: minProp = null, max: maxProp = null, monthFormat = MonthFormat.LONG, placeholder, disabledRules, onDateFocus, onChange, }: CalendarProps) => { const intl = useIntl(); const { isRTL } = useDirection(); const selectedDate = getStartOfDay(value); const min = getStartOfDay(minProp); const max = getStartOfDay(maxProp); const disabledReasonId = useId(); const disabledRulesRef = useRef(disabledRules); useEffect(() => { disabledRulesRef.current = disabledRules; }); const [hasInteracted, setHasInteracted] = useState(false); const [focusedDate, setFocusedDate] = useState(selectedDate); useEffect(() => { // eslint-disable-next-line react-hooks/set-state-in-effect setFocusedDate(selectedDate); }, [selectedDate?.getTime()]); // eslint-disable-line react-hooks/exhaustive-deps const checkIsEnabled = (date: Date | null) => { if (!date) return true; return isWithinRange(date, min, max) && !isDateDisabled(date, disabledRulesRef.current); }; const focusedDateDisabled = focusedDate ? !isWithinRange(focusedDate, min, max) || isDateDisabled(focusedDate, disabledRules) : false; useEffect(() => { if (selectedDate && !isWithinRange(selectedDate, min, max)) { const clamped = moveToWithinRange(selectedDate, min, max); setFocusedDate(clamped); // eslint-disable-line react-hooks/set-state-in-effect onDateFocus?.(clamped, { isEnabled: checkIsEnabled(clamped) }); } }, [selectedDate?.getTime(), min?.getTime(), max?.getTime(), onDateFocus]); // eslint-disable-line react-hooks/exhaustive-deps const dateView = returnDateView(selectedDate, min, max); const [viewMonth, setViewMonth] = useState(dateView.getMonth()); const [viewYear, setViewYear] = useState(dateView.getFullYear()); const [mode, setMode] = useState<'day' | 'month' | 'year'>('day'); useEffect(() => { const view = returnDateView(selectedDate, min, max); // eslint-disable-next-line react-hooks/set-state-in-effect setViewMonth(view.getMonth()); setViewYear(view.getFullYear()); }, [selectedDate?.getTime(), min?.getTime(), max?.getTime()]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (focusedDate) { // eslint-disable-next-line react-hooks/set-state-in-effect setViewMonth(focusedDate.getMonth()); setViewYear(focusedDate.getFullYear()); } }, [focusedDate?.getTime()]); // eslint-disable-line react-hooks/exhaustive-deps const handleViewDateUpdate = useCallback( // eslint-disable-next-line react-hooks/preserve-manual-memoization ({ month, year }: { month?: number; year?: number }) => { if (month !== undefined) setViewMonth(month); if (year !== undefined) setViewYear(year); setHasInteracted(false); }, [], ); const switchToDays = useCallback(() => setMode('day'), []); const switchToMonths = useCallback(() => setMode('month'), []); const switchToYears = useCallback(() => setMode('year'), []); const handleSelectedDateUpdate = useCallback( (date: Date) => { if (!hasInteracted) setHasInteracted(true); const isEnabled = checkIsEnabled(date); setFocusedDate(date); onDateFocus?.(date, { isEnabled }); if (isEnabled && onChange) { onChange(date); } }, [onDateFocus, onChange], // eslint-disable-line react-hooks/exhaustive-deps ); const adjustDate = useCallback( (daysToAdd: number, monthsToAdd: number, yearsToAdd: number) => { const base = focusedDate ?? selectedDate; let date: Date | null; if (base) { date = new Date( mode === 'year' ? base.getFullYear() + yearsToAdd : base.getFullYear(), mode === 'month' ? base.getMonth() + monthsToAdd : base.getMonth(), mode === 'day' ? base.getDate() + daysToAdd : base.getDate(), ); } else { date = getStartOfDay(new Date()); } date &&= STRICT_KEYBOARD_CLAMPING || mode !== 'day' ? moveToWithinRange(date, min, max) : clampToDayViewBoundary(date, min, max); if (date?.getTime() !== focusedDate?.getTime()) { const monthChanged = date ? date.getMonth() !== focusedDate?.getMonth() || date.getFullYear() !== focusedDate?.getFullYear() : false; setFocusedDate(date); if (date) { setViewMonth(date.getMonth()); setViewYear(date.getFullYear()); } if (monthChanged) { setHasInteracted(false); } else if (!hasInteracted) { setHasInteracted(true); } onDateFocus?.(date, { isEnabled: checkIsEnabled(date) }); } }, [focusedDate, selectedDate, min, max, mode, onDateFocus], // eslint-disable-line react-hooks/exhaustive-deps ); const handleDayFocus = useCallback( (date: Date) => { if (date.getTime() !== focusedDate?.getTime()) { setFocusedDate(date); onDateFocus?.(date, { isEnabled: checkIsEnabled(date) }); } }, [focusedDate, onDateFocus], // eslint-disable-line react-hooks/exhaustive-deps ); const handleKeyDown = useCallback( (event: KeyboardEvent) => { const orientationSign = isRTL ? -1 : 1; switch (event.key) { case 'ArrowLeft': adjustDate(-1 * orientationSign, -1 * orientationSign, -1 * orientationSign); event.preventDefault(); break; case 'ArrowUp': adjustDate(-7, -4, -4); event.preventDefault(); break; case 'ArrowRight': adjustDate(1 * orientationSign, 1 * orientationSign, 1 * orientationSign); event.preventDefault(); break; case 'ArrowDown': adjustDate(7, 4, 4); event.preventDefault(); break; case 'Enter': case ' ': if ( mode === 'day' && focusedDate && (event.target as HTMLElement).hasAttribute('data-calendar-cell') ) { handleSelectedDateUpdate(focusedDate); event.preventDefault(); } break; default: break; } }, [adjustDate, focusedDate, mode, handleSelectedDateUpdate, isRTL], ); const focusedDateOutOfRange = focusedDate ? !isWithinRange(focusedDate, min, max) : false; const formatDateForPrompt = (date: Date) => formatDate(date, intl.locale, LONG_DAY_FORMAT); const outOfRangePromptText = min && max ? intl.formatMessage(messages.outOfRangeBetween, { min: formatDateForPrompt(min), max: formatDateForPrompt(max), }) : min ? intl.formatMessage(messages.outOfRangeAfter, { min: formatDateForPrompt(min) }) : max ? intl.formatMessage(messages.outOfRangeBefore, { max: formatDateForPrompt(max) }) : ''; const hasOutOfRangeDates = mode === 'day' && !!(min || max); const showRulesPrompt = mode === 'day' && !!disabledRules && hasDisabledDatesInMonth(viewMonth, viewYear, disabledRules, min, max); const showOutOfRangePrompt = mode === 'day' && focusedDateOutOfRange; const showPrompt = hasOutOfRangeDates || showRulesPrompt; const promptText = showOutOfRangePrompt ? outOfRangePromptText : (disabledRules?.reason ?? outOfRangePromptText); const promptSentiment = showOutOfRangePrompt || focusedDateDisabled ? 'negative' : 'neutral'; // Visible when there's an actionable message; sr-only when only hasOutOfRangeDates is true // (prompt exists for aria-describedby but no visual cue needed until an out-of-range date is focused) const promptClassName = showOutOfRangePrompt || showRulesPrompt ? 'm-t-1' : 'sr-only'; return ( // eslint-disable-next-line jsx-a11y/no-static-element-interactions
{mode === 'day' && ( )} {mode === 'month' && ( )} {mode === 'year' && ( )} {showPrompt && ( {promptText} )}
); }; export default Calendar;