import { classNames, create, createEventRegistrar, text, } from "@hesxenon/prelude/Dom.js"; import { addMonths, addYears } from "date-fns/fp"; import { update } from "../../utils/Date"; import { Events } from "../events"; import { getMonthName } from "../format"; import { connectSelection } from "../parts/selection"; import type { Connect, View } from "../uwc-datepicker"; const getStartOfPage = update((copy) => { copy.setMonth(0); }); const connectGrid: Connect = (datepicker, opts) => { const on = createEventRegistrar(datepicker, opts.disconnect); const createGrid = () => { const months = create("ul", { role: "grid" }); const now = new Date(); const start = getStartOfPage(datepicker.anchorDate); const end = addYears(1, start); let cursor = start; while (cursor < end) { const next = addMonths(1, cursor); const dataValue = cursor.toISOString(); months.append( create( "li", { "data-value": dataValue, className: classNames({ current: cursor <= now && now <= next, }), }, [text(getMonthName(cursor, datepicker.locale, "long"))], ), ); cursor = next; } return months; }; let grid = createGrid(); on(Events["anchor-dateChanged"], () => { grid.remove(); grid = createGrid(); datepicker.append(grid); }); datepicker.append(grid); }; export const monthView: View = { addOneUnit: addMonths(1), connect: (datepicker, opts) => { connectSelection(datepicker, { addPages: addYears, leapPages: 10, getStartOfPage, getLabel: (current) => String(current.getFullYear()), disconnect: opts.disconnect, }); connectGrid(datepicker, opts); }, };