figmaParser.ts
7.16 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
import type { FigmaNodeDSL, FigmaFill, DSLResult } from './types'
/**
* 从 Figma URL 中解析 fileKey 和 nodeId
* 支持格式:
* - https://www.figma.com/design/:fileKey/:name?node-id=xxx
* - https://www.figma.com/file/:fileKey/:name?node-id=xxx
*/
export function parseFigmaUrl(url: string): { fileKey: string; nodeId: string | null } {
const fileKeyMatch = url.match(/figma\.com\/(?:design|file)\/([^/?#]+)/)
if (!fileKeyMatch) {
throw new Error('无效的 Figma URL,无法提取 fileKey,请确认链接格式正确')
}
const fileKey = fileKeyMatch[1]
const nodeIdMatch = url.match(/node-id=([^&#]+)/)
let nodeId: string | null = null
if (nodeIdMatch) {
// Figma URL 中的 node-id 使用连字符,API 中使用冒号
nodeId = decodeURIComponent(nodeIdMatch[1]).replace(/-/g, ':')
}
return { fileKey, nodeId }
}
/**
* 调用 Figma REST API 拉取文件 JSON
*/
export async function fetchFigmaFile(
fileKey: string,
token: string,
nodeId?: string | null
): Promise<any> {
const baseUrl = 'https://api.figma.com/v1'
console.log('nodeId', nodeId)
const url = nodeId
? `${baseUrl}/files/${fileKey}/nodes?ids=${encodeURIComponent(nodeId)}`
: `${baseUrl}/files/${fileKey}`
console.log('url', url)
const res = await fetch(url, {
headers: { 'X-Figma-Token': token },
})
if (!res.ok) {
const errText = await res.text()
throw new Error(`Figma API 请求失败 (HTTP ${res.status}):${errText}`)
}
const data = await res.json()
// 若按节点维度拉取,仅保留目标节点子树,使下游逻辑保持兼容(仍然有 document 根节点)
if (nodeId) {
const nodeEntry = data.nodes?.[nodeId]
if (!nodeEntry || !nodeEntry.document) {
throw new Error(`Figma API 返回中未找到节点(nodeId: ${nodeId})`)
}
return {
name: data.name,
document: nodeEntry.document,
}
}
return data
}
/**
* 解析用于导出的截图节点 ID(与 DSL 目标节点一致)。
* 未指定 URL 中的 node-id 时,取首页第一个子节点(整帧/画板级预览)。
*/
export async function resolveScreenshotNodeId(
fileKey: string,
token: string,
nodeId: string | null,
): Promise<string> {
if (nodeId) return nodeId
const figmaData = await fetchFigmaFile(fileKey, token, null)
const node = findTargetNode(figmaData, null)
if (!node?.id) {
throw new Error('无法解析截图节点:文件中未找到可用节点')
}
return node.id
}
export type FigmaImageFormat = 'png' | 'jpg' | 'svg' | 'pdf'
/**
* GET /v1/images/:fileKey?ids=:nodeId → 节点渲染图 URL(PNG 等)
* 大图异步导出时 images[id] 可能短暂为 null,会做有限次重试。
*/
export async function fetchFigmaNodeImageUrl(
fileKey: string,
token: string,
renderNodeId: string,
options?: { format?: FigmaImageFormat; scale?: number },
): Promise<string> {
const format = options?.format ?? 'png'
const scale = options?.scale ?? 2
const baseUrl = 'https://api.figma.com/v1'
const query = new URLSearchParams({
ids: renderNodeId,
format,
scale: String(scale),
})
const url = `${baseUrl}/images/${fileKey}?${query.toString()}`
const maxAttempts = 5
const delayMs = 1200
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const res = await fetch(url, {
headers: { 'X-Figma-Token': token },
})
if (!res.ok) {
const errText = await res.text()
throw new Error(`Figma Images API 请求失败 (HTTP ${res.status}):${errText}`)
}
const data = (await res.json()) as {
err?: string | null
images?: Record<string, string | null>
}
if (data.err) {
throw new Error(`Figma Images API:${data.err}`)
}
const imageUrl = data.images?.[renderNodeId]
if (imageUrl) return imageUrl
if (attempt < maxAttempts) {
await new Promise(r => setTimeout(r, delayMs))
}
}
throw new Error('Figma 截图尚未就绪或导出失败,请稍后重试')
}
/**
* 将 Figma 原始节点转换为精简的 DSL 节点
* 去除噪声字段,保留布局/尺寸/颜色/文本/圆角等关键属性
*/
function toDSLNode(node: any): FigmaNodeDSL {
const dsl: FigmaNodeDSL = {
id: node.id,
name: node.name,
type: node.type,
}
if (node.visible === false) dsl.visible = false
// 尺寸和位置
if (node.absoluteBoundingBox) {
dsl.width = Math.round(node.absoluteBoundingBox.width)
dsl.height = Math.round(node.absoluteBoundingBox.height)
dsl.x = Math.round(node.absoluteBoundingBox.x)
dsl.y = Math.round(node.absoluteBoundingBox.y)
}
// 文本节点
if (node.type === 'TEXT') {
dsl.text = node.characters ?? ''
if (node.style) {
dsl.textStyle = {
fontFamily: node.style.fontFamily,
fontSize: node.style.fontSize,
fontWeight: node.style.fontWeight,
lineHeightPx: node.style.lineHeightPx,
textAlignHorizontal: node.style.textAlignHorizontal,
letterSpacing: node.style.letterSpacing,
}
}
}
// 填充和描边
if (node.fills?.length) dsl.fills = node.fills as FigmaFill[]
if (node.strokes?.length) dsl.strokes = node.strokes as FigmaFill[]
// 圆角
if (node.rectangleCornerRadii) {
dsl.cornerRadius = node.rectangleCornerRadii as number[]
} else if (node.cornerRadius !== undefined) {
dsl.cornerRadius = node.cornerRadius as number
}
// Auto Layout
if (node.layoutMode && node.layoutMode !== 'NONE') {
dsl.layoutMode = node.layoutMode
dsl.primaryAxisAlignItems = node.primaryAxisAlignItems
dsl.counterAxisAlignItems = node.counterAxisAlignItems
if (node.itemSpacing) dsl.itemSpacing = node.itemSpacing
const top = node.paddingTop
const right = node.paddingRight
const bottom = node.paddingBottom
const left = node.paddingLeft
if (top || right || bottom || left) {
dsl.padding = { top, right, bottom, left }
}
}
// 递归处理子节点
if (node.children?.length) {
dsl.children = node.children.map(toDSLNode)
}
return dsl
}
/**
* 深度优先搜索指定 nodeId 的节点
* 未指定 nodeId 时取首页第一个子节点
*/
function findTargetNode(figmaData: any, nodeId: string | null): any {
const document = figmaData.document
if (!nodeId) {
const firstPage = document?.children?.[0]
return firstPage?.children?.[0] ?? firstPage ?? document
}
function dfs(node: any): any {
if (!node) return null
if (node.id === nodeId) return node
if (node.children) {
for (const child of node.children) {
const found = dfs(child)
if (found) return found
}
}
return null
}
return dfs(document)
}
/**
* 构建完整 DSL 对象(包含 meta 信息)
*/
export function buildDSL(figmaData: any, fileKey: string, nodeId: string | null): DSLResult {
const targetNode = findTargetNode(figmaData, nodeId)
if (!targetNode) {
throw new Error(`未找到目标节点(nodeId: ${nodeId ?? '自动取首个节点'}),请检查节点 ID 是否正确`)
}
return {
meta: {
figmaFileKey: fileKey,
figmaNodeId: nodeId,
name: figmaData.name ?? targetNode.name,
generatedAt: new Date().toISOString(),
},
root: toDSLNode(targetNode),
}
}