@bigbinary/neeto-email-notifications-frontend 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2573 +1,19 @@
1
- import React, { createContext, useContext, useState, useRef, useEffect } from 'react';
1
+ import React from 'react';
2
2
  import classNames from 'classnames';
3
- import { isNotEmpty, noop as noop$1 } from '@bigbinary/neeto-commons-frontend/pure';
3
+ import { isNotEmpty, noop } from '@bigbinary/neeto-cist';
4
4
  import { EmailFormProvider, EmailForm, EmailPreview } from '@bigbinary/neeto-molecules/EmailForm';
5
5
  import PageLoader from '@bigbinary/neeto-molecules/PageLoader';
6
6
  import { Tooltip, Typography } from '@bigbinary/neetoui';
7
7
  import { Switch } from '@bigbinary/neetoui/formik';
8
8
  import { prop, isEmpty, pluck } from 'ramda';
9
+ import { useTranslation } from 'react-i18next';
9
10
  import { DEFAULT_STALE_TIME } from '@bigbinary/neeto-commons-frontend/constants';
10
- import { useQuery, useQueryClient, useMutation } from 'react-query';
11
+ import { useMutationWithInvalidation } from '@bigbinary/neeto-commons-frontend/react-utils';
12
+ import { useQuery } from 'react-query';
11
13
  import axios from 'axios';
12
14
  import * as yup from 'yup';
13
15
  import { string } from 'yup';
14
16
 
15
- const consoleLogger = {
16
- type: 'logger',
17
- log(args) {
18
- this.output('log', args);
19
- },
20
- warn(args) {
21
- this.output('warn', args);
22
- },
23
- error(args) {
24
- this.output('error', args);
25
- },
26
- output(type, args) {
27
- if (console && console[type]) console[type].apply(console, args);
28
- }
29
- };
30
- class Logger {
31
- constructor(concreteLogger) {
32
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
33
- this.init(concreteLogger, options);
34
- }
35
- init(concreteLogger) {
36
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
37
- this.prefix = options.prefix || 'i18next:';
38
- this.logger = concreteLogger || consoleLogger;
39
- this.options = options;
40
- this.debug = options.debug;
41
- }
42
- log() {
43
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
44
- args[_key] = arguments[_key];
45
- }
46
- return this.forward(args, 'log', '', true);
47
- }
48
- warn() {
49
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
50
- args[_key2] = arguments[_key2];
51
- }
52
- return this.forward(args, 'warn', '', true);
53
- }
54
- error() {
55
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
56
- args[_key3] = arguments[_key3];
57
- }
58
- return this.forward(args, 'error', '');
59
- }
60
- deprecate() {
61
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
62
- args[_key4] = arguments[_key4];
63
- }
64
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
65
- }
66
- forward(args, lvl, prefix, debugOnly) {
67
- if (debugOnly && !this.debug) return null;
68
- if (typeof args[0] === 'string') args[0] = `${prefix}${this.prefix} ${args[0]}`;
69
- return this.logger[lvl](args);
70
- }
71
- create(moduleName) {
72
- return new Logger(this.logger, {
73
- ...{
74
- prefix: `${this.prefix}:${moduleName}:`
75
- },
76
- ...this.options
77
- });
78
- }
79
- clone(options) {
80
- options = options || this.options;
81
- options.prefix = options.prefix || this.prefix;
82
- return new Logger(this.logger, options);
83
- }
84
- }
85
- var baseLogger = new Logger();
86
-
87
- class EventEmitter {
88
- constructor() {
89
- this.observers = {};
90
- }
91
- on(events, listener) {
92
- events.split(' ').forEach(event => {
93
- this.observers[event] = this.observers[event] || [];
94
- this.observers[event].push(listener);
95
- });
96
- return this;
97
- }
98
- off(event, listener) {
99
- if (!this.observers[event]) return;
100
- if (!listener) {
101
- delete this.observers[event];
102
- return;
103
- }
104
- this.observers[event] = this.observers[event].filter(l => l !== listener);
105
- }
106
- emit(event) {
107
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
108
- args[_key - 1] = arguments[_key];
109
- }
110
- if (this.observers[event]) {
111
- const cloned = [].concat(this.observers[event]);
112
- cloned.forEach(observer => {
113
- observer(...args);
114
- });
115
- }
116
- if (this.observers['*']) {
117
- const cloned = [].concat(this.observers['*']);
118
- cloned.forEach(observer => {
119
- observer.apply(observer, [event, ...args]);
120
- });
121
- }
122
- }
123
- }
124
-
125
- function defer() {
126
- let res;
127
- let rej;
128
- const promise = new Promise((resolve, reject) => {
129
- res = resolve;
130
- rej = reject;
131
- });
132
- promise.resolve = res;
133
- promise.reject = rej;
134
- return promise;
135
- }
136
- function makeString(object) {
137
- if (object == null) return '';
138
- return '' + object;
139
- }
140
- function copy(a, s, t) {
141
- a.forEach(m => {
142
- if (s[m]) t[m] = s[m];
143
- });
144
- }
145
- function getLastOfPath(object, path, Empty) {
146
- function cleanKey(key) {
147
- return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
148
- }
149
- function canNotTraverseDeeper() {
150
- return !object || typeof object === 'string';
151
- }
152
- const stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
153
- while (stack.length > 1) {
154
- if (canNotTraverseDeeper()) return {};
155
- const key = cleanKey(stack.shift());
156
- if (!object[key] && Empty) object[key] = new Empty();
157
- if (Object.prototype.hasOwnProperty.call(object, key)) {
158
- object = object[key];
159
- } else {
160
- object = {};
161
- }
162
- }
163
- if (canNotTraverseDeeper()) return {};
164
- return {
165
- obj: object,
166
- k: cleanKey(stack.shift())
167
- };
168
- }
169
- function setPath(object, path, newValue) {
170
- const {
171
- obj,
172
- k
173
- } = getLastOfPath(object, path, Object);
174
- obj[k] = newValue;
175
- }
176
- function pushPath(object, path, newValue, concat) {
177
- const {
178
- obj,
179
- k
180
- } = getLastOfPath(object, path, Object);
181
- obj[k] = obj[k] || [];
182
- if (concat) obj[k] = obj[k].concat(newValue);
183
- if (!concat) obj[k].push(newValue);
184
- }
185
- function getPath(object, path) {
186
- const {
187
- obj,
188
- k
189
- } = getLastOfPath(object, path);
190
- if (!obj) return undefined;
191
- return obj[k];
192
- }
193
- function getPathWithDefaults(data, defaultData, key) {
194
- const value = getPath(data, key);
195
- if (value !== undefined) {
196
- return value;
197
- }
198
- return getPath(defaultData, key);
199
- }
200
- function deepExtend(target, source, overwrite) {
201
- for (const prop in source) {
202
- if (prop !== '__proto__' && prop !== 'constructor') {
203
- if (prop in target) {
204
- if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
205
- if (overwrite) target[prop] = source[prop];
206
- } else {
207
- deepExtend(target[prop], source[prop], overwrite);
208
- }
209
- } else {
210
- target[prop] = source[prop];
211
- }
212
- }
213
- }
214
- return target;
215
- }
216
- function regexEscape(str) {
217
- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
218
- }
219
- var _entityMap = {
220
- '&': '&amp;',
221
- '<': '&lt;',
222
- '>': '&gt;',
223
- '"': '&quot;',
224
- "'": '&#39;',
225
- '/': '&#x2F;'
226
- };
227
- function escape(data) {
228
- if (typeof data === 'string') {
229
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
230
- }
231
- return data;
232
- }
233
- const chars = [' ', ',', '?', '!', ';'];
234
- function looksLikeObjectPath(key, nsSeparator, keySeparator) {
235
- nsSeparator = nsSeparator || '';
236
- keySeparator = keySeparator || '';
237
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
238
- if (possibleChars.length === 0) return true;
239
- const r = new RegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
240
- let matched = !r.test(key);
241
- if (!matched) {
242
- const ki = key.indexOf(keySeparator);
243
- if (ki > 0 && !r.test(key.substring(0, ki))) {
244
- matched = true;
245
- }
246
- }
247
- return matched;
248
- }
249
- function deepFind(obj, path) {
250
- let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
251
- if (!obj) return undefined;
252
- if (obj[path]) return obj[path];
253
- const paths = path.split(keySeparator);
254
- let current = obj;
255
- for (let i = 0; i < paths.length; ++i) {
256
- if (!current) return undefined;
257
- if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
258
- return undefined;
259
- }
260
- if (current[paths[i]] === undefined) {
261
- let j = 2;
262
- let p = paths.slice(i, i + j).join(keySeparator);
263
- let mix = current[p];
264
- while (mix === undefined && paths.length > i + j) {
265
- j++;
266
- p = paths.slice(i, i + j).join(keySeparator);
267
- mix = current[p];
268
- }
269
- if (mix === undefined) return undefined;
270
- if (mix === null) return null;
271
- if (path.endsWith(p)) {
272
- if (typeof mix === 'string') return mix;
273
- if (p && typeof mix[p] === 'string') return mix[p];
274
- }
275
- const joinedPath = paths.slice(i + j).join(keySeparator);
276
- if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
277
- return undefined;
278
- }
279
- current = current[paths[i]];
280
- }
281
- return current;
282
- }
283
- function getCleanedCode(code) {
284
- if (code && code.indexOf('_') > 0) return code.replace('_', '-');
285
- return code;
286
- }
287
-
288
- class ResourceStore extends EventEmitter {
289
- constructor(data) {
290
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
291
- ns: ['translation'],
292
- defaultNS: 'translation'
293
- };
294
- super();
295
- this.data = data || {};
296
- this.options = options;
297
- if (this.options.keySeparator === undefined) {
298
- this.options.keySeparator = '.';
299
- }
300
- if (this.options.ignoreJSONStructure === undefined) {
301
- this.options.ignoreJSONStructure = true;
302
- }
303
- }
304
- addNamespaces(ns) {
305
- if (this.options.ns.indexOf(ns) < 0) {
306
- this.options.ns.push(ns);
307
- }
308
- }
309
- removeNamespaces(ns) {
310
- const index = this.options.ns.indexOf(ns);
311
- if (index > -1) {
312
- this.options.ns.splice(index, 1);
313
- }
314
- }
315
- getResource(lng, ns, key) {
316
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
317
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
318
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
319
- let path = [lng, ns];
320
- if (key && typeof key !== 'string') path = path.concat(key);
321
- if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
322
- if (lng.indexOf('.') > -1) {
323
- path = lng.split('.');
324
- }
325
- const result = getPath(this.data, path);
326
- if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
327
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
328
- }
329
- addResource(lng, ns, key, value) {
330
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
331
- silent: false
332
- };
333
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
334
- let path = [lng, ns];
335
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
336
- if (lng.indexOf('.') > -1) {
337
- path = lng.split('.');
338
- value = ns;
339
- ns = path[1];
340
- }
341
- this.addNamespaces(ns);
342
- setPath(this.data, path, value);
343
- if (!options.silent) this.emit('added', lng, ns, key, value);
344
- }
345
- addResources(lng, ns, resources) {
346
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
347
- silent: false
348
- };
349
- for (const m in resources) {
350
- if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
351
- silent: true
352
- });
353
- }
354
- if (!options.silent) this.emit('added', lng, ns, resources);
355
- }
356
- addResourceBundle(lng, ns, resources, deep, overwrite) {
357
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
358
- silent: false
359
- };
360
- let path = [lng, ns];
361
- if (lng.indexOf('.') > -1) {
362
- path = lng.split('.');
363
- deep = resources;
364
- resources = ns;
365
- ns = path[1];
366
- }
367
- this.addNamespaces(ns);
368
- let pack = getPath(this.data, path) || {};
369
- if (deep) {
370
- deepExtend(pack, resources, overwrite);
371
- } else {
372
- pack = {
373
- ...pack,
374
- ...resources
375
- };
376
- }
377
- setPath(this.data, path, pack);
378
- if (!options.silent) this.emit('added', lng, ns, resources);
379
- }
380
- removeResourceBundle(lng, ns) {
381
- if (this.hasResourceBundle(lng, ns)) {
382
- delete this.data[lng][ns];
383
- }
384
- this.removeNamespaces(ns);
385
- this.emit('removed', lng, ns);
386
- }
387
- hasResourceBundle(lng, ns) {
388
- return this.getResource(lng, ns) !== undefined;
389
- }
390
- getResourceBundle(lng, ns) {
391
- if (!ns) ns = this.options.defaultNS;
392
- if (this.options.compatibilityAPI === 'v1') return {
393
- ...{},
394
- ...this.getResource(lng, ns)
395
- };
396
- return this.getResource(lng, ns);
397
- }
398
- getDataByLanguage(lng) {
399
- return this.data[lng];
400
- }
401
- hasLanguageSomeTranslations(lng) {
402
- const data = this.getDataByLanguage(lng);
403
- const n = data && Object.keys(data) || [];
404
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
405
- }
406
- toJSON() {
407
- return this.data;
408
- }
409
- }
410
-
411
- var postProcessor = {
412
- processors: {},
413
- addPostProcessor(module) {
414
- this.processors[module.name] = module;
415
- },
416
- handle(processors, value, key, options, translator) {
417
- processors.forEach(processor => {
418
- if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);
419
- });
420
- return value;
421
- }
422
- };
423
-
424
- const checkedLoadedFor = {};
425
- class Translator extends EventEmitter {
426
- constructor(services) {
427
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
428
- super();
429
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
430
- this.options = options;
431
- if (this.options.keySeparator === undefined) {
432
- this.options.keySeparator = '.';
433
- }
434
- this.logger = baseLogger.create('translator');
435
- }
436
- changeLanguage(lng) {
437
- if (lng) this.language = lng;
438
- }
439
- exists(key) {
440
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
441
- interpolation: {}
442
- };
443
- if (key === undefined || key === null) {
444
- return false;
445
- }
446
- const resolved = this.resolve(key, options);
447
- return resolved && resolved.res !== undefined;
448
- }
449
- extractFromKey(key, options) {
450
- let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
451
- if (nsSeparator === undefined) nsSeparator = ':';
452
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
453
- let namespaces = options.ns || this.options.defaultNS || [];
454
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
455
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
456
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
457
- const m = key.match(this.interpolator.nestingRegexp);
458
- if (m && m.length > 0) {
459
- return {
460
- key,
461
- namespaces
462
- };
463
- }
464
- const parts = key.split(nsSeparator);
465
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
466
- key = parts.join(keySeparator);
467
- }
468
- if (typeof namespaces === 'string') namespaces = [namespaces];
469
- return {
470
- key,
471
- namespaces
472
- };
473
- }
474
- translate(keys, options, lastKey) {
475
- if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {
476
- options = this.options.overloadTranslationOptionHandler(arguments);
477
- }
478
- if (typeof options === 'object') options = {
479
- ...options
480
- };
481
- if (!options) options = {};
482
- if (keys === undefined || keys === null) return '';
483
- if (!Array.isArray(keys)) keys = [String(keys)];
484
- const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
485
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
486
- const {
487
- key,
488
- namespaces
489
- } = this.extractFromKey(keys[keys.length - 1], options);
490
- const namespace = namespaces[namespaces.length - 1];
491
- const lng = options.lng || this.language;
492
- const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
493
- if (lng && lng.toLowerCase() === 'cimode') {
494
- if (appendNamespaceToCIMode) {
495
- const nsSeparator = options.nsSeparator || this.options.nsSeparator;
496
- if (returnDetails) {
497
- return {
498
- res: `${namespace}${nsSeparator}${key}`,
499
- usedKey: key,
500
- exactUsedKey: key,
501
- usedLng: lng,
502
- usedNS: namespace
503
- };
504
- }
505
- return `${namespace}${nsSeparator}${key}`;
506
- }
507
- if (returnDetails) {
508
- return {
509
- res: key,
510
- usedKey: key,
511
- exactUsedKey: key,
512
- usedLng: lng,
513
- usedNS: namespace
514
- };
515
- }
516
- return key;
517
- }
518
- const resolved = this.resolve(keys, options);
519
- let res = resolved && resolved.res;
520
- const resUsedKey = resolved && resolved.usedKey || key;
521
- const resExactUsedKey = resolved && resolved.exactUsedKey || key;
522
- const resType = Object.prototype.toString.apply(res);
523
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
524
- const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
525
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
526
- const handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
527
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
528
- if (!options.returnObjects && !this.options.returnObjects) {
529
- if (!this.options.returnedObjectHandler) {
530
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
531
- }
532
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
533
- ...options,
534
- ns: namespaces
535
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
536
- if (returnDetails) {
537
- resolved.res = r;
538
- return resolved;
539
- }
540
- return r;
541
- }
542
- if (keySeparator) {
543
- const resTypeIsArray = resType === '[object Array]';
544
- const copy = resTypeIsArray ? [] : {};
545
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
546
- for (const m in res) {
547
- if (Object.prototype.hasOwnProperty.call(res, m)) {
548
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
549
- copy[m] = this.translate(deepKey, {
550
- ...options,
551
- ...{
552
- joinArrays: false,
553
- ns: namespaces
554
- }
555
- });
556
- if (copy[m] === deepKey) copy[m] = res[m];
557
- }
558
- }
559
- res = copy;
560
- }
561
- } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
562
- res = res.join(joinArrays);
563
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
564
- } else {
565
- let usedDefault = false;
566
- let usedKey = false;
567
- const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
568
- const hasDefaultValue = Translator.hasDefaultValue(options);
569
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
570
- const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
571
- ordinal: false
572
- }) : '';
573
- const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
574
- if (!this.isValidLookup(res) && hasDefaultValue) {
575
- usedDefault = true;
576
- res = defaultValue;
577
- }
578
- if (!this.isValidLookup(res)) {
579
- usedKey = true;
580
- res = key;
581
- }
582
- const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
583
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
584
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
585
- if (usedKey || usedDefault || updateMissing) {
586
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
587
- if (keySeparator) {
588
- const fk = this.resolve(key, {
589
- ...options,
590
- keySeparator: false
591
- });
592
- if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
593
- }
594
- let lngs = [];
595
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
596
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
597
- for (let i = 0; i < fallbackLngs.length; i++) {
598
- lngs.push(fallbackLngs[i]);
599
- }
600
- } else if (this.options.saveMissingTo === 'all') {
601
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
602
- } else {
603
- lngs.push(options.lng || this.language);
604
- }
605
- const send = (l, k, specificDefaultValue) => {
606
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
607
- if (this.options.missingKeyHandler) {
608
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
609
- } else if (this.backendConnector && this.backendConnector.saveMissing) {
610
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
611
- }
612
- this.emit('missingKey', l, namespace, k, res);
613
- };
614
- if (this.options.saveMissing) {
615
- if (this.options.saveMissingPlurals && needsPluralHandling) {
616
- lngs.forEach(language => {
617
- this.pluralResolver.getSuffixes(language, options).forEach(suffix => {
618
- send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
619
- });
620
- });
621
- } else {
622
- send(lngs, key, defaultValue);
623
- }
624
- }
625
- }
626
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
627
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
628
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
629
- if (this.options.compatibilityAPI !== 'v1') {
630
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);
631
- } else {
632
- res = this.options.parseMissingKeyHandler(res);
633
- }
634
- }
635
- }
636
- if (returnDetails) {
637
- resolved.res = res;
638
- return resolved;
639
- }
640
- return res;
641
- }
642
- extendTranslation(res, key, options, resolved, lastKey) {
643
- var _this = this;
644
- if (this.i18nFormat && this.i18nFormat.parse) {
645
- res = this.i18nFormat.parse(res, {
646
- ...this.options.interpolation.defaultVariables,
647
- ...options
648
- }, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
649
- resolved
650
- });
651
- } else if (!options.skipInterpolation) {
652
- if (options.interpolation) this.interpolator.init({
653
- ...options,
654
- ...{
655
- interpolation: {
656
- ...this.options.interpolation,
657
- ...options.interpolation
658
- }
659
- }
660
- });
661
- const skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
662
- let nestBef;
663
- if (skipOnVariables) {
664
- const nb = res.match(this.interpolator.nestingRegexp);
665
- nestBef = nb && nb.length;
666
- }
667
- let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
668
- if (this.options.interpolation.defaultVariables) data = {
669
- ...this.options.interpolation.defaultVariables,
670
- ...data
671
- };
672
- res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
673
- if (skipOnVariables) {
674
- const na = res.match(this.interpolator.nestingRegexp);
675
- const nestAft = na && na.length;
676
- if (nestBef < nestAft) options.nest = false;
677
- }
678
- if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;
679
- if (options.nest !== false) res = this.interpolator.nest(res, function () {
680
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
681
- args[_key] = arguments[_key];
682
- }
683
- if (lastKey && lastKey[0] === args[0] && !options.context) {
684
- _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
685
- return null;
686
- }
687
- return _this.translate(...args, key);
688
- }, options);
689
- if (options.interpolation) this.interpolator.reset();
690
- }
691
- const postProcess = options.postProcess || this.options.postProcess;
692
- const postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
693
- if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
694
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
695
- i18nResolved: resolved,
696
- ...options
697
- } : options, this);
698
- }
699
- return res;
700
- }
701
- resolve(keys) {
702
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
703
- let found;
704
- let usedKey;
705
- let exactUsedKey;
706
- let usedLng;
707
- let usedNS;
708
- if (typeof keys === 'string') keys = [keys];
709
- keys.forEach(k => {
710
- if (this.isValidLookup(found)) return;
711
- const extracted = this.extractFromKey(k, options);
712
- const key = extracted.key;
713
- usedKey = key;
714
- let namespaces = extracted.namespaces;
715
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
716
- const needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
717
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
718
- const needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
719
- const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
720
- namespaces.forEach(ns => {
721
- if (this.isValidLookup(found)) return;
722
- usedNS = ns;
723
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
724
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
725
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
726
- }
727
- codes.forEach(code => {
728
- if (this.isValidLookup(found)) return;
729
- usedLng = code;
730
- const finalKeys = [key];
731
- if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
732
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
733
- } else {
734
- let pluralSuffix;
735
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
736
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
737
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
738
- if (needsPluralHandling) {
739
- finalKeys.push(key + pluralSuffix);
740
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
741
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
742
- }
743
- if (needsZeroSuffixLookup) {
744
- finalKeys.push(key + zeroSuffix);
745
- }
746
- }
747
- if (needsContextHandling) {
748
- const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
749
- finalKeys.push(contextKey);
750
- if (needsPluralHandling) {
751
- finalKeys.push(contextKey + pluralSuffix);
752
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
753
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
754
- }
755
- if (needsZeroSuffixLookup) {
756
- finalKeys.push(contextKey + zeroSuffix);
757
- }
758
- }
759
- }
760
- }
761
- let possibleKey;
762
- while (possibleKey = finalKeys.pop()) {
763
- if (!this.isValidLookup(found)) {
764
- exactUsedKey = possibleKey;
765
- found = this.getResource(code, ns, possibleKey, options);
766
- }
767
- }
768
- });
769
- });
770
- });
771
- return {
772
- res: found,
773
- usedKey,
774
- exactUsedKey,
775
- usedLng,
776
- usedNS
777
- };
778
- }
779
- isValidLookup(res) {
780
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
781
- }
782
- getResource(code, ns, key) {
783
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
784
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
785
- return this.resourceStore.getResource(code, ns, key, options);
786
- }
787
- static hasDefaultValue(options) {
788
- const prefix = 'defaultValue';
789
- for (const option in options) {
790
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
791
- return true;
792
- }
793
- }
794
- return false;
795
- }
796
- }
797
-
798
- function capitalize(string) {
799
- return string.charAt(0).toUpperCase() + string.slice(1);
800
- }
801
- class LanguageUtil {
802
- constructor(options) {
803
- this.options = options;
804
- this.supportedLngs = this.options.supportedLngs || false;
805
- this.logger = baseLogger.create('languageUtils');
806
- }
807
- getScriptPartFromCode(code) {
808
- code = getCleanedCode(code);
809
- if (!code || code.indexOf('-') < 0) return null;
810
- const p = code.split('-');
811
- if (p.length === 2) return null;
812
- p.pop();
813
- if (p[p.length - 1].toLowerCase() === 'x') return null;
814
- return this.formatLanguageCode(p.join('-'));
815
- }
816
- getLanguagePartFromCode(code) {
817
- code = getCleanedCode(code);
818
- if (!code || code.indexOf('-') < 0) return code;
819
- const p = code.split('-');
820
- return this.formatLanguageCode(p[0]);
821
- }
822
- formatLanguageCode(code) {
823
- if (typeof code === 'string' && code.indexOf('-') > -1) {
824
- const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
825
- let p = code.split('-');
826
- if (this.options.lowerCaseLng) {
827
- p = p.map(part => part.toLowerCase());
828
- } else if (p.length === 2) {
829
- p[0] = p[0].toLowerCase();
830
- p[1] = p[1].toUpperCase();
831
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
832
- } else if (p.length === 3) {
833
- p[0] = p[0].toLowerCase();
834
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
835
- if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
836
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
837
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
838
- }
839
- return p.join('-');
840
- }
841
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
842
- }
843
- isSupportedCode(code) {
844
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
845
- code = this.getLanguagePartFromCode(code);
846
- }
847
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
848
- }
849
- getBestMatchFromCodes(codes) {
850
- if (!codes) return null;
851
- let found;
852
- codes.forEach(code => {
853
- if (found) return;
854
- const cleanedLng = this.formatLanguageCode(code);
855
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
856
- });
857
- if (!found && this.options.supportedLngs) {
858
- codes.forEach(code => {
859
- if (found) return;
860
- const lngOnly = this.getLanguagePartFromCode(code);
861
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
862
- found = this.options.supportedLngs.find(supportedLng => {
863
- if (supportedLng === lngOnly) return supportedLng;
864
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
865
- if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
866
- });
867
- });
868
- }
869
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
870
- return found;
871
- }
872
- getFallbackCodes(fallbacks, code) {
873
- if (!fallbacks) return [];
874
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
875
- if (typeof fallbacks === 'string') fallbacks = [fallbacks];
876
- if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
877
- if (!code) return fallbacks.default || [];
878
- let found = fallbacks[code];
879
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
880
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
881
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
882
- if (!found) found = fallbacks.default;
883
- return found || [];
884
- }
885
- toResolveHierarchy(code, fallbackCode) {
886
- const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
887
- const codes = [];
888
- const addCode = c => {
889
- if (!c) return;
890
- if (this.isSupportedCode(c)) {
891
- codes.push(c);
892
- } else {
893
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
894
- }
895
- };
896
- if (typeof code === 'string' && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
897
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
898
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
899
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
900
- } else if (typeof code === 'string') {
901
- addCode(this.formatLanguageCode(code));
902
- }
903
- fallbackCodes.forEach(fc => {
904
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
905
- });
906
- return codes;
907
- }
908
- }
909
-
910
- let sets = [{
911
- lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
912
- nr: [1, 2],
913
- fc: 1
914
- }, {
915
- lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
916
- nr: [1, 2],
917
- fc: 2
918
- }, {
919
- lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
920
- nr: [1],
921
- fc: 3
922
- }, {
923
- lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
924
- nr: [1, 2, 5],
925
- fc: 4
926
- }, {
927
- lngs: ['ar'],
928
- nr: [0, 1, 2, 3, 11, 100],
929
- fc: 5
930
- }, {
931
- lngs: ['cs', 'sk'],
932
- nr: [1, 2, 5],
933
- fc: 6
934
- }, {
935
- lngs: ['csb', 'pl'],
936
- nr: [1, 2, 5],
937
- fc: 7
938
- }, {
939
- lngs: ['cy'],
940
- nr: [1, 2, 3, 8],
941
- fc: 8
942
- }, {
943
- lngs: ['fr'],
944
- nr: [1, 2],
945
- fc: 9
946
- }, {
947
- lngs: ['ga'],
948
- nr: [1, 2, 3, 7, 11],
949
- fc: 10
950
- }, {
951
- lngs: ['gd'],
952
- nr: [1, 2, 3, 20],
953
- fc: 11
954
- }, {
955
- lngs: ['is'],
956
- nr: [1, 2],
957
- fc: 12
958
- }, {
959
- lngs: ['jv'],
960
- nr: [0, 1],
961
- fc: 13
962
- }, {
963
- lngs: ['kw'],
964
- nr: [1, 2, 3, 4],
965
- fc: 14
966
- }, {
967
- lngs: ['lt'],
968
- nr: [1, 2, 10],
969
- fc: 15
970
- }, {
971
- lngs: ['lv'],
972
- nr: [1, 2, 0],
973
- fc: 16
974
- }, {
975
- lngs: ['mk'],
976
- nr: [1, 2],
977
- fc: 17
978
- }, {
979
- lngs: ['mnk'],
980
- nr: [0, 1, 2],
981
- fc: 18
982
- }, {
983
- lngs: ['mt'],
984
- nr: [1, 2, 11, 20],
985
- fc: 19
986
- }, {
987
- lngs: ['or'],
988
- nr: [2, 1],
989
- fc: 2
990
- }, {
991
- lngs: ['ro'],
992
- nr: [1, 2, 20],
993
- fc: 20
994
- }, {
995
- lngs: ['sl'],
996
- nr: [5, 1, 2, 3],
997
- fc: 21
998
- }, {
999
- lngs: ['he', 'iw'],
1000
- nr: [1, 2, 20, 21],
1001
- fc: 22
1002
- }];
1003
- let _rulesPluralsTypes = {
1004
- 1: function (n) {
1005
- return Number(n > 1);
1006
- },
1007
- 2: function (n) {
1008
- return Number(n != 1);
1009
- },
1010
- 3: function (n) {
1011
- return 0;
1012
- },
1013
- 4: function (n) {
1014
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1015
- },
1016
- 5: function (n) {
1017
- return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
1018
- },
1019
- 6: function (n) {
1020
- return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
1021
- },
1022
- 7: function (n) {
1023
- return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1024
- },
1025
- 8: function (n) {
1026
- return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
1027
- },
1028
- 9: function (n) {
1029
- return Number(n >= 2);
1030
- },
1031
- 10: function (n) {
1032
- return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
1033
- },
1034
- 11: function (n) {
1035
- return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
1036
- },
1037
- 12: function (n) {
1038
- return Number(n % 10 != 1 || n % 100 == 11);
1039
- },
1040
- 13: function (n) {
1041
- return Number(n !== 0);
1042
- },
1043
- 14: function (n) {
1044
- return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
1045
- },
1046
- 15: function (n) {
1047
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1048
- },
1049
- 16: function (n) {
1050
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
1051
- },
1052
- 17: function (n) {
1053
- return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
1054
- },
1055
- 18: function (n) {
1056
- return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
1057
- },
1058
- 19: function (n) {
1059
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
1060
- },
1061
- 20: function (n) {
1062
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
1063
- },
1064
- 21: function (n) {
1065
- return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
1066
- },
1067
- 22: function (n) {
1068
- return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
1069
- }
1070
- };
1071
- const nonIntlVersions = ['v1', 'v2', 'v3'];
1072
- const intlVersions = ['v4'];
1073
- const suffixesOrder = {
1074
- zero: 0,
1075
- one: 1,
1076
- two: 2,
1077
- few: 3,
1078
- many: 4,
1079
- other: 5
1080
- };
1081
- function createRules() {
1082
- const rules = {};
1083
- sets.forEach(set => {
1084
- set.lngs.forEach(l => {
1085
- rules[l] = {
1086
- numbers: set.nr,
1087
- plurals: _rulesPluralsTypes[set.fc]
1088
- };
1089
- });
1090
- });
1091
- return rules;
1092
- }
1093
- class PluralResolver {
1094
- constructor(languageUtils) {
1095
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1096
- this.languageUtils = languageUtils;
1097
- this.options = options;
1098
- this.logger = baseLogger.create('pluralResolver');
1099
- if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
1100
- this.options.compatibilityJSON = 'v3';
1101
- this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
1102
- }
1103
- this.rules = createRules();
1104
- }
1105
- addRule(lng, obj) {
1106
- this.rules[lng] = obj;
1107
- }
1108
- getRule(code) {
1109
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1110
- if (this.shouldUseIntlApi()) {
1111
- try {
1112
- return new Intl.PluralRules(getCleanedCode(code), {
1113
- type: options.ordinal ? 'ordinal' : 'cardinal'
1114
- });
1115
- } catch {
1116
- return;
1117
- }
1118
- }
1119
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1120
- }
1121
- needsPlural(code) {
1122
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1123
- const rule = this.getRule(code, options);
1124
- if (this.shouldUseIntlApi()) {
1125
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
1126
- }
1127
- return rule && rule.numbers.length > 1;
1128
- }
1129
- getPluralFormsOfKey(code, key) {
1130
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1131
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1132
- }
1133
- getSuffixes(code) {
1134
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1135
- const rule = this.getRule(code, options);
1136
- if (!rule) {
1137
- return [];
1138
- }
1139
- if (this.shouldUseIntlApi()) {
1140
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1141
- }
1142
- return rule.numbers.map(number => this.getSuffix(code, number, options));
1143
- }
1144
- getSuffix(code, count) {
1145
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1146
- const rule = this.getRule(code, options);
1147
- if (rule) {
1148
- if (this.shouldUseIntlApi()) {
1149
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1150
- }
1151
- return this.getSuffixRetroCompatible(rule, count);
1152
- }
1153
- this.logger.warn(`no plural rule found for: ${code}`);
1154
- return '';
1155
- }
1156
- getSuffixRetroCompatible(rule, count) {
1157
- const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
1158
- let suffix = rule.numbers[idx];
1159
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1160
- if (suffix === 2) {
1161
- suffix = 'plural';
1162
- } else if (suffix === 1) {
1163
- suffix = '';
1164
- }
1165
- }
1166
- const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
1167
- if (this.options.compatibilityJSON === 'v1') {
1168
- if (suffix === 1) return '';
1169
- if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;
1170
- return returnSuffix();
1171
- } else if (this.options.compatibilityJSON === 'v2') {
1172
- return returnSuffix();
1173
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1174
- return returnSuffix();
1175
- }
1176
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
1177
- }
1178
- shouldUseIntlApi() {
1179
- return !nonIntlVersions.includes(this.options.compatibilityJSON);
1180
- }
1181
- }
1182
-
1183
- function deepFindWithDefaults(data, defaultData, key) {
1184
- let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
1185
- let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
1186
- let path = getPathWithDefaults(data, defaultData, key);
1187
- if (!path && ignoreJSONStructure && typeof key === 'string') {
1188
- path = deepFind(data, key, keySeparator);
1189
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1190
- }
1191
- return path;
1192
- }
1193
- class Interpolator {
1194
- constructor() {
1195
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1196
- this.logger = baseLogger.create('interpolator');
1197
- this.options = options;
1198
- this.format = options.interpolation && options.interpolation.format || (value => value);
1199
- this.init(options);
1200
- }
1201
- init() {
1202
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1203
- if (!options.interpolation) options.interpolation = {
1204
- escapeValue: true
1205
- };
1206
- const iOpts = options.interpolation;
1207
- this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
1208
- this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
1209
- this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
1210
- this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
1211
- this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
1212
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1213
- this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
1214
- this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
1215
- this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
1216
- this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
1217
- this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
1218
- this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
1219
- this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
1220
- this.resetRegExp();
1221
- }
1222
- reset() {
1223
- if (this.options) this.init(this.options);
1224
- }
1225
- resetRegExp() {
1226
- const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
1227
- this.regexp = new RegExp(regexpStr, 'g');
1228
- const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
1229
- this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
1230
- const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
1231
- this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
1232
- }
1233
- interpolate(str, data, lng, options) {
1234
- let match;
1235
- let value;
1236
- let replaces;
1237
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1238
- function regexSafe(val) {
1239
- return val.replace(/\$/g, '$$$$');
1240
- }
1241
- const handleFormat = key => {
1242
- if (key.indexOf(this.formatSeparator) < 0) {
1243
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1244
- return this.alwaysFormat ? this.format(path, undefined, lng, {
1245
- ...options,
1246
- ...data,
1247
- interpolationkey: key
1248
- }) : path;
1249
- }
1250
- const p = key.split(this.formatSeparator);
1251
- const k = p.shift().trim();
1252
- const f = p.join(this.formatSeparator).trim();
1253
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1254
- ...options,
1255
- ...data,
1256
- interpolationkey: k
1257
- });
1258
- };
1259
- this.resetRegExp();
1260
- const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
1261
- const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1262
- const todos = [{
1263
- regex: this.regexpUnescape,
1264
- safeValue: val => regexSafe(val)
1265
- }, {
1266
- regex: this.regexp,
1267
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1268
- }];
1269
- todos.forEach(todo => {
1270
- replaces = 0;
1271
- while (match = todo.regex.exec(str)) {
1272
- const matchedVar = match[1].trim();
1273
- value = handleFormat(matchedVar);
1274
- if (value === undefined) {
1275
- if (typeof missingInterpolationHandler === 'function') {
1276
- const temp = missingInterpolationHandler(str, match, options);
1277
- value = typeof temp === 'string' ? temp : '';
1278
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1279
- value = '';
1280
- } else if (skipOnVariables) {
1281
- value = match[0];
1282
- continue;
1283
- } else {
1284
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1285
- value = '';
1286
- }
1287
- } else if (typeof value !== 'string' && !this.useRawValueToEscape) {
1288
- value = makeString(value);
1289
- }
1290
- const safeValue = todo.safeValue(value);
1291
- str = str.replace(match[0], safeValue);
1292
- if (skipOnVariables) {
1293
- todo.regex.lastIndex += value.length;
1294
- todo.regex.lastIndex -= match[0].length;
1295
- } else {
1296
- todo.regex.lastIndex = 0;
1297
- }
1298
- replaces++;
1299
- if (replaces >= this.maxReplaces) {
1300
- break;
1301
- }
1302
- }
1303
- });
1304
- return str;
1305
- }
1306
- nest(str, fc) {
1307
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1308
- let match;
1309
- let value;
1310
- let clonedOptions;
1311
- function handleHasOptions(key, inheritedOptions) {
1312
- const sep = this.nestingOptionsSeparator;
1313
- if (key.indexOf(sep) < 0) return key;
1314
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1315
- let optionsString = `{${c[1]}`;
1316
- key = c[0];
1317
- optionsString = this.interpolate(optionsString, clonedOptions);
1318
- const matchedSingleQuotes = optionsString.match(/'/g);
1319
- const matchedDoubleQuotes = optionsString.match(/"/g);
1320
- if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1321
- optionsString = optionsString.replace(/'/g, '"');
1322
- }
1323
- try {
1324
- clonedOptions = JSON.parse(optionsString);
1325
- if (inheritedOptions) clonedOptions = {
1326
- ...inheritedOptions,
1327
- ...clonedOptions
1328
- };
1329
- } catch (e) {
1330
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1331
- return `${key}${sep}${optionsString}`;
1332
- }
1333
- delete clonedOptions.defaultValue;
1334
- return key;
1335
- }
1336
- while (match = this.nestingRegexp.exec(str)) {
1337
- let formatters = [];
1338
- clonedOptions = {
1339
- ...options
1340
- };
1341
- clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
1342
- clonedOptions.applyPostProcessor = false;
1343
- delete clonedOptions.defaultValue;
1344
- let doReduce = false;
1345
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1346
- const r = match[1].split(this.formatSeparator).map(elem => elem.trim());
1347
- match[1] = r.shift();
1348
- formatters = r;
1349
- doReduce = true;
1350
- }
1351
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1352
- if (value && match[0] === str && typeof value !== 'string') return value;
1353
- if (typeof value !== 'string') value = makeString(value);
1354
- if (!value) {
1355
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1356
- value = '';
1357
- }
1358
- if (doReduce) {
1359
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1360
- ...options,
1361
- interpolationkey: match[1].trim()
1362
- }), value.trim());
1363
- }
1364
- str = str.replace(match[0], value);
1365
- this.regexp.lastIndex = 0;
1366
- }
1367
- return str;
1368
- }
1369
- }
1370
-
1371
- function parseFormatStr(formatStr) {
1372
- let formatName = formatStr.toLowerCase().trim();
1373
- const formatOptions = {};
1374
- if (formatStr.indexOf('(') > -1) {
1375
- const p = formatStr.split('(');
1376
- formatName = p[0].toLowerCase().trim();
1377
- const optStr = p[1].substring(0, p[1].length - 1);
1378
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1379
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1380
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1381
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1382
- } else {
1383
- const opts = optStr.split(';');
1384
- opts.forEach(opt => {
1385
- if (!opt) return;
1386
- const [key, ...rest] = opt.split(':');
1387
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1388
- if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
1389
- if (val === 'false') formatOptions[key.trim()] = false;
1390
- if (val === 'true') formatOptions[key.trim()] = true;
1391
- if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
1392
- });
1393
- }
1394
- }
1395
- return {
1396
- formatName,
1397
- formatOptions
1398
- };
1399
- }
1400
- function createCachedFormatter(fn) {
1401
- const cache = {};
1402
- return function invokeFormatter(val, lng, options) {
1403
- const key = lng + JSON.stringify(options);
1404
- let formatter = cache[key];
1405
- if (!formatter) {
1406
- formatter = fn(getCleanedCode(lng), options);
1407
- cache[key] = formatter;
1408
- }
1409
- return formatter(val);
1410
- };
1411
- }
1412
- class Formatter {
1413
- constructor() {
1414
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1415
- this.logger = baseLogger.create('formatter');
1416
- this.options = options;
1417
- this.formats = {
1418
- number: createCachedFormatter((lng, opt) => {
1419
- const formatter = new Intl.NumberFormat(lng, {
1420
- ...opt
1421
- });
1422
- return val => formatter.format(val);
1423
- }),
1424
- currency: createCachedFormatter((lng, opt) => {
1425
- const formatter = new Intl.NumberFormat(lng, {
1426
- ...opt,
1427
- style: 'currency'
1428
- });
1429
- return val => formatter.format(val);
1430
- }),
1431
- datetime: createCachedFormatter((lng, opt) => {
1432
- const formatter = new Intl.DateTimeFormat(lng, {
1433
- ...opt
1434
- });
1435
- return val => formatter.format(val);
1436
- }),
1437
- relativetime: createCachedFormatter((lng, opt) => {
1438
- const formatter = new Intl.RelativeTimeFormat(lng, {
1439
- ...opt
1440
- });
1441
- return val => formatter.format(val, opt.range || 'day');
1442
- }),
1443
- list: createCachedFormatter((lng, opt) => {
1444
- const formatter = new Intl.ListFormat(lng, {
1445
- ...opt
1446
- });
1447
- return val => formatter.format(val);
1448
- })
1449
- };
1450
- this.init(options);
1451
- }
1452
- init(services) {
1453
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1454
- interpolation: {}
1455
- };
1456
- const iOpts = options.interpolation;
1457
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1458
- }
1459
- add(name, fc) {
1460
- this.formats[name.toLowerCase().trim()] = fc;
1461
- }
1462
- addCached(name, fc) {
1463
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1464
- }
1465
- format(value, format, lng) {
1466
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1467
- const formats = format.split(this.formatSeparator);
1468
- const result = formats.reduce((mem, f) => {
1469
- const {
1470
- formatName,
1471
- formatOptions
1472
- } = parseFormatStr(f);
1473
- if (this.formats[formatName]) {
1474
- let formatted = mem;
1475
- try {
1476
- const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
1477
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1478
- formatted = this.formats[formatName](mem, l, {
1479
- ...formatOptions,
1480
- ...options,
1481
- ...valOptions
1482
- });
1483
- } catch (error) {
1484
- this.logger.warn(error);
1485
- }
1486
- return formatted;
1487
- } else {
1488
- this.logger.warn(`there was no format function for ${formatName}`);
1489
- }
1490
- return mem;
1491
- }, value);
1492
- return result;
1493
- }
1494
- }
1495
-
1496
- function removePending(q, name) {
1497
- if (q.pending[name] !== undefined) {
1498
- delete q.pending[name];
1499
- q.pendingCount--;
1500
- }
1501
- }
1502
- class Connector extends EventEmitter {
1503
- constructor(backend, store, services) {
1504
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1505
- super();
1506
- this.backend = backend;
1507
- this.store = store;
1508
- this.services = services;
1509
- this.languageUtils = services.languageUtils;
1510
- this.options = options;
1511
- this.logger = baseLogger.create('backendConnector');
1512
- this.waitingReads = [];
1513
- this.maxParallelReads = options.maxParallelReads || 10;
1514
- this.readingCalls = 0;
1515
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1516
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1517
- this.state = {};
1518
- this.queue = [];
1519
- if (this.backend && this.backend.init) {
1520
- this.backend.init(services, options.backend, options);
1521
- }
1522
- }
1523
- queueLoad(languages, namespaces, options, callback) {
1524
- const toLoad = {};
1525
- const pending = {};
1526
- const toLoadLanguages = {};
1527
- const toLoadNamespaces = {};
1528
- languages.forEach(lng => {
1529
- let hasAllNamespaces = true;
1530
- namespaces.forEach(ns => {
1531
- const name = `${lng}|${ns}`;
1532
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1533
- this.state[name] = 2;
1534
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1535
- if (pending[name] === undefined) pending[name] = true;
1536
- } else {
1537
- this.state[name] = 1;
1538
- hasAllNamespaces = false;
1539
- if (pending[name] === undefined) pending[name] = true;
1540
- if (toLoad[name] === undefined) toLoad[name] = true;
1541
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1542
- }
1543
- });
1544
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1545
- });
1546
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1547
- this.queue.push({
1548
- pending,
1549
- pendingCount: Object.keys(pending).length,
1550
- loaded: {},
1551
- errors: [],
1552
- callback
1553
- });
1554
- }
1555
- return {
1556
- toLoad: Object.keys(toLoad),
1557
- pending: Object.keys(pending),
1558
- toLoadLanguages: Object.keys(toLoadLanguages),
1559
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1560
- };
1561
- }
1562
- loaded(name, err, data) {
1563
- const s = name.split('|');
1564
- const lng = s[0];
1565
- const ns = s[1];
1566
- if (err) this.emit('failedLoading', lng, ns, err);
1567
- if (data) {
1568
- this.store.addResourceBundle(lng, ns, data);
1569
- }
1570
- this.state[name] = err ? -1 : 2;
1571
- const loaded = {};
1572
- this.queue.forEach(q => {
1573
- pushPath(q.loaded, [lng], ns);
1574
- removePending(q, name);
1575
- if (err) q.errors.push(err);
1576
- if (q.pendingCount === 0 && !q.done) {
1577
- Object.keys(q.loaded).forEach(l => {
1578
- if (!loaded[l]) loaded[l] = {};
1579
- const loadedKeys = q.loaded[l];
1580
- if (loadedKeys.length) {
1581
- loadedKeys.forEach(n => {
1582
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1583
- });
1584
- }
1585
- });
1586
- q.done = true;
1587
- if (q.errors.length) {
1588
- q.callback(q.errors);
1589
- } else {
1590
- q.callback();
1591
- }
1592
- }
1593
- });
1594
- this.emit('loaded', loaded);
1595
- this.queue = this.queue.filter(q => !q.done);
1596
- }
1597
- read(lng, ns, fcName) {
1598
- let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1599
- let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
1600
- let callback = arguments.length > 5 ? arguments[5] : undefined;
1601
- if (!lng.length) return callback(null, {});
1602
- if (this.readingCalls >= this.maxParallelReads) {
1603
- this.waitingReads.push({
1604
- lng,
1605
- ns,
1606
- fcName,
1607
- tried,
1608
- wait,
1609
- callback
1610
- });
1611
- return;
1612
- }
1613
- this.readingCalls++;
1614
- const resolver = (err, data) => {
1615
- this.readingCalls--;
1616
- if (this.waitingReads.length > 0) {
1617
- const next = this.waitingReads.shift();
1618
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1619
- }
1620
- if (err && data && tried < this.maxRetries) {
1621
- setTimeout(() => {
1622
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1623
- }, wait);
1624
- return;
1625
- }
1626
- callback(err, data);
1627
- };
1628
- const fc = this.backend[fcName].bind(this.backend);
1629
- if (fc.length === 2) {
1630
- try {
1631
- const r = fc(lng, ns);
1632
- if (r && typeof r.then === 'function') {
1633
- r.then(data => resolver(null, data)).catch(resolver);
1634
- } else {
1635
- resolver(null, r);
1636
- }
1637
- } catch (err) {
1638
- resolver(err);
1639
- }
1640
- return;
1641
- }
1642
- return fc(lng, ns, resolver);
1643
- }
1644
- prepareLoading(languages, namespaces) {
1645
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1646
- let callback = arguments.length > 3 ? arguments[3] : undefined;
1647
- if (!this.backend) {
1648
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1649
- return callback && callback();
1650
- }
1651
- if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
1652
- if (typeof namespaces === 'string') namespaces = [namespaces];
1653
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1654
- if (!toLoad.toLoad.length) {
1655
- if (!toLoad.pending.length) callback();
1656
- return null;
1657
- }
1658
- toLoad.toLoad.forEach(name => {
1659
- this.loadOne(name);
1660
- });
1661
- }
1662
- load(languages, namespaces, callback) {
1663
- this.prepareLoading(languages, namespaces, {}, callback);
1664
- }
1665
- reload(languages, namespaces, callback) {
1666
- this.prepareLoading(languages, namespaces, {
1667
- reload: true
1668
- }, callback);
1669
- }
1670
- loadOne(name) {
1671
- let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
1672
- const s = name.split('|');
1673
- const lng = s[0];
1674
- const ns = s[1];
1675
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1676
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1677
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1678
- this.loaded(name, err, data);
1679
- });
1680
- }
1681
- saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
1682
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
1683
- let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};
1684
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
1685
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
1686
- return;
1687
- }
1688
- if (key === undefined || key === null || key === '') return;
1689
- if (this.backend && this.backend.create) {
1690
- const opts = {
1691
- ...options,
1692
- isUpdate
1693
- };
1694
- const fc = this.backend.create.bind(this.backend);
1695
- if (fc.length < 6) {
1696
- try {
1697
- let r;
1698
- if (fc.length === 5) {
1699
- r = fc(languages, namespace, key, fallbackValue, opts);
1700
- } else {
1701
- r = fc(languages, namespace, key, fallbackValue);
1702
- }
1703
- if (r && typeof r.then === 'function') {
1704
- r.then(data => clb(null, data)).catch(clb);
1705
- } else {
1706
- clb(null, r);
1707
- }
1708
- } catch (err) {
1709
- clb(err);
1710
- }
1711
- } else {
1712
- fc(languages, namespace, key, fallbackValue, clb, opts);
1713
- }
1714
- }
1715
- if (!languages || !languages[0]) return;
1716
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1717
- }
1718
- }
1719
-
1720
- function get() {
1721
- return {
1722
- debug: false,
1723
- initImmediate: true,
1724
- ns: ['translation'],
1725
- defaultNS: ['translation'],
1726
- fallbackLng: ['dev'],
1727
- fallbackNS: false,
1728
- supportedLngs: false,
1729
- nonExplicitSupportedLngs: false,
1730
- load: 'all',
1731
- preload: false,
1732
- simplifyPluralSuffix: true,
1733
- keySeparator: '.',
1734
- nsSeparator: ':',
1735
- pluralSeparator: '_',
1736
- contextSeparator: '_',
1737
- partialBundledLanguages: false,
1738
- saveMissing: false,
1739
- updateMissing: false,
1740
- saveMissingTo: 'fallback',
1741
- saveMissingPlurals: true,
1742
- missingKeyHandler: false,
1743
- missingInterpolationHandler: false,
1744
- postProcess: false,
1745
- postProcessPassResolved: false,
1746
- returnNull: false,
1747
- returnEmptyString: true,
1748
- returnObjects: false,
1749
- joinArrays: false,
1750
- returnedObjectHandler: false,
1751
- parseMissingKeyHandler: false,
1752
- appendNamespaceToMissingKey: false,
1753
- appendNamespaceToCIMode: false,
1754
- overloadTranslationOptionHandler: function handle(args) {
1755
- let ret = {};
1756
- if (typeof args[1] === 'object') ret = args[1];
1757
- if (typeof args[1] === 'string') ret.defaultValue = args[1];
1758
- if (typeof args[2] === 'string') ret.tDescription = args[2];
1759
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1760
- const options = args[3] || args[2];
1761
- Object.keys(options).forEach(key => {
1762
- ret[key] = options[key];
1763
- });
1764
- }
1765
- return ret;
1766
- },
1767
- interpolation: {
1768
- escapeValue: true,
1769
- format: (value, format, lng, options) => value,
1770
- prefix: '{{',
1771
- suffix: '}}',
1772
- formatSeparator: ',',
1773
- unescapePrefix: '-',
1774
- nestingPrefix: '$t(',
1775
- nestingSuffix: ')',
1776
- nestingOptionsSeparator: ',',
1777
- maxReplaces: 1000,
1778
- skipOnVariables: true
1779
- }
1780
- };
1781
- }
1782
- function transformOptions(options) {
1783
- if (typeof options.ns === 'string') options.ns = [options.ns];
1784
- if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
1785
- if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
1786
- if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
1787
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
1788
- }
1789
- return options;
1790
- }
1791
-
1792
- function noop() {}
1793
- function bindMemberFunctions(inst) {
1794
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1795
- mems.forEach(mem => {
1796
- if (typeof inst[mem] === 'function') {
1797
- inst[mem] = inst[mem].bind(inst);
1798
- }
1799
- });
1800
- }
1801
- class I18n extends EventEmitter {
1802
- constructor() {
1803
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1804
- let callback = arguments.length > 1 ? arguments[1] : undefined;
1805
- super();
1806
- this.options = transformOptions(options);
1807
- this.services = {};
1808
- this.logger = baseLogger;
1809
- this.modules = {
1810
- external: []
1811
- };
1812
- bindMemberFunctions(this);
1813
- if (callback && !this.isInitialized && !options.isClone) {
1814
- if (!this.options.initImmediate) {
1815
- this.init(options, callback);
1816
- return this;
1817
- }
1818
- setTimeout(() => {
1819
- this.init(options, callback);
1820
- }, 0);
1821
- }
1822
- }
1823
- init() {
1824
- var _this = this;
1825
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1826
- let callback = arguments.length > 1 ? arguments[1] : undefined;
1827
- if (typeof options === 'function') {
1828
- callback = options;
1829
- options = {};
1830
- }
1831
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
1832
- if (typeof options.ns === 'string') {
1833
- options.defaultNS = options.ns;
1834
- } else if (options.ns.indexOf('translation') < 0) {
1835
- options.defaultNS = options.ns[0];
1836
- }
1837
- }
1838
- const defOpts = get();
1839
- this.options = {
1840
- ...defOpts,
1841
- ...this.options,
1842
- ...transformOptions(options)
1843
- };
1844
- if (this.options.compatibilityAPI !== 'v1') {
1845
- this.options.interpolation = {
1846
- ...defOpts.interpolation,
1847
- ...this.options.interpolation
1848
- };
1849
- }
1850
- if (options.keySeparator !== undefined) {
1851
- this.options.userDefinedKeySeparator = options.keySeparator;
1852
- }
1853
- if (options.nsSeparator !== undefined) {
1854
- this.options.userDefinedNsSeparator = options.nsSeparator;
1855
- }
1856
- function createClassOnDemand(ClassOrObject) {
1857
- if (!ClassOrObject) return null;
1858
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
1859
- return ClassOrObject;
1860
- }
1861
- if (!this.options.isClone) {
1862
- if (this.modules.logger) {
1863
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1864
- } else {
1865
- baseLogger.init(null, this.options);
1866
- }
1867
- let formatter;
1868
- if (this.modules.formatter) {
1869
- formatter = this.modules.formatter;
1870
- } else if (typeof Intl !== 'undefined') {
1871
- formatter = Formatter;
1872
- }
1873
- const lu = new LanguageUtil(this.options);
1874
- this.store = new ResourceStore(this.options.resources, this.options);
1875
- const s = this.services;
1876
- s.logger = baseLogger;
1877
- s.resourceStore = this.store;
1878
- s.languageUtils = lu;
1879
- s.pluralResolver = new PluralResolver(lu, {
1880
- prepend: this.options.pluralSeparator,
1881
- compatibilityJSON: this.options.compatibilityJSON,
1882
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1883
- });
1884
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1885
- s.formatter = createClassOnDemand(formatter);
1886
- s.formatter.init(s, this.options);
1887
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1888
- }
1889
- s.interpolator = new Interpolator(this.options);
1890
- s.utils = {
1891
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1892
- };
1893
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1894
- s.backendConnector.on('*', function (event) {
1895
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1896
- args[_key - 1] = arguments[_key];
1897
- }
1898
- _this.emit(event, ...args);
1899
- });
1900
- if (this.modules.languageDetector) {
1901
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1902
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1903
- }
1904
- if (this.modules.i18nFormat) {
1905
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1906
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1907
- }
1908
- this.translator = new Translator(this.services, this.options);
1909
- this.translator.on('*', function (event) {
1910
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1911
- args[_key2 - 1] = arguments[_key2];
1912
- }
1913
- _this.emit(event, ...args);
1914
- });
1915
- this.modules.external.forEach(m => {
1916
- if (m.init) m.init(this);
1917
- });
1918
- }
1919
- this.format = this.options.interpolation.format;
1920
- if (!callback) callback = noop;
1921
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1922
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1923
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1924
- }
1925
- if (!this.services.languageDetector && !this.options.lng) {
1926
- this.logger.warn('init: no languageDetector is used and no lng is defined');
1927
- }
1928
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1929
- storeApi.forEach(fcName => {
1930
- this[fcName] = function () {
1931
- return _this.store[fcName](...arguments);
1932
- };
1933
- });
1934
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1935
- storeApiChained.forEach(fcName => {
1936
- this[fcName] = function () {
1937
- _this.store[fcName](...arguments);
1938
- return _this;
1939
- };
1940
- });
1941
- const deferred = defer();
1942
- const load = () => {
1943
- const finish = (err, t) => {
1944
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1945
- this.isInitialized = true;
1946
- if (!this.options.isClone) this.logger.log('initialized', this.options);
1947
- this.emit('initialized', this.options);
1948
- deferred.resolve(t);
1949
- callback(err, t);
1950
- };
1951
- if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));
1952
- this.changeLanguage(this.options.lng, finish);
1953
- };
1954
- if (this.options.resources || !this.options.initImmediate) {
1955
- load();
1956
- } else {
1957
- setTimeout(load, 0);
1958
- }
1959
- return deferred;
1960
- }
1961
- loadResources(language) {
1962
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
1963
- let usedCallback = callback;
1964
- const usedLng = typeof language === 'string' ? language : this.language;
1965
- if (typeof language === 'function') usedCallback = language;
1966
- if (!this.options.resources || this.options.partialBundledLanguages) {
1967
- if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
1968
- const toLoad = [];
1969
- const append = lng => {
1970
- if (!lng) return;
1971
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1972
- lngs.forEach(l => {
1973
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1974
- });
1975
- };
1976
- if (!usedLng) {
1977
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1978
- fallbacks.forEach(l => append(l));
1979
- } else {
1980
- append(usedLng);
1981
- }
1982
- if (this.options.preload) {
1983
- this.options.preload.forEach(l => append(l));
1984
- }
1985
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
1986
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1987
- usedCallback(e);
1988
- });
1989
- } else {
1990
- usedCallback(null);
1991
- }
1992
- }
1993
- reloadResources(lngs, ns, callback) {
1994
- const deferred = defer();
1995
- if (!lngs) lngs = this.languages;
1996
- if (!ns) ns = this.options.ns;
1997
- if (!callback) callback = noop;
1998
- this.services.backendConnector.reload(lngs, ns, err => {
1999
- deferred.resolve();
2000
- callback(err);
2001
- });
2002
- return deferred;
2003
- }
2004
- use(module) {
2005
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2006
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2007
- if (module.type === 'backend') {
2008
- this.modules.backend = module;
2009
- }
2010
- if (module.type === 'logger' || module.log && module.warn && module.error) {
2011
- this.modules.logger = module;
2012
- }
2013
- if (module.type === 'languageDetector') {
2014
- this.modules.languageDetector = module;
2015
- }
2016
- if (module.type === 'i18nFormat') {
2017
- this.modules.i18nFormat = module;
2018
- }
2019
- if (module.type === 'postProcessor') {
2020
- postProcessor.addPostProcessor(module);
2021
- }
2022
- if (module.type === 'formatter') {
2023
- this.modules.formatter = module;
2024
- }
2025
- if (module.type === '3rdParty') {
2026
- this.modules.external.push(module);
2027
- }
2028
- return this;
2029
- }
2030
- setResolvedLanguage(l) {
2031
- if (!l || !this.languages) return;
2032
- if (['cimode', 'dev'].indexOf(l) > -1) return;
2033
- for (let li = 0; li < this.languages.length; li++) {
2034
- const lngInLngs = this.languages[li];
2035
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2036
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2037
- this.resolvedLanguage = lngInLngs;
2038
- break;
2039
- }
2040
- }
2041
- }
2042
- changeLanguage(lng, callback) {
2043
- var _this2 = this;
2044
- this.isLanguageChangingTo = lng;
2045
- const deferred = defer();
2046
- this.emit('languageChanging', lng);
2047
- const setLngProps = l => {
2048
- this.language = l;
2049
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2050
- this.resolvedLanguage = undefined;
2051
- this.setResolvedLanguage(l);
2052
- };
2053
- const done = (err, l) => {
2054
- if (l) {
2055
- setLngProps(l);
2056
- this.translator.changeLanguage(l);
2057
- this.isLanguageChangingTo = undefined;
2058
- this.emit('languageChanged', l);
2059
- this.logger.log('languageChanged', l);
2060
- } else {
2061
- this.isLanguageChangingTo = undefined;
2062
- }
2063
- deferred.resolve(function () {
2064
- return _this2.t(...arguments);
2065
- });
2066
- if (callback) callback(err, function () {
2067
- return _this2.t(...arguments);
2068
- });
2069
- };
2070
- const setLng = lngs => {
2071
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2072
- const l = typeof lngs === 'string' ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
2073
- if (l) {
2074
- if (!this.language) {
2075
- setLngProps(l);
2076
- }
2077
- if (!this.translator.language) this.translator.changeLanguage(l);
2078
- if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
2079
- }
2080
- this.loadResources(l, err => {
2081
- done(err, l);
2082
- });
2083
- };
2084
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2085
- setLng(this.services.languageDetector.detect());
2086
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2087
- if (this.services.languageDetector.detect.length === 0) {
2088
- this.services.languageDetector.detect().then(setLng);
2089
- } else {
2090
- this.services.languageDetector.detect(setLng);
2091
- }
2092
- } else {
2093
- setLng(lng);
2094
- }
2095
- return deferred;
2096
- }
2097
- getFixedT(lng, ns, keyPrefix) {
2098
- var _this3 = this;
2099
- const fixedT = function (key, opts) {
2100
- let options;
2101
- if (typeof opts !== 'object') {
2102
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2103
- rest[_key3 - 2] = arguments[_key3];
2104
- }
2105
- options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2106
- } else {
2107
- options = {
2108
- ...opts
2109
- };
2110
- }
2111
- options.lng = options.lng || fixedT.lng;
2112
- options.lngs = options.lngs || fixedT.lngs;
2113
- options.ns = options.ns || fixedT.ns;
2114
- options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2115
- const keySeparator = _this3.options.keySeparator || '.';
2116
- let resultKey;
2117
- if (options.keyPrefix && Array.isArray(key)) {
2118
- resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);
2119
- } else {
2120
- resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
2121
- }
2122
- return _this3.t(resultKey, options);
2123
- };
2124
- if (typeof lng === 'string') {
2125
- fixedT.lng = lng;
2126
- } else {
2127
- fixedT.lngs = lng;
2128
- }
2129
- fixedT.ns = ns;
2130
- fixedT.keyPrefix = keyPrefix;
2131
- return fixedT;
2132
- }
2133
- t() {
2134
- return this.translator && this.translator.translate(...arguments);
2135
- }
2136
- exists() {
2137
- return this.translator && this.translator.exists(...arguments);
2138
- }
2139
- setDefaultNamespace(ns) {
2140
- this.options.defaultNS = ns;
2141
- }
2142
- hasLoadedNamespace(ns) {
2143
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2144
- if (!this.isInitialized) {
2145
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2146
- return false;
2147
- }
2148
- if (!this.languages || !this.languages.length) {
2149
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2150
- return false;
2151
- }
2152
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2153
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2154
- const lastLng = this.languages[this.languages.length - 1];
2155
- if (lng.toLowerCase() === 'cimode') return true;
2156
- const loadNotPending = (l, n) => {
2157
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2158
- return loadState === -1 || loadState === 2;
2159
- };
2160
- if (options.precheck) {
2161
- const preResult = options.precheck(this, loadNotPending);
2162
- if (preResult !== undefined) return preResult;
2163
- }
2164
- if (this.hasResourceBundle(lng, ns)) return true;
2165
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2166
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2167
- return false;
2168
- }
2169
- loadNamespaces(ns, callback) {
2170
- const deferred = defer();
2171
- if (!this.options.ns) {
2172
- if (callback) callback();
2173
- return Promise.resolve();
2174
- }
2175
- if (typeof ns === 'string') ns = [ns];
2176
- ns.forEach(n => {
2177
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2178
- });
2179
- this.loadResources(err => {
2180
- deferred.resolve();
2181
- if (callback) callback(err);
2182
- });
2183
- return deferred;
2184
- }
2185
- loadLanguages(lngs, callback) {
2186
- const deferred = defer();
2187
- if (typeof lngs === 'string') lngs = [lngs];
2188
- const preloaded = this.options.preload || [];
2189
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0);
2190
- if (!newLngs.length) {
2191
- if (callback) callback();
2192
- return Promise.resolve();
2193
- }
2194
- this.options.preload = preloaded.concat(newLngs);
2195
- this.loadResources(err => {
2196
- deferred.resolve();
2197
- if (callback) callback(err);
2198
- });
2199
- return deferred;
2200
- }
2201
- dir(lng) {
2202
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
2203
- if (!lng) return 'rtl';
2204
- const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
2205
- const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
2206
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2207
- }
2208
- static createInstance() {
2209
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2210
- let callback = arguments.length > 1 ? arguments[1] : undefined;
2211
- return new I18n(options, callback);
2212
- }
2213
- cloneInstance() {
2214
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2215
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2216
- const forkResourceStore = options.forkResourceStore;
2217
- if (forkResourceStore) delete options.forkResourceStore;
2218
- const mergedOptions = {
2219
- ...this.options,
2220
- ...options,
2221
- ...{
2222
- isClone: true
2223
- }
2224
- };
2225
- const clone = new I18n(mergedOptions);
2226
- if (options.debug !== undefined || options.prefix !== undefined) {
2227
- clone.logger = clone.logger.clone(options);
2228
- }
2229
- const membersToCopy = ['store', 'services', 'language'];
2230
- membersToCopy.forEach(m => {
2231
- clone[m] = this[m];
2232
- });
2233
- clone.services = {
2234
- ...this.services
2235
- };
2236
- clone.services.utils = {
2237
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2238
- };
2239
- if (forkResourceStore) {
2240
- clone.store = new ResourceStore(this.store.data, mergedOptions);
2241
- clone.services.resourceStore = clone.store;
2242
- }
2243
- clone.translator = new Translator(clone.services, mergedOptions);
2244
- clone.translator.on('*', function (event) {
2245
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
2246
- args[_key4 - 1] = arguments[_key4];
2247
- }
2248
- clone.emit(event, ...args);
2249
- });
2250
- clone.init(mergedOptions, callback);
2251
- clone.translator.options = mergedOptions;
2252
- clone.translator.backendConnector.services.utils = {
2253
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2254
- };
2255
- return clone;
2256
- }
2257
- toJSON() {
2258
- return {
2259
- options: this.options,
2260
- store: this.store,
2261
- language: this.language,
2262
- languages: this.languages,
2263
- resolvedLanguage: this.resolvedLanguage
2264
- };
2265
- }
2266
- }
2267
- const instance = I18n.createInstance();
2268
- instance.createInstance = I18n.createInstance;
2269
-
2270
- instance.createInstance;
2271
- instance.dir;
2272
- instance.init;
2273
- instance.loadResources;
2274
- instance.reloadResources;
2275
- instance.use;
2276
- instance.changeLanguage;
2277
- instance.getFixedT;
2278
- instance.t;
2279
- instance.exists;
2280
- instance.setDefaultNamespace;
2281
- instance.hasLoadedNamespace;
2282
- instance.loadNamespaces;
2283
- instance.loadLanguages;
2284
-
2285
- function warn() {
2286
- if (console && console.warn) {
2287
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2288
- args[_key] = arguments[_key];
2289
- }
2290
- if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`;
2291
- console.warn(...args);
2292
- }
2293
- }
2294
- const alreadyWarned = {};
2295
- function warnOnce() {
2296
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
2297
- args[_key2] = arguments[_key2];
2298
- }
2299
- if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
2300
- if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
2301
- warn(...args);
2302
- }
2303
- const loadedClb = (i18n, cb) => () => {
2304
- if (i18n.isInitialized) {
2305
- cb();
2306
- } else {
2307
- const initialized = () => {
2308
- setTimeout(() => {
2309
- i18n.off('initialized', initialized);
2310
- }, 0);
2311
- cb();
2312
- };
2313
- i18n.on('initialized', initialized);
2314
- }
2315
- };
2316
- function loadNamespaces(i18n, ns, cb) {
2317
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
2318
- }
2319
- function loadLanguages(i18n, lng, ns, cb) {
2320
- if (typeof ns === 'string') ns = [ns];
2321
- ns.forEach(n => {
2322
- if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
2323
- });
2324
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
2325
- }
2326
- function oldI18nextHasLoadedNamespace(ns, i18n) {
2327
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2328
- const lng = i18n.languages[0];
2329
- const fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
2330
- const lastLng = i18n.languages[i18n.languages.length - 1];
2331
- if (lng.toLowerCase() === 'cimode') return true;
2332
- const loadNotPending = (l, n) => {
2333
- const loadState = i18n.services.backendConnector.state[`${l}|${n}`];
2334
- return loadState === -1 || loadState === 2;
2335
- };
2336
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
2337
- if (i18n.hasResourceBundle(lng, ns)) return true;
2338
- if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
2339
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2340
- return false;
2341
- }
2342
- function hasLoadedNamespace(ns, i18n) {
2343
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2344
- if (!i18n.languages || !i18n.languages.length) {
2345
- warnOnce('i18n.languages were undefined or empty', i18n.languages);
2346
- return true;
2347
- }
2348
- const isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;
2349
- if (!isNewerI18next) {
2350
- return oldI18nextHasLoadedNamespace(ns, i18n, options);
2351
- }
2352
- return i18n.hasLoadedNamespace(ns, {
2353
- lng: options.lng,
2354
- precheck: (i18nInstance, loadNotPending) => {
2355
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
2356
- }
2357
- });
2358
- }
2359
-
2360
- const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
2361
- const htmlEntities = {
2362
- '&amp;': '&',
2363
- '&#38;': '&',
2364
- '&lt;': '<',
2365
- '&#60;': '<',
2366
- '&gt;': '>',
2367
- '&#62;': '>',
2368
- '&apos;': "'",
2369
- '&#39;': "'",
2370
- '&quot;': '"',
2371
- '&#34;': '"',
2372
- '&nbsp;': ' ',
2373
- '&#160;': ' ',
2374
- '&copy;': '©',
2375
- '&#169;': '©',
2376
- '&reg;': '®',
2377
- '&#174;': '®',
2378
- '&hellip;': '…',
2379
- '&#8230;': '…',
2380
- '&#x2F;': '/',
2381
- '&#47;': '/'
2382
- };
2383
- const unescapeHtmlEntity = m => htmlEntities[m];
2384
- const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
2385
-
2386
- let defaultOptions = {
2387
- bindI18n: 'languageChanged',
2388
- bindI18nStore: '',
2389
- transEmptyNodeValue: '',
2390
- transSupportBasicHtmlNodes: true,
2391
- transWrapTextNodes: '',
2392
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
2393
- useSuspense: true,
2394
- unescape
2395
- };
2396
- function setDefaults() {
2397
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2398
- defaultOptions = {
2399
- ...defaultOptions,
2400
- ...options
2401
- };
2402
- }
2403
- function getDefaults() {
2404
- return defaultOptions;
2405
- }
2406
-
2407
- let i18nInstance;
2408
- function setI18n(instance) {
2409
- i18nInstance = instance;
2410
- }
2411
- function getI18n() {
2412
- return i18nInstance;
2413
- }
2414
-
2415
- const initReactI18next = {
2416
- type: '3rdParty',
2417
- init(instance) {
2418
- setDefaults(instance.options.react);
2419
- setI18n(instance);
2420
- }
2421
- };
2422
-
2423
- const I18nContext = createContext();
2424
- class ReportNamespaces {
2425
- constructor() {
2426
- this.usedNamespaces = {};
2427
- }
2428
- addUsedNamespaces(namespaces) {
2429
- namespaces.forEach(ns => {
2430
- if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
2431
- });
2432
- }
2433
- getUsedNamespaces() {
2434
- return Object.keys(this.usedNamespaces);
2435
- }
2436
- }
2437
-
2438
- const usePrevious = (value, ignore) => {
2439
- const ref = useRef();
2440
- useEffect(() => {
2441
- ref.current = ignore ? ref.current : value;
2442
- }, [value, ignore]);
2443
- return ref.current;
2444
- };
2445
- function useTranslation(ns) {
2446
- let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2447
- const {
2448
- i18n: i18nFromProps
2449
- } = props;
2450
- const {
2451
- i18n: i18nFromContext,
2452
- defaultNS: defaultNSFromContext
2453
- } = useContext(I18nContext) || {};
2454
- const i18n = i18nFromProps || i18nFromContext || getI18n();
2455
- if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
2456
- if (!i18n) {
2457
- warnOnce('You will need to pass in an i18next instance by using initReactI18next');
2458
- const notReadyT = (k, optsOrDefaultValue) => {
2459
- if (typeof optsOrDefaultValue === 'string') return optsOrDefaultValue;
2460
- if (optsOrDefaultValue && typeof optsOrDefaultValue === 'object' && typeof optsOrDefaultValue.defaultValue === 'string') return optsOrDefaultValue.defaultValue;
2461
- return Array.isArray(k) ? k[k.length - 1] : k;
2462
- };
2463
- const retNotReady = [notReadyT, {}, false];
2464
- retNotReady.t = notReadyT;
2465
- retNotReady.i18n = {};
2466
- retNotReady.ready = false;
2467
- return retNotReady;
2468
- }
2469
- if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
2470
- const i18nOptions = {
2471
- ...getDefaults(),
2472
- ...i18n.options.react,
2473
- ...props
2474
- };
2475
- const {
2476
- useSuspense,
2477
- keyPrefix
2478
- } = i18nOptions;
2479
- let namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
2480
- namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
2481
- if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
2482
- const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
2483
- function getT() {
2484
- return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
2485
- }
2486
- const [t, setT] = useState(getT);
2487
- let joinedNS = namespaces.join();
2488
- if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
2489
- const previousJoinedNS = usePrevious(joinedNS);
2490
- const isMounted = useRef(true);
2491
- useEffect(() => {
2492
- const {
2493
- bindI18n,
2494
- bindI18nStore
2495
- } = i18nOptions;
2496
- isMounted.current = true;
2497
- if (!ready && !useSuspense) {
2498
- if (props.lng) {
2499
- loadLanguages(i18n, props.lng, namespaces, () => {
2500
- if (isMounted.current) setT(getT);
2501
- });
2502
- } else {
2503
- loadNamespaces(i18n, namespaces, () => {
2504
- if (isMounted.current) setT(getT);
2505
- });
2506
- }
2507
- }
2508
- if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
2509
- setT(getT);
2510
- }
2511
- function boundReset() {
2512
- if (isMounted.current) setT(getT);
2513
- }
2514
- if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
2515
- if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
2516
- return () => {
2517
- isMounted.current = false;
2518
- if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset));
2519
- if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
2520
- };
2521
- }, [i18n, joinedNS]);
2522
- const isInitial = useRef(true);
2523
- useEffect(() => {
2524
- if (isMounted.current && !isInitial.current) {
2525
- setT(getT);
2526
- }
2527
- isInitial.current = false;
2528
- }, [i18n, keyPrefix]);
2529
- const ret = [t, i18n, ready];
2530
- ret.t = t;
2531
- ret.i18n = i18n;
2532
- ret.ready = ready;
2533
- if (ready) return ret;
2534
- if (!ready && !useSuspense) return ret;
2535
- throw new Promise(resolve => {
2536
- if (props.lng) {
2537
- loadLanguages(i18n, props.lng, namespaces, () => resolve());
2538
- } else {
2539
- loadNamespaces(i18n, namespaces, () => resolve());
2540
- }
2541
- });
2542
- }
2543
-
2544
- var welcomeScreen = "Welcome to neeto wheel nano";
2545
- var errors = {
2546
- invalidEmailAddress: "Please enter a valid email address",
2547
- sendFromRequired: "'Send from' email address is required",
2548
- sendToRequired: "'Send to' email address is required",
2549
- subjectRequired: "Subject is required",
2550
- messageRequired: "Message is required"
2551
- };
2552
- var emailNotification = {
2553
- title: "Email notification",
2554
- subTitle: "Send an email notification when a new event occurred"
2555
- };
2556
- var en = {
2557
- welcomeScreen: welcomeScreen,
2558
- errors: errors,
2559
- emailNotification: emailNotification
2560
- };
2561
-
2562
- instance.use(initReactI18next).init({
2563
- resources: {
2564
- en: {
2565
- translation: en
2566
- }
2567
- },
2568
- fallbackLng: "en"
2569
- });
2570
-
2571
17
  function _extends() {
2572
18
  _extends = Object.assign ? Object.assign.bind() : function (target) {
2573
19
  for (var i = 1; i < arguments.length; i++) {
@@ -2583,14 +29,14 @@ function _extends() {
2583
29
  return _extends.apply(this, arguments);
2584
30
  }
2585
31
 
2586
- function _typeof(obj) {
32
+ function _typeof(o) {
2587
33
  "@babel/helpers - typeof";
2588
34
 
2589
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
2590
- return typeof obj;
2591
- } : function (obj) {
2592
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
2593
- }, _typeof(obj);
35
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
36
+ return typeof o;
37
+ } : function (o) {
38
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
39
+ }, _typeof(o);
2594
40
  }
2595
41
 
2596
42
  function _toPrimitive(input, hint) {
@@ -2653,14 +99,13 @@ var useFetchEmailNotifications = function useFetchEmailNotifications(params) {
2653
99
  });
2654
100
  };
2655
101
  var useUpdateEmailNotification = function useUpdateEmailNotification() {
2656
- var queryClient = useQueryClient();
2657
- return useMutation(function (params) {
102
+ return useMutationWithInvalidation(function (params) {
2658
103
  return emailNotificationsApi.update(params);
2659
104
  }, {
2660
- onSuccess: function onSuccess(_, _ref) {
105
+ keysToInvalidate: [function (_, _ref) {
2661
106
  var notificationHolderId = _ref.notificationHolderId;
2662
- return queryClient.invalidateQueries([QUERY_KEYS.NEETO_EMAIL_NOTIFICATIONS, notificationHolderId]);
2663
- }
107
+ return [QUERY_KEYS.NEETO_EMAIL_NOTIFICATIONS, notificationHolderId];
108
+ }]
2664
109
  });
2665
110
  };
2666
111
 
@@ -2699,8 +144,8 @@ function _objectWithoutProperties(source, excluded) {
2699
144
 
2700
145
  var _excluded = ["notifyEmails", "notifyCcEmails", "notifyBccEmails", "replyToId", "customFields"],
2701
146
  _excluded2 = ["id", "isEnabled", "sendTo", "sendToCc", "sendToBcc", "showCopyEmails", "replyTo", "message", "subject", "sendFrom"];
2702
- 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; }
2703
- 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(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; }
147
+ function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
148
+ function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2704
149
  var isValidEmail = function isValidEmail(email) {
2705
150
  return string().email().isValidSync(email);
2706
151
  };
@@ -2769,8 +214,8 @@ var renderText = function renderText(text, fallbackTranslation) {
2769
214
  return isEmpty(text) ? fallbackTranslation : text;
2770
215
  };
2771
216
 
2772
- 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; }
2773
- 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; }
217
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
218
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2774
219
  var NeetoEmailNotificationForm = function NeetoEmailNotificationForm(_ref) {
2775
220
  var _ref$emailNotificatio = _ref.emailNotificationParams,
2776
221
  emailNotificationParams = _ref$emailNotificatio === void 0 ? {} : _ref$emailNotificatio,
@@ -2789,7 +234,7 @@ var NeetoEmailNotificationForm = function NeetoEmailNotificationForm(_ref) {
2789
234
  _ref$tooltipProps = _ref.tooltipProps,
2790
235
  tooltipProps = _ref$tooltipProps === void 0 ? {} : _ref$tooltipProps,
2791
236
  _ref$onSuccess = _ref.onSuccess,
2792
- onSuccess = _ref$onSuccess === void 0 ? noop$1 : _ref$onSuccess,
237
+ onSuccess = _ref$onSuccess === void 0 ? noop : _ref$onSuccess,
2793
238
  children = _ref.children;
2794
239
  var _useTranslation = useTranslation(),
2795
240
  t = _useTranslation.t;
@@ -2824,7 +269,7 @@ var NeetoEmailNotificationForm = function NeetoEmailNotificationForm(_ref) {
2824
269
  }, emailFormikProps), function (_ref2) {
2825
270
  var values = _ref2.values;
2826
271
  return /*#__PURE__*/React.createElement("div", {
2827
- className: "grid grid-cols-2 items-stretch gap-8"
272
+ className: "grid grid-cols-1 items-stretch gap-10 lg:grid-cols-2 lg:gap-6 xl:gap-8"
2828
273
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
2829
274
  className: "flex items-center justify-between gap-6"
2830
275
  }, /*#__PURE__*/React.createElement("div", {
@@ -2835,31 +280,38 @@ var NeetoEmailNotificationForm = function NeetoEmailNotificationForm(_ref) {
2835
280
  }, tooltipProps), /*#__PURE__*/React.createElement("div", {
2836
281
  className: "flex items-center gap-2"
2837
282
  }, /*#__PURE__*/React.createElement(Switch, {
2838
- "data-cy": "receive-email-notification-switch",
2839
283
  disabled: disabled,
284
+ "data-cy": "receive-email-notification-switch",
2840
285
  name: "isEnabled"
2841
286
  }), /*#__PURE__*/React.createElement(Typography, {
2842
287
  component: "span",
2843
288
  "data-cy": "receive-email-notification-label",
2844
289
  lineHeight: "normal",
2845
- style: "h2",
290
+ style: "h3",
2846
291
  weight: "semibold"
2847
- }, renderText(title, t("emailNotification.title"))))), /*#__PURE__*/React.createElement(Typography, {
292
+ }, renderText(title, t("neetoEmailNotifications.emailNotification.title"))))), /*#__PURE__*/React.createElement(Typography, {
2848
293
  lineHeight: "normal",
2849
294
  style: "body2"
2850
- }, renderText(subTitle, t("emailNotification.subTitle"))))), values.isEnabled && children, /*#__PURE__*/React.createElement(EmailForm, _extends({
295
+ }, renderText(subTitle, t("neetoEmailNotifications.emailNotification.subTitle"))))), values.isEnabled && children, /*#__PURE__*/React.createElement(EmailForm, _extends({
2851
296
  showSendToField: true,
2852
297
  className: classNames({
2853
298
  "pt-3 ": values.isEnabled
2854
299
  }),
2855
300
  isLoading: isSubmitting,
2856
301
  showFields: values.isEnabled
2857
- }, emailFormProps))), values.isEnabled && /*#__PURE__*/React.createElement(EmailPreview, _extends({
302
+ }, emailFormProps))), /*#__PURE__*/React.createElement("div", {
303
+ className: "flex flex-col"
304
+ }, /*#__PURE__*/React.createElement(Typography, {
305
+ className: "mb-3 block lg:hidden",
306
+ lineHeight: "normal",
307
+ style: "h3",
308
+ weight: "semibold"
309
+ }, t("neetoEmailNotifications.preview")), values.isEnabled && /*#__PURE__*/React.createElement(EmailPreview, _extends({
2858
310
  body: values.message,
2859
311
  from: values.sendFrom,
2860
312
  subject: values.subject,
2861
313
  to: pluck("value", values.sendTo)
2862
- }, emailPreviewProps)));
314
+ }, emailPreviewProps))));
2863
315
  }));
2864
316
  };
2865
317