UNPKG

@eccenca/gui-elements

Version:

GUI elements based on other libraries, usable in React application, written in Typescript.

75 lines 2.91 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import React from "react"; import { renderToString } from "react-dom/server.js"; import * as ReactIs from "react-is"; import { utils } from "./../index.js"; export var reduceToText = function (input, options) { var _a = options || {}, maxNodes = _a.maxNodes, maxLength = _a.maxLength, decodeHtmlEntities = _a.decodeHtmlEntities; var content = input; var nodeCount = 0; var onlyText = function (nodes) { if (typeof maxNodes !== "undefined" && nodeCount >= maxNodes) return ""; return React.Children.toArray(nodes) .slice(0, maxNodes) .map(function (child) { var _a; if (typeof maxNodes !== "undefined" && nodeCount >= maxNodes) return ""; if (ReactIs.isFragment(child)) return onlyText((_a = child.props) === null || _a === void 0 ? void 0 : _a.children); if (typeof child === "string" || typeof child === "number") { nodeCount++; return child.toString(); } if (ReactIs.isElement(child)) { nodeCount++; return renderToString(React.createElement("span", null, child)); } return ""; }) .join(" "); }; var text = typeof content === "string" ? content : onlyText(content); // Basic HTML cleanup text = text.replace(/<[^\s][^>]*>/g, "").replace(/\n/g, " "); if (decodeHtmlEntities) { var decodeDefaultOptions_1 = { isAttributeValue: true, strict: true, }; var decodeErrors_1 = 0; // we decode in pieces to apply some error tolerance even in strict mode text = text .split(" ") .map(function (value) { try { return utils.decodeHtmlEntities(value, __assign(__assign({}, decodeDefaultOptions_1), options === null || options === void 0 ? void 0 : options.decodeHtmlEntitiesOptions)); } catch (_a) { decodeErrors_1++; return value; } }) .join(" "); if (decodeErrors_1 > 0) { // eslint-disable-next-line no-console console.warn("".concat(decodeErrors_1, " parse error(s) for decodeHtmlEntities, return un-decoded text"), text); } } if (typeof maxLength === "number") { text = text.slice(0, maxLength); } return text.trim(); }; //# sourceMappingURL=reduceToText.js.map