UNPKG

1.84 kBJavaScriptView Raw
1import moment from 'moment';
2import toISOMonthString from './toISOMonthString';
3
4export default function getVisibleDays(
5 month,
6 numberOfMonths,
7 enableOutsideDays,
8 withoutTransitionMonths,
9) {
10 if (!moment.isMoment(month)) return {};
11
12 const visibleDaysByMonth = {};
13 let currentMonth = withoutTransitionMonths ? month.clone() : month.clone().subtract(1, 'month');
14 for (let i = 0; i < (withoutTransitionMonths ? numberOfMonths : numberOfMonths + 2); i += 1) {
15 const visibleDays = [];
16
17 // set utc offset to get correct dates in future (when timezone changes)
18 const baseDate = currentMonth.clone();
19 const firstOfMonth = baseDate.clone().startOf('month').hour(12);
20 const lastOfMonth = baseDate.clone().endOf('month').hour(12);
21
22 const currentDay = firstOfMonth.clone();
23
24 // days belonging to the previous month
25 if (enableOutsideDays) {
26 for (let j = 0; j < currentDay.weekday(); j += 1) {
27 const prevDay = currentDay.clone().subtract(j + 1, 'day');
28 visibleDays.unshift(prevDay);
29 }
30 }
31
32 while (currentDay < lastOfMonth) {
33 visibleDays.push(currentDay.clone());
34 currentDay.add(1, 'day');
35 }
36
37 if (enableOutsideDays) {
38 // weekday() returns the index of the day of the week according to the locale
39 // this means if the week starts on Monday, weekday() will return 0 for a Monday date, not 1
40 if (currentDay.weekday() !== 0) {
41 // days belonging to the next month
42 for (let k = currentDay.weekday(), count = 0; k < 7; k += 1, count += 1) {
43 const nextDay = currentDay.clone().add(count, 'day');
44 visibleDays.push(nextDay);
45 }
46 }
47 }
48
49 visibleDaysByMonth[toISOMonthString(currentMonth)] = visibleDays;
50 currentMonth = currentMonth.clone().add(1, 'month');
51 }
52
53 return visibleDaysByMonth;
54}