-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
207 lines (181 loc) · 6.69 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
const utils = require('./utils')
const DEFAULT_CLASS_ATTRIBUTE = 'styleName'
const DEFAULT_ADD_CSS_HASH = false
const DEFAULT_EXTENSIONS = ['css', 'styl']
const DEFAULT_WRAP_IN_MEMO = false
const ADD_CSS_HASH_DELAY = 800
const CSSTA_TEMPLATE = 'styled'
const NEW_TAG_PREFIX = 'Styled'
function isTargetAttr (attribute, classAttribute) {
if (!classAttribute) classAttribute = DEFAULT_CLASS_ATTRIBUTE
return attribute.name.name === classAttribute
}
function hasTargetExtension (filename = '', extensions = DEFAULT_EXTENSIONS) {
const match = filename.match(/\.([^/]+)$/)
const extension = match && match[1]
return extension && extensions.includes(extension)
}
module.exports = ({ types: t }) => {
let lastImport
let stylesImport
let program
let csstaTemplate
let importAnimated // TODO: Add Animated import automatically
let hasTransformedClassName
let ast
let processedItems = []
function getUniqueStyledTag (className) {
const capitalized = className.charAt(0).toUpperCase() + className.slice(1)
const uniqueName = program.scope.generateUidIdentifier(capitalized).name
return NEW_TAG_PREFIX + uniqueName
}
function processItem (JSXOpeningElement, className, wrapInMemo) {
const oldTag = JSXOpeningElement.node.name.name
let item = processedItems.find(i => (
i.className === className && i.oldTag === oldTag
))
let initNewTag = false
if (!item) {
initNewTag = true
const newTag = getUniqueStyledTag(className)
item = {
className,
oldTag,
newTag
}
processedItems.push(item)
}
replaceWithNewTag(JSXOpeningElement, item.newTag)
if (initNewTag) {
let styles = utils.getStylesMatchingClassFromAst(ast, className)
styles = utils.transformStylesForCssta(styles, className)
const animate = utils.hasAnimation(styles) && utils.isAnimatable(item.oldTag)
const oldTagExpr = getOldTagExpr(item.oldTag, animate)
const newTagExpr = getNewTagExpr(item.newTag, oldTagExpr, styles, JSXOpeningElement, wrapInMemo)
lastImport.insertAfter(newTagExpr)
}
}
function replaceWithNewTag (JSXOpeningElement, newTag) {
JSXOpeningElement.get('name').replaceWith(t.jSXIdentifier(newTag))
if (!JSXOpeningElement.node.selfClosing) {
JSXOpeningElement.getSibling('closingElement').get('name').replaceWith(t.jSXIdentifier(newTag))
}
}
function getOldTagExpr (oldTag, animate) {
if (animate) {
// TODO: add import Animated from 'react-native'
importAnimated = true
return t.memberExpression(t.identifier('Animated'), t.identifier(oldTag))
} else {
return t.identifier(oldTag)
}
}
function getNewTagExpr (newTag, oldTagExpr, styles, path, wrapInMemo) {
let styled = t.taggedTemplateExpression(
t.callExpression(csstaTemplate, [oldTagExpr]),
t.templateLiteral([
t.templateElement({
raw: `\n${styles}\n`.replace(/\\|`|\${/g, '\\$&'),
cooked: `\n${styles}\n`
})
], [])
)
if (wrapInMemo == null) wrapInMemo = DEFAULT_WRAP_IN_MEMO
if (wrapInMemo) {
const reactIdentifier = utils.getReactImport(t, path)
styled = t.callExpression(t.memberExpression(reactIdentifier, t.identifier('memo')), [styled])
}
const d = t.variableDeclarator(t.identifier(newTag), styled)
return t.variableDeclaration('const', [d])
}
function processClass (JSXOpeningElement, state) {
var className = null
JSXOpeningElement.traverse({
JSXAttribute (JSXAttribute) {
if (!isTargetAttr(JSXAttribute.node, state.opts.classAttribute)) return
if (t.isStringLiteral(JSXAttribute.node.value)) {
var classNameValue = JSXAttribute.node.value.value.split(' ')
className = classNameValue[0]
if (classNameValue.length > 1) {
// TODO: Maybe throw an error when more than 1 class specified
JSXAttribute.get('value').replaceWith(t.stringLiteral(classNameValue.slice(1).join(' ')))
} else {
JSXAttribute.remove()
}
}
}
})
if (className && stylesImport) {
hasTransformedClassName = true
processItem(JSXOpeningElement, className, state.opts.wrapInMemo)
}
}
function maybeUpdateCssHash (delayExecution, state) {
// Force update JS file in the same directory with the new css file hash.
// This is required for proper development experience on native and web.
// TODO: Make this a plugin option and only enabled in dev env.
const addCssHash = state.opts.addCssHash != null
? state.opts.addCssHash
: DEFAULT_ADD_CSS_HASH
if (addCssHash && hasTargetExtension(state.file.opts.filename, state.opts.extensions)) {
const filename = state.file.opts.filename
// Delay execution to account for Save All delay in IDEs
if (delayExecution) {
setTimeout(() => {
utils.maybeUpdateCssHash(filename, state.opts.extensions || DEFAULT_EXTENSIONS)
}, ADD_CSS_HASH_DELAY)
} else {
utils.maybeUpdateCssHash(filename, state.opts.extensions || DEFAULT_EXTENSIONS)
}
}
}
return {
post () {
},
visitor: {
Program: {
enter (path, state) {
if (stylesImport) return
path
.get('body')
.forEach(p => {
if (p.isImportDeclaration()) {
lastImport = p
if (hasTargetExtension(p.node.source.value, state.opts.extensions)) stylesImport = p
}
})
if (!stylesImport) return
program = path
csstaTemplate = path.scope.generateUidIdentifier(CSSTA_TEMPLATE)
try {
ast = utils.parseAst(state.file.opts.filename, stylesImport.node.source.value)
} catch (e) {
throw new Error('Error parsing CSS file "' + state.file.opts.filename + '": ' + e.message || e)
}
const csstaSpecifier = t.importDefaultSpecifier(csstaTemplate)
const csstaImport = t.importDeclaration([csstaSpecifier], t.stringLiteral('cssta/native'))
const [newPath] = program.unshiftContainer('body', csstaImport)
for (const specifier of newPath.get('specifiers')) {
program.scope.registerBinding('module', specifier)
}
},
exit (path, state) {
lastImport = null
stylesImport = null
program = null
csstaTemplate = null
importAnimated = null
hasTransformedClassName = null
ast = null
processedItems = []
maybeUpdateCssHash(true, state)
}
},
JSXOpeningElement (path, state) {
if (!stylesImport) return
if (!ast) return
processClass(path, state)
}
}
}
}