@odigos/ui-kit 0.0.97 → 0.0.99

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.
@@ -1,3598 +0,0 @@
1
- import { O as useModalStore, Q as useDrawerStore, U as useActiveNodeStore } from './index-40dfa720.js';
2
- import { AddNodeTypes, EntityTypes, PayloadCollectionKeyTypes, CodeAttributesKeyTypes, CustomInstrumentationsKeyTypes } from './types.js';
3
- import React, { useState, useMemo, useEffect, useRef, useCallback } from 'react';
4
- import styled from 'styled-components';
5
- import { d as deepClone } from './index-5e5f7bda.js';
6
-
7
- const useGenericForm = (initialFormData) => {
8
- function copyInitial() {
9
- // this is to avoid reference issues with the initial form data,
10
- // when an object has arrays or objects as part of it's values, a simple spread operator won't work, the children would act as references,
11
- // so we use JSON.parse(JSON.stringify()) to create a deep copy of the object without affecting the original
12
- if (initialFormData === undefined)
13
- return {};
14
- return JSON.parse(JSON.stringify(initialFormData));
15
- }
16
- const [formData, setFormData] = useState(copyInitial());
17
- const [formErrors, setFormErrors] = useState({});
18
- const isFormDirty = useMemo(() => {
19
- return initialFormData !== undefined && JSON.stringify(formData) !== JSON.stringify(initialFormData);
20
- }, [initialFormData, formData]);
21
- useEffect(() => {
22
- if (initialFormData !== undefined && JSON.stringify(formData) === '{}')
23
- setFormData(copyInitial());
24
- // eslint-disable-next-line react-hooks/exhaustive-deps
25
- }, [initialFormData, formData]);
26
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
- const handleFormChange = (key, val, obj) => {
28
- if (key) {
29
- // this is for cases where the form contains objects such as "exportedSignals",
30
- // the object's child is targeted with a "." for example: "exportedSignals.logs"
31
- const splittedKeys = key.toString().split('.');
32
- if (splittedKeys.length === 1) {
33
- setFormData((prev) => ({ ...prev, [key]: val }));
34
- }
35
- else {
36
- setFormData((prev) => {
37
- const payload = deepClone(prev);
38
- let current = payload;
39
- // Navigate to the parent of the final key, creating objects as needed
40
- for (let i = 0; i < splittedKeys.length - 1; i++) {
41
- const key = splittedKeys[i];
42
- if (!current[key] || typeof current[key] !== 'object') {
43
- current[key] = {};
44
- }
45
- current = current[key];
46
- }
47
- // Set the final value
48
- const finalKey = splittedKeys[splittedKeys.length - 1];
49
- current[finalKey] = val;
50
- return payload;
51
- });
52
- }
53
- }
54
- else if (obj) {
55
- setFormData({ ...obj });
56
- }
57
- };
58
- const handleErrorChange = (key, val, obj) => {
59
- if (key) {
60
- setFormErrors((prev) => ({ ...prev, [key]: val }));
61
- }
62
- else if (obj) {
63
- setFormErrors({ ...obj });
64
- }
65
- };
66
- const resetFormData = () => {
67
- setFormData(copyInitial());
68
- setFormErrors({});
69
- };
70
- return {
71
- formData,
72
- formErrors,
73
- isFormDirty,
74
- handleFormChange,
75
- handleErrorChange,
76
- resetFormData,
77
- };
78
- };
79
-
80
- const useClickNode = () => {
81
- const { setCurrentModal } = useModalStore();
82
- const { setDrawerType, setDrawerEntityId } = useDrawerStore();
83
- const { setActiveNodeType, setActiveNodeId, activeNodeId } = useActiveNodeStore();
84
- const onClickNode = (_, object) => {
85
- const { id: nodeId, type: nodeType, data: { id: entityId, type: entityType }, } = object;
86
- if (activeNodeId === nodeId) {
87
- setActiveNodeType(null);
88
- setActiveNodeId(null);
89
- }
90
- else {
91
- setActiveNodeType(nodeType);
92
- setActiveNodeId(nodeId);
93
- }
94
- switch (entityType) {
95
- case EntityTypes.Source:
96
- case EntityTypes.Destination:
97
- case EntityTypes.Action:
98
- case EntityTypes.InstrumentationRule:
99
- setDrawerType(entityType);
100
- setDrawerEntityId(entityId);
101
- break;
102
- case AddNodeTypes.AddSource:
103
- setCurrentModal(EntityTypes.Source);
104
- break;
105
- case AddNodeTypes.AddDestination:
106
- setCurrentModal(EntityTypes.Destination);
107
- break;
108
- case AddNodeTypes.AddAction:
109
- setCurrentModal(EntityTypes.Action);
110
- break;
111
- case AddNodeTypes.AddRule:
112
- setCurrentModal(EntityTypes.InstrumentationRule);
113
- break;
114
- default:
115
- console.warn('Unhandled node click', object);
116
- break;
117
- }
118
- };
119
- return { onClickNode };
120
- };
121
-
122
- const useContainerSize = () => {
123
- const ref = useRef(null);
124
- const [width, setWidth] = useState(0);
125
- const [height, setHeight] = useState(0);
126
- useEffect(() => {
127
- const resize = () => {
128
- if (ref.current) {
129
- const { width, height } = ref.current.getBoundingClientRect();
130
- setWidth(width);
131
- setHeight(height);
132
- }
133
- };
134
- resize();
135
- window.addEventListener('resize', resize);
136
- return () => window.removeEventListener('resize', resize);
137
- }, []);
138
- return {
139
- containerRef: ref,
140
- containerWidth: width,
141
- containerHeight: height,
142
- };
143
- };
144
-
145
- const useCopy = () => {
146
- const [isCopied, setIsCopied] = useState(false);
147
- const [copiedIndex, setCopiedIndex] = useState(-1);
148
- const clickCopy = async (str, idx) => {
149
- if (!isCopied) {
150
- setIsCopied(true);
151
- if (idx !== undefined)
152
- setCopiedIndex(idx);
153
- if (navigator?.clipboard && navigator.clipboard.writeText) {
154
- try {
155
- await navigator.clipboard.writeText(str);
156
- }
157
- catch (err) {
158
- console.error('Clipboard write failed:', err);
159
- }
160
- }
161
- else {
162
- // Fallback: Create a temporary textarea
163
- const textArea = document.createElement('textarea');
164
- textArea.value = str;
165
- document.body.appendChild(textArea);
166
- textArea.select();
167
- try {
168
- document.execCommand('copy');
169
- }
170
- catch (err) {
171
- console.error('execCommand copy failed:', err);
172
- }
173
- document.body.removeChild(textArea);
174
- }
175
- setTimeout(() => {
176
- setIsCopied(false);
177
- setCopiedIndex(-1);
178
- }, 1000);
179
- }
180
- };
181
- return { isCopied, copiedIndex, clickCopy };
182
- };
183
-
184
- const INITIAL = {
185
- ruleName: '',
186
- notes: '',
187
- disabled: false,
188
- workloads: null,
189
- instrumentationLibraries: null,
190
- payloadCollection: {
191
- [PayloadCollectionKeyTypes.HttpRequest]: null,
192
- [PayloadCollectionKeyTypes.HttpResponse]: null,
193
- [PayloadCollectionKeyTypes.DbQuery]: null,
194
- [PayloadCollectionKeyTypes.Messaging]: null,
195
- },
196
- codeAttributes: {
197
- [CodeAttributesKeyTypes.Column]: null,
198
- [CodeAttributesKeyTypes.FilePath]: null,
199
- [CodeAttributesKeyTypes.Function]: null,
200
- [CodeAttributesKeyTypes.LineNumber]: null,
201
- [CodeAttributesKeyTypes.Namespace]: null,
202
- [CodeAttributesKeyTypes.StackTrace]: null,
203
- },
204
- headersCollection: null,
205
- customInstrumentations: {
206
- [CustomInstrumentationsKeyTypes.Probes]: null,
207
- },
208
- };
209
- const useInstrumentationRuleFormData = () => {
210
- const { formData, formErrors, handleFormChange, handleErrorChange, resetFormData } = useGenericForm(INITIAL);
211
- const validateForm = () => {
212
- // We don't have any specific validations for this form yet
213
- handleErrorChange(undefined, undefined, {});
214
- return true;
215
- };
216
- const loadFormWithDrawerItem = ({ ruleName, notes, disabled, payloadCollection, codeAttributes, headersCollection, customInstrumentations }) => {
217
- const updatedData = {
218
- ...INITIAL,
219
- ruleName,
220
- notes,
221
- disabled,
222
- };
223
- if (payloadCollection) {
224
- updatedData['payloadCollection'] = {
225
- [PayloadCollectionKeyTypes.HttpRequest]: !!payloadCollection[PayloadCollectionKeyTypes.HttpRequest] ? {} : null,
226
- [PayloadCollectionKeyTypes.HttpResponse]: !!payloadCollection[PayloadCollectionKeyTypes.HttpResponse] ? {} : null,
227
- [PayloadCollectionKeyTypes.DbQuery]: !!payloadCollection[PayloadCollectionKeyTypes.DbQuery] ? {} : null,
228
- [PayloadCollectionKeyTypes.Messaging]: !!payloadCollection[PayloadCollectionKeyTypes.Messaging] ? {} : null,
229
- };
230
- }
231
- if (codeAttributes) {
232
- updatedData['codeAttributes'] = {
233
- [CodeAttributesKeyTypes.Column]: codeAttributes[CodeAttributesKeyTypes.Column] || null,
234
- [CodeAttributesKeyTypes.FilePath]: codeAttributes[CodeAttributesKeyTypes.FilePath] || null,
235
- [CodeAttributesKeyTypes.Function]: codeAttributes[CodeAttributesKeyTypes.Function] || null,
236
- [CodeAttributesKeyTypes.LineNumber]: codeAttributes[CodeAttributesKeyTypes.LineNumber] || null,
237
- [CodeAttributesKeyTypes.Namespace]: codeAttributes[CodeAttributesKeyTypes.Namespace] || null,
238
- [CodeAttributesKeyTypes.StackTrace]: codeAttributes[CodeAttributesKeyTypes.StackTrace] || null,
239
- };
240
- }
241
- if (headersCollection) {
242
- updatedData['headersCollection'] = headersCollection;
243
- }
244
- if (customInstrumentations) {
245
- updatedData['customInstrumentations'] = {
246
- [CustomInstrumentationsKeyTypes.Probes]: customInstrumentations[CustomInstrumentationsKeyTypes.Probes] || null,
247
- };
248
- }
249
- handleFormChange(undefined, undefined, updatedData);
250
- };
251
- return {
252
- formData,
253
- formErrors,
254
- handleFormChange,
255
- resetFormData,
256
- validateForm,
257
- loadFormWithDrawerItem,
258
- };
259
- };
260
-
261
- const useKeyDown = ({ active, key, withAltKey, withCtrlKey, withShiftKey, withMetaKey }, callback) => {
262
- useEffect(() => {
263
- const handleKeyDown = (e) => {
264
- if (active &&
265
- key === e.key &&
266
- (!withAltKey || (withAltKey && e.altKey)) &&
267
- (!withCtrlKey || (withCtrlKey && e.ctrlKey)) &&
268
- (!withShiftKey || (withShiftKey && e.shiftKey)) &&
269
- (!withMetaKey || (withMetaKey && e.metaKey))) {
270
- e.preventDefault();
271
- e.stopPropagation();
272
- callback(e);
273
- }
274
- };
275
- window.addEventListener('keydown', handleKeyDown);
276
- return () => {
277
- window.removeEventListener('keydown', handleKeyDown);
278
- };
279
- }, [key, active, withAltKey, withCtrlKey, withShiftKey, withMetaKey, callback]);
280
- return null;
281
- };
282
-
283
- const useOnClickOutside = (ref, handler) => {
284
- useEffect(() => {
285
- const listener = (event) => {
286
- // Do nothing if clicking ref's element or descendent elements
287
- if (!ref.current || ref.current.contains(event.target)) {
288
- return;
289
- }
290
- handler();
291
- };
292
- document.addEventListener('mousedown', listener);
293
- document.addEventListener('touchstart', listener);
294
- return () => {
295
- document.removeEventListener('mousedown', listener);
296
- document.removeEventListener('touchstart', listener);
297
- };
298
- }, [ref, handler]);
299
- };
300
-
301
- const usePopup = ({ defaultClientHeight = 0, defaultClientwidth = 0, onClickOutside } = {}) => {
302
- const popupRef = useRef(null);
303
- const [popupOpen, setPopupOpen] = useState(false);
304
- const [popupPosition, setPopupPosition] = useState({ top: 0, left: 0 });
305
- useOnClickOutside(popupRef, () => {
306
- if (popupOpen) {
307
- setPopupOpen(false);
308
- onClickOutside?.();
309
- }
310
- });
311
- const handlePosition = (clientX, clientY) => {
312
- const { innerWidth, innerHeight } = window;
313
- let top = clientY;
314
- let left = clientX;
315
- if (top >= innerHeight / 2)
316
- top += -(popupRef.current?.clientHeight || defaultClientHeight);
317
- if (left >= innerWidth / 2)
318
- left += -(popupRef.current?.clientWidth || defaultClientwidth);
319
- setPopupPosition({ top, left });
320
- };
321
- return {
322
- popupRef,
323
- popupOpen,
324
- setPopupOpen,
325
- popupPosition,
326
- handlePosition,
327
- };
328
- };
329
-
330
- // Fallback locale.
331
- // (when not a single one of the supplied "preferred" locales is available)
332
- var defaultLocale$1 = 'en'; // For all locales added
333
- // their relative time formatter messages will be stored here.
334
-
335
- var localesData$1 = {}; // According to the spec BCP 47 language tags are case-insensitive.
336
- // https://tools.ietf.org/html/rfc5646
337
-
338
- var lowercaseLocaleLookup = {};
339
- function getDefaultLocale() {
340
- return defaultLocale$1;
341
- }
342
- function setDefaultLocale(locale) {
343
- defaultLocale$1 = locale;
344
- }
345
- /**
346
- * Gets locale data previously added by `addLocaleData()`.
347
- * @return {object} [localeData]
348
- */
349
-
350
- function getLocaleData$1(locale) {
351
- return localesData$1[locale];
352
- }
353
- /**
354
- * Adds locale data.
355
- * Is called by `RelativeTimeFormat.addLocale(...)`.
356
- * @param {object} localeData
357
- */
358
-
359
- function addLocaleData$1(localeData) {
360
- if (!localeData) {
361
- throw new Error('No locale data passed');
362
- } // This locale data is stored in a global variable
363
- // and later used when calling `.format(time)`.
364
-
365
-
366
- localesData$1[localeData.locale] = localeData;
367
- lowercaseLocaleLookup[localeData.locale.toLowerCase()] = localeData.locale;
368
- }
369
- /**
370
- * Returns a locale for which locale data has been added
371
- * via `RelativeTimeFormat.addLocale(...)`.
372
- * @param {string} locale
373
- * @return {string} [locale]
374
- */
375
-
376
- function resolveLocale$1(locale) {
377
- if (localesData$1[locale]) {
378
- return locale;
379
- }
380
-
381
- if (lowercaseLocaleLookup[locale.toLowerCase()]) {
382
- return lowercaseLocaleLookup[locale.toLowerCase()];
383
- }
384
- }
385
-
386
- /**
387
- * Resolves a locale to a supported one (if any).
388
- * @param {string} locale
389
- * @param {Object} [options] - An object that may have the following property:
390
- * @param {string} [options.localeMatcher="lookup"] - The locale matching algorithm to use. Possible values are "lookup" and "best fit". Currently only "lookup" is supported.
391
- * @return {string} [locale]
392
- * @example
393
- * // Returns "sr"
394
- * resolveLocale("sr-Cyrl-BA")
395
- * // Returns `undefined`
396
- * resolveLocale("xx-Latn")
397
- */
398
-
399
- function resolveLocale(locale) {
400
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
401
- var localeMatcher = options.localeMatcher || 'lookup';
402
-
403
- switch (localeMatcher) {
404
- case 'lookup':
405
- return resolveLocaleLookup(locale);
406
- // "best fit" locale matching is not supported.
407
- // https://github.com/catamphetamine/relative-time-format/issues/2
408
-
409
- case 'best fit':
410
- // return resolveLocaleBestFit(locale)
411
- return resolveLocaleLookup(locale);
412
-
413
- default:
414
- throw new RangeError("Invalid \"localeMatcher\" option: ".concat(localeMatcher));
415
- }
416
- }
417
- /**
418
- * Resolves a locale to a supported one (if any).
419
- * Starts from the most specific locale and gradually
420
- * falls back to less specific ones.
421
- * This is a basic implementation of the "lookup" algorithm.
422
- * https://tools.ietf.org/html/rfc4647#section-3.4
423
- * @param {string} locale
424
- * @return {string} [locale]
425
- * @example
426
- * // Returns "sr"
427
- * resolveLocaleLookup("sr-Cyrl-BA")
428
- * // Returns `undefined`
429
- * resolveLocaleLookup("xx-Latn")
430
- */
431
-
432
- function resolveLocaleLookup(locale) {
433
- var resolvedLocale = resolveLocale$1(locale);
434
-
435
- if (resolvedLocale) {
436
- return resolvedLocale;
437
- } // `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.
438
-
439
-
440
- var parts = locale.split('-');
441
-
442
- while (locale.length > 1) {
443
- parts.pop();
444
- locale = parts.join('-');
445
-
446
- var _resolvedLocale = resolveLocale$1(locale);
447
-
448
- if (_resolvedLocale) {
449
- return _resolvedLocale;
450
- }
451
- }
452
- }
453
-
454
- // (this file was autogenerated by `generate-locales`)
455
- // "plural rules" functions are not stored in locale JSON files because they're not strings.
456
- // This file isn't big — it's about 5 kilobytes in size (minified).
457
- // Alternatively, the pluralization rules for each locale could be stored
458
- // in their JSON files in a non-parsed form and later parsed via `make-plural` library.
459
- // But `make-plural` library itself is relatively big in size:
460
- // `make-plural.min.js` is about 6 kilobytes (https://unpkg.com/make-plural/).
461
- // So, it's more practical to bypass runtime `make-plural` pluralization rules compilation
462
- // and just include the already compiled pluarlization rules for all locales in the library code.
463
- var $ = {
464
- af: function af(n) {
465
- return n == 1 ? 'one' : 'other';
466
- },
467
- am: function am(n) {
468
- return n >= 0 && n <= 1 ? 'one' : 'other';
469
- },
470
- ar: function ar(n) {
471
- var s = String(n).split('.'),
472
- t0 = Number(s[0]) == n,
473
- n100 = t0 && s[0].slice(-2);
474
- return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n100 >= 3 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 99 ? 'many' : 'other';
475
- },
476
- ast: function ast(n) {
477
- var s = String(n).split('.'),
478
- v0 = !s[1];
479
- return n == 1 && v0 ? 'one' : 'other';
480
- },
481
- be: function be(n) {
482
- var s = String(n).split('.'),
483
- t0 = Number(s[0]) == n,
484
- n10 = t0 && s[0].slice(-1),
485
- n100 = t0 && s[0].slice(-2);
486
- return n10 == 1 && n100 != 11 ? 'one' : n10 >= 2 && n10 <= 4 && (n100 < 12 || n100 > 14) ? 'few' : t0 && n10 == 0 || n10 >= 5 && n10 <= 9 || n100 >= 11 && n100 <= 14 ? 'many' : 'other';
487
- },
488
- br: function br(n) {
489
- var s = String(n).split('.'),
490
- t0 = Number(s[0]) == n,
491
- n10 = t0 && s[0].slice(-1),
492
- n100 = t0 && s[0].slice(-2),
493
- n1000000 = t0 && s[0].slice(-6);
494
- return n10 == 1 && n100 != 11 && n100 != 71 && n100 != 91 ? 'one' : n10 == 2 && n100 != 12 && n100 != 72 && n100 != 92 ? 'two' : (n10 == 3 || n10 == 4 || n10 == 9) && (n100 < 10 || n100 > 19) && (n100 < 70 || n100 > 79) && (n100 < 90 || n100 > 99) ? 'few' : n != 0 && t0 && n1000000 == 0 ? 'many' : 'other';
495
- },
496
- bs: function bs(n) {
497
- var s = String(n).split('.'),
498
- i = s[0],
499
- f = s[1] || '',
500
- v0 = !s[1],
501
- i10 = i.slice(-1),
502
- i100 = i.slice(-2),
503
- f10 = f.slice(-1),
504
- f100 = f.slice(-2);
505
- return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other';
506
- },
507
- ca: function ca(n) {
508
- var s = String(n).split('.'),
509
- i = s[0],
510
- v0 = !s[1],
511
- i1000000 = i.slice(-6);
512
- return n == 1 && v0 ? 'one' : i != 0 && i1000000 == 0 && v0 ? 'many' : 'other';
513
- },
514
- ceb: function ceb(n) {
515
- var s = String(n).split('.'),
516
- i = s[0],
517
- f = s[1] || '',
518
- v0 = !s[1],
519
- i10 = i.slice(-1),
520
- f10 = f.slice(-1);
521
- return v0 && (i == 1 || i == 2 || i == 3) || v0 && i10 != 4 && i10 != 6 && i10 != 9 || !v0 && f10 != 4 && f10 != 6 && f10 != 9 ? 'one' : 'other';
522
- },
523
- cs: function cs(n) {
524
- var s = String(n).split('.'),
525
- i = s[0],
526
- v0 = !s[1];
527
- return n == 1 && v0 ? 'one' : i >= 2 && i <= 4 && v0 ? 'few' : !v0 ? 'many' : 'other';
528
- },
529
- cy: function cy(n) {
530
- return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n == 3 ? 'few' : n == 6 ? 'many' : 'other';
531
- },
532
- da: function da(n) {
533
- var s = String(n).split('.'),
534
- i = s[0],
535
- t0 = Number(s[0]) == n;
536
- return n == 1 || !t0 && (i == 0 || i == 1) ? 'one' : 'other';
537
- },
538
- dsb: function dsb(n) {
539
- var s = String(n).split('.'),
540
- i = s[0],
541
- f = s[1] || '',
542
- v0 = !s[1],
543
- i100 = i.slice(-2),
544
- f100 = f.slice(-2);
545
- return v0 && i100 == 1 || f100 == 1 ? 'one' : v0 && i100 == 2 || f100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || f100 == 3 || f100 == 4 ? 'few' : 'other';
546
- },
547
- dz: function dz(n) {
548
- return 'other';
549
- },
550
- es: function es(n) {
551
- var s = String(n).split('.'),
552
- i = s[0],
553
- v0 = !s[1],
554
- i1000000 = i.slice(-6);
555
- return n == 1 ? 'one' : i != 0 && i1000000 == 0 && v0 ? 'many' : 'other';
556
- },
557
- ff: function ff(n) {
558
- return n >= 0 && n < 2 ? 'one' : 'other';
559
- },
560
- fr: function fr(n) {
561
- var s = String(n).split('.'),
562
- i = s[0],
563
- v0 = !s[1],
564
- i1000000 = i.slice(-6);
565
- return n >= 0 && n < 2 ? 'one' : i != 0 && i1000000 == 0 && v0 ? 'many' : 'other';
566
- },
567
- ga: function ga(n) {
568
- var s = String(n).split('.'),
569
- t0 = Number(s[0]) == n;
570
- return n == 1 ? 'one' : n == 2 ? 'two' : t0 && n >= 3 && n <= 6 ? 'few' : t0 && n >= 7 && n <= 10 ? 'many' : 'other';
571
- },
572
- gd: function gd(n) {
573
- var s = String(n).split('.'),
574
- t0 = Number(s[0]) == n;
575
- return n == 1 || n == 11 ? 'one' : n == 2 || n == 12 ? 'two' : t0 && n >= 3 && n <= 10 || t0 && n >= 13 && n <= 19 ? 'few' : 'other';
576
- },
577
- he: function he(n) {
578
- var s = String(n).split('.'),
579
- i = s[0],
580
- v0 = !s[1];
581
- return i == 1 && v0 || i == 0 && !v0 ? 'one' : i == 2 && v0 ? 'two' : 'other';
582
- },
583
- is: function is(n) {
584
- var s = String(n).split('.'),
585
- i = s[0],
586
- t = (s[1] || '').replace(/0+$/, ''),
587
- t0 = Number(s[0]) == n,
588
- i10 = i.slice(-1),
589
- i100 = i.slice(-2);
590
- return t0 && i10 == 1 && i100 != 11 || t % 10 == 1 && t % 100 != 11 ? 'one' : 'other';
591
- },
592
- ksh: function ksh(n) {
593
- return n == 0 ? 'zero' : n == 1 ? 'one' : 'other';
594
- },
595
- lt: function lt(n) {
596
- var s = String(n).split('.'),
597
- f = s[1] || '',
598
- t0 = Number(s[0]) == n,
599
- n10 = t0 && s[0].slice(-1),
600
- n100 = t0 && s[0].slice(-2);
601
- return n10 == 1 && (n100 < 11 || n100 > 19) ? 'one' : n10 >= 2 && n10 <= 9 && (n100 < 11 || n100 > 19) ? 'few' : f != 0 ? 'many' : 'other';
602
- },
603
- lv: function lv(n) {
604
- var s = String(n).split('.'),
605
- f = s[1] || '',
606
- v = f.length,
607
- t0 = Number(s[0]) == n,
608
- n10 = t0 && s[0].slice(-1),
609
- n100 = t0 && s[0].slice(-2),
610
- f100 = f.slice(-2),
611
- f10 = f.slice(-1);
612
- return t0 && n10 == 0 || n100 >= 11 && n100 <= 19 || v == 2 && f100 >= 11 && f100 <= 19 ? 'zero' : n10 == 1 && n100 != 11 || v == 2 && f10 == 1 && f100 != 11 || v != 2 && f10 == 1 ? 'one' : 'other';
613
- },
614
- mk: function mk(n) {
615
- var s = String(n).split('.'),
616
- i = s[0],
617
- f = s[1] || '',
618
- v0 = !s[1],
619
- i10 = i.slice(-1),
620
- i100 = i.slice(-2),
621
- f10 = f.slice(-1),
622
- f100 = f.slice(-2);
623
- return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : 'other';
624
- },
625
- mt: function mt(n) {
626
- var s = String(n).split('.'),
627
- t0 = Number(s[0]) == n,
628
- n100 = t0 && s[0].slice(-2);
629
- return n == 1 ? 'one' : n == 2 ? 'two' : n == 0 || n100 >= 3 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 19 ? 'many' : 'other';
630
- },
631
- pa: function pa(n) {
632
- return n == 0 || n == 1 ? 'one' : 'other';
633
- },
634
- pl: function pl(n) {
635
- var s = String(n).split('.'),
636
- i = s[0],
637
- v0 = !s[1],
638
- i10 = i.slice(-1),
639
- i100 = i.slice(-2);
640
- return n == 1 && v0 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i != 1 && (i10 == 0 || i10 == 1) || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 12 && i100 <= 14 ? 'many' : 'other';
641
- },
642
- pt: function pt(n) {
643
- var s = String(n).split('.'),
644
- i = s[0],
645
- v0 = !s[1],
646
- i1000000 = i.slice(-6);
647
- return i == 0 || i == 1 ? 'one' : i != 0 && i1000000 == 0 && v0 ? 'many' : 'other';
648
- },
649
- ro: function ro(n) {
650
- var s = String(n).split('.'),
651
- v0 = !s[1],
652
- t0 = Number(s[0]) == n,
653
- n100 = t0 && s[0].slice(-2);
654
- return n == 1 && v0 ? 'one' : !v0 || n == 0 || n != 1 && n100 >= 1 && n100 <= 19 ? 'few' : 'other';
655
- },
656
- ru: function ru(n) {
657
- var s = String(n).split('.'),
658
- i = s[0],
659
- v0 = !s[1],
660
- i10 = i.slice(-1),
661
- i100 = i.slice(-2);
662
- return v0 && i10 == 1 && i100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i10 == 0 || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 11 && i100 <= 14 ? 'many' : 'other';
663
- },
664
- se: function se(n) {
665
- return n == 1 ? 'one' : n == 2 ? 'two' : 'other';
666
- },
667
- si: function si(n) {
668
- var s = String(n).split('.'),
669
- i = s[0],
670
- f = s[1] || '';
671
- return n == 0 || n == 1 || i == 0 && f == 1 ? 'one' : 'other';
672
- },
673
- sl: function sl(n) {
674
- var s = String(n).split('.'),
675
- i = s[0],
676
- v0 = !s[1],
677
- i100 = i.slice(-2);
678
- return v0 && i100 == 1 ? 'one' : v0 && i100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || !v0 ? 'few' : 'other';
679
- }
680
- };
681
- $.as = $.am;
682
- $.az = $.af;
683
- $.bg = $.af;
684
- $.bn = $.am;
685
- $.brx = $.af;
686
- $.ce = $.af;
687
- $.chr = $.af;
688
- $.de = $.ast;
689
- $.ee = $.af;
690
- $.el = $.af;
691
- $.en = $.ast;
692
- $.et = $.ast;
693
- $.eu = $.af;
694
- $.fa = $.am;
695
- $.fi = $.ast;
696
- $.fil = $.ceb;
697
- $.fo = $.af;
698
- $.fur = $.af;
699
- $.fy = $.ast;
700
- $.gl = $.ast;
701
- $.gu = $.am;
702
- $.ha = $.af;
703
- $.hi = $.am;
704
- $.hr = $.bs;
705
- $.hsb = $.dsb;
706
- $.hu = $.af;
707
- $.hy = $.ff;
708
- $.ia = $.ast;
709
- $.id = $.dz;
710
- $.ig = $.dz;
711
- $.it = $.ca;
712
- $.ja = $.dz;
713
- $.jgo = $.af;
714
- $.jv = $.dz;
715
- $.ka = $.af;
716
- $.kea = $.dz;
717
- $.kk = $.af;
718
- $.kl = $.af;
719
- $.km = $.dz;
720
- $.kn = $.am;
721
- $.ko = $.dz;
722
- $.ks = $.af;
723
- $.ku = $.af;
724
- $.ky = $.af;
725
- $.lb = $.af;
726
- $.lkt = $.dz;
727
- $.lo = $.dz;
728
- $.ml = $.af;
729
- $.mn = $.af;
730
- $.mr = $.af;
731
- $.ms = $.dz;
732
- $.my = $.dz;
733
- $.nb = $.af;
734
- $.ne = $.af;
735
- $.nl = $.ast;
736
- $.nn = $.af;
737
- $.no = $.af;
738
- $.or = $.af;
739
- $.pcm = $.am;
740
- $.ps = $.af;
741
- $.rm = $.af;
742
- $.sah = $.dz;
743
- $.sc = $.ast;
744
- $.sd = $.af;
745
- $.sk = $.cs;
746
- $.so = $.af;
747
- $.sq = $.af;
748
- $.sr = $.bs;
749
- $.su = $.dz;
750
- $.sv = $.ast;
751
- $.sw = $.ast;
752
- $.ta = $.af;
753
- $.te = $.af;
754
- $.th = $.dz;
755
- $.ti = $.pa;
756
- $.tk = $.af;
757
- $.to = $.dz;
758
- $.tr = $.af;
759
- $.ug = $.af;
760
- $.uk = $.ru;
761
- $.ur = $.ast;
762
- $.uz = $.af;
763
- $.vi = $.dz;
764
- $.wae = $.af;
765
- $.wo = $.dz;
766
- $.xh = $.af;
767
- $.yi = $.ast;
768
- $.yo = $.dz;
769
- $.yue = $.dz;
770
- $.zh = $.dz;
771
- $.zu = $.am;
772
- var PluralRuleFunctions = $;
773
-
774
- /**
775
- * Returns a `locale` for which a function exists in `./PluralRuleFunctions.js`.
776
- * @param {string} locale
777
- * @return {string}
778
- * @example
779
- * getPluralRulesLocale("ru-RU-Cyrl") // Returns "ru".
780
- */
781
- function getPluralRulesLocale(locale) {
782
- // "pt" language is the only one having different pluralization rules
783
- // for the one ("pt") (Portuguese) locale and the other ("pt-PT") (European Portuguese).
784
- // http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
785
- // (see the entries for "pt" and "pt_PT" there)
786
- if (locale === 'pt-PT') {
787
- return locale;
788
- }
789
-
790
- return getLanguageFromLanguageTag(locale);
791
- }
792
- /**
793
- * Extracts language from an IETF BCP 47 language tag.
794
- * @param {string} languageTag - IETF BCP 47 language tag.
795
- * @return {string}
796
- * @example
797
- * // Returns "he"
798
- * getLanguageFromLanguageTag("he-IL-u-ca-hebrew-tz-jeruslm")
799
- * // Returns "ar"
800
- * getLanguageFromLanguageTag("ar-u-nu-latn")
801
- */
802
-
803
- var LANGUAGE_REG_EXP = /^([a-z0-9]+)/i;
804
-
805
- function getLanguageFromLanguageTag(languageTag) {
806
- var match = languageTag.match(LANGUAGE_REG_EXP);
807
-
808
- if (!match) {
809
- throw new TypeError("Invalid locale: ".concat(languageTag));
810
- }
811
-
812
- return match[1];
813
- }
814
-
815
- function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
816
-
817
- function _defineProperties$3(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
818
-
819
- function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
820
- /**
821
- * `Intl.PluralRules` polyfill.
822
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/PluralRules
823
- */
824
-
825
- var PluralRules = /*#__PURE__*/function () {
826
- function PluralRules(locale, options) {
827
- _classCallCheck$3(this, PluralRules);
828
-
829
- var locales = PluralRules.supportedLocalesOf(locale);
830
-
831
- if (locales.length === 0) {
832
- throw new RangeError("Unsupported locale: " + locale);
833
- }
834
-
835
- if (options && options.type !== "cardinal") {
836
- throw new RangeError("Only \"cardinal\" \"type\" is supported");
837
- }
838
-
839
- this.$ = PluralRuleFunctions[getPluralRulesLocale(locales[0])];
840
- }
841
-
842
- _createClass$3(PluralRules, [{
843
- key: "select",
844
- value: function select(number) {
845
- return this.$(number);
846
- }
847
- }], [{
848
- key: "supportedLocalesOf",
849
- value: function supportedLocalesOf(locales) {
850
- if (typeof locales === "string") {
851
- locales = [locales];
852
- }
853
-
854
- return locales.filter(function (locale) {
855
- return PluralRuleFunctions[getPluralRulesLocale(locale)];
856
- });
857
- }
858
- }]);
859
-
860
- return PluralRules;
861
- }();
862
-
863
- function _typeof$5(obj) { "@babel/helpers - typeof"; return _typeof$5 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$5(obj); }
864
-
865
- function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
866
-
867
- function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$9(Object(source), !0).forEach(function (key) { _defineProperty$9(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
868
-
869
- function _defineProperty$9(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
870
-
871
- function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest$1(); }
872
-
873
- function _nonIterableRest$1() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
874
-
875
- function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen); }
876
-
877
- function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
878
-
879
- function _iterableToArrayLimit$1(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
880
-
881
- function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; }
882
-
883
- function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
884
-
885
- function _defineProperties$2(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
886
-
887
- function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
888
- // results in a bundle that is larger by 1kB for some reason.
889
- // import PluralRules from 'intl-plural-rules-polyfill/cardinal'
890
- // Valid time units.
891
-
892
- var UNITS = ["second", "minute", "hour", "day", "week", "month", "quarter", "year"]; // Valid values for the `numeric` option.
893
-
894
- var NUMERIC_VALUES = ["auto", "always"]; // Valid values for the `style` option.
895
-
896
- var STYLE_VALUES = ["long", "short", "narrow"]; // Valid values for the `localeMatcher` option.
897
-
898
- var LOCALE_MATCHER_VALUES = ["lookup", "best fit"];
899
- /**
900
- * Polyfill for `Intl.RelativeTimeFormat` proposal.
901
- * https://github.com/tc39/proposal-intl-relative-time
902
- * https://github.com/tc39/proposal-intl-relative-time/issues/55
903
- */
904
-
905
- var RelativeTimeFormat = /*#__PURE__*/function () {
906
- /**
907
- * @param {(string|string[])} [locales] - Preferred locales (or locale).
908
- * @param {Object} [options] - Formatting options.
909
- * @param {string} [options.style="long"] - One of: "long", "short", "narrow".
910
- * @param {string} [options.numeric="always"] - (Version >= 2) One of: "always", "auto".
911
- * @param {string} [options.localeMatcher="lookup"] - One of: "lookup", "best fit". Currently only "lookup" is supported.
912
- */
913
- function RelativeTimeFormat() {
914
- var locales = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
915
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
916
-
917
- _classCallCheck$2(this, RelativeTimeFormat);
918
-
919
- var numeric = options.numeric,
920
- style = options.style,
921
- localeMatcher = options.localeMatcher;
922
- this.numeric = "always";
923
- this.style = "long";
924
- this.localeMatcher = "lookup"; // Set `numeric` option.
925
-
926
- if (numeric !== undefined) {
927
- if (NUMERIC_VALUES.indexOf(numeric) < 0) {
928
- throw new RangeError("Invalid \"numeric\" option: ".concat(numeric));
929
- }
930
-
931
- this.numeric = numeric;
932
- } // Set `style` option.
933
-
934
-
935
- if (style !== undefined) {
936
- if (STYLE_VALUES.indexOf(style) < 0) {
937
- throw new RangeError("Invalid \"style\" option: ".concat(style));
938
- }
939
-
940
- this.style = style;
941
- } // Set `localeMatcher` option.
942
-
943
-
944
- if (localeMatcher !== undefined) {
945
- if (LOCALE_MATCHER_VALUES.indexOf(localeMatcher) < 0) {
946
- throw new RangeError("Invalid \"localeMatcher\" option: ".concat(localeMatcher));
947
- }
948
-
949
- this.localeMatcher = localeMatcher;
950
- } // Set `locale`.
951
- // Convert `locales` to an array.
952
-
953
-
954
- if (typeof locales === 'string') {
955
- locales = [locales];
956
- } // Add default locale.
957
-
958
-
959
- locales.push(getDefaultLocale()); // Choose the most appropriate locale.
960
-
961
- this.locale = RelativeTimeFormat.supportedLocalesOf(locales, {
962
- localeMatcher: this.localeMatcher
963
- })[0];
964
-
965
- if (!this.locale) {
966
- throw new Error("No supported locale was found");
967
- } // Construct an `Intl.PluralRules` instance (polyfill).
968
-
969
-
970
- if (PluralRules.supportedLocalesOf(this.locale).length > 0) {
971
- this.pluralRules = new PluralRules(this.locale);
972
- } else {
973
- console.warn("\"".concat(this.locale, "\" locale is not supported"));
974
- } // Use `Intl.NumberFormat` for formatting numbers (when available).
975
-
976
-
977
- if (typeof Intl !== 'undefined' && Intl.NumberFormat) {
978
- this.numberFormat = new Intl.NumberFormat(this.locale);
979
- this.numberingSystem = this.numberFormat.resolvedOptions().numberingSystem;
980
- } else {
981
- this.numberingSystem = 'latn';
982
- }
983
-
984
- this.locale = resolveLocale(this.locale, {
985
- localeMatcher: this.localeMatcher
986
- });
987
- }
988
- /**
989
- * Formats time `number` in `units` (either in past or in future).
990
- * @param {number} number - Time interval value.
991
- * @param {string} unit - Time interval measurement unit.
992
- * @return {string}
993
- * @throws {RangeError} If unit is not one of "second", "minute", "hour", "day", "week", "month", "quarter".
994
- * @example
995
- * // Returns "2 days ago"
996
- * rtf.format(-2, "day")
997
- * // Returns "in 5 minutes"
998
- * rtf.format(5, "minute")
999
- */
1000
-
1001
-
1002
- _createClass$2(RelativeTimeFormat, [{
1003
- key: "format",
1004
- value: function format() {
1005
- var _parseFormatArgs = parseFormatArgs(arguments),
1006
- _parseFormatArgs2 = _slicedToArray$1(_parseFormatArgs, 2),
1007
- number = _parseFormatArgs2[0],
1008
- unit = _parseFormatArgs2[1];
1009
-
1010
- return this.getRule(number, unit).replace('{0}', this.formatNumber(Math.abs(number)));
1011
- }
1012
- /**
1013
- * Formats time `number` in `units` (either in past or in future).
1014
- * @param {number} number - Time interval value.
1015
- * @param {string} unit - Time interval measurement unit.
1016
- * @return {Object[]} The parts (`{ type, value, unit? }`).
1017
- * @throws {RangeError} If unit is not one of "second", "minute", "hour", "day", "week", "month", "quarter".
1018
- * @example
1019
- * // Version 1 (deprecated).
1020
- * // Returns [
1021
- * // { type: "literal", value: "in " },
1022
- * // { type: "day", value: "100" },
1023
- * // { type: "literal", value: " days" }
1024
- * // ]
1025
- * rtf.formatToParts(100, "day")
1026
- * //
1027
- * // Version 2.
1028
- * // Returns [
1029
- * // { type: "literal", value: "in " },
1030
- * // { type: "integer", value: "100", unit: "day" },
1031
- * // { type: "literal", value: " days" }
1032
- * // ]
1033
- * rtf.formatToParts(100, "day")
1034
- */
1035
-
1036
- }, {
1037
- key: "formatToParts",
1038
- value: function formatToParts() {
1039
- var _parseFormatArgs3 = parseFormatArgs(arguments),
1040
- _parseFormatArgs4 = _slicedToArray$1(_parseFormatArgs3, 2),
1041
- number = _parseFormatArgs4[0],
1042
- unit = _parseFormatArgs4[1];
1043
-
1044
- var rule = this.getRule(number, unit);
1045
- var valueIndex = rule.indexOf("{0}"); // "yesterday"/"today"/"tomorrow".
1046
-
1047
- if (valueIndex < 0) {
1048
- return [{
1049
- type: "literal",
1050
- value: rule
1051
- }];
1052
- }
1053
-
1054
- var parts = [];
1055
-
1056
- if (valueIndex > 0) {
1057
- parts.push({
1058
- type: "literal",
1059
- value: rule.slice(0, valueIndex)
1060
- });
1061
- }
1062
-
1063
- parts = parts.concat(this.formatNumberToParts(Math.abs(number)).map(function (part) {
1064
- return _objectSpread$9(_objectSpread$9({}, part), {}, {
1065
- unit: unit
1066
- });
1067
- }));
1068
-
1069
- if (valueIndex + "{0}".length < rule.length - 1) {
1070
- parts.push({
1071
- type: "literal",
1072
- value: rule.slice(valueIndex + "{0}".length)
1073
- });
1074
- }
1075
-
1076
- return parts;
1077
- }
1078
- /**
1079
- * Returns formatting rule for `value` in `units` (either in past or in future).
1080
- * @param {number} value - Time interval value.
1081
- * @param {string} unit - Time interval measurement unit.
1082
- * @return {string}
1083
- * @throws {RangeError} If unit is not one of "second", "minute", "hour", "day", "week", "month", "quarter".
1084
- * @example
1085
- * // Returns "{0} days ago"
1086
- * getRule(-2, "day")
1087
- */
1088
-
1089
- }, {
1090
- key: "getRule",
1091
- value: function getRule(value, unit) {
1092
- // Get locale-specific time interval formatting rules
1093
- // of a given `style` for the given value of measurement `unit`.
1094
- //
1095
- // E.g.:
1096
- //
1097
- // ```json
1098
- // {
1099
- // "past": {
1100
- // "one": "a second ago",
1101
- // "other": "{0} seconds ago"
1102
- // },
1103
- // "future": {
1104
- // "one": "in a second",
1105
- // "other": "in {0} seconds"
1106
- // }
1107
- // }
1108
- // ```
1109
- //
1110
- var unitMessages = getLocaleData$1(this.locale)[this.style][unit]; // Bundle size optimization technique for styles like
1111
- // "tiny" in `javascript-time-ago`: "1m", "2h", "3d"...
1112
-
1113
- if (typeof unitMessages === 'string') {
1114
- return unitMessages;
1115
- } // Special case for "yesterday"/"today"/"tomorrow".
1116
-
1117
-
1118
- if (this.numeric === "auto") {
1119
- // "yesterday", "the day before yesterday", etc.
1120
- if (value === -2 || value === -1) {
1121
- var message = unitMessages["previous".concat(value === -1 ? '' : '-' + Math.abs(value))];
1122
-
1123
- if (message) {
1124
- return message;
1125
- }
1126
- } // "tomorrow", "the day after tomorrow", etc.
1127
- else if (value === 1 || value === 2) {
1128
- var _message = unitMessages["next".concat(value === 1 ? '' : '-' + Math.abs(value))];
1129
-
1130
- if (_message) {
1131
- return _message;
1132
- }
1133
- } // "today"
1134
- else if (value === 0) {
1135
- if (unitMessages.current) {
1136
- return unitMessages.current;
1137
- }
1138
- }
1139
- } // Choose either "past" or "future" based on time `value` sign.
1140
- // If there's only "other" then it's being collapsed.
1141
- // (the resulting bundle size optimization technique)
1142
-
1143
-
1144
- var pluralizedMessages = unitMessages[isNegative(value) ? "past" : "future"]; // Bundle size optimization technique for styles like "narrow"
1145
- // having messages like "in {0} d." or "{0} d. ago".
1146
-
1147
- if (typeof pluralizedMessages === "string") {
1148
- return pluralizedMessages;
1149
- } // Quantify `value`.
1150
- // There seems to be no such locale in CLDR
1151
- // for which "plural rules" function is missing.
1152
-
1153
-
1154
- var quantifier = this.pluralRules && this.pluralRules.select(Math.abs(value)) || 'other'; // "other" rule is supposed to be always present.
1155
- // If only "other" rule is present then "rules" is not an object and is a string.
1156
-
1157
- return pluralizedMessages[quantifier] || pluralizedMessages.other;
1158
- }
1159
- /**
1160
- * Formats a number into a string.
1161
- * Uses `Intl.NumberFormat` when available.
1162
- * @param {number} number
1163
- * @return {string}
1164
- */
1165
-
1166
- }, {
1167
- key: "formatNumber",
1168
- value: function formatNumber(number) {
1169
- return this.numberFormat ? this.numberFormat.format(number) : String(number);
1170
- }
1171
- /**
1172
- * Formats a number into a list of parts.
1173
- * Uses `Intl.NumberFormat` when available.
1174
- * @param {number} number
1175
- * @return {object[]}
1176
- */
1177
-
1178
- }, {
1179
- key: "formatNumberToParts",
1180
- value: function formatNumberToParts(number) {
1181
- // `Intl.NumberFormat.formatToParts()` is not present, for example,
1182
- // in Node.js 8.x while `Intl.NumberFormat` itself is present.
1183
- return this.numberFormat && this.numberFormat.formatToParts ? this.numberFormat.formatToParts(number) : [{
1184
- type: "integer",
1185
- value: this.formatNumber(number)
1186
- }];
1187
- }
1188
- /**
1189
- * Returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this DateTimeFormat object.
1190
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
1191
- * @return {Object}
1192
- */
1193
-
1194
- }, {
1195
- key: "resolvedOptions",
1196
- value: function resolvedOptions() {
1197
- return {
1198
- locale: this.locale,
1199
- style: this.style,
1200
- numeric: this.numeric,
1201
- numberingSystem: this.numberingSystem
1202
- };
1203
- }
1204
- }]);
1205
-
1206
- return RelativeTimeFormat;
1207
- }();
1208
-
1209
- RelativeTimeFormat.supportedLocalesOf = function (locales) {
1210
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1211
-
1212
- // Convert `locales` to an array.
1213
- if (typeof locales === 'string') {
1214
- locales = [locales];
1215
- } else if (!Array.isArray(locales)) {
1216
- throw new TypeError('Invalid "locales" argument');
1217
- }
1218
-
1219
- return locales.filter(function (locale) {
1220
- return resolveLocale(locale, options);
1221
- });
1222
- };
1223
- /**
1224
- * Adds locale data for a specific locale.
1225
- * @param {Object} localeData
1226
- */
1227
-
1228
-
1229
- RelativeTimeFormat.addLocale = addLocaleData$1;
1230
- /**
1231
- * Sets default locale.
1232
- * @param {string} locale
1233
- */
1234
-
1235
- RelativeTimeFormat.setDefaultLocale = setDefaultLocale;
1236
- /**
1237
- * Gets default locale.
1238
- * @return {string} locale
1239
- */
1240
-
1241
- RelativeTimeFormat.getDefaultLocale = getDefaultLocale;
1242
- /**
1243
- * Export `Intl.PluralRules` just in case it's used somewhere else.
1244
- */
1245
-
1246
- RelativeTimeFormat.PluralRules = PluralRules; // The specification allows units to be in plural form.
1247
- // Convert plural to singular.
1248
- // Example: "seconds" -> "second".
1249
-
1250
- var UNIT_ERROR = 'Invalid "unit" argument';
1251
-
1252
- function parseUnit(unit) {
1253
- if (_typeof$5(unit) === 'symbol') {
1254
- throw new TypeError(UNIT_ERROR);
1255
- }
1256
-
1257
- if (typeof unit !== 'string') {
1258
- throw new RangeError("".concat(UNIT_ERROR, ": ").concat(unit));
1259
- }
1260
-
1261
- if (unit[unit.length - 1] === 's') {
1262
- unit = unit.slice(0, unit.length - 1);
1263
- }
1264
-
1265
- if (UNITS.indexOf(unit) < 0) {
1266
- throw new RangeError("".concat(UNIT_ERROR, ": ").concat(unit));
1267
- }
1268
-
1269
- return unit;
1270
- } // Converts `value` to a `Number`.
1271
- // The specification allows value to be a non-number.
1272
- // For example, "-0" is supposed to be treated as `-0`.
1273
- // Also checks if `value` is a finite number.
1274
-
1275
-
1276
- var NUMBER_ERROR = 'Invalid "number" argument';
1277
-
1278
- function parseNumber(value) {
1279
- value = Number(value);
1280
-
1281
- if (Number.isFinite) {
1282
- if (!Number.isFinite(value)) {
1283
- throw new RangeError("".concat(NUMBER_ERROR, ": ").concat(value));
1284
- }
1285
- }
1286
-
1287
- return value;
1288
- }
1289
- /**
1290
- * Tells `0` from `-0`.
1291
- * https://stackoverflow.com/questions/7223359/are-0-and-0-the-same
1292
- * @param {number} number
1293
- * @return {Boolean}
1294
- * @example
1295
- * isNegativeZero(0); // false
1296
- * isNegativeZero(-0); // true
1297
- */
1298
-
1299
-
1300
- function isNegativeZero(number) {
1301
- return 1 / number === -Infinity;
1302
- }
1303
-
1304
- function isNegative(number) {
1305
- return number < 0 || number === 0 && isNegativeZero(number);
1306
- }
1307
-
1308
- function parseFormatArgs(args) {
1309
- if (args.length < 2) {
1310
- throw new TypeError("\"unit\" argument is required");
1311
- }
1312
-
1313
- return [parseNumber(args[0]), parseUnit(args[1])];
1314
- }
1315
-
1316
- function _typeof$4(obj) { "@babel/helpers - typeof"; return _typeof$4 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$4(obj); }
1317
-
1318
- function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1319
-
1320
- function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
1321
-
1322
- function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1323
-
1324
- /**
1325
- * A basic in-memory cache.
1326
- *
1327
- * import Cache from 'javascript-time-ago/Cache'
1328
- * const cache = new Cache()
1329
- * const object = cache.get('key1', 'key2', ...) || cache.put('key1', 'key2', ..., createObject())
1330
- */
1331
- var Cache = /*#__PURE__*/function () {
1332
- function Cache() {
1333
- _classCallCheck$1(this, Cache);
1334
-
1335
- this.cache = {};
1336
- }
1337
-
1338
- _createClass$1(Cache, [{
1339
- key: "get",
1340
- value: function get() {
1341
- var cache = this.cache;
1342
-
1343
- for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
1344
- keys[_key] = arguments[_key];
1345
- }
1346
-
1347
- for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
1348
- var key = _keys[_i];
1349
-
1350
- if (_typeof$4(cache) !== 'object') {
1351
- return;
1352
- }
1353
-
1354
- cache = cache[key];
1355
- }
1356
-
1357
- return cache;
1358
- }
1359
- }, {
1360
- key: "put",
1361
- value: function put() {
1362
- for (var _len2 = arguments.length, keys = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
1363
- keys[_key2] = arguments[_key2];
1364
- }
1365
-
1366
- var value = keys.pop();
1367
- var lastKey = keys.pop();
1368
- var cache = this.cache;
1369
-
1370
- for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) {
1371
- var key = _keys2[_i2];
1372
-
1373
- if (_typeof$4(cache[key]) !== 'object') {
1374
- cache[key] = {};
1375
- }
1376
-
1377
- cache = cache[key];
1378
- }
1379
-
1380
- return cache[lastKey] = value;
1381
- }
1382
- }]);
1383
-
1384
- return Cache;
1385
- }();
1386
-
1387
- function _typeof$3(obj) { "@babel/helpers - typeof"; return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$3(obj); }
1388
-
1389
- function _createForOfIteratorHelperLoose$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1390
-
1391
- function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
1392
-
1393
- function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1394
-
1395
- /**
1396
- * Chooses the most appropriate locale
1397
- * (one of the registered ones)
1398
- * based on the list of preferred `locales` supplied by the user.
1399
- *
1400
- * @param {string[]} locales - the list of preferable locales (in [IETF format](https://en.wikipedia.org/wiki/IETF_language_tag)).
1401
- * @param {Function} isLocaleDataAvailable - tests if a locale is available.
1402
- *
1403
- * @returns {string} The most suitable locale.
1404
- *
1405
- * @example
1406
- * // Returns 'en'
1407
- * chooseLocale(['en-US'], undefined, (locale) => locale === 'ru' || locale === 'en')
1408
- */
1409
- function chooseLocale(locales, isLocaleDataAvailable) {
1410
- // This is not an intelligent algorithm,
1411
- // but it will do for this library's case.
1412
- // `sr-Cyrl-BA` -> `sr-Cyrl` -> `sr`.
1413
- for (var _iterator = _createForOfIteratorHelperLoose$1(locales), _step; !(_step = _iterator()).done;) {
1414
- var locale = _step.value;
1415
-
1416
- if (isLocaleDataAvailable(locale)) {
1417
- return locale;
1418
- }
1419
-
1420
- var parts = locale.split('-');
1421
-
1422
- while (parts.length > 1) {
1423
- parts.pop();
1424
- locale = parts.join('-');
1425
-
1426
- if (isLocaleDataAvailable(locale)) {
1427
- return locale;
1428
- }
1429
- }
1430
- }
1431
-
1432
- throw new Error("No locale data has been registered for any of the locales: ".concat(locales.join(', ')));
1433
- }
1434
- /**
1435
- * Whether can use `Intl.DateTimeFormat`.
1436
- * @return {boolean}
1437
- */
1438
-
1439
- function intlDateTimeFormatSupported() {
1440
- // Babel transforms `typeof` into some "branches"
1441
- // so istanbul will show this as "branch not covered".
1442
-
1443
- /* istanbul ignore next */
1444
- var isIntlAvailable = (typeof Intl === "undefined" ? "undefined" : _typeof$3(Intl)) === 'object';
1445
- return isIntlAvailable && typeof Intl.DateTimeFormat === 'function';
1446
- }
1447
-
1448
- function _typeof$2(obj) { "@babel/helpers - typeof"; return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$2(obj); }
1449
-
1450
- function isStyleObject(object) {
1451
- return isObject(object) && (Array.isArray(object.steps) || // `gradation` property is deprecated: it has been renamed to `steps`.
1452
- Array.isArray(object.gradation) || // `flavour` property is deprecated: it has been renamed to `labels`.
1453
- Array.isArray(object.flavour) || typeof object.flavour === 'string' || Array.isArray(object.labels) || typeof object.labels === 'string' || // `units` property is deprecated.
1454
- Array.isArray(object.units) || // `custom` property is deprecated.
1455
- typeof object.custom === 'function');
1456
- }
1457
- var OBJECT_CONSTRUCTOR = {}.constructor;
1458
-
1459
- function isObject(object) {
1460
- return _typeof$2(object) !== undefined && object !== null && object.constructor === OBJECT_CONSTRUCTOR;
1461
- }
1462
-
1463
- var minute = 60; // in seconds
1464
-
1465
- var hour = 60 * minute; // in seconds
1466
-
1467
- var day = 24 * hour; // in seconds
1468
-
1469
- var week = 7 * day; // in seconds
1470
- // https://www.quora.com/What-is-the-average-number-of-days-in-a-month
1471
-
1472
- var month = 30.44 * day; // in seconds
1473
- // "400 years have 146097 days (taking into account leap year rules)"
1474
-
1475
- var year = 146097 / 400 * day; // in seconds
1476
-
1477
- function getSecondsInUnit(unit) {
1478
- switch (unit) {
1479
- case 'second':
1480
- return 1;
1481
-
1482
- case 'minute':
1483
- return minute;
1484
-
1485
- case 'hour':
1486
- return hour;
1487
-
1488
- case 'day':
1489
- return day;
1490
-
1491
- case 'week':
1492
- return week;
1493
-
1494
- case 'month':
1495
- return month;
1496
-
1497
- case 'year':
1498
- return year;
1499
- }
1500
- } // export function getPreviousUnitFor(unit) {
1501
- // switch (unit) {
1502
- // case 'second':
1503
- // return 'now'
1504
- // case 'minute':
1505
- // return 'second'
1506
- // case 'hour':
1507
- // return 'minute'
1508
- // case 'day':
1509
- // return 'hour'
1510
- // case 'week':
1511
- // return 'day'
1512
- // case 'month':
1513
- // return 'week'
1514
- // case 'year':
1515
- // return 'month'
1516
- // }
1517
- // }
1518
-
1519
- function getStepDenominator(step) {
1520
- // `factor` is a legacy property.
1521
- if (step.factor !== undefined) {
1522
- return step.factor;
1523
- } // "unit" is now called "formatAs".
1524
-
1525
-
1526
- return getSecondsInUnit(step.unit || step.formatAs) || 1;
1527
- }
1528
-
1529
- function getRoundFunction(round) {
1530
- switch (round) {
1531
- case 'floor':
1532
- return Math.floor;
1533
-
1534
- default:
1535
- return Math.round;
1536
- }
1537
- } // For non-negative numbers.
1538
-
1539
- function getDiffRatioToNextRoundedNumber(round) {
1540
- switch (round) {
1541
- case 'floor':
1542
- // Math.floor(x) = x
1543
- // Math.floor(x + 1) = x + 1
1544
- return 1;
1545
-
1546
- default:
1547
- // Math.round(x) = x
1548
- // Math.round(x + 0.5) = x + 1
1549
- return 0.5;
1550
- }
1551
- }
1552
-
1553
- function _typeof$1(obj) { "@babel/helpers - typeof"; return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$1(obj); }
1554
- function getStepMinTime(step, _ref) {
1555
- var prevStep = _ref.prevStep,
1556
- timestamp = _ref.timestamp,
1557
- now = _ref.now,
1558
- future = _ref.future,
1559
- round = _ref.round;
1560
- var minTime; // "threshold_for_xxx" is a legacy property.
1561
-
1562
- if (prevStep) {
1563
- if (prevStep.id || prevStep.unit) {
1564
- minTime = step["threshold_for_".concat(prevStep.id || prevStep.unit)];
1565
- }
1566
- }
1567
-
1568
- if (minTime === undefined) {
1569
- // "threshold" is a legacy property.
1570
- if (step.threshold !== undefined) {
1571
- // "threshold" is a legacy name for "minTime".
1572
- minTime = step.threshold; // "threshold" function is deprecated.
1573
-
1574
- if (typeof minTime === 'function') {
1575
- minTime = minTime(now, future);
1576
- }
1577
- }
1578
- }
1579
-
1580
- if (minTime === undefined) {
1581
- minTime = step.minTime;
1582
- } // A deprecated way of specifying a different threshold
1583
- // depending on the previous step's unit.
1584
-
1585
-
1586
- if (_typeof$1(minTime) === 'object') {
1587
- if (prevStep && prevStep.id && minTime[prevStep.id] !== undefined) {
1588
- minTime = minTime[prevStep.id];
1589
- } else {
1590
- minTime = minTime["default"];
1591
- }
1592
- }
1593
-
1594
- if (typeof minTime === 'function') {
1595
- minTime = minTime(timestamp, {
1596
- future: future,
1597
- getMinTimeForUnit: function getMinTimeForUnit(toUnit, fromUnit) {
1598
- return _getMinTimeForUnit(toUnit, fromUnit || prevStep && prevStep.formatAs, {
1599
- round: round
1600
- });
1601
- }
1602
- });
1603
- } // Evaluate the `test()` function.
1604
- // `test()` function is deprecated.
1605
-
1606
-
1607
- if (minTime === undefined) {
1608
- if (step.test) {
1609
- if (step.test(timestamp, {
1610
- now: now,
1611
- future: future
1612
- })) {
1613
- // `0` threshold always passes.
1614
- minTime = 0;
1615
- } else {
1616
- // `MAX_SAFE_INTEGER` threshold won't ever pass in real life.
1617
- minTime = 9007199254740991; // Number.MAX_SAFE_INTEGER
1618
- }
1619
- }
1620
- }
1621
-
1622
- if (minTime === undefined) {
1623
- if (prevStep) {
1624
- if (step.formatAs && prevStep.formatAs) {
1625
- minTime = _getMinTimeForUnit(step.formatAs, prevStep.formatAs, {
1626
- round: round
1627
- });
1628
- }
1629
- } else {
1630
- // The first step's `minTime` is `0` by default.
1631
- minTime = 0;
1632
- }
1633
- } // Warn if no `minTime` was defined or could be deduced.
1634
-
1635
-
1636
- if (minTime === undefined) {
1637
- console.warn('[javascript-time-ago] A step should specify `minTime`:\n' + JSON.stringify(step, null, 2));
1638
- }
1639
-
1640
- return minTime;
1641
- }
1642
-
1643
- function _getMinTimeForUnit(toUnit, fromUnit, _ref2) {
1644
- var round = _ref2.round;
1645
- var toUnitAmount = getSecondsInUnit(toUnit); // if (!fromUnit) {
1646
- // return toUnitAmount;
1647
- // }
1648
- // if (!fromUnit) {
1649
- // fromUnit = getPreviousUnitFor(toUnit)
1650
- // }
1651
-
1652
- var fromUnitAmount;
1653
-
1654
- if (fromUnit === 'now') {
1655
- fromUnitAmount = getSecondsInUnit(toUnit);
1656
- } else {
1657
- fromUnitAmount = getSecondsInUnit(fromUnit);
1658
- }
1659
-
1660
- if (toUnitAmount !== undefined && fromUnitAmount !== undefined) {
1661
- return toUnitAmount - fromUnitAmount * (1 - getDiffRatioToNextRoundedNumber(round));
1662
- }
1663
- }
1664
-
1665
- function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1666
-
1667
- function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$8(Object(source), !0).forEach(function (key) { _defineProperty$8(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1668
-
1669
- function _defineProperty$8(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
1670
- /**
1671
- * Finds an appropriate `step` of `steps` for the time interval (in seconds).
1672
- *
1673
- * @param {Object[]} steps - Time formatting steps.
1674
- *
1675
- * @param {number} secondsPassed - Time interval (in seconds).
1676
- * `< 0` for past dates and `> 0` for future dates.
1677
- *
1678
- * @param {number} options.now - Current timestamp.
1679
- *
1680
- * @param {boolean} [options.future] - Whether the date should be formatted as a future one
1681
- * instead of a past one.
1682
- *
1683
- * @param {string} [options.round] - (undocumented) Rounding mechanism.
1684
- *
1685
- * @param {string[]} [options.units] - A list of allowed time units.
1686
- * (Example: ['second', 'minute', 'hour', …])
1687
- *
1688
- * @param {boolean} [options.getNextStep] - Pass true to return `[step, nextStep]` instead of just `step`.
1689
- *
1690
- * @return {Object|Object[]} [step] — Either a `step` or `[prevStep, step, nextStep]`.
1691
- */
1692
-
1693
- function getStep(steps, secondsPassed, _ref) {
1694
- var now = _ref.now,
1695
- future = _ref.future,
1696
- round = _ref.round,
1697
- units = _ref.units,
1698
- getNextStep = _ref.getNextStep;
1699
- // Ignore steps having not-supported time units in `formatAs`.
1700
- steps = filterStepsByUnits(steps, units);
1701
-
1702
- var step = _getStep(steps, secondsPassed, {
1703
- now: now,
1704
- future: future,
1705
- round: round
1706
- });
1707
-
1708
- if (getNextStep) {
1709
- if (step) {
1710
- var prevStep = steps[steps.indexOf(step) - 1];
1711
- var nextStep = steps[steps.indexOf(step) + 1];
1712
- return [prevStep, step, nextStep];
1713
- }
1714
-
1715
- return [undefined, undefined, steps[0]];
1716
- }
1717
-
1718
- return step;
1719
- }
1720
-
1721
- function _getStep(steps, secondsPassed, _ref2) {
1722
- var now = _ref2.now,
1723
- future = _ref2.future,
1724
- round = _ref2.round;
1725
-
1726
- // If no steps fit the conditions then return nothing.
1727
- if (steps.length === 0) {
1728
- return;
1729
- } // Find the most appropriate step.
1730
-
1731
-
1732
- var i = getStepIndex(steps, secondsPassed, {
1733
- now: now,
1734
- future: future || secondsPassed < 0,
1735
- round: round
1736
- }); // If no step is applicable the return nothing.
1737
-
1738
- if (i === -1) {
1739
- return;
1740
- }
1741
-
1742
- var step = steps[i]; // Apply granularity to the time amount
1743
- // (and fall back to the previous step
1744
- // if the first level of granularity
1745
- // isn't met by this amount)
1746
-
1747
- if (step.granularity) {
1748
- // Recalculate the amount of seconds passed based on `granularity`.
1749
- var secondsPassedGranular = getRoundFunction(round)(Math.abs(secondsPassed) / getStepDenominator(step) / step.granularity) * step.granularity; // If the granularity for this step is too high,
1750
- // then fall back to the previous step.
1751
- // (if there is any previous step)
1752
-
1753
- if (secondsPassedGranular === 0 && i > 0) {
1754
- return steps[i - 1];
1755
- }
1756
- }
1757
-
1758
- return step;
1759
- }
1760
- /**
1761
- * Iterates through steps until it finds the maximum one satisfying the `minTime` threshold.
1762
- * @param {Object} steps - Steps.
1763
- * @param {number} secondsPassed - How much seconds have passed since the date till `now`.
1764
- * @param {number} options.now - Current timestamp.
1765
- * @param {boolean} options.future - Whether the time interval should be formatted as a future one.
1766
- * @param {number} [i] - Gradation step currently being tested.
1767
- * @return {number} Gradation step index.
1768
- */
1769
-
1770
-
1771
- function getStepIndex(steps, secondsPassed, options) {
1772
- var i = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1773
- var minTime = getStepMinTime(steps[i], _objectSpread$8({
1774
- prevStep: steps[i - 1],
1775
- timestamp: options.now - secondsPassed * 1000
1776
- }, options)); // If `minTime` isn't defined or deduceable for this step, then stop.
1777
-
1778
- if (minTime === undefined) {
1779
- return i - 1;
1780
- } // If the `minTime` threshold for moving from previous step
1781
- // to this step is too high then return the previous step.
1782
-
1783
-
1784
- if (Math.abs(secondsPassed) < minTime) {
1785
- return i - 1;
1786
- } // If it's the last step then return it.
1787
-
1788
-
1789
- if (i === steps.length - 1) {
1790
- return i;
1791
- } // Move to the next step.
1792
-
1793
-
1794
- return getStepIndex(steps, secondsPassed, options, i + 1);
1795
- }
1796
- /**
1797
- * Leaves only allowed steps.
1798
- * @param {Object[]} steps
1799
- * @param {string[]} units - Allowed time units.
1800
- * @return {Object[]}
1801
- */
1802
-
1803
-
1804
- function filterStepsByUnits(steps, units) {
1805
- return steps.filter(function (_ref3) {
1806
- var unit = _ref3.unit,
1807
- formatAs = _ref3.formatAs;
1808
- // "unit" is now called "formatAs".
1809
- unit = unit || formatAs; // If this step has a `unit` defined
1810
- // then this `unit` must be in the list of allowed `units`.
1811
-
1812
- if (unit) {
1813
- return units.indexOf(unit) >= 0;
1814
- } // A step is not required to specify a `unit`:
1815
- // alternatively, it could specify `format()`.
1816
- // (see "twitter" style for an example)
1817
-
1818
-
1819
- return true;
1820
- });
1821
- }
1822
-
1823
- /**
1824
- * Gets the time to next update for a step with a time unit defined.
1825
- * @param {string} unit
1826
- * @param {number} date — The date passed to `.format()`, converted to a timestamp.
1827
- * @param {number} options.now
1828
- * @param {string} [options.round] — (undocumented) Rounding mechanism.
1829
- * @return {number} [timeToNextUpdate]
1830
- */
1831
-
1832
- function getTimeToNextUpdateForUnit(unit, timestamp, _ref) {
1833
- var now = _ref.now,
1834
- round = _ref.round;
1835
-
1836
- // For some units, like "now", there's no defined amount of seconds in them.
1837
- if (!getSecondsInUnit(unit)) {
1838
- // If there's no amount of seconds defined for this unit
1839
- // then the update interval can't be determined reliably.
1840
- return;
1841
- }
1842
-
1843
- var unitDenominator = getSecondsInUnit(unit) * 1000;
1844
- var future = timestamp > now;
1845
- var preciseAmount = Math.abs(timestamp - now);
1846
- var roundedAmount = getRoundFunction(round)(preciseAmount / unitDenominator) * unitDenominator;
1847
-
1848
- if (future) {
1849
- if (roundedAmount > 0) {
1850
- // Amount decreases with time.
1851
- return preciseAmount - roundedAmount + getDiffToPreviousRoundedNumber(round, unitDenominator);
1852
- } else {
1853
- // Refresh right after the zero point,
1854
- // when "future" changes to "past".
1855
- return preciseAmount - roundedAmount + 1;
1856
- }
1857
- } // Amount increases with time.
1858
-
1859
-
1860
- return -(preciseAmount - roundedAmount) + getDiffToNextRoundedNumber(round, unitDenominator);
1861
- }
1862
-
1863
- function getDiffToNextRoundedNumber(round, unitDenominator) {
1864
- return getDiffRatioToNextRoundedNumber(round) * unitDenominator;
1865
- }
1866
-
1867
- function getDiffToPreviousRoundedNumber(round, unitDenominator) {
1868
- return (1 - getDiffRatioToNextRoundedNumber(round)) * unitDenominator + 1;
1869
- }
1870
-
1871
- var YEAR = 365 * 24 * 60 * 60 * 1000;
1872
- var INFINITY = 1000 * YEAR;
1873
- /**
1874
- * Gets the time to next update for a date and a step.
1875
- * @param {number} date — The date passed to `.format()`, converted to a timestamp.
1876
- * @param {object} step
1877
- * @param {object} [options.previousStep]
1878
- * @param {object} [options.nextStep]
1879
- * @param {number} options.now
1880
- * @param {boolean} options.future
1881
- * @param {string} [options.round] - (undocumented) Rounding mechanism.
1882
- * @return {number} [timeToNextUpdate]
1883
- */
1884
-
1885
- function getTimeToNextUpdate(date, step, _ref) {
1886
- var prevStep = _ref.prevStep,
1887
- nextStep = _ref.nextStep,
1888
- now = _ref.now,
1889
- future = _ref.future,
1890
- round = _ref.round;
1891
- var timestamp = date.getTime ? date.getTime() : date;
1892
-
1893
- var getTimeToNextUpdateForUnit$1 = function getTimeToNextUpdateForUnit$1(unit) {
1894
- return getTimeToNextUpdateForUnit(unit, timestamp, {
1895
- now: now,
1896
- round: round
1897
- });
1898
- }; // For future dates, steps move from the last one to the first one,
1899
- // while for past dates, steps move from the first one to the last one,
1900
- // due to the fact that time flows in one direction,
1901
- // and future dates' interval naturally becomes smaller
1902
- // while past dates' interval naturally grows larger.
1903
- //
1904
- // For future dates, it's the transition
1905
- // from the current step to the previous step,
1906
- // therefore check the `minTime` of the current step.
1907
- //
1908
- // For past dates, it's the transition
1909
- // from the current step to the next step,
1910
- // therefore check the `minTime` of the next step.
1911
- //
1912
-
1913
-
1914
- var timeToStepChange = getTimeToStepChange(future ? step : nextStep, timestamp, {
1915
- future: future,
1916
- now: now,
1917
- round: round,
1918
- prevStep: future ? prevStep : step // isFirstStep: future && isFirstStep
1919
-
1920
- });
1921
-
1922
- if (timeToStepChange === undefined) {
1923
- // Can't reliably determine "time to next update"
1924
- // if not all of the steps provide `minTime`.
1925
- return;
1926
- }
1927
-
1928
- var timeToNextUpdate;
1929
-
1930
- if (step) {
1931
- if (step.getTimeToNextUpdate) {
1932
- timeToNextUpdate = step.getTimeToNextUpdate(timestamp, {
1933
- getTimeToNextUpdateForUnit: getTimeToNextUpdateForUnit$1,
1934
- getRoundFunction: getRoundFunction,
1935
- now: now,
1936
- future: future,
1937
- round: round
1938
- });
1939
- }
1940
-
1941
- if (timeToNextUpdate === undefined) {
1942
- // "unit" is now called "formatAs".
1943
- var unit = step.unit || step.formatAs;
1944
-
1945
- if (unit) {
1946
- // For some units, like "now", there's no defined amount of seconds in them.
1947
- // In such cases, `getTimeToNextUpdateForUnit()` returns `undefined`,
1948
- // and the next step's `minTime` could be used to calculate the update interval:
1949
- // it will just assume that the label never changes for this step.
1950
- timeToNextUpdate = getTimeToNextUpdateForUnit$1(unit);
1951
- }
1952
- }
1953
- }
1954
-
1955
- if (timeToNextUpdate === undefined) {
1956
- return timeToStepChange;
1957
- }
1958
-
1959
- return Math.min(timeToNextUpdate, timeToStepChange);
1960
- }
1961
- function getStepChangesAt(currentOrNextStep, timestamp, _ref2) {
1962
- var now = _ref2.now,
1963
- future = _ref2.future,
1964
- round = _ref2.round,
1965
- prevStep = _ref2.prevStep;
1966
- // The first step's `minTime` is `0` by default.
1967
- // It doesn't "change" steps at zero point
1968
- // but it does change the wording when switching
1969
- // from "future" to "past": "in ..." -> "... ago".
1970
- // Therefore, the label should be updated at zero-point too.
1971
- var minTime = getStepMinTime(currentOrNextStep, {
1972
- timestamp: timestamp,
1973
- now: now,
1974
- future: future,
1975
- round: round,
1976
- prevStep: prevStep
1977
- });
1978
-
1979
- if (minTime === undefined) {
1980
- return;
1981
- }
1982
-
1983
- if (future) {
1984
- // The step changes to the previous step
1985
- // as soon as `timestamp - now` becomes
1986
- // less than the `minTime` of the current step:
1987
- // `timestamp - now === minTime - 1`
1988
- // => `now === timestamp - minTime + 1`.
1989
- return timestamp - minTime * 1000 + 1;
1990
- } else {
1991
- // The step changes to the next step
1992
- // as soon as `now - timestamp` becomes
1993
- // equal to `minTime` of the next step:
1994
- // `now - timestamp === minTime`
1995
- // => `now === timestamp + minTime`.
1996
- // This is a special case when double-update could be skipped.
1997
- if (minTime === 0 && timestamp === now) {
1998
- return INFINITY;
1999
- }
2000
-
2001
- return timestamp + minTime * 1000;
2002
- }
2003
- }
2004
- function getTimeToStepChange(step, timestamp, _ref3) {
2005
- var now = _ref3.now,
2006
- future = _ref3.future,
2007
- round = _ref3.round,
2008
- prevStep = _ref3.prevStep;
2009
-
2010
- if (step) {
2011
- var stepChangesAt = getStepChangesAt(step, timestamp, {
2012
- now: now,
2013
- future: future,
2014
- round: round,
2015
- prevStep: prevStep
2016
- });
2017
-
2018
- if (stepChangesAt === undefined) {
2019
- return;
2020
- }
2021
-
2022
- return stepChangesAt - now;
2023
- } else {
2024
- if (future) {
2025
- // No step.
2026
- // Update right after zero point, when it changes from "future" to "past".
2027
- return timestamp - now + 1;
2028
- } else {
2029
- // The last step doesn't ever change when `date` is in the past.
2030
- return INFINITY;
2031
- }
2032
- }
2033
- }
2034
-
2035
- // For all locales added
2036
- // their relative time formatter messages will be stored here.
2037
- var localesData = {};
2038
- function getLocaleData(locale) {
2039
- return localesData[locale];
2040
- }
2041
- function addLocaleData(localeData) {
2042
- if (!localeData) {
2043
- throw new Error('[javascript-time-ago] No locale data passed.');
2044
- } // This locale data is stored in a global variable
2045
- // and later used when calling `.format(time)`.
2046
-
2047
-
2048
- localesData[localeData.locale] = localeData;
2049
- }
2050
-
2051
- // just now
2052
- // 1 second ago
2053
- // 2 seconds ago
2054
- // …
2055
- // 59 seconds ago
2056
- // 1 minute ago
2057
- // 2 minutes ago
2058
- // …
2059
- // 59 minutes ago
2060
- // 1 hour ago
2061
- // 2 hours ago
2062
- // …
2063
- // 24 hours ago
2064
- // 1 day ago
2065
- // 2 days ago
2066
- // …
2067
- // 6 days ago
2068
- // 1 week ago
2069
- // 2 weeks ago
2070
- // …
2071
- // 3 weeks ago
2072
- // 1 month ago
2073
- // 2 months ago
2074
- // …
2075
- // 11 months ago
2076
- // 1 year ago
2077
- // 2 years ago
2078
- // …
2079
- var round$1 = [{
2080
- formatAs: 'now'
2081
- }, {
2082
- formatAs: 'second'
2083
- }, {
2084
- formatAs: 'minute'
2085
- }, {
2086
- formatAs: 'hour'
2087
- }, {
2088
- formatAs: 'day'
2089
- }, {
2090
- formatAs: 'week'
2091
- }, {
2092
- formatAs: 'month'
2093
- }, {
2094
- formatAs: 'year'
2095
- }];
2096
-
2097
- // 1 second ago
2098
- // 2 seconds ago
2099
- // …
2100
- // 59 seconds ago
2101
- // 1 minute ago
2102
- // 2 minutes ago
2103
- // …
2104
- // 59 minutes ago
2105
- // 1 minute ago
2106
- // 2 minutes ago
2107
- // …
2108
- // 59 minutes ago
2109
- // 1 hour ago
2110
- // 2 hours ago
2111
- // …
2112
- // 24 hours ago
2113
- // 1 day ago
2114
- // 2 days ago
2115
- // …
2116
- // 6 days ago
2117
- // 1 week ago
2118
- // 2 weeks ago
2119
- // 3 weeks ago
2120
- // 4 weeks ago
2121
- // 1 month ago
2122
- // 2 months ago
2123
- // …
2124
- // 11 months ago
2125
- // 1 year ago
2126
- // 2 years ago
2127
- // …
2128
- //
2129
-
2130
- var round = {
2131
- steps: round$1,
2132
- labels: 'long'
2133
- };
2134
-
2135
- function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2136
-
2137
- function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$7(Object(source), !0).forEach(function (key) { _defineProperty$7(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2138
-
2139
- function _defineProperty$7(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2140
- // 1 minute ago
2141
- // 2 minutes ago
2142
- // …
2143
- // 59 minutes ago
2144
- // 1 minute ago
2145
- // 2 minutes ago
2146
- // …
2147
- // 59 minutes ago
2148
- // 1 hour ago
2149
- // 2 hours ago
2150
- // …
2151
- // 24 hours ago
2152
- // 1 day ago
2153
- // 2 days ago
2154
- // …
2155
- // 6 days ago
2156
- // 1 week ago
2157
- // 2 weeks ago
2158
- // 3 weeks ago
2159
- // 4 weeks ago
2160
- // 1 month ago
2161
- // 2 months ago
2162
- // …
2163
- // 11 months ago
2164
- // 1 year ago
2165
- // 2 years ago
2166
- // …
2167
- //
2168
-
2169
- var defaultStyle = _objectSpread$7(_objectSpread$7({}, round), {}, {
2170
- // Skip "seconds".
2171
- steps: round.steps.filter(function (step) {
2172
- return step.formatAs !== 'second';
2173
- })
2174
- });
2175
-
2176
- // Developers shouldn't need to use it in their custom steps.
2177
- // "threshold" is a legacy name of "min".
2178
- // Developers should use "min" property name instead of "threshold".
2179
- // "threshold_for_idOrUnit: value" is a legacy way of specifying "min: { id: value }".
2180
- // Developers should use "min" property instead of "threshold".
2181
- // just now
2182
- // 1 minute ago
2183
- // 2 minutes ago
2184
- // 5 minutes ago
2185
- // 10 minutes ago
2186
- // 15 minutes ago
2187
- // 20 minutes ago
2188
- // …
2189
- // 50 minutes ago
2190
- // an hour ago
2191
- // 2 hours ago
2192
- // …
2193
- // 20 hours ago
2194
- // a day ago
2195
- // 2 days ago
2196
- // 5 days ago
2197
- // a week ago
2198
- // 2 weeks ago
2199
- // 3 weeks ago
2200
- // a month ago
2201
- // 2 months ago
2202
- // 4 months ago
2203
- // a year ago
2204
- // 2 years ago
2205
- // …
2206
-
2207
- var approximate$1 = [{
2208
- // This step returns the amount of seconds
2209
- // by dividing the amount of seconds by `1`.
2210
- factor: 1,
2211
- // "now" labels are used for formatting the output.
2212
- unit: 'now'
2213
- }, {
2214
- // When the language doesn't support `now` unit,
2215
- // the first step is ignored, and it uses this `second` unit.
2216
- threshold: 1,
2217
- // `threshold_for_now` should be the same as `threshold` on minutes.
2218
- threshold_for_now: 45.5,
2219
- // This step returns the amount of seconds
2220
- // by dividing the amount of seconds by `1`.
2221
- factor: 1,
2222
- // "second" labels are used for formatting the output.
2223
- unit: 'second'
2224
- }, {
2225
- // `threshold` should be the same as `threshold_for_now` on seconds.
2226
- threshold: 45.5,
2227
- // Return the amount of minutes by dividing the amount
2228
- // of seconds by the amount of seconds in a minute.
2229
- factor: minute,
2230
- // "minute" labels are used for formatting the output.
2231
- unit: 'minute'
2232
- }, {
2233
- // This step is effective starting from 2.5 minutes.
2234
- threshold: 2.5 * minute,
2235
- // Allow only 5-minute increments of minutes starting from 2.5 minutes.
2236
- // `granularity` — (advanced) Time interval value "granularity".
2237
- // For example, it could be set to `5` for minutes to allow only 5-minute increments
2238
- // when formatting time intervals: `0 minutes`, `5 minutes`, `10 minutes`, etc.
2239
- // Perhaps this feature will be removed because there seem to be no use cases
2240
- // of it in the real world.
2241
- granularity: 5,
2242
- // Return the amount of minutes by dividing the amount
2243
- // of seconds by the amount of seconds in a minute.
2244
- factor: minute,
2245
- // "minute" labels are used for formatting the output.
2246
- unit: 'minute'
2247
- }, {
2248
- // This step is effective starting from 22.5 minutes.
2249
- threshold: 22.5 * minute,
2250
- // Return the amount of minutes by dividing the amount
2251
- // of seconds by the amount of seconds in half-an-hour.
2252
- factor: 0.5 * hour,
2253
- // "half-hour" labels are used for formatting the output.
2254
- // (if available, which is no longer the case)
2255
- unit: 'half-hour'
2256
- }, {
2257
- // This step is effective starting from 42.5 minutes.
2258
- threshold: 42.5 * minute,
2259
- threshold_for_minute: 52.5 * minute,
2260
- // Return the amount of minutes by dividing the amount
2261
- // of seconds by the amount of seconds in an hour.
2262
- factor: hour,
2263
- // "hour" labels are used for formatting the output.
2264
- unit: 'hour'
2265
- }, {
2266
- // This step is effective starting from 20.5 hours.
2267
- threshold: 20.5 / 24 * day,
2268
- // Return the amount of minutes by dividing the amount
2269
- // of seconds by the amount of seconds in a day.
2270
- factor: day,
2271
- // "day" labels are used for formatting the output.
2272
- unit: 'day'
2273
- }, {
2274
- // This step is effective starting from 5.5 days.
2275
- threshold: 5.5 * day,
2276
- // Return the amount of minutes by dividing the amount
2277
- // of seconds by the amount of seconds in a week.
2278
- factor: week,
2279
- // "week" labels are used for formatting the output.
2280
- unit: 'week'
2281
- }, {
2282
- // This step is effective starting from 3.5 weeks.
2283
- threshold: 3.5 * week,
2284
- // Return the amount of minutes by dividing the amount
2285
- // of seconds by the amount of seconds in a month.
2286
- factor: month,
2287
- // "month" labels are used for formatting the output.
2288
- unit: 'month'
2289
- }, {
2290
- // This step is effective starting from 10.5 months.
2291
- threshold: 10.5 * month,
2292
- // Return the amount of minutes by dividing the amount
2293
- // of seconds by the amount of seconds in a year.
2294
- factor: year,
2295
- // "year" labels are used for formatting the output.
2296
- unit: 'year'
2297
- }];
2298
-
2299
- // It's here just for legacy compatibility.
2300
- // Use "steps" name instead.
2301
- // "flavour" is a legacy name for "labels".
2302
- // It's here just for legacy compatibility.
2303
- // Use "labels" name instead.
2304
- // "units" is a legacy property.
2305
- // It's here just for legacy compatibility.
2306
- // Developers shouldn't need to use it in their custom styles.
2307
-
2308
- var approximate = {
2309
- gradation: approximate$1,
2310
- flavour: 'long',
2311
- units: ['now', 'minute', 'hour', 'day', 'week', 'month', 'year']
2312
- };
2313
-
2314
- // It's here just for legacy compatibility.
2315
- // Use "steps" name instead.
2316
- // "flavour" is a legacy name for "labels".
2317
- // It's here just for legacy compatibility.
2318
- // Use "labels" name instead.
2319
- // "units" is a legacy property.
2320
- // It's here just for legacy compatibility.
2321
- // Developers shouldn't need to use it in their custom styles.
2322
- // Similar to the default style but with "ago" omitted.
2323
- //
2324
- // just now
2325
- // 5 minutes
2326
- // 10 minutes
2327
- // 15 minutes
2328
- // 20 minutes
2329
- // an hour
2330
- // 2 hours
2331
- // …
2332
- // 20 hours
2333
- // 1 day
2334
- // 2 days
2335
- // a week
2336
- // 2 weeks
2337
- // 3 weeks
2338
- // a month
2339
- // 2 months
2340
- // 3 months
2341
- // 4 months
2342
- // a year
2343
- // 2 years
2344
- //
2345
-
2346
- var approximateTime = {
2347
- gradation: approximate$1,
2348
- flavour: 'long-time',
2349
- units: ['now', 'minute', 'hour', 'day', 'week', 'month', 'year']
2350
- };
2351
-
2352
- // Looks like this one's deprecated.
2353
- // /**
2354
- // * Returns a step corresponding to the unit.
2355
- // * @param {Object[]} steps
2356
- // * @param {string} unit
2357
- // * @return {?Object}
2358
- // */
2359
- // export function getStepForUnit(steps, unit) {
2360
- // for (const step of steps) {
2361
- // if (step.unit === unit) {
2362
- // return step
2363
- // }
2364
- // }
2365
- // }
2366
- // Looks like this one won't be used in the next major version.
2367
-
2368
- /**
2369
- * Converts value to a `Date`
2370
- * @param {(number|Date)} value
2371
- * @return {Date}
2372
- */
2373
- function getDate(value) {
2374
- return value instanceof Date ? value : new Date(value);
2375
- }
2376
-
2377
- // ("1m", "2h", "Mar 3", "Apr 4, 2012").
2378
- //
2379
- // Seconds, minutes or hours are shown for shorter intervals,
2380
- // and longer intervals are formatted using full date format.
2381
-
2382
- var steps = [{
2383
- formatAs: 'second'
2384
- }, {
2385
- formatAs: 'minute'
2386
- }, {
2387
- formatAs: 'hour'
2388
- }]; // A cache for `Intl.DateTimeFormat` formatters
2389
- // for various locales (is a global variable).
2390
-
2391
- var formatters = {}; // Starting from day intervals, output month and day.
2392
-
2393
- var monthAndDay = {
2394
- minTime: function minTime(timestamp, _ref) {
2395
- _ref.future;
2396
- var getMinTimeForUnit = _ref.getMinTimeForUnit;
2397
- // Returns `23.5 * 60 * 60` when `round` is "round",
2398
- // and `24 * 60 * 60` when `round` is "floor".
2399
- return getMinTimeForUnit('day');
2400
- },
2401
- format: function format(value, locale) {
2402
- /* istanbul ignore else */
2403
- if (!formatters[locale]) {
2404
- formatters[locale] = {};
2405
- }
2406
- /* istanbul ignore else */
2407
-
2408
-
2409
- if (!formatters[locale].dayMonth) {
2410
- // "Apr 11" (MMMd)
2411
- formatters[locale].dayMonth = new Intl.DateTimeFormat(locale, {
2412
- month: 'short',
2413
- day: 'numeric'
2414
- });
2415
- } // Output month and day.
2416
-
2417
-
2418
- return formatters[locale].dayMonth.format(getDate(value));
2419
- }
2420
- }; // If the `date` happened/happens outside of current year,
2421
- // then output day, month and year.
2422
- // The interval should be such that the `date` lies outside of the current year.
2423
-
2424
- var yearMonthAndDay = {
2425
- minTime: function minTime(timestamp, _ref2) {
2426
- var future = _ref2.future;
2427
-
2428
- if (future) {
2429
- // January 1, 00:00, of the `date`'s year is right after
2430
- // the maximum `now` for formatting a future date:
2431
- // When `now` is before that date, the `date` is formatted as "day/month/year" (this step),
2432
- // When `now` is equal to or after that date, the `date` is formatted as "day/month" (another step).
2433
- // After that, it's hours, minutes, seconds, and after that it's no longer `future`.
2434
- // The date is right after the maximum `now` for formatting a future date,
2435
- // so subtract 1 millisecond from it.
2436
- var maxFittingNow = new Date(new Date(timestamp).getFullYear(), 0).getTime() - 1; // Return `minTime` (in seconds).
2437
-
2438
- return (timestamp - maxFittingNow) / 1000;
2439
- } else {
2440
- // January 1, 00:00, of the year following the `date`'s year
2441
- // is the minimum `now` for formatting a past date:
2442
- // When `now` is before that date, the `date` is formatted as "day/month" (another step),
2443
- // When `now` is equal to or after that date, the `date` is formatted as "day/month/year" (this step).
2444
- // After that, it's hours, minutes, seconds, and after that it's no longer `future`.
2445
- var minFittingNow = new Date(new Date(timestamp).getFullYear() + 1, 0).getTime(); // Return `minTime` (in seconds).
2446
-
2447
- return (minFittingNow - timestamp) / 1000;
2448
- }
2449
- },
2450
- format: function format(value, locale) {
2451
- /* istanbul ignore if */
2452
- if (!formatters[locale]) {
2453
- formatters[locale] = {};
2454
- }
2455
- /* istanbul ignore else */
2456
-
2457
-
2458
- if (!formatters[locale].dayMonthYear) {
2459
- // "Apr 11, 2017" (yMMMd)
2460
- formatters[locale].dayMonthYear = new Intl.DateTimeFormat(locale, {
2461
- year: 'numeric',
2462
- month: 'short',
2463
- day: 'numeric'
2464
- });
2465
- } // Output day, month and year.
2466
-
2467
-
2468
- return formatters[locale].dayMonthYear.format(getDate(value));
2469
- }
2470
- }; // If `Intl.DateTimeFormat` is supported,
2471
- // then longer time intervals will be formatted as dates.
2472
-
2473
- /* istanbul ignore else */
2474
-
2475
- if (intlDateTimeFormatSupported()) {
2476
- steps.push(monthAndDay, yearMonthAndDay);
2477
- } // Otherwise, if `Intl.DateTimeFormat` is not supported,
2478
- // which could be the case when using Internet Explorer,
2479
- // then simply mimick "round" steps.
2480
- else {
2481
- steps.push({
2482
- formatAs: 'day'
2483
- }, {
2484
- formatAs: 'week'
2485
- }, {
2486
- formatAs: 'month'
2487
- }, {
2488
- formatAs: 'year'
2489
- });
2490
- }
2491
-
2492
- var twitter = {
2493
- steps: steps,
2494
- labels: [// "mini" labels are only defined for a few languages.
2495
- 'mini', // "short-time" labels are only defined for a few languages.
2496
- 'short-time', // "narrow" and "short" labels are defined for all languages.
2497
- // "narrow" labels can sometimes be weird (like "+5d."),
2498
- // but "short" labels have the " ago" part, so "narrow" seem
2499
- // more appropriate.
2500
- // "short" labels would have been more appropriate if they
2501
- // didn't have the " ago" part, hence the "short-time" above.
2502
- 'narrow', // Since "narrow" labels are always present, "short" element
2503
- // of this array can be removed.
2504
- 'short']
2505
- };
2506
-
2507
- function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2508
-
2509
- function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6(Object(source), !0).forEach(function (key) { _defineProperty$6(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2510
-
2511
- function _defineProperty$6(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2512
- var twitterNow = _objectSpread$6(_objectSpread$6({}, twitter), {}, {
2513
- // Add "now".
2514
- steps: [{
2515
- formatAs: 'now'
2516
- }].concat(twitter.steps)
2517
- });
2518
-
2519
- function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2520
-
2521
- function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5(Object(source), !0).forEach(function (key) { _defineProperty$5(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2522
-
2523
- function _defineProperty$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2524
- var twitterMinute = _objectSpread$5(_objectSpread$5({}, twitter), {}, {
2525
- // Skip "seconds".
2526
- steps: twitter.steps.filter(function (step) {
2527
- return step.formatAs !== 'second';
2528
- })
2529
- });
2530
-
2531
- function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2532
-
2533
- function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty$4(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2534
-
2535
- function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2536
- var twitterMinuteNow = _objectSpread$4(_objectSpread$4({}, twitterMinute), {}, {
2537
- // Add "now".
2538
- steps: [{
2539
- formatAs: 'now'
2540
- }].concat(twitterMinute.steps)
2541
- });
2542
-
2543
- function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2544
-
2545
- function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty$3(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2546
-
2547
- function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2548
- var twitterFirstMinute = _objectSpread$3(_objectSpread$3({}, twitter), {}, {
2549
- // Skip "seconds".
2550
- steps: twitter.steps.filter(function (step) {
2551
- return step.formatAs !== 'second';
2552
- }) // Start showing `1m` from the first minute.
2553
- .map(function (step) {
2554
- return step.formatAs === 'minute' ? _objectSpread$3(_objectSpread$3({}, step), {}, {
2555
- minTime: minute
2556
- }) : step;
2557
- })
2558
- });
2559
-
2560
- var mini = {
2561
- steps: [{
2562
- formatAs: 'second'
2563
- }, {
2564
- formatAs: 'minute'
2565
- }, {
2566
- formatAs: 'hour'
2567
- }, {
2568
- formatAs: 'day'
2569
- }, {
2570
- formatAs: 'month'
2571
- }, {
2572
- formatAs: 'year'
2573
- }],
2574
- labels: [// "mini" labels are only defined for a few languages.
2575
- 'mini', // "short-time" labels are only defined for a few languages.
2576
- 'short-time', // "narrow" and "short" labels are defined for all languages.
2577
- // "narrow" labels can sometimes be weird (like "+5d."),
2578
- // but "short" labels have the " ago" part, so "narrow" seem
2579
- // more appropriate.
2580
- // "short" labels would have been more appropriate if they
2581
- // didn't have the " ago" part, hence the "short-time" above.
2582
- 'narrow', // Since "narrow" labels are always present, "short" element
2583
- // of this array can be removed.
2584
- 'short']
2585
- };
2586
-
2587
- function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2588
-
2589
- function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty$2(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2590
-
2591
- function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2592
- var miniNow = _objectSpread$2(_objectSpread$2({}, mini), {}, {
2593
- // Add "now".
2594
- steps: [{
2595
- formatAs: 'now'
2596
- }].concat(mini.steps)
2597
- });
2598
-
2599
- function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2600
-
2601
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2602
-
2603
- function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2604
- var miniMinute = _objectSpread$1(_objectSpread$1({}, mini), {}, {
2605
- // Skip "seconds".
2606
- steps: mini.steps.filter(function (step) {
2607
- return step.formatAs !== 'second';
2608
- })
2609
- });
2610
-
2611
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2612
-
2613
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2614
-
2615
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2616
- var miniMinuteNow = _objectSpread(_objectSpread({}, miniMinute), {}, {
2617
- // Add "now".
2618
- steps: [{
2619
- formatAs: 'now'
2620
- }].concat(miniMinute.steps)
2621
- });
2622
-
2623
- function getStyleByName(style) {
2624
- switch (style) {
2625
- // "default" style name is deprecated.
2626
- case 'default':
2627
- case 'round':
2628
- return round;
2629
-
2630
- case 'round-minute':
2631
- return defaultStyle;
2632
-
2633
- case 'approximate':
2634
- return approximate;
2635
- // "time" style name is deprecated.
2636
-
2637
- case 'time':
2638
- case 'approximate-time':
2639
- return approximateTime;
2640
-
2641
- case 'mini':
2642
- return mini;
2643
-
2644
- case 'mini-now':
2645
- return miniNow;
2646
-
2647
- case 'mini-minute':
2648
- return miniMinute;
2649
-
2650
- case 'mini-minute-now':
2651
- return miniMinuteNow;
2652
-
2653
- case 'twitter':
2654
- return twitter;
2655
-
2656
- case 'twitter-now':
2657
- return twitterNow;
2658
-
2659
- case 'twitter-minute':
2660
- return twitterMinute;
2661
-
2662
- case 'twitter-minute-now':
2663
- return twitterMinuteNow;
2664
-
2665
- case 'twitter-first-minute':
2666
- return twitterFirstMinute;
2667
-
2668
- default:
2669
- // For historical reasons, the default style is "approximate".
2670
- return approximate;
2671
- }
2672
- }
2673
-
2674
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2675
-
2676
- function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
2677
-
2678
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2679
-
2680
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
2681
-
2682
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
2683
-
2684
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
2685
-
2686
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
2687
-
2688
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
2689
-
2690
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2691
-
2692
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
2693
-
2694
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2695
-
2696
- var TimeAgo = /*#__PURE__*/function () {
2697
- /**
2698
- * @param {(string|string[])} locales=[] - Preferred locales (or locale).
2699
- * @param {boolean} [polyfill] — Pass `false` to use native `Intl.RelativeTimeFormat` and `Intl.PluralRules` instead of the polyfills.
2700
- */
2701
- function TimeAgo() {
2702
- var locales = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2703
-
2704
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
2705
- polyfill = _ref.polyfill;
2706
-
2707
- _classCallCheck(this, TimeAgo);
2708
-
2709
- // Convert `locales` to an array.
2710
- if (typeof locales === 'string') {
2711
- locales = [locales];
2712
- } // Choose the most appropriate locale
2713
- // from the list of `locales` added by the user.
2714
- // For example, new TimeAgo("en-US") -> "en".
2715
-
2716
-
2717
- this.locale = chooseLocale(locales.concat(TimeAgo.getDefaultLocale()), getLocaleData);
2718
-
2719
- if (typeof Intl !== 'undefined') {
2720
- // Use `Intl.NumberFormat` for formatting numbers (when available).
2721
- if (Intl.NumberFormat) {
2722
- this.numberFormat = new Intl.NumberFormat(this.locale);
2723
- }
2724
- } // Some people have requested the ability to use native
2725
- // `Intl.RelativeTimeFormat` and `Intl.PluralRules`
2726
- // instead of the polyfills.
2727
- // https://github.com/catamphetamine/javascript-time-ago/issues/21
2728
-
2729
-
2730
- if (polyfill === false) {
2731
- this.IntlRelativeTimeFormat = Intl.RelativeTimeFormat;
2732
- this.IntlPluralRules = Intl.PluralRules;
2733
- } else {
2734
- this.IntlRelativeTimeFormat = RelativeTimeFormat;
2735
- this.IntlPluralRules = RelativeTimeFormat.PluralRules;
2736
- } // Cache `Intl.RelativeTimeFormat` instance.
2737
-
2738
-
2739
- this.relativeTimeFormatCache = new Cache(); // Cache `Intl.PluralRules` instance.
2740
-
2741
- this.pluralRulesCache = new Cache();
2742
- }
2743
- /**
2744
- * Formats relative date/time.
2745
- *
2746
- * @param {(number|Date)} input — A `Date` or a javascript timestamp.
2747
- *
2748
- * @param {(string|object)} style — Date/time formatting style. Either one of the built-in style names or a "custom" style definition object having `steps: object[]` and `labels: string[]`.
2749
- *
2750
- * @param {number} [options.now] - Sets the current date timestamp.
2751
- *
2752
- * @param {boolean} [options.future] — Tells how to format value `0`:
2753
- * as "future" (`true`) or "past" (`false`).
2754
- * Is `false` by default, but should have been `true` actually,
2755
- * in order to correspond to `Intl.RelativeTimeFormat`
2756
- * that uses `future` formatting for `0` unless `-0` is passed.
2757
- *
2758
- * @param {string} [options.round] — Rounding method. Overrides the style's one.
2759
- *
2760
- * @param {boolean} [options.getTimeToNextUpdate] — Pass `true` to return `[formattedDate, timeToNextUpdate]` instead of just `formattedDate`.
2761
- *
2762
- * @return {string} The formatted relative date/time. If no eligible `step` is found, then an empty string is returned.
2763
- */
2764
-
2765
-
2766
- _createClass(TimeAgo, [{
2767
- key: "format",
2768
- value: function format(input, style, options) {
2769
- if (!options) {
2770
- if (style && !isStyle(style)) {
2771
- options = style;
2772
- style = undefined;
2773
- } else {
2774
- options = {};
2775
- }
2776
- }
2777
-
2778
- if (!style) {
2779
- style = defaultStyle;
2780
- }
2781
-
2782
- if (typeof style === 'string') {
2783
- style = getStyleByName(style);
2784
- }
2785
-
2786
- var timestamp = getTimestamp(input); // Get locale messages for this type of labels.
2787
- // "flavour" is a legacy name for "labels".
2788
-
2789
- var _this$getLabels = this.getLabels(style.flavour || style.labels),
2790
- labels = _this$getLabels.labels,
2791
- labelsType = _this$getLabels.labelsType;
2792
-
2793
- var now; // Can pass a custom `now`, e.g. for testing purposes.
2794
- //
2795
- // Legacy way was passing `now` in `style`.
2796
- // That way is deprecated.
2797
-
2798
- if (style.now !== undefined) {
2799
- now = style.now;
2800
- } // The new way is passing `now` option to `.format()`.
2801
-
2802
-
2803
- if (now === undefined && options.now !== undefined) {
2804
- now = options.now;
2805
- }
2806
-
2807
- if (now === undefined) {
2808
- now = Date.now();
2809
- } // how much time has passed (in seconds)
2810
-
2811
-
2812
- var secondsPassed = (now - timestamp) / 1000; // in seconds
2813
-
2814
- var future = options.future || secondsPassed < 0;
2815
- var nowLabel = getNowLabel(labels, getLocaleData(this.locale).now, getLocaleData(this.locale)["long"], future); // `custom` – A function of `{ elapsed, time, date, now, locale }`.
2816
- //
2817
- // Looks like `custom` function is deprecated and will be removed
2818
- // in the next major version.
2819
- //
2820
- // If this function returns a value, then the `.format()` call will return that value.
2821
- // Otherwise the relative date/time is formatted as usual.
2822
- // This feature is currently not used anywhere and is here
2823
- // just for providing the ultimate customization point
2824
- // in case anyone would ever need that. Prefer using
2825
- // `steps[step].format(value, locale)` instead.
2826
- //
2827
-
2828
- if (style.custom) {
2829
- var custom = style.custom({
2830
- now: now,
2831
- date: new Date(timestamp),
2832
- time: timestamp,
2833
- elapsed: secondsPassed,
2834
- locale: this.locale
2835
- });
2836
-
2837
- if (custom !== undefined) {
2838
- // Won't return `timeToNextUpdate` here
2839
- // because `custom()` seems deprecated.
2840
- return custom;
2841
- }
2842
- } // Get the list of available time interval units.
2843
-
2844
-
2845
- var units = getTimeIntervalMeasurementUnits( // Controlling `style.steps` through `style.units` seems to be deprecated:
2846
- // create a new custom `style` instead.
2847
- style.units, labels, nowLabel); // // If no available time unit is suitable, just output an empty string.
2848
- // if (units.length === 0) {
2849
- // console.error(`None of the "${units.join(', ')}" time units have been found in "${labelsType}" labels for "${this.locale}" locale.`)
2850
- // return ''
2851
- // }
2852
-
2853
- var round = options.round || style.round; // Choose the appropriate time measurement unit
2854
- // and get the corresponding rounded time amount.
2855
-
2856
- var _getStep = getStep( // "gradation" is a legacy name for "steps".
2857
- // For historical reasons, "approximate" steps are used by default.
2858
- // In the next major version, there'll be no default for `steps`.
2859
- style.gradation || style.steps || defaultStyle.steps, secondsPassed, {
2860
- now: now,
2861
- units: units,
2862
- round: round,
2863
- future: future,
2864
- getNextStep: true
2865
- }),
2866
- _getStep2 = _slicedToArray(_getStep, 3),
2867
- prevStep = _getStep2[0],
2868
- step = _getStep2[1],
2869
- nextStep = _getStep2[2];
2870
-
2871
- var formattedDate = this.formatDateForStep(timestamp, step, secondsPassed, {
2872
- labels: labels,
2873
- labelsType: labelsType,
2874
- nowLabel: nowLabel,
2875
- now: now,
2876
- future: future,
2877
- round: round
2878
- }) || '';
2879
-
2880
- if (options.getTimeToNextUpdate) {
2881
- var timeToNextUpdate = getTimeToNextUpdate(timestamp, step, {
2882
- nextStep: nextStep,
2883
- prevStep: prevStep,
2884
- now: now,
2885
- future: future,
2886
- round: round
2887
- });
2888
- return [formattedDate, timeToNextUpdate];
2889
- }
2890
-
2891
- return formattedDate;
2892
- }
2893
- }, {
2894
- key: "formatDateForStep",
2895
- value: function formatDateForStep(timestamp, step, secondsPassed, _ref2) {
2896
- var _this = this;
2897
-
2898
- var labels = _ref2.labels,
2899
- labelsType = _ref2.labelsType,
2900
- nowLabel = _ref2.nowLabel,
2901
- now = _ref2.now,
2902
- future = _ref2.future,
2903
- round = _ref2.round;
2904
-
2905
- // If no step matches, then output an empty string.
2906
- if (!step) {
2907
- return;
2908
- }
2909
-
2910
- if (step.format) {
2911
- return step.format(timestamp, this.locale, {
2912
- formatAs: function formatAs(unit, value) {
2913
- // Mimicks `Intl.RelativeTimeFormat.format()`.
2914
- return _this.formatValue(value, unit, {
2915
- labels: labels,
2916
- future: future
2917
- });
2918
- },
2919
- now: now,
2920
- future: future
2921
- });
2922
- } // "unit" is now called "formatAs".
2923
-
2924
-
2925
- var unit = step.unit || step.formatAs;
2926
-
2927
- if (!unit) {
2928
- throw new Error("[javascript-time-ago] Each step must define either `formatAs` or `format()`. Step: ".concat(JSON.stringify(step)));
2929
- } // `Intl.RelativeTimeFormat` doesn't operate in "now" units.
2930
- // Therefore, threat "now" as a special case.
2931
-
2932
-
2933
- if (unit === 'now') {
2934
- return nowLabel;
2935
- } // Amount in units.
2936
-
2937
-
2938
- var amount = Math.abs(secondsPassed) / getStepDenominator(step); // Apply granularity to the time amount
2939
- // (and fallback to the previous step
2940
- // if the first level of granularity
2941
- // isn't met by this amount)
2942
- //
2943
- // `granularity` — (advanced) Time interval value "granularity".
2944
- // For example, it could be set to `5` for minutes to allow only 5-minute increments
2945
- // when formatting time intervals: `0 minutes`, `5 minutes`, `10 minutes`, etc.
2946
- // Perhaps this feature will be removed because there seem to be no use cases
2947
- // of it in the real world.
2948
- //
2949
-
2950
- if (step.granularity) {
2951
- // Recalculate the amount of seconds passed based on granularity
2952
- amount = getRoundFunction(round)(amount / step.granularity) * step.granularity;
2953
- }
2954
-
2955
- var valueForFormatting = -1 * Math.sign(secondsPassed) * getRoundFunction(round)(amount); // By default, this library formats a `0` in "past" mode,
2956
- // unless `future: true` option is passed.
2957
- // This is different to `relative-time-format`'s behavior
2958
- // which formats a `0` in "future" mode by default, unless it's a `-0`.
2959
- // So, convert `0` to `-0` if `future: true` option wasn't passed.
2960
- // `=== 0` matches both `0` and `-0`.
2961
-
2962
- if (valueForFormatting === 0) {
2963
- if (future) {
2964
- valueForFormatting = 0;
2965
- } else {
2966
- valueForFormatting = -0;
2967
- }
2968
- }
2969
-
2970
- switch (labelsType) {
2971
- case 'long':
2972
- case 'short':
2973
- case 'narrow':
2974
- // Format the amount using `Intl.RelativeTimeFormat`.
2975
- return this.getFormatter(labelsType).format(valueForFormatting, unit);
2976
-
2977
- default:
2978
- // Format the amount.
2979
- // (mimicks `Intl.RelativeTimeFormat` behavior for other time label styles)
2980
- return this.formatValue(valueForFormatting, unit, {
2981
- labels: labels,
2982
- future: future
2983
- });
2984
- }
2985
- }
2986
- /**
2987
- * Mimicks what `Intl.RelativeTimeFormat` does for additional locale styles.
2988
- * @param {number} value
2989
- * @param {string} unit
2990
- * @param {object} options.labels — Relative time labels.
2991
- * @param {boolean} [options.future] — Tells how to format value `0`: as "future" (`true`) or "past" (`false`). Is `false` by default, but should have been `true` actually.
2992
- * @return {string}
2993
- */
2994
-
2995
- }, {
2996
- key: "formatValue",
2997
- value: function formatValue(value, unit, _ref3) {
2998
- var labels = _ref3.labels,
2999
- future = _ref3.future;
3000
- return this.getFormattingRule(labels, unit, value, {
3001
- future: future
3002
- }).replace('{0}', this.formatNumber(Math.abs(value)));
3003
- }
3004
- /**
3005
- * Returns formatting rule for `value` in `units` (either in past or in future).
3006
- * @param {object} formattingRules — Relative time labels for different units.
3007
- * @param {string} unit - Time interval measurement unit.
3008
- * @param {number} value - Time interval value.
3009
- * @param {boolean} [options.future] — Tells how to format value `0`: as "future" (`true`) or "past" (`false`). Is `false` by default.
3010
- * @return {string}
3011
- * @example
3012
- * // Returns "{0} days ago"
3013
- * getFormattingRule(en.long, "day", -2, 'en')
3014
- */
3015
-
3016
- }, {
3017
- key: "getFormattingRule",
3018
- value: function getFormattingRule(formattingRules, unit, value, _ref4) {
3019
- var future = _ref4.future;
3020
- // Passing the language is required in order to
3021
- // be able to correctly classify the `value` as a number.
3022
- this.locale;
3023
- formattingRules = formattingRules[unit]; // Check for a special "compacted" rules case:
3024
- // if formatting rules are the same for "past" and "future",
3025
- // and also for all possible `value`s, then those rules are
3026
- // stored as a single string.
3027
-
3028
- if (typeof formattingRules === 'string') {
3029
- return formattingRules;
3030
- } // Choose either "past" or "future" based on time `value` sign.
3031
- // If "past" is same as "future" then they're stored as "other".
3032
- // If there's only "other" then it's being collapsed.
3033
-
3034
-
3035
- var pastOrFuture = value === 0 ? future ? 'future' : 'past' : value < 0 ? 'past' : 'future';
3036
- var quantifierRules = formattingRules[pastOrFuture] || formattingRules; // Bundle size optimization technique.
3037
-
3038
- if (typeof quantifierRules === 'string') {
3039
- return quantifierRules;
3040
- } // Quantify `value`.
3041
-
3042
-
3043
- var quantifier = this.getPluralRules().select(Math.abs(value)); // "other" rule is supposed to always be present.
3044
- // If only "other" rule is present then "rules" is not an object and is a string.
3045
-
3046
- return quantifierRules[quantifier] || quantifierRules.other;
3047
- }
3048
- /**
3049
- * Formats a number into a string.
3050
- * Uses `Intl.NumberFormat` when available.
3051
- * @param {number} number
3052
- * @return {string}
3053
- */
3054
-
3055
- }, {
3056
- key: "formatNumber",
3057
- value: function formatNumber(number) {
3058
- return this.numberFormat ? this.numberFormat.format(number) : String(number);
3059
- }
3060
- /**
3061
- * Returns an `Intl.RelativeTimeFormat` for a given `labelsType`.
3062
- * @param {string} labelsType
3063
- * @return {object} `Intl.RelativeTimeFormat` instance
3064
- */
3065
-
3066
- }, {
3067
- key: "getFormatter",
3068
- value: function getFormatter(labelsType) {
3069
- // `Intl.RelativeTimeFormat` instance creation is (hypothetically) assumed
3070
- // a lengthy operation so the instances are cached and reused.
3071
- return this.relativeTimeFormatCache.get(this.locale, labelsType) || this.relativeTimeFormatCache.put(this.locale, labelsType, new this.IntlRelativeTimeFormat(this.locale, {
3072
- style: labelsType
3073
- }));
3074
- }
3075
- /**
3076
- * Returns an `Intl.PluralRules` instance.
3077
- * @return {object} `Intl.PluralRules` instance
3078
- */
3079
-
3080
- }, {
3081
- key: "getPluralRules",
3082
- value: function getPluralRules() {
3083
- // `Intl.PluralRules` instance creation is (hypothetically) assumed
3084
- // a lengthy operation so the instances are cached and reused.
3085
- return this.pluralRulesCache.get(this.locale) || this.pluralRulesCache.put(this.locale, new this.IntlPluralRules(this.locale));
3086
- }
3087
- /**
3088
- * Gets localized labels for this type of labels.
3089
- *
3090
- * @param {(string|string[])} labelsType - Relative date/time labels type.
3091
- * If it's an array then all label types are tried
3092
- * until a suitable one is found.
3093
- *
3094
- * @returns {Object} Returns an object of shape { labelsType, labels }
3095
- */
3096
-
3097
- }, {
3098
- key: "getLabels",
3099
- value: function getLabels() {
3100
- var labelsType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3101
-
3102
- // Convert `labels` to an array.
3103
- if (typeof labelsType === 'string') {
3104
- labelsType = [labelsType];
3105
- } // Supports legacy "tiny" and "mini-time" label styles.
3106
-
3107
-
3108
- labelsType = labelsType.map(function (labelsType) {
3109
- switch (labelsType) {
3110
- case 'tiny':
3111
- case 'mini-time':
3112
- return 'mini';
3113
-
3114
- default:
3115
- return labelsType;
3116
- }
3117
- }); // "long" labels type is the default one.
3118
- // (it's always present for all languages)
3119
-
3120
- labelsType = labelsType.concat('long'); // Find a suitable labels type.
3121
-
3122
- var localeData = getLocaleData(this.locale);
3123
-
3124
- for (var _iterator = _createForOfIteratorHelperLoose(labelsType), _step; !(_step = _iterator()).done;) {
3125
- var _labelsType = _step.value;
3126
-
3127
- if (localeData[_labelsType]) {
3128
- return {
3129
- labelsType: _labelsType,
3130
- labels: localeData[_labelsType]
3131
- };
3132
- }
3133
- }
3134
- }
3135
- }]);
3136
-
3137
- return TimeAgo;
3138
- }();
3139
- var defaultLocale = 'en';
3140
- /**
3141
- * Gets default locale.
3142
- * @return {string} locale
3143
- */
3144
-
3145
- TimeAgo.getDefaultLocale = function () {
3146
- return defaultLocale;
3147
- };
3148
- /**
3149
- * Sets default locale.
3150
- * @param {string} locale
3151
- */
3152
-
3153
-
3154
- TimeAgo.setDefaultLocale = function (locale) {
3155
- return defaultLocale = locale;
3156
- };
3157
- /**
3158
- * Adds locale data for a specific locale and marks the locale as default.
3159
- * @param {Object} localeData
3160
- */
3161
-
3162
-
3163
- TimeAgo.addDefaultLocale = function (localeData) {
3164
- if (defaultLocaleHasBeenSpecified) {
3165
- return console.error('[javascript-time-ago] `TimeAgo.addDefaultLocale()` can only be called once. To add other locales, use `TimeAgo.addLocale()`.');
3166
- }
3167
-
3168
- defaultLocaleHasBeenSpecified = true;
3169
- TimeAgo.setDefaultLocale(localeData.locale);
3170
- TimeAgo.addLocale(localeData);
3171
- };
3172
-
3173
- var defaultLocaleHasBeenSpecified;
3174
- /**
3175
- * Adds locale data for a specific locale.
3176
- * @param {Object} localeData
3177
- */
3178
-
3179
- TimeAgo.addLocale = function (localeData) {
3180
- addLocaleData(localeData);
3181
- RelativeTimeFormat.addLocale(localeData);
3182
- };
3183
- /**
3184
- * (legacy alias)
3185
- * Adds locale data for a specific locale.
3186
- * @param {Object} localeData
3187
- * @deprecated
3188
- */
3189
-
3190
-
3191
- TimeAgo.locale = TimeAgo.addLocale;
3192
- /**
3193
- * Adds custom labels to locale data.
3194
- * @param {string} locale
3195
- * @param {string} name
3196
- * @param {object} labels
3197
- */
3198
-
3199
- TimeAgo.addLabels = function (locale, name, labels) {
3200
- var localeData = getLocaleData(locale);
3201
-
3202
- if (!localeData) {
3203
- addLocaleData({
3204
- locale: locale
3205
- });
3206
- localeData = getLocaleData(locale); // throw new Error(`[javascript-time-ago] No data for locale "${locale}"`)
3207
- }
3208
-
3209
- localeData[name] = labels;
3210
- }; // Normalizes `.format()` `time` argument.
3211
-
3212
-
3213
- function getTimestamp(input) {
3214
- if (input.constructor === Date || isMockedDate(input)) {
3215
- return input.getTime();
3216
- }
3217
-
3218
- if (typeof input === 'number') {
3219
- return input;
3220
- } // For some weird reason istanbul doesn't see this `throw` covered.
3221
-
3222
- /* istanbul ignore next */
3223
-
3224
-
3225
- throw new Error("Unsupported relative time formatter input: ".concat(_typeof(input), ", ").concat(input));
3226
- } // During testing via some testing libraries `Date`s aren't actually `Date`s.
3227
- // https://github.com/catamphetamine/javascript-time-ago/issues/22
3228
-
3229
-
3230
- function isMockedDate(object) {
3231
- return _typeof(object) === 'object' && typeof object.getTime === 'function';
3232
- } // Get available time interval measurement units.
3233
-
3234
-
3235
- function getTimeIntervalMeasurementUnits(allowedUnits, labels, nowLabel) {
3236
- // Get all time interval measurement units that're available
3237
- // in locale data for a given time labels style.
3238
- var units = Object.keys(labels); // `now` unit is handled separately and is shipped in its own `now.json` file.
3239
- // `now.json` isn't present for all locales, so it could be substituted with
3240
- // ".second.current".
3241
- // Add `now` unit if it's available in locale data.
3242
-
3243
- if (nowLabel) {
3244
- units.push('now');
3245
- } // If only a specific set of available time measurement units can be used
3246
- // then only those units are allowed (if they're present in locale data).
3247
-
3248
-
3249
- if (allowedUnits) {
3250
- units = allowedUnits.filter(function (unit) {
3251
- return unit === 'now' || units.indexOf(unit) >= 0;
3252
- });
3253
- }
3254
-
3255
- return units;
3256
- }
3257
-
3258
- function getNowLabel(labels, nowLabels, longLabels, future) {
3259
- var nowLabel = labels.now || nowLabels && nowLabels.now; // Specific "now" message form extended locale data (if present).
3260
-
3261
- if (nowLabel) {
3262
- // Bundle size optimization technique.
3263
- if (typeof nowLabel === 'string') {
3264
- return nowLabel;
3265
- } // Not handling `value === 0` as `localeData.now.current` here
3266
- // because it wouldn't make sense: "now" is a moment,
3267
- // so one can't possibly differentiate between a
3268
- // "previous" moment, a "current" moment and a "next moment".
3269
- // It can only be differentiated between "past" and "future".
3270
-
3271
-
3272
- if (future) {
3273
- return nowLabel.future;
3274
- } else {
3275
- return nowLabel.past;
3276
- }
3277
- } // Use ".second.current" as "now" message.
3278
-
3279
-
3280
- if (longLabels && longLabels.second && longLabels.second.current) {
3281
- return longLabels.second.current;
3282
- }
3283
- }
3284
-
3285
- function isStyle(variable) {
3286
- return typeof variable === 'string' || isStyleObject(variable);
3287
- }
3288
-
3289
- var en = {
3290
- "locale": "en",
3291
- "long": {
3292
- "year": {
3293
- "previous": "last year",
3294
- "current": "this year",
3295
- "next": "next year",
3296
- "past": {
3297
- "one": "{0} year ago",
3298
- "other": "{0} years ago"
3299
- },
3300
- "future": {
3301
- "one": "in {0} year",
3302
- "other": "in {0} years"
3303
- }
3304
- },
3305
- "quarter": {
3306
- "previous": "last quarter",
3307
- "current": "this quarter",
3308
- "next": "next quarter",
3309
- "past": {
3310
- "one": "{0} quarter ago",
3311
- "other": "{0} quarters ago"
3312
- },
3313
- "future": {
3314
- "one": "in {0} quarter",
3315
- "other": "in {0} quarters"
3316
- }
3317
- },
3318
- "month": {
3319
- "previous": "last month",
3320
- "current": "this month",
3321
- "next": "next month",
3322
- "past": {
3323
- "one": "{0} month ago",
3324
- "other": "{0} months ago"
3325
- },
3326
- "future": {
3327
- "one": "in {0} month",
3328
- "other": "in {0} months"
3329
- }
3330
- },
3331
- "week": {
3332
- "previous": "last week",
3333
- "current": "this week",
3334
- "next": "next week",
3335
- "past": {
3336
- "one": "{0} week ago",
3337
- "other": "{0} weeks ago"
3338
- },
3339
- "future": {
3340
- "one": "in {0} week",
3341
- "other": "in {0} weeks"
3342
- }
3343
- },
3344
- "day": {
3345
- "previous": "yesterday",
3346
- "current": "today",
3347
- "next": "tomorrow",
3348
- "past": {
3349
- "one": "{0} day ago",
3350
- "other": "{0} days ago"
3351
- },
3352
- "future": {
3353
- "one": "in {0} day",
3354
- "other": "in {0} days"
3355
- }
3356
- },
3357
- "hour": {
3358
- "current": "this hour",
3359
- "past": {
3360
- "one": "{0} hour ago",
3361
- "other": "{0} hours ago"
3362
- },
3363
- "future": {
3364
- "one": "in {0} hour",
3365
- "other": "in {0} hours"
3366
- }
3367
- },
3368
- "minute": {
3369
- "current": "this minute",
3370
- "past": {
3371
- "one": "{0} minute ago",
3372
- "other": "{0} minutes ago"
3373
- },
3374
- "future": {
3375
- "one": "in {0} minute",
3376
- "other": "in {0} minutes"
3377
- }
3378
- },
3379
- "second": {
3380
- "current": "now",
3381
- "past": {
3382
- "one": "{0} second ago",
3383
- "other": "{0} seconds ago"
3384
- },
3385
- "future": {
3386
- "one": "in {0} second",
3387
- "other": "in {0} seconds"
3388
- }
3389
- }
3390
- },
3391
- "short": {
3392
- "year": {
3393
- "previous": "last yr.",
3394
- "current": "this yr.",
3395
- "next": "next yr.",
3396
- "past": "{0} yr. ago",
3397
- "future": "in {0} yr."
3398
- },
3399
- "quarter": {
3400
- "previous": "last qtr.",
3401
- "current": "this qtr.",
3402
- "next": "next qtr.",
3403
- "past": {
3404
- "one": "{0} qtr. ago",
3405
- "other": "{0} qtrs. ago"
3406
- },
3407
- "future": {
3408
- "one": "in {0} qtr.",
3409
- "other": "in {0} qtrs."
3410
- }
3411
- },
3412
- "month": {
3413
- "previous": "last mo.",
3414
- "current": "this mo.",
3415
- "next": "next mo.",
3416
- "past": "{0} mo. ago",
3417
- "future": "in {0} mo."
3418
- },
3419
- "week": {
3420
- "previous": "last wk.",
3421
- "current": "this wk.",
3422
- "next": "next wk.",
3423
- "past": "{0} wk. ago",
3424
- "future": "in {0} wk."
3425
- },
3426
- "day": {
3427
- "previous": "yesterday",
3428
- "current": "today",
3429
- "next": "tomorrow",
3430
- "past": {
3431
- "one": "{0} day ago",
3432
- "other": "{0} days ago"
3433
- },
3434
- "future": {
3435
- "one": "in {0} day",
3436
- "other": "in {0} days"
3437
- }
3438
- },
3439
- "hour": {
3440
- "current": "this hour",
3441
- "past": "{0} hr. ago",
3442
- "future": "in {0} hr."
3443
- },
3444
- "minute": {
3445
- "current": "this minute",
3446
- "past": "{0} min. ago",
3447
- "future": "in {0} min."
3448
- },
3449
- "second": {
3450
- "current": "now",
3451
- "past": "{0} sec. ago",
3452
- "future": "in {0} sec."
3453
- }
3454
- },
3455
- "narrow": {
3456
- "year": {
3457
- "previous": "last yr.",
3458
- "current": "this yr.",
3459
- "next": "next yr.",
3460
- "past": "{0}y ago",
3461
- "future": "in {0}y"
3462
- },
3463
- "quarter": {
3464
- "previous": "last qtr.",
3465
- "current": "this qtr.",
3466
- "next": "next qtr.",
3467
- "past": "{0}q ago",
3468
- "future": "in {0}q"
3469
- },
3470
- "month": {
3471
- "previous": "last mo.",
3472
- "current": "this mo.",
3473
- "next": "next mo.",
3474
- "past": "{0}mo ago",
3475
- "future": "in {0}mo"
3476
- },
3477
- "week": {
3478
- "previous": "last wk.",
3479
- "current": "this wk.",
3480
- "next": "next wk.",
3481
- "past": "{0}w ago",
3482
- "future": "in {0}w"
3483
- },
3484
- "day": {
3485
- "previous": "yesterday",
3486
- "current": "today",
3487
- "next": "tomorrow",
3488
- "past": "{0}d ago",
3489
- "future": "in {0}d"
3490
- },
3491
- "hour": {
3492
- "current": "this hour",
3493
- "past": "{0}h ago",
3494
- "future": "in {0}h"
3495
- },
3496
- "minute": {
3497
- "current": "this minute",
3498
- "past": "{0}m ago",
3499
- "future": "in {0}m"
3500
- },
3501
- "second": {
3502
- "current": "now",
3503
- "past": "{0}s ago",
3504
- "future": "in {0}s"
3505
- }
3506
- },
3507
- "now": {
3508
- "now": {
3509
- "current": "now",
3510
- "future": "in a moment",
3511
- "past": "just now"
3512
- }
3513
- },
3514
- "mini": {
3515
- "year": "{0}yr",
3516
- "month": "{0}mo",
3517
- "week": "{0}wk",
3518
- "day": "{0}d",
3519
- "hour": "{0}h",
3520
- "minute": "{0}m",
3521
- "second": "{0}s",
3522
- "now": "now"
3523
- },
3524
- "short-time": {
3525
- "year": "{0} yr.",
3526
- "month": "{0} mo.",
3527
- "week": "{0} wk.",
3528
- "day": {
3529
- "one": "{0} day",
3530
- "other": "{0} days"
3531
- },
3532
- "hour": "{0} hr.",
3533
- "minute": "{0} min.",
3534
- "second": "{0} sec."
3535
- },
3536
- "long-time": {
3537
- "year": {
3538
- "one": "{0} year",
3539
- "other": "{0} years"
3540
- },
3541
- "month": {
3542
- "one": "{0} month",
3543
- "other": "{0} months"
3544
- },
3545
- "week": {
3546
- "one": "{0} week",
3547
- "other": "{0} weeks"
3548
- },
3549
- "day": {
3550
- "one": "{0} day",
3551
- "other": "{0} days"
3552
- },
3553
- "hour": {
3554
- "one": "{0} hour",
3555
- "other": "{0} hours"
3556
- },
3557
- "minute": {
3558
- "one": "{0} minute",
3559
- "other": "{0} minutes"
3560
- },
3561
- "second": {
3562
- "one": "{0} second",
3563
- "other": "{0} seconds"
3564
- }
3565
- }
3566
- };
3567
-
3568
- TimeAgo.addDefaultLocale(en);
3569
- const useTimeAgo = () => {
3570
- const timeAgo = new TimeAgo('en-US');
3571
- return timeAgo;
3572
- };
3573
-
3574
- const useTransition = ({ container, animateIn, animateOut, duration = 300 }) => {
3575
- const Animated = styled(container) `
3576
- animation-name: ${({ $isEntering, $isLeaving }) => ($isEntering ? animateIn : $isLeaving ? animateOut : 'none')};
3577
- animation-duration: ${duration}ms;
3578
- animation-fill-mode: forwards;
3579
- `;
3580
- // !! Do not deprecate this "useCallback" hook, it is necessary for the transition to work properly
3581
- const Transition = useCallback(({ children, enter, ...props }) => {
3582
- // eslint-disable-next-line react-hooks/rules-of-hooks
3583
- const [mounted, setMounted] = useState(false);
3584
- // eslint-disable-next-line react-hooks/rules-of-hooks
3585
- useEffect(() => {
3586
- const t = setTimeout(() => setMounted(enter), duration + 50); // +50ms to ensure the animation is finished
3587
- return () => clearTimeout(t);
3588
- }, [enter, duration]);
3589
- if (!enter && !mounted)
3590
- return null;
3591
- return (React.createElement(Animated, { "$isEntering": enter, "$isLeaving": !enter && mounted, ...props }, children));
3592
- },
3593
- // !! Do not add dependencies here, it will cause re-renders which we want to avoid
3594
- []);
3595
- return Transition;
3596
- };
3597
-
3598
- export { useContainerSize as a, useClickNode as b, usePopup as c, useOnClickOutside as d, useInstrumentationRuleFormData as e, useTransition as f, useTimeAgo as g, useCopy as h, useGenericForm as i, useKeyDown as u };