formatElements.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  5. }) : (function(o, m, k, k2) {
  6. if (k2 === undefined) k2 = k;
  7. o[k2] = m[k];
  8. }));
  9. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  10. Object.defineProperty(o, "default", { enumerable: true, value: v });
  11. }) : function(o, v) {
  12. o["default"] = v;
  13. });
  14. var __importStar = (this && this.__importStar) || function (mod) {
  15. if (mod && mod.__esModule) return mod;
  16. var result = {};
  17. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  18. __setModuleDefault(result, mod);
  19. return result;
  20. };
  21. Object.defineProperty(exports, "__esModule", { value: true });
  22. var react_1 = __importStar(require("react"));
  23. var tagRe = /<(\w+)>(.*?)<\/\1>|<(\w+)\/>/;
  24. var nlRe = /(?:\r\n|\r|\n)/g;
  25. function getElements(parts) {
  26. if (!parts.length)
  27. return [];
  28. var _a = parts.slice(0, 4), paired = _a[0], children = _a[1], unpaired = _a[2], after = _a[3];
  29. return [
  30. [(paired || unpaired), children || '', after],
  31. ].concat(getElements(parts.slice(4, parts.length)));
  32. }
  33. function formatElements(value, elements) {
  34. if (elements === void 0) { elements = []; }
  35. var parts = value.replace(nlRe, '').split(tagRe);
  36. if (parts.length === 1)
  37. return value;
  38. var tree = [];
  39. var before = parts.shift();
  40. if (before)
  41. tree.push(before);
  42. getElements(parts).forEach(function (_a, realIndex) {
  43. var key = _a[0], children = _a[1], after = _a[2];
  44. var element = elements[key] || react_1.default.createElement(react_1.Fragment, null);
  45. tree.push((0, react_1.cloneElement)(element, { key: realIndex }, children ? formatElements(children, elements) : element.props.children));
  46. if (after)
  47. tree.push(after);
  48. });
  49. return tree;
  50. }
  51. exports.default = formatElements;