index.ts
3.04 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
import type { FigmaFrameInfo } from '../../../types/figma-types';
import type { Protocol } from '../../../types';
import { callModel } from '../../../utils/call-model';
import { logger } from '../../../utils/logger';
import { generateStructurePrompt } from './prompt';
import { extractNodePositionsHierarchical, postProcessStructure, populateComponentProps } from './utils';
import { extractJSON } from '../../../utils/parser';
/**
* Structure node - generates component hierarchy from Figma design
*
* Responsibilities:
* 1. Analyzes Figma frame structure using AI model
* 2. Extracts component relationships and data
* 3. Generates file paths and naming conventions
* 4. Populates component props and states for code generation
*
* @param state - Current graph state
* @returns Updated state with protocol
*/
export const generateStructure = async (figma: FigmaFrameInfo) => {
const frames = figma.frames || figma.children;
const imageWidth = figma.absoluteBoundingBox?.width;
const thumbnailUrl = figma.thumbnailUrl;
if (!frames || frames.length === 0) {
logger.printErrorLog('未找到已处理的界面帧(state 为空)');
throw new Error('No processed frames found');
}
logger.reportPhase('结构识别', 35);
logger.printInfoLog('正在分析界面结构…');
try {
// Extract hierarchical position data from Figma frames
const positions = extractNodePositionsHierarchical(frames);
const positionsJson = JSON.stringify(positions);
// Generate structure using AI
const prompt = generateStructurePrompt({
positions: positionsJson,
width: imageWidth ? String(imageWidth) : '1440',
});
logger.printInfoLog('正在调用模型生成组件结构…');
const structureResult = await callModel({
question: prompt,
imageUrls: thumbnailUrl,
responseFormat: { type: 'json_object' },
maxTokens: 20240,
});
// Parse AI response
const jsonContent = extractJSON(structureResult);
const parsedStructure = JSON.parse(jsonContent) as Protocol | Protocol[];
// Post-process structure: normalize names, populate elements, annotate paths
logger.printInfoLog('正在处理结构树…');
postProcessStructure(parsedStructure, frames);
const protocol = (Array.isArray(parsedStructure) ? parsedStructure[0] : parsedStructure) as Protocol;
// Extract component props and states for reusable components
if (frames && protocol) {
logger.printInfoLog('正在提取组件属性与状态…');
await populateComponentProps(protocol, frames, thumbnailUrl);
}
logger.printSuccessLog('组件结构已生成');
return protocol;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
logger.printErrorLog(`生成组件结构时出错:${errorMessage}`);
throw new Error(`Failed to parse component structure: ${errorMessage}`);
}
};