-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
generateProptypes.ts
302 lines (267 loc) · 8.75 KB
/
generateProptypes.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
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
import * as path from 'path';
import * as fse from 'fs-extra';
import * as ttp from 'typescript-to-proptypes';
import * as prettier from 'prettier';
import * as globCallback from 'glob';
import { promisify } from 'util';
import * as _ from 'lodash';
import * as yargs from 'yargs';
import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scripts/helpers';
const glob = promisify(globCallback);
enum GenerateResult {
Success,
Skipped,
NoComponent,
Failed,
}
const useExternalPropsFromInputBase = [
'autoComplete',
'autoFocus',
'color',
'defaultValue',
'disabled',
'endAdornment',
'error',
'id',
'inputProps',
'inputRef',
'margin',
'name',
'onChange',
'placeholder',
'readOnly',
'required',
'rows',
'rowsMax',
// TODO: why no rowsMin?
'startAdornment',
'value',
];
/**
* TODO: RESOLVE_BEFORE_MERGE
* Stop special casing `children`. They have to be implemented by each
* component individually and need a sensible description. There's no such thing
* as a default implementation for `children`.
*/
/**
* A map of components and their props that should be documented
* but are not used directly in their implementation.
*
* TODO: In the future we want to remove them from the API docs in favor
* of dynamically loading them. At that point this list should be removed.
* TODO: typecheck values
*/
const useExternalDocumentation: Record<string, string[]> = {
FilledInput: useExternalPropsFromInputBase,
Input: useExternalPropsFromInputBase,
OutlinedInput: useExternalPropsFromInputBase,
Radio: ['disableRipple', 'id', 'inputProps', 'inputRef', 'required'],
Switch: [
'checked',
'defaultChecked',
'disabled',
'disableRipple',
'edge',
'id',
'inputProps',
'inputRef',
'onChange',
'required',
'value',
],
};
/**
* These are components that use props implemented by external components.
* Those props have their own JSDOC which we don't want to emit in our docs
* but do want them to have JSDOC in IntelliSense
* TODO: In the future we want to ignore external docs on the initial load anyway
* since they will be fetched dynamically.
*/
const ignoreExternalDocumentation: Record<string, string[]> = {
Collapse: ['onEnter', 'onEntered', 'onEntering', 'onExit', 'onExiting'],
Fade: ['onEnter', 'onExit'],
Grow: ['onEnter', 'onExit'],
InputBase: ['aria-describedby'],
Menu: ['PaperProps'],
Slide: ['onEnter', 'onEntering', 'onExit', 'onExited'],
Zoom: ['onEnter', 'onExit'],
};
const tsconfig = ttp.loadConfig(path.resolve(__dirname, '../tsconfig.json'));
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), {
config: path.join(__dirname, '../prettier.config.js'),
});
function isExternalProp(prop: ttp.PropTypeNode, component: ttp.ComponentNode): boolean {
return Array.from(prop.filenames).some((filename) => filename !== component.propsFilename);
}
async function generateProptypes(
tsFile: string,
jsFile: string,
program: ttp.ts.Program,
): Promise<GenerateResult> {
const proptypes = ttp.parseFromProgram(tsFile, program, {
shouldResolveObject: ({ name }) => {
if (name.toLowerCase().endsWith('classes') || name === 'theme' || name.endsWith('Props')) {
return false;
}
return undefined;
},
});
if (proptypes.body.length === 0) {
return GenerateResult.NoComponent;
}
proptypes.body.forEach((component) => {
component.types.forEach((prop) => {
if (prop.name === 'classes' && prop.jsDoc) {
prop.jsDoc += '\nSee [CSS API](#css) below for more details.';
} else if (prop.name === 'children' && !prop.jsDoc) {
prop.jsDoc = 'The content of the component.';
} else if (
!prop.jsDoc ||
(ignoreExternalDocumentation[component.name] &&
ignoreExternalDocumentation[component.name].includes(prop.name))
) {
prop.jsDoc = '@ignore';
}
});
});
const jsContent = await fse.readFile(jsFile, 'utf8');
const result = ttp.inject(proptypes, jsContent, {
removeExistingPropTypes: true,
comment: [
'----------------------------- Warning --------------------------------',
'| These PropTypes are generated from the TypeScript type definitions |',
'| To update them edit the d.ts file and run "yarn proptypes" |',
'----------------------------------------------------------------------',
].join('\n'),
reconcilePropTypes: (prop, previous, generated) => {
const usedCustomValidator = previous !== undefined && !previous.startsWith('PropTypes');
const ignoreGenerated =
previous !== undefined &&
previous.startsWith('PropTypes /* @typescript-to-proptypes-ignore */');
if (usedCustomValidator || ignoreGenerated) {
// `usedCustomValidator` and `ignoreGenerated` narrow `previous` to `string`
return previous!;
}
return generated;
},
shouldInclude: ({ component, prop, usedProps }) => {
if (prop.name === 'children') {
return true;
}
let shouldDocument;
const documentRegExp = new RegExp(/\r?\n?@document/);
if (prop.jsDoc && documentRegExp.test(prop.jsDoc)) {
prop.jsDoc = prop.jsDoc.replace(documentRegExp, '');
shouldDocument = true;
} else {
prop.filenames.forEach((filename) => {
const isExternal = filename !== tsFile;
if (!isExternal) {
shouldDocument = true;
}
});
}
const { name: componentName } = component;
if (
useExternalDocumentation[componentName] &&
useExternalDocumentation[componentName].includes(prop.name)
) {
shouldDocument = true;
}
return shouldDocument;
},
});
if (!result) {
return GenerateResult.Failed;
}
const prettified = prettier.format(result, { ...prettierConfig, filepath: jsFile });
const formatted = fixBabelGeneratorIssues(prettified);
const correctedLineEndings = fixLineEndings(jsContent, formatted);
await fse.writeFile(jsFile, correctedLineEndings);
return GenerateResult.Success;
}
interface HandlerArgv {
'disable-cache': boolean;
pattern: string;
verbose: boolean;
}
async function run(argv: HandlerArgv) {
const { 'disable-cache': ignoreCache, pattern, verbose } = argv;
const filePattern = new RegExp(pattern);
if (pattern.length > 0) {
console.log(`Only considering declaration files matching ${filePattern}`);
}
// Matches files where the folder and file both start with uppercase letters
// Example: AppBar/AppBar.d.ts
const allFiles = await Promise.all(
[
path.resolve(__dirname, '../packages/material-ui/src'),
path.resolve(__dirname, '../packages/material-ui-lab/src'),
].map((folderPath) =>
glob('+([A-Z])*/+([A-Z])*.d.ts', {
absolute: true,
cwd: folderPath,
}),
),
);
const files = _.flatten(allFiles)
// Filter out files where the directory name and filename doesn't match
// Example: Modal/ModalManager.d.ts
.filter((filePath) => {
const folderName = path.basename(path.dirname(filePath));
const fileName = path.basename(filePath, '.d.ts');
return fileName === folderName;
})
.filter((filePath) => {
return filePattern.test(filePath);
});
const program = ttp.createProgram(files, tsconfig);
const promises = files.map<Promise<GenerateResult>>(async (tsFile) => {
const jsFile = tsFile.replace('.d.ts', '.js');
if (!ignoreCache && (await fse.stat(jsFile)).mtimeMs > (await fse.stat(tsFile)).mtimeMs) {
// Javascript version is newer, skip file
return GenerateResult.Skipped;
}
return generateProptypes(tsFile, jsFile, program);
});
const results = await Promise.all(promises);
if (verbose) {
files.forEach((file, index) => {
console.log('%s - %s', GenerateResult[results[index]], path.basename(file, '.d.ts'));
});
}
console.log('--- Summary ---');
const groups = _.groupBy(results, (x) => x);
_.forOwn(groups, (count, key) => {
console.log('%s: %d', GenerateResult[(key as unknown) as GenerateResult], count.length);
});
console.log('Total: %d', results.length);
}
yargs
.command({
command: '$0',
describe: 'Generates Component.propTypes from TypeScript declarations',
builder: (command) => {
return command
.option('disable-cache', {
default: false,
describe: 'Considers all files on every run',
type: 'boolean',
})
.option('verbose', {
default: false,
describe: 'Logs result for each file',
type: 'boolean',
})
.option('pattern', {
default: '',
describe: 'Only considers declaration files matching this pattern.',
type: 'string',
});
},
handler: run,
})
.help()
.strict(true)
.version(false)
.parse();