You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

959 lines
31 KiB

  1. define(['exports', 'react'], function (exports, React) { 'use strict';
  2. var React__default = 'default' in React ? React['default'] : React;
  3. function _defineProperty(obj, key, value) {
  4. if (key in obj) {
  5. Object.defineProperty(obj, key, {
  6. value: value,
  7. enumerable: true,
  8. configurable: true,
  9. writable: true
  10. });
  11. } else {
  12. obj[key] = value;
  13. }
  14. return obj;
  15. }
  16. function _extends() {
  17. _extends = Object.assign || function (target) {
  18. for (var i = 1; i < arguments.length; i++) {
  19. var source = arguments[i];
  20. for (var key in source) {
  21. if (Object.prototype.hasOwnProperty.call(source, key)) {
  22. target[key] = source[key];
  23. }
  24. }
  25. }
  26. return target;
  27. };
  28. return _extends.apply(this, arguments);
  29. }
  30. function ownKeys(object, enumerableOnly) {
  31. var keys = Object.keys(object);
  32. if (Object.getOwnPropertySymbols) {
  33. var symbols = Object.getOwnPropertySymbols(object);
  34. if (enumerableOnly) symbols = symbols.filter(function (sym) {
  35. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  36. });
  37. keys.push.apply(keys, symbols);
  38. }
  39. return keys;
  40. }
  41. function _objectSpread2(target) {
  42. for (var i = 1; i < arguments.length; i++) {
  43. var source = arguments[i] != null ? arguments[i] : {};
  44. if (i % 2) {
  45. ownKeys(source, true).forEach(function (key) {
  46. _defineProperty(target, key, source[key]);
  47. });
  48. } else if (Object.getOwnPropertyDescriptors) {
  49. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  50. } else {
  51. ownKeys(source).forEach(function (key) {
  52. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  53. });
  54. }
  55. }
  56. return target;
  57. }
  58. function _objectWithoutPropertiesLoose(source, excluded) {
  59. if (source == null) return {};
  60. var target = {};
  61. var sourceKeys = Object.keys(source);
  62. var key, i;
  63. for (i = 0; i < sourceKeys.length; i++) {
  64. key = sourceKeys[i];
  65. if (excluded.indexOf(key) >= 0) continue;
  66. target[key] = source[key];
  67. }
  68. return target;
  69. }
  70. function _objectWithoutProperties(source, excluded) {
  71. if (source == null) return {};
  72. var target = _objectWithoutPropertiesLoose(source, excluded);
  73. var key, i;
  74. if (Object.getOwnPropertySymbols) {
  75. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  76. for (i = 0; i < sourceSymbolKeys.length; i++) {
  77. key = sourceSymbolKeys[i];
  78. if (excluded.indexOf(key) >= 0) continue;
  79. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  80. target[key] = source[key];
  81. }
  82. }
  83. return target;
  84. }
  85. /**
  86. * This file automatically generated from `pre-publish.js`.
  87. * Do not manually edit.
  88. */
  89. var voidElements = {
  90. "area": true,
  91. "base": true,
  92. "br": true,
  93. "col": true,
  94. "embed": true,
  95. "hr": true,
  96. "img": true,
  97. "input": true,
  98. "keygen": true,
  99. "link": true,
  100. "menuitem": true,
  101. "meta": true,
  102. "param": true,
  103. "source": true,
  104. "track": true,
  105. "wbr": true
  106. };
  107. var attrRE = /([\w-]+)|=|(['"])([.\s\S]*?)\2/g;
  108. var parseTag = function (tag) {
  109. var i = 0;
  110. var key;
  111. var expectingValueAfterEquals = true;
  112. var res = {
  113. type: 'tag',
  114. name: '',
  115. voidElement: false,
  116. attrs: {},
  117. children: []
  118. };
  119. tag.replace(attrRE, function (match) {
  120. if (match === '=') {
  121. expectingValueAfterEquals = true;
  122. i++;
  123. return;
  124. }
  125. if (!expectingValueAfterEquals) {
  126. if (key) {
  127. res.attrs[key] = key; // boolean attribute
  128. }
  129. key = match;
  130. } else {
  131. if (i === 0) {
  132. if (voidElements[match] || tag.charAt(tag.length - 2) === '/') {
  133. res.voidElement = true;
  134. }
  135. res.name = match;
  136. } else {
  137. res.attrs[key] = match.replace(/^['"]|['"]$/g, '');
  138. key = undefined;
  139. }
  140. }
  141. i++;
  142. expectingValueAfterEquals = false;
  143. });
  144. return res;
  145. };
  146. /*jshint -W030 */
  147. var tagRE = /(?:<!--[\S\s]*?-->|<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>)/g;
  148. // re-used obj for quick lookups of components
  149. var empty = Object.create ? Object.create(null) : {}; // common logic for pushing a child node onto a list
  150. function pushTextNode(list, html, level, start, ignoreWhitespace) {
  151. // calculate correct end of the content slice in case there's
  152. // no tag after the text node.
  153. var end = html.indexOf('<', start);
  154. var content = html.slice(start, end === -1 ? undefined : end); // if a node is nothing but whitespace, collapse it as the spec states:
  155. // https://www.w3.org/TR/html4/struct/text.html#h-9.1
  156. if (/^\s*$/.test(content)) {
  157. content = ' ';
  158. } // don't add whitespace-only text nodes if they would be trailing text nodes
  159. // or if they would be leading whitespace-only text nodes:
  160. // * end > -1 indicates this is not a trailing text node
  161. // * leading node is when level is -1 and list has length 0
  162. if (!ignoreWhitespace && end > -1 && level + list.length >= 0 || content !== ' ') {
  163. list.push({
  164. type: 'text',
  165. content: content
  166. });
  167. }
  168. }
  169. var parse = function parse(html, options) {
  170. options || (options = {});
  171. options.components || (options.components = empty);
  172. var result = [];
  173. var current;
  174. var level = -1;
  175. var arr = [];
  176. var byTag = {};
  177. var inComponent = false;
  178. html.replace(tagRE, function (tag, index) {
  179. if (inComponent) {
  180. if (tag !== '</' + current.name + '>') {
  181. return;
  182. } else {
  183. inComponent = false;
  184. }
  185. }
  186. var isOpen = tag.charAt(1) !== '/';
  187. var isComment = tag.indexOf('<!--') === 0;
  188. var start = index + tag.length;
  189. var nextChar = html.charAt(start);
  190. var parent;
  191. if (isOpen && !isComment) {
  192. level++;
  193. current = parseTag(tag);
  194. if (current.type === 'tag' && options.components[current.name]) {
  195. current.type = 'component';
  196. inComponent = true;
  197. }
  198. if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') {
  199. pushTextNode(current.children, html, level, start, options.ignoreWhitespace);
  200. }
  201. byTag[current.tagName] = current; // if we're at root, push new base node
  202. if (level === 0) {
  203. result.push(current);
  204. }
  205. parent = arr[level - 1];
  206. if (parent) {
  207. parent.children.push(current);
  208. }
  209. arr[level] = current;
  210. }
  211. if (isComment || !isOpen || current.voidElement) {
  212. if (!isComment) {
  213. level--;
  214. }
  215. if (!inComponent && nextChar !== '<' && nextChar) {
  216. // trailing text node
  217. // if we're at the root, push a base text node. otherwise add as
  218. // a child to the current node.
  219. parent = level === -1 ? result : arr[level].children;
  220. pushTextNode(parent, html, level, start, options.ignoreWhitespace);
  221. }
  222. }
  223. }); // If the "html" passed isn't actually html, add it as a text node.
  224. if (!result.length && html.length) {
  225. pushTextNode(result, html, 0, 0, options.ignoreWhitespace);
  226. }
  227. return result;
  228. };
  229. function attrString(attrs) {
  230. var buff = [];
  231. for (var key in attrs) {
  232. buff.push(key + '="' + attrs[key] + '"');
  233. }
  234. if (!buff.length) {
  235. return '';
  236. }
  237. return ' ' + buff.join(' ');
  238. }
  239. function stringify(buff, doc) {
  240. switch (doc.type) {
  241. case 'text':
  242. return buff + doc.content;
  243. case 'tag':
  244. buff += '<' + doc.name + (doc.attrs ? attrString(doc.attrs) : '') + (doc.voidElement ? '/>' : '>');
  245. if (doc.voidElement) {
  246. return buff;
  247. }
  248. return buff + doc.children.reduce(stringify, '') + '</' + doc.name + '>';
  249. }
  250. }
  251. var stringify_1 = function (doc) {
  252. return doc.reduce(function (token, rootEl) {
  253. return token + stringify('', rootEl);
  254. }, '');
  255. };
  256. var htmlParseStringify2 = {
  257. parse: parse,
  258. stringify: stringify_1
  259. };
  260. var defaultOptions = {
  261. bindI18n: 'languageChanging languageChanged',
  262. bindI18nStore: '',
  263. // nsMode: 'fallback' // loop through all namespaces given to hook, HOC, render prop for key lookup
  264. transEmptyNodeValue: '',
  265. transSupportBasicHtmlNodes: true,
  266. transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],
  267. // hashTransKey: key => key // calculate a key for Trans component based on defaultValue
  268. useSuspense: true
  269. };
  270. var i18nInstance;
  271. var hasUsedI18nextProvider;
  272. var I18nContext = React__default.createContext();
  273. function usedI18nextProvider(used) {
  274. hasUsedI18nextProvider = used;
  275. }
  276. function getHasUsedI18nextProvider() {
  277. return hasUsedI18nextProvider;
  278. }
  279. function setDefaults() {
  280. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  281. defaultOptions = _objectSpread2({}, defaultOptions, {}, options);
  282. }
  283. function getDefaults() {
  284. return defaultOptions;
  285. }
  286. class ReportNamespaces {
  287. constructor() {
  288. this.usedNamespaces = {};
  289. }
  290. addUsedNamespaces(namespaces) {
  291. namespaces.forEach(ns => {
  292. if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
  293. });
  294. }
  295. getUsedNamespaces() {
  296. return Object.keys(this.usedNamespaces);
  297. }
  298. }
  299. function setI18n(instance) {
  300. i18nInstance = instance;
  301. }
  302. function getI18n() {
  303. return i18nInstance;
  304. }
  305. var initReactI18next = {
  306. type: '3rdParty',
  307. init(instance) {
  308. setDefaults(instance.options.react);
  309. setI18n(instance);
  310. }
  311. };
  312. function composeInitialProps(ForComponent) {
  313. return ctx => new Promise(resolve => {
  314. var i18nInitialProps = getInitialProps();
  315. if (ForComponent.getInitialProps) {
  316. ForComponent.getInitialProps(ctx).then(componentsInitialProps => {
  317. resolve(_objectSpread2({}, componentsInitialProps, {}, i18nInitialProps));
  318. });
  319. } else {
  320. resolve(i18nInitialProps);
  321. }
  322. }); // Avoid async for now - so we do not need to pull in regenerator
  323. // return async ctx => {
  324. // const componentsInitialProps = ForComponent.getInitialProps
  325. // ? await ForComponent.getInitialProps(ctx)
  326. // : {};
  327. // const i18nInitialProps = getInitialProps();
  328. // return {
  329. // ...componentsInitialProps,
  330. // ...i18nInitialProps,
  331. // };
  332. // };
  333. }
  334. function getInitialProps() {
  335. var i18n = getI18n();
  336. var namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : [];
  337. var ret = {};
  338. var initialI18nStore = {};
  339. i18n.languages.forEach(l => {
  340. initialI18nStore[l] = {};
  341. namespaces.forEach(ns => {
  342. initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};
  343. });
  344. });
  345. ret.initialI18nStore = initialI18nStore;
  346. ret.initialLanguage = i18n.language;
  347. return ret;
  348. }
  349. function warn() {
  350. if (console && console.warn) {
  351. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  352. args[_key] = arguments[_key];
  353. }
  354. if (typeof args[0] === 'string') args[0] = "react-i18next:: ".concat(args[0]);
  355. console.warn(...args);
  356. }
  357. }
  358. var alreadyWarned = {};
  359. function warnOnce() {
  360. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  361. args[_key2] = arguments[_key2];
  362. }
  363. if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;
  364. if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();
  365. warn(...args);
  366. } // not needed right now
  367. //
  368. // export function deprecated(...args) {
  369. // if (process && process.env && (!"development" || "development" === 'development')) {
  370. // if (typeof args[0] === 'string') args[0] = `deprecation warning -> ${args[0]}`;
  371. // warnOnce(...args);
  372. // }
  373. // }
  374. function loadNamespaces(i18n, ns, cb) {
  375. i18n.loadNamespaces(ns, () => {
  376. // delay ready if not yet initialized i18n instance
  377. if (i18n.isInitialized) {
  378. cb();
  379. } else {
  380. var initialized = () => {
  381. // due to emitter removing issue in i18next we need to delay remove
  382. setTimeout(() => {
  383. i18n.off('initialized', initialized);
  384. }, 0);
  385. cb();
  386. };
  387. i18n.on('initialized', initialized);
  388. }
  389. });
  390. }
  391. function hasLoadedNamespace(ns, i18n) {
  392. if (!i18n.languages || !i18n.languages.length) {
  393. warnOnce('i18n.languages were undefined or empty', i18n.languages);
  394. return true;
  395. }
  396. var lng = i18n.languages[0];
  397. var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
  398. var lastLng = i18n.languages[i18n.languages.length - 1]; // we're in cimode so this shall pass
  399. if (lng.toLowerCase() === 'cimode') return true;
  400. var loadNotPending = (l, n) => {
  401. var loadState = i18n.services.backendConnector.state["".concat(l, "|").concat(n)];
  402. return loadState === -1 || loadState === 2;
  403. }; // loaded -> SUCCESS
  404. if (i18n.hasResourceBundle(lng, ns)) return true; // were not loading at all -> SEMI SUCCESS
  405. if (!i18n.services.backendConnector.backend) return true; // failed loading ns - but at least fallback is not pending -> SEMI SUCCESS
  406. if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
  407. return false;
  408. }
  409. function getDisplayName(Component) {
  410. return Component.displayName || Component.name || (typeof Component === 'string' && Component.length > 0 ? Component : 'Unknown');
  411. }
  412. function hasChildren(node) {
  413. return node && (node.children || node.props && node.props.children);
  414. }
  415. function getChildren(node) {
  416. if (!node) return [];
  417. return node && node.children ? node.children : node.props && node.props.children;
  418. }
  419. function hasValidReactChildren(children) {
  420. if (Object.prototype.toString.call(children) !== '[object Array]') return false;
  421. return children.every(child => React__default.isValidElement(child));
  422. }
  423. function getAsArray(data) {
  424. return Array.isArray(data) ? data : [data];
  425. }
  426. function nodesToString(startingString, children, index, i18nOptions) {
  427. if (!children) return '';
  428. var stringNode = startingString;
  429. var childrenArray = getAsArray(children);
  430. var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  431. childrenArray.forEach((child, i) => {
  432. var elementKey = "".concat(i);
  433. if (typeof child === 'string') {
  434. stringNode = "".concat(stringNode).concat(child);
  435. } else if (hasChildren(child)) {
  436. var elementTag = keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 1 && typeof hasChildren(child) === 'string' ? child.type : elementKey;
  437. if (child.props && child.props.i18nIsDynamicList) {
  438. // we got a dynamic list like "<ul>{['a', 'b'].map(item => ( <li key={item}>{item}</li> ))}</ul>""
  439. // the result should be "<0></0>" and not "<0><0>a</0><1>b</1></0>"
  440. stringNode = "".concat(stringNode, "<").concat(elementTag, "></").concat(elementTag, ">");
  441. } else {
  442. // regular case mapping the inner children
  443. stringNode = "".concat(stringNode, "<").concat(elementTag, ">").concat(nodesToString('', getChildren(child), i + 1, i18nOptions), "</").concat(elementTag, ">");
  444. }
  445. } else if (React__default.isValidElement(child)) {
  446. if (keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 0) {
  447. stringNode = "".concat(stringNode, "<").concat(child.type, "/>");
  448. } else {
  449. stringNode = "".concat(stringNode, "<").concat(elementKey, "></").concat(elementKey, ">");
  450. }
  451. } else if (typeof child === 'object') {
  452. var clone = _objectSpread2({}, child);
  453. var {
  454. format
  455. } = clone;
  456. delete clone.format;
  457. var keys = Object.keys(clone);
  458. if (format && keys.length === 1) {
  459. stringNode = "".concat(stringNode, "{{").concat(keys[0], ", ").concat(format, "}}");
  460. } else if (keys.length === 1) {
  461. stringNode = "".concat(stringNode, "{{").concat(keys[0], "}}");
  462. } else {
  463. // not a valid interpolation object (can only contain one value plus format)
  464. warn("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.", child);
  465. }
  466. } else {
  467. warn("Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.", child);
  468. }
  469. });
  470. return stringNode;
  471. }
  472. function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts) {
  473. if (targetString === '') return []; // check if contains tags we need to replace from html string to react nodes
  474. var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  475. var emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString); // no need to replace tags in the targetstring
  476. if (!children && !emptyChildrenButNeedsHandling) return [targetString]; // v2 -> interpolates upfront no need for "some <0>{{var}}</0>"" -> will be just "some {{var}}" in translation file
  477. var data = {};
  478. function getData(childs) {
  479. var childrenArray = getAsArray(childs);
  480. childrenArray.forEach(child => {
  481. if (typeof child === 'string') return;
  482. if (hasChildren(child)) getData(getChildren(child));else if (typeof child === 'object' && !React__default.isValidElement(child)) Object.assign(data, child);
  483. });
  484. }
  485. getData(children);
  486. var interpolatedString = i18n.services.interpolator.interpolate(targetString, _objectSpread2({}, data, {}, combinedTOpts), i18n.language); // parse ast from string with additional wrapper tag
  487. // -> avoids issues in parser removing prepending text nodes
  488. var ast = htmlParseStringify2.parse("<0>".concat(interpolatedString, "</0>"));
  489. function mapAST(reactNode, astNode) {
  490. var reactNodes = getAsArray(reactNode);
  491. var astNodes = getAsArray(astNode);
  492. return astNodes.reduce((mem, node, i) => {
  493. var translationContent = node.children && node.children[0] && node.children[0].content;
  494. if (node.type === 'tag') {
  495. var child = reactNodes[parseInt(node.name, 10)] || {};
  496. var isElement = React__default.isValidElement(child);
  497. if (typeof child === 'string') {
  498. mem.push(child);
  499. } else if (hasChildren(child)) {
  500. var childs = getChildren(child);
  501. var mappedChildren = mapAST(childs, node.children);
  502. var inner = hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
  503. if (child.dummy) child.children = inner; // needed on preact!
  504. mem.push(React__default.cloneElement(child, _objectSpread2({}, child.props, {
  505. key: i
  506. }), inner));
  507. } else if (emptyChildrenButNeedsHandling && typeof child === 'object' && child.dummy && !isElement) {
  508. // we have a empty Trans node (the dummy element) with a targetstring that contains html tags needing
  509. // conversion to react nodes
  510. // so we just need to map the inner stuff
  511. var _inner = mapAST(reactNodes
  512. /* wrong but we need something */
  513. , node.children);
  514. mem.push(React__default.cloneElement(child, _objectSpread2({}, child.props, {
  515. key: i
  516. }), _inner));
  517. } else if (Number.isNaN(parseFloat(node.name))) {
  518. if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
  519. if (node.voidElement) {
  520. mem.push(React__default.createElement(node.name, {
  521. key: "".concat(node.name, "-").concat(i)
  522. }));
  523. } else {
  524. var _inner2 = mapAST(reactNodes
  525. /* wrong but we need something */
  526. , node.children);
  527. mem.push(React__default.createElement(node.name, {
  528. key: "".concat(node.name, "-").concat(i)
  529. }, _inner2));
  530. }
  531. } else if (node.voidElement) {
  532. mem.push("<".concat(node.name, " />"));
  533. } else {
  534. var _inner3 = mapAST(reactNodes
  535. /* wrong but we need something */
  536. , node.children);
  537. mem.push("<".concat(node.name, ">").concat(_inner3, "</").concat(node.name, ">"));
  538. }
  539. } else if (typeof child === 'object' && !isElement) {
  540. var content = node.children[0] ? translationContent : null; // v1
  541. // as interpolation was done already we just have a regular content node
  542. // in the translation AST while having an object in reactNodes
  543. // -> push the content no need to interpolate again
  544. if (content) mem.push(content);
  545. } else if (node.children.length === 1 && translationContent) {
  546. // If component does not have children, but translation - has
  547. // with this in component could be components={[<span class='make-beautiful'/>]} and in translation - 'some text <0>some highlighted message</0>'
  548. mem.push(React__default.cloneElement(child, _objectSpread2({}, child.props, {
  549. key: i
  550. }), translationContent));
  551. } else {
  552. mem.push(React__default.cloneElement(child, _objectSpread2({}, child.props, {
  553. key: i
  554. })));
  555. }
  556. } else if (node.type === 'text') {
  557. mem.push(node.content);
  558. }
  559. return mem;
  560. }, []);
  561. } // call mapAST with having react nodes nested into additional node like
  562. // we did for the string ast from translation
  563. // return the children of that extra node to get expected result
  564. var result = mapAST([{
  565. dummy: true,
  566. children
  567. }], ast);
  568. return getChildren(result[0]);
  569. }
  570. function Trans(_ref) {
  571. var {
  572. children,
  573. count,
  574. parent,
  575. i18nKey,
  576. tOptions,
  577. values,
  578. defaults,
  579. components,
  580. ns,
  581. i18n: i18nFromProps,
  582. t: tFromProps
  583. } = _ref,
  584. additionalProps = _objectWithoutProperties(_ref, ["children", "count", "parent", "i18nKey", "tOptions", "values", "defaults", "components", "ns", "i18n", "t"]);
  585. var {
  586. i18n: i18nFromContext,
  587. defaultNS: defaultNSFromContext
  588. } = getHasUsedI18nextProvider() ? React.useContext(I18nContext) || {} : {};
  589. var i18n = i18nFromProps || i18nFromContext || getI18n();
  590. if (!i18n) {
  591. warnOnce('You will need pass in an i18next instance by using i18nextReactModule');
  592. return children;
  593. }
  594. var t = tFromProps || i18n.t.bind(i18n) || (k => k);
  595. var reactI18nextOptions = _objectSpread2({}, getDefaults(), {}, i18n.options && i18n.options.react);
  596. var useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; // prepare having a namespace
  597. var namespaces = ns || t.ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
  598. namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
  599. var defaultValue = defaults || nodesToString('', children, 0, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue;
  600. var {
  601. hashTransKey
  602. } = reactI18nextOptions;
  603. var key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
  604. var interpolationOverride = values ? {} : {
  605. interpolation: {
  606. prefix: '#$?',
  607. suffix: '?$#'
  608. }
  609. };
  610. var combinedTOpts = _objectSpread2({}, tOptions, {
  611. count
  612. }, values, {}, interpolationOverride, {
  613. defaultValue,
  614. ns: namespaces
  615. });
  616. var translation = key ? t(key, combinedTOpts) : defaultValue;
  617. if (!useAsParent) return renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts);
  618. return React__default.createElement(useAsParent, additionalProps, renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts));
  619. }
  620. function useTranslation(ns) {
  621. var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  622. // assert we have the needed i18nInstance
  623. var {
  624. i18n: i18nFromProps
  625. } = props;
  626. var ReactI18nContext = React.useContext(I18nContext);
  627. var {
  628. i18n: i18nFromContext,
  629. defaultNS: defaultNSFromContext
  630. } = getHasUsedI18nextProvider() ? ReactI18nContext || {} : {};
  631. var i18n = i18nFromProps || i18nFromContext || getI18n();
  632. if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
  633. if (!i18n) {
  634. warnOnce('You will need pass in an i18next instance by using initReactI18next');
  635. var retNotReady = [k => k, {}, false];
  636. retNotReady.t = k => k;
  637. retNotReady.i18n = {};
  638. retNotReady.ready = false;
  639. return retNotReady;
  640. }
  641. var i18nOptions = _objectSpread2({}, getDefaults(), {}, i18n.options.react);
  642. var {
  643. useSuspense = i18nOptions.useSuspense
  644. } = props; // prepare having a namespace
  645. var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
  646. namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation']; // report namespaces as used
  647. if (i18n.reportNamespaces.addUsedNamespaces) 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)
  648. var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n)); // binding t function to namespace (acts also as rerender trigger)
  649. function getT() {
  650. return {
  651. t: i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0])
  652. };
  653. }
  654. var [t, setT] = React.useState(getT()); // seems we can't have functions as value -> wrap it in obj
  655. React.useEffect(() => {
  656. var isMounted = true;
  657. var {
  658. bindI18n,
  659. bindI18nStore
  660. } = i18nOptions; // if not ready and not using suspense load the namespaces
  661. // in side effect and do not call resetT if unmounted
  662. if (!ready && !useSuspense) {
  663. loadNamespaces(i18n, namespaces, () => {
  664. if (isMounted) setT(getT());
  665. });
  666. }
  667. function boundReset() {
  668. if (isMounted) setT(getT());
  669. } // bind events to trigger change, like languageChanged
  670. if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
  671. if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset); // unbinding on unmount
  672. return () => {
  673. isMounted = false;
  674. if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, boundReset));
  675. if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, boundReset));
  676. };
  677. }, [namespaces.join()]); // re-run effect whenever list of namespaces changes
  678. var ret = [t.t, i18n, ready];
  679. ret.t = t.t;
  680. ret.i18n = i18n;
  681. ret.ready = ready; // return hook stuff if ready
  682. if (ready) return ret; // not yet loaded namespaces -> load them -> and return if useSuspense option set false
  683. if (!ready && !useSuspense) return ret; // not yet loaded namespaces -> load them -> and trigger suspense
  684. throw new Promise(resolve => {
  685. loadNamespaces(i18n, namespaces, () => {
  686. setT(getT());
  687. resolve();
  688. });
  689. });
  690. }
  691. function withTranslation(ns) {
  692. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  693. return function Extend(WrappedComponent) {
  694. function I18nextWithTranslation(_ref) {
  695. var {
  696. forwardedRef
  697. } = _ref,
  698. rest = _objectWithoutProperties(_ref, ["forwardedRef"]);
  699. var [t, i18n, ready] = useTranslation(ns, rest);
  700. var passDownProps = _objectSpread2({}, rest, {
  701. t,
  702. i18n,
  703. tReady: ready
  704. });
  705. if (options.withRef && forwardedRef) {
  706. passDownProps.ref = forwardedRef;
  707. }
  708. return React__default.createElement(WrappedComponent, passDownProps);
  709. }
  710. I18nextWithTranslation.displayName = "withI18nextTranslation(".concat(getDisplayName(WrappedComponent), ")");
  711. I18nextWithTranslation.WrappedComponent = WrappedComponent;
  712. var forwardRef = (props, ref) => React__default.createElement(I18nextWithTranslation, _extends({}, props, {
  713. forwardedRef: ref
  714. }));
  715. return options.withRef ? React__default.forwardRef(forwardRef) : I18nextWithTranslation;
  716. };
  717. }
  718. function Translation(props) {
  719. var {
  720. ns,
  721. children
  722. } = props,
  723. options = _objectWithoutProperties(props, ["ns", "children"]);
  724. var [t, i18n, ready] = useTranslation(ns, options);
  725. return children(t, {
  726. i18n,
  727. lng: i18n.language
  728. }, ready);
  729. }
  730. function I18nextProvider(_ref) {
  731. var {
  732. i18n,
  733. defaultNS,
  734. children
  735. } = _ref;
  736. usedI18nextProvider(true);
  737. return React__default.createElement(I18nContext.Provider, {
  738. value: {
  739. i18n,
  740. defaultNS
  741. }
  742. }, children);
  743. }
  744. function useSSR(initialI18nStore, initialLanguage) {
  745. var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  746. var {
  747. i18n: i18nFromProps
  748. } = props;
  749. var ReactI18nContext = React.useContext(I18nContext);
  750. var {
  751. i18n: i18nFromContext
  752. } = getHasUsedI18nextProvider() ? ReactI18nContext || {} : {};
  753. var i18n = i18nFromProps || i18nFromContext || getI18n(); // opt out if is a cloned instance, eg. created by i18next-express-middleware on request
  754. // -> do not set initial stuff on server side
  755. if (i18n.options && i18n.options.isClone) return; // nextjs / SSR: getting data from next.js or other ssr stack
  756. if (initialI18nStore && !i18n.initializedStoreOnce) {
  757. i18n.services.resourceStore.data = initialI18nStore;
  758. i18n.initializedStoreOnce = true;
  759. }
  760. if (initialLanguage && !i18n.initializedLanguageOnce) {
  761. i18n.changeLanguage(initialLanguage);
  762. i18n.initializedLanguageOnce = true;
  763. }
  764. }
  765. function withSSR() {
  766. return function Extend(WrappedComponent) {
  767. function I18nextWithSSR(_ref) {
  768. var {
  769. initialI18nStore,
  770. initialLanguage
  771. } = _ref,
  772. rest = _objectWithoutProperties(_ref, ["initialI18nStore", "initialLanguage"]);
  773. useSSR(initialI18nStore, initialLanguage);
  774. return React__default.createElement(WrappedComponent, _objectSpread2({}, rest));
  775. }
  776. I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent);
  777. I18nextWithSSR.displayName = "withI18nextSSR(".concat(getDisplayName(WrappedComponent), ")");
  778. I18nextWithSSR.WrappedComponent = WrappedComponent;
  779. return I18nextWithSSR;
  780. };
  781. }
  782. exports.I18nContext = I18nContext;
  783. exports.I18nextProvider = I18nextProvider;
  784. exports.Trans = Trans;
  785. exports.Translation = Translation;
  786. exports.composeInitialProps = composeInitialProps;
  787. exports.getDefaults = getDefaults;
  788. exports.getI18n = getI18n;
  789. exports.getInitialProps = getInitialProps;
  790. exports.initReactI18next = initReactI18next;
  791. exports.setDefaults = setDefaults;
  792. exports.setI18n = setI18n;
  793. exports.useSSR = useSSR;
  794. exports.useTranslation = useTranslation;
  795. exports.withSSR = withSSR;
  796. exports.withTranslation = withTranslation;
  797. Object.defineProperty(exports, '__esModule', { value: true });
  798. });