@svar-ui/gantt-data-provider 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3248 @@
1
+ // src/helpers.ts
2
+ (/* @__PURE__ */ new Date()).valueOf();
3
+ function isTempID(v) {
4
+ return typeof v === "string" && v.length === 20 && parseInt(v.substr(7)) > 1e12;
5
+ }
6
+
7
+ // src/EventBus.ts
8
+ var EventBus = class {
9
+ constructor() {
10
+ this._nextHandler = null;
11
+ this._handlers = {};
12
+ this._tag = /* @__PURE__ */ new WeakMap();
13
+ this.exec = this.exec.bind(this);
14
+ }
15
+ on(name, handler, config) {
16
+ let prev = this._handlers[name];
17
+ if (!prev) {
18
+ prev = this._handlers[name] = [handler];
19
+ } else {
20
+ if (config && config.intercept) prev.unshift(handler);
21
+ else prev.push(handler);
22
+ }
23
+ if (config && config.tag) this._tag.set(handler, config.tag);
24
+ }
25
+ intercept(name, handler, config) {
26
+ this.on(name, handler, { ...config, intercept: true });
27
+ }
28
+ detach(tag) {
29
+ for (const key in this._handlers) {
30
+ const stack = this._handlers[key];
31
+ for (let i = stack.length - 1; i >= 0; i--) {
32
+ if (this._tag.get(stack[i]) === tag) {
33
+ stack.splice(i, 1);
34
+ }
35
+ }
36
+ }
37
+ }
38
+ async exec(name, ev) {
39
+ const stack = this._handlers[name];
40
+ if (stack) {
41
+ for (let i = 0; i < stack.length; i++) {
42
+ const res = stack[i](ev);
43
+ if (res === false) return;
44
+ if (res && res.then) {
45
+ const res2 = await res;
46
+ if (res2 === false) return;
47
+ }
48
+ }
49
+ }
50
+ if (this._nextHandler) await this._nextHandler.exec(name, ev);
51
+ return ev;
52
+ }
53
+ setNext(next) {
54
+ return this._nextHandler = next;
55
+ }
56
+ };
57
+
58
+ // src/RestDataProvider.ts
59
+ var cantSendYet = Symbol();
60
+ var SYNC = 0;
61
+ var NOTSENT = 1;
62
+ var SENDING = 2;
63
+ var ActionQueue = class {
64
+ constructor() {
65
+ this.reset(true);
66
+ }
67
+ reset(ids = false) {
68
+ this._awaitAddingQueue = [];
69
+ this._queue = {};
70
+ this._waitPull = {};
71
+ this._status = [];
72
+ if (ids) {
73
+ this._idPool = {};
74
+ this._backId = [];
75
+ }
76
+ }
77
+ resolve(id, type) {
78
+ const col = this._backId[type];
79
+ if (typeof col === "undefined") return id;
80
+ const tID = col[id];
81
+ return typeof tID === "undefined" ? id : tID;
82
+ }
83
+ getSync() {
84
+ const t = this._awaitAddingQueue;
85
+ if (!t.length) return SYNC;
86
+ for (let i = 0; i < t.length; i++) {
87
+ if (!t[i].sent) return NOTSENT;
88
+ }
89
+ return SENDING;
90
+ }
91
+ waitSync() {
92
+ return new Promise((resolve) => {
93
+ if (this.getSync() === SYNC) resolve();
94
+ else this._status.push(resolve);
95
+ });
96
+ }
97
+ getId(id) {
98
+ return this._idPool[id] || (isTempID(id) ? null : id);
99
+ }
100
+ waitId(id) {
101
+ return new Promise((resolve) => {
102
+ const sid = this.getId(id);
103
+ if (sid !== null) resolve(sid);
104
+ const warr = this._waitPull[id] || [];
105
+ warr.push(resolve);
106
+ this._waitPull[id] = warr;
107
+ });
108
+ }
109
+ add(action, data, proc) {
110
+ return new Promise((resolve, reject) => {
111
+ proc = { ...proc, resolve, reject };
112
+ if (proc.debounce) {
113
+ const qid = `${action}"/"${data.id}`;
114
+ const item = this._queue[qid];
115
+ if (item) {
116
+ proc.resolve = (v) => {
117
+ item.resolve(v);
118
+ resolve(v);
119
+ };
120
+ proc.reject = (e) => {
121
+ item.reject(e);
122
+ reject();
123
+ };
124
+ clearTimeout(item.timer);
125
+ }
126
+ this._queue[qid] = proc;
127
+ proc.timer = setTimeout(() => {
128
+ this.tryExec(action, data, proc);
129
+ }, proc.debounce);
130
+ return;
131
+ }
132
+ this.tryExec(action, data, proc);
133
+ });
134
+ }
135
+ tryExec(action, data, proc, finish) {
136
+ const ready = this.exec(action, data, proc, finish);
137
+ if (ready === null) {
138
+ if (!finish) this._awaitAddingQueue.push({ action, data, proc });
139
+ return false;
140
+ }
141
+ ready.then(
142
+ (res) => {
143
+ const check = res && res.id && res.id != data.id && isTempID(data.id);
144
+ if (check) {
145
+ this._idPool[data.id] = res.id;
146
+ if (this._waitPull[data.id]) {
147
+ this._waitPull[data.id].forEach((v) => v(res.id));
148
+ delete this._waitPull[data.id];
149
+ }
150
+ if (proc.kind) {
151
+ let t = this._backId[proc.kind];
152
+ if (!t) t = this._backId[proc.kind] = {};
153
+ t[res.id] = data.id;
154
+ }
155
+ }
156
+ data.response = res;
157
+ proc.resolve(true);
158
+ if (finish) finish();
159
+ if (check) this.execQueue();
160
+ },
161
+ (e) => {
162
+ if (finish) finish();
163
+ proc.reject(e);
164
+ }
165
+ );
166
+ return true;
167
+ }
168
+ exec(action, data, proc, finish) {
169
+ const correctData = this.correctID(data, proc.ignoreID ? data.id : null);
170
+ if (correctData === cantSendYet) {
171
+ return null;
172
+ }
173
+ let res;
174
+ try {
175
+ res = proc.handler(correctData, action, data);
176
+ } catch (e) {
177
+ finish();
178
+ proc.reject(e);
179
+ }
180
+ return res;
181
+ }
182
+ correctID(obj, ignore) {
183
+ let copy = null;
184
+ for (const key in obj) {
185
+ const test = obj[key];
186
+ if (typeof test === "object") {
187
+ const after = this.correctID(test, ignore);
188
+ if (after !== test) {
189
+ if (after === cantSendYet) {
190
+ return cantSendYet;
191
+ }
192
+ if (copy === null) {
193
+ copy = { ...obj };
194
+ }
195
+ copy[key] = after;
196
+ }
197
+ } else if (isTempID(test)) {
198
+ const hasRealID = this._idPool[test];
199
+ if (hasRealID) {
200
+ if (copy === null) {
201
+ copy = { ...obj };
202
+ }
203
+ copy[key] = hasRealID;
204
+ } else if (!ignore) {
205
+ return cantSendYet;
206
+ }
207
+ }
208
+ }
209
+ return copy || obj;
210
+ }
211
+ execQueue() {
212
+ this._awaitAddingQueue.forEach((a) => {
213
+ if (!a.sent) {
214
+ const finish = () => this._finishQueue(a);
215
+ if (this.tryExec(a.action, a.data, a.proc, finish)) a.sent = true;
216
+ }
217
+ });
218
+ }
219
+ _finishQueue(a) {
220
+ this._awaitAddingQueue = this._awaitAddingQueue.filter((v) => v !== a);
221
+ if (!this._awaitAddingQueue.length && this._status.length) {
222
+ const temp = [...this._status];
223
+ this._status = [];
224
+ temp.forEach((resolve) => resolve());
225
+ }
226
+ }
227
+ };
228
+
229
+ // src/RestDataProvider.ts
230
+ var Rest = class extends EventBus {
231
+ constructor(url, config) {
232
+ super();
233
+ this._customHeaders = {};
234
+ this._batchQueue = [];
235
+ this._batchTimeout = null;
236
+ this._url = url;
237
+ this._batchUrl = config?.batchURL;
238
+ this._queue = new ActionQueue();
239
+ const handlers = this.getHandlers();
240
+ for (const x in handlers) {
241
+ this.on(x, (ev) => {
242
+ if (!ev.skipProvider)
243
+ return this._queue.add(x, ev, handlers[x]);
244
+ });
245
+ }
246
+ }
247
+ getHandlers() {
248
+ return {};
249
+ }
250
+ setHeaders(headers) {
251
+ this._customHeaders = headers;
252
+ }
253
+ getQueue() {
254
+ return this._queue;
255
+ }
256
+ async send(url, method, data, customHeaders = {}) {
257
+ if (this._batchUrl && method !== "GET") {
258
+ return this.sendBatchRequest(url, method, data, customHeaders);
259
+ } else {
260
+ return this.sendRequest(url, method, data, customHeaders);
261
+ }
262
+ }
263
+ async sendBatchRequest(url, method, data, customHeaders) {
264
+ return new Promise((resolve) => {
265
+ this._batchQueue.push({
266
+ url,
267
+ method,
268
+ data,
269
+ resolve
270
+ });
271
+ if (this._batchTimeout) {
272
+ clearTimeout(this._batchTimeout);
273
+ }
274
+ this._batchTimeout = setTimeout(async () => {
275
+ const currentQueue = [...this._batchQueue];
276
+ this._batchQueue = [];
277
+ if (currentQueue.length > 1) {
278
+ const batchData = currentQueue.map((req) => ({
279
+ url: req.url,
280
+ method: req.method,
281
+ data: {
282
+ ...req.data
283
+ }
284
+ }));
285
+ const results = await this.sendRequest(
286
+ this._batchUrl,
287
+ "POST",
288
+ batchData
289
+ );
290
+ currentQueue.forEach((q, i) => q.resolve(results[i]));
291
+ } else {
292
+ const result = await this.sendRequest(
293
+ url,
294
+ method,
295
+ data,
296
+ customHeaders
297
+ );
298
+ resolve(result);
299
+ }
300
+ }, 10);
301
+ });
302
+ }
303
+ toPayload(obj) {
304
+ return JSON.stringify(obj);
305
+ }
306
+ async sendRequest(url, method, data, customHeaders = {}) {
307
+ const headers = {
308
+ "Content-Type": "application/json",
309
+ ...customHeaders,
310
+ ...this._customHeaders
311
+ };
312
+ const req = {
313
+ method,
314
+ headers
315
+ };
316
+ if (data) {
317
+ req.body = typeof data === "object" ? this.toPayload(data) : data;
318
+ }
319
+ const slash = this._url.charAt(-1) === "/" || url[0] === "/" ? "" : "/";
320
+ return fetch(`${this._url}${slash}${url || ""}`, req).then(
321
+ (res) => res.json()
322
+ );
323
+ }
324
+ };
325
+
326
+ /**
327
+ * @name toDate
328
+ * @category Common Helpers
329
+ * @summary Convert the given argument to an instance of Date.
330
+ *
331
+ * @description
332
+ * Convert the given argument to an instance of Date.
333
+ *
334
+ * If the argument is an instance of Date, the function returns its clone.
335
+ *
336
+ * If the argument is a number, it is treated as a timestamp.
337
+ *
338
+ * If the argument is none of the above, the function returns Invalid Date.
339
+ *
340
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
341
+ *
342
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
343
+ *
344
+ * @param argument - The value to convert
345
+ *
346
+ * @returns The parsed date in the local time zone
347
+ *
348
+ * @example
349
+ * // Clone the date:
350
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
351
+ * //=> Tue Feb 11 2014 11:30:30
352
+ *
353
+ * @example
354
+ * // Convert the timestamp to date:
355
+ * const result = toDate(1392098430000)
356
+ * //=> Tue Feb 11 2014 11:30:30
357
+ */
358
+ function toDate(argument) {
359
+ const argStr = Object.prototype.toString.call(argument);
360
+
361
+ // Clone the date
362
+ if (
363
+ argument instanceof Date ||
364
+ (typeof argument === "object" && argStr === "[object Date]")
365
+ ) {
366
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
367
+ return new argument.constructor(+argument);
368
+ } else if (
369
+ typeof argument === "number" ||
370
+ argStr === "[object Number]" ||
371
+ typeof argument === "string" ||
372
+ argStr === "[object String]"
373
+ ) {
374
+ // TODO: Can we get rid of as?
375
+ return new Date(argument);
376
+ } else {
377
+ // TODO: Can we get rid of as?
378
+ return new Date(NaN);
379
+ }
380
+ }
381
+
382
+ /**
383
+ * @name constructFrom
384
+ * @category Generic Helpers
385
+ * @summary Constructs a date using the reference date and the value
386
+ *
387
+ * @description
388
+ * The function constructs a new date using the constructor from the reference
389
+ * date and the given value. It helps to build generic functions that accept
390
+ * date extensions.
391
+ *
392
+ * It defaults to `Date` if the passed reference date is a number or a string.
393
+ *
394
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
395
+ *
396
+ * @param date - The reference date to take constructor from
397
+ * @param value - The value to create the date
398
+ *
399
+ * @returns Date initialized using the given date and value
400
+ *
401
+ * @example
402
+ * import { constructFrom } from 'date-fns'
403
+ *
404
+ * // A function that clones a date preserving the original type
405
+ * function cloneDate<DateType extends Date(date: DateType): DateType {
406
+ * return constructFrom(
407
+ * date, // Use contrustor from the given date
408
+ * date.getTime() // Use the date value to create a new date
409
+ * )
410
+ * }
411
+ */
412
+ function constructFrom(date, value) {
413
+ if (date instanceof Date) {
414
+ return new date.constructor(value);
415
+ } else {
416
+ return new Date(value);
417
+ }
418
+ }
419
+
420
+ /**
421
+ * @module constants
422
+ * @summary Useful constants
423
+ * @description
424
+ * Collection of useful date constants.
425
+ *
426
+ * The constants could be imported from `date-fns/constants`:
427
+ *
428
+ * ```ts
429
+ * import { maxTime, minTime } from "./constants/date-fns/constants";
430
+ *
431
+ * function isAllowedTime(time) {
432
+ * return time <= maxTime && time >= minTime;
433
+ * }
434
+ * ```
435
+ */
436
+
437
+
438
+ /**
439
+ * @constant
440
+ * @name millisecondsInWeek
441
+ * @summary Milliseconds in 1 week.
442
+ */
443
+ const millisecondsInWeek = 604800000;
444
+
445
+ /**
446
+ * @constant
447
+ * @name millisecondsInDay
448
+ * @summary Milliseconds in 1 day.
449
+ */
450
+ const millisecondsInDay = 86400000;
451
+
452
+ let defaultOptions = {};
453
+
454
+ function getDefaultOptions() {
455
+ return defaultOptions;
456
+ }
457
+
458
+ /**
459
+ * The {@link startOfWeek} function options.
460
+ */
461
+
462
+ /**
463
+ * @name startOfWeek
464
+ * @category Week Helpers
465
+ * @summary Return the start of a week for the given date.
466
+ *
467
+ * @description
468
+ * Return the start of a week for the given date.
469
+ * The result will be in the local timezone.
470
+ *
471
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
472
+ *
473
+ * @param date - The original date
474
+ * @param options - An object with options
475
+ *
476
+ * @returns The start of a week
477
+ *
478
+ * @example
479
+ * // The start of a week for 2 September 2014 11:55:00:
480
+ * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
481
+ * //=> Sun Aug 31 2014 00:00:00
482
+ *
483
+ * @example
484
+ * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
485
+ * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
486
+ * //=> Mon Sep 01 2014 00:00:00
487
+ */
488
+ function startOfWeek(date, options) {
489
+ const defaultOptions = getDefaultOptions();
490
+ const weekStartsOn =
491
+ options?.weekStartsOn ??
492
+ options?.locale?.options?.weekStartsOn ??
493
+ defaultOptions.weekStartsOn ??
494
+ defaultOptions.locale?.options?.weekStartsOn ??
495
+ 0;
496
+
497
+ const _date = toDate(date);
498
+ const day = _date.getDay();
499
+ const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
500
+
501
+ _date.setDate(_date.getDate() - diff);
502
+ _date.setHours(0, 0, 0, 0);
503
+ return _date;
504
+ }
505
+
506
+ /**
507
+ * @name startOfISOWeek
508
+ * @category ISO Week Helpers
509
+ * @summary Return the start of an ISO week for the given date.
510
+ *
511
+ * @description
512
+ * Return the start of an ISO week for the given date.
513
+ * The result will be in the local timezone.
514
+ *
515
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
516
+ *
517
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
518
+ *
519
+ * @param date - The original date
520
+ *
521
+ * @returns The start of an ISO week
522
+ *
523
+ * @example
524
+ * // The start of an ISO week for 2 September 2014 11:55:00:
525
+ * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
526
+ * //=> Mon Sep 01 2014 00:00:00
527
+ */
528
+ function startOfISOWeek(date) {
529
+ return startOfWeek(date, { weekStartsOn: 1 });
530
+ }
531
+
532
+ /**
533
+ * @name getISOWeekYear
534
+ * @category ISO Week-Numbering Year Helpers
535
+ * @summary Get the ISO week-numbering year of the given date.
536
+ *
537
+ * @description
538
+ * Get the ISO week-numbering year of the given date,
539
+ * which always starts 3 days before the year's first Thursday.
540
+ *
541
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
542
+ *
543
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
544
+ *
545
+ * @param date - The given date
546
+ *
547
+ * @returns The ISO week-numbering year
548
+ *
549
+ * @example
550
+ * // Which ISO-week numbering year is 2 January 2005?
551
+ * const result = getISOWeekYear(new Date(2005, 0, 2))
552
+ * //=> 2004
553
+ */
554
+ function getISOWeekYear(date) {
555
+ const _date = toDate(date);
556
+ const year = _date.getFullYear();
557
+
558
+ const fourthOfJanuaryOfNextYear = constructFrom(date, 0);
559
+ fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
560
+ fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
561
+ const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
562
+
563
+ const fourthOfJanuaryOfThisYear = constructFrom(date, 0);
564
+ fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
565
+ fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
566
+ const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
567
+
568
+ if (_date.getTime() >= startOfNextYear.getTime()) {
569
+ return year + 1;
570
+ } else if (_date.getTime() >= startOfThisYear.getTime()) {
571
+ return year;
572
+ } else {
573
+ return year - 1;
574
+ }
575
+ }
576
+
577
+ /**
578
+ * @name startOfDay
579
+ * @category Day Helpers
580
+ * @summary Return the start of a day for the given date.
581
+ *
582
+ * @description
583
+ * Return the start of a day for the given date.
584
+ * The result will be in the local timezone.
585
+ *
586
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
587
+ *
588
+ * @param date - The original date
589
+ *
590
+ * @returns The start of a day
591
+ *
592
+ * @example
593
+ * // The start of a day for 2 September 2014 11:55:00:
594
+ * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
595
+ * //=> Tue Sep 02 2014 00:00:00
596
+ */
597
+ function startOfDay(date) {
598
+ const _date = toDate(date);
599
+ _date.setHours(0, 0, 0, 0);
600
+ return _date;
601
+ }
602
+
603
+ /**
604
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
605
+ * They usually appear for dates that denote time before the timezones were introduced
606
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
607
+ * and GMT+01:00:00 after that date)
608
+ *
609
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
610
+ * which would lead to incorrect calculations.
611
+ *
612
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
613
+ */
614
+ function getTimezoneOffsetInMilliseconds(date) {
615
+ const _date = toDate(date);
616
+ const utcDate = new Date(
617
+ Date.UTC(
618
+ _date.getFullYear(),
619
+ _date.getMonth(),
620
+ _date.getDate(),
621
+ _date.getHours(),
622
+ _date.getMinutes(),
623
+ _date.getSeconds(),
624
+ _date.getMilliseconds(),
625
+ ),
626
+ );
627
+ utcDate.setUTCFullYear(_date.getFullYear());
628
+ return +date - +utcDate;
629
+ }
630
+
631
+ /**
632
+ * @name differenceInCalendarDays
633
+ * @category Day Helpers
634
+ * @summary Get the number of calendar days between the given dates.
635
+ *
636
+ * @description
637
+ * Get the number of calendar days between the given dates. This means that the times are removed
638
+ * from the dates and then the difference in days is calculated.
639
+ *
640
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
641
+ *
642
+ * @param dateLeft - The later date
643
+ * @param dateRight - The earlier date
644
+ *
645
+ * @returns The number of calendar days
646
+ *
647
+ * @example
648
+ * // How many calendar days are between
649
+ * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
650
+ * const result = differenceInCalendarDays(
651
+ * new Date(2012, 6, 2, 0, 0),
652
+ * new Date(2011, 6, 2, 23, 0)
653
+ * )
654
+ * //=> 366
655
+ * // How many calendar days are between
656
+ * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
657
+ * const result = differenceInCalendarDays(
658
+ * new Date(2011, 6, 3, 0, 1),
659
+ * new Date(2011, 6, 2, 23, 59)
660
+ * )
661
+ * //=> 1
662
+ */
663
+ function differenceInCalendarDays(dateLeft, dateRight) {
664
+ const startOfDayLeft = startOfDay(dateLeft);
665
+ const startOfDayRight = startOfDay(dateRight);
666
+
667
+ const timestampLeft =
668
+ +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft);
669
+ const timestampRight =
670
+ +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight);
671
+
672
+ // Round the number of days to the nearest integer because the number of
673
+ // milliseconds in a day is not constant (e.g. it's different in the week of
674
+ // the daylight saving time clock shift).
675
+ return Math.round((timestampLeft - timestampRight) / millisecondsInDay);
676
+ }
677
+
678
+ /**
679
+ * @name startOfISOWeekYear
680
+ * @category ISO Week-Numbering Year Helpers
681
+ * @summary Return the start of an ISO week-numbering year for the given date.
682
+ *
683
+ * @description
684
+ * Return the start of an ISO week-numbering year,
685
+ * which always starts 3 days before the year's first Thursday.
686
+ * The result will be in the local timezone.
687
+ *
688
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
689
+ *
690
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
691
+ *
692
+ * @param date - The original date
693
+ *
694
+ * @returns The start of an ISO week-numbering year
695
+ *
696
+ * @example
697
+ * // The start of an ISO week-numbering year for 2 July 2005:
698
+ * const result = startOfISOWeekYear(new Date(2005, 6, 2))
699
+ * //=> Mon Jan 03 2005 00:00:00
700
+ */
701
+ function startOfISOWeekYear(date) {
702
+ const year = getISOWeekYear(date);
703
+ const fourthOfJanuary = constructFrom(date, 0);
704
+ fourthOfJanuary.setFullYear(year, 0, 4);
705
+ fourthOfJanuary.setHours(0, 0, 0, 0);
706
+ return startOfISOWeek(fourthOfJanuary);
707
+ }
708
+
709
+ /**
710
+ * @name isDate
711
+ * @category Common Helpers
712
+ * @summary Is the given value a date?
713
+ *
714
+ * @description
715
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
716
+ *
717
+ * @param value - The value to check
718
+ *
719
+ * @returns True if the given value is a date
720
+ *
721
+ * @example
722
+ * // For a valid date:
723
+ * const result = isDate(new Date())
724
+ * //=> true
725
+ *
726
+ * @example
727
+ * // For an invalid date:
728
+ * const result = isDate(new Date(NaN))
729
+ * //=> true
730
+ *
731
+ * @example
732
+ * // For some value:
733
+ * const result = isDate('2014-02-31')
734
+ * //=> false
735
+ *
736
+ * @example
737
+ * // For an object:
738
+ * const result = isDate({})
739
+ * //=> false
740
+ */
741
+ function isDate(value) {
742
+ return (
743
+ value instanceof Date ||
744
+ (typeof value === "object" &&
745
+ Object.prototype.toString.call(value) === "[object Date]")
746
+ );
747
+ }
748
+
749
+ /**
750
+ * @name isValid
751
+ * @category Common Helpers
752
+ * @summary Is the given date valid?
753
+ *
754
+ * @description
755
+ * Returns false if argument is Invalid Date and true otherwise.
756
+ * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)
757
+ * Invalid Date is a Date, whose time value is NaN.
758
+ *
759
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
760
+ *
761
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
762
+ *
763
+ * @param date - The date to check
764
+ *
765
+ * @returns The date is valid
766
+ *
767
+ * @example
768
+ * // For the valid date:
769
+ * const result = isValid(new Date(2014, 1, 31))
770
+ * //=> true
771
+ *
772
+ * @example
773
+ * // For the value, convertable into a date:
774
+ * const result = isValid(1393804800000)
775
+ * //=> true
776
+ *
777
+ * @example
778
+ * // For the invalid date:
779
+ * const result = isValid(new Date(''))
780
+ * //=> false
781
+ */
782
+ function isValid(date) {
783
+ if (!isDate(date) && typeof date !== "number") {
784
+ return false;
785
+ }
786
+ const _date = toDate(date);
787
+ return !isNaN(Number(_date));
788
+ }
789
+
790
+ /**
791
+ * @name startOfYear
792
+ * @category Year Helpers
793
+ * @summary Return the start of a year for the given date.
794
+ *
795
+ * @description
796
+ * Return the start of a year for the given date.
797
+ * The result will be in the local timezone.
798
+ *
799
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
800
+ *
801
+ * @param date - The original date
802
+ *
803
+ * @returns The start of a year
804
+ *
805
+ * @example
806
+ * // The start of a year for 2 September 2014 11:55:00:
807
+ * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))
808
+ * //=> Wed Jan 01 2014 00:00:00
809
+ */
810
+ function startOfYear(date) {
811
+ const cleanDate = toDate(date);
812
+ const _date = constructFrom(date, 0);
813
+ _date.setFullYear(cleanDate.getFullYear(), 0, 1);
814
+ _date.setHours(0, 0, 0, 0);
815
+ return _date;
816
+ }
817
+
818
+ const formatDistanceLocale = {
819
+ lessThanXSeconds: {
820
+ one: "less than a second",
821
+ other: "less than {{count}} seconds",
822
+ },
823
+
824
+ xSeconds: {
825
+ one: "1 second",
826
+ other: "{{count}} seconds",
827
+ },
828
+
829
+ halfAMinute: "half a minute",
830
+
831
+ lessThanXMinutes: {
832
+ one: "less than a minute",
833
+ other: "less than {{count}} minutes",
834
+ },
835
+
836
+ xMinutes: {
837
+ one: "1 minute",
838
+ other: "{{count}} minutes",
839
+ },
840
+
841
+ aboutXHours: {
842
+ one: "about 1 hour",
843
+ other: "about {{count}} hours",
844
+ },
845
+
846
+ xHours: {
847
+ one: "1 hour",
848
+ other: "{{count}} hours",
849
+ },
850
+
851
+ xDays: {
852
+ one: "1 day",
853
+ other: "{{count}} days",
854
+ },
855
+
856
+ aboutXWeeks: {
857
+ one: "about 1 week",
858
+ other: "about {{count}} weeks",
859
+ },
860
+
861
+ xWeeks: {
862
+ one: "1 week",
863
+ other: "{{count}} weeks",
864
+ },
865
+
866
+ aboutXMonths: {
867
+ one: "about 1 month",
868
+ other: "about {{count}} months",
869
+ },
870
+
871
+ xMonths: {
872
+ one: "1 month",
873
+ other: "{{count}} months",
874
+ },
875
+
876
+ aboutXYears: {
877
+ one: "about 1 year",
878
+ other: "about {{count}} years",
879
+ },
880
+
881
+ xYears: {
882
+ one: "1 year",
883
+ other: "{{count}} years",
884
+ },
885
+
886
+ overXYears: {
887
+ one: "over 1 year",
888
+ other: "over {{count}} years",
889
+ },
890
+
891
+ almostXYears: {
892
+ one: "almost 1 year",
893
+ other: "almost {{count}} years",
894
+ },
895
+ };
896
+
897
+ const formatDistance = (token, count, options) => {
898
+ let result;
899
+
900
+ const tokenValue = formatDistanceLocale[token];
901
+ if (typeof tokenValue === "string") {
902
+ result = tokenValue;
903
+ } else if (count === 1) {
904
+ result = tokenValue.one;
905
+ } else {
906
+ result = tokenValue.other.replace("{{count}}", count.toString());
907
+ }
908
+
909
+ if (options?.addSuffix) {
910
+ if (options.comparison && options.comparison > 0) {
911
+ return "in " + result;
912
+ } else {
913
+ return result + " ago";
914
+ }
915
+ }
916
+
917
+ return result;
918
+ };
919
+
920
+ function buildFormatLongFn(args) {
921
+ return (options = {}) => {
922
+ // TODO: Remove String()
923
+ const width = options.width ? String(options.width) : args.defaultWidth;
924
+ const format = args.formats[width] || args.formats[args.defaultWidth];
925
+ return format;
926
+ };
927
+ }
928
+
929
+ const dateFormats = {
930
+ full: "EEEE, MMMM do, y",
931
+ long: "MMMM do, y",
932
+ medium: "MMM d, y",
933
+ short: "MM/dd/yyyy",
934
+ };
935
+
936
+ const timeFormats = {
937
+ full: "h:mm:ss a zzzz",
938
+ long: "h:mm:ss a z",
939
+ medium: "h:mm:ss a",
940
+ short: "h:mm a",
941
+ };
942
+
943
+ const dateTimeFormats = {
944
+ full: "{{date}} 'at' {{time}}",
945
+ long: "{{date}} 'at' {{time}}",
946
+ medium: "{{date}}, {{time}}",
947
+ short: "{{date}}, {{time}}",
948
+ };
949
+
950
+ const formatLong = {
951
+ date: buildFormatLongFn({
952
+ formats: dateFormats,
953
+ defaultWidth: "full",
954
+ }),
955
+
956
+ time: buildFormatLongFn({
957
+ formats: timeFormats,
958
+ defaultWidth: "full",
959
+ }),
960
+
961
+ dateTime: buildFormatLongFn({
962
+ formats: dateTimeFormats,
963
+ defaultWidth: "full",
964
+ }),
965
+ };
966
+
967
+ const formatRelativeLocale = {
968
+ lastWeek: "'last' eeee 'at' p",
969
+ yesterday: "'yesterday at' p",
970
+ today: "'today at' p",
971
+ tomorrow: "'tomorrow at' p",
972
+ nextWeek: "eeee 'at' p",
973
+ other: "P",
974
+ };
975
+
976
+ const formatRelative = (token, _date, _baseDate, _options) =>
977
+ formatRelativeLocale[token];
978
+
979
+ /* eslint-disable no-unused-vars */
980
+
981
+ /**
982
+ * The localize function argument callback which allows to convert raw value to
983
+ * the actual type.
984
+ *
985
+ * @param value - The value to convert
986
+ *
987
+ * @returns The converted value
988
+ */
989
+
990
+ /**
991
+ * The map of localized values for each width.
992
+ */
993
+
994
+ /**
995
+ * The index type of the locale unit value. It types conversion of units of
996
+ * values that don't start at 0 (i.e. quarters).
997
+ */
998
+
999
+ /**
1000
+ * Converts the unit value to the tuple of values.
1001
+ */
1002
+
1003
+ /**
1004
+ * The tuple of localized era values. The first element represents BC,
1005
+ * the second element represents AD.
1006
+ */
1007
+
1008
+ /**
1009
+ * The tuple of localized quarter values. The first element represents Q1.
1010
+ */
1011
+
1012
+ /**
1013
+ * The tuple of localized day values. The first element represents Sunday.
1014
+ */
1015
+
1016
+ /**
1017
+ * The tuple of localized month values. The first element represents January.
1018
+ */
1019
+
1020
+ function buildLocalizeFn(args) {
1021
+ return (value, options) => {
1022
+ const context = options?.context ? String(options.context) : "standalone";
1023
+
1024
+ let valuesArray;
1025
+ if (context === "formatting" && args.formattingValues) {
1026
+ const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1027
+ const width = options?.width ? String(options.width) : defaultWidth;
1028
+
1029
+ valuesArray =
1030
+ args.formattingValues[width] || args.formattingValues[defaultWidth];
1031
+ } else {
1032
+ const defaultWidth = args.defaultWidth;
1033
+ const width = options?.width ? String(options.width) : args.defaultWidth;
1034
+
1035
+ valuesArray = args.values[width] || args.values[defaultWidth];
1036
+ }
1037
+ const index = args.argumentCallback ? args.argumentCallback(value) : value;
1038
+
1039
+ // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
1040
+ return valuesArray[index];
1041
+ };
1042
+ }
1043
+
1044
+ const eraValues = {
1045
+ narrow: ["B", "A"],
1046
+ abbreviated: ["BC", "AD"],
1047
+ wide: ["Before Christ", "Anno Domini"],
1048
+ };
1049
+
1050
+ const quarterValues = {
1051
+ narrow: ["1", "2", "3", "4"],
1052
+ abbreviated: ["Q1", "Q2", "Q3", "Q4"],
1053
+ wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
1054
+ };
1055
+
1056
+ // Note: in English, the names of days of the week and months are capitalized.
1057
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1058
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1059
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1060
+ const monthValues = {
1061
+ narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
1062
+ abbreviated: [
1063
+ "Jan",
1064
+ "Feb",
1065
+ "Mar",
1066
+ "Apr",
1067
+ "May",
1068
+ "Jun",
1069
+ "Jul",
1070
+ "Aug",
1071
+ "Sep",
1072
+ "Oct",
1073
+ "Nov",
1074
+ "Dec",
1075
+ ],
1076
+
1077
+ wide: [
1078
+ "January",
1079
+ "February",
1080
+ "March",
1081
+ "April",
1082
+ "May",
1083
+ "June",
1084
+ "July",
1085
+ "August",
1086
+ "September",
1087
+ "October",
1088
+ "November",
1089
+ "December",
1090
+ ],
1091
+ };
1092
+
1093
+ const dayValues = {
1094
+ narrow: ["S", "M", "T", "W", "T", "F", "S"],
1095
+ short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
1096
+ abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
1097
+ wide: [
1098
+ "Sunday",
1099
+ "Monday",
1100
+ "Tuesday",
1101
+ "Wednesday",
1102
+ "Thursday",
1103
+ "Friday",
1104
+ "Saturday",
1105
+ ],
1106
+ };
1107
+
1108
+ const dayPeriodValues = {
1109
+ narrow: {
1110
+ am: "a",
1111
+ pm: "p",
1112
+ midnight: "mi",
1113
+ noon: "n",
1114
+ morning: "morning",
1115
+ afternoon: "afternoon",
1116
+ evening: "evening",
1117
+ night: "night",
1118
+ },
1119
+ abbreviated: {
1120
+ am: "AM",
1121
+ pm: "PM",
1122
+ midnight: "midnight",
1123
+ noon: "noon",
1124
+ morning: "morning",
1125
+ afternoon: "afternoon",
1126
+ evening: "evening",
1127
+ night: "night",
1128
+ },
1129
+ wide: {
1130
+ am: "a.m.",
1131
+ pm: "p.m.",
1132
+ midnight: "midnight",
1133
+ noon: "noon",
1134
+ morning: "morning",
1135
+ afternoon: "afternoon",
1136
+ evening: "evening",
1137
+ night: "night",
1138
+ },
1139
+ };
1140
+
1141
+ const formattingDayPeriodValues = {
1142
+ narrow: {
1143
+ am: "a",
1144
+ pm: "p",
1145
+ midnight: "mi",
1146
+ noon: "n",
1147
+ morning: "in the morning",
1148
+ afternoon: "in the afternoon",
1149
+ evening: "in the evening",
1150
+ night: "at night",
1151
+ },
1152
+ abbreviated: {
1153
+ am: "AM",
1154
+ pm: "PM",
1155
+ midnight: "midnight",
1156
+ noon: "noon",
1157
+ morning: "in the morning",
1158
+ afternoon: "in the afternoon",
1159
+ evening: "in the evening",
1160
+ night: "at night",
1161
+ },
1162
+ wide: {
1163
+ am: "a.m.",
1164
+ pm: "p.m.",
1165
+ midnight: "midnight",
1166
+ noon: "noon",
1167
+ morning: "in the morning",
1168
+ afternoon: "in the afternoon",
1169
+ evening: "in the evening",
1170
+ night: "at night",
1171
+ },
1172
+ };
1173
+
1174
+ const ordinalNumber = (dirtyNumber, _options) => {
1175
+ const number = Number(dirtyNumber);
1176
+
1177
+ // If ordinal numbers depend on context, for example,
1178
+ // if they are different for different grammatical genders,
1179
+ // use `options.unit`.
1180
+ //
1181
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
1182
+ // 'day', 'hour', 'minute', 'second'.
1183
+
1184
+ const rem100 = number % 100;
1185
+ if (rem100 > 20 || rem100 < 10) {
1186
+ switch (rem100 % 10) {
1187
+ case 1:
1188
+ return number + "st";
1189
+ case 2:
1190
+ return number + "nd";
1191
+ case 3:
1192
+ return number + "rd";
1193
+ }
1194
+ }
1195
+ return number + "th";
1196
+ };
1197
+
1198
+ const localize = {
1199
+ ordinalNumber,
1200
+
1201
+ era: buildLocalizeFn({
1202
+ values: eraValues,
1203
+ defaultWidth: "wide",
1204
+ }),
1205
+
1206
+ quarter: buildLocalizeFn({
1207
+ values: quarterValues,
1208
+ defaultWidth: "wide",
1209
+ argumentCallback: (quarter) => quarter - 1,
1210
+ }),
1211
+
1212
+ month: buildLocalizeFn({
1213
+ values: monthValues,
1214
+ defaultWidth: "wide",
1215
+ }),
1216
+
1217
+ day: buildLocalizeFn({
1218
+ values: dayValues,
1219
+ defaultWidth: "wide",
1220
+ }),
1221
+
1222
+ dayPeriod: buildLocalizeFn({
1223
+ values: dayPeriodValues,
1224
+ defaultWidth: "wide",
1225
+ formattingValues: formattingDayPeriodValues,
1226
+ defaultFormattingWidth: "wide",
1227
+ }),
1228
+ };
1229
+
1230
+ function buildMatchFn(args) {
1231
+ return (string, options = {}) => {
1232
+ const width = options.width;
1233
+
1234
+ const matchPattern =
1235
+ (width && args.matchPatterns[width]) ||
1236
+ args.matchPatterns[args.defaultMatchWidth];
1237
+ const matchResult = string.match(matchPattern);
1238
+
1239
+ if (!matchResult) {
1240
+ return null;
1241
+ }
1242
+ const matchedString = matchResult[0];
1243
+
1244
+ const parsePatterns =
1245
+ (width && args.parsePatterns[width]) ||
1246
+ args.parsePatterns[args.defaultParseWidth];
1247
+
1248
+ const key = Array.isArray(parsePatterns)
1249
+ ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))
1250
+ : // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1251
+ findKey(parsePatterns, (pattern) => pattern.test(matchedString));
1252
+
1253
+ let value;
1254
+
1255
+ value = args.valueCallback ? args.valueCallback(key) : key;
1256
+ value = options.valueCallback
1257
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1258
+ options.valueCallback(value)
1259
+ : value;
1260
+
1261
+ const rest = string.slice(matchedString.length);
1262
+
1263
+ return { value, rest };
1264
+ };
1265
+ }
1266
+
1267
+ function findKey(object, predicate) {
1268
+ for (const key in object) {
1269
+ if (
1270
+ Object.prototype.hasOwnProperty.call(object, key) &&
1271
+ predicate(object[key])
1272
+ ) {
1273
+ return key;
1274
+ }
1275
+ }
1276
+ return undefined;
1277
+ }
1278
+
1279
+ function findIndex(array, predicate) {
1280
+ for (let key = 0; key < array.length; key++) {
1281
+ if (predicate(array[key])) {
1282
+ return key;
1283
+ }
1284
+ }
1285
+ return undefined;
1286
+ }
1287
+
1288
+ function buildMatchPatternFn(args) {
1289
+ return (string, options = {}) => {
1290
+ const matchResult = string.match(args.matchPattern);
1291
+ if (!matchResult) return null;
1292
+ const matchedString = matchResult[0];
1293
+
1294
+ const parseResult = string.match(args.parsePattern);
1295
+ if (!parseResult) return null;
1296
+ let value = args.valueCallback
1297
+ ? args.valueCallback(parseResult[0])
1298
+ : parseResult[0];
1299
+
1300
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1301
+ value = options.valueCallback ? options.valueCallback(value) : value;
1302
+
1303
+ const rest = string.slice(matchedString.length);
1304
+
1305
+ return { value, rest };
1306
+ };
1307
+ }
1308
+
1309
+ const matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
1310
+ const parseOrdinalNumberPattern = /\d+/i;
1311
+
1312
+ const matchEraPatterns = {
1313
+ narrow: /^(b|a)/i,
1314
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
1315
+ wide: /^(before christ|before common era|anno domini|common era)/i,
1316
+ };
1317
+ const parseEraPatterns = {
1318
+ any: [/^b/i, /^(a|c)/i],
1319
+ };
1320
+
1321
+ const matchQuarterPatterns = {
1322
+ narrow: /^[1234]/i,
1323
+ abbreviated: /^q[1234]/i,
1324
+ wide: /^[1234](th|st|nd|rd)? quarter/i,
1325
+ };
1326
+ const parseQuarterPatterns = {
1327
+ any: [/1/i, /2/i, /3/i, /4/i],
1328
+ };
1329
+
1330
+ const matchMonthPatterns = {
1331
+ narrow: /^[jfmasond]/i,
1332
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
1333
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,
1334
+ };
1335
+ const parseMonthPatterns = {
1336
+ narrow: [
1337
+ /^j/i,
1338
+ /^f/i,
1339
+ /^m/i,
1340
+ /^a/i,
1341
+ /^m/i,
1342
+ /^j/i,
1343
+ /^j/i,
1344
+ /^a/i,
1345
+ /^s/i,
1346
+ /^o/i,
1347
+ /^n/i,
1348
+ /^d/i,
1349
+ ],
1350
+
1351
+ any: [
1352
+ /^ja/i,
1353
+ /^f/i,
1354
+ /^mar/i,
1355
+ /^ap/i,
1356
+ /^may/i,
1357
+ /^jun/i,
1358
+ /^jul/i,
1359
+ /^au/i,
1360
+ /^s/i,
1361
+ /^o/i,
1362
+ /^n/i,
1363
+ /^d/i,
1364
+ ],
1365
+ };
1366
+
1367
+ const matchDayPatterns = {
1368
+ narrow: /^[smtwf]/i,
1369
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
1370
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
1371
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,
1372
+ };
1373
+ const parseDayPatterns = {
1374
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
1375
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],
1376
+ };
1377
+
1378
+ const matchDayPeriodPatterns = {
1379
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
1380
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,
1381
+ };
1382
+ const parseDayPeriodPatterns = {
1383
+ any: {
1384
+ am: /^a/i,
1385
+ pm: /^p/i,
1386
+ midnight: /^mi/i,
1387
+ noon: /^no/i,
1388
+ morning: /morning/i,
1389
+ afternoon: /afternoon/i,
1390
+ evening: /evening/i,
1391
+ night: /night/i,
1392
+ },
1393
+ };
1394
+
1395
+ const match = {
1396
+ ordinalNumber: buildMatchPatternFn({
1397
+ matchPattern: matchOrdinalNumberPattern,
1398
+ parsePattern: parseOrdinalNumberPattern,
1399
+ valueCallback: (value) => parseInt(value, 10),
1400
+ }),
1401
+
1402
+ era: buildMatchFn({
1403
+ matchPatterns: matchEraPatterns,
1404
+ defaultMatchWidth: "wide",
1405
+ parsePatterns: parseEraPatterns,
1406
+ defaultParseWidth: "any",
1407
+ }),
1408
+
1409
+ quarter: buildMatchFn({
1410
+ matchPatterns: matchQuarterPatterns,
1411
+ defaultMatchWidth: "wide",
1412
+ parsePatterns: parseQuarterPatterns,
1413
+ defaultParseWidth: "any",
1414
+ valueCallback: (index) => index + 1,
1415
+ }),
1416
+
1417
+ month: buildMatchFn({
1418
+ matchPatterns: matchMonthPatterns,
1419
+ defaultMatchWidth: "wide",
1420
+ parsePatterns: parseMonthPatterns,
1421
+ defaultParseWidth: "any",
1422
+ }),
1423
+
1424
+ day: buildMatchFn({
1425
+ matchPatterns: matchDayPatterns,
1426
+ defaultMatchWidth: "wide",
1427
+ parsePatterns: parseDayPatterns,
1428
+ defaultParseWidth: "any",
1429
+ }),
1430
+
1431
+ dayPeriod: buildMatchFn({
1432
+ matchPatterns: matchDayPeriodPatterns,
1433
+ defaultMatchWidth: "any",
1434
+ parsePatterns: parseDayPeriodPatterns,
1435
+ defaultParseWidth: "any",
1436
+ }),
1437
+ };
1438
+
1439
+ /**
1440
+ * @category Locales
1441
+ * @summary English locale (United States).
1442
+ * @language English
1443
+ * @iso-639-2 eng
1444
+ * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)
1445
+ * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)
1446
+ */
1447
+ const enUS = {
1448
+ code: "en-US",
1449
+ formatDistance: formatDistance,
1450
+ formatLong: formatLong,
1451
+ formatRelative: formatRelative,
1452
+ localize: localize,
1453
+ match: match,
1454
+ options: {
1455
+ weekStartsOn: 0 /* Sunday */,
1456
+ firstWeekContainsDate: 1,
1457
+ },
1458
+ };
1459
+
1460
+ /**
1461
+ * @name getDayOfYear
1462
+ * @category Day Helpers
1463
+ * @summary Get the day of the year of the given date.
1464
+ *
1465
+ * @description
1466
+ * Get the day of the year of the given date.
1467
+ *
1468
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
1469
+ *
1470
+ * @param date - The given date
1471
+ *
1472
+ * @returns The day of year
1473
+ *
1474
+ * @example
1475
+ * // Which day of the year is 2 July 2014?
1476
+ * const result = getDayOfYear(new Date(2014, 6, 2))
1477
+ * //=> 183
1478
+ */
1479
+ function getDayOfYear(date) {
1480
+ const _date = toDate(date);
1481
+ const diff = differenceInCalendarDays(_date, startOfYear(_date));
1482
+ const dayOfYear = diff + 1;
1483
+ return dayOfYear;
1484
+ }
1485
+
1486
+ /**
1487
+ * @name getISOWeek
1488
+ * @category ISO Week Helpers
1489
+ * @summary Get the ISO week of the given date.
1490
+ *
1491
+ * @description
1492
+ * Get the ISO week of the given date.
1493
+ *
1494
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
1495
+ *
1496
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
1497
+ *
1498
+ * @param date - The given date
1499
+ *
1500
+ * @returns The ISO week
1501
+ *
1502
+ * @example
1503
+ * // Which week of the ISO-week numbering year is 2 January 2005?
1504
+ * const result = getISOWeek(new Date(2005, 0, 2))
1505
+ * //=> 53
1506
+ */
1507
+ function getISOWeek(date) {
1508
+ const _date = toDate(date);
1509
+ const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
1510
+
1511
+ // Round the number of weeks to the nearest integer because the number of
1512
+ // milliseconds in a week is not constant (e.g. it's different in the week of
1513
+ // the daylight saving time clock shift).
1514
+ return Math.round(diff / millisecondsInWeek) + 1;
1515
+ }
1516
+
1517
+ /**
1518
+ * The {@link getWeekYear} function options.
1519
+ */
1520
+
1521
+ /**
1522
+ * @name getWeekYear
1523
+ * @category Week-Numbering Year Helpers
1524
+ * @summary Get the local week-numbering year of the given date.
1525
+ *
1526
+ * @description
1527
+ * Get the local week-numbering year of the given date.
1528
+ * The exact calculation depends on the values of
1529
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1530
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1531
+ * the first week of the week-numbering year)
1532
+ *
1533
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1534
+ *
1535
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
1536
+ *
1537
+ * @param date - The given date
1538
+ * @param options - An object with options.
1539
+ *
1540
+ * @returns The local week-numbering year
1541
+ *
1542
+ * @example
1543
+ * // Which week numbering year is 26 December 2004 with the default settings?
1544
+ * const result = getWeekYear(new Date(2004, 11, 26))
1545
+ * //=> 2005
1546
+ *
1547
+ * @example
1548
+ * // Which week numbering year is 26 December 2004 if week starts on Saturday?
1549
+ * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })
1550
+ * //=> 2004
1551
+ *
1552
+ * @example
1553
+ * // Which week numbering year is 26 December 2004 if the first week contains 4 January?
1554
+ * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })
1555
+ * //=> 2004
1556
+ */
1557
+ function getWeekYear(date, options) {
1558
+ const _date = toDate(date);
1559
+ const year = _date.getFullYear();
1560
+
1561
+ const defaultOptions = getDefaultOptions();
1562
+ const firstWeekContainsDate =
1563
+ options?.firstWeekContainsDate ??
1564
+ options?.locale?.options?.firstWeekContainsDate ??
1565
+ defaultOptions.firstWeekContainsDate ??
1566
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
1567
+ 1;
1568
+
1569
+ const firstWeekOfNextYear = constructFrom(date, 0);
1570
+ firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
1571
+ firstWeekOfNextYear.setHours(0, 0, 0, 0);
1572
+ const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
1573
+
1574
+ const firstWeekOfThisYear = constructFrom(date, 0);
1575
+ firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
1576
+ firstWeekOfThisYear.setHours(0, 0, 0, 0);
1577
+ const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
1578
+
1579
+ if (_date.getTime() >= startOfNextYear.getTime()) {
1580
+ return year + 1;
1581
+ } else if (_date.getTime() >= startOfThisYear.getTime()) {
1582
+ return year;
1583
+ } else {
1584
+ return year - 1;
1585
+ }
1586
+ }
1587
+
1588
+ /**
1589
+ * The {@link startOfWeekYear} function options.
1590
+ */
1591
+
1592
+ /**
1593
+ * @name startOfWeekYear
1594
+ * @category Week-Numbering Year Helpers
1595
+ * @summary Return the start of a local week-numbering year for the given date.
1596
+ *
1597
+ * @description
1598
+ * Return the start of a local week-numbering year.
1599
+ * The exact calculation depends on the values of
1600
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1601
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1602
+ * the first week of the week-numbering year)
1603
+ *
1604
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1605
+ *
1606
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
1607
+ *
1608
+ * @param date - The original date
1609
+ * @param options - An object with options
1610
+ *
1611
+ * @returns The start of a week-numbering year
1612
+ *
1613
+ * @example
1614
+ * // The start of an a week-numbering year for 2 July 2005 with default settings:
1615
+ * const result = startOfWeekYear(new Date(2005, 6, 2))
1616
+ * //=> Sun Dec 26 2004 00:00:00
1617
+ *
1618
+ * @example
1619
+ * // The start of a week-numbering year for 2 July 2005
1620
+ * // if Monday is the first day of week
1621
+ * // and 4 January is always in the first week of the year:
1622
+ * const result = startOfWeekYear(new Date(2005, 6, 2), {
1623
+ * weekStartsOn: 1,
1624
+ * firstWeekContainsDate: 4
1625
+ * })
1626
+ * //=> Mon Jan 03 2005 00:00:00
1627
+ */
1628
+ function startOfWeekYear(date, options) {
1629
+ const defaultOptions = getDefaultOptions();
1630
+ const firstWeekContainsDate =
1631
+ options?.firstWeekContainsDate ??
1632
+ options?.locale?.options?.firstWeekContainsDate ??
1633
+ defaultOptions.firstWeekContainsDate ??
1634
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
1635
+ 1;
1636
+
1637
+ const year = getWeekYear(date, options);
1638
+ const firstWeek = constructFrom(date, 0);
1639
+ firstWeek.setFullYear(year, 0, firstWeekContainsDate);
1640
+ firstWeek.setHours(0, 0, 0, 0);
1641
+ const _date = startOfWeek(firstWeek, options);
1642
+ return _date;
1643
+ }
1644
+
1645
+ /**
1646
+ * The {@link getWeek} function options.
1647
+ */
1648
+
1649
+ /**
1650
+ * @name getWeek
1651
+ * @category Week Helpers
1652
+ * @summary Get the local week index of the given date.
1653
+ *
1654
+ * @description
1655
+ * Get the local week index of the given date.
1656
+ * The exact calculation depends on the values of
1657
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1658
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1659
+ * the first week of the week-numbering year)
1660
+ *
1661
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1662
+ *
1663
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
1664
+ *
1665
+ * @param date - The given date
1666
+ * @param options - An object with options
1667
+ *
1668
+ * @returns The week
1669
+ *
1670
+ * @example
1671
+ * // Which week of the local week numbering year is 2 January 2005 with default options?
1672
+ * const result = getWeek(new Date(2005, 0, 2))
1673
+ * //=> 2
1674
+ *
1675
+ * @example
1676
+ * // Which week of the local week numbering year is 2 January 2005,
1677
+ * // if Monday is the first day of the week,
1678
+ * // and the first week of the year always contains 4 January?
1679
+ * const result = getWeek(new Date(2005, 0, 2), {
1680
+ * weekStartsOn: 1,
1681
+ * firstWeekContainsDate: 4
1682
+ * })
1683
+ * //=> 53
1684
+ */
1685
+
1686
+ function getWeek(date, options) {
1687
+ const _date = toDate(date);
1688
+ const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
1689
+
1690
+ // Round the number of weeks to the nearest integer because the number of
1691
+ // milliseconds in a week is not constant (e.g. it's different in the week of
1692
+ // the daylight saving time clock shift).
1693
+ return Math.round(diff / millisecondsInWeek) + 1;
1694
+ }
1695
+
1696
+ function addLeadingZeros(number, targetLength) {
1697
+ const sign = number < 0 ? "-" : "";
1698
+ const output = Math.abs(number).toString().padStart(targetLength, "0");
1699
+ return sign + output;
1700
+ }
1701
+
1702
+ /*
1703
+ * | | Unit | | Unit |
1704
+ * |-----|--------------------------------|-----|--------------------------------|
1705
+ * | a | AM, PM | A* | |
1706
+ * | d | Day of month | D | |
1707
+ * | h | Hour [1-12] | H | Hour [0-23] |
1708
+ * | m | Minute | M | Month |
1709
+ * | s | Second | S | Fraction of second |
1710
+ * | y | Year (abs) | Y | |
1711
+ *
1712
+ * Letters marked by * are not implemented but reserved by Unicode standard.
1713
+ */
1714
+
1715
+ const lightFormatters = {
1716
+ // Year
1717
+ y(date, token) {
1718
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
1719
+ // | Year | y | yy | yyy | yyyy | yyyyy |
1720
+ // |----------|-------|----|-------|-------|-------|
1721
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
1722
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
1723
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
1724
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
1725
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
1726
+
1727
+ const signedYear = date.getFullYear();
1728
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1729
+ const year = signedYear > 0 ? signedYear : 1 - signedYear;
1730
+ return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
1731
+ },
1732
+
1733
+ // Month
1734
+ M(date, token) {
1735
+ const month = date.getMonth();
1736
+ return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
1737
+ },
1738
+
1739
+ // Day of the month
1740
+ d(date, token) {
1741
+ return addLeadingZeros(date.getDate(), token.length);
1742
+ },
1743
+
1744
+ // AM or PM
1745
+ a(date, token) {
1746
+ const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am";
1747
+
1748
+ switch (token) {
1749
+ case "a":
1750
+ case "aa":
1751
+ return dayPeriodEnumValue.toUpperCase();
1752
+ case "aaa":
1753
+ return dayPeriodEnumValue;
1754
+ case "aaaaa":
1755
+ return dayPeriodEnumValue[0];
1756
+ case "aaaa":
1757
+ default:
1758
+ return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
1759
+ }
1760
+ },
1761
+
1762
+ // Hour [1-12]
1763
+ h(date, token) {
1764
+ return addLeadingZeros(date.getHours() % 12 || 12, token.length);
1765
+ },
1766
+
1767
+ // Hour [0-23]
1768
+ H(date, token) {
1769
+ return addLeadingZeros(date.getHours(), token.length);
1770
+ },
1771
+
1772
+ // Minute
1773
+ m(date, token) {
1774
+ return addLeadingZeros(date.getMinutes(), token.length);
1775
+ },
1776
+
1777
+ // Second
1778
+ s(date, token) {
1779
+ return addLeadingZeros(date.getSeconds(), token.length);
1780
+ },
1781
+
1782
+ // Fraction of second
1783
+ S(date, token) {
1784
+ const numberOfDigits = token.length;
1785
+ const milliseconds = date.getMilliseconds();
1786
+ const fractionalSeconds = Math.trunc(
1787
+ milliseconds * Math.pow(10, numberOfDigits - 3),
1788
+ );
1789
+ return addLeadingZeros(fractionalSeconds, token.length);
1790
+ },
1791
+ };
1792
+
1793
+ const dayPeriodEnum = {
1794
+ am: "am",
1795
+ pm: "pm",
1796
+ midnight: "midnight",
1797
+ noon: "noon",
1798
+ morning: "morning",
1799
+ afternoon: "afternoon",
1800
+ evening: "evening",
1801
+ night: "night",
1802
+ };
1803
+
1804
+ /*
1805
+ * | | Unit | | Unit |
1806
+ * |-----|--------------------------------|-----|--------------------------------|
1807
+ * | a | AM, PM | A* | Milliseconds in day |
1808
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
1809
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
1810
+ * | d | Day of month | D | Day of year |
1811
+ * | e | Local day of week | E | Day of week |
1812
+ * | f | | F* | Day of week in month |
1813
+ * | g* | Modified Julian day | G | Era |
1814
+ * | h | Hour [1-12] | H | Hour [0-23] |
1815
+ * | i! | ISO day of week | I! | ISO week of year |
1816
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
1817
+ * | k | Hour [1-24] | K | Hour [0-11] |
1818
+ * | l* | (deprecated) | L | Stand-alone month |
1819
+ * | m | Minute | M | Month |
1820
+ * | n | | N | |
1821
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
1822
+ * | p! | Long localized time | P! | Long localized date |
1823
+ * | q | Stand-alone quarter | Q | Quarter |
1824
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
1825
+ * | s | Second | S | Fraction of second |
1826
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
1827
+ * | u | Extended year | U* | Cyclic year |
1828
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
1829
+ * | w | Local week of year | W* | Week of month |
1830
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
1831
+ * | y | Year (abs) | Y | Local week-numbering year |
1832
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
1833
+ *
1834
+ * Letters marked by * are not implemented but reserved by Unicode standard.
1835
+ *
1836
+ * Letters marked by ! are non-standard, but implemented by date-fns:
1837
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
1838
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
1839
+ * i.e. 7 for Sunday, 1 for Monday, etc.
1840
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
1841
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
1842
+ * `R` is supposed to be used in conjunction with `I` and `i`
1843
+ * for universal ISO week-numbering date, whereas
1844
+ * `Y` is supposed to be used in conjunction with `w` and `e`
1845
+ * for week-numbering date specific to the locale.
1846
+ * - `P` is long localized date format
1847
+ * - `p` is long localized time format
1848
+ */
1849
+
1850
+ const formatters = {
1851
+ // Era
1852
+ G: function (date, token, localize) {
1853
+ const era = date.getFullYear() > 0 ? 1 : 0;
1854
+ switch (token) {
1855
+ // AD, BC
1856
+ case "G":
1857
+ case "GG":
1858
+ case "GGG":
1859
+ return localize.era(era, { width: "abbreviated" });
1860
+ // A, B
1861
+ case "GGGGG":
1862
+ return localize.era(era, { width: "narrow" });
1863
+ // Anno Domini, Before Christ
1864
+ case "GGGG":
1865
+ default:
1866
+ return localize.era(era, { width: "wide" });
1867
+ }
1868
+ },
1869
+
1870
+ // Year
1871
+ y: function (date, token, localize) {
1872
+ // Ordinal number
1873
+ if (token === "yo") {
1874
+ const signedYear = date.getFullYear();
1875
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1876
+ const year = signedYear > 0 ? signedYear : 1 - signedYear;
1877
+ return localize.ordinalNumber(year, { unit: "year" });
1878
+ }
1879
+
1880
+ return lightFormatters.y(date, token);
1881
+ },
1882
+
1883
+ // Local week-numbering year
1884
+ Y: function (date, token, localize, options) {
1885
+ const signedWeekYear = getWeekYear(date, options);
1886
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1887
+ const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
1888
+
1889
+ // Two digit year
1890
+ if (token === "YY") {
1891
+ const twoDigitYear = weekYear % 100;
1892
+ return addLeadingZeros(twoDigitYear, 2);
1893
+ }
1894
+
1895
+ // Ordinal number
1896
+ if (token === "Yo") {
1897
+ return localize.ordinalNumber(weekYear, { unit: "year" });
1898
+ }
1899
+
1900
+ // Padding
1901
+ return addLeadingZeros(weekYear, token.length);
1902
+ },
1903
+
1904
+ // ISO week-numbering year
1905
+ R: function (date, token) {
1906
+ const isoWeekYear = getISOWeekYear(date);
1907
+
1908
+ // Padding
1909
+ return addLeadingZeros(isoWeekYear, token.length);
1910
+ },
1911
+
1912
+ // Extended year. This is a single number designating the year of this calendar system.
1913
+ // The main difference between `y` and `u` localizers are B.C. years:
1914
+ // | Year | `y` | `u` |
1915
+ // |------|-----|-----|
1916
+ // | AC 1 | 1 | 1 |
1917
+ // | BC 1 | 1 | 0 |
1918
+ // | BC 2 | 2 | -1 |
1919
+ // Also `yy` always returns the last two digits of a year,
1920
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
1921
+ u: function (date, token) {
1922
+ const year = date.getFullYear();
1923
+ return addLeadingZeros(year, token.length);
1924
+ },
1925
+
1926
+ // Quarter
1927
+ Q: function (date, token, localize) {
1928
+ const quarter = Math.ceil((date.getMonth() + 1) / 3);
1929
+ switch (token) {
1930
+ // 1, 2, 3, 4
1931
+ case "Q":
1932
+ return String(quarter);
1933
+ // 01, 02, 03, 04
1934
+ case "QQ":
1935
+ return addLeadingZeros(quarter, 2);
1936
+ // 1st, 2nd, 3rd, 4th
1937
+ case "Qo":
1938
+ return localize.ordinalNumber(quarter, { unit: "quarter" });
1939
+ // Q1, Q2, Q3, Q4
1940
+ case "QQQ":
1941
+ return localize.quarter(quarter, {
1942
+ width: "abbreviated",
1943
+ context: "formatting",
1944
+ });
1945
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
1946
+ case "QQQQQ":
1947
+ return localize.quarter(quarter, {
1948
+ width: "narrow",
1949
+ context: "formatting",
1950
+ });
1951
+ // 1st quarter, 2nd quarter, ...
1952
+ case "QQQQ":
1953
+ default:
1954
+ return localize.quarter(quarter, {
1955
+ width: "wide",
1956
+ context: "formatting",
1957
+ });
1958
+ }
1959
+ },
1960
+
1961
+ // Stand-alone quarter
1962
+ q: function (date, token, localize) {
1963
+ const quarter = Math.ceil((date.getMonth() + 1) / 3);
1964
+ switch (token) {
1965
+ // 1, 2, 3, 4
1966
+ case "q":
1967
+ return String(quarter);
1968
+ // 01, 02, 03, 04
1969
+ case "qq":
1970
+ return addLeadingZeros(quarter, 2);
1971
+ // 1st, 2nd, 3rd, 4th
1972
+ case "qo":
1973
+ return localize.ordinalNumber(quarter, { unit: "quarter" });
1974
+ // Q1, Q2, Q3, Q4
1975
+ case "qqq":
1976
+ return localize.quarter(quarter, {
1977
+ width: "abbreviated",
1978
+ context: "standalone",
1979
+ });
1980
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
1981
+ case "qqqqq":
1982
+ return localize.quarter(quarter, {
1983
+ width: "narrow",
1984
+ context: "standalone",
1985
+ });
1986
+ // 1st quarter, 2nd quarter, ...
1987
+ case "qqqq":
1988
+ default:
1989
+ return localize.quarter(quarter, {
1990
+ width: "wide",
1991
+ context: "standalone",
1992
+ });
1993
+ }
1994
+ },
1995
+
1996
+ // Month
1997
+ M: function (date, token, localize) {
1998
+ const month = date.getMonth();
1999
+ switch (token) {
2000
+ case "M":
2001
+ case "MM":
2002
+ return lightFormatters.M(date, token);
2003
+ // 1st, 2nd, ..., 12th
2004
+ case "Mo":
2005
+ return localize.ordinalNumber(month + 1, { unit: "month" });
2006
+ // Jan, Feb, ..., Dec
2007
+ case "MMM":
2008
+ return localize.month(month, {
2009
+ width: "abbreviated",
2010
+ context: "formatting",
2011
+ });
2012
+ // J, F, ..., D
2013
+ case "MMMMM":
2014
+ return localize.month(month, {
2015
+ width: "narrow",
2016
+ context: "formatting",
2017
+ });
2018
+ // January, February, ..., December
2019
+ case "MMMM":
2020
+ default:
2021
+ return localize.month(month, { width: "wide", context: "formatting" });
2022
+ }
2023
+ },
2024
+
2025
+ // Stand-alone month
2026
+ L: function (date, token, localize) {
2027
+ const month = date.getMonth();
2028
+ switch (token) {
2029
+ // 1, 2, ..., 12
2030
+ case "L":
2031
+ return String(month + 1);
2032
+ // 01, 02, ..., 12
2033
+ case "LL":
2034
+ return addLeadingZeros(month + 1, 2);
2035
+ // 1st, 2nd, ..., 12th
2036
+ case "Lo":
2037
+ return localize.ordinalNumber(month + 1, { unit: "month" });
2038
+ // Jan, Feb, ..., Dec
2039
+ case "LLL":
2040
+ return localize.month(month, {
2041
+ width: "abbreviated",
2042
+ context: "standalone",
2043
+ });
2044
+ // J, F, ..., D
2045
+ case "LLLLL":
2046
+ return localize.month(month, {
2047
+ width: "narrow",
2048
+ context: "standalone",
2049
+ });
2050
+ // January, February, ..., December
2051
+ case "LLLL":
2052
+ default:
2053
+ return localize.month(month, { width: "wide", context: "standalone" });
2054
+ }
2055
+ },
2056
+
2057
+ // Local week of year
2058
+ w: function (date, token, localize, options) {
2059
+ const week = getWeek(date, options);
2060
+
2061
+ if (token === "wo") {
2062
+ return localize.ordinalNumber(week, { unit: "week" });
2063
+ }
2064
+
2065
+ return addLeadingZeros(week, token.length);
2066
+ },
2067
+
2068
+ // ISO week of year
2069
+ I: function (date, token, localize) {
2070
+ const isoWeek = getISOWeek(date);
2071
+
2072
+ if (token === "Io") {
2073
+ return localize.ordinalNumber(isoWeek, { unit: "week" });
2074
+ }
2075
+
2076
+ return addLeadingZeros(isoWeek, token.length);
2077
+ },
2078
+
2079
+ // Day of the month
2080
+ d: function (date, token, localize) {
2081
+ if (token === "do") {
2082
+ return localize.ordinalNumber(date.getDate(), { unit: "date" });
2083
+ }
2084
+
2085
+ return lightFormatters.d(date, token);
2086
+ },
2087
+
2088
+ // Day of year
2089
+ D: function (date, token, localize) {
2090
+ const dayOfYear = getDayOfYear(date);
2091
+
2092
+ if (token === "Do") {
2093
+ return localize.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
2094
+ }
2095
+
2096
+ return addLeadingZeros(dayOfYear, token.length);
2097
+ },
2098
+
2099
+ // Day of week
2100
+ E: function (date, token, localize) {
2101
+ const dayOfWeek = date.getDay();
2102
+ switch (token) {
2103
+ // Tue
2104
+ case "E":
2105
+ case "EE":
2106
+ case "EEE":
2107
+ return localize.day(dayOfWeek, {
2108
+ width: "abbreviated",
2109
+ context: "formatting",
2110
+ });
2111
+ // T
2112
+ case "EEEEE":
2113
+ return localize.day(dayOfWeek, {
2114
+ width: "narrow",
2115
+ context: "formatting",
2116
+ });
2117
+ // Tu
2118
+ case "EEEEEE":
2119
+ return localize.day(dayOfWeek, {
2120
+ width: "short",
2121
+ context: "formatting",
2122
+ });
2123
+ // Tuesday
2124
+ case "EEEE":
2125
+ default:
2126
+ return localize.day(dayOfWeek, {
2127
+ width: "wide",
2128
+ context: "formatting",
2129
+ });
2130
+ }
2131
+ },
2132
+
2133
+ // Local day of week
2134
+ e: function (date, token, localize, options) {
2135
+ const dayOfWeek = date.getDay();
2136
+ const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
2137
+ switch (token) {
2138
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
2139
+ case "e":
2140
+ return String(localDayOfWeek);
2141
+ // Padded numerical value
2142
+ case "ee":
2143
+ return addLeadingZeros(localDayOfWeek, 2);
2144
+ // 1st, 2nd, ..., 7th
2145
+ case "eo":
2146
+ return localize.ordinalNumber(localDayOfWeek, { unit: "day" });
2147
+ case "eee":
2148
+ return localize.day(dayOfWeek, {
2149
+ width: "abbreviated",
2150
+ context: "formatting",
2151
+ });
2152
+ // T
2153
+ case "eeeee":
2154
+ return localize.day(dayOfWeek, {
2155
+ width: "narrow",
2156
+ context: "formatting",
2157
+ });
2158
+ // Tu
2159
+ case "eeeeee":
2160
+ return localize.day(dayOfWeek, {
2161
+ width: "short",
2162
+ context: "formatting",
2163
+ });
2164
+ // Tuesday
2165
+ case "eeee":
2166
+ default:
2167
+ return localize.day(dayOfWeek, {
2168
+ width: "wide",
2169
+ context: "formatting",
2170
+ });
2171
+ }
2172
+ },
2173
+
2174
+ // Stand-alone local day of week
2175
+ c: function (date, token, localize, options) {
2176
+ const dayOfWeek = date.getDay();
2177
+ const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
2178
+ switch (token) {
2179
+ // Numerical value (same as in `e`)
2180
+ case "c":
2181
+ return String(localDayOfWeek);
2182
+ // Padded numerical value
2183
+ case "cc":
2184
+ return addLeadingZeros(localDayOfWeek, token.length);
2185
+ // 1st, 2nd, ..., 7th
2186
+ case "co":
2187
+ return localize.ordinalNumber(localDayOfWeek, { unit: "day" });
2188
+ case "ccc":
2189
+ return localize.day(dayOfWeek, {
2190
+ width: "abbreviated",
2191
+ context: "standalone",
2192
+ });
2193
+ // T
2194
+ case "ccccc":
2195
+ return localize.day(dayOfWeek, {
2196
+ width: "narrow",
2197
+ context: "standalone",
2198
+ });
2199
+ // Tu
2200
+ case "cccccc":
2201
+ return localize.day(dayOfWeek, {
2202
+ width: "short",
2203
+ context: "standalone",
2204
+ });
2205
+ // Tuesday
2206
+ case "cccc":
2207
+ default:
2208
+ return localize.day(dayOfWeek, {
2209
+ width: "wide",
2210
+ context: "standalone",
2211
+ });
2212
+ }
2213
+ },
2214
+
2215
+ // ISO day of week
2216
+ i: function (date, token, localize) {
2217
+ const dayOfWeek = date.getDay();
2218
+ const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
2219
+ switch (token) {
2220
+ // 2
2221
+ case "i":
2222
+ return String(isoDayOfWeek);
2223
+ // 02
2224
+ case "ii":
2225
+ return addLeadingZeros(isoDayOfWeek, token.length);
2226
+ // 2nd
2227
+ case "io":
2228
+ return localize.ordinalNumber(isoDayOfWeek, { unit: "day" });
2229
+ // Tue
2230
+ case "iii":
2231
+ return localize.day(dayOfWeek, {
2232
+ width: "abbreviated",
2233
+ context: "formatting",
2234
+ });
2235
+ // T
2236
+ case "iiiii":
2237
+ return localize.day(dayOfWeek, {
2238
+ width: "narrow",
2239
+ context: "formatting",
2240
+ });
2241
+ // Tu
2242
+ case "iiiiii":
2243
+ return localize.day(dayOfWeek, {
2244
+ width: "short",
2245
+ context: "formatting",
2246
+ });
2247
+ // Tuesday
2248
+ case "iiii":
2249
+ default:
2250
+ return localize.day(dayOfWeek, {
2251
+ width: "wide",
2252
+ context: "formatting",
2253
+ });
2254
+ }
2255
+ },
2256
+
2257
+ // AM or PM
2258
+ a: function (date, token, localize) {
2259
+ const hours = date.getHours();
2260
+ const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
2261
+
2262
+ switch (token) {
2263
+ case "a":
2264
+ case "aa":
2265
+ return localize.dayPeriod(dayPeriodEnumValue, {
2266
+ width: "abbreviated",
2267
+ context: "formatting",
2268
+ });
2269
+ case "aaa":
2270
+ return localize
2271
+ .dayPeriod(dayPeriodEnumValue, {
2272
+ width: "abbreviated",
2273
+ context: "formatting",
2274
+ })
2275
+ .toLowerCase();
2276
+ case "aaaaa":
2277
+ return localize.dayPeriod(dayPeriodEnumValue, {
2278
+ width: "narrow",
2279
+ context: "formatting",
2280
+ });
2281
+ case "aaaa":
2282
+ default:
2283
+ return localize.dayPeriod(dayPeriodEnumValue, {
2284
+ width: "wide",
2285
+ context: "formatting",
2286
+ });
2287
+ }
2288
+ },
2289
+
2290
+ // AM, PM, midnight, noon
2291
+ b: function (date, token, localize) {
2292
+ const hours = date.getHours();
2293
+ let dayPeriodEnumValue;
2294
+ if (hours === 12) {
2295
+ dayPeriodEnumValue = dayPeriodEnum.noon;
2296
+ } else if (hours === 0) {
2297
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
2298
+ } else {
2299
+ dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
2300
+ }
2301
+
2302
+ switch (token) {
2303
+ case "b":
2304
+ case "bb":
2305
+ return localize.dayPeriod(dayPeriodEnumValue, {
2306
+ width: "abbreviated",
2307
+ context: "formatting",
2308
+ });
2309
+ case "bbb":
2310
+ return localize
2311
+ .dayPeriod(dayPeriodEnumValue, {
2312
+ width: "abbreviated",
2313
+ context: "formatting",
2314
+ })
2315
+ .toLowerCase();
2316
+ case "bbbbb":
2317
+ return localize.dayPeriod(dayPeriodEnumValue, {
2318
+ width: "narrow",
2319
+ context: "formatting",
2320
+ });
2321
+ case "bbbb":
2322
+ default:
2323
+ return localize.dayPeriod(dayPeriodEnumValue, {
2324
+ width: "wide",
2325
+ context: "formatting",
2326
+ });
2327
+ }
2328
+ },
2329
+
2330
+ // in the morning, in the afternoon, in the evening, at night
2331
+ B: function (date, token, localize) {
2332
+ const hours = date.getHours();
2333
+ let dayPeriodEnumValue;
2334
+ if (hours >= 17) {
2335
+ dayPeriodEnumValue = dayPeriodEnum.evening;
2336
+ } else if (hours >= 12) {
2337
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
2338
+ } else if (hours >= 4) {
2339
+ dayPeriodEnumValue = dayPeriodEnum.morning;
2340
+ } else {
2341
+ dayPeriodEnumValue = dayPeriodEnum.night;
2342
+ }
2343
+
2344
+ switch (token) {
2345
+ case "B":
2346
+ case "BB":
2347
+ case "BBB":
2348
+ return localize.dayPeriod(dayPeriodEnumValue, {
2349
+ width: "abbreviated",
2350
+ context: "formatting",
2351
+ });
2352
+ case "BBBBB":
2353
+ return localize.dayPeriod(dayPeriodEnumValue, {
2354
+ width: "narrow",
2355
+ context: "formatting",
2356
+ });
2357
+ case "BBBB":
2358
+ default:
2359
+ return localize.dayPeriod(dayPeriodEnumValue, {
2360
+ width: "wide",
2361
+ context: "formatting",
2362
+ });
2363
+ }
2364
+ },
2365
+
2366
+ // Hour [1-12]
2367
+ h: function (date, token, localize) {
2368
+ if (token === "ho") {
2369
+ let hours = date.getHours() % 12;
2370
+ if (hours === 0) hours = 12;
2371
+ return localize.ordinalNumber(hours, { unit: "hour" });
2372
+ }
2373
+
2374
+ return lightFormatters.h(date, token);
2375
+ },
2376
+
2377
+ // Hour [0-23]
2378
+ H: function (date, token, localize) {
2379
+ if (token === "Ho") {
2380
+ return localize.ordinalNumber(date.getHours(), { unit: "hour" });
2381
+ }
2382
+
2383
+ return lightFormatters.H(date, token);
2384
+ },
2385
+
2386
+ // Hour [0-11]
2387
+ K: function (date, token, localize) {
2388
+ const hours = date.getHours() % 12;
2389
+
2390
+ if (token === "Ko") {
2391
+ return localize.ordinalNumber(hours, { unit: "hour" });
2392
+ }
2393
+
2394
+ return addLeadingZeros(hours, token.length);
2395
+ },
2396
+
2397
+ // Hour [1-24]
2398
+ k: function (date, token, localize) {
2399
+ let hours = date.getHours();
2400
+ if (hours === 0) hours = 24;
2401
+
2402
+ if (token === "ko") {
2403
+ return localize.ordinalNumber(hours, { unit: "hour" });
2404
+ }
2405
+
2406
+ return addLeadingZeros(hours, token.length);
2407
+ },
2408
+
2409
+ // Minute
2410
+ m: function (date, token, localize) {
2411
+ if (token === "mo") {
2412
+ return localize.ordinalNumber(date.getMinutes(), { unit: "minute" });
2413
+ }
2414
+
2415
+ return lightFormatters.m(date, token);
2416
+ },
2417
+
2418
+ // Second
2419
+ s: function (date, token, localize) {
2420
+ if (token === "so") {
2421
+ return localize.ordinalNumber(date.getSeconds(), { unit: "second" });
2422
+ }
2423
+
2424
+ return lightFormatters.s(date, token);
2425
+ },
2426
+
2427
+ // Fraction of second
2428
+ S: function (date, token) {
2429
+ return lightFormatters.S(date, token);
2430
+ },
2431
+
2432
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
2433
+ X: function (date, token, _localize) {
2434
+ const timezoneOffset = date.getTimezoneOffset();
2435
+
2436
+ if (timezoneOffset === 0) {
2437
+ return "Z";
2438
+ }
2439
+
2440
+ switch (token) {
2441
+ // Hours and optional minutes
2442
+ case "X":
2443
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
2444
+
2445
+ // Hours, minutes and optional seconds without `:` delimiter
2446
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2447
+ // so this token always has the same output as `XX`
2448
+ case "XXXX":
2449
+ case "XX": // Hours and minutes without `:` delimiter
2450
+ return formatTimezone(timezoneOffset);
2451
+
2452
+ // Hours, minutes and optional seconds with `:` delimiter
2453
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2454
+ // so this token always has the same output as `XXX`
2455
+ case "XXXXX":
2456
+ case "XXX": // Hours and minutes with `:` delimiter
2457
+ default:
2458
+ return formatTimezone(timezoneOffset, ":");
2459
+ }
2460
+ },
2461
+
2462
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
2463
+ x: function (date, token, _localize) {
2464
+ const timezoneOffset = date.getTimezoneOffset();
2465
+
2466
+ switch (token) {
2467
+ // Hours and optional minutes
2468
+ case "x":
2469
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
2470
+
2471
+ // Hours, minutes and optional seconds without `:` delimiter
2472
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2473
+ // so this token always has the same output as `xx`
2474
+ case "xxxx":
2475
+ case "xx": // Hours and minutes without `:` delimiter
2476
+ return formatTimezone(timezoneOffset);
2477
+
2478
+ // Hours, minutes and optional seconds with `:` delimiter
2479
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2480
+ // so this token always has the same output as `xxx`
2481
+ case "xxxxx":
2482
+ case "xxx": // Hours and minutes with `:` delimiter
2483
+ default:
2484
+ return formatTimezone(timezoneOffset, ":");
2485
+ }
2486
+ },
2487
+
2488
+ // Timezone (GMT)
2489
+ O: function (date, token, _localize) {
2490
+ const timezoneOffset = date.getTimezoneOffset();
2491
+
2492
+ switch (token) {
2493
+ // Short
2494
+ case "O":
2495
+ case "OO":
2496
+ case "OOO":
2497
+ return "GMT" + formatTimezoneShort(timezoneOffset, ":");
2498
+ // Long
2499
+ case "OOOO":
2500
+ default:
2501
+ return "GMT" + formatTimezone(timezoneOffset, ":");
2502
+ }
2503
+ },
2504
+
2505
+ // Timezone (specific non-location)
2506
+ z: function (date, token, _localize) {
2507
+ const timezoneOffset = date.getTimezoneOffset();
2508
+
2509
+ switch (token) {
2510
+ // Short
2511
+ case "z":
2512
+ case "zz":
2513
+ case "zzz":
2514
+ return "GMT" + formatTimezoneShort(timezoneOffset, ":");
2515
+ // Long
2516
+ case "zzzz":
2517
+ default:
2518
+ return "GMT" + formatTimezone(timezoneOffset, ":");
2519
+ }
2520
+ },
2521
+
2522
+ // Seconds timestamp
2523
+ t: function (date, token, _localize) {
2524
+ const timestamp = Math.trunc(date.getTime() / 1000);
2525
+ return addLeadingZeros(timestamp, token.length);
2526
+ },
2527
+
2528
+ // Milliseconds timestamp
2529
+ T: function (date, token, _localize) {
2530
+ const timestamp = date.getTime();
2531
+ return addLeadingZeros(timestamp, token.length);
2532
+ },
2533
+ };
2534
+
2535
+ function formatTimezoneShort(offset, delimiter = "") {
2536
+ const sign = offset > 0 ? "-" : "+";
2537
+ const absOffset = Math.abs(offset);
2538
+ const hours = Math.trunc(absOffset / 60);
2539
+ const minutes = absOffset % 60;
2540
+ if (minutes === 0) {
2541
+ return sign + String(hours);
2542
+ }
2543
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
2544
+ }
2545
+
2546
+ function formatTimezoneWithOptionalMinutes(offset, delimiter) {
2547
+ if (offset % 60 === 0) {
2548
+ const sign = offset > 0 ? "-" : "+";
2549
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
2550
+ }
2551
+ return formatTimezone(offset, delimiter);
2552
+ }
2553
+
2554
+ function formatTimezone(offset, delimiter = "") {
2555
+ const sign = offset > 0 ? "-" : "+";
2556
+ const absOffset = Math.abs(offset);
2557
+ const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
2558
+ const minutes = addLeadingZeros(absOffset % 60, 2);
2559
+ return sign + hours + delimiter + minutes;
2560
+ }
2561
+
2562
+ const dateLongFormatter = (pattern, formatLong) => {
2563
+ switch (pattern) {
2564
+ case "P":
2565
+ return formatLong.date({ width: "short" });
2566
+ case "PP":
2567
+ return formatLong.date({ width: "medium" });
2568
+ case "PPP":
2569
+ return formatLong.date({ width: "long" });
2570
+ case "PPPP":
2571
+ default:
2572
+ return formatLong.date({ width: "full" });
2573
+ }
2574
+ };
2575
+
2576
+ const timeLongFormatter = (pattern, formatLong) => {
2577
+ switch (pattern) {
2578
+ case "p":
2579
+ return formatLong.time({ width: "short" });
2580
+ case "pp":
2581
+ return formatLong.time({ width: "medium" });
2582
+ case "ppp":
2583
+ return formatLong.time({ width: "long" });
2584
+ case "pppp":
2585
+ default:
2586
+ return formatLong.time({ width: "full" });
2587
+ }
2588
+ };
2589
+
2590
+ const dateTimeLongFormatter = (pattern, formatLong) => {
2591
+ const matchResult = pattern.match(/(P+)(p+)?/) || [];
2592
+ const datePattern = matchResult[1];
2593
+ const timePattern = matchResult[2];
2594
+
2595
+ if (!timePattern) {
2596
+ return dateLongFormatter(pattern, formatLong);
2597
+ }
2598
+
2599
+ let dateTimeFormat;
2600
+
2601
+ switch (datePattern) {
2602
+ case "P":
2603
+ dateTimeFormat = formatLong.dateTime({ width: "short" });
2604
+ break;
2605
+ case "PP":
2606
+ dateTimeFormat = formatLong.dateTime({ width: "medium" });
2607
+ break;
2608
+ case "PPP":
2609
+ dateTimeFormat = formatLong.dateTime({ width: "long" });
2610
+ break;
2611
+ case "PPPP":
2612
+ default:
2613
+ dateTimeFormat = formatLong.dateTime({ width: "full" });
2614
+ break;
2615
+ }
2616
+
2617
+ return dateTimeFormat
2618
+ .replace("{{date}}", dateLongFormatter(datePattern, formatLong))
2619
+ .replace("{{time}}", timeLongFormatter(timePattern, formatLong));
2620
+ };
2621
+
2622
+ const longFormatters = {
2623
+ p: timeLongFormatter,
2624
+ P: dateTimeLongFormatter,
2625
+ };
2626
+
2627
+ const dayOfYearTokenRE = /^D+$/;
2628
+ const weekYearTokenRE = /^Y+$/;
2629
+
2630
+ const throwTokens = ["D", "DD", "YY", "YYYY"];
2631
+
2632
+ function isProtectedDayOfYearToken(token) {
2633
+ return dayOfYearTokenRE.test(token);
2634
+ }
2635
+
2636
+ function isProtectedWeekYearToken(token) {
2637
+ return weekYearTokenRE.test(token);
2638
+ }
2639
+
2640
+ function warnOrThrowProtectedError(token, format, input) {
2641
+ const _message = message(token, format, input);
2642
+ console.warn(_message);
2643
+ if (throwTokens.includes(token)) throw new RangeError(_message);
2644
+ }
2645
+
2646
+ function message(token, format, input) {
2647
+ const subject = token[0] === "Y" ? "years" : "days of the month";
2648
+ return `Use \`${token.toLowerCase()}\` instead of \`${token}\` (in \`${format}\`) for formatting ${subject} to the input \`${input}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;
2649
+ }
2650
+
2651
+ // This RegExp consists of three parts separated by `|`:
2652
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2653
+ // (one of the certain letters followed by `o`)
2654
+ // - (\w)\1* matches any sequences of the same letter
2655
+ // - '' matches two quote characters in a row
2656
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2657
+ // except a single quote symbol, which ends the sequence.
2658
+ // Two quote characters do not end the sequence.
2659
+ // If there is no matching single quote
2660
+ // then the sequence will continue until the end of the string.
2661
+ // - . matches any single character unmatched by previous parts of the RegExps
2662
+ const formattingTokensRegExp =
2663
+ /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
2664
+
2665
+ // This RegExp catches symbols escaped by quotes, and also
2666
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2667
+ const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2668
+
2669
+ const escapedStringRegExp = /^'([^]*?)'?$/;
2670
+ const doubleQuoteRegExp = /''/g;
2671
+ const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2672
+
2673
+ /**
2674
+ * The {@link format} function options.
2675
+ */
2676
+
2677
+ /**
2678
+ * @name format
2679
+ * @alias formatDate
2680
+ * @category Common Helpers
2681
+ * @summary Format the date.
2682
+ *
2683
+ * @description
2684
+ * Return the formatted date string in the given format. The result may vary by locale.
2685
+ *
2686
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2687
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2688
+ *
2689
+ * The characters wrapped between two single quotes characters (') are escaped.
2690
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2691
+ * (see the last example)
2692
+ *
2693
+ * Format of the string is based on Unicode Technical Standard #35:
2694
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2695
+ * with a few additions (see note 7 below the table).
2696
+ *
2697
+ * Accepted patterns:
2698
+ * | Unit | Pattern | Result examples | Notes |
2699
+ * |---------------------------------|---------|-----------------------------------|-------|
2700
+ * | Era | G..GGG | AD, BC | |
2701
+ * | | GGGG | Anno Domini, Before Christ | 2 |
2702
+ * | | GGGGG | A, B | |
2703
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
2704
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
2705
+ * | | yy | 44, 01, 00, 17 | 5 |
2706
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
2707
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
2708
+ * | | yyyyy | ... | 3,5 |
2709
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
2710
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
2711
+ * | | YY | 44, 01, 00, 17 | 5,8 |
2712
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
2713
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
2714
+ * | | YYYYY | ... | 3,5 |
2715
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
2716
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
2717
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
2718
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
2719
+ * | | RRRRR | ... | 3,5,7 |
2720
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
2721
+ * | | uu | -43, 01, 1900, 2017 | 5 |
2722
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
2723
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
2724
+ * | | uuuuu | ... | 3,5 |
2725
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
2726
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
2727
+ * | | QQ | 01, 02, 03, 04 | |
2728
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
2729
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2730
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
2731
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
2732
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
2733
+ * | | qq | 01, 02, 03, 04 | |
2734
+ * | | qqq | Q1, Q2, Q3, Q4 | |
2735
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2736
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
2737
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
2738
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
2739
+ * | | MM | 01, 02, ..., 12 | |
2740
+ * | | MMM | Jan, Feb, ..., Dec | |
2741
+ * | | MMMM | January, February, ..., December | 2 |
2742
+ * | | MMMMM | J, F, ..., D | |
2743
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
2744
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
2745
+ * | | LL | 01, 02, ..., 12 | |
2746
+ * | | LLL | Jan, Feb, ..., Dec | |
2747
+ * | | LLLL | January, February, ..., December | 2 |
2748
+ * | | LLLLL | J, F, ..., D | |
2749
+ * | Local week of year | w | 1, 2, ..., 53 | |
2750
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
2751
+ * | | ww | 01, 02, ..., 53 | |
2752
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
2753
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
2754
+ * | | II | 01, 02, ..., 53 | 7 |
2755
+ * | Day of month | d | 1, 2, ..., 31 | |
2756
+ * | | do | 1st, 2nd, ..., 31st | 7 |
2757
+ * | | dd | 01, 02, ..., 31 | |
2758
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
2759
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
2760
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
2761
+ * | | DDD | 001, 002, ..., 365, 366 | |
2762
+ * | | DDDD | ... | 3 |
2763
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
2764
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2765
+ * | | EEEEE | M, T, W, T, F, S, S | |
2766
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2767
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
2768
+ * | | io | 1st, 2nd, ..., 7th | 7 |
2769
+ * | | ii | 01, 02, ..., 07 | 7 |
2770
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
2771
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
2772
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
2773
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
2774
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
2775
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
2776
+ * | | ee | 02, 03, ..., 01 | |
2777
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
2778
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2779
+ * | | eeeee | M, T, W, T, F, S, S | |
2780
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2781
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
2782
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
2783
+ * | | cc | 02, 03, ..., 01 | |
2784
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
2785
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2786
+ * | | ccccc | M, T, W, T, F, S, S | |
2787
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2788
+ * | AM, PM | a..aa | AM, PM | |
2789
+ * | | aaa | am, pm | |
2790
+ * | | aaaa | a.m., p.m. | 2 |
2791
+ * | | aaaaa | a, p | |
2792
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
2793
+ * | | bbb | am, pm, noon, midnight | |
2794
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
2795
+ * | | bbbbb | a, p, n, mi | |
2796
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
2797
+ * | | BBBB | at night, in the morning, ... | 2 |
2798
+ * | | BBBBB | at night, in the morning, ... | |
2799
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
2800
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
2801
+ * | | hh | 01, 02, ..., 11, 12 | |
2802
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
2803
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
2804
+ * | | HH | 00, 01, 02, ..., 23 | |
2805
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
2806
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
2807
+ * | | KK | 01, 02, ..., 11, 00 | |
2808
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
2809
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
2810
+ * | | kk | 24, 01, 02, ..., 23 | |
2811
+ * | Minute | m | 0, 1, ..., 59 | |
2812
+ * | | mo | 0th, 1st, ..., 59th | 7 |
2813
+ * | | mm | 00, 01, ..., 59 | |
2814
+ * | Second | s | 0, 1, ..., 59 | |
2815
+ * | | so | 0th, 1st, ..., 59th | 7 |
2816
+ * | | ss | 00, 01, ..., 59 | |
2817
+ * | Fraction of second | S | 0, 1, ..., 9 | |
2818
+ * | | SS | 00, 01, ..., 99 | |
2819
+ * | | SSS | 000, 001, ..., 999 | |
2820
+ * | | SSSS | ... | 3 |
2821
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
2822
+ * | | XX | -0800, +0530, Z | |
2823
+ * | | XXX | -08:00, +05:30, Z | |
2824
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
2825
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2826
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
2827
+ * | | xx | -0800, +0530, +0000 | |
2828
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
2829
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
2830
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2831
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
2832
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
2833
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
2834
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
2835
+ * | Seconds timestamp | t | 512969520 | 7 |
2836
+ * | | tt | ... | 3,7 |
2837
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
2838
+ * | | TT | ... | 3,7 |
2839
+ * | Long localized date | P | 04/29/1453 | 7 |
2840
+ * | | PP | Apr 29, 1453 | 7 |
2841
+ * | | PPP | April 29th, 1453 | 7 |
2842
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
2843
+ * | Long localized time | p | 12:00 AM | 7 |
2844
+ * | | pp | 12:00:00 AM | 7 |
2845
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
2846
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
2847
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
2848
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
2849
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
2850
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
2851
+ * Notes:
2852
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2853
+ * are the same as "stand-alone" units, but are different in some languages.
2854
+ * "Formatting" units are declined according to the rules of the language
2855
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2856
+ *
2857
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2858
+ *
2859
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2860
+ *
2861
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2862
+ * the single quote characters (see below).
2863
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2864
+ * the output will be the same as default pattern for this unit, usually
2865
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2866
+ * are marked with "2" in the last column of the table.
2867
+ *
2868
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2869
+ *
2870
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2871
+ *
2872
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2873
+ *
2874
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2875
+ *
2876
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2877
+ *
2878
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2879
+ * The output will be padded with zeros to match the length of the pattern.
2880
+ *
2881
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2882
+ *
2883
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2884
+ * These tokens represent the shortest form of the quarter.
2885
+ *
2886
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2887
+ *
2888
+ * | Year | `y` | `u` |
2889
+ * |------|-----|-----|
2890
+ * | AC 1 | 1 | 1 |
2891
+ * | BC 1 | 1 | 0 |
2892
+ * | BC 2 | 2 | -1 |
2893
+ *
2894
+ * Also `yy` always returns the last two digits of a year,
2895
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2896
+ *
2897
+ * | Year | `yy` | `uu` |
2898
+ * |------|------|------|
2899
+ * | 1 | 01 | 01 |
2900
+ * | 14 | 14 | 14 |
2901
+ * | 376 | 76 | 376 |
2902
+ * | 1453 | 53 | 1453 |
2903
+ *
2904
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2905
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2906
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)
2907
+ * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).
2908
+ *
2909
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2910
+ * so right now these tokens fall back to GMT timezones.
2911
+ *
2912
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2913
+ * - `i`: ISO day of week
2914
+ * - `I`: ISO week of year
2915
+ * - `R`: ISO week-numbering year
2916
+ * - `t`: seconds timestamp
2917
+ * - `T`: milliseconds timestamp
2918
+ * - `o`: ordinal number modifier
2919
+ * - `P`: long localized date
2920
+ * - `p`: long localized time
2921
+ *
2922
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2923
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2924
+ *
2925
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2926
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2927
+ *
2928
+ * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
2929
+ *
2930
+ * @param date - The original date
2931
+ * @param format - The string of tokens
2932
+ * @param options - An object with options
2933
+ *
2934
+ * @returns The formatted date string
2935
+ *
2936
+ * @throws `date` must not be Invalid Date
2937
+ * @throws `options.locale` must contain `localize` property
2938
+ * @throws `options.locale` must contain `formatLong` property
2939
+ * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2940
+ * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2941
+ * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2942
+ * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2943
+ * @throws format string contains an unescaped latin alphabet character
2944
+ *
2945
+ * @example
2946
+ * // Represent 11 February 2014 in middle-endian format:
2947
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2948
+ * //=> '02/11/2014'
2949
+ *
2950
+ * @example
2951
+ * // Represent 2 July 2014 in Esperanto:
2952
+ * import { eoLocale } from 'date-fns/locale/eo'
2953
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2954
+ * locale: eoLocale
2955
+ * })
2956
+ * //=> '2-a de julio 2014'
2957
+ *
2958
+ * @example
2959
+ * // Escape string by single quote characters:
2960
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2961
+ * //=> "3 o'clock"
2962
+ */
2963
+ function format(date, formatStr, options) {
2964
+ const defaultOptions = getDefaultOptions();
2965
+ const locale = defaultOptions.locale ?? enUS;
2966
+
2967
+ const firstWeekContainsDate =
2968
+ defaultOptions.firstWeekContainsDate ??
2969
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
2970
+ 1;
2971
+
2972
+ const weekStartsOn =
2973
+ defaultOptions.weekStartsOn ??
2974
+ defaultOptions.locale?.options?.weekStartsOn ??
2975
+ 0;
2976
+
2977
+ const originalDate = toDate(date);
2978
+
2979
+ if (!isValid(originalDate)) {
2980
+ throw new RangeError("Invalid time value");
2981
+ }
2982
+
2983
+ let parts = formatStr
2984
+ .match(longFormattingTokensRegExp)
2985
+ .map((substring) => {
2986
+ const firstCharacter = substring[0];
2987
+ if (firstCharacter === "p" || firstCharacter === "P") {
2988
+ const longFormatter = longFormatters[firstCharacter];
2989
+ return longFormatter(substring, locale.formatLong);
2990
+ }
2991
+ return substring;
2992
+ })
2993
+ .join("")
2994
+ .match(formattingTokensRegExp)
2995
+ .map((substring) => {
2996
+ // Replace two single quote characters with one single quote character
2997
+ if (substring === "''") {
2998
+ return { isToken: false, value: "'" };
2999
+ }
3000
+
3001
+ const firstCharacter = substring[0];
3002
+ if (firstCharacter === "'") {
3003
+ return { isToken: false, value: cleanEscapedString(substring) };
3004
+ }
3005
+
3006
+ if (formatters[firstCharacter]) {
3007
+ return { isToken: true, value: substring };
3008
+ }
3009
+
3010
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
3011
+ throw new RangeError(
3012
+ "Format string contains an unescaped latin alphabet character `" +
3013
+ firstCharacter +
3014
+ "`",
3015
+ );
3016
+ }
3017
+
3018
+ return { isToken: false, value: substring };
3019
+ });
3020
+
3021
+ // invoke localize preprocessor (only for french locales at the moment)
3022
+ if (locale.localize.preprocessor) {
3023
+ parts = locale.localize.preprocessor(originalDate, parts);
3024
+ }
3025
+
3026
+ const formatterOptions = {
3027
+ firstWeekContainsDate,
3028
+ weekStartsOn,
3029
+ locale,
3030
+ };
3031
+
3032
+ return parts
3033
+ .map((part) => {
3034
+ if (!part.isToken) return part.value;
3035
+
3036
+ const token = part.value;
3037
+
3038
+ if (
3039
+ (isProtectedWeekYearToken(token)) ||
3040
+ (isProtectedDayOfYearToken(token))
3041
+ ) {
3042
+ warnOrThrowProtectedError(token, formatStr, String(date));
3043
+ }
3044
+
3045
+ const formatter = formatters[token[0]];
3046
+ return formatter(originalDate, token, locale.localize, formatterOptions);
3047
+ })
3048
+ .join("");
3049
+ }
3050
+
3051
+ function cleanEscapedString(input) {
3052
+ const matched = input.match(escapedStringRegExp);
3053
+
3054
+ if (!matched) {
3055
+ return input;
3056
+ }
3057
+
3058
+ return matched[1].replace(doubleQuoteRegExp, "'");
3059
+ }
3060
+
3061
+ class RestDataProvider extends Rest {
3062
+ changeQueue = [];
3063
+ _batchUrl;
3064
+ flushTimeout = null;
3065
+ constructor(url, config) {
3066
+ super(url);
3067
+ this._batchUrl = config?.batchURL;
3068
+ }
3069
+ getHandlers() {
3070
+ return {
3071
+ "add-task": {
3072
+ ignoreID: true,
3073
+ handler: async (ev) => {
3074
+ ev.task.parent = this.correctID(ev.task.parent);
3075
+ return this.sendBatch(`tasks`, "POST", {
3076
+ task: ev.task,
3077
+ mode: ev.mode,
3078
+ target: this.correctID(ev.target)
3079
+ });
3080
+ }
3081
+ },
3082
+ "update-task": {
3083
+ debounce: 500,
3084
+ handler: async (ev) => {
3085
+ const task = { ...ev.task };
3086
+ delete task.data;
3087
+ return this.sendBatch(`tasks/${ev.id}`, "PUT", task);
3088
+ }
3089
+ },
3090
+ "delete-task": {
3091
+ handler: async (ev) => this.sendBatch(`tasks/${ev.id}`, "DELETE")
3092
+ },
3093
+ "copy-task": {
3094
+ ignoreID: true,
3095
+ handler: async (ev) => {
3096
+ return this.sendBatch(`tasks/${ev.source}`, "PUT", {
3097
+ operation: "copy",
3098
+ id: ev.id,
3099
+ target: this.correctID(ev.target),
3100
+ mode: ev.mode,
3101
+ lazy: !!ev.lazy
3102
+ });
3103
+ }
3104
+ },
3105
+ "move-task": {
3106
+ handler: async (ev) => {
3107
+ if (!ev.inProgress) {
3108
+ return this.sendBatch(`tasks/${ev.id}`, "PUT", {
3109
+ operation: "move",
3110
+ target: ev.target,
3111
+ mode: ev.mode
3112
+ });
3113
+ }
3114
+ }
3115
+ },
3116
+ "add-link": {
3117
+ ignoreID: true,
3118
+ handler: async (ev) => {
3119
+ ev.link.source = this.correctID(ev.link.source);
3120
+ ev.link.target = this.correctID(ev.link.target);
3121
+ return this.sendBatch(`links`, "POST", ev.link);
3122
+ }
3123
+ },
3124
+ "update-link": {
3125
+ handler: async (ev) => this.sendBatch(`links/${ev.id}`, "PUT", ev.link)
3126
+ },
3127
+ "delete-link": {
3128
+ handler: async (ev) => this.sendBatch(`links/${ev.id}`, "DELETE")
3129
+ }
3130
+ };
3131
+ }
3132
+ async getData(id) {
3133
+ const tempId = id;
3134
+ id = this.getQueue().getId(id);
3135
+ const [tasksResponse, links] = await Promise.all([
3136
+ this.send(id ? `tasks/${id}` : "tasks", "GET"),
3137
+ this.send(id ? `links/${id}` : "links", "GET")
3138
+ ]);
3139
+ const tasks = this.parseDates(tasksResponse).map((t) => {
3140
+ if (t.parent == id) t.parent = tempId;
3141
+ return t;
3142
+ });
3143
+ return { tasks, links };
3144
+ }
3145
+ parseDates(data) {
3146
+ data.forEach((item) => {
3147
+ item.start = new Date(item.start);
3148
+ if (item.end) item.end = new Date(item.end);
3149
+ if (item.base_start) item.base_start = new Date(item.base_start);
3150
+ if (item.base_end) item.base_end = new Date(item.base_end);
3151
+ });
3152
+ return data;
3153
+ }
3154
+ formatDate(date) {
3155
+ return format(date, "yyyy-MM-dd HH:mm:ss");
3156
+ }
3157
+ async sendBatch(url, method, data, customHeaders) {
3158
+ if (this._batchUrl) {
3159
+ return this.sendBatchRequest(url, method, data, customHeaders);
3160
+ } else {
3161
+ return this.send(url, method, data, customHeaders);
3162
+ }
3163
+ }
3164
+ async sendBatchRequest(url, method, data, customHeaders) {
3165
+ this.changeQueue.push({ url, method, data });
3166
+ if (this.flushTimeout) {
3167
+ clearTimeout(this.flushTimeout);
3168
+ }
3169
+ return new Promise((resolve) => {
3170
+ this.flushTimeout = setTimeout(async () => {
3171
+ if (this.changeQueue.length > 1) {
3172
+ const batchData = this.changeQueue.map((req) => {
3173
+ return {
3174
+ url: req.url,
3175
+ method: req.method,
3176
+ data: {
3177
+ ...req.data
3178
+ }
3179
+ };
3180
+ });
3181
+ this.changeQueue = [];
3182
+ const result = await this.send(
3183
+ this._batchUrl,
3184
+ "POST",
3185
+ batchData
3186
+ );
3187
+ resolve(result);
3188
+ } else {
3189
+ this.changeQueue = [];
3190
+ const result = await this.send(
3191
+ url,
3192
+ method,
3193
+ data,
3194
+ customHeaders
3195
+ );
3196
+ resolve(result);
3197
+ }
3198
+ }, 10);
3199
+ });
3200
+ }
3201
+ async send(url, method, data, customHeaders = {}) {
3202
+ const headers = {
3203
+ "Content-Type": "application/json",
3204
+ ...customHeaders
3205
+ };
3206
+ const req = {
3207
+ method,
3208
+ headers
3209
+ };
3210
+ if (data) {
3211
+ req.body = this.getPayload(data);
3212
+ }
3213
+ return fetch(`${this._url}/${url}`, req).then((res) => {
3214
+ return res.json().catch((error) => {
3215
+ console.error(error);
3216
+ });
3217
+ });
3218
+ }
3219
+ getPayload(obj) {
3220
+ const transformedObj = this.transformDates(obj);
3221
+ return JSON.stringify(transformedObj);
3222
+ }
3223
+ transformDates = (item) => {
3224
+ if (Array.isArray(item)) {
3225
+ return item.map(this.transformDates);
3226
+ }
3227
+ if (typeof item === "object" && item !== null) {
3228
+ for (const key in item) {
3229
+ const value = item[key];
3230
+ if (value instanceof Date) {
3231
+ item[key] = this.formatDate(value);
3232
+ } else if (typeof value === "object") {
3233
+ item[key] = this.transformDates(value);
3234
+ }
3235
+ }
3236
+ }
3237
+ return item;
3238
+ };
3239
+ correctID(localId) {
3240
+ const tempId = localId;
3241
+ const id = this.getQueue().getId(tempId);
3242
+ if (localId !== id) return id;
3243
+ return localId;
3244
+ }
3245
+ }
3246
+
3247
+ export { RestDataProvider };
3248
+ //# sourceMappingURL=index.js.map