/
task-generate.ts
213 lines (174 loc) · 5.9 KB
/
task-generate.ts
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
import type { Config } from '../declarations';
import type { CoreCompiler } from './load-compiler';
import { IS_NODE_ENV } from '../compiler/sys/environment';
import { validateComponentTag } from '@utils';
/**
* Task to generate component boilerplate.
*/
export const taskGenerate = async (coreCompiler: CoreCompiler, config: Config) => {
if (!IS_NODE_ENV) {
config.logger.error(`"generate" command is currently only implemented for a NodeJS environment`);
config.sys.exit(1);
}
const path = coreCompiler.path;
if (!config.configPath) {
config.logger.error('Please run this command in your root directory (i. e. the one containing stencil.config.ts).');
config.sys.exit(1);
}
const absoluteSrcDir = config.srcDir;
if (!absoluteSrcDir) {
config.logger.error(`Stencil's srcDir was not specified.`);
config.sys.exit(1);
}
const { prompt } = await import('prompts');
const input =
config.flags.unknownArgs.find(arg => !arg.startsWith('-')) || ((await prompt({ name: 'tagName', type: 'text', message: 'Component tag name (dash-case):' })).tagName as string);
const { dir, base: componentName } = path.parse(input);
const tagError = validateComponentTag(componentName);
if (tagError) {
config.logger.error(tagError);
config.sys.exit(1);
}
const extensionsToGenerate: GeneratableExtension[] = ['tsx', ...(await chooseFilesToGenerate())];
const testFolder = extensionsToGenerate.some(isTest) ? 'test' : '';
const outDir = path.join(absoluteSrcDir, 'components', dir, componentName);
await config.sys.createDir(path.join(outDir, testFolder), { recursive: true });
const writtenFiles = await Promise.all(
extensionsToGenerate.map(extension => writeFileByExtension(coreCompiler, config, outDir, componentName, extension, extensionsToGenerate.includes('css'))),
).catch(error => config.logger.error(error));
if (!writtenFiles) {
return config.sys.exit(1);
}
console.log();
console.log(`${config.logger.gray('$')} stencil generate ${input}`);
console.log();
console.log(config.logger.bold('The following files have been generated:'));
const absoluteRootDir = config.rootDir;
writtenFiles.map(file => console.log(` - ${path.relative(absoluteRootDir, file)}`));
};
/**
* Show a checkbox prompt to select the files to be generated.
*/
const chooseFilesToGenerate = async () => {
const { prompt } = await import('prompts');
return (
await prompt({
name: 'filesToGenerate',
type: 'multiselect',
message: 'Which additional files do you want to generate?',
choices: [
{ value: 'css', title: 'Stylesheet (.css)', selected: true },
{ value: 'spec.tsx', title: 'Spec Test (.spec.tsx)', selected: true },
{ value: 'e2e.ts', title: 'E2E Test (.e2e.ts)', selected: true },
] as any[],
})
).filesToGenerate as GeneratableExtension[];
};
/**
* Get a file's boilerplate by its extension and write it to disk.
*/
const writeFileByExtension = async (coreCompiler: CoreCompiler, config: Config, path: string, name: string, extension: GeneratableExtension, withCss: boolean) => {
if (isTest(extension)) {
path = coreCompiler.path.join(path, 'test');
}
const outFile = coreCompiler.path.join(path, `${name}.${extension}`);
const boilerplate = getBoilerplateByExtension(name, extension, withCss);
await config.sys.writeFile(outFile, boilerplate);
return outFile;
};
const isTest = (extension: string) => {
return extension === 'e2e.ts' || extension === 'spec.tsx';
};
/**
* Get the boilerplate for a file by its extension.
*/
const getBoilerplateByExtension = (tagName: string, extension: GeneratableExtension, withCss: boolean) => {
switch (extension) {
case 'tsx':
return getComponentBoilerplate(tagName, withCss);
case 'css':
return getStyleUrlBoilerplate();
case 'spec.tsx':
return getSpecTestBoilerplate(tagName);
case 'e2e.ts':
return getE2eTestBoilerplate(tagName);
default:
throw new Error(`Unkown extension "${extension}".`);
}
};
/**
* Get the boilerplate for a component.
*/
const getComponentBoilerplate = (tagName: string, hasStyle: boolean) => {
const decorator = [`{`];
decorator.push(` tag: '${tagName}',`);
if (hasStyle) {
decorator.push(` styleUrl: '${tagName}.css',`);
}
decorator.push(` shadow: true,`);
decorator.push(`}`);
return `import { Component, Host, h } from '@stencil/core';
@Component(${decorator.join('\n')})
export class ${toPascalCase(tagName)} {
render() {
return (
<Host>
<slot></slot>
</Host>
);
}
}
`;
};
/**
* Get the boilerplate for style.
*/
const getStyleUrlBoilerplate = () =>
`:host {
display: block;
}
`;
/**
* Get the boilerplate for a spec test.
*/
const getSpecTestBoilerplate = (tagName: string) =>
`import { newSpecPage } from '@stencil/core/testing';
import { ${toPascalCase(tagName)} } from '../${tagName}';
describe('${tagName}', () => {
it('renders', async () => {
const page = await newSpecPage({
components: [${toPascalCase(tagName)}],
html: \`<${tagName}></${tagName}>\`,
});
expect(page.root).toEqualHtml(\`
<${tagName}>
<mock:shadow-root>
<slot></slot>
</mock:shadow-root>
</${tagName}>
\`);
});
});
`;
/**
* Get the boilerplate for an E2E test.
*/
const getE2eTestBoilerplate = (name: string) =>
`import { newE2EPage } from '@stencil/core/testing';
describe('${name}', () => {
it('renders', async () => {
const page = await newE2EPage();
await page.setContent('<${name}></${name}>');
const element = await page.find('${name}');
expect(element).toHaveClass('hydrated');
});
});
`;
/**
* Convert a dash case string to pascal case.
*/
const toPascalCase = (str: string) => str.split('-').reduce((res, part) => res + part[0].toUpperCase() + part.substr(1), '');
/**
* Extensions available to generate.
*/
type GeneratableExtension = 'tsx' | 'css' | 'spec.tsx' | 'e2e.ts';