UNPKG

2.73 kBPlain TextView Raw
1import { CalendarWeek, CalendarDay, CalendarMonth } from "../classes/index.js";
2import type { DateLib, DayPickerProps } from "../types/index.js";
3
4/** Return the months to display in the calendar. */
5export function getMonths(
6 /** The months (as dates) to display in the calendar. */
7 displayMonths: Date[],
8 /** The dates to display in the calendar. */
9 dates: Date[],
10 /** Options from the props context. */
11 props: Pick<
12 DayPickerProps,
13 | "fixedWeeks"
14 | "ISOWeek"
15 | "locale"
16 | "weekStartsOn"
17 | "reverseMonths"
18 | "firstWeekContainsDate"
19 >,
20 dateLib: DateLib
21): CalendarMonth[] {
22 const {
23 startOfWeek,
24 endOfWeek,
25 startOfISOWeek,
26 endOfISOWeek,
27 endOfMonth,
28 addDays,
29 getWeek,
30 getISOWeek
31 } = dateLib;
32 const dayPickerMonths = displayMonths.reduce<CalendarMonth[]>(
33 (months, month) => {
34 const firstDateOfFirstWeek = props.ISOWeek
35 ? startOfISOWeek(month)
36 : startOfWeek(month, {
37 locale: props.locale,
38 weekStartsOn: props.weekStartsOn
39 });
40
41 const lastDateOfLastWeek = props.ISOWeek
42 ? endOfISOWeek(endOfMonth(month))
43 : endOfWeek(endOfMonth(month), {
44 locale: props.locale,
45 weekStartsOn: props.weekStartsOn
46 });
47
48 /** The dates to display in the month. */
49 const monthDates = dates.filter((date) => {
50 return date >= firstDateOfFirstWeek && date <= lastDateOfLastWeek;
51 });
52
53 if (props.fixedWeeks && monthDates.length < 42) {
54 const extraDates = dates.filter((date) => {
55 return (
56 date > lastDateOfLastWeek && date <= addDays(lastDateOfLastWeek, 7)
57 );
58 });
59 monthDates.push(...extraDates);
60 }
61
62 const weeks: CalendarWeek[] = monthDates.reduce<CalendarWeek[]>(
63 (weeks, date) => {
64 const weekNumber = props.ISOWeek
65 ? getISOWeek(date)
66 : getWeek(date, {
67 locale: props.locale,
68 weekStartsOn: props.weekStartsOn,
69 firstWeekContainsDate: props.firstWeekContainsDate
70 });
71 const week = weeks.find((week) => week.weekNumber === weekNumber);
72
73 const day = new CalendarDay(date, month, dateLib);
74 if (!week) {
75 weeks.push(new CalendarWeek(weekNumber, [day]));
76 } else {
77 week.days.push(day);
78 }
79 return weeks;
80 },
81 []
82 );
83
84 const dayPickerMonth = new CalendarMonth(month, weeks);
85
86 months.push(dayPickerMonth);
87 return months;
88 },
89 []
90 );
91
92 if (!props.reverseMonths) {
93 return dayPickerMonths;
94 } else {
95 return dayPickerMonths.reverse();
96 }
97}