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.
 
 
 
 

272 lines
12 KiB

  1. "use strict";
  2. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
  3. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  4. Object.defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.nodesToString = nodesToString;
  8. exports.Trans = Trans;
  9. var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
  10. var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
  11. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  12. var _react = _interopRequireWildcard(require("react"));
  13. var _htmlParseStringify = _interopRequireDefault(require("html-parse-stringify2"));
  14. var _context = require("./context");
  15. var _utils = require("./utils");
  16. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  17. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  18. function hasChildren(node) {
  19. return node && (node.children || node.props && node.props.children);
  20. }
  21. function getChildren(node) {
  22. if (!node) return [];
  23. return node && node.children ? node.children : node.props && node.props.children;
  24. }
  25. function hasValidReactChildren(children) {
  26. if (Object.prototype.toString.call(children) !== '[object Array]') return false;
  27. return children.every(function (child) {
  28. return _react["default"].isValidElement(child);
  29. });
  30. }
  31. function getAsArray(data) {
  32. return Array.isArray(data) ? data : [data];
  33. }
  34. function nodesToString(startingString, children, index, i18nOptions) {
  35. if (!children) return '';
  36. var stringNode = startingString;
  37. var childrenArray = getAsArray(children);
  38. var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  39. childrenArray.forEach(function (child, i) {
  40. var elementKey = "".concat(i);
  41. if (typeof child === 'string') {
  42. stringNode = "".concat(stringNode).concat(child);
  43. } else if (hasChildren(child)) {
  44. var elementTag = keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 1 && typeof hasChildren(child) === 'string' ? child.type : elementKey;
  45. if (child.props && child.props.i18nIsDynamicList) {
  46. // we got a dynamic list like "<ul>{['a', 'b'].map(item => ( <li key={item}>{item}</li> ))}</ul>""
  47. // the result should be "<0></0>" and not "<0><0>a</0><1>b</1></0>"
  48. stringNode = "".concat(stringNode, "<").concat(elementTag, "></").concat(elementTag, ">");
  49. } else {
  50. // regular case mapping the inner children
  51. stringNode = "".concat(stringNode, "<").concat(elementTag, ">").concat(nodesToString('', getChildren(child), i + 1, i18nOptions), "</").concat(elementTag, ">");
  52. }
  53. } else if (_react["default"].isValidElement(child)) {
  54. if (keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 0) {
  55. stringNode = "".concat(stringNode, "<").concat(child.type, "/>");
  56. } else {
  57. stringNode = "".concat(stringNode, "<").concat(elementKey, "></").concat(elementKey, ">");
  58. }
  59. } else if ((0, _typeof2["default"])(child) === 'object') {
  60. var clone = _objectSpread({}, child);
  61. var format = clone.format;
  62. delete clone.format;
  63. var keys = Object.keys(clone);
  64. if (format && keys.length === 1) {
  65. stringNode = "".concat(stringNode, "{{").concat(keys[0], ", ").concat(format, "}}");
  66. } else if (keys.length === 1) {
  67. stringNode = "".concat(stringNode, "{{").concat(keys[0], "}}");
  68. } else {
  69. // not a valid interpolation object (can only contain one value plus format)
  70. (0, _utils.warn)("react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.", child);
  71. }
  72. } else {
  73. (0, _utils.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);
  74. }
  75. });
  76. return stringNode;
  77. }
  78. function renderNodes(children, targetString, i18n, i18nOptions, combinedTOpts) {
  79. if (targetString === '') return []; // check if contains tags we need to replace from html string to react nodes
  80. var keepArray = i18nOptions.transKeepBasicHtmlNodesFor || [];
  81. var emptyChildrenButNeedsHandling = targetString && new RegExp(keepArray.join('|')).test(targetString); // no need to replace tags in the targetstring
  82. if (!children && !emptyChildrenButNeedsHandling) return [targetString]; // v2 -> interpolates upfront no need for "some <0>{{var}}</0>"" -> will be just "some {{var}}" in translation file
  83. var data = {};
  84. function getData(childs) {
  85. var childrenArray = getAsArray(childs);
  86. childrenArray.forEach(function (child) {
  87. if (typeof child === 'string') return;
  88. if (hasChildren(child)) getData(getChildren(child));else if ((0, _typeof2["default"])(child) === 'object' && !_react["default"].isValidElement(child)) Object.assign(data, child);
  89. });
  90. }
  91. getData(children);
  92. var interpolatedString = i18n.services.interpolator.interpolate(targetString, _objectSpread({}, data, {}, combinedTOpts), i18n.language); // parse ast from string with additional wrapper tag
  93. // -> avoids issues in parser removing prepending text nodes
  94. var ast = _htmlParseStringify["default"].parse("<0>".concat(interpolatedString, "</0>"));
  95. function mapAST(reactNode, astNode) {
  96. var reactNodes = getAsArray(reactNode);
  97. var astNodes = getAsArray(astNode);
  98. return astNodes.reduce(function (mem, node, i) {
  99. var translationContent = node.children && node.children[0] && node.children[0].content;
  100. if (node.type === 'tag') {
  101. var child = reactNodes[parseInt(node.name, 10)] || {};
  102. var isElement = _react["default"].isValidElement(child);
  103. if (typeof child === 'string') {
  104. mem.push(child);
  105. } else if (hasChildren(child)) {
  106. var childs = getChildren(child);
  107. var mappedChildren = mapAST(childs, node.children);
  108. var inner = hasValidReactChildren(childs) && mappedChildren.length === 0 ? childs : mappedChildren;
  109. if (child.dummy) child.children = inner; // needed on preact!
  110. mem.push(_react["default"].cloneElement(child, _objectSpread({}, child.props, {
  111. key: i
  112. }), inner));
  113. } else if (emptyChildrenButNeedsHandling && (0, _typeof2["default"])(child) === 'object' && child.dummy && !isElement) {
  114. // we have a empty Trans node (the dummy element) with a targetstring that contains html tags needing
  115. // conversion to react nodes
  116. // so we just need to map the inner stuff
  117. var _inner = mapAST(reactNodes
  118. /* wrong but we need something */
  119. , node.children);
  120. mem.push(_react["default"].cloneElement(child, _objectSpread({}, child.props, {
  121. key: i
  122. }), _inner));
  123. } else if (Number.isNaN(parseFloat(node.name))) {
  124. if (i18nOptions.transSupportBasicHtmlNodes && keepArray.indexOf(node.name) > -1) {
  125. if (node.voidElement) {
  126. mem.push(_react["default"].createElement(node.name, {
  127. key: "".concat(node.name, "-").concat(i)
  128. }));
  129. } else {
  130. var _inner2 = mapAST(reactNodes
  131. /* wrong but we need something */
  132. , node.children);
  133. mem.push(_react["default"].createElement(node.name, {
  134. key: "".concat(node.name, "-").concat(i)
  135. }, _inner2));
  136. }
  137. } else if (node.voidElement) {
  138. mem.push("<".concat(node.name, " />"));
  139. } else {
  140. var _inner3 = mapAST(reactNodes
  141. /* wrong but we need something */
  142. , node.children);
  143. mem.push("<".concat(node.name, ">").concat(_inner3, "</").concat(node.name, ">"));
  144. }
  145. } else if ((0, _typeof2["default"])(child) === 'object' && !isElement) {
  146. var content = node.children[0] ? translationContent : null; // v1
  147. // as interpolation was done already we just have a regular content node
  148. // in the translation AST while having an object in reactNodes
  149. // -> push the content no need to interpolate again
  150. if (content) mem.push(content);
  151. } else if (node.children.length === 1 && translationContent) {
  152. // If component does not have children, but translation - has
  153. // with this in component could be components={[<span class='make-beautiful'/>]} and in translation - 'some text <0>some highlighted message</0>'
  154. mem.push(_react["default"].cloneElement(child, _objectSpread({}, child.props, {
  155. key: i
  156. }), translationContent));
  157. } else {
  158. mem.push(_react["default"].cloneElement(child, _objectSpread({}, child.props, {
  159. key: i
  160. })));
  161. }
  162. } else if (node.type === 'text') {
  163. mem.push(node.content);
  164. }
  165. return mem;
  166. }, []);
  167. } // call mapAST with having react nodes nested into additional node like
  168. // we did for the string ast from translation
  169. // return the children of that extra node to get expected result
  170. var result = mapAST([{
  171. dummy: true,
  172. children: children
  173. }], ast);
  174. return getChildren(result[0]);
  175. }
  176. function Trans(_ref) {
  177. var children = _ref.children,
  178. count = _ref.count,
  179. parent = _ref.parent,
  180. i18nKey = _ref.i18nKey,
  181. tOptions = _ref.tOptions,
  182. values = _ref.values,
  183. defaults = _ref.defaults,
  184. components = _ref.components,
  185. ns = _ref.ns,
  186. i18nFromProps = _ref.i18n,
  187. tFromProps = _ref.t,
  188. additionalProps = (0, _objectWithoutProperties2["default"])(_ref, ["children", "count", "parent", "i18nKey", "tOptions", "values", "defaults", "components", "ns", "i18n", "t"]);
  189. var _ref2 = (0, _context.getHasUsedI18nextProvider)() ? (0, _react.useContext)(_context.I18nContext) || {} : {},
  190. i18nFromContext = _ref2.i18n,
  191. defaultNSFromContext = _ref2.defaultNS;
  192. var i18n = i18nFromProps || i18nFromContext || (0, _context.getI18n)();
  193. if (!i18n) {
  194. (0, _utils.warnOnce)('You will need pass in an i18next instance by using i18nextReactModule');
  195. return children;
  196. }
  197. var t = tFromProps || i18n.t.bind(i18n) || function (k) {
  198. return k;
  199. };
  200. var reactI18nextOptions = _objectSpread({}, (0, _context.getDefaults)(), {}, i18n.options && i18n.options.react);
  201. var useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; // prepare having a namespace
  202. var namespaces = ns || t.ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;
  203. namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
  204. var defaultValue = defaults || nodesToString('', children, 0, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue;
  205. var hashTransKey = reactI18nextOptions.hashTransKey;
  206. var key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue);
  207. var interpolationOverride = values ? {} : {
  208. interpolation: {
  209. prefix: '#$?',
  210. suffix: '?$#'
  211. }
  212. };
  213. var combinedTOpts = _objectSpread({}, tOptions, {
  214. count: count
  215. }, values, {}, interpolationOverride, {
  216. defaultValue: defaultValue,
  217. ns: namespaces
  218. });
  219. var translation = key ? t(key, combinedTOpts) : defaultValue;
  220. if (!useAsParent) return renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts);
  221. return _react["default"].createElement(useAsParent, additionalProps, renderNodes(components || children, translation, i18n, reactI18nextOptions, combinedTOpts));
  222. }