2023-06-28 21:04:37 +02:00
|
|
|
const allowedAttrs = [
|
|
|
|
|
'xmlns',
|
|
|
|
|
'width',
|
|
|
|
|
'height',
|
|
|
|
|
'viewBox',
|
|
|
|
|
'fill',
|
|
|
|
|
'stroke',
|
|
|
|
|
'stroke-width',
|
|
|
|
|
'stroke-linecap',
|
|
|
|
|
'stroke-linejoin',
|
|
|
|
|
'class',
|
2024-02-01 22:38:21 +09:00
|
|
|
];
|
2023-06-28 21:04:37 +02:00
|
|
|
|
|
|
|
|
export default function getSVGIcon(element?: HTMLElement, attrs?: Record<string, string>) {
|
2024-02-01 22:38:21 +09:00
|
|
|
const svg = element ?? document.querySelector('#previewer svg');
|
|
|
|
|
if (!svg) return;
|
2023-06-28 21:04:37 +02:00
|
|
|
|
2024-02-01 22:38:21 +09: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)) {
|
2024-02-01 22:38:21 +09:00
|
|
|
clonedSvg.removeAttribute(attr.name);
|
2023-06-28 21:04:37 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const [key, value] of Object.entries(attrs ?? {})) {
|
2024-02-01 22:38:21 +09:00
|
|
|
clonedSvg.setAttribute(key, value);
|
2023-06-28 21:04:37 +02:00
|
|
|
}
|
|
|
|
|
|
2024-02-01 22:38:21 +09:00
|
|
|
const svgString = new XMLSerializer().serializeToString(clonedSvg);
|
2023-06-28 21:04:37 +02:00
|
|
|
|
2024-02-01 22:38:21 +09:00
|
|
|
return svgString;
|
2023-06-28 21:04:37 +02:00
|
|
|
}
|