figma-client.mjs
24.4 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
/**
* Figma MCP 客户端
*
* 默认通过 `figma-developer-mcp` npm 模块的 stdio server 获取设计上下文、
* 截图和变量定义。若显式设置 FIGMA_MCP_TRANSPORT=http,则退回到本地
* Figma Desktop MCP 的 Streamable HTTP 服务。
* 默认命令会执行 `pnpm --dir scripts/mcp-bridge exec tmegit-figma-developer-mcp --stdio`,
* 因此前提是 `scripts/mcp-bridge/package.json` 已安装该依赖。
*/
const DEFAULT_TRANSPORT = process.env.FIGMA_MCP_TRANSPORT || "stdio";
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
const MCP_BRIDGE_DIR = MODULE_DIR;
const DEFAULT_SERVER_COMMAND = process.env.FIGMA_DEVELOPER_MCP_COMMAND || "pnpm";
const DEFAULT_SERVER_BIN = process.env.FIGMA_DEVELOPER_MCP_BIN || "tmegit-figma-developer-mcp";
const DEFAULT_SERVER_PACKAGE = process.env.FIGMA_DEVELOPER_MCP_PACKAGE || "@tmegit/figma-developer-mcp";
const DEFAULT_UPSTREAM_URL = process.env.FIGMA_DESKTOP_MCP_URL || "http://127.0.0.1:3845/mcp";
let clientPromise = null;
let toolNameCache = null;
function getFigmaApiKey() {
return process.env.FIGMA_DEVELOPER_MCP_API_KEY || process.env.FIGMA_API_KEY || "";
}
function getDefaultCommandArgs() {
return ["--dir", MCP_BRIDGE_DIR, "exec", DEFAULT_SERVER_BIN, "--stdio"];
}
function parseArgString(rawArgs) {
if (!rawArgs) {
return getDefaultCommandArgs();
}
const trimmed = rawArgs.trim();
if (!trimmed) {
return getDefaultCommandArgs();
}
if (trimmed.startsWith("[")) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
return parsed;
}
} catch {
// ignore and fallback to whitespace split
}
}
return trimmed.split(/\s+/u).filter(Boolean);
}
function createTransport(options = {}) {
const transportMode = options.transport || DEFAULT_TRANSPORT;
if (transportMode === "http") {
const upstreamUrl = options.upstreamUrl || DEFAULT_UPSTREAM_URL;
return new StreamableHTTPClientTransport(new URL(upstreamUrl));
}
const command = options.command || DEFAULT_SERVER_COMMAND;
const args = options.commandArgs || parseArgString(process.env.FIGMA_DEVELOPER_MCP_ARGS || "");
const env = { ...process.env };
if (process.env.FIGMA_DEVELOPER_MCP_API_KEY && !env.FIGMA_API_KEY) {
env.FIGMA_API_KEY = process.env.FIGMA_DEVELOPER_MCP_API_KEY;
}
return new StdioClientTransport({
command,
args,
env,
stderr: "pipe",
});
}
// ── URL 解析 ──
function normalizeNodeId(nodeId) {
return nodeId ? String(nodeId).replaceAll("-", ":") : undefined;
}
export function parseFigmaUrl(figmaUrl) {
if (!figmaUrl) {
return {};
}
const url = new URL(figmaUrl);
const fileKeyMatch = url.pathname.match(/\/design\/([^/]+)/);
return {
fileKey: fileKeyMatch?.[1],
nodeId: normalizeNodeId(url.searchParams.get("node-id") || undefined),
};
}
// ── Tool 调用 ──
function isToolNotFoundError(error) {
return /上游 MCP 未找到工具|Tool not found|tools?\/call/i.test(error?.message || "");
}
async function resolveToolName(upstreamUrl, candidates) {
if (!toolNameCache) {
const client = await ensureClient({ upstreamUrl });
const result = await client.listTools();
toolNameCache = new Map((result.tools || []).map((tool) => [tool.name, tool.name]));
}
for (const candidate of candidates) {
if (toolNameCache.has(candidate)) {
return toolNameCache.get(candidate);
}
}
for (const candidate of candidates) {
for (const toolName of toolNameCache.keys()) {
if (toolName.endsWith(candidate)) {
return toolName;
}
}
}
throw new Error(`上游 MCP 未找到工具: ${candidates.join(", ")}`);
}
async function callUpstreamTool(upstreamUrl, candidates, args) {
const client = await ensureClient({ upstreamUrl });
const toolName = await resolveToolName(upstreamUrl, candidates);
return client.callTool({
name: toolName,
arguments: args,
});
}
async function ensureClient(options = {}) {
if (!clientPromise) {
clientPromise = (async () => {
const client = new Client({
name: "venus-figma-client",
version: "0.1.0",
});
const transport = createTransport(options);
await client.connect(transport);
return client;
})();
}
return clientPromise;
}
// ── 响应解析 ──
/**
* 从 MCP tool 响应中提取 HTML 文本内容
* @param {object} mcpResult - MCP tool call result
* @returns {string} Extracted HTML text
*/
export function extractHtmlFromMcpResponse(mcpResult) {
if (typeof mcpResult === "string") {
return mcpResult;
}
if (Array.isArray(mcpResult?.content)) {
const textParts = [];
for (const item of mcpResult.content) {
if (item.type === "text" && typeof item.text === "string") {
textParts.push(item.text);
continue;
}
textParts.push(JSON.stringify(item, null, 2));
}
return textParts.join("\n");
}
if (mcpResult?.structuredContent) {
return JSON.stringify(mcpResult.structuredContent, null, 2);
}
if (mcpResult && typeof mcpResult === "object") {
return JSON.stringify(mcpResult, null, 2);
}
return "";
}
function bufferToBase64(buffer) {
return Buffer.from(buffer).toString("base64");
}
async function fetchRemoteImageAsBase64(imageUrl) {
const response = await fetch(imageUrl, {
headers: {
connection: "close",
},
});
if (!response.ok) {
throw new Error(`截图资源下载失败: ${response.status} ${response.statusText}`);
}
const contentType = response.headers.get("content-type") || "image/png";
const arrayBuffer = await response.arrayBuffer();
return {
mimeType: contentType,
base64: bufferToBase64(arrayBuffer),
};
}
function extractImageUrlFromMcpResponse(mcpResult) {
if (Array.isArray(mcpResult?.content)) {
for (const item of mcpResult.content) {
if (item.type === "image" && typeof item.data === "string") {
return {
mimeType: item.mimeType || "image/png",
base64: item.data,
};
}
if (item.type === "resource_link" && typeof item.uri === "string") {
return {
url: item.uri,
};
}
if (item.type === "text" && typeof item.text === "string") {
const urlMatch = item.text.match(/https?:\/\/\S+/u);
if (urlMatch) {
return {
url: urlMatch[0],
};
}
}
}
}
if (mcpResult?.structuredContent && typeof mcpResult.structuredContent === "object") {
const candidates = [
mcpResult.structuredContent.imageUrl,
mcpResult.structuredContent.url,
mcpResult.structuredContent.image?.url,
].filter(Boolean);
if (candidates.length > 0) {
return {
url: candidates[0],
};
}
}
return null;
}
async function fetchRenderedNodeScreenshot({ fileKey, nodeId, scale = 1 }) {
const figmaApiKey = getFigmaApiKey();
if (!figmaApiKey) {
throw new Error("当前未配置 FIGMA_API_KEY,无法通过 Figma Images API 获取截图");
}
const endpoint = new URL(`https://api.figma.com/v1/images/${fileKey}`);
endpoint.searchParams.set("ids", nodeId);
endpoint.searchParams.set("format", "png");
endpoint.searchParams.set("scale", String(scale));
endpoint.searchParams.set("use_absolute_bounds", "true");
const response = await fetch(endpoint, {
headers: {
"x-figma-token": figmaApiKey,
connection: "close",
},
});
if (!response.ok) {
const errorText = (await response.text()).trim();
const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
throw new Error(`Figma Images API 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
const imageUrl = payload?.images?.[nodeId];
if (!imageUrl) {
throw new Error("Figma Images API 未返回当前 node 的截图地址");
}
const imagePayload = await fetchRemoteImageAsBase64(imageUrl);
return {
source: "figma-rest-image-render",
fileKey,
nodeId,
imageUrl,
...imagePayload,
};
}
// ── Public API ──
/**
* 获取 Figma 设计上下文(HTML 结构)
* @param {string} figmaUrl - Figma design URL with node-id parameter
* @param {object} [options] - Optional overrides
* @returns {Promise<string>} HTML design context string
*/
export async function fetchDesignContext(figmaUrl, options = {}) {
const upstreamUrl = options.upstreamUrl || DEFAULT_UPSTREAM_URL;
const { fileKey: fromUrl, nodeId: nodeFromUrl } = parseFigmaUrl(figmaUrl);
const fileKey = options.fileKey || fromUrl;
const nodeId = normalizeNodeId(options.nodeId || nodeFromUrl);
if (!nodeId) {
throw new Error("缺少 nodeId,或 figmaUrl 中没有 node-id。");
}
const candidateSets = [["get_figma_design"], ["get_design_context", "figma_get_design_context"]];
let mcpResult = null;
for (const candidates of candidateSets) {
try {
mcpResult = await callUpstreamTool(upstreamUrl, candidates, {
fileKey,
nodeId,
clientLanguages: "html",
clientFrameworks: "vue",
});
break;
} catch (error) {
if (!isToolNotFoundError(error)) {
throw error;
}
}
}
if (!mcpResult) {
throw new Error("上游 MCP 未提供可用于设计上下文的工具。");
}
return extractHtmlFromMcpResponse(mcpResult);
}
/**
* 获取 Figma 截图(base64 图片)
* @param {string} figmaUrl - Figma design URL with node-id parameter
* @param {object} [options] - Optional overrides
* @returns {Promise<object>} MCP tool call result with screenshot data
*/
export async function fetchScreenshot(figmaUrl, options = {}) {
const upstreamUrl = options.upstreamUrl || DEFAULT_UPSTREAM_URL;
const { fileKey: fromUrl, nodeId: nodeFromUrl } = parseFigmaUrl(figmaUrl);
const fileKey = options.fileKey || fromUrl;
const nodeId = normalizeNodeId(options.nodeId || nodeFromUrl);
if (!nodeId) {
throw new Error("缺少 nodeId,或 figmaUrl 中没有 node-id。");
}
try {
const mcpResult = await callUpstreamTool(upstreamUrl, ["get_screenshot", "figma_get_screenshot"], {
fileKey,
nodeId,
contentsOnly: options.contentsOnly ?? true,
});
const extracted = extractImageUrlFromMcpResponse(mcpResult);
if (extracted?.base64) {
return {
source: "mcp-screenshot-tool",
fileKey,
nodeId,
mimeType: extracted.mimeType || "image/png",
base64: extracted.base64,
};
}
if (extracted?.url) {
const imagePayload = await fetchRemoteImageAsBase64(extracted.url);
return {
source: "mcp-screenshot-tool",
fileKey,
nodeId,
imageUrl: extracted.url,
...imagePayload,
};
}
} catch (error) {
if (!isToolNotFoundError(error)) {
throw error;
}
}
return fetchRenderedNodeScreenshot({
fileKey,
nodeId,
scale: options.scale || 1,
});
}
/**
* 获取 Figma 变量定义
* @param {string} figmaUrl - Figma design URL with node-id parameter
* @param {object} [options] - Optional overrides
* @returns {Promise<object>} MCP tool call result with variable definitions
*/
export async function fetchVariableDefs(figmaUrl, options = {}) {
const upstreamUrl = options.upstreamUrl || DEFAULT_UPSTREAM_URL;
const { fileKey: fromUrl, nodeId: nodeFromUrl } = parseFigmaUrl(figmaUrl);
const fileKey = options.fileKey || fromUrl;
const nodeId = normalizeNodeId(options.nodeId || nodeFromUrl);
if (!nodeId) {
throw new Error("缺少 nodeId,或 figmaUrl 中没有 node-id。");
}
try {
return await callUpstreamTool(upstreamUrl, ["get_variable_defs", "figma_get_variable_defs"], {
fileKey,
nodeId,
clientLanguages: "css",
});
} catch (error) {
if (!isToolNotFoundError(error)) {
throw error;
}
return {
unsupported: true,
reason: "当前 figma-developer-mcp 版本未提供 get_variable_defs 工具",
fileKey,
nodeId,
};
}
}
/**
* 获取 Figma 节点的原始详情(含坐标、布局、样式等完整数据)
* 调用 Figma REST API: GET /v1/files/:file_key/nodes?ids=:node_id
*
* @param {string} figmaUrl - Figma design URL
* @param {object} [options] - Optional overrides
* @returns {Promise<object>} 节点详情数据
*/
export async function fetchNodeDetails(figmaUrl, options = {}) {
const { fileKey: fromUrl, nodeId: nodeFromUrl } = parseFigmaUrl(figmaUrl);
const fileKey = options.fileKey || fromUrl;
const nodeId = normalizeNodeId(options.nodeId || nodeFromUrl);
if (!fileKey || !nodeId) {
throw new Error("缺少 fileKey 或 nodeId");
}
const figmaApiKey = getFigmaApiKey();
if (!figmaApiKey) {
throw new Error("当前未配置 FIGMA_API_KEY,无法通过 Figma REST API 获取节点详情");
}
const endpoint = new URL(`https://api.figma.com/v1/files/${fileKey}/nodes`);
endpoint.searchParams.set("ids", nodeId);
endpoint.searchParams.set("depth", String(options.depth || 10));
const response = await fetch(endpoint, {
headers: {
"x-figma-token": figmaApiKey,
connection: "close",
},
});
if (!response.ok) {
const errorText = (await response.text()).trim();
const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
throw new Error(`Figma REST API 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
const nodeData = payload?.nodes?.[nodeId];
if (!nodeData) {
throw new Error(`Figma REST API 未返回节点 ${nodeId} 的数据`);
}
return nodeData;
}
/**
* 从 Figma 节点树中提取语义化布局摘要
* 不是简单导出原始坐标,而是:
* 1. 过滤噪音节点(蒙版、纯装饰矩形等)
* 2. 收集文本内容,让 AI 知道每个区域是什么
* 3. 计算相对位置(相对于父节点/根节点)
* 4. 按 Y 轴分段,自动检测垂直区域
* 5. 检测布局模式(grid/flex 等)
*
* @param {object} nodeData - Figma 节点数据(fetchNodeDetails 返回的 nodeData)
* @param {number} [maxDepth] - 最大递归深度
* @returns {object} 语义化布局摘要
*/
export function extractLayoutInfo(nodeData, maxDepth = 8) {
const doc = nodeData?.document;
if (!doc) {
return { sections: [], textNodes: [], summary: "无节点数据" };
}
const rootBounds = doc.absoluteBoundingBox;
const rootX = rootBounds?.x || 0;
const rootY = rootBounds?.y || 0;
const rootW = rootBounds?.width || 0;
const rootH = rootBounds?.height || 0;
// 1. 收集所有有意义的节点(含文本、坐标、层级)
const allNodes = [];
const textNodes = [];
collectSemanticNodes(doc, allNodes, textNodes, 0, maxDepth, rootX, rootY);
// 2. 按 Y 坐标分段(检测垂直方向的区域划分)
const sections = detectVerticalSections(allNodes, rootH);
// 3. 检测底部固定栏(Y 坐标接近底部的区域)
const bottomBar = detectBottomFixedBar(allNodes, rootH, rootW);
// 4. 检测重复模式(grid/list)
const patterns = detectRepeatPatterns(allNodes);
return {
rootName: doc.name || "",
rootSize: { width: Math.round(rootW), height: Math.round(rootH) },
sections,
bottomBar,
patterns,
textNodes: textNodes.slice(0, 60), // 限制文本节点数量
totalSemanticNodes: allNodes.length,
};
}
// 噪音节点名称(设计装饰元素,不含语义信息)
const NOISE_NAMES = new Set(["Ellipse", "Line", "Mask", "Rectangle", "Vector", "矩形", "蒙版"]);
// 噪音节点类型
const NOISE_TYPES = new Set(["BOOLEAN_OPERATION", "ELLIPSE", "LINE", "POLYGON", "STAR", "VECTOR"]);
/**
* Figma primaryAxisAlignItems → CSS justify-content
*/
function mapFigmaAlign(align) {
switch (align) {
case "CENTER": { return "center";
}
case "MAX": { return "flex-end";
}
case "MIN": { return "flex-start";
}
case "SPACE_BETWEEN": { return "space-between";
}
default: { return "flex-start";
}
}
}
/**
* Figma counterAxisAlignItems → CSS align-items
*/
function mapFigmaCrossAlign(align) {
switch (align) {
case "BASELINE": { return "baseline";
}
case "CENTER": { return "center";
}
case "MAX": { return "flex-end";
}
case "MIN": { return "flex-start";
}
default: { return "flex-start";
}
}
}
function collectSemanticNodes(figmaNode, allNodes, textNodes, depth, maxDepth, rootX, rootY) {
if (depth > maxDepth || !figmaNode) return;
const type = figmaNode.type;
const name = figmaNode.name || "";
const bounds = figmaNode.absoluteBoundingBox;
// 收集文本节点
if (type === "TEXT" && figmaNode.characters) {
const text = figmaNode.characters.trim();
if (text && text.length <= 100) {
textNodes.push({
text,
x: Math.round((bounds?.x || 0) - rootX),
y: Math.round((bounds?.y || 0) - rootY),
w: Math.round(bounds?.width || 0),
h: Math.round(bounds?.height || 0),
fontSize: figmaNode.style?.fontSize,
});
}
}
// 跳过噪音节点(但要递归子节点,因为 GROUP 里可能有 TEXT)
const isNoise = NOISE_TYPES.has(type) || (NOISE_NAMES.has(name) && !hasTextChildren(figmaNode));
if (!isNoise && bounds) {
const relX = Math.round(bounds.x - rootX);
const relY = Math.round(bounds.y - rootY);
const w = Math.round(bounds.width);
const h = Math.round(bounds.height);
// 只保留有实际尺寸且不是纯装饰的节点
if (w > 5 && h > 5) {
const info = {
depth,
type,
name,
x: relX,
y: relY,
w,
h,
};
// Auto Layout (直接映射到 CSS Flexbox)
if (figmaNode.layoutMode) {
info.layout = figmaNode.layoutMode;
info.gap = figmaNode.itemSpacing;
info.padding = {
t: figmaNode.paddingTop || 0,
r: figmaNode.paddingRight || 0,
b: figmaNode.paddingBottom || 0,
l: figmaNode.paddingLeft || 0,
};
info.align = figmaNode.primaryAxisAlignItems;
info.crossAlign = figmaNode.counterAxisAlignItems;
// CSS Flexbox 映射提示
info.cssFlex = {
display: "flex",
flexDirection: figmaNode.layoutMode === "HORIZONTAL" ? "row" : "column",
gap: `${figmaNode.itemSpacing || 0}px`,
justifyContent: mapFigmaAlign(figmaNode.primaryAxisAlignItems),
alignItems: mapFigmaCrossAlign(figmaNode.counterAxisAlignItems),
};
}
// Figma Component Instance 语义信息
if (type === "INSTANCE" || type === "COMPONENT") {
info.componentId = figmaNode.componentId || "";
info.componentName = figmaNode.name || "";
if (figmaNode.componentProperties) {
info.componentProperties = {};
for (const [key, prop] of Object.entries(figmaNode.componentProperties)) {
if (prop.value !== undefined) {
info.componentProperties[key] = prop.value;
}
}
}
}
// 收集直接子文本
const directTexts = collectDirectTexts(figmaNode);
if (directTexts.length > 0) {
info.texts = directTexts;
}
allNodes.push(info);
}
}
// 递归子节点
if (Array.isArray(figmaNode.children)) {
for (const child of figmaNode.children) {
collectSemanticNodes(child, allNodes, textNodes, depth + 1, maxDepth, rootX, rootY);
}
}
}
function hasTextChildren(figmaNode) {
if (!figmaNode.children) return false;
for (const child of figmaNode.children) {
if (child.type === "TEXT" && child.characters?.trim()) return true;
if (hasTextChildren(child)) return true;
}
return false;
}
function collectDirectTexts(figmaNode) {
const texts = [];
if (!figmaNode.children) return texts;
for (const child of figmaNode.children) {
if (child.type === "TEXT" && child.characters?.trim()) {
const t = child.characters.trim();
if (t.length <= 50) texts.push(t);
}
// 只深入一层 GROUP
if (child.type === "GROUP" && child.children) {
for (const grandChild of child.children) {
if (grandChild.type === "TEXT" && grandChild.characters?.trim()) {
const t = grandChild.characters.trim();
if (t.length <= 50) texts.push(t);
}
}
}
}
return texts.slice(0, 5); // 最多 5 个文本
}
/**
* 按 Y 坐标分段:将节点按垂直位置聚类为若干 section
*/
function detectVerticalSections(nodes, rootHeight) {
if (nodes.length === 0) return [];
// 只取 depth <= 2 的节点作为 section 候选
const topLevel = nodes.filter((n) => n.depth <= 2 && n.h > 30);
if (topLevel.length === 0) return [];
// 按 Y 排序
topLevel.sort((a, b) => a.y - b.y);
// 合并重叠/相邻的节点为 section
const sections = [];
for (const node of topLevel) {
// 跳过根节点自身
if (node.depth === 0) continue;
const section = {
name: node.name,
type: node.type,
y: node.y,
height: node.h,
width: node.w,
texts: node.texts || [],
};
if (node.layout) {
section.layout = node.layout;
section.gap = node.gap;
section.padding = node.padding;
}
sections.push(section);
}
return sections.slice(0, 20);
}
/**
* 检测底部固定栏:Y 坐标接近页面底部、宽度接近页面宽度的区域
*/
function detectBottomFixedBar(nodes, rootHeight, rootWidth) {
// 查找 Y + H 接近 rootHeight 且 W 接近 rootWidth 的节点
const candidates = nodes.filter((n) => {
const bottomEdge = n.y + n.h;
const isNearBottom = bottomEdge >= rootHeight - 100;
const isFullWidth = n.w >= rootWidth * 0.8;
return isNearBottom && isFullWidth && n.h < 120;
});
if (candidates.length === 0) return null;
// 取最底部的
candidates.sort((a, b) => (b.y + b.h) - (a.y + a.h));
const bar = candidates[0];
return {
name: bar.name,
y: bar.y,
height: bar.h,
width: bar.w,
texts: bar.texts || [],
};
}
/**
* 检测重复模式:同一父节点下多个相似尺寸的子节点 → grid/list
*/
function detectRepeatPatterns(nodes) {
const patterns = [];
// 按 depth 分组,找同一层级下尺寸相似的节点
const byDepth = {};
for (const node of nodes) {
if (!byDepth[node.depth]) byDepth[node.depth] = [];
byDepth[node.depth].push(node);
}
for (const [depth, siblings] of Object.entries(byDepth)) {
if (siblings.length < 3) continue;
// 按宽度聚类
const widthGroups = clusterByValue(siblings, (n) => n.w, 20);
for (const group of widthGroups) {
if (group.length < 3) continue;
// 按 Y 排序,检查间距是否一致
group.sort((a, b) => a.y - b.y);
const gaps = [];
for (let i = 1; i < group.length; i++) {
gaps.push(group[i].y - (group[i - 1].y + group[i - 1].h));
}
const avgGap = gaps.length > 0 ? Math.round(gaps.reduce((a, b) => a + b, 0) / gaps.length) : 0;
const gapVariance = gaps.length > 0
? Math.round(Math.sqrt(gaps.reduce((sum, g) => sum + (g - avgGap) ** 2, 0) / gaps.length))
: 0;
// 间距一致(方差 < 5px)→ 检测为重复模式
if (gapVariance < 5 && avgGap >= 0) {
patterns.push({
type: "vertical-list",
count: group.length,
itemWidth: Math.round(group[0].w),
itemHeight: Math.round(group[0].h),
gap: avgGap,
startY: group[0].y,
sampleTexts: group.slice(0, 3).map((n) => n.texts?.[0] || n.name),
});
}
}
// 按高度聚类,检查水平排列
const heightGroups = clusterByValue(siblings, (n) => n.h, 10);
for (const group of heightGroups) {
if (group.length < 3) continue;
group.sort((a, b) => a.x - b.x);
const gaps = [];
for (let i = 1; i < group.length; i++) {
gaps.push(group[i].x - (group[i - 1].x + group[i - 1].w));
}
const avgGap = gaps.length > 0 ? Math.round(gaps.reduce((a, b) => a + b, 0) / gaps.length) : 0;
const gapVariance = gaps.length > 0
? Math.round(Math.sqrt(gaps.reduce((sum, g) => sum + (g - avgGap) ** 2, 0) / gaps.length))
: 0;
if (gapVariance < 5 && avgGap >= 0) {
patterns.push({
type: "horizontal-row",
count: group.length,
itemWidth: Math.round(group[0].w),
itemHeight: Math.round(group[0].h),
gap: avgGap,
startX: group[0].x,
sampleTexts: group.slice(0, 3).map((n) => n.texts?.[0] || n.name),
});
}
}
}
return patterns.slice(0, 10);
}
function clusterByValue(items, getValueFn, tolerance) {
const sorted = [...items].sort((a, b) => getValueFn(a) - getValueFn(b));
const clusters = [];
let current = [sorted[0]];
for (let i = 1; i < sorted.length; i++) {
if (Math.abs(getValueFn(sorted[i]) - getValueFn(current[0])) <= tolerance) {
current.push(sorted[i]);
} else {
if (current.length > 0) clusters.push(current);
current = [sorted[i]];
}
}
if (current.length > 0) clusters.push(current);
return clusters;
}
/**
* 检测 Figma Desktop MCP 是否可达
* @param {object} [options] - Optional overrides
* @returns {Promise<boolean>} Whether the MCP server is reachable
*/
export async function isMcpAvailable(options = {}) {
try {
const client = await ensureClient(options);
const result = await client.listTools();
return Boolean(result?.tools);
} catch {
return false;
}
}
/**
* 重置内部缓存(用于测试或长时间运行后刷新)
*/
export function resetCache() {
toolNameCache = null;
clientPromise = null;
}