UNPKG

ice.fo.utils

Version:

73 lines (59 loc) 1.47 kB
function traverseAttributes(el, callback) { const attrs = el.attributes; if (!attrs) { return {}; } for (let i = 0; i < attrs.length; i++) { const key = attrs[i].name; const value = attrs[i].value; callback(key, value); } } function splitTags(text) { const t = text.trim(); const bracket = text.indexOf('<'); const space = text.indexOf(' '); const close = text.indexOf('>'); const tag = t.substring(bracket + 1, Math.min(space, close)); const end = t.indexOf(`</${tag}>`); const content = t.substring(close + 1, end); const result = [{ tag, attrs: {}, content, html: t, }]; if (end + `</${tag}>`.length == t.length) { return result; } return result.concat(splitTags(t.substr(end + `</${tag}>`.length))); } export default function parseToHtmlInfo(text) { if (!text) { return []; } // TODO: Support SSR if (typeof window === 'undefined') { return splitTags(text); } const result = []; const div = document.createElement('div'); // Parse div.innerHTML = text; // Find all outer element const children = div.childNodes; for (let i = 0; i < children.length; i++) { const el = children[i]; const attrs = {}; traverseAttributes(el, (key, value) => { attrs[key] = value; }); result.push({ tag: el.tagName, attrs, content: el.innerHTML || el.data, html: el.outerHTML || el.data, }); } return result; }