-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathindex.js
157 lines (137 loc) · 5 KB
/
index.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
import { extname, dirname } from 'path';
import { readFileSync } from 'fs';
import template from 'babel-template';
import traverse from 'babel-traverse';
import { parse } from 'babylon';
import resolveFrom from 'resolve-from';
import optimize from './optimize';
import escapeBraces from './escapeBraces';
import transformSvg from './transformSvg';
import fileExistsWithCaseSync from './fileExistsWithCaseSync';
const buildSvg = template(`
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
`);
const buildSvgWithDefaults = template(`
var SVG_NAME = function SVG_NAME(props) { return SVG_CODE; };
SVG_NAME.defaultProps = SVG_DEFAULT_PROPS_CODE;
`);
const buildSvgSF = template(`
class SVG_NAME extends React.Component {
render (){
const props = Object.assign({}, this.props);
const refcb = this.props.svgRef ? this.props.svgRef : function(){}
delete props.svgRef
return SVG_CODE
}
}
`);
const buildSvgWithDefaultsSF = template(`
class SVG_NAME extends React.Component {
render (){
const props = Object.assign({}, this.props);
const refcb = this.props.svgRef ? this.props.svgRef : function(){}
delete props.svgRef
return SVG_CODE
}
}
SVG_NAME.defaultProps = SVG_DEFAULT_PROPS_CODE;
`);
let ignoreRegex;
export default ({ types: t }) => ({
visitor: {
Program: {
enter({ scope, node }, { file }) {
if (!scope.hasBinding('React')) {
const reactImportDeclaration = t.importDeclaration([
t.importDefaultSpecifier(t.identifier('React')),
], t.stringLiteral('react'));
file.set('ensureReact', () => { node.body.unshift(reactImportDeclaration); });
} else {
file.set('ensureReact', () => {});
}
},
},
ImportDeclaration(path, state) {
const importPath = path.node.source.value;
const { ignorePattern, caseSensitive, statefulComponent } = state.opts;
const { file } = state;
if (ignorePattern) {
// Only set the ignoreRegex once:
ignoreRegex = ignoreRegex || new RegExp(ignorePattern);
// Test if we should ignore this:
if (ignoreRegex.test(importPath)) {
return;
}
}
// This plugin only applies for SVGs:
if (extname(importPath) === '.svg') {
// We only support the import default specifier, so let's use that identifier:
const importIdentifier = path.node.specifiers[0].local;
const iconPath = state.file.opts.filename;
const svgPath = resolveFrom(dirname(iconPath), importPath);
if (caseSensitive && !fileExistsWithCaseSync(svgPath)) {
throw new Error(`File path didn't match case of file on disk: ${svgPath}`);
}
if (!svgPath) {
throw new Error(`File path does not exist: ${importPath}`);
}
const rawSource = readFileSync(svgPath, 'utf8');
const optimizedSource = state.opts.svgo === false
? rawSource
: optimize(rawSource, state.opts.svgo);
const escapeSvgSource = escapeBraces(optimizedSource);
const parsedSvgAst = parse(escapeSvgSource, {
sourceType: 'module',
plugins: ['jsx'],
});
traverse(parsedSvgAst, transformSvg(t));
const svgCode = traverse.removeProperties(parsedSvgAst.program.body[0].expression);
const opts = {
SVG_NAME: importIdentifier,
SVG_CODE: svgCode,
};
// Move props off of element and into defaultProps
if (svgCode.openingElement.attributes.length > 1) {
const keepProps = [];
const defaultProps = [];
svgCode.openingElement.attributes.forEach((prop) => {
if (prop.type === 'JSXSpreadAttribute') {
keepProps.push(prop);
} else {
defaultProps.push(t.objectProperty(t.identifier(prop.name.name), prop.value));
}
});
svgCode.openingElement.attributes = keepProps
if (statefulComponent){
svgCode.openingElement.attributes.push(
t.jSXAttribute(
t.jSXIdentifier('ref'),
t.jSXExpressionContainer(
t.arrowFunctionExpression(
[t.identifier('el')],
t.callExpression(
t.identifier('refcb'),
[t.identifier('el')]
)
)
)
)
);
}
opts.SVG_DEFAULT_PROPS_CODE = t.objectExpression(defaultProps);
}
if (opts.SVG_DEFAULT_PROPS_CODE) {
const svgReplacement = (
statefulComponent ? buildSvgWithDefaultsSF(opts) : buildSvgWithDefaults(opts)
);
path.replaceWithMultiple(svgReplacement);
} else {
const svgReplacement = statefulComponent ? buildSvgSF(opts) : buildSvg(opts);
path.replaceWith(svgReplacement);
}
file.get('ensureReact')();
file.set('ensureReact', () => {});
}
},
},
});