Files
lucide/docs/.vitepress/theme/utils/getSVGIcon.ts

35 lines
813 B
TypeScript
Raw Normal View History

2023-06-28 21:04:37 +02:00
const allowedAttrs = [
'xmlns',
'width',
'height',
'viewBox',
'fill',
'stroke',
'stroke-width',
'stroke-linecap',
'stroke-linejoin',
'class',
];
2023-06-28 21:04:37 +02:00
export default function getSVGIcon(element?: HTMLElement, attrs?: Record<string, string>) {
const svg = element ?? document.querySelector('#previewer svg');
if (!svg) return;
2023-06-28 21:04:37 +02:00
const clonedSvg = svg.cloneNode(true) as SVGElement;
2023-06-28 21:04:37 +02:00
// Filter out attributes that are not allowed in SVGs
for (const attr of Array.from(clonedSvg.attributes)) {
if (!allowedAttrs.includes(attr.name)) {
clonedSvg.removeAttribute(attr.name);
2023-06-28 21:04:37 +02:00
}
}
for (const [key, value] of Object.entries(attrs ?? {})) {
clonedSvg.setAttribute(key, value);
2023-06-28 21:04:37 +02:00
}
const svgString = new XMLSerializer().serializeToString(clonedSvg);
2023-06-28 21:04:37 +02:00
return svgString;
2023-06-28 21:04:37 +02:00
}