-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (47 loc) · 1.24 KB
/
index.js
File metadata and controls
53 lines (47 loc) · 1.24 KB
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
import { useEffect, useState } from 'react'
import {
addDays,
startOfWeek,
differenceInCalendarWeeks,
endOfMonth,
startOfMonth,
} from 'date-fns'
export const generateMatrix = (
year,
month,
formatDay,
weekStartsOn,
daysInWeek
) => {
let date = new Date(year, month)
let startDay = startOfMonth(date)
let lastDay = endOfMonth(date)
const startDate = startOfWeek(startDay, { weekStartsOn })
const rows =
differenceInCalendarWeeks(lastDay, startDay, { weekStartsOn }) + 1
const cols = daysInWeek
const totalDays = rows * cols
return Array.from({ length: totalDays })
.map((_, index) => addDays(startDate, index))
.map(day => (typeof formatDay === 'function' ? formatDay(day) : day))
.reduce((matrix, current, index, days) => {
return index % cols === 0
? [...matrix, days.slice(index, index + cols)]
: matrix
}, [])
}
export const useCalendarMatrix = (
year,
month,
formatDay = day => day,
weekStartsOn = 1,
daysInWeek = 7
) => {
let [matrix, setMatrix] = useState(
generateMatrix(year, month, formatDay, weekStartsOn, daysInWeek)
)
useEffect(() => {
setMatrix(generateMatrix(year, month, formatDay, weekStartsOn, daysInWeek))
}, [year, month])
return [matrix]
}