@hhfenpm/utils 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3380 @@
1
+ function _typeof(o) {
2
+ "@babel/helpers - typeof";
3
+
4
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
5
+ return typeof o;
6
+ } : function (o) {
7
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
8
+ }, _typeof(o);
9
+ }
10
+
11
+ function requiredArgs(required, args) {
12
+ if (args.length < required) {
13
+ throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
14
+ }
15
+ }
16
+
17
+ /**
18
+ * @name isDate
19
+ * @category Common Helpers
20
+ * @summary Is the given value a date?
21
+ *
22
+ * @description
23
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
24
+ *
25
+ * @param {*} value - the value to check
26
+ * @returns {boolean} true if the given value is a date
27
+ * @throws {TypeError} 1 arguments required
28
+ *
29
+ * @example
30
+ * // For a valid date:
31
+ * const result = isDate(new Date())
32
+ * //=> true
33
+ *
34
+ * @example
35
+ * // For an invalid date:
36
+ * const result = isDate(new Date(NaN))
37
+ * //=> true
38
+ *
39
+ * @example
40
+ * // For some value:
41
+ * const result = isDate('2014-02-31')
42
+ * //=> false
43
+ *
44
+ * @example
45
+ * // For an object:
46
+ * const result = isDate({})
47
+ * //=> false
48
+ */
49
+ function isDate(value) {
50
+ requiredArgs(1, arguments);
51
+ return value instanceof Date || _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
52
+ }
53
+
54
+ /**
55
+ * @name toDate
56
+ * @category Common Helpers
57
+ * @summary Convert the given argument to an instance of Date.
58
+ *
59
+ * @description
60
+ * Convert the given argument to an instance of Date.
61
+ *
62
+ * If the argument is an instance of Date, the function returns its clone.
63
+ *
64
+ * If the argument is a number, it is treated as a timestamp.
65
+ *
66
+ * If the argument is none of the above, the function returns Invalid Date.
67
+ *
68
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
69
+ *
70
+ * @param {Date|Number} argument - the value to convert
71
+ * @returns {Date} the parsed date in the local time zone
72
+ * @throws {TypeError} 1 argument required
73
+ *
74
+ * @example
75
+ * // Clone the date:
76
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
77
+ * //=> Tue Feb 11 2014 11:30:30
78
+ *
79
+ * @example
80
+ * // Convert the timestamp to date:
81
+ * const result = toDate(1392098430000)
82
+ * //=> Tue Feb 11 2014 11:30:30
83
+ */
84
+ function toDate(argument) {
85
+ requiredArgs(1, arguments);
86
+ var argStr = Object.prototype.toString.call(argument);
87
+
88
+ // Clone the date
89
+ if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
90
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
91
+ return new Date(argument.getTime());
92
+ } else if (typeof argument === 'number' || argStr === '[object Number]') {
93
+ return new Date(argument);
94
+ } else {
95
+ if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
96
+ // eslint-disable-next-line no-console
97
+ console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
98
+ // eslint-disable-next-line no-console
99
+ console.warn(new Error().stack);
100
+ }
101
+ return new Date(NaN);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * @name isValid
107
+ * @category Common Helpers
108
+ * @summary Is the given date valid?
109
+ *
110
+ * @description
111
+ * Returns false if argument is Invalid Date and true otherwise.
112
+ * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
113
+ * Invalid Date is a Date, whose time value is NaN.
114
+ *
115
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
116
+ *
117
+ * @param {*} date - the date to check
118
+ * @returns {Boolean} the date is valid
119
+ * @throws {TypeError} 1 argument required
120
+ *
121
+ * @example
122
+ * // For the valid date:
123
+ * const result = isValid(new Date(2014, 1, 31))
124
+ * //=> true
125
+ *
126
+ * @example
127
+ * // For the value, convertable into a date:
128
+ * const result = isValid(1393804800000)
129
+ * //=> true
130
+ *
131
+ * @example
132
+ * // For the invalid date:
133
+ * const result = isValid(new Date(''))
134
+ * //=> false
135
+ */
136
+ function isValid(dirtyDate) {
137
+ requiredArgs(1, arguments);
138
+ if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
139
+ return false;
140
+ }
141
+ var date = toDate(dirtyDate);
142
+ return !isNaN(Number(date));
143
+ }
144
+
145
+ function toInteger(dirtyNumber) {
146
+ if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
147
+ return NaN;
148
+ }
149
+ var number = Number(dirtyNumber);
150
+ if (isNaN(number)) {
151
+ return number;
152
+ }
153
+ return number < 0 ? Math.ceil(number) : Math.floor(number);
154
+ }
155
+
156
+ /**
157
+ * @name addMilliseconds
158
+ * @category Millisecond Helpers
159
+ * @summary Add the specified number of milliseconds to the given date.
160
+ *
161
+ * @description
162
+ * Add the specified number of milliseconds to the given date.
163
+ *
164
+ * @param {Date|Number} date - the date to be changed
165
+ * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
166
+ * @returns {Date} the new date with the milliseconds added
167
+ * @throws {TypeError} 2 arguments required
168
+ *
169
+ * @example
170
+ * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
171
+ * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
172
+ * //=> Thu Jul 10 2014 12:45:30.750
173
+ */
174
+ function addMilliseconds(dirtyDate, dirtyAmount) {
175
+ requiredArgs(2, arguments);
176
+ var timestamp = toDate(dirtyDate).getTime();
177
+ var amount = toInteger(dirtyAmount);
178
+ return new Date(timestamp + amount);
179
+ }
180
+
181
+ /**
182
+ * @name subMilliseconds
183
+ * @category Millisecond Helpers
184
+ * @summary Subtract the specified number of milliseconds from the given date.
185
+ *
186
+ * @description
187
+ * Subtract the specified number of milliseconds from the given date.
188
+ *
189
+ * @param {Date|Number} date - the date to be changed
190
+ * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
191
+ * @returns {Date} the new date with the milliseconds subtracted
192
+ * @throws {TypeError} 2 arguments required
193
+ *
194
+ * @example
195
+ * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
196
+ * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
197
+ * //=> Thu Jul 10 2014 12:45:29.250
198
+ */
199
+ function subMilliseconds(dirtyDate, dirtyAmount) {
200
+ requiredArgs(2, arguments);
201
+ var amount = toInteger(dirtyAmount);
202
+ return addMilliseconds(dirtyDate, -amount);
203
+ }
204
+
205
+ var MILLISECONDS_IN_DAY = 86400000;
206
+ function getUTCDayOfYear(dirtyDate) {
207
+ requiredArgs(1, arguments);
208
+ var date = toDate(dirtyDate);
209
+ var timestamp = date.getTime();
210
+ date.setUTCMonth(0, 1);
211
+ date.setUTCHours(0, 0, 0, 0);
212
+ var startOfYearTimestamp = date.getTime();
213
+ var difference = timestamp - startOfYearTimestamp;
214
+ return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
215
+ }
216
+
217
+ function startOfUTCISOWeek(dirtyDate) {
218
+ requiredArgs(1, arguments);
219
+ var weekStartsOn = 1;
220
+ var date = toDate(dirtyDate);
221
+ var day = date.getUTCDay();
222
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
223
+ date.setUTCDate(date.getUTCDate() - diff);
224
+ date.setUTCHours(0, 0, 0, 0);
225
+ return date;
226
+ }
227
+
228
+ function getUTCISOWeekYear(dirtyDate) {
229
+ requiredArgs(1, arguments);
230
+ var date = toDate(dirtyDate);
231
+ var year = date.getUTCFullYear();
232
+ var fourthOfJanuaryOfNextYear = new Date(0);
233
+ fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
234
+ fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
235
+ var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
236
+ var fourthOfJanuaryOfThisYear = new Date(0);
237
+ fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
238
+ fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
239
+ var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
240
+ if (date.getTime() >= startOfNextYear.getTime()) {
241
+ return year + 1;
242
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
243
+ return year;
244
+ } else {
245
+ return year - 1;
246
+ }
247
+ }
248
+
249
+ function startOfUTCISOWeekYear(dirtyDate) {
250
+ requiredArgs(1, arguments);
251
+ var year = getUTCISOWeekYear(dirtyDate);
252
+ var fourthOfJanuary = new Date(0);
253
+ fourthOfJanuary.setUTCFullYear(year, 0, 4);
254
+ fourthOfJanuary.setUTCHours(0, 0, 0, 0);
255
+ var date = startOfUTCISOWeek(fourthOfJanuary);
256
+ return date;
257
+ }
258
+
259
+ var MILLISECONDS_IN_WEEK$1 = 604800000;
260
+ function getUTCISOWeek(dirtyDate) {
261
+ requiredArgs(1, arguments);
262
+ var date = toDate(dirtyDate);
263
+ var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
264
+
265
+ // Round the number of days to the nearest integer
266
+ // because the number of milliseconds in a week is not constant
267
+ // (e.g. it's different in the week of the daylight saving time clock shift)
268
+ return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
269
+ }
270
+
271
+ var defaultOptions = {};
272
+ function getDefaultOptions() {
273
+ return defaultOptions;
274
+ }
275
+
276
+ function startOfUTCWeek(dirtyDate, options) {
277
+ var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
278
+ requiredArgs(1, arguments);
279
+ var defaultOptions = getDefaultOptions();
280
+ var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
281
+
282
+ // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
283
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
284
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
285
+ }
286
+ var date = toDate(dirtyDate);
287
+ var day = date.getUTCDay();
288
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
289
+ date.setUTCDate(date.getUTCDate() - diff);
290
+ date.setUTCHours(0, 0, 0, 0);
291
+ return date;
292
+ }
293
+
294
+ function getUTCWeekYear(dirtyDate, options) {
295
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
296
+ requiredArgs(1, arguments);
297
+ var date = toDate(dirtyDate);
298
+ var year = date.getUTCFullYear();
299
+ var defaultOptions = getDefaultOptions();
300
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
301
+
302
+ // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
303
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
304
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
305
+ }
306
+ var firstWeekOfNextYear = new Date(0);
307
+ firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
308
+ firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
309
+ var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
310
+ var firstWeekOfThisYear = new Date(0);
311
+ firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
312
+ firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
313
+ var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
314
+ if (date.getTime() >= startOfNextYear.getTime()) {
315
+ return year + 1;
316
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
317
+ return year;
318
+ } else {
319
+ return year - 1;
320
+ }
321
+ }
322
+
323
+ function startOfUTCWeekYear(dirtyDate, options) {
324
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
325
+ requiredArgs(1, arguments);
326
+ var defaultOptions = getDefaultOptions();
327
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
328
+ var year = getUTCWeekYear(dirtyDate, options);
329
+ var firstWeek = new Date(0);
330
+ firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
331
+ firstWeek.setUTCHours(0, 0, 0, 0);
332
+ var date = startOfUTCWeek(firstWeek, options);
333
+ return date;
334
+ }
335
+
336
+ var MILLISECONDS_IN_WEEK = 604800000;
337
+ function getUTCWeek(dirtyDate, options) {
338
+ requiredArgs(1, arguments);
339
+ var date = toDate(dirtyDate);
340
+ var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
341
+
342
+ // Round the number of days to the nearest integer
343
+ // because the number of milliseconds in a week is not constant
344
+ // (e.g. it's different in the week of the daylight saving time clock shift)
345
+ return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
346
+ }
347
+
348
+ function addLeadingZeros(number, targetLength) {
349
+ var sign = number < 0 ? '-' : '';
350
+ var output = Math.abs(number).toString();
351
+ while (output.length < targetLength) {
352
+ output = '0' + output;
353
+ }
354
+ return sign + output;
355
+ }
356
+
357
+ /*
358
+ * | | Unit | | Unit |
359
+ * |-----|--------------------------------|-----|--------------------------------|
360
+ * | a | AM, PM | A* | |
361
+ * | d | Day of month | D | |
362
+ * | h | Hour [1-12] | H | Hour [0-23] |
363
+ * | m | Minute | M | Month |
364
+ * | s | Second | S | Fraction of second |
365
+ * | y | Year (abs) | Y | |
366
+ *
367
+ * Letters marked by * are not implemented but reserved by Unicode standard.
368
+ */
369
+ var formatters$2 = {
370
+ // Year
371
+ y: function y(date, token) {
372
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
373
+ // | Year | y | yy | yyy | yyyy | yyyyy |
374
+ // |----------|-------|----|-------|-------|-------|
375
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
376
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
377
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
378
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
379
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
380
+
381
+ var signedYear = date.getUTCFullYear();
382
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
383
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
384
+ return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
385
+ },
386
+ // Month
387
+ M: function M(date, token) {
388
+ var month = date.getUTCMonth();
389
+ return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
390
+ },
391
+ // Day of the month
392
+ d: function d(date, token) {
393
+ return addLeadingZeros(date.getUTCDate(), token.length);
394
+ },
395
+ // AM or PM
396
+ a: function a(date, token) {
397
+ var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
398
+ switch (token) {
399
+ case 'a':
400
+ case 'aa':
401
+ return dayPeriodEnumValue.toUpperCase();
402
+ case 'aaa':
403
+ return dayPeriodEnumValue;
404
+ case 'aaaaa':
405
+ return dayPeriodEnumValue[0];
406
+ case 'aaaa':
407
+ default:
408
+ return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
409
+ }
410
+ },
411
+ // Hour [1-12]
412
+ h: function h(date, token) {
413
+ return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
414
+ },
415
+ // Hour [0-23]
416
+ H: function H(date, token) {
417
+ return addLeadingZeros(date.getUTCHours(), token.length);
418
+ },
419
+ // Minute
420
+ m: function m(date, token) {
421
+ return addLeadingZeros(date.getUTCMinutes(), token.length);
422
+ },
423
+ // Second
424
+ s: function s(date, token) {
425
+ return addLeadingZeros(date.getUTCSeconds(), token.length);
426
+ },
427
+ // Fraction of second
428
+ S: function S(date, token) {
429
+ var numberOfDigits = token.length;
430
+ var milliseconds = date.getUTCMilliseconds();
431
+ var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
432
+ return addLeadingZeros(fractionalSeconds, token.length);
433
+ }
434
+ };
435
+ var lightFormatters = formatters$2;
436
+
437
+ var dayPeriodEnum = {
438
+ am: 'am',
439
+ pm: 'pm',
440
+ midnight: 'midnight',
441
+ noon: 'noon',
442
+ morning: 'morning',
443
+ afternoon: 'afternoon',
444
+ evening: 'evening',
445
+ night: 'night'
446
+ };
447
+ /*
448
+ * | | Unit | | Unit |
449
+ * |-----|--------------------------------|-----|--------------------------------|
450
+ * | a | AM, PM | A* | Milliseconds in day |
451
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
452
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
453
+ * | d | Day of month | D | Day of year |
454
+ * | e | Local day of week | E | Day of week |
455
+ * | f | | F* | Day of week in month |
456
+ * | g* | Modified Julian day | G | Era |
457
+ * | h | Hour [1-12] | H | Hour [0-23] |
458
+ * | i! | ISO day of week | I! | ISO week of year |
459
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
460
+ * | k | Hour [1-24] | K | Hour [0-11] |
461
+ * | l* | (deprecated) | L | Stand-alone month |
462
+ * | m | Minute | M | Month |
463
+ * | n | | N | |
464
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
465
+ * | p! | Long localized time | P! | Long localized date |
466
+ * | q | Stand-alone quarter | Q | Quarter |
467
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
468
+ * | s | Second | S | Fraction of second |
469
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
470
+ * | u | Extended year | U* | Cyclic year |
471
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
472
+ * | w | Local week of year | W* | Week of month |
473
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
474
+ * | y | Year (abs) | Y | Local week-numbering year |
475
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
476
+ *
477
+ * Letters marked by * are not implemented but reserved by Unicode standard.
478
+ *
479
+ * Letters marked by ! are non-standard, but implemented by date-fns:
480
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
481
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
482
+ * i.e. 7 for Sunday, 1 for Monday, etc.
483
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
484
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
485
+ * `R` is supposed to be used in conjunction with `I` and `i`
486
+ * for universal ISO week-numbering date, whereas
487
+ * `Y` is supposed to be used in conjunction with `w` and `e`
488
+ * for week-numbering date specific to the locale.
489
+ * - `P` is long localized date format
490
+ * - `p` is long localized time format
491
+ */
492
+
493
+ var formatters = {
494
+ // Era
495
+ G: function G(date, token, localize) {
496
+ var era = date.getUTCFullYear() > 0 ? 1 : 0;
497
+ switch (token) {
498
+ // AD, BC
499
+ case 'G':
500
+ case 'GG':
501
+ case 'GGG':
502
+ return localize.era(era, {
503
+ width: 'abbreviated'
504
+ });
505
+ // A, B
506
+ case 'GGGGG':
507
+ return localize.era(era, {
508
+ width: 'narrow'
509
+ });
510
+ // Anno Domini, Before Christ
511
+ case 'GGGG':
512
+ default:
513
+ return localize.era(era, {
514
+ width: 'wide'
515
+ });
516
+ }
517
+ },
518
+ // Year
519
+ y: function y(date, token, localize) {
520
+ // Ordinal number
521
+ if (token === 'yo') {
522
+ var signedYear = date.getUTCFullYear();
523
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
524
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
525
+ return localize.ordinalNumber(year, {
526
+ unit: 'year'
527
+ });
528
+ }
529
+ return lightFormatters.y(date, token);
530
+ },
531
+ // Local week-numbering year
532
+ Y: function Y(date, token, localize, options) {
533
+ var signedWeekYear = getUTCWeekYear(date, options);
534
+ // Returns 1 for 1 BC (which is year 0 in JavaScript)
535
+ var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
536
+
537
+ // Two digit year
538
+ if (token === 'YY') {
539
+ var twoDigitYear = weekYear % 100;
540
+ return addLeadingZeros(twoDigitYear, 2);
541
+ }
542
+
543
+ // Ordinal number
544
+ if (token === 'Yo') {
545
+ return localize.ordinalNumber(weekYear, {
546
+ unit: 'year'
547
+ });
548
+ }
549
+
550
+ // Padding
551
+ return addLeadingZeros(weekYear, token.length);
552
+ },
553
+ // ISO week-numbering year
554
+ R: function R(date, token) {
555
+ var isoWeekYear = getUTCISOWeekYear(date);
556
+
557
+ // Padding
558
+ return addLeadingZeros(isoWeekYear, token.length);
559
+ },
560
+ // Extended year. This is a single number designating the year of this calendar system.
561
+ // The main difference between `y` and `u` localizers are B.C. years:
562
+ // | Year | `y` | `u` |
563
+ // |------|-----|-----|
564
+ // | AC 1 | 1 | 1 |
565
+ // | BC 1 | 1 | 0 |
566
+ // | BC 2 | 2 | -1 |
567
+ // Also `yy` always returns the last two digits of a year,
568
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
569
+ u: function u(date, token) {
570
+ var year = date.getUTCFullYear();
571
+ return addLeadingZeros(year, token.length);
572
+ },
573
+ // Quarter
574
+ Q: function Q(date, token, localize) {
575
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
576
+ switch (token) {
577
+ // 1, 2, 3, 4
578
+ case 'Q':
579
+ return String(quarter);
580
+ // 01, 02, 03, 04
581
+ case 'QQ':
582
+ return addLeadingZeros(quarter, 2);
583
+ // 1st, 2nd, 3rd, 4th
584
+ case 'Qo':
585
+ return localize.ordinalNumber(quarter, {
586
+ unit: 'quarter'
587
+ });
588
+ // Q1, Q2, Q3, Q4
589
+ case 'QQQ':
590
+ return localize.quarter(quarter, {
591
+ width: 'abbreviated',
592
+ context: 'formatting'
593
+ });
594
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
595
+ case 'QQQQQ':
596
+ return localize.quarter(quarter, {
597
+ width: 'narrow',
598
+ context: 'formatting'
599
+ });
600
+ // 1st quarter, 2nd quarter, ...
601
+ case 'QQQQ':
602
+ default:
603
+ return localize.quarter(quarter, {
604
+ width: 'wide',
605
+ context: 'formatting'
606
+ });
607
+ }
608
+ },
609
+ // Stand-alone quarter
610
+ q: function q(date, token, localize) {
611
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
612
+ switch (token) {
613
+ // 1, 2, 3, 4
614
+ case 'q':
615
+ return String(quarter);
616
+ // 01, 02, 03, 04
617
+ case 'qq':
618
+ return addLeadingZeros(quarter, 2);
619
+ // 1st, 2nd, 3rd, 4th
620
+ case 'qo':
621
+ return localize.ordinalNumber(quarter, {
622
+ unit: 'quarter'
623
+ });
624
+ // Q1, Q2, Q3, Q4
625
+ case 'qqq':
626
+ return localize.quarter(quarter, {
627
+ width: 'abbreviated',
628
+ context: 'standalone'
629
+ });
630
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
631
+ case 'qqqqq':
632
+ return localize.quarter(quarter, {
633
+ width: 'narrow',
634
+ context: 'standalone'
635
+ });
636
+ // 1st quarter, 2nd quarter, ...
637
+ case 'qqqq':
638
+ default:
639
+ return localize.quarter(quarter, {
640
+ width: 'wide',
641
+ context: 'standalone'
642
+ });
643
+ }
644
+ },
645
+ // Month
646
+ M: function M(date, token, localize) {
647
+ var month = date.getUTCMonth();
648
+ switch (token) {
649
+ case 'M':
650
+ case 'MM':
651
+ return lightFormatters.M(date, token);
652
+ // 1st, 2nd, ..., 12th
653
+ case 'Mo':
654
+ return localize.ordinalNumber(month + 1, {
655
+ unit: 'month'
656
+ });
657
+ // Jan, Feb, ..., Dec
658
+ case 'MMM':
659
+ return localize.month(month, {
660
+ width: 'abbreviated',
661
+ context: 'formatting'
662
+ });
663
+ // J, F, ..., D
664
+ case 'MMMMM':
665
+ return localize.month(month, {
666
+ width: 'narrow',
667
+ context: 'formatting'
668
+ });
669
+ // January, February, ..., December
670
+ case 'MMMM':
671
+ default:
672
+ return localize.month(month, {
673
+ width: 'wide',
674
+ context: 'formatting'
675
+ });
676
+ }
677
+ },
678
+ // Stand-alone month
679
+ L: function L(date, token, localize) {
680
+ var month = date.getUTCMonth();
681
+ switch (token) {
682
+ // 1, 2, ..., 12
683
+ case 'L':
684
+ return String(month + 1);
685
+ // 01, 02, ..., 12
686
+ case 'LL':
687
+ return addLeadingZeros(month + 1, 2);
688
+ // 1st, 2nd, ..., 12th
689
+ case 'Lo':
690
+ return localize.ordinalNumber(month + 1, {
691
+ unit: 'month'
692
+ });
693
+ // Jan, Feb, ..., Dec
694
+ case 'LLL':
695
+ return localize.month(month, {
696
+ width: 'abbreviated',
697
+ context: 'standalone'
698
+ });
699
+ // J, F, ..., D
700
+ case 'LLLLL':
701
+ return localize.month(month, {
702
+ width: 'narrow',
703
+ context: 'standalone'
704
+ });
705
+ // January, February, ..., December
706
+ case 'LLLL':
707
+ default:
708
+ return localize.month(month, {
709
+ width: 'wide',
710
+ context: 'standalone'
711
+ });
712
+ }
713
+ },
714
+ // Local week of year
715
+ w: function w(date, token, localize, options) {
716
+ var week = getUTCWeek(date, options);
717
+ if (token === 'wo') {
718
+ return localize.ordinalNumber(week, {
719
+ unit: 'week'
720
+ });
721
+ }
722
+ return addLeadingZeros(week, token.length);
723
+ },
724
+ // ISO week of year
725
+ I: function I(date, token, localize) {
726
+ var isoWeek = getUTCISOWeek(date);
727
+ if (token === 'Io') {
728
+ return localize.ordinalNumber(isoWeek, {
729
+ unit: 'week'
730
+ });
731
+ }
732
+ return addLeadingZeros(isoWeek, token.length);
733
+ },
734
+ // Day of the month
735
+ d: function d(date, token, localize) {
736
+ if (token === 'do') {
737
+ return localize.ordinalNumber(date.getUTCDate(), {
738
+ unit: 'date'
739
+ });
740
+ }
741
+ return lightFormatters.d(date, token);
742
+ },
743
+ // Day of year
744
+ D: function D(date, token, localize) {
745
+ var dayOfYear = getUTCDayOfYear(date);
746
+ if (token === 'Do') {
747
+ return localize.ordinalNumber(dayOfYear, {
748
+ unit: 'dayOfYear'
749
+ });
750
+ }
751
+ return addLeadingZeros(dayOfYear, token.length);
752
+ },
753
+ // Day of week
754
+ E: function E(date, token, localize) {
755
+ var dayOfWeek = date.getUTCDay();
756
+ switch (token) {
757
+ // Tue
758
+ case 'E':
759
+ case 'EE':
760
+ case 'EEE':
761
+ return localize.day(dayOfWeek, {
762
+ width: 'abbreviated',
763
+ context: 'formatting'
764
+ });
765
+ // T
766
+ case 'EEEEE':
767
+ return localize.day(dayOfWeek, {
768
+ width: 'narrow',
769
+ context: 'formatting'
770
+ });
771
+ // Tu
772
+ case 'EEEEEE':
773
+ return localize.day(dayOfWeek, {
774
+ width: 'short',
775
+ context: 'formatting'
776
+ });
777
+ // Tuesday
778
+ case 'EEEE':
779
+ default:
780
+ return localize.day(dayOfWeek, {
781
+ width: 'wide',
782
+ context: 'formatting'
783
+ });
784
+ }
785
+ },
786
+ // Local day of week
787
+ e: function e(date, token, localize, options) {
788
+ var dayOfWeek = date.getUTCDay();
789
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
790
+ switch (token) {
791
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
792
+ case 'e':
793
+ return String(localDayOfWeek);
794
+ // Padded numerical value
795
+ case 'ee':
796
+ return addLeadingZeros(localDayOfWeek, 2);
797
+ // 1st, 2nd, ..., 7th
798
+ case 'eo':
799
+ return localize.ordinalNumber(localDayOfWeek, {
800
+ unit: 'day'
801
+ });
802
+ case 'eee':
803
+ return localize.day(dayOfWeek, {
804
+ width: 'abbreviated',
805
+ context: 'formatting'
806
+ });
807
+ // T
808
+ case 'eeeee':
809
+ return localize.day(dayOfWeek, {
810
+ width: 'narrow',
811
+ context: 'formatting'
812
+ });
813
+ // Tu
814
+ case 'eeeeee':
815
+ return localize.day(dayOfWeek, {
816
+ width: 'short',
817
+ context: 'formatting'
818
+ });
819
+ // Tuesday
820
+ case 'eeee':
821
+ default:
822
+ return localize.day(dayOfWeek, {
823
+ width: 'wide',
824
+ context: 'formatting'
825
+ });
826
+ }
827
+ },
828
+ // Stand-alone local day of week
829
+ c: function c(date, token, localize, options) {
830
+ var dayOfWeek = date.getUTCDay();
831
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
832
+ switch (token) {
833
+ // Numerical value (same as in `e`)
834
+ case 'c':
835
+ return String(localDayOfWeek);
836
+ // Padded numerical value
837
+ case 'cc':
838
+ return addLeadingZeros(localDayOfWeek, token.length);
839
+ // 1st, 2nd, ..., 7th
840
+ case 'co':
841
+ return localize.ordinalNumber(localDayOfWeek, {
842
+ unit: 'day'
843
+ });
844
+ case 'ccc':
845
+ return localize.day(dayOfWeek, {
846
+ width: 'abbreviated',
847
+ context: 'standalone'
848
+ });
849
+ // T
850
+ case 'ccccc':
851
+ return localize.day(dayOfWeek, {
852
+ width: 'narrow',
853
+ context: 'standalone'
854
+ });
855
+ // Tu
856
+ case 'cccccc':
857
+ return localize.day(dayOfWeek, {
858
+ width: 'short',
859
+ context: 'standalone'
860
+ });
861
+ // Tuesday
862
+ case 'cccc':
863
+ default:
864
+ return localize.day(dayOfWeek, {
865
+ width: 'wide',
866
+ context: 'standalone'
867
+ });
868
+ }
869
+ },
870
+ // ISO day of week
871
+ i: function i(date, token, localize) {
872
+ var dayOfWeek = date.getUTCDay();
873
+ var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
874
+ switch (token) {
875
+ // 2
876
+ case 'i':
877
+ return String(isoDayOfWeek);
878
+ // 02
879
+ case 'ii':
880
+ return addLeadingZeros(isoDayOfWeek, token.length);
881
+ // 2nd
882
+ case 'io':
883
+ return localize.ordinalNumber(isoDayOfWeek, {
884
+ unit: 'day'
885
+ });
886
+ // Tue
887
+ case 'iii':
888
+ return localize.day(dayOfWeek, {
889
+ width: 'abbreviated',
890
+ context: 'formatting'
891
+ });
892
+ // T
893
+ case 'iiiii':
894
+ return localize.day(dayOfWeek, {
895
+ width: 'narrow',
896
+ context: 'formatting'
897
+ });
898
+ // Tu
899
+ case 'iiiiii':
900
+ return localize.day(dayOfWeek, {
901
+ width: 'short',
902
+ context: 'formatting'
903
+ });
904
+ // Tuesday
905
+ case 'iiii':
906
+ default:
907
+ return localize.day(dayOfWeek, {
908
+ width: 'wide',
909
+ context: 'formatting'
910
+ });
911
+ }
912
+ },
913
+ // AM or PM
914
+ a: function a(date, token, localize) {
915
+ var hours = date.getUTCHours();
916
+ var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
917
+ switch (token) {
918
+ case 'a':
919
+ case 'aa':
920
+ return localize.dayPeriod(dayPeriodEnumValue, {
921
+ width: 'abbreviated',
922
+ context: 'formatting'
923
+ });
924
+ case 'aaa':
925
+ return localize.dayPeriod(dayPeriodEnumValue, {
926
+ width: 'abbreviated',
927
+ context: 'formatting'
928
+ }).toLowerCase();
929
+ case 'aaaaa':
930
+ return localize.dayPeriod(dayPeriodEnumValue, {
931
+ width: 'narrow',
932
+ context: 'formatting'
933
+ });
934
+ case 'aaaa':
935
+ default:
936
+ return localize.dayPeriod(dayPeriodEnumValue, {
937
+ width: 'wide',
938
+ context: 'formatting'
939
+ });
940
+ }
941
+ },
942
+ // AM, PM, midnight, noon
943
+ b: function b(date, token, localize) {
944
+ var hours = date.getUTCHours();
945
+ var dayPeriodEnumValue;
946
+ if (hours === 12) {
947
+ dayPeriodEnumValue = dayPeriodEnum.noon;
948
+ } else if (hours === 0) {
949
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
950
+ } else {
951
+ dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
952
+ }
953
+ switch (token) {
954
+ case 'b':
955
+ case 'bb':
956
+ return localize.dayPeriod(dayPeriodEnumValue, {
957
+ width: 'abbreviated',
958
+ context: 'formatting'
959
+ });
960
+ case 'bbb':
961
+ return localize.dayPeriod(dayPeriodEnumValue, {
962
+ width: 'abbreviated',
963
+ context: 'formatting'
964
+ }).toLowerCase();
965
+ case 'bbbbb':
966
+ return localize.dayPeriod(dayPeriodEnumValue, {
967
+ width: 'narrow',
968
+ context: 'formatting'
969
+ });
970
+ case 'bbbb':
971
+ default:
972
+ return localize.dayPeriod(dayPeriodEnumValue, {
973
+ width: 'wide',
974
+ context: 'formatting'
975
+ });
976
+ }
977
+ },
978
+ // in the morning, in the afternoon, in the evening, at night
979
+ B: function B(date, token, localize) {
980
+ var hours = date.getUTCHours();
981
+ var dayPeriodEnumValue;
982
+ if (hours >= 17) {
983
+ dayPeriodEnumValue = dayPeriodEnum.evening;
984
+ } else if (hours >= 12) {
985
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
986
+ } else if (hours >= 4) {
987
+ dayPeriodEnumValue = dayPeriodEnum.morning;
988
+ } else {
989
+ dayPeriodEnumValue = dayPeriodEnum.night;
990
+ }
991
+ switch (token) {
992
+ case 'B':
993
+ case 'BB':
994
+ case 'BBB':
995
+ return localize.dayPeriod(dayPeriodEnumValue, {
996
+ width: 'abbreviated',
997
+ context: 'formatting'
998
+ });
999
+ case 'BBBBB':
1000
+ return localize.dayPeriod(dayPeriodEnumValue, {
1001
+ width: 'narrow',
1002
+ context: 'formatting'
1003
+ });
1004
+ case 'BBBB':
1005
+ default:
1006
+ return localize.dayPeriod(dayPeriodEnumValue, {
1007
+ width: 'wide',
1008
+ context: 'formatting'
1009
+ });
1010
+ }
1011
+ },
1012
+ // Hour [1-12]
1013
+ h: function h(date, token, localize) {
1014
+ if (token === 'ho') {
1015
+ var hours = date.getUTCHours() % 12;
1016
+ if (hours === 0) hours = 12;
1017
+ return localize.ordinalNumber(hours, {
1018
+ unit: 'hour'
1019
+ });
1020
+ }
1021
+ return lightFormatters.h(date, token);
1022
+ },
1023
+ // Hour [0-23]
1024
+ H: function H(date, token, localize) {
1025
+ if (token === 'Ho') {
1026
+ return localize.ordinalNumber(date.getUTCHours(), {
1027
+ unit: 'hour'
1028
+ });
1029
+ }
1030
+ return lightFormatters.H(date, token);
1031
+ },
1032
+ // Hour [0-11]
1033
+ K: function K(date, token, localize) {
1034
+ var hours = date.getUTCHours() % 12;
1035
+ if (token === 'Ko') {
1036
+ return localize.ordinalNumber(hours, {
1037
+ unit: 'hour'
1038
+ });
1039
+ }
1040
+ return addLeadingZeros(hours, token.length);
1041
+ },
1042
+ // Hour [1-24]
1043
+ k: function k(date, token, localize) {
1044
+ var hours = date.getUTCHours();
1045
+ if (hours === 0) hours = 24;
1046
+ if (token === 'ko') {
1047
+ return localize.ordinalNumber(hours, {
1048
+ unit: 'hour'
1049
+ });
1050
+ }
1051
+ return addLeadingZeros(hours, token.length);
1052
+ },
1053
+ // Minute
1054
+ m: function m(date, token, localize) {
1055
+ if (token === 'mo') {
1056
+ return localize.ordinalNumber(date.getUTCMinutes(), {
1057
+ unit: 'minute'
1058
+ });
1059
+ }
1060
+ return lightFormatters.m(date, token);
1061
+ },
1062
+ // Second
1063
+ s: function s(date, token, localize) {
1064
+ if (token === 'so') {
1065
+ return localize.ordinalNumber(date.getUTCSeconds(), {
1066
+ unit: 'second'
1067
+ });
1068
+ }
1069
+ return lightFormatters.s(date, token);
1070
+ },
1071
+ // Fraction of second
1072
+ S: function S(date, token) {
1073
+ return lightFormatters.S(date, token);
1074
+ },
1075
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
1076
+ X: function X(date, token, _localize, options) {
1077
+ var originalDate = options._originalDate || date;
1078
+ var timezoneOffset = originalDate.getTimezoneOffset();
1079
+ if (timezoneOffset === 0) {
1080
+ return 'Z';
1081
+ }
1082
+ switch (token) {
1083
+ // Hours and optional minutes
1084
+ case 'X':
1085
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1086
+
1087
+ // Hours, minutes and optional seconds without `:` delimiter
1088
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1089
+ // so this token always has the same output as `XX`
1090
+ case 'XXXX':
1091
+ case 'XX':
1092
+ // Hours and minutes without `:` delimiter
1093
+ return formatTimezone(timezoneOffset);
1094
+
1095
+ // Hours, minutes and optional seconds with `:` delimiter
1096
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1097
+ // so this token always has the same output as `XXX`
1098
+ case 'XXXXX':
1099
+ case 'XXX': // Hours and minutes with `:` delimiter
1100
+ default:
1101
+ return formatTimezone(timezoneOffset, ':');
1102
+ }
1103
+ },
1104
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
1105
+ x: function x(date, token, _localize, options) {
1106
+ var originalDate = options._originalDate || date;
1107
+ var timezoneOffset = originalDate.getTimezoneOffset();
1108
+ switch (token) {
1109
+ // Hours and optional minutes
1110
+ case 'x':
1111
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1112
+
1113
+ // Hours, minutes and optional seconds without `:` delimiter
1114
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1115
+ // so this token always has the same output as `xx`
1116
+ case 'xxxx':
1117
+ case 'xx':
1118
+ // Hours and minutes without `:` delimiter
1119
+ return formatTimezone(timezoneOffset);
1120
+
1121
+ // Hours, minutes and optional seconds with `:` delimiter
1122
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1123
+ // so this token always has the same output as `xxx`
1124
+ case 'xxxxx':
1125
+ case 'xxx': // Hours and minutes with `:` delimiter
1126
+ default:
1127
+ return formatTimezone(timezoneOffset, ':');
1128
+ }
1129
+ },
1130
+ // Timezone (GMT)
1131
+ O: function O(date, token, _localize, options) {
1132
+ var originalDate = options._originalDate || date;
1133
+ var timezoneOffset = originalDate.getTimezoneOffset();
1134
+ switch (token) {
1135
+ // Short
1136
+ case 'O':
1137
+ case 'OO':
1138
+ case 'OOO':
1139
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1140
+ // Long
1141
+ case 'OOOO':
1142
+ default:
1143
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1144
+ }
1145
+ },
1146
+ // Timezone (specific non-location)
1147
+ z: function z(date, token, _localize, options) {
1148
+ var originalDate = options._originalDate || date;
1149
+ var timezoneOffset = originalDate.getTimezoneOffset();
1150
+ switch (token) {
1151
+ // Short
1152
+ case 'z':
1153
+ case 'zz':
1154
+ case 'zzz':
1155
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1156
+ // Long
1157
+ case 'zzzz':
1158
+ default:
1159
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1160
+ }
1161
+ },
1162
+ // Seconds timestamp
1163
+ t: function t(date, token, _localize, options) {
1164
+ var originalDate = options._originalDate || date;
1165
+ var timestamp = Math.floor(originalDate.getTime() / 1000);
1166
+ return addLeadingZeros(timestamp, token.length);
1167
+ },
1168
+ // Milliseconds timestamp
1169
+ T: function T(date, token, _localize, options) {
1170
+ var originalDate = options._originalDate || date;
1171
+ var timestamp = originalDate.getTime();
1172
+ return addLeadingZeros(timestamp, token.length);
1173
+ }
1174
+ };
1175
+ function formatTimezoneShort(offset, dirtyDelimiter) {
1176
+ var sign = offset > 0 ? '-' : '+';
1177
+ var absOffset = Math.abs(offset);
1178
+ var hours = Math.floor(absOffset / 60);
1179
+ var minutes = absOffset % 60;
1180
+ if (minutes === 0) {
1181
+ return sign + String(hours);
1182
+ }
1183
+ var delimiter = dirtyDelimiter || '';
1184
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
1185
+ }
1186
+ function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
1187
+ if (offset % 60 === 0) {
1188
+ var sign = offset > 0 ? '-' : '+';
1189
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
1190
+ }
1191
+ return formatTimezone(offset, dirtyDelimiter);
1192
+ }
1193
+ function formatTimezone(offset, dirtyDelimiter) {
1194
+ var delimiter = dirtyDelimiter || '';
1195
+ var sign = offset > 0 ? '-' : '+';
1196
+ var absOffset = Math.abs(offset);
1197
+ var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
1198
+ var minutes = addLeadingZeros(absOffset % 60, 2);
1199
+ return sign + hours + delimiter + minutes;
1200
+ }
1201
+ var formatters$1 = formatters;
1202
+
1203
+ var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
1204
+ switch (pattern) {
1205
+ case 'P':
1206
+ return formatLong.date({
1207
+ width: 'short'
1208
+ });
1209
+ case 'PP':
1210
+ return formatLong.date({
1211
+ width: 'medium'
1212
+ });
1213
+ case 'PPP':
1214
+ return formatLong.date({
1215
+ width: 'long'
1216
+ });
1217
+ case 'PPPP':
1218
+ default:
1219
+ return formatLong.date({
1220
+ width: 'full'
1221
+ });
1222
+ }
1223
+ };
1224
+ var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
1225
+ switch (pattern) {
1226
+ case 'p':
1227
+ return formatLong.time({
1228
+ width: 'short'
1229
+ });
1230
+ case 'pp':
1231
+ return formatLong.time({
1232
+ width: 'medium'
1233
+ });
1234
+ case 'ppp':
1235
+ return formatLong.time({
1236
+ width: 'long'
1237
+ });
1238
+ case 'pppp':
1239
+ default:
1240
+ return formatLong.time({
1241
+ width: 'full'
1242
+ });
1243
+ }
1244
+ };
1245
+ var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
1246
+ var matchResult = pattern.match(/(P+)(p+)?/) || [];
1247
+ var datePattern = matchResult[1];
1248
+ var timePattern = matchResult[2];
1249
+ if (!timePattern) {
1250
+ return dateLongFormatter(pattern, formatLong);
1251
+ }
1252
+ var dateTimeFormat;
1253
+ switch (datePattern) {
1254
+ case 'P':
1255
+ dateTimeFormat = formatLong.dateTime({
1256
+ width: 'short'
1257
+ });
1258
+ break;
1259
+ case 'PP':
1260
+ dateTimeFormat = formatLong.dateTime({
1261
+ width: 'medium'
1262
+ });
1263
+ break;
1264
+ case 'PPP':
1265
+ dateTimeFormat = formatLong.dateTime({
1266
+ width: 'long'
1267
+ });
1268
+ break;
1269
+ case 'PPPP':
1270
+ default:
1271
+ dateTimeFormat = formatLong.dateTime({
1272
+ width: 'full'
1273
+ });
1274
+ break;
1275
+ }
1276
+ return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
1277
+ };
1278
+ var longFormatters = {
1279
+ p: timeLongFormatter,
1280
+ P: dateTimeLongFormatter
1281
+ };
1282
+ var longFormatters$1 = longFormatters;
1283
+
1284
+ /**
1285
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
1286
+ * They usually appear for dates that denote time before the timezones were introduced
1287
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
1288
+ * and GMT+01:00:00 after that date)
1289
+ *
1290
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
1291
+ * which would lead to incorrect calculations.
1292
+ *
1293
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
1294
+ */
1295
+ function getTimezoneOffsetInMilliseconds(date) {
1296
+ var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
1297
+ utcDate.setUTCFullYear(date.getFullYear());
1298
+ return date.getTime() - utcDate.getTime();
1299
+ }
1300
+
1301
+ var protectedDayOfYearTokens = ['D', 'DD'];
1302
+ var protectedWeekYearTokens = ['YY', 'YYYY'];
1303
+ function isProtectedDayOfYearToken(token) {
1304
+ return protectedDayOfYearTokens.indexOf(token) !== -1;
1305
+ }
1306
+ function isProtectedWeekYearToken(token) {
1307
+ return protectedWeekYearTokens.indexOf(token) !== -1;
1308
+ }
1309
+ function throwProtectedError(token, format, input) {
1310
+ if (token === 'YYYY') {
1311
+ throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1312
+ } else if (token === 'YY') {
1313
+ throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1314
+ } else if (token === 'D') {
1315
+ throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1316
+ } else if (token === 'DD') {
1317
+ throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1318
+ }
1319
+ }
1320
+
1321
+ var formatDistanceLocale = {
1322
+ lessThanXSeconds: {
1323
+ one: 'less than a second',
1324
+ other: 'less than {{count}} seconds'
1325
+ },
1326
+ xSeconds: {
1327
+ one: '1 second',
1328
+ other: '{{count}} seconds'
1329
+ },
1330
+ halfAMinute: 'half a minute',
1331
+ lessThanXMinutes: {
1332
+ one: 'less than a minute',
1333
+ other: 'less than {{count}} minutes'
1334
+ },
1335
+ xMinutes: {
1336
+ one: '1 minute',
1337
+ other: '{{count}} minutes'
1338
+ },
1339
+ aboutXHours: {
1340
+ one: 'about 1 hour',
1341
+ other: 'about {{count}} hours'
1342
+ },
1343
+ xHours: {
1344
+ one: '1 hour',
1345
+ other: '{{count}} hours'
1346
+ },
1347
+ xDays: {
1348
+ one: '1 day',
1349
+ other: '{{count}} days'
1350
+ },
1351
+ aboutXWeeks: {
1352
+ one: 'about 1 week',
1353
+ other: 'about {{count}} weeks'
1354
+ },
1355
+ xWeeks: {
1356
+ one: '1 week',
1357
+ other: '{{count}} weeks'
1358
+ },
1359
+ aboutXMonths: {
1360
+ one: 'about 1 month',
1361
+ other: 'about {{count}} months'
1362
+ },
1363
+ xMonths: {
1364
+ one: '1 month',
1365
+ other: '{{count}} months'
1366
+ },
1367
+ aboutXYears: {
1368
+ one: 'about 1 year',
1369
+ other: 'about {{count}} years'
1370
+ },
1371
+ xYears: {
1372
+ one: '1 year',
1373
+ other: '{{count}} years'
1374
+ },
1375
+ overXYears: {
1376
+ one: 'over 1 year',
1377
+ other: 'over {{count}} years'
1378
+ },
1379
+ almostXYears: {
1380
+ one: 'almost 1 year',
1381
+ other: 'almost {{count}} years'
1382
+ }
1383
+ };
1384
+ var formatDistance = function formatDistance(token, count, options) {
1385
+ var result;
1386
+ var tokenValue = formatDistanceLocale[token];
1387
+ if (typeof tokenValue === 'string') {
1388
+ result = tokenValue;
1389
+ } else if (count === 1) {
1390
+ result = tokenValue.one;
1391
+ } else {
1392
+ result = tokenValue.other.replace('{{count}}', count.toString());
1393
+ }
1394
+ if (options !== null && options !== void 0 && options.addSuffix) {
1395
+ if (options.comparison && options.comparison > 0) {
1396
+ return 'in ' + result;
1397
+ } else {
1398
+ return result + ' ago';
1399
+ }
1400
+ }
1401
+ return result;
1402
+ };
1403
+ var formatDistance$1 = formatDistance;
1404
+
1405
+ function buildFormatLongFn(args) {
1406
+ return function () {
1407
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1408
+ // TODO: Remove String()
1409
+ var width = options.width ? String(options.width) : args.defaultWidth;
1410
+ var format = args.formats[width] || args.formats[args.defaultWidth];
1411
+ return format;
1412
+ };
1413
+ }
1414
+
1415
+ var dateFormats = {
1416
+ full: 'EEEE, MMMM do, y',
1417
+ long: 'MMMM do, y',
1418
+ medium: 'MMM d, y',
1419
+ short: 'MM/dd/yyyy'
1420
+ };
1421
+ var timeFormats = {
1422
+ full: 'h:mm:ss a zzzz',
1423
+ long: 'h:mm:ss a z',
1424
+ medium: 'h:mm:ss a',
1425
+ short: 'h:mm a'
1426
+ };
1427
+ var dateTimeFormats = {
1428
+ full: "{{date}} 'at' {{time}}",
1429
+ long: "{{date}} 'at' {{time}}",
1430
+ medium: '{{date}}, {{time}}',
1431
+ short: '{{date}}, {{time}}'
1432
+ };
1433
+ var formatLong = {
1434
+ date: buildFormatLongFn({
1435
+ formats: dateFormats,
1436
+ defaultWidth: 'full'
1437
+ }),
1438
+ time: buildFormatLongFn({
1439
+ formats: timeFormats,
1440
+ defaultWidth: 'full'
1441
+ }),
1442
+ dateTime: buildFormatLongFn({
1443
+ formats: dateTimeFormats,
1444
+ defaultWidth: 'full'
1445
+ })
1446
+ };
1447
+ var formatLong$1 = formatLong;
1448
+
1449
+ var formatRelativeLocale = {
1450
+ lastWeek: "'last' eeee 'at' p",
1451
+ yesterday: "'yesterday at' p",
1452
+ today: "'today at' p",
1453
+ tomorrow: "'tomorrow at' p",
1454
+ nextWeek: "eeee 'at' p",
1455
+ other: 'P'
1456
+ };
1457
+ var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
1458
+ return formatRelativeLocale[token];
1459
+ };
1460
+ var formatRelative$1 = formatRelative;
1461
+
1462
+ function buildLocalizeFn(args) {
1463
+ return function (dirtyIndex, options) {
1464
+ var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
1465
+ var valuesArray;
1466
+ if (context === 'formatting' && args.formattingValues) {
1467
+ var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1468
+ var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
1469
+ valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
1470
+ } else {
1471
+ var _defaultWidth = args.defaultWidth;
1472
+ var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
1473
+ valuesArray = args.values[_width] || args.values[_defaultWidth];
1474
+ }
1475
+ var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
1476
+ // @ts-ignore: 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!
1477
+ return valuesArray[index];
1478
+ };
1479
+ }
1480
+
1481
+ var eraValues = {
1482
+ narrow: ['B', 'A'],
1483
+ abbreviated: ['BC', 'AD'],
1484
+ wide: ['Before Christ', 'Anno Domini']
1485
+ };
1486
+ var quarterValues = {
1487
+ narrow: ['1', '2', '3', '4'],
1488
+ abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
1489
+ wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
1490
+ };
1491
+
1492
+ // Note: in English, the names of days of the week and months are capitalized.
1493
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1494
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1495
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1496
+ var monthValues = {
1497
+ narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
1498
+ abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
1499
+ wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
1500
+ };
1501
+ var dayValues = {
1502
+ narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
1503
+ short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
1504
+ abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
1505
+ wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
1506
+ };
1507
+ var dayPeriodValues = {
1508
+ narrow: {
1509
+ am: 'a',
1510
+ pm: 'p',
1511
+ midnight: 'mi',
1512
+ noon: 'n',
1513
+ morning: 'morning',
1514
+ afternoon: 'afternoon',
1515
+ evening: 'evening',
1516
+ night: 'night'
1517
+ },
1518
+ abbreviated: {
1519
+ am: 'AM',
1520
+ pm: 'PM',
1521
+ midnight: 'midnight',
1522
+ noon: 'noon',
1523
+ morning: 'morning',
1524
+ afternoon: 'afternoon',
1525
+ evening: 'evening',
1526
+ night: 'night'
1527
+ },
1528
+ wide: {
1529
+ am: 'a.m.',
1530
+ pm: 'p.m.',
1531
+ midnight: 'midnight',
1532
+ noon: 'noon',
1533
+ morning: 'morning',
1534
+ afternoon: 'afternoon',
1535
+ evening: 'evening',
1536
+ night: 'night'
1537
+ }
1538
+ };
1539
+ var formattingDayPeriodValues = {
1540
+ narrow: {
1541
+ am: 'a',
1542
+ pm: 'p',
1543
+ midnight: 'mi',
1544
+ noon: 'n',
1545
+ morning: 'in the morning',
1546
+ afternoon: 'in the afternoon',
1547
+ evening: 'in the evening',
1548
+ night: 'at night'
1549
+ },
1550
+ abbreviated: {
1551
+ am: 'AM',
1552
+ pm: 'PM',
1553
+ midnight: 'midnight',
1554
+ noon: 'noon',
1555
+ morning: 'in the morning',
1556
+ afternoon: 'in the afternoon',
1557
+ evening: 'in the evening',
1558
+ night: 'at night'
1559
+ },
1560
+ wide: {
1561
+ am: 'a.m.',
1562
+ pm: 'p.m.',
1563
+ midnight: 'midnight',
1564
+ noon: 'noon',
1565
+ morning: 'in the morning',
1566
+ afternoon: 'in the afternoon',
1567
+ evening: 'in the evening',
1568
+ night: 'at night'
1569
+ }
1570
+ };
1571
+ var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
1572
+ var number = Number(dirtyNumber);
1573
+
1574
+ // If ordinal numbers depend on context, for example,
1575
+ // if they are different for different grammatical genders,
1576
+ // use `options.unit`.
1577
+ //
1578
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
1579
+ // 'day', 'hour', 'minute', 'second'.
1580
+
1581
+ var rem100 = number % 100;
1582
+ if (rem100 > 20 || rem100 < 10) {
1583
+ switch (rem100 % 10) {
1584
+ case 1:
1585
+ return number + 'st';
1586
+ case 2:
1587
+ return number + 'nd';
1588
+ case 3:
1589
+ return number + 'rd';
1590
+ }
1591
+ }
1592
+ return number + 'th';
1593
+ };
1594
+ var localize = {
1595
+ ordinalNumber: ordinalNumber,
1596
+ era: buildLocalizeFn({
1597
+ values: eraValues,
1598
+ defaultWidth: 'wide'
1599
+ }),
1600
+ quarter: buildLocalizeFn({
1601
+ values: quarterValues,
1602
+ defaultWidth: 'wide',
1603
+ argumentCallback: function argumentCallback(quarter) {
1604
+ return quarter - 1;
1605
+ }
1606
+ }),
1607
+ month: buildLocalizeFn({
1608
+ values: monthValues,
1609
+ defaultWidth: 'wide'
1610
+ }),
1611
+ day: buildLocalizeFn({
1612
+ values: dayValues,
1613
+ defaultWidth: 'wide'
1614
+ }),
1615
+ dayPeriod: buildLocalizeFn({
1616
+ values: dayPeriodValues,
1617
+ defaultWidth: 'wide',
1618
+ formattingValues: formattingDayPeriodValues,
1619
+ defaultFormattingWidth: 'wide'
1620
+ })
1621
+ };
1622
+ var localize$1 = localize;
1623
+
1624
+ function buildMatchFn(args) {
1625
+ return function (string) {
1626
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1627
+ var width = options.width;
1628
+ var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
1629
+ var matchResult = string.match(matchPattern);
1630
+ if (!matchResult) {
1631
+ return null;
1632
+ }
1633
+ var matchedString = matchResult[0];
1634
+ var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
1635
+ var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
1636
+ return pattern.test(matchedString);
1637
+ }) : findKey(parsePatterns, function (pattern) {
1638
+ return pattern.test(matchedString);
1639
+ });
1640
+ var value;
1641
+ value = args.valueCallback ? args.valueCallback(key) : key;
1642
+ value = options.valueCallback ? options.valueCallback(value) : value;
1643
+ var rest = string.slice(matchedString.length);
1644
+ return {
1645
+ value: value,
1646
+ rest: rest
1647
+ };
1648
+ };
1649
+ }
1650
+ function findKey(object, predicate) {
1651
+ for (var key in object) {
1652
+ if (object.hasOwnProperty(key) && predicate(object[key])) {
1653
+ return key;
1654
+ }
1655
+ }
1656
+ return undefined;
1657
+ }
1658
+ function findIndex(array, predicate) {
1659
+ for (var key = 0; key < array.length; key++) {
1660
+ if (predicate(array[key])) {
1661
+ return key;
1662
+ }
1663
+ }
1664
+ return undefined;
1665
+ }
1666
+
1667
+ function buildMatchPatternFn(args) {
1668
+ return function (string) {
1669
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1670
+ var matchResult = string.match(args.matchPattern);
1671
+ if (!matchResult) return null;
1672
+ var matchedString = matchResult[0];
1673
+ var parseResult = string.match(args.parsePattern);
1674
+ if (!parseResult) return null;
1675
+ var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
1676
+ value = options.valueCallback ? options.valueCallback(value) : value;
1677
+ var rest = string.slice(matchedString.length);
1678
+ return {
1679
+ value: value,
1680
+ rest: rest
1681
+ };
1682
+ };
1683
+ }
1684
+
1685
+ var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
1686
+ var parseOrdinalNumberPattern = /\d+/i;
1687
+ var matchEraPatterns = {
1688
+ narrow: /^(b|a)/i,
1689
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
1690
+ wide: /^(before christ|before common era|anno domini|common era)/i
1691
+ };
1692
+ var parseEraPatterns = {
1693
+ any: [/^b/i, /^(a|c)/i]
1694
+ };
1695
+ var matchQuarterPatterns = {
1696
+ narrow: /^[1234]/i,
1697
+ abbreviated: /^q[1234]/i,
1698
+ wide: /^[1234](th|st|nd|rd)? quarter/i
1699
+ };
1700
+ var parseQuarterPatterns = {
1701
+ any: [/1/i, /2/i, /3/i, /4/i]
1702
+ };
1703
+ var matchMonthPatterns = {
1704
+ narrow: /^[jfmasond]/i,
1705
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
1706
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
1707
+ };
1708
+ var parseMonthPatterns = {
1709
+ narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
1710
+ any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
1711
+ };
1712
+ var matchDayPatterns = {
1713
+ narrow: /^[smtwf]/i,
1714
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
1715
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
1716
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
1717
+ };
1718
+ var parseDayPatterns = {
1719
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
1720
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
1721
+ };
1722
+ var matchDayPeriodPatterns = {
1723
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
1724
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
1725
+ };
1726
+ var parseDayPeriodPatterns = {
1727
+ any: {
1728
+ am: /^a/i,
1729
+ pm: /^p/i,
1730
+ midnight: /^mi/i,
1731
+ noon: /^no/i,
1732
+ morning: /morning/i,
1733
+ afternoon: /afternoon/i,
1734
+ evening: /evening/i,
1735
+ night: /night/i
1736
+ }
1737
+ };
1738
+ var match = {
1739
+ ordinalNumber: buildMatchPatternFn({
1740
+ matchPattern: matchOrdinalNumberPattern,
1741
+ parsePattern: parseOrdinalNumberPattern,
1742
+ valueCallback: function valueCallback(value) {
1743
+ return parseInt(value, 10);
1744
+ }
1745
+ }),
1746
+ era: buildMatchFn({
1747
+ matchPatterns: matchEraPatterns,
1748
+ defaultMatchWidth: 'wide',
1749
+ parsePatterns: parseEraPatterns,
1750
+ defaultParseWidth: 'any'
1751
+ }),
1752
+ quarter: buildMatchFn({
1753
+ matchPatterns: matchQuarterPatterns,
1754
+ defaultMatchWidth: 'wide',
1755
+ parsePatterns: parseQuarterPatterns,
1756
+ defaultParseWidth: 'any',
1757
+ valueCallback: function valueCallback(index) {
1758
+ return index + 1;
1759
+ }
1760
+ }),
1761
+ month: buildMatchFn({
1762
+ matchPatterns: matchMonthPatterns,
1763
+ defaultMatchWidth: 'wide',
1764
+ parsePatterns: parseMonthPatterns,
1765
+ defaultParseWidth: 'any'
1766
+ }),
1767
+ day: buildMatchFn({
1768
+ matchPatterns: matchDayPatterns,
1769
+ defaultMatchWidth: 'wide',
1770
+ parsePatterns: parseDayPatterns,
1771
+ defaultParseWidth: 'any'
1772
+ }),
1773
+ dayPeriod: buildMatchFn({
1774
+ matchPatterns: matchDayPeriodPatterns,
1775
+ defaultMatchWidth: 'any',
1776
+ parsePatterns: parseDayPeriodPatterns,
1777
+ defaultParseWidth: 'any'
1778
+ })
1779
+ };
1780
+ var match$1 = match;
1781
+
1782
+ /**
1783
+ * @type {Locale}
1784
+ * @category Locales
1785
+ * @summary English locale (United States).
1786
+ * @language English
1787
+ * @iso-639-2 eng
1788
+ * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
1789
+ * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
1790
+ */
1791
+ var locale = {
1792
+ code: 'en-US',
1793
+ formatDistance: formatDistance$1,
1794
+ formatLong: formatLong$1,
1795
+ formatRelative: formatRelative$1,
1796
+ localize: localize$1,
1797
+ match: match$1,
1798
+ options: {
1799
+ weekStartsOn: 0 /* Sunday */,
1800
+ firstWeekContainsDate: 1
1801
+ }
1802
+ };
1803
+ var defaultLocale = locale;
1804
+
1805
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
1806
+ // (one of the certain letters followed by `o`)
1807
+ // - (\w)\1* matches any sequences of the same letter
1808
+ // - '' matches two quote characters in a row
1809
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
1810
+ // except a single quote symbol, which ends the sequence.
1811
+ // Two quote characters do not end the sequence.
1812
+ // If there is no matching single quote
1813
+ // then the sequence will continue until the end of the string.
1814
+ // - . matches any single character unmatched by previous parts of the RegExps
1815
+ var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
1816
+
1817
+ // This RegExp catches symbols escaped by quotes, and also
1818
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
1819
+ var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
1820
+ var escapedStringRegExp = /^'([^]*?)'?$/;
1821
+ var doubleQuoteRegExp = /''/g;
1822
+ var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
1823
+
1824
+ /**
1825
+ * @name format
1826
+ * @category Common Helpers
1827
+ * @summary Format the date.
1828
+ *
1829
+ * @description
1830
+ * Return the formatted date string in the given format. The result may vary by locale.
1831
+ *
1832
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
1833
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
1834
+ *
1835
+ * The characters wrapped between two single quotes characters (') are escaped.
1836
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
1837
+ * (see the last example)
1838
+ *
1839
+ * Format of the string is based on Unicode Technical Standard #35:
1840
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
1841
+ * with a few additions (see note 7 below the table).
1842
+ *
1843
+ * Accepted patterns:
1844
+ * | Unit | Pattern | Result examples | Notes |
1845
+ * |---------------------------------|---------|-----------------------------------|-------|
1846
+ * | Era | G..GGG | AD, BC | |
1847
+ * | | GGGG | Anno Domini, Before Christ | 2 |
1848
+ * | | GGGGG | A, B | |
1849
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
1850
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
1851
+ * | | yy | 44, 01, 00, 17 | 5 |
1852
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
1853
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
1854
+ * | | yyyyy | ... | 3,5 |
1855
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
1856
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
1857
+ * | | YY | 44, 01, 00, 17 | 5,8 |
1858
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
1859
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
1860
+ * | | YYYYY | ... | 3,5 |
1861
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
1862
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
1863
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
1864
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
1865
+ * | | RRRRR | ... | 3,5,7 |
1866
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
1867
+ * | | uu | -43, 01, 1900, 2017 | 5 |
1868
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
1869
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
1870
+ * | | uuuuu | ... | 3,5 |
1871
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
1872
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
1873
+ * | | QQ | 01, 02, 03, 04 | |
1874
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
1875
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
1876
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
1877
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
1878
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
1879
+ * | | qq | 01, 02, 03, 04 | |
1880
+ * | | qqq | Q1, Q2, Q3, Q4 | |
1881
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
1882
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
1883
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
1884
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
1885
+ * | | MM | 01, 02, ..., 12 | |
1886
+ * | | MMM | Jan, Feb, ..., Dec | |
1887
+ * | | MMMM | January, February, ..., December | 2 |
1888
+ * | | MMMMM | J, F, ..., D | |
1889
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
1890
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
1891
+ * | | LL | 01, 02, ..., 12 | |
1892
+ * | | LLL | Jan, Feb, ..., Dec | |
1893
+ * | | LLLL | January, February, ..., December | 2 |
1894
+ * | | LLLLL | J, F, ..., D | |
1895
+ * | Local week of year | w | 1, 2, ..., 53 | |
1896
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
1897
+ * | | ww | 01, 02, ..., 53 | |
1898
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
1899
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
1900
+ * | | II | 01, 02, ..., 53 | 7 |
1901
+ * | Day of month | d | 1, 2, ..., 31 | |
1902
+ * | | do | 1st, 2nd, ..., 31st | 7 |
1903
+ * | | dd | 01, 02, ..., 31 | |
1904
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
1905
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
1906
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
1907
+ * | | DDD | 001, 002, ..., 365, 366 | |
1908
+ * | | DDDD | ... | 3 |
1909
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
1910
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
1911
+ * | | EEEEE | M, T, W, T, F, S, S | |
1912
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
1913
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
1914
+ * | | io | 1st, 2nd, ..., 7th | 7 |
1915
+ * | | ii | 01, 02, ..., 07 | 7 |
1916
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
1917
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
1918
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
1919
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
1920
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
1921
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
1922
+ * | | ee | 02, 03, ..., 01 | |
1923
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
1924
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
1925
+ * | | eeeee | M, T, W, T, F, S, S | |
1926
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
1927
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
1928
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
1929
+ * | | cc | 02, 03, ..., 01 | |
1930
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
1931
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
1932
+ * | | ccccc | M, T, W, T, F, S, S | |
1933
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
1934
+ * | AM, PM | a..aa | AM, PM | |
1935
+ * | | aaa | am, pm | |
1936
+ * | | aaaa | a.m., p.m. | 2 |
1937
+ * | | aaaaa | a, p | |
1938
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
1939
+ * | | bbb | am, pm, noon, midnight | |
1940
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
1941
+ * | | bbbbb | a, p, n, mi | |
1942
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
1943
+ * | | BBBB | at night, in the morning, ... | 2 |
1944
+ * | | BBBBB | at night, in the morning, ... | |
1945
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
1946
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
1947
+ * | | hh | 01, 02, ..., 11, 12 | |
1948
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
1949
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
1950
+ * | | HH | 00, 01, 02, ..., 23 | |
1951
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
1952
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
1953
+ * | | KK | 01, 02, ..., 11, 00 | |
1954
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
1955
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
1956
+ * | | kk | 24, 01, 02, ..., 23 | |
1957
+ * | Minute | m | 0, 1, ..., 59 | |
1958
+ * | | mo | 0th, 1st, ..., 59th | 7 |
1959
+ * | | mm | 00, 01, ..., 59 | |
1960
+ * | Second | s | 0, 1, ..., 59 | |
1961
+ * | | so | 0th, 1st, ..., 59th | 7 |
1962
+ * | | ss | 00, 01, ..., 59 | |
1963
+ * | Fraction of second | S | 0, 1, ..., 9 | |
1964
+ * | | SS | 00, 01, ..., 99 | |
1965
+ * | | SSS | 000, 001, ..., 999 | |
1966
+ * | | SSSS | ... | 3 |
1967
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
1968
+ * | | XX | -0800, +0530, Z | |
1969
+ * | | XXX | -08:00, +05:30, Z | |
1970
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
1971
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
1972
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
1973
+ * | | xx | -0800, +0530, +0000 | |
1974
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
1975
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
1976
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
1977
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
1978
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
1979
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
1980
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
1981
+ * | Seconds timestamp | t | 512969520 | 7 |
1982
+ * | | tt | ... | 3,7 |
1983
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
1984
+ * | | TT | ... | 3,7 |
1985
+ * | Long localized date | P | 04/29/1453 | 7 |
1986
+ * | | PP | Apr 29, 1453 | 7 |
1987
+ * | | PPP | April 29th, 1453 | 7 |
1988
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
1989
+ * | Long localized time | p | 12:00 AM | 7 |
1990
+ * | | pp | 12:00:00 AM | 7 |
1991
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
1992
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
1993
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
1994
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
1995
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
1996
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
1997
+ * Notes:
1998
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
1999
+ * are the same as "stand-alone" units, but are different in some languages.
2000
+ * "Formatting" units are declined according to the rules of the language
2001
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2002
+ *
2003
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2004
+ *
2005
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2006
+ *
2007
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2008
+ * the single quote characters (see below).
2009
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2010
+ * the output will be the same as default pattern for this unit, usually
2011
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2012
+ * are marked with "2" in the last column of the table.
2013
+ *
2014
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2015
+ *
2016
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2017
+ *
2018
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2019
+ *
2020
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2021
+ *
2022
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2023
+ *
2024
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2025
+ * The output will be padded with zeros to match the length of the pattern.
2026
+ *
2027
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2028
+ *
2029
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2030
+ * These tokens represent the shortest form of the quarter.
2031
+ *
2032
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2033
+ *
2034
+ * | Year | `y` | `u` |
2035
+ * |------|-----|-----|
2036
+ * | AC 1 | 1 | 1 |
2037
+ * | BC 1 | 1 | 0 |
2038
+ * | BC 2 | 2 | -1 |
2039
+ *
2040
+ * Also `yy` always returns the last two digits of a year,
2041
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2042
+ *
2043
+ * | Year | `yy` | `uu` |
2044
+ * |------|------|------|
2045
+ * | 1 | 01 | 01 |
2046
+ * | 14 | 14 | 14 |
2047
+ * | 376 | 76 | 376 |
2048
+ * | 1453 | 53 | 1453 |
2049
+ *
2050
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2051
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2052
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
2053
+ * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
2054
+ *
2055
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2056
+ * so right now these tokens fall back to GMT timezones.
2057
+ *
2058
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2059
+ * - `i`: ISO day of week
2060
+ * - `I`: ISO week of year
2061
+ * - `R`: ISO week-numbering year
2062
+ * - `t`: seconds timestamp
2063
+ * - `T`: milliseconds timestamp
2064
+ * - `o`: ordinal number modifier
2065
+ * - `P`: long localized date
2066
+ * - `p`: long localized time
2067
+ *
2068
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2069
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2070
+ *
2071
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2072
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2073
+ *
2074
+ * @param {Date|Number} date - the original date
2075
+ * @param {String} format - the string of tokens
2076
+ * @param {Object} [options] - an object with options.
2077
+ * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
2078
+ * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
2079
+ * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
2080
+ * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
2081
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2082
+ * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
2083
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2084
+ * @returns {String} the formatted date string
2085
+ * @throws {TypeError} 2 arguments required
2086
+ * @throws {RangeError} `date` must not be Invalid Date
2087
+ * @throws {RangeError} `options.locale` must contain `localize` property
2088
+ * @throws {RangeError} `options.locale` must contain `formatLong` property
2089
+ * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
2090
+ * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
2091
+ * @throws {RangeError} 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
2092
+ * @throws {RangeError} 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
2093
+ * @throws {RangeError} 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
2094
+ * @throws {RangeError} 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
2095
+ * @throws {RangeError} format string contains an unescaped latin alphabet character
2096
+ *
2097
+ * @example
2098
+ * // Represent 11 February 2014 in middle-endian format:
2099
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2100
+ * //=> '02/11/2014'
2101
+ *
2102
+ * @example
2103
+ * // Represent 2 July 2014 in Esperanto:
2104
+ * import { eoLocale } from 'date-fns/locale/eo'
2105
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2106
+ * locale: eoLocale
2107
+ * })
2108
+ * //=> '2-a de julio 2014'
2109
+ *
2110
+ * @example
2111
+ * // Escape string by single quote characters:
2112
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2113
+ * //=> "3 o'clock"
2114
+ */
2115
+
2116
+ function format(dirtyDate, dirtyFormatStr, options) {
2117
+ var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
2118
+ requiredArgs(2, arguments);
2119
+ var formatStr = String(dirtyFormatStr);
2120
+ var defaultOptions = getDefaultOptions();
2121
+ var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale;
2122
+ var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
2123
+
2124
+ // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
2125
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
2126
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
2127
+ }
2128
+ var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
2129
+
2130
+ // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
2131
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
2132
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
2133
+ }
2134
+ if (!locale.localize) {
2135
+ throw new RangeError('locale must contain localize property');
2136
+ }
2137
+ if (!locale.formatLong) {
2138
+ throw new RangeError('locale must contain formatLong property');
2139
+ }
2140
+ var originalDate = toDate(dirtyDate);
2141
+ if (!isValid(originalDate)) {
2142
+ throw new RangeError('Invalid time value');
2143
+ }
2144
+
2145
+ // Convert the date in system timezone to the same date in UTC+00:00 timezone.
2146
+ // This ensures that when UTC functions will be implemented, locales will be compatible with them.
2147
+ // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
2148
+ var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
2149
+ var utcDate = subMilliseconds(originalDate, timezoneOffset);
2150
+ var formatterOptions = {
2151
+ firstWeekContainsDate: firstWeekContainsDate,
2152
+ weekStartsOn: weekStartsOn,
2153
+ locale: locale,
2154
+ _originalDate: originalDate
2155
+ };
2156
+ var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
2157
+ var firstCharacter = substring[0];
2158
+ if (firstCharacter === 'p' || firstCharacter === 'P') {
2159
+ var longFormatter = longFormatters$1[firstCharacter];
2160
+ return longFormatter(substring, locale.formatLong);
2161
+ }
2162
+ return substring;
2163
+ }).join('').match(formattingTokensRegExp).map(function (substring) {
2164
+ // Replace two single quote characters with one single quote character
2165
+ if (substring === "''") {
2166
+ return "'";
2167
+ }
2168
+ var firstCharacter = substring[0];
2169
+ if (firstCharacter === "'") {
2170
+ return cleanEscapedString(substring);
2171
+ }
2172
+ var formatter = formatters$1[firstCharacter];
2173
+ if (formatter) {
2174
+ if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
2175
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2176
+ }
2177
+ if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
2178
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2179
+ }
2180
+ return formatter(utcDate, substring, locale.localize, formatterOptions);
2181
+ }
2182
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2183
+ throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
2184
+ }
2185
+ return substring;
2186
+ }).join('');
2187
+ return result;
2188
+ }
2189
+ function cleanEscapedString(input) {
2190
+ var matched = input.match(escapedStringRegExp);
2191
+ if (!matched) {
2192
+ return input;
2193
+ }
2194
+ return matched[1].replace(doubleQuoteRegExp, "'");
2195
+ }
2196
+
2197
+ // 数据格式化
2198
+
2199
+ // 完整时间:yyyy-MM-dd HH:mm:ss
2200
+ function format_date(timestamp, str = "yyyy-MM-dd") {
2201
+ if (!timestamp) return ''
2202
+ try {
2203
+ const num = +timestamp;
2204
+ if (num) {
2205
+ return format(num, str)
2206
+ }
2207
+ return format(new Date(timestamp), str)
2208
+ } catch (error) {
2209
+ return ''
2210
+ }
2211
+ }
2212
+
2213
+ function formatDateMinute(timestamp) {
2214
+ if (!timestamp) return ''
2215
+ try {
2216
+ return format(+timestamp, "yyyy-MM-dd HH:mm")
2217
+ } catch (error) {
2218
+ return ''
2219
+ }
2220
+ }
2221
+
2222
+ // 小数转百分比 数字(会删除小数点后面的0)
2223
+ function format_decimal(number = 0, num = 2, scale = 100) {
2224
+ return +(+number * scale).toFixed(num)
2225
+ }
2226
+
2227
+ // 小数转百分比 字符串(不会删除小数点后面的0)
2228
+ function format_decimal_string(number = 0, num = 2, scale = 100) {
2229
+ return (+number * scale).toFixed(num)
2230
+ }
2231
+
2232
+ // 处理金额
2233
+ function format_money(number = 0, num = 2, scale = 100) {
2234
+ return (+number / scale).toFixed(num)
2235
+ }
2236
+
2237
+ // 创建唯一id
2238
+ function create_guid() {
2239
+ return (
2240
+ (Math.random() * 10000000).toString(16).substring(0, 4) +
2241
+ "-" +
2242
+ new Date().getTime() +
2243
+ "-" +
2244
+ Math.random().toString().substring(2, 7)
2245
+ )
2246
+ }
2247
+
2248
+ // 数字格式
2249
+ function format_number(num) {
2250
+ if (!num) return 0
2251
+ let str = `${num}`;
2252
+ let len = str.length;
2253
+ if (len === 3) {
2254
+ return str
2255
+ }
2256
+ let str2 = "";
2257
+ let max = Math.floor(len / 3);
2258
+ if (len % 3 === 0) {
2259
+ max = max - 1;
2260
+ }
2261
+ for (let i = 0; i < max; i++) {
2262
+ let s = str.slice(len - 3, len);
2263
+ str = str.substring(0, len - 3);
2264
+ str2 = "," + s + str2;
2265
+ len = str.length;
2266
+ }
2267
+ str += str2;
2268
+ return str
2269
+ }
2270
+
2271
+ // 数组转标签
2272
+ function arr_label(arr, props) {
2273
+ props = {
2274
+ label: "label",
2275
+ value: "value",
2276
+ children: "children",
2277
+ re: true,
2278
+ ...props,
2279
+ };
2280
+ const obj = {};
2281
+ function re(arr) {
2282
+ if (arr && arr.length > 0) {
2283
+ for (let item of arr) {
2284
+ obj[item[props.value]] = item[props.label];
2285
+ if (props.re) re(item[props.children]);
2286
+ }
2287
+ }
2288
+ }
2289
+ re(arr);
2290
+ return obj
2291
+ }
2292
+
2293
+ // 数组转对象
2294
+ function arr_obj(arr, props) {
2295
+ props = {
2296
+ value: "value",
2297
+ children: "children",
2298
+ re: true,
2299
+ ...props,
2300
+ };
2301
+ const obj = {};
2302
+ function re(arr) {
2303
+ if (arr && arr.length > 0) {
2304
+ for (let item of arr) {
2305
+ obj[item[props.value]] = item;
2306
+ if (props.re) re(item[props.children]);
2307
+ }
2308
+ }
2309
+ }
2310
+ re(arr);
2311
+ return obj
2312
+ }
2313
+
2314
+ // 复制
2315
+ function copy_content(content) {
2316
+ if (typeof document === 'undefined') {
2317
+ console.warn('copy_content需要在浏览器环境使用');
2318
+ return false
2319
+ }
2320
+ const input = document.createElement("input");
2321
+ input.setAttribute("value", content);
2322
+ document.body.appendChild(input);
2323
+ input.select();
2324
+ const result = document.execCommand("copy");
2325
+ document.body.removeChild(input);
2326
+ return result
2327
+ }
2328
+
2329
+ //计算高度
2330
+ function calculate_height(item, container) {
2331
+ if (typeof document === 'undefined') {
2332
+ return false
2333
+ }
2334
+ const dom = document.getElementById(item);
2335
+ const containerDom = document.getElementById(container);
2336
+ if (dom && containerDom) {
2337
+ const height = dom.offsetHeight;
2338
+ const max_height = containerDom.offsetHeight;
2339
+ return height > max_height
2340
+ }
2341
+ return false
2342
+ }
2343
+
2344
+ // 文字超过8个...
2345
+ function formatTxt(text) {
2346
+ if (!text) return ""
2347
+
2348
+ let trimTetx = text.trim();
2349
+
2350
+ if (trimTetx.length <= 8) {
2351
+ return trimTetx
2352
+ }
2353
+
2354
+ return trimTetx.substring(0, 8) + "..."
2355
+ }
2356
+
2357
+ //设置光标
2358
+ function set_cursor(dom, start = 0, end = 0) {
2359
+ if (typeof window === 'undefined' || !dom) {
2360
+ console.warn('set_cursor需要在浏览器环境使用');
2361
+ return
2362
+ }
2363
+ const selection = window.getSelection();
2364
+ const range = document.createRange();
2365
+ range.setStart(dom, start);
2366
+ range.setEnd(dom, end);
2367
+ selection.removeAllRanges();
2368
+ selection.addRange(range);
2369
+ dom.focus();
2370
+ }
2371
+
2372
+ // 同步setTimeout
2373
+ function sleep(time) {
2374
+ return new Promise((resolve) => setTimeout(resolve, time))
2375
+ }
2376
+
2377
+ function detectZoom() {
2378
+ if (typeof window === 'undefined') {
2379
+ return 1
2380
+ }
2381
+ let ratio = 0;
2382
+ const screen = window.screen;
2383
+ const ua = navigator.userAgent.toLowerCase();
2384
+
2385
+ if (window.devicePixelRatio !== undefined) {
2386
+ ratio = window.devicePixelRatio;
2387
+ } else if (~ua.indexOf('msie')) {
2388
+ if (screen.deviceXDPI && screen.logicalXDPI) {
2389
+ ratio = screen.deviceXDPI / screen.logicalXDPI;
2390
+ }
2391
+ } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
2392
+ ratio = window.outerWidth / window.innerWidth;
2393
+ }
2394
+
2395
+ return +ratio
2396
+ }
2397
+
2398
+ /**
2399
+ * 递归查找树节点
2400
+ * @param {Array} tree 树数据
2401
+ * @param {String} id 节点id值
2402
+ * @param {Object} keyMap 节点字段映射
2403
+ * @returns {Object|Null} 节点对象
2404
+ */
2405
+ function findNodeOfTree(tree, id, keyMap = {}) {
2406
+ const _keyMap = {
2407
+ id: "id",
2408
+ children: "children",
2409
+ ...keyMap,
2410
+ };
2411
+
2412
+ function searchTree(nodes) {
2413
+ for (let node of nodes) {
2414
+ if (node[_keyMap.id] === id) {
2415
+ return node
2416
+ }
2417
+ if (node[_keyMap.children] && node[_keyMap.children].length > 0) {
2418
+ const foundNode = searchTree(node[_keyMap.children]);
2419
+ if (foundNode) {
2420
+ return foundNode
2421
+ }
2422
+ }
2423
+ }
2424
+ return null
2425
+ }
2426
+
2427
+ return searchTree(tree)
2428
+ }
2429
+
2430
+ function copyToClip(content, type = "input") {
2431
+ if (typeof document === 'undefined') {
2432
+ console.warn('copyToClip需要在浏览器环境使用');
2433
+ return false
2434
+ }
2435
+ var aux = document.createElement(type);
2436
+ document.body.appendChild(aux);
2437
+ if (type === "input") {
2438
+ aux.setAttribute("value", content);
2439
+ } else {
2440
+ aux.value = content;
2441
+ }
2442
+ aux.select();
2443
+ const result = document.execCommand("copy");
2444
+ document.body.removeChild(aux);
2445
+ return result
2446
+ }
2447
+
2448
+ function hidePhone(phone) {
2449
+ if (!phone) return ''
2450
+ phone = phone.toString();
2451
+ return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
2452
+ }
2453
+
2454
+ /**
2455
+ * 将字符串中的属于正则表达式的特殊字符,转换成正则表达式中的普通字符
2456
+ */
2457
+ function escapeRegExp(string) {
2458
+ if (!string) {
2459
+ return ''
2460
+ }
2461
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
2462
+ }
2463
+
2464
+ // 基于 Promise 的 validateField 方法,为了校验多个字段时避免回调地狱
2465
+ function validateFieldAsync(prop, form) {
2466
+ return new Promise((resolve, reject) => {
2467
+ form.validateField(prop, (valid) => {
2468
+ if (valid) {
2469
+ reject(new Error(valid));
2470
+ } else {
2471
+ resolve();
2472
+ }
2473
+ });
2474
+ })
2475
+ }
2476
+
2477
+ // 校验手机号
2478
+ function validatePhone(rule, value, callback) {
2479
+ const reg = /^1[3456789]\d{9}$/;
2480
+ if (!value) {
2481
+ return callback(new Error("请输入手机号"))
2482
+ } else if (!reg.test(value)) {
2483
+ return callback(new Error("请输入正确的手机号"))
2484
+ } else {
2485
+ callback();
2486
+ }
2487
+ }
2488
+
2489
+ // 对象是否为空
2490
+ function isEmptyObj(obj) {
2491
+ for (const name in obj) {
2492
+ return false
2493
+ }
2494
+ return true
2495
+ }
2496
+
2497
+ // 只判断两个值对应相等,不包含引用
2498
+ function isEqual(a, b) {
2499
+ const classNameA = Object.prototype.toString.call(a);
2500
+ const classNameB = Object.prototype.toString.call(b);
2501
+ // 如果数据类型不相等,则返回false
2502
+ if (classNameA !== classNameB) {
2503
+ return false
2504
+ } else {
2505
+ // 如果数据类型相等,再根据不同数据类型分别判断
2506
+ if (classNameA === "[object Object]") {
2507
+ for (let key in a) {
2508
+ if (!isEqual(a[key], b[key])) return false
2509
+ }
2510
+ for (let key in b) {
2511
+ if (!isEqual(a[key], b[key])) return false
2512
+ }
2513
+ return true
2514
+ } else if (classNameA === "[object Array]") {
2515
+ if (a.length !== b.length) {
2516
+ return false
2517
+ } else {
2518
+ for (let i = 0, len = a.length; i < len; i++) {
2519
+ if (!isEqual(a[i], b[i])) return false
2520
+ }
2521
+ return true
2522
+ }
2523
+ } else if (classNameA === "[object Function]") {
2524
+ return a.toString() === b.toString()
2525
+ } else {
2526
+ return Object.is(a, b)
2527
+ }
2528
+ }
2529
+ }
2530
+
2531
+ // 是否为空
2532
+ function isEmpty(value) {
2533
+ if (value === undefined || value === null || value === "") {
2534
+ return true
2535
+ }
2536
+ return false
2537
+ }
2538
+
2539
+ function getBrowserInfo() {
2540
+ if (typeof navigator === 'undefined') {
2541
+ return {
2542
+ type: "Unknown",
2543
+ version: "Unknown",
2544
+ }
2545
+ }
2546
+ const userAgent = navigator.userAgent;
2547
+ let browserType = "Unknown";
2548
+ let browserVersion = "Unknown";
2549
+
2550
+ // Check for Firefox
2551
+ if (userAgent.indexOf("Firefox") > -1) {
2552
+ browserType = "Mozilla Firefox";
2553
+ const match = userAgent.match(/Firefox\/(\d+\.\d+)/);
2554
+ browserVersion = match ? match[1] : "Unknown";
2555
+ }
2556
+ // Check for Samsung Browser
2557
+ else if (userAgent.indexOf("SamsungBrowser") > -1) {
2558
+ browserType = "Samsung Internet";
2559
+ const match = userAgent.match(/SamsungBrowser\/(\d+\.\d+)/);
2560
+ browserVersion = match ? match[1] : "Unknown";
2561
+ }
2562
+ // Check for Opera or OPR (Opera based on Chromium)
2563
+ else if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) {
2564
+ browserType = "Opera";
2565
+ const match = userAgent.match(/(Opera|OPR)\/(\d+\.\d+)/);
2566
+ browserVersion = match ? match[2] : "Unknown";
2567
+ }
2568
+ // Check for Internet Explorer
2569
+ else if (userAgent.indexOf("Trident") > -1) {
2570
+ browserType = "Microsoft Internet Explorer";
2571
+ const versionMatch = userAgent.match(/rv:(\d+\.\d+)/);
2572
+ if (versionMatch) {
2573
+ browserVersion = versionMatch[1];
2574
+ }
2575
+ }
2576
+ // Check for Microsoft Edge
2577
+ else if (userAgent.indexOf("Edge") > -1) {
2578
+ browserType = "Microsoft Edge";
2579
+ const match = userAgent.match(/Edge\/(\d+\.\d+)/);
2580
+ browserVersion = match ? match[1] : "Unknown";
2581
+ }
2582
+ // Check for Google Chrome
2583
+ else if (userAgent.indexOf("Chrome") > -1) {
2584
+ browserType = "Google Chrome";
2585
+ const match = userAgent.match(/Chrome\/(\d+\.\d+)/);
2586
+ browserVersion = match ? match[1] : "Unknown";
2587
+ }
2588
+ // Check for Apple Safari
2589
+ else if (userAgent.indexOf("Safari") > -1) {
2590
+ browserType = "Apple Safari";
2591
+ const match = userAgent.match(/Version\/(\d+\.\d+)/);
2592
+ browserVersion = match ? match[1] : "Unknown";
2593
+ }
2594
+
2595
+ return {
2596
+ type: browserType,
2597
+ version: browserVersion,
2598
+ }
2599
+ }
2600
+
2601
+ function isSupported() {
2602
+ if (typeof navigator === 'undefined') {
2603
+ return false
2604
+ }
2605
+ const browserInfo = getBrowserInfo();
2606
+ if (browserInfo.type === "Mozilla Firefox") {
2607
+ return parseFloat(browserInfo.version) > 38
2608
+ }
2609
+ return !!(
2610
+ navigator.mediaDevices &&
2611
+ (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia)
2612
+ )
2613
+ }
2614
+
2615
+ // 校验无意义连续符号
2616
+ function validateMeaninglessConsecutiveSymbols(input) {
2617
+ // 检查是否为空
2618
+ if (input.trim() === '') {
2619
+ return {
2620
+ isValid: false,
2621
+ message: '请输入内容',
2622
+ }
2623
+ }
2624
+ // 检查连续符号(中英文符号)
2625
+ const symbolRegex =
2626
+ /([\-\+\=\*\.\,\;\:\!\@\#\$\%\^\&\_\(\)\[\]\{\}\|\\\/\?\<\>\~\"\'\`\s]|[\u3000-\u303F]|[\uFF00-\uFFEF])\1{6,}/;
2627
+ if (symbolRegex.test(input)) {
2628
+ return {
2629
+ isValid: false,
2630
+ message: '输入无意义内容,请修改',
2631
+ }
2632
+ }
2633
+ // 检查连续数字
2634
+ const digitRegex = /(\d)\1{6,}/;
2635
+ if (digitRegex.test(input)) {
2636
+ return {
2637
+ isValid: false,
2638
+ message: '输入无意义内容,请修改',
2639
+ }
2640
+ }
2641
+ // 检查连续相同文字(中英文)
2642
+ const charRegex = /([\u4e00-\u9fa5a-zA-Z])\1{2,}/;
2643
+ if (charRegex.test(input)) {
2644
+ return {
2645
+ isValid: false,
2646
+ message: '输入无意义内容,请修改',
2647
+ }
2648
+ }
2649
+ return {
2650
+ isValid: true,
2651
+ message: '',
2652
+ }
2653
+ }
2654
+
2655
+ // 数据存储
2656
+ const cache = {
2657
+ data: {},
2658
+ set(key, data) {
2659
+ this.data[key] = data;
2660
+ },
2661
+ get(key) {
2662
+ return this.data[key]
2663
+ },
2664
+ clear(key) {
2665
+ if (key) {
2666
+ delete this.data[key];
2667
+ } else {
2668
+ this.data = {};
2669
+ }
2670
+ }
2671
+ };
2672
+
2673
+ // 建立唯一的key值
2674
+ const buildUniqueUrl = (url, method, params = {}, data = {}) => {
2675
+ const paramStr = (obj) => {
2676
+ if (Object.prototype.toString.call(obj) === '[object Object]') {
2677
+ return JSON.stringify(Object.keys(obj).sort().reduce((result, key) => {
2678
+ result[key] = obj[key];
2679
+ return result
2680
+ }, {}))
2681
+ } else {
2682
+ return JSON.stringify(obj)
2683
+ }
2684
+ };
2685
+ url += `?${paramStr(params)}&${paramStr(data)}&${method}`;
2686
+ return url
2687
+ };
2688
+
2689
+ // 系统标识
2690
+ let system_flag = null;
2691
+
2692
+ function set_system_key(key) {
2693
+ system_flag = key;
2694
+ return system_flag;
2695
+ }
2696
+
2697
+ function get_system_key(key) {
2698
+ if (!system_flag) {
2699
+ console.warn("系统标识未设置,请先调用 set_system_key()");
2700
+ return key;
2701
+ }
2702
+ return `${system_flag}_${key}`;
2703
+ }
2704
+
2705
+ // 用户信息
2706
+ function removeSession(key = "session") {
2707
+ if (typeof window === "undefined" || !window.localStorage) {
2708
+ console.warn("localStorage不可用");
2709
+ return;
2710
+ }
2711
+ localStorage.removeItem(get_system_key(key));
2712
+ }
2713
+
2714
+ function setSession(session, key = "session") {
2715
+ if (typeof window === "undefined" || !window.localStorage) {
2716
+ console.warn("localStorage不可用");
2717
+ return;
2718
+ }
2719
+ localStorage.setItem(get_system_key(key), JSON.stringify(session));
2720
+ }
2721
+
2722
+ function getSession(key = "session") {
2723
+ if (typeof window === "undefined" || !window.localStorage) {
2724
+ console.warn("localStorage不可用");
2725
+ return null;
2726
+ }
2727
+ const value = localStorage.getItem(get_system_key(key));
2728
+ if (value === null || value === undefined || value === "") {
2729
+ return value;
2730
+ } else if (value === "undefined") {
2731
+ return undefined;
2732
+ } else {
2733
+ try {
2734
+ return JSON.parse(value);
2735
+ } catch (e) {
2736
+ console.error("解析session失败:", e);
2737
+ return value;
2738
+ }
2739
+ }
2740
+ }
2741
+
2742
+ // 扩展session中的部分属性,而不是全量替换
2743
+ function extentSession(patch, key = "session") {
2744
+ if (typeof window === "undefined" || !window.localStorage) {
2745
+ console.warn("localStorage不可用");
2746
+ return null;
2747
+ }
2748
+ const prev = getSession(key);
2749
+ if (typeof prev === "object" && prev !== null) {
2750
+ localStorage.setItem(
2751
+ get_system_key(key),
2752
+ JSON.stringify({ ...prev, ...patch })
2753
+ );
2754
+ }
2755
+ return getSession(key);
2756
+ }
2757
+
2758
+ function setSessionStorage(session, key = "collapse") {
2759
+ if (typeof window === "undefined" || !window.sessionStorage) {
2760
+ console.warn("sessionStorage不可用");
2761
+ return;
2762
+ }
2763
+ sessionStorage.setItem(get_system_key(key), JSON.stringify(session));
2764
+ }
2765
+
2766
+ function getSessionStorage(key = "collapse") {
2767
+ if (typeof window === "undefined" || !window.sessionStorage) {
2768
+ console.warn("sessionStorage不可用");
2769
+ return null;
2770
+ }
2771
+ const value = sessionStorage.getItem(get_system_key(key));
2772
+ if (value === null || value === undefined || value === "") {
2773
+ return value;
2774
+ } else if (value === "undefined") {
2775
+ return undefined;
2776
+ } else {
2777
+ try {
2778
+ return JSON.parse(value);
2779
+ } catch (e) {
2780
+ console.error("解析sessionStorage失败:", e);
2781
+ return value;
2782
+ }
2783
+ }
2784
+ }
2785
+
2786
+ function removeSessionStorage(key = "collapse") {
2787
+ if (typeof window === "undefined" || !window.sessionStorage) {
2788
+ console.warn("sessionStorage不可用");
2789
+ return;
2790
+ }
2791
+ sessionStorage.removeItem(get_system_key(key));
2792
+ }
2793
+
2794
+ // 图片地址
2795
+ function getImgURL(url) {
2796
+ if (!url) return ''
2797
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2798
+ const backendServer = typeof window !== 'undefined' && window.GLOBAL_CONFIG
2799
+ ? window.GLOBAL_CONFIG.backend_server
2800
+ : '';
2801
+ if (backendServer) {
2802
+ url = `${backendServer}/_uploads/files/${url}`;
2803
+ }
2804
+ }
2805
+ return url
2806
+ }
2807
+
2808
+ // 量表图片地址
2809
+ function getGaugeImgUrl(url) {
2810
+ if (!url) return ''
2811
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2812
+ const backendServer = typeof window !== 'undefined' && window.GLOBAL_CONFIG
2813
+ ? window.GLOBAL_CONFIG.backend_server
2814
+ : '';
2815
+ if (backendServer) {
2816
+ url = `${backendServer}/api/v1/ma/mobile/resource/local/files?file=${url}`;
2817
+ }
2818
+ }
2819
+ return url
2820
+ }
2821
+
2822
+ // 医生头像
2823
+ function doctor_head_img(url) {
2824
+ if (!url) {
2825
+ return './img/doc_defalut_male.jpg'
2826
+ }
2827
+ if (!/^http/g.test(url) && !/^data:image/g.test(url)) {
2828
+ return `https://annetinfo1.oss-cn-shenzhen.aliyuncs.com/${url}`
2829
+ }
2830
+ return url
2831
+ }
2832
+
2833
+ /**
2834
+ * 设备检测工具函数
2835
+ */
2836
+
2837
+ /**
2838
+ * 检测当前设备是否为平板
2839
+ * @returns {boolean} 是否为平板设备
2840
+ */
2841
+ function isTablet() {
2842
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2843
+ return false
2844
+ }
2845
+
2846
+ // 获取用户代理字符串
2847
+ const userAgent = navigator.userAgent.toLowerCase();
2848
+
2849
+ // 检测常见的平板设备标识
2850
+ const tabletPatterns = [
2851
+ /ipad/, // iPad
2852
+ /android.*tablet/, // Android 平板
2853
+ /kindle/, // Kindle
2854
+ /silk/, // Amazon Silk
2855
+ /playbook/, // BlackBerry PlayBook
2856
+ /bb10/, // BlackBerry 10
2857
+ /rim tablet/, // BlackBerry Tablet OS
2858
+ /windows.*touch/, // Windows 平板
2859
+ /tablet/, // 通用平板标识
2860
+ ];
2861
+
2862
+ // 检查用户代理是否匹配平板模式
2863
+ const isTabletByUserAgent = tabletPatterns.some(pattern => pattern.test(userAgent));
2864
+
2865
+ // 检测屏幕尺寸和触摸支持
2866
+ const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
2867
+ const screenWidth = window.screen.width;
2868
+ const screenHeight = window.screen.height;
2869
+ const minDimension = Math.min(screenWidth, screenHeight);
2870
+ const maxDimension = Math.max(screenWidth, screenHeight);
2871
+
2872
+ // 平板设备的典型屏幕尺寸范围
2873
+ const isTabletByScreenSize = (
2874
+ (minDimension >= 600 && minDimension <= 1200) &&
2875
+ (maxDimension >= 800 && maxDimension <= 1600)
2876
+ );
2877
+
2878
+ // 检测是否为移动设备但屏幕较大(可能是平板)
2879
+ const isMobile = /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
2880
+ const isLargeMobile = isMobile && minDimension >= 600;
2881
+
2882
+ // 综合判断:用户代理匹配 或 (屏幕尺寸符合平板特征 且 支持触摸) 或 (大屏移动设备)
2883
+ return isTabletByUserAgent ||
2884
+ (isTabletByScreenSize && hasTouch) ||
2885
+ isLargeMobile
2886
+ }
2887
+
2888
+ /**
2889
+ * 检测当前设备类型
2890
+ * @returns {string} 'desktop' | 'tablet' | 'mobile'
2891
+ */
2892
+ function getDeviceType() {
2893
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2894
+ return 'desktop'
2895
+ }
2896
+
2897
+ if (isTablet()) {
2898
+ return 'tablet'
2899
+ }
2900
+
2901
+ const userAgent = navigator.userAgent.toLowerCase();
2902
+ const isMobile = /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
2903
+
2904
+ return isMobile ? 'mobile' : 'desktop'
2905
+ }
2906
+
2907
+ /**
2908
+ * 检测是否为触摸设备
2909
+ * @returns {boolean} 是否为触摸设备
2910
+ */
2911
+ function isTouchDevice() {
2912
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2913
+ return false
2914
+ }
2915
+ return 'ontouchstart' in window || navigator.maxTouchPoints > 0
2916
+ }
2917
+
2918
+ /**
2919
+ * 获取设备信息
2920
+ * @returns {object} 设备信息对象
2921
+ */
2922
+ function getDeviceInfo() {
2923
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
2924
+ return {
2925
+ isTablet: false,
2926
+ deviceType: 'desktop',
2927
+ isTouchDevice: false,
2928
+ userAgent: '',
2929
+ screenWidth: 0,
2930
+ screenHeight: 0,
2931
+ devicePixelRatio: 1,
2932
+ orientation: 'unknown'
2933
+ }
2934
+ }
2935
+
2936
+ return {
2937
+ isTablet: isTablet(),
2938
+ deviceType: getDeviceType(),
2939
+ isTouchDevice: isTouchDevice(),
2940
+ userAgent: navigator.userAgent,
2941
+ screenWidth: window.screen.width,
2942
+ screenHeight: window.screen.height,
2943
+ devicePixelRatio: window.devicePixelRatio || 1,
2944
+ orientation: screen.orientation ? screen.orientation.type : 'unknown'
2945
+ }
2946
+ }
2947
+
2948
+ /* eslint-disable */
2949
+
2950
+ /*
2951
+ 将url的传参参数形式的字符串转化为json对象格式
2952
+
2953
+ let param = 'school=gongda&hobby=skating&number=3'
2954
+ let jsonObj = queryToObj(param)
2955
+
2956
+ console.log(jsonObj)
2957
+ 输出:{
2958
+ school: 'gongda',
2959
+ hobby: 'skaing',
2960
+ number: '3'
2961
+ }
2962
+ */
2963
+ function queryToObj(str) {
2964
+ var theRequest = {};
2965
+ if (str) {
2966
+ var strs = str.includes('&') ? str.split('&') : ('&' + str).split('&');
2967
+ for (let i = 0; i < strs.length; i++) {
2968
+ if (strs[i].includes('=')) {
2969
+ const parts = strs[i].split('=');
2970
+ theRequest[parts[0]] = decodeURIComponent(parts[1] || '');
2971
+ }
2972
+ }
2973
+ }
2974
+ return theRequest
2975
+ }
2976
+
2977
+ /*
2978
+ * 将obj转换成url参数形式
2979
+ * toQueryString({a:1,b:2}) => a=1&b=2
2980
+ *
2981
+ * */
2982
+ function toQueryPair(key, value) {
2983
+ if (typeof value == 'undefined') {
2984
+ return key
2985
+ }
2986
+ return key + '=' + encodeURIComponent(value === null ? '' : String(value))
2987
+ }
2988
+
2989
+ function toQueryString(obj) {
2990
+ var ret = [];
2991
+ for (var key in obj) {
2992
+ key = encodeURIComponent(key);
2993
+ var values = obj[key];
2994
+ if (values && values.constructor == Array) {
2995
+ //数组
2996
+ var queryValues = [];
2997
+ for (var i = 0, len = values.length, value; i < len; i++) {
2998
+ value = values[i];
2999
+ queryValues.push(toQueryPair(key, value));
3000
+ }
3001
+ ret = ret.concat(queryValues);
3002
+ } else {
3003
+ //字符串
3004
+ ret.push(toQueryPair(key, values));
3005
+ }
3006
+ }
3007
+ return ret.join('&')
3008
+ }
3009
+
3010
+ /*
3011
+ 直接取url中的参数转为json(或者不转)
3012
+ 用法1:
3013
+ let para = urlToJson()
3014
+ console.log(para)
3015
+
3016
+ 用法2:
3017
+ let para = urlToJson('https://www.baidu.com?a=1&b=2')
3018
+ console.log(para)
3019
+
3020
+ * */
3021
+ function urlToJson(selfUrl) {
3022
+ if (typeof window === 'undefined') {
3023
+ return { paramStr: '', paramJson: {} }
3024
+ }
3025
+ const url = selfUrl ? selfUrl : window.location.href;
3026
+
3027
+ const reg = /\?.*$/; // 正则取'?后的参数'
3028
+ const urlMatch = url.match(reg);
3029
+
3030
+ // 匹配去掉?的纯参数(正则精髓,贪婪永远匹配最后一个?后的参数)
3031
+ const param = urlMatch && urlMatch.length ? urlMatch[0].replace(/^\?*.*\?/, '') : '';
3032
+
3033
+ const output = {
3034
+ paramStr: param,
3035
+ paramJson: queryToObj(param)
3036
+ };
3037
+
3038
+ return output
3039
+ }
3040
+
3041
+ /*
3042
+ 直接取url中的某个参数
3043
+ 用法:
3044
+ let deviceType = getQueryString('deviceType')
3045
+ console.log(deviceType)
3046
+
3047
+ * */
3048
+ function getQueryString(name, url) {
3049
+ if (typeof window === 'undefined') {
3050
+ return ''
3051
+ }
3052
+ url = url || window.location.href;
3053
+ var str = url.match(new RegExp('([?&#])' + name.replace('#', '') + '=([^#&?]*)', 'gi'));
3054
+ return str ? decodeURIComponent(str[0].split('=')[1]) : ''
3055
+ }
3056
+
3057
+ /*
3058
+ 更改url中的某个参数,返回更改后的最终带参数url
3059
+ 参数解析:
3060
+ json: 更改参数的json对象
3061
+ originUrl:预置的网站地址
3062
+
3063
+ 用法一:
3064
+ let resultUrl = setUrl({id: 1, name: '测试页面'})
3065
+ console.log(resultUrl) // 输出:https://********.html?id=1&name=测试页面
3066
+
3067
+ 用法二:
3068
+ let resultUrl = setUrl({id: 3, name: '哈哈哈'}, 'https://www.baidu.com')
3069
+ console.log(resultUrl) // 输出:https://www.baidu.com?id=3&name=哈哈哈
3070
+
3071
+ * */
3072
+ function setUrl(json, originUrl = '') {
3073
+ if (typeof window === 'undefined') {
3074
+ return ''
3075
+ }
3076
+ let paramJson = urlToJson().paramJson;
3077
+ // 新的参数
3078
+ let newJson = {
3079
+ ...paramJson,
3080
+ ...json
3081
+ };
3082
+
3083
+ // 参数对象 =》get参数
3084
+ let paramStr = toQueryString(newJson);
3085
+
3086
+ // url的origin + pathname
3087
+ let oPath = originUrl ? originUrl : window.location.origin + window.location.pathname;
3088
+
3089
+ let resultUrl = oPath + '?' + paramStr;
3090
+ return resultUrl
3091
+ }
3092
+
3093
+ // url参数(兼容旧API)
3094
+ function get_url_params(url) {
3095
+ if (typeof window === 'undefined') {
3096
+ return {}
3097
+ }
3098
+ const targetUrl = url || window.location.href;
3099
+ return urlToJson(targetUrl).paramJson
3100
+ }
3101
+
3102
+ function convertMilliseconds(ms, secondsTo2decimal = false) {
3103
+ if (!ms) return "";
3104
+
3105
+ const hours = Math.floor(ms / 3600000); // 计算小时
3106
+ const minutes = Math.floor((ms % 3600000) / 60000); // 计算分钟
3107
+ let seconds = 0;
3108
+ if (secondsTo2decimal) {
3109
+ seconds = parseFloat(((ms % 60000) / 1000).toFixed(2));
3110
+ } else {
3111
+ seconds = Math.floor((ms % 60000) / 1000); // 计算秒数
3112
+ }
3113
+
3114
+ return {
3115
+ hours,
3116
+ minutes,
3117
+ seconds,
3118
+ };
3119
+ }
3120
+
3121
+ const myDebounce = function (fn, time = 600) {
3122
+ let timerId = "";
3123
+ return function (...arg) {
3124
+ timerId && clearTimeout(timerId);
3125
+ timerId = setTimeout(() => {
3126
+ fn && fn.call(this, ...arg);
3127
+ }, time);
3128
+ };
3129
+ };
3130
+
3131
+ const mapStringifyReplacer = function (key, value) {
3132
+ if (value instanceof Map) {
3133
+ return {
3134
+ dataType: "Map",
3135
+ value: Array.from(value.entries()),
3136
+ };
3137
+ } else {
3138
+ return value;
3139
+ }
3140
+ };
3141
+
3142
+ const mapParseReviver = function (key, value) {
3143
+ if (typeof value === "object" && value !== null) {
3144
+ if (value.dataType === "Map") {
3145
+ return new Map(value.value);
3146
+ }
3147
+ }
3148
+ return value;
3149
+ };
3150
+
3151
+ function getHalfYearAgoToday(reduce = 12) {
3152
+ const today = new Date().setHours(0, 0, 0, 0);
3153
+ const currentMonth = new Date().getMonth();
3154
+ return new Date(today).setMonth(currentMonth - reduce);
3155
+ }
3156
+
3157
+ // 文件下载助手
3158
+ const fileDownloadHelper = {
3159
+ /**
3160
+ * 下载文件
3161
+ * @param {Blob} blob - 文件Blob对象
3162
+ * @param {string} filename - 下载文件名
3163
+ */
3164
+ download(blob, filename) {
3165
+ if (typeof window === "undefined") {
3166
+ console.warn("fileDownloadHelper.download只能在浏览器环境使用");
3167
+ return;
3168
+ }
3169
+ const url = window.URL.createObjectURL(blob);
3170
+ const link = document.createElement("a");
3171
+ link.href = url;
3172
+ link.setAttribute("download", filename);
3173
+ document.body.appendChild(link);
3174
+ link.click();
3175
+ window.URL.revokeObjectURL(url);
3176
+ document.body.removeChild(link);
3177
+ },
3178
+
3179
+ /**
3180
+ * 从响应头获取文件名
3181
+ * @param {Object} headers - 响应头
3182
+ * @param {string} defaultName - 默认文件名
3183
+ * @returns {string} 文件名
3184
+ */
3185
+ getFilenameFromHeaders(headers, defaultName) {
3186
+ const contentDisposition = headers["content-disposition"];
3187
+ if (!contentDisposition) return defaultName;
3188
+
3189
+ const filenameMatch = contentDisposition.match(/filename=(.+)/);
3190
+ return filenameMatch && filenameMatch.length > 1
3191
+ ? decodeURIComponent(filenameMatch[1]).replace(/['"]/g, "")
3192
+ : defaultName;
3193
+ },
3194
+ };
3195
+
3196
+ /**
3197
+ * 复制文本到剪贴板
3198
+ * @param {string} text - 要复制的文本
3199
+ * @returns {Promise<boolean>} - 返回一个Promise,复制成功返回true,失败返回false
3200
+ */
3201
+ async function copyText(text) {
3202
+ if (typeof window === "undefined") {
3203
+ console.warn("copyText只能在浏览器环境使用");
3204
+ return false;
3205
+ }
3206
+
3207
+ try {
3208
+ // 优先使用现代的Clipboard API
3209
+ if (navigator.clipboard && window.isSecureContext) {
3210
+ await navigator.clipboard.writeText(text);
3211
+ return true;
3212
+ }
3213
+
3214
+ // 降级方案:使用传统的document.execCommand方法
3215
+ const textArea = document.createElement("textarea");
3216
+ textArea.value = text;
3217
+
3218
+ // 防止页面滚动
3219
+ textArea.style.position = "fixed";
3220
+ textArea.style.left = "-999999px";
3221
+ textArea.style.top = "-999999px";
3222
+
3223
+ document.body.appendChild(textArea);
3224
+ textArea.focus();
3225
+ textArea.select();
3226
+
3227
+ try {
3228
+ const successful = document.execCommand("copy");
3229
+ document.body.removeChild(textArea);
3230
+ return successful;
3231
+ } catch (err) {
3232
+ document.body.removeChild(textArea);
3233
+ return false;
3234
+ }
3235
+ } catch (err) {
3236
+ return false;
3237
+ }
3238
+ }
3239
+
3240
+ // 防抖(兼容旧API)
3241
+ function debounce(fn, delay = 200) {
3242
+ let timeout = null;
3243
+ return function () {
3244
+ let context = this;
3245
+ let args = arguments;
3246
+ clearTimeout(timeout);
3247
+ timeout = setTimeout(() => {
3248
+ fn.apply(context, args);
3249
+ }, delay);
3250
+ };
3251
+ }
3252
+
3253
+ // 节流
3254
+ const throttle = (fn, delay = 100) => {
3255
+ let timer = null;
3256
+ let start_time = Date.now();
3257
+ return function (...args) {
3258
+ const current_time = Date.now();
3259
+ const diff = delay - (current_time - start_time);
3260
+ if (timer) clearTimeout(timer);
3261
+ if (diff <= 0) {
3262
+ fn.apply(this, args);
3263
+ start_time = Date.now();
3264
+ } else {
3265
+ timer = setTimeout(() => {
3266
+ fn.apply(this, args);
3267
+ }, diff);
3268
+ }
3269
+ };
3270
+ };
3271
+
3272
+ const uuid = function () {
3273
+ let random;
3274
+
3275
+ try {
3276
+ if (typeof window !== 'undefined' && window.crypto) {
3277
+ const arr = new Uint32Array(1);
3278
+ // https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
3279
+ window.crypto.getRandomValues(arr);
3280
+ random = arr[0] & 2147483647;
3281
+ } else {
3282
+ random = Math.floor(Math.random() * 2147483648);
3283
+ }
3284
+ } catch (b) {
3285
+ random = Math.floor(Math.random() * 2147483648);
3286
+ }
3287
+
3288
+ return random.toString(36)
3289
+ };
3290
+
3291
+ const uuidLong = function () {
3292
+ return `${uuid()}${uuid()}${uuid()}`
3293
+ };
3294
+
3295
+ function baseGet(object, path) {
3296
+ path = castPath(path);
3297
+
3298
+ var index = 0,
3299
+ length = path.length;
3300
+
3301
+ while (object != null && index < length) {
3302
+ object = object[path[index++]];
3303
+ }
3304
+ return (index && index == length) ? object : undefined
3305
+ }
3306
+
3307
+ function castPath(value, object) {
3308
+ if (Array.isArray(value)) {
3309
+ return value
3310
+ }
3311
+ return stringToPath(String(value))
3312
+ }
3313
+
3314
+ function stringToPath(string) {
3315
+ var result = [];
3316
+ if (string.charCodeAt(0) === 46 /* . */) {
3317
+ result.push('');
3318
+ }
3319
+ string.replace(/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, function(match, number, quote, subString) {
3320
+ result.push(quote ? subString.replace(/\\(\\)?/g, '$1') : (number || match));
3321
+ });
3322
+ return result
3323
+ }
3324
+
3325
+ function get(object, path, defaultValue) {
3326
+ var result = object == null ? undefined : baseGet(object, path);
3327
+ return result === undefined ? defaultValue : result
3328
+ }
3329
+
3330
+ // 防止重复请求
3331
+ var index = (options = {}) =>
3332
+ async (config) => {
3333
+ const defaultOptions = {
3334
+ time: 0, // 设置为0,不清除缓存
3335
+ ...options,
3336
+ };
3337
+ const index = buildUniqueUrl(
3338
+ config.url,
3339
+ config.method,
3340
+ config.params,
3341
+ config.data
3342
+ );
3343
+ let responsePromise = cache.get(index);
3344
+ if (!responsePromise) {
3345
+ responsePromise = (async () => {
3346
+ try {
3347
+ // 需要确保axios可用,这里假设axios已经通过其他方式引入
3348
+ let axios = null;
3349
+ if (typeof window !== "undefined" && window.axios) {
3350
+ axios = window.axios;
3351
+ } else if (typeof require !== "undefined") {
3352
+ try {
3353
+ axios = require("axios");
3354
+ } catch (e) {
3355
+ // ignore
3356
+ }
3357
+ }
3358
+
3359
+ if (axios && axios.defaults && axios.defaults.adapter) {
3360
+ const response = await axios.defaults.adapter(config);
3361
+ return Promise.resolve(response);
3362
+ } else {
3363
+ throw new Error("axios未找到,请确保已安装axios");
3364
+ }
3365
+ } catch (reason) {
3366
+ cache.clear(index);
3367
+ return Promise.reject(reason);
3368
+ }
3369
+ })();
3370
+ cache.set(index, responsePromise);
3371
+ if (defaultOptions.time !== 0) {
3372
+ setTimeout(() => {
3373
+ cache.clear(index);
3374
+ }, defaultOptions.time);
3375
+ }
3376
+ }
3377
+ return responsePromise.then((data) => JSON.parse(JSON.stringify(data))); // 为防止数据源污染
3378
+ };
3379
+
3380
+ export { arr_label, arr_obj, buildUniqueUrl, cache, calculate_height, convertMilliseconds, copyText, copyToClip, copy_content, create_guid, debounce, index as defaultAdapter, detectZoom, doctor_head_img, escapeRegExp, extentSession, fileDownloadHelper, findNodeOfTree, formatDateMinute, formatTxt, format_date, format_decimal, format_decimal_string, format_money, format_number, get, getBrowserInfo, getDeviceInfo, getDeviceType, getGaugeImgUrl, getHalfYearAgoToday, getImgURL, getQueryString, getSession, getSessionStorage, get_system_key, get_url_params, hidePhone, isEmpty, isEmptyObj, isEqual, isSupported, isTablet, isTouchDevice, mapParseReviver, mapStringifyReplacer, myDebounce, queryToObj, removeSession, removeSessionStorage, setSession, setSessionStorage, setUrl, set_cursor, set_system_key, sleep, throttle, toQueryString, urlToJson, uuid, uuidLong, validateFieldAsync, validateMeaninglessConsecutiveSymbols, validatePhone };