/* istanbul ignore file */ import * as React from "react"; import styles from "./BaseDatePickerCalendar.module.scss"; import classNames from "classnames"; import { useOnClickOutside, useOnKeyDown } from "../hooks"; import { TfiAngleLeft, TfiAngleRight, TfiAngleDoubleRight, TfiAngleDoubleLeft, } from "react-icons/tfi"; import { getCalendarDays, getNextDay, getNextWeek, getPreviousDay, getPreviousWeek, } from "../utility/getDatePickerCalendarUtilities"; import { DatePickerContext } from "./DatePickerContext"; import { Button } from "../Button"; import { FocusTrap } from "../FocusTrap/FocusTrap"; import { IconButton } from "../IconButton/IconButton"; export interface BaseDatePickerCalendarProps { /** * The callback fired when the DatePickerCalendar requests to close */ onClose: () => void; /** * The trigger ref for the DatePicker */ triggerRef: React.RefObject; } /** * @private */ export const BaseDatePickerCalendar: React.FC = (props) => { const { onClose, triggerRef } = props; const { selectedDate, setSelectedDate } = React.useContext(DatePickerContext); const [date, setDate] = React.useState( selectedDate ?? new Date() ); const [focusedDate, setFocusedDate] = React.useState(0); const [days, setDays] = React.useState>([]); const daysRefs = React.useRef>( [] ); const calendarRef = React.useRef(null); const headerLabels = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", ]; const increaseMonth = () => { setDate( new Date( date.getFullYear(), date.getMonth() + 1, date.getDate() ) ); }; const increaseYear = () => { setDate( new Date( date.getFullYear() + 1, date.getMonth(), date.getDate() ) ); }; const decreaseMonth = () => { setDate( new Date( date.getFullYear(), date.getMonth() - 1, date.getDate() ) ); }; const decreaseYear = () => { setDate( new Date( date.getFullYear() - 1, date.getMonth(), date.getDate() ) ); }; React.useEffect(() => { setDays(getCalendarDays(date)); setFocusedDate(date.getDate()); }, [date]); React.useEffect(() => { daysRefs.current[focusedDate]?.focus(); }, [focusedDate]); useOnClickOutside([calendarRef, triggerRef], onClose); useOnKeyDown(["Escape"], onClose); return (
} size="medium" onClick={decreaseYear} /> } size="medium" onClick={decreaseMonth} />
{`${date.toLocaleString("en-US", { month: "long", })} ${date.getFullYear()}`}
} size="medium" onClick={increaseMonth} /> } size="medium" onClick={increaseYear} />
{headerLabels.map((label, index) => { return (
{label}
); })}
{days.map((day, index) => { if (day !== null) { const isSelected = new Date( date.getFullYear(), date.getMonth(), day ).getTime() === selectedDate?.getTime(); const isToday = new Date( date.getFullYear(), date.getMonth(), day ).getTime() === new Date( new Date().getFullYear(), new Date().getMonth(), new Date().getDate() ).getTime(); return (
); } else { return (
); } })}
); }; BaseDatePickerCalendar.displayName = "BaseDatePickerCalendar";