forked from vercel/styled-jsx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel.js
331 lines (285 loc) · 9.68 KB
/
babel.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
// Packages
import jsx from '@babel/plugin-syntax-jsx'
import { visitor as externalStylesVisitor } from './babel-external'
import {
isGlobalEl,
isStyledJsx,
findStyles,
makeStyledJsxTag,
getJSXStyleInfo,
computeClassNames,
addClassName,
getScope,
processCss,
createReactComponentImportDeclaration,
setStateOptions
} from './_utils'
import { STYLE_COMPONENT } from './_constants'
export function macro() {
return require('./macro')
}
export function test() {
return require('./babel-test')
}
export default function({ types: t }) {
const jsxVisitors = {
JSXOpeningElement(path, state) {
const el = path.node
const { name } = el.name || {}
if (!state.hasJSXStyle) {
return
}
if (state.ignoreClosing === null) {
// We keep a counter of elements inside so that we
// can keep track of when we exit the parent to reset state
// note: if we wished to add an option to turn off
// selectors to reach parent elements, it would suffice to
// set this to `1` and do an early return instead
state.ignoreClosing = 0
}
const tag = path.get('name')
if (
name &&
name !== 'style' &&
name !== state.styleComponentImportName &&
(name.charAt(0) !== name.charAt(0).toUpperCase() ||
Object.values(path.scope.bindings).some(binding =>
binding.referencePaths.some(r => r === tag)
))
) {
if (state.className) {
addClassName(path, state.className)
}
}
state.ignoreClosing++
// Next visit will be: JSXElement exit()
},
JSXElement: {
enter(path, state) {
if (state.hasJSXStyle !== null) {
return
}
const styles = findStyles(path)
if (styles.length === 0) {
return
}
state.styles = []
state.externalStyles = []
const scope = getScope(path)
for (const style of styles) {
// Compute children excluding whitespace
const children = style.get('children').filter(
c =>
t.isJSXExpressionContainer(c.node) ||
// Ignore whitespace around the expression container
(t.isJSXText(c.node) && c.node.value.trim() !== '')
)
if (children.length !== 1) {
throw path.buildCodeFrameError(
`Expected one child under ` +
`JSX Style tag, but got ${children.length} ` +
`(eg: <style jsx>{\`hi\`}</style>)`
)
}
const child = children[0]
if (!t.isJSXExpressionContainer(child)) {
throw path.buildCodeFrameError(
`Expected a child of ` +
`type JSXExpressionContainer under JSX Style tag ` +
`(eg: <style jsx>{\`hi\`}</style>), got ${child.type}`
)
}
const expression = child.get('expression')
if (t.isIdentifier(expression)) {
const idName = expression.node.name
if (expression.scope.hasBinding(idName)) {
const externalStylesIdentifier = t.identifier(idName)
const isGlobal = isGlobalEl(style.get('openingElement').node)
state.externalStyles.push([
t.memberExpression(
externalStylesIdentifier,
t.identifier('__hash')
),
externalStylesIdentifier,
isGlobal
])
continue
}
throw path.buildCodeFrameError(
`The Identifier ` +
`\`${expression.getSource()}\` is either \`undefined\` or ` +
`it is not an external StyleSheet reference i.e. ` +
`it doesn't come from an \`import\` or \`require\` statement`
)
}
if (
!t.isTemplateLiteral(expression) &&
!t.isStringLiteral(expression)
) {
throw path.buildCodeFrameError(
`Expected a template ` +
`literal or String literal as the child of the ` +
`JSX Style tag (eg: <style jsx>{\`some css\`}</style>),` +
` but got ${expression.type}`
)
}
state.styles.push(getJSXStyleInfo(expression, scope))
}
let externalJsxId
if (state.externalStyles.length > 0) {
const expressions = state.externalStyles
// Remove globals
.filter(s => !s[2])
.map(s => s[0])
const expressionsLength = expressions.length
if (expressionsLength === 0) {
externalJsxId = null
} else {
// Construct a template literal of this form:
// `jsx-${styles.__scopedHash} jsx-${otherStyles.__scopedHash}`
externalJsxId = t.templateLiteral(
[
t.templateElement({ raw: 'jsx-', cooked: 'jsx-' }),
...[...new Array(expressionsLength - 1).fill(null)].map(() =>
t.templateElement({ raw: ' jsx-', cooked: ' jsx-' })
),
t.templateElement({ raw: '', cooked: '' }, true)
],
expressions
)
}
}
if (state.styles.length > 0 || externalJsxId) {
const { staticClassName, className } = computeClassNames(
state.styles,
externalJsxId,
state.styleComponentImportName
)
state.className = className
state.staticClassName = staticClassName
}
state.hasJSXStyle = true
state.file.hasJSXStyle = true
// Next visit will be: JSXOpeningElement
},
exit(path, state) {
const isGlobal = isGlobalEl(path.node.openingElement)
if (state.hasJSXStyle && !--state.ignoreClosing && !isGlobal) {
state.hasJSXStyle = null
state.className = null
state.externalJsxId = null
}
if (!state.hasJSXStyle || !isStyledJsx(path)) {
return
}
if (state.ignoreClosing > 1) {
let styleTagSrc
try {
styleTagSrc = path.getSource()
} catch (error) {}
throw path.buildCodeFrameError(
'Detected nested style tag' +
(styleTagSrc ? `: \n\n${styleTagSrc}\n\n` : ' ') +
'styled-jsx only allows style tags ' +
'to be direct descendants (children) of the outermost ' +
'JSX element i.e. the subtree root.'
)
}
if (
state.externalStyles.length > 0 &&
path.get('children').filter(child => {
if (!t.isJSXExpressionContainer(child)) {
return false
}
const expression = child.get('expression')
return expression && expression.isIdentifier()
}).length === 1
) {
const [id, css] = state.externalStyles.shift()
path.replaceWith(
makeStyledJsxTag(id, css, [], state.styleComponentImportName)
)
return
}
const { vendorPrefixes, sourceMaps } = state.opts
const stylesInfo = {
...state.styles.shift(),
file: state.file,
staticClassName: state.staticClassName,
isGlobal,
plugins: state.plugins,
vendorPrefixes,
sourceMaps
}
const splitRules =
typeof state.opts.optimizeForSpeed === 'boolean'
? state.opts.optimizeForSpeed
: process.env.NODE_ENV === 'production'
const { hash, css, expressions } = processCss(stylesInfo, {
splitRules
})
path.replaceWith(
makeStyledJsxTag(
hash,
css,
expressions,
state.styleComponentImportName
)
)
}
}
}
// only apply JSXFragment visitor if supported
if (t.isJSXFragment) {
jsxVisitors.JSXFragment = jsxVisitors.JSXElement
jsxVisitors.JSXOpeningFragment = {
enter(path, state) {
if (!state.hasJSXStyle) {
return
}
if (state.ignoreClosing === null) {
// We keep a counter of elements inside so that we
// can keep track of when we exit the parent to reset state
// note: if we wished to add an option to turn off
// selectors to reach parent elements, it would suffice to
// set this to `1` and do an early return instead
state.ignoreClosing = 0
}
state.ignoreClosing++
}
}
}
const visitors = {
inherits: jsx,
visitor: {
Program: {
enter(path, state) {
setStateOptions(state)
state.hasJSXStyle = null
state.ignoreClosing = null
state.file.hasJSXStyle = false
state.file.hasCssResolve = false
// create unique identifier for _JSXStyle component
state.styleComponentImportName = path.scope.generateUidIdentifier(
STYLE_COMPONENT
).name
// we need to beat the arrow function transform and
// possibly others so we traverse from here or else
// dynamic values in classNames could be incorrect
path.traverse(jsxVisitors, state)
// Transpile external styles
path.traverse(externalStylesVisitor, state)
},
exit(path, state) {
if (!state.file.hasJSXStyle && !state.file.hasCssResolve) {
return
}
state.file.hasJSXStyle = true
const importDeclaration = createReactComponentImportDeclaration(state)
path.unshiftContainer('body', importDeclaration)
}
}
}
}
return visitors
}