Skip to content

Commit c76db7d

Browse files
authored
fix: 修复icon丢失根属性导致的样式错误 (#6986)
1 parent 6f39e91 commit c76db7d

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

packages/icons/src/svg/load.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,28 @@ function parseSvg(svgData: string): IconifyIconStructure {
1313
const xmlDoc = parser.parseFromString(svgData, 'image/svg+xml');
1414
const svgElement = xmlDoc.documentElement;
1515

16+
// 提取 SVG 根元素的关键样式属性
17+
const getAttrs = (el: Element, attrs: string[]) =>
18+
attrs
19+
.map((attr) =>
20+
el.hasAttribute(attr) ? `${attr}="${el.getAttribute(attr)}"` : '',
21+
)
22+
.filter(Boolean)
23+
.join(' ');
24+
25+
const rootAttrs = getAttrs(svgElement, [
26+
'fill',
27+
'stroke',
28+
'fill-rule',
29+
'stroke-width',
30+
]);
31+
1632
const svgContent = [...svgElement.childNodes]
1733
.filter((node) => node.nodeType === Node.ELEMENT_NODE)
1834
.map((node) => new XMLSerializer().serializeToString(node))
1935
.join('');
36+
// 若根有属性,用一个 g 标签包裹内容并继承属性
37+
const body = rootAttrs ? `<g ${rootAttrs}>${svgContent}</g>` : svgContent;
2038

2139
const viewBoxValue = svgElement.getAttribute('viewBox') || '';
2240
const [left, top, width, height] = viewBoxValue.split(' ').map((val) => {
@@ -25,7 +43,7 @@ function parseSvg(svgData: string): IconifyIconStructure {
2543
});
2644

2745
return {
28-
body: svgContent,
46+
body,
2947
height,
3048
left,
3149
top,

0 commit comments

Comments
 (0)