From e69a6dd08c9956fef5201968ff186fbb0e28c661 Mon Sep 17 00:00:00 2001 From: Ramachandra Avuthu Date: Wed, 24 Jun 2026 15:52:03 -0400 Subject: [PATCH] updated svg util from Loc PR so that it can be used for other blocks migration --- nx2/utils/svg.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/nx2/utils/svg.js b/nx2/utils/svg.js index 276a03376..4bcd6f285 100644 --- a/nx2/utils/svg.js +++ b/nx2/utils/svg.js @@ -20,6 +20,50 @@ export const loadHrefSvg = (() => { }; })(); +const iconCache = new Map(); + +async function fetchIcon(path) { + // Check if we already have a request in flight or completed + if (iconCache.has(path)) { + const cachedSvg = await iconCache.get(path); + // Clone the node because an element can only exist in one place in the DOM + return cachedSvg ? cachedSvg.cloneNode(true) : null; + } + + const fetchPromise = (async () => { + try { + const resp = await fetch(path); + if (!resp.ok) return null; + + const text = await resp.text(); + const parser = new DOMParser(); + const doc = parser.parseFromString(text, 'image/svg+xml'); + return doc.querySelector('svg'); + } catch (err) { + // eslint-disable-next-line no-console + console.error(`Failed to fetch icon: ${path}`, err); + return null; + } + })(); + + iconCache.set(path, fetchPromise); + + const svg = await fetchPromise; + return svg ? svg.cloneNode(true) : null; +} + +export async function getSvg({ parent, paths }) { + const svgs = await Promise.all(paths.map((path) => fetchIcon(path))); + + if (parent) { + svgs.forEach((svg) => { + if (svg) parent.append(svg); + }); + } + + return svgs; +} + export default function loadIcons({ paths, icons, size = iconSize }) { if (paths) return Promise.all(paths.map((path) => loadHrefSvg(path)));