-
Notifications
You must be signed in to change notification settings - Fork 16
/
useCalendar.ts
360 lines (325 loc) Β· 9.5 KB
/
useCalendar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import { useMemo } from "react";
import type { DayState } from "@/components/CalendarItemDay";
import {
addDays,
endOfMonth,
fromDateId,
isWeekend,
startOfMonth,
startOfWeek,
subDays,
toDateId,
} from "@/helpers/dates";
import { range } from "@/helpers/numbers";
const getNumberOfEmptyCellsAtStart = (
month: Date,
firstDayOfWeek: "sunday" | "monday"
) => {
const startOfMonthDay = month.getDay();
if (firstDayOfWeek === "sunday") {
return startOfMonthDay;
}
return startOfMonthDay === 0 ? 6 : startOfMonthDay - 1;
};
/** All fields that affects the day's state. */
interface CalendarDayStateFields {
/** Is this day disabled? */
isDisabled: boolean;
/** Is this the current day? */
isToday: boolean;
/** Is this the start of a range? */
isStartOfRange: boolean;
/** Is this the end of a range? */
isEndOfRange: boolean;
/** The state of the day */
state: DayState;
/** Is the range valid (has both start and end dates set)? */
isRangeValid: boolean;
}
/**
* The type of each day in the calendar. Has a few pre-computed properties to
* help increase re-rendering performance.
*/
export type CalendarDayMetadata = {
date: Date;
/** The day displayed in the desired format from `calendarDayFormat` */
displayLabel: string;
/** Does this day belong to a different month? */
isDifferentMonth: boolean;
/** Is this the last day of the month? */
isEndOfMonth: boolean;
/** Is this the last day of the week? */
isEndOfWeek: boolean;
/** Is this the first day of the month? */
isStartOfMonth: boolean;
/** Is this the first day of the week? */
isStartOfWeek: boolean;
/** Is this day part of the weekend? */
isWeekend: boolean;
/** The ID of this date is the `YYYY-MM-DD` representation */
id: string;
} & CalendarDayStateFields;
/**
* An active date range to highlight in the calendar.
*/
export interface CalendarActiveDateRange {
startId?: string;
endId?: string;
}
export interface UseCalendarParams {
/**
* The calendar's month. It can be any date within the month, since it gets
* normalized to the first day of the month.
*
* **Tip**: To convert to date ID, use `toDateId(date)`.
*/
calendarMonthId: string;
/**
* The minimum date allowed to be selected (inclusive). Dates earlier than
* this will be disabled.
*
* **Tip**: To convert to date ID, use `toDateId(date)`.
*/
calendarMinDateId?: string;
/**
* The maximum date allowed to be selected (inclusive). Dates later than this
* will be disabled.
*
* **Tip**: To convert to date ID, use `toDateId(date)`.
*/
calendarMaxDateId?: string;
/**
* A custom function to override the default month format ("January 2022").
*/
getCalendarMonthFormat?: (date: Date) => string;
/**
* A custom function to override the default month format ("S", "M", "T").
*/
getCalendarWeekDayFormat?: (date: Date) => string;
/**
* A custom function to override the default day format ("1", "9", "17").
*/
getCalendarDayFormat?: (date: Date) => string;
/**
* The day of the week to start the calendar with.
* @defaultValue "sunday"
*/
calendarFirstDayOfWeek?: "sunday" | "monday";
/**
* The active date ranges to highlight in the calendar.
*/
calendarActiveDateRanges?: CalendarActiveDateRange[];
/**
* The disabled date IDs. Dates in this list will be in the `disabled` state
* unless they are part of an active range.
*/
calendarDisabledDateIds?: string[];
}
type GetStateFields = Pick<
UseCalendarParams,
| "calendarActiveDateRanges"
| "calendarMinDateId"
| "calendarMaxDateId"
| "calendarDisabledDateIds"
> & {
todayId?: string;
id: string;
};
/**
* Computes the state fields for a given date.
*/
export const getStateFields = ({
todayId,
id,
calendarActiveDateRanges,
calendarMinDateId,
calendarMaxDateId,
calendarDisabledDateIds,
}: GetStateFields): CalendarDayStateFields => {
const activeRange = calendarActiveDateRanges?.find(({ startId, endId }) => {
// Regular range
if (startId && endId) {
return id >= startId && id <= endId;
} else if (startId) {
return id === startId;
} else if (endId) {
return id === endId;
}
return false;
});
const isRangeValid =
activeRange?.startId !== undefined && activeRange.endId !== undefined;
const isDisabled =
(calendarDisabledDateIds?.includes(id) ||
(calendarMinDateId && id < calendarMinDateId) ||
(calendarMaxDateId && id > calendarMaxDateId)) === true;
const isToday = todayId === id;
const state: DayState = activeRange
? ("active" as const)
: isDisabled
? "disabled"
: isToday
? "today"
: "idle";
return {
isStartOfRange: id === activeRange?.startId,
isEndOfRange: id === activeRange?.endId,
isRangeValid,
state,
isDisabled,
isToday,
};
};
const monthIdToLabel = {
0: "January",
1: "February",
2: "March",
3: "April",
4: "May",
5: "June",
6: "July",
7: "August",
8: "September",
9: "October",
10: "November",
11: "December",
};
const weekDayIdToLabel = {
0: "S",
1: "M",
2: "T",
3: "W",
4: "T",
5: "F",
6: "S",
};
const getBaseCalendarMonthFormat = (date: Date) => {
const year = date.getFullYear();
const month =
monthIdToLabel[date.getMonth() as unknown as keyof typeof monthIdToLabel];
return `${month} ${year}`;
};
const getBaseCalendarWeekDayFormat = (date: Date) => {
return weekDayIdToLabel[
date.getDay() as unknown as keyof typeof weekDayIdToLabel
];
};
const getBaseCalendarDayFormat = (date: Date) => {
return `${date.getDate()}`;
};
/**
* Builds a calendar based on the given parameters.
*/
export const buildCalendar = (params: UseCalendarParams) => {
const {
calendarMonthId: monthId,
calendarFirstDayOfWeek = "sunday",
getCalendarMonthFormat = getBaseCalendarMonthFormat,
getCalendarWeekDayFormat = getBaseCalendarWeekDayFormat,
getCalendarDayFormat = getBaseCalendarDayFormat,
} = params;
const month = fromDateId(monthId);
const monthStart = startOfMonth(month);
const monthStartId = toDateId(monthStart);
const monthEnd = endOfMonth(month);
const monthEndId = toDateId(monthEnd);
const emptyDaysAtStart = getNumberOfEmptyCellsAtStart(
monthStart,
calendarFirstDayOfWeek
);
const startOfWeekIndex = calendarFirstDayOfWeek === "sunday" ? 0 : 1;
const endOfWeekIndex = calendarFirstDayOfWeek === "sunday" ? 6 : 0;
const todayId = toDateId(new Date());
// The first day to iterate is the first day of the month minus the empty days at the start
let dayToIterate = subDays(monthStart, emptyDaysAtStart);
const weeksList: CalendarDayMetadata[][] = [
[
...range(1, emptyDaysAtStart).map((): CalendarDayMetadata => {
const id = toDateId(dayToIterate);
const dayShape: CalendarDayMetadata = {
date: dayToIterate,
displayLabel: getCalendarDayFormat(dayToIterate),
id,
isDifferentMonth: true,
isEndOfMonth: false,
isEndOfWeek: dayToIterate.getDay() === endOfWeekIndex,
isStartOfMonth: false,
isStartOfWeek: dayToIterate.getDay() === startOfWeekIndex,
isWeekend: isWeekend(dayToIterate),
...getStateFields({
...params,
todayId,
id,
}),
};
dayToIterate = addDays(dayToIterate, 1);
return dayShape;
}),
],
];
// By this point, we're back at the start of the month
while (dayToIterate.getMonth() === monthStart.getMonth()) {
const currentWeek = weeksList[weeksList.length - 1];
if (currentWeek.length === 7) {
weeksList.push([]);
}
const id = toDateId(dayToIterate);
weeksList[weeksList.length - 1].push({
date: dayToIterate,
displayLabel: getCalendarDayFormat(dayToIterate),
id,
isDifferentMonth: false,
isEndOfMonth: id === monthEndId,
isEndOfWeek: dayToIterate.getDay() === endOfWeekIndex,
isStartOfMonth: id === monthStartId,
isStartOfWeek: dayToIterate.getDay() === startOfWeekIndex,
isWeekend: isWeekend(dayToIterate),
...getStateFields({
...params,
todayId,
id,
}),
});
dayToIterate = addDays(dayToIterate, 1);
}
// Once all the days of the month have been added, we need to add the empty days at the end
const lastWeek = weeksList[weeksList.length - 1];
const emptyDaysAtEnd = 7 - lastWeek.length;
lastWeek.push(
...range(1, emptyDaysAtEnd).map(() => {
const id = toDateId(dayToIterate);
const dayShape: CalendarDayMetadata = {
date: dayToIterate,
displayLabel: getCalendarDayFormat(dayToIterate),
id,
isDifferentMonth: true,
isEndOfMonth: false,
isEndOfWeek: dayToIterate.getDay() === endOfWeekIndex,
isStartOfMonth: false,
isStartOfWeek: dayToIterate.getDay() === startOfWeekIndex,
isWeekend: isWeekend(dayToIterate),
...getStateFields({
...params,
todayId,
id,
}),
};
dayToIterate = addDays(dayToIterate, 1);
return dayShape;
})
);
const startOfWeekDate = startOfWeek(month, calendarFirstDayOfWeek);
const weekDaysList = range(1, 7).map((i) =>
getCalendarWeekDayFormat(addDays(startOfWeekDate, i - 1))
);
return {
weeksList,
calendarRowMonth: getCalendarMonthFormat(month),
weekDaysList,
};
};
/**
* Returns a memoized calendar based on the given parameters.
*/
export const useCalendar = (params: UseCalendarParams) =>
useMemo(() => buildCalendar(params), [params]);