@bigbinary/neeto-message-templates-frontend 0.3.5 → 0.3.6

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,13 +1,15 @@
1
- import React, { useContext, useState, useRef, useEffect } from 'react';
2
- import { isNotEmpty, noop as noop$1, renameKeys, findBy, capitalize as capitalize$1, nullSafe } from '@bigbinary/neeto-commons-frontend/pure';
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { isNotEmpty, noop, renameKeys, findBy, capitalize, nullSafe } from '@bigbinary/neeto-cist';
3
3
  import { buildFiltersFromURL, Bar } from '@bigbinary/neeto-filters-frontend';
4
4
  import Container from '@bigbinary/neeto-molecules/Container';
5
5
  import NeetoHeader from '@bigbinary/neeto-molecules/Header';
6
6
  import SubHeader from '@bigbinary/neeto-molecules/SubHeader';
7
7
  import { Dropdown, Typography, Button, Pane, Table, NoData, Alert, Select, Textarea } from '@bigbinary/neetoui';
8
8
  import { isEmpty, prop, equals, includes, pick, omit, assoc, mergeAll, pluck } from 'ramda';
9
+ import { t } from 'i18next';
9
10
  import { MenuHorizontal } from '@bigbinary/neeto-icons';
10
- import { DEFAULT_PAGE_INDEX } from '@bigbinary/neeto-commons-frontend/constants';
11
+ import { useTranslation, Trans } from 'react-i18next';
12
+ import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_INDEX } from '@bigbinary/neeto-commons-frontend/constants';
11
13
  import { useMutationWithInvalidation, withImmutableActions } from '@bigbinary/neeto-commons-frontend/react-utils';
12
14
  import { useQuery } from 'react-query';
13
15
  import axios from 'axios';
@@ -29,3489 +31,39 @@ function _typeof$1(obj) {
29
31
  }, _typeof$1(obj);
30
32
  }
31
33
 
32
- function _classCallCheck(instance, Constructor) {
33
- if (!(instance instanceof Constructor)) {
34
- throw new TypeError("Cannot call a class as a function");
35
- }
36
- }
37
-
38
- function _toPrimitive(input, hint) {
39
- if (_typeof$1(input) !== "object" || input === null) return input;
40
- var prim = input[Symbol.toPrimitive];
41
- if (prim !== undefined) {
42
- var res = prim.call(input, hint || "default");
43
- if (_typeof$1(res) !== "object") return res;
44
- throw new TypeError("@@toPrimitive must return a primitive value.");
45
- }
46
- return (hint === "string" ? String : Number)(input);
47
- }
48
-
49
- function _toPropertyKey(arg) {
50
- var key = _toPrimitive(arg, "string");
51
- return _typeof$1(key) === "symbol" ? key : String(key);
52
- }
53
-
54
- function _defineProperties(target, props) {
55
- for (var i = 0; i < props.length; i++) {
56
- var descriptor = props[i];
57
- descriptor.enumerable = descriptor.enumerable || false;
58
- descriptor.configurable = true;
59
- if ("value" in descriptor) descriptor.writable = true;
60
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
61
- }
62
- }
63
- function _createClass(Constructor, protoProps, staticProps) {
64
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
65
- if (staticProps) _defineProperties(Constructor, staticProps);
66
- Object.defineProperty(Constructor, "prototype", {
67
- writable: false
68
- });
69
- return Constructor;
70
- }
71
-
72
- function _assertThisInitialized(self) {
73
- if (self === void 0) {
74
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
75
- }
76
- return self;
77
- }
78
-
79
- function _setPrototypeOf(o, p) {
80
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
81
- o.__proto__ = p;
82
- return o;
83
- };
84
- return _setPrototypeOf(o, p);
85
- }
86
-
87
- function _inherits(subClass, superClass) {
88
- if (typeof superClass !== "function" && superClass !== null) {
89
- throw new TypeError("Super expression must either be null or a function");
90
- }
91
- subClass.prototype = Object.create(superClass && superClass.prototype, {
92
- constructor: {
93
- value: subClass,
94
- writable: true,
95
- configurable: true
96
- }
97
- });
98
- Object.defineProperty(subClass, "prototype", {
99
- writable: false
100
- });
101
- if (superClass) _setPrototypeOf(subClass, superClass);
102
- }
103
-
104
- function _possibleConstructorReturn(self, call) {
105
- if (call && (_typeof$1(call) === "object" || typeof call === "function")) {
106
- return call;
107
- } else if (call !== void 0) {
108
- throw new TypeError("Derived constructors may only return object or undefined");
109
- }
110
- return _assertThisInitialized(self);
111
- }
112
-
113
- function _getPrototypeOf(o) {
114
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
115
- return o.__proto__ || Object.getPrototypeOf(o);
116
- };
117
- return _getPrototypeOf(o);
118
- }
119
-
120
- function _defineProperty(obj, key, value) {
121
- key = _toPropertyKey(key);
122
- if (key in obj) {
123
- Object.defineProperty(obj, key, {
124
- value: value,
125
- enumerable: true,
126
- configurable: true,
127
- writable: true
128
- });
129
- } else {
130
- obj[key] = value;
131
- }
132
- return obj;
133
- }
134
-
135
- function _arrayWithHoles(arr) {
136
- if (Array.isArray(arr)) return arr;
137
- }
138
-
139
- function _iterableToArray(iter) {
140
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
141
- }
142
-
143
- function _arrayLikeToArray(arr, len) {
144
- if (len == null || len > arr.length) len = arr.length;
145
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
146
- return arr2;
147
- }
148
-
149
- function _unsupportedIterableToArray(o, minLen) {
150
- if (!o) return;
151
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
152
- var n = Object.prototype.toString.call(o).slice(8, -1);
153
- if (n === "Object" && o.constructor) n = o.constructor.name;
154
- if (n === "Map" || n === "Set") return Array.from(o);
155
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
156
- }
157
-
158
- function _nonIterableRest() {
159
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
160
- }
161
-
162
- function _toArray(arr) {
163
- return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
164
- }
165
-
166
- function ownKeys$6$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; }
167
- function _objectSpread$6$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
168
- var consoleLogger = {
169
- type: 'logger',
170
- log: function log(args) {
171
- this.output('log', args);
172
- },
173
- warn: function warn(args) {
174
- this.output('warn', args);
175
- },
176
- error: function error(args) {
177
- this.output('error', args);
178
- },
179
- output: function output(type, args) {
180
- if (console && console[type]) console[type].apply(console, args);
181
- }
182
- };
183
- var Logger = function () {
184
- function Logger(concreteLogger) {
185
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
186
- _classCallCheck(this, Logger);
187
- this.init(concreteLogger, options);
188
- }
189
- _createClass(Logger, [{
190
- key: "init",
191
- value: function init(concreteLogger) {
192
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
193
- this.prefix = options.prefix || 'i18next:';
194
- this.logger = concreteLogger || consoleLogger;
195
- this.options = options;
196
- this.debug = options.debug;
197
- }
198
- }, {
199
- key: "setDebug",
200
- value: function setDebug(bool) {
201
- this.debug = bool;
202
- }
203
- }, {
204
- key: "log",
205
- value: function log() {
206
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
207
- args[_key] = arguments[_key];
208
- }
209
- return this.forward(args, 'log', '', true);
210
- }
211
- }, {
212
- key: "warn",
213
- value: function warn() {
214
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
215
- args[_key2] = arguments[_key2];
216
- }
217
- return this.forward(args, 'warn', '', true);
218
- }
219
- }, {
220
- key: "error",
221
- value: function error() {
222
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
223
- args[_key3] = arguments[_key3];
224
- }
225
- return this.forward(args, 'error', '');
226
- }
227
- }, {
228
- key: "deprecate",
229
- value: function deprecate() {
230
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
231
- args[_key4] = arguments[_key4];
232
- }
233
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
234
- }
235
- }, {
236
- key: "forward",
237
- value: function forward(args, lvl, prefix, debugOnly) {
238
- if (debugOnly && !this.debug) return null;
239
- if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
240
- return this.logger[lvl](args);
241
- }
242
- }, {
243
- key: "create",
244
- value: function create(moduleName) {
245
- return new Logger(this.logger, _objectSpread$6$1(_objectSpread$6$1({}, {
246
- prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
247
- }), this.options));
248
- }
249
- }, {
250
- key: "clone",
251
- value: function clone(options) {
252
- options = options || this.options;
253
- options.prefix = options.prefix || this.prefix;
254
- return new Logger(this.logger, options);
255
- }
256
- }]);
257
- return Logger;
258
- }();
259
- var baseLogger = new Logger();
260
-
261
- var EventEmitter = function () {
262
- function EventEmitter() {
263
- _classCallCheck(this, EventEmitter);
264
- this.observers = {};
265
- }
266
- _createClass(EventEmitter, [{
267
- key: "on",
268
- value: function on(events, listener) {
269
- var _this = this;
270
- events.split(' ').forEach(function (event) {
271
- _this.observers[event] = _this.observers[event] || [];
272
- _this.observers[event].push(listener);
273
- });
274
- return this;
275
- }
276
- }, {
277
- key: "off",
278
- value: function off(event, listener) {
279
- if (!this.observers[event]) return;
280
- if (!listener) {
281
- delete this.observers[event];
282
- return;
283
- }
284
- this.observers[event] = this.observers[event].filter(function (l) {
285
- return l !== listener;
286
- });
287
- }
288
- }, {
289
- key: "emit",
290
- value: function emit(event) {
291
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
292
- args[_key - 1] = arguments[_key];
293
- }
294
- if (this.observers[event]) {
295
- var cloned = [].concat(this.observers[event]);
296
- cloned.forEach(function (observer) {
297
- observer.apply(void 0, args);
298
- });
299
- }
300
- if (this.observers['*']) {
301
- var _cloned = [].concat(this.observers['*']);
302
- _cloned.forEach(function (observer) {
303
- observer.apply(observer, [event].concat(args));
304
- });
305
- }
306
- }
307
- }]);
308
- return EventEmitter;
309
- }();
310
-
311
- function defer() {
312
- var res;
313
- var rej;
314
- var promise = new Promise(function (resolve, reject) {
315
- res = resolve;
316
- rej = reject;
317
- });
318
- promise.resolve = res;
319
- promise.reject = rej;
320
- return promise;
321
- }
322
- function makeString(object) {
323
- if (object == null) return '';
324
- return '' + object;
325
- }
326
- function copy(a, s, t) {
327
- a.forEach(function (m) {
328
- if (s[m]) t[m] = s[m];
329
- });
330
- }
331
- function getLastOfPath(object, path, Empty) {
332
- function cleanKey(key) {
333
- return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
334
- }
335
- function canNotTraverseDeeper() {
336
- return !object || typeof object === 'string';
337
- }
338
- var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
339
- while (stack.length > 1) {
340
- if (canNotTraverseDeeper()) return {};
341
- var key = cleanKey(stack.shift());
342
- if (!object[key] && Empty) object[key] = new Empty();
343
- if (Object.prototype.hasOwnProperty.call(object, key)) {
344
- object = object[key];
345
- } else {
346
- object = {};
347
- }
348
- }
349
- if (canNotTraverseDeeper()) return {};
350
- return {
351
- obj: object,
352
- k: cleanKey(stack.shift())
353
- };
354
- }
355
- function setPath(object, path, newValue) {
356
- var _getLastOfPath = getLastOfPath(object, path, Object),
357
- obj = _getLastOfPath.obj,
358
- k = _getLastOfPath.k;
359
- obj[k] = newValue;
360
- }
361
- function pushPath(object, path, newValue, concat) {
362
- var _getLastOfPath2 = getLastOfPath(object, path, Object),
363
- obj = _getLastOfPath2.obj,
364
- k = _getLastOfPath2.k;
365
- obj[k] = obj[k] || [];
366
- if (concat) obj[k] = obj[k].concat(newValue);
367
- if (!concat) obj[k].push(newValue);
368
- }
369
- function getPath(object, path) {
370
- var _getLastOfPath3 = getLastOfPath(object, path),
371
- obj = _getLastOfPath3.obj,
372
- k = _getLastOfPath3.k;
373
- if (!obj) return undefined;
374
- return obj[k];
375
- }
376
- function getPathWithDefaults(data, defaultData, key) {
377
- var value = getPath(data, key);
378
- if (value !== undefined) {
379
- return value;
380
- }
381
- return getPath(defaultData, key);
382
- }
383
- function deepExtend(target, source, overwrite) {
384
- for (var prop in source) {
385
- if (prop !== '__proto__' && prop !== 'constructor') {
386
- if (prop in target) {
387
- if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
388
- if (overwrite) target[prop] = source[prop];
389
- } else {
390
- deepExtend(target[prop], source[prop], overwrite);
391
- }
392
- } else {
393
- target[prop] = source[prop];
394
- }
395
- }
396
- }
397
- return target;
398
- }
399
- function regexEscape(str) {
400
- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
401
- }
402
- var _entityMap = {
403
- '&': '&amp;',
404
- '<': '&lt;',
405
- '>': '&gt;',
406
- '"': '&quot;',
407
- "'": '&#39;',
408
- '/': '&#x2F;'
409
- };
410
- function escape(data) {
411
- if (typeof data === 'string') {
412
- return data.replace(/[&<>"'\/]/g, function (s) {
413
- return _entityMap[s];
414
- });
415
- }
416
- return data;
417
- }
418
- var isIE10 = typeof window !== 'undefined' && window.navigator && typeof window.navigator.userAgentData === 'undefined' && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
419
- var chars = [' ', ',', '?', '!', ';'];
420
- function looksLikeObjectPath(key, nsSeparator, keySeparator) {
421
- nsSeparator = nsSeparator || '';
422
- keySeparator = keySeparator || '';
423
- var possibleChars = chars.filter(function (c) {
424
- return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
425
- });
426
- if (possibleChars.length === 0) return true;
427
- var r = new RegExp("(".concat(possibleChars.map(function (c) {
428
- return c === '?' ? '\\?' : c;
429
- }).join('|'), ")"));
430
- var matched = !r.test(key);
431
- if (!matched) {
432
- var ki = key.indexOf(keySeparator);
433
- if (ki > 0 && !r.test(key.substring(0, ki))) {
434
- matched = true;
435
- }
436
- }
437
- return matched;
438
- }
439
-
440
- function ownKeys$5$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; }
441
- function _objectSpread$5$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
442
- function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
443
- function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
444
- function deepFind(obj, path) {
445
- var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
446
- if (!obj) return undefined;
447
- if (obj[path]) return obj[path];
448
- var paths = path.split(keySeparator);
449
- var current = obj;
450
- for (var i = 0; i < paths.length; ++i) {
451
- if (!current) return undefined;
452
- if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
453
- return undefined;
454
- }
455
- if (current[paths[i]] === undefined) {
456
- var j = 2;
457
- var p = paths.slice(i, i + j).join(keySeparator);
458
- var mix = current[p];
459
- while (mix === undefined && paths.length > i + j) {
460
- j++;
461
- p = paths.slice(i, i + j).join(keySeparator);
462
- mix = current[p];
463
- }
464
- if (mix === undefined) return undefined;
465
- if (mix === null) return null;
466
- if (path.endsWith(p)) {
467
- if (typeof mix === 'string') return mix;
468
- if (p && typeof mix[p] === 'string') return mix[p];
469
- }
470
- var joinedPath = paths.slice(i + j).join(keySeparator);
471
- if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
472
- return undefined;
473
- }
474
- current = current[paths[i]];
475
- }
476
- return current;
477
- }
478
- var ResourceStore = function (_EventEmitter) {
479
- _inherits(ResourceStore, _EventEmitter);
480
- var _super = _createSuper$3(ResourceStore);
481
- function ResourceStore(data) {
482
- var _this;
483
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
484
- ns: ['translation'],
485
- defaultNS: 'translation'
486
- };
487
- _classCallCheck(this, ResourceStore);
488
- _this = _super.call(this);
489
- if (isIE10) {
490
- EventEmitter.call(_assertThisInitialized(_this));
491
- }
492
- _this.data = data || {};
493
- _this.options = options;
494
- if (_this.options.keySeparator === undefined) {
495
- _this.options.keySeparator = '.';
496
- }
497
- if (_this.options.ignoreJSONStructure === undefined) {
498
- _this.options.ignoreJSONStructure = true;
499
- }
500
- return _this;
501
- }
502
- _createClass(ResourceStore, [{
503
- key: "addNamespaces",
504
- value: function addNamespaces(ns) {
505
- if (this.options.ns.indexOf(ns) < 0) {
506
- this.options.ns.push(ns);
507
- }
508
- }
509
- }, {
510
- key: "removeNamespaces",
511
- value: function removeNamespaces(ns) {
512
- var index = this.options.ns.indexOf(ns);
513
- if (index > -1) {
514
- this.options.ns.splice(index, 1);
515
- }
516
- }
517
- }, {
518
- key: "getResource",
519
- value: function getResource(lng, ns, key) {
520
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
521
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
522
- var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
523
- var path = [lng, ns];
524
- if (key && typeof key !== 'string') path = path.concat(key);
525
- if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
526
- if (lng.indexOf('.') > -1) {
527
- path = lng.split('.');
528
- }
529
- var result = getPath(this.data, path);
530
- if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
531
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
532
- }
533
- }, {
534
- key: "addResource",
535
- value: function addResource(lng, ns, key, value) {
536
- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
537
- silent: false
538
- };
539
- var keySeparator = this.options.keySeparator;
540
- if (keySeparator === undefined) keySeparator = '.';
541
- var path = [lng, ns];
542
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
543
- if (lng.indexOf('.') > -1) {
544
- path = lng.split('.');
545
- value = ns;
546
- ns = path[1];
547
- }
548
- this.addNamespaces(ns);
549
- setPath(this.data, path, value);
550
- if (!options.silent) this.emit('added', lng, ns, key, value);
551
- }
552
- }, {
553
- key: "addResources",
554
- value: function addResources(lng, ns, resources) {
555
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
556
- silent: false
557
- };
558
- for (var m in resources) {
559
- if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
560
- silent: true
561
- });
562
- }
563
- if (!options.silent) this.emit('added', lng, ns, resources);
564
- }
565
- }, {
566
- key: "addResourceBundle",
567
- value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
568
- var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
569
- silent: false
570
- };
571
- var path = [lng, ns];
572
- if (lng.indexOf('.') > -1) {
573
- path = lng.split('.');
574
- deep = resources;
575
- resources = ns;
576
- ns = path[1];
577
- }
578
- this.addNamespaces(ns);
579
- var pack = getPath(this.data, path) || {};
580
- if (deep) {
581
- deepExtend(pack, resources, overwrite);
582
- } else {
583
- pack = _objectSpread$5$1(_objectSpread$5$1({}, pack), resources);
584
- }
585
- setPath(this.data, path, pack);
586
- if (!options.silent) this.emit('added', lng, ns, resources);
587
- }
588
- }, {
589
- key: "removeResourceBundle",
590
- value: function removeResourceBundle(lng, ns) {
591
- if (this.hasResourceBundle(lng, ns)) {
592
- delete this.data[lng][ns];
593
- }
594
- this.removeNamespaces(ns);
595
- this.emit('removed', lng, ns);
596
- }
597
- }, {
598
- key: "hasResourceBundle",
599
- value: function hasResourceBundle(lng, ns) {
600
- return this.getResource(lng, ns) !== undefined;
601
- }
602
- }, {
603
- key: "getResourceBundle",
604
- value: function getResourceBundle(lng, ns) {
605
- if (!ns) ns = this.options.defaultNS;
606
- if (this.options.compatibilityAPI === 'v1') return _objectSpread$5$1(_objectSpread$5$1({}, {}), this.getResource(lng, ns));
607
- return this.getResource(lng, ns);
608
- }
609
- }, {
610
- key: "getDataByLanguage",
611
- value: function getDataByLanguage(lng) {
612
- return this.data[lng];
613
- }
614
- }, {
615
- key: "hasLanguageSomeTranslations",
616
- value: function hasLanguageSomeTranslations(lng) {
617
- var data = this.getDataByLanguage(lng);
618
- var n = data && Object.keys(data) || [];
619
- return !!n.find(function (v) {
620
- return data[v] && Object.keys(data[v]).length > 0;
621
- });
622
- }
623
- }, {
624
- key: "toJSON",
625
- value: function toJSON() {
626
- return this.data;
627
- }
628
- }]);
629
- return ResourceStore;
630
- }(EventEmitter);
631
-
632
- var postProcessor = {
633
- processors: {},
634
- addPostProcessor: function addPostProcessor(module) {
635
- this.processors[module.name] = module;
636
- },
637
- handle: function handle(processors, value, key, options, translator) {
638
- var _this = this;
639
- processors.forEach(function (processor) {
640
- if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
641
- });
642
- return value;
643
- }
644
- };
645
-
646
- function ownKeys$4$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; }
647
- function _objectSpread$4$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
648
- function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
649
- function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
650
- var checkedLoadedFor = {};
651
- var Translator = function (_EventEmitter) {
652
- _inherits(Translator, _EventEmitter);
653
- var _super = _createSuper$2(Translator);
654
- function Translator(services) {
655
- var _this;
656
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
657
- _classCallCheck(this, Translator);
658
- _this = _super.call(this);
659
- if (isIE10) {
660
- EventEmitter.call(_assertThisInitialized(_this));
661
- }
662
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this));
663
- _this.options = options;
664
- if (_this.options.keySeparator === undefined) {
665
- _this.options.keySeparator = '.';
666
- }
667
- _this.logger = baseLogger.create('translator');
668
- return _this;
669
- }
670
- _createClass(Translator, [{
671
- key: "changeLanguage",
672
- value: function changeLanguage(lng) {
673
- if (lng) this.language = lng;
674
- }
675
- }, {
676
- key: "exists",
677
- value: function exists(key) {
678
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
679
- interpolation: {}
680
- };
681
- if (key === undefined || key === null) {
682
- return false;
683
- }
684
- var resolved = this.resolve(key, options);
685
- return resolved && resolved.res !== undefined;
686
- }
687
- }, {
688
- key: "extractFromKey",
689
- value: function extractFromKey(key, options) {
690
- var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
691
- if (nsSeparator === undefined) nsSeparator = ':';
692
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
693
- var namespaces = options.ns || this.options.defaultNS || [];
694
- var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
695
- var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
696
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
697
- var m = key.match(this.interpolator.nestingRegexp);
698
- if (m && m.length > 0) {
699
- return {
700
- key: key,
701
- namespaces: namespaces
702
- };
703
- }
704
- var parts = key.split(nsSeparator);
705
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
706
- key = parts.join(keySeparator);
707
- }
708
- if (typeof namespaces === 'string') namespaces = [namespaces];
709
- return {
710
- key: key,
711
- namespaces: namespaces
712
- };
713
- }
714
- }, {
715
- key: "translate",
716
- value: function translate(keys, options, lastKey) {
717
- var _this2 = this;
718
- if (_typeof$1(options) !== 'object' && this.options.overloadTranslationOptionHandler) {
719
- options = this.options.overloadTranslationOptionHandler(arguments);
720
- }
721
- if (!options) options = {};
722
- if (keys === undefined || keys === null) return '';
723
- if (!Array.isArray(keys)) keys = [String(keys)];
724
- var returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
725
- var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
726
- var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
727
- key = _this$extractFromKey.key,
728
- namespaces = _this$extractFromKey.namespaces;
729
- var namespace = namespaces[namespaces.length - 1];
730
- var lng = options.lng || this.language;
731
- var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
732
- if (lng && lng.toLowerCase() === 'cimode') {
733
- if (appendNamespaceToCIMode) {
734
- var nsSeparator = options.nsSeparator || this.options.nsSeparator;
735
- if (returnDetails) {
736
- return {
737
- res: "".concat(namespace).concat(nsSeparator).concat(key),
738
- usedKey: key,
739
- exactUsedKey: key,
740
- usedLng: lng,
741
- usedNS: namespace
742
- };
743
- }
744
- return "".concat(namespace).concat(nsSeparator).concat(key);
745
- }
746
- if (returnDetails) {
747
- return {
748
- res: key,
749
- usedKey: key,
750
- exactUsedKey: key,
751
- usedLng: lng,
752
- usedNS: namespace
753
- };
754
- }
755
- return key;
756
- }
757
- var resolved = this.resolve(keys, options);
758
- var res = resolved && resolved.res;
759
- var resUsedKey = resolved && resolved.usedKey || key;
760
- var resExactUsedKey = resolved && resolved.exactUsedKey || key;
761
- var resType = Object.prototype.toString.apply(res);
762
- var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
763
- var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
764
- var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
765
- var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
766
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
767
- if (!options.returnObjects && !this.options.returnObjects) {
768
- if (!this.options.returnedObjectHandler) {
769
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
770
- }
771
- var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$4$1(_objectSpread$4$1({}, options), {}, {
772
- ns: namespaces
773
- })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
774
- if (returnDetails) {
775
- resolved.res = r;
776
- return resolved;
777
- }
778
- return r;
779
- }
780
- if (keySeparator) {
781
- var resTypeIsArray = resType === '[object Array]';
782
- var copy = resTypeIsArray ? [] : {};
783
- var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
784
- for (var m in res) {
785
- if (Object.prototype.hasOwnProperty.call(res, m)) {
786
- var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
787
- copy[m] = this.translate(deepKey, _objectSpread$4$1(_objectSpread$4$1({}, options), {
788
- joinArrays: false,
789
- ns: namespaces
790
- }));
791
- if (copy[m] === deepKey) copy[m] = res[m];
792
- }
793
- }
794
- res = copy;
795
- }
796
- } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
797
- res = res.join(joinArrays);
798
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
799
- } else {
800
- var usedDefault = false;
801
- var usedKey = false;
802
- var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
803
- var hasDefaultValue = Translator.hasDefaultValue(options);
804
- var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
805
- var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
806
- if (!this.isValidLookup(res) && hasDefaultValue) {
807
- usedDefault = true;
808
- res = defaultValue;
809
- }
810
- if (!this.isValidLookup(res)) {
811
- usedKey = true;
812
- res = key;
813
- }
814
- var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
815
- var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
816
- var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
817
- if (usedKey || usedDefault || updateMissing) {
818
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
819
- if (keySeparator) {
820
- var fk = this.resolve(key, _objectSpread$4$1(_objectSpread$4$1({}, options), {}, {
821
- keySeparator: false
822
- }));
823
- 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.');
824
- }
825
- var lngs = [];
826
- var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
827
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
828
- for (var i = 0; i < fallbackLngs.length; i++) {
829
- lngs.push(fallbackLngs[i]);
830
- }
831
- } else if (this.options.saveMissingTo === 'all') {
832
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
833
- } else {
834
- lngs.push(options.lng || this.language);
835
- }
836
- var send = function send(l, k, specificDefaultValue) {
837
- var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
838
- if (_this2.options.missingKeyHandler) {
839
- _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
840
- } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
841
- _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
842
- }
843
- _this2.emit('missingKey', l, namespace, k, res);
844
- };
845
- if (this.options.saveMissing) {
846
- if (this.options.saveMissingPlurals && needsPluralHandling) {
847
- lngs.forEach(function (language) {
848
- _this2.pluralResolver.getSuffixes(language, options).forEach(function (suffix) {
849
- send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
850
- });
851
- });
852
- } else {
853
- send(lngs, key, defaultValue);
854
- }
855
- }
856
- }
857
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
858
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
859
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
860
- if (this.options.compatibilityAPI !== 'v1') {
861
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : undefined);
862
- } else {
863
- res = this.options.parseMissingKeyHandler(res);
864
- }
865
- }
866
- }
867
- if (returnDetails) {
868
- resolved.res = res;
869
- return resolved;
870
- }
871
- return res;
872
- }
873
- }, {
874
- key: "extendTranslation",
875
- value: function extendTranslation(res, key, options, resolved, lastKey) {
876
- var _this3 = this;
877
- if (this.i18nFormat && this.i18nFormat.parse) {
878
- res = this.i18nFormat.parse(res, _objectSpread$4$1(_objectSpread$4$1({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, {
879
- resolved: resolved
880
- });
881
- } else if (!options.skipInterpolation) {
882
- if (options.interpolation) this.interpolator.init(_objectSpread$4$1(_objectSpread$4$1({}, options), {
883
- interpolation: _objectSpread$4$1(_objectSpread$4$1({}, this.options.interpolation), options.interpolation)
884
- }));
885
- var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
886
- var nestBef;
887
- if (skipOnVariables) {
888
- var nb = res.match(this.interpolator.nestingRegexp);
889
- nestBef = nb && nb.length;
890
- }
891
- var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
892
- if (this.options.interpolation.defaultVariables) data = _objectSpread$4$1(_objectSpread$4$1({}, this.options.interpolation.defaultVariables), data);
893
- res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
894
- if (skipOnVariables) {
895
- var na = res.match(this.interpolator.nestingRegexp);
896
- var nestAft = na && na.length;
897
- if (nestBef < nestAft) options.nest = false;
898
- }
899
- if (options.nest !== false) res = this.interpolator.nest(res, function () {
900
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
901
- args[_key] = arguments[_key];
902
- }
903
- if (lastKey && lastKey[0] === args[0] && !options.context) {
904
- _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
905
- return null;
906
- }
907
- return _this3.translate.apply(_this3, args.concat([key]));
908
- }, options);
909
- if (options.interpolation) this.interpolator.reset();
910
- }
911
- var postProcess = options.postProcess || this.options.postProcess;
912
- var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
913
- if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
914
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$4$1({
915
- i18nResolved: resolved
916
- }, options) : options, this);
917
- }
918
- return res;
919
- }
920
- }, {
921
- key: "resolve",
922
- value: function resolve(keys) {
923
- var _this4 = this;
924
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
925
- var found;
926
- var usedKey;
927
- var exactUsedKey;
928
- var usedLng;
929
- var usedNS;
930
- if (typeof keys === 'string') keys = [keys];
931
- keys.forEach(function (k) {
932
- if (_this4.isValidLookup(found)) return;
933
- var extracted = _this4.extractFromKey(k, options);
934
- var key = extracted.key;
935
- usedKey = key;
936
- var namespaces = extracted.namespaces;
937
- if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
938
- var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
939
- var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
940
- var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
941
- var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
942
- namespaces.forEach(function (ns) {
943
- if (_this4.isValidLookup(found)) return;
944
- usedNS = ns;
945
- if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
946
- checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
947
- _this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(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!!!');
948
- }
949
- codes.forEach(function (code) {
950
- if (_this4.isValidLookup(found)) return;
951
- usedLng = code;
952
- var finalKeys = [key];
953
- if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
954
- _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
955
- } else {
956
- var pluralSuffix;
957
- if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
958
- var zeroSuffix = "".concat(_this4.options.pluralSeparator, "zero");
959
- if (needsPluralHandling) {
960
- finalKeys.push(key + pluralSuffix);
961
- if (needsZeroSuffixLookup) {
962
- finalKeys.push(key + zeroSuffix);
963
- }
964
- }
965
- if (needsContextHandling) {
966
- var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
967
- finalKeys.push(contextKey);
968
- if (needsPluralHandling) {
969
- finalKeys.push(contextKey + pluralSuffix);
970
- if (needsZeroSuffixLookup) {
971
- finalKeys.push(contextKey + zeroSuffix);
972
- }
973
- }
974
- }
975
- }
976
- var possibleKey;
977
- while (possibleKey = finalKeys.pop()) {
978
- if (!_this4.isValidLookup(found)) {
979
- exactUsedKey = possibleKey;
980
- found = _this4.getResource(code, ns, possibleKey, options);
981
- }
982
- }
983
- });
984
- });
985
- });
986
- return {
987
- res: found,
988
- usedKey: usedKey,
989
- exactUsedKey: exactUsedKey,
990
- usedLng: usedLng,
991
- usedNS: usedNS
992
- };
993
- }
994
- }, {
995
- key: "isValidLookup",
996
- value: function isValidLookup(res) {
997
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
998
- }
999
- }, {
1000
- key: "getResource",
1001
- value: function getResource(code, ns, key) {
1002
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1003
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1004
- return this.resourceStore.getResource(code, ns, key, options);
1005
- }
1006
- }], [{
1007
- key: "hasDefaultValue",
1008
- value: function hasDefaultValue(options) {
1009
- var prefix = 'defaultValue';
1010
- for (var option in options) {
1011
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1012
- return true;
1013
- }
1014
- }
1015
- return false;
1016
- }
1017
- }]);
1018
- return Translator;
1019
- }(EventEmitter);
1020
-
1021
- function capitalize(string) {
1022
- return string.charAt(0).toUpperCase() + string.slice(1);
1023
- }
1024
- var LanguageUtil = function () {
1025
- function LanguageUtil(options) {
1026
- _classCallCheck(this, LanguageUtil);
1027
- this.options = options;
1028
- this.supportedLngs = this.options.supportedLngs || false;
1029
- this.logger = baseLogger.create('languageUtils');
1030
- }
1031
- _createClass(LanguageUtil, [{
1032
- key: "getScriptPartFromCode",
1033
- value: function getScriptPartFromCode(code) {
1034
- if (!code || code.indexOf('-') < 0) return null;
1035
- var p = code.split('-');
1036
- if (p.length === 2) return null;
1037
- p.pop();
1038
- if (p[p.length - 1].toLowerCase() === 'x') return null;
1039
- return this.formatLanguageCode(p.join('-'));
1040
- }
1041
- }, {
1042
- key: "getLanguagePartFromCode",
1043
- value: function getLanguagePartFromCode(code) {
1044
- if (!code || code.indexOf('-') < 0) return code;
1045
- var p = code.split('-');
1046
- return this.formatLanguageCode(p[0]);
1047
- }
1048
- }, {
1049
- key: "formatLanguageCode",
1050
- value: function formatLanguageCode(code) {
1051
- if (typeof code === 'string' && code.indexOf('-') > -1) {
1052
- var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
1053
- var p = code.split('-');
1054
- if (this.options.lowerCaseLng) {
1055
- p = p.map(function (part) {
1056
- return part.toLowerCase();
1057
- });
1058
- } else if (p.length === 2) {
1059
- p[0] = p[0].toLowerCase();
1060
- p[1] = p[1].toUpperCase();
1061
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1062
- } else if (p.length === 3) {
1063
- p[0] = p[0].toLowerCase();
1064
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
1065
- if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
1066
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1067
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
1068
- }
1069
- return p.join('-');
1070
- }
1071
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1072
- }
1073
- }, {
1074
- key: "isSupportedCode",
1075
- value: function isSupportedCode(code) {
1076
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1077
- code = this.getLanguagePartFromCode(code);
1078
- }
1079
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1080
- }
1081
- }, {
1082
- key: "getBestMatchFromCodes",
1083
- value: function getBestMatchFromCodes(codes) {
1084
- var _this = this;
1085
- if (!codes) return null;
1086
- var found;
1087
- codes.forEach(function (code) {
1088
- if (found) return;
1089
- var cleanedLng = _this.formatLanguageCode(code);
1090
- if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
1091
- });
1092
- if (!found && this.options.supportedLngs) {
1093
- codes.forEach(function (code) {
1094
- if (found) return;
1095
- var lngOnly = _this.getLanguagePartFromCode(code);
1096
- if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
1097
- found = _this.options.supportedLngs.find(function (supportedLng) {
1098
- if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
1099
- });
1100
- });
1101
- }
1102
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1103
- return found;
1104
- }
1105
- }, {
1106
- key: "getFallbackCodes",
1107
- value: function getFallbackCodes(fallbacks, code) {
1108
- if (!fallbacks) return [];
1109
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1110
- if (typeof fallbacks === 'string') fallbacks = [fallbacks];
1111
- if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
1112
- if (!code) return fallbacks["default"] || [];
1113
- var found = fallbacks[code];
1114
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1115
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
1116
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1117
- if (!found) found = fallbacks["default"];
1118
- return found || [];
1119
- }
1120
- }, {
1121
- key: "toResolveHierarchy",
1122
- value: function toResolveHierarchy(code, fallbackCode) {
1123
- var _this2 = this;
1124
- var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
1125
- var codes = [];
1126
- var addCode = function addCode(c) {
1127
- if (!c) return;
1128
- if (_this2.isSupportedCode(c)) {
1129
- codes.push(c);
1130
- } else {
1131
- _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
1132
- }
1133
- };
1134
- if (typeof code === 'string' && code.indexOf('-') > -1) {
1135
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1136
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1137
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1138
- } else if (typeof code === 'string') {
1139
- addCode(this.formatLanguageCode(code));
1140
- }
1141
- fallbackCodes.forEach(function (fc) {
1142
- if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
1143
- });
1144
- return codes;
1145
- }
1146
- }]);
1147
- return LanguageUtil;
1148
- }();
1149
-
1150
- var sets = [{
1151
- lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
1152
- nr: [1, 2],
1153
- fc: 1
1154
- }, {
1155
- 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'],
1156
- nr: [1, 2],
1157
- fc: 2
1158
- }, {
1159
- lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
1160
- nr: [1],
1161
- fc: 3
1162
- }, {
1163
- lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
1164
- nr: [1, 2, 5],
1165
- fc: 4
1166
- }, {
1167
- lngs: ['ar'],
1168
- nr: [0, 1, 2, 3, 11, 100],
1169
- fc: 5
1170
- }, {
1171
- lngs: ['cs', 'sk'],
1172
- nr: [1, 2, 5],
1173
- fc: 6
1174
- }, {
1175
- lngs: ['csb', 'pl'],
1176
- nr: [1, 2, 5],
1177
- fc: 7
1178
- }, {
1179
- lngs: ['cy'],
1180
- nr: [1, 2, 3, 8],
1181
- fc: 8
1182
- }, {
1183
- lngs: ['fr'],
1184
- nr: [1, 2],
1185
- fc: 9
1186
- }, {
1187
- lngs: ['ga'],
1188
- nr: [1, 2, 3, 7, 11],
1189
- fc: 10
1190
- }, {
1191
- lngs: ['gd'],
1192
- nr: [1, 2, 3, 20],
1193
- fc: 11
1194
- }, {
1195
- lngs: ['is'],
1196
- nr: [1, 2],
1197
- fc: 12
1198
- }, {
1199
- lngs: ['jv'],
1200
- nr: [0, 1],
1201
- fc: 13
1202
- }, {
1203
- lngs: ['kw'],
1204
- nr: [1, 2, 3, 4],
1205
- fc: 14
1206
- }, {
1207
- lngs: ['lt'],
1208
- nr: [1, 2, 10],
1209
- fc: 15
1210
- }, {
1211
- lngs: ['lv'],
1212
- nr: [1, 2, 0],
1213
- fc: 16
1214
- }, {
1215
- lngs: ['mk'],
1216
- nr: [1, 2],
1217
- fc: 17
1218
- }, {
1219
- lngs: ['mnk'],
1220
- nr: [0, 1, 2],
1221
- fc: 18
1222
- }, {
1223
- lngs: ['mt'],
1224
- nr: [1, 2, 11, 20],
1225
- fc: 19
1226
- }, {
1227
- lngs: ['or'],
1228
- nr: [2, 1],
1229
- fc: 2
1230
- }, {
1231
- lngs: ['ro'],
1232
- nr: [1, 2, 20],
1233
- fc: 20
1234
- }, {
1235
- lngs: ['sl'],
1236
- nr: [5, 1, 2, 3],
1237
- fc: 21
1238
- }, {
1239
- lngs: ['he', 'iw'],
1240
- nr: [1, 2, 20, 21],
1241
- fc: 22
1242
- }];
1243
- var _rulesPluralsTypes = {
1244
- 1: function _(n) {
1245
- return Number(n > 1);
1246
- },
1247
- 2: function _(n) {
1248
- return Number(n != 1);
1249
- },
1250
- 3: function _(n) {
1251
- return 0;
1252
- },
1253
- 4: function _(n) {
1254
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1255
- },
1256
- 5: function _(n) {
1257
- return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
1258
- },
1259
- 6: function _(n) {
1260
- return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
1261
- },
1262
- 7: function _(n) {
1263
- return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1264
- },
1265
- 8: function _(n) {
1266
- return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
1267
- },
1268
- 9: function _(n) {
1269
- return Number(n >= 2);
1270
- },
1271
- 10: function _(n) {
1272
- return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
1273
- },
1274
- 11: function _(n) {
1275
- return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
1276
- },
1277
- 12: function _(n) {
1278
- return Number(n % 10 != 1 || n % 100 == 11);
1279
- },
1280
- 13: function _(n) {
1281
- return Number(n !== 0);
1282
- },
1283
- 14: function _(n) {
1284
- return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
1285
- },
1286
- 15: function _(n) {
1287
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1288
- },
1289
- 16: function _(n) {
1290
- return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
1291
- },
1292
- 17: function _(n) {
1293
- return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
1294
- },
1295
- 18: function _(n) {
1296
- return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
1297
- },
1298
- 19: function _(n) {
1299
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
1300
- },
1301
- 20: function _(n) {
1302
- return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
1303
- },
1304
- 21: function _(n) {
1305
- return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
1306
- },
1307
- 22: function _(n) {
1308
- return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
1309
- }
1310
- };
1311
- var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
1312
- var suffixesOrder = {
1313
- zero: 0,
1314
- one: 1,
1315
- two: 2,
1316
- few: 3,
1317
- many: 4,
1318
- other: 5
1319
- };
1320
- function createRules() {
1321
- var rules = {};
1322
- sets.forEach(function (set) {
1323
- set.lngs.forEach(function (l) {
1324
- rules[l] = {
1325
- numbers: set.nr,
1326
- plurals: _rulesPluralsTypes[set.fc]
1327
- };
1328
- });
1329
- });
1330
- return rules;
1331
- }
1332
- var PluralResolver = function () {
1333
- function PluralResolver(languageUtils) {
1334
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1335
- _classCallCheck(this, PluralResolver);
1336
- this.languageUtils = languageUtils;
1337
- this.options = options;
1338
- this.logger = baseLogger.create('pluralResolver');
1339
- if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
1340
- this.options.compatibilityJSON = 'v3';
1341
- 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.');
1342
- }
1343
- this.rules = createRules();
1344
- }
1345
- _createClass(PluralResolver, [{
1346
- key: "addRule",
1347
- value: function addRule(lng, obj) {
1348
- this.rules[lng] = obj;
1349
- }
1350
- }, {
1351
- key: "getRule",
1352
- value: function getRule(code) {
1353
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1354
- if (this.shouldUseIntlApi()) {
1355
- try {
1356
- return new Intl.PluralRules(code, {
1357
- type: options.ordinal ? 'ordinal' : 'cardinal'
1358
- });
1359
- } catch (_unused) {
1360
- return;
1361
- }
1362
- }
1363
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1364
- }
1365
- }, {
1366
- key: "needsPlural",
1367
- value: function needsPlural(code) {
1368
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1369
- var rule = this.getRule(code, options);
1370
- if (this.shouldUseIntlApi()) {
1371
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
1372
- }
1373
- return rule && rule.numbers.length > 1;
1374
- }
1375
- }, {
1376
- key: "getPluralFormsOfKey",
1377
- value: function getPluralFormsOfKey(code, key) {
1378
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1379
- return this.getSuffixes(code, options).map(function (suffix) {
1380
- return "".concat(key).concat(suffix);
1381
- });
1382
- }
1383
- }, {
1384
- key: "getSuffixes",
1385
- value: function getSuffixes(code) {
1386
- var _this = this;
1387
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1388
- var rule = this.getRule(code, options);
1389
- if (!rule) {
1390
- return [];
1391
- }
1392
- if (this.shouldUseIntlApi()) {
1393
- return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
1394
- return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
1395
- }).map(function (pluralCategory) {
1396
- return "".concat(_this.options.prepend).concat(pluralCategory);
1397
- });
1398
- }
1399
- return rule.numbers.map(function (number) {
1400
- return _this.getSuffix(code, number, options);
1401
- });
1402
- }
1403
- }, {
1404
- key: "getSuffix",
1405
- value: function getSuffix(code, count) {
1406
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1407
- var rule = this.getRule(code, options);
1408
- if (rule) {
1409
- if (this.shouldUseIntlApi()) {
1410
- return "".concat(this.options.prepend).concat(rule.select(count));
1411
- }
1412
- return this.getSuffixRetroCompatible(rule, count);
1413
- }
1414
- this.logger.warn("no plural rule found for: ".concat(code));
1415
- return '';
1416
- }
1417
- }, {
1418
- key: "getSuffixRetroCompatible",
1419
- value: function getSuffixRetroCompatible(rule, count) {
1420
- var _this2 = this;
1421
- var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
1422
- var suffix = rule.numbers[idx];
1423
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1424
- if (suffix === 2) {
1425
- suffix = 'plural';
1426
- } else if (suffix === 1) {
1427
- suffix = '';
1428
- }
1429
- }
1430
- var returnSuffix = function returnSuffix() {
1431
- return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
1432
- };
1433
- if (this.options.compatibilityJSON === 'v1') {
1434
- if (suffix === 1) return '';
1435
- if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
1436
- return returnSuffix();
1437
- } else if (this.options.compatibilityJSON === 'v2') {
1438
- return returnSuffix();
1439
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
1440
- return returnSuffix();
1441
- }
1442
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
1443
- }
1444
- }, {
1445
- key: "shouldUseIntlApi",
1446
- value: function shouldUseIntlApi() {
1447
- return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
1448
- }
1449
- }]);
1450
- return PluralResolver;
1451
- }();
1452
-
1453
- function ownKeys$3$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; }
1454
- function _objectSpread$3$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1455
- var Interpolator = function () {
1456
- function Interpolator() {
1457
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1458
- _classCallCheck(this, Interpolator);
1459
- this.logger = baseLogger.create('interpolator');
1460
- this.options = options;
1461
- this.format = options.interpolation && options.interpolation.format || function (value) {
1462
- return value;
1463
- };
1464
- this.init(options);
1465
- }
1466
- _createClass(Interpolator, [{
1467
- key: "init",
1468
- value: function init() {
1469
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1470
- if (!options.interpolation) options.interpolation = {
1471
- escapeValue: true
1472
- };
1473
- var iOpts = options.interpolation;
1474
- this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
1475
- this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
1476
- this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
1477
- this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
1478
- this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
1479
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1480
- this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
1481
- this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
1482
- this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
1483
- this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
1484
- this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
1485
- this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
1486
- this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
1487
- this.resetRegExp();
1488
- }
1489
- }, {
1490
- key: "reset",
1491
- value: function reset() {
1492
- if (this.options) this.init(this.options);
1493
- }
1494
- }, {
1495
- key: "resetRegExp",
1496
- value: function resetRegExp() {
1497
- var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
1498
- this.regexp = new RegExp(regexpStr, 'g');
1499
- var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
1500
- this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
1501
- var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
1502
- this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
1503
- }
1504
- }, {
1505
- key: "interpolate",
1506
- value: function interpolate(str, data, lng, options) {
1507
- var _this = this;
1508
- var match;
1509
- var value;
1510
- var replaces;
1511
- var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1512
- function regexSafe(val) {
1513
- return val.replace(/\$/g, '$$$$');
1514
- }
1515
- var handleFormat = function handleFormat(key) {
1516
- if (key.indexOf(_this.formatSeparator) < 0) {
1517
- var path = getPathWithDefaults(data, defaultData, key);
1518
- return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3$1(_objectSpread$3$1(_objectSpread$3$1({}, options), data), {}, {
1519
- interpolationkey: key
1520
- })) : path;
1521
- }
1522
- var p = key.split(_this.formatSeparator);
1523
- var k = p.shift().trim();
1524
- var f = p.join(_this.formatSeparator).trim();
1525
- return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread$3$1(_objectSpread$3$1(_objectSpread$3$1({}, options), data), {}, {
1526
- interpolationkey: k
1527
- }));
1528
- };
1529
- this.resetRegExp();
1530
- var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
1531
- var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1532
- var todos = [{
1533
- regex: this.regexpUnescape,
1534
- safeValue: function safeValue(val) {
1535
- return regexSafe(val);
1536
- }
1537
- }, {
1538
- regex: this.regexp,
1539
- safeValue: function safeValue(val) {
1540
- return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
1541
- }
1542
- }];
1543
- todos.forEach(function (todo) {
1544
- replaces = 0;
1545
- while (match = todo.regex.exec(str)) {
1546
- var matchedVar = match[1].trim();
1547
- value = handleFormat(matchedVar);
1548
- if (value === undefined) {
1549
- if (typeof missingInterpolationHandler === 'function') {
1550
- var temp = missingInterpolationHandler(str, match, options);
1551
- value = typeof temp === 'string' ? temp : '';
1552
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1553
- value = '';
1554
- } else if (skipOnVariables) {
1555
- value = match[0];
1556
- continue;
1557
- } else {
1558
- _this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str));
1559
- value = '';
1560
- }
1561
- } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
1562
- value = makeString(value);
1563
- }
1564
- var safeValue = todo.safeValue(value);
1565
- str = str.replace(match[0], safeValue);
1566
- if (skipOnVariables) {
1567
- todo.regex.lastIndex += value.length;
1568
- todo.regex.lastIndex -= match[0].length;
1569
- } else {
1570
- todo.regex.lastIndex = 0;
1571
- }
1572
- replaces++;
1573
- if (replaces >= _this.maxReplaces) {
1574
- break;
1575
- }
1576
- }
1577
- });
1578
- return str;
1579
- }
1580
- }, {
1581
- key: "nest",
1582
- value: function nest(str, fc) {
1583
- var _this2 = this;
1584
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1585
- var match;
1586
- var value;
1587
- var clonedOptions;
1588
- function handleHasOptions(key, inheritedOptions) {
1589
- var sep = this.nestingOptionsSeparator;
1590
- if (key.indexOf(sep) < 0) return key;
1591
- var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
1592
- var optionsString = "{".concat(c[1]);
1593
- key = c[0];
1594
- optionsString = this.interpolate(optionsString, clonedOptions);
1595
- var matchedSingleQuotes = optionsString.match(/'/g);
1596
- var matchedDoubleQuotes = optionsString.match(/"/g);
1597
- if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1598
- optionsString = optionsString.replace(/'/g, '"');
1599
- }
1600
- try {
1601
- clonedOptions = JSON.parse(optionsString);
1602
- if (inheritedOptions) clonedOptions = _objectSpread$3$1(_objectSpread$3$1({}, inheritedOptions), clonedOptions);
1603
- } catch (e) {
1604
- this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
1605
- return "".concat(key).concat(sep).concat(optionsString);
1606
- }
1607
- delete clonedOptions.defaultValue;
1608
- return key;
1609
- }
1610
- while (match = this.nestingRegexp.exec(str)) {
1611
- var formatters = [];
1612
- clonedOptions = _objectSpread$3$1({}, options);
1613
- clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
1614
- clonedOptions.applyPostProcessor = false;
1615
- delete clonedOptions.defaultValue;
1616
- var doReduce = false;
1617
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
1618
- var r = match[1].split(this.formatSeparator).map(function (elem) {
1619
- return elem.trim();
1620
- });
1621
- match[1] = r.shift();
1622
- formatters = r;
1623
- doReduce = true;
1624
- }
1625
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1626
- if (value && match[0] === str && typeof value !== 'string') return value;
1627
- if (typeof value !== 'string') value = makeString(value);
1628
- if (!value) {
1629
- this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
1630
- value = '';
1631
- }
1632
- if (doReduce) {
1633
- value = formatters.reduce(function (v, f) {
1634
- return _this2.format(v, f, options.lng, _objectSpread$3$1(_objectSpread$3$1({}, options), {}, {
1635
- interpolationkey: match[1].trim()
1636
- }));
1637
- }, value.trim());
1638
- }
1639
- str = str.replace(match[0], value);
1640
- this.regexp.lastIndex = 0;
1641
- }
1642
- return str;
1643
- }
1644
- }]);
1645
- return Interpolator;
1646
- }();
1647
-
1648
- function ownKeys$2$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; }
1649
- function _objectSpread$2$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1650
- function parseFormatStr(formatStr) {
1651
- var formatName = formatStr.toLowerCase().trim();
1652
- var formatOptions = {};
1653
- if (formatStr.indexOf('(') > -1) {
1654
- var p = formatStr.split('(');
1655
- formatName = p[0].toLowerCase().trim();
1656
- var optStr = p[1].substring(0, p[1].length - 1);
1657
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1658
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1659
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1660
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1661
- } else {
1662
- var opts = optStr.split(';');
1663
- opts.forEach(function (opt) {
1664
- if (!opt) return;
1665
- var _opt$split = opt.split(':'),
1666
- _opt$split2 = _toArray(_opt$split),
1667
- key = _opt$split2[0],
1668
- rest = _opt$split2.slice(1);
1669
- var val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1670
- if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
1671
- if (val === 'false') formatOptions[key.trim()] = false;
1672
- if (val === 'true') formatOptions[key.trim()] = true;
1673
- if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
1674
- });
1675
- }
1676
- }
1677
- return {
1678
- formatName: formatName,
1679
- formatOptions: formatOptions
1680
- };
1681
- }
1682
- function createCachedFormatter(fn) {
1683
- var cache = {};
1684
- return function invokeFormatter(val, lng, options) {
1685
- var key = lng + JSON.stringify(options);
1686
- var formatter = cache[key];
1687
- if (!formatter) {
1688
- formatter = fn(lng, options);
1689
- cache[key] = formatter;
1690
- }
1691
- return formatter(val);
1692
- };
1693
- }
1694
- var Formatter = function () {
1695
- function Formatter() {
1696
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1697
- _classCallCheck(this, Formatter);
1698
- this.logger = baseLogger.create('formatter');
1699
- this.options = options;
1700
- this.formats = {
1701
- number: createCachedFormatter(function (lng, opt) {
1702
- var formatter = new Intl.NumberFormat(lng, _objectSpread$2$1({}, opt));
1703
- return function (val) {
1704
- return formatter.format(val);
1705
- };
1706
- }),
1707
- currency: createCachedFormatter(function (lng, opt) {
1708
- var formatter = new Intl.NumberFormat(lng, _objectSpread$2$1(_objectSpread$2$1({}, opt), {}, {
1709
- style: 'currency'
1710
- }));
1711
- return function (val) {
1712
- return formatter.format(val);
1713
- };
1714
- }),
1715
- datetime: createCachedFormatter(function (lng, opt) {
1716
- var formatter = new Intl.DateTimeFormat(lng, _objectSpread$2$1({}, opt));
1717
- return function (val) {
1718
- return formatter.format(val);
1719
- };
1720
- }),
1721
- relativetime: createCachedFormatter(function (lng, opt) {
1722
- var formatter = new Intl.RelativeTimeFormat(lng, _objectSpread$2$1({}, opt));
1723
- return function (val) {
1724
- return formatter.format(val, opt.range || 'day');
1725
- };
1726
- }),
1727
- list: createCachedFormatter(function (lng, opt) {
1728
- var formatter = new Intl.ListFormat(lng, _objectSpread$2$1({}, opt));
1729
- return function (val) {
1730
- return formatter.format(val);
1731
- };
1732
- })
1733
- };
1734
- this.init(options);
1735
- }
1736
- _createClass(Formatter, [{
1737
- key: "init",
1738
- value: function init(services) {
1739
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1740
- interpolation: {}
1741
- };
1742
- var iOpts = options.interpolation;
1743
- this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
1744
- }
1745
- }, {
1746
- key: "add",
1747
- value: function add(name, fc) {
1748
- this.formats[name.toLowerCase().trim()] = fc;
1749
- }
1750
- }, {
1751
- key: "addCached",
1752
- value: function addCached(name, fc) {
1753
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1754
- }
1755
- }, {
1756
- key: "format",
1757
- value: function format(value, _format, lng) {
1758
- var _this = this;
1759
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1760
- var formats = _format.split(this.formatSeparator);
1761
- var result = formats.reduce(function (mem, f) {
1762
- var _parseFormatStr = parseFormatStr(f),
1763
- formatName = _parseFormatStr.formatName,
1764
- formatOptions = _parseFormatStr.formatOptions;
1765
- if (_this.formats[formatName]) {
1766
- var formatted = mem;
1767
- try {
1768
- var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
1769
- var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1770
- formatted = _this.formats[formatName](mem, l, _objectSpread$2$1(_objectSpread$2$1(_objectSpread$2$1({}, formatOptions), options), valOptions));
1771
- } catch (error) {
1772
- _this.logger.warn(error);
1773
- }
1774
- return formatted;
1775
- } else {
1776
- _this.logger.warn("there was no format function for ".concat(formatName));
1777
- }
1778
- return mem;
1779
- }, value);
1780
- return result;
1781
- }
1782
- }]);
1783
- return Formatter;
1784
- }();
1785
-
1786
- function ownKeys$1$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; }
1787
- function _objectSpread$1$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1788
- function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
1789
- function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1790
- function removePending(q, name) {
1791
- if (q.pending[name] !== undefined) {
1792
- delete q.pending[name];
1793
- q.pendingCount--;
1794
- }
1795
- }
1796
- var Connector = function (_EventEmitter) {
1797
- _inherits(Connector, _EventEmitter);
1798
- var _super = _createSuper$1(Connector);
1799
- function Connector(backend, store, services) {
1800
- var _this;
1801
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1802
- _classCallCheck(this, Connector);
1803
- _this = _super.call(this);
1804
- if (isIE10) {
1805
- EventEmitter.call(_assertThisInitialized(_this));
1806
- }
1807
- _this.backend = backend;
1808
- _this.store = store;
1809
- _this.services = services;
1810
- _this.languageUtils = services.languageUtils;
1811
- _this.options = options;
1812
- _this.logger = baseLogger.create('backendConnector');
1813
- _this.waitingReads = [];
1814
- _this.maxParallelReads = options.maxParallelReads || 10;
1815
- _this.readingCalls = 0;
1816
- _this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1817
- _this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1818
- _this.state = {};
1819
- _this.queue = [];
1820
- if (_this.backend && _this.backend.init) {
1821
- _this.backend.init(services, options.backend, options);
1822
- }
1823
- return _this;
1824
- }
1825
- _createClass(Connector, [{
1826
- key: "queueLoad",
1827
- value: function queueLoad(languages, namespaces, options, callback) {
1828
- var _this2 = this;
1829
- var toLoad = {};
1830
- var pending = {};
1831
- var toLoadLanguages = {};
1832
- var toLoadNamespaces = {};
1833
- languages.forEach(function (lng) {
1834
- var hasAllNamespaces = true;
1835
- namespaces.forEach(function (ns) {
1836
- var name = "".concat(lng, "|").concat(ns);
1837
- if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
1838
- _this2.state[name] = 2;
1839
- } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
1840
- if (pending[name] === undefined) pending[name] = true;
1841
- } else {
1842
- _this2.state[name] = 1;
1843
- hasAllNamespaces = false;
1844
- if (pending[name] === undefined) pending[name] = true;
1845
- if (toLoad[name] === undefined) toLoad[name] = true;
1846
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1847
- }
1848
- });
1849
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1850
- });
1851
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1852
- this.queue.push({
1853
- pending: pending,
1854
- pendingCount: Object.keys(pending).length,
1855
- loaded: {},
1856
- errors: [],
1857
- callback: callback
1858
- });
1859
- }
1860
- return {
1861
- toLoad: Object.keys(toLoad),
1862
- pending: Object.keys(pending),
1863
- toLoadLanguages: Object.keys(toLoadLanguages),
1864
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1865
- };
1866
- }
1867
- }, {
1868
- key: "loaded",
1869
- value: function loaded(name, err, data) {
1870
- var s = name.split('|');
1871
- var lng = s[0];
1872
- var ns = s[1];
1873
- if (err) this.emit('failedLoading', lng, ns, err);
1874
- if (data) {
1875
- this.store.addResourceBundle(lng, ns, data);
1876
- }
1877
- this.state[name] = err ? -1 : 2;
1878
- var loaded = {};
1879
- this.queue.forEach(function (q) {
1880
- pushPath(q.loaded, [lng], ns);
1881
- removePending(q, name);
1882
- if (err) q.errors.push(err);
1883
- if (q.pendingCount === 0 && !q.done) {
1884
- Object.keys(q.loaded).forEach(function (l) {
1885
- if (!loaded[l]) loaded[l] = {};
1886
- var loadedKeys = q.loaded[l];
1887
- if (loadedKeys.length) {
1888
- loadedKeys.forEach(function (n) {
1889
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1890
- });
1891
- }
1892
- });
1893
- q.done = true;
1894
- if (q.errors.length) {
1895
- q.callback(q.errors);
1896
- } else {
1897
- q.callback();
1898
- }
1899
- }
1900
- });
1901
- this.emit('loaded', loaded);
1902
- this.queue = this.queue.filter(function (q) {
1903
- return !q.done;
1904
- });
1905
- }
1906
- }, {
1907
- key: "read",
1908
- value: function read(lng, ns, fcName) {
1909
- var _this3 = this;
1910
- var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
1911
- var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
1912
- var callback = arguments.length > 5 ? arguments[5] : undefined;
1913
- if (!lng.length) return callback(null, {});
1914
- if (this.readingCalls >= this.maxParallelReads) {
1915
- this.waitingReads.push({
1916
- lng: lng,
1917
- ns: ns,
1918
- fcName: fcName,
1919
- tried: tried,
1920
- wait: wait,
1921
- callback: callback
1922
- });
1923
- return;
1924
- }
1925
- this.readingCalls++;
1926
- var resolver = function resolver(err, data) {
1927
- _this3.readingCalls--;
1928
- if (_this3.waitingReads.length > 0) {
1929
- var next = _this3.waitingReads.shift();
1930
- _this3.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1931
- }
1932
- if (err && data && tried < _this3.maxRetries) {
1933
- setTimeout(function () {
1934
- _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
1935
- }, wait);
1936
- return;
1937
- }
1938
- callback(err, data);
1939
- };
1940
- var fc = this.backend[fcName].bind(this.backend);
1941
- if (fc.length === 2) {
1942
- try {
1943
- var r = fc(lng, ns);
1944
- if (r && typeof r.then === 'function') {
1945
- r.then(function (data) {
1946
- return resolver(null, data);
1947
- })["catch"](resolver);
1948
- } else {
1949
- resolver(null, r);
1950
- }
1951
- } catch (err) {
1952
- resolver(err);
1953
- }
1954
- return;
1955
- }
1956
- return fc(lng, ns, resolver);
1957
- }
1958
- }, {
1959
- key: "prepareLoading",
1960
- value: function prepareLoading(languages, namespaces) {
1961
- var _this4 = this;
1962
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1963
- var callback = arguments.length > 3 ? arguments[3] : undefined;
1964
- if (!this.backend) {
1965
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1966
- return callback && callback();
1967
- }
1968
- if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
1969
- if (typeof namespaces === 'string') namespaces = [namespaces];
1970
- var toLoad = this.queueLoad(languages, namespaces, options, callback);
1971
- if (!toLoad.toLoad.length) {
1972
- if (!toLoad.pending.length) callback();
1973
- return null;
1974
- }
1975
- toLoad.toLoad.forEach(function (name) {
1976
- _this4.loadOne(name);
1977
- });
1978
- }
1979
- }, {
1980
- key: "load",
1981
- value: function load(languages, namespaces, callback) {
1982
- this.prepareLoading(languages, namespaces, {}, callback);
1983
- }
1984
- }, {
1985
- key: "reload",
1986
- value: function reload(languages, namespaces, callback) {
1987
- this.prepareLoading(languages, namespaces, {
1988
- reload: true
1989
- }, callback);
1990
- }
1991
- }, {
1992
- key: "loadOne",
1993
- value: function loadOne(name) {
1994
- var _this5 = this;
1995
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
1996
- var s = name.split('|');
1997
- var lng = s[0];
1998
- var ns = s[1];
1999
- this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
2000
- if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
2001
- if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
2002
- _this5.loaded(name, err, data);
2003
- });
2004
- }
2005
- }, {
2006
- key: "saveMissing",
2007
- value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
2008
- var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
2009
- var clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : function () {};
2010
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
2011
- this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(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!!!');
2012
- return;
2013
- }
2014
- if (key === undefined || key === null || key === '') return;
2015
- if (this.backend && this.backend.create) {
2016
- var opts = _objectSpread$1$1(_objectSpread$1$1({}, options), {}, {
2017
- isUpdate: isUpdate
2018
- });
2019
- var fc = this.backend.create.bind(this.backend);
2020
- if (fc.length < 6) {
2021
- try {
2022
- var r;
2023
- if (fc.length === 5) {
2024
- r = fc(languages, namespace, key, fallbackValue, opts);
2025
- } else {
2026
- r = fc(languages, namespace, key, fallbackValue);
2027
- }
2028
- if (r && typeof r.then === 'function') {
2029
- r.then(function (data) {
2030
- return clb(null, data);
2031
- })["catch"](clb);
2032
- } else {
2033
- clb(null, r);
2034
- }
2035
- } catch (err) {
2036
- clb(err);
2037
- }
2038
- } else {
2039
- fc(languages, namespace, key, fallbackValue, clb, opts);
2040
- }
2041
- }
2042
- if (!languages || !languages[0]) return;
2043
- this.store.addResource(languages[0], namespace, key, fallbackValue);
2044
- }
2045
- }]);
2046
- return Connector;
2047
- }(EventEmitter);
2048
-
2049
- function get() {
2050
- return {
2051
- debug: false,
2052
- initImmediate: true,
2053
- ns: ['translation'],
2054
- defaultNS: ['translation'],
2055
- fallbackLng: ['dev'],
2056
- fallbackNS: false,
2057
- supportedLngs: false,
2058
- nonExplicitSupportedLngs: false,
2059
- load: 'all',
2060
- preload: false,
2061
- simplifyPluralSuffix: true,
2062
- keySeparator: '.',
2063
- nsSeparator: ':',
2064
- pluralSeparator: '_',
2065
- contextSeparator: '_',
2066
- partialBundledLanguages: false,
2067
- saveMissing: false,
2068
- updateMissing: false,
2069
- saveMissingTo: 'fallback',
2070
- saveMissingPlurals: true,
2071
- missingKeyHandler: false,
2072
- missingInterpolationHandler: false,
2073
- postProcess: false,
2074
- postProcessPassResolved: false,
2075
- returnNull: true,
2076
- returnEmptyString: true,
2077
- returnObjects: false,
2078
- joinArrays: false,
2079
- returnedObjectHandler: false,
2080
- parseMissingKeyHandler: false,
2081
- appendNamespaceToMissingKey: false,
2082
- appendNamespaceToCIMode: false,
2083
- overloadTranslationOptionHandler: function handle(args) {
2084
- var ret = {};
2085
- if (_typeof$1(args[1]) === 'object') ret = args[1];
2086
- if (typeof args[1] === 'string') ret.defaultValue = args[1];
2087
- if (typeof args[2] === 'string') ret.tDescription = args[2];
2088
- if (_typeof$1(args[2]) === 'object' || _typeof$1(args[3]) === 'object') {
2089
- var options = args[3] || args[2];
2090
- Object.keys(options).forEach(function (key) {
2091
- ret[key] = options[key];
2092
- });
2093
- }
2094
- return ret;
2095
- },
2096
- interpolation: {
2097
- escapeValue: true,
2098
- format: function format(value, _format, lng, options) {
2099
- return value;
2100
- },
2101
- prefix: '{{',
2102
- suffix: '}}',
2103
- formatSeparator: ',',
2104
- unescapePrefix: '-',
2105
- nestingPrefix: '$t(',
2106
- nestingSuffix: ')',
2107
- nestingOptionsSeparator: ',',
2108
- maxReplaces: 1000,
2109
- skipOnVariables: true
2110
- }
2111
- };
2112
- }
2113
- function transformOptions(options) {
2114
- if (typeof options.ns === 'string') options.ns = [options.ns];
2115
- if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
2116
- if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
2117
- if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
2118
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
2119
- }
2120
- return options;
2121
- }
2122
-
2123
- function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2124
- function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$8(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2125
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
2126
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2127
- function noop() {}
2128
- function bindMemberFunctions(inst) {
2129
- var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
2130
- mems.forEach(function (mem) {
2131
- if (typeof inst[mem] === 'function') {
2132
- inst[mem] = inst[mem].bind(inst);
2133
- }
2134
- });
2135
- }
2136
- var I18n = function (_EventEmitter) {
2137
- _inherits(I18n, _EventEmitter);
2138
- var _super = _createSuper(I18n);
2139
- function I18n() {
2140
- var _this;
2141
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2142
- var callback = arguments.length > 1 ? arguments[1] : undefined;
2143
- _classCallCheck(this, I18n);
2144
- _this = _super.call(this);
2145
- if (isIE10) {
2146
- EventEmitter.call(_assertThisInitialized(_this));
2147
- }
2148
- _this.options = transformOptions(options);
2149
- _this.services = {};
2150
- _this.logger = baseLogger;
2151
- _this.modules = {
2152
- external: []
2153
- };
2154
- bindMemberFunctions(_assertThisInitialized(_this));
2155
- if (callback && !_this.isInitialized && !options.isClone) {
2156
- if (!_this.options.initImmediate) {
2157
- _this.init(options, callback);
2158
- return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
2159
- }
2160
- setTimeout(function () {
2161
- _this.init(options, callback);
2162
- }, 0);
2163
- }
2164
- return _this;
2165
- }
2166
- _createClass(I18n, [{
2167
- key: "init",
2168
- value: function init() {
2169
- var _this2 = this;
2170
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2171
- var callback = arguments.length > 1 ? arguments[1] : undefined;
2172
- if (typeof options === 'function') {
2173
- callback = options;
2174
- options = {};
2175
- }
2176
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
2177
- if (typeof options.ns === 'string') {
2178
- options.defaultNS = options.ns;
2179
- } else if (options.ns.indexOf('translation') < 0) {
2180
- options.defaultNS = options.ns[0];
2181
- }
2182
- }
2183
- var defOpts = get();
2184
- this.options = _objectSpread$8(_objectSpread$8(_objectSpread$8({}, defOpts), this.options), transformOptions(options));
2185
- if (this.options.compatibilityAPI !== 'v1') {
2186
- this.options.interpolation = _objectSpread$8(_objectSpread$8({}, defOpts.interpolation), this.options.interpolation);
2187
- }
2188
- if (options.keySeparator !== undefined) {
2189
- this.options.userDefinedKeySeparator = options.keySeparator;
2190
- }
2191
- if (options.nsSeparator !== undefined) {
2192
- this.options.userDefinedNsSeparator = options.nsSeparator;
2193
- }
2194
- function createClassOnDemand(ClassOrObject) {
2195
- if (!ClassOrObject) return null;
2196
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
2197
- return ClassOrObject;
2198
- }
2199
- if (!this.options.isClone) {
2200
- if (this.modules.logger) {
2201
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2202
- } else {
2203
- baseLogger.init(null, this.options);
2204
- }
2205
- var formatter;
2206
- if (this.modules.formatter) {
2207
- formatter = this.modules.formatter;
2208
- } else if (typeof Intl !== 'undefined') {
2209
- formatter = Formatter;
2210
- }
2211
- var lu = new LanguageUtil(this.options);
2212
- this.store = new ResourceStore(this.options.resources, this.options);
2213
- var s = this.services;
2214
- s.logger = baseLogger;
2215
- s.resourceStore = this.store;
2216
- s.languageUtils = lu;
2217
- s.pluralResolver = new PluralResolver(lu, {
2218
- prepend: this.options.pluralSeparator,
2219
- compatibilityJSON: this.options.compatibilityJSON,
2220
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
2221
- });
2222
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2223
- s.formatter = createClassOnDemand(formatter);
2224
- s.formatter.init(s, this.options);
2225
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2226
- }
2227
- s.interpolator = new Interpolator(this.options);
2228
- s.utils = {
2229
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2230
- };
2231
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2232
- s.backendConnector.on('*', function (event) {
2233
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2234
- args[_key - 1] = arguments[_key];
2235
- }
2236
- _this2.emit.apply(_this2, [event].concat(args));
2237
- });
2238
- if (this.modules.languageDetector) {
2239
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2240
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2241
- }
2242
- if (this.modules.i18nFormat) {
2243
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2244
- if (s.i18nFormat.init) s.i18nFormat.init(this);
2245
- }
2246
- this.translator = new Translator(this.services, this.options);
2247
- this.translator.on('*', function (event) {
2248
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2249
- args[_key2 - 1] = arguments[_key2];
2250
- }
2251
- _this2.emit.apply(_this2, [event].concat(args));
2252
- });
2253
- this.modules.external.forEach(function (m) {
2254
- if (m.init) m.init(_this2);
2255
- });
2256
- }
2257
- this.format = this.options.interpolation.format;
2258
- if (!callback) callback = noop;
2259
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2260
- var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2261
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2262
- }
2263
- if (!this.services.languageDetector && !this.options.lng) {
2264
- this.logger.warn('init: no languageDetector is used and no lng is defined');
2265
- }
2266
- var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2267
- storeApi.forEach(function (fcName) {
2268
- _this2[fcName] = function () {
2269
- var _this2$store;
2270
- return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
2271
- };
2272
- });
2273
- var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2274
- storeApiChained.forEach(function (fcName) {
2275
- _this2[fcName] = function () {
2276
- var _this2$store2;
2277
- (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
2278
- return _this2;
2279
- };
2280
- });
2281
- var deferred = defer();
2282
- var load = function load() {
2283
- var finish = function finish(err, t) {
2284
- if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
2285
- _this2.isInitialized = true;
2286
- if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
2287
- _this2.emit('initialized', _this2.options);
2288
- deferred.resolve(t);
2289
- callback(err, t);
2290
- };
2291
- if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
2292
- _this2.changeLanguage(_this2.options.lng, finish);
2293
- };
2294
- if (this.options.resources || !this.options.initImmediate) {
2295
- load();
2296
- } else {
2297
- setTimeout(load, 0);
2298
- }
2299
- return deferred;
2300
- }
2301
- }, {
2302
- key: "loadResources",
2303
- value: function loadResources(language) {
2304
- var _this3 = this;
2305
- var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2306
- var usedCallback = callback;
2307
- var usedLng = typeof language === 'string' ? language : this.language;
2308
- if (typeof language === 'function') usedCallback = language;
2309
- if (!this.options.resources || this.options.partialBundledLanguages) {
2310
- if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
2311
- var toLoad = [];
2312
- var append = function append(lng) {
2313
- if (!lng) return;
2314
- var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
2315
- lngs.forEach(function (l) {
2316
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
2317
- });
2318
- };
2319
- if (!usedLng) {
2320
- var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2321
- fallbacks.forEach(function (l) {
2322
- return append(l);
2323
- });
2324
- } else {
2325
- append(usedLng);
2326
- }
2327
- if (this.options.preload) {
2328
- this.options.preload.forEach(function (l) {
2329
- return append(l);
2330
- });
2331
- }
2332
- this.services.backendConnector.load(toLoad, this.options.ns, function (e) {
2333
- if (!e && !_this3.resolvedLanguage && _this3.language) _this3.setResolvedLanguage(_this3.language);
2334
- usedCallback(e);
2335
- });
2336
- } else {
2337
- usedCallback(null);
2338
- }
2339
- }
2340
- }, {
2341
- key: "reloadResources",
2342
- value: function reloadResources(lngs, ns, callback) {
2343
- var deferred = defer();
2344
- if (!lngs) lngs = this.languages;
2345
- if (!ns) ns = this.options.ns;
2346
- if (!callback) callback = noop;
2347
- this.services.backendConnector.reload(lngs, ns, function (err) {
2348
- deferred.resolve();
2349
- callback(err);
2350
- });
2351
- return deferred;
2352
- }
2353
- }, {
2354
- key: "use",
2355
- value: function use(module) {
2356
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2357
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2358
- if (module.type === 'backend') {
2359
- this.modules.backend = module;
2360
- }
2361
- if (module.type === 'logger' || module.log && module.warn && module.error) {
2362
- this.modules.logger = module;
2363
- }
2364
- if (module.type === 'languageDetector') {
2365
- this.modules.languageDetector = module;
2366
- }
2367
- if (module.type === 'i18nFormat') {
2368
- this.modules.i18nFormat = module;
2369
- }
2370
- if (module.type === 'postProcessor') {
2371
- postProcessor.addPostProcessor(module);
2372
- }
2373
- if (module.type === 'formatter') {
2374
- this.modules.formatter = module;
2375
- }
2376
- if (module.type === '3rdParty') {
2377
- this.modules.external.push(module);
2378
- }
2379
- return this;
2380
- }
2381
- }, {
2382
- key: "setResolvedLanguage",
2383
- value: function setResolvedLanguage(l) {
2384
- if (!l || !this.languages) return;
2385
- if (['cimode', 'dev'].indexOf(l) > -1) return;
2386
- for (var li = 0; li < this.languages.length; li++) {
2387
- var lngInLngs = this.languages[li];
2388
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2389
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2390
- this.resolvedLanguage = lngInLngs;
2391
- break;
2392
- }
2393
- }
2394
- }
2395
- }, {
2396
- key: "changeLanguage",
2397
- value: function changeLanguage(lng, callback) {
2398
- var _this4 = this;
2399
- this.isLanguageChangingTo = lng;
2400
- var deferred = defer();
2401
- this.emit('languageChanging', lng);
2402
- var setLngProps = function setLngProps(l) {
2403
- _this4.language = l;
2404
- _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
2405
- _this4.resolvedLanguage = undefined;
2406
- _this4.setResolvedLanguage(l);
2407
- };
2408
- var done = function done(err, l) {
2409
- if (l) {
2410
- setLngProps(l);
2411
- _this4.translator.changeLanguage(l);
2412
- _this4.isLanguageChangingTo = undefined;
2413
- _this4.emit('languageChanged', l);
2414
- _this4.logger.log('languageChanged', l);
2415
- } else {
2416
- _this4.isLanguageChangingTo = undefined;
2417
- }
2418
- deferred.resolve(function () {
2419
- return _this4.t.apply(_this4, arguments);
2420
- });
2421
- if (callback) callback(err, function () {
2422
- return _this4.t.apply(_this4, arguments);
2423
- });
2424
- };
2425
- var setLng = function setLng(lngs) {
2426
- if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
2427
- var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
2428
- if (l) {
2429
- if (!_this4.language) {
2430
- setLngProps(l);
2431
- }
2432
- if (!_this4.translator.language) _this4.translator.changeLanguage(l);
2433
- if (_this4.services.languageDetector && _this4.services.languageDetector.cacheUserLanguage) _this4.services.languageDetector.cacheUserLanguage(l);
2434
- }
2435
- _this4.loadResources(l, function (err) {
2436
- done(err, l);
2437
- });
2438
- };
2439
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2440
- setLng(this.services.languageDetector.detect());
2441
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2442
- if (this.services.languageDetector.detect.length === 0) {
2443
- this.services.languageDetector.detect().then(setLng);
2444
- } else {
2445
- this.services.languageDetector.detect(setLng);
2446
- }
2447
- } else {
2448
- setLng(lng);
2449
- }
2450
- return deferred;
2451
- }
2452
- }, {
2453
- key: "getFixedT",
2454
- value: function getFixedT(lng, ns, keyPrefix) {
2455
- var _this5 = this;
2456
- var fixedT = function fixedT(key, opts) {
2457
- var options;
2458
- if (_typeof$1(opts) !== 'object') {
2459
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
2460
- rest[_key3 - 2] = arguments[_key3];
2461
- }
2462
- options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2463
- } else {
2464
- options = _objectSpread$8({}, opts);
2465
- }
2466
- options.lng = options.lng || fixedT.lng;
2467
- options.lngs = options.lngs || fixedT.lngs;
2468
- options.ns = options.ns || fixedT.ns;
2469
- options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
2470
- var keySeparator = _this5.options.keySeparator || '.';
2471
- var resultKey;
2472
- if (options.keyPrefix && Array.isArray(key)) {
2473
- resultKey = key.map(function (k) {
2474
- return "".concat(options.keyPrefix).concat(keySeparator).concat(k);
2475
- });
2476
- } else {
2477
- resultKey = options.keyPrefix ? "".concat(options.keyPrefix).concat(keySeparator).concat(key) : key;
2478
- }
2479
- return _this5.t(resultKey, options);
2480
- };
2481
- if (typeof lng === 'string') {
2482
- fixedT.lng = lng;
2483
- } else {
2484
- fixedT.lngs = lng;
2485
- }
2486
- fixedT.ns = ns;
2487
- fixedT.keyPrefix = keyPrefix;
2488
- return fixedT;
2489
- }
2490
- }, {
2491
- key: "t",
2492
- value: function t() {
2493
- var _this$translator;
2494
- return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
2495
- }
2496
- }, {
2497
- key: "exists",
2498
- value: function exists() {
2499
- var _this$translator2;
2500
- return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
2501
- }
2502
- }, {
2503
- key: "setDefaultNamespace",
2504
- value: function setDefaultNamespace(ns) {
2505
- this.options.defaultNS = ns;
2506
- }
2507
- }, {
2508
- key: "hasLoadedNamespace",
2509
- value: function hasLoadedNamespace(ns) {
2510
- var _this6 = this;
2511
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2512
- if (!this.isInitialized) {
2513
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2514
- return false;
2515
- }
2516
- if (!this.languages || !this.languages.length) {
2517
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2518
- return false;
2519
- }
2520
- var lng = this.resolvedLanguage || this.languages[0];
2521
- var fallbackLng = this.options ? this.options.fallbackLng : false;
2522
- var lastLng = this.languages[this.languages.length - 1];
2523
- if (lng.toLowerCase() === 'cimode') return true;
2524
- var loadNotPending = function loadNotPending(l, n) {
2525
- var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
2526
- return loadState === -1 || loadState === 2;
2527
- };
2528
- if (options.precheck) {
2529
- var preResult = options.precheck(this, loadNotPending);
2530
- if (preResult !== undefined) return preResult;
2531
- }
2532
- if (this.hasResourceBundle(lng, ns)) return true;
2533
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2534
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2535
- return false;
2536
- }
2537
- }, {
2538
- key: "loadNamespaces",
2539
- value: function loadNamespaces(ns, callback) {
2540
- var _this7 = this;
2541
- var deferred = defer();
2542
- if (!this.options.ns) {
2543
- if (callback) callback();
2544
- return Promise.resolve();
2545
- }
2546
- if (typeof ns === 'string') ns = [ns];
2547
- ns.forEach(function (n) {
2548
- if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
2549
- });
2550
- this.loadResources(function (err) {
2551
- deferred.resolve();
2552
- if (callback) callback(err);
2553
- });
2554
- return deferred;
2555
- }
2556
- }, {
2557
- key: "loadLanguages",
2558
- value: function loadLanguages(lngs, callback) {
2559
- var deferred = defer();
2560
- if (typeof lngs === 'string') lngs = [lngs];
2561
- var preloaded = this.options.preload || [];
2562
- var newLngs = lngs.filter(function (lng) {
2563
- return preloaded.indexOf(lng) < 0;
2564
- });
2565
- if (!newLngs.length) {
2566
- if (callback) callback();
2567
- return Promise.resolve();
2568
- }
2569
- this.options.preload = preloaded.concat(newLngs);
2570
- this.loadResources(function (err) {
2571
- deferred.resolve();
2572
- if (callback) callback(err);
2573
- });
2574
- return deferred;
2575
- }
2576
- }, {
2577
- key: "dir",
2578
- value: function dir(lng) {
2579
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
2580
- if (!lng) return 'rtl';
2581
- var 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'];
2582
- var languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
2583
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2584
- }
2585
- }, {
2586
- key: "cloneInstance",
2587
- value: function cloneInstance() {
2588
- var _this8 = this;
2589
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2590
- var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2591
- var mergedOptions = _objectSpread$8(_objectSpread$8(_objectSpread$8({}, this.options), options), {
2592
- isClone: true
2593
- });
2594
- var clone = new I18n(mergedOptions);
2595
- if (options.debug !== undefined || options.prefix !== undefined) {
2596
- clone.logger = clone.logger.clone(options);
2597
- }
2598
- var membersToCopy = ['store', 'services', 'language'];
2599
- membersToCopy.forEach(function (m) {
2600
- clone[m] = _this8[m];
2601
- });
2602
- clone.services = _objectSpread$8({}, this.services);
2603
- clone.services.utils = {
2604
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2605
- };
2606
- clone.translator = new Translator(clone.services, clone.options);
2607
- clone.translator.on('*', function (event) {
2608
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
2609
- args[_key4 - 1] = arguments[_key4];
2610
- }
2611
- clone.emit.apply(clone, [event].concat(args));
2612
- });
2613
- clone.init(mergedOptions, callback);
2614
- clone.translator.options = clone.options;
2615
- clone.translator.backendConnector.services.utils = {
2616
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2617
- };
2618
- return clone;
2619
- }
2620
- }, {
2621
- key: "toJSON",
2622
- value: function toJSON() {
2623
- return {
2624
- options: this.options,
2625
- store: this.store,
2626
- language: this.language,
2627
- languages: this.languages,
2628
- resolvedLanguage: this.resolvedLanguage
2629
- };
2630
- }
2631
- }]);
2632
- return I18n;
2633
- }(EventEmitter);
2634
- _defineProperty(I18n, "createInstance", function () {
2635
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2636
- var callback = arguments.length > 1 ? arguments[1] : undefined;
2637
- return new I18n(options, callback);
2638
- });
2639
- var instance = I18n.createInstance();
2640
- instance.createInstance = I18n.createInstance;
2641
-
2642
- instance.createInstance;
2643
- instance.dir;
2644
- instance.init;
2645
- instance.loadResources;
2646
- instance.reloadResources;
2647
- instance.use;
2648
- instance.changeLanguage;
2649
- instance.getFixedT;
2650
- var t$1 = instance.t;
2651
- instance.exists;
2652
- instance.setDefaultNamespace;
2653
- instance.hasLoadedNamespace;
2654
- instance.loadNamespaces;
2655
- instance.loadLanguages;
2656
-
2657
- var arr = [];
2658
- var each = arr.forEach;
2659
- var slice = arr.slice;
2660
- function defaults(obj) {
2661
- each.call(slice.call(arguments, 1), function (source) {
2662
- if (source) {
2663
- for (var prop in source) {
2664
- if (obj[prop] === undefined) obj[prop] = source[prop];
2665
- }
2666
- }
2667
- });
2668
- return obj;
2669
- }
2670
-
2671
- // eslint-disable-next-line no-control-regex
2672
- var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
2673
- var serializeCookie = function serializeCookie(name, val, options) {
2674
- var opt = options || {};
2675
- opt.path = opt.path || '/';
2676
- var value = encodeURIComponent(val);
2677
- var str = "".concat(name, "=").concat(value);
2678
- if (opt.maxAge > 0) {
2679
- var maxAge = opt.maxAge - 0;
2680
- if (Number.isNaN(maxAge)) throw new Error('maxAge should be a Number');
2681
- str += "; Max-Age=".concat(Math.floor(maxAge));
2682
- }
2683
- if (opt.domain) {
2684
- if (!fieldContentRegExp.test(opt.domain)) {
2685
- throw new TypeError('option domain is invalid');
2686
- }
2687
- str += "; Domain=".concat(opt.domain);
2688
- }
2689
- if (opt.path) {
2690
- if (!fieldContentRegExp.test(opt.path)) {
2691
- throw new TypeError('option path is invalid');
2692
- }
2693
- str += "; Path=".concat(opt.path);
2694
- }
2695
- if (opt.expires) {
2696
- if (typeof opt.expires.toUTCString !== 'function') {
2697
- throw new TypeError('option expires is invalid');
2698
- }
2699
- str += "; Expires=".concat(opt.expires.toUTCString());
2700
- }
2701
- if (opt.httpOnly) str += '; HttpOnly';
2702
- if (opt.secure) str += '; Secure';
2703
- if (opt.sameSite) {
2704
- var sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
2705
- switch (sameSite) {
2706
- case true:
2707
- str += '; SameSite=Strict';
2708
- break;
2709
- case 'lax':
2710
- str += '; SameSite=Lax';
2711
- break;
2712
- case 'strict':
2713
- str += '; SameSite=Strict';
2714
- break;
2715
- case 'none':
2716
- str += '; SameSite=None';
2717
- break;
2718
- default:
2719
- throw new TypeError('option sameSite is invalid');
2720
- }
2721
- }
2722
- return str;
2723
- };
2724
- var cookie = {
2725
- create: function create(name, value, minutes, domain) {
2726
- var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
2727
- path: '/',
2728
- sameSite: 'strict'
2729
- };
2730
- if (minutes) {
2731
- cookieOptions.expires = new Date();
2732
- cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
2733
- }
2734
- if (domain) cookieOptions.domain = domain;
2735
- document.cookie = serializeCookie(name, encodeURIComponent(value), cookieOptions);
2736
- },
2737
- read: function read(name) {
2738
- var nameEQ = "".concat(name, "=");
2739
- var ca = document.cookie.split(';');
2740
- for (var i = 0; i < ca.length; i++) {
2741
- var c = ca[i];
2742
- while (c.charAt(0) === ' ') {
2743
- c = c.substring(1, c.length);
2744
- }
2745
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
2746
- }
2747
- return null;
2748
- },
2749
- remove: function remove(name) {
2750
- this.create(name, '', -1);
2751
- }
2752
- };
2753
- var cookie$1 = {
2754
- name: 'cookie',
2755
- lookup: function lookup(options) {
2756
- var found;
2757
- if (options.lookupCookie && typeof document !== 'undefined') {
2758
- var c = cookie.read(options.lookupCookie);
2759
- if (c) found = c;
2760
- }
2761
- return found;
2762
- },
2763
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
2764
- if (options.lookupCookie && typeof document !== 'undefined') {
2765
- cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
2766
- }
2767
- }
2768
- };
2769
-
2770
- var querystring = {
2771
- name: 'querystring',
2772
- lookup: function lookup(options) {
2773
- var found;
2774
- if (typeof window !== 'undefined') {
2775
- var search = window.location.search;
2776
- if (!window.location.search && window.location.hash && window.location.hash.indexOf('?') > -1) {
2777
- search = window.location.hash.substring(window.location.hash.indexOf('?'));
2778
- }
2779
- var query = search.substring(1);
2780
- var params = query.split('&');
2781
- for (var i = 0; i < params.length; i++) {
2782
- var pos = params[i].indexOf('=');
2783
- if (pos > 0) {
2784
- var key = params[i].substring(0, pos);
2785
- if (key === options.lookupQuerystring) {
2786
- found = params[i].substring(pos + 1);
2787
- }
2788
- }
2789
- }
2790
- }
2791
- return found;
2792
- }
2793
- };
2794
-
2795
- var hasLocalStorageSupport = null;
2796
- var localStorageAvailable = function localStorageAvailable() {
2797
- if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
2798
- try {
2799
- hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
2800
- var testKey = 'i18next.translate.boo';
2801
- window.localStorage.setItem(testKey, 'foo');
2802
- window.localStorage.removeItem(testKey);
2803
- } catch (e) {
2804
- hasLocalStorageSupport = false;
2805
- }
2806
- return hasLocalStorageSupport;
2807
- };
2808
- var localStorage = {
2809
- name: 'localStorage',
2810
- lookup: function lookup(options) {
2811
- var found;
2812
- if (options.lookupLocalStorage && localStorageAvailable()) {
2813
- var lng = window.localStorage.getItem(options.lookupLocalStorage);
2814
- if (lng) found = lng;
2815
- }
2816
- return found;
2817
- },
2818
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
2819
- if (options.lookupLocalStorage && localStorageAvailable()) {
2820
- window.localStorage.setItem(options.lookupLocalStorage, lng);
2821
- }
2822
- }
2823
- };
2824
-
2825
- var hasSessionStorageSupport = null;
2826
- var sessionStorageAvailable = function sessionStorageAvailable() {
2827
- if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
2828
- try {
2829
- hasSessionStorageSupport = window !== 'undefined' && window.sessionStorage !== null;
2830
- var testKey = 'i18next.translate.boo';
2831
- window.sessionStorage.setItem(testKey, 'foo');
2832
- window.sessionStorage.removeItem(testKey);
2833
- } catch (e) {
2834
- hasSessionStorageSupport = false;
2835
- }
2836
- return hasSessionStorageSupport;
2837
- };
2838
- var sessionStorage = {
2839
- name: 'sessionStorage',
2840
- lookup: function lookup(options) {
2841
- var found;
2842
- if (options.lookupSessionStorage && sessionStorageAvailable()) {
2843
- var lng = window.sessionStorage.getItem(options.lookupSessionStorage);
2844
- if (lng) found = lng;
2845
- }
2846
- return found;
2847
- },
2848
- cacheUserLanguage: function cacheUserLanguage(lng, options) {
2849
- if (options.lookupSessionStorage && sessionStorageAvailable()) {
2850
- window.sessionStorage.setItem(options.lookupSessionStorage, lng);
2851
- }
2852
- }
2853
- };
2854
-
2855
- var navigator$1 = {
2856
- name: 'navigator',
2857
- lookup: function lookup(options) {
2858
- var found = [];
2859
- if (typeof navigator !== 'undefined') {
2860
- if (navigator.languages) {
2861
- // chrome only; not an array, so can't use .push.apply instead of iterating
2862
- for (var i = 0; i < navigator.languages.length; i++) {
2863
- found.push(navigator.languages[i]);
2864
- }
2865
- }
2866
- if (navigator.userLanguage) {
2867
- found.push(navigator.userLanguage);
2868
- }
2869
- if (navigator.language) {
2870
- found.push(navigator.language);
2871
- }
2872
- }
2873
- return found.length > 0 ? found : undefined;
2874
- }
2875
- };
2876
-
2877
- var htmlTag = {
2878
- name: 'htmlTag',
2879
- lookup: function lookup(options) {
2880
- var found;
2881
- var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
2882
- if (htmlTag && typeof htmlTag.getAttribute === 'function') {
2883
- found = htmlTag.getAttribute('lang');
2884
- }
2885
- return found;
2886
- }
2887
- };
2888
-
2889
- var path = {
2890
- name: 'path',
2891
- lookup: function lookup(options) {
2892
- var found;
2893
- if (typeof window !== 'undefined') {
2894
- var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
2895
- if (language instanceof Array) {
2896
- if (typeof options.lookupFromPathIndex === 'number') {
2897
- if (typeof language[options.lookupFromPathIndex] !== 'string') {
2898
- return undefined;
2899
- }
2900
- found = language[options.lookupFromPathIndex].replace('/', '');
2901
- } else {
2902
- found = language[0].replace('/', '');
2903
- }
2904
- }
2905
- }
2906
- return found;
2907
- }
2908
- };
2909
-
2910
- var subdomain = {
2911
- name: 'subdomain',
2912
- lookup: function lookup(options) {
2913
- // If given get the subdomain index else 1
2914
- var lookupFromSubdomainIndex = typeof options.lookupFromSubdomainIndex === 'number' ? options.lookupFromSubdomainIndex + 1 : 1;
2915
- // get all matches if window.location. is existing
2916
- // first item of match is the match itself and the second is the first group macht which sould be the first subdomain match
2917
- // is the hostname no public domain get the or option of localhost
2918
- var language = typeof window !== 'undefined' && window.location && window.location.hostname && window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);
2919
-
2920
- // if there is no match (null) return undefined
2921
- if (!language) return undefined;
2922
- // return the given group match
2923
- return language[lookupFromSubdomainIndex];
2924
- }
2925
- };
2926
-
2927
- function getDefaults$1() {
2928
- return {
2929
- order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
2930
- lookupQuerystring: 'lng',
2931
- lookupCookie: 'i18next',
2932
- lookupLocalStorage: 'i18nextLng',
2933
- lookupSessionStorage: 'i18nextLng',
2934
- // cache user language
2935
- caches: ['localStorage'],
2936
- excludeCacheFor: ['cimode']
2937
- // cookieMinutes: 10,
2938
- // cookieDomain: 'myDomain'
2939
- };
2940
- }
2941
- var Browser = /*#__PURE__*/function () {
2942
- function Browser(services) {
2943
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2944
- _classCallCheck(this, Browser);
2945
- this.type = 'languageDetector';
2946
- this.detectors = {};
2947
- this.init(services, options);
2948
- }
2949
- _createClass(Browser, [{
2950
- key: "init",
2951
- value: function init(services) {
2952
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2953
- var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2954
- this.services = services;
2955
- this.options = defaults(options, this.options || {}, getDefaults$1());
2956
-
2957
- // backwards compatibility
2958
- if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
2959
- this.i18nOptions = i18nOptions;
2960
- this.addDetector(cookie$1);
2961
- this.addDetector(querystring);
2962
- this.addDetector(localStorage);
2963
- this.addDetector(sessionStorage);
2964
- this.addDetector(navigator$1);
2965
- this.addDetector(htmlTag);
2966
- this.addDetector(path);
2967
- this.addDetector(subdomain);
2968
- }
2969
- }, {
2970
- key: "addDetector",
2971
- value: function addDetector(detector) {
2972
- this.detectors[detector.name] = detector;
2973
- }
2974
- }, {
2975
- key: "detect",
2976
- value: function detect(detectionOrder) {
2977
- var _this = this;
2978
- if (!detectionOrder) detectionOrder = this.options.order;
2979
- var detected = [];
2980
- detectionOrder.forEach(function (detectorName) {
2981
- if (_this.detectors[detectorName]) {
2982
- var lookup = _this.detectors[detectorName].lookup(_this.options);
2983
- if (lookup && typeof lookup === 'string') lookup = [lookup];
2984
- if (lookup) detected = detected.concat(lookup);
2985
- }
2986
- });
2987
- if (this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
2988
- return detected.length > 0 ? detected[0] : null; // a little backward compatibility
2989
- }
2990
- }, {
2991
- key: "cacheUserLanguage",
2992
- value: function cacheUserLanguage(lng, caches) {
2993
- var _this2 = this;
2994
- if (!caches) caches = this.options.caches;
2995
- if (!caches) return;
2996
- if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
2997
- caches.forEach(function (cacheName) {
2998
- if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
2999
- });
3000
- }
3001
- }]);
3002
- return Browser;
3003
- }();
3004
- Browser.type = 'languageDetector';
3005
-
3006
- function _objectWithoutPropertiesLoose(source, excluded) {
3007
- if (source == null) return {};
3008
- var target = {};
3009
- var sourceKeys = Object.keys(source);
3010
- var key, i;
3011
- for (i = 0; i < sourceKeys.length; i++) {
3012
- key = sourceKeys[i];
3013
- if (excluded.indexOf(key) >= 0) continue;
3014
- target[key] = source[key];
3015
- }
3016
- return target;
3017
- }
3018
-
3019
- function _objectWithoutProperties(source, excluded) {
3020
- if (source == null) return {};
3021
- var target = _objectWithoutPropertiesLoose(source, excluded);
3022
- var key, i;
3023
- if (Object.getOwnPropertySymbols) {
3024
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
3025
- for (i = 0; i < sourceSymbolKeys.length; i++) {
3026
- key = sourceSymbolKeys[i];
3027
- if (excluded.indexOf(key) >= 0) continue;
3028
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
3029
- target[key] = source[key];
3030
- }
3031
- }
3032
- return target;
3033
- }
3034
-
3035
- function getDefaultExportFromCjs (x) {
3036
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3037
- }
3038
-
3039
- /**
3040
- * This file automatically generated from `pre-publish.js`.
3041
- * Do not manually edit.
3042
- */
3043
-
3044
- var voidElements = {
3045
- "area": true,
3046
- "base": true,
3047
- "br": true,
3048
- "col": true,
3049
- "embed": true,
3050
- "hr": true,
3051
- "img": true,
3052
- "input": true,
3053
- "link": true,
3054
- "meta": true,
3055
- "param": true,
3056
- "source": true,
3057
- "track": true,
3058
- "wbr": true
3059
- };
3060
-
3061
- var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
3062
-
3063
- var t=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function n(n){var r={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},i=n.match(/<\/?([^\s]+?)[/\s>]/);if(i&&(r.name=i[1],(e[i[1]]||"/"===n.charAt(n.length-2))&&(r.voidElement=!0),r.name.startsWith("!--"))){var s=n.indexOf("--\x3e");return {type:"comment",comment:-1!==s?n.slice(4,s):""}}for(var a=new RegExp(t),c=null;null!==(c=a.exec(n));)if(c[0].trim())if(c[1]){var o=c[1].trim(),l=[o,""];o.indexOf("=")>-1&&(l=o.split("=")),r.attrs[l[0]]=l[1],a.lastIndex--;}else c[2]&&(r.attrs[c[2]]=c[3].trim().substring(1,c[3].length-1));return r}var r=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,i=/^\s*$/,s=Object.create(null);function a(e,t){switch(t.type){case"text":return e+t.content;case"tag":return e+="<"+t.name+(t.attrs?function(e){var t=[];for(var n in e)t.push(n+'="'+e[n]+'"');return t.length?" "+t.join(" "):""}(t.attrs):"")+(t.voidElement?"/>":">"),t.voidElement?e:e+t.children.reduce(a,"")+"</"+t.name+">";case"comment":return e+"\x3c!--"+t.comment+"--\x3e"}}var c={parse:function(e,t){t||(t={}),t.components||(t.components=s);var a,c=[],o=[],l=-1,m=!1;if(0!==e.indexOf("<")){var u=e.indexOf("<");c.push({type:"text",content:-1===u?e:e.substring(0,u)});}return e.replace(r,function(r,s){if(m){if(r!=="</"+a.name+">")return;m=!1;}var u,f="/"!==r.charAt(1),h=r.startsWith("\x3c!--"),p=s+r.length,d=e.charAt(p);if(h){var v=n(r);return l<0?(c.push(v),c):((u=o[l]).children.push(v),c)}if(f&&(l++,"tag"===(a=n(r)).type&&t.components[a.name]&&(a.type="component",m=!0),a.voidElement||m||!d||"<"===d||a.children.push({type:"text",content:e.slice(p,e.indexOf("<",p))}),0===l&&c.push(a),(u=o[l-1])&&u.children.push(a),o[l]=a),(!f||a.voidElement)&&(l>-1&&(a.voidElement||a.name===r.slice(2,-1))&&(l--,a=-1===l?c:o[l]),!m&&"<"!==d&&d)){u=-1===l?c:o[l].children;var x=e.indexOf("<",p),g=e.slice(p,-1===x?void 0:x);i.test(g)&&(g=" "),(x>-1&&l+u.length>=0||" "!==g)&&u.push({type:"text",content:g});}}),c},stringify:function(e){return e.reduce(function(e,t){return e+a("",t)},"")}};
3064
-
3065
- /**
3066
- * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection
3067
- *
3068
- * Permission is hereby granted, free of charge, to any person obtaining a copy
3069
- * of this software and associated documentation files (the "Software"), to deal
3070
- * in the Software without restriction, including without limitation the rights
3071
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3072
- * copies of the Software, and to permit persons to whom the Software is
3073
- * furnished to do so, subject to the following conditions:
3074
- *
3075
- * The above copyright notice and this permission notice shall be included in
3076
- * all copies or substantial portions of the Software.
3077
- *
3078
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3079
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3080
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3081
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3082
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3083
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3084
- * THE SOFTWARE.
3085
- */
3086
-
3087
- var replace = ''.replace;
3088
- var es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
3089
- var unes = {
3090
- '&amp;': '&',
3091
- '&#38;': '&',
3092
- '&lt;': '<',
3093
- '&#60;': '<',
3094
- '&gt;': '>',
3095
- '&#62;': '>',
3096
- '&apos;': "'",
3097
- '&#39;': "'",
3098
- '&quot;': '"',
3099
- '&#34;': '"'
3100
- };
3101
-
3102
- function unescape(un) {
3103
- return replace.call(un, es, cape);
3104
- }
3105
- function cape(m) {
3106
- return unes[m];
3107
- }
3108
-
3109
- function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
3110
-
3111
- function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3112
- var defaultOptions = {
3113
- bindI18n: 'languageChanged',
3114
- bindI18nStore: '',
3115
- transEmptyNodeValue: '',
3116
- transSupportBasicHtmlNodes: true,
3117
- transWrapTextNodes: '',
3118
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
3119
- useSuspense: true
3120
- };
3121
- var i18nInstance;
3122
- var I18nContext = React.createContext();
3123
- function setDefaults() {
3124
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3125
- defaultOptions = _objectSpread$7(_objectSpread$7({}, defaultOptions), options);
3126
- }
3127
- function getDefaults() {
3128
- return defaultOptions;
3129
- }
3130
- var ReportNamespaces = function () {
3131
- function ReportNamespaces() {
3132
- _classCallCheck(this, ReportNamespaces);
3133
-
3134
- this.usedNamespaces = {};
3135
- }
3136
-
3137
- _createClass(ReportNamespaces, [{
3138
- key: "addUsedNamespaces",
3139
- value: function addUsedNamespaces(namespaces) {
3140
- var _this = this;
3141
-
3142
- namespaces.forEach(function (ns) {
3143
- if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;
3144
- });
3145
- }
3146
- }, {
3147
- key: "getUsedNamespaces",
3148
- value: function getUsedNamespaces() {
3149
- return Object.keys(this.usedNamespaces);
3150
- }
3151
- }]);
3152
-
3153
- return ReportNamespaces;
3154
- }();
3155
- function setI18n(instance) {
3156
- i18nInstance = instance;
3157
- }
3158
- function getI18n() {
3159
- return i18nInstance;
3160
- }
3161
- var initReactI18next = {
3162
- type: '3rdParty',
3163
- init: function init(instance) {
3164
- setDefaults(instance.options.react);
3165
- setI18n(instance);
3166
- }
3167
- };
3168
-
3169
- function warn() {
3170
- if (console && console.warn) {
3171
- var _console;
3172
-
3173
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3174
- args[_key] = arguments[_key];
3175
- }
3176
-
3177
- if (typeof args[0] === 'string') args[0] = "react-i18next:: ".concat(args[0]);
3178
-
3179
- (_console = console).warn.apply(_console, args);
3180
- }
3181
- }
3182
- var alreadyWarned = {};
3183
- function warnOnce() {
3184
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3185
- args[_key2] = arguments[_key2];
3186
- }
3187
-
3188
- if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
3189
- if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
3190
- warn.apply(void 0, args);
3191
- }
3192
- function loadNamespaces(i18n, ns, cb) {
3193
- i18n.loadNamespaces(ns, function () {
3194
- if (i18n.isInitialized) {
3195
- cb();
3196
- } else {
3197
- var initialized = function initialized() {
3198
- setTimeout(function () {
3199
- i18n.off('initialized', initialized);
3200
- }, 0);
3201
- cb();
3202
- };
3203
-
3204
- i18n.on('initialized', initialized);
3205
- }
3206
- });
3207
- }
3208
-
3209
- function oldI18nextHasLoadedNamespace(ns, i18n) {
3210
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
3211
- var lng = i18n.languages[0];
3212
- var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
3213
- var lastLng = i18n.languages[i18n.languages.length - 1];
3214
- if (lng.toLowerCase() === 'cimode') return true;
3215
-
3216
- var loadNotPending = function loadNotPending(l, n) {
3217
- var loadState = i18n.services.backendConnector.state["".concat(l, "|").concat(n)];
3218
- return loadState === -1 || loadState === 2;
3219
- };
3220
-
3221
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
3222
- if (i18n.hasResourceBundle(lng, ns)) return true;
3223
- if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
3224
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
3225
- return false;
3226
- }
3227
-
3228
- function hasLoadedNamespace(ns, i18n) {
3229
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
3230
-
3231
- if (!i18n.languages || !i18n.languages.length) {
3232
- warnOnce('i18n.languages were undefined or empty', i18n.languages);
3233
- return true;
3234
- }
3235
-
3236
- var isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;
3237
-
3238
- if (!isNewerI18next) {
3239
- return oldI18nextHasLoadedNamespace(ns, i18n, options);
34
+ function _toPrimitive(input, hint) {
35
+ if (_typeof$1(input) !== "object" || input === null) return input;
36
+ var prim = input[Symbol.toPrimitive];
37
+ if (prim !== undefined) {
38
+ var res = prim.call(input, hint || "default");
39
+ if (_typeof$1(res) !== "object") return res;
40
+ throw new TypeError("@@toPrimitive must return a primitive value.");
3240
41
  }
3241
-
3242
- return i18n.hasLoadedNamespace(ns, {
3243
- precheck: function precheck(i18nInstance, loadNotPending) {
3244
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
3245
- }
3246
- });
3247
- }
3248
-
3249
- var _excluded = ["format"],
3250
- _excluded2 = ["children", "count", "parent", "i18nKey", "context", "tOptions", "values", "defaults", "components", "ns", "i18n", "t", "shouldUnescape"];
3251
-
3252
- function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
3253
-
3254
- function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3255
-
3256
- function hasChildren(node, checkLength) {
3257
- if (!node) return false;
3258
- var base = node.props ? node.props.children : node.children;
3259
- if (checkLength) return base.length > 0;
3260
- return !!base;
3261
- }
3262
-
3263
- function getChildren(node) {
3264
- if (!node) return [];
3265
- return node && node.children ? node.children : node.props && node.props.children;
3266
- }
3267
-
3268
- function hasValidReactChildren(children) {
3269
- if (Object.prototype.toString.call(children) !== '[object Array]') return false;
3270
- return children.every(function (child) {
3271
- return React.isValidElement(child);
3272
- });
3273
- }
3274
-
3275
- function getAsArray(data) {
3276
- return Array.isArray(data) ? data : [data];
3277
- }
3278
-
3279
- function mergeProps(source, target) {
3280
- var newTarget = _objectSpread$6({}, target);
3281
-
3282
- newTarget.props = Object.assign(source.props, target.props);
3283
- return newTarget;
42
+ return (hint === "string" ? String : Number)(input);
3284
43
  }
3285
44
 
3286
- function nodesToString(children, i18nOptions) {
3287
- if (!children) return '';
3288
- var stringNode = '';
3289
- var childrenArray = getAsArray(children);
3290
- var keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : [];
3291
- childrenArray.forEach(function (child, childIndex) {
3292
- if (typeof child === 'string') {
3293
- stringNode += "".concat(child);
3294
- } else if (React.isValidElement(child)) {
3295
- var childPropsCount = Object.keys(child.props).length;
3296
- var shouldKeepChild = keepArray.indexOf(child.type) > -1;
3297
- var childChildren = child.props.children;
3298
-
3299
- if (!childChildren && shouldKeepChild && childPropsCount === 0) {
3300
- stringNode += "<".concat(child.type, "/>");
3301
- } else if (!childChildren && (!shouldKeepChild || childPropsCount !== 0)) {
3302
- stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
3303
- } else if (child.props.i18nIsDynamicList) {
3304
- stringNode += "<".concat(childIndex, "></").concat(childIndex, ">");
3305
- } else if (shouldKeepChild && childPropsCount === 1 && typeof childChildren === 'string') {
3306
- stringNode += "<".concat(child.type, ">").concat(childChildren, "</").concat(child.type, ">");
3307
- } else {
3308
- var content = nodesToString(childChildren, i18nOptions);
3309
- stringNode += "<".concat(childIndex, ">").concat(content, "</").concat(childIndex, ">");
3310
- }
3311
- } else if (child === null) {
3312
- warn("Trans: the passed in value is invalid - seems you passed in a null child.");
3313
- } else if (_typeof$1(child) === 'object') {
3314
- var format = child.format,
3315
- clone = _objectWithoutProperties(child, _excluded);
3316
-
3317
- var keys = Object.keys(clone);
3318
-
3319
- if (keys.length === 1) {
3320
- var value = format ? "".concat(keys[0], ", ").concat(format) : keys[0];
3321
- stringNode += "{{".concat(value, "}}");
3322
- } else {
3323
- warn("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.", child);
3324
- }
3325
- } else {
3326
- warn("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.", child);
3327
- }
3328
- });
3329
- return stringNode;
45
+ function _toPropertyKey(arg) {
46
+ var key = _toPrimitive(arg, "string");
47
+ return _typeof$1(key) === "symbol" ? key : String(key);
3330
48
  }
3331
49
 
3332
- function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) {
3333
- if (targetString === '') return [];
3334
- var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
3335
- var emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString);
3336
- if (!children && !emptyChildrenButNeedsHandling) return [targetString];
3337
- var data = {};
3338
-
3339
- function getData(childs) {
3340
- var childrenArray = getAsArray(childs);
3341
- childrenArray.forEach(function (child) {
3342
- if (typeof child === 'string') return;
3343
- if (hasChildren(child)) getData(getChildren(child));else if (_typeof$1(child) === 'object' && !React.isValidElement(child)) Object.assign(data, child);
50
+ function _defineProperty(obj, key, value) {
51
+ key = _toPropertyKey(key);
52
+ if (key in obj) {
53
+ Object.defineProperty(obj, key, {
54
+ value: value,
55
+ enumerable: true,
56
+ configurable: true,
57
+ writable: true
3344
58
  });
59
+ } else {
60
+ obj[key] = value;
3345
61
  }
3346
-
3347
- getData(children);
3348
- var ast = c.parse("<0>".concat(targetString, "</0>"));
3349
-
3350
- var opts = _objectSpread$6(_objectSpread$6({}, data), combinedTOpts);
3351
-
3352
- function renderInner(child, node, rootReactNode) {
3353
- var childs = getChildren(child);
3354
- var mappedChildren = mapAST(childs, node.children, rootReactNode);
3355
- return hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
3356
- }
3357
-
3358
- function pushTranslatedJSX(child, inner, mem, i, isVoid) {
3359
- if (child.dummy) child.children = inner;
3360
- mem.push(React.cloneElement(child, _objectSpread$6(_objectSpread$6({}, child.props), {}, {
3361
- key: i
3362
- }), isVoid ? undefined : inner));
3363
- }
3364
-
3365
- function mapAST(reactNode, astNode, rootReactNode) {
3366
- var reactNodes = getAsArray(reactNode);
3367
- var astNodes = getAsArray(astNode);
3368
- return astNodes.reduce(function (mem, node, i) {
3369
- var translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
3370
-
3371
- if (node.type === 'tag') {
3372
- var tmp = reactNodes[parseInt(node.name, 10)];
3373
- if (!tmp && rootReactNode.length === 1 && rootReactNode[0][node.name]) tmp = rootReactNode[0][node.name];
3374
- if (!tmp) tmp = {};
3375
- var child = Object.keys(node.attrs).length !== 0 ? mergeProps({
3376
- props: node.attrs
3377
- }, tmp) : tmp;
3378
- var isElement = React.isValidElement(child);
3379
- var isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
3380
- var isEmptyTransWithHTML = emptyChildrenButNeedsHandling && _typeof$1(child) === 'object' && child.dummy && !isElement;
3381
- var isKnownComponent = _typeof$1(children) === 'object' && children !== null && Object.hasOwnProperty.call(children, node.name);
3382
-
3383
- if (typeof child === 'string') {
3384
- var value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
3385
- mem.push(value);
3386
- } else if (hasChildren(child) || isValidTranslationWithChildren) {
3387
- var inner = renderInner(child, node, rootReactNode);
3388
- pushTranslatedJSX(child, inner, mem, i);
3389
- } else if (isEmptyTransWithHTML) {
3390
- var _inner = mapAST(reactNodes, node.children, rootReactNode);
3391
-
3392
- mem.push(React.cloneElement(child, _objectSpread$6(_objectSpread$6({}, child.props), {}, {
3393
- key: i
3394
- }), _inner));
3395
- } else if (Number.isNaN(parseFloat(node.name))) {
3396
- if (isKnownComponent) {
3397
- var _inner2 = renderInner(child, node, rootReactNode);
3398
-
3399
- pushTranslatedJSX(child, _inner2, mem, i, node.voidElement);
3400
- } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
3401
- if (node.voidElement) {
3402
- mem.push(React.createElement(node.name, {
3403
- key: "".concat(node.name, "-").concat(i)
3404
- }));
3405
- } else {
3406
- var _inner3 = mapAST(reactNodes, node.children, rootReactNode);
3407
-
3408
- mem.push(React.createElement(node.name, {
3409
- key: "".concat(node.name, "-").concat(i)
3410
- }, _inner3));
3411
- }
3412
- } else if (node.voidElement) {
3413
- mem.push("<".concat(node.name, " />"));
3414
- } else {
3415
- var _inner4 = mapAST(reactNodes, node.children, rootReactNode);
3416
-
3417
- mem.push("<".concat(node.name, ">").concat(_inner4, "</").concat(node.name, ">"));
3418
- }
3419
- } else if (_typeof$1(child) === 'object' && !isElement) {
3420
- var content = node.children[0] ? translationContent : null;
3421
- if (content) mem.push(content);
3422
- } else if (node.children.length === 1 && translationContent) {
3423
- mem.push(React.cloneElement(child, _objectSpread$6(_objectSpread$6({}, child.props), {}, {
3424
- key: i
3425
- }), translationContent));
3426
- } else {
3427
- mem.push(React.cloneElement(child, _objectSpread$6(_objectSpread$6({}, child.props), {}, {
3428
- key: i
3429
- })));
3430
- }
3431
- } else if (node.type === 'text') {
3432
- var wrapTextNodes = i18nOptions.transWrapTextNodes;
3433
-
3434
- var _content = shouldUnescape ? unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
3435
-
3436
- if (wrapTextNodes) {
3437
- mem.push(React.createElement(wrapTextNodes, {
3438
- key: "".concat(node.name, "-").concat(i)
3439
- }, _content));
3440
- } else {
3441
- mem.push(_content);
3442
- }
3443
- }
3444
-
3445
- return mem;
3446
- }, []);
3447
- }
3448
-
3449
- var result = mapAST([{
3450
- dummy: true,
3451
- children: children || []
3452
- }], ast, getAsArray(children || []));
3453
- return getChildren(result[0]);
62
+ return obj;
3454
63
  }
3455
64
 
3456
- function Trans(_ref) {
3457
- var children = _ref.children,
3458
- count = _ref.count,
3459
- parent = _ref.parent,
3460
- i18nKey = _ref.i18nKey,
3461
- context = _ref.context,
3462
- _ref$tOptions = _ref.tOptions,
3463
- tOptions = _ref$tOptions === void 0 ? {} : _ref$tOptions,
3464
- values = _ref.values,
3465
- defaults = _ref.defaults,
3466
- components = _ref.components,
3467
- ns = _ref.ns,
3468
- i18nFromProps = _ref.i18n,
3469
- tFromProps = _ref.t,
3470
- shouldUnescape = _ref.shouldUnescape,
3471
- additionalProps = _objectWithoutProperties(_ref, _excluded2);
3472
-
3473
- var _ref2 = useContext(I18nContext) || {},
3474
- i18nFromContext = _ref2.i18n,
3475
- defaultNSFromContext = _ref2.defaultNS;
3476
-
3477
- var i18n = i18nFromProps || i18nFromContext || getI18n();
3478
-
3479
- if (!i18n) {
3480
- warnOnce('You will need to pass in an i18next instance by using i18nextReactModule');
3481
- return children;
3482
- }
3483
-
3484
- var t = tFromProps || i18n.t.bind(i18n) || function (k) {
3485
- return k;
3486
- };
3487
-
3488
- if (context) tOptions.context = context;
3489
-
3490
- var reactI18nextOptions = _objectSpread$6(_objectSpread$6({}, getDefaults()), i18n.options && i18n.options.react);
3491
-
3492
- var namespaces = ns || t.ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
3493
- namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
3494
- var defaultValue = defaults || nodesToString(children, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue || i18nKey;
3495
- var hashTransKey = reactI18nextOptions.hashTransKey;
3496
- var key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
3497
- var interpolationOverride = values ? tOptions.interpolation : {
3498
- interpolation: _objectSpread$6(_objectSpread$6({}, tOptions.interpolation), {}, {
3499
- prefix: '#$?',
3500
- suffix: '?$#'
3501
- })
3502
- };
3503
-
3504
- var combinedTOpts = _objectSpread$6(_objectSpread$6(_objectSpread$6(_objectSpread$6({}, tOptions), {}, {
3505
- count: count
3506
- }, values), interpolationOverride), {}, {
3507
- defaultValue: defaultValue,
3508
- ns: namespaces
3509
- });
3510
-
3511
- var translation = key ? t(key, combinedTOpts) : defaultValue;
3512
- var content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
3513
- var useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent;
3514
- return useAsParent ? React.createElement(useAsParent, additionalProps, content) : content;
65
+ function _arrayWithHoles(arr) {
66
+ if (Array.isArray(arr)) return arr;
3515
67
  }
3516
68
 
3517
69
  function _iterableToArrayLimit(arr, i) {
@@ -3542,204 +94,50 @@ function _iterableToArrayLimit(arr, i) {
3542
94
  }
3543
95
  }
3544
96
 
3545
- function _slicedToArray(arr, i) {
3546
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
97
+ function _arrayLikeToArray(arr, len) {
98
+ if (len == null || len > arr.length) len = arr.length;
99
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
100
+ return arr2;
3547
101
  }
3548
102
 
3549
- function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
3550
-
3551
- function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3552
- function useTranslation(ns) {
3553
- var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3554
- var i18nFromProps = props.i18n;
3555
-
3556
- var _ref = useContext(I18nContext) || {},
3557
- i18nFromContext = _ref.i18n,
3558
- defaultNSFromContext = _ref.defaultNS;
3559
-
3560
- var i18n = i18nFromProps || i18nFromContext || getI18n();
3561
- if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
3562
-
3563
- if (!i18n) {
3564
- warnOnce('You will need to pass in an i18next instance by using initReactI18next');
3565
-
3566
- var notReadyT = function notReadyT(k) {
3567
- return Array.isArray(k) ? k[k.length - 1] : k;
3568
- };
3569
-
3570
- var retNotReady = [notReadyT, {}, false];
3571
- retNotReady.t = notReadyT;
3572
- retNotReady.i18n = {};
3573
- retNotReady.ready = false;
3574
- return retNotReady;
3575
- }
3576
-
3577
- 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.');
3578
-
3579
- var i18nOptions = _objectSpread$5(_objectSpread$5(_objectSpread$5({}, getDefaults()), i18n.options.react), props);
3580
-
3581
- var useSuspense = i18nOptions.useSuspense,
3582
- keyPrefix = i18nOptions.keyPrefix;
3583
- var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
3584
- namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
3585
- if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
3586
- var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(function (n) {
3587
- return hasLoadedNamespace(n, i18n, i18nOptions);
3588
- });
3589
-
3590
- function getT() {
3591
- return i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
3592
- }
3593
-
3594
- var _useState = useState(getT),
3595
- _useState2 = _slicedToArray(_useState, 2),
3596
- t = _useState2[0],
3597
- setT = _useState2[1];
3598
-
3599
- var isMounted = useRef(true);
3600
- useEffect(function () {
3601
- var bindI18n = i18nOptions.bindI18n,
3602
- bindI18nStore = i18nOptions.bindI18nStore;
3603
- isMounted.current = true;
3604
-
3605
- if (!ready && !useSuspense) {
3606
- loadNamespaces(i18n, namespaces, function () {
3607
- if (isMounted.current) setT(getT);
3608
- });
3609
- }
3610
-
3611
- function boundReset() {
3612
- if (isMounted.current) setT(getT);
3613
- }
3614
-
3615
- if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
3616
- if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
3617
- return function () {
3618
- isMounted.current = false;
3619
- if (bindI18n && i18n) bindI18n.split(' ').forEach(function (e) {
3620
- return i18n.off(e, boundReset);
3621
- });
3622
- if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(function (e) {
3623
- return i18n.store.off(e, boundReset);
3624
- });
3625
- };
3626
- }, [i18n, namespaces.join()]);
3627
- var isInitial = useRef(true);
3628
- useEffect(function () {
3629
- if (isMounted.current && !isInitial.current) {
3630
- setT(getT);
3631
- }
3632
-
3633
- isInitial.current = false;
3634
- }, [i18n]);
3635
- var ret = [t, i18n, ready];
3636
- ret.t = t;
3637
- ret.i18n = i18n;
3638
- ret.ready = ready;
3639
- if (ready) return ret;
3640
- if (!ready && !useSuspense) return ret;
3641
- throw new Promise(function (resolve) {
3642
- loadNamespaces(i18n, namespaces, function () {
3643
- resolve();
3644
- });
3645
- });
103
+ function _unsupportedIterableToArray(o, minLen) {
104
+ if (!o) return;
105
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
106
+ var n = Object.prototype.toString.call(o).slice(8, -1);
107
+ if (n === "Object" && o.constructor) n = o.constructor.name;
108
+ if (n === "Map" || n === "Set") return Array.from(o);
109
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
3646
110
  }
3647
111
 
3648
- var neetoMessageTemplate = {
3649
- template: {
3650
- addEmailTemplate: "Add new email template",
3651
- addSmsTemplate: "Add new sms template",
3652
- addWhatsappTemplate: "Add new whatsapp template",
3653
- editEmailTemplate: "Edit email template",
3654
- editSmsTemplate: "Edit sms template",
3655
- editWhatsappTemplate: "Edit whatsapp template",
3656
- search: "Search {{what}}",
3657
- markAsActive: "Mark as active",
3658
- markAsInactive: "Mark as inactive",
3659
- close: "Close",
3660
- "delete": "Delete",
3661
- edit: "Edit",
3662
- saveChanges: "Save changes",
3663
- send: "Send",
3664
- cancel: "Cancel",
3665
- emailAddress: "Email address",
3666
- phoneNumber: "Phone number",
3667
- name: "Name",
3668
- body: "Body",
3669
- subject: "Subject",
3670
- title: "Template",
3671
- active: "Active",
3672
- templateDeleteConfirmation: "Are you sure want to delete <strong>{{name}}</strong>. This action cannot be undone.",
3673
- deleteTemplate: "Delete {{label}}",
3674
- emailTemplates: "Email Templates",
3675
- emailTemplate: "Email Template",
3676
- smsTemplates: "Sms Templates",
3677
- smsTemplate: "Sms Template",
3678
- whatsappTemplates: "Whatsapp Templates",
3679
- whatsappTemplate: "Whatsapp Template",
3680
- emptyState: "There are no {{type}} to show.",
3681
- sendTestEmail: "Send test email",
3682
- sendTestSms: "Send test sms",
3683
- filtersEmptyState: "There are no {{type}} to show for applied filters.",
3684
- preview: "Template Preview",
3685
- resolveVariable: "Resolve {{type}} variables",
3686
- validation: {
3687
- namePresence: "Name is required",
3688
- subjectPresence: "Subject is required",
3689
- bodyPresence: "Body is required",
3690
- emailAddressPresence: "Email address is required",
3691
- emailAddressFormatValidation: "Invalid email address",
3692
- validPhoneNumber: "Enter valid phone number",
3693
- variablePresence: "Variable should not be empty"
3694
- }
3695
- },
3696
- sendMessage: {
3697
- email: "Send email",
3698
- sms: "Send sms",
3699
- selectTemplate: "Select a template",
3700
- testSmsNote: "Note: Variable values will be empty for test sms."
3701
- },
3702
- common: {
3703
- send: "Send"
3704
- }
3705
- };
3706
- var en = {
3707
- neetoMessageTemplate: neetoMessageTemplate
3708
- };
112
+ function _nonIterableRest() {
113
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
114
+ }
3709
115
 
3710
- instance.use(Browser).use(initReactI18next).init({
3711
- resources: {
3712
- en: {
3713
- translation: en
3714
- }
3715
- },
3716
- fallbackLng: "en",
3717
- detection: {
3718
- order: ["navigator"]
3719
- }
3720
- });
116
+ function _slicedToArray(arr, i) {
117
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
118
+ }
3721
119
 
3722
120
  var MESSAGE_TEMPLATES = {
3723
121
  email: {
3724
- label: t$1("neetoMessageTemplate.template.emailTemplates"),
122
+ label: t("neetoMessageTemplate.template.emailTemplates"),
3725
123
  value: "email_template",
3726
- addText: t$1("neetoMessageTemplate.template.addEmailTemplate"),
3727
- labelSingular: t$1("neetoMessageTemplate.template.emailTemplate"),
3728
- editText: t$1("neetoMessageTemplate.template.editEmailTemplate")
124
+ addText: t("neetoMessageTemplate.template.addEmailTemplate"),
125
+ labelSingular: t("neetoMessageTemplate.template.emailTemplate"),
126
+ editText: t("neetoMessageTemplate.template.editEmailTemplate")
3729
127
  },
3730
128
  sms: {
3731
- label: t$1("neetoMessageTemplate.template.smsTemplates"),
129
+ label: t("neetoMessageTemplate.template.smsTemplates"),
3732
130
  value: "sms_template",
3733
- addText: t$1("neetoMessageTemplate.template.addSmsTemplate"),
3734
- labelSingular: t$1("neetoMessageTemplate.template.smsTemplate"),
3735
- editText: t$1("neetoMessageTemplate.template.editSmsTemplate")
131
+ addText: t("neetoMessageTemplate.template.addSmsTemplate"),
132
+ labelSingular: t("neetoMessageTemplate.template.smsTemplate"),
133
+ editText: t("neetoMessageTemplate.template.editSmsTemplate")
3736
134
  },
3737
135
  whatsapp: {
3738
- label: t$1("neetoMessageTemplate.template.whatsappTemplates"),
136
+ label: t("neetoMessageTemplate.template.whatsappTemplates"),
3739
137
  value: "whatsapp_template",
3740
- addText: t$1("neetoMessageTemplate.template.addWhatsappTemplate"),
3741
- labelSingular: t$1("neetoMessageTemplate.template.whatsappTemplate"),
3742
- editText: t$1("neetoMessageTemplate.template.editWhatsappTemplate")
138
+ addText: t("neetoMessageTemplate.template.addWhatsappTemplate"),
139
+ labelSingular: t("neetoMessageTemplate.template.whatsappTemplate"),
140
+ editText: t("neetoMessageTemplate.template.editWhatsappTemplate")
3743
141
  }
3744
142
  };
3745
143
  var DEFAULT_EDITOR_ROW_COUNT = 15;
@@ -3750,7 +148,6 @@ var MESSAGE_TEMPLATE_INITIAL_STATE = {
3750
148
  isDelete: false,
3751
149
  template: {}
3752
150
  };
3753
- var DEFAULT_PAGE_SIZE = 10;
3754
151
  var DEFAULT_PAGE_PROPERTIES = {
3755
152
  size: DEFAULT_PAGE_SIZE,
3756
153
  index: DEFAULT_PAGE_INDEX
@@ -3908,7 +305,7 @@ var RowActions = function RowActions(_ref) {
3908
305
 
3909
306
  var renderSearchProps = function renderSearchProps(label, setSearchTerm, searchTerm) {
3910
307
  return {
3911
- placeholder: t$1("neetoMessageTemplate.template.search", {
308
+ placeholder: t("neetoMessageTemplate.template.search", {
3912
309
  what: label.toLowerCase()
3913
310
  }),
3914
311
  onChange: function onChange(_ref) {
@@ -3923,8 +320,8 @@ var buildTableColumnData = function buildTableColumnData(setManageTemplatePane,
3923
320
  dataIndex: "name",
3924
321
  key: "name",
3925
322
  node: "name",
3926
- title: t$1("neetoMessageTemplate.template.name"),
3927
- label: t$1("neetoMessageTemplate.template.name"),
323
+ title: t("neetoMessageTemplate.template.name"),
324
+ label: t("neetoMessageTemplate.template.name"),
3928
325
  type: "text",
3929
326
  render: function render(name, template) {
3930
327
  return /*#__PURE__*/React.createElement("div", {
@@ -3941,8 +338,8 @@ var buildTableColumnData = function buildTableColumnData(setManageTemplatePane,
3941
338
  dataIndex: "status",
3942
339
  key: "status",
3943
340
  node: "status",
3944
- title: t$1("neetoMessageTemplate.template.active"),
3945
- label: t$1("neetoMessageTemplate.template.active"),
341
+ title: t("neetoMessageTemplate.template.active"),
342
+ label: t("neetoMessageTemplate.template.active"),
3946
343
  type: "single_option",
3947
344
  values: [{
3948
345
  label: "Yes",
@@ -3974,20 +371,20 @@ var SMS_TEMPLATE_INITIAL_VALUES = {
3974
371
  testPhoneNumber: ""
3975
372
  };
3976
373
  var EMAIL_TEMPLATE_FORM_SCHEMA = yup.object({
3977
- name: yup.string().trim().required(t$1("neetoMessageTemplate.template.validation.namePresence")),
3978
- subject: yup.string().trim().required(t$1("neetoMessageTemplate.template.validation.subjectPresence")),
3979
- body: yup.string().test("name", t$1("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
374
+ name: yup.string().trim().required(t("neetoMessageTemplate.template.validation.namePresence")),
375
+ subject: yup.string().trim().required(t("neetoMessageTemplate.template.validation.subjectPresence")),
376
+ body: yup.string().test("name", t("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
3980
377
  return !!formatEditorContent$1(value);
3981
378
  })
3982
379
  });
3983
380
  var SMS_TEMPLATE_FORM_VALIDATION_SCHEMA = yup.object({
3984
- name: yup.string().trim().required(t$1("neetoMessageTemplate.template.validation.namePresence")),
3985
- body: yup.string().test("body", t$1("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
381
+ name: yup.string().trim().required(t("neetoMessageTemplate.template.validation.namePresence")),
382
+ body: yup.string().test("body", t("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
3986
383
  return !!formatEditorContent$1(value);
3987
384
  })
3988
385
  });
3989
- var SEND_TEST_EMAIL_SCHEMA = yup.string().trim().required(t$1("neetoMessageTemplate.template.validation.emailAddressPresence")).email(t$1("neetoMessageTemplate.template.validation.emailAddressFormatValidation"));
3990
- var PHONE_NUMBER_VALIDATION_SCHEMA = yup.string().test("testPhoneNumber", t$1("neetoMessageTemplate.template.validation.validPhoneNumber"), function (value) {
386
+ var SEND_TEST_EMAIL_SCHEMA = yup.string().trim().required(t("neetoMessageTemplate.template.validation.emailAddressPresence")).email(t("neetoMessageTemplate.template.validation.emailAddressFormatValidation"));
387
+ var PHONE_NUMBER_VALIDATION_SCHEMA = yup.string().test("testPhoneNumber", t("neetoMessageTemplate.template.validation.validPhoneNumber"), function (value) {
3991
388
  return isPhoneNumberValid(value);
3992
389
  });
3993
390
 
@@ -4022,6 +419,10 @@ function _asyncToGenerator(fn) {
4022
419
  };
4023
420
  }
4024
421
 
422
+ function getDefaultExportFromCjs (x) {
423
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
424
+ }
425
+
4025
426
  var regeneratorRuntime$1 = {exports: {}};
4026
427
 
4027
428
  var _typeof = {exports: {}};
@@ -4586,6 +987,10 @@ function _arrayWithoutHoles(arr) {
4586
987
  if (Array.isArray(arr)) return _arrayLikeToArray(arr);
4587
988
  }
4588
989
 
990
+ function _iterableToArray(iter) {
991
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
992
+ }
993
+
4589
994
  function _nonIterableSpread() {
4590
995
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
4591
996
  }
@@ -4636,7 +1041,7 @@ var useTemplates = function useTemplates(_ref) {
4636
1041
  var pageIndex = pageProperties.index,
4637
1042
  pageSize = pageProperties.size;
4638
1043
  var templateParams = {
4639
- pageIndex: pageIndex,
1044
+ page: pageIndex,
4640
1045
  pageSize: pageSize,
4641
1046
  filters: JSON.stringify(filters),
4642
1047
  templateType: MESSAGE_TEMPLATES[type].value,
@@ -4760,7 +1165,7 @@ var MessageTemplates = function MessageTemplates(_ref) {
4760
1165
  _ref$type = _ref.type,
4761
1166
  type = _ref$type === void 0 ? "" : _ref$type,
4762
1167
  _ref$handleSubmitTest = _ref.handleSubmitTestTemplate,
4763
- handleSubmitTestTemplate = _ref$handleSubmitTest === void 0 ? noop$1 : _ref$handleSubmitTest,
1168
+ handleSubmitTestTemplate = _ref$handleSubmitTest === void 0 ? noop : _ref$handleSubmitTest,
4764
1169
  _ref$isTestMessageLoa = _ref.isTestMessageLoading,
4765
1170
  isTestMessageLoading = _ref$isTestMessageLoa === void 0 ? false : _ref$isTestMessageLoa,
4766
1171
  _ref$shouldIncludeTes = _ref.shouldIncludeTestTemplate,
@@ -4876,19 +1281,19 @@ var SEND_MESSAGE_INITIAL_VALUES = {
4876
1281
  body: ""
4877
1282
  };
4878
1283
  var EMAIL_MESSAGE_FORM_SCHEMA = yup.object().shape({
4879
- subject: yup.string().trim().required(t$1("neetoMessageTemplate.template.validation.subjectPresence")),
4880
- body: yup.string().test("body", t$1("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
1284
+ subject: yup.string().trim().required(t("neetoMessageTemplate.template.validation.subjectPresence")),
1285
+ body: yup.string().test("body", t("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
4881
1286
  return !!formatEditorContent(value);
4882
- }).required(t$1("neetoMessageTemplate.template.validation.bodyPresence"))
1287
+ }).required(t("neetoMessageTemplate.template.validation.bodyPresence"))
4883
1288
  });
4884
1289
  var SMS_MESSAGE_FORM_VALIDATION_SCHEMA = yup.object().shape({
4885
- body: yup.string().required(t$1("neetoMessageTemplate.template.validation.bodyPresence")).test("body", t$1("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
1290
+ body: yup.string().required(t("neetoMessageTemplate.template.validation.bodyPresence")).test("body", t("neetoMessageTemplate.template.validation.bodyPresence"), function (value) {
4886
1291
  return !!formatEditorContent(value);
4887
1292
  })
4888
1293
  });
4889
1294
  var WHATSAPP_MESSAGE_FORM_VALIDATIONS_SCHEMA = yup.object().shape({
4890
1295
  variableContents: yup.object().shape({
4891
- body: yup.array().of(yup.string().required(t$1("neetoMessageTemplate.template.validation.variablePresence")))
1296
+ body: yup.array().of(yup.string().required(t("neetoMessageTemplate.template.validation.variablePresence")))
4892
1297
  })
4893
1298
  });
4894
1299
 
@@ -5066,7 +1471,7 @@ var Whatsapp = function Whatsapp(_ref) {
5066
1471
  }, /*#__PURE__*/React.createElement(Typography, {
5067
1472
  style: "h4"
5068
1473
  }, t("neetoMessageTemplate.template.resolveVariable", {
5069
- type: capitalize$1(group)
1474
+ type: capitalize(group)
5070
1475
  })), values.variableContents[group].map(function (_, index) {
5071
1476
  return /*#__PURE__*/React.createElement("div", {
5072
1477
  key: "".concat(group, "-").concat(index)
@@ -5099,9 +1504,9 @@ var SendMessagePane = function SendMessagePane(_ref) {
5099
1504
  _ref$type = _ref.type,
5100
1505
  type = _ref$type === void 0 ? "" : _ref$type,
5101
1506
  _ref$handleSubmit = _ref.handleSubmit,
5102
- handleSubmit = _ref$handleSubmit === void 0 ? noop$1 : _ref$handleSubmit,
1507
+ handleSubmit = _ref$handleSubmit === void 0 ? noop : _ref$handleSubmit,
5103
1508
  _ref$onClose = _ref.onClose,
5104
- onClose = _ref$onClose === void 0 ? noop$1 : _ref$onClose,
1509
+ onClose = _ref$onClose === void 0 ? noop : _ref$onClose,
5105
1510
  _ref$customFields = _ref.customFields,
5106
1511
  customFields = _ref$customFields === void 0 ? null : _ref$customFields,
5107
1512
  _ref$customFieldsInit = _ref.customFieldsInitialValues,