UNPKG

30.1 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactI18next = {}, global.React));
5})(this, (function (exports, react) { 'use strict';
6
7 function getDefaultExportFromCjs (x) {
8 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9 }
10
11 var voidElements = {
12 "area": true,
13 "base": true,
14 "br": true,
15 "col": true,
16 "embed": true,
17 "hr": true,
18 "img": true,
19 "input": true,
20 "link": true,
21 "meta": true,
22 "param": true,
23 "source": true,
24 "track": true,
25 "wbr": true
26 };
27
28 var e = /*@__PURE__*/getDefaultExportFromCjs(voidElements);
29
30 var t = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
31 function n(n) {
32 var r = {
33 type: "tag",
34 name: "",
35 voidElement: !1,
36 attrs: {},
37 children: []
38 },
39 i = n.match(/<\/?([^\s]+?)[/\s>]/);
40 if (i && (r.name = i[1], (e[i[1]] || "/" === n.charAt(n.length - 2)) && (r.voidElement = !0), r.name.startsWith("!--"))) {
41 var s = n.indexOf("--\x3e");
42 return {
43 type: "comment",
44 comment: -1 !== s ? n.slice(4, s) : ""
45 };
46 }
47 for (var a = new RegExp(t), c = null; null !== (c = a.exec(n));) if (c[0].trim()) if (c[1]) {
48 var o = c[1].trim(),
49 l = [o, ""];
50 o.indexOf("=") > -1 && (l = o.split("=")), r.attrs[l[0]] = l[1], a.lastIndex--;
51 } else c[2] && (r.attrs[c[2]] = c[3].trim().substring(1, c[3].length - 1));
52 return r;
53 }
54 var r = /<[a-zA-Z0-9\-\!\/](?:"[^"]*"|'[^']*'|[^'">])*>/g,
55 i = /^\s*$/,
56 s = Object.create(null);
57 function a(e, t) {
58 switch (t.type) {
59 case "text":
60 return e + t.content;
61 case "tag":
62 return e += "<" + t.name + (t.attrs ? function (e) {
63 var t = [];
64 for (var n in e) t.push(n + '="' + e[n] + '"');
65 return t.length ? " " + t.join(" ") : "";
66 }(t.attrs) : "") + (t.voidElement ? "/>" : ">"), t.voidElement ? e : e + t.children.reduce(a, "") + "</" + t.name + ">";
67 case "comment":
68 return e + "\x3c!--" + t.comment + "--\x3e";
69 }
70 }
71 var c = {
72 parse: function (e, t) {
73 t || (t = {}), t.components || (t.components = s);
74 var a,
75 c = [],
76 o = [],
77 l = -1,
78 m = !1;
79 if (0 !== e.indexOf("<")) {
80 var u = e.indexOf("<");
81 c.push({
82 type: "text",
83 content: -1 === u ? e : e.substring(0, u)
84 });
85 }
86 return e.replace(r, function (r, s) {
87 if (m) {
88 if (r !== "</" + a.name + ">") return;
89 m = !1;
90 }
91 var u,
92 f = "/" !== r.charAt(1),
93 h = r.startsWith("\x3c!--"),
94 p = s + r.length,
95 d = e.charAt(p);
96 if (h) {
97 var v = n(r);
98 return l < 0 ? (c.push(v), c) : ((u = o[l]).children.push(v), c);
99 }
100 if (f && (l++, "tag" === (a = n(r)).type && t.components[a.name] && (a.type = "component", m = !0), a.voidElement || m || !d || "<" === d || a.children.push({
101 type: "text",
102 content: e.slice(p, e.indexOf("<", p))
103 }), 0 === l && c.push(a), (u = o[l - 1]) && u.children.push(a), o[l] = a), (!f || a.voidElement) && (l > -1 && (a.voidElement || a.name === r.slice(2, -1)) && (l--, a = -1 === l ? c : o[l]), !m && "<" !== d && d)) {
104 u = -1 === l ? c : o[l].children;
105 var x = e.indexOf("<", p),
106 g = e.slice(p, -1 === x ? void 0 : x);
107 i.test(g) && (g = " "), (x > -1 && l + u.length >= 0 || " " !== g) && u.push({
108 type: "text",
109 content: g
110 });
111 }
112 }), c;
113 },
114 stringify: function (e) {
115 return e.reduce(function (e, t) {
116 return e + a("", t);
117 }, "");
118 }
119 };
120
121 const warn = (i18n, code, msg, rest) => {
122 const args = [msg, {
123 code,
124 ...(rest || {})
125 }];
126 if (i18n?.services?.logger?.forward) {
127 return i18n.services.logger.forward(args, 'warn', 'react-i18next::', true);
128 }
129 if (isString(args[0])) args[0] = `react-i18next:: ${args[0]}`;
130 if (i18n?.services?.logger?.warn) {
131 i18n.services.logger.warn(...args);
132 } else if (console?.warn) {
133 console.warn(...args);
134 }
135 };
136 const alreadyWarned = {};
137 const warnOnce = (i18n, code, msg, rest) => {
138 if (isString(msg) && alreadyWarned[msg]) return;
139 if (isString(msg)) alreadyWarned[msg] = new Date();
140 warn(i18n, code, msg, rest);
141 };
142 const loadedClb = (i18n, cb) => () => {
143 if (i18n.isInitialized) {
144 cb();
145 } else {
146 const initialized = () => {
147 setTimeout(() => {
148 i18n.off('initialized', initialized);
149 }, 0);
150 cb();
151 };
152 i18n.on('initialized', initialized);
153 }
154 };
155 const loadNamespaces = (i18n, ns, cb) => {
156 i18n.loadNamespaces(ns, loadedClb(i18n, cb));
157 };
158 const loadLanguages = (i18n, lng, ns, cb) => {
159 if (isString(ns)) ns = [ns];
160 if (i18n.options.preload && i18n.options.preload.indexOf(lng) > -1) return loadNamespaces(i18n, ns, cb);
161 ns.forEach(n => {
162 if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
163 });
164 i18n.loadLanguages(lng, loadedClb(i18n, cb));
165 };
166 const hasLoadedNamespace = function (ns, i18n) {
167 let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
168 if (!i18n.languages || !i18n.languages.length) {
169 warnOnce(i18n, 'NO_LANGUAGES', 'i18n.languages were undefined or empty', {
170 languages: i18n.languages
171 });
172 return true;
173 }
174 return i18n.hasLoadedNamespace(ns, {
175 lng: options.lng,
176 precheck: (i18nInstance, loadNotPending) => {
177 if (options.bindI18n?.indexOf('languageChanging') > -1 && i18nInstance.services.backendConnector.backend && i18nInstance.isLanguageChangingTo && !loadNotPending(i18nInstance.isLanguageChangingTo, ns)) return false;
178 }
179 });
180 };
181 const getDisplayName = Component => Component.displayName || Component.name || (isString(Component) && Component.length > 0 ? Component : 'Unknown');
182 const isString = obj => typeof obj === 'string';
183 const isObject = obj => typeof obj === 'object' && obj !== null;
184
185 const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
186 const htmlEntities = {
187 '&amp;': '&',
188 '&#38;': '&',
189 '&lt;': '<',
190 '&#60;': '<',
191 '&gt;': '>',
192 '&#62;': '>',
193 '&apos;': "'",
194 '&#39;': "'",
195 '&quot;': '"',
196 '&#34;': '"',
197 '&nbsp;': ' ',
198 '&#160;': ' ',
199 '&copy;': '©',
200 '&#169;': '©',
201 '&reg;': '®',
202 '&#174;': '®',
203 '&hellip;': '…',
204 '&#8230;': '…',
205 '&#x2F;': '/',
206 '&#47;': '/'
207 };
208 const unescapeHtmlEntity = m => htmlEntities[m];
209 const unescape = text => text.replace(matchHtmlEntity, unescapeHtmlEntity);
210
211 let defaultOptions = {
212 bindI18n: 'languageChanged',
213 bindI18nStore: '',
214 transEmptyNodeValue: '',
215 transSupportBasicHtmlNodes: true,
216 transWrapTextNodes: '',
217 transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
218 useSuspense: true,
219 unescape
220 };
221 const setDefaults = function () {
222 let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
223 defaultOptions = {
224 ...defaultOptions,
225 ...options
226 };
227 };
228 const getDefaults = () => defaultOptions;
229
230 let i18nInstance;
231 const setI18n = instance => {
232 i18nInstance = instance;
233 };
234 const getI18n = () => i18nInstance;
235
236 const hasChildren = (node, checkLength) => {
237 if (!node) return false;
238 const base = node.props?.children ?? node.children;
239 if (checkLength) return base.length > 0;
240 return !!base;
241 };
242 const getChildren = node => {
243 if (!node) return [];
244 const children = node.props?.children ?? node.children;
245 return node.props?.i18nIsDynamicList ? getAsArray(children) : children;
246 };
247 const hasValidReactChildren = children => Array.isArray(children) && children.every(react.isValidElement);
248 const getAsArray = data => Array.isArray(data) ? data : [data];
249 const mergeProps = (source, target) => {
250 const newTarget = {
251 ...target
252 };
253 newTarget.props = Object.assign(source.props, target.props);
254 return newTarget;
255 };
256 const nodesToString = (children, i18nOptions, i18n, i18nKey) => {
257 if (!children) return '';
258 let stringNode = '';
259 const childrenArray = getAsArray(children);
260 const keepArray = i18nOptions?.transSupportBasicHtmlNodes ? i18nOptions.transKeepBasicHtmlNodesFor ?? [] : [];
261 childrenArray.forEach((child, childIndex) => {
262 if (isString(child)) {
263 stringNode += `${child}`;
264 return;
265 }
266 if (react.isValidElement(child)) {
267 const {
268 props,
269 type
270 } = child;
271 const childPropsCount = Object.keys(props).length;
272 const shouldKeepChild = keepArray.indexOf(type) > -1;
273 const childChildren = props.children;
274 if (!childChildren && shouldKeepChild && !childPropsCount) {
275 stringNode += `<${type}/>`;
276 return;
277 }
278 if (!childChildren && (!shouldKeepChild || childPropsCount) || props.i18nIsDynamicList) {
279 stringNode += `<${childIndex}></${childIndex}>`;
280 return;
281 }
282 if (shouldKeepChild && childPropsCount === 1 && isString(childChildren)) {
283 stringNode += `<${type}>${childChildren}</${type}>`;
284 return;
285 }
286 const content = nodesToString(childChildren, i18nOptions, i18n, i18nKey);
287 stringNode += `<${childIndex}>${content}</${childIndex}>`;
288 return;
289 }
290 if (child === null) {
291 warn(i18n, 'TRANS_NULL_VALUE', `Passed in a null value as child`, {
292 i18nKey
293 });
294 return;
295 }
296 if (isObject(child)) {
297 const {
298 format,
299 ...clone
300 } = child;
301 const keys = Object.keys(clone);
302 if (keys.length === 1) {
303 const value = format ? `${keys[0]}, ${format}` : keys[0];
304 stringNode += `{{${value}}}`;
305 return;
306 }
307 warn(i18n, 'TRANS_INVALID_OBJ', `Invalid child - Object should only have keys {{ value, format }} (format is optional).`, {
308 i18nKey,
309 child
310 });
311 return;
312 }
313 warn(i18n, 'TRANS_INVALID_VAR', `Passed in a variable like {number} - pass variables for interpolation as full objects like {{number}}.`, {
314 i18nKey,
315 child
316 });
317 });
318 return stringNode;
319 };
320 const renderNodes = (children, targetString, i18n, i18nOptions, combinedTOpts, shouldUnescape) => {
321 if (targetString === '') return [];
322 const keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
323 const emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.map(keep => `<${keep}`).join('|')).test(targetString);
324 if (!children && !emptyChildrenButNeedsHandling && !shouldUnescape) return [targetString];
325 const data = {};
326 const getData = childs => {
327 const childrenArray = getAsArray(childs);
328 childrenArray.forEach(child => {
329 if (isString(child)) return;
330 if (hasChildren(child)) getData(getChildren(child));else if (isObject(child) && !react.isValidElement(child)) Object.assign(data, child);
331 });
332 };
333 getData(children);
334 const ast = c.parse(`<0>${targetString}</0>`);
335 const opts = {
336 ...data,
337 ...combinedTOpts
338 };
339 const renderInner = (child, node, rootReactNode) => {
340 const childs = getChildren(child);
341 const mappedChildren = mapAST(childs, node.children, rootReactNode);
342 return hasValidReactChildren(childs) && mappedChildren.length === 0 || child.props?.i18nIsDynamicList ? childs : mappedChildren;
343 };
344 const pushTranslatedJSX = (child, inner, mem, i, isVoid) => {
345 if (child.dummy) {
346 child.children = inner;
347 mem.push(react.cloneElement(child, {
348 key: i
349 }, isVoid ? undefined : inner));
350 } else {
351 mem.push(...react.Children.map([child], c => {
352 const props = {
353 ...c.props
354 };
355 delete props.i18nIsDynamicList;
356 return react.createElement(c.type, {
357 ...props,
358 key: i,
359 ref: c.ref
360 }, isVoid ? null : inner);
361 }));
362 }
363 };
364 const mapAST = (reactNode, astNode, rootReactNode) => {
365 const reactNodes = getAsArray(reactNode);
366 const astNodes = getAsArray(astNode);
367 return astNodes.reduce((mem, node, i) => {
368 const translationContent = node.children?.[0]?.content && i18n.services.interpolator.interpolate(node.children[0].content, opts, i18n.language);
369 if (node.type === 'tag') {
370 let tmp = reactNodes[parseInt(node.name, 10)];
371 if (rootReactNode.length === 1 && !tmp) tmp = rootReactNode[0][node.name];
372 if (!tmp) tmp = {};
373 const child = Object.keys(node.attrs).length !== 0 ? mergeProps({
374 props: node.attrs
375 }, tmp) : tmp;
376 const isElement = react.isValidElement(child);
377 const isValidTranslationWithChildren = isElement && hasChildren(node, true) && !node.voidElement;
378 const isEmptyTransWithHTML = emptyChildrenButNeedsHandling && isObject(child) && child.dummy && !isElement;
379 const isKnownComponent = isObject(children) && Object.hasOwnProperty.call(children, node.name);
380 if (isString(child)) {
381 const value = i18n.services.interpolator.interpolate(child, opts, i18n.language);
382 mem.push(value);
383 } else if (hasChildren(child) || isValidTranslationWithChildren) {
384 const inner = renderInner(child, node, rootReactNode);
385 pushTranslatedJSX(child, inner, mem, i);
386 } else if (isEmptyTransWithHTML) {
387 const inner = mapAST(reactNodes, node.children, rootReactNode);
388 pushTranslatedJSX(child, inner, mem, i);
389 } else if (Number.isNaN(parseFloat(node.name))) {
390 if (isKnownComponent) {
391 const inner = renderInner(child, node, rootReactNode);
392 pushTranslatedJSX(child, inner, mem, i, node.voidElement);
393 } else if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
394 if (node.voidElement) {
395 mem.push(react.createElement(node.name, {
396 key: `${node.name}-${i}`
397 }));
398 } else {
399 const inner = mapAST(reactNodes, node.children, rootReactNode);
400 mem.push(react.createElement(node.name, {
401 key: `${node.name}-${i}`
402 }, inner));
403 }
404 } else if (node.voidElement) {
405 mem.push(`<${node.name} />`);
406 } else {
407 const inner = mapAST(reactNodes, node.children, rootReactNode);
408 mem.push(`<${node.name}>${inner}</${node.name}>`);
409 }
410 } else if (isObject(child) && !isElement) {
411 const content = node.children[0] ? translationContent : null;
412 if (content) mem.push(content);
413 } else {
414 pushTranslatedJSX(child, translationContent, mem, i, node.children.length !== 1 || !translationContent);
415 }
416 } else if (node.type === 'text') {
417 const wrapTextNodes = i18nOptions.transWrapTextNodes;
418 const content = shouldUnescape ? i18nOptions.unescape(i18n.services.interpolator.interpolate(node.content, opts, i18n.language)) : i18n.services.interpolator.interpolate(node.content, opts, i18n.language);
419 if (wrapTextNodes) {
420 mem.push(react.createElement(wrapTextNodes, {
421 key: `${node.name}-${i}`
422 }, content));
423 } else {
424 mem.push(content);
425 }
426 }
427 return mem;
428 }, []);
429 };
430 const result = mapAST([{
431 dummy: true,
432 children: children || []
433 }], ast, getAsArray(children || []));
434 return getChildren(result[0]);
435 };
436 const fixComponentProps = (component, index, translation) => {
437 const componentKey = component.key || index;
438 const comp = react.cloneElement(component, {
439 key: componentKey
440 });
441 if (!comp.props || !comp.props.children || translation.indexOf(`${index}/>`) < 0 && translation.indexOf(`${index} />`) < 0) {
442 return comp;
443 }
444 function Componentized() {
445 return react.createElement(react.Fragment, null, comp);
446 }
447 return react.createElement(Componentized);
448 };
449 const generateArrayComponents = (components, translation) => components.map((c, index) => fixComponentProps(c, index, translation));
450 const generateObjectComponents = (components, translation) => {
451 const componentMap = {};
452 Object.keys(components).forEach(c => {
453 Object.assign(componentMap, {
454 [c]: fixComponentProps(components[c], c, translation)
455 });
456 });
457 return componentMap;
458 };
459 const generateComponents = (components, translation, i18n, i18nKey) => {
460 if (!components) return null;
461 if (Array.isArray(components)) {
462 return generateArrayComponents(components, translation);
463 }
464 if (isObject(components)) {
465 return generateObjectComponents(components, translation);
466 }
467 warnOnce(i18n, 'TRANS_INVALID_COMPONENTS', `<Trans /> "components" prop expects an object or array`, {
468 i18nKey
469 });
470 return null;
471 };
472 function Trans$1(_ref) {
473 let {
474 children,
475 count,
476 parent,
477 i18nKey,
478 context,
479 tOptions = {},
480 values,
481 defaults,
482 components,
483 ns,
484 i18n: i18nFromProps,
485 t: tFromProps,
486 shouldUnescape,
487 ...additionalProps
488 } = _ref;
489 const i18n = i18nFromProps || getI18n();
490 if (!i18n) {
491 warnOnce(i18n, 'NO_I18NEXT_INSTANCE', `Trans: You need to pass in an i18next instance using i18nextReactModule`, {
492 i18nKey
493 });
494 return children;
495 }
496 const t = tFromProps || i18n.t.bind(i18n) || (k => k);
497 const reactI18nextOptions = {
498 ...getDefaults(),
499 ...i18n.options?.react
500 };
501 let namespaces = ns || t.ns || i18n.options?.defaultNS;
502 namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
503 const nodeAsString = nodesToString(children, reactI18nextOptions, i18n, i18nKey);
504 const defaultValue = defaults || nodeAsString || reactI18nextOptions.transEmptyNodeValue || i18nKey;
505 const {
506 hashTransKey
507 } = reactI18nextOptions;
508 const key = i18nKey || (hashTransKey ? hashTransKey(nodeAsString || defaultValue) : nodeAsString || defaultValue);
509 if (i18n.options?.interpolation?.defaultVariables) {
510 values = values && Object.keys(values).length > 0 ? {
511 ...values,
512 ...i18n.options.interpolation.defaultVariables
513 } : {
514 ...i18n.options.interpolation.defaultVariables
515 };
516 }
517 const interpolationOverride = values || count !== undefined && !i18n.options?.interpolation?.alwaysFormat || !children ? tOptions.interpolation : {
518 interpolation: {
519 ...tOptions.interpolation,
520 prefix: '#$?',
521 suffix: '?$#'
522 }
523 };
524 const combinedTOpts = {
525 ...tOptions,
526 context: context || tOptions.context,
527 count,
528 ...values,
529 ...interpolationOverride,
530 defaultValue,
531 ns: namespaces
532 };
533 const translation = key ? t(key, combinedTOpts) : defaultValue;
534 const generatedComponents = generateComponents(components, translation, i18n, i18nKey);
535 const content = renderNodes(generatedComponents || children, translation, i18n, reactI18nextOptions, combinedTOpts, shouldUnescape);
536 const useAsParent = parent ?? reactI18nextOptions.defaultTransParent;
537 return useAsParent ? react.createElement(useAsParent, additionalProps, content) : content;
538 }
539
540 const initReactI18next = {
541 type: '3rdParty',
542 init(instance) {
543 setDefaults(instance.options.react);
544 setI18n(instance);
545 }
546 };
547
548 const I18nContext = react.createContext();
549 class ReportNamespaces {
550 constructor() {
551 this.usedNamespaces = {};
552 }
553 addUsedNamespaces(namespaces) {
554 namespaces.forEach(ns => {
555 if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
556 });
557 }
558 getUsedNamespaces() {
559 return Object.keys(this.usedNamespaces);
560 }
561 }
562 const composeInitialProps = ForComponent => async ctx => {
563 const componentsInitialProps = (await ForComponent.getInitialProps?.(ctx)) ?? {};
564 const i18nInitialProps = getInitialProps();
565 return {
566 ...componentsInitialProps,
567 ...i18nInitialProps
568 };
569 };
570 const getInitialProps = () => {
571 const i18n = getI18n();
572 const namespaces = i18n.reportNamespaces?.getUsedNamespaces() ?? [];
573 const ret = {};
574 const initialI18nStore = {};
575 i18n.languages.forEach(l => {
576 initialI18nStore[l] = {};
577 namespaces.forEach(ns => {
578 initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};
579 });
580 });
581 ret.initialI18nStore = initialI18nStore;
582 ret.initialLanguage = i18n.language;
583 return ret;
584 };
585
586 function Trans(_ref) {
587 let {
588 children,
589 count,
590 parent,
591 i18nKey,
592 context,
593 tOptions = {},
594 values,
595 defaults,
596 components,
597 ns,
598 i18n: i18nFromProps,
599 t: tFromProps,
600 shouldUnescape,
601 ...additionalProps
602 } = _ref;
603 const {
604 i18n: i18nFromContext,
605 defaultNS: defaultNSFromContext
606 } = react.useContext(I18nContext) || {};
607 const i18n = i18nFromProps || i18nFromContext || getI18n();
608 const t = tFromProps || i18n?.t.bind(i18n);
609 return Trans$1({
610 children,
611 count,
612 parent,
613 i18nKey,
614 context,
615 tOptions,
616 values,
617 defaults,
618 components,
619 ns: ns || t?.ns || defaultNSFromContext || i18n?.options?.defaultNS,
620 i18n,
621 t: tFromProps,
622 shouldUnescape,
623 ...additionalProps
624 });
625 }
626
627 const usePrevious = (value, ignore) => {
628 const ref = react.useRef();
629 react.useEffect(() => {
630 ref.current = value;
631 }, [value, ignore]);
632 return ref.current;
633 };
634 const alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);
635 const useMemoizedT = (i18n, language, namespace, keyPrefix) => react.useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
636 const useTranslation = function (ns) {
637 let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
638 const {
639 i18n: i18nFromProps
640 } = props;
641 const {
642 i18n: i18nFromContext,
643 defaultNS: defaultNSFromContext
644 } = react.useContext(I18nContext) || {};
645 const i18n = i18nFromProps || i18nFromContext || getI18n();
646 if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
647 if (!i18n) {
648 warnOnce(i18n, 'NO_I18NEXT_INSTANCE', 'useTranslation: You will need to pass in an i18next instance by using initReactI18next');
649 const notReadyT = (k, optsOrDefaultValue) => {
650 if (isString(optsOrDefaultValue)) return optsOrDefaultValue;
651 if (isObject(optsOrDefaultValue) && isString(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
652 return Array.isArray(k) ? k[k.length - 1] : k;
653 };
654 const retNotReady = [notReadyT, {}, false];
655 retNotReady.t = notReadyT;
656 retNotReady.i18n = {};
657 retNotReady.ready = false;
658 return retNotReady;
659 }
660 if (i18n.options.react?.wait) warnOnce(i18n, 'DEPRECATED_OPTION', 'useTranslation: It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');
661 const i18nOptions = {
662 ...getDefaults(),
663 ...i18n.options.react,
664 ...props
665 };
666 const {
667 useSuspense,
668 keyPrefix
669 } = i18nOptions;
670 let namespaces = ns || defaultNSFromContext || i18n.options?.defaultNS;
671 namespaces = isString(namespaces) ? [namespaces] : namespaces || ['translation'];
672 i18n.reportNamespaces.addUsedNamespaces?.(namespaces);
673 const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
674 const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
675 const getT = () => memoGetT;
676 const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
677 const [t, setT] = react.useState(getT);
678 let joinedNS = namespaces.join();
679 if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
680 const previousJoinedNS = usePrevious(joinedNS);
681 const isMounted = react.useRef(true);
682 react.useEffect(() => {
683 const {
684 bindI18n,
685 bindI18nStore
686 } = i18nOptions;
687 isMounted.current = true;
688 if (!ready && !useSuspense) {
689 if (props.lng) {
690 loadLanguages(i18n, props.lng, namespaces, () => {
691 if (isMounted.current) setT(getNewT);
692 });
693 } else {
694 loadNamespaces(i18n, namespaces, () => {
695 if (isMounted.current) setT(getNewT);
696 });
697 }
698 }
699 if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
700 setT(getNewT);
701 }
702 const boundReset = () => {
703 if (isMounted.current) setT(getNewT);
704 };
705 if (bindI18n) i18n?.on(bindI18n, boundReset);
706 if (bindI18nStore) i18n?.store.on(bindI18nStore, boundReset);
707 return () => {
708 isMounted.current = false;
709 if (i18n) bindI18n?.split(' ').forEach(e => i18n.off(e, boundReset));
710 if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
711 };
712 }, [i18n, joinedNS]);
713 react.useEffect(() => {
714 if (isMounted.current && ready) {
715 setT(getT);
716 }
717 }, [i18n, keyPrefix, ready]);
718 const ret = [t, i18n, ready];
719 ret.t = t;
720 ret.i18n = i18n;
721 ret.ready = ready;
722 if (ready) return ret;
723 if (!ready && !useSuspense) return ret;
724 throw new Promise(resolve => {
725 if (props.lng) {
726 loadLanguages(i18n, props.lng, namespaces, () => resolve());
727 } else {
728 loadNamespaces(i18n, namespaces, () => resolve());
729 }
730 });
731 };
732
733 const withTranslation = function (ns) {
734 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
735 return function Extend(WrappedComponent) {
736 function I18nextWithTranslation(_ref) {
737 let {
738 forwardedRef,
739 ...rest
740 } = _ref;
741 const [t, i18n, ready] = useTranslation(ns, {
742 ...rest,
743 keyPrefix: options.keyPrefix
744 });
745 const passDownProps = {
746 ...rest,
747 t,
748 i18n,
749 tReady: ready
750 };
751 if (options.withRef && forwardedRef) {
752 passDownProps.ref = forwardedRef;
753 } else if (!options.withRef && forwardedRef) {
754 passDownProps.forwardedRef = forwardedRef;
755 }
756 return react.createElement(WrappedComponent, passDownProps);
757 }
758 I18nextWithTranslation.displayName = `withI18nextTranslation(${getDisplayName(WrappedComponent)})`;
759 I18nextWithTranslation.WrappedComponent = WrappedComponent;
760 const forwardRef = (props, ref) => react.createElement(I18nextWithTranslation, Object.assign({}, props, {
761 forwardedRef: ref
762 }));
763 return options.withRef ? react.forwardRef(forwardRef) : I18nextWithTranslation;
764 };
765 };
766
767 const Translation = _ref => {
768 let {
769 ns,
770 children,
771 ...options
772 } = _ref;
773 const [t, i18n, ready] = useTranslation(ns, options);
774 return children(t, {
775 i18n,
776 lng: i18n.language
777 }, ready);
778 };
779
780 function I18nextProvider(_ref) {
781 let {
782 i18n,
783 defaultNS,
784 children
785 } = _ref;
786 const value = react.useMemo(() => ({
787 i18n,
788 defaultNS
789 }), [i18n, defaultNS]);
790 return react.createElement(I18nContext.Provider, {
791 value
792 }, children);
793 }
794
795 const useSSR = function (initialI18nStore, initialLanguage) {
796 let props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
797 const {
798 i18n: i18nFromProps
799 } = props;
800 const {
801 i18n: i18nFromContext
802 } = react.useContext(I18nContext) || {};
803 const i18n = i18nFromProps || i18nFromContext || getI18n();
804 if (i18n.options?.isClone) return;
805 if (initialI18nStore && !i18n.initializedStoreOnce) {
806 i18n.services.resourceStore.data = initialI18nStore;
807 i18n.options.ns = Object.values(initialI18nStore).reduce((mem, lngResources) => {
808 Object.keys(lngResources).forEach(ns => {
809 if (mem.indexOf(ns) < 0) mem.push(ns);
810 });
811 return mem;
812 }, i18n.options.ns);
813 i18n.initializedStoreOnce = true;
814 i18n.isInitialized = true;
815 }
816 if (initialLanguage && !i18n.initializedLanguageOnce) {
817 i18n.changeLanguage(initialLanguage);
818 i18n.initializedLanguageOnce = true;
819 }
820 };
821
822 const withSSR = () => function Extend(WrappedComponent) {
823 function I18nextWithSSR(_ref) {
824 let {
825 initialI18nStore,
826 initialLanguage,
827 ...rest
828 } = _ref;
829 useSSR(initialI18nStore, initialLanguage);
830 return react.createElement(WrappedComponent, {
831 ...rest
832 });
833 }
834 I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
835 I18nextWithSSR.displayName = `withI18nextSSR(${getDisplayName(WrappedComponent)})`;
836 I18nextWithSSR.WrappedComponent = WrappedComponent;
837 return I18nextWithSSR;
838 };
839
840 const date = () => '';
841 const time = () => '';
842 const number = () => '';
843 const select = () => '';
844 const plural = () => '';
845 const selectOrdinal = () => '';
846
847 exports.I18nContext = I18nContext;
848 exports.I18nextProvider = I18nextProvider;
849 exports.Trans = Trans;
850 exports.TransWithoutContext = Trans$1;
851 exports.Translation = Translation;
852 exports.composeInitialProps = composeInitialProps;
853 exports.date = date;
854 exports.getDefaults = getDefaults;
855 exports.getI18n = getI18n;
856 exports.getInitialProps = getInitialProps;
857 exports.initReactI18next = initReactI18next;
858 exports.number = number;
859 exports.plural = plural;
860 exports.select = select;
861 exports.selectOrdinal = selectOrdinal;
862 exports.setDefaults = setDefaults;
863 exports.setI18n = setI18n;
864 exports.time = time;
865 exports.useSSR = useSSR;
866 exports.useTranslation = useTranslation;
867 exports.withSSR = withSSR;
868 exports.withTranslation = withTranslation;
869
870}));