-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
435 lines (396 loc) · 15.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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/**
* Glamorous to Emotion codemod
*
* This babel plugin should migrate any existing codebase
* using React or Preact and glamorous to one using
* emotion (emotion.sh).
*
* It follows the glamorous to emotion migration guide
* found at https://github.com/paypal/glamorous/blob/master/other/EMOTION_MIGRATION.md
*
* Check out the README for how to use it.
*/
const htmlElementAttributes = require("react-html-attributes");
const validElementNames = new Set([
...htmlElementAttributes.elements.html,
...htmlElementAttributes.elements.svg,
]);
const MODES = {
withJsxPragma: "withJsxPragma",
withBabelPlugin: "withBabelPlugin",
className: "className",
};
module.exports = function(babel) {
const {types: t} = babel;
// try to convert filterProps etc into something emotion understands
const processOptions = options => {
if (!t.isObjectExpression(options)) {
const name = t.isIdentifier(options) ? options.name : options.type;
console.warn(
`codemod received '${name}' as an options argument. This is left in place, but will probably contain content that emotion won't understand`
);
return options;
} else {
const transformedOptions = [];
let forwardPropsExpr = [];
options.properties.forEach(prop => {
const {key, value} = prop;
switch (key.name) {
case "filterProps": {
// filterProps: ["one"] ---> prop !== "one"
if (t.isArrayExpression(value) && value.elements.length === 1) {
forwardPropsExpr.push(
t.binaryExpression("!==", t.identifier("prop"), value.elements[0])
);
} else {
// filterProps: ["one", "two"] ---> ["one", "two"].indexOf(prop) === -1
forwardPropsExpr.push(
t.binaryExpression(
"===",
t.callExpression(t.memberExpression(value, t.identifier("indexOf")), [
t.identifier("prop"),
]),
t.numericLiteral(-1)
)
);
}
break;
}
case "forwardProps": {
// forwardProps: ["one"] ---> prop === "one"
if (t.isArrayExpression(value) && value.elements.length === 1) {
forwardPropsExpr.push(
t.binaryExpression("===", t.identifier("prop"), value.elements[0])
);
} else {
// forwardProps: ["one", "two"] ---> ["one", "two"].indexOf(prop) > -1
forwardPropsExpr.push(
t.binaryExpression(
">",
t.callExpression(t.memberExpression(value, t.identifier("indexOf")), [
t.identifier("prop"),
]),
t.numericLiteral(-1)
)
);
}
break;
}
default: {
console.warn(
`codemod received '${key}' as an option. This is left in place, but will probably not be undestood by emotion`
);
transformedOptions.push(prop);
}
}
});
if (forwardPropsExpr.length) {
// concatenate all expressions via "&&"
const reducedExpr = forwardPropsExpr.reduce((existing, expr) =>
t.logicalExpression("&&", existing, expr)
);
// create `{shouldForwardProp: prop => [reducedExpr]}` expression
transformedOptions.push(
t.objectProperty(
t.identifier("shouldForwardProp"),
t.arrowFunctionExpression([t.identifier("prop")], reducedExpr)
)
);
}
return t.objectExpression(transformedOptions);
}
};
const processGlamorousArgs = args => {
if (args.length === 0) throw new Error("Can't handle glamorous call with 0 arguments");
if (args.length > 2) throw new Error("Can't handle glamorous call with more than 2 arguments");
if (args.length === 1) return args;
return [args[0], processOptions(args[1])];
};
// glamorous and emotion treat the css attribute "content" differently.
// we need to put its content inside a string.
// i.e. turn {content: ""} into {content: '""'}
const fixContentProp = glamorousFactoryArguments => {
return glamorousFactoryArguments.map(arg => {
if (t.isObjectExpression(arg)) {
arg.properties = arg.properties.map(prop =>
prop.key.name === "content"
? {...prop, value: t.stringLiteral(`"${prop.value.value}"`)}
: prop
);
}
// TODO: if `arg` is a function, we might want to inspect its return value
return arg;
});
};
// transform <glamorous.Div css={styles} width={100}/> to <div css={{...styles, width: 100}}/>
const transformJSXAttributes = ({tagName, jsxAttrs, mode, getCssFn, getCxFn, useJsxPragma}) => {
if (!jsxAttrs) return [];
const stylesArguments = [];
let classNameAttr = null;
const spreadsAttrs = [];
let originalCssValue;
/*
We go through all jsx attributes and filter out all style-specific props. E.g `css` or `marginTop`.
All style-specific props are gathered within `stylesArguments` and processed below
*/
const transformedJsxAttrs = jsxAttrs.filter(attr => {
if (t.isJSXSpreadAttribute(attr)) {
spreadsAttrs.push(attr);
return true;
}
const {value, name: jsxKey} = attr;
if (jsxKey.name === "css") {
originalCssValue = value;
// move properties of css attribute to the very front via unshift
if (!t.isObjectExpression(value.expression)) {
stylesArguments.unshift(t.spreadElement(value.expression));
} else {
stylesArguments.unshift(...value.expression.properties);
}
if (mode === MODES.withJsxPragma) useJsxPragma();
return mode !== MODES.className;
} else if (jsxKey.name === "className") {
classNameAttr = attr;
} else if (jsxKey.name === "innerRef") {
// turn `innerRef` into `ref`
jsxKey.name = "ref";
} else {
// ignore event handlers
if (jsxKey.name.match(/on[A-Z]/)) return true;
if (jsxKey.name === "key") return true;
// ignore generic attributes like 'id'
if (htmlElementAttributes["*"].includes(jsxKey.name)) return true;
// ignore tag specific attrs like 'disabled'
const tagSpecificAttrs = htmlElementAttributes[tagName];
if (tagSpecificAttrs && tagSpecificAttrs.includes(jsxKey.name)) return true;
stylesArguments.push(
t.objectProperty(
t.identifier(jsxKey.name),
t.isJSXExpressionContainer(value) ? value.expression : value
)
);
return false;
}
return true;
});
if (stylesArguments.length > 0) {
// if the css property was the only object, we don't need to use it's spreaded version
const stylesObject =
originalCssValue && stylesArguments.length === 1
? originalCssValue.expression
: t.objectExpression(stylesArguments);
if (mode !== MODES.className) {
// if we allow using the css prop, use <div css={styles}/> syntax
if (originalCssValue) {
originalCssValue.expression = stylesObject;
} else {
transformedJsxAttrs.push(
t.jsxAttribute(t.jsxIdentifier("css"), t.jsxExpressionContainer(stylesObject))
);
}
} else {
// if we don't allow using the css prop, use <div className={css(styles)}/> syntax
let classNameValue;
if (!classNameAttr && !spreadsAttrs.length) {
const cssCall = t.callExpression(getCssFn(), [stylesObject]);
classNameValue = t.jsxExpressionContainer(cssCall);
} else {
let args = [];
if (classNameAttr) {
// if className is already present use <div className={cx("my-className", styles)}/> syntax
args.push(classNameAttr.value);
} else {
// if spreads are present use <div {...props} className={cx(props.className, styles)}/> syntax
spreadsAttrs.forEach(attr => {
args.push(t.memberExpression(attr.argument, t.identifier("className")));
});
}
args.push(stylesObject);
const cxCall = t.callExpression(getCxFn(), args);
classNameValue = t.jsxExpressionContainer(cxCall);
}
if (classNameAttr) {
classNameAttr.value = classNameValue;
} else {
transformedJsxAttrs.push(t.jsxAttribute(t.jsxIdentifier("className"), classNameValue));
}
}
}
return transformedJsxAttrs;
};
const glamorousVisitor = {
// for each reference to an identifier...
ReferencedIdentifier(path, {getStyledFn, oldName, mode, getCssFn, getCxFn, useJsxPragma}) {
// skip if the name of the identifier does not correspond to the name of glamorous default import
if (path.node.name !== oldName) return;
switch (path.parent.type) {
// replace `glamorous()` with `styled()`
case "CallExpression": {
const transformedArguments = processGlamorousArgs(path.parent.arguments);
path.parentPath.replaceWith(t.callExpression(getStyledFn(), transformedArguments));
break;
}
// replace `glamorous.div()` with `styled("div")()`
case "MemberExpression": {
const grandParentPath = path.parentPath.parentPath;
if (t.isCallExpression(grandParentPath.node)) {
grandParentPath.replaceWith(
t.callExpression(
t.callExpression(getStyledFn(), [
t.stringLiteral(grandParentPath.node.callee.property.name),
]),
fixContentProp(grandParentPath.node.arguments)
)
);
} else {
throw new Error(
`Not sure how to deal with glamorous within MemberExpression @ ${path.node.loc}`
);
}
break;
}
// replace <glamorous.Div/> with `<div/>`
case "JSXMemberExpression": {
const grandParent = path.parentPath.parent;
const tagName = grandParent.name.property.name.toLowerCase();
grandParent.name = t.identifier(tagName);
if (t.isJSXOpeningElement(grandParent)) {
grandParent.attributes = transformJSXAttributes({
tagName,
jsxAttrs: grandParent.attributes,
mode,
getCssFn,
getCxFn,
useJsxPragma,
});
}
break;
}
default: {
console.warning("Found glamorous being used in an unkonwn context:", path.parent.type);
}
}
},
};
return {
name: "glamorousToEmotion",
visitor: {
ImportDeclaration(path, {opts}) {
const {value: libName} = path.node.source;
const mode = MODES[opts.mode] || MODES.withJsxPragma;
if (libName !== "glamorous" && libName !== "glamorous.macro") {
return;
}
// use "name" as identifier, but only if it's not already used in the current scope
const createUniqueIdentifier = name =>
path.scope.hasBinding(name) ? path.scope.generateUidIdentifier(name) : t.identifier(name);
// this object collects all the imports we'll need to add
let imports = {};
const getStyledFn = () => {
if (!imports["@emotion/styled"]) {
imports["@emotion/styled"] = {
default: t.importDefaultSpecifier(createUniqueIdentifier("styled")),
};
}
return imports["@emotion/styled"].default.local;
};
const getCssFn = () => {
if (!imports["@emotion/core"]) imports["@emotion/core"] = {};
if (!imports["@emotion/core"].css) {
const specifier = t.importSpecifier(t.identifier("css"), createUniqueIdentifier("css"));
imports["@emotion/core"].css = specifier;
}
return imports["@emotion/core"].css.local;
};
const getCxFn = () => {
if (!imports["emotion"]) imports["emotion"] = {};
if (!imports["emotion"].cx) {
const specifier = t.importSpecifier(t.identifier("cx"), createUniqueIdentifier("cx"));
imports["emotion"].cx = specifier;
}
return imports["emotion"].cx.local;
};
const useJsxPragma = () => {
if (!imports["@emotion/core"]) imports["@emotion/core"] = {};
if (!imports["@emotion/core"].jsx) {
t.addComment(path.parent, "leading", "* @jsx jsx ");
const specifier = t.importSpecifier(t.identifier("jsx"), createUniqueIdentifier("jsx"));
imports["@emotion/core"].jsx = specifier;
}
};
// only if the default import of glamorous is used, we're gonna apply the transforms
path.node.specifiers
.filter(s => t.isImportDefaultSpecifier(s))
.forEach(s => {
path.parentPath.traverse(glamorousVisitor, {
getStyledFn,
oldName: s.local.name,
mode,
getCssFn,
getCxFn,
useJsxPragma,
});
});
/*
`import {Span, Div as StyledDiv} from "glamorous"`
will be represented as `importedTags = {"Span": "span", "StyledDiv": "div"}`
*/
const importedTags = {};
path.node.specifiers
.filter(s => t.isImportSpecifier(s))
.forEach(({imported, local}) => {
const tagName = imported.name.toLowerCase();
if (validElementNames.has(tagName)) {
importedTags[local.name] = tagName;
}
});
// transform corresponding JSXElements if any html element imports were found
if (Object.keys(importedTags).length) {
path.parentPath.traverse({
"JSXOpeningElement|JSXClosingElement": path => {
const componentIdentifier = path.node.name;
// exclude MemberEpressions
if (!t.isJSXIdentifier(componentIdentifier)) return;
const targetTagName = importedTags[componentIdentifier.name];
if (!targetTagName) return;
componentIdentifier.name = targetTagName;
if (t.isJSXOpeningElement(path)) {
path.node.attributes = transformJSXAttributes({
targetTagName,
jsxAttrs: path.node.attributes,
mode,
getCssFn,
getCxFn,
useJsxPragma,
});
}
},
});
}
const themeProvider = path.node.specifiers.find(
specifier => specifier.local.name === "ThemeProvider"
);
if (themeProvider) {
path.insertBefore(
t.importDeclaration(
[t.importSpecifier(t.identifier("ThemeProvider"), t.identifier("ThemeProvider"))],
t.stringLiteral("emotion-theming")
)
);
}
const preactLibs = {
"@emotion/styled": "@emotion/preact-styled",
};
// if we used any emotion imports, we add them before the glamorous import path
Object.entries(imports).forEach(([rawLibName, libImports]) => {
const libName = (opts.preact && preactLibs[rawLibName]) || rawLibName;
path.insertBefore(
t.importDeclaration(Object.values(libImports), t.stringLiteral(libName))
);
});
path.remove();
},
},
};
};
module.exports.MODES = MODES;