UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

50 lines 2.4 kB
import { isSameMonth, setMonth, setYear, startOfMonth } from "date-fns"; import React, { useState } from "react"; import { BodyShort } from "../../../typography/index.js"; import { isMatch } from "../../date-utils/index.js"; import { useMonthPickerContext } from "../MonthPicker.context.js"; import MonthButton from "./MonthPicker.Button.js"; const getAllMonths = () => { const months = []; const date = startOfMonth(new Date()); for (let month = 0; month <= 11; month++) { months.push(setMonth(date, month)); } return months; }; const MonthPickerTable = () => { const [focus, setFocus] = useState(); const { selected, year, disabled } = useMonthPickerContext(); const months = getAllMonths(); const hasSelected = selected && months.some((m) => isSameMonth(setYear(m, year.getFullYear()), selected)); const getRootFallback = () => { const today = startOfMonth(new Date()); if ((year === null || year === void 0 ? void 0 : year.getFullYear()) === today.getFullYear() && !isMatch(today, disabled)) { return today; } for (let i = 0; i < months.length; i++) { const m = months[i]; if (!isMatch(setYear(m, year.getFullYear()), disabled)) { return setYear(m, year.getFullYear()); } } }; const [tabRoot, setTabRoot] = useState(hasSelected ? selected : getRootFallback()); if ((tabRoot === null || tabRoot === void 0 ? void 0 : tabRoot.getFullYear()) !== year.getFullYear()) { setTabRoot(hasSelected ? selected : getRootFallback()); } const tableMonths = [ months.slice(0, 4), months.slice(4, 8), months.slice(8, 12), ]; return (React.createElement(BodyShort, { as: "table", className: "rdp-table" }, React.createElement("tbody", { className: "rdp-tbody" }, tableMonths.map((tableRow, i) => (React.createElement("tr", { className: "rdp-row", key: i }, tableRow.map((month) => { return (React.createElement("td", { key: month.toDateString(), className: "rdp-cell" }, React.createElement(MonthButton, { month: setYear(month, year.getFullYear()), months: months, focus: focus, setFocus: setFocus, tabRoot: tabRoot, setTabRoot: setTabRoot }))); }))))))); }; export { MonthPickerTable }; //# sourceMappingURL=MonthPicker.Table.js.map