UNPKG

1.07 kBPlain TextView Raw
1import type { DateLib, DayPickerProps } from "../index.js";
2
3/** Return the start month based on the props passed to DayPicker. */
4export function getInitialMonth(
5 props: Pick<
6 DayPickerProps,
7 | "fromYear"
8 | "toYear"
9 | "startMonth"
10 | "endMonth"
11 | "month"
12 | "defaultMonth"
13 | "today"
14 | "numberOfMonths"
15 >,
16 dateLib: DateLib
17): Date {
18 const {
19 month,
20 defaultMonth,
21 today = new dateLib.Date(),
22 numberOfMonths = 1,
23 endMonth,
24 startMonth
25 } = props;
26 let initialMonth = month || defaultMonth || today;
27 const { differenceInCalendarMonths, addMonths, startOfMonth } = dateLib;
28
29 // Fix the initialMonth if is after the to-date
30 if (endMonth && differenceInCalendarMonths(endMonth, initialMonth) < 0) {
31 const offset = -1 * (numberOfMonths - 1);
32 initialMonth = addMonths(endMonth, offset);
33 }
34 // Fix the initialMonth if is before the from-date
35 if (startMonth && differenceInCalendarMonths(initialMonth, startMonth) < 0) {
36 initialMonth = startMonth;
37 }
38 return startOfMonth(initialMonth);
39}