@dialiq/calendar-component 1.0.0

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.
@@ -0,0 +1,3674 @@
1
+ import React, { useState, useCallback, useEffect } from 'react';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+
20
+ function __awaiter(thisArg, _arguments, P, generator) {
21
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22
+ return new (P || (P = Promise))(function (resolve, reject) {
23
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
24
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
25
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
26
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
27
+ });
28
+ }
29
+
30
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
31
+ var e = new Error(message);
32
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
33
+ };
34
+
35
+ /**
36
+ * @name toDate
37
+ * @category Common Helpers
38
+ * @summary Convert the given argument to an instance of Date.
39
+ *
40
+ * @description
41
+ * Convert the given argument to an instance of Date.
42
+ *
43
+ * If the argument is an instance of Date, the function returns its clone.
44
+ *
45
+ * If the argument is a number, it is treated as a timestamp.
46
+ *
47
+ * If the argument is none of the above, the function returns Invalid Date.
48
+ *
49
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
50
+ *
51
+ * @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).
52
+ *
53
+ * @param argument - The value to convert
54
+ *
55
+ * @returns The parsed date in the local time zone
56
+ *
57
+ * @example
58
+ * // Clone the date:
59
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
60
+ * //=> Tue Feb 11 2014 11:30:30
61
+ *
62
+ * @example
63
+ * // Convert the timestamp to date:
64
+ * const result = toDate(1392098430000)
65
+ * //=> Tue Feb 11 2014 11:30:30
66
+ */
67
+ function toDate(argument) {
68
+ const argStr = Object.prototype.toString.call(argument);
69
+
70
+ // Clone the date
71
+ if (
72
+ argument instanceof Date ||
73
+ (typeof argument === "object" && argStr === "[object Date]")
74
+ ) {
75
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
76
+ return new argument.constructor(+argument);
77
+ } else if (
78
+ typeof argument === "number" ||
79
+ argStr === "[object Number]" ||
80
+ typeof argument === "string" ||
81
+ argStr === "[object String]"
82
+ ) {
83
+ // TODO: Can we get rid of as?
84
+ return new Date(argument);
85
+ } else {
86
+ // TODO: Can we get rid of as?
87
+ return new Date(NaN);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * @name constructFrom
93
+ * @category Generic Helpers
94
+ * @summary Constructs a date using the reference date and the value
95
+ *
96
+ * @description
97
+ * The function constructs a new date using the constructor from the reference
98
+ * date and the given value. It helps to build generic functions that accept
99
+ * date extensions.
100
+ *
101
+ * It defaults to `Date` if the passed reference date is a number or a string.
102
+ *
103
+ * @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).
104
+ *
105
+ * @param date - The reference date to take constructor from
106
+ * @param value - The value to create the date
107
+ *
108
+ * @returns Date initialized using the given date and value
109
+ *
110
+ * @example
111
+ * import { constructFrom } from 'date-fns'
112
+ *
113
+ * // A function that clones a date preserving the original type
114
+ * function cloneDate<DateType extends Date(date: DateType): DateType {
115
+ * return constructFrom(
116
+ * date, // Use contrustor from the given date
117
+ * date.getTime() // Use the date value to create a new date
118
+ * )
119
+ * }
120
+ */
121
+ function constructFrom(date, value) {
122
+ if (date instanceof Date) {
123
+ return new date.constructor(value);
124
+ } else {
125
+ return new Date(value);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * @name addDays
131
+ * @category Day Helpers
132
+ * @summary Add the specified number of days to the given date.
133
+ *
134
+ * @description
135
+ * Add the specified number of days to the given date.
136
+ *
137
+ * @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).
138
+ *
139
+ * @param date - The date to be changed
140
+ * @param amount - The amount of days to be added.
141
+ *
142
+ * @returns The new date with the days added
143
+ *
144
+ * @example
145
+ * // Add 10 days to 1 September 2014:
146
+ * const result = addDays(new Date(2014, 8, 1), 10)
147
+ * //=> Thu Sep 11 2014 00:00:00
148
+ */
149
+ function addDays(date, amount) {
150
+ const _date = toDate(date);
151
+ if (isNaN(amount)) return constructFrom(date, NaN);
152
+ if (!amount) {
153
+ // If 0 days, no-op to avoid changing times in the hour before end of DST
154
+ return _date;
155
+ }
156
+ _date.setDate(_date.getDate() + amount);
157
+ return _date;
158
+ }
159
+
160
+ /**
161
+ * @name addMonths
162
+ * @category Month Helpers
163
+ * @summary Add the specified number of months to the given date.
164
+ *
165
+ * @description
166
+ * Add the specified number of months to the given date.
167
+ *
168
+ * @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).
169
+ *
170
+ * @param date - The date to be changed
171
+ * @param amount - The amount of months to be added.
172
+ *
173
+ * @returns The new date with the months added
174
+ *
175
+ * @example
176
+ * // Add 5 months to 1 September 2014:
177
+ * const result = addMonths(new Date(2014, 8, 1), 5)
178
+ * //=> Sun Feb 01 2015 00:00:00
179
+ *
180
+ * // Add one month to 30 January 2023:
181
+ * const result = addMonths(new Date(2023, 0, 30), 1)
182
+ * //=> Tue Feb 28 2023 00:00:00
183
+ */
184
+ function addMonths(date, amount) {
185
+ const _date = toDate(date);
186
+ if (isNaN(amount)) return constructFrom(date, NaN);
187
+ if (!amount) {
188
+ // If 0 months, no-op to avoid changing times in the hour before end of DST
189
+ return _date;
190
+ }
191
+ const dayOfMonth = _date.getDate();
192
+
193
+ // The JS Date object supports date math by accepting out-of-bounds values for
194
+ // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and
195
+ // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we
196
+ // want except that dates will wrap around the end of a month, meaning that
197
+ // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So
198
+ // we'll default to the end of the desired month by adding 1 to the desired
199
+ // month and using a date of 0 to back up one day to the end of the desired
200
+ // month.
201
+ const endOfDesiredMonth = constructFrom(date, _date.getTime());
202
+ endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);
203
+ const daysInMonth = endOfDesiredMonth.getDate();
204
+ if (dayOfMonth >= daysInMonth) {
205
+ // If we're already at the end of the month, then this is the correct date
206
+ // and we're done.
207
+ return endOfDesiredMonth;
208
+ } else {
209
+ // Otherwise, we now know that setting the original day-of-month value won't
210
+ // cause an overflow, so set the desired day-of-month. Note that we can't
211
+ // just set the date of `endOfDesiredMonth` because that object may have had
212
+ // its time changed in the unusual case where where a DST transition was on
213
+ // the last day of the month and its local time was in the hour skipped or
214
+ // repeated next to a DST transition. So we use `date` instead which is
215
+ // guaranteed to still have the original time.
216
+ _date.setFullYear(
217
+ endOfDesiredMonth.getFullYear(),
218
+ endOfDesiredMonth.getMonth(),
219
+ dayOfMonth,
220
+ );
221
+ return _date;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * @module constants
227
+ * @summary Useful constants
228
+ * @description
229
+ * Collection of useful date constants.
230
+ *
231
+ * The constants could be imported from `date-fns/constants`:
232
+ *
233
+ * ```ts
234
+ * import { maxTime, minTime } from "./constants/date-fns/constants";
235
+ *
236
+ * function isAllowedTime(time) {
237
+ * return time <= maxTime && time >= minTime;
238
+ * }
239
+ * ```
240
+ */
241
+
242
+
243
+ /**
244
+ * @constant
245
+ * @name millisecondsInWeek
246
+ * @summary Milliseconds in 1 week.
247
+ */
248
+ const millisecondsInWeek = 604800000;
249
+
250
+ /**
251
+ * @constant
252
+ * @name millisecondsInDay
253
+ * @summary Milliseconds in 1 day.
254
+ */
255
+ const millisecondsInDay = 86400000;
256
+
257
+ /**
258
+ * @constant
259
+ * @name millisecondsInMinute
260
+ * @summary Milliseconds in 1 minute
261
+ */
262
+ const millisecondsInMinute = 60000;
263
+
264
+ /**
265
+ * @constant
266
+ * @name millisecondsInHour
267
+ * @summary Milliseconds in 1 hour
268
+ */
269
+ const millisecondsInHour = 3600000;
270
+
271
+ let defaultOptions = {};
272
+
273
+ function getDefaultOptions() {
274
+ return defaultOptions;
275
+ }
276
+
277
+ /**
278
+ * The {@link startOfWeek} function options.
279
+ */
280
+
281
+ /**
282
+ * @name startOfWeek
283
+ * @category Week Helpers
284
+ * @summary Return the start of a week for the given date.
285
+ *
286
+ * @description
287
+ * Return the start of a week for the given date.
288
+ * The result will be in the local timezone.
289
+ *
290
+ * @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).
291
+ *
292
+ * @param date - The original date
293
+ * @param options - An object with options
294
+ *
295
+ * @returns The start of a week
296
+ *
297
+ * @example
298
+ * // The start of a week for 2 September 2014 11:55:00:
299
+ * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
300
+ * //=> Sun Aug 31 2014 00:00:00
301
+ *
302
+ * @example
303
+ * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
304
+ * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
305
+ * //=> Mon Sep 01 2014 00:00:00
306
+ */
307
+ function startOfWeek(date, options) {
308
+ const defaultOptions = getDefaultOptions();
309
+ const weekStartsOn =
310
+ options?.weekStartsOn ??
311
+ options?.locale?.options?.weekStartsOn ??
312
+ defaultOptions.weekStartsOn ??
313
+ defaultOptions.locale?.options?.weekStartsOn ??
314
+ 0;
315
+
316
+ const _date = toDate(date);
317
+ const day = _date.getDay();
318
+ const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
319
+
320
+ _date.setDate(_date.getDate() - diff);
321
+ _date.setHours(0, 0, 0, 0);
322
+ return _date;
323
+ }
324
+
325
+ /**
326
+ * @name startOfISOWeek
327
+ * @category ISO Week Helpers
328
+ * @summary Return the start of an ISO week for the given date.
329
+ *
330
+ * @description
331
+ * Return the start of an ISO week for the given date.
332
+ * The result will be in the local timezone.
333
+ *
334
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
335
+ *
336
+ * @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).
337
+ *
338
+ * @param date - The original date
339
+ *
340
+ * @returns The start of an ISO week
341
+ *
342
+ * @example
343
+ * // The start of an ISO week for 2 September 2014 11:55:00:
344
+ * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
345
+ * //=> Mon Sep 01 2014 00:00:00
346
+ */
347
+ function startOfISOWeek(date) {
348
+ return startOfWeek(date, { weekStartsOn: 1 });
349
+ }
350
+
351
+ /**
352
+ * @name getISOWeekYear
353
+ * @category ISO Week-Numbering Year Helpers
354
+ * @summary Get the ISO week-numbering year of the given date.
355
+ *
356
+ * @description
357
+ * Get the ISO week-numbering year of the given date,
358
+ * which always starts 3 days before the year's first Thursday.
359
+ *
360
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
361
+ *
362
+ * @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).
363
+ *
364
+ * @param date - The given date
365
+ *
366
+ * @returns The ISO week-numbering year
367
+ *
368
+ * @example
369
+ * // Which ISO-week numbering year is 2 January 2005?
370
+ * const result = getISOWeekYear(new Date(2005, 0, 2))
371
+ * //=> 2004
372
+ */
373
+ function getISOWeekYear(date) {
374
+ const _date = toDate(date);
375
+ const year = _date.getFullYear();
376
+
377
+ const fourthOfJanuaryOfNextYear = constructFrom(date, 0);
378
+ fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
379
+ fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
380
+ const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
381
+
382
+ const fourthOfJanuaryOfThisYear = constructFrom(date, 0);
383
+ fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
384
+ fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
385
+ const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
386
+
387
+ if (_date.getTime() >= startOfNextYear.getTime()) {
388
+ return year + 1;
389
+ } else if (_date.getTime() >= startOfThisYear.getTime()) {
390
+ return year;
391
+ } else {
392
+ return year - 1;
393
+ }
394
+ }
395
+
396
+ /**
397
+ * @name startOfDay
398
+ * @category Day Helpers
399
+ * @summary Return the start of a day for the given date.
400
+ *
401
+ * @description
402
+ * Return the start of a day for the given date.
403
+ * The result will be in the local timezone.
404
+ *
405
+ * @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).
406
+ *
407
+ * @param date - The original date
408
+ *
409
+ * @returns The start of a day
410
+ *
411
+ * @example
412
+ * // The start of a day for 2 September 2014 11:55:00:
413
+ * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))
414
+ * //=> Tue Sep 02 2014 00:00:00
415
+ */
416
+ function startOfDay(date) {
417
+ const _date = toDate(date);
418
+ _date.setHours(0, 0, 0, 0);
419
+ return _date;
420
+ }
421
+
422
+ /**
423
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
424
+ * They usually appear for dates that denote time before the timezones were introduced
425
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
426
+ * and GMT+01:00:00 after that date)
427
+ *
428
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
429
+ * which would lead to incorrect calculations.
430
+ *
431
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
432
+ */
433
+ function getTimezoneOffsetInMilliseconds(date) {
434
+ const _date = toDate(date);
435
+ const utcDate = new Date(
436
+ Date.UTC(
437
+ _date.getFullYear(),
438
+ _date.getMonth(),
439
+ _date.getDate(),
440
+ _date.getHours(),
441
+ _date.getMinutes(),
442
+ _date.getSeconds(),
443
+ _date.getMilliseconds(),
444
+ ),
445
+ );
446
+ utcDate.setUTCFullYear(_date.getFullYear());
447
+ return +date - +utcDate;
448
+ }
449
+
450
+ /**
451
+ * @name differenceInCalendarDays
452
+ * @category Day Helpers
453
+ * @summary Get the number of calendar days between the given dates.
454
+ *
455
+ * @description
456
+ * Get the number of calendar days between the given dates. This means that the times are removed
457
+ * from the dates and then the difference in days is calculated.
458
+ *
459
+ * @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).
460
+ *
461
+ * @param dateLeft - The later date
462
+ * @param dateRight - The earlier date
463
+ *
464
+ * @returns The number of calendar days
465
+ *
466
+ * @example
467
+ * // How many calendar days are between
468
+ * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?
469
+ * const result = differenceInCalendarDays(
470
+ * new Date(2012, 6, 2, 0, 0),
471
+ * new Date(2011, 6, 2, 23, 0)
472
+ * )
473
+ * //=> 366
474
+ * // How many calendar days are between
475
+ * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?
476
+ * const result = differenceInCalendarDays(
477
+ * new Date(2011, 6, 3, 0, 1),
478
+ * new Date(2011, 6, 2, 23, 59)
479
+ * )
480
+ * //=> 1
481
+ */
482
+ function differenceInCalendarDays(dateLeft, dateRight) {
483
+ const startOfDayLeft = startOfDay(dateLeft);
484
+ const startOfDayRight = startOfDay(dateRight);
485
+
486
+ const timestampLeft =
487
+ +startOfDayLeft - getTimezoneOffsetInMilliseconds(startOfDayLeft);
488
+ const timestampRight =
489
+ +startOfDayRight - getTimezoneOffsetInMilliseconds(startOfDayRight);
490
+
491
+ // Round the number of days to the nearest integer because the number of
492
+ // milliseconds in a day is not constant (e.g. it's different in the week of
493
+ // the daylight saving time clock shift).
494
+ return Math.round((timestampLeft - timestampRight) / millisecondsInDay);
495
+ }
496
+
497
+ /**
498
+ * @name startOfISOWeekYear
499
+ * @category ISO Week-Numbering Year Helpers
500
+ * @summary Return the start of an ISO week-numbering year for the given date.
501
+ *
502
+ * @description
503
+ * Return the start of an ISO week-numbering year,
504
+ * which always starts 3 days before the year's first Thursday.
505
+ * The result will be in the local timezone.
506
+ *
507
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
508
+ *
509
+ * @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).
510
+ *
511
+ * @param date - The original date
512
+ *
513
+ * @returns The start of an ISO week-numbering year
514
+ *
515
+ * @example
516
+ * // The start of an ISO week-numbering year for 2 July 2005:
517
+ * const result = startOfISOWeekYear(new Date(2005, 6, 2))
518
+ * //=> Mon Jan 03 2005 00:00:00
519
+ */
520
+ function startOfISOWeekYear(date) {
521
+ const year = getISOWeekYear(date);
522
+ const fourthOfJanuary = constructFrom(date, 0);
523
+ fourthOfJanuary.setFullYear(year, 0, 4);
524
+ fourthOfJanuary.setHours(0, 0, 0, 0);
525
+ return startOfISOWeek(fourthOfJanuary);
526
+ }
527
+
528
+ /**
529
+ * @name isSameDay
530
+ * @category Day Helpers
531
+ * @summary Are the given dates in the same day (and year and month)?
532
+ *
533
+ * @description
534
+ * Are the given dates in the same day (and year and month)?
535
+ *
536
+ * @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).
537
+ *
538
+ * @param dateLeft - The first date to check
539
+ * @param dateRight - The second date to check
540
+
541
+ * @returns The dates are in the same day (and year and month)
542
+ *
543
+ * @example
544
+ * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?
545
+ * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))
546
+ * //=> true
547
+ *
548
+ * @example
549
+ * // Are 4 September and 4 October in the same day?
550
+ * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))
551
+ * //=> false
552
+ *
553
+ * @example
554
+ * // Are 4 September, 2014 and 4 September, 2015 in the same day?
555
+ * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))
556
+ * //=> false
557
+ */
558
+ function isSameDay(dateLeft, dateRight) {
559
+ const dateLeftStartOfDay = startOfDay(dateLeft);
560
+ const dateRightStartOfDay = startOfDay(dateRight);
561
+
562
+ return +dateLeftStartOfDay === +dateRightStartOfDay;
563
+ }
564
+
565
+ /**
566
+ * @name isDate
567
+ * @category Common Helpers
568
+ * @summary Is the given value a date?
569
+ *
570
+ * @description
571
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
572
+ *
573
+ * @param value - The value to check
574
+ *
575
+ * @returns True if the given value is a date
576
+ *
577
+ * @example
578
+ * // For a valid date:
579
+ * const result = isDate(new Date())
580
+ * //=> true
581
+ *
582
+ * @example
583
+ * // For an invalid date:
584
+ * const result = isDate(new Date(NaN))
585
+ * //=> true
586
+ *
587
+ * @example
588
+ * // For some value:
589
+ * const result = isDate('2014-02-31')
590
+ * //=> false
591
+ *
592
+ * @example
593
+ * // For an object:
594
+ * const result = isDate({})
595
+ * //=> false
596
+ */
597
+ function isDate(value) {
598
+ return (
599
+ value instanceof Date ||
600
+ (typeof value === "object" &&
601
+ Object.prototype.toString.call(value) === "[object Date]")
602
+ );
603
+ }
604
+
605
+ /**
606
+ * @name isValid
607
+ * @category Common Helpers
608
+ * @summary Is the given date valid?
609
+ *
610
+ * @description
611
+ * Returns false if argument is Invalid Date and true otherwise.
612
+ * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)
613
+ * Invalid Date is a Date, whose time value is NaN.
614
+ *
615
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
616
+ *
617
+ * @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).
618
+ *
619
+ * @param date - The date to check
620
+ *
621
+ * @returns The date is valid
622
+ *
623
+ * @example
624
+ * // For the valid date:
625
+ * const result = isValid(new Date(2014, 1, 31))
626
+ * //=> true
627
+ *
628
+ * @example
629
+ * // For the value, convertable into a date:
630
+ * const result = isValid(1393804800000)
631
+ * //=> true
632
+ *
633
+ * @example
634
+ * // For the invalid date:
635
+ * const result = isValid(new Date(''))
636
+ * //=> false
637
+ */
638
+ function isValid(date) {
639
+ if (!isDate(date) && typeof date !== "number") {
640
+ return false;
641
+ }
642
+ const _date = toDate(date);
643
+ return !isNaN(Number(_date));
644
+ }
645
+
646
+ /**
647
+ * @name endOfMonth
648
+ * @category Month Helpers
649
+ * @summary Return the end of a month for the given date.
650
+ *
651
+ * @description
652
+ * Return the end of a month for the given date.
653
+ * The result will be in the local timezone.
654
+ *
655
+ * @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).
656
+ *
657
+ * @param date - The original date
658
+ *
659
+ * @returns The end of a month
660
+ *
661
+ * @example
662
+ * // The end of a month for 2 September 2014 11:55:00:
663
+ * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))
664
+ * //=> Tue Sep 30 2014 23:59:59.999
665
+ */
666
+ function endOfMonth(date) {
667
+ const _date = toDate(date);
668
+ const month = _date.getMonth();
669
+ _date.setFullYear(_date.getFullYear(), month + 1, 0);
670
+ _date.setHours(23, 59, 59, 999);
671
+ return _date;
672
+ }
673
+
674
+ /**
675
+ * @name startOfMonth
676
+ * @category Month Helpers
677
+ * @summary Return the start of a month for the given date.
678
+ *
679
+ * @description
680
+ * Return the start of a month for the given date.
681
+ * The result will be in the local timezone.
682
+ *
683
+ * @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).
684
+ *
685
+ * @param date - The original date
686
+ *
687
+ * @returns The start of a month
688
+ *
689
+ * @example
690
+ * // The start of a month for 2 September 2014 11:55:00:
691
+ * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))
692
+ * //=> Mon Sep 01 2014 00:00:00
693
+ */
694
+ function startOfMonth(date) {
695
+ const _date = toDate(date);
696
+ _date.setDate(1);
697
+ _date.setHours(0, 0, 0, 0);
698
+ return _date;
699
+ }
700
+
701
+ /**
702
+ * @name startOfYear
703
+ * @category Year Helpers
704
+ * @summary Return the start of a year for the given date.
705
+ *
706
+ * @description
707
+ * Return the start of a year for the given date.
708
+ * The result will be in the local timezone.
709
+ *
710
+ * @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).
711
+ *
712
+ * @param date - The original date
713
+ *
714
+ * @returns The start of a year
715
+ *
716
+ * @example
717
+ * // The start of a year for 2 September 2014 11:55:00:
718
+ * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))
719
+ * //=> Wed Jan 01 2014 00:00:00
720
+ */
721
+ function startOfYear(date) {
722
+ const cleanDate = toDate(date);
723
+ const _date = constructFrom(date, 0);
724
+ _date.setFullYear(cleanDate.getFullYear(), 0, 1);
725
+ _date.setHours(0, 0, 0, 0);
726
+ return _date;
727
+ }
728
+
729
+ /**
730
+ * The {@link endOfWeek} function options.
731
+ */
732
+
733
+ /**
734
+ * @name endOfWeek
735
+ * @category Week Helpers
736
+ * @summary Return the end of a week for the given date.
737
+ *
738
+ * @description
739
+ * Return the end of a week for the given date.
740
+ * The result will be in the local timezone.
741
+ *
742
+ * @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).
743
+ *
744
+ * @param date - The original date
745
+ * @param options - An object with options
746
+ *
747
+ * @returns The end of a week
748
+ *
749
+ * @example
750
+ * // The end of a week for 2 September 2014 11:55:00:
751
+ * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
752
+ * //=> Sat Sep 06 2014 23:59:59.999
753
+ *
754
+ * @example
755
+ * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
756
+ * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
757
+ * //=> Sun Sep 07 2014 23:59:59.999
758
+ */
759
+ function endOfWeek(date, options) {
760
+ const defaultOptions = getDefaultOptions();
761
+ const weekStartsOn =
762
+ options?.weekStartsOn ??
763
+ options?.locale?.options?.weekStartsOn ??
764
+ defaultOptions.weekStartsOn ??
765
+ defaultOptions.locale?.options?.weekStartsOn ??
766
+ 0;
767
+
768
+ const _date = toDate(date);
769
+ const day = _date.getDay();
770
+ const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
771
+
772
+ _date.setDate(_date.getDate() + diff);
773
+ _date.setHours(23, 59, 59, 999);
774
+ return _date;
775
+ }
776
+
777
+ const formatDistanceLocale = {
778
+ lessThanXSeconds: {
779
+ one: "less than a second",
780
+ other: "less than {{count}} seconds",
781
+ },
782
+
783
+ xSeconds: {
784
+ one: "1 second",
785
+ other: "{{count}} seconds",
786
+ },
787
+
788
+ halfAMinute: "half a minute",
789
+
790
+ lessThanXMinutes: {
791
+ one: "less than a minute",
792
+ other: "less than {{count}} minutes",
793
+ },
794
+
795
+ xMinutes: {
796
+ one: "1 minute",
797
+ other: "{{count}} minutes",
798
+ },
799
+
800
+ aboutXHours: {
801
+ one: "about 1 hour",
802
+ other: "about {{count}} hours",
803
+ },
804
+
805
+ xHours: {
806
+ one: "1 hour",
807
+ other: "{{count}} hours",
808
+ },
809
+
810
+ xDays: {
811
+ one: "1 day",
812
+ other: "{{count}} days",
813
+ },
814
+
815
+ aboutXWeeks: {
816
+ one: "about 1 week",
817
+ other: "about {{count}} weeks",
818
+ },
819
+
820
+ xWeeks: {
821
+ one: "1 week",
822
+ other: "{{count}} weeks",
823
+ },
824
+
825
+ aboutXMonths: {
826
+ one: "about 1 month",
827
+ other: "about {{count}} months",
828
+ },
829
+
830
+ xMonths: {
831
+ one: "1 month",
832
+ other: "{{count}} months",
833
+ },
834
+
835
+ aboutXYears: {
836
+ one: "about 1 year",
837
+ other: "about {{count}} years",
838
+ },
839
+
840
+ xYears: {
841
+ one: "1 year",
842
+ other: "{{count}} years",
843
+ },
844
+
845
+ overXYears: {
846
+ one: "over 1 year",
847
+ other: "over {{count}} years",
848
+ },
849
+
850
+ almostXYears: {
851
+ one: "almost 1 year",
852
+ other: "almost {{count}} years",
853
+ },
854
+ };
855
+
856
+ const formatDistance = (token, count, options) => {
857
+ let result;
858
+
859
+ const tokenValue = formatDistanceLocale[token];
860
+ if (typeof tokenValue === "string") {
861
+ result = tokenValue;
862
+ } else if (count === 1) {
863
+ result = tokenValue.one;
864
+ } else {
865
+ result = tokenValue.other.replace("{{count}}", count.toString());
866
+ }
867
+
868
+ if (options?.addSuffix) {
869
+ if (options.comparison && options.comparison > 0) {
870
+ return "in " + result;
871
+ } else {
872
+ return result + " ago";
873
+ }
874
+ }
875
+
876
+ return result;
877
+ };
878
+
879
+ function buildFormatLongFn(args) {
880
+ return (options = {}) => {
881
+ // TODO: Remove String()
882
+ const width = options.width ? String(options.width) : args.defaultWidth;
883
+ const format = args.formats[width] || args.formats[args.defaultWidth];
884
+ return format;
885
+ };
886
+ }
887
+
888
+ const dateFormats = {
889
+ full: "EEEE, MMMM do, y",
890
+ long: "MMMM do, y",
891
+ medium: "MMM d, y",
892
+ short: "MM/dd/yyyy",
893
+ };
894
+
895
+ const timeFormats = {
896
+ full: "h:mm:ss a zzzz",
897
+ long: "h:mm:ss a z",
898
+ medium: "h:mm:ss a",
899
+ short: "h:mm a",
900
+ };
901
+
902
+ const dateTimeFormats = {
903
+ full: "{{date}} 'at' {{time}}",
904
+ long: "{{date}} 'at' {{time}}",
905
+ medium: "{{date}}, {{time}}",
906
+ short: "{{date}}, {{time}}",
907
+ };
908
+
909
+ const formatLong = {
910
+ date: buildFormatLongFn({
911
+ formats: dateFormats,
912
+ defaultWidth: "full",
913
+ }),
914
+
915
+ time: buildFormatLongFn({
916
+ formats: timeFormats,
917
+ defaultWidth: "full",
918
+ }),
919
+
920
+ dateTime: buildFormatLongFn({
921
+ formats: dateTimeFormats,
922
+ defaultWidth: "full",
923
+ }),
924
+ };
925
+
926
+ const formatRelativeLocale = {
927
+ lastWeek: "'last' eeee 'at' p",
928
+ yesterday: "'yesterday at' p",
929
+ today: "'today at' p",
930
+ tomorrow: "'tomorrow at' p",
931
+ nextWeek: "eeee 'at' p",
932
+ other: "P",
933
+ };
934
+
935
+ const formatRelative = (token, _date, _baseDate, _options) =>
936
+ formatRelativeLocale[token];
937
+
938
+ /* eslint-disable no-unused-vars */
939
+
940
+ /**
941
+ * The localize function argument callback which allows to convert raw value to
942
+ * the actual type.
943
+ *
944
+ * @param value - The value to convert
945
+ *
946
+ * @returns The converted value
947
+ */
948
+
949
+ /**
950
+ * The map of localized values for each width.
951
+ */
952
+
953
+ /**
954
+ * The index type of the locale unit value. It types conversion of units of
955
+ * values that don't start at 0 (i.e. quarters).
956
+ */
957
+
958
+ /**
959
+ * Converts the unit value to the tuple of values.
960
+ */
961
+
962
+ /**
963
+ * The tuple of localized era values. The first element represents BC,
964
+ * the second element represents AD.
965
+ */
966
+
967
+ /**
968
+ * The tuple of localized quarter values. The first element represents Q1.
969
+ */
970
+
971
+ /**
972
+ * The tuple of localized day values. The first element represents Sunday.
973
+ */
974
+
975
+ /**
976
+ * The tuple of localized month values. The first element represents January.
977
+ */
978
+
979
+ function buildLocalizeFn(args) {
980
+ return (value, options) => {
981
+ const context = options?.context ? String(options.context) : "standalone";
982
+
983
+ let valuesArray;
984
+ if (context === "formatting" && args.formattingValues) {
985
+ const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
986
+ const width = options?.width ? String(options.width) : defaultWidth;
987
+
988
+ valuesArray =
989
+ args.formattingValues[width] || args.formattingValues[defaultWidth];
990
+ } else {
991
+ const defaultWidth = args.defaultWidth;
992
+ const width = options?.width ? String(options.width) : args.defaultWidth;
993
+
994
+ valuesArray = args.values[width] || args.values[defaultWidth];
995
+ }
996
+ const index = args.argumentCallback ? args.argumentCallback(value) : value;
997
+
998
+ // @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!
999
+ return valuesArray[index];
1000
+ };
1001
+ }
1002
+
1003
+ const eraValues = {
1004
+ narrow: ["B", "A"],
1005
+ abbreviated: ["BC", "AD"],
1006
+ wide: ["Before Christ", "Anno Domini"],
1007
+ };
1008
+
1009
+ const quarterValues = {
1010
+ narrow: ["1", "2", "3", "4"],
1011
+ abbreviated: ["Q1", "Q2", "Q3", "Q4"],
1012
+ wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
1013
+ };
1014
+
1015
+ // Note: in English, the names of days of the week and months are capitalized.
1016
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1017
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1018
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1019
+ const monthValues = {
1020
+ narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
1021
+ abbreviated: [
1022
+ "Jan",
1023
+ "Feb",
1024
+ "Mar",
1025
+ "Apr",
1026
+ "May",
1027
+ "Jun",
1028
+ "Jul",
1029
+ "Aug",
1030
+ "Sep",
1031
+ "Oct",
1032
+ "Nov",
1033
+ "Dec",
1034
+ ],
1035
+
1036
+ wide: [
1037
+ "January",
1038
+ "February",
1039
+ "March",
1040
+ "April",
1041
+ "May",
1042
+ "June",
1043
+ "July",
1044
+ "August",
1045
+ "September",
1046
+ "October",
1047
+ "November",
1048
+ "December",
1049
+ ],
1050
+ };
1051
+
1052
+ const dayValues = {
1053
+ narrow: ["S", "M", "T", "W", "T", "F", "S"],
1054
+ short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
1055
+ abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
1056
+ wide: [
1057
+ "Sunday",
1058
+ "Monday",
1059
+ "Tuesday",
1060
+ "Wednesday",
1061
+ "Thursday",
1062
+ "Friday",
1063
+ "Saturday",
1064
+ ],
1065
+ };
1066
+
1067
+ const dayPeriodValues = {
1068
+ narrow: {
1069
+ am: "a",
1070
+ pm: "p",
1071
+ midnight: "mi",
1072
+ noon: "n",
1073
+ morning: "morning",
1074
+ afternoon: "afternoon",
1075
+ evening: "evening",
1076
+ night: "night",
1077
+ },
1078
+ abbreviated: {
1079
+ am: "AM",
1080
+ pm: "PM",
1081
+ midnight: "midnight",
1082
+ noon: "noon",
1083
+ morning: "morning",
1084
+ afternoon: "afternoon",
1085
+ evening: "evening",
1086
+ night: "night",
1087
+ },
1088
+ wide: {
1089
+ am: "a.m.",
1090
+ pm: "p.m.",
1091
+ midnight: "midnight",
1092
+ noon: "noon",
1093
+ morning: "morning",
1094
+ afternoon: "afternoon",
1095
+ evening: "evening",
1096
+ night: "night",
1097
+ },
1098
+ };
1099
+
1100
+ const formattingDayPeriodValues = {
1101
+ narrow: {
1102
+ am: "a",
1103
+ pm: "p",
1104
+ midnight: "mi",
1105
+ noon: "n",
1106
+ morning: "in the morning",
1107
+ afternoon: "in the afternoon",
1108
+ evening: "in the evening",
1109
+ night: "at night",
1110
+ },
1111
+ abbreviated: {
1112
+ am: "AM",
1113
+ pm: "PM",
1114
+ midnight: "midnight",
1115
+ noon: "noon",
1116
+ morning: "in the morning",
1117
+ afternoon: "in the afternoon",
1118
+ evening: "in the evening",
1119
+ night: "at night",
1120
+ },
1121
+ wide: {
1122
+ am: "a.m.",
1123
+ pm: "p.m.",
1124
+ midnight: "midnight",
1125
+ noon: "noon",
1126
+ morning: "in the morning",
1127
+ afternoon: "in the afternoon",
1128
+ evening: "in the evening",
1129
+ night: "at night",
1130
+ },
1131
+ };
1132
+
1133
+ const ordinalNumber = (dirtyNumber, _options) => {
1134
+ const number = Number(dirtyNumber);
1135
+
1136
+ // If ordinal numbers depend on context, for example,
1137
+ // if they are different for different grammatical genders,
1138
+ // use `options.unit`.
1139
+ //
1140
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
1141
+ // 'day', 'hour', 'minute', 'second'.
1142
+
1143
+ const rem100 = number % 100;
1144
+ if (rem100 > 20 || rem100 < 10) {
1145
+ switch (rem100 % 10) {
1146
+ case 1:
1147
+ return number + "st";
1148
+ case 2:
1149
+ return number + "nd";
1150
+ case 3:
1151
+ return number + "rd";
1152
+ }
1153
+ }
1154
+ return number + "th";
1155
+ };
1156
+
1157
+ const localize = {
1158
+ ordinalNumber,
1159
+
1160
+ era: buildLocalizeFn({
1161
+ values: eraValues,
1162
+ defaultWidth: "wide",
1163
+ }),
1164
+
1165
+ quarter: buildLocalizeFn({
1166
+ values: quarterValues,
1167
+ defaultWidth: "wide",
1168
+ argumentCallback: (quarter) => quarter - 1,
1169
+ }),
1170
+
1171
+ month: buildLocalizeFn({
1172
+ values: monthValues,
1173
+ defaultWidth: "wide",
1174
+ }),
1175
+
1176
+ day: buildLocalizeFn({
1177
+ values: dayValues,
1178
+ defaultWidth: "wide",
1179
+ }),
1180
+
1181
+ dayPeriod: buildLocalizeFn({
1182
+ values: dayPeriodValues,
1183
+ defaultWidth: "wide",
1184
+ formattingValues: formattingDayPeriodValues,
1185
+ defaultFormattingWidth: "wide",
1186
+ }),
1187
+ };
1188
+
1189
+ function buildMatchFn(args) {
1190
+ return (string, options = {}) => {
1191
+ const width = options.width;
1192
+
1193
+ const matchPattern =
1194
+ (width && args.matchPatterns[width]) ||
1195
+ args.matchPatterns[args.defaultMatchWidth];
1196
+ const matchResult = string.match(matchPattern);
1197
+
1198
+ if (!matchResult) {
1199
+ return null;
1200
+ }
1201
+ const matchedString = matchResult[0];
1202
+
1203
+ const parsePatterns =
1204
+ (width && args.parsePatterns[width]) ||
1205
+ args.parsePatterns[args.defaultParseWidth];
1206
+
1207
+ const key = Array.isArray(parsePatterns)
1208
+ ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))
1209
+ : // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1210
+ findKey(parsePatterns, (pattern) => pattern.test(matchedString));
1211
+
1212
+ let value;
1213
+
1214
+ value = args.valueCallback ? args.valueCallback(key) : key;
1215
+ value = options.valueCallback
1216
+ ? // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1217
+ options.valueCallback(value)
1218
+ : value;
1219
+
1220
+ const rest = string.slice(matchedString.length);
1221
+
1222
+ return { value, rest };
1223
+ };
1224
+ }
1225
+
1226
+ function findKey(object, predicate) {
1227
+ for (const key in object) {
1228
+ if (
1229
+ Object.prototype.hasOwnProperty.call(object, key) &&
1230
+ predicate(object[key])
1231
+ ) {
1232
+ return key;
1233
+ }
1234
+ }
1235
+ return undefined;
1236
+ }
1237
+
1238
+ function findIndex(array, predicate) {
1239
+ for (let key = 0; key < array.length; key++) {
1240
+ if (predicate(array[key])) {
1241
+ return key;
1242
+ }
1243
+ }
1244
+ return undefined;
1245
+ }
1246
+
1247
+ function buildMatchPatternFn(args) {
1248
+ return (string, options = {}) => {
1249
+ const matchResult = string.match(args.matchPattern);
1250
+ if (!matchResult) return null;
1251
+ const matchedString = matchResult[0];
1252
+
1253
+ const parseResult = string.match(args.parsePattern);
1254
+ if (!parseResult) return null;
1255
+ let value = args.valueCallback
1256
+ ? args.valueCallback(parseResult[0])
1257
+ : parseResult[0];
1258
+
1259
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- I challange you to fix the type
1260
+ value = options.valueCallback ? options.valueCallback(value) : value;
1261
+
1262
+ const rest = string.slice(matchedString.length);
1263
+
1264
+ return { value, rest };
1265
+ };
1266
+ }
1267
+
1268
+ const matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
1269
+ const parseOrdinalNumberPattern = /\d+/i;
1270
+
1271
+ const matchEraPatterns = {
1272
+ narrow: /^(b|a)/i,
1273
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
1274
+ wide: /^(before christ|before common era|anno domini|common era)/i,
1275
+ };
1276
+ const parseEraPatterns = {
1277
+ any: [/^b/i, /^(a|c)/i],
1278
+ };
1279
+
1280
+ const matchQuarterPatterns = {
1281
+ narrow: /^[1234]/i,
1282
+ abbreviated: /^q[1234]/i,
1283
+ wide: /^[1234](th|st|nd|rd)? quarter/i,
1284
+ };
1285
+ const parseQuarterPatterns = {
1286
+ any: [/1/i, /2/i, /3/i, /4/i],
1287
+ };
1288
+
1289
+ const matchMonthPatterns = {
1290
+ narrow: /^[jfmasond]/i,
1291
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
1292
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,
1293
+ };
1294
+ const parseMonthPatterns = {
1295
+ narrow: [
1296
+ /^j/i,
1297
+ /^f/i,
1298
+ /^m/i,
1299
+ /^a/i,
1300
+ /^m/i,
1301
+ /^j/i,
1302
+ /^j/i,
1303
+ /^a/i,
1304
+ /^s/i,
1305
+ /^o/i,
1306
+ /^n/i,
1307
+ /^d/i,
1308
+ ],
1309
+
1310
+ any: [
1311
+ /^ja/i,
1312
+ /^f/i,
1313
+ /^mar/i,
1314
+ /^ap/i,
1315
+ /^may/i,
1316
+ /^jun/i,
1317
+ /^jul/i,
1318
+ /^au/i,
1319
+ /^s/i,
1320
+ /^o/i,
1321
+ /^n/i,
1322
+ /^d/i,
1323
+ ],
1324
+ };
1325
+
1326
+ const matchDayPatterns = {
1327
+ narrow: /^[smtwf]/i,
1328
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
1329
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
1330
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,
1331
+ };
1332
+ const parseDayPatterns = {
1333
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
1334
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],
1335
+ };
1336
+
1337
+ const matchDayPeriodPatterns = {
1338
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
1339
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,
1340
+ };
1341
+ const parseDayPeriodPatterns = {
1342
+ any: {
1343
+ am: /^a/i,
1344
+ pm: /^p/i,
1345
+ midnight: /^mi/i,
1346
+ noon: /^no/i,
1347
+ morning: /morning/i,
1348
+ afternoon: /afternoon/i,
1349
+ evening: /evening/i,
1350
+ night: /night/i,
1351
+ },
1352
+ };
1353
+
1354
+ const match = {
1355
+ ordinalNumber: buildMatchPatternFn({
1356
+ matchPattern: matchOrdinalNumberPattern,
1357
+ parsePattern: parseOrdinalNumberPattern,
1358
+ valueCallback: (value) => parseInt(value, 10),
1359
+ }),
1360
+
1361
+ era: buildMatchFn({
1362
+ matchPatterns: matchEraPatterns,
1363
+ defaultMatchWidth: "wide",
1364
+ parsePatterns: parseEraPatterns,
1365
+ defaultParseWidth: "any",
1366
+ }),
1367
+
1368
+ quarter: buildMatchFn({
1369
+ matchPatterns: matchQuarterPatterns,
1370
+ defaultMatchWidth: "wide",
1371
+ parsePatterns: parseQuarterPatterns,
1372
+ defaultParseWidth: "any",
1373
+ valueCallback: (index) => index + 1,
1374
+ }),
1375
+
1376
+ month: buildMatchFn({
1377
+ matchPatterns: matchMonthPatterns,
1378
+ defaultMatchWidth: "wide",
1379
+ parsePatterns: parseMonthPatterns,
1380
+ defaultParseWidth: "any",
1381
+ }),
1382
+
1383
+ day: buildMatchFn({
1384
+ matchPatterns: matchDayPatterns,
1385
+ defaultMatchWidth: "wide",
1386
+ parsePatterns: parseDayPatterns,
1387
+ defaultParseWidth: "any",
1388
+ }),
1389
+
1390
+ dayPeriod: buildMatchFn({
1391
+ matchPatterns: matchDayPeriodPatterns,
1392
+ defaultMatchWidth: "any",
1393
+ parsePatterns: parseDayPeriodPatterns,
1394
+ defaultParseWidth: "any",
1395
+ }),
1396
+ };
1397
+
1398
+ /**
1399
+ * @category Locales
1400
+ * @summary English locale (United States).
1401
+ * @language English
1402
+ * @iso-639-2 eng
1403
+ * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)
1404
+ * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)
1405
+ */
1406
+ const enUS = {
1407
+ code: "en-US",
1408
+ formatDistance: formatDistance,
1409
+ formatLong: formatLong,
1410
+ formatRelative: formatRelative,
1411
+ localize: localize,
1412
+ match: match,
1413
+ options: {
1414
+ weekStartsOn: 0 /* Sunday */,
1415
+ firstWeekContainsDate: 1,
1416
+ },
1417
+ };
1418
+
1419
+ /**
1420
+ * @name getDayOfYear
1421
+ * @category Day Helpers
1422
+ * @summary Get the day of the year of the given date.
1423
+ *
1424
+ * @description
1425
+ * Get the day of the year of the given date.
1426
+ *
1427
+ * @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).
1428
+ *
1429
+ * @param date - The given date
1430
+ *
1431
+ * @returns The day of year
1432
+ *
1433
+ * @example
1434
+ * // Which day of the year is 2 July 2014?
1435
+ * const result = getDayOfYear(new Date(2014, 6, 2))
1436
+ * //=> 183
1437
+ */
1438
+ function getDayOfYear(date) {
1439
+ const _date = toDate(date);
1440
+ const diff = differenceInCalendarDays(_date, startOfYear(_date));
1441
+ const dayOfYear = diff + 1;
1442
+ return dayOfYear;
1443
+ }
1444
+
1445
+ /**
1446
+ * @name getISOWeek
1447
+ * @category ISO Week Helpers
1448
+ * @summary Get the ISO week of the given date.
1449
+ *
1450
+ * @description
1451
+ * Get the ISO week of the given date.
1452
+ *
1453
+ * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
1454
+ *
1455
+ * @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).
1456
+ *
1457
+ * @param date - The given date
1458
+ *
1459
+ * @returns The ISO week
1460
+ *
1461
+ * @example
1462
+ * // Which week of the ISO-week numbering year is 2 January 2005?
1463
+ * const result = getISOWeek(new Date(2005, 0, 2))
1464
+ * //=> 53
1465
+ */
1466
+ function getISOWeek(date) {
1467
+ const _date = toDate(date);
1468
+ const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
1469
+
1470
+ // Round the number of weeks to the nearest integer because the number of
1471
+ // milliseconds in a week is not constant (e.g. it's different in the week of
1472
+ // the daylight saving time clock shift).
1473
+ return Math.round(diff / millisecondsInWeek) + 1;
1474
+ }
1475
+
1476
+ /**
1477
+ * The {@link getWeekYear} function options.
1478
+ */
1479
+
1480
+ /**
1481
+ * @name getWeekYear
1482
+ * @category Week-Numbering Year Helpers
1483
+ * @summary Get the local week-numbering year of the given date.
1484
+ *
1485
+ * @description
1486
+ * Get the local week-numbering year of the given date.
1487
+ * The exact calculation depends on the values of
1488
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1489
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1490
+ * the first week of the week-numbering year)
1491
+ *
1492
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1493
+ *
1494
+ * @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).
1495
+ *
1496
+ * @param date - The given date
1497
+ * @param options - An object with options.
1498
+ *
1499
+ * @returns The local week-numbering year
1500
+ *
1501
+ * @example
1502
+ * // Which week numbering year is 26 December 2004 with the default settings?
1503
+ * const result = getWeekYear(new Date(2004, 11, 26))
1504
+ * //=> 2005
1505
+ *
1506
+ * @example
1507
+ * // Which week numbering year is 26 December 2004 if week starts on Saturday?
1508
+ * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })
1509
+ * //=> 2004
1510
+ *
1511
+ * @example
1512
+ * // Which week numbering year is 26 December 2004 if the first week contains 4 January?
1513
+ * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })
1514
+ * //=> 2004
1515
+ */
1516
+ function getWeekYear(date, options) {
1517
+ const _date = toDate(date);
1518
+ const year = _date.getFullYear();
1519
+
1520
+ const defaultOptions = getDefaultOptions();
1521
+ const firstWeekContainsDate =
1522
+ options?.firstWeekContainsDate ??
1523
+ options?.locale?.options?.firstWeekContainsDate ??
1524
+ defaultOptions.firstWeekContainsDate ??
1525
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
1526
+ 1;
1527
+
1528
+ const firstWeekOfNextYear = constructFrom(date, 0);
1529
+ firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
1530
+ firstWeekOfNextYear.setHours(0, 0, 0, 0);
1531
+ const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
1532
+
1533
+ const firstWeekOfThisYear = constructFrom(date, 0);
1534
+ firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
1535
+ firstWeekOfThisYear.setHours(0, 0, 0, 0);
1536
+ const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
1537
+
1538
+ if (_date.getTime() >= startOfNextYear.getTime()) {
1539
+ return year + 1;
1540
+ } else if (_date.getTime() >= startOfThisYear.getTime()) {
1541
+ return year;
1542
+ } else {
1543
+ return year - 1;
1544
+ }
1545
+ }
1546
+
1547
+ /**
1548
+ * The {@link startOfWeekYear} function options.
1549
+ */
1550
+
1551
+ /**
1552
+ * @name startOfWeekYear
1553
+ * @category Week-Numbering Year Helpers
1554
+ * @summary Return the start of a local week-numbering year for the given date.
1555
+ *
1556
+ * @description
1557
+ * Return the start of a local week-numbering year.
1558
+ * The exact calculation depends on the values of
1559
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1560
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1561
+ * the first week of the week-numbering year)
1562
+ *
1563
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1564
+ *
1565
+ * @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).
1566
+ *
1567
+ * @param date - The original date
1568
+ * @param options - An object with options
1569
+ *
1570
+ * @returns The start of a week-numbering year
1571
+ *
1572
+ * @example
1573
+ * // The start of an a week-numbering year for 2 July 2005 with default settings:
1574
+ * const result = startOfWeekYear(new Date(2005, 6, 2))
1575
+ * //=> Sun Dec 26 2004 00:00:00
1576
+ *
1577
+ * @example
1578
+ * // The start of a week-numbering year for 2 July 2005
1579
+ * // if Monday is the first day of week
1580
+ * // and 4 January is always in the first week of the year:
1581
+ * const result = startOfWeekYear(new Date(2005, 6, 2), {
1582
+ * weekStartsOn: 1,
1583
+ * firstWeekContainsDate: 4
1584
+ * })
1585
+ * //=> Mon Jan 03 2005 00:00:00
1586
+ */
1587
+ function startOfWeekYear(date, options) {
1588
+ const defaultOptions = getDefaultOptions();
1589
+ const firstWeekContainsDate =
1590
+ options?.firstWeekContainsDate ??
1591
+ options?.locale?.options?.firstWeekContainsDate ??
1592
+ defaultOptions.firstWeekContainsDate ??
1593
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
1594
+ 1;
1595
+
1596
+ const year = getWeekYear(date, options);
1597
+ const firstWeek = constructFrom(date, 0);
1598
+ firstWeek.setFullYear(year, 0, firstWeekContainsDate);
1599
+ firstWeek.setHours(0, 0, 0, 0);
1600
+ const _date = startOfWeek(firstWeek, options);
1601
+ return _date;
1602
+ }
1603
+
1604
+ /**
1605
+ * The {@link getWeek} function options.
1606
+ */
1607
+
1608
+ /**
1609
+ * @name getWeek
1610
+ * @category Week Helpers
1611
+ * @summary Get the local week index of the given date.
1612
+ *
1613
+ * @description
1614
+ * Get the local week index of the given date.
1615
+ * The exact calculation depends on the values of
1616
+ * `options.weekStartsOn` (which is the index of the first day of the week)
1617
+ * and `options.firstWeekContainsDate` (which is the day of January, which is always in
1618
+ * the first week of the week-numbering year)
1619
+ *
1620
+ * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
1621
+ *
1622
+ * @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).
1623
+ *
1624
+ * @param date - The given date
1625
+ * @param options - An object with options
1626
+ *
1627
+ * @returns The week
1628
+ *
1629
+ * @example
1630
+ * // Which week of the local week numbering year is 2 January 2005 with default options?
1631
+ * const result = getWeek(new Date(2005, 0, 2))
1632
+ * //=> 2
1633
+ *
1634
+ * @example
1635
+ * // Which week of the local week numbering year is 2 January 2005,
1636
+ * // if Monday is the first day of the week,
1637
+ * // and the first week of the year always contains 4 January?
1638
+ * const result = getWeek(new Date(2005, 0, 2), {
1639
+ * weekStartsOn: 1,
1640
+ * firstWeekContainsDate: 4
1641
+ * })
1642
+ * //=> 53
1643
+ */
1644
+
1645
+ function getWeek(date, options) {
1646
+ const _date = toDate(date);
1647
+ const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
1648
+
1649
+ // Round the number of weeks to the nearest integer because the number of
1650
+ // milliseconds in a week is not constant (e.g. it's different in the week of
1651
+ // the daylight saving time clock shift).
1652
+ return Math.round(diff / millisecondsInWeek) + 1;
1653
+ }
1654
+
1655
+ function addLeadingZeros(number, targetLength) {
1656
+ const sign = number < 0 ? "-" : "";
1657
+ const output = Math.abs(number).toString().padStart(targetLength, "0");
1658
+ return sign + output;
1659
+ }
1660
+
1661
+ /*
1662
+ * | | Unit | | Unit |
1663
+ * |-----|--------------------------------|-----|--------------------------------|
1664
+ * | a | AM, PM | A* | |
1665
+ * | d | Day of month | D | |
1666
+ * | h | Hour [1-12] | H | Hour [0-23] |
1667
+ * | m | Minute | M | Month |
1668
+ * | s | Second | S | Fraction of second |
1669
+ * | y | Year (abs) | Y | |
1670
+ *
1671
+ * Letters marked by * are not implemented but reserved by Unicode standard.
1672
+ */
1673
+
1674
+ const lightFormatters = {
1675
+ // Year
1676
+ y(date, token) {
1677
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
1678
+ // | Year | y | yy | yyy | yyyy | yyyyy |
1679
+ // |----------|-------|----|-------|-------|-------|
1680
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
1681
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
1682
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
1683
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
1684
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
1685
+
1686
+ const signedYear = date.getFullYear();
1687
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1688
+ const year = signedYear > 0 ? signedYear : 1 - signedYear;
1689
+ return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
1690
+ },
1691
+
1692
+ // Month
1693
+ M(date, token) {
1694
+ const month = date.getMonth();
1695
+ return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
1696
+ },
1697
+
1698
+ // Day of the month
1699
+ d(date, token) {
1700
+ return addLeadingZeros(date.getDate(), token.length);
1701
+ },
1702
+
1703
+ // AM or PM
1704
+ a(date, token) {
1705
+ const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? "pm" : "am";
1706
+
1707
+ switch (token) {
1708
+ case "a":
1709
+ case "aa":
1710
+ return dayPeriodEnumValue.toUpperCase();
1711
+ case "aaa":
1712
+ return dayPeriodEnumValue;
1713
+ case "aaaaa":
1714
+ return dayPeriodEnumValue[0];
1715
+ case "aaaa":
1716
+ default:
1717
+ return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
1718
+ }
1719
+ },
1720
+
1721
+ // Hour [1-12]
1722
+ h(date, token) {
1723
+ return addLeadingZeros(date.getHours() % 12 || 12, token.length);
1724
+ },
1725
+
1726
+ // Hour [0-23]
1727
+ H(date, token) {
1728
+ return addLeadingZeros(date.getHours(), token.length);
1729
+ },
1730
+
1731
+ // Minute
1732
+ m(date, token) {
1733
+ return addLeadingZeros(date.getMinutes(), token.length);
1734
+ },
1735
+
1736
+ // Second
1737
+ s(date, token) {
1738
+ return addLeadingZeros(date.getSeconds(), token.length);
1739
+ },
1740
+
1741
+ // Fraction of second
1742
+ S(date, token) {
1743
+ const numberOfDigits = token.length;
1744
+ const milliseconds = date.getMilliseconds();
1745
+ const fractionalSeconds = Math.trunc(
1746
+ milliseconds * Math.pow(10, numberOfDigits - 3),
1747
+ );
1748
+ return addLeadingZeros(fractionalSeconds, token.length);
1749
+ },
1750
+ };
1751
+
1752
+ const dayPeriodEnum = {
1753
+ am: "am",
1754
+ pm: "pm",
1755
+ midnight: "midnight",
1756
+ noon: "noon",
1757
+ morning: "morning",
1758
+ afternoon: "afternoon",
1759
+ evening: "evening",
1760
+ night: "night",
1761
+ };
1762
+
1763
+ /*
1764
+ * | | Unit | | Unit |
1765
+ * |-----|--------------------------------|-----|--------------------------------|
1766
+ * | a | AM, PM | A* | Milliseconds in day |
1767
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
1768
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
1769
+ * | d | Day of month | D | Day of year |
1770
+ * | e | Local day of week | E | Day of week |
1771
+ * | f | | F* | Day of week in month |
1772
+ * | g* | Modified Julian day | G | Era |
1773
+ * | h | Hour [1-12] | H | Hour [0-23] |
1774
+ * | i! | ISO day of week | I! | ISO week of year |
1775
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
1776
+ * | k | Hour [1-24] | K | Hour [0-11] |
1777
+ * | l* | (deprecated) | L | Stand-alone month |
1778
+ * | m | Minute | M | Month |
1779
+ * | n | | N | |
1780
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
1781
+ * | p! | Long localized time | P! | Long localized date |
1782
+ * | q | Stand-alone quarter | Q | Quarter |
1783
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
1784
+ * | s | Second | S | Fraction of second |
1785
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
1786
+ * | u | Extended year | U* | Cyclic year |
1787
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
1788
+ * | w | Local week of year | W* | Week of month |
1789
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
1790
+ * | y | Year (abs) | Y | Local week-numbering year |
1791
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
1792
+ *
1793
+ * Letters marked by * are not implemented but reserved by Unicode standard.
1794
+ *
1795
+ * Letters marked by ! are non-standard, but implemented by date-fns:
1796
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
1797
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
1798
+ * i.e. 7 for Sunday, 1 for Monday, etc.
1799
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
1800
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
1801
+ * `R` is supposed to be used in conjunction with `I` and `i`
1802
+ * for universal ISO week-numbering date, whereas
1803
+ * `Y` is supposed to be used in conjunction with `w` and `e`
1804
+ * for week-numbering date specific to the locale.
1805
+ * - `P` is long localized date format
1806
+ * - `p` is long localized time format
1807
+ */
1808
+
1809
+ const formatters = {
1810
+ // Era
1811
+ G: function (date, token, localize) {
1812
+ const era = date.getFullYear() > 0 ? 1 : 0;
1813
+ switch (token) {
1814
+ // AD, BC
1815
+ case "G":
1816
+ case "GG":
1817
+ case "GGG":
1818
+ return localize.era(era, { width: "abbreviated" });
1819
+ // A, B
1820
+ case "GGGGG":
1821
+ return localize.era(era, { width: "narrow" });
1822
+ // Anno Domini, Before Christ
1823
+ case "GGGG":
1824
+ default:
1825
+ return localize.era(era, { width: "wide" });
1826
+ }
1827
+ },
1828
+
1829
+ // Year
1830
+ y: function (date, token, localize) {
1831
+ // Ordinal number
1832
+ if (token === "yo") {
1833
+ const signedYear = date.getFullYear();
1834
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1835
+ const year = signedYear > 0 ? signedYear : 1 - signedYear;
1836
+ return localize.ordinalNumber(year, { unit: "year" });
1837
+ }
1838
+
1839
+ return lightFormatters.y(date, token);
1840
+ },
1841
+
1842
+ // Local week-numbering year
1843
+ Y: function (date, token, localize, options) {
1844
+ const signedWeekYear = getWeekYear(date, options);
1845
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
1846
+ const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
1847
+
1848
+ // Two digit year
1849
+ if (token === "YY") {
1850
+ const twoDigitYear = weekYear % 100;
1851
+ return addLeadingZeros(twoDigitYear, 2);
1852
+ }
1853
+
1854
+ // Ordinal number
1855
+ if (token === "Yo") {
1856
+ return localize.ordinalNumber(weekYear, { unit: "year" });
1857
+ }
1858
+
1859
+ // Padding
1860
+ return addLeadingZeros(weekYear, token.length);
1861
+ },
1862
+
1863
+ // ISO week-numbering year
1864
+ R: function (date, token) {
1865
+ const isoWeekYear = getISOWeekYear(date);
1866
+
1867
+ // Padding
1868
+ return addLeadingZeros(isoWeekYear, token.length);
1869
+ },
1870
+
1871
+ // Extended year. This is a single number designating the year of this calendar system.
1872
+ // The main difference between `y` and `u` localizers are B.C. years:
1873
+ // | Year | `y` | `u` |
1874
+ // |------|-----|-----|
1875
+ // | AC 1 | 1 | 1 |
1876
+ // | BC 1 | 1 | 0 |
1877
+ // | BC 2 | 2 | -1 |
1878
+ // Also `yy` always returns the last two digits of a year,
1879
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
1880
+ u: function (date, token) {
1881
+ const year = date.getFullYear();
1882
+ return addLeadingZeros(year, token.length);
1883
+ },
1884
+
1885
+ // Quarter
1886
+ Q: function (date, token, localize) {
1887
+ const quarter = Math.ceil((date.getMonth() + 1) / 3);
1888
+ switch (token) {
1889
+ // 1, 2, 3, 4
1890
+ case "Q":
1891
+ return String(quarter);
1892
+ // 01, 02, 03, 04
1893
+ case "QQ":
1894
+ return addLeadingZeros(quarter, 2);
1895
+ // 1st, 2nd, 3rd, 4th
1896
+ case "Qo":
1897
+ return localize.ordinalNumber(quarter, { unit: "quarter" });
1898
+ // Q1, Q2, Q3, Q4
1899
+ case "QQQ":
1900
+ return localize.quarter(quarter, {
1901
+ width: "abbreviated",
1902
+ context: "formatting",
1903
+ });
1904
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
1905
+ case "QQQQQ":
1906
+ return localize.quarter(quarter, {
1907
+ width: "narrow",
1908
+ context: "formatting",
1909
+ });
1910
+ // 1st quarter, 2nd quarter, ...
1911
+ case "QQQQ":
1912
+ default:
1913
+ return localize.quarter(quarter, {
1914
+ width: "wide",
1915
+ context: "formatting",
1916
+ });
1917
+ }
1918
+ },
1919
+
1920
+ // Stand-alone quarter
1921
+ q: function (date, token, localize) {
1922
+ const quarter = Math.ceil((date.getMonth() + 1) / 3);
1923
+ switch (token) {
1924
+ // 1, 2, 3, 4
1925
+ case "q":
1926
+ return String(quarter);
1927
+ // 01, 02, 03, 04
1928
+ case "qq":
1929
+ return addLeadingZeros(quarter, 2);
1930
+ // 1st, 2nd, 3rd, 4th
1931
+ case "qo":
1932
+ return localize.ordinalNumber(quarter, { unit: "quarter" });
1933
+ // Q1, Q2, Q3, Q4
1934
+ case "qqq":
1935
+ return localize.quarter(quarter, {
1936
+ width: "abbreviated",
1937
+ context: "standalone",
1938
+ });
1939
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
1940
+ case "qqqqq":
1941
+ return localize.quarter(quarter, {
1942
+ width: "narrow",
1943
+ context: "standalone",
1944
+ });
1945
+ // 1st quarter, 2nd quarter, ...
1946
+ case "qqqq":
1947
+ default:
1948
+ return localize.quarter(quarter, {
1949
+ width: "wide",
1950
+ context: "standalone",
1951
+ });
1952
+ }
1953
+ },
1954
+
1955
+ // Month
1956
+ M: function (date, token, localize) {
1957
+ const month = date.getMonth();
1958
+ switch (token) {
1959
+ case "M":
1960
+ case "MM":
1961
+ return lightFormatters.M(date, token);
1962
+ // 1st, 2nd, ..., 12th
1963
+ case "Mo":
1964
+ return localize.ordinalNumber(month + 1, { unit: "month" });
1965
+ // Jan, Feb, ..., Dec
1966
+ case "MMM":
1967
+ return localize.month(month, {
1968
+ width: "abbreviated",
1969
+ context: "formatting",
1970
+ });
1971
+ // J, F, ..., D
1972
+ case "MMMMM":
1973
+ return localize.month(month, {
1974
+ width: "narrow",
1975
+ context: "formatting",
1976
+ });
1977
+ // January, February, ..., December
1978
+ case "MMMM":
1979
+ default:
1980
+ return localize.month(month, { width: "wide", context: "formatting" });
1981
+ }
1982
+ },
1983
+
1984
+ // Stand-alone month
1985
+ L: function (date, token, localize) {
1986
+ const month = date.getMonth();
1987
+ switch (token) {
1988
+ // 1, 2, ..., 12
1989
+ case "L":
1990
+ return String(month + 1);
1991
+ // 01, 02, ..., 12
1992
+ case "LL":
1993
+ return addLeadingZeros(month + 1, 2);
1994
+ // 1st, 2nd, ..., 12th
1995
+ case "Lo":
1996
+ return localize.ordinalNumber(month + 1, { unit: "month" });
1997
+ // Jan, Feb, ..., Dec
1998
+ case "LLL":
1999
+ return localize.month(month, {
2000
+ width: "abbreviated",
2001
+ context: "standalone",
2002
+ });
2003
+ // J, F, ..., D
2004
+ case "LLLLL":
2005
+ return localize.month(month, {
2006
+ width: "narrow",
2007
+ context: "standalone",
2008
+ });
2009
+ // January, February, ..., December
2010
+ case "LLLL":
2011
+ default:
2012
+ return localize.month(month, { width: "wide", context: "standalone" });
2013
+ }
2014
+ },
2015
+
2016
+ // Local week of year
2017
+ w: function (date, token, localize, options) {
2018
+ const week = getWeek(date, options);
2019
+
2020
+ if (token === "wo") {
2021
+ return localize.ordinalNumber(week, { unit: "week" });
2022
+ }
2023
+
2024
+ return addLeadingZeros(week, token.length);
2025
+ },
2026
+
2027
+ // ISO week of year
2028
+ I: function (date, token, localize) {
2029
+ const isoWeek = getISOWeek(date);
2030
+
2031
+ if (token === "Io") {
2032
+ return localize.ordinalNumber(isoWeek, { unit: "week" });
2033
+ }
2034
+
2035
+ return addLeadingZeros(isoWeek, token.length);
2036
+ },
2037
+
2038
+ // Day of the month
2039
+ d: function (date, token, localize) {
2040
+ if (token === "do") {
2041
+ return localize.ordinalNumber(date.getDate(), { unit: "date" });
2042
+ }
2043
+
2044
+ return lightFormatters.d(date, token);
2045
+ },
2046
+
2047
+ // Day of year
2048
+ D: function (date, token, localize) {
2049
+ const dayOfYear = getDayOfYear(date);
2050
+
2051
+ if (token === "Do") {
2052
+ return localize.ordinalNumber(dayOfYear, { unit: "dayOfYear" });
2053
+ }
2054
+
2055
+ return addLeadingZeros(dayOfYear, token.length);
2056
+ },
2057
+
2058
+ // Day of week
2059
+ E: function (date, token, localize) {
2060
+ const dayOfWeek = date.getDay();
2061
+ switch (token) {
2062
+ // Tue
2063
+ case "E":
2064
+ case "EE":
2065
+ case "EEE":
2066
+ return localize.day(dayOfWeek, {
2067
+ width: "abbreviated",
2068
+ context: "formatting",
2069
+ });
2070
+ // T
2071
+ case "EEEEE":
2072
+ return localize.day(dayOfWeek, {
2073
+ width: "narrow",
2074
+ context: "formatting",
2075
+ });
2076
+ // Tu
2077
+ case "EEEEEE":
2078
+ return localize.day(dayOfWeek, {
2079
+ width: "short",
2080
+ context: "formatting",
2081
+ });
2082
+ // Tuesday
2083
+ case "EEEE":
2084
+ default:
2085
+ return localize.day(dayOfWeek, {
2086
+ width: "wide",
2087
+ context: "formatting",
2088
+ });
2089
+ }
2090
+ },
2091
+
2092
+ // Local day of week
2093
+ e: function (date, token, localize, options) {
2094
+ const dayOfWeek = date.getDay();
2095
+ const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
2096
+ switch (token) {
2097
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
2098
+ case "e":
2099
+ return String(localDayOfWeek);
2100
+ // Padded numerical value
2101
+ case "ee":
2102
+ return addLeadingZeros(localDayOfWeek, 2);
2103
+ // 1st, 2nd, ..., 7th
2104
+ case "eo":
2105
+ return localize.ordinalNumber(localDayOfWeek, { unit: "day" });
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
+ // Stand-alone local day of week
2134
+ c: 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 (same as in `e`)
2139
+ case "c":
2140
+ return String(localDayOfWeek);
2141
+ // Padded numerical value
2142
+ case "cc":
2143
+ return addLeadingZeros(localDayOfWeek, token.length);
2144
+ // 1st, 2nd, ..., 7th
2145
+ case "co":
2146
+ return localize.ordinalNumber(localDayOfWeek, { unit: "day" });
2147
+ case "ccc":
2148
+ return localize.day(dayOfWeek, {
2149
+ width: "abbreviated",
2150
+ context: "standalone",
2151
+ });
2152
+ // T
2153
+ case "ccccc":
2154
+ return localize.day(dayOfWeek, {
2155
+ width: "narrow",
2156
+ context: "standalone",
2157
+ });
2158
+ // Tu
2159
+ case "cccccc":
2160
+ return localize.day(dayOfWeek, {
2161
+ width: "short",
2162
+ context: "standalone",
2163
+ });
2164
+ // Tuesday
2165
+ case "cccc":
2166
+ default:
2167
+ return localize.day(dayOfWeek, {
2168
+ width: "wide",
2169
+ context: "standalone",
2170
+ });
2171
+ }
2172
+ },
2173
+
2174
+ // ISO day of week
2175
+ i: function (date, token, localize) {
2176
+ const dayOfWeek = date.getDay();
2177
+ const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
2178
+ switch (token) {
2179
+ // 2
2180
+ case "i":
2181
+ return String(isoDayOfWeek);
2182
+ // 02
2183
+ case "ii":
2184
+ return addLeadingZeros(isoDayOfWeek, token.length);
2185
+ // 2nd
2186
+ case "io":
2187
+ return localize.ordinalNumber(isoDayOfWeek, { unit: "day" });
2188
+ // Tue
2189
+ case "iii":
2190
+ return localize.day(dayOfWeek, {
2191
+ width: "abbreviated",
2192
+ context: "formatting",
2193
+ });
2194
+ // T
2195
+ case "iiiii":
2196
+ return localize.day(dayOfWeek, {
2197
+ width: "narrow",
2198
+ context: "formatting",
2199
+ });
2200
+ // Tu
2201
+ case "iiiiii":
2202
+ return localize.day(dayOfWeek, {
2203
+ width: "short",
2204
+ context: "formatting",
2205
+ });
2206
+ // Tuesday
2207
+ case "iiii":
2208
+ default:
2209
+ return localize.day(dayOfWeek, {
2210
+ width: "wide",
2211
+ context: "formatting",
2212
+ });
2213
+ }
2214
+ },
2215
+
2216
+ // AM or PM
2217
+ a: function (date, token, localize) {
2218
+ const hours = date.getHours();
2219
+ const dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
2220
+
2221
+ switch (token) {
2222
+ case "a":
2223
+ case "aa":
2224
+ return localize.dayPeriod(dayPeriodEnumValue, {
2225
+ width: "abbreviated",
2226
+ context: "formatting",
2227
+ });
2228
+ case "aaa":
2229
+ return localize
2230
+ .dayPeriod(dayPeriodEnumValue, {
2231
+ width: "abbreviated",
2232
+ context: "formatting",
2233
+ })
2234
+ .toLowerCase();
2235
+ case "aaaaa":
2236
+ return localize.dayPeriod(dayPeriodEnumValue, {
2237
+ width: "narrow",
2238
+ context: "formatting",
2239
+ });
2240
+ case "aaaa":
2241
+ default:
2242
+ return localize.dayPeriod(dayPeriodEnumValue, {
2243
+ width: "wide",
2244
+ context: "formatting",
2245
+ });
2246
+ }
2247
+ },
2248
+
2249
+ // AM, PM, midnight, noon
2250
+ b: function (date, token, localize) {
2251
+ const hours = date.getHours();
2252
+ let dayPeriodEnumValue;
2253
+ if (hours === 12) {
2254
+ dayPeriodEnumValue = dayPeriodEnum.noon;
2255
+ } else if (hours === 0) {
2256
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
2257
+ } else {
2258
+ dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
2259
+ }
2260
+
2261
+ switch (token) {
2262
+ case "b":
2263
+ case "bb":
2264
+ return localize.dayPeriod(dayPeriodEnumValue, {
2265
+ width: "abbreviated",
2266
+ context: "formatting",
2267
+ });
2268
+ case "bbb":
2269
+ return localize
2270
+ .dayPeriod(dayPeriodEnumValue, {
2271
+ width: "abbreviated",
2272
+ context: "formatting",
2273
+ })
2274
+ .toLowerCase();
2275
+ case "bbbbb":
2276
+ return localize.dayPeriod(dayPeriodEnumValue, {
2277
+ width: "narrow",
2278
+ context: "formatting",
2279
+ });
2280
+ case "bbbb":
2281
+ default:
2282
+ return localize.dayPeriod(dayPeriodEnumValue, {
2283
+ width: "wide",
2284
+ context: "formatting",
2285
+ });
2286
+ }
2287
+ },
2288
+
2289
+ // in the morning, in the afternoon, in the evening, at night
2290
+ B: function (date, token, localize) {
2291
+ const hours = date.getHours();
2292
+ let dayPeriodEnumValue;
2293
+ if (hours >= 17) {
2294
+ dayPeriodEnumValue = dayPeriodEnum.evening;
2295
+ } else if (hours >= 12) {
2296
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
2297
+ } else if (hours >= 4) {
2298
+ dayPeriodEnumValue = dayPeriodEnum.morning;
2299
+ } else {
2300
+ dayPeriodEnumValue = dayPeriodEnum.night;
2301
+ }
2302
+
2303
+ switch (token) {
2304
+ case "B":
2305
+ case "BB":
2306
+ case "BBB":
2307
+ return localize.dayPeriod(dayPeriodEnumValue, {
2308
+ width: "abbreviated",
2309
+ context: "formatting",
2310
+ });
2311
+ case "BBBBB":
2312
+ return localize.dayPeriod(dayPeriodEnumValue, {
2313
+ width: "narrow",
2314
+ context: "formatting",
2315
+ });
2316
+ case "BBBB":
2317
+ default:
2318
+ return localize.dayPeriod(dayPeriodEnumValue, {
2319
+ width: "wide",
2320
+ context: "formatting",
2321
+ });
2322
+ }
2323
+ },
2324
+
2325
+ // Hour [1-12]
2326
+ h: function (date, token, localize) {
2327
+ if (token === "ho") {
2328
+ let hours = date.getHours() % 12;
2329
+ if (hours === 0) hours = 12;
2330
+ return localize.ordinalNumber(hours, { unit: "hour" });
2331
+ }
2332
+
2333
+ return lightFormatters.h(date, token);
2334
+ },
2335
+
2336
+ // Hour [0-23]
2337
+ H: function (date, token, localize) {
2338
+ if (token === "Ho") {
2339
+ return localize.ordinalNumber(date.getHours(), { unit: "hour" });
2340
+ }
2341
+
2342
+ return lightFormatters.H(date, token);
2343
+ },
2344
+
2345
+ // Hour [0-11]
2346
+ K: function (date, token, localize) {
2347
+ const hours = date.getHours() % 12;
2348
+
2349
+ if (token === "Ko") {
2350
+ return localize.ordinalNumber(hours, { unit: "hour" });
2351
+ }
2352
+
2353
+ return addLeadingZeros(hours, token.length);
2354
+ },
2355
+
2356
+ // Hour [1-24]
2357
+ k: function (date, token, localize) {
2358
+ let hours = date.getHours();
2359
+ if (hours === 0) hours = 24;
2360
+
2361
+ if (token === "ko") {
2362
+ return localize.ordinalNumber(hours, { unit: "hour" });
2363
+ }
2364
+
2365
+ return addLeadingZeros(hours, token.length);
2366
+ },
2367
+
2368
+ // Minute
2369
+ m: function (date, token, localize) {
2370
+ if (token === "mo") {
2371
+ return localize.ordinalNumber(date.getMinutes(), { unit: "minute" });
2372
+ }
2373
+
2374
+ return lightFormatters.m(date, token);
2375
+ },
2376
+
2377
+ // Second
2378
+ s: function (date, token, localize) {
2379
+ if (token === "so") {
2380
+ return localize.ordinalNumber(date.getSeconds(), { unit: "second" });
2381
+ }
2382
+
2383
+ return lightFormatters.s(date, token);
2384
+ },
2385
+
2386
+ // Fraction of second
2387
+ S: function (date, token) {
2388
+ return lightFormatters.S(date, token);
2389
+ },
2390
+
2391
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
2392
+ X: function (date, token, _localize) {
2393
+ const timezoneOffset = date.getTimezoneOffset();
2394
+
2395
+ if (timezoneOffset === 0) {
2396
+ return "Z";
2397
+ }
2398
+
2399
+ switch (token) {
2400
+ // Hours and optional minutes
2401
+ case "X":
2402
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
2403
+
2404
+ // Hours, minutes and optional seconds without `:` delimiter
2405
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2406
+ // so this token always has the same output as `XX`
2407
+ case "XXXX":
2408
+ case "XX": // Hours and minutes without `:` delimiter
2409
+ return formatTimezone(timezoneOffset);
2410
+
2411
+ // Hours, minutes and optional seconds with `:` delimiter
2412
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2413
+ // so this token always has the same output as `XXX`
2414
+ case "XXXXX":
2415
+ case "XXX": // Hours and minutes with `:` delimiter
2416
+ default:
2417
+ return formatTimezone(timezoneOffset, ":");
2418
+ }
2419
+ },
2420
+
2421
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
2422
+ x: function (date, token, _localize) {
2423
+ const timezoneOffset = date.getTimezoneOffset();
2424
+
2425
+ switch (token) {
2426
+ // Hours and optional minutes
2427
+ case "x":
2428
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
2429
+
2430
+ // Hours, minutes and optional seconds without `:` delimiter
2431
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2432
+ // so this token always has the same output as `xx`
2433
+ case "xxxx":
2434
+ case "xx": // Hours and minutes without `:` delimiter
2435
+ return formatTimezone(timezoneOffset);
2436
+
2437
+ // Hours, minutes and optional seconds with `:` delimiter
2438
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
2439
+ // so this token always has the same output as `xxx`
2440
+ case "xxxxx":
2441
+ case "xxx": // Hours and minutes with `:` delimiter
2442
+ default:
2443
+ return formatTimezone(timezoneOffset, ":");
2444
+ }
2445
+ },
2446
+
2447
+ // Timezone (GMT)
2448
+ O: function (date, token, _localize) {
2449
+ const timezoneOffset = date.getTimezoneOffset();
2450
+
2451
+ switch (token) {
2452
+ // Short
2453
+ case "O":
2454
+ case "OO":
2455
+ case "OOO":
2456
+ return "GMT" + formatTimezoneShort(timezoneOffset, ":");
2457
+ // Long
2458
+ case "OOOO":
2459
+ default:
2460
+ return "GMT" + formatTimezone(timezoneOffset, ":");
2461
+ }
2462
+ },
2463
+
2464
+ // Timezone (specific non-location)
2465
+ z: function (date, token, _localize) {
2466
+ const timezoneOffset = date.getTimezoneOffset();
2467
+
2468
+ switch (token) {
2469
+ // Short
2470
+ case "z":
2471
+ case "zz":
2472
+ case "zzz":
2473
+ return "GMT" + formatTimezoneShort(timezoneOffset, ":");
2474
+ // Long
2475
+ case "zzzz":
2476
+ default:
2477
+ return "GMT" + formatTimezone(timezoneOffset, ":");
2478
+ }
2479
+ },
2480
+
2481
+ // Seconds timestamp
2482
+ t: function (date, token, _localize) {
2483
+ const timestamp = Math.trunc(date.getTime() / 1000);
2484
+ return addLeadingZeros(timestamp, token.length);
2485
+ },
2486
+
2487
+ // Milliseconds timestamp
2488
+ T: function (date, token, _localize) {
2489
+ const timestamp = date.getTime();
2490
+ return addLeadingZeros(timestamp, token.length);
2491
+ },
2492
+ };
2493
+
2494
+ function formatTimezoneShort(offset, delimiter = "") {
2495
+ const sign = offset > 0 ? "-" : "+";
2496
+ const absOffset = Math.abs(offset);
2497
+ const hours = Math.trunc(absOffset / 60);
2498
+ const minutes = absOffset % 60;
2499
+ if (minutes === 0) {
2500
+ return sign + String(hours);
2501
+ }
2502
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
2503
+ }
2504
+
2505
+ function formatTimezoneWithOptionalMinutes(offset, delimiter) {
2506
+ if (offset % 60 === 0) {
2507
+ const sign = offset > 0 ? "-" : "+";
2508
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
2509
+ }
2510
+ return formatTimezone(offset, delimiter);
2511
+ }
2512
+
2513
+ function formatTimezone(offset, delimiter = "") {
2514
+ const sign = offset > 0 ? "-" : "+";
2515
+ const absOffset = Math.abs(offset);
2516
+ const hours = addLeadingZeros(Math.trunc(absOffset / 60), 2);
2517
+ const minutes = addLeadingZeros(absOffset % 60, 2);
2518
+ return sign + hours + delimiter + minutes;
2519
+ }
2520
+
2521
+ const dateLongFormatter = (pattern, formatLong) => {
2522
+ switch (pattern) {
2523
+ case "P":
2524
+ return formatLong.date({ width: "short" });
2525
+ case "PP":
2526
+ return formatLong.date({ width: "medium" });
2527
+ case "PPP":
2528
+ return formatLong.date({ width: "long" });
2529
+ case "PPPP":
2530
+ default:
2531
+ return formatLong.date({ width: "full" });
2532
+ }
2533
+ };
2534
+
2535
+ const timeLongFormatter = (pattern, formatLong) => {
2536
+ switch (pattern) {
2537
+ case "p":
2538
+ return formatLong.time({ width: "short" });
2539
+ case "pp":
2540
+ return formatLong.time({ width: "medium" });
2541
+ case "ppp":
2542
+ return formatLong.time({ width: "long" });
2543
+ case "pppp":
2544
+ default:
2545
+ return formatLong.time({ width: "full" });
2546
+ }
2547
+ };
2548
+
2549
+ const dateTimeLongFormatter = (pattern, formatLong) => {
2550
+ const matchResult = pattern.match(/(P+)(p+)?/) || [];
2551
+ const datePattern = matchResult[1];
2552
+ const timePattern = matchResult[2];
2553
+
2554
+ if (!timePattern) {
2555
+ return dateLongFormatter(pattern, formatLong);
2556
+ }
2557
+
2558
+ let dateTimeFormat;
2559
+
2560
+ switch (datePattern) {
2561
+ case "P":
2562
+ dateTimeFormat = formatLong.dateTime({ width: "short" });
2563
+ break;
2564
+ case "PP":
2565
+ dateTimeFormat = formatLong.dateTime({ width: "medium" });
2566
+ break;
2567
+ case "PPP":
2568
+ dateTimeFormat = formatLong.dateTime({ width: "long" });
2569
+ break;
2570
+ case "PPPP":
2571
+ default:
2572
+ dateTimeFormat = formatLong.dateTime({ width: "full" });
2573
+ break;
2574
+ }
2575
+
2576
+ return dateTimeFormat
2577
+ .replace("{{date}}", dateLongFormatter(datePattern, formatLong))
2578
+ .replace("{{time}}", timeLongFormatter(timePattern, formatLong));
2579
+ };
2580
+
2581
+ const longFormatters = {
2582
+ p: timeLongFormatter,
2583
+ P: dateTimeLongFormatter,
2584
+ };
2585
+
2586
+ const dayOfYearTokenRE = /^D+$/;
2587
+ const weekYearTokenRE = /^Y+$/;
2588
+
2589
+ const throwTokens = ["D", "DD", "YY", "YYYY"];
2590
+
2591
+ function isProtectedDayOfYearToken(token) {
2592
+ return dayOfYearTokenRE.test(token);
2593
+ }
2594
+
2595
+ function isProtectedWeekYearToken(token) {
2596
+ return weekYearTokenRE.test(token);
2597
+ }
2598
+
2599
+ function warnOrThrowProtectedError(token, format, input) {
2600
+ const _message = message(token, format, input);
2601
+ console.warn(_message);
2602
+ if (throwTokens.includes(token)) throw new RangeError(_message);
2603
+ }
2604
+
2605
+ function message(token, format, input) {
2606
+ const subject = token[0] === "Y" ? "years" : "days of the month";
2607
+ 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`;
2608
+ }
2609
+
2610
+ // This RegExp consists of three parts separated by `|`:
2611
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2612
+ // (one of the certain letters followed by `o`)
2613
+ // - (\w)\1* matches any sequences of the same letter
2614
+ // - '' matches two quote characters in a row
2615
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2616
+ // except a single quote symbol, which ends the sequence.
2617
+ // Two quote characters do not end the sequence.
2618
+ // If there is no matching single quote
2619
+ // then the sequence will continue until the end of the string.
2620
+ // - . matches any single character unmatched by previous parts of the RegExps
2621
+ const formattingTokensRegExp =
2622
+ /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
2623
+
2624
+ // This RegExp catches symbols escaped by quotes, and also
2625
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2626
+ const longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2627
+
2628
+ const escapedStringRegExp = /^'([^]*?)'?$/;
2629
+ const doubleQuoteRegExp = /''/g;
2630
+ const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2631
+
2632
+ /**
2633
+ * The {@link format} function options.
2634
+ */
2635
+
2636
+ /**
2637
+ * @name format
2638
+ * @alias formatDate
2639
+ * @category Common Helpers
2640
+ * @summary Format the date.
2641
+ *
2642
+ * @description
2643
+ * Return the formatted date string in the given format. The result may vary by locale.
2644
+ *
2645
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2646
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2647
+ *
2648
+ * The characters wrapped between two single quotes characters (') are escaped.
2649
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2650
+ * (see the last example)
2651
+ *
2652
+ * Format of the string is based on Unicode Technical Standard #35:
2653
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2654
+ * with a few additions (see note 7 below the table).
2655
+ *
2656
+ * Accepted patterns:
2657
+ * | Unit | Pattern | Result examples | Notes |
2658
+ * |---------------------------------|---------|-----------------------------------|-------|
2659
+ * | Era | G..GGG | AD, BC | |
2660
+ * | | GGGG | Anno Domini, Before Christ | 2 |
2661
+ * | | GGGGG | A, B | |
2662
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
2663
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
2664
+ * | | yy | 44, 01, 00, 17 | 5 |
2665
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
2666
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
2667
+ * | | yyyyy | ... | 3,5 |
2668
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
2669
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
2670
+ * | | YY | 44, 01, 00, 17 | 5,8 |
2671
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
2672
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
2673
+ * | | YYYYY | ... | 3,5 |
2674
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
2675
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
2676
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
2677
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
2678
+ * | | RRRRR | ... | 3,5,7 |
2679
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
2680
+ * | | uu | -43, 01, 1900, 2017 | 5 |
2681
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
2682
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
2683
+ * | | uuuuu | ... | 3,5 |
2684
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
2685
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
2686
+ * | | QQ | 01, 02, 03, 04 | |
2687
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
2688
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2689
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
2690
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
2691
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
2692
+ * | | qq | 01, 02, 03, 04 | |
2693
+ * | | qqq | Q1, Q2, Q3, Q4 | |
2694
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2695
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
2696
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
2697
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
2698
+ * | | MM | 01, 02, ..., 12 | |
2699
+ * | | MMM | Jan, Feb, ..., Dec | |
2700
+ * | | MMMM | January, February, ..., December | 2 |
2701
+ * | | MMMMM | J, F, ..., D | |
2702
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
2703
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
2704
+ * | | LL | 01, 02, ..., 12 | |
2705
+ * | | LLL | Jan, Feb, ..., Dec | |
2706
+ * | | LLLL | January, February, ..., December | 2 |
2707
+ * | | LLLLL | J, F, ..., D | |
2708
+ * | Local week of year | w | 1, 2, ..., 53 | |
2709
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
2710
+ * | | ww | 01, 02, ..., 53 | |
2711
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
2712
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
2713
+ * | | II | 01, 02, ..., 53 | 7 |
2714
+ * | Day of month | d | 1, 2, ..., 31 | |
2715
+ * | | do | 1st, 2nd, ..., 31st | 7 |
2716
+ * | | dd | 01, 02, ..., 31 | |
2717
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
2718
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
2719
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
2720
+ * | | DDD | 001, 002, ..., 365, 366 | |
2721
+ * | | DDDD | ... | 3 |
2722
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
2723
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2724
+ * | | EEEEE | M, T, W, T, F, S, S | |
2725
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2726
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
2727
+ * | | io | 1st, 2nd, ..., 7th | 7 |
2728
+ * | | ii | 01, 02, ..., 07 | 7 |
2729
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
2730
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
2731
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
2732
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
2733
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
2734
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
2735
+ * | | ee | 02, 03, ..., 01 | |
2736
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
2737
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2738
+ * | | eeeee | M, T, W, T, F, S, S | |
2739
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2740
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
2741
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
2742
+ * | | cc | 02, 03, ..., 01 | |
2743
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
2744
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2745
+ * | | ccccc | M, T, W, T, F, S, S | |
2746
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2747
+ * | AM, PM | a..aa | AM, PM | |
2748
+ * | | aaa | am, pm | |
2749
+ * | | aaaa | a.m., p.m. | 2 |
2750
+ * | | aaaaa | a, p | |
2751
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
2752
+ * | | bbb | am, pm, noon, midnight | |
2753
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
2754
+ * | | bbbbb | a, p, n, mi | |
2755
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
2756
+ * | | BBBB | at night, in the morning, ... | 2 |
2757
+ * | | BBBBB | at night, in the morning, ... | |
2758
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
2759
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
2760
+ * | | hh | 01, 02, ..., 11, 12 | |
2761
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
2762
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
2763
+ * | | HH | 00, 01, 02, ..., 23 | |
2764
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
2765
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
2766
+ * | | KK | 01, 02, ..., 11, 00 | |
2767
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
2768
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
2769
+ * | | kk | 24, 01, 02, ..., 23 | |
2770
+ * | Minute | m | 0, 1, ..., 59 | |
2771
+ * | | mo | 0th, 1st, ..., 59th | 7 |
2772
+ * | | mm | 00, 01, ..., 59 | |
2773
+ * | Second | s | 0, 1, ..., 59 | |
2774
+ * | | so | 0th, 1st, ..., 59th | 7 |
2775
+ * | | ss | 00, 01, ..., 59 | |
2776
+ * | Fraction of second | S | 0, 1, ..., 9 | |
2777
+ * | | SS | 00, 01, ..., 99 | |
2778
+ * | | SSS | 000, 001, ..., 999 | |
2779
+ * | | SSSS | ... | 3 |
2780
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
2781
+ * | | XX | -0800, +0530, Z | |
2782
+ * | | XXX | -08:00, +05:30, Z | |
2783
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
2784
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2785
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
2786
+ * | | xx | -0800, +0530, +0000 | |
2787
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
2788
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
2789
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2790
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
2791
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
2792
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
2793
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
2794
+ * | Seconds timestamp | t | 512969520 | 7 |
2795
+ * | | tt | ... | 3,7 |
2796
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
2797
+ * | | TT | ... | 3,7 |
2798
+ * | Long localized date | P | 04/29/1453 | 7 |
2799
+ * | | PP | Apr 29, 1453 | 7 |
2800
+ * | | PPP | April 29th, 1453 | 7 |
2801
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
2802
+ * | Long localized time | p | 12:00 AM | 7 |
2803
+ * | | pp | 12:00:00 AM | 7 |
2804
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
2805
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
2806
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
2807
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
2808
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
2809
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
2810
+ * Notes:
2811
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2812
+ * are the same as "stand-alone" units, but are different in some languages.
2813
+ * "Formatting" units are declined according to the rules of the language
2814
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2815
+ *
2816
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2817
+ *
2818
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2819
+ *
2820
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2821
+ * the single quote characters (see below).
2822
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2823
+ * the output will be the same as default pattern for this unit, usually
2824
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2825
+ * are marked with "2" in the last column of the table.
2826
+ *
2827
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2828
+ *
2829
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2830
+ *
2831
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2832
+ *
2833
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2834
+ *
2835
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2836
+ *
2837
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2838
+ * The output will be padded with zeros to match the length of the pattern.
2839
+ *
2840
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2841
+ *
2842
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2843
+ * These tokens represent the shortest form of the quarter.
2844
+ *
2845
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2846
+ *
2847
+ * | Year | `y` | `u` |
2848
+ * |------|-----|-----|
2849
+ * | AC 1 | 1 | 1 |
2850
+ * | BC 1 | 1 | 0 |
2851
+ * | BC 2 | 2 | -1 |
2852
+ *
2853
+ * Also `yy` always returns the last two digits of a year,
2854
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2855
+ *
2856
+ * | Year | `yy` | `uu` |
2857
+ * |------|------|------|
2858
+ * | 1 | 01 | 01 |
2859
+ * | 14 | 14 | 14 |
2860
+ * | 376 | 76 | 376 |
2861
+ * | 1453 | 53 | 1453 |
2862
+ *
2863
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2864
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2865
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)
2866
+ * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).
2867
+ *
2868
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2869
+ * so right now these tokens fall back to GMT timezones.
2870
+ *
2871
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2872
+ * - `i`: ISO day of week
2873
+ * - `I`: ISO week of year
2874
+ * - `R`: ISO week-numbering year
2875
+ * - `t`: seconds timestamp
2876
+ * - `T`: milliseconds timestamp
2877
+ * - `o`: ordinal number modifier
2878
+ * - `P`: long localized date
2879
+ * - `p`: long localized time
2880
+ *
2881
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2882
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2883
+ *
2884
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2885
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2886
+ *
2887
+ * @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).
2888
+ *
2889
+ * @param date - The original date
2890
+ * @param format - The string of tokens
2891
+ * @param options - An object with options
2892
+ *
2893
+ * @returns The formatted date string
2894
+ *
2895
+ * @throws `date` must not be Invalid Date
2896
+ * @throws `options.locale` must contain `localize` property
2897
+ * @throws `options.locale` must contain `formatLong` property
2898
+ * @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
2899
+ * @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
2900
+ * @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
2901
+ * @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
2902
+ * @throws format string contains an unescaped latin alphabet character
2903
+ *
2904
+ * @example
2905
+ * // Represent 11 February 2014 in middle-endian format:
2906
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2907
+ * //=> '02/11/2014'
2908
+ *
2909
+ * @example
2910
+ * // Represent 2 July 2014 in Esperanto:
2911
+ * import { eoLocale } from 'date-fns/locale/eo'
2912
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2913
+ * locale: eoLocale
2914
+ * })
2915
+ * //=> '2-a de julio 2014'
2916
+ *
2917
+ * @example
2918
+ * // Escape string by single quote characters:
2919
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2920
+ * //=> "3 o'clock"
2921
+ */
2922
+ function format(date, formatStr, options) {
2923
+ const defaultOptions = getDefaultOptions();
2924
+ const locale = options?.locale ?? defaultOptions.locale ?? enUS;
2925
+
2926
+ const firstWeekContainsDate =
2927
+ options?.firstWeekContainsDate ??
2928
+ options?.locale?.options?.firstWeekContainsDate ??
2929
+ defaultOptions.firstWeekContainsDate ??
2930
+ defaultOptions.locale?.options?.firstWeekContainsDate ??
2931
+ 1;
2932
+
2933
+ const weekStartsOn =
2934
+ options?.weekStartsOn ??
2935
+ options?.locale?.options?.weekStartsOn ??
2936
+ defaultOptions.weekStartsOn ??
2937
+ defaultOptions.locale?.options?.weekStartsOn ??
2938
+ 0;
2939
+
2940
+ const originalDate = toDate(date);
2941
+
2942
+ if (!isValid(originalDate)) {
2943
+ throw new RangeError("Invalid time value");
2944
+ }
2945
+
2946
+ let parts = formatStr
2947
+ .match(longFormattingTokensRegExp)
2948
+ .map((substring) => {
2949
+ const firstCharacter = substring[0];
2950
+ if (firstCharacter === "p" || firstCharacter === "P") {
2951
+ const longFormatter = longFormatters[firstCharacter];
2952
+ return longFormatter(substring, locale.formatLong);
2953
+ }
2954
+ return substring;
2955
+ })
2956
+ .join("")
2957
+ .match(formattingTokensRegExp)
2958
+ .map((substring) => {
2959
+ // Replace two single quote characters with one single quote character
2960
+ if (substring === "''") {
2961
+ return { isToken: false, value: "'" };
2962
+ }
2963
+
2964
+ const firstCharacter = substring[0];
2965
+ if (firstCharacter === "'") {
2966
+ return { isToken: false, value: cleanEscapedString(substring) };
2967
+ }
2968
+
2969
+ if (formatters[firstCharacter]) {
2970
+ return { isToken: true, value: substring };
2971
+ }
2972
+
2973
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2974
+ throw new RangeError(
2975
+ "Format string contains an unescaped latin alphabet character `" +
2976
+ firstCharacter +
2977
+ "`",
2978
+ );
2979
+ }
2980
+
2981
+ return { isToken: false, value: substring };
2982
+ });
2983
+
2984
+ // invoke localize preprocessor (only for french locales at the moment)
2985
+ if (locale.localize.preprocessor) {
2986
+ parts = locale.localize.preprocessor(originalDate, parts);
2987
+ }
2988
+
2989
+ const formatterOptions = {
2990
+ firstWeekContainsDate,
2991
+ weekStartsOn,
2992
+ locale,
2993
+ };
2994
+
2995
+ return parts
2996
+ .map((part) => {
2997
+ if (!part.isToken) return part.value;
2998
+
2999
+ const token = part.value;
3000
+
3001
+ if (
3002
+ (!options?.useAdditionalWeekYearTokens &&
3003
+ isProtectedWeekYearToken(token)) ||
3004
+ (!options?.useAdditionalDayOfYearTokens &&
3005
+ isProtectedDayOfYearToken(token))
3006
+ ) {
3007
+ warnOrThrowProtectedError(token, formatStr, String(date));
3008
+ }
3009
+
3010
+ const formatter = formatters[token[0]];
3011
+ return formatter(originalDate, token, locale.localize, formatterOptions);
3012
+ })
3013
+ .join("");
3014
+ }
3015
+
3016
+ function cleanEscapedString(input) {
3017
+ const matched = input.match(escapedStringRegExp);
3018
+
3019
+ if (!matched) {
3020
+ return input;
3021
+ }
3022
+
3023
+ return matched[1].replace(doubleQuoteRegExp, "'");
3024
+ }
3025
+
3026
+ /**
3027
+ * @name isSameMonth
3028
+ * @category Month Helpers
3029
+ * @summary Are the given dates in the same month (and year)?
3030
+ *
3031
+ * @description
3032
+ * Are the given dates in the same month (and year)?
3033
+ *
3034
+ * @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).
3035
+ *
3036
+ * @param dateLeft - The first date to check
3037
+ * @param dateRight - The second date to check
3038
+ *
3039
+ * @returns The dates are in the same month (and year)
3040
+ *
3041
+ * @example
3042
+ * // Are 2 September 2014 and 25 September 2014 in the same month?
3043
+ * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))
3044
+ * //=> true
3045
+ *
3046
+ * @example
3047
+ * // Are 2 September 2014 and 25 September 2015 in the same month?
3048
+ * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))
3049
+ * //=> false
3050
+ */
3051
+ function isSameMonth(dateLeft, dateRight) {
3052
+ const _dateLeft = toDate(dateLeft);
3053
+ const _dateRight = toDate(dateRight);
3054
+ return (
3055
+ _dateLeft.getFullYear() === _dateRight.getFullYear() &&
3056
+ _dateLeft.getMonth() === _dateRight.getMonth()
3057
+ );
3058
+ }
3059
+
3060
+ /**
3061
+ * The {@link parseISO} function options.
3062
+ */
3063
+
3064
+ /**
3065
+ * @name parseISO
3066
+ * @category Common Helpers
3067
+ * @summary Parse ISO string
3068
+ *
3069
+ * @description
3070
+ * Parse the given string in ISO 8601 format and return an instance of Date.
3071
+ *
3072
+ * Function accepts complete ISO 8601 formats as well as partial implementations.
3073
+ * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601
3074
+ *
3075
+ * If the argument isn't a string, the function cannot parse the string or
3076
+ * the values are invalid, it returns Invalid Date.
3077
+ *
3078
+ * @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).
3079
+ *
3080
+ * @param argument - The value to convert
3081
+ * @param options - An object with options
3082
+ *
3083
+ * @returns The parsed date in the local time zone
3084
+ *
3085
+ * @example
3086
+ * // Convert string '2014-02-11T11:30:30' to date:
3087
+ * const result = parseISO('2014-02-11T11:30:30')
3088
+ * //=> Tue Feb 11 2014 11:30:30
3089
+ *
3090
+ * @example
3091
+ * // Convert string '+02014101' to date,
3092
+ * // if the additional number of digits in the extended year format is 1:
3093
+ * const result = parseISO('+02014101', { additionalDigits: 1 })
3094
+ * //=> Fri Apr 11 2014 00:00:00
3095
+ */
3096
+ function parseISO(argument, options) {
3097
+ const additionalDigits = options?.additionalDigits ?? 2;
3098
+ const dateStrings = splitDateString(argument);
3099
+
3100
+ let date;
3101
+ if (dateStrings.date) {
3102
+ const parseYearResult = parseYear(dateStrings.date, additionalDigits);
3103
+ date = parseDate(parseYearResult.restDateString, parseYearResult.year);
3104
+ }
3105
+
3106
+ if (!date || isNaN(date.getTime())) {
3107
+ return new Date(NaN);
3108
+ }
3109
+
3110
+ const timestamp = date.getTime();
3111
+ let time = 0;
3112
+ let offset;
3113
+
3114
+ if (dateStrings.time) {
3115
+ time = parseTime(dateStrings.time);
3116
+ if (isNaN(time)) {
3117
+ return new Date(NaN);
3118
+ }
3119
+ }
3120
+
3121
+ if (dateStrings.timezone) {
3122
+ offset = parseTimezone(dateStrings.timezone);
3123
+ if (isNaN(offset)) {
3124
+ return new Date(NaN);
3125
+ }
3126
+ } else {
3127
+ const dirtyDate = new Date(timestamp + time);
3128
+ // JS parsed string assuming it's in UTC timezone
3129
+ // but we need it to be parsed in our timezone
3130
+ // so we use utc values to build date in our timezone.
3131
+ // Year values from 0 to 99 map to the years 1900 to 1999
3132
+ // so set year explicitly with setFullYear.
3133
+ const result = new Date(0);
3134
+ result.setFullYear(
3135
+ dirtyDate.getUTCFullYear(),
3136
+ dirtyDate.getUTCMonth(),
3137
+ dirtyDate.getUTCDate(),
3138
+ );
3139
+ result.setHours(
3140
+ dirtyDate.getUTCHours(),
3141
+ dirtyDate.getUTCMinutes(),
3142
+ dirtyDate.getUTCSeconds(),
3143
+ dirtyDate.getUTCMilliseconds(),
3144
+ );
3145
+ return result;
3146
+ }
3147
+
3148
+ return new Date(timestamp + time + offset);
3149
+ }
3150
+
3151
+ const patterns = {
3152
+ dateTimeDelimiter: /[T ]/,
3153
+ timeZoneDelimiter: /[Z ]/i,
3154
+ timezone: /([Z+-].*)$/,
3155
+ };
3156
+
3157
+ const dateRegex =
3158
+ /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
3159
+ const timeRegex =
3160
+ /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
3161
+ const timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
3162
+
3163
+ function splitDateString(dateString) {
3164
+ const dateStrings = {};
3165
+ const array = dateString.split(patterns.dateTimeDelimiter);
3166
+ let timeString;
3167
+
3168
+ // The regex match should only return at maximum two array elements.
3169
+ // [date], [time], or [date, time].
3170
+ if (array.length > 2) {
3171
+ return dateStrings;
3172
+ }
3173
+
3174
+ if (/:/.test(array[0])) {
3175
+ timeString = array[0];
3176
+ } else {
3177
+ dateStrings.date = array[0];
3178
+ timeString = array[1];
3179
+ if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
3180
+ dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
3181
+ timeString = dateString.substr(
3182
+ dateStrings.date.length,
3183
+ dateString.length,
3184
+ );
3185
+ }
3186
+ }
3187
+
3188
+ if (timeString) {
3189
+ const token = patterns.timezone.exec(timeString);
3190
+ if (token) {
3191
+ dateStrings.time = timeString.replace(token[1], "");
3192
+ dateStrings.timezone = token[1];
3193
+ } else {
3194
+ dateStrings.time = timeString;
3195
+ }
3196
+ }
3197
+
3198
+ return dateStrings;
3199
+ }
3200
+
3201
+ function parseYear(dateString, additionalDigits) {
3202
+ const regex = new RegExp(
3203
+ "^(?:(\\d{4}|[+-]\\d{" +
3204
+ (4 + additionalDigits) +
3205
+ "})|(\\d{2}|[+-]\\d{" +
3206
+ (2 + additionalDigits) +
3207
+ "})$)",
3208
+ );
3209
+
3210
+ const captures = dateString.match(regex);
3211
+ // Invalid ISO-formatted year
3212
+ if (!captures) return { year: NaN, restDateString: "" };
3213
+
3214
+ const year = captures[1] ? parseInt(captures[1]) : null;
3215
+ const century = captures[2] ? parseInt(captures[2]) : null;
3216
+
3217
+ // either year or century is null, not both
3218
+ return {
3219
+ year: century === null ? year : century * 100,
3220
+ restDateString: dateString.slice((captures[1] || captures[2]).length),
3221
+ };
3222
+ }
3223
+
3224
+ function parseDate(dateString, year) {
3225
+ // Invalid ISO-formatted year
3226
+ if (year === null) return new Date(NaN);
3227
+
3228
+ const captures = dateString.match(dateRegex);
3229
+ // Invalid ISO-formatted string
3230
+ if (!captures) return new Date(NaN);
3231
+
3232
+ const isWeekDate = !!captures[4];
3233
+ const dayOfYear = parseDateUnit(captures[1]);
3234
+ const month = parseDateUnit(captures[2]) - 1;
3235
+ const day = parseDateUnit(captures[3]);
3236
+ const week = parseDateUnit(captures[4]);
3237
+ const dayOfWeek = parseDateUnit(captures[5]) - 1;
3238
+
3239
+ if (isWeekDate) {
3240
+ if (!validateWeekDate(year, week, dayOfWeek)) {
3241
+ return new Date(NaN);
3242
+ }
3243
+ return dayOfISOWeekYear(year, week, dayOfWeek);
3244
+ } else {
3245
+ const date = new Date(0);
3246
+ if (
3247
+ !validateDate(year, month, day) ||
3248
+ !validateDayOfYearDate(year, dayOfYear)
3249
+ ) {
3250
+ return new Date(NaN);
3251
+ }
3252
+ date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
3253
+ return date;
3254
+ }
3255
+ }
3256
+
3257
+ function parseDateUnit(value) {
3258
+ return value ? parseInt(value) : 1;
3259
+ }
3260
+
3261
+ function parseTime(timeString) {
3262
+ const captures = timeString.match(timeRegex);
3263
+ if (!captures) return NaN; // Invalid ISO-formatted time
3264
+
3265
+ const hours = parseTimeUnit(captures[1]);
3266
+ const minutes = parseTimeUnit(captures[2]);
3267
+ const seconds = parseTimeUnit(captures[3]);
3268
+
3269
+ if (!validateTime(hours, minutes, seconds)) {
3270
+ return NaN;
3271
+ }
3272
+
3273
+ return (
3274
+ hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000
3275
+ );
3276
+ }
3277
+
3278
+ function parseTimeUnit(value) {
3279
+ return (value && parseFloat(value.replace(",", "."))) || 0;
3280
+ }
3281
+
3282
+ function parseTimezone(timezoneString) {
3283
+ if (timezoneString === "Z") return 0;
3284
+
3285
+ const captures = timezoneString.match(timezoneRegex);
3286
+ if (!captures) return 0;
3287
+
3288
+ const sign = captures[1] === "+" ? -1 : 1;
3289
+ const hours = parseInt(captures[2]);
3290
+ const minutes = (captures[3] && parseInt(captures[3])) || 0;
3291
+
3292
+ if (!validateTimezone(hours, minutes)) {
3293
+ return NaN;
3294
+ }
3295
+
3296
+ return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute);
3297
+ }
3298
+
3299
+ function dayOfISOWeekYear(isoWeekYear, week, day) {
3300
+ const date = new Date(0);
3301
+ date.setUTCFullYear(isoWeekYear, 0, 4);
3302
+ const fourthOfJanuaryDay = date.getUTCDay() || 7;
3303
+ const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
3304
+ date.setUTCDate(date.getUTCDate() + diff);
3305
+ return date;
3306
+ }
3307
+
3308
+ // Validation functions
3309
+
3310
+ // February is null to handle the leap year (using ||)
3311
+ const daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
3312
+
3313
+ function isLeapYearIndex(year) {
3314
+ return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);
3315
+ }
3316
+
3317
+ function validateDate(year, month, date) {
3318
+ return (
3319
+ month >= 0 &&
3320
+ month <= 11 &&
3321
+ date >= 1 &&
3322
+ date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28))
3323
+ );
3324
+ }
3325
+
3326
+ function validateDayOfYearDate(year, dayOfYear) {
3327
+ return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
3328
+ }
3329
+
3330
+ function validateWeekDate(_year, week, day) {
3331
+ return week >= 1 && week <= 53 && day >= 0 && day <= 6;
3332
+ }
3333
+
3334
+ function validateTime(hours, minutes, seconds) {
3335
+ if (hours === 24) {
3336
+ return minutes === 0 && seconds === 0;
3337
+ }
3338
+
3339
+ return (
3340
+ seconds >= 0 &&
3341
+ seconds < 60 &&
3342
+ minutes >= 0 &&
3343
+ minutes < 60 &&
3344
+ hours >= 0 &&
3345
+ hours < 25
3346
+ );
3347
+ }
3348
+
3349
+ function validateTimezone(_hours, minutes) {
3350
+ return minutes >= 0 && minutes <= 59;
3351
+ }
3352
+
3353
+ /**
3354
+ * @name subMonths
3355
+ * @category Month Helpers
3356
+ * @summary Subtract the specified number of months from the given date.
3357
+ *
3358
+ * @description
3359
+ * Subtract the specified number of months from the given date.
3360
+ *
3361
+ * @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).
3362
+ *
3363
+ * @param date - The date to be changed
3364
+ * @param amount - The amount of months to be subtracted.
3365
+ *
3366
+ * @returns The new date with the months subtracted
3367
+ *
3368
+ * @example
3369
+ * // Subtract 5 months from 1 February 2015:
3370
+ * const result = subMonths(new Date(2015, 1, 1), 5)
3371
+ * //=> Mon Sep 01 2014 00:00:00
3372
+ */
3373
+ function subMonths(date, amount) {
3374
+ return addMonths(date, -amount);
3375
+ }
3376
+
3377
+ const getBaseUrl = () => {
3378
+ if (typeof process !== 'undefined' && process.env && process.env.REACT_APP_CALENDAR_API_URL) {
3379
+ return process.env.REACT_APP_CALENDAR_API_URL;
3380
+ }
3381
+ if (typeof window !== 'undefined' && window.CALENDAR_API_URL) {
3382
+ return window.CALENDAR_API_URL;
3383
+ }
3384
+ return 'http://localhost:8080';
3385
+ };
3386
+ const createBooking = (businessId, booking, apiBaseUrl) => __awaiter(void 0, void 0, void 0, function* () {
3387
+ const baseUrl = apiBaseUrl || getBaseUrl();
3388
+ const response = yield fetch(`${baseUrl}/businesses/${businessId}/bookings`, {
3389
+ method: 'POST',
3390
+ headers: {
3391
+ 'Content-Type': 'application/json',
3392
+ },
3393
+ body: JSON.stringify(booking),
3394
+ });
3395
+ if (!response.ok) {
3396
+ const error = yield response.json();
3397
+ throw new Error(error.error || 'Failed to create booking');
3398
+ }
3399
+ return response.json();
3400
+ });
3401
+ const getResourceSchedule = (businessId, resourceId, startDate, endDate, apiBaseUrl) => __awaiter(void 0, void 0, void 0, function* () {
3402
+ const baseUrl = apiBaseUrl || getBaseUrl();
3403
+ const url = new URL(`${baseUrl}/businesses/${businessId}/schedules/${resourceId}`);
3404
+ url.searchParams.append('start_date', startDate);
3405
+ url.searchParams.append('end_date', endDate);
3406
+ const response = yield fetch(url.toString());
3407
+ if (!response.ok) {
3408
+ const error = yield response.json();
3409
+ throw new Error(error.error || 'Failed to fetch schedule');
3410
+ }
3411
+ return response.json();
3412
+ });
3413
+ const getAllBookings = (businessId, startDate, endDate, apiBaseUrl) => __awaiter(void 0, void 0, void 0, function* () {
3414
+ const baseUrl = apiBaseUrl || getBaseUrl();
3415
+ const url = new URL(`${baseUrl}/businesses/${businessId}/bookings`);
3416
+ url.searchParams.append('start_date', startDate);
3417
+ url.searchParams.append('end_date', endDate);
3418
+ const response = yield fetch(url.toString());
3419
+ if (!response.ok) {
3420
+ const error = yield response.json();
3421
+ throw new Error(error.error || 'Failed to fetch bookings');
3422
+ }
3423
+ return response.json();
3424
+ });
3425
+ const getMeetingDetails = (businessId, meetingId, apiBaseUrl) => __awaiter(void 0, void 0, void 0, function* () {
3426
+ const baseUrl = apiBaseUrl || getBaseUrl();
3427
+ const response = yield fetch(`${baseUrl}/businesses/${businessId}/meetings/${meetingId}`);
3428
+ if (!response.ok) {
3429
+ const error = yield response.json();
3430
+ throw new Error(error.error || 'Failed to fetch meeting details');
3431
+ }
3432
+ return response.json();
3433
+ });
3434
+
3435
+ function styleInject(css, ref) {
3436
+ if ( ref === void 0 ) ref = {};
3437
+ var insertAt = ref.insertAt;
3438
+
3439
+ if (!css || typeof document === 'undefined') { return; }
3440
+
3441
+ var head = document.head || document.getElementsByTagName('head')[0];
3442
+ var style = document.createElement('style');
3443
+ style.type = 'text/css';
3444
+
3445
+ if (insertAt === 'top') {
3446
+ if (head.firstChild) {
3447
+ head.insertBefore(style, head.firstChild);
3448
+ } else {
3449
+ head.appendChild(style);
3450
+ }
3451
+ } else {
3452
+ head.appendChild(style);
3453
+ }
3454
+
3455
+ if (style.styleSheet) {
3456
+ style.styleSheet.cssText = css;
3457
+ } else {
3458
+ style.appendChild(document.createTextNode(css));
3459
+ }
3460
+ }
3461
+
3462
+ var css_248z$1 = ".modal-overlay {\r\n position: fixed;\r\n top: 0;\r\n left: 0;\r\n right: 0;\r\n bottom: 0;\r\n background: rgba(0, 0, 0, 0.5);\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n z-index: 1000;\r\n padding: 20px;\r\n}\r\n\r\n.modal-content {\r\n background: #ffffff;\r\n border-radius: 8px;\r\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);\r\n width: 100%;\r\n max-width: 500px;\r\n max-height: 90vh;\r\n overflow-y: auto;\r\n}\r\n\r\n.modal-header {\r\n display: flex;\r\n justify-content: space-between;\r\n align-items: center;\r\n padding: 20px;\r\n border-bottom: 1px solid #e9ecef;\r\n}\r\n\r\n.modal-header h3 {\r\n margin: 0;\r\n font-size: 20px;\r\n font-weight: 600;\r\n color: #212529;\r\n}\r\n\r\n.modal-close-btn {\r\n background: none;\r\n border: none;\r\n font-size: 32px;\r\n line-height: 1;\r\n color: #6c757d;\r\n cursor: pointer;\r\n padding: 0;\r\n width: 32px;\r\n height: 32px;\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n border-radius: 4px;\r\n transition: background-color 0.2s;\r\n}\r\n\r\n.modal-close-btn:hover {\r\n background: #e9ecef;\r\n color: #212529;\r\n}\r\n\r\n.modal-body {\r\n padding: 20px;\r\n}\r\n\r\n.modal-footer {\r\n display: flex;\r\n justify-content: flex-end;\r\n gap: 12px;\r\n padding: 20px;\r\n border-top: 1px solid #e9ecef;\r\n}\r\n\r\n.modal-error {\r\n background: #f8d7da;\r\n color: #842029;\r\n padding: 12px;\r\n border-radius: 4px;\r\n margin-bottom: 16px;\r\n font-size: 14px;\r\n}\r\n\r\n.form-group {\r\n margin-bottom: 16px;\r\n}\r\n\r\n.form-group label {\r\n display: block;\r\n font-weight: 500;\r\n font-size: 14px;\r\n color: #212529;\r\n margin-bottom: 6px;\r\n}\r\n\r\n.form-group input,\r\n.form-group textarea {\r\n width: 100%;\r\n padding: 10px 12px;\r\n border: 1px solid #ced4da;\r\n border-radius: 4px;\r\n font-size: 14px;\r\n font-family: inherit;\r\n color: #212529;\r\n transition: border-color 0.2s;\r\n box-sizing: border-box;\r\n}\r\n\r\n.form-group input:focus,\r\n.form-group textarea:focus {\r\n outline: none;\r\n border-color: #0d6efd;\r\n box-shadow: 0 0 0 3px rgba(13, 110, 253, 0.1);\r\n}\r\n\r\n.form-group textarea {\r\n resize: vertical;\r\n}\r\n\r\n.form-group small {\r\n display: block;\r\n margin-top: 4px;\r\n font-size: 12px;\r\n color: #6c757d;\r\n}\r\n\r\n.form-row {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 12px;\r\n}\r\n\r\n.modal-btn {\r\n padding: 10px 20px;\r\n border: none;\r\n border-radius: 4px;\r\n font-size: 14px;\r\n font-weight: 500;\r\n cursor: pointer;\r\n transition: all 0.2s;\r\n}\r\n\r\n.modal-btn:disabled {\r\n opacity: 0.6;\r\n cursor: not-allowed;\r\n}\r\n\r\n.modal-btn-primary {\r\n background: #0d6efd;\r\n color: #ffffff;\r\n}\r\n\r\n.modal-btn-primary:hover:not(:disabled) {\r\n background: #0b5ed7;\r\n}\r\n\r\n.modal-btn-secondary {\r\n background: #6c757d;\r\n color: #ffffff;\r\n}\r\n\r\n.modal-btn-secondary:hover:not(:disabled) {\r\n background: #5c636a;\r\n}\r\n\r\n@media (max-width: 576px) {\r\n .modal-content {\r\n max-width: 100%;\r\n }\r\n\r\n .form-row {\r\n grid-template-columns: 1fr;\r\n }\r\n}\r\n";
3463
+ styleInject(css_248z$1);
3464
+
3465
+ const CreateBookingModal = ({ businessId, apiBaseUrl, initialDate, participants: defaultParticipants, onClose, onBookingCreated, }) => {
3466
+ const [title, setTitle] = useState('');
3467
+ const [description, setDescription] = useState('');
3468
+ const [startDate, setStartDate] = useState(format(initialDate, "yyyy-MM-dd"));
3469
+ const [startTime, setStartTime] = useState('09:00');
3470
+ const [endTime, setEndTime] = useState('10:00');
3471
+ const [participants, setParticipants] = useState(defaultParticipants.join(', '));
3472
+ const [loading, setLoading] = useState(false);
3473
+ const [error, setError] = useState(null);
3474
+ const handleSubmit = (e) => __awaiter(void 0, void 0, void 0, function* () {
3475
+ e.preventDefault();
3476
+ setLoading(true);
3477
+ setError(null);
3478
+ try {
3479
+ const participantList = participants
3480
+ .split(',')
3481
+ .map((p) => p.trim())
3482
+ .filter((p) => p.length > 0);
3483
+ if (participantList.length === 0) {
3484
+ throw new Error('At least one participant is required');
3485
+ }
3486
+ const startDateTime = new Date(`${startDate}T${startTime}:00.000Z`);
3487
+ const endDateTime = new Date(`${startDate}T${endTime}:00.000Z`);
3488
+ if (endDateTime <= startDateTime) {
3489
+ throw new Error('End time must be after start time');
3490
+ }
3491
+ const booking = yield createBooking(businessId, {
3492
+ participants: participantList,
3493
+ start: startDateTime.toISOString(),
3494
+ end: endDateTime.toISOString(),
3495
+ metadata: {
3496
+ title: title || 'Untitled Meeting',
3497
+ description,
3498
+ },
3499
+ }, apiBaseUrl);
3500
+ onBookingCreated(booking);
3501
+ }
3502
+ catch (err) {
3503
+ setError(err instanceof Error ? err.message : 'Failed to create booking');
3504
+ }
3505
+ finally {
3506
+ setLoading(false);
3507
+ }
3508
+ });
3509
+ return (React.createElement("div", { className: "modal-overlay", onClick: onClose },
3510
+ React.createElement("div", { className: "modal-content", onClick: (e) => e.stopPropagation() },
3511
+ React.createElement("div", { className: "modal-header" },
3512
+ React.createElement("h3", null, "Create New Booking"),
3513
+ React.createElement("button", { className: "modal-close-btn", onClick: onClose }, "\u00D7")),
3514
+ React.createElement("form", { onSubmit: handleSubmit },
3515
+ React.createElement("div", { className: "modal-body" },
3516
+ error && React.createElement("div", { className: "modal-error" }, error),
3517
+ React.createElement("div", { className: "form-group" },
3518
+ React.createElement("label", { htmlFor: "title" }, "Title"),
3519
+ React.createElement("input", { id: "title", type: "text", value: title, onChange: (e) => setTitle(e.target.value), placeholder: "Meeting title", required: true })),
3520
+ React.createElement("div", { className: "form-group" },
3521
+ React.createElement("label", { htmlFor: "description" }, "Description"),
3522
+ React.createElement("textarea", { id: "description", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Meeting description (optional)", rows: 3 })),
3523
+ React.createElement("div", { className: "form-group" },
3524
+ React.createElement("label", { htmlFor: "participants" }, "Participants"),
3525
+ React.createElement("input", { id: "participants", type: "text", value: participants, onChange: (e) => setParticipants(e.target.value), placeholder: "user_A, room_101 (comma-separated)", required: true }),
3526
+ React.createElement("small", null, "Enter participant IDs separated by commas")),
3527
+ React.createElement("div", { className: "form-row" },
3528
+ React.createElement("div", { className: "form-group" },
3529
+ React.createElement("label", { htmlFor: "date" }, "Date"),
3530
+ React.createElement("input", { id: "date", type: "date", value: startDate, onChange: (e) => setStartDate(e.target.value), required: true }))),
3531
+ React.createElement("div", { className: "form-row" },
3532
+ React.createElement("div", { className: "form-group" },
3533
+ React.createElement("label", { htmlFor: "startTime" }, "Start Time"),
3534
+ React.createElement("input", { id: "startTime", type: "time", value: startTime, onChange: (e) => setStartTime(e.target.value), required: true })),
3535
+ React.createElement("div", { className: "form-group" },
3536
+ React.createElement("label", { htmlFor: "endTime" }, "End Time"),
3537
+ React.createElement("input", { id: "endTime", type: "time", value: endTime, onChange: (e) => setEndTime(e.target.value), required: true })))),
3538
+ React.createElement("div", { className: "modal-footer" },
3539
+ React.createElement("button", { type: "button", className: "modal-btn modal-btn-secondary", onClick: onClose, disabled: loading }, "Cancel"),
3540
+ React.createElement("button", { type: "submit", className: "modal-btn modal-btn-primary", disabled: loading }, loading ? 'Creating...' : 'Create Booking'))))));
3541
+ };
3542
+
3543
+ var css_248z = ".calendar-container {\r\n width: 100%;\r\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\r\n background: #ffffff;\r\n border-radius: 8px;\r\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\r\n overflow: hidden;\r\n}\r\n\r\n.calendar-header {\r\n background: #f8f9fa;\r\n padding: 20px;\r\n border-bottom: 1px solid #e9ecef;\r\n}\r\n\r\n.calendar-title-section {\r\n display: flex;\r\n justify-content: space-between;\r\n align-items: center;\r\n margin-bottom: 16px;\r\n}\r\n\r\n.calendar-title {\r\n margin: 0;\r\n font-size: 24px;\r\n font-weight: 600;\r\n color: #212529;\r\n}\r\n\r\n.calendar-navigation {\r\n display: flex;\r\n align-items: center;\r\n gap: 12px;\r\n}\r\n\r\n.calendar-current-month {\r\n font-size: 18px;\r\n font-weight: 500;\r\n color: #495057;\r\n margin-left: 12px;\r\n}\r\n\r\n.calendar-btn {\r\n padding: 8px 16px;\r\n border: 1px solid #dee2e6;\r\n background: #ffffff;\r\n border-radius: 4px;\r\n cursor: pointer;\r\n font-size: 14px;\r\n font-weight: 500;\r\n color: #495057;\r\n transition: all 0.2s;\r\n}\r\n\r\n.calendar-btn:hover {\r\n background: #e9ecef;\r\n border-color: #adb5bd;\r\n}\r\n\r\n.calendar-btn-create {\r\n background: #0d6efd;\r\n color: #ffffff;\r\n border-color: #0d6efd;\r\n}\r\n\r\n.calendar-btn-create:hover {\r\n background: #0b5ed7;\r\n border-color: #0a58ca;\r\n}\r\n\r\n.calendar-days-row {\r\n display: grid;\r\n grid-template-columns: repeat(7, 1fr);\r\n background: #f8f9fa;\r\n border-bottom: 2px solid #dee2e6;\r\n}\r\n\r\n.calendar-day-header {\r\n padding: 12px;\r\n text-align: center;\r\n font-weight: 600;\r\n font-size: 14px;\r\n color: #6c757d;\r\n text-transform: uppercase;\r\n}\r\n\r\n.calendar-body {\r\n background: #ffffff;\r\n}\r\n\r\n.calendar-row {\r\n display: grid;\r\n grid-template-columns: repeat(7, 1fr);\r\n border-bottom: 1px solid #e9ecef;\r\n}\r\n\r\n.calendar-row:last-child {\r\n border-bottom: none;\r\n}\r\n\r\n.calendar-cell {\r\n min-height: 120px;\r\n padding: 8px;\r\n border-right: 1px solid #e9ecef;\r\n cursor: pointer;\r\n transition: background-color 0.2s;\r\n position: relative;\r\n}\r\n\r\n.calendar-cell:last-child {\r\n border-right: none;\r\n}\r\n\r\n.calendar-cell:hover {\r\n background: #f8f9fa;\r\n}\r\n\r\n.calendar-cell-disabled {\r\n background: #f8f9fa;\r\n opacity: 0.5;\r\n cursor: not-allowed;\r\n}\r\n\r\n.calendar-cell-disabled:hover {\r\n background: #f8f9fa;\r\n}\r\n\r\n.calendar-cell-today {\r\n background: #e7f5ff;\r\n}\r\n\r\n.calendar-cell-today .calendar-cell-number {\r\n background: #0d6efd;\r\n color: #ffffff;\r\n}\r\n\r\n.calendar-cell-number {\r\n display: inline-flex;\r\n align-items: center;\r\n justify-content: center;\r\n width: 28px;\r\n height: 28px;\r\n border-radius: 50%;\r\n font-weight: 600;\r\n font-size: 14px;\r\n color: #212529;\r\n margin-bottom: 4px;\r\n}\r\n\r\n.calendar-cell-bookings {\r\n margin-top: 4px;\r\n}\r\n\r\n.calendar-booking {\r\n background: #0d6efd;\r\n color: #ffffff;\r\n padding: 4px 8px;\r\n margin-bottom: 4px;\r\n border-radius: 4px;\r\n font-size: 12px;\r\n cursor: pointer;\r\n transition: background-color 0.2s;\r\n display: flex;\r\n gap: 4px;\r\n overflow: hidden;\r\n text-overflow: ellipsis;\r\n white-space: nowrap;\r\n}\r\n\r\n.calendar-booking:hover {\r\n background: #0b5ed7;\r\n}\r\n\r\n.calendar-booking-time {\r\n font-weight: 600;\r\n}\r\n\r\n.calendar-booking-title {\r\n flex: 1;\r\n overflow: hidden;\r\n text-overflow: ellipsis;\r\n}\r\n\r\n.calendar-booking-more {\r\n color: #6c757d;\r\n font-size: 11px;\r\n padding: 2px 4px;\r\n font-weight: 500;\r\n}\r\n\r\n.calendar-error {\r\n background: #f8d7da;\r\n color: #842029;\r\n padding: 12px 20px;\r\n border-bottom: 1px solid #f5c2c7;\r\n}\r\n\r\n.calendar-loading {\r\n background: #cff4fc;\r\n color: #055160;\r\n padding: 12px 20px;\r\n border-bottom: 1px solid #b6effb;\r\n text-align: center;\r\n}\r\n\r\n@media (max-width: 768px) {\r\n .calendar-title-section {\r\n flex-direction: column;\r\n align-items: flex-start;\r\n gap: 12px;\r\n }\r\n\r\n .calendar-cell {\r\n min-height: 80px;\r\n padding: 4px;\r\n }\r\n\r\n .calendar-cell-number {\r\n width: 24px;\r\n height: 24px;\r\n font-size: 12px;\r\n }\r\n\r\n .calendar-booking {\r\n font-size: 10px;\r\n padding: 2px 4px;\r\n }\r\n}\r\n";
3544
+ styleInject(css_248z);
3545
+
3546
+ const Calendar = ({ businessId, resourceId, title = 'Calendar', apiBaseUrl, defaultView = 'month', onBookingCreate, onBookingClick, participants = [], }) => {
3547
+ const [currentDate, setCurrentDate] = useState(new Date());
3548
+ const [bookings, setBookings] = useState([]);
3549
+ const [loading, setLoading] = useState(false);
3550
+ const [error, setError] = useState(null);
3551
+ const [showCreateModal, setShowCreateModal] = useState(false);
3552
+ const [selectedDate, setSelectedDate] = useState(null);
3553
+ const fetchBookings = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
3554
+ setLoading(true);
3555
+ setError(null);
3556
+ try {
3557
+ const monthStart = startOfMonth(currentDate);
3558
+ const monthEnd = endOfMonth(currentDate);
3559
+ const startDate = startOfWeek(monthStart);
3560
+ const endDate = endOfWeek(monthEnd);
3561
+ let fetchedBookings;
3562
+ if (resourceId) {
3563
+ fetchedBookings = yield getResourceSchedule(businessId, resourceId, startDate.toISOString(), endDate.toISOString(), apiBaseUrl);
3564
+ }
3565
+ else {
3566
+ fetchedBookings = yield getAllBookings(businessId, startDate.toISOString(), endDate.toISOString(), apiBaseUrl);
3567
+ }
3568
+ setBookings(fetchedBookings);
3569
+ }
3570
+ catch (err) {
3571
+ setError(err instanceof Error ? err.message : 'Failed to load bookings');
3572
+ }
3573
+ finally {
3574
+ setLoading(false);
3575
+ }
3576
+ }), [businessId, resourceId, currentDate, apiBaseUrl]);
3577
+ useEffect(() => {
3578
+ fetchBookings();
3579
+ }, [fetchBookings]);
3580
+ const handlePreviousMonth = () => {
3581
+ setCurrentDate(subMonths(currentDate, 1));
3582
+ };
3583
+ const handleNextMonth = () => {
3584
+ setCurrentDate(addMonths(currentDate, 1));
3585
+ };
3586
+ const handleToday = () => {
3587
+ setCurrentDate(new Date());
3588
+ };
3589
+ const handleDateClick = (day) => {
3590
+ setSelectedDate(day);
3591
+ setShowCreateModal(true);
3592
+ };
3593
+ const handleBookingCreated = (booking) => __awaiter(void 0, void 0, void 0, function* () {
3594
+ setShowCreateModal(false);
3595
+ setSelectedDate(null);
3596
+ yield fetchBookings();
3597
+ if (onBookingCreate) {
3598
+ onBookingCreate(booking);
3599
+ }
3600
+ });
3601
+ const getBookingsForDay = (day) => {
3602
+ return bookings.filter((booking) => {
3603
+ const bookingStart = parseISO(booking.start);
3604
+ return isSameDay(bookingStart, day);
3605
+ });
3606
+ };
3607
+ const renderHeader = () => {
3608
+ return (React.createElement("div", { className: "calendar-header" },
3609
+ React.createElement("div", { className: "calendar-title-section" },
3610
+ React.createElement("h2", { className: "calendar-title" }, title),
3611
+ React.createElement("button", { className: "calendar-btn calendar-btn-create", onClick: () => setShowCreateModal(true) }, "+ Create Booking")),
3612
+ React.createElement("div", { className: "calendar-navigation" },
3613
+ React.createElement("button", { className: "calendar-btn", onClick: handlePreviousMonth }, "\u2039"),
3614
+ React.createElement("button", { className: "calendar-btn", onClick: handleToday }, "Today"),
3615
+ React.createElement("button", { className: "calendar-btn", onClick: handleNextMonth }, "\u203A"),
3616
+ React.createElement("span", { className: "calendar-current-month" }, format(currentDate, 'MMMM yyyy')))));
3617
+ };
3618
+ const renderDaysOfWeek = () => {
3619
+ const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
3620
+ return (React.createElement("div", { className: "calendar-days-row" }, days.map((day) => (React.createElement("div", { key: day, className: "calendar-day-header" }, day)))));
3621
+ };
3622
+ const renderCells = () => {
3623
+ const monthStart = startOfMonth(currentDate);
3624
+ const monthEnd = endOfMonth(currentDate);
3625
+ const startDate = startOfWeek(monthStart);
3626
+ const endDate = endOfWeek(monthEnd);
3627
+ const rows = [];
3628
+ let days = [];
3629
+ let day = startDate;
3630
+ while (day <= endDate) {
3631
+ for (let i = 0; i < 7; i++) {
3632
+ const currentDay = day;
3633
+ const dayBookings = getBookingsForDay(currentDay);
3634
+ const isCurrentMonth = isSameMonth(currentDay, monthStart);
3635
+ const isToday = isSameDay(currentDay, new Date());
3636
+ days.push(React.createElement("div", { key: day.toString(), className: `calendar-cell ${!isCurrentMonth ? 'calendar-cell-disabled' : ''} ${isToday ? 'calendar-cell-today' : ''}`, onClick: () => isCurrentMonth && handleDateClick(currentDay) },
3637
+ React.createElement("div", { className: "calendar-cell-number" }, format(currentDay, 'd')),
3638
+ React.createElement("div", { className: "calendar-cell-bookings" },
3639
+ dayBookings.slice(0, 3).map((booking, idx) => {
3640
+ var _a, _b;
3641
+ return (React.createElement("div", { key: booking.meeting_id, className: "calendar-booking", onClick: (e) => {
3642
+ e.stopPropagation();
3643
+ if (onBookingClick) {
3644
+ onBookingClick(booking);
3645
+ }
3646
+ }, title: ((_a = booking.metadata) === null || _a === void 0 ? void 0 : _a.title) || 'Untitled' },
3647
+ React.createElement("span", { className: "calendar-booking-time" }, format(parseISO(booking.start), 'HH:mm')),
3648
+ React.createElement("span", { className: "calendar-booking-title" }, ((_b = booking.metadata) === null || _b === void 0 ? void 0 : _b.title) || 'Untitled')));
3649
+ }),
3650
+ dayBookings.length > 3 && (React.createElement("div", { className: "calendar-booking-more" },
3651
+ "+",
3652
+ dayBookings.length - 3,
3653
+ " more")))));
3654
+ day = addDays(day, 1);
3655
+ }
3656
+ rows.push(React.createElement("div", { key: day.toString(), className: "calendar-row" }, days));
3657
+ days = [];
3658
+ }
3659
+ return React.createElement("div", { className: "calendar-body" }, rows);
3660
+ };
3661
+ return (React.createElement("div", { className: "calendar-container" },
3662
+ renderHeader(),
3663
+ error && React.createElement("div", { className: "calendar-error" }, error),
3664
+ loading && React.createElement("div", { className: "calendar-loading" }, "Loading..."),
3665
+ renderDaysOfWeek(),
3666
+ renderCells(),
3667
+ showCreateModal && (React.createElement(CreateBookingModal, { businessId: businessId, apiBaseUrl: apiBaseUrl, initialDate: selectedDate || new Date(), participants: participants, onClose: () => {
3668
+ setShowCreateModal(false);
3669
+ setSelectedDate(null);
3670
+ }, onBookingCreated: handleBookingCreated }))));
3671
+ };
3672
+
3673
+ export { Calendar, createBooking, getAllBookings, getMeetingDetails, getResourceSchedule };
3674
+ //# sourceMappingURL=index.esm.js.map