-
-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathtranspileCssProp.js
More file actions
363 lines (312 loc) · 11.8 KB
/
Copy pathtranspileCssProp.js
File metadata and controls
363 lines (312 loc) · 11.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
// Most of this code was taken from @satya164's babel-plugin-css-prop
import { addDefault } from '@babel/helper-module-imports'
import { importLocalName } from '../utils/detectors'
import { useCssProp, useCssPropImportPath } from '../utils/options'
import { processCallExpression, processTaggedTemplate } from './process'
const TAG_NAME_REGEXP = /^[a-z][a-z\d]*(\-[a-z][a-z\d]*)?$/
const ISSUE_URL =
'https://github.com/styled-components/babel-plugin-styled-components'
const getName = (node, t, path) => {
if (typeof node.name === 'string') return node.name
if (t.isJSXMemberExpression(node)) {
return `${getName(node.object, t, path)}.${node.property.name}`
}
throw path.buildCodeFrameError(
`Cannot infer name from node with type "${node.type}". Please submit an issue at ${ISSUE_URL} with your code so we can take a look at your use case!`
)
}
const getNameExpression = (node, t, path) => {
if (typeof node.name === 'string') return t.identifier(node.name)
if (t.isJSXMemberExpression(node)) {
return t.memberExpression(
getNameExpression(node.object, t, path),
t.identifier(node.property.name)
)
}
throw path.buildCodeFrameError(
`Cannot infer name expression from node with type "${node.type}". Please submit an issue at ${ISSUE_URL} with your code so we can take a look at your use case!`
)
}
const getLocalIdentifier = path => {
const identifier = path.scope.generateUidIdentifier('css')
// make it transient
identifier.name = identifier.name.replace('_', '$_')
return identifier
}
const PROGRAM_BODY_PRENUMBERED = 'styled-components-program-prenumbered'
export default t => {
const taggedTemplateVisit = processTaggedTemplate(t)
const callExpressionVisit = processCallExpression(t)
return (path, state) => {
if (!useCssProp(state)) return
if (path.node.name.name !== 'css') return
const program = state.file.path
// state.customImportName is passed through from styled-components/macro if it's used
// since the macro also inserts the import
let importName = state.customImportName || importLocalName('default', state)
const { bindings } = program.scope
const importBindingName = importName && (importName.name || importName)
const importBinding = importBindingName && bindings[importBindingName]
const importBindingIsNamespace =
importBinding &&
importBinding.path &&
importBinding.path.isImportNamespaceSpecifier()
// A namespace binding (`import * as styled from 'styled-components'`) is
// not directly callable, so treat it the same as "no default binding" and
// inject a fresh default import to use as the css-prop callee.
if (!importBinding || importBindingIsNamespace) {
addDefault(path, useCssPropImportPath(state), {
nameHint: 'styled',
})
importName = t.identifier(
importLocalName('default', state, { bypassCache: true })
)
}
if (!t.isIdentifier(importName)) importName = t.identifier(importName)
const elem = path.parentPath
const name = getName(elem.node.name, t, path)
const nameExpression = getNameExpression(elem.node.name, t, path)
const id = path.scope.generateUidIdentifier(
'Styled' + name.replace(/^([a-z])/, (match, p1) => p1.toUpperCase())
)
let styled
let injector
if (TAG_NAME_REGEXP.test(name)) {
styled = t.callExpression(importName, [t.stringLiteral(name)])
} else {
styled = t.callExpression(importName, [nameExpression])
if (
bindings[name] &&
!t.isImportDeclaration(bindings[name].path.parent)
) {
injector = nodeToInsert =>
(t.isVariableDeclaration(bindings[name].path.parent)
? bindings[name].path.parentPath
: bindings[name].path
).insertAfter(nodeToInsert)
}
}
let css
if (t.isStringLiteral(path.node.value)) {
css = t.templateLiteral(
[
t.templateElement(
{ raw: path.node.value.value, cooked: path.node.value.value },
true
),
],
[]
)
} else if (t.isJSXExpressionContainer(path.node.value)) {
if (t.isTemplateLiteral(path.node.value.expression)) {
css = path.node.value.expression
} else if (
t.isTaggedTemplateExpression(path.node.value.expression) &&
path.node.value.expression.tag.name === 'css'
) {
css = path.node.value.expression.quasi
} else if (t.isObjectExpression(path.node.value.expression)) {
css = path.node.value.expression
} else {
css = t.templateLiteral(
[
t.templateElement({ raw: '', cooked: '' }, false),
t.templateElement({ raw: '', cooked: '' }, true),
],
[path.node.value.expression]
)
}
}
if (!css) return
// strip off css prop from final output
elem.node.attributes = elem.node.attributes.filter(
x =>
t.isJSXSpreadAttribute(x) ||
(t.isJSXAttribute(x) ? x.name.name !== 'css' : false)
)
elem.node.name = t.jSXIdentifier(id.name)
if (elem.parentPath.node.closingElement) {
elem.parentPath.node.closingElement.name = t.jSXIdentifier(id.name)
}
// object syntax
if (t.isObjectExpression(css)) {
/**
* for objects as CSS props, we have to recurse through the object and replace any
* object key/value scope references with generated props similar to how the template
* literal transform above creates dynamic interpolations
*/
const p = t.identifier('p')
let replaceObjectWithPropFunction = false
css.properties = css.properties.reduce(function propertiesReducer(
acc,
property
) {
/**
* handle potential object key interpolations
*/
if (
t.isMemberExpression(property.key) ||
t.isCallExpression(property.key) ||
// checking for css={{[something]: something}}; a plain (non-computed)
// identifier key is a literal property name and never resolves to a
// binding, even if the local scope happens to define a same-named
// variable. Only computed keys reference the surrounding scope.
(t.isIdentifier(property.key) &&
property.computed &&
path.scope.hasBinding(property.key.name) &&
// but not a object reference shorthand like css={{ color }}
(t.isIdentifier(property.value)
? property.key.name !== property.value.name
: true) &&
// and not a tricky expression
!t.isMemberExpression(property.value) &&
!t.isLogicalExpression(property.value) &&
!t.isConditionalExpression(property.value))
) {
replaceObjectWithPropFunction = true
const identifier = getLocalIdentifier(path)
elem.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier(identifier.name),
t.jSXExpressionContainer(property.key)
)
)
property.key = t.memberExpression(p, identifier)
}
if (t.isObjectExpression(property.value)) {
// recurse for objects within objects (e.g. {'::before': { content: x }})
property.value.properties = property.value.properties.reduce(
propertiesReducer,
[]
)
acc.push(property)
} else if (t.isSpreadElement(property)) {
// handle spread variables and such
if (t.isObjectExpression(property.argument)) {
property.argument.properties = property.argument.properties.reduce(
propertiesReducer,
[]
)
} else {
replaceObjectWithPropFunction = true
const identifier = getLocalIdentifier(path)
elem.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier(identifier.name),
t.jSXExpressionContainer(property.argument)
)
)
property.argument = t.memberExpression(p, identifier)
}
acc.push(property)
} else if (
// if a non-primitive value we have to interpolate it
[
t.isBigIntLiteral,
t.isBooleanLiteral,
t.isNullLiteral,
t.isNumericLiteral,
t.isStringLiteral,
]
.filter(Boolean) // older versions of babel might not have bigint support baked in
.every(x => !x(property.value))
) {
replaceObjectWithPropFunction = true
const identifier = getLocalIdentifier(path)
elem.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier(identifier.name),
t.jSXExpressionContainer(property.value)
)
)
acc.push(
t.objectProperty(
property.key,
t.memberExpression(p, identifier),
property.computed,
// shorthand requires `value` to be the same Identifier as `key`;
// after rewriting `{ color }` to `{ color: p.$_cssN }` the
// invariant no longer holds, so force-clear the flag.
false
)
)
} else {
// some sort of primitive which is safe to pass through as-is
acc.push(property)
}
return acc
}, [])
if (replaceObjectWithPropFunction) {
css = t.arrowFunctionExpression([p], css)
}
} else {
// tagged template literal
css.expressions = css.expressions.reduce((acc, ex) => {
if (
Object.keys(bindings).some(key =>
bindings[key].referencePaths.find(p => p.node === ex)
) ||
t.isFunctionExpression(ex) ||
t.isArrowFunctionExpression(ex)
) {
acc.push(ex)
} else {
const identifier = getLocalIdentifier(path)
const p = t.identifier('p')
elem.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier(identifier.name),
t.jSXExpressionContainer(ex)
)
)
acc.push(
t.arrowFunctionExpression([p], t.memberExpression(p, identifier))
)
}
return acc
}, [])
}
if (!injector) {
let parent = elem
while (!t.isProgram(parent)) {
parent = parent.parentPath
}
injector = nodeToInsert => parent.pushContainer('body', nodeToInsert)
}
// Eagerly number every user-written styled component already present in
// Program.body BEFORE the css-prop injection lands, then number the
// injected declaration via the explicit loop below. Babel's outer
// traversal does not reliably re-visit nodes pushed onto Program from
// inside Program-enter, so without this pre-pass user-written components
// discovered later would compete with injected ones for counter values.
if (!state.file.get(PROGRAM_BODY_PRENUMBERED)) {
state.file.set(PROGRAM_BODY_PRENUMBERED, true)
program.traverse({
TaggedTemplateExpression(p) {
taggedTemplateVisit(p, state)
},
CallExpression(p) {
callExpressionVisit(p, state)
},
})
}
const insertedPaths = injector(
t.variableDeclaration('var', [
t.variableDeclarator(
id,
t.isObjectExpression(css) || t.isArrowFunctionExpression(css)
? t.callExpression(styled, [css])
: t.taggedTemplateExpression(styled, css)
),
])
)
for (const inserted of [].concat(insertedPaths)) {
const initPath = inserted.get('declarations.0.init')
if (initPath.isTaggedTemplateExpression()) {
taggedTemplateVisit(initPath, state)
} else if (initPath.isCallExpression()) {
callExpressionVisit(initPath, state)
}
}
}
}