Skip to content

Commit 8fb4010

Browse files
authored
Remove recast and use ast-types directly (#349)
* Remove recast and use ast-types directly * Add benchmark * Add custom serializer for NodePath * Support printing created identifiers * Fix test * Add comment * Fix lint * Fix typescript to not use recast and fix flow types
1 parent d1b07c4 commit 8fb4010

File tree

111 files changed

+1221
-1063
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

111 files changed

+1221
-1063
lines changed

.eslintrc.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ module.exports = {
1616
globals: {
1717
ASTNode: true,
1818
NodePath: true,
19-
Recast: true,
19+
$Exact: true,
2020
},
2121
overrides: [
2222
{
@@ -28,7 +28,7 @@ module.exports = {
2828
},
2929
},
3030
{
31-
files: 'src/**/__tests__/*-test.js',
31+
files: '@(src|bin)/**/__tests__/*-test.js',
3232
env: { jest: true },
3333
},
3434
],

README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
`react-docgen` is a CLI and toolbox to help extracting information from [React][] components, and generate documentation from it.
44

5-
It uses [recast][] and [@babel/parser][] to parse the source into an AST and provides methods to process this AST to extract the desired information. The output / return value is a JSON blob / JavaScript object.
5+
It uses [ast-types][] and [@babel/parser][] to parse the source into an AST and provides methods to process this AST to extract the desired information. The output / return value is a JSON blob / JavaScript object.
66

77
It provides a default implementation for React components defined via
88
`React.createClass`, [ES2015 class definitions][classes] or functions
@@ -82,8 +82,8 @@ As with the CLI, this will look for the exported component created through `Reac
8282
| Parameter | Type | Description |
8383
| -------------- | ------ | --------------- |
8484
| source | string | The source text |
85-
| resolver | function | A function of the form `(ast: ASTNode, recast: Object) => (NodePath|Array<NodePath>)`. Given an AST and a reference to recast, it returns an (array of) NodePath which represents the component definition. |
86-
| handlers | Array\<function\> | An array of functions of the form `(documentation: Documentation, definition: NodePath) => void`. Each function is called with a `Documentation` object and a reference to the component definition as returned by `resolver`. Handlers extract relevant information from the definition and augment `documentation`. |
85+
| resolver | function | A function of the form `(ast: ASTNode, parser: Parser) => (NodePath|Array<NodePath>)`. Given an AST and a reference to the parser, it returns an (array of) NodePath which represents the component definition. |
86+
| handlers | Array\<function\> | An array of functions of the form `(documentation: Documentation, definition: NodePath, parser: Parser) => void`. Each function is called with a `Documentation` object and a reference to the component definition as returned by `resolver`. Handlers extract relevant information from the definition and augment `documentation`. |
8787
| opt
8888

8989
#### options
@@ -412,6 +412,6 @@ The structure of the JSON blob / JavaScript object is as follows:
412412
[react]: http://facebook.github.io/react/
413413
[flow]: http://flowtype.org/
414414
[typescript]: http://typescriptlang.org/
415-
[recast]: https://github.com/benjamn/recast
415+
[ast-types]: https://github.com/benjamn/ast-types
416416
[@babel/parser]: https://github.com/babel/babel/tree/master/packages/babel-parser
417417
[classes]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
+249
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
import React from 'react';
2+
import PropTypes from 'prop-types';
3+
import clsx from 'clsx';
4+
import { chainPropTypes } from '@material-ui/utils';
5+
import withStyles from '../styles/withStyles';
6+
import { capitalize } from '../utils/helpers';
7+
8+
const SIZE = 44;
9+
10+
function getRelativeValue(value, min, max) {
11+
const clampedValue = Math.min(Math.max(min, value), max);
12+
return (clampedValue - min) / (max - min);
13+
}
14+
15+
function easeOut(t) {
16+
t = getRelativeValue(t, 0, 1);
17+
// https://gist.github.com/gre/1650294
18+
t = (t -= 1) * t * t + 1;
19+
return t;
20+
}
21+
22+
function easeIn(t) {
23+
return t * t;
24+
}
25+
26+
export const styles = theme => ({
27+
/* Styles applied to the root element. */
28+
root: {
29+
display: 'inline-block',
30+
lineHeight: 1, // Keep the progress centered
31+
},
32+
/* Styles applied to the root element if `variant="static"`. */
33+
static: {
34+
transition: theme.transitions.create('transform'),
35+
},
36+
/* Styles applied to the root element if `variant="indeterminate"`. */
37+
indeterminate: {
38+
animation: 'mui-progress-circular-rotate 1.4s linear infinite',
39+
// Backward compatible logic between JSS v9 and v10.
40+
// To remove with the release of Material-UI v4
41+
animationName: '$mui-progress-circular-rotate',
42+
},
43+
/* Styles applied to the root element if `color="primary"`. */
44+
colorPrimary: {
45+
color: theme.palette.primary.main,
46+
},
47+
/* Styles applied to the root element if `color="secondary"`. */
48+
colorSecondary: {
49+
color: theme.palette.secondary.main,
50+
},
51+
/* Styles applied to the `svg` element. */
52+
svg: {},
53+
/* Styles applied to the `circle` svg path. */
54+
circle: {
55+
stroke: 'currentColor',
56+
// Use butt to follow the specification, by chance, it's already the default CSS value.
57+
// strokeLinecap: 'butt',
58+
},
59+
/* Styles applied to the `circle` svg path if `variant="static"`. */
60+
circleStatic: {
61+
transition: theme.transitions.create('stroke-dashoffset'),
62+
},
63+
/* Styles applied to the `circle` svg path if `variant="indeterminate"`. */
64+
circleIndeterminate: {
65+
animation: 'mui-progress-circular-dash 1.4s ease-in-out infinite',
66+
// Backward compatible logic between JSS v9 and v10.
67+
// To remove with the release of Material-UI v4
68+
animationName: '$mui-progress-circular-dash',
69+
// Some default value that looks fine waiting for the animation to kicks in.
70+
strokeDasharray: '80px, 200px',
71+
strokeDashoffset: '0px', // Add the unit to fix a Edge 16 and below bug.
72+
},
73+
'@keyframes mui-progress-circular-rotate': {
74+
'100%': {
75+
transform: 'rotate(360deg)',
76+
},
77+
},
78+
'@keyframes mui-progress-circular-dash': {
79+
'0%': {
80+
strokeDasharray: '1px, 200px',
81+
strokeDashoffset: '0px',
82+
},
83+
'50%': {
84+
strokeDasharray: '100px, 200px',
85+
strokeDashoffset: '-15px',
86+
},
87+
'100%': {
88+
strokeDasharray: '100px, 200px',
89+
strokeDashoffset: '-125px',
90+
},
91+
},
92+
/* Styles applied to the `circle` svg path if `disableShrink={true}`. */
93+
circleDisableShrink: {
94+
animation: 'none',
95+
},
96+
});
97+
98+
/**
99+
* ## ARIA
100+
*
101+
* If the progress bar is describing the loading progress of a particular region of a page,
102+
* you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
103+
* attribute to `true` on that region until it has finished loading.
104+
*/
105+
const CircularProgress = React.forwardRef(function CircularProgress(
106+
props,
107+
ref,
108+
) {
109+
const {
110+
classes,
111+
className,
112+
color,
113+
disableShrink,
114+
size,
115+
style,
116+
thickness,
117+
value,
118+
variant,
119+
...other
120+
} = props;
121+
122+
const circleStyle = {};
123+
const rootStyle = {};
124+
const rootProps = {};
125+
126+
if (variant === 'determinate' || variant === 'static') {
127+
const circumference = 2 * Math.PI * ((SIZE - thickness) / 2);
128+
circleStyle.strokeDasharray = circumference.toFixed(3);
129+
rootProps['aria-valuenow'] = Math.round(value);
130+
131+
if (variant === 'static') {
132+
circleStyle.strokeDashoffset = `${(
133+
((100 - value) / 100) *
134+
circumference
135+
).toFixed(3)}px`;
136+
rootStyle.transform = 'rotate(-90deg)';
137+
} else {
138+
circleStyle.strokeDashoffset = `${(
139+
easeIn((100 - value) / 100) * circumference
140+
).toFixed(3)}px`;
141+
rootStyle.transform = `rotate(${(easeOut(value / 70) * 270).toFixed(
142+
3,
143+
)}deg)`;
144+
}
145+
}
146+
147+
return (
148+
<div
149+
className={clsx(
150+
classes.root,
151+
{
152+
[classes[`color${capitalize(color)}`]]: color !== 'inherit',
153+
[classes.indeterminate]: variant === 'indeterminate',
154+
[classes.static]: variant === 'static',
155+
},
156+
className,
157+
)}
158+
style={{ width: size, height: size, ...rootStyle, ...style }}
159+
ref={ref}
160+
role="progressbar"
161+
{...rootProps}
162+
{...other}
163+
>
164+
<svg
165+
className={classes.svg}
166+
viewBox={`${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`}
167+
>
168+
<circle
169+
className={clsx(classes.circle, {
170+
[classes.circleIndeterminate]: variant === 'indeterminate',
171+
[classes.circleStatic]: variant === 'static',
172+
[classes.circleDisableShrink]: disableShrink,
173+
})}
174+
style={circleStyle}
175+
cx={SIZE}
176+
cy={SIZE}
177+
r={(SIZE - thickness) / 2}
178+
fill="none"
179+
strokeWidth={thickness}
180+
/>
181+
</svg>
182+
</div>
183+
);
184+
});
185+
186+
CircularProgress.propTypes = {
187+
/**
188+
* Override or extend the styles applied to the component.
189+
* See [CSS API](#css) below for more details.
190+
*/
191+
classes: PropTypes.object.isRequired,
192+
/**
193+
* @ignore
194+
*/
195+
className: PropTypes.string,
196+
/**
197+
* The color of the component. It supports those theme colors that make sense for this component.
198+
*/
199+
color: PropTypes.oneOf(['primary', 'secondary', 'inherit']),
200+
/**
201+
* If `true`, the shrink animation is disabled.
202+
* This only works if variant is `indeterminate`.
203+
*/
204+
disableShrink: chainPropTypes(PropTypes.bool, props => {
205+
if (props.disableShrink && props.variant !== 'indeterminate') {
206+
return new Error(
207+
'Material-UI: you have provided the `disableShrink` property ' +
208+
'with a variant other than `indeterminate`. This will have no effect.',
209+
);
210+
}
211+
212+
return null;
213+
}),
214+
/**
215+
* The size of the circle.
216+
*/
217+
size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
218+
/**
219+
* @ignore
220+
*/
221+
style: PropTypes.object,
222+
/**
223+
* The thickness of the circle.
224+
*/
225+
thickness: PropTypes.number,
226+
/**
227+
* The value of the progress indicator for the determinate and static variants.
228+
* Value between 0 and 100.
229+
*/
230+
value: PropTypes.number,
231+
/**
232+
* The variant to use.
233+
* Use indeterminate when there is no progress value.
234+
*/
235+
variant: PropTypes.oneOf(['determinate', 'indeterminate', 'static']),
236+
};
237+
238+
CircularProgress.defaultProps = {
239+
color: 'primary',
240+
disableShrink: false,
241+
size: 40,
242+
thickness: 3.6,
243+
value: 0,
244+
variant: 'indeterminate',
245+
};
246+
247+
export default withStyles(styles, { name: 'MuiCircularProgress', flip: false })(
248+
CircularProgress,
249+
);

benchmark/index.js

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/* eslint-disable */
2+
const fs = require('fs');
3+
const path = require('path');
4+
const Table = require('cli-table');
5+
const Benchmark = require('benchmark');
6+
const { parse } = require('..');
7+
8+
console.log(`Node: ${process.version}`);
9+
10+
const head = ['fixture', 'timing'];
11+
12+
const files = ['./fixtures/CircularProgress.js'];
13+
14+
const table = new Table({
15+
head,
16+
style: {
17+
head: ['bold'],
18+
},
19+
});
20+
21+
if (!global.gc) {
22+
console.error(
23+
'Garbage collection unavailable. Pass --expose-gc ' +
24+
'when launching node to enable forced garbage collection.',
25+
);
26+
process.exit();
27+
}
28+
29+
files.forEach(file => {
30+
const code = fs.readFileSync(path.join(__dirname, file), 'utf-8');
31+
const suite = new Benchmark.Suite(file.replace(/\.\/fixtures\//, ''));
32+
const options = { filename: file, babelrc: false, configFile: false };
33+
34+
// warmup
35+
parse(code, null, null, options);
36+
global.gc();
37+
suite.add(0, () => {
38+
parse(code, null, null, options);
39+
});
40+
const result = [suite.name];
41+
suite.on('cycle', function(event) {
42+
{
43+
// separate scope so we can cleanup all this afterwards
44+
const bench = event.target;
45+
const factor = bench.hz < 100 ? 100 : 1;
46+
const msg = `${Math.round(bench.hz * factor) /
47+
factor} ops/sec ±${Math.round(bench.stats.rme * 100) /
48+
100}% (${Math.round(bench.stats.mean * 1000)}ms)`;
49+
result.push(msg);
50+
}
51+
global.gc();
52+
});
53+
54+
console.log(`Running benchmark for ${suite.name} ...`);
55+
global.gc();
56+
suite.run({ async: false });
57+
global.gc(); // gc is disabled so ensure we run it
58+
table.push(result);
59+
});
60+
global.gc(); // gc is disabled so ensure we run it
61+
console.log(table.toString());

bin/__tests__/example/customResolver.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@ const code = `
1616
})
1717
`;
1818

19-
module.exports = function(ast, recast) {
20-
return new recast.types.NodePath(recast.parse(code)).get(
19+
const { NodePath } = require('ast-types');
20+
21+
module.exports = function(ast, parser) {
22+
return new NodePath(parser.parse(code)).get(
2123
'program',
2224
'body',
2325
0,

bin/__tests__/react-docgen-test.js

+1-5
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,11 @@
66
*
77
*/
88

9-
/*global jasmine, describe, it, expect, afterEach*/
10-
119
// NOTE: This test spawns a subprocesses that load the files from dist/, not
1210
// src/. Before running this test run `npm run build` or `npm run watch`.
1311

1412
const TEST_TIMEOUT = 120000;
1513

16-
jasmine.DEFAULT_TIMEOUT_INTERVAL = TEST_TIMEOUT;
17-
1814
const fs = require('fs');
1915
const path = require('path');
2016
const rimraf = require('rimraf');
@@ -90,7 +86,7 @@ describe('react-docgen CLI', () => {
9086
tempDir = null;
9187
tempComponents = [];
9288
tempNoComponents = [];
93-
});
89+
}, TEST_TIMEOUT);
9490

9591
it(
9692
'reads from stdin',

0 commit comments

Comments
 (0)