luoqiz
11 months ago
committed by
GitHub
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with
19 additions and
1 deletions
-
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, |
|
|
|
|