-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathgenerateProptypes.ts
354 lines (315 loc) · 9.97 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
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
/* eslint-disable no-console */
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,
TODO,
}
/**
* Includes component names for which we can't generate .propTypes from the TypeScript types.
*/
const todoComponents: string[] = [];
const useExternalPropsFromInputBase = [
'autoComplete',
'autoFocus',
'color',
'defaultValue',
'disabled',
'endAdornment',
'error',
'id',
'inputProps',
'inputRef',
'margin',
'maxRows',
'minRows',
'name',
'onChange',
'placeholder',
'readOnly',
'required',
'rows',
'startAdornment',
'value',
];
/**
* 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[]> = {
Button: ['disableRipple'],
// `classes` is always external since it is applied from a HOC
// In DialogContentText we pass it through
// Therefore it's considered "unused" in the actual component but we still want to document it.
DialogContentText: ['classes'],
FilledInput: useExternalPropsFromInputBase,
IconButton: ['disableRipple'],
Input: useExternalPropsFromInputBase,
MenuItem: ['dense'],
OutlinedInput: useExternalPropsFromInputBase,
Radio: ['disableRipple', 'id', 'inputProps', 'inputRef', 'required'],
Switch: [
'checked',
'defaultChecked',
'disabled',
'disableRipple',
'edge',
'id',
'inputProps',
'inputRef',
'onChange',
'required',
'value',
],
SwipeableDrawer: [
'anchor',
'hideBackdrop',
'ModalProps',
'PaperProps',
'transitionDuration',
'variant',
],
Tab: ['disableRipple'],
ToggleButton: ['disableRipple'],
};
const transitionCallbacks = [
'onEnter',
'onEntered',
'onEntering',
'onExit',
'onExiting',
'onExited',
];
/**
* 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[]> = {
Button: ['focusVisibleClassName', 'type'],
Collapse: transitionCallbacks,
CardActionArea: ['focusVisibleClassName'],
AccordionSummary: ['onFocusVisible'],
Dialog: ['BackdropProps'],
Drawer: ['BackdropProps'],
Fab: ['focusVisibleClassName'],
Fade: transitionCallbacks,
Grow: transitionCallbacks,
ListItem: ['focusVisibleClassName'],
InputBase: ['aria-describedby'],
Menu: ['PaperProps'],
MenuItem: ['button', 'disabled', 'selected'],
Slide: transitionCallbacks,
SwipeableDrawer: ['anchor', 'hideBackdrop', 'ModalProps', 'PaperProps', 'variant'],
TextField: ['hiddenLabel'],
Zoom: transitionCallbacks,
};
function sortBreakpointsLiteralByViewportAscending(a: ttp.LiteralType, b: ttp.LiteralType) {
// default breakpoints ordered by their size ascending
const breakpointOrder: unknown[] = ['"xs"', '"sm"', '"md"', '"lg"', '"xl"'];
return breakpointOrder.indexOf(a.value) - breakpointOrder.indexOf(b.value);
}
// Custom order of literal unions by component
const getSortLiteralUnions: ttp.InjectOptions['getSortLiteralUnions'] = (component, propType) => {
if (
component.name === 'Hidden' &&
(propType.name === 'initialWidth' || propType.name === 'only')
) {
return sortBreakpointsLiteralByViewportAscending;
}
return undefined;
};
const tsconfig = ttp.loadConfig(path.resolve(__dirname, '../tsconfig.json'));
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), {
config: path.join(__dirname, '../prettier.config.js'),
});
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;
},
checkDeclarations: true,
});
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.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,
babelOptions: {
filename: jsFile,
},
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'),
getSortLiteralUnions,
reconcilePropTypes: (prop, previous, generated) => {
const usedCustomValidator = previous !== undefined && !previous.startsWith('PropTypes');
const ignoreGenerated =
previous !== undefined &&
previous.startsWith('PropTypes /* @typescript-to-proptypes-ignore */');
if (
ignoreGenerated &&
// `ignoreGenerated` implies that `previous !== undefined`
previous!
.replace('PropTypes /* @typescript-to-proptypes-ignore */', 'PropTypes')
.replace(/\s/g, '') === generated.replace(/\s/g, '')
) {
throw new Error(
`Unused \`@typescript-to-proptypes-ignore\` directive for prop '${prop.name}'.`,
);
}
if (usedCustomValidator || ignoreGenerated) {
// `usedCustomValidator` and `ignoreGenerated` narrow `previous` to `string`
return previous!;
}
return generated;
},
shouldInclude: ({ component, prop }) => {
if (prop.name === 'children') {
return true;
}
let shouldDocument;
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 {
pattern: string;
verbose: boolean;
}
async function run(argv: HandlerArgv) {
const { 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.createTSProgram(files, tsconfig);
const promises = files.map<Promise<GenerateResult>>(async (tsFile) => {
const jsFile = tsFile.replace('.d.ts', '.js');
if (todoComponents.includes(path.basename(jsFile, '.js'))) {
return GenerateResult.TODO;
}
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('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();