diff --git a/react-i18next.js b/react-i18next.js index f3c46d205..213a32f05 100644 --- a/react-i18next.js +++ b/react-i18next.js @@ -118,24 +118,24 @@ } }; - function warn() { - if (console && console.warn) { + const warn = function () { + if (console?.warn) { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`; console.warn(...args); } - } + }; const alreadyWarned = {}; - function warnOnce() { + const warnOnce = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (isString(args[0]) && alreadyWarned[args[0]]) return; if (isString(args[0])) alreadyWarned[args[0]] = new Date(); warn(...args); - } + }; const loadedClb = (i18n, cb) => () => { if (i18n.isInitialized) { cb(); @@ -162,14 +162,14 @@ const oldI18nextHasLoadedNamespace = function (ns, i18n) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const lng = i18n.languages[0]; - const fallbackLng = i18n.options ? i18n.options.fallbackLng : false; + const fallbackLng = i18n.options?.fallbackLng ?? false; const lastLng = i18n.languages[i18n.languages.length - 1]; if (lng.toLowerCase() === 'cimode') return true; const loadNotPending = (l, n) => { const loadState = i18n.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 2; }; - if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false; + if (options.bindI18n?.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false; if (i18n.hasResourceBundle(lng, ns)) return true; if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true; if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; @@ -188,7 +188,7 @@ return i18n.hasLoadedNamespace(ns, { lng: options.lng, precheck: (i18nInstance, loadNotPending) => { - if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false; + if (options.bindI18n?.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false; } }); }; @@ -249,14 +249,14 @@ const hasChildren = (node, checkLength) => { if (!node) return false; - const base = node.props ? node.props.children : node.children; + const base = node.props?.children ?? node.children; if (checkLength) return base.length > 0; return !!base; }; const getChildren = node => { if (!node) return []; - const children = node.props ? node.props.children : node.children; - return node.props && node.props.i18nIsDynamicList ? getAsArray(children) : children; + const children = node.props?.children ?? node.children; + return node.props?.i18nIsDynamicList ? getAsArray(children) : children; }; const hasValidReactChildren = children => Array.isArray(children) && children.every(react.isValidElement); const getAsArray = data => Array.isArray(data) ? data : [data]; @@ -271,7 +271,7 @@ if (!children) return ''; let stringNode = ''; const childrenArray = getAsArray(children); - const keepArray = i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor ? i18nOptions.transKeepBasicHtmlNodesFor : []; + const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : []; childrenArray.forEach((child, childIndex) => { if (isString(child)) { stringNode += `${child}`; @@ -335,7 +335,7 @@ const renderInner = (child, node, rootReactNode) => { const childs = getChildren(child); const mappedChildren = mapAST(childs, node.children, rootReactNode); - return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props && child.props.i18nIsDynamicList ? childs : mappedChildren; + return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren; }; const pushTranslatedJSX = (child, inner, mem, i, isVoid) => { if (child.dummy) { @@ -361,7 +361,7 @@ const reactNodes = getAsArray(reactNode); const astNodes = getAsArray(astNode); return astNodes.reduce((mem, node, i) => { - const translationContent = node.children && node.children[0] && node.children[0].content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language); + const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language); if (node.type === 'tag') { let tmp = reactNodes[parseInt(node.name, 10)]; if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name]; @@ -454,9 +454,9 @@ const t = tFromProps || i18n.t.bind(i18n) || (k => k); const reactI18nextOptions = { ...getDefaults(), - ...(i18n.options && i18n.options.react) + ...i18n.options?.react }; - let namespaces = ns || t.ns || i18n.options && i18n.options.defaultNS; + let namespaces = ns || t.ns || i18n.options?.defaultNS; namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation']; const nodeAsString = nodesToString(children, reactI18nextOptions); const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey; @@ -464,7 +464,7 @@ hashTransKey } = reactI18nextOptions; const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue); - if (i18n.options && i18n.options.interpolation && i18n.options.interpolation.defaultVariables) { + if (i18n.options?.interpolation?.defaultVariables) { values = values && Object.keys(values).length > 0 ? { ...values, ...i18n.options.interpolation.defaultVariables @@ -500,7 +500,7 @@ }); } const content = renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape); - const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; + const useAsParent = parent ?? reactI18nextOptions.defaultTransParent; return useAsParent ? react.createElement(useAsParent, additionalProps, content) : content; } @@ -519,13 +519,13 @@ } addUsedNamespaces(namespaces) { namespaces.forEach(ns => { - if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; + this.usedNamespaces[ns] ??= true; }); } getUsedNamespaces = () => Object.keys(this.usedNamespaces); } const composeInitialProps = ForComponent => async ctx => { - const componentsInitialProps = ForComponent.getInitialProps ? await ForComponent.getInitialProps(ctx) : {}; + const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {}; const i18nInitialProps = getInitialProps(); return { ...componentsInitialProps, @@ -534,7 +534,7 @@ }; const getInitialProps = () => { const i18n = getI18n(); - const namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : []; + const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? []; const ret = {}; const initialI18nStore = {}; i18n.languages.forEach(l => { @@ -570,7 +570,7 @@ defaultNS: defaultNSFromContext } = react.useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); - const t = tFromProps || i18n && i18n.t.bind(i18n); + const t = tFromProps || i18n?.t.bind(i18n); return Trans$1({ children, count, @@ -581,7 +581,7 @@ values, defaults, components, - ns: ns || t && t.ns || defaultNSFromContext || i18n && i18n.options && i18n.options.defaultNS, + ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS, i18n, t: tFromProps, shouldUnescape, @@ -592,7 +592,7 @@ const usePrevious = (value, ignore) => { const ref = react.useRef(); react.useEffect(() => { - ref.current = ignore ? ref.current : value; + ref.current = value; }, [value, ignore]); return ref.current; }; @@ -622,7 +622,7 @@ retNotReady.ready = false; return retNotReady; } - 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.'); + if (i18n.options.react?.wait) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.'); const i18nOptions = { ...getDefaults(), ...i18n.options.react, @@ -632,9 +632,9 @@ useSuspense, keyPrefix } = i18nOptions; - let namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS; + let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS; namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation']; - if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces); + i18n.reportNamespaces.addUsedNamespaces?.(namespaces); const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions)); const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix); const getT = () => memoGetT; @@ -667,11 +667,11 @@ const boundReset = () => { if (isMounted.current) setT(getNewT); }; - if (bindI18n && i18n) i18n.on(bindI18n, boundReset); - if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset); + if (bindI18n) i18n?.on(bindI18n, boundReset); + if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset); return () => { isMounted.current = false; - if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset)); + if (i18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset)); if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset)); }; }, [i18n, joinedNS]); @@ -729,18 +729,18 @@ }; }; - function Translation(props) { - const { + const Translation = _ref => { + let { ns, children, ...options - } = props; + } = _ref; const [t, i18n, ready] = useTranslation(ns, options); return children(t, { i18n, lng: i18n.language }, ready); - } + }; function I18nextProvider(_ref) { let { @@ -766,7 +766,7 @@ i18n: i18nFromContext } = react.useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); - if (i18n.options && i18n.options.isClone) return; + if (i18n.options?.isClone) return; if (initialI18nStore && !i18n.initializedStoreOnce) { i18n.services.resourceStore.data = initialI18nStore; i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => { diff --git a/react-i18next.min.js b/react-i18next.min.js index 03a7699de..aeecb57a0 100644 --- a/react-i18next.min.js +++ b/react-i18next.min.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).ReactI18next={},e.React)}(this,(function(e,n){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s=t({area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),i=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function a(e){var n={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},t=e.match(/<\/?([^\s]+?)[/\s>]/);if(t&&(n.name=t[1],(s[t[1]]||"/"===e.charAt(e.length-2))&&(n.voidElement=!0),n.name.startsWith("!--"))){var a=e.indexOf("--\x3e");return{type:"comment",comment:-1!==a?e.slice(4,a):""}}for(var o=new RegExp(i),r=null;null!==(r=o.exec(e));)if(r[0].trim())if(r[1]){var l=r[1].trim(),c=[l,""];l.indexOf("=")>-1&&(c=l.split("=")),n.attrs[c[0]]=c[1],o.lastIndex--}else r[2]&&(n.attrs[r[2]]=r[3].trim().substring(1,r[3].length-1));return n}var o=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,r=/^\s*$/,l=Object.create(null);var c=function(e,n){n||(n={}),n.components||(n.components=l);var t,s=[],i=[],c=-1,u=!1;if(0!==e.indexOf("<")){var p=e.indexOf("<");s.push({type:"text",content:-1===p?e:e.substring(0,p)})}return e.replace(o,(function(o,l){if(u){if(o!=="")return;u=!1}var p,d="/"!==o.charAt(1),f=o.startsWith("\x3c!--"),g=l+o.length,h=e.charAt(g);if(f){var m=a(o);return c<0?(s.push(m),s):((p=i[c]).children.push(m),s)}if(d&&(c++,"tag"===(t=a(o)).type&&n.components[t.name]&&(t.type="component",u=!0),t.voidElement||u||!h||"<"===h||t.children.push({type:"text",content:e.slice(g,e.indexOf("<",g))}),0===c&&s.push(t),(p=i[c-1])&&p.children.push(t),i[c]=t),(!d||t.voidElement)&&(c>-1&&(t.voidElement||t.name===o.slice(2,-1))&&(c--,t=-1===c?s:i[c]),!u&&"<"!==h&&h)){p=-1===c?s:i[c].children;var y=e.indexOf("<",g),b=e.slice(g,-1===y?void 0:y);r.test(b)&&(b=" "),(y>-1&&c+p.length>=0||" "!==b)&&p.push({type:"text",content:b})}})),s};function u(){if(console&&console.warn){for(var e=arguments.length,n=new Array(e),t=0;t()=>{if(e.isInitialized)n();else{const t=()=>{setTimeout((()=>{e.off("initialized",t)}),0),n()};e.on("initialized",t)}},g=(e,n,t)=>{e.loadNamespaces(n,f(e,t))},h=(e,n,t,s)=>{y(t)&&(t=[t]),t.forEach((n=>{e.options.ns.indexOf(n)<0&&e.options.ns.push(n)})),e.loadLanguages(n,f(e,s))},m=e=>e.displayName||e.name||(y(e)&&e.length>0?e:"Unknown"),y=e=>"string"==typeof e,b=e=>"object"==typeof e&&null!==e,v=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,x={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},E=e=>x[e];let N={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(v,E)};const O=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};N={...N,...e}},$=()=>N;let k;const w=e=>{k=e},I=()=>k,S=(e,n)=>{if(!e)return!1;const t=e.props?e.props.children:e.children;return n?t.length>0:!!t},C=e=>{if(!e)return[];const n=e.props?e.props.children:e.children;return e.props&&e.props.i18nIsDynamicList?R(n):n},R=e=>Array.isArray(e)?e:[e],j=(e,t)=>{if(!e)return"";let s="";const i=R(e),a=t.transSupportBasicHtmlNodes&&t.transKeepBasicHtmlNodesFor?t.transKeepBasicHtmlNodesFor:[];return i.forEach(((e,i)=>{if(y(e))s+=`${e}`;else if(n.isValidElement(e)){const{props:n,type:o}=e,r=Object.keys(n).length,l=a.indexOf(o)>-1,c=n.children;if(c||!l||r)if(!c&&(!l||r)||n.i18nIsDynamicList)s+=`<${i}>`;else if(l&&1===r&&y(c))s+=`<${o}>${c}`;else{const e=j(c,t);s+=`<${i}>${e}`}else s+=`<${o}/>`}else if(null===e)u("Trans: the passed in value is invalid - seems you passed in a null child.");else if(b(e)){const{format:n,...t}=e,i=Object.keys(t);if(1===i.length){const e=n?`${i[0]}, ${n}`:i[0];s+=`{{${e}}}`}else u("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.",e)}else u("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.",e)})),s},T=(e,t,s,i,a,o)=>{if(""===t)return[];const r=i.transKeepBasicHtmlNodesFor||[],l=t&&new RegExp(r.map((e=>`<${e}`)).join("|")).test(t);if(!e&&!l&&!o)return[t];const u={},p=e=>{R(e).forEach((e=>{y(e)||(S(e)?p(C(e)):b(e)&&!n.isValidElement(e)&&Object.assign(u,e))}))};p(e);const d=c(`<0>${t}`),f={...u,...a},g=(e,t,s)=>{const i=C(e),a=m(i,t.children,s);return(e=>Array.isArray(e)&&e.every(n.isValidElement))(i)&&0===a.length||e.props&&e.props.i18nIsDynamicList?i:a},h=(e,t,s,i,a)=>{e.dummy?(e.children=t,s.push(n.cloneElement(e,{key:i},a?void 0:t))):s.push(...n.Children.map([e],(e=>{const s={...e.props};return delete s.i18nIsDynamicList,n.createElement(e.type,{...s,key:i,ref:e.ref},a?null:t)})))},m=(t,a,c)=>{const u=R(t);return R(a).reduce(((t,a,p)=>{const d=a.children&&a.children[0]&&a.children[0].content&&s.services.interpolator.interpolate(a.children[0].content,f,s.language);if("tag"===a.type){let o=u[parseInt(a.name,10)];1!==c.length||o||(o=c[0][a.name]),o||(o={});const v=0!==Object.keys(a.attrs).length?((e,n)=>{const t={...n};return t.props=Object.assign(e.props,n.props),t})({props:a.attrs},o):o,x=n.isValidElement(v),E=x&&S(a,!0)&&!a.voidElement,N=l&&b(v)&&v.dummy&&!x,O=b(e)&&Object.hasOwnProperty.call(e,a.name);if(y(v)){const e=s.services.interpolator.interpolate(v,f,s.language);t.push(e)}else if(S(v)||E){const e=g(v,a,c);h(v,e,t,p)}else if(N){const e=m(u,a.children,c);h(v,e,t,p)}else if(Number.isNaN(parseFloat(a.name)))if(O){const e=g(v,a,c);h(v,e,t,p,a.voidElement)}else if(i.transSupportBasicHtmlNodes&&r.indexOf(a.name)>-1)if(a.voidElement)t.push(n.createElement(a.name,{key:`${a.name}-${p}`}));else{const e=m(u,a.children,c);t.push(n.createElement(a.name,{key:`${a.name}-${p}`},e))}else if(a.voidElement)t.push(`<${a.name} />`);else{const e=m(u,a.children,c);t.push(`<${a.name}>${e}`)}else if(b(v)&&!x){const e=a.children[0]?d:null;e&&t.push(e)}else h(v,d,t,p,1!==a.children.length||!d)}else if("text"===a.type){const e=i.transWrapTextNodes,r=o?i.unescape(s.services.interpolator.interpolate(a.content,f,s.language)):s.services.interpolator.interpolate(a.content,f,s.language);e?t.push(n.createElement(e,{key:`${a.name}-${p}`},r)):t.push(r)}return t}),[])},v=m([{dummy:!0,children:e||[]}],d,R(e||[]));return C(v[0])};function L(e){let{children:t,count:s,parent:i,i18nKey:a,context:o,tOptions:r={},values:l,defaults:c,components:u,ns:p,i18n:f,t:g,shouldUnescape:h,...m}=e;const b=f||I();if(!b)return d("You will need to pass in an i18next instance by using i18nextReactModule"),t;const v=g||b.t.bind(b)||(e=>e),x={...$(),...b.options&&b.options.react};let E=p||v.ns||b.options&&b.options.defaultNS;E=y(E)?[E]:E||["translation"];const N=j(t,x),O=c||N||x.transEmptyNodeValue||a,{hashTransKey:k}=x,w=a||(k?k(N||O):N||O);b.options&&b.options.interpolation&&b.options.interpolation.defaultVariables&&(l=l&&Object.keys(l).length>0?{...l,...b.options.interpolation.defaultVariables}:{...b.options.interpolation.defaultVariables});const S=l||void 0!==s||!t?r.interpolation:{interpolation:{...r.interpolation,prefix:"#$?",suffix:"?$#"}},C={...r,context:o||r.context,count:s,...l,...S,defaultValue:O,ns:E},R=w?v(w,C):O;u&&Object.keys(u).forEach((e=>{const t=u[e];"function"==typeof t.type||!t.props||!t.props.children||R.indexOf(`${e}/>`)<0&&R.indexOf(`${e} />`)<0||(u[e]=n.createElement((function(){return n.createElement(n.Fragment,null,t)})))}));const L=T(u||t,R,b,x,C,h),P=void 0!==i?i:x.defaultTransParent;return P?n.createElement(P,m,L):L}const P={type:"3rdParty",init(e){O(e.options.react),w(e)}},A=n.createContext();class V{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach((e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)}))}getUsedNamespaces=()=>Object.keys(this.usedNamespaces)}const z=e=>async n=>({...e.getInitialProps?await e.getInitialProps(n):{},...B()}),B=()=>{const e=I(),n=e.reportNamespaces?e.reportNamespaces.getUsedNamespaces():[],t={},s={};return e.languages.forEach((t=>{s[t]={},n.forEach((n=>{s[t][n]=e.getResourceBundle(t,n)||{}}))})),t.initialI18nStore=s,t.initialLanguage=e.language,t};const F=(e,n,t,s)=>e.getFixedT(n,t,s),U=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{i18n:s}=t,{i18n:i,defaultNS:a}=n.useContext(A)||{},o=s||i||I();if(o&&!o.reportNamespaces&&(o.reportNamespaces=new V),!o){d("You will need to pass in an i18next instance by using initReactI18next");const e=(e,n)=>y(n)?n:b(n)&&y(n.defaultValue)?n.defaultValue:Array.isArray(e)?e[e.length-1]:e,n=[e,{},!1];return n.t=e,n.i18n={},n.ready=!1,n}o.options.react&&void 0!==o.options.react.wait&&d("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const r={...$(),...o.options.react,...t},{useSuspense:l,keyPrefix:c}=r;let u=e||a||o.options&&o.options.defaultNS;u=y(u)?[u]:u||["translation"],o.reportNamespaces.addUsedNamespaces&&o.reportNamespaces.addUsedNamespaces(u);const p=(o.isInitialized||o.initializedStoreOnce)&&u.every((e=>function(e,n){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.languages&&n.languages.length?void 0!==n.options.ignoreJSONStructure?n.hasLoadedNamespace(e,{lng:t.lng,precheck:(n,s)=>{if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!s(n.isLanguageChangingTo,e))return!1}}):function(e,n){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s=n.languages[0],i=!!n.options&&n.options.fallbackLng,a=n.languages[n.languages.length-1];if("cimode"===s.toLowerCase())return!0;const o=(e,t)=>{const s=n.services.backendConnector.state[`${e}|${t}`];return-1===s||2===s};return!(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,e)||!n.hasResourceBundle(s,e)&&n.services.backendConnector.backend&&(!n.options.resources||n.options.partialBundledLanguages)&&(!o(s,e)||i&&!o(a,e)))}(e,n,t):(d("i18n.languages were undefined or empty",n.languages),!0)}(e,o,r))),f=((e,t,s,i)=>n.useCallback(F(e,t,s,i),[e,t,s,i]))(o,t.lng||null,"fallback"===r.nsMode?u:u[0],c),m=()=>f,v=()=>F(o,t.lng||null,"fallback"===r.nsMode?u:u[0],c),[x,E]=n.useState(m);let N=u.join();t.lng&&(N=`${t.lng}${N}`);const O=((e,t)=>{const s=n.useRef();return n.useEffect((()=>{s.current=t?s.current:e}),[e,t]),s.current})(N),k=n.useRef(!0);n.useEffect((()=>{const{bindI18n:e,bindI18nStore:n}=r;k.current=!0,p||l||(t.lng?h(o,t.lng,u,(()=>{k.current&&E(v)})):g(o,u,(()=>{k.current&&E(v)}))),p&&O&&O!==N&&k.current&&E(v);const s=()=>{k.current&&E(v)};return e&&o&&o.on(e,s),n&&o&&o.store.on(n,s),()=>{k.current=!1,e&&o&&e.split(" ").forEach((e=>o.off(e,s))),n&&o&&n.split(" ").forEach((e=>o.store.off(e,s)))}}),[o,N]),n.useEffect((()=>{k.current&&p&&E(m)}),[o,c,p]);const w=[x,o,p];if(w.t=x,w.i18n=o,w.ready=p,p)return w;if(!p&&!l)return w;throw new Promise((e=>{t.lng?h(o,t.lng,u,(()=>e())):g(o,u,(()=>e()))}))};const K=function(e,t){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{i18n:i}=s,{i18n:a}=n.useContext(A)||{},o=i||a||I();o.options&&o.options.isClone||(e&&!o.initializedStoreOnce&&(o.services.resourceStore.data=e,o.options.ns=Object.values(e).reduce(((e,n)=>(Object.keys(n).forEach((n=>{e.indexOf(n)<0&&e.push(n)})),e)),o.options.ns),o.initializedStoreOnce=!0,o.isInitialized=!0),t&&!o.initializedLanguageOnce&&(o.changeLanguage(t),o.initializedLanguageOnce=!0))};e.I18nContext=A,e.I18nextProvider=function(e){let{i18n:t,defaultNS:s,children:i}=e;const a=n.useMemo((()=>({i18n:t,defaultNS:s})),[t,s]);return n.createElement(A.Provider,{value:a},i)},e.Trans=function(e){let{children:t,count:s,parent:i,i18nKey:a,context:o,tOptions:r={},values:l,defaults:c,components:u,ns:p,i18n:d,t:f,shouldUnescape:g,...h}=e;const{i18n:m,defaultNS:y}=n.useContext(A)||{},b=d||m||I(),v=f||b&&b.t.bind(b);return L({children:t,count:s,parent:i,i18nKey:a,context:o,tOptions:r,values:l,defaults:c,components:u,ns:p||v&&v.ns||y||b&&b.options&&b.options.defaultNS,i18n:b,t:f,shouldUnescape:g,...h})},e.TransWithoutContext=L,e.Translation=function(e){const{ns:n,children:t,...s}=e,[i,a,o]=U(n,s);return t(i,{i18n:a,lng:a.language},o)},e.composeInitialProps=z,e.date=()=>"",e.getDefaults=$,e.getI18n=I,e.getInitialProps=B,e.initReactI18next=P,e.number=()=>"",e.plural=()=>"",e.select=()=>"",e.selectOrdinal=()=>"",e.setDefaults=O,e.setI18n=w,e.time=()=>"",e.useSSR=K,e.useTranslation=U,e.withSSR=()=>function(e){function t(t){let{initialI18nStore:s,initialLanguage:i,...a}=t;return K(s,i),n.createElement(e,{...a})}return t.getInitialProps=z(e),t.displayName=`withI18nextSSR(${m(e)})`,t.WrappedComponent=e,t},e.withTranslation=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(s){function i(i){let{forwardedRef:a,...o}=i;const[r,l,c]=U(e,{...o,keyPrefix:t.keyPrefix}),u={...o,t:r,i18n:l,tReady:c};return t.withRef&&a?u.ref=a:!t.withRef&&a&&(u.forwardedRef=a),n.createElement(s,u)}i.displayName=`withI18nextTranslation(${m(s)})`,i.WrappedComponent=s;return t.withRef?n.forwardRef(((e,t)=>n.createElement(i,Object.assign({},e,{forwardedRef:t})))):i}}})); +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).ReactI18next={},e.React)}(this,(function(e,n){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s=t({area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),a=/\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;function i(e){var n={type:"tag",name:"",voidElement:!1,attrs:{},children:[]},t=e.match(/<\/?([^\s]+?)[/\s>]/);if(t&&(n.name=t[1],(s[t[1]]||"/"===e.charAt(e.length-2))&&(n.voidElement=!0),n.name.startsWith("!--"))){var i=e.indexOf("--\x3e");return{type:"comment",comment:-1!==i?e.slice(4,i):""}}for(var r=new RegExp(a),o=null;null!==(o=r.exec(e));)if(o[0].trim())if(o[1]){var l=o[1].trim(),c=[l,""];l.indexOf("=")>-1&&(c=l.split("=")),n.attrs[c[0]]=c[1],r.lastIndex--}else o[2]&&(n.attrs[o[2]]=o[3].trim().substring(1,o[3].length-1));return n}var r=/<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,o=/^\s*$/,l=Object.create(null);var c=function(e,n){n||(n={}),n.components||(n.components=l);var t,s=[],a=[],c=-1,u=!1;if(0!==e.indexOf("<")){var p=e.indexOf("<");s.push({type:"text",content:-1===p?e:e.substring(0,p)})}return e.replace(r,(function(r,l){if(u){if(r!=="")return;u=!1}var p,d="/"!==r.charAt(1),f=r.startsWith("\x3c!--"),g=l+r.length,h=e.charAt(g);if(f){var m=i(r);return c<0?(s.push(m),s):((p=a[c]).children.push(m),s)}if(d&&(c++,"tag"===(t=i(r)).type&&n.components[t.name]&&(t.type="component",u=!0),t.voidElement||u||!h||"<"===h||t.children.push({type:"text",content:e.slice(g,e.indexOf("<",g))}),0===c&&s.push(t),(p=a[c-1])&&p.children.push(t),a[c]=t),(!d||t.voidElement)&&(c>-1&&(t.voidElement||t.name===r.slice(2,-1))&&(c--,t=-1===c?s:a[c]),!u&&"<"!==h&&h)){p=-1===c?s:a[c].children;var y=e.indexOf("<",g),b=e.slice(g,-1===y?void 0:y);o.test(b)&&(b=" "),(y>-1&&c+p.length>=0||" "!==b)&&p.push({type:"text",content:b})}})),s};const u=function(){if(console?.warn){for(var e=arguments.length,n=new Array(e),t=0;t()=>{if(e.isInitialized)n();else{const t=()=>{setTimeout((()=>{e.off("initialized",t)}),0),n()};e.on("initialized",t)}},g=(e,n,t)=>{e.loadNamespaces(n,f(e,t))},h=(e,n,t,s)=>{y(t)&&(t=[t]),t.forEach((n=>{e.options.ns.indexOf(n)<0&&e.options.ns.push(n)})),e.loadLanguages(n,f(e,s))},m=e=>e.displayName||e.name||(y(e)&&e.length>0?e:"Unknown"),y=e=>"string"==typeof e,b=e=>"object"==typeof e&&null!==e,v=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,x={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},E=e=>x[e];let O={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(v,E)};const N=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};O={...O,...e}},$=()=>O;let k;const w=e=>{k=e},I=()=>k,S=(e,n)=>{if(!e)return!1;const t=e.props?.children??e.children;return n?t.length>0:!!t},C=e=>{if(!e)return[];const n=e.props?.children??e.children;return e.props?.i18nIsDynamicList?R(n):n},R=e=>Array.isArray(e)?e:[e],j=(e,t)=>{if(!e)return"";let s="";const a=R(e),i=t?.transSupportBasicHtmlNodes?t.transKeepBasicHtmlNodesFor??[]:[];return a.forEach(((e,a)=>{if(y(e))s+=`${e}`;else if(n.isValidElement(e)){const{props:n,type:r}=e,o=Object.keys(n).length,l=i.indexOf(r)>-1,c=n.children;if(c||!l||o)if(!c&&(!l||o)||n.i18nIsDynamicList)s+=`<${a}>`;else if(l&&1===o&&y(c))s+=`<${r}>${c}`;else{const e=j(c,t);s+=`<${a}>${e}`}else s+=`<${r}/>`}else if(null===e)u("Trans: the passed in value is invalid - seems you passed in a null child.");else if(b(e)){const{format:n,...t}=e,a=Object.keys(t);if(1===a.length){const e=n?`${a[0]}, ${n}`:a[0];s+=`{{${e}}}`}else u("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.",e)}else u("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.",e)})),s},T=(e,t,s,a,i,r)=>{if(""===t)return[];const o=a.transKeepBasicHtmlNodesFor||[],l=t&&new RegExp(o.map((e=>`<${e}`)).join("|")).test(t);if(!e&&!l&&!r)return[t];const u={},p=e=>{R(e).forEach((e=>{y(e)||(S(e)?p(C(e)):b(e)&&!n.isValidElement(e)&&Object.assign(u,e))}))};p(e);const d=c(`<0>${t}`),f={...u,...i},g=(e,t,s)=>{const a=C(e),i=m(a,t.children,s);return(e=>Array.isArray(e)&&e.every(n.isValidElement))(a)&&0===i.length||e.props?.i18nIsDynamicList?a:i},h=(e,t,s,a,i)=>{e.dummy?(e.children=t,s.push(n.cloneElement(e,{key:a},i?void 0:t))):s.push(...n.Children.map([e],(e=>{const s={...e.props};return delete s.i18nIsDynamicList,n.createElement(e.type,{...s,key:a,ref:e.ref},i?null:t)})))},m=(t,i,c)=>{const u=R(t);return R(i).reduce(((t,i,p)=>{const d=i.children?.[0]?.content&&s.services.interpolator.interpolate(i.children[0].content,f,s.language);if("tag"===i.type){let r=u[parseInt(i.name,10)];1!==c.length||r||(r=c[0][i.name]),r||(r={});const v=0!==Object.keys(i.attrs).length?((e,n)=>{const t={...n};return t.props=Object.assign(e.props,n.props),t})({props:i.attrs},r):r,x=n.isValidElement(v),E=x&&S(i,!0)&&!i.voidElement,O=l&&b(v)&&v.dummy&&!x,N=b(e)&&Object.hasOwnProperty.call(e,i.name);if(y(v)){const e=s.services.interpolator.interpolate(v,f,s.language);t.push(e)}else if(S(v)||E){const e=g(v,i,c);h(v,e,t,p)}else if(O){const e=m(u,i.children,c);h(v,e,t,p)}else if(Number.isNaN(parseFloat(i.name)))if(N){const e=g(v,i,c);h(v,e,t,p,i.voidElement)}else if(a.transSupportBasicHtmlNodes&&o.indexOf(i.name)>-1)if(i.voidElement)t.push(n.createElement(i.name,{key:`${i.name}-${p}`}));else{const e=m(u,i.children,c);t.push(n.createElement(i.name,{key:`${i.name}-${p}`},e))}else if(i.voidElement)t.push(`<${i.name} />`);else{const e=m(u,i.children,c);t.push(`<${i.name}>${e}`)}else if(b(v)&&!x){const e=i.children[0]?d:null;e&&t.push(e)}else h(v,d,t,p,1!==i.children.length||!d)}else if("text"===i.type){const e=a.transWrapTextNodes,o=r?a.unescape(s.services.interpolator.interpolate(i.content,f,s.language)):s.services.interpolator.interpolate(i.content,f,s.language);e?t.push(n.createElement(e,{key:`${i.name}-${p}`},o)):t.push(o)}return t}),[])},v=m([{dummy:!0,children:e||[]}],d,R(e||[]));return C(v[0])};function L(e){let{children:t,count:s,parent:a,i18nKey:i,context:r,tOptions:o={},values:l,defaults:c,components:u,ns:p,i18n:f,t:g,shouldUnescape:h,...m}=e;const b=f||I();if(!b)return d("You will need to pass in an i18next instance by using i18nextReactModule"),t;const v=g||b.t.bind(b)||(e=>e),x={...$(),...b.options?.react};let E=p||v.ns||b.options?.defaultNS;E=y(E)?[E]:E||["translation"];const O=j(t,x),N=c||O||x.transEmptyNodeValue||i,{hashTransKey:k}=x,w=i||(k?k(O||N):O||N);b.options?.interpolation?.defaultVariables&&(l=l&&Object.keys(l).length>0?{...l,...b.options.interpolation.defaultVariables}:{...b.options.interpolation.defaultVariables});const S=l||void 0!==s||!t?o.interpolation:{interpolation:{...o.interpolation,prefix:"#$?",suffix:"?$#"}},C={...o,context:r||o.context,count:s,...l,...S,defaultValue:N,ns:E},R=w?v(w,C):N;u&&Object.keys(u).forEach((e=>{const t=u[e];"function"==typeof t.type||!t.props||!t.props.children||R.indexOf(`${e}/>`)<0&&R.indexOf(`${e} />`)<0||(u[e]=n.createElement((function(){return n.createElement(n.Fragment,null,t)})))}));const L=T(u||t,R,b,x,C,h),P=a??x.defaultTransParent;return P?n.createElement(P,m,L):L}const P={type:"3rdParty",init(e){N(e.options.react),w(e)}},A=n.createContext();class V{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach((e=>{this.usedNamespaces[e]??=!0}))}getUsedNamespaces=()=>Object.keys(this.usedNamespaces)}const z=e=>async n=>({...await(e.getInitialProps?.(n))??{},...B()}),B=()=>{const e=I(),n=e.reportNamespaces?.getUsedNamespaces()??[],t={},s={};return e.languages.forEach((t=>{s[t]={},n.forEach((n=>{s[t][n]=e.getResourceBundle(t,n)||{}}))})),t.initialI18nStore=s,t.initialLanguage=e.language,t};const F=(e,n,t,s)=>e.getFixedT(n,t,s),U=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{i18n:s}=t,{i18n:a,defaultNS:i}=n.useContext(A)||{},r=s||a||I();if(r&&!r.reportNamespaces&&(r.reportNamespaces=new V),!r){d("You will need to pass in an i18next instance by using initReactI18next");const e=(e,n)=>y(n)?n:b(n)&&y(n.defaultValue)?n.defaultValue:Array.isArray(e)?e[e.length-1]:e,n=[e,{},!1];return n.t=e,n.i18n={},n.ready=!1,n}r.options.react?.wait&&d("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const o={...$(),...r.options.react,...t},{useSuspense:l,keyPrefix:c}=o;let u=e||i||r.options?.defaultNS;u=y(u)?[u]:u||["translation"],r.reportNamespaces.addUsedNamespaces?.(u);const p=(r.isInitialized||r.initializedStoreOnce)&&u.every((e=>function(e,n){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.languages&&n.languages.length?void 0!==n.options.ignoreJSONStructure?n.hasLoadedNamespace(e,{lng:t.lng,precheck:(n,s)=>{if(t.bindI18n?.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!s(n.isLanguageChangingTo,e))return!1}}):function(e,n){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s=n.languages[0],a=n.options?.fallbackLng??!1,i=n.languages[n.languages.length-1];if("cimode"===s.toLowerCase())return!0;const r=(e,t)=>{const s=n.services.backendConnector.state[`${e}|${t}`];return-1===s||2===s};return!(t.bindI18n?.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,e)||!n.hasResourceBundle(s,e)&&n.services.backendConnector.backend&&(!n.options.resources||n.options.partialBundledLanguages)&&(!r(s,e)||a&&!r(i,e)))}(e,n,t):(d("i18n.languages were undefined or empty",n.languages),!0)}(e,r,o))),f=((e,t,s,a)=>n.useCallback(F(e,t,s,a),[e,t,s,a]))(r,t.lng||null,"fallback"===o.nsMode?u:u[0],c),m=()=>f,v=()=>F(r,t.lng||null,"fallback"===o.nsMode?u:u[0],c),[x,E]=n.useState(m);let O=u.join();t.lng&&(O=`${t.lng}${O}`);const N=((e,t)=>{const s=n.useRef();return n.useEffect((()=>{s.current=e}),[e,t]),s.current})(O),k=n.useRef(!0);n.useEffect((()=>{const{bindI18n:e,bindI18nStore:n}=o;k.current=!0,p||l||(t.lng?h(r,t.lng,u,(()=>{k.current&&E(v)})):g(r,u,(()=>{k.current&&E(v)}))),p&&N&&N!==O&&k.current&&E(v);const s=()=>{k.current&&E(v)};return e&&r?.on(e,s),n&&r?.store.on(n,s),()=>{k.current=!1,r&&e?.split(" ").forEach((e=>r.off(e,s))),n&&r&&n.split(" ").forEach((e=>r.store.off(e,s)))}}),[r,O]),n.useEffect((()=>{k.current&&p&&E(m)}),[r,c,p]);const w=[x,r,p];if(w.t=x,w.i18n=r,w.ready=p,p)return w;if(!p&&!l)return w;throw new Promise((e=>{t.lng?h(r,t.lng,u,(()=>e())):g(r,u,(()=>e()))}))};const D=function(e,t){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{i18n:a}=s,{i18n:i}=n.useContext(A)||{},r=a||i||I();r.options?.isClone||(e&&!r.initializedStoreOnce&&(r.services.resourceStore.data=e,r.options.ns=Object.values(e).reduce(((e,n)=>(Object.keys(n).forEach((n=>{e.indexOf(n)<0&&e.push(n)})),e)),r.options.ns),r.initializedStoreOnce=!0,r.isInitialized=!0),t&&!r.initializedLanguageOnce&&(r.changeLanguage(t),r.initializedLanguageOnce=!0))};e.I18nContext=A,e.I18nextProvider=function(e){let{i18n:t,defaultNS:s,children:a}=e;const i=n.useMemo((()=>({i18n:t,defaultNS:s})),[t,s]);return n.createElement(A.Provider,{value:i},a)},e.Trans=function(e){let{children:t,count:s,parent:a,i18nKey:i,context:r,tOptions:o={},values:l,defaults:c,components:u,ns:p,i18n:d,t:f,shouldUnescape:g,...h}=e;const{i18n:m,defaultNS:y}=n.useContext(A)||{},b=d||m||I(),v=f||b?.t.bind(b);return L({children:t,count:s,parent:a,i18nKey:i,context:r,tOptions:o,values:l,defaults:c,components:u,ns:p||v?.ns||y||b?.options?.defaultNS,i18n:b,t:f,shouldUnescape:g,...h})},e.TransWithoutContext=L,e.Translation=e=>{let{ns:n,children:t,...s}=e;const[a,i,r]=U(n,s);return t(a,{i18n:i,lng:i.language},r)},e.composeInitialProps=z,e.date=()=>"",e.getDefaults=$,e.getI18n=I,e.getInitialProps=B,e.initReactI18next=P,e.number=()=>"",e.plural=()=>"",e.select=()=>"",e.selectOrdinal=()=>"",e.setDefaults=N,e.setI18n=w,e.time=()=>"",e.useSSR=D,e.useTranslation=U,e.withSSR=()=>function(e){function t(t){let{initialI18nStore:s,initialLanguage:a,...i}=t;return D(s,a),n.createElement(e,{...i})}return t.getInitialProps=z(e),t.displayName=`withI18nextSSR(${m(e)})`,t.WrappedComponent=e,t},e.withTranslation=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(s){function a(a){let{forwardedRef:i,...r}=a;const[o,l,c]=U(e,{...r,keyPrefix:t.keyPrefix}),u={...r,t:o,i18n:l,tReady:c};return t.withRef&&i?u.ref=i:!t.withRef&&i&&(u.forwardedRef=i),n.createElement(s,u)}a.displayName=`withI18nextTranslation(${m(s)})`,a.WrappedComponent=s;return t.withRef?n.forwardRef(((e,t)=>n.createElement(a,Object.assign({},e,{forwardedRef:t})))):a}}})); diff --git a/src/Trans.js b/src/Trans.js index b14cfd599..7f10ebe81 100644 --- a/src/Trans.js +++ b/src/Trans.js @@ -23,7 +23,7 @@ export function Trans({ const { i18n: i18nFromContext, defaultNS: defaultNSFromContext } = useContext(I18nContext) || {}; const i18n = i18nFromProps || i18nFromContext || getI18n(); - const t = tFromProps || (i18n && i18n.t.bind(i18n)); + const t = tFromProps || i18n?.t.bind(i18n); return TransWithoutContext({ children, @@ -36,8 +36,7 @@ export function Trans({ defaults, components, // prepare having a namespace - ns: - ns || (t && t.ns) || defaultNSFromContext || (i18n && i18n.options && i18n.options.defaultNS), + ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS, i18n, t: tFromProps, shouldUnescape, diff --git a/src/TransWithoutContext.js b/src/TransWithoutContext.js index a2858aeba..c10b57443 100644 --- a/src/TransWithoutContext.js +++ b/src/TransWithoutContext.js @@ -6,15 +6,15 @@ import { getI18n } from './i18nInstance.js'; const hasChildren = (node, checkLength) => { if (!node) return false; - const base = node.props ? node.props.children : node.children; + const base = node.props?.children ?? node.children; if (checkLength) return base.length > 0; return !!base; }; const getChildren = (node) => { if (!node) return []; - const children = node.props ? node.props.children : node.children; - return node.props && node.props.i18nIsDynamicList ? getAsArray(children) : children; + const children = node.props?.children ?? node.children; + return node.props?.i18nIsDynamicList ? getAsArray(children) : children; }; const hasValidReactChildren = (children) => @@ -35,10 +35,9 @@ export const nodesToString = (children, i18nOptions) => { // do not use `React.Children.toArray`, will fail at object children const childrenArray = getAsArray(children); - const keepArray = - i18nOptions.transSupportBasicHtmlNodes && i18nOptions.transKeepBasicHtmlNodesFor - ? i18nOptions.transKeepBasicHtmlNodesFor - : []; + const keepArray = i18nOptions?.transSupportBasicHtmlNodes + ? (i18nOptions.transKeepBasicHtmlNodesFor ?? []) + : []; // e.g. lorem
ipsum {{ messageCount, format }} dolor bold amet childrenArray.forEach((child, childIndex) => { @@ -141,7 +140,7 @@ const renderNodes = (children, targetString, i18n, i18nOptions, combinedTOpts, s // `mappedChildren` will always be empty if using the `i18nIsDynamicList` prop, // but the children might not necessarily be react components return (hasValidReactChildren(childs) && mappedChildren.length === 0) || - (child.props && child.props.i18nIsDynamicList) + child.props?.i18nIsDynamicList ? childs : mappedChildren; }; @@ -179,9 +178,7 @@ const renderNodes = (children, targetString, i18n, i18nOptions, combinedTOpts, s return astNodes.reduce((mem, node, i) => { const translationContent = - node.children && - node.children[0] && - node.children[0].content && + node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language); if (node.type === 'tag') { @@ -326,10 +323,10 @@ export function Trans({ const t = tFromProps || i18n.t.bind(i18n) || ((k) => k); - const reactI18nextOptions = { ...getDefaults(), ...(i18n.options && i18n.options.react) }; + const reactI18nextOptions = { ...getDefaults(), ...i18n.options?.react }; // prepare having a namespace - let namespaces = ns || t.ns || (i18n.options && i18n.options.defaultNS); + let namespaces = ns || t.ns || i18n.options?.defaultNS; namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation']; const nodeAsString = nodesToString(children, reactI18nextOptions); @@ -339,7 +336,7 @@ export function Trans({ const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue); - if (i18n.options && i18n.options.interpolation && i18n.options.interpolation.defaultVariables) { + if (i18n.options?.interpolation?.defaultVariables) { // eslint-disable-next-line no-param-reassign values = values && Object.keys(values).length > 0 @@ -393,7 +390,7 @@ export function Trans({ // allows user to pass `null` to `parent` // and override `defaultTransParent` if is present - const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; + const useAsParent = parent ?? reactI18nextOptions.defaultTransParent; return useAsParent ? createElement(useAsParent, additionalProps, content) : content; } diff --git a/src/context.js b/src/context.js index 3b00a459f..8434992e0 100644 --- a/src/context.js +++ b/src/context.js @@ -14,7 +14,7 @@ export class ReportNamespaces { addUsedNamespaces(namespaces) { namespaces.forEach((ns) => { - if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; + this.usedNamespaces[ns] ??= true; }); } @@ -22,9 +22,7 @@ export class ReportNamespaces { } export const composeInitialProps = (ForComponent) => async (ctx) => { - const componentsInitialProps = ForComponent.getInitialProps - ? await ForComponent.getInitialProps(ctx) - : {}; + const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {}; const i18nInitialProps = getInitialProps(); @@ -36,7 +34,7 @@ export const composeInitialProps = (ForComponent) => async (ctx) => { export const getInitialProps = () => { const i18n = getI18n(); - const namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : []; + const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? []; const ret = {}; const initialI18nStore = {}; diff --git a/src/useSSR.js b/src/useSSR.js index b3da6f82f..a1d44a83e 100644 --- a/src/useSSR.js +++ b/src/useSSR.js @@ -8,7 +8,7 @@ export const useSSR = (initialI18nStore, initialLanguage, props = {}) => { // opt out if is a cloned instance, eg. created by i18next-http-middleware on request // -> do not set initial stuff on server side - if (i18n.options && i18n.options.isClone) return; + if (i18n.options?.isClone) return; // nextjs / SSR: getting data from next.js or other ssr stack if (initialI18nStore && !i18n.initializedStoreOnce) { diff --git a/src/useTranslation.js b/src/useTranslation.js index e28581dd3..7b9b4426d 100644 --- a/src/useTranslation.js +++ b/src/useTranslation.js @@ -49,7 +49,7 @@ export const useTranslation = (ns, props = {}) => { return retNotReady; } - if (i18n.options.react && i18n.options.react.wait !== undefined) + if (i18n.options.react?.wait) warnOnce( 'It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.', ); @@ -58,11 +58,11 @@ export const useTranslation = (ns, props = {}) => { const { useSuspense, keyPrefix } = i18nOptions; // prepare having a namespace - let namespaces = ns || defaultNSFromContext || (i18n.options && i18n.options.defaultNS); + let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS; namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation']; // report namespaces as used - if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces); + i18n.reportNamespaces.addUsedNamespaces?.(namespaces); // are we ready? yes if all namespaces in first language are loaded already (either with data or empty object on failed load) const ready = @@ -120,13 +120,13 @@ export const useTranslation = (ns, props = {}) => { }; // bind events to trigger change, like languageChanged - if (bindI18n && i18n) i18n.on(bindI18n, boundReset); - if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset); + if (bindI18n) i18n?.on(bindI18n, boundReset); + if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset); // unbinding on unmount return () => { isMounted.current = false; - if (bindI18n && i18n) bindI18n.split(' ').forEach((e) => i18n.off(e, boundReset)); + if (i18n) bindI18n?.split(' ').forEach((e) => i18n.off(e, boundReset)); if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach((e) => i18n.store.off(e, boundReset)); }; diff --git a/src/utils.js b/src/utils.js index 8c10aa5e5..26b3155bc 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,5 +1,5 @@ export const warn = (...args) => { - if (console && console.warn) { + if (console?.warn) { if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`; console.warn(...args); } @@ -54,7 +54,7 @@ export const loadLanguages = (i18n, lng, ns, cb) => { // WAIT A LITTLE FOR I18NEXT BEING UPDATED IN THE WILD, before removing this old i18next version support const oldI18nextHasLoadedNamespace = (ns, i18n, options = {}) => { const lng = i18n.languages[0]; - const fallbackLng = i18n.options ? i18n.options.fallbackLng : false; + const fallbackLng = i18n.options?.fallbackLng ?? false; const lastLng = i18n.languages[i18n.languages.length - 1]; // we're in cimode so this shall pass @@ -69,8 +69,7 @@ const oldI18nextHasLoadedNamespace = (ns, i18n, options = {}) => { // so set ready to false while we are changing the language // and namespace pending (depends on having a backend) if ( - options.bindI18n && - options.bindI18n.indexOf('languageChanging') > -1 && + options.bindI18n?.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns) @@ -111,8 +110,7 @@ export const hasLoadedNamespace = (ns, i18n, options = {}) => { lng: options.lng, precheck: (i18nInstance, loadNotPending) => { if ( - options.bindI18n && - options.bindI18n.indexOf('languageChanging') > -1 && + options.bindI18n?.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)