UNPKG

ice.fo.utils

Version:

88 lines (72 loc) 1.85 kB
export function bodyScroll (value, bodyCSS = 'body_no_scroll') { if (!value) { document.body.style.top = `-${window.scrollY}px` document.body.classList.add(bodyCSS) } else { document.body.classList.remove(bodyCSS) const scrollY = document.body.style.top document.body.style.position = '' document.body.style.top = '' window.scrollTo(0, parseInt(scrollY || '0') * -1) } } export 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 } 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 } else { return result.concat(splitTags(t.substr(end + `</${tag}>`.length))) } }