-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
233 lines (213 loc) · 6.96 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
const cx = require('./cx')
const dedupe = require('./dedupe')
const PRIMITIVE_TYPES = ['NullLiteral', 'BooleanLiteral', 'NumericLiteral', 'StringLiteral']
const SIMPLE_PROP_KEY_TYPES = ['Identifier', 'StringLiteral']
module.exports = function (base) {
const t = base.types
const requireCx = (fileName) => {
return [
t.ImportDeclaration(
[t.ImportDefaultSpecifier(cxId)],
t.StringLiteral('babel-plugin-transform-jsx-classnames/' + fileName),
),
]
}
const checkChanges = (info, node) => {
switch (node.type) {
case 'NullLiteral':
case 'NumericLiteral':
case 'StringLiteral':
return info
case 'ConditionalExpression':
checkChanges(info, node.consequent)
checkChanges(info, node.alternate)
return info
}
info.change = true
return info
}
const extractArgs = (attrs, info = {}, depth = 0) => {
const args = attrs.reduce((acc, attr) => {
switch (attr.type) {
case 'TemplateLiteral':
info.onRuntime = true
return acc
case 'StringLiteral':
acc.push(attr.value.trim())
return acc
case 'NumericLiteral':
if (attr.value) acc.push(attr.value)
return acc
case 'ObjectExpression':
acc.push(
attr.properties.reduce((h, prop) => {
if (
prop.type === 'ObjectProperty' &&
prop.key &&
prop.value &&
PRIMITIVE_TYPES.includes(prop.value.type) &&
SIMPLE_PROP_KEY_TYPES.includes(prop.key.type) &&
(!t.isIdentifier(prop.key) || !prop.computed) &&
!prop.method &&
!prop.shorthand
) {
h[t.isIdentifier(prop.key) ? prop.key.name : prop.key.value] = prop.value.value
return h
}
info.onRuntime = true
return h
}, {}),
)
return acc
case 'ConditionalExpression':
info.noChange = depth === 0 && attrs.length === 1 && !checkChanges({}, attr).change
}
info.onRuntime = true
return acc
}, [])
return { args, ...info }
}
const flattenAttrs = (attrs, flat = []) => {
attrs.forEach((attr) => {
if (t.isArrayExpression(attr)) {
flattenAttrs(attr.elements, flat)
} else {
flat.push(attr)
}
})
return flat
}
const convertTemplateLiteral = (attr, method, info = { acc: [], change: true }) => {
let exp
switch (attr.type) {
case 'TemplateLiteral':
exp = attr.expressions.concat(attr.quasis).sort((a, b) => (a.start > b.start ? 1 : -1))
exp.forEach((e) => convertTemplateLiteral(e, method, info))
break
case 'TemplateElement':
info.acc.push(attr.value.raw)
break
case 'StringLiteral':
info.acc.push(attr.value)
break
case 'NumericLiteral':
info.acc.push(String(attr.value))
break
default:
info.change = false
}
return info.change ? t.stringLiteral(info.acc.join('')) : attr
}
const convertObjectValues = (attr) => {
if (attr.type === 'ObjectExpression') {
attr.properties = attr.properties.map((prop) => {
if (prop.type === 'ObjectProperty' && prop.key && prop.value && PRIMITIVE_TYPES.includes(prop.value.type)) {
prop.value = t.numericLiteral(prop.value.value ? 1 : 0)
}
return prop
})
}
return attr
}
const callCx = (prop, attrs) => {
attrs = flattenAttrs(attrs)
.filter((attr) => !t.isNullLiteral(attr))
.map((attr) => (t.isTemplateLiteral(attr) ? convertTemplateLiteral(attr) : convertObjectValues(attr)))
const values = extractArgs(attrs)
if (values.noChange) {
return null
}
if (values.onRuntime) {
if (attrs.length === 1 && t.isTemplateLiteral(attrs[0]))
return t.JSXAttribute(t.JSXIdentifier(prop), t.JSXExpressionContainer(attrs[0]))
flags.used = true
return t.JSXAttribute(t.JSXIdentifier(prop), t.JSXExpressionContainer(t.CallExpression(cxId, attrs)))
}
return t.JSXAttribute(t.JSXIdentifier(prop), t.stringLiteral(cxFunc(values.args)))
}
const readAttributes = (path, selectedAttributes) => {
const info = {}
selectedAttributes.forEach((prop) => {
const paths = []
let attrs = []
const readAttribute = (name, value, p) => {
switch (name) {
case prop:
if (!value || t.isStringLiteral(value)) return
if (t.isJSXExpressionContainer(value)) {
value = value.expression
}
if (t.isTemplateLiteral(value)) return
if (!value.expressions && (t.isBooleanLiteral(value) || t.isNullLiteral(value)) && !value.value) return
paths.push(p)
attrs = value.expressions || [value]
break
}
}
const attributes = path.node.openingElement.attributes
for (let i = 0, len = attributes.length; i < len; i++) {
if (attributes[i].type === 'JSXSpreadAttribute') {
path.get('openingElement.attributes.' + i).traverse({
ObjectProperty(propPath) {
const prop = propPath.node
readAttribute(prop.key.name, prop.value, propPath)
},
})
continue
}
const name = attributes[i].name.name
const value = attributes[i].value
const p = path.get('openingElement.attributes.' + i)
readAttribute(name, value, p)
}
info[prop] = { paths, attrs }
})
return info
}
const mutateAttributes = (path, info) => {
Object.keys(info).forEach((prop) => {
const attributes = info[prop]
if (!attributes.attrs.length) return
const attrValue = callCx(prop, attributes.attrs)
if (attrValue === null) return
attributes.paths.forEach((path) => path.remove())
path.get('openingElement').pushContainer('attributes', attrValue)
})
}
function getOptions(stats) {
const options = Object.assign(
{
dedupe: false,
attributes: ['className', 'styleName'],
},
/* istanbul ignore next */
stats.opts || {},
)
if (!Array.isArray(options.attributes)) options.attributes = [options.attributes]
return options
}
let options;
let cxId;
let flags;
let programPath
let cxFunc
return {
visitor: {
JSXElement(path) {
mutateAttributes(path, readAttributes(path, options.attributes))
if (flags.used && !flags.imported) {
flags.imported = true;
programPath.unshiftContainer('body', requireCx(options.dedupe ? 'dedupe' : 'cx'))
}
},
Program(path, stats) {
programPath = path
options = getOptions(stats)
cxId = path.scope.generateUidIdentifier('_cx')
cxFunc = options.dedupe ? dedupe : cx
flags = { used: false, imported: false }
},
},
inherits: require('babel-plugin-syntax-jsx'),
}
}