No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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