fix: 修复icon丢失根属性导致的样式错误 (#6986)

This commit is contained in:
luoqiz
2025-12-01 09:51:27 +08:00
committed by GitHub
parent 6f39e9136e
commit c76db7d8d1

View File

@@ -13,10 +13,28 @@ function parseSvg(svgData: string): IconifyIconStructure {
const xmlDoc = parser.parseFromString(svgData, 'image/svg+xml');
const svgElement = xmlDoc.documentElement;
// 提取 SVG 根元素的关键样式属性
const getAttrs = (el: Element, attrs: string[]) =>
attrs
.map((attr) =>
el.hasAttribute(attr) ? `${attr}="${el.getAttribute(attr)}"` : '',
)
.filter(Boolean)
.join(' ');
const rootAttrs = getAttrs(svgElement, [
'fill',
'stroke',
'fill-rule',
'stroke-width',
]);
const svgContent = [...svgElement.childNodes]
.filter((node) => node.nodeType === Node.ELEMENT_NODE)
.map((node) => new XMLSerializer().serializeToString(node))
.join('');
// 若根有属性,用一个 g 标签包裹内容并继承属性
const body = rootAttrs ? `<g ${rootAttrs}>${svgContent}</g>` : svgContent;
const viewBoxValue = svgElement.getAttribute('viewBox') || '';
const [left, top, width, height] = viewBoxValue.split(' ').map((val) => {
@@ -25,7 +43,7 @@ function parseSvg(svgData: string): IconifyIconStructure {
});
return {
body: svgContent,
body,
height,
left,
top,