1 import { transform } from "@svgr/core"
2 import jsx from "@svgr/plugin-jsx"
3 import prettier from "@svgr/plugin-prettier"
4 import svgo from "@svgr/plugin-svgo"
5
6 import { defaultTemplate, fixedTemplate } from "@/templates"
7
8 type TransformArgs = {
9 code: string
10 componentName: string
11 fixed?: boolean
12 }
13
14 function ensureViewBox(code: string) {
15 if (/viewBox\s*=/.test(code)) {
16 return code
17 }
18
19 const svgTagMatch = code.match(/<svg\b[^>]*>/i)
20 if (!svgTagMatch) {
21 return code
22 }
23
24 const svgTag = svgTagMatch[0]
25 const widthMatch = svgTag.match(/\bwidth\s*=\s*["']([^"']+)["']/i)
26 const heightMatch = svgTag.match(/\bheight\s*=\s*["']([^"']+)["']/i)
27
28 if (!widthMatch || !heightMatch) {
29 return code
30 }
31
32 const width = Number.parseFloat(widthMatch[1])
33 const height = Number.parseFloat(heightMatch[1])
34
35 if (!Number.isFinite(width) || !Number.isFinite(height)) {
36 return code
37 }
38
39 const viewBox = `0 0 ${width} ${height}`
40
41 return code.replace(/<svg\b([^>]*?)>/i, (_match, attrs) => {
42 return `<svg${attrs} viewBox="${viewBox}">`
43 })
44 }
45
46 export async function transformSvg({
47 code,
48 componentName,
49 fixed = false,
50 }: TransformArgs) {
51 const codeWithViewBox = ensureViewBox(code)
52
53 return await transform(
54 codeWithViewBox,
55 {
56 typescript: true,
57 replaceAttrValues: !fixed
58 ? {
59 "#18181B": "{color}",
60 }
61 : undefined,
62 svgProps: {
63 ref: "{ref}",
64 },
65 expandProps: "end",
66 plugins: [svgo, jsx, prettier],
67 jsxRuntime: "classic",
68 prettierConfig: {
69 semi: false,
70 parser: "typescript",
71 },
72 svgoConfig: {
73 plugins: [
74 {
75 name: "preset-default",
76 params: {
77 overrides: {
78 removeTitle: false,
79 },
80 },
81 },
82 ],
83 },
84 template: fixed ? fixedTemplate : defaultTemplate,
85 },
86 {
87 componentName,
88 }
89 )
90 }