@aemforms/af-formatters 0.22.31 → 0.22.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,530 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.adjustTimeZone = adjustTimeZone;
7
+ exports.datetimeToNumber = datetimeToNumber;
8
+ exports.formatDate = formatDate;
9
+ exports.numberToDatetime = numberToDatetime;
10
+ exports.offsetMS = offsetMS;
11
+ exports.offsetMSFallback = offsetMSFallback;
12
+ exports.parseDate = parseDate;
13
+ exports.parseDefaultDate = parseDefaultDate;
14
+
15
+ var _SkeletonParser = require("./SkeletonParser.js");
16
+
17
+ /*************************************************************************
18
+ * ADOBE CONFIDENTIAL
19
+ * ___________________
20
+ *
21
+ * Copyright 2022 Adobe
22
+ * All Rights Reserved.
23
+ *
24
+ * NOTICE: All information contained herein is, and remains
25
+ * the property of Adobe and its suppliers, if any. The intellectual
26
+ * and technical concepts contained herein are proprietary to Adobe
27
+ * and its suppliers and are protected by all applicable intellectual
28
+ * property laws, including trade secret and copyright laws.
29
+ * Dissemination of this information or reproduction of this material
30
+ * is strictly forbidden unless prior written permission is obtained
31
+ * from Adobe.
32
+
33
+ * Adobe permits you to use and modify this file solely in accordance with
34
+ * the terms of the Adobe license agreement accompanying it.
35
+ *************************************************************************/
36
+
37
+ /**
38
+ * Credit: https://git.corp.adobe.com/dc/dfl/blob/master/src/patterns/dates.js
39
+ */
40
+ // Test Japanese full/half width character support
41
+ // get the localized month names resulting from a given pattern
42
+ const twelveMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(m => new Date(2000, m, 1));
43
+ /**
44
+ * returns the name of all the months for a given locale and given Date Format Settings
45
+ * @param locale {string}
46
+ * @param options {string} instance of Intl.DateTimeFormatOptions
47
+ */
48
+
49
+ function monthNames(locale, options) {
50
+ return twelveMonths.map(month => {
51
+ const parts = new Intl.DateTimeFormat(locale, options).formatToParts(month);
52
+ const m = parts.find(p => p.type === 'month');
53
+ return m && m.value;
54
+ });
55
+ }
56
+ /**
57
+ * return an array of digits used by a given locale
58
+ * @param locale {string}
59
+ */
60
+
61
+
62
+ function digitChars(locale) {
63
+ return new Intl.NumberFormat(locale, {
64
+ style: 'decimal',
65
+ useGrouping: false
66
+ }).format(9876543210).split('').reverse();
67
+ }
68
+ /**
69
+ * returns the calendar name used in a given locale
70
+ * @param locale {string}
71
+ */
72
+
73
+
74
+ function calendarName(locale) {
75
+ var _parts$find;
76
+
77
+ const parts = new Intl.DateTimeFormat(locale, {
78
+ era: 'short'
79
+ }).formatToParts(new Date());
80
+ const era = (_parts$find = parts.find(p => p.type === 'era')) === null || _parts$find === void 0 ? void 0 : _parts$find.value;
81
+ return era === 'هـ' ? 'islamic' : 'gregory';
82
+ }
83
+ /**
84
+ * returns the representation of the time of day for a given language
85
+ * @param language {string}
86
+ */
87
+
88
+
89
+ function getDayPeriod(language) {
90
+ const morning = new Date(2000, 1, 1, 1, 1, 1);
91
+ const afternoon = new Date(2000, 1, 1, 16, 1, 1);
92
+ const df = new Intl.DateTimeFormat(language, {
93
+ dateStyle: 'full',
94
+ timeStyle: 'full'
95
+ });
96
+ const am = df.formatToParts(morning).find(p => p.type === 'dayPeriod');
97
+ const pm = df.formatToParts(afternoon).find(p => p.type === 'dayPeriod');
98
+ if (!am || !pm) return null;
99
+ return {
100
+ regex: `(${am.value}|${pm.value})`,
101
+ fn: (period, obj) => obj.hour += period === pm.value ? 12 : 0
102
+ };
103
+ }
104
+ /**
105
+ * get the offset in MS, given a date and timezone
106
+ * @param dateObj {Date}
107
+ * @param timeZone {string}
108
+ */
109
+
110
+
111
+ function offsetMS(dateObj, timeZone) {
112
+ let tzOffset;
113
+
114
+ try {
115
+ tzOffset = new Intl.DateTimeFormat('en-US', {
116
+ timeZone,
117
+ timeZoneName: 'longOffset'
118
+ }).format(dateObj);
119
+ } catch (e) {
120
+ return offsetMSFallback(dateObj, timeZone);
121
+ }
122
+
123
+ const offset = /GMT([+\-−])?(\d{1,2}):?(\d{0,2})?/.exec(tzOffset);
124
+ if (!offset) return 0;
125
+ const [sign, hours, minutes] = offset.slice(1);
126
+ const nHours = isNaN(parseInt(hours)) ? 0 : parseInt(hours);
127
+ const nMinutes = isNaN(parseInt(minutes)) ? 0 : parseInt(minutes);
128
+ const result = (nHours * 60 + nMinutes) * 60 * 1000;
129
+ return sign === '-' ? -result : result;
130
+ }
131
+
132
+ function getTimezoneOffsetFrom(otherTimezone) {
133
+ var date = new Date();
134
+
135
+ function objFromStr(str) {
136
+ var array = str.replace(":", " ").split(" ");
137
+ return {
138
+ day: parseInt(array[0]),
139
+ hour: parseInt(array[1]),
140
+ minute: parseInt(array[2])
141
+ };
142
+ }
143
+
144
+ var str = date.toLocaleString('en-US', {
145
+ timeZone: otherTimezone,
146
+ day: 'numeric',
147
+ hour: 'numeric',
148
+ minute: 'numeric',
149
+ hourCycle: 'h23'
150
+ });
151
+ var other = objFromStr(str);
152
+ str = date.toLocaleString('en-US', {
153
+ day: 'numeric',
154
+ hour: 'numeric',
155
+ minute: 'numeric',
156
+ hourCycle: 'h23'
157
+ });
158
+ var myLocale = objFromStr(str);
159
+ var otherOffset = other.day * 24 * 60 + other.hour * 60 + other.minute; // utc date + otherTimezoneDifference
160
+
161
+ var myLocaleOffset = myLocale.day * 24 * 60 + myLocale.hour * 60 + myLocale.minute; // utc date + myTimeZoneDifference
162
+ // (utc date + otherZoneDifference) - (utc date + myZoneDifference) - (-1 * myTimeZoneDifference)
163
+
164
+ return otherOffset - myLocaleOffset - date.getTimezoneOffset();
165
+ }
166
+
167
+ function offsetMSFallback(dateObj, timezone) {
168
+ //const defaultOffset = dateObj.getTimezoneOffset();
169
+ const timezoneOffset = getTimezoneOffsetFrom(timezone);
170
+ return timezoneOffset * 60 * 1000;
171
+ }
172
+ /**
173
+ * adjust from the default JavaScript timezone to the default timezone
174
+ * @param dateObj {Date}
175
+ * @param timeZone {string}
176
+ */
177
+
178
+
179
+ function adjustTimeZone(dateObj, timeZone) {
180
+ if (dateObj === null) return null; // const defaultOffset = new Intl.DateTimeFormat('en-US', { timeZoneName: 'longOffset'}).format(dateObj);
181
+
182
+ let baseDate = dateObj.getTime() - dateObj.getTimezoneOffset() * 60 * 1000;
183
+ const offset = offsetMS(dateObj, timeZone);
184
+ const fallBackOffset = offsetMSFallback(dateObj, timeZone);
185
+ baseDate += -offset; // get the offset for the default JS environment
186
+ // return days since the epoch
187
+
188
+ return new Date(baseDate);
189
+ }
190
+ /**
191
+ * Our script object model treats dates as numbers where the integer portion is days since the epoch,
192
+ * the fractional portion is the number hours in the day
193
+ * @param dateObj {Date}
194
+ * @returns {number}
195
+ */
196
+
197
+
198
+ function datetimeToNumber(dateObj) {
199
+ if (dateObj === null) return 0; // return days since the epoch
200
+
201
+ return dateObj.getTime() / (1000 * 60 * 60 * 24);
202
+ }
203
+ /**
204
+ * Our script object model treats dates as numbers where the integer portion is days since the epoch,
205
+ * the fractional portion is the number hours in the day
206
+ * @param num
207
+ * @returns {Date}
208
+ */
209
+
210
+
211
+ function numberToDatetime(num) {
212
+ return new Date(Math.round(num * 1000 * 60 * 60 * 24));
213
+ }
214
+ /**
215
+ * in some cases, DateTimeFormat doesn't respect the 'numeric' vs. '2-digit' setting
216
+ * for time values. The function corrects that
217
+ * @param formattedParts instance of Intl.DateTimeFormatPart[]
218
+ * @param parsed
219
+ */
220
+
221
+
222
+ function fixDigits(formattedParts, parsed) {
223
+ ['hour', 'minute', 'second'].forEach(type => {
224
+ const defn = formattedParts.find(f => f.type === type);
225
+ if (!defn) return;
226
+ const fmt = parsed.find(pair => pair[0] === type)[1];
227
+ if (fmt === '2-digit' && defn.value.length === 1) defn.value = `0${defn.value}`;
228
+ if (fmt === 'numeric' && defn.value.length === 2 && defn.value.charAt(0) === '0') defn.value = defn.value.slice(1);
229
+ });
230
+ }
231
+
232
+ function fixYear(formattedParts, parsed) {
233
+ // two digit years are handled differently in DateTimeFormat. 00 becomes 1900
234
+ // providing a two digit year 0010 gets formatted to 10 and when parsed becomes 1910
235
+ // Hence we need to pad the year with 0 as required by the skeleton and mentioned in
236
+ // unicode. https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-year
237
+ const defn = formattedParts.find(f => f.type === 'year');
238
+ if (!defn) return; // eslint-disable-next-line no-unused-vars
239
+
240
+ const chars = parsed.find(pair => pair[0] === 'year')[2];
241
+
242
+ while (defn.value.length < chars) {
243
+ defn.value = `0${defn.value}`;
244
+ }
245
+ }
246
+ /**
247
+ *
248
+ * @param dateValue {Date}
249
+ * @param language {string}
250
+ * @param skeleton {string}
251
+ * @param timeZone {string}
252
+ * @returns {T}
253
+ */
254
+
255
+
256
+ function formatDateToParts(dateValue, language, skeleton, timeZone) {
257
+ // DateTimeFormat renames some of the options in its formatted output
258
+ //@ts-ignore
259
+ const mappings = key => ({
260
+ hour12: 'dayPeriod',
261
+ fractionalSecondDigits: 'fractionalSecond'
262
+ })[key] || key; // produces an array of name/value pairs of skeleton parts
263
+
264
+
265
+ const allParameters = (0, _SkeletonParser.parseDateTimeSkeleton)(skeleton, language);
266
+ allParameters.push(['timeZone', timeZone]);
267
+ const parsed = allParameters.filter(p => !p[0].startsWith('x-'));
268
+ const nonStandard = allParameters.filter(p => p[0].startsWith('x-')); // reduce to a set of options that can be used to format
269
+
270
+ const options = Object.fromEntries(parsed);
271
+ delete options.literal;
272
+ const df = new Intl.DateTimeFormat(language, options); // formattedParts will have all the pieces we need for our date -- but not in the correct order
273
+
274
+ const formattedParts = df.formatToParts(dateValue);
275
+ fixDigits(formattedParts, allParameters);
276
+ fixYear(formattedParts, parsed); // iterate through the original parsed components and use its ordering and literals,
277
+ // and add the formatted pieces
278
+
279
+ return parsed.reduce((result, cur) => {
280
+ if (cur[0] === 'literal') result.push(cur);else {
281
+ const v = formattedParts.find(p => p.type === mappings(cur[0]));
282
+
283
+ if (v && v.type === 'timeZoneName') {
284
+ const tz = nonStandard.find(p => p[0] === 'x-timeZoneName')[1];
285
+ const category = tz[0];
286
+
287
+ if (category === 'Z') {
288
+ if (tz.length < 4) {
289
+ // handle 'Z', 'ZZ', 'ZZZ' Time Zone: ISO8601 basic hms? / RFC 822
290
+ v.value = v.value.replace(/(GMT|:)/g, '');
291
+ if (v.value === '') v.value = '+0000';
292
+ } else if (tz.length === 5) {
293
+ // 'ZZZZZ' Time Zone: ISO8601 extended hms?
294
+ if (v.value === 'GMT') v.value = 'Z';else v.value = v.value.replace(/GMT/, '');
295
+ }
296
+ }
297
+
298
+ if (category === 'X' || category === 'x') {
299
+ if (tz.length === 1) {
300
+ // 'X' ISO8601 basic hm?, with Z for 0
301
+ // -08, +0530, Z
302
+ // 'x' ISO8601 basic hm?, without Z for 0
303
+ v.value = v.value.replace(/(GMT|:(00)?)/g, '');
304
+ }
305
+
306
+ if (tz.length === 2) {
307
+ // 'XX' ISO8601 basic hm, with Z
308
+ // -0800, Z
309
+ // 'xx' ISO8601 basic hm, without Z
310
+ v.value = v.value.replace(/(GMT|:)/g, '');
311
+ }
312
+
313
+ if (tz.length === 3) {
314
+ // 'XXX' ISO8601 extended hm, with Z
315
+ // -08:00, Z
316
+ // 'xxx' ISO8601 extended hm, without Z
317
+ v.value = v.value.replace(/GMT/g, '');
318
+ }
319
+
320
+ if (category === 'X' && v.value === '') v.value = 'Z';
321
+ } else if (tz === 'O') {
322
+ // eliminate 'GMT', leading and trailing zeros
323
+ v.value = v.value.replace(/GMT/g, '').replace(/0(\d+):/, '$1:').replace(/:00/, '');
324
+ if (v.value === '') v.value = '+0';
325
+ }
326
+ }
327
+
328
+ if (v) result.push([v.type, v.value]);
329
+ }
330
+ return result;
331
+ }, []);
332
+ }
333
+ /**
334
+ *
335
+ * @param dateValue {Date}
336
+ * @param language {string}
337
+ * @param skeleton {string}
338
+ * @param timeZone {string}
339
+ */
340
+
341
+
342
+ function formatDate(dateValue, language, skeleton, timeZone) {
343
+ if (skeleton.startsWith('date|')) {
344
+ skeleton = skeleton.split('|')[1];
345
+ }
346
+
347
+ if (_SkeletonParser.ShorthandStyles.find(type => skeleton.includes(type))) {
348
+ const options = {
349
+ timeZone
350
+ }; // the skeleton could have two keywords -- one for date, one for time
351
+
352
+ const parts = skeleton.split(/\s/).filter(s => s.length);
353
+
354
+ if (_SkeletonParser.ShorthandStyles.indexOf(parts[0]) > -1) {
355
+ options.dateStyle = parts[0];
356
+ }
357
+
358
+ if (parts.length > 1 && _SkeletonParser.ShorthandStyles.indexOf(parts[1]) > -1) {
359
+ options.timeStyle = parts[1];
360
+ }
361
+
362
+ return new Intl.DateTimeFormat(language, options).format(dateValue);
363
+ }
364
+
365
+ const parts = formatDateToParts(dateValue, language, skeleton, timeZone);
366
+ return parts.map(p => p[1]).join('');
367
+ }
368
+ /**
369
+ *
370
+ * @param dateString {string}
371
+ * @param language {string}
372
+ * @param skeleton {string}
373
+ * @param timeZone {string}
374
+ */
375
+
376
+
377
+ function parseDate(dateString, language, skeleton, timeZone) {
378
+ let bUseUTC = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
379
+
380
+ // start by getting all the localized parts of a date/time picture:
381
+ // digits, calendar name
382
+ if (skeleton.startsWith('date|')) {
383
+ skeleton = skeleton.split('|')[1];
384
+ }
385
+
386
+ const lookups = [];
387
+ const regexParts = [];
388
+ const calendar = calendarName(language);
389
+ const digits = digitChars(language);
390
+ const twoDigit = `([${digits[0]}-${digits[9]}]{1,2})`;
391
+ const threeDigit = `([${digits[0]}-${digits[9]}]{1,3})`;
392
+ const fourDigit = `([${digits[0]}-${digits[9]}]{1,4})`;
393
+ let hourCycle = 'h12';
394
+ let _bUseUTC = bUseUTC;
395
+ let _setFullYear = false; // functions to process the results of the regex match
396
+
397
+ const isSeparator = str => str.length === 1 && ':-/.'.includes(str);
398
+
399
+ const monthNumber = str => getNumber(str) - 1;
400
+
401
+ const getNumber = str => str.split('').reduce((total, digit) => total * 10 + digits.indexOf(digit), 0);
402
+
403
+ const yearNumber = templateDigits => str => {
404
+ let year = getNumber(str); //todo: align with AF
405
+
406
+ year = year < 100 && templateDigits === 2 ? year + 2000 : year;
407
+ if (calendar === 'islamic') year = Math.ceil(year * 0.97 + 622);
408
+
409
+ if (templateDigits > 2 && year < 100) {
410
+ _setFullYear = true;
411
+ }
412
+
413
+ return year;
414
+ };
415
+
416
+ const monthLookup = list => month => list.indexOf(month);
417
+
418
+ const parsed = (0, _SkeletonParser.parseDateTimeSkeleton)(skeleton, language);
419
+ const months = monthNames(language, Object.fromEntries(parsed)); // build up a regex expression that identifies each option in the skeleton
420
+ // We build two parallel structures:
421
+ // 1. the regex expression that will extract parts of the date/time
422
+ // 2. a lookup array that will convert the matched results into date/time values
423
+
424
+ parsed.forEach(_ref => {
425
+ let [option, value, len] = _ref;
426
+
427
+ // use a generic regex pattern for all single-character separator literals.
428
+ // Then we'll be forgiving when it comes to separators: / vs - vs : etc
429
+ if (option === 'literal') {
430
+ if (isSeparator(value)) regexParts.push(`[^${digits[0]}-${digits[9]}]`);else regexParts.push(value);
431
+ } else if (option === 'month' && ['numeric', '2-digit'].includes(value)) {
432
+ regexParts.push(twoDigit);
433
+ lookups.push(['month', monthNumber]);
434
+ } else if (option === 'month' && ['formatted', 'long', 'short', 'narrow'].includes(value)) {
435
+ regexParts.push(`(${months.join('|')})`);
436
+ lookups.push(['month', monthLookup(months)]);
437
+ } else if (['day', 'minute', 'second'].includes(option)) {
438
+ if (option === 'minute' || option === 'second') {
439
+ _bUseUTC = false;
440
+ }
441
+
442
+ regexParts.push(twoDigit);
443
+ lookups.push([option, getNumber]);
444
+ } else if (option === 'fractionalSecondDigits') {
445
+ _bUseUTC = false;
446
+ regexParts.push(threeDigit);
447
+ lookups.push([option, (v, obj) => obj.fractionalSecondDigits + getNumber(v)]);
448
+ } else if (option === 'hour') {
449
+ _bUseUTC = false;
450
+ regexParts.push(twoDigit);
451
+ lookups.push([option, (v, obj) => obj.hour + getNumber(v)]);
452
+ } else if (option === 'year') {
453
+ regexParts.push('numeric' === value ? fourDigit : twoDigit);
454
+ lookups.push(['year', yearNumber(len)]);
455
+ } else if (option === 'dayPeriod') {
456
+ _bUseUTC = false;
457
+ const dayPeriod = getDayPeriod(language);
458
+
459
+ if (dayPeriod) {
460
+ regexParts.push(dayPeriod.regex);
461
+ lookups.push(['hour', dayPeriod.fn]);
462
+ } // Any other part that we don't need, we'll just add a non-greedy consumption
463
+
464
+ } else if (option === 'hourCycle') {
465
+ _bUseUTC = false;
466
+ hourCycle = value;
467
+ } else if (option === 'x-timeZoneName') {
468
+ _bUseUTC = false; // we handle only the GMT offset picture
469
+
470
+ regexParts.push('(?:GMT|UTC|Z)?([+\\-−0-9]{0,3}:?[0-9]{0,2})');
471
+ lookups.push([option, (v, obj) => {
472
+ _bUseUTC = true; // v could be undefined if we're on GMT time
473
+
474
+ if (!v) return; // replace the unicode minus, then extract hours [and minutes]
475
+
476
+ const timeParts = v.replace(/−/, '-').match(/([+\-\d]{2,3}):?(\d{0,2})/);
477
+ const hours = timeParts[1] * 1;
478
+ obj.hour -= hours;
479
+ const mins = timeParts.length > 2 ? timeParts[2] * 1 : 0;
480
+ obj.minute -= hours < 0 ? -mins : mins;
481
+ }]);
482
+ } else if (option !== 'timeZoneName') {
483
+ _bUseUTC = false;
484
+ regexParts.push('.+?');
485
+ }
486
+
487
+ return regexParts;
488
+ }, []);
489
+ const regex = new RegExp(regexParts.join(''));
490
+ const match = dateString.match(regex);
491
+ if (match === null) return dateString; // now loop through all the matched pieces and build up an object we'll use to create a Date object
492
+
493
+ const dateObj = {
494
+ year: 1972,
495
+ month: 0,
496
+ day: 1,
497
+ hour: 0,
498
+ minute: 0,
499
+ second: 0,
500
+ fractionalSecondDigits: 0
501
+ };
502
+ match.slice(1).forEach((m, index) => {
503
+ const [element, func] = lookups[index];
504
+ dateObj[element] = func(m, dateObj);
505
+ });
506
+ if (hourCycle === 'h24' && dateObj.hour === 24) dateObj.hour = 0;
507
+ if (hourCycle === 'h12' && dateObj.hour === 12) dateObj.hour = 0;
508
+
509
+ if (_bUseUTC) {
510
+ const utcDate = new Date(Date.UTC(dateObj.year, dateObj.month, dateObj.day, dateObj.hour, dateObj.minute, dateObj.second, dateObj.fractionalSecondDigits));
511
+
512
+ if (_setFullYear) {
513
+ utcDate.setUTCFullYear(dateObj.year);
514
+ }
515
+
516
+ return utcDate;
517
+ }
518
+
519
+ const jsDate = new Date(dateObj.year, dateObj.month, dateObj.day, dateObj.hour, dateObj.minute, dateObj.second, dateObj.fractionalSecondDigits);
520
+
521
+ if (_setFullYear) {
522
+ jsDate.setFullYear(dateObj.year);
523
+ }
524
+
525
+ return timeZone == null ? jsDate : adjustTimeZone(jsDate, timeZone);
526
+ }
527
+
528
+ function parseDefaultDate(dateString, language, bUseUTC) {
529
+ return parseDate(dateString, language, 'short', null, false);
530
+ }