-
Notifications
You must be signed in to change notification settings - Fork 833
/
type-definition.js
421 lines (376 loc) · 11.7 KB
/
type-definition.js
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
/*
Copyright (c) 2018-2019 Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
/* eslint-disable flowtype/require-valid-file-annotation */
import * as React from 'react';
import {useStyletron} from 'baseui';
import {formatCode} from 'react-view';
export function resolveToLast(type) {
switch (type.kind) {
case 'id':
case 'object':
case 'import':
return type;
case 'memberExpression':
return resolveToLast(type.object);
default:
break;
}
}
export function resolveFromGeneric(type) {
if (type.kind !== 'generic') return type;
if (type.typeParams) {
// If a generic type is an Array, we don't want to just return the value,
// But also the entire type object, so we can parse the typeParams later on.
return type;
}
if (type.value.kind === 'generic') {
return resolveFromGeneric(type.value);
}
return type.value;
}
export function reduceToObj(type) {
const reducableKinds = ['generic', 'object', 'intersection'];
if (type.kind === 'generic') {
// Only attempt to reduce generic if it has a reducable value
// Unreducable generics that have an identifier value, e.g. ElementConfig, are still valid
// so we return early to avoid the console warn below
return reducableKinds.includes(type.value.kind)
? reduceToObj(type.value)
: [];
} else if (type.kind === 'object') {
return type.members;
} else if (type.kind === 'intersection') {
return type.types.reduce((acc, i) => [...acc, ...reduceToObj(i)], []);
}
/* eslint-disable-next-line no-console */
console.warn('was expecting to reduce to an object and could not', type);
return [];
}
const unaryWhiteList = ['-', '+', '!'];
function mapConvertAndJoin(array, joiner = ', ') {
if (!Array.isArray(array)) return '';
return array.map(a => convert(a)).join(joiner);
}
const converters = {
/*
If the value here is undefined, we can safely assume that we're dealing with
a BooleanTypeAnnotation and not a BooleanLiteralTypeAnnotation.
*/
boolean: type => (type.value != null ? type.value.toString() : type.kind),
exists: type => '*',
/*
If the value here is undefined, we can safely assume that we're dealing with
a NumberTypeAnnotation and not a NumberLiteralTypeAnnotation.
*/
number: type => (type.value != null ? type.value.toString() : type.kind),
/*
If the value here is undefined, we can safely assume that we're dealing with
a StringTypeAnnotation and not a StringLiteralTypeAnnotation.
*/
string: type =>
type.value != null ? `"${type.value.toString()}"` : type.kind,
custom: type => type.value.toString(),
any: type => type.kind,
void: type => 'undefined',
literal: type => `${type.kind}`,
mixed: type => type.kind,
null: type => 'null',
logicalExpression: type => {
return `${convert(type.left)} ${type.operator} ${convert(type.right)}`;
},
unary: type => {
let space = unaryWhiteList.includes(type.operator) ? '' : ' ';
return `${type.operator}${space}${convert(type.argument)}`;
},
id: type => {
return type.name;
},
// this is not right and needs to be improved
opaqueType: type => {
return convert(type.id);
},
interfaceDeclaration: type => {
return convert(type.id);
},
typeCastExpression: type => {
return convert(type.expression);
},
JSXMemberExpression: type => {
return `${convert(type.object)}.${convert(type.property)}`;
},
JSXExpressionContainer: type => {
return `{${convert(type.expression)}}`;
},
JSXOpeningElement: type => {
return `${convert(type.name)} ${mapConvertAndJoin(type.attributes, ' ')}`;
},
JSXElement: type => {
return `<${convert(type.value)} />`;
},
JSXIdentifier: type => {
return `${type.value}`;
},
JSXAttribute: type => {
return `${convert(type.name)}=${convert(type.value)}`;
},
binary: type => {
const left = convert(type.left);
const right = convert(type.right);
return `${left} ${type.operator} ${right}`;
},
function: type => {
return `(${mapConvertAndJoin(type.parameters)}) => ${
type.returnType === null ? 'undefined' : convert(type.returnType)
}`;
},
/*
Make this resolve members in a unique way that will allow us to
handle property keys with no assigned value
*/
objectPattern: type => {
// ({ a, b }) => undefined ({a: a, b: b}) => undefined
// ({ a = 2, b }) => undefined ({a: a = 2, b: b })=> undefined
return `{ ${mapConvertAndJoin(type.members)} }`;
},
rest: type => {
return `...${convert(type.argument)}`;
},
assignmentPattern: type => {
return `${convert(type.left)} = ${convert(type.right)}`;
},
param: type => {
// this will not hold once we have types
return convert(type.value);
},
array: type => {
return `[${mapConvertAndJoin(type.elements)}]`;
},
arrayType: type => {
// return `Array of ${convert(type.type)}`;
return `Array<${convert(type.type)}>`;
},
spread: type => {
return `...${convert(type.value)}`;
},
property: type => {
// const sameId =
// type.key.kind === 'id' &&
// type.value.kind === 'id' &&
// type.key.name === type.value.name;
// const assignmentSameId =
// type.value.kind === 'assignmentPattern' &&
// type.key.kind === 'id' &&
// type.value.left.kind === 'id' &&
// type.key.name === type.value.left.name;
// if (sameId) {
// // If both keys are IDs we're applying syntactic sugar
// return `${convert(type.key)}`;
// } else if (assignmentSameId) {
// // If the value is an assignment pattern with a left hand ID that is the same as our type.key, just return the resolved value.
// return `${convert(type.value)}`;
// } else {
return `${convert(type.key)}${type.optional ? '?' : ''}: ${convert(
type.value,
)}`;
// }
},
object: type => {
if (type.members.length === 0) return `{}`;
return `{ ${mapConvertAndJoin(type.members)} }`;
},
memberExpression: type => {
const object = resolveToLast(type.object);
const property = convert(type.property);
switch (object.kind) {
case 'id':
return `${convert(type.object)}.${property}`;
case 'object': {
const mem = object.members.find(m => {
if (typeof m.key !== 'string') {
// Issue here is that convert(key) can result in either a String type or an Id type,
// one returns the value wrapped in quotations, the other does not.
// We're stripping the quotations so we can do an accurate match against the property which is always an Id
return convert(m.key).replace(/"/g, '') === property;
}
return m.key === property;
});
if (mem && mem.value) {
return convert(mem.value);
} else {
console.error(`${property} not found in ${convert(object)}`);
return 'undefined';
}
}
case 'import':
return `${convert(type.object)}.${property}`;
default:
console.error('failed to resolve member expression');
return '';
}
},
call: type => {
let callSignature = '';
if (type.callee.referenceIdName) {
callSignature = type.callee.referenceIdName;
} else if (type.callee.id) {
callSignature = convert(type.callee.id);
} else {
callSignature = convert(type.callee);
}
// $FlowFixMe - this is incorrectly reading type.callee.referenceIdName as possibly not a string.
return `${callSignature}(${mapConvertAndJoin(type.args)})`;
},
new: type => {
const callee = convert(type.callee);
const args = mapConvertAndJoin(type.args);
return `new ${callee}(${args})`;
},
variable: type => {
const val = type.declarations[type.declarations.length - 1];
if (val.value) {
return convert(val.value);
}
return convert(val.id);
},
templateExpression: type => {
return `${convert(type.tag)}`;
},
templateLiteral: type => {
let str = type.quasis.reduce((newStr, v, i) => {
let quasi = convert(v);
let newStrClone = newStr;
newStrClone = `${newStrClone}${quasi}`;
if (type.expressions[i]) {
let exp = convert(type.expressions[i]);
newStrClone = `${newStrClone}\${${exp}}`;
}
return newStrClone;
}, '');
return `\`${str}\``;
},
templateElement: type => {
return type.value.cooked.toString();
},
class: type => {
return convert(type.name);
},
// We should write these
generic: type => {
const typeParams = type.typeParams ? convert(type.typeParams) : '';
const value = convert(type.value);
return `${value}${typeParams}`;
},
intersection: type => `${mapConvertAndJoin(type.types, ' & ')}`,
nullable: type => `?${convert(type.arguments)}`,
typeParam: type => `${type.name}`,
typeParams: type => `<${mapConvertAndJoin(type.params, ', ')}>`,
typeParamsDeclaration: type => `<${mapConvertAndJoin(type.params, ', ')}>`,
typeof: type => {
return type.name ? `typeof ${type.name}` : `${type.type.kind}`;
},
union: type => `${mapConvertAndJoin(type.types, ' | ')}`,
import: type => {
if (type.name === 'default') {
return `${type.moduleSpecifier}`;
} else {
return `${type.moduleSpecifier}.${type.name}`;
}
},
export: type => {
if (type.exports.length === 1) {
return convert(type.exports[0]);
}
return '';
},
exportSpecifier: (type, mode) => convert(type.exported),
// TS
tuple: type => `[${mapConvertAndJoin(type.types)}]`,
};
function convert(type, expandType) {
if (!type) {
console.error('No type argument has been passed in');
return '';
}
if (type.referenceIdName && !expandType) {
return type.referenceIdName;
}
const converter = converters[type.kind];
if (!converter) {
if (!type.kind) {
console.error('convert was passed an object without a kind', type);
} else {
console.error('could not find converter for', type.kind);
}
} else {
return converter(type);
}
return '';
}
const getPropTypes = propTypesObj => {
let resolvedTypes = resolveFromGeneric(propTypesObj);
let propTypes;
if (resolvedTypes.kind === 'object') {
propTypes = resolvedTypes.members;
} else if (resolvedTypes.kind === 'intersection') {
propTypes = resolvedTypes.types.reduce(
(acc, type) => [...acc, ...reduceToObj(type)],
[],
);
}
return propTypes;
};
function TypeDefinition(props) {
const [css, theme] = useStyletron();
let name = '';
let value = null;
let definition = '';
let errored = false;
try {
if (props.type.component.value.name === '$Shape') {
value = props.type.component.typeParams.params[0];
name = value.value.referenceIdName;
} else {
value = props.type.component.value;
name = value.referenceIdName;
}
const proptypes = getPropTypes(value).map(property => {
return convert(property, true);
});
definition = formatCode(`type ${name} = {` + proptypes.join(',') + '}');
} catch (e) {
errored = true;
}
if (errored) {
return (
<div
className={css({
paddingLeft: theme.sizing.scale700,
paddingRight: theme.sizing.scale700,
})}
>
<p>
extract-react-types is not being run in dev mode for speed reasons. If
you need to see prop types, run:
</p>
<p>
<code>FORCE_EXTRACT_REACT_TYPES=true yarn documentation:dev</code>
</p>
</div>
);
}
return (
<div
className={css({
whiteSpace: 'pre',
fontFamily: 'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',
fontSize: theme.sizing.scale500,
})}
>
{definition}
</div>
);
}
export default TypeDefinition;