1 import { client } from "@/figma-client"
2 import fse from "fs-extra"
3 import { extname, join, resolve } from "path"
4 import dedent from "ts-dedent"
5
6 import { generateIndex, getIconData } from "@/commands/icons/utils"
7 import { transformSvg } from "@/transformers"
8
9 import { FIGMA_FILE_ID, FIGMA_ICONS_NODE_ID } from "@/constants"
10 import { logger } from "@/logger"
11
12 type GenerateIconsArgs = {
13 output: string
14 }
15
16 // We don't want to generate icons for these frames as they are not optimized
17 const BANNED_FRAMES = ["Flags"]
18
19 export async function generateIcons({ output }: GenerateIconsArgs) {
20 const skippedIcons: string[] = []
21
22 // Ensure the destination directory exists
23 await fse.mkdirp(output)
24
25 logger.info("Fetching components from Figma")
26
27 const fileComponents = await client
28 .getFileComponents(FIGMA_FILE_ID)
29 .then((file) => {
30 logger.success("Successfully fetched components from Figma")
31 return file
32 })
33 .catch((_error) => {
34 logger.error("Failed to fetch components from Figma")
35 return null
36 })
37
38 if (!fileComponents) {
39 return
40 }
41
42 logger.info("Fetching URLs for SVGs")
43
44 const iconNodes = fileComponents.meta?.components.reduce((acc, component) => {
45 const frameInfo = component.containing_frame
46
47 if (!frameInfo) {
48 return acc
49 }
50
51 if (BANNED_FRAMES.includes(frameInfo.name)) {
52 return acc
53 }
54
55 if (frameInfo.pageId !== FIGMA_ICONS_NODE_ID) {
56 return acc
57 }
58
59 acc.push({
60 node_id: component.node_id,
61 name: component.name,
62 frame_name: frameInfo.name,
63 })
64
65 return acc
66 }, [] as { node_id: string; name: string; frame_name: string }[])
67
68 if (!iconNodes) {
69 logger.error(
70 "Found no SVGs to export. Make sure that the Figma file is correct."
71 )
72 return
73 }
74
75 const URLData = await client.getImage(FIGMA_FILE_ID, {
76 ids: iconNodes.map((icon) => icon.node_id),
77 format: "svg",
78 scale: 1,
79 })
80
81 logger.success("Successfully fetched URLs for SVGs")
82
83 const length = iconNodes.length
84
85 logger.info("Transforming SVGs")
86 for (let i = 0; i < length; i += 20) {
87 const slice = iconNodes.slice(i, i + 20)
88
89 const requests = slice.map(async (icon) => {
90 const URL = URLData.images[icon.node_id]
91
92 if (!URL) {
93 logger.warn(`Failed to fetch icon ${icon.name}. Skipping...`)
94 skippedIcons.push(icon.name)
95 return
96 }
97
98 let code: string | null = null
99
100 try {
101 code = await client.getResource(URL)
102 } catch (e) {
103 logger.warn(`Failed to fetch icon ${icon.name}. Skipping...`)
104 skippedIcons.push(icon.name)
105 }
106
107 if (!code) {
108 return
109 }
110
111 const { componentName, fileName, testName, fixed } = getIconData(
112 icon.name,
113 icon.frame_name
114 )
115
116 const component = await transformSvg({
117 code,
118 componentName,
119 fixed,
120 })
121
122 const filePath = resolve(output, fileName)
123
124 await fse.outputFile(filePath, component)
125
126 // Get fileName without extension
127 const ext = extname(fileName)
128 const fileNameWithoutExt = fileName.replace(ext, "")
129
130 // Generate a test file for the icon
131 const testFilePath = resolve(join(output, "__tests__"), testName)
132
133 const testFile = dedent`
134 import * as React from "react"
135 import { cleanup, render, screen } from "@testing-library/react"
136
137 import ${componentName} from "../${fileNameWithoutExt}"
138
139 describe("${componentName}", () => {
140 it("should render the icon without errors", async () => {
141 render(<${componentName} data-testid="icon" />)
142
143
144 const svgElement = screen.getByTestId("icon")
145
146 expect(svgElement).toBeInTheDocument()
147
148 cleanup()
149 })
150 })
151 `
152
153 await fse.outputFile(testFilePath, testFile)
154 })
155
156 await Promise.all(requests)
157 }
158 logger.success("Successfully transformed SVGs")
159
160 if (skippedIcons.length) {
161 logger.warn(
162 `Skipped ${skippedIcons.length} icons. Check the logs for more information.`
163 )
164 }
165
166 logger.info("Generating index file")
167
168 await generateIndex(output)
169
170 logger.success("Successfully generated index file")
171
172 logger.success(`Successfully generated ${length} icons ✨`)
173 }