-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.ts
221 lines (209 loc) · 6.76 KB
/
helper.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
import dayjs, { Dayjs } from 'dayjs';
import calendar from 'dayjs/plugin/calendar';
import updateLocale from 'dayjs/plugin/updateLocale';
import localeData from 'dayjs/plugin/localeData';
import isoWeek from 'dayjs/plugin/isoWeek';
import duration from 'dayjs/plugin/duration';
import { MONTHS_NUMERIC, WEEKDAYS_NUMERIC } from './constants';
dayjs.extend(calendar);
dayjs.extend(updateLocale);
dayjs.extend(localeData);
dayjs.extend(isoWeek);
dayjs.extend(duration);
type Options = {
/**
* If `true` - renders previous dates(before today) as `null`
*
* @type {boolean}
*/
disableBeforeToday?: boolean;
/**
* Date to view
* @default
* dayjs()
*
* @type {Dayjs}
*/
date?: Dayjs;
locale?: string;
}
type WeekdayOptions = {
/**
* Week day format to display:
* @example
* format: 'short' // Thu. Equals Thursday
* format: 'narrow'// T Equals Thursday
* format: 'long'// Thursday
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
* @default
* 'short'
*/
format?: "short" | "long" | "narrow";
/**
* Week day format to display:
* @example
* format: 'short' // Aug. Equals August
* format: 'long'// August
* @default
* '2-digit'
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
*/
dayFormat?: "numeric" | "2-digit",
/**
* Wrap each 7 days(Week) to chunks
* @default
* false
* @example
* [
* [1,2,3,4,5,6,7],
* [8,9,10,11,12,13],
* ...etc
* ]
*
* @type {boolean}
*/
chunks?: boolean;
};
type MonthOptions = {
/**
* Week day format to display:
* @example
* format: 'short' // Aug. Equals August
* format: 'long'// August
* @default
* 'short'
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
*/
format?: "numeric" | "2-digit" | "long" | "short" | "narrow";
/**
* Split months to sub-arrays(grids).
*
* @default
* 1
* @example
* helper.Months({chunks: 1}).render() // [ Jan, Feb, Mar, Apr, etc]
* helper.Months({chunks: 2}).render() // [ [Jan, Feb], [Mar, Apr], etc]
* helper.Months({chunks: 3}).render() // [ [Jan, Feb, Mar], [Apr, May, Jun], etc]
* helper.Months({chunks: 4}).render() // [ [Jan, Feb, Mar, Apr], [May, Jun, July], etc]
* helper.Months({chunks: 12}).render() // [ [Jan], [Feb], [Mar], [Apr], etc]
* helper.Months({chunks: 'season'}).render() // [
* // [Dec, Jan, Feb], // winter = 0
* // [Mar, Apr, May], // spring = 1
* // [June, July, August] // summer = 2
* // [Sept, Oct, Nov] // autumn = 3
* // ]
*
*/
chunks?: 1 | 2 | 3 | 4 | 6 | 12 | 'season'
}
export function Helper(options?: Options) {
const viewedDate = (options?.date ?? dayjs()).set('hour', 1).set('second', 1);
const today = dayjs().set('hour', 1).set('second', 1);
function Month(monthOptions?: MonthOptions) {
const isCurrentYear = viewedDate.year() === today.year();
const startedYear = viewedDate.startOf('year');
const intl = new Intl.DateTimeFormat(options?.locale ?? 'en-US', { month: monthOptions?.format ?? 'short' })
const chunkSize = monthOptions?.chunks ?? 1;
const isDisabled = (index: number): boolean => {
return (
!!options?.disableBeforeToday &&
(viewedDate.year() < today.year() ||
(isCurrentYear && index < today.month()))
)
}
const render = () => {
const monthsArray = MONTHS_NUMERIC.map((month, index) => {
if (isDisabled(index)) return null;
return intl.format(startedYear.set('month', month).set('date', 1).toDate())
});
if (chunkSize === 1) {
return monthsArray;
}
if (chunkSize === 'season') {
const december = monthsArray.at(-1);
const monthsWithoutDec = monthsArray.slice(0, -1);
const seasons = [december, ...monthsWithoutDec]
return chunks(seasons, 3);
}
else {
return chunks(monthsArray, chunkSize);
}
}
return { render }
}
function Weekdays(weekdayOptions?: WeekdayOptions) {
const startedMonth = viewedDate.startOf('month');
const endedMonth = viewedDate.endOf('month');
const startingDay = (startedMonth.day() + 6) % 7;
const endingDay = (7 - (endedMonth.day()));
const today = dayjs().startOf('day');
const weekdayIntl = Intl.DateTimeFormat(options?.locale ?? 'en-US', { weekday: weekdayOptions?.format ?? 'short' });
const dayFormat = weekdayOptions?.dayFormat ?? 'numeric';
const generateDays = (): string[] => {
return Array.from(
new Array(viewedDate.daysInMonth()),
(_, index) => {
const result = index + 1;
if (dayFormat === '2-digit') {
return result.toFixed(2)
}
if (dayFormat === 'numeric') {
return String(result);
} else {
throw new Error(`invalid day format "${dayFormat}". Available formats: "numeric" and "2-digit"`)
}
}
)
}
const isDisabled = (day: number): boolean => {
return (
(!!options?.disableBeforeToday &&
(viewedDate.year() < today.year() ||
(viewedDate.year() === today.year() &&
(viewedDate.month() < today.month() ||
(viewedDate.month() === today.month() &&
day < today.date())))))
)
}
const render = (): (string | null[][]) | (string | null[][][]) => {
const dayOfWeek = startedMonth.startOf('week');
const weekdays = WEEKDAYS_NUMERIC.map(v => {
return weekdayIntl.format(dayOfWeek.set('day', v + 1).toDate())
});
const emptyStart = Array(startingDay).fill(null);
let emptyEnd = Array(endingDay).fill(null)
const days = generateDays().map(day => {
if (isDisabled(+day)) return null;
return day;
});
const totalDays = [...emptyStart, ...days, ...emptyEnd];
return [
weekdays,
weekdayOptions?.chunks ? chunks(totalDays, 7) : totalDays,
];
};
return { render }
}
return {
Weekdays,
Month,
};
}
/**
* Chunkify array.
* @see https://stackoverflow.com/a/37826698/6515842
* @param {unknown[]} array incoming array
* @param {number} [size=0] chunk size
*/
export function chunks<T>(array: T[], size = 7): T[][] {
const result = array.reduce((resultArray: T[][], item, index) => {
const chunkIndex = Math.floor(index / size);
if (!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []// start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, []);
return result;
}
// console.log(Helper({ disableBeforeToday: true, date: dayjs(Date.UTC(2022, 7, 1, 1, 1)) }).Weekdays({ chunks: false }).render());