1 | import { useEffect, useState } from "react";
|
2 | import { getDates } from "./helpers/getDates.js";
|
3 | import { getDays } from "./helpers/getDays.js";
|
4 | import { getDisplayMonths } from "./helpers/getDisplayMonths.js";
|
5 | import { getInitialMonth } from "./helpers/getInitialMonth.js";
|
6 | import { getMonths } from "./helpers/getMonths.js";
|
7 | import { getNavMonths } from "./helpers/getNavMonth.js";
|
8 | import { getNextMonth } from "./helpers/getNextMonth.js";
|
9 | import { getPreviousMonth } from "./helpers/getPreviousMonth.js";
|
10 | import { getWeeks } from "./helpers/getWeeks.js";
|
11 |
|
12 | export function useCalendar(props, dateLib) {
|
13 | const [navStart, navEnd] = getNavMonths(props, dateLib);
|
14 | const { startOfMonth, endOfMonth } = dateLib;
|
15 | const initialMonth = getInitialMonth(props, dateLib);
|
16 | const [firstMonth, setFirstMonth] = useState(initialMonth);
|
17 |
|
18 | useEffect(() => {
|
19 | const initialDisplayMonth = getInitialMonth(props, dateLib);
|
20 | setFirstMonth(initialDisplayMonth);
|
21 |
|
22 | }, [props.month]);
|
23 |
|
24 | useEffect(() => {
|
25 |
|
26 |
|
27 | const initialDisplayMonth = getInitialMonth(props, dateLib);
|
28 | setFirstMonth(initialDisplayMonth);
|
29 |
|
30 | }, [props.startMonth, props.endMonth]);
|
31 |
|
32 | const displayMonths = getDisplayMonths(firstMonth, navEnd, props, dateLib);
|
33 |
|
34 | const dates = getDates(displayMonths, props.endMonth ? endOfMonth(props.endMonth) : undefined, props, dateLib);
|
35 |
|
36 | const months = getMonths(displayMonths, dates, props, dateLib);
|
37 |
|
38 | const weeks = getWeeks(months);
|
39 |
|
40 | const days = getDays(months);
|
41 | const previousMonth = getPreviousMonth(firstMonth, navStart, props, dateLib);
|
42 | const nextMonth = getNextMonth(firstMonth, navEnd, props, dateLib);
|
43 | const { disableNavigation, onMonthChange } = props;
|
44 | const isDayInCalendar = (day) => weeks.some((week) => week.days.some((d) => d.isEqualTo(day)));
|
45 | const goToMonth = (date) => {
|
46 | if (disableNavigation) {
|
47 | return;
|
48 | }
|
49 | let newMonth = startOfMonth(date);
|
50 |
|
51 | if (navStart && newMonth < startOfMonth(navStart)) {
|
52 | newMonth = startOfMonth(navStart);
|
53 | }
|
54 |
|
55 | if (navEnd && newMonth > startOfMonth(navEnd)) {
|
56 | newMonth = startOfMonth(navEnd);
|
57 | }
|
58 | setFirstMonth(newMonth);
|
59 | onMonthChange?.(newMonth);
|
60 | };
|
61 | const goToDay = (day) => {
|
62 |
|
63 | if (isDayInCalendar(day)) {
|
64 | return;
|
65 | }
|
66 | goToMonth(day.date);
|
67 | };
|
68 | const calendar = {
|
69 | months,
|
70 | weeks,
|
71 | days,
|
72 | navStart,
|
73 | navEnd,
|
74 | previousMonth,
|
75 | nextMonth,
|
76 | goToMonth,
|
77 | goToDay
|
78 | };
|
79 | return calendar;
|
80 | }
|
81 |
|
\ | No newline at end of file |