1 | import { DropdownOption } from "../components/Dropdown.js";
|
2 | import type { DateLib, Formatters } from "../types/index.js";
|
3 |
|
4 |
|
5 | export function getYearOptions(
|
6 | displayMonth: Date,
|
7 | calendarStart: Date | undefined,
|
8 | calendarEnd: Date | undefined,
|
9 | formatters: Pick<Formatters, "formatYearDropdown">,
|
10 | dateLib: DateLib
|
11 | ): DropdownOption[] | undefined {
|
12 | if (!calendarStart) return undefined;
|
13 | if (!calendarEnd) return undefined;
|
14 | const {
|
15 | startOfMonth,
|
16 | startOfYear,
|
17 | endOfYear,
|
18 | addYears,
|
19 | isBefore,
|
20 | isSameYear,
|
21 | Date
|
22 | } = dateLib;
|
23 | const month = displayMonth.getMonth();
|
24 | const firstNavYear = startOfYear(calendarStart);
|
25 | const lastNavYear = endOfYear(calendarEnd);
|
26 | const years: number[] = [];
|
27 |
|
28 | let year = firstNavYear;
|
29 | while (isBefore(year, lastNavYear) || isSameYear(year, lastNavYear)) {
|
30 | years.push(year.getFullYear());
|
31 | year = addYears(year, 1);
|
32 | }
|
33 |
|
34 | return years.map((value) => {
|
35 | const disabled =
|
36 | (calendarStart && new Date(value, month) < startOfMonth(calendarStart)) ||
|
37 | (month &&
|
38 | calendarEnd &&
|
39 | new Date(value, month) > startOfMonth(calendarEnd)) ||
|
40 | false;
|
41 | const label = formatters.formatYearDropdown(value);
|
42 | return {
|
43 | value,
|
44 | label,
|
45 | disabled
|
46 | };
|
47 | });
|
48 | }
|