/* eslint-disable @typescript-eslint/no-empty-function */ import React, { useState, useRef, useEffect, FC, } from 'react'; import dayjs from 'dayjs'; import 'dayjs/locale/da'; import advancedFormat from 'dayjs/plugin/advancedFormat'; import isoWeek from 'dayjs/plugin/isoWeek'; import localizedFormat from 'dayjs/plugin/localizedFormat'; const months: Record = { da: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December'], en: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], }; const dayTitles: Record = { da: ['Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør', 'Søn'], en: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], }; const dayNames: Record = { da: ['Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag'], en: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], }; const adjacentMonthLabels: Record = { da: { before: 'forrige måned', after: 'næste måned' }, en: { before: 'previous month', after: 'next month' }, }; const daysInMonth = (year: number, month: number): number => new Date(year, month, 0).getDate(); // eslint-disable-next-line max-len const addDays = (days: number, date: Date): Date => new Date(date.getTime() + days * 60 * 24 * 60000); const calcEaster = (year: number): Date => { const a = year % 19; const b = Math.floor(year / 100); const c = year % 100; const d = Math.floor(b / 4); const e = b % 4; const f = Math.floor((b + 8) / 25); const g = Math.floor((b - f + 1) / 3); const h = (19 * a + b - d - g + 15) % 30; const i = Math.floor(c / 4); const k = c % 4; const l = (32 + 2 * e + 2 * i - h - k) % 7; const m = Math.floor((a + 11 * h + 22 * l) / 451); const n0 = (h + l + 7 * m + 114); const n = Math.floor(n0 / 31) - 1; const p = (n0 % 31) + 1; const date = new Date(year, n, p); return date; }; const isHoliday = (date: Date): boolean => { const year = date.getFullYear(); const holidays: Date[] = []; const newYear = new Date(year, 0, 1); holidays.push(newYear); const easter = calcEaster(year); holidays.push(easter); const easterThu = addDays(-3, easter); holidays.push(easterThu); const easterFri = addDays(-2, easter); holidays.push(easterFri); const easter2 = addDays(1, easter); holidays.push(easter2); const stBededag = addDays(26, easter); holidays.push(stBededag); const kristiHf = addDays(39, easter); holidays.push(kristiHf); const whitsun = addDays(49, easter); holidays.push(whitsun); const whitsun2 = addDays(1, whitsun); holidays.push(whitsun2); const grundlov = new Date(year, 5, 5); holidays.push(grundlov); const christmas = new Date(year, 11, 25); holidays.push(christmas); const christmas2 = addDays(1, christmas); holidays.push(christmas2); return holidays.map((h) => h.toString()).filter((x) => x === date.toString()).length > 0; }; const dateAllowed = (date: Date, limitStart: Date, limitEnd: Date): boolean => { if (limitStart && !limitEnd) { return date >= limitStart; } if (!limitStart && limitEnd) { return date <= limitEnd; } if (limitStart && limitEnd) { return date >= limitStart && date <= limitEnd; } return true; }; const skipDays = [6, 0, 1, 2, 3, 4, 5]; // Calendar arithmetic - built from the date parts rather than from milliseconds so a // step never lands on the wrong day across a daylight saving change const shiftDays = (date: Date, days: number): Date => new Date( date.getFullYear(), date.getMonth(), date.getDate() + days, ); const shiftMonths = (date: Date, months2: number): Date => { const targetMonth = date.getMonth() + months2; const year = date.getFullYear() + Math.floor(targetMonth / 12); const month = ((targetMonth % 12) + 12) % 12; const day = Math.min(date.getDate(), daysInMonth(year, month + 1)); return new Date(year, month, day); }; // Time is picked for the selected date, not for whatever month the calendar is showing const withTime = (date: Date, hour: number, minute: number): Date => new Date( date.getFullYear(), date.getMonth(), date.getDate(), hour, minute, ); type Props = { lang?: string; day: number; month: number; year: number; hour: number; minute: number; selected?: Date; onSelected: (selected: Date) => void; highlightWeekend?: boolean; highlightHolidays?: boolean; yearSpanMinus?: number; yearSpanPlus?: number; minuteInterval?: number; showTime?: boolean; closeable?: boolean; onClose?: () => void; limitStart?: Date | null; limitEnd?: Date | null; // 'week' marks the whole week of the date being hovered, focused or clicked selectionMode?: 'day' | 'week'; controls: string; }; const AUCalendarComponent: FC = ({ lang = 'da', day, month, year, hour, minute, selected = new Date(), onSelected, highlightWeekend = true, highlightHolidays = true, yearSpanMinus = 5, yearSpanPlus = 5, minuteInterval = 5, showTime = true, closeable = false, onClose = () => { }, limitStart = null, limitEnd = null, selectionMode = 'day', controls, }) => { dayjs.locale(lang); dayjs.extend(advancedFormat); dayjs.extend(isoWeek); // Without this the LL token below is emitted literally instead of a readable date dayjs.extend(localizedFormat); const [calendarState, setCalendarState] = useState({ day, month, year, hour, minute, selected: selected as Date, }); // The monday of the marked week, null when no week is marked const [markedWeek, setMarkedWeek] = useState(null); const weekMode = selectionMode === 'week'; // Roving tabindex: the grid is a single tab stop and the arrow keys move between the // cells, so a keyboard user is not forced through 40-odd buttons to pass the calendar const [activeKey, setActiveKey] = useState(null); const cellRefs = useRef(new Map()); const moveFocusOnRender = useRef(false); const weekKey = (date: Date): string => dayjs(date).startOf('isoWeek').format('YYYY-MM-DD'); const dateKey = (date: Date): string => dayjs(date).format('YYYY-MM-DD'); const weekHeaderKey = (date: Date): string => `week:${weekKey(date)}`; const registerCell = (key: string) => (element: HTMLButtonElement | null) => { if (element) { cellRefs.current.set(key, element); } else { cellRefs.current.delete(key); } }; useEffect(() => { if (!moveFocusOnRender.current || activeKey === null) { return; } moveFocusOnRender.current = false; cellRefs.current.get(activeKey)?.focus(); }); const { month: sMonth, year: sYear, hour: sHour, minute: sMinute, selected: sSelected, } = calendarState; const goBack = () => { const newMonth = sMonth - 1 < 1 ? 12 : (sMonth - 1); const newYear = newMonth === 12 ? (sYear - 1) : sYear; setCalendarState({ ...calendarState, ...{ month: newMonth, year: newYear, }, }); }; const goForward = () => { const newMonth = sMonth + 1 > 12 ? 1 : (sMonth + 1); const newYear = newMonth === 1 ? (sYear + 1) : sYear; setCalendarState({ ...calendarState, ...{ month: newMonth, year: newYear, }, }); }; const renderMonths = months[lang as string].map( (m: string, i: number) => ( ), ); let yearStart = yearSpanMinus; // eslint-disable-next-line max-len if (limitStart && limitStart.getFullYear() > (sSelected.getFullYear() - (yearSpanMinus as number))) { yearStart = sSelected.getFullYear() - limitStart.getFullYear(); } let yearEnd = yearSpanPlus; if (limitEnd && limitEnd.getFullYear() < (sSelected.getFullYear() + (yearSpanPlus as number))) { yearEnd = limitEnd.getFullYear() + sSelected.getFullYear(); } const yearArr: number[] = []; for (let y = sYear - (yearStart as number); y <= sYear + (yearEnd as number); y += 1) { yearArr.push(y); } const renderYears = yearArr.map( (y) => ( ), ); const renderWeekDays = (
{lang === 'da' ? 'Uge' : 'Wk'} {dayTitles[lang as string].map( (w: string, i: number) => ( {w} ), )}
); const firstDayInMonth = new Date(sYear, sMonth - 1, 1); const emptyDaysBefore = skipDays[firstDayInMonth.getDay()]; const prevYear = sMonth === 1 ? sYear - 1 : sYear; const prevMonth = sMonth === 1 ? 12 : sMonth - 1; const numberOfDaysInPrevMonth = daysInMonth(prevYear, prevMonth); const numberOfDaysInMonth = daysInMonth(sYear, sMonth); const nextYear = sMonth === 12 ? (sYear + 1) : sYear; const nextMonth = sMonth === 12 ? 1 : (sMonth + 1); const totalCells = Math.ceil((emptyDaysBefore + numberOfDaysInMonth) / 7) * 7; const emptyDaysAfter = totalCells - emptyDaysBefore - numberOfDaysInMonth; type DayCell = { key: string; date: Date; label: number; kind: 'before' | 'current' | 'after'; }; const cells: DayCell[] = []; for (let i = 0; i < emptyDaysBefore; i += 1) { const label = numberOfDaysInPrevMonth - emptyDaysBefore + i + 1; cells.push({ key: `before-${label}`, date: new Date(prevYear, prevMonth - 1, label), label, kind: 'before', }); } for (let i = 0; i < numberOfDaysInMonth; i += 1) { const label = i + 1; cells.push({ key: `current-${label}`, date: new Date(sYear, sMonth - 1, label, sHour, sMinute), label, kind: 'current', }); } for (let i = 0; i < emptyDaysAfter; i += 1) { const label = i + 1; cells.push({ key: `after-${label}`, date: new Date(nextYear, nextMonth - 1, label), label, kind: 'after', }); } const rows: DayCell[][] = []; for (let i = 0; i < cells.length; i += 7) { rows.push(cells.slice(i, i + 7)); } // Every cell the arrow keys can currently reach, week numbers included const navigableKeys = new Set(); rows.forEach((row) => { navigableKeys.add(weekHeaderKey(row[0].date)); row.forEach((cell) => navigableKeys.add(dateKey(cell.date))); }); const isDateEnabled = (date: Date): boolean => dateAllowed( date, limitStart as Date, limitEnd as Date, ); // The first date from `from` in the given direction that is inside the allowed range, // so the arrow keys step over disabled dates instead of getting stuck on them const nextEnabled = (from: Date, direction: number): Date | null => { let candidate = from; for (let i = 0; i < 400; i += 1) { if (isDateEnabled(candidate)) { return candidate; } candidate = shiftDays(candidate, direction); } return null; }; // The selected date is the default active cell, so tabbing in lands where the user // left off. When it is not on screen the first day of the shown month takes over. const selectedKey = dateKey(sSelected); const fallbackKey = dateKey(new Date(sYear, sMonth - 1, 1)); let defaultActiveKey = fallbackKey; if (navigableKeys.has(selectedKey)) { defaultActiveKey = selectedKey; } const activeCellKey = activeKey && navigableKeys.has(activeKey) ? activeKey : defaultActiveKey; const showMonthOf = (date: Date) => { setCalendarState({ ...calendarState, ...{ month: date.getMonth() + 1, year: date.getFullYear(), }, }); }; const focusCell = (key: string, date: Date) => { if (!navigableKeys.has(key)) { showMonthOf(date); } setActiveKey(key); moveFocusOnRender.current = true; }; // Arrowing onto a date from a neighbouring month moves the whole grid to that month, // so the cell under focus is always one that selects rather than one that pages const focusDate = (date: Date | null) => { if (!date) { return; } if (date.getMonth() + 1 !== sMonth || date.getFullYear() !== sYear) { showMonthOf(date); } setActiveKey(dateKey(date)); moveFocusOnRender.current = true; }; const startOfWeek = (date: Date): Date => dayjs(date).startOf('isoWeek').toDate(); const focusWeekHeader = (date: Date) => { const monday = startOfWeek(date); if (isDateEnabled(monday)) { focusCell(weekHeaderKey(monday), monday); } }; // Arrow keys walk the grid, Home/End jump to monday/sunday and PageUp/PageDown change // month - or year when combined with shift, as in the WAI-ARIA date picker pattern const handleGridKeyDown = ( event: React.KeyboardEvent, date: Date, onWeekHeader: boolean, ) => { const monday = startOfWeek(date); const stepTo = (days: number, direction: number) => { if (onWeekHeader) { const target = shiftDays(monday, days); if (isDateEnabled(target)) { focusCell(weekHeaderKey(target), target); } return; } focusDate(nextEnabled(shiftDays(date, days), direction)); }; switch (event.key) { case 'ArrowLeft': if (onWeekHeader) { return; } if (dayjs(date).isoWeekday() === 1) { focusWeekHeader(date); } else { stepTo(-1, -1); } break; case 'ArrowRight': if (onWeekHeader) { focusDate(isDateEnabled(monday) ? monday : null); } else { stepTo(1, 1); } break; case 'ArrowUp': stepTo(-7, -1); break; case 'ArrowDown': stepTo(7, 1); break; case 'Home': if (!onWeekHeader) { focusDate(isDateEnabled(monday) ? monday : null); } break; case 'End': { const sunday = shiftDays(monday, 6); focusDate(isDateEnabled(sunday) ? sunday : null); break; } case 'PageUp': case 'PageDown': { const forward = event.key === 'PageDown'; const anchor = onWeekHeader ? monday : date; const moved = event.shiftKey ? shiftMonths(anchor, forward ? 12 : -12) : shiftMonths(anchor, forward ? 1 : -1); const target = nextEnabled(moved, forward ? 1 : -1); if (target && onWeekHeader) { focusCell(weekHeaderKey(startOfWeek(target)), target); } else { focusDate(target); } break; } default: return; } event.preventDefault(); }; const selectWeek = (weekStart: Date) => { const newSelected = new Date( weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate(), sHour, sMinute, ); setCalendarState({ ...calendarState, ...{ day: newSelected.getDate(), month: newSelected.getMonth() + 1, year: newSelected.getFullYear(), selected: newSelected, }, }); setMarkedWeek(weekKey(weekStart)); onSelected(newSelected); }; const renderCell = (cell: DayCell, columnIndex: number) => { const isWeekend = (highlightWeekend && columnIndex > 4) || (highlightHolidays && isHoliday(cell.date)); const isSelected = cell.kind === 'current' && cell.label === sSelected.getDate() && sYear === sSelected.getFullYear() && sMonth === sSelected.getMonth() + 1; const cellWeek = weekKey(cell.date); const isInMarkedWeek = markedWeek !== null && cellWeek === markedWeek; let isDisabled: boolean; if (cell.kind === 'current') { // eslint-disable-next-line max-len isDisabled = ((limitStart && cell.date < limitStart) || (limitEnd && cell.date > limitEnd)) as boolean; } else if (cell.kind === 'before') { isDisabled = (limitStart && cell.date < limitStart) as boolean; } else { isDisabled = (limitEnd && cell.date > limitEnd) as boolean; } let className = 'calendar__days__date'; if (cell.kind !== 'current') { className = `${className} calendar__days__date--empty`; } if (isWeekend) { className = `${className} calendar__days__date--weekend`; } if (isInMarkedWeek) { className = `${className} calendar__days__date--week-marked`; if (columnIndex === 6) { className = `${className} calendar__days__date--week-marked-last`; } } if (isSelected) { className = `${className} calendar__days__date--selected`; } const onClick = () => { if (cell.kind === 'before') { goBack(); return; } if (cell.kind === 'after') { goForward(); return; } const newSelected = cell.date; setCalendarState({ ...calendarState, ...{ day: cell.label, selected: newSelected, }, }); setMarkedWeek(weekMode ? cellWeek : null); onSelected(newSelected); }; const key = dateKey(cell.date); let cellLabel = dayjs(cell.date).format('dddd LL'); if (cell.kind !== 'current') { cellLabel = `${cellLabel}, ${adjacentMonthLabels[lang as string][cell.kind]}`; } return ( ); }; const renderWeekHeader = (cell: DayCell) => { const weekNumber = dayjs(cell.date).isoWeek(); // eslint-disable-next-line max-len const weekDisabled = ((limitStart && cell.date < limitStart) || (limitEnd && cell.date > limitEnd)) as boolean; const weekLabel = lang === 'da' ? `Uge ${weekNumber}` : `Week ${weekNumber}`; const cellWeek = weekKey(cell.date); const isInMarkedWeek = markedWeek !== null && cellWeek === markedWeek; const key = weekHeaderKey(cell.date); let weekClassName = 'calendar__days__week-number'; if (isInMarkedWeek) { weekClassName = `${weekClassName} calendar__days__week-number--marked`; } return ( ); }; const renderDays = rows.map((row) => (
{renderWeekHeader(row[0])} {row.map((cell, columnIndex) => renderCell(cell, columnIndex))}
)); const renderHours = Array(24).fill(null).map((_, i) => { const key = i; const optHour = i < 10 ? `0${i}` : i; return ( ); }); const renderMinutes = Array(60).fill(null).map((_, i) => { const key = i; if (i % (minuteInterval as number) === 0) { const optMinute = i < 10 ? `0${i}` : i; return ( ); } return null; }); return (
{ closeable && ( ) }
{renderWeekDays} {renderDays}
{ showTime && (
) }
); }; AUCalendarComponent.displayName = 'AUCalendarComponent'; export default AUCalendarComponent;