utils.ts
9.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
258
259
260
261
262
263
264
265
266
267
268
269
import fs from 'fs';
import { GraphState } from '../../state';
import { logger } from '../../utils/logger';
import { callModel } from '../../utils/call-model';
import { promisePool } from '../../utils/promise-pool';
import { generateFramePrompt, generateComponentPrompt, injectRootComponentPrompt } from './prompt';
import { Protocol } from '../../types';
import { createFiles, writeFile } from '../../utils/file';
import { DEFAULT_APP_CONTENT, DEFAULT_STYLING } from './constants';
import path from 'path';
import { extractCode, extractFiles } from '../../utils/parser';
import { workspaceManager } from '../../utils/workspace';
import { CodeCache, isComponentGenerated, saveComponentGenerated, isAppInjected, saveAppInjected } from '../../utils/code-cache';
/**
* Process a node tree and generate code for all nodes
* Uses post-order traversal (children first, then parent)
*/
export async function processNode(state: GraphState, cache: CodeCache): Promise<number> {
// Read asset files list once for the entire generation run
const assetFilesList = getAssetFilesList(state);
// Flatten tree using post-order traversal (children first, then parent)
const flatNodes = flattenPostOrder(state.protocol!);
const total = flatNodes.length;
if (total === 0) {
logger.printWarnLog('No components found in structure to generate.');
return 0;
}
logger.printInfoLog(`Processing ${total} nodes...`);
let processedCount = 0;
let skippedCount = 0;
const processSingleNode = async (currentNode: Protocol) => {
const componentName = currentNode.data.name || currentNode.data.componentName || 'UnknownComponent';
const nodeId = currentNode.id;
// Check if component is already generated
if (isComponentGenerated(cache, nodeId)) {
skippedCount++;
logger.printInfoLog(`[${processedCount + skippedCount}/${total}] ⏭️ Skipping (cached): ${componentName}`);
return;
}
const progressInfo = `[${++processedCount + skippedCount}/${total}]`;
const isLeaf = !currentNode.children?.length;
if (isLeaf) {
await generateComponent(currentNode, state, assetFilesList, progressInfo);
} else {
await generateFrame(currentNode, state, assetFilesList, progressInfo);
}
// Mark component as generated and save immediately to prevent cache loss on interruption
saveComponentGenerated(cache, nodeId, state.workspace);
};
// Process nodes with concurrency control
await promisePool(flatNodes, processSingleNode);
if (skippedCount > 0) {
logger.printInfoLog(`⏭️ Skipped ${skippedCount} cached components`);
}
logger.printSuccessLog(`Generated ${processedCount} components`);
return processedCount;
}
/**
* Flatten tree into array using post-order traversal
*/
export function flattenPostOrder(node: Protocol): Protocol[] {
const result: Protocol[] = [];
function traverse(n: Protocol) {
n.children?.forEach(child => traverse(child));
result.push(n);
}
traverse(node);
return result;
}
/**
* Detect which rendering modes are used in this frame
*/
export function detectRenderingModes(node: Protocol): {
hasStates: boolean;
hasIndependentChildren: boolean;
} {
const hasStates = !!node.data.states?.length;
let hasIndependentChildren = false;
(node.children || []).forEach(child => {
if (!child.data.componentName) {
hasIndependentChildren = true;
}
});
return { hasStates, hasIndependentChildren };
}
/**
* Generate a frame/container component
* Frames compose multiple child components based on layout
*/
export async function generateFrame(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> {
const frameName = node.data.name;
logger.printInfoLog(`${progressInfo} 🖼️ Generating Frame: ${frameName}`);
// Build children imports information
const childrenImports = (node.children || []).map(child => ({
name: child.data.name || '',
path: child.data.path,
}));
// Detect rendering modes
const renderingModes = detectRenderingModes(node);
// Generate prompt
const prompt = generateFramePrompt({
frameDetails: JSON.stringify(node.data),
childrenImports: JSON.stringify(childrenImports),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
renderingModes,
});
// Call AI model
const code = await callModel({
question: prompt,
imageUrls: state.figmaInfo.thumbnail,
});
// Save generated files
const componentPath = node.data.path || '';
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath);
logger.printSuccessLog(`Successfully generated frame: ${frameName}`);
}
/**
* Generate a component (leaf or reusable)
* Components are self-contained UI elements driven by props
*/
export async function generateComponent(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> {
const componentName = node.data.componentName || node.data.name || 'UnknownComponent';
const componentPath = node.data.componentPath || node.data.path || '';
logger.printInfoLog(`${progressInfo} 📦 Generating Component: ${componentName}`);
// Generate prompt
const prompt = generateComponentPrompt({
componentName,
componentDetails: JSON.stringify(node.data),
styling: JSON.stringify(DEFAULT_STYLING),
assetFiles: assetFilesList,
});
// Call AI model
const code = await callModel({
question: prompt,
imageUrls: state.figmaInfo.thumbnail,
});
// Save generated files
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath);
logger.printSuccessLog(`Successfully generated component: ${componentName}`);
}
/**
* Helper function to save generated code (handles both single and multi-file output)
*/
export function saveGeneratedCode(code: string, filePath: string): void {
const files = extractFiles(code);
if (files.length > 0) {
// Multi-file output (e.g., index.tsx + index.module.less)
createFiles({ files, filePath });
} else {
const extractedCode = extractCode(code);
const folderPath = path.dirname(filePath);
const fileName = path.basename(filePath);
writeFile(folderPath, fileName, extractedCode);
}
}
/**
* Get list of available asset files for AI to match against
*/
function getAssetFilesList(state: GraphState) {
try {
const assetsDir = workspaceManager.resolveAppSrc(state.workspace, 'assets');
if (!fs.existsSync(assetsDir)) {
return '';
}
const files = fs.readdirSync(assetsDir);
return files.join(', ');
} catch {
return '';
}
}
/**
* Inject root component into App.tsx
* Reads existing App.tsx, adds import and renders the root component
*/
export async function injectRootComponentToApp(state: GraphState, cache: CodeCache): Promise<void> {
try {
// Check if already injected
if (isAppInjected(cache)) {
logger.printInfoLog('⏭️ Skipping App.tsx injection (already injected)');
return;
}
logger.printInfoLog('💉 Injecting root component into App.tsx...');
// Construct App.tsx path
const appTsxPath = workspaceManager.resolveAppSrc(state.workspace, 'App.tsx');
// Read existing App.tsx or use default template
let appContent: string;
try {
appContent = fs.readFileSync(appTsxPath, 'utf8');
} catch {
// Use default template if App.tsx doesn't exist
logger.printWarnLog('App.tsx not found, using default template');
appContent = DEFAULT_APP_CONTENT;
}
// Get root component information
const rootNode = state.protocol!;
const componentName = rootNode.data.name || 'RootComponent';
const componentPath = rootNode.data.path || '';
// Generate prompt
const prompt = injectRootComponentPrompt({
appContent,
componentName,
componentPath,
});
// Call AI model
const updatedCode = await callModel({
question: prompt,
});
// Extract code (no markdown blocks expected based on prompt requirements)
const finalCode = updatedCode.includes('```') ? extractCode(updatedCode) : updatedCode.trim();
// Write updated App.tsx
const appFolderPath = path.dirname(appTsxPath);
writeFile(appFolderPath, 'App.tsx', finalCode);
// Mark as injected and save immediately
saveAppInjected(cache, state.workspace);
logger.printSuccessLog(`Successfully injected ${componentName} into App.tsx`);
} catch (error) {
logger.printErrorLog(`Failed to inject root component: ${(error as Error).message}`);
// Don't throw - allow the process to continue even if injection fails
}
}