-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain.js
More file actions
363 lines (305 loc) · 13.5 KB
/
Copy pathmain.js
File metadata and controls
363 lines (305 loc) · 13.5 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
import { select, Separator, search, input } from '@inquirer/prompts';
import chalk from 'chalk';// Import path
import path from 'path';
import { loadAdminForthConfig } from './configLoader.js'; // Helper to load config
import { generateComponentFile, generateLoginOrGlobalComponentFile, generateCrudInjectionComponent } from './fileGenerator.js'; // Helper to create the .vue file
import { updateResourceConfig, injectLoginComponent, injectGlobalComponent, updateCrudInjectionConfig } from './configUpdater.js'; // Helper to modify resource .ts file
function sanitizeLabel(input){
return input
.replace(/[^a-zA-Z0-9\s]/g, '')
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join('');
}
export default async function createComponent(args) {
console.log('This command will help you to generate boilerplate for component.\n');
const config = await loadAdminForthConfig();
const resources = config.resources;
const componentType = await select({
message: 'What component type would you like to add?',
choices: [
{ name: `🔤 Custom fields ${chalk.grey('fields')}`, value: 'fields' },
{ name: `➖ CRUD page injections ${chalk.grey('crudPage')}`, value: 'crudPage' },
{ name: `🔐 Login page injections ${chalk.grey('login')}`, value: 'login' },
{ name: `🌐 Global Injections ${chalk.grey('global')}`, value: 'global' },
],
});
if (componentType === 'fields') {
await handleFieldComponentCreation(config, resources);
} else if (componentType === 'crudPage') {
await handleCrudPageInjectionCreation(config, resources);
} else if (componentType === 'login') {
await handleLoginPageInjectionCreation(config);
} else if (componentType === 'global') {
await handleGlobalInjectionCreation(config);
}
}
async function handleFieldComponentCreation(config, resources) {
console.log(chalk.grey('Selected ❯ 🔤 Custom fields'));
const fieldType = await select({
message: 'What view component would you like to add?',
choices: [
{ name: '🔸 list', value: 'list' },
{ name: '📃 show', value: 'show' },
{ name: '✏️ edit', value: 'edit' },
{ name: '➕ create', value: 'create' },
{ name: '🔍 filter', value: 'filter'},
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
]
});
if (fieldType === '__BACK__') return createComponent([]); // Go back to main menu
console.log(chalk.grey(`Selected ❯ 🔤 Custom fields ❯ ${fieldType}`));
const resourceId = await search({
message: 'Select resource for which you want to change component:',
source: async (input) => {
const searchTerm = input ? input.toLowerCase() : '';
const filtered = resources.filter(r => {
const label = r.label || '';
const id = r.resourceId || '';
return label.toLowerCase().includes(searchTerm) || id.toLowerCase().includes(searchTerm);
});
return [
...filtered.map(r => ({
name: `${r.label} ${chalk.grey(`${r.resourceId}`)}`,
value: r.resourceId,
})),
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
];
}
});
if (resourceId === '__BACK__') return handleFieldComponentCreation(config, resources); // Pass config back
const selectedResource = resources.find(r => r.resourceId === resourceId);
console.log(chalk.grey(`Selected ❯ 🔤 Custom fields ❯ ${fieldType} ❯ ${selectedResource.label}`));
const columnName = await search({
message: 'Select column for which you want to create component:',
source: async (input) => {
const searchTerm = input ? input.toLowerCase() : '';
const filteredColumns = selectedResource.columns.filter(c => {
const label = c.label || '';
const name = c.name || '';
return label.toLowerCase().includes(searchTerm) || name.toLowerCase().includes(searchTerm);
});
return [
...filteredColumns.map(c => ({ name: `${c.label} ${chalk.grey(`${c.name}`)}`, value: c.name })),
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
];
},
});
if (columnName === '__BACK__') return handleFieldComponentCreation(config, resources); // Pass config back
const selectedColumn = selectedResource.columns.find(c => c.name === columnName);
console.log(chalk.grey(`Selected ❯ 🔤 Custom fields ❯ ${fieldType} ❯ ${selectedResource.label} ❯ ${selectedColumn.label}`));
console.log(chalk.dim(`One-line alternative: |adminforth component fields.${fieldType}.${resourceId}.${columnName}|`));
const safeResourceLabel = sanitizeLabel(selectedResource.label)
const safeColumnLabel = sanitizeLabel(selectedColumn.label)
const componentFileName = `${safeResourceLabel}${safeColumnLabel}${fieldType.charAt(0).toUpperCase() + fieldType.slice(1)}.vue`; // e.g., UserEmailShow.vue
const componentPathForConfig = `@@/${componentFileName}`; // Path relative to custom dir for config
try {
const { alreadyExists, path: absoluteComponentPath } = await generateComponentFile(
componentFileName,
fieldType,
{ resource: selectedResource, column: selectedColumn },
config
);
if (!alreadyExists) {
console.log(chalk.dim(`Component generation successful: ${absoluteComponentPath}`));
await updateResourceConfig(selectedResource.resourceId, columnName, fieldType, componentPathForConfig);
console.log(
chalk.bold.greenBright('You can now open the component in your IDE:'),
chalk.underline.cyanBright(absoluteComponentPath)
);
}
process.exit(0);
}catch (error) {
console.error(error);
console.error(chalk.red('\n❌ Component creation failed. Please check the errors above.'));
process.exit(1);
}
}
async function handleCrudPageInjectionCreation(config, resources) {
console.log(chalk.grey('Selected ❯ 📄 CRUD Page Injection'));
const crudType = await select({
message: 'What view do you want to inject a custom component into?',
choices: [
{ name: '🔸 list', value: 'list' },
{ name: '📃 show', value: 'show' },
{ name: '✏️ edit', value: 'edit' },
{ name: '➕ create', value: 'create' },
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
],
});
if (crudType === '__BACK__') return createComponent([]);
console.log(chalk.grey(`Selected ❯ 📄 CRUD Page Injection ❯ ${crudType}`));
const resourceId = await search({
message: 'Select resource for which you want to inject the component:',
source: async (input) => {
const searchTerm = input ? input.toLowerCase() : '';
const filtered = resources.filter(r => {
const label = r.label || '';
const id = r.resourceId || '';
return label.toLowerCase().includes(searchTerm) || id.toLowerCase().includes(searchTerm);
});
return [
...filtered.map(r => ({
name: `${r.label} ${chalk.grey(`${r.resourceId}`)}`,
value: r.resourceId,
})),
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
];
}
});
if (resourceId === '__BACK__') return handleCrudPageInjectionCreation(config, resources);
const selectedResource = resources.find(r => r.resourceId === resourceId);
console.log(chalk.grey(`Selected ❯ 📄 CRUD Page Injection ❯ ${crudType} ❯ ${selectedResource.label}`));
const injectionPosition = await select({
message: 'Where exactly do you want to inject the component?',
choices: [
{ name: '⬆️ Before Breadcrumbs', value: 'beforeBreadcrumbs' },
{ name: '➡️ Before Action Buttons', value: 'beforeActionButtons' },
{ name: '⬇️ After Breadcrumbs', value: 'afterBreadcrumbs' },
{ name: '📄 After Page', value: 'bottom' },
{ name: '⋯ threeDotsDropdownItems', value: 'threeDotsDropdownItems' },
new Separator(),
{ name: '🔙 BACK', value: '__BACK__' },
],
});
if (injectionPosition === '__BACK__') return handleCrudPageInjectionCreation(config, resources);
const additionalName = await input({
message: 'Enter additional name (optional, e.g., "CustomExport"):',
validate: (value) => {
if (!value) return true;
return /^[A-Za-z0-9_-]+$/.test(value) || 'Only alphanumeric characters, hyphens or underscores are allowed.';
},
});
const isThin = crudType === 'list'
? await select({
message: 'Will this component be thin enough to fit on the same page with list (so list will still shrink)?',
choices: [
{ name: 'Yes', value: true },
{ name: 'No', value: false },
],
})
: false;
const formattedAdditionalName = additionalName
? additionalName[0].toUpperCase() + additionalName.slice(1)
: '';
const safeResourceLabel = sanitizeLabel(selectedResource.label)
const componentFileName = `${safeResourceLabel}${crudType.charAt(0).toUpperCase() + crudType.slice(1)}${injectionPosition.charAt(0).toUpperCase() + injectionPosition.slice(1) + formattedAdditionalName}.vue`;
const componentPathForConfig = `@@/${componentFileName}`;
try {
const { alreadyExists, path: absoluteComponentPath } = await generateCrudInjectionComponent(
componentFileName,
injectionPosition,
{ resource: selectedResource },
config
);
if (!alreadyExists) {
console.log(chalk.dim(`Component generation successful: ${absoluteComponentPath}`));
await updateCrudInjectionConfig(
selectedResource.resourceId,
crudType,
injectionPosition,
componentPathForConfig,
isThin
);
console.log(
chalk.bold.greenBright('You can now open the component in your IDE:'),
chalk.underline.cyanBright(absoluteComponentPath)
);
}
process.exit(0);
} catch (error) {
console.error(error);
console.error(chalk.red('\n❌ Component creation failed. Please check the errors above.'));
process.exit(1);
}
}
async function handleLoginPageInjectionCreation(config) {
console.log('Selected ❯ 🔐 Login page injections');
const injectionType = await select({
message: 'Select injection type:',
choices: [
{ name: 'Before Login and password inputs', value: 'beforeLogin' },
{ name: 'After Login and password inputs', value: 'afterLogin' },
{ name: '🔙 BACK', value: '__BACK__' },
],
});
if (injectionType === '__BACK__') return createComponent([]);
console.log(chalk.grey(`Selected ❯ 🔐 Login page injections ❯ ${injectionType}`));
const reason = await input({
message: 'What will you need component for? (enter name)',
});
console.log(chalk.grey(`Selected ❯ 🔐 Login page injections ❯ ${injectionType} ❯ ${reason}`));
try {
const safeName = sanitizeLabel(reason)
const componentFileName = `CustomLogin${safeName}.vue`;
const context = { reason };
const { alreadyExists, path: absoluteComponentPath } = await generateLoginOrGlobalComponentFile(
componentFileName,
injectionType,
context
);
if (!alreadyExists) {
console.log(chalk.dim(`Component generation successful: ${absoluteComponentPath}`));
const configFilePath = path.resolve(process.cwd(), 'index.ts');
console.log(chalk.dim(`Injecting component: ${configFilePath}, ${componentFileName}`));
await injectLoginComponent(configFilePath, `@@/${componentFileName}`, injectionType);
console.log(
chalk.bold.greenBright('You can now open the component in your IDE:'),
chalk.underline.cyanBright(absoluteComponentPath)
);
}
process.exit(0);
}catch (error) {
console.error(error);
console.error(chalk.red('\n❌ Component creation failed. Please check the errors above.'));
process.exit(1);
}
}
async function handleGlobalInjectionCreation(config) {
console.log('Selected ❯ 🌍 Global page injections');
const injectionType = await select({
message: 'Select global injection type:',
choices: [
{ name: 'User Menu', value: 'userMenu' },
{ name: 'Header', value: 'header' },
{ name: 'Sidebar', value: 'sidebar' },
{ name: 'Every Page Bottom', value: 'everyPageBottom' },
{ name: '🔙 BACK', value: '__BACK__' },
],
});
if (injectionType === '__BACK__') return createComponent([]);
console.log(chalk.grey(`Selected ❯ 🌍 Global page injections ❯ ${injectionType}`));
const reason = await input({
message: 'What will you need the component for? (enter name)',
});
console.log(chalk.grey(`Selected ❯ 🌍 Global page injections ❯ ${injectionType} ❯ ${reason}`));
try {
const safeName = sanitizeLabel(reason)
const componentFileName = `CustomGlobal${safeName}.vue`;
const context = { reason };
const { alreadyExists, path: absoluteComponentPath } = await generateLoginOrGlobalComponentFile(
componentFileName,
injectionType,
context
);
if (!alreadyExists) {
console.log(chalk.dim(`Component generation successful: ${absoluteComponentPath}`));
const configFilePath = path.resolve(process.cwd(), 'index.ts');
await injectGlobalComponent(configFilePath, injectionType, `@@/${componentFileName}`);
console.log(
chalk.bold.greenBright('You can now open the component in your IDE:'),
chalk.underline.cyanBright(absoluteComponentPath)
);
}
process.exit(0);
} catch (error) {
console.error(error);
console.error(chalk.red('\n❌ Component creation failed. Please check the errors above.'));
process.exit(1);
}
}