images.ts
12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import { FigmaColorObject, FigmaFrameInfo, FigmaImageFormat, FigmaPositionAndSize } from '../../types/figma-types';
import { ImageNode } from './types';
import fs from 'fs';
import path from 'path';
import axios from 'axios';
import { promisePool } from '../../utils/promise-pool';
import { fetchFigmaImages } from './figma';
import { DEFAULT_DOWNLOAD_CONCURRENCY, DOWNLOAD_TIMEOUT_MS, MAX_DOWNLOAD_RETRIES, BASE_RETRY_DELAY_MS } from './constants';
import { logger } from '../../utils/logger';
/**
* Fetch images from figma document
* @param nodes - Image nodes
* @param fileId - Figma file ID
* @param token - Figma API token
* @returns Image nodes
*/
export const fetchImages = async (nodes: ImageNode[], fileId: string, token: string): Promise<ImageNode[]> => {
if (!fileId || !nodes?.length) {
return [];
}
const svgs = nodes.filter(node => node.format === FigmaImageFormat.SVG);
const pngs = nodes.filter(node => node.format === FigmaImageFormat.PNG);
const getImagePromises: Promise<{ [key: string]: string } | undefined>[] = [];
if (svgs.length > 0) {
getImagePromises.push(fetchFigmaImages(fileId, svgs.map(node => node.id).join(','), token, FigmaImageFormat.SVG));
}
if (pngs.length > 0) {
getImagePromises.push(fetchFigmaImages(fileId, pngs.map(node => node.id).join(','), token, FigmaImageFormat.PNG));
}
const images: ImageNode[] = [];
const results = await Promise.all(getImagePromises);
results.forEach((res: { [key: string]: string } | undefined) => {
if (res) {
for (const [key, value] of Object.entries(res)) {
images.push({
id: key,
name: '',
format: FigmaImageFormat.PNG,
...(nodes.find(n => n.id === key) || {}),
url: value || '',
});
}
}
});
return images;
};
/**
* Download images from figma document
* @param images - Image nodes
* @param imageDir - Output directory path
* @param concurrency - Concurrency level
* @returns Download results
*/
export const executeDownloadImages = async (
images: ImageNode[],
imageDir?: string,
concurrency: number = DEFAULT_DOWNLOAD_CONCURRENCY
): Promise<{ successCount: number; failCount: number; imageNodesMap: Map<string, ImageNode> }> => {
if (!images || !images.length || !imageDir) {
return {
successCount: 0,
failCount: 0,
imageNodesMap: new Map(),
};
}
// Process all images with dynamic concurrency control using promisePool
const results = await promisePool(images, image => createDownloadTask(image, imageDir), concurrency);
// Aggregate log after completion
const successCount = results.filter(r => r.success).length;
const failCount = results.length - successCount;
// Convert results array to Map with id as key
const imageNodesMap = new Map<string, ImageNode>(results.map(img => [img.id, img]));
return {
successCount,
failCount,
imageNodesMap,
};
};
/**
* Find image nodes in figma document
* @param nodes - Figma nodes
* @param absoluteBoundingBox - Absolute bounding box of the document
* @returns Image nodes
*/
export const findImageNodes = (nodes: FigmaFrameInfo[], absoluteBoundingBox?: FigmaPositionAndSize): ImageNode[] => {
const imageNodes: ImageNode[] = [];
if (!nodes || !Array.isArray(nodes)) {
return imageNodes;
}
for (const node of nodes) {
if (node.visible === false) {
continue;
}
// Rule 1: If node type is VECTOR, directly add to imageNodeIds
else if (node.type === 'VECTOR') {
imageNodes.push(assignImageObject(node, exportSvgIfNeeded(node, absoluteBoundingBox)));
}
// Rule 2: If node type is IMAGE or has imageRef, directly add to imageNodeIds
else if (isImageNode(node) || isImageNodeViaName(node)) {
if (isImageNode(node) || hasAnyImageNodeInDescendants(node)) {
imageNodes.push(assignImageObject(node, FigmaImageFormat.PNG));
} else {
imageNodes.push(assignImageObject(node, exportSvgIfNeeded(node, absoluteBoundingBox)));
}
} else if (isMaskNode(node)) {
imageNodes.push(assignImageObject(node, FigmaImageFormat.PNG));
}
// Rule 3: For nodes with children, check if any leaf descendant is a TEXT node with characters
else if (node.children && node.children.length > 0) {
const hasAnyTextNode = hasAnyTextNodeWithCharacters(node);
if (hasAnyTextNode) {
const firstLevelChildrenHasImageNode = node.children.some((child: FigmaFrameInfo) => isImageNode(child));
const firstLevelChildrenHasTextNode = node.children.some((child: FigmaFrameInfo) => isTextNode(child));
if (firstLevelChildrenHasImageNode && !firstLevelChildrenHasTextNode) {
imageNodes.push(assignImageObject(node, FigmaImageFormat.PNG));
} else {
const childImageIds = findImageNodes(node.children, absoluteBoundingBox);
imageNodes.push(...childImageIds);
}
} else if (hasAnyImageNodeInDescendants(node)) {
imageNodes.push(assignImageObject(node, FigmaImageFormat.PNG));
} else {
imageNodes.push(assignImageObject(node, exportSvgIfNeeded(node, absoluteBoundingBox)));
}
}
}
return imageNodes;
};
/**
* Determine whether a node should be exported as SVG or PNG
* @param node - Figma node
* @param absoluteBoundingBox - Absolute bounding box of the document
* @returns Figma image format
*/
export const exportSvgIfNeeded = (node: FigmaFrameInfo, absoluteBoundingBox?: FigmaPositionAndSize) => {
// Rule 1: Check if node is very large (likely a background) -> PNG
if (node.absoluteBoundingBox && absoluteBoundingBox) {
const { width, height } = node.absoluteBoundingBox;
const { width: pageWidth, height: pageHeight } = absoluteBoundingBox;
if (width >= pageWidth && height >= pageHeight) {
return FigmaImageFormat.PNG;
}
}
// Rule 2: Check exportSettings for explicit format specification
if (node.exportSettings && node.exportSettings.length > 0) {
const format = node.exportSettings[0].format;
if (format === FigmaImageFormat.PNG) {
return FigmaImageFormat.PNG;
}
if (format === FigmaImageFormat.SVG) {
return FigmaImageFormat.SVG;
}
}
// Rule 3: Check node name for background keywords -> PNG
if (node.name.includes('背景') || node.name.toLowerCase().includes('background')) {
return FigmaImageFormat.PNG;
}
// Default: Export as SVG
return FigmaImageFormat.SVG;
};
/** Assign image object from figma node and format **/
export const assignImageObject = (node: { id: string; name: string }, format: FigmaImageFormat) => {
return {
id: node.id,
name: node.name,
format,
};
};
/** Check if node has image ref in fills **/
export const hasImageRefInFills = (node: FigmaFrameInfo): boolean => {
if (!node || !node.fills || node.fills.length === 0) {
return false;
}
return node.fills.some((fill: FigmaColorObject) => {
const fillWithImageRef = fill;
return (fillWithImageRef.imageRef && fillWithImageRef.imageRef !== '') || fillWithImageRef.type === 'IMAGE';
});
};
/** Check if node is image node **/
export const isImageNode = (node: FigmaFrameInfo): boolean => {
if (!node) {
return false;
}
if (node.type === 'IMAGE') {
return true;
}
if (node.fills && node.fills.length > 0) {
return hasImageRefInFills(node);
}
return false;
};
/** Check if node is image node via name **/
export const isImageNodeViaName = (node: FigmaFrameInfo): boolean => {
return (node && node.name.toLowerCase().includes('img')) || node.name.toLowerCase().includes('image');
};
/** Check if node is mask node **/
export const isMaskNode = (node: FigmaFrameInfo): boolean => {
return node && node.name.toLowerCase().includes('mask');
};
/** Check if node is text node **/
export const isTextNode = (node: FigmaFrameInfo): boolean => {
return node && node.type === 'TEXT' && node.characters !== undefined && node.characters.trim() !== '';
};
/** Check if node has any image node in descendants **/
export const hasAnyImageNodeInDescendants = (node: FigmaFrameInfo): boolean => {
if (!node) return false;
if (!node.children || node.children.length === 0) {
return isImageNode(node);
}
return node.children.some((child: FigmaFrameInfo) => hasAnyImageNodeInDescendants(child));
};
/** Check if node has any text node in descendants **/
export const hasAnyTextNodeWithCharacters = (node: FigmaFrameInfo): boolean => {
if (!node) return false;
if (!node.children || node.children.length === 0) {
return isTextNode(node);
}
return node.children.some((child: FigmaFrameInfo) => hasAnyTextNodeWithCharacters(child));
};
/**
* Download an image from URL and save to local directory
* @param url - Image URL to download
* @param filename - Local filename (with extension)
* @param outputDir - Output directory path
* @returns Local file path
*/
export async function downloadImage(url: string, filename?: string, imageDir?: string, base64?: boolean): Promise<string> {
if (!url || (!base64 && (!filename || !imageDir))) {
return '';
}
const maxRetries = MAX_DOWNLOAD_RETRIES;
let lastError: unknown;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const response = await axios.get(url, {
responseType: 'arraybuffer',
timeout: DOWNLOAD_TIMEOUT_MS,
});
if (base64) {
return Buffer.from(response.data).toString('base64');
} else {
if (!imageDir || !filename) {
return '';
}
// Create directory if it doesn't exist
if (!fs.existsSync(imageDir)) {
fs.mkdirSync(imageDir, { recursive: true });
}
const filepath = path.join(imageDir, filename);
fs.writeFileSync(filepath, Buffer.from(response.data));
return filepath;
}
} catch (error) {
lastError = error;
// Don't wait on the last attempt
if (attempt < maxRetries) {
// Wait 1s, 2s, 3s, 4s, 5s
const delay = BASE_RETRY_DELAY_MS * (attempt + 1);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
const errorMessage = lastError instanceof Error ? lastError.message : String(lastError);
throw new Error(`Failed to download image from ${url} after ${maxRetries} retries: ${errorMessage}`);
}
/**
* Create download task for image
* @param image - Image object
* @param outputDir - Output directory path
* @returns Download task object
*/
export const createDownloadTask = async (image: ImageNode, imageDir?: string): Promise<ImageNode> => {
if (!image.url) {
return {
id: image.id,
name: image.name,
format: image.format,
url: image.url,
remote: image.url,
success: false,
};
}
const ext = image.format || FigmaImageFormat.PNG;
// Sanitize filename: remove special characters, replace spaces with dashes
const sanitizedName = (image.name || image.id).replace(/[^a-zA-Z0-9-_]/g, '-').toLowerCase();
const filename = `${sanitizedName}-${image.id.replace(/:/g, '-')}.${ext}`;
try {
const localPath = await downloadImage(image.url, filename, imageDir);
const normalizedImageDir = imageDir ? path.normalize(imageDir) : '';
const dirParts = normalizedImageDir.split(path.sep).filter(Boolean);
const srcIndex = dirParts.lastIndexOf('src');
const srcDir =
srcIndex >= 0 ? (normalizedImageDir.startsWith(path.sep) ? path.sep : '') + path.join(...dirParts.slice(0, srcIndex + 1)) : '';
const relativeFromSrc = srcDir ? path.relative(srcDir, localPath) : '';
const normalizedRelative = relativeFromSrc.split(path.sep).join('/');
const aliasPath = `@/${normalizedRelative}`;
return {
id: image.id,
name: image.name,
format: image.format,
url: aliasPath,
remote: image.url,
success: true,
};
} catch {
logger.printErrorLog(`Failed to download image: ${image.url}`);
return {
id: image.id,
name: image.name,
format: image.format,
url: image.url,
remote: image.url,
success: false,
};
}
};