1 | import moment from 'moment';
|
2 |
|
3 | import { WEEKDAYS } from '../constants';
|
4 |
|
5 | export default function getCalendarMonthWeeks(
|
6 | month,
|
7 | enableOutsideDays,
|
8 | firstDayOfWeek = moment.localeData().firstDayOfWeek(),
|
9 | ) {
|
10 | if (!moment.isMoment(month) || !month.isValid()) {
|
11 | throw new TypeError('`month` must be a valid moment object');
|
12 | }
|
13 | if (WEEKDAYS.indexOf(firstDayOfWeek) === -1) {
|
14 | throw new TypeError('`firstDayOfWeek` must be an integer between 0 and 6');
|
15 | }
|
16 |
|
17 |
|
18 | const firstOfMonth = month.clone().startOf('month').hour(12);
|
19 | const lastOfMonth = month.clone().endOf('month').hour(12);
|
20 |
|
21 |
|
22 |
|
23 | const prevDays = ((firstOfMonth.day() + 7 - firstDayOfWeek) % 7);
|
24 | const nextDays = ((firstDayOfWeek + 6 - lastOfMonth.day()) % 7);
|
25 | const firstDay = firstOfMonth.clone().subtract(prevDays, 'day');
|
26 | const lastDay = lastOfMonth.clone().add(nextDays, 'day');
|
27 |
|
28 | const totalDays = lastDay.diff(firstDay, 'days') + 1;
|
29 |
|
30 | const currentDay = firstDay.clone();
|
31 | const weeksInMonth = [];
|
32 |
|
33 | for (let i = 0; i < totalDays; i += 1) {
|
34 | if (i % 7 === 0) {
|
35 | weeksInMonth.push([]);
|
36 | }
|
37 |
|
38 | let day = null;
|
39 | if ((i >= prevDays && i < (totalDays - nextDays)) || enableOutsideDays) {
|
40 | day = currentDay.clone();
|
41 | }
|
42 |
|
43 | weeksInMonth[weeksInMonth.length - 1].push(day);
|
44 |
|
45 | currentDay.add(1, 'day');
|
46 | }
|
47 |
|
48 | return weeksInMonth;
|
49 | }
|