@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
53 lines • 2.83 kB
JavaScript
import { compareAsc, compareDesc, format, isSameMonth, setYear, } from "date-fns";
import React, { useEffect, useRef } from "react";
import { useRenameCSS } from "../../../theme/Theme.js";
import { dateIsInCurrentMonth, isMatch } from "../../date-utils/index.js";
import { useMonthPickerContext } from "../MonthPicker.context.js";
import { nextEnabled } from "../MonthPicker.util.js";
const disableMonth = (month, fromDate, toDate) => {
if (fromDate && toDate) {
return ((compareAsc(month, fromDate) === -1 && !isSameMonth(month, fromDate)) ||
(compareDesc(month, toDate) === -1 && !isSameMonth(month, toDate)));
}
if (fromDate) {
return compareAsc(month, fromDate) === -1 && !isSameMonth(month, fromDate);
}
if (toDate) {
return compareDesc(month, toDate) === -1 && !isSameMonth(month, toDate);
}
return false;
};
export const MonthButton = ({ month, months, focus, setFocus, tabRoot, setTabRoot, }) => {
const ref = useRef(null);
const { cn } = useRenameCSS();
const { fromDate, toDate, locale, selected, disabled, year, onYearChange, onMonthSelect, caption, } = useMonthPickerContext();
const isSelected = selected && isSameMonth(month, selected);
useEffect(() => {
if (focus) {
isSameMonth(month, focus) && ref.current && ref.current.focus();
setFocus();
}
}, [focus, month, setFocus]);
const isDisabled = isMatch(setYear(month, year.getFullYear()), disabled) ||
disableMonth(month, fromDate, toDate);
const isThisMonth = dateIsInCurrentMonth(month, year);
return (React.createElement("button", { ref: ref, type: "button", onClick: () => onMonthSelect === null || onMonthSelect === void 0 ? void 0 : onMonthSelect(isSelected ? undefined : month), disabled: isDisabled, "aria-pressed": !!isSelected, "data-current-month": isThisMonth, className: cn("navds-date__month-button", {
"rdp-day_today": isThisMonth,
"rdp-day_selected": isSelected,
"rdp-day_disabled": isDisabled,
}), tabIndex: tabRoot && isSameMonth(month, setYear(tabRoot, year.getFullYear()))
? 0
: -1, onKeyDown: (e) => {
const next = nextEnabled(months, e.key, disabled, month, onYearChange, year, caption === "dropdown", fromDate, toDate);
setFocus(next);
setTabRoot(next);
}, onFocus: () => {
setTabRoot(focus);
} },
React.createElement("span", { "aria-hidden": "true" }, format(new Date(month), "LLL", { locale })
.replace(".", "")
.substring(0, 3)),
React.createElement("span", { className: cn("navds-sr-only") }, format(new Date(month), "LLLL", { locale }))));
};
export default MonthButton;
//# sourceMappingURL=MonthPicker.Button.js.map