From 7fa4410eabbe89ae96a648121a15cc32b3489119 Mon Sep 17 00:00:00 2001
From: Li Kui <90845831+likui628@users.noreply.github.com>
Date: Sat, 24 Aug 2024 12:43:48 +0800
Subject: [PATCH] fix: correct the SVG icon format (#4224)
* fix: correct the SVG icon format
closes #4220
* fix: ci fail
* chore: apply suggestion
---
packages/icons/src/svg/load.ts | 51 +++++++++++++++++-----------------
1 file changed, 26 insertions(+), 25 deletions(-)
diff --git a/packages/icons/src/svg/load.ts b/packages/icons/src/svg/load.ts
index d0fb459a..a07f1961 100644
--- a/packages/icons/src/svg/load.ts
+++ b/packages/icons/src/svg/load.ts
@@ -1,7 +1,4 @@
-import {
- addIcon,
- // addCollection
-} from '@vben-core/icons';
+import { addIcon, type IconifyIcon } from '@vben-core/icons';
let loaded = false;
if (!loaded) {
@@ -9,32 +6,36 @@ if (!loaded) {
loaded = true;
}
-// addCollection({
-// prefix: 'mdi',
-// icons: {
-// 'account-box': {
-// body: '',
-// },
-// 'account-cash': {
-// body: '',
-// },
-// 'account': {
-// body: '',
-// },
-// 'home': {
-// body: '',
-// },
-// },
-// width: 24,
-// height: 24,
-// });
+function parseSvg(svgData: string): IconifyIcon {
+ const parser = new DOMParser();
+ const xmlDoc = parser.parseFromString(svgData, 'image/svg+xml');
+ const svgElement = xmlDoc.documentElement;
+
+ const svgContent = [...svgElement.childNodes]
+ .filter((node) => node.nodeType === Node.ELEMENT_NODE)
+ .map((node) => new XMLSerializer().serializeToString(node))
+ .join('');
+
+ const viewBoxValue = svgElement.getAttribute('viewBox') || '';
+ const [left, top, width, height] = viewBoxValue.split(' ').map((val) => {
+ const num = Number(val);
+ return Number.isNaN(num) ? undefined : num;
+ });
+
+ return {
+ body: svgContent,
+ height,
+ left,
+ top,
+ width,
+ };
+}
/**
* 自定义的svg图片转化为组件
* @example ./svg/avatar.svg
*
*/
-
async function loadSvgIcons() {
const svgEagers = import.meta.glob('./icons/**', {
eager: true,
@@ -51,7 +52,7 @@ async function loadSvgIcons() {
const iconName = key.slice(start, end);
return addIcon(`svg:${iconName}`, {
- body: typeof body === 'object' ? body.default : body,
+ ...parseSvg(typeof body === 'object' ? body.default : body),
});
}),
);