فهرست منبع

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

luoqiz 6 ماه پیش
والد
کامیت
c76db7d8d1
1فایلهای تغییر یافته به همراه19 افزوده شده و 1 حذف شده
  1. 19 1
      packages/icons/src/svg/load.ts

+ 19 - 1
packages/icons/src/svg/load.ts

@@ -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,