forked from elastic/eui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact-docgen-typescript.js
More file actions
421 lines (389 loc) Β· 13.8 KB
/
react-docgen-typescript.js
File metadata and controls
421 lines (389 loc) Β· 13.8 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
/* eslint-disable @typescript-eslint/no-var-requires */
const gc = require('expose-gc/function');
const propsParser = require('react-docgen-typescript');
const template = require('@babel/template');
const ts = require('typescript');
const glob = require('glob');
const util = require('util');
const { SyntaxKind } = require('typescript');
const chokidar = require('chokidar');
const { NODE_ENV, CI, WEBPACK_DEV_SERVER } = process.env;
const isDevelopment = WEBPACK_DEV_SERVER === 'true' && CI == null;
const bypassWatch = NODE_ENV === 'puppeteer' || NODE_ENV === 'production';
/**
* To support extended props from tsx files.
*/
const programOptions = {
jsx: ts.JsxEmit.React,
};
let program;
function buildProgram() {
const files = [
...glob.sync('src/**/!(*.test).{ts,tsx}', { absolute: true }),
...glob.sync('src-docs/**/!(*.test).{ts,tsx}', { absolute: true }),
];
program = null;
gc();
program = ts.createProgram(files, programOptions);
}
buildProgram();
if (isDevelopment && !bypassWatch) {
chokidar
.watch(['./src/**/*.(ts|tsx)', './src-docs/**/*.(ts|tsx)'], {
ignoreInitial: true, // don't emit `add` event during file discovery
ignored: ['__snapshots__', /\.test\./],
})
.on('add', buildProgram)
.on('change', buildProgram);
}
module.exports = function ({ types }) {
return {
pre() {
this.fileProcessed = false;
},
visitor: {
Program: {
enter: function visitNode(path, state) {
const { filename } = state.file.opts;
if (this.fileProcessed) return;
this.fileProcessed = true;
// find if components extends types from other modules
const componentExtends = [];
// props that should be whitelisted even if its from an external module
const whiteListedProps = ['children', 'className', 'aria-label'];
// external modules whose props must be whitelisted
const whiteListedParent = [
'AutoSizerProps',
'DragDropContextProps',
'DraggableProps',
'DroppableProps',
'RefAttributes',
];
let docgenResults = [];
try {
docgenResults = propsParser
.withDefaultConfig({
propFilter: (prop, component) =>
filterProp(
prop,
component,
state,
whiteListedProps,
whiteListedParent,
componentExtends
),
shouldExtractLiteralValuesFromEnum: true,
shouldRemoveUndefinedFromOptional: true,
savePropValueAsString: true,
})
.parseWithProgramProvider(filename, () => program);
// eslint-disable-next-line no-empty
} catch (e) {}
/**
* react-docgen-typescript takes type of children from PropsWithChildren of FunctionComponent,
* For our case we need our custom types to replace them.
*/
if (state.get('childrenProp') && state.get('componentName')) {
getChildrenTypeFromPropTypes(
state.get('childrenProp'),
state.get('componentName'),
program,
filename
);
}
if (docgenResults.length !== 0) {
docgenResults.forEach(function (docgenResult) {
const exportName = docgenResult.displayName;
docgenResult.extendedInterfaces = componentExtends;
path.node.body.push(
template.default.ast(`
try{
${exportName}.__docgenInfo = ${util.inspect(docgenResult, {
showHidden: false,
depth: null,
maxArrayLength: null,
})}
} catch(e) {}
`)
);
});
}
// get all the exported types and interfaces of all the files to the state remove their exported
// declarations in the exit stage
if (!state.get('exportedTypes')) {
let allExportedTypes = [];
program.getSourceFiles().forEach((source) => {
const exportedTypes = source
.getChildAt(0)
.getChildren()
.filter((child) => {
if (
child.kind !== SyntaxKind.InterfaceDeclaration &&
child.kind !== SyntaxKind.TypeAliasDeclaration
)
return false;
// verify this interface is exported
const isExported =
child.modifiers &&
child.modifiers.reduce((isExported, modifier) => {
if (isExported) return isExported;
if (modifier.kind === SyntaxKind.ExportKeyword)
return true;
return false;
}, false);
return isExported;
})
.map((type) => type.name.escapedText);
allExportedTypes = [...allExportedTypes, ...exportedTypes];
});
state.set('exportedTypes', allExportedTypes);
}
},
exit: function exitProgram(path, state) {
// remove any exported identifiers that are TS types or interfaces
// this prevents TS-only identifiers from leaking into ES code
path.traverse({
ExportNamedDeclaration: (nodePath) => {
const specifiers = nodePath.get('specifiers');
const typeDefinitions = state.get('exportedTypes');
const source = nodePath.get('source');
specifiers.forEach((specifierPath) => {
if (types.isExportSpecifier(specifierPath)) {
const {
node: { local },
} = specifierPath;
if (types.isIdentifier(local)) {
const { name } = local;
if (typeDefinitions.includes(name)) {
// this is a locally-known value
specifierPath.remove();
} else if (types.isStringLiteral(source)) {
const libraryName = source.get('value').node;
const isRelativeSource = libraryName.startsWith('.');
if (isRelativeSource === false) {
// comes from a 3rd-party library
// best way to reliably check if this is
// a type or value is to require the
// library and check its exports
const library = require(libraryName);
if (library.hasOwnProperty(name) === false) {
specifierPath.remove();
}
}
}
}
}
});
},
});
},
},
},
};
};
/**
* Filter props to remove props from node modules while keeping those whitelisted
*
* @param {*} prop
* @param {*} state
* @param {*} whiteListedProps
* @param {*} whiteListedParent
* @param {*} componentExtends
*/
function filterProp(
prop,
component,
state,
whiteListedProps,
whiteListedParent,
componentExtends
) {
if (prop.name === 'children') {
state.set('childrenProp', prop);
state.set('componentName', component.name);
}
if (whiteListedProps.includes(prop.name)) {
return true;
}
if (prop.type.name === 'ReactText') {
// if prop type is string | number typescript takes it as ReactText if HTMLAttributes are extended
// in the interface in that case replace it with "string | number"
prop.type.name = 'string | number';
} else if (prop.type.name === 'Primitive') {
// "Primitive" comes from src/services/sort/comparators.ts
// TypeScript sees its overlap with `boolean | number | string` and decides to name the type union
prop.type.name = 'boolean | number | string';
}
// if prop.type is ReactElement it will be expanded to show all the supported
// react element types that makes the list too long in this case we could show
// it as ReactElement
prop.type.name = prop.type.name.replace(
reactElementTypeExpanded,
'ReactElement'
);
prop.type.name = prop.type.name.replace(reactNodeTypeExpanded, 'ReactNode');
// prop.type is key of HTMLElement then all the html attributes will be shown
// in that case we could only show it as any HTML Elements
if (prop.type.name === 'enum') {
const propValueArray = prop.type.value.map((type) => type.value);
const found = intrinsicValuesRaw.every(
(value) => propValueArray.indexOf(value) >= 0
);
if (found) {
prop.type.name = 'any HTML Element';
}
}
if (prop.parent) {
//Check if props are extended from other node module
if (whiteListedParent.includes(prop.parent.name)) return true;
if (!componentExtends.includes(prop.parent.name)) {
componentExtends.push(prop.parent.name);
}
if (prop.name.includes(whiteListedProps)) {
return true;
}
if (prop.parent.fileName.includes('@elastic/charts')) return true;
return !prop.parent.fileName.includes('node_modules');
}
return true;
}
/**
* Parser takes type generated for children prop from PropsWithChildren. Here
* children prop is parsed from the interface used the component by reusing
* typescript program.
*
* @param {*} initialProp
* @param {*} componentName
* @param {*} program
* @param {*} filename
*/
function getChildrenTypeFromPropTypes(
initialProp,
componentName,
program,
filename
) {
const source = program.getSourceFile(filename);
const checker = program.getTypeChecker();
// Get the symbol property of the source file
const moduleSymbol = checker.getSymbolAtLocation(source);
// Components must be mostly exported.
const components = checker.getExportsOfModule(moduleSymbol);
/**
* A single file may contain many components. Filter the component whose children prop
* has to be updated
*/
const componentToParse = components.filter(
(component) => component.escapedName === componentName
)[0];
/**
* If there are no declarations, then there will be no interfaces.
*/
if (
!!componentToParse.declarations &&
componentToParse.declarations.length === 0
) {
return null;
}
const declaration =
componentToParse.valueDeclaration ||
(componentToParse.declarations && componentToParse.declarations[0]);
// get Type of the component symbol
const type = checker.getTypeOfSymbolAtLocation(componentToParse, declaration);
// For stateless components there will be callSignatures.
const callSignatures = type.getCallSignatures();
if (callSignatures && callSignatures.length) {
for (const sig of callSignatures) {
const params = sig.getParameters();
// if there are no parameters then there will be no props
if (params.length === 0) {
continue;
}
const propsParam = params[0];
if (propsParam.name === 'props') {
replaceProp(propsParam, checker, initialProp);
}
}
} else {
// For for statefull components there will be constructSignatures.
const constructSignatures = type.getConstructSignatures();
if (constructSignatures && constructSignatures.length) {
for (const sig of constructSignatures) {
const instanceType = sig.getReturnType();
const props = instanceType.getProperty('props');
if (props.valueDeclaration) {
replaceProp(props, checker, initialProp);
}
}
}
}
}
/**
* Replace children prop type and required from information from interface
*
* @param {*} props
* @param {*} checker
* @param {*} initialProp
*/
function replaceProp(props, checker, initialProp) {
const propsType = checker.getTypeOfSymbolAtLocation(
props,
props.valueDeclaration
);
// get all the props of the interface
const propTypes = propsType.getProperties();
// filter to get the children prop
const childrenProp = propTypes.filter(
(prop) => prop.getName() === 'children'
)[0];
/**
* get the first declaration of the props, skip if children prop is from DOMAttributes,
* propsWithChildren declaration only occurs last
*/
const prop = childrenProp.declarations.filter(
(declarations) => declarations.parent.symbol.name !== 'DOMAttributes'
)[0];
if (prop) {
prop.symbol.parent.members.forEach((value, key) => {
if (key === 'children') {
const propType = checker.getTypeOfSymbolAtLocation(
value,
value.valueDeclaration
);
const type = checker.typeToString(propType);
initialProp.required = !prop.questionToken;
initialProp.type.name = type.replace(' | undefined', '');
initialProp.type.name = initialProp.type.name.replace(
reactElementTypeExpanded,
'ReactElement'
);
initialProp.type.name = initialProp.type.name.replace(
reactNodeTypeExpanded,
'ReactNode'
);
}
});
}
}
/**
* For types declared as (key of HTMLElements) all the HTML Element types will appear. This creates a large
* list of types. To avoid this we could check if the props the props include the firse few keys of HTMLElements
*/
const intrinsicValuesRaw = [
'"a"',
'"abbr"',
'"address"',
'"animate"',
'"animateMotion"',
'"animateTransform"',
'"area"',
'"article"',
'"aside"',
'"audio"',
];
/**
* Replace ReactElement and ReactNode expanded types with ReactElement and ReactNode
*/
const reactElementTypeExpanded =
'ReactElement<any, string | JSXElementConstructor<any>>';
const reactNodeTypeExpanded = /(string \| number \| boolean \| {} \| ReactElement \| ReactNodeArray \| ReactPortal)( \| \({} & string\).+\(ReactPortal & string\))?/g;