import { sanitizeDomElement } from "../services/sanitize/sanitize.js"; let hiddenSvgContainer = void 0 as SVGDefsElement; let newID = 1; const installSvgClipPathInDom = async (container: SVGClipPathElement, url, originalId) => { const r = await fetch(url); const text = await r.text(); const parser = new DOMParser(); const dom = parser.parseFromString(text, "image/svg+xml"); const root = dom.documentElement; sanitizeDomElement(root); const cp = dom.documentElement.querySelector("clipPath#"+ originalId); let path = void 0 as SVGPathElement; const cpFirstChild = cp.firstElementChild; if(/use/i.test(cpFirstChild.tagName)) { // find path... path = dom.documentElement.querySelector(cpFirstChild.getAttribute("href")); } else if(/path/i.test(cpFirstChild.tagName)) { path = cpFirstChild as SVGPathElement; } if(!path) { console.error("No clip path found"); return; } path.removeAttribute("id"); path.remove(); container.appendChild(path); }; const map = new Map(); export const installSvgClipPath = (value: string) => { const svgNS = "http://www.w3.org/2000/svg"; if(!hiddenSvgContainer) { const root = document.createElementNS("http://www.w3.org/2000/svg", "svg"); root.setAttribute("no-track", "true"); root.setAttributeNS(svgNS, "width" , "0"); root.setAttributeNS(svgNS, "height" , "0"); document.body.appendChild(root); hiddenSvgContainer = document.createElementNS("http://www.w3.org/2000/svg", "defs"); root.appendChild(hiddenSvgContainer); } const tokens = value.split("#", 2); const url = tokens[0]; let installed = map.get(url); if(!installed) { let _id = tokens[1] ?? "clip-path"; // download url... const id = `clip-path-${newID++}`; const cp = document.createElementNS("http://www.w3.org/2000/svg", "clipPath"); cp.setAttribute("clipPathUnits", "objectBoundingBox"); cp.setAttribute("id", id); hiddenSvgContainer.appendChild(cp); installSvgClipPathInDom(cp, url, _id).catch(console.error); installed = "#" + id; } return installed; };