UNPKG

rich-text-editor

Version:
54 lines (53 loc) 2.38 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.sanitize = sanitize; exports.convertLinksToRelative = convertLinksToRelative; const sanitize_html_1 = __importDefault(require("sanitize-html")); const sanitizeOpts = { allowedTags: ['img', 'br', 'span'], allowedAttributes: { img: ['src', 'alt'], }, allowedSchemes: ['data'], }; function sanitize(html, opts) { return [ (v) => (0, sanitize_html_1.default)(v, Object.assign(Object.assign(Object.assign({}, sanitizeOpts), { allowedTags: [...sanitizeOpts.allowedTags, 'div', 'p'], allowedSchemes: ['data', 'http', 'https'] }), opts)), (v) => convertLinksToRelative(v), (v) => stripBlockElements(v), ].reduce((value, fn) => fn(value), html); } function convertLinksToRelative(html) { return html.replace(new RegExp(document.location.origin, 'g'), ''); } function isBlockElement(node) { return node.nodeName === 'DIV' || node.nodeName === 'P'; } // This is copied pretty much as-is from the legacy jQuery version; // it's difficult to say *what exactly* it does but it attempts to // change block-elements (namely `div` and `p`) into `br`s. function stripBlockElements(html) { var _a; const parent = document.createElement('div'); parent.innerHTML = html; do { let lastNode = undefined; for (let i = 0; i < parent.childNodes.length; i++) { const node = parent.childNodes[i]; if (isBlockElement(node)) { if (lastNode !== undefined && lastNode.nodeType === Node.TEXT_NODE && /\S/.test((_a = lastNode.textContent) !== null && _a !== void 0 ? _a : '')) parent.insertBefore(document.createElement('br'), node); if (node.lastChild && node.lastChild.nodeName !== 'BR') node.insertBefore(document.createElement('br'), null); while (node.childNodes.length && node.firstChild !== null) parent.insertBefore(node.firstChild, node); parent.removeChild(node); } lastNode = node; } } while (Array.prototype.some.call(parent.childNodes, (node) => isBlockElement(node))); return parent.innerHTML; }