@trii/components 2.0.12 → 2.0.13

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/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as React from 'react';
2
- import React__default, { createContext, useContext, useState, useRef, useEffect, useCallback } from 'react';
3
- import { Button, styled as styled$3, Box, IconButton, Avatar, Typography, Tooltip, Chip, Popper, ClickAwayListener, CardContent, FormControl, InputLabel, Select, MenuItem } from '@mui/material';
2
+ import React__default, { useEffect } from 'react';
3
+ import { Button, styled as styled$3, Box, IconButton, Avatar, Typography, Tooltip, Chip, Popper, ClickAwayListener, CardContent } from '@mui/material';
4
4
  import { withEmotionCache, ThemeContext, CacheProvider, Global, css, keyframes } from '@emotion/react';
5
5
 
6
6
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
@@ -3010,16 +3010,16 @@ var getDisplayName = /*#__PURE__*/Object.freeze({
3010
3010
  //
3011
3011
  // A strict capitalization should uppercase the first letter of each word in the sentence.
3012
3012
  // We only handle the first word.
3013
- function capitalize$2(string) {
3013
+ function capitalize$1(string) {
3014
3014
  if (typeof string !== 'string') {
3015
3015
  throw new Error(process.env.NODE_ENV !== "production" ? `MUI: \`capitalize(string)\` expects a string argument.` : formatMuiErrorMessage$1(7));
3016
3016
  }
3017
3017
  return string.charAt(0).toUpperCase() + string.slice(1);
3018
3018
  }
3019
3019
 
3020
- var capitalize$1 = /*#__PURE__*/Object.freeze({
3020
+ var capitalize = /*#__PURE__*/Object.freeze({
3021
3021
  __proto__: null,
3022
- default: capitalize$2
3022
+ default: capitalize$1
3023
3023
  });
3024
3024
 
3025
3025
  /**
@@ -3735,7 +3735,7 @@ function removeUnusedBreakpoints(breakpointKeys, style) {
3735
3735
  }, style);
3736
3736
  }
3737
3737
 
3738
- function getPath$1(obj, path, checkVars = true) {
3738
+ function getPath(obj, path, checkVars = true) {
3739
3739
  if (!path || typeof path !== 'string') {
3740
3740
  return null;
3741
3741
  }
@@ -3761,7 +3761,7 @@ function getStyleValue(themeMapping, transform, propValueFinal, userValue = prop
3761
3761
  } else if (Array.isArray(themeMapping)) {
3762
3762
  value = themeMapping[propValueFinal] || userValue;
3763
3763
  } else {
3764
- value = getPath$1(themeMapping, propValueFinal) || userValue;
3764
+ value = getPath(themeMapping, propValueFinal) || userValue;
3765
3765
  }
3766
3766
  if (transform) {
3767
3767
  value = transform(value, userValue, themeMapping);
@@ -3784,12 +3784,12 @@ function style$1(options) {
3784
3784
  }
3785
3785
  const propValue = props[prop];
3786
3786
  const theme = props.theme;
3787
- const themeMapping = getPath$1(theme, themeKey) || {};
3787
+ const themeMapping = getPath(theme, themeKey) || {};
3788
3788
  const styleFromPropValue = propValueFinal => {
3789
3789
  let value = getStyleValue(themeMapping, transform, propValueFinal);
3790
3790
  if (propValueFinal === value && typeof propValueFinal === 'string') {
3791
3791
  // Haven't found value
3792
- value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize$2(propValueFinal)}`, propValueFinal);
3792
+ value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize$1(propValueFinal)}`, propValueFinal);
3793
3793
  }
3794
3794
  if (cssProperty === false) {
3795
3795
  return value;
@@ -3858,7 +3858,7 @@ const paddingKeys = ['p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'padding', 'paddin
3858
3858
  const spacingKeys = [...marginKeys, ...paddingKeys];
3859
3859
  function createUnaryUnit(theme, themeKey, defaultValue, propName) {
3860
3860
  var _getPath;
3861
- const themeSpacing = (_getPath = getPath$1(theme, themeKey, false)) != null ? _getPath : defaultValue;
3861
+ const themeSpacing = (_getPath = getPath(theme, themeKey, false)) != null ? _getPath : defaultValue;
3862
3862
  if (typeof themeSpacing === 'number') {
3863
3863
  return abs => {
3864
3864
  if (typeof abs === 'string') {
@@ -4542,7 +4542,7 @@ function unstable_createStyleFunctionSx() {
4542
4542
  [prop]: val
4543
4543
  };
4544
4544
  }
4545
- const themeMapping = getPath$1(theme, themeKey) || {};
4545
+ const themeMapping = getPath(theme, themeKey) || {};
4546
4546
  if (style) {
4547
4547
  return style(props);
4548
4548
  }
@@ -4550,7 +4550,7 @@ function unstable_createStyleFunctionSx() {
4550
4550
  let value = getStyleValue(themeMapping, transform, propValueFinal);
4551
4551
  if (propValueFinal === value && typeof propValueFinal === 'string') {
4552
4552
  // Haven't found value
4553
- value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize$2(propValueFinal)}`, propValueFinal);
4553
+ value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize$1(propValueFinal)}`, propValueFinal);
4554
4554
  }
4555
4555
  if (cssProperty === false) {
4556
4556
  return value;
@@ -5738,7 +5738,7 @@ function node (value, root, parent, type, props, children, length) {
5738
5738
  * @param {object} props
5739
5739
  * @return {object}
5740
5740
  */
5741
- function copy$1 (root, props) {
5741
+ function copy (root, props) {
5742
5742
  return assign(node('', null, null, '', null, null, 0), root, {length: -root.length}, props)
5743
5743
  }
5744
5744
 
@@ -6614,7 +6614,7 @@ var prefixer = function prefixer(element, index, children, callback) {
6614
6614
  break;
6615
6615
 
6616
6616
  case KEYFRAMES:
6617
- return serialize([copy$1(element, {
6617
+ return serialize([copy(element, {
6618
6618
  value: replace(element.value, '@', '@' + WEBKIT)
6619
6619
  })], callback);
6620
6620
 
@@ -6624,17 +6624,17 @@ var prefixer = function prefixer(element, index, children, callback) {
6624
6624
  // :read-(only|write)
6625
6625
  case ':read-only':
6626
6626
  case ':read-write':
6627
- return serialize([copy$1(element, {
6627
+ return serialize([copy(element, {
6628
6628
  props: [replace(value, /:(read-\w+)/, ':' + MOZ + '$1')]
6629
6629
  })], callback);
6630
6630
  // :placeholder
6631
6631
 
6632
6632
  case '::placeholder':
6633
- return serialize([copy$1(element, {
6633
+ return serialize([copy(element, {
6634
6634
  props: [replace(value, /:(plac\w+)/, ':' + WEBKIT + 'input-$1')]
6635
- }), copy$1(element, {
6635
+ }), copy(element, {
6636
6636
  props: [replace(value, /:(plac\w+)/, ':' + MOZ + '$1')]
6637
- }), copy$1(element, {
6637
+ }), copy(element, {
6638
6638
  props: [replace(value, /:(plac\w+)/, MS + 'input-$1')]
6639
6639
  })], callback);
6640
6640
  }
@@ -8188,7 +8188,7 @@ var require$$3 = /*@__PURE__*/getAugmentedNamespace(styledEngine);
8188
8188
 
8189
8189
  var require$$4 = /*@__PURE__*/getAugmentedNamespace(deepmerge);
8190
8190
 
8191
- var require$$5 = /*@__PURE__*/getAugmentedNamespace(capitalize$1);
8191
+ var require$$5 = /*@__PURE__*/getAugmentedNamespace(capitalize);
8192
8192
 
8193
8193
  var require$$6 = /*@__PURE__*/getAugmentedNamespace(getDisplayName);
8194
8194
 
@@ -8474,7 +8474,7 @@ const useUtilityClasses = ownerState => {
8474
8474
  classes
8475
8475
  } = ownerState;
8476
8476
  const slots = {
8477
- root: ['root', color !== 'inherit' && `color${capitalize$2(color)}`, `fontSize${capitalize$2(fontSize)}`]
8477
+ root: ['root', color !== 'inherit' && `color${capitalize$1(color)}`, `fontSize${capitalize$1(fontSize)}`]
8478
8478
  };
8479
8479
  return composeClasses(slots, getSvgIconUtilityClass, classes);
8480
8480
  };
@@ -8485,7 +8485,7 @@ const SvgIconRoot = styled$1('svg', {
8485
8485
  const {
8486
8486
  ownerState
8487
8487
  } = props;
8488
- return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize$2(ownerState.color)}`], styles[`fontSize${capitalize$2(ownerState.fontSize)}`]];
8488
+ return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize$1(ownerState.color)}`], styles[`fontSize${capitalize$1(ownerState.fontSize)}`]];
8489
8489
  }
8490
8490
  })(({
8491
8491
  theme,
@@ -8671,7 +8671,7 @@ const unstable_ClassNameGenerator = {
8671
8671
 
8672
8672
  var utils = /*#__PURE__*/Object.freeze({
8673
8673
  __proto__: null,
8674
- capitalize: capitalize$2,
8674
+ capitalize: capitalize$1,
8675
8675
  createChainedFunction: createChainedFunction,
8676
8676
  createSvgIcon: createSvgIcon$1,
8677
8677
  debounce: debounce,
@@ -8717,6 +8717,10 @@ var PhoneEnabled = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
8717
8717
  d: "m17.38 10.79-2.2-2.2c-.28-.28-.36-.67-.25-1.02.37-1.12.57-2.32.57-3.57 0-.55.45-1 1-1H20c.55 0 1 .45 1 1 0 9.39-7.61 17-17 17-.55 0-1-.45-1-1v-3.49c0-.55.45-1 1-1 1.24 0 2.45-.2 3.57-.57.35-.12.75-.03 1.02.24l2.2 2.2c2.83-1.45 5.15-3.76 6.59-6.59"
8718
8718
  }), 'PhoneEnabled');
8719
8719
 
8720
+ var ThreeP = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
8721
+ d: "M20 2H4.01c-1.1 0-2 .9-2 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-8 4c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2m4 8H8v-.57c0-.81.48-1.53 1.22-1.85.85-.37 1.79-.58 2.78-.58.99 0 1.93.21 2.78.58.74.32 1.22 1.04 1.22 1.85z"
8722
+ }), 'ThreeP');
8723
+
8720
8724
  var WhatsApp = createSvgIcon$1( /*#__PURE__*/jsxRuntimeExports.jsx("path", {
8721
8725
  d: "M16.75 13.96c.25.13.41.2.46.3.06.11.04.61-.21 1.18-.2.56-1.24 1.1-1.7 1.12-.46.02-.47.36-2.96-.73-2.49-1.09-3.99-3.75-4.11-3.92-.12-.17-.96-1.38-.92-2.61.05-1.22.69-1.8.95-2.04.24-.26.51-.29.68-.26h.47c.15 0 .36-.06.55.45l.69 1.87c.06.13.1.28.01.44l-.27.41-.39.42c-.12.12-.26.25-.12.5.12.26.62 1.09 1.32 1.78.91.88 1.71 1.17 1.95 1.3.24.14.39.12.54-.04l.81-.94c.19-.25.35-.19.58-.11l1.67.88M12 2a10 10 0 0 1 10 10 10 10 0 0 1-10 10c-1.97 0-3.8-.57-5.35-1.55L2 22l1.55-4.65A9.969 9.969 0 0 1 2 12 10 10 0 0 1 12 2m0 2a8 8 0 0 0-8 8c0 1.72.54 3.31 1.46 4.61L4.5 19.5l2.89-.96A7.95 7.95 0 0 0 12 20a8 8 0 0 0 8-8 8 8 0 0 0-8-8z"
8722
8726
  }), 'WhatsApp');
@@ -8792,7 +8796,7 @@ const ContactName = styled$3(Typography)({
8792
8796
  maxWidth: 200,
8793
8797
  textAlign: 'center',
8794
8798
  });
8795
- const Header = ({ contactId, imgUrl, name, navigate }) => {
8799
+ const Header = ({ imgUrl, name, contactId, navigate }) => {
8796
8800
  const handleOpenInNewTab = (event) => {
8797
8801
  event.preventDefault();
8798
8802
  event.stopPropagation();
@@ -14807,289 +14811,6 @@ const MembersSection = ({ contactData, title }) => {
14807
14811
  return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(SectionTitle, { gutterBottom: true, mt: 2, variant: "subtitle1", children: title }), jsxRuntimeExports.jsx(Typography, { variant: "body2", color: "text.secondary", children: contactData?.members.map((member) => (jsxRuntimeExports.jsx(MemberItem, { name: member.name }, member.id))) })] }));
14808
14812
  };
14809
14813
 
14810
- function warn() {
14811
- if (console && console.warn) {
14812
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
14813
- args[_key] = arguments[_key];
14814
- }
14815
- if (isString$1(args[0])) args[0] = `react-i18next:: ${args[0]}`;
14816
- console.warn(...args);
14817
- }
14818
- }
14819
- const alreadyWarned = {};
14820
- function warnOnce() {
14821
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
14822
- args[_key2] = arguments[_key2];
14823
- }
14824
- if (isString$1(args[0]) && alreadyWarned[args[0]]) return;
14825
- if (isString$1(args[0])) alreadyWarned[args[0]] = new Date();
14826
- warn(...args);
14827
- }
14828
- const loadedClb = (i18n, cb) => () => {
14829
- if (i18n.isInitialized) {
14830
- cb();
14831
- } else {
14832
- const initialized = () => {
14833
- setTimeout(() => {
14834
- i18n.off('initialized', initialized);
14835
- }, 0);
14836
- cb();
14837
- };
14838
- i18n.on('initialized', initialized);
14839
- }
14840
- };
14841
- const loadNamespaces = (i18n, ns, cb) => {
14842
- i18n.loadNamespaces(ns, loadedClb(i18n, cb));
14843
- };
14844
- const loadLanguages = (i18n, lng, ns, cb) => {
14845
- if (isString$1(ns)) ns = [ns];
14846
- ns.forEach(n => {
14847
- if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
14848
- });
14849
- i18n.loadLanguages(lng, loadedClb(i18n, cb));
14850
- };
14851
- const oldI18nextHasLoadedNamespace = function (ns, i18n) {
14852
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
14853
- const lng = i18n.languages[0];
14854
- const fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
14855
- const lastLng = i18n.languages[i18n.languages.length - 1];
14856
- if (lng.toLowerCase() === 'cimode') return true;
14857
- const loadNotPending = (l, n) => {
14858
- const loadState = i18n.services.backendConnector.state[`${l}|${n}`];
14859
- return loadState === -1 || loadState === 2;
14860
- };
14861
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
14862
- if (i18n.hasResourceBundle(lng, ns)) return true;
14863
- if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
14864
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
14865
- return false;
14866
- };
14867
- const hasLoadedNamespace = function (ns, i18n) {
14868
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
14869
- if (!i18n.languages || !i18n.languages.length) {
14870
- warnOnce('i18n.languages were undefined or empty', i18n.languages);
14871
- return true;
14872
- }
14873
- const isNewerI18next = i18n.options.ignoreJSONStructure !== undefined;
14874
- if (!isNewerI18next) {
14875
- return oldI18nextHasLoadedNamespace(ns, i18n, options);
14876
- }
14877
- return i18n.hasLoadedNamespace(ns, {
14878
- lng: options.lng,
14879
- precheck: (i18nInstance, loadNotPending) => {
14880
- if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
14881
- }
14882
- });
14883
- };
14884
- const isString$1 = obj => typeof obj === 'string';
14885
- const isObject = obj => typeof obj === 'object' && obj !== null;
14886
-
14887
- const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
14888
- const htmlEntities = {
14889
- '&amp;': '&',
14890
- '&#38;': '&',
14891
- '&lt;': '<',
14892
- '&#60;': '<',
14893
- '&gt;': '>',
14894
- '&#62;': '>',
14895
- '&apos;': "'",
14896
- '&#39;': "'",
14897
- '&quot;': '"',
14898
- '&#34;': '"',
14899
- '&nbsp;': ' ',
14900
- '&#160;': ' ',
14901
- '&copy;': '©',
14902
- '&#169;': '©',
14903
- '&reg;': '®',
14904
- '&#174;': '®',
14905
- '&hellip;': '…',
14906
- '&#8230;': '…',
14907
- '&#x2F;': '/',
14908
- '&#47;': '/'
14909
- };
14910
- const unescapeHtmlEntity = m => htmlEntities[m];
14911
- const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
14912
-
14913
- let defaultOptions = {
14914
- bindI18n: 'languageChanged',
14915
- bindI18nStore: '',
14916
- transEmptyNodeValue: '',
14917
- transSupportBasicHtmlNodes: true,
14918
- transWrapTextNodes: '',
14919
- transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
14920
- useSuspense: true,
14921
- unescape
14922
- };
14923
- const setDefaults = function () {
14924
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
14925
- defaultOptions = {
14926
- ...defaultOptions,
14927
- ...options
14928
- };
14929
- };
14930
- const getDefaults = () => defaultOptions;
14931
-
14932
- let i18nInstance;
14933
- const setI18n = instance => {
14934
- i18nInstance = instance;
14935
- };
14936
- const getI18n = () => i18nInstance;
14937
-
14938
- const initReactI18next = {
14939
- type: '3rdParty',
14940
- init(instance) {
14941
- setDefaults(instance.options.react);
14942
- setI18n(instance);
14943
- }
14944
- };
14945
-
14946
- const I18nContext = createContext();
14947
- class ReportNamespaces {
14948
- constructor() {
14949
- this.usedNamespaces = {};
14950
- }
14951
- addUsedNamespaces(namespaces) {
14952
- namespaces.forEach(ns => {
14953
- if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
14954
- });
14955
- }
14956
- getUsedNamespaces = () => Object.keys(this.usedNamespaces);
14957
- }
14958
-
14959
- const usePrevious = (value, ignore) => {
14960
- const ref = useRef();
14961
- useEffect(() => {
14962
- ref.current = ignore ? ref.current : value;
14963
- }, [value, ignore]);
14964
- return ref.current;
14965
- };
14966
- const alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);
14967
- const useMemoizedT = (i18n, language, namespace, keyPrefix) => useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
14968
- const useTranslation = function (ns) {
14969
- let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14970
- const {
14971
- i18n: i18nFromProps
14972
- } = props;
14973
- const {
14974
- i18n: i18nFromContext,
14975
- defaultNS: defaultNSFromContext
14976
- } = useContext(I18nContext) || {};
14977
- const i18n = i18nFromProps || i18nFromContext || getI18n();
14978
- if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
14979
- if (!i18n) {
14980
- warnOnce('You will need to pass in an i18next instance by using initReactI18next');
14981
- const notReadyT = (k, optsOrDefaultValue) => {
14982
- if (isString$1(optsOrDefaultValue)) return optsOrDefaultValue;
14983
- if (isObject(optsOrDefaultValue) && isString$1(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
14984
- return Array.isArray(k) ? k[k.length - 1] : k;
14985
- };
14986
- const retNotReady = [notReadyT, {}, false];
14987
- retNotReady.t = notReadyT;
14988
- retNotReady.i18n = {};
14989
- retNotReady.ready = false;
14990
- return retNotReady;
14991
- }
14992
- 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.');
14993
- const i18nOptions = {
14994
- ...getDefaults(),
14995
- ...i18n.options.react,
14996
- ...props
14997
- };
14998
- const {
14999
- useSuspense,
15000
- keyPrefix
15001
- } = i18nOptions;
15002
- let namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
15003
- namespaces = isString$1(namespaces) ? [namespaces] : namespaces || ['translation'];
15004
- if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
15005
- const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
15006
- const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
15007
- const getT = () => memoGetT;
15008
- const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
15009
- const [t, setT] = useState(getT);
15010
- let joinedNS = namespaces.join();
15011
- if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
15012
- const previousJoinedNS = usePrevious(joinedNS);
15013
- const isMounted = useRef(true);
15014
- useEffect(() => {
15015
- const {
15016
- bindI18n,
15017
- bindI18nStore
15018
- } = i18nOptions;
15019
- isMounted.current = true;
15020
- if (!ready && !useSuspense) {
15021
- if (props.lng) {
15022
- loadLanguages(i18n, props.lng, namespaces, () => {
15023
- if (isMounted.current) setT(getNewT);
15024
- });
15025
- } else {
15026
- loadNamespaces(i18n, namespaces, () => {
15027
- if (isMounted.current) setT(getNewT);
15028
- });
15029
- }
15030
- }
15031
- if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
15032
- setT(getNewT);
15033
- }
15034
- const boundReset = () => {
15035
- if (isMounted.current) setT(getNewT);
15036
- };
15037
- if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
15038
- if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
15039
- return () => {
15040
- isMounted.current = false;
15041
- if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset));
15042
- if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
15043
- };
15044
- }, [i18n, joinedNS]);
15045
- useEffect(() => {
15046
- if (isMounted.current && ready) {
15047
- setT(getT);
15048
- }
15049
- }, [i18n, keyPrefix, ready]);
15050
- const ret = [t, i18n, ready];
15051
- ret.t = t;
15052
- ret.i18n = i18n;
15053
- ret.ready = ready;
15054
- if (ready) return ret;
15055
- if (!ready && !useSuspense) return ret;
15056
- throw new Promise(resolve => {
15057
- if (props.lng) {
15058
- loadLanguages(i18n, props.lng, namespaces, () => resolve());
15059
- } else {
15060
- loadNamespaces(i18n, namespaces, () => resolve());
15061
- }
15062
- });
15063
- };
15064
-
15065
- const useContactInfoPopupTranslation = () => {
15066
- const { t } = useTranslation();
15067
- return {
15068
- businessSection: {
15069
- title: t('components.contactInfoPopup.businessSection.title'),
15070
- description: t('components.contactInfoPopup.businessSection.description'),
15071
- },
15072
- contactMethod: {
15073
- email: t('components.contactInfoPopup.contactMethod.email'),
15074
- phone: t('components.contactInfoPopup.contactMethod.phone'),
15075
- website: t('components.contactInfoPopup.contactMethod.website'),
15076
- },
15077
- labelsSection: {
15078
- title: t('components.contactInfoPopup.labelsSection.title'),
15079
- },
15080
- membersSection: {
15081
- title: t('components.contactInfoPopup.membersSection.title'),
15082
- noMembers: t('components.contactInfoPopup.membersSection.noMembers'),
15083
- },
15084
- global: {
15085
- properties: t('components.contactInfoPopup.global.properties'),
15086
- business: t('components.contactInfoPopup.global.business'),
15087
- businessMembers: t('components.contactInfoPopup.global.businessMembers'),
15088
- labels: t('components.contactInfoPopup.global.labels'),
15089
- },
15090
- };
15091
- };
15092
-
15093
14814
  const PopupContainer = styled$3(Box)(({ theme }) => ({
15094
14815
  //@ts-ignore
15095
14816
  backgroundColor: theme.palette.background.panel,
@@ -15117,40 +14838,50 @@ const PopupContainer = styled$3(Box)(({ theme }) => ({
15117
14838
  background: '#616161',
15118
14839
  },
15119
14840
  }));
15120
- const ContactInfoPopup = ({ open, anchorEl, onClose, contactData, avatarImgUrl, navigate, }) => {
14841
+ const ContactInfoPopup = ({ open, anchorEl, onClose, contactData, avatarImgUrl, navigate, t = (key) => ({
14842
+ labels: 'Etiquetas',
14843
+ phone: 'Teléfono',
14844
+ business: 'Empresa',
14845
+ businessMembers: 'Miembros de la empresa',
14846
+ properties: 'Propiedades',
14847
+ view: 'Ver',
14848
+ email: 'Correo Electrónico',
14849
+ }[key] || key), }) => {
15121
14850
  const dataIsBusiness = isBusiness(contactData);
15122
14851
  const dataIsContact = isContact(contactData);
15123
- const translations = useContactInfoPopupTranslation();
15124
14852
  const contactMethods = [
15125
14853
  {
15126
14854
  icon: jsxRuntimeExports.jsx(PhoneEnabled, { fontSize: "small" }),
15127
- title: translations.contactMethod.phone,
14855
+ title: t('phone'),
15128
14856
  contactList: contactData?.phones || [],
15129
14857
  showTitle: true,
15130
14858
  },
15131
14859
  {
15132
14860
  icon: jsxRuntimeExports.jsx(Email, { fontSize: "small" }),
15133
- title: translations.contactMethod.email,
14861
+ title: t('email'),
15134
14862
  contactList: contactData?.emails || [],
15135
14863
  showTitle: true,
15136
14864
  },
15137
14865
  {
15138
14866
  icon: jsxRuntimeExports.jsx(WhatsApp, { fontSize: "small" }),
15139
- title: 'WhatsApp',
14867
+ title: 'IM',
15140
14868
  contactList: contactData?.ims_whatsapp || [],
15141
14869
  showTitle: true,
15142
14870
  },
15143
14871
  {
15144
14872
  icon: jsxRuntimeExports.jsx(Facebook, { fontSize: "small" }),
15145
- title: 'Facebook',
15146
14873
  contactList: contactData?.ims_facebook || [],
15147
- showTitle: true,
14874
+ showTitle: false,
15148
14875
  },
15149
14876
  {
15150
14877
  icon: jsxRuntimeExports.jsx(Instagram, { fontSize: "small" }),
15151
- title: 'Instagram',
15152
14878
  contactList: contactData?.ims_instagram || [],
15153
- showTitle: true,
14879
+ showTitle: false,
14880
+ },
14881
+ {
14882
+ icon: jsxRuntimeExports.jsx(ThreeP, { fontSize: "small" }),
14883
+ contactList: contactData?.ims_webchat || [],
14884
+ showTitle: false,
15154
14885
  },
15155
14886
  ];
15156
14887
  useEffect(() => {
@@ -15166,2502 +14897,8 @@ const ContactInfoPopup = ({ open, anchorEl, onClose, contactData, avatarImgUrl,
15166
14897
  window.removeEventListener('keydown', handleKeyDown);
15167
14898
  };
15168
14899
  }, [open, onClose]);
15169
- return (jsxRuntimeExports.jsx(Popper, { sx: { zIndex: 1300 }, open: open, anchorEl: anchorEl, placement: "bottom-start", "data-popper-child": "true", children: jsxRuntimeExports.jsx(ClickAwayListener, { onClickAway: onClose, children: jsxRuntimeExports.jsx(PopupContainer, { children: jsxRuntimeExports.jsxs(CardContent, { children: [jsxRuntimeExports.jsx(Header, { contactId: contactData?.id, imgUrl: avatarImgUrl, name: contactData?.name, navigate: navigate }), jsxRuntimeExports.jsx(LabelsSection, { contactData: contactData, title: translations.global.labels }), dataIsContact && (jsxRuntimeExports.jsx(BusinessSection, { contactData: contactData, title: translations.global.business })), dataIsBusiness && (jsxRuntimeExports.jsx(MembersSection, { contactData: contactData, title: translations.global.businessMembers })), contactMethods.map((method, index) => (jsxRuntimeExports.jsx(ContactMethod, { icon: method.icon, title: method.title, contactList: method.contactList, showTitle: method.showTitle }, index))), jsxRuntimeExports.jsx(Properties, { properties: contactData?.properties, title: translations.global.properties })] }) }) }) }));
15170
- };
15171
-
15172
- const isString = obj => typeof obj === 'string';
15173
- const defer = () => {
15174
- let res;
15175
- let rej;
15176
- const promise = new Promise((resolve, reject) => {
15177
- res = resolve;
15178
- rej = reject;
15179
- });
15180
- promise.resolve = res;
15181
- promise.reject = rej;
15182
- return promise;
15183
- };
15184
- const makeString = object => {
15185
- if (object == null) return '';
15186
- return '' + object;
15187
- };
15188
- const copy = (a, s, t) => {
15189
- a.forEach(m => {
15190
- if (s[m]) t[m] = s[m];
15191
- });
15192
- };
15193
- const lastOfPathSeparatorRegExp = /###/g;
15194
- const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
15195
- const canNotTraverseDeeper = object => !object || isString(object);
15196
- const getLastOfPath = (object, path, Empty) => {
15197
- const stack = !isString(path) ? path : path.split('.');
15198
- let stackIndex = 0;
15199
- while (stackIndex < stack.length - 1) {
15200
- if (canNotTraverseDeeper(object)) return {};
15201
- const key = cleanKey(stack[stackIndex]);
15202
- if (!object[key] && Empty) object[key] = new Empty();
15203
- if (Object.prototype.hasOwnProperty.call(object, key)) {
15204
- object = object[key];
15205
- } else {
15206
- object = {};
15207
- }
15208
- ++stackIndex;
15209
- }
15210
- if (canNotTraverseDeeper(object)) return {};
15211
- return {
15212
- obj: object,
15213
- k: cleanKey(stack[stackIndex])
15214
- };
15215
- };
15216
- const setPath = (object, path, newValue) => {
15217
- const {
15218
- obj,
15219
- k
15220
- } = getLastOfPath(object, path, Object);
15221
- if (obj !== undefined || path.length === 1) {
15222
- obj[k] = newValue;
15223
- return;
15224
- }
15225
- let e = path[path.length - 1];
15226
- let p = path.slice(0, path.length - 1);
15227
- let last = getLastOfPath(object, p, Object);
15228
- while (last.obj === undefined && p.length) {
15229
- e = `${p[p.length - 1]}.${e}`;
15230
- p = p.slice(0, p.length - 1);
15231
- last = getLastOfPath(object, p, Object);
15232
- if (last && last.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
15233
- last.obj = undefined;
15234
- }
15235
- }
15236
- last.obj[`${last.k}.${e}`] = newValue;
15237
- };
15238
- const pushPath = (object, path, newValue, concat) => {
15239
- const {
15240
- obj,
15241
- k
15242
- } = getLastOfPath(object, path, Object);
15243
- obj[k] = obj[k] || [];
15244
- obj[k].push(newValue);
15245
- };
15246
- const getPath = (object, path) => {
15247
- const {
15248
- obj,
15249
- k
15250
- } = getLastOfPath(object, path);
15251
- if (!obj) return undefined;
15252
- return obj[k];
15253
- };
15254
- const getPathWithDefaults = (data, defaultData, key) => {
15255
- const value = getPath(data, key);
15256
- if (value !== undefined) {
15257
- return value;
15258
- }
15259
- return getPath(defaultData, key);
15260
- };
15261
- const deepExtend = (target, source, overwrite) => {
15262
- for (const prop in source) {
15263
- if (prop !== '__proto__' && prop !== 'constructor') {
15264
- if (prop in target) {
15265
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
15266
- if (overwrite) target[prop] = source[prop];
15267
- } else {
15268
- deepExtend(target[prop], source[prop], overwrite);
15269
- }
15270
- } else {
15271
- target[prop] = source[prop];
15272
- }
15273
- }
15274
- }
15275
- return target;
15276
- };
15277
- const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
15278
- var _entityMap = {
15279
- '&': '&amp;',
15280
- '<': '&lt;',
15281
- '>': '&gt;',
15282
- '"': '&quot;',
15283
- "'": '&#39;',
15284
- '/': '&#x2F;'
15285
- };
15286
- const escape = data => {
15287
- if (isString(data)) {
15288
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
15289
- }
15290
- return data;
15291
- };
15292
- class RegExpCache {
15293
- constructor(capacity) {
15294
- this.capacity = capacity;
15295
- this.regExpMap = new Map();
15296
- this.regExpQueue = [];
15297
- }
15298
- getRegExp(pattern) {
15299
- const regExpFromCache = this.regExpMap.get(pattern);
15300
- if (regExpFromCache !== undefined) {
15301
- return regExpFromCache;
15302
- }
15303
- const regExpNew = new RegExp(pattern);
15304
- if (this.regExpQueue.length === this.capacity) {
15305
- this.regExpMap.delete(this.regExpQueue.shift());
15306
- }
15307
- this.regExpMap.set(pattern, regExpNew);
15308
- this.regExpQueue.push(pattern);
15309
- return regExpNew;
15310
- }
15311
- }
15312
- const chars = [' ', ',', '?', '!', ';'];
15313
- const looksLikeObjectPathRegExpCache = new RegExpCache(20);
15314
- const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
15315
- nsSeparator = nsSeparator || '';
15316
- keySeparator = keySeparator || '';
15317
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
15318
- if (possibleChars.length === 0) return true;
15319
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
15320
- let matched = !r.test(key);
15321
- if (!matched) {
15322
- const ki = key.indexOf(keySeparator);
15323
- if (ki > 0 && !r.test(key.substring(0, ki))) {
15324
- matched = true;
15325
- }
15326
- }
15327
- return matched;
15328
- };
15329
- const deepFind = function (obj, path) {
15330
- let keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
15331
- if (!obj) return undefined;
15332
- if (obj[path]) return obj[path];
15333
- const tokens = path.split(keySeparator);
15334
- let current = obj;
15335
- for (let i = 0; i < tokens.length;) {
15336
- if (!current || typeof current !== 'object') {
15337
- return undefined;
15338
- }
15339
- let next;
15340
- let nextPath = '';
15341
- for (let j = i; j < tokens.length; ++j) {
15342
- if (j !== i) {
15343
- nextPath += keySeparator;
15344
- }
15345
- nextPath += tokens[j];
15346
- next = current[nextPath];
15347
- if (next !== undefined) {
15348
- if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
15349
- continue;
15350
- }
15351
- i += j - i + 1;
15352
- break;
15353
- }
15354
- }
15355
- current = next;
15356
- }
15357
- return current;
15358
- };
15359
- const getCleanedCode = code => code && code.replace('_', '-');
15360
-
15361
- const consoleLogger = {
15362
- type: 'logger',
15363
- log(args) {
15364
- this.output('log', args);
15365
- },
15366
- warn(args) {
15367
- this.output('warn', args);
15368
- },
15369
- error(args) {
15370
- this.output('error', args);
15371
- },
15372
- output(type, args) {
15373
- if (console && console[type]) console[type].apply(console, args);
15374
- }
15375
- };
15376
- class Logger {
15377
- constructor(concreteLogger) {
15378
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
15379
- this.init(concreteLogger, options);
15380
- }
15381
- init(concreteLogger) {
15382
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
15383
- this.prefix = options.prefix || 'i18next:';
15384
- this.logger = concreteLogger || consoleLogger;
15385
- this.options = options;
15386
- this.debug = options.debug;
15387
- }
15388
- log() {
15389
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
15390
- args[_key] = arguments[_key];
15391
- }
15392
- return this.forward(args, 'log', '', true);
15393
- }
15394
- warn() {
15395
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
15396
- args[_key2] = arguments[_key2];
15397
- }
15398
- return this.forward(args, 'warn', '', true);
15399
- }
15400
- error() {
15401
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
15402
- args[_key3] = arguments[_key3];
15403
- }
15404
- return this.forward(args, 'error', '');
15405
- }
15406
- deprecate() {
15407
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
15408
- args[_key4] = arguments[_key4];
15409
- }
15410
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
15411
- }
15412
- forward(args, lvl, prefix, debugOnly) {
15413
- if (debugOnly && !this.debug) return null;
15414
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
15415
- return this.logger[lvl](args);
15416
- }
15417
- create(moduleName) {
15418
- return new Logger(this.logger, {
15419
- ...{
15420
- prefix: `${this.prefix}:${moduleName}:`
15421
- },
15422
- ...this.options
15423
- });
15424
- }
15425
- clone(options) {
15426
- options = options || this.options;
15427
- options.prefix = options.prefix || this.prefix;
15428
- return new Logger(this.logger, options);
15429
- }
15430
- }
15431
- var baseLogger = new Logger();
15432
-
15433
- class EventEmitter {
15434
- constructor() {
15435
- this.observers = {};
15436
- }
15437
- on(events, listener) {
15438
- events.split(' ').forEach(event => {
15439
- if (!this.observers[event]) this.observers[event] = new Map();
15440
- const numListeners = this.observers[event].get(listener) || 0;
15441
- this.observers[event].set(listener, numListeners + 1);
15442
- });
15443
- return this;
15444
- }
15445
- off(event, listener) {
15446
- if (!this.observers[event]) return;
15447
- if (!listener) {
15448
- delete this.observers[event];
15449
- return;
15450
- }
15451
- this.observers[event].delete(listener);
15452
- }
15453
- emit(event) {
15454
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
15455
- args[_key - 1] = arguments[_key];
15456
- }
15457
- if (this.observers[event]) {
15458
- const cloned = Array.from(this.observers[event].entries());
15459
- cloned.forEach(_ref => {
15460
- let [observer, numTimesAdded] = _ref;
15461
- for (let i = 0; i < numTimesAdded; i++) {
15462
- observer(...args);
15463
- }
15464
- });
15465
- }
15466
- if (this.observers['*']) {
15467
- const cloned = Array.from(this.observers['*'].entries());
15468
- cloned.forEach(_ref2 => {
15469
- let [observer, numTimesAdded] = _ref2;
15470
- for (let i = 0; i < numTimesAdded; i++) {
15471
- observer.apply(observer, [event, ...args]);
15472
- }
15473
- });
15474
- }
15475
- }
15476
- }
15477
-
15478
- class ResourceStore extends EventEmitter {
15479
- constructor(data) {
15480
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
15481
- ns: ['translation'],
15482
- defaultNS: 'translation'
15483
- };
15484
- super();
15485
- this.data = data || {};
15486
- this.options = options;
15487
- if (this.options.keySeparator === undefined) {
15488
- this.options.keySeparator = '.';
15489
- }
15490
- if (this.options.ignoreJSONStructure === undefined) {
15491
- this.options.ignoreJSONStructure = true;
15492
- }
15493
- }
15494
- addNamespaces(ns) {
15495
- if (this.options.ns.indexOf(ns) < 0) {
15496
- this.options.ns.push(ns);
15497
- }
15498
- }
15499
- removeNamespaces(ns) {
15500
- const index = this.options.ns.indexOf(ns);
15501
- if (index > -1) {
15502
- this.options.ns.splice(index, 1);
15503
- }
15504
- }
15505
- getResource(lng, ns, key) {
15506
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
15507
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
15508
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
15509
- let path;
15510
- if (lng.indexOf('.') > -1) {
15511
- path = lng.split('.');
15512
- } else {
15513
- path = [lng, ns];
15514
- if (key) {
15515
- if (Array.isArray(key)) {
15516
- path.push(...key);
15517
- } else if (isString(key) && keySeparator) {
15518
- path.push(...key.split(keySeparator));
15519
- } else {
15520
- path.push(key);
15521
- }
15522
- }
15523
- }
15524
- const result = getPath(this.data, path);
15525
- if (!result && !ns && !key && lng.indexOf('.') > -1) {
15526
- lng = path[0];
15527
- ns = path[1];
15528
- key = path.slice(2).join('.');
15529
- }
15530
- if (result || !ignoreJSONStructure || !isString(key)) return result;
15531
- return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
15532
- }
15533
- addResource(lng, ns, key, value) {
15534
- let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
15535
- silent: false
15536
- };
15537
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
15538
- let path = [lng, ns];
15539
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
15540
- if (lng.indexOf('.') > -1) {
15541
- path = lng.split('.');
15542
- value = ns;
15543
- ns = path[1];
15544
- }
15545
- this.addNamespaces(ns);
15546
- setPath(this.data, path, value);
15547
- if (!options.silent) this.emit('added', lng, ns, key, value);
15548
- }
15549
- addResources(lng, ns, resources) {
15550
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
15551
- silent: false
15552
- };
15553
- for (const m in resources) {
15554
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
15555
- silent: true
15556
- });
15557
- }
15558
- if (!options.silent) this.emit('added', lng, ns, resources);
15559
- }
15560
- addResourceBundle(lng, ns, resources, deep, overwrite) {
15561
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
15562
- silent: false,
15563
- skipCopy: false
15564
- };
15565
- let path = [lng, ns];
15566
- if (lng.indexOf('.') > -1) {
15567
- path = lng.split('.');
15568
- deep = resources;
15569
- resources = ns;
15570
- ns = path[1];
15571
- }
15572
- this.addNamespaces(ns);
15573
- let pack = getPath(this.data, path) || {};
15574
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
15575
- if (deep) {
15576
- deepExtend(pack, resources, overwrite);
15577
- } else {
15578
- pack = {
15579
- ...pack,
15580
- ...resources
15581
- };
15582
- }
15583
- setPath(this.data, path, pack);
15584
- if (!options.silent) this.emit('added', lng, ns, resources);
15585
- }
15586
- removeResourceBundle(lng, ns) {
15587
- if (this.hasResourceBundle(lng, ns)) {
15588
- delete this.data[lng][ns];
15589
- }
15590
- this.removeNamespaces(ns);
15591
- this.emit('removed', lng, ns);
15592
- }
15593
- hasResourceBundle(lng, ns) {
15594
- return this.getResource(lng, ns) !== undefined;
15595
- }
15596
- getResourceBundle(lng, ns) {
15597
- if (!ns) ns = this.options.defaultNS;
15598
- if (this.options.compatibilityAPI === 'v1') return {
15599
- ...{},
15600
- ...this.getResource(lng, ns)
15601
- };
15602
- return this.getResource(lng, ns);
15603
- }
15604
- getDataByLanguage(lng) {
15605
- return this.data[lng];
15606
- }
15607
- hasLanguageSomeTranslations(lng) {
15608
- const data = this.getDataByLanguage(lng);
15609
- const n = data && Object.keys(data) || [];
15610
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
15611
- }
15612
- toJSON() {
15613
- return this.data;
15614
- }
15615
- }
15616
-
15617
- var postProcessor = {
15618
- processors: {},
15619
- addPostProcessor(module) {
15620
- this.processors[module.name] = module;
15621
- },
15622
- handle(processors, value, key, options, translator) {
15623
- processors.forEach(processor => {
15624
- if (this.processors[processor]) value = this.processors[processor].process(value, key, options, translator);
15625
- });
15626
- return value;
15627
- }
15628
- };
15629
-
15630
- const checkedLoadedFor = {};
15631
- class Translator extends EventEmitter {
15632
- constructor(services) {
15633
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
15634
- super();
15635
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
15636
- this.options = options;
15637
- if (this.options.keySeparator === undefined) {
15638
- this.options.keySeparator = '.';
15639
- }
15640
- this.logger = baseLogger.create('translator');
15641
- }
15642
- changeLanguage(lng) {
15643
- if (lng) this.language = lng;
15644
- }
15645
- exists(key) {
15646
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
15647
- interpolation: {}
15648
- };
15649
- if (key === undefined || key === null) {
15650
- return false;
15651
- }
15652
- const resolved = this.resolve(key, options);
15653
- return resolved && resolved.res !== undefined;
15654
- }
15655
- extractFromKey(key, options) {
15656
- let nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
15657
- if (nsSeparator === undefined) nsSeparator = ':';
15658
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
15659
- let namespaces = options.ns || this.options.defaultNS || [];
15660
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
15661
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
15662
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
15663
- const m = key.match(this.interpolator.nestingRegexp);
15664
- if (m && m.length > 0) {
15665
- return {
15666
- key,
15667
- namespaces: isString(namespaces) ? [namespaces] : namespaces
15668
- };
15669
- }
15670
- const parts = key.split(nsSeparator);
15671
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
15672
- key = parts.join(keySeparator);
15673
- }
15674
- return {
15675
- key,
15676
- namespaces: isString(namespaces) ? [namespaces] : namespaces
15677
- };
15678
- }
15679
- translate(keys, options, lastKey) {
15680
- if (typeof options !== 'object' && this.options.overloadTranslationOptionHandler) {
15681
- options = this.options.overloadTranslationOptionHandler(arguments);
15682
- }
15683
- if (typeof options === 'object') options = {
15684
- ...options
15685
- };
15686
- if (!options) options = {};
15687
- if (keys === undefined || keys === null) return '';
15688
- if (!Array.isArray(keys)) keys = [String(keys)];
15689
- const returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
15690
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
15691
- const {
15692
- key,
15693
- namespaces
15694
- } = this.extractFromKey(keys[keys.length - 1], options);
15695
- const namespace = namespaces[namespaces.length - 1];
15696
- const lng = options.lng || this.language;
15697
- const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
15698
- if (lng && lng.toLowerCase() === 'cimode') {
15699
- if (appendNamespaceToCIMode) {
15700
- const nsSeparator = options.nsSeparator || this.options.nsSeparator;
15701
- if (returnDetails) {
15702
- return {
15703
- res: `${namespace}${nsSeparator}${key}`,
15704
- usedKey: key,
15705
- exactUsedKey: key,
15706
- usedLng: lng,
15707
- usedNS: namespace,
15708
- usedParams: this.getUsedParamsDetails(options)
15709
- };
15710
- }
15711
- return `${namespace}${nsSeparator}${key}`;
15712
- }
15713
- if (returnDetails) {
15714
- return {
15715
- res: key,
15716
- usedKey: key,
15717
- exactUsedKey: key,
15718
- usedLng: lng,
15719
- usedNS: namespace,
15720
- usedParams: this.getUsedParamsDetails(options)
15721
- };
15722
- }
15723
- return key;
15724
- }
15725
- const resolved = this.resolve(keys, options);
15726
- let res = resolved && resolved.res;
15727
- const resUsedKey = resolved && resolved.usedKey || key;
15728
- const resExactUsedKey = resolved && resolved.exactUsedKey || key;
15729
- const resType = Object.prototype.toString.apply(res);
15730
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
15731
- const joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
15732
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
15733
- const handleAsObject = !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
15734
- if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(res))) {
15735
- if (!options.returnObjects && !this.options.returnObjects) {
15736
- if (!this.options.returnedObjectHandler) {
15737
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
15738
- }
15739
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
15740
- ...options,
15741
- ns: namespaces
15742
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
15743
- if (returnDetails) {
15744
- resolved.res = r;
15745
- resolved.usedParams = this.getUsedParamsDetails(options);
15746
- return resolved;
15747
- }
15748
- return r;
15749
- }
15750
- if (keySeparator) {
15751
- const resTypeIsArray = Array.isArray(res);
15752
- const copy = resTypeIsArray ? [] : {};
15753
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
15754
- for (const m in res) {
15755
- if (Object.prototype.hasOwnProperty.call(res, m)) {
15756
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
15757
- copy[m] = this.translate(deepKey, {
15758
- ...options,
15759
- ...{
15760
- joinArrays: false,
15761
- ns: namespaces
15762
- }
15763
- });
15764
- if (copy[m] === deepKey) copy[m] = res[m];
15765
- }
15766
- }
15767
- res = copy;
15768
- }
15769
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
15770
- res = res.join(joinArrays);
15771
- if (res) res = this.extendTranslation(res, keys, options, lastKey);
15772
- } else {
15773
- let usedDefault = false;
15774
- let usedKey = false;
15775
- const needsPluralHandling = options.count !== undefined && !isString(options.count);
15776
- const hasDefaultValue = Translator.hasDefaultValue(options);
15777
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
15778
- const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
15779
- ordinal: false
15780
- }) : '';
15781
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
15782
- const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
15783
- if (!this.isValidLookup(res) && hasDefaultValue) {
15784
- usedDefault = true;
15785
- res = defaultValue;
15786
- }
15787
- if (!this.isValidLookup(res)) {
15788
- usedKey = true;
15789
- res = key;
15790
- }
15791
- const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
15792
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
15793
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
15794
- if (usedKey || usedDefault || updateMissing) {
15795
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
15796
- if (keySeparator) {
15797
- const fk = this.resolve(key, {
15798
- ...options,
15799
- keySeparator: false
15800
- });
15801
- 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.');
15802
- }
15803
- let lngs = [];
15804
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
15805
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
15806
- for (let i = 0; i < fallbackLngs.length; i++) {
15807
- lngs.push(fallbackLngs[i]);
15808
- }
15809
- } else if (this.options.saveMissingTo === 'all') {
15810
- lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
15811
- } else {
15812
- lngs.push(options.lng || this.language);
15813
- }
15814
- const send = (l, k, specificDefaultValue) => {
15815
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
15816
- if (this.options.missingKeyHandler) {
15817
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
15818
- } else if (this.backendConnector && this.backendConnector.saveMissing) {
15819
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
15820
- }
15821
- this.emit('missingKey', l, namespace, k, res);
15822
- };
15823
- if (this.options.saveMissing) {
15824
- if (this.options.saveMissingPlurals && needsPluralHandling) {
15825
- lngs.forEach(language => {
15826
- const suffixes = this.pluralResolver.getSuffixes(language, options);
15827
- if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
15828
- suffixes.push(`${this.options.pluralSeparator}zero`);
15829
- }
15830
- suffixes.forEach(suffix => {
15831
- send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
15832
- });
15833
- });
15834
- } else {
15835
- send(lngs, key, defaultValue);
15836
- }
15837
- }
15838
- }
15839
- res = this.extendTranslation(res, keys, options, resolved, lastKey);
15840
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
15841
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
15842
- if (this.options.compatibilityAPI !== 'v1') {
15843
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : undefined);
15844
- } else {
15845
- res = this.options.parseMissingKeyHandler(res);
15846
- }
15847
- }
15848
- }
15849
- if (returnDetails) {
15850
- resolved.res = res;
15851
- resolved.usedParams = this.getUsedParamsDetails(options);
15852
- return resolved;
15853
- }
15854
- return res;
15855
- }
15856
- extendTranslation(res, key, options, resolved, lastKey) {
15857
- var _this = this;
15858
- if (this.i18nFormat && this.i18nFormat.parse) {
15859
- res = this.i18nFormat.parse(res, {
15860
- ...this.options.interpolation.defaultVariables,
15861
- ...options
15862
- }, options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
15863
- resolved
15864
- });
15865
- } else if (!options.skipInterpolation) {
15866
- if (options.interpolation) this.interpolator.init({
15867
- ...options,
15868
- ...{
15869
- interpolation: {
15870
- ...this.options.interpolation,
15871
- ...options.interpolation
15872
- }
15873
- }
15874
- });
15875
- const skipOnVariables = isString(res) && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
15876
- let nestBef;
15877
- if (skipOnVariables) {
15878
- const nb = res.match(this.interpolator.nestingRegexp);
15879
- nestBef = nb && nb.length;
15880
- }
15881
- let data = options.replace && !isString(options.replace) ? options.replace : options;
15882
- if (this.options.interpolation.defaultVariables) data = {
15883
- ...this.options.interpolation.defaultVariables,
15884
- ...data
15885
- };
15886
- res = this.interpolator.interpolate(res, data, options.lng || this.language || resolved.usedLng, options);
15887
- if (skipOnVariables) {
15888
- const na = res.match(this.interpolator.nestingRegexp);
15889
- const nestAft = na && na.length;
15890
- if (nestBef < nestAft) options.nest = false;
15891
- }
15892
- if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = this.language || resolved.usedLng;
15893
- if (options.nest !== false) res = this.interpolator.nest(res, function () {
15894
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
15895
- args[_key] = arguments[_key];
15896
- }
15897
- if (lastKey && lastKey[0] === args[0] && !options.context) {
15898
- _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
15899
- return null;
15900
- }
15901
- return _this.translate(...args, key);
15902
- }, options);
15903
- if (options.interpolation) this.interpolator.reset();
15904
- }
15905
- const postProcess = options.postProcess || this.options.postProcess;
15906
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
15907
- if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
15908
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
15909
- i18nResolved: {
15910
- ...resolved,
15911
- usedParams: this.getUsedParamsDetails(options)
15912
- },
15913
- ...options
15914
- } : options, this);
15915
- }
15916
- return res;
15917
- }
15918
- resolve(keys) {
15919
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
15920
- let found;
15921
- let usedKey;
15922
- let exactUsedKey;
15923
- let usedLng;
15924
- let usedNS;
15925
- if (isString(keys)) keys = [keys];
15926
- keys.forEach(k => {
15927
- if (this.isValidLookup(found)) return;
15928
- const extracted = this.extractFromKey(k, options);
15929
- const key = extracted.key;
15930
- usedKey = key;
15931
- let namespaces = extracted.namespaces;
15932
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
15933
- const needsPluralHandling = options.count !== undefined && !isString(options.count);
15934
- const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
15935
- const needsContextHandling = options.context !== undefined && (isString(options.context) || typeof options.context === 'number') && options.context !== '';
15936
- const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
15937
- namespaces.forEach(ns => {
15938
- if (this.isValidLookup(found)) return;
15939
- usedNS = ns;
15940
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
15941
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
15942
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
15943
- }
15944
- codes.forEach(code => {
15945
- if (this.isValidLookup(found)) return;
15946
- usedLng = code;
15947
- const finalKeys = [key];
15948
- if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
15949
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
15950
- } else {
15951
- let pluralSuffix;
15952
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
15953
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
15954
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
15955
- if (needsPluralHandling) {
15956
- finalKeys.push(key + pluralSuffix);
15957
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
15958
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
15959
- }
15960
- if (needsZeroSuffixLookup) {
15961
- finalKeys.push(key + zeroSuffix);
15962
- }
15963
- }
15964
- if (needsContextHandling) {
15965
- const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
15966
- finalKeys.push(contextKey);
15967
- if (needsPluralHandling) {
15968
- finalKeys.push(contextKey + pluralSuffix);
15969
- if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
15970
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
15971
- }
15972
- if (needsZeroSuffixLookup) {
15973
- finalKeys.push(contextKey + zeroSuffix);
15974
- }
15975
- }
15976
- }
15977
- }
15978
- let possibleKey;
15979
- while (possibleKey = finalKeys.pop()) {
15980
- if (!this.isValidLookup(found)) {
15981
- exactUsedKey = possibleKey;
15982
- found = this.getResource(code, ns, possibleKey, options);
15983
- }
15984
- }
15985
- });
15986
- });
15987
- });
15988
- return {
15989
- res: found,
15990
- usedKey,
15991
- exactUsedKey,
15992
- usedLng,
15993
- usedNS
15994
- };
15995
- }
15996
- isValidLookup(res) {
15997
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
15998
- }
15999
- getResource(code, ns, key) {
16000
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
16001
- if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
16002
- return this.resourceStore.getResource(code, ns, key, options);
16003
- }
16004
- getUsedParamsDetails() {
16005
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
16006
- const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
16007
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
16008
- let data = useOptionsReplaceForData ? options.replace : options;
16009
- if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
16010
- data.count = options.count;
16011
- }
16012
- if (this.options.interpolation.defaultVariables) {
16013
- data = {
16014
- ...this.options.interpolation.defaultVariables,
16015
- ...data
16016
- };
16017
- }
16018
- if (!useOptionsReplaceForData) {
16019
- data = {
16020
- ...data
16021
- };
16022
- for (const key of optionsKeys) {
16023
- delete data[key];
16024
- }
16025
- }
16026
- return data;
16027
- }
16028
- static hasDefaultValue(options) {
16029
- const prefix = 'defaultValue';
16030
- for (const option in options) {
16031
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
16032
- return true;
16033
- }
16034
- }
16035
- return false;
16036
- }
16037
- }
16038
-
16039
- const capitalize = string => string.charAt(0).toUpperCase() + string.slice(1);
16040
- class LanguageUtil {
16041
- constructor(options) {
16042
- this.options = options;
16043
- this.supportedLngs = this.options.supportedLngs || false;
16044
- this.logger = baseLogger.create('languageUtils');
16045
- }
16046
- getScriptPartFromCode(code) {
16047
- code = getCleanedCode(code);
16048
- if (!code || code.indexOf('-') < 0) return null;
16049
- const p = code.split('-');
16050
- if (p.length === 2) return null;
16051
- p.pop();
16052
- if (p[p.length - 1].toLowerCase() === 'x') return null;
16053
- return this.formatLanguageCode(p.join('-'));
16054
- }
16055
- getLanguagePartFromCode(code) {
16056
- code = getCleanedCode(code);
16057
- if (!code || code.indexOf('-') < 0) return code;
16058
- const p = code.split('-');
16059
- return this.formatLanguageCode(p[0]);
16060
- }
16061
- formatLanguageCode(code) {
16062
- if (isString(code) && code.indexOf('-') > -1) {
16063
- if (typeof Intl !== 'undefined' && typeof Intl.getCanonicalLocales !== 'undefined') {
16064
- try {
16065
- let formattedCode = Intl.getCanonicalLocales(code)[0];
16066
- if (formattedCode && this.options.lowerCaseLng) {
16067
- formattedCode = formattedCode.toLowerCase();
16068
- }
16069
- if (formattedCode) return formattedCode;
16070
- } catch (e) {}
16071
- }
16072
- const specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
16073
- let p = code.split('-');
16074
- if (this.options.lowerCaseLng) {
16075
- p = p.map(part => part.toLowerCase());
16076
- } else if (p.length === 2) {
16077
- p[0] = p[0].toLowerCase();
16078
- p[1] = p[1].toUpperCase();
16079
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
16080
- } else if (p.length === 3) {
16081
- p[0] = p[0].toLowerCase();
16082
- if (p[1].length === 2) p[1] = p[1].toUpperCase();
16083
- if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
16084
- if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
16085
- if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
16086
- }
16087
- return p.join('-');
16088
- }
16089
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
16090
- }
16091
- isSupportedCode(code) {
16092
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
16093
- code = this.getLanguagePartFromCode(code);
16094
- }
16095
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
16096
- }
16097
- getBestMatchFromCodes(codes) {
16098
- if (!codes) return null;
16099
- let found;
16100
- codes.forEach(code => {
16101
- if (found) return;
16102
- const cleanedLng = this.formatLanguageCode(code);
16103
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
16104
- });
16105
- if (!found && this.options.supportedLngs) {
16106
- codes.forEach(code => {
16107
- if (found) return;
16108
- const lngOnly = this.getLanguagePartFromCode(code);
16109
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
16110
- found = this.options.supportedLngs.find(supportedLng => {
16111
- if (supportedLng === lngOnly) return supportedLng;
16112
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
16113
- if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
16114
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
16115
- });
16116
- });
16117
- }
16118
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
16119
- return found;
16120
- }
16121
- getFallbackCodes(fallbacks, code) {
16122
- if (!fallbacks) return [];
16123
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
16124
- if (isString(fallbacks)) fallbacks = [fallbacks];
16125
- if (Array.isArray(fallbacks)) return fallbacks;
16126
- if (!code) return fallbacks.default || [];
16127
- let found = fallbacks[code];
16128
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
16129
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
16130
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
16131
- if (!found) found = fallbacks.default;
16132
- return found || [];
16133
- }
16134
- toResolveHierarchy(code, fallbackCode) {
16135
- const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
16136
- const codes = [];
16137
- const addCode = c => {
16138
- if (!c) return;
16139
- if (this.isSupportedCode(c)) {
16140
- codes.push(c);
16141
- } else {
16142
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
16143
- }
16144
- };
16145
- if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
16146
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
16147
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
16148
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
16149
- } else if (isString(code)) {
16150
- addCode(this.formatLanguageCode(code));
16151
- }
16152
- fallbackCodes.forEach(fc => {
16153
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
16154
- });
16155
- return codes;
16156
- }
16157
- }
16158
-
16159
- let sets = [{
16160
- lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
16161
- nr: [1, 2],
16162
- fc: 1
16163
- }, {
16164
- 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'],
16165
- nr: [1, 2],
16166
- fc: 2
16167
- }, {
16168
- lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
16169
- nr: [1],
16170
- fc: 3
16171
- }, {
16172
- lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
16173
- nr: [1, 2, 5],
16174
- fc: 4
16175
- }, {
16176
- lngs: ['ar'],
16177
- nr: [0, 1, 2, 3, 11, 100],
16178
- fc: 5
16179
- }, {
16180
- lngs: ['cs', 'sk'],
16181
- nr: [1, 2, 5],
16182
- fc: 6
16183
- }, {
16184
- lngs: ['csb', 'pl'],
16185
- nr: [1, 2, 5],
16186
- fc: 7
16187
- }, {
16188
- lngs: ['cy'],
16189
- nr: [1, 2, 3, 8],
16190
- fc: 8
16191
- }, {
16192
- lngs: ['fr'],
16193
- nr: [1, 2],
16194
- fc: 9
16195
- }, {
16196
- lngs: ['ga'],
16197
- nr: [1, 2, 3, 7, 11],
16198
- fc: 10
16199
- }, {
16200
- lngs: ['gd'],
16201
- nr: [1, 2, 3, 20],
16202
- fc: 11
16203
- }, {
16204
- lngs: ['is'],
16205
- nr: [1, 2],
16206
- fc: 12
16207
- }, {
16208
- lngs: ['jv'],
16209
- nr: [0, 1],
16210
- fc: 13
16211
- }, {
16212
- lngs: ['kw'],
16213
- nr: [1, 2, 3, 4],
16214
- fc: 14
16215
- }, {
16216
- lngs: ['lt'],
16217
- nr: [1, 2, 10],
16218
- fc: 15
16219
- }, {
16220
- lngs: ['lv'],
16221
- nr: [1, 2, 0],
16222
- fc: 16
16223
- }, {
16224
- lngs: ['mk'],
16225
- nr: [1, 2],
16226
- fc: 17
16227
- }, {
16228
- lngs: ['mnk'],
16229
- nr: [0, 1, 2],
16230
- fc: 18
16231
- }, {
16232
- lngs: ['mt'],
16233
- nr: [1, 2, 11, 20],
16234
- fc: 19
16235
- }, {
16236
- lngs: ['or'],
16237
- nr: [2, 1],
16238
- fc: 2
16239
- }, {
16240
- lngs: ['ro'],
16241
- nr: [1, 2, 20],
16242
- fc: 20
16243
- }, {
16244
- lngs: ['sl'],
16245
- nr: [5, 1, 2, 3],
16246
- fc: 21
16247
- }, {
16248
- lngs: ['he', 'iw'],
16249
- nr: [1, 2, 20, 21],
16250
- fc: 22
16251
- }];
16252
- let _rulesPluralsTypes = {
16253
- 1: n => Number(n > 1),
16254
- 2: n => Number(n != 1),
16255
- 3: n => 0,
16256
- 4: n => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
16257
- 5: n => Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5),
16258
- 6: n => Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2),
16259
- 7: n => Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
16260
- 8: n => Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3),
16261
- 9: n => Number(n >= 2),
16262
- 10: n => Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4),
16263
- 11: n => Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3),
16264
- 12: n => Number(n % 10 != 1 || n % 100 == 11),
16265
- 13: n => Number(n !== 0),
16266
- 14: n => Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3),
16267
- 15: n => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2),
16268
- 16: n => Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2),
16269
- 17: n => Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1),
16270
- 18: n => Number(n == 0 ? 0 : n == 1 ? 1 : 2),
16271
- 19: n => Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3),
16272
- 20: n => Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2),
16273
- 21: n => Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0),
16274
- 22: n => Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3)
16275
- };
16276
- const nonIntlVersions = ['v1', 'v2', 'v3'];
16277
- const intlVersions = ['v4'];
16278
- const suffixesOrder = {
16279
- zero: 0,
16280
- one: 1,
16281
- two: 2,
16282
- few: 3,
16283
- many: 4,
16284
- other: 5
16285
- };
16286
- const createRules = () => {
16287
- const rules = {};
16288
- sets.forEach(set => {
16289
- set.lngs.forEach(l => {
16290
- rules[l] = {
16291
- numbers: set.nr,
16292
- plurals: _rulesPluralsTypes[set.fc]
16293
- };
16294
- });
16295
- });
16296
- return rules;
16297
- };
16298
- class PluralResolver {
16299
- constructor(languageUtils) {
16300
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
16301
- this.languageUtils = languageUtils;
16302
- this.options = options;
16303
- this.logger = baseLogger.create('pluralResolver');
16304
- if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
16305
- this.options.compatibilityJSON = 'v3';
16306
- 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.');
16307
- }
16308
- this.rules = createRules();
16309
- this.pluralRulesCache = {};
16310
- }
16311
- addRule(lng, obj) {
16312
- this.rules[lng] = obj;
16313
- }
16314
- clearCache() {
16315
- this.pluralRulesCache = {};
16316
- }
16317
- getRule(code) {
16318
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
16319
- if (this.shouldUseIntlApi()) {
16320
- const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
16321
- const type = options.ordinal ? 'ordinal' : 'cardinal';
16322
- const cacheKey = JSON.stringify({
16323
- cleanedCode,
16324
- type
16325
- });
16326
- if (cacheKey in this.pluralRulesCache) {
16327
- return this.pluralRulesCache[cacheKey];
16328
- }
16329
- let rule;
16330
- try {
16331
- rule = new Intl.PluralRules(cleanedCode, {
16332
- type
16333
- });
16334
- } catch (err) {
16335
- if (!code.match(/-|_/)) return;
16336
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
16337
- rule = this.getRule(lngPart, options);
16338
- }
16339
- this.pluralRulesCache[cacheKey] = rule;
16340
- return rule;
16341
- }
16342
- return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
16343
- }
16344
- needsPlural(code) {
16345
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
16346
- const rule = this.getRule(code, options);
16347
- if (this.shouldUseIntlApi()) {
16348
- return rule && rule.resolvedOptions().pluralCategories.length > 1;
16349
- }
16350
- return rule && rule.numbers.length > 1;
16351
- }
16352
- getPluralFormsOfKey(code, key) {
16353
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
16354
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
16355
- }
16356
- getSuffixes(code) {
16357
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
16358
- const rule = this.getRule(code, options);
16359
- if (!rule) {
16360
- return [];
16361
- }
16362
- if (this.shouldUseIntlApi()) {
16363
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
16364
- }
16365
- return rule.numbers.map(number => this.getSuffix(code, number, options));
16366
- }
16367
- getSuffix(code, count) {
16368
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
16369
- const rule = this.getRule(code, options);
16370
- if (rule) {
16371
- if (this.shouldUseIntlApi()) {
16372
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
16373
- }
16374
- return this.getSuffixRetroCompatible(rule, count);
16375
- }
16376
- this.logger.warn(`no plural rule found for: ${code}`);
16377
- return '';
16378
- }
16379
- getSuffixRetroCompatible(rule, count) {
16380
- const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
16381
- let suffix = rule.numbers[idx];
16382
- if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
16383
- if (suffix === 2) {
16384
- suffix = 'plural';
16385
- } else if (suffix === 1) {
16386
- suffix = '';
16387
- }
16388
- }
16389
- const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
16390
- if (this.options.compatibilityJSON === 'v1') {
16391
- if (suffix === 1) return '';
16392
- if (typeof suffix === 'number') return `_plural_${suffix.toString()}`;
16393
- return returnSuffix();
16394
- } else if (this.options.compatibilityJSON === 'v2') {
16395
- return returnSuffix();
16396
- } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
16397
- return returnSuffix();
16398
- }
16399
- return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
16400
- }
16401
- shouldUseIntlApi() {
16402
- return !nonIntlVersions.includes(this.options.compatibilityJSON);
16403
- }
16404
- }
16405
-
16406
- const deepFindWithDefaults = function (data, defaultData, key) {
16407
- let keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
16408
- let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
16409
- let path = getPathWithDefaults(data, defaultData, key);
16410
- if (!path && ignoreJSONStructure && isString(key)) {
16411
- path = deepFind(data, key, keySeparator);
16412
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
16413
- }
16414
- return path;
16415
- };
16416
- const regexSafe = val => val.replace(/\$/g, '$$$$');
16417
- class Interpolator {
16418
- constructor() {
16419
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
16420
- this.logger = baseLogger.create('interpolator');
16421
- this.options = options;
16422
- this.format = options.interpolation && options.interpolation.format || (value => value);
16423
- this.init(options);
16424
- }
16425
- init() {
16426
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
16427
- if (!options.interpolation) options.interpolation = {
16428
- escapeValue: true
16429
- };
16430
- const {
16431
- escape: escape$1,
16432
- escapeValue,
16433
- useRawValueToEscape,
16434
- prefix,
16435
- prefixEscaped,
16436
- suffix,
16437
- suffixEscaped,
16438
- formatSeparator,
16439
- unescapeSuffix,
16440
- unescapePrefix,
16441
- nestingPrefix,
16442
- nestingPrefixEscaped,
16443
- nestingSuffix,
16444
- nestingSuffixEscaped,
16445
- nestingOptionsSeparator,
16446
- maxReplaces,
16447
- alwaysFormat
16448
- } = options.interpolation;
16449
- this.escape = escape$1 !== undefined ? escape$1 : escape;
16450
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
16451
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
16452
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
16453
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
16454
- this.formatSeparator = formatSeparator || ',';
16455
- this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
16456
- this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
16457
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
16458
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
16459
- this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
16460
- this.maxReplaces = maxReplaces || 1000;
16461
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
16462
- this.resetRegExp();
16463
- }
16464
- reset() {
16465
- if (this.options) this.init(this.options);
16466
- }
16467
- resetRegExp() {
16468
- const getOrResetRegExp = (existingRegExp, pattern) => {
16469
- if (existingRegExp && existingRegExp.source === pattern) {
16470
- existingRegExp.lastIndex = 0;
16471
- return existingRegExp;
16472
- }
16473
- return new RegExp(pattern, 'g');
16474
- };
16475
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
16476
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
16477
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
16478
- }
16479
- interpolate(str, data, lng, options) {
16480
- let match;
16481
- let value;
16482
- let replaces;
16483
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
16484
- const handleFormat = key => {
16485
- if (key.indexOf(this.formatSeparator) < 0) {
16486
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
16487
- return this.alwaysFormat ? this.format(path, undefined, lng, {
16488
- ...options,
16489
- ...data,
16490
- interpolationkey: key
16491
- }) : path;
16492
- }
16493
- const p = key.split(this.formatSeparator);
16494
- const k = p.shift().trim();
16495
- const f = p.join(this.formatSeparator).trim();
16496
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
16497
- ...options,
16498
- ...data,
16499
- interpolationkey: k
16500
- });
16501
- };
16502
- this.resetRegExp();
16503
- const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
16504
- const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
16505
- const todos = [{
16506
- regex: this.regexpUnescape,
16507
- safeValue: val => regexSafe(val)
16508
- }, {
16509
- regex: this.regexp,
16510
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
16511
- }];
16512
- todos.forEach(todo => {
16513
- replaces = 0;
16514
- while (match = todo.regex.exec(str)) {
16515
- const matchedVar = match[1].trim();
16516
- value = handleFormat(matchedVar);
16517
- if (value === undefined) {
16518
- if (typeof missingInterpolationHandler === 'function') {
16519
- const temp = missingInterpolationHandler(str, match, options);
16520
- value = isString(temp) ? temp : '';
16521
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
16522
- value = '';
16523
- } else if (skipOnVariables) {
16524
- value = match[0];
16525
- continue;
16526
- } else {
16527
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
16528
- value = '';
16529
- }
16530
- } else if (!isString(value) && !this.useRawValueToEscape) {
16531
- value = makeString(value);
16532
- }
16533
- const safeValue = todo.safeValue(value);
16534
- str = str.replace(match[0], safeValue);
16535
- if (skipOnVariables) {
16536
- todo.regex.lastIndex += value.length;
16537
- todo.regex.lastIndex -= match[0].length;
16538
- } else {
16539
- todo.regex.lastIndex = 0;
16540
- }
16541
- replaces++;
16542
- if (replaces >= this.maxReplaces) {
16543
- break;
16544
- }
16545
- }
16546
- });
16547
- return str;
16548
- }
16549
- nest(str, fc) {
16550
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
16551
- let match;
16552
- let value;
16553
- let clonedOptions;
16554
- const handleHasOptions = (key, inheritedOptions) => {
16555
- const sep = this.nestingOptionsSeparator;
16556
- if (key.indexOf(sep) < 0) return key;
16557
- const c = key.split(new RegExp(`${sep}[ ]*{`));
16558
- let optionsString = `{${c[1]}`;
16559
- key = c[0];
16560
- optionsString = this.interpolate(optionsString, clonedOptions);
16561
- const matchedSingleQuotes = optionsString.match(/'/g);
16562
- const matchedDoubleQuotes = optionsString.match(/"/g);
16563
- if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
16564
- optionsString = optionsString.replace(/'/g, '"');
16565
- }
16566
- try {
16567
- clonedOptions = JSON.parse(optionsString);
16568
- if (inheritedOptions) clonedOptions = {
16569
- ...inheritedOptions,
16570
- ...clonedOptions
16571
- };
16572
- } catch (e) {
16573
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
16574
- return `${key}${sep}${optionsString}`;
16575
- }
16576
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
16577
- return key;
16578
- };
16579
- while (match = this.nestingRegexp.exec(str)) {
16580
- let formatters = [];
16581
- clonedOptions = {
16582
- ...options
16583
- };
16584
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
16585
- clonedOptions.applyPostProcessor = false;
16586
- delete clonedOptions.defaultValue;
16587
- let doReduce = false;
16588
- if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
16589
- const r = match[1].split(this.formatSeparator).map(elem => elem.trim());
16590
- match[1] = r.shift();
16591
- formatters = r;
16592
- doReduce = true;
16593
- }
16594
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
16595
- if (value && match[0] === str && !isString(value)) return value;
16596
- if (!isString(value)) value = makeString(value);
16597
- if (!value) {
16598
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
16599
- value = '';
16600
- }
16601
- if (doReduce) {
16602
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
16603
- ...options,
16604
- interpolationkey: match[1].trim()
16605
- }), value.trim());
16606
- }
16607
- str = str.replace(match[0], value);
16608
- this.regexp.lastIndex = 0;
16609
- }
16610
- return str;
16611
- }
16612
- }
16613
-
16614
- const parseFormatStr = formatStr => {
16615
- let formatName = formatStr.toLowerCase().trim();
16616
- const formatOptions = {};
16617
- if (formatStr.indexOf('(') > -1) {
16618
- const p = formatStr.split('(');
16619
- formatName = p[0].toLowerCase().trim();
16620
- const optStr = p[1].substring(0, p[1].length - 1);
16621
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
16622
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
16623
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
16624
- if (!formatOptions.range) formatOptions.range = optStr.trim();
16625
- } else {
16626
- const opts = optStr.split(';');
16627
- opts.forEach(opt => {
16628
- if (opt) {
16629
- const [key, ...rest] = opt.split(':');
16630
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
16631
- const trimmedKey = key.trim();
16632
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
16633
- if (val === 'false') formatOptions[trimmedKey] = false;
16634
- if (val === 'true') formatOptions[trimmedKey] = true;
16635
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
16636
- }
16637
- });
16638
- }
16639
- }
16640
- return {
16641
- formatName,
16642
- formatOptions
16643
- };
16644
- };
16645
- const createCachedFormatter = fn => {
16646
- const cache = {};
16647
- return (val, lng, options) => {
16648
- let optForCache = options;
16649
- if (options && options.interpolationkey && options.formatParams && options.formatParams[options.interpolationkey] && options[options.interpolationkey]) {
16650
- optForCache = {
16651
- ...optForCache,
16652
- [options.interpolationkey]: undefined
16653
- };
16654
- }
16655
- const key = lng + JSON.stringify(optForCache);
16656
- let formatter = cache[key];
16657
- if (!formatter) {
16658
- formatter = fn(getCleanedCode(lng), options);
16659
- cache[key] = formatter;
16660
- }
16661
- return formatter(val);
16662
- };
16663
- };
16664
- class Formatter {
16665
- constructor() {
16666
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
16667
- this.logger = baseLogger.create('formatter');
16668
- this.options = options;
16669
- this.formats = {
16670
- number: createCachedFormatter((lng, opt) => {
16671
- const formatter = new Intl.NumberFormat(lng, {
16672
- ...opt
16673
- });
16674
- return val => formatter.format(val);
16675
- }),
16676
- currency: createCachedFormatter((lng, opt) => {
16677
- const formatter = new Intl.NumberFormat(lng, {
16678
- ...opt,
16679
- style: 'currency'
16680
- });
16681
- return val => formatter.format(val);
16682
- }),
16683
- datetime: createCachedFormatter((lng, opt) => {
16684
- const formatter = new Intl.DateTimeFormat(lng, {
16685
- ...opt
16686
- });
16687
- return val => formatter.format(val);
16688
- }),
16689
- relativetime: createCachedFormatter((lng, opt) => {
16690
- const formatter = new Intl.RelativeTimeFormat(lng, {
16691
- ...opt
16692
- });
16693
- return val => formatter.format(val, opt.range || 'day');
16694
- }),
16695
- list: createCachedFormatter((lng, opt) => {
16696
- const formatter = new Intl.ListFormat(lng, {
16697
- ...opt
16698
- });
16699
- return val => formatter.format(val);
16700
- })
16701
- };
16702
- this.init(options);
16703
- }
16704
- init(services) {
16705
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
16706
- interpolation: {}
16707
- };
16708
- this.formatSeparator = options.interpolation.formatSeparator || ',';
16709
- }
16710
- add(name, fc) {
16711
- this.formats[name.toLowerCase().trim()] = fc;
16712
- }
16713
- addCached(name, fc) {
16714
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
16715
- }
16716
- format(value, format, lng) {
16717
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
16718
- const formats = format.split(this.formatSeparator);
16719
- if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
16720
- const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
16721
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
16722
- }
16723
- const result = formats.reduce((mem, f) => {
16724
- const {
16725
- formatName,
16726
- formatOptions
16727
- } = parseFormatStr(f);
16728
- if (this.formats[formatName]) {
16729
- let formatted = mem;
16730
- try {
16731
- const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
16732
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
16733
- formatted = this.formats[formatName](mem, l, {
16734
- ...formatOptions,
16735
- ...options,
16736
- ...valOptions
16737
- });
16738
- } catch (error) {
16739
- this.logger.warn(error);
16740
- }
16741
- return formatted;
16742
- } else {
16743
- this.logger.warn(`there was no format function for ${formatName}`);
16744
- }
16745
- return mem;
16746
- }, value);
16747
- return result;
16748
- }
16749
- }
16750
-
16751
- const removePending = (q, name) => {
16752
- if (q.pending[name] !== undefined) {
16753
- delete q.pending[name];
16754
- q.pendingCount--;
16755
- }
16756
- };
16757
- class Connector extends EventEmitter {
16758
- constructor(backend, store, services) {
16759
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
16760
- super();
16761
- this.backend = backend;
16762
- this.store = store;
16763
- this.services = services;
16764
- this.languageUtils = services.languageUtils;
16765
- this.options = options;
16766
- this.logger = baseLogger.create('backendConnector');
16767
- this.waitingReads = [];
16768
- this.maxParallelReads = options.maxParallelReads || 10;
16769
- this.readingCalls = 0;
16770
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
16771
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
16772
- this.state = {};
16773
- this.queue = [];
16774
- if (this.backend && this.backend.init) {
16775
- this.backend.init(services, options.backend, options);
16776
- }
16777
- }
16778
- queueLoad(languages, namespaces, options, callback) {
16779
- const toLoad = {};
16780
- const pending = {};
16781
- const toLoadLanguages = {};
16782
- const toLoadNamespaces = {};
16783
- languages.forEach(lng => {
16784
- let hasAllNamespaces = true;
16785
- namespaces.forEach(ns => {
16786
- const name = `${lng}|${ns}`;
16787
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
16788
- this.state[name] = 2;
16789
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
16790
- if (pending[name] === undefined) pending[name] = true;
16791
- } else {
16792
- this.state[name] = 1;
16793
- hasAllNamespaces = false;
16794
- if (pending[name] === undefined) pending[name] = true;
16795
- if (toLoad[name] === undefined) toLoad[name] = true;
16796
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
16797
- }
16798
- });
16799
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
16800
- });
16801
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
16802
- this.queue.push({
16803
- pending,
16804
- pendingCount: Object.keys(pending).length,
16805
- loaded: {},
16806
- errors: [],
16807
- callback
16808
- });
16809
- }
16810
- return {
16811
- toLoad: Object.keys(toLoad),
16812
- pending: Object.keys(pending),
16813
- toLoadLanguages: Object.keys(toLoadLanguages),
16814
- toLoadNamespaces: Object.keys(toLoadNamespaces)
16815
- };
16816
- }
16817
- loaded(name, err, data) {
16818
- const s = name.split('|');
16819
- const lng = s[0];
16820
- const ns = s[1];
16821
- if (err) this.emit('failedLoading', lng, ns, err);
16822
- if (!err && data) {
16823
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
16824
- skipCopy: true
16825
- });
16826
- }
16827
- this.state[name] = err ? -1 : 2;
16828
- if (err && data) this.state[name] = 0;
16829
- const loaded = {};
16830
- this.queue.forEach(q => {
16831
- pushPath(q.loaded, [lng], ns);
16832
- removePending(q, name);
16833
- if (err) q.errors.push(err);
16834
- if (q.pendingCount === 0 && !q.done) {
16835
- Object.keys(q.loaded).forEach(l => {
16836
- if (!loaded[l]) loaded[l] = {};
16837
- const loadedKeys = q.loaded[l];
16838
- if (loadedKeys.length) {
16839
- loadedKeys.forEach(n => {
16840
- if (loaded[l][n] === undefined) loaded[l][n] = true;
16841
- });
16842
- }
16843
- });
16844
- q.done = true;
16845
- if (q.errors.length) {
16846
- q.callback(q.errors);
16847
- } else {
16848
- q.callback();
16849
- }
16850
- }
16851
- });
16852
- this.emit('loaded', loaded);
16853
- this.queue = this.queue.filter(q => !q.done);
16854
- }
16855
- read(lng, ns, fcName) {
16856
- let tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
16857
- let wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
16858
- let callback = arguments.length > 5 ? arguments[5] : undefined;
16859
- if (!lng.length) return callback(null, {});
16860
- if (this.readingCalls >= this.maxParallelReads) {
16861
- this.waitingReads.push({
16862
- lng,
16863
- ns,
16864
- fcName,
16865
- tried,
16866
- wait,
16867
- callback
16868
- });
16869
- return;
16870
- }
16871
- this.readingCalls++;
16872
- const resolver = (err, data) => {
16873
- this.readingCalls--;
16874
- if (this.waitingReads.length > 0) {
16875
- const next = this.waitingReads.shift();
16876
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
16877
- }
16878
- if (err && data && tried < this.maxRetries) {
16879
- setTimeout(() => {
16880
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
16881
- }, wait);
16882
- return;
16883
- }
16884
- callback(err, data);
16885
- };
16886
- const fc = this.backend[fcName].bind(this.backend);
16887
- if (fc.length === 2) {
16888
- try {
16889
- const r = fc(lng, ns);
16890
- if (r && typeof r.then === 'function') {
16891
- r.then(data => resolver(null, data)).catch(resolver);
16892
- } else {
16893
- resolver(null, r);
16894
- }
16895
- } catch (err) {
16896
- resolver(err);
16897
- }
16898
- return;
16899
- }
16900
- return fc(lng, ns, resolver);
16901
- }
16902
- prepareLoading(languages, namespaces) {
16903
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
16904
- let callback = arguments.length > 3 ? arguments[3] : undefined;
16905
- if (!this.backend) {
16906
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
16907
- return callback && callback();
16908
- }
16909
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
16910
- if (isString(namespaces)) namespaces = [namespaces];
16911
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
16912
- if (!toLoad.toLoad.length) {
16913
- if (!toLoad.pending.length) callback();
16914
- return null;
16915
- }
16916
- toLoad.toLoad.forEach(name => {
16917
- this.loadOne(name);
16918
- });
16919
- }
16920
- load(languages, namespaces, callback) {
16921
- this.prepareLoading(languages, namespaces, {}, callback);
16922
- }
16923
- reload(languages, namespaces, callback) {
16924
- this.prepareLoading(languages, namespaces, {
16925
- reload: true
16926
- }, callback);
16927
- }
16928
- loadOne(name) {
16929
- let prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
16930
- const s = name.split('|');
16931
- const lng = s[0];
16932
- const ns = s[1];
16933
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
16934
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
16935
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
16936
- this.loaded(name, err, data);
16937
- });
16938
- }
16939
- saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
16940
- let options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
16941
- let clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : () => {};
16942
- if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
16943
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
16944
- return;
16945
- }
16946
- if (key === undefined || key === null || key === '') return;
16947
- if (this.backend && this.backend.create) {
16948
- const opts = {
16949
- ...options,
16950
- isUpdate
16951
- };
16952
- const fc = this.backend.create.bind(this.backend);
16953
- if (fc.length < 6) {
16954
- try {
16955
- let r;
16956
- if (fc.length === 5) {
16957
- r = fc(languages, namespace, key, fallbackValue, opts);
16958
- } else {
16959
- r = fc(languages, namespace, key, fallbackValue);
16960
- }
16961
- if (r && typeof r.then === 'function') {
16962
- r.then(data => clb(null, data)).catch(clb);
16963
- } else {
16964
- clb(null, r);
16965
- }
16966
- } catch (err) {
16967
- clb(err);
16968
- }
16969
- } else {
16970
- fc(languages, namespace, key, fallbackValue, clb, opts);
16971
- }
16972
- }
16973
- if (!languages || !languages[0]) return;
16974
- this.store.addResource(languages[0], namespace, key, fallbackValue);
16975
- }
16976
- }
16977
-
16978
- const get = () => ({
16979
- debug: false,
16980
- initImmediate: true,
16981
- ns: ['translation'],
16982
- defaultNS: ['translation'],
16983
- fallbackLng: ['dev'],
16984
- fallbackNS: false,
16985
- supportedLngs: false,
16986
- nonExplicitSupportedLngs: false,
16987
- load: 'all',
16988
- preload: false,
16989
- simplifyPluralSuffix: true,
16990
- keySeparator: '.',
16991
- nsSeparator: ':',
16992
- pluralSeparator: '_',
16993
- contextSeparator: '_',
16994
- partialBundledLanguages: false,
16995
- saveMissing: false,
16996
- updateMissing: false,
16997
- saveMissingTo: 'fallback',
16998
- saveMissingPlurals: true,
16999
- missingKeyHandler: false,
17000
- missingInterpolationHandler: false,
17001
- postProcess: false,
17002
- postProcessPassResolved: false,
17003
- returnNull: false,
17004
- returnEmptyString: true,
17005
- returnObjects: false,
17006
- joinArrays: false,
17007
- returnedObjectHandler: false,
17008
- parseMissingKeyHandler: false,
17009
- appendNamespaceToMissingKey: false,
17010
- appendNamespaceToCIMode: false,
17011
- overloadTranslationOptionHandler: args => {
17012
- let ret = {};
17013
- if (typeof args[1] === 'object') ret = args[1];
17014
- if (isString(args[1])) ret.defaultValue = args[1];
17015
- if (isString(args[2])) ret.tDescription = args[2];
17016
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
17017
- const options = args[3] || args[2];
17018
- Object.keys(options).forEach(key => {
17019
- ret[key] = options[key];
17020
- });
17021
- }
17022
- return ret;
17023
- },
17024
- interpolation: {
17025
- escapeValue: true,
17026
- format: value => value,
17027
- prefix: '{{',
17028
- suffix: '}}',
17029
- formatSeparator: ',',
17030
- unescapePrefix: '-',
17031
- nestingPrefix: '$t(',
17032
- nestingSuffix: ')',
17033
- nestingOptionsSeparator: ',',
17034
- maxReplaces: 1000,
17035
- skipOnVariables: true
17036
- }
17037
- });
17038
- const transformOptions = options => {
17039
- if (isString(options.ns)) options.ns = [options.ns];
17040
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
17041
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
17042
- if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
17043
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
17044
- }
17045
- return options;
17046
- };
17047
-
17048
- const noop = () => {};
17049
- const bindMemberFunctions = inst => {
17050
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
17051
- mems.forEach(mem => {
17052
- if (typeof inst[mem] === 'function') {
17053
- inst[mem] = inst[mem].bind(inst);
17054
- }
17055
- });
17056
- };
17057
- class I18n extends EventEmitter {
17058
- constructor() {
17059
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
17060
- let callback = arguments.length > 1 ? arguments[1] : undefined;
17061
- super();
17062
- this.options = transformOptions(options);
17063
- this.services = {};
17064
- this.logger = baseLogger;
17065
- this.modules = {
17066
- external: []
17067
- };
17068
- bindMemberFunctions(this);
17069
- if (callback && !this.isInitialized && !options.isClone) {
17070
- if (!this.options.initImmediate) {
17071
- this.init(options, callback);
17072
- return this;
17073
- }
17074
- setTimeout(() => {
17075
- this.init(options, callback);
17076
- }, 0);
17077
- }
17078
- }
17079
- init() {
17080
- var _this = this;
17081
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
17082
- let callback = arguments.length > 1 ? arguments[1] : undefined;
17083
- this.isInitializing = true;
17084
- if (typeof options === 'function') {
17085
- callback = options;
17086
- options = {};
17087
- }
17088
- if (!options.defaultNS && options.defaultNS !== false && options.ns) {
17089
- if (isString(options.ns)) {
17090
- options.defaultNS = options.ns;
17091
- } else if (options.ns.indexOf('translation') < 0) {
17092
- options.defaultNS = options.ns[0];
17093
- }
17094
- }
17095
- const defOpts = get();
17096
- this.options = {
17097
- ...defOpts,
17098
- ...this.options,
17099
- ...transformOptions(options)
17100
- };
17101
- if (this.options.compatibilityAPI !== 'v1') {
17102
- this.options.interpolation = {
17103
- ...defOpts.interpolation,
17104
- ...this.options.interpolation
17105
- };
17106
- }
17107
- if (options.keySeparator !== undefined) {
17108
- this.options.userDefinedKeySeparator = options.keySeparator;
17109
- }
17110
- if (options.nsSeparator !== undefined) {
17111
- this.options.userDefinedNsSeparator = options.nsSeparator;
17112
- }
17113
- const createClassOnDemand = ClassOrObject => {
17114
- if (!ClassOrObject) return null;
17115
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
17116
- return ClassOrObject;
17117
- };
17118
- if (!this.options.isClone) {
17119
- if (this.modules.logger) {
17120
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
17121
- } else {
17122
- baseLogger.init(null, this.options);
17123
- }
17124
- let formatter;
17125
- if (this.modules.formatter) {
17126
- formatter = this.modules.formatter;
17127
- } else if (typeof Intl !== 'undefined') {
17128
- formatter = Formatter;
17129
- }
17130
- const lu = new LanguageUtil(this.options);
17131
- this.store = new ResourceStore(this.options.resources, this.options);
17132
- const s = this.services;
17133
- s.logger = baseLogger;
17134
- s.resourceStore = this.store;
17135
- s.languageUtils = lu;
17136
- s.pluralResolver = new PluralResolver(lu, {
17137
- prepend: this.options.pluralSeparator,
17138
- compatibilityJSON: this.options.compatibilityJSON,
17139
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
17140
- });
17141
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
17142
- s.formatter = createClassOnDemand(formatter);
17143
- s.formatter.init(s, this.options);
17144
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
17145
- }
17146
- s.interpolator = new Interpolator(this.options);
17147
- s.utils = {
17148
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
17149
- };
17150
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
17151
- s.backendConnector.on('*', function (event) {
17152
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
17153
- args[_key - 1] = arguments[_key];
17154
- }
17155
- _this.emit(event, ...args);
17156
- });
17157
- if (this.modules.languageDetector) {
17158
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
17159
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
17160
- }
17161
- if (this.modules.i18nFormat) {
17162
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
17163
- if (s.i18nFormat.init) s.i18nFormat.init(this);
17164
- }
17165
- this.translator = new Translator(this.services, this.options);
17166
- this.translator.on('*', function (event) {
17167
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
17168
- args[_key2 - 1] = arguments[_key2];
17169
- }
17170
- _this.emit(event, ...args);
17171
- });
17172
- this.modules.external.forEach(m => {
17173
- if (m.init) m.init(this);
17174
- });
17175
- }
17176
- this.format = this.options.interpolation.format;
17177
- if (!callback) callback = noop;
17178
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
17179
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
17180
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
17181
- }
17182
- if (!this.services.languageDetector && !this.options.lng) {
17183
- this.logger.warn('init: no languageDetector is used and no lng is defined');
17184
- }
17185
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
17186
- storeApi.forEach(fcName => {
17187
- this[fcName] = function () {
17188
- return _this.store[fcName](...arguments);
17189
- };
17190
- });
17191
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
17192
- storeApiChained.forEach(fcName => {
17193
- this[fcName] = function () {
17194
- _this.store[fcName](...arguments);
17195
- return _this;
17196
- };
17197
- });
17198
- const deferred = defer();
17199
- const load = () => {
17200
- const finish = (err, t) => {
17201
- this.isInitializing = false;
17202
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
17203
- this.isInitialized = true;
17204
- if (!this.options.isClone) this.logger.log('initialized', this.options);
17205
- this.emit('initialized', this.options);
17206
- deferred.resolve(t);
17207
- callback(err, t);
17208
- };
17209
- if (this.languages && this.options.compatibilityAPI !== 'v1' && !this.isInitialized) return finish(null, this.t.bind(this));
17210
- this.changeLanguage(this.options.lng, finish);
17211
- };
17212
- if (this.options.resources || !this.options.initImmediate) {
17213
- load();
17214
- } else {
17215
- setTimeout(load, 0);
17216
- }
17217
- return deferred;
17218
- }
17219
- loadResources(language) {
17220
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
17221
- let usedCallback = callback;
17222
- const usedLng = isString(language) ? language : this.language;
17223
- if (typeof language === 'function') usedCallback = language;
17224
- if (!this.options.resources || this.options.partialBundledLanguages) {
17225
- if (usedLng && usedLng.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
17226
- const toLoad = [];
17227
- const append = lng => {
17228
- if (!lng) return;
17229
- if (lng === 'cimode') return;
17230
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
17231
- lngs.forEach(l => {
17232
- if (l === 'cimode') return;
17233
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
17234
- });
17235
- };
17236
- if (!usedLng) {
17237
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
17238
- fallbacks.forEach(l => append(l));
17239
- } else {
17240
- append(usedLng);
17241
- }
17242
- if (this.options.preload) {
17243
- this.options.preload.forEach(l => append(l));
17244
- }
17245
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
17246
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
17247
- usedCallback(e);
17248
- });
17249
- } else {
17250
- usedCallback(null);
17251
- }
17252
- }
17253
- reloadResources(lngs, ns, callback) {
17254
- const deferred = defer();
17255
- if (typeof lngs === 'function') {
17256
- callback = lngs;
17257
- lngs = undefined;
17258
- }
17259
- if (typeof ns === 'function') {
17260
- callback = ns;
17261
- ns = undefined;
17262
- }
17263
- if (!lngs) lngs = this.languages;
17264
- if (!ns) ns = this.options.ns;
17265
- if (!callback) callback = noop;
17266
- this.services.backendConnector.reload(lngs, ns, err => {
17267
- deferred.resolve();
17268
- callback(err);
17269
- });
17270
- return deferred;
17271
- }
17272
- use(module) {
17273
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
17274
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
17275
- if (module.type === 'backend') {
17276
- this.modules.backend = module;
17277
- }
17278
- if (module.type === 'logger' || module.log && module.warn && module.error) {
17279
- this.modules.logger = module;
17280
- }
17281
- if (module.type === 'languageDetector') {
17282
- this.modules.languageDetector = module;
17283
- }
17284
- if (module.type === 'i18nFormat') {
17285
- this.modules.i18nFormat = module;
17286
- }
17287
- if (module.type === 'postProcessor') {
17288
- postProcessor.addPostProcessor(module);
17289
- }
17290
- if (module.type === 'formatter') {
17291
- this.modules.formatter = module;
17292
- }
17293
- if (module.type === '3rdParty') {
17294
- this.modules.external.push(module);
17295
- }
17296
- return this;
17297
- }
17298
- setResolvedLanguage(l) {
17299
- if (!l || !this.languages) return;
17300
- if (['cimode', 'dev'].indexOf(l) > -1) return;
17301
- for (let li = 0; li < this.languages.length; li++) {
17302
- const lngInLngs = this.languages[li];
17303
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
17304
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
17305
- this.resolvedLanguage = lngInLngs;
17306
- break;
17307
- }
17308
- }
17309
- }
17310
- changeLanguage(lng, callback) {
17311
- var _this2 = this;
17312
- this.isLanguageChangingTo = lng;
17313
- const deferred = defer();
17314
- this.emit('languageChanging', lng);
17315
- const setLngProps = l => {
17316
- this.language = l;
17317
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
17318
- this.resolvedLanguage = undefined;
17319
- this.setResolvedLanguage(l);
17320
- };
17321
- const done = (err, l) => {
17322
- if (l) {
17323
- setLngProps(l);
17324
- this.translator.changeLanguage(l);
17325
- this.isLanguageChangingTo = undefined;
17326
- this.emit('languageChanged', l);
17327
- this.logger.log('languageChanged', l);
17328
- } else {
17329
- this.isLanguageChangingTo = undefined;
17330
- }
17331
- deferred.resolve(function () {
17332
- return _this2.t(...arguments);
17333
- });
17334
- if (callback) callback(err, function () {
17335
- return _this2.t(...arguments);
17336
- });
17337
- };
17338
- const setLng = lngs => {
17339
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
17340
- const l = isString(lngs) ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
17341
- if (l) {
17342
- if (!this.language) {
17343
- setLngProps(l);
17344
- }
17345
- if (!this.translator.language) this.translator.changeLanguage(l);
17346
- if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage) this.services.languageDetector.cacheUserLanguage(l);
17347
- }
17348
- this.loadResources(l, err => {
17349
- done(err, l);
17350
- });
17351
- };
17352
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
17353
- setLng(this.services.languageDetector.detect());
17354
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
17355
- if (this.services.languageDetector.detect.length === 0) {
17356
- this.services.languageDetector.detect().then(setLng);
17357
- } else {
17358
- this.services.languageDetector.detect(setLng);
17359
- }
17360
- } else {
17361
- setLng(lng);
17362
- }
17363
- return deferred;
17364
- }
17365
- getFixedT(lng, ns, keyPrefix) {
17366
- var _this3 = this;
17367
- const fixedT = function (key, opts) {
17368
- let options;
17369
- if (typeof opts !== 'object') {
17370
- for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
17371
- rest[_key3 - 2] = arguments[_key3];
17372
- }
17373
- options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
17374
- } else {
17375
- options = {
17376
- ...opts
17377
- };
17378
- }
17379
- options.lng = options.lng || fixedT.lng;
17380
- options.lngs = options.lngs || fixedT.lngs;
17381
- options.ns = options.ns || fixedT.ns;
17382
- if (options.keyPrefix !== '') options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
17383
- const keySeparator = _this3.options.keySeparator || '.';
17384
- let resultKey;
17385
- if (options.keyPrefix && Array.isArray(key)) {
17386
- resultKey = key.map(k => `${options.keyPrefix}${keySeparator}${k}`);
17387
- } else {
17388
- resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
17389
- }
17390
- return _this3.t(resultKey, options);
17391
- };
17392
- if (isString(lng)) {
17393
- fixedT.lng = lng;
17394
- } else {
17395
- fixedT.lngs = lng;
17396
- }
17397
- fixedT.ns = ns;
17398
- fixedT.keyPrefix = keyPrefix;
17399
- return fixedT;
17400
- }
17401
- t() {
17402
- return this.translator && this.translator.translate(...arguments);
17403
- }
17404
- exists() {
17405
- return this.translator && this.translator.exists(...arguments);
17406
- }
17407
- setDefaultNamespace(ns) {
17408
- this.options.defaultNS = ns;
17409
- }
17410
- hasLoadedNamespace(ns) {
17411
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
17412
- if (!this.isInitialized) {
17413
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
17414
- return false;
17415
- }
17416
- if (!this.languages || !this.languages.length) {
17417
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
17418
- return false;
17419
- }
17420
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
17421
- const fallbackLng = this.options ? this.options.fallbackLng : false;
17422
- const lastLng = this.languages[this.languages.length - 1];
17423
- if (lng.toLowerCase() === 'cimode') return true;
17424
- const loadNotPending = (l, n) => {
17425
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
17426
- return loadState === -1 || loadState === 0 || loadState === 2;
17427
- };
17428
- if (options.precheck) {
17429
- const preResult = options.precheck(this, loadNotPending);
17430
- if (preResult !== undefined) return preResult;
17431
- }
17432
- if (this.hasResourceBundle(lng, ns)) return true;
17433
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
17434
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
17435
- return false;
17436
- }
17437
- loadNamespaces(ns, callback) {
17438
- const deferred = defer();
17439
- if (!this.options.ns) {
17440
- if (callback) callback();
17441
- return Promise.resolve();
17442
- }
17443
- if (isString(ns)) ns = [ns];
17444
- ns.forEach(n => {
17445
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
17446
- });
17447
- this.loadResources(err => {
17448
- deferred.resolve();
17449
- if (callback) callback(err);
17450
- });
17451
- return deferred;
17452
- }
17453
- loadLanguages(lngs, callback) {
17454
- const deferred = defer();
17455
- if (isString(lngs)) lngs = [lngs];
17456
- const preloaded = this.options.preload || [];
17457
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
17458
- if (!newLngs.length) {
17459
- if (callback) callback();
17460
- return Promise.resolve();
17461
- }
17462
- this.options.preload = preloaded.concat(newLngs);
17463
- this.loadResources(err => {
17464
- deferred.resolve();
17465
- if (callback) callback(err);
17466
- });
17467
- return deferred;
17468
- }
17469
- dir(lng) {
17470
- if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
17471
- if (!lng) return 'rtl';
17472
- const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
17473
- const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
17474
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
17475
- }
17476
- static createInstance() {
17477
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
17478
- let callback = arguments.length > 1 ? arguments[1] : undefined;
17479
- return new I18n(options, callback);
17480
- }
17481
- cloneInstance() {
17482
- let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
17483
- let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
17484
- const forkResourceStore = options.forkResourceStore;
17485
- if (forkResourceStore) delete options.forkResourceStore;
17486
- const mergedOptions = {
17487
- ...this.options,
17488
- ...options,
17489
- ...{
17490
- isClone: true
17491
- }
17492
- };
17493
- const clone = new I18n(mergedOptions);
17494
- if (options.debug !== undefined || options.prefix !== undefined) {
17495
- clone.logger = clone.logger.clone(options);
17496
- }
17497
- const membersToCopy = ['store', 'services', 'language'];
17498
- membersToCopy.forEach(m => {
17499
- clone[m] = this[m];
17500
- });
17501
- clone.services = {
17502
- ...this.services
17503
- };
17504
- clone.services.utils = {
17505
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
17506
- };
17507
- if (forkResourceStore) {
17508
- clone.store = new ResourceStore(this.store.data, mergedOptions);
17509
- clone.services.resourceStore = clone.store;
17510
- }
17511
- clone.translator = new Translator(clone.services, mergedOptions);
17512
- clone.translator.on('*', function (event) {
17513
- for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
17514
- args[_key4 - 1] = arguments[_key4];
17515
- }
17516
- clone.emit(event, ...args);
17517
- });
17518
- clone.init(mergedOptions, callback);
17519
- clone.translator.options = mergedOptions;
17520
- clone.translator.backendConnector.services.utils = {
17521
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
17522
- };
17523
- return clone;
17524
- }
17525
- toJSON() {
17526
- return {
17527
- options: this.options,
17528
- store: this.store,
17529
- language: this.language,
17530
- languages: this.languages,
17531
- resolvedLanguage: this.resolvedLanguage
17532
- };
17533
- }
17534
- }
17535
- const instance = I18n.createInstance();
17536
- instance.createInstance = I18n.createInstance;
17537
-
17538
- instance.createInstance;
17539
- instance.dir;
17540
- instance.init;
17541
- instance.loadResources;
17542
- instance.reloadResources;
17543
- instance.use;
17544
- instance.changeLanguage;
17545
- instance.getFixedT;
17546
- instance.t;
17547
- instance.exists;
17548
- instance.setDefaultNamespace;
17549
- instance.hasLoadedNamespace;
17550
- instance.loadNamespaces;
17551
- instance.loadLanguages;
17552
-
17553
- const enTranslations = {
17554
- components: {
17555
- contactInfoPopup: {
17556
- businessSection: {
17557
- title: 'Business Information',
17558
- description: 'Details about the business',
17559
- },
17560
- contactMethod: {
17561
- email: 'Email',
17562
- phone: 'Phone',
17563
- website: 'Website',
17564
- },
17565
- labelsSection: {
17566
- title: 'Labels',
17567
- },
17568
- membersSection: {
17569
- title: 'Members',
17570
- noMembers: 'No members found',
17571
- },
17572
- global: {
17573
- properties: 'Properties',
17574
- business: 'Business',
17575
- businessMembers: 'Business Members',
17576
- labels: 'Labels',
17577
- },
17578
- },
17579
- textBox: {
17580
- placeholder: 'Enter text...',
17581
- },
17582
- },
17583
- };
17584
-
17585
- const esTranslations = {
17586
- components: {
17587
- contactInfoPopup: {
17588
- businessSection: {
17589
- title: 'Información del Negocio',
17590
- description: 'Detalles sobre el negocio',
17591
- },
17592
- contactMethod: {
17593
- email: 'Correo electrónico',
17594
- phone: 'Teléfono',
17595
- website: 'Sitio web',
17596
- },
17597
- labelsSection: {
17598
- title: 'Etiquetas',
17599
- },
17600
- membersSection: {
17601
- title: 'Miembros',
17602
- noMembers: 'No se encontraron miembros',
17603
- },
17604
- global: {
17605
- properties: 'Propiedades',
17606
- business: 'Empresa',
17607
- businessMembers: 'Miembros de la empresa',
17608
- labels: 'Etiquetas',
17609
- },
17610
- },
17611
- textBox: {
17612
- placeholder: 'Ingrese texto...',
17613
- },
17614
- },
17615
- };
17616
-
17617
- instance.use(initReactI18next).init({
17618
- resources: {
17619
- en: {
17620
- translation: enTranslations,
17621
- },
17622
- es: {
17623
- translation: esTranslations,
17624
- },
17625
- },
17626
- lng: 'en',
17627
- fallbackLng: 'en',
17628
- interpolation: {
17629
- escapeValue: false,
17630
- },
17631
- });
17632
-
17633
- const LanguageContext = createContext(undefined);
17634
- const LanguageProvider = ({ children, }) => {
17635
- const [language, setLanguage] = useState(instance.language);
17636
- const changeLanguage = (lang) => {
17637
- instance.changeLanguage(lang);
17638
- setLanguage(lang);
17639
- };
17640
- return (jsxRuntimeExports.jsx(LanguageContext.Provider, { value: { language, setLanguage: changeLanguage }, children: children }));
17641
- };
17642
- const useLanguage = () => {
17643
- const context = useContext(LanguageContext);
17644
- if (context === undefined) {
17645
- throw new Error('useLanguage must be used within a LanguageProvider');
17646
- }
17647
- return context;
17648
- };
17649
-
17650
- const LanguageSelector = () => {
17651
- const { language, setLanguage } = useLanguage();
17652
- return (jsxRuntimeExports.jsxs(FormControl, { fullWidth: true, children: [jsxRuntimeExports.jsx(InputLabel, { id: "language-select-label", children: "Language" }), jsxRuntimeExports.jsxs(Select, { labelId: "language-select-label", value: language, label: "Language", onChange: (e) => setLanguage(e.target.value), children: [jsxRuntimeExports.jsx(MenuItem, { value: "en", children: "English" }), jsxRuntimeExports.jsx(MenuItem, { value: "es", children: "Espa\u00F1ol" })] })] }));
17653
- };
17654
-
17655
- const useTriiTranslation = (namespace) => {
17656
- const { t, i18n } = useTranslation(namespace);
17657
- const translate = (key, options) => {
17658
- return t(key, options);
17659
- };
17660
- return {
17661
- t: translate,
17662
- i18n,
17663
- };
14900
+ return (jsxRuntimeExports.jsx(Popper, { sx: { zIndex: 1300 }, open: open, anchorEl: anchorEl, placement: "bottom-start", "data-popper-child": "true", children: jsxRuntimeExports.jsx(ClickAwayListener, { onClickAway: onClose, children: jsxRuntimeExports.jsx(PopupContainer, { children: jsxRuntimeExports.jsxs(CardContent, { children: [jsxRuntimeExports.jsx(Header, { navigate: navigate, contactId: contactData?.id, imgUrl: avatarImgUrl, name: contactData?.name }), jsxRuntimeExports.jsx(LabelsSection, { contactData: contactData, title: t('labels') }), dataIsContact && (jsxRuntimeExports.jsx(BusinessSection, { contactData: contactData, title: t('business') })), dataIsBusiness && (jsxRuntimeExports.jsx(MembersSection, { contactData: contactData, title: t('businessMembers') })), contactMethods.map((method, index) => (jsxRuntimeExports.jsx(ContactMethod, { icon: method.icon, title: method.title, contactList: method.contactList, showTitle: method.showTitle }, index))), jsxRuntimeExports.jsx(Properties, { properties: contactData?.properties, title: t('global.properties') })] }) }) }) }));
17664
14901
  };
17665
14902
 
17666
- export { ContactInfoPopup, LanguageProvider, LanguageSelector, TestBox, enTranslations, esTranslations, useLanguage, useTriiTranslation };
14903
+ export { ContactInfoPopup, TestBox };
17667
14904
  //# sourceMappingURL=index.js.map