import {SDUIDescriptor, SDUINode} from "./types"; export default class SDUIUtils { static toJson(nodes: HTMLCollection) { const desc: SDUIDescriptor = {}; desc.nodes = []; for (const node of nodes) { const parsedChild = SDUIUtils.parseNode(node); if (parsedChild) { desc.nodes.push(parsedChild); } } const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(desc, null, 2)); const dlAnchorElem = document.createElement("a"); dlAnchorElem.setAttribute("href", dataStr); dlAnchorElem.setAttribute("download", "sdui.json"); document.body.appendChild(dlAnchorElem); dlAnchorElem.click(); dlAnchorElem.remove(); return JSON.stringify(desc, null, 4); } static parseNode(node: Node) { const sdui: SDUINode = {}; const nodeType = node.nodeType; if (nodeType == Node.ELEMENT_NODE) { const name = node.nodeName.toLowerCase(); sdui.tagName = name; const element = node as HTMLElement; sdui.attributes = {}; const attributes = element.attributes; const attrLength = attributes.length; for (let i = 0; i < attrLength; i++) { const attribute = attributes.item(i); if (attribute) sdui.attributes[attribute.name] = attribute.value; } let childNodes = element.childNodes; let children = element.children; if (name == "template") { const template = node as HTMLTemplateElement; childNodes = template.content.childNodes; children = template.content.children; } if (children.length > 0) { sdui.nodes = []; for (const ch of childNodes) { const parsedChild = SDUIUtils.parseNode(ch); if (parsedChild) { sdui.nodes.push(parsedChild); } } } else if (element.innerHTML) { sdui.innerHTML = element.innerHTML; } } if (nodeType == Node.TEXT_NODE) { const content = (node.textContent || "").trim(); if (!content) return null; sdui.markup = content; } return sdui; } }