UNPKG

1.18 kBPlain TextView Raw
1import type { DateLib, DayPickerProps } from "../types/index.js";
2
3/**
4 * Return the next previous the user can navigate to, according to the given
5 * options.
6 *
7 * Please note that the previous month is not always the previous calendar
8 * month:
9 *
10 * - If before the `calendarStartMonth` date, is `undefined`;
11 * - If the navigation is paged, is the number of months displayed before.
12 */
13export function getPreviousMonth(
14 firstDisplayedMonth: Date,
15 calendarStartMonth: Date | undefined,
16 options: Pick<
17 DayPickerProps,
18 "numberOfMonths" | "pagedNavigation" | "disableNavigation"
19 >,
20 dateLib: DateLib
21): Date | undefined {
22 if (options.disableNavigation) {
23 return undefined;
24 }
25 const { pagedNavigation, numberOfMonths } = options;
26 const { startOfMonth, addMonths, differenceInCalendarMonths } = dateLib;
27 const offset = pagedNavigation ? (numberOfMonths ?? 1) : 1;
28 const month = startOfMonth(firstDisplayedMonth);
29 if (!calendarStartMonth) {
30 return addMonths(month, -offset);
31 }
32 const monthsDiff = differenceInCalendarMonths(month, calendarStartMonth);
33
34 if (monthsDiff <= 0) {
35 return undefined;
36 }
37
38 return addMonths(month, -offset);
39}