Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions nx2/utils/svg.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)));

Expand Down
Loading