-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProjectFolderStructure.js
471 lines (413 loc) · 17.6 KB
/
ProjectFolderStructure.js
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
import React, { useState, useEffect } from 'react';
import { FaFolder, FaFolderOpen, FaFile } from 'react-icons/fa';
import { MdCircle } from 'react-icons/md';
import { generateNormalReactPage, generateSQLDatabaseQuery, generateServerlessApi } from '../utils/api';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import axios from 'axios';
const extractEnvVariables = (code) => {
const regex = /process\.env\.([A-Z_]+)|const\s*{\s*([^}]+)\s*}\s*=\s*process\.env/g;
const matches = new Set();
let match;
while ((match = regex.exec(code)) !== null) {
// Match for process.env.VAR_NAME
if (match[1]) {
matches.add(match[1]);
}
// Match for destructuring: const { var1, var2 } = process.env
if (match[2]) {
const vars = match[2].split(',').map(variable => variable.trim());
vars.forEach(variable => matches.add(variable));
}
}
return Array.from(matches);
};
const ProjectFolderStructure = ({ structure, projectData, sqlCode, droppedComponents, dropAreaHeight }) => {
const [openNodes, setOpenNodes] = useState({});
const [visibleCode, setVisibleCode] = useState({});
const [deploying, setDeploying] = useState(false);
const [deployError, setDeployError] = useState(null);
const [projectName, setProjectName] = useState('');
const [requiredEnvVars, setRequiredEnvVars] = useState([]);
const [envVariables, setEnvVariables] = useState({});
const [keys, setKeys] = useState({
SUPABASE_DB_URL: '',
VERCEL_TOKEN: ''
});
useEffect(() => {
const extractRequiredEnvVars = () => {
const allEnvVars = new Set();
const traverseStructure = (node) => {
if (node.content) {
const envVars = extractEnvVariables(node.content);
envVars.forEach((envVar) => allEnvVars.add(envVar));
}
if (node.children && node.children.length > 0) {
node.children.forEach(traverseStructure);
}
};
traverseStructure(structure);
setRequiredEnvVars(Array.from(allEnvVars));
};
extractRequiredEnvVars();
}, [structure]);
const toggleOpen = (nodeName) => {
setOpenNodes((prev) => ({
...prev,
[nodeName]: !prev[nodeName],
}));
};
const toggleCodeVisibility = (nodeName) => {
setVisibleCode((prev) => ({
...prev,
[nodeName]: !prev[nodeName],
}));
};
const regeneratePageContent = async (node, path) => {
try {
let newContent;
const jsconfigFile = structure.children.find((child) => child.name === 'jsconfig.json');
const jsconfig = jsconfigFile ? JSON.parse(jsconfigFile.content) : {};
if (path.includes('/api')) {
// Handle API regeneration (if applicable)
} else if (path.includes('/pages')) {
const pageName = node.originalName || node.name;
const pageComponents = droppedComponents[pageName] || [];
if (pageComponents.length > 0) {
// Generate import statements
const componentImports = pageComponents
.map(
(component) =>
`import ${component.name} from '../components/${component.name}';`
)
.join('\n');
// Generate JSX code for components
const componentJSX = pageComponents
.map((component) => {
const { position, dimensions } = component;
const { x, y } = position;
const { width, height } = dimensions;
return `
<div style={{
position: 'absolute',
left: ${x}px,
top: ${y}px,
width: ${width}px,
height: ${height}px
}}>
<${component.name} />
</div>
`;
})
.join('\n');
// Build the page content
newContent = `
import React from 'react';
${componentImports}
export default function ${node.name}() {
return (
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
${componentJSX}
</div>
);
}
`;
} else {
newContent = `
import React from 'react';
export default function ${node.name}() {
return (
<div>
<p>This page has no components.</p>
</div>
);
}
`;
}
// Update the node's content
node.children.find(child => child.name === 'index.js').content = newContent;
}
toggleCodeVisibility(`${path}/${node.name}`);
} catch (error) {
console.error(`Error regenerating content for ${node.name}:`, error);
node.content = '// Error regenerating content';
}
};
const allChildrenHaveContent = (children) => {
return children.every((child) => {
if (child.children && child.children.length > 0) {
return allChildrenHaveContent(child.children);
}
return child.content && typeof child.content === 'string' && child.content.trim().length > 0;
});
};
const renderStructure = (node, path = '') => {
if (!node) return null;
const nodePath = `${path}/${node.name}`;
const isOpen = openNodes[nodePath];
const hasChildren = node.children && node.children.length > 0;
const isContentFilled = typeof node.content === 'string' && node.content.trim().length > 0;
const isCodeVisible = visibleCode[nodePath];
const folderIsGreen = hasChildren && allChildrenHaveContent(node.children);
return (
<ul style={{ listStyleType: 'none', paddingLeft: '20px' }}>
<li>
<div
style={{ display: 'flex', alignItems: 'center', cursor: hasChildren ? 'pointer' : 'default' }}
onClick={() => hasChildren && toggleOpen(nodePath)}
>
{hasChildren ? (
isOpen ? (
<FaFolderOpen
style={{ marginRight: '8px', color: folderIsGreen ? 'green' : 'inherit' }}
/>
) : (
<FaFolder style={{ marginRight: '8px', color: folderIsGreen ? 'green' : 'inherit' }} />
)
) : (
<FaFile style={{ marginRight: '8px' }} />
)}
{node.name}
<MdCircle
style={{ marginLeft: '8px', color: isContentFilled || folderIsGreen ? 'green' : 'red' }}
size={12}
/>
{!hasChildren && (
<button
style={{ marginLeft: '8px' }}
onClick={(e) => {
e.stopPropagation();
regeneratePageContent(node, path);
}}
className="btn py-1 px-2 bg-red-500 text-white rounded"
>
Regenerate
</button>
)}
{!hasChildren && isContentFilled && (
<button
style={{ marginLeft: '8px' }}
onClick={(e) => {
e.stopPropagation();
toggleCodeVisibility(nodePath);
}}
className="btn py-1 px-2 bg-blue-500 text-white rounded"
>
{isCodeVisible ? 'Hide Code' : 'Show Code'}
</button>
)}
</div>
{isOpen && hasChildren && (
<div style={{ marginLeft: '20px' }}>
{node.children.map((child, index) => (
<div key={index}>{renderStructure(child, nodePath)}</div>
))}
</div>
)}
{isCodeVisible && node.content && (
<pre
style={{
marginLeft: '20px',
backgroundColor: '#f5f5f5',
padding: '10px',
borderRadius: '5px',
}}
>
{node.content}
</pre>
)}
</li>
</ul>
);
};
const handleDeploy = async () => {
setDeploying(true);
setDeployError(null);
try {
const collectedData = await collectProjectData(structure);
const response = await axios.post(`${process.env.NGROK_DEPLOYER_URL}/deploy`, {
structure: collectedData,
});
if (response.status === 200) {
console.log('Deployment started successfully');
} else {
setDeployError('Deployment failed. Please check the logs for more details.');
}
} catch (error) {
console.error('Deployment failed:', error);
setDeployError('Deployment failed. Please try again.');
} finally {
setDeploying(false);
}
};
const collectProjectData = async (structure) => {
const collectedData = {
files: [],
packageJson: '',
jsConfigCode: '',
nextConfigJs: '',
postcssConfig: '',
tailwindConfig: '',
globalsCss: '',
envVariables: [],
sqlCode: '',
keys: {},
projectName: '',
};
const traverseStructure = (node, parentPath = '') => {
const nodePath = `${parentPath}/${node.name}`;
if (node.children && node.children.length > 0) {
node.children.forEach((child) => traverseStructure(child, nodePath));
} else if (node.content) {
const fileInfo = {
fileName: node.name,
content: node.content,
};
if (parentPath.includes('/api')) {
collectedData.files.push({ ...fileInfo, type: 'api' });
} else if (parentPath.includes('/pages')) {
collectedData.files.push({ ...fileInfo, type: 'page' });
} else if (parentPath.includes('/middleware')) {
collectedData.files.push({ ...fileInfo, type: 'middleware' });
} else if (parentPath.includes('/components')) {
collectedData.files.push({ ...fileInfo, type: 'component' });
} else if (node.name === 'package.json') {
collectedData.packageJson = node.content;
} else if (node.name === 'jsconfig.json') {
collectedData.jsConfigCode = node.content;
} else if (node.name === 'next.config.js') {
collectedData.nextConfigJs = node.content;
} else if (node.name === 'postcss.config.js') {
collectedData.postcssConfig = node.content;
} else if (node.name === 'tailwind.config.js') {
collectedData.tailwindConfig = node.content;
} else if (node.name === 'globals.css') {
collectedData.globalsCss = node.content;
}
}
};
traverseStructure(structure);
collectedData.envVariables = requiredEnvVars.map((key) => ({
key,
type: 'plain',
value: envVariables[key] || '',
target: ['production', 'preview', 'development'],
}));
collectedData.sqlCode = sqlCode;
collectedData.keys = {
SUPABASE_DB_URL: keys.SUPABASE_DB_URL || '',
VERCEL_TOKEN: keys.VERCEL_TOKEN || '',
};
collectedData.projectName = projectName;
return JSON.stringify(collectedData);
};
const generateZipFile = (structure) => {
const zip = new JSZip();
const traverseStructure = (node, parentPath = '') => {
const nodePath = `${parentPath}/${node.name}`;
if (node.children && node.children.length > 0) {
node.children.forEach((child) => traverseStructure(child, nodePath));
} else if (node.content) {
// Check if the file is inside the 'pages' folder and name it 'index.js'
if (parentPath.includes('/pages') && !node.name.includes('.')) {
// This condition assumes that node.name without an extension is a folder (i.e., a page directory)
zip.file(`${parentPath}/index.js`, node.content);
} else {
zip.file(nodePath.startsWith('/') ? nodePath.slice(1) : nodePath, node.content);
}
}
};
traverseStructure(structure);
return zip;
};
const handleDownload = async () => {
const zip = generateZipFile(structure);
const content = await zip.generateAsync({ type: 'blob' });
saveAs(content, `${projectName || 'project'}.zip`);
};
const handleEnvVarChange = (key, value) => {
setEnvVariables((prev) => ({
...prev,
[key]: value,
}));
};
const handleKeyChange = (key, value) => {
setKeys((prev) => ({
...prev,
[key]: value,
}));
};
return (
<div className="folder-structure">
<h3 style={{fontWeight:500, marginBottom:'10px'}}>Project Folder Structure</h3>
<hr></hr>
<div style={{ marginBottom: '20px', marginTop:'15px' }}>
<label style={{ marginRight: '10px' }}>Vercel Project Name:</label>
<input
type="text"
value={projectName}
onChange={(e) => setProjectName(e.target.value)}
className="border rounded px-2 py-1"
placeholder="Enter project name"
/>
</div>
{requiredEnvVars.map((key) => (
<div key={key} style={{ marginBottom: '10px' }}>
<label style={{ marginRight: '10px' }}>{key}:</label>
<input
type="text"
value={envVariables[key] || ''}
onChange={(e) => handleEnvVarChange(key, e.target.value)}
className="border rounded px-2 py-1"
placeholder={`Enter value for ${key}`}
/>
</div>
))}
<div style={{ marginBottom: '10px' }}>
<label style={{ marginRight: '10px' }}>SUPABASE_DB_URL:</label>
<input
type="text"
value={keys.SUPABASE_DB_URL}
onChange={(e) => handleKeyChange('SUPABASE_DB_URL', e.target.value)}
className="border rounded px-2 py-1"
placeholder="Enter SUPABASE_DB_URL"
/>
</div>
<div style={{ marginBottom: '10px' }}>
<label style={{ marginRight: '10px' }}>VERCEL_TOKEN:</label>
<input
type="text"
value={keys.VERCEL_TOKEN}
onChange={(e) => handleKeyChange('VERCEL_TOKEN', e.target.value)}
className="border rounded px-2 py-1"
placeholder="Enter VERCEL_TOKEN"
/>
</div>
{renderStructure(structure)}
<div style={{ marginTop: '20px' }}>
<button
onClick={handleDeploy}
className={`py-2 px-4 ${deploying ? 'bg-gray-500' : 'bg-green-500'} text-white rounded`}
disabled={
deploying ||
requiredEnvVars.some((key) => !envVariables[key]) ||
!keys.SUPABASE_DB_URL ||
!keys.VERCEL_TOKEN
}
style={{cursor:'pointer'}}
>
{deploying ? 'Deploying...' : 'Deploy Project'}
</button>
{deployError && <p style={{ color: 'red', marginTop: '10px' }}>{deployError}</p>}
<button
onClick={handleDownload}
className="py-2 px-4 bg-blue-500 text-white rounded ml-4"
style={{cursor:'pointer'}}
>
Download Project
</button>
</div>
</div>
);
};
export default ProjectFolderStructure;