forked from onlook-dev/onlook
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcomponents.ts
More file actions
331 lines (263 loc) · 9.61 KB
/
components.ts
File metadata and controls
331 lines (263 loc) · 9.61 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
import {
Project,
ts,
Node,
type FunctionDeclaration,
type ClassDeclaration,
type VariableStatement,
} from 'ts-morph';
import * as path from 'path';
import { promises as fs } from 'fs';
function isUppercase(s: string) {
return s === s.toUpperCase();
}
export interface ReactComponentDescriptor {
name: string;
sourceFilePath: string;
isDelete?: boolean;
}
function isExported(node: FunctionDeclaration | VariableStatement | ClassDeclaration) {
return node.getModifiers().some((m) => m.getKind() === ts.SyntaxKind.ExportKeyword);
}
function getReactComponentDescriptor(
node: Node,
): Omit<ReactComponentDescriptor, 'sourceFilePath'> | null {
if (Node.isVariableStatement(node)) {
if (!isExported(node)) {
return null;
}
const declaration = node.getDeclarationList().getDeclarations().at(0);
if (declaration == null) {
return null;
}
const name = declaration.getName();
if (name == null || !isUppercase(name[0])) {
return null;
}
const initializer = declaration.getInitializer();
if (Node.isArrowFunction(initializer) || Node.isFunctionExpression(initializer)) {
return { name };
}
}
if (Node.isFunctionDeclaration(node)) {
if (!isExported(node)) {
return null;
}
const name = node.getName();
if (name != null && isUppercase(name[0])) {
return { name };
}
}
if (Node.isClassDeclaration(node)) {
if (!isExported(node)) {
return null;
}
const heritageClauses = node.getHeritageClauses();
if (heritageClauses == null) {
return null;
}
const isDerivedFromReactComponent = heritageClauses.some(
(clause) =>
clause.getText().includes('React.Component') ||
clause.getText().includes('React.PureComponent'),
);
if (!isDerivedFromReactComponent) {
return null;
}
const name = node.getName();
if (name == null) {
return null;
}
return { name };
}
return null;
}
function extractReactComponentsFromFile(filePath: string) {
const project = new Project();
const sourceFile = project.addSourceFileAtPath(filePath);
const exportedComponents: ReactComponentDescriptor[] = [];
sourceFile.forEachChild((node) => {
const descriptor = getReactComponentDescriptor(node);
if (descriptor != null) {
exportedComponents.push({
...descriptor,
sourceFilePath: sourceFile.getFilePath(),
isDelete: false,
});
}
});
return exportedComponents;
}
async function scanDirectory(dir: string): Promise<string[]> {
const filesInDirectory = await fs.readdir(dir);
const validFiles = await Promise.all(
filesInDirectory.flatMap(async (file) => {
const fullPath = path.join(dir, file);
if (fullPath.endsWith('node_modules')) {
return [];
}
const isDirectory = (await fs.lstat(fullPath)).isDirectory();
if (isDirectory) {
return scanDirectory(fullPath);
}
if (fullPath.endsWith('.ts') || fullPath.endsWith('.tsx')) {
return [fullPath];
}
return [];
}),
);
return validFiles.flat();
}
export async function extractComponentsFromDirectory(dir: string) {
const files = await scanDirectory(dir);
const allExportedComponents: ReactComponentDescriptor[] = [];
files.forEach((file) => {
const components = extractReactComponentsFromFile(file);
allExportedComponents.push(...components);
});
const updatedExportedComponent = checkIfComponentIsUsed(allExportedComponents, files);
const filteredComponents = updatedExportedComponent.filter((component) => {
const fileName = path.basename(component.sourceFilePath).toLowerCase();
return !(fileName === 'page.tsx' || fileName === 'layout.tsx');
});
return filteredComponents;
}
export async function duplicateComponent(filePath: string, componentName: string) {
try {
const directory = path.dirname(filePath);
const project = new Project();
const sourceFile = project.addSourceFileAtPath(filePath);
const baseName = componentName.replace(/\d+$/, '');
const files = await fs.readdir(directory);
const regex = new RegExp(`^${baseName}(\\d+)?.tsx$`);
const existingNumbers = files
.map((file) => {
const match = file.match(regex);
return match && match[1] ? parseInt(match[1], 10) : 0;
})
.filter((num) => num !== null)
.sort((a, b) => a - b);
const nextNumber = existingNumbers.length ? Math.max(...existingNumbers) + 1 : 1;
const newComponentName = `${baseName}${nextNumber}`;
const newFileName = `${newComponentName}.tsx`;
const newFilePath = path.join(directory, newFileName);
const clonedSourceFile = sourceFile.copy(newFilePath);
const nodesToRename = [
...clonedSourceFile.getFunctions(),
...clonedSourceFile.getVariableDeclarations(),
...clonedSourceFile.getClasses(),
];
nodesToRename.forEach((node) => {
if (node.getName() === componentName) {
node.rename(newComponentName);
}
});
await clonedSourceFile.save();
return newFilePath;
} catch (error) {
console.error('Error duplicating component:', error);
throw error;
}
}
export async function renameComponent(newName: string, filePath: string) {
try {
const directory = path.dirname(filePath);
const oldFileName = path.basename(filePath, '.tsx');
const newFilePath = path.join(directory, `${newName}.tsx`);
const project = new Project();
const sourceFile = project.addSourceFileAtPath(filePath);
const nodesToRename = [
...sourceFile.getFunctions(),
...sourceFile.getVariableDeclarations(),
...sourceFile.getClasses(),
];
let renamed = false;
nodesToRename.forEach((node) => {
if (node.getName() === oldFileName) {
node.rename(newName);
renamed = true;
}
});
if (!renamed) {
console.warn(`No matching component named '${oldFileName}' found for renaming.`);
}
await sourceFile.save();
await fs.rename(filePath, newFilePath);
return newFilePath;
} catch (error) {
console.error('Error renaming component:', error);
throw error;
}
}
export async function createNewComponent(componentName: string, filePath: string) {
try {
const dirPath = path.dirname(filePath);
const newFilePath = path.join(dirPath, `${componentName}.tsx`);
const componentTemplate = `export default function ${componentName}() {
return (
<div className="w-full min-h-screen flex items-center justify-center bg-white dark:bg-black transition-colors duration-200 flex-col p-4 gap-[32px]">
<div className="text-center text-gray-900 dark:text-gray-100 p-4">
<h1 className="text-4xl md:text-5xl font-semibold mb-4 tracking-tight">
This is a blank ${componentName}
</h1>
</div>
</div>
);
}`;
await fs.writeFile(newFilePath, componentTemplate, 'utf-8');
return newFilePath;
} catch (error) {
console.error('Error creating component:', error);
throw error;
}
}
function checkIfComponentIsUsed(
allExportedComponents: ReactComponentDescriptor[],
files: string[],
) {
const project = new Project();
files.forEach((filePath) => {
project.addSourceFileAtPath(filePath);
});
const componentFiles = allExportedComponents.map((comp) => comp.sourceFilePath);
const sourceFiles = project
.getSourceFiles()
.filter((file) => componentFiles.includes(file.getFilePath()));
allExportedComponents.forEach((component) => {
const componentName = component.name;
const isUsed = sourceFiles.some((file) => {
if (!file) {
return false;
}
const isImported = file.getImportDeclarations().some((importDecl) => {
const namedImports = importDecl
.getNamedImports()
.some((namedImport) => namedImport.getName() === componentName);
const defaultImport = importDecl.getDefaultImport()?.getText() === componentName;
return namedImports || defaultImport;
});
if (isImported) {
return true;
}
const isJsxUsage = file
.getDescendantsOfKind(ts.SyntaxKind.JsxOpeningElement)
.some((jsxElement) => {
const tagName = jsxElement.getTagNameNode()?.getText();
return tagName === componentName;
});
return isJsxUsage;
});
component.isDelete = !isUsed;
});
return allExportedComponents;
}
export async function deleteComponent(filePath: string) {
try {
await fs.access(filePath);
await fs.unlink(filePath);
console.log(`Component deleted successfully: ${filePath}`);
} catch (error) {
console.error('Error deleting component:', error);
throw error;
}
}