-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathcreate-new-component-tool.js
More file actions
502 lines (461 loc) · 18.5 KB
/
create-new-component-tool.js
File metadata and controls
502 lines (461 loc) · 18.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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
* Copyright (c) 2025, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import fs from 'fs/promises'
import path from 'path'
import {HookRecommenderTool} from './hook-recommender-tool.js'
import {toKebabCase, toPascalCase} from './utils.js'
export const getCopyrightHeader = () => {
const year = new Date().getFullYear()
return `/*
* Copyright (c) ${year}, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/`
}
// Utility to infer entity from component name
function inferEntityFromComponentName(componentName) {
const name = componentName.toLowerCase()
if (name.includes('customer')) return 'customer'
if (name.includes('product')) return 'product'
if (name.includes('basket')) return 'basket'
if (name.includes('category')) return 'category'
return null
}
class CreateNewComponentTool {
constructor() {
this.currentStep = 0
this.componentData = {
name: null,
location: null,
createTestFile: null,
customCode: null,
entityType: null
}
}
/**
* Creates the component based on all collected data
* @returns {Promise<string>} The result of component creation
*/
async createComponent() {
const messages = []
// Use the provided absolute path directly if available
const location = this.componentData.location
const componentMessage = await this.createComponentFile(
this.componentData.name,
location,
this.componentData.customCode
)
messages.push(componentMessage)
// Create test file if requested
if (this.componentData.createTestFile) {
const testMessage = await this.createTestFile(this.componentData.name, location)
messages.push(testMessage)
}
// Handle entity type information
if (this.componentData.entityType) {
messages.push(
`\nℹ️ Entity type '${this.componentData.entityType}' ${
inferEntityFromComponentName(this.componentData.name)
? 'was inferred'
: 'was specified'
} for component '${this.componentData.name}'.`
)
} else {
messages.push(
`\nℹ️ No entity type was specified or could be inferred for component '${this.componentData.name}'.`
)
}
// Recommend hooks if entity is available
if (this.componentData.entityType) {
const recommender = new HookRecommenderTool()
const recommendations = recommender.getRecommendations(this.componentData.entityType)
if (Array.isArray(recommendations)) {
messages.push(
`\n🔗 Recommended hooks for entity '${this.componentData.entityType}':`
)
recommendations.forEach((hook) => {
messages.push(`- ${hook.name}: ${hook.description} (from ${hook.package})`)
})
} else if (recommendations.error) {
messages.push(`\n${recommendations.error}`)
}
} else {
messages.push('\nℹ️ No entity provided or inferred for hook recommendations.')
}
// Always append lint reminder
messages.push(
"\n💡 After creating or modifying a component, run 'npm run lint -- --fix' to automatically fix formatting and linter issues."
)
// Reset for next use
this.reset()
return messages.join('\n')
}
/**
* Resets the tool state for the next component creation
*/
reset() {
this.currentStep = 0
this.componentData = {
name: null,
location: null,
createTestFile: null,
customCode: null,
entityType: null
}
}
/**
* Creates a new React component file.
* @param {string} componentName - Name for the new component.
* @param {string} projectDir - The absolute path to the project directory for the new component.
* @param {string} [componentCode] - Code of the component to create. If not provided, a default skeleton will be used.
*/
async createComponentFile(componentName, projectDir, componentCode) {
const kebabDirName = toKebabCase(componentName)
const pascalComponentName = toPascalCase(componentName)
const componentDir = path.join(projectDir, kebabDirName)
try {
await fs.mkdir(componentDir, {recursive: true})
// Create component file
const componentFilePath = path.join(componentDir, 'index.jsx')
const codeToWrite =
!componentCode || componentCode === 'default skeleton'
? `${getCopyrightHeader()}
import React from 'react';
const ${pascalComponentName} = () => {
return (
<div>${pascalComponentName} component</div>
);
};
export default ${pascalComponentName};
`
: componentCode
await fs.writeFile(componentFilePath, codeToWrite, 'utf-8')
return `✅ Created ${componentFilePath}`
} catch (err) {
console.error('Error during file creation:', err)
return `❌ Error creating component file at ${componentDir}: ${err.message}`
}
}
/**
* Creates a test file for an existing component.
* @param {string} componentName - Name of the component to create a test file for.
* @param {string} projectDir - The absolute path to the project directory where the component exists.
*/
async createTestFile(componentName, projectDir) {
const kebabDirName = toKebabCase(componentName)
const pascalComponentName = toPascalCase(componentName)
const componentDir = path.join(projectDir, kebabDirName)
try {
// Create test file
const testFilePath = path.join(componentDir, 'index.test.jsx')
const testCode = `${getCopyrightHeader()}
import React from 'react'
import {screen} from '@testing-library/react'
import {renderWithProviders} from '@salesforce/retail-react-app/app/utils/test-utils'
import ${pascalComponentName} from './index'
describe('${pascalComponentName}', () => {
test('renders correctly', () => {
renderWithProviders(<${pascalComponentName} />)
expect(screen.getByText('${pascalComponentName} component')).toBeInTheDocument()
})
})
`
await fs.writeFile(testFilePath, testCode, 'utf-8')
return `✅ Created ${testFilePath}`
} catch (err) {
console.error('Error during test file creation:', err)
return `❌ Error creating test file at ${componentDir}: ${err.message}`
}
}
/**
* Updates the component file to be a presentational component for the given data model.
* @param {string} entityType - The entity type (e.g., 'product').
* @param {string} componentName - The component name.
* @param {string} location - The absolute path to the component's parent directory.
* @param {object} dataModel - The data model schema (properties object).
*/
async updateComponentToPresentational(
entityType,
componentName,
location,
dataModel,
options = {}
) {
const kebabDirName = toKebabCase(componentName)
const pascalComponentName = toPascalCase(componentName)
const componentDir = path.join(location, kebabDirName)
await fs.mkdir(componentDir, {recursive: true})
const componentFilePath = path.join(componentDir, 'index.jsx')
const fields = Object.keys(dataModel)
let code = ''
// Special logic for product entity
if (entityType === 'product') {
// If options.list is true, generate a list-of-products component
if (options.list) {
code = `${getCopyrightHeader()}
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Text, Image, Stack } from '@chakra-ui/react';
const ${pascalComponentName} = ({ products }) => (
<Stack spacing={4}>
{products.map(product => (
<Box key={product.productId} borderWidth="1px" borderRadius="md" p={4}>
<Text fontSize="xl" fontWeight="bold">{product.name}</Text>
{product.imageGroups && product.imageGroups[0]?.images[0]?.link && (
<Image
src={product.imageGroups[0].images[0].link}
alt={product.name}
maxW="150px"
mb={2}
/>
)}
<Text>assigned_categories: {product.assigned_categories?.toString?.() ?? ''}</Text>
<Text>price: {product.price?.toString?.() ?? ''}</Text>
</Box>
))}
</Stack>
);
${pascalComponentName}.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
productId: PropTypes.string,
name: PropTypes.string,
assigned_categories: PropTypes.any,
price: PropTypes.any,
imageGroups: PropTypes.array
})).isRequired
};
export default ${pascalComponentName};
`
} else {
// Single product component (with selectors, image, etc.)
code = `${getCopyrightHeader()}
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Box, Text, Image, Button, HStack, Stack } from '@chakra-ui/react';
// Helper to filter variants by selected attribute values
const filterVariants = (variants, selected) => {
return variants.filter(variant =>
Object.entries(selected).every(
([attr, value]) => !value || variant.variationValues?.[attr] === value
)
);
};
// Helper to get the image for the selected color
const getImageForSelection = (imageGroups, selected) => {
if (selected.color) {
const group = imageGroups.find(
g =>
g.variationAttributes &&
g.variationAttributes.some(
va =>
va.id === 'color' &&
va.values.some(v => v.value === selected.color)
)
);
if (group && group.images.length > 0) {
return group.images[0].link;
}
}
if (imageGroups.length > 0 && imageGroups[0].images.length > 0) {
return imageGroups[0].images[0].link;
}
return null;
};
const ${pascalComponentName} = ({ product }) => {
const { variationAttributes = [], variants = [], imageGroups = [] } = product;
const [selected, setSelected] = useState(() => {
const initial = {};
variationAttributes.forEach(attr => {
initial[attr.id] = '';
});
return initial;
});
// Build a color code to swatch image URL map
const swatchMap = {};
imageGroups
.filter(group => group.viewType === 'swatch')
.forEach(group => {
const colorCode = group.variationAttributes?.[0]?.values?.[0]?.value;
if (colorCode && group.images[0]?.link) {
swatchMap[colorCode] = group.images[0].link;
}
});
const filteredVariants = filterVariants(variants, selected);
const getAvailableValues = (attrId) => {
const otherSelected = { ...selected };
delete otherSelected[attrId];
const possibleVariants = filterVariants(variants, otherSelected);
const values = new Set();
possibleVariants.forEach(v => {
if (v.variationValues?.[attrId]) values.add(v.variationValues[attrId]);
});
return Array.from(values);
};
const imageUrl = getImageForSelection(imageGroups, selected);
return (
<Box>
<Text fontSize="2xl" fontWeight="bold" mb={2}>{product.name}</Text>
{imageUrl && (
<Image src={imageUrl} alt={product.name} maxW="300px" mb={4} />
)}
<Text>assigned_categories: {product.assigned_categories?.toString?.() ?? ''}</Text>
<Text>price: {product.price?.toString?.() ?? ''}</Text>
{/* Dynamic variant attribute selectors */}
{variationAttributes.map(attr => (
<Box key={attr.id} my={2}>
<Text as="span" fontWeight="semibold">{attr.name}:</Text>
<HStack spacing={2} mt={1}>
{getAvailableValues(attr.id).map(val =>
attr.id === 'color' ? (
<Button
key={val}
onClick={() => setSelected(sel => ({ ...sel, [attr.id]: val }))}
variant={selected[attr.id] === val ? 'solid' : 'outline'}
borderRadius="full"
minW="32px"
h="32px"
p={0}
borderColor={
selected[attr.id] === val ? 'blue.500' : 'gray.200'
}
_hover={{opacity: 0.8}}
aria-label={val}
>
{swatchMap[val] ? (
<Image
src={swatchMap[val]}
alt={val}
borderRadius="full"
boxSize="28px"
/>
) : (
val
)}
</Button>
) : (
<Button
key={val}
onClick={() => setSelected(sel => ({ ...sel, [attr.id]: val }))}
variant={selected[attr.id] === val ? 'solid' : 'outline'}
colorScheme={selected[attr.id] === val ? 'blue' : 'gray'}
borderRadius="md"
size="sm"
>
{val}
</Button>
)
)}
</HStack>
</Box>
))}
</Box>
);
};
${pascalComponentName}.propTypes = {
product: PropTypes.shape({
name: PropTypes.string,
assigned_categories: PropTypes.any,
price: PropTypes.any,
variationAttributes: PropTypes.array,
variants: PropTypes.array,
imageGroups: PropTypes.array
}).isRequired
};
export default ${pascalComponentName};
`
}
} else {
// Generic component for other entities
const propName = options.propName || entityType
const isArray = options.array || false
if (isArray) {
// Array of entities
code = `${getCopyrightHeader()}
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Text, Stack } from '@chakra-ui/react';
const ${pascalComponentName} = ({ ${propName} }) => (
<Stack spacing={4}>
{${propName}.map(item => (
<Box key={item.id || item.${entityType}Id} borderWidth="1px" borderRadius="md" p={4}>
${fields
.map((field) => ` <Text>${field}: {item.${field}?.toString?.() ?? ''}</Text>`)
.join('\n')}
</Box>
))}
</Stack>
);
${pascalComponentName}.propTypes = {
${propName}: PropTypes.arrayOf(PropTypes.shape({
${fields.map((field) => ` ${field}: PropTypes.any`).join(',\n')}
})).isRequired
};
export default ${pascalComponentName};
`
} else {
// Single entity
code = `${getCopyrightHeader()}
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Text, Stack } from '@chakra-ui/react';
const ${pascalComponentName} = ({ ${propName} }) => (
<Box>
<Text fontSize="2xl" fontWeight="bold" mb={4}>{${propName}.name || ${propName}.id || '${pascalComponentName}'}</Text>
<Stack spacing={2}>
${fields
.map(
(field) =>
` <Text><strong>${field}:</strong> {${propName}.${field}?.toString?.() ?? ''}</Text>`
)
.join('\n')}
</Stack>
</Box>
);
${pascalComponentName}.propTypes = {
${propName}: PropTypes.shape({
${fields.map((field) => ` ${field}: PropTypes.any`).join(',\n')}
}).isRequired
};
export default ${pascalComponentName};
`
}
}
await fs.writeFile(componentFilePath, code, 'utf-8')
return `✅ Updated ${componentFilePath} to presentational component for ${entityType}`
}
/**
* Handles developer's hook selection and updates the component accordingly.
* The generated component expects the data as a prop (not from the hook directly).
*/
async handleHookSelection(selectedHook, entityType, componentName, location, dataModels) {
// Support for product entity hooks
if (entityType === 'product' && dataModels.product) {
if (selectedHook === 'useProduct') {
return await this.updateComponentToPresentational(
'product',
componentName,
location,
dataModels.product.properties,
{array: false, propName: 'product'}
)
}
if (selectedHook === 'useProducts' || selectedHook === 'useProductSearch') {
return await this.updateComponentToPresentational(
'product',
componentName,
location,
dataModels.product.properties,
{array: true, propName: 'products'}
)
}
}
// Add more hook/entity support as needed
return 'Selected hook/entity not supported for presentational generation.'
}
}
export default CreateNewComponentTool