Skip to content

Commit 0a531d1

Browse files
committed
wip with overly permissive id scraper
1 parent a2a82cb commit 0a531d1

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

src/styled-components.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import checkValidOptions from './options'
2+
import * as t from 'babel-types'
3+
4+
export default function TaggedTemplateExpression(path, state) {
5+
const options = checkValidOptions(state)
6+
const scope = path.scope
7+
8+
try {
9+
if (isStyledPrefix(path.node.tag)) {
10+
const id = getIdFrom(path.parentPath)
11+
if (!id) return
12+
path.node.tag = insertBefore(path.node.tag, id)
13+
return
14+
}
15+
let node = path.node.tag
16+
while (true) {
17+
if (!node.callee) debugger
18+
if (!node || !node.callee) break
19+
if (isStyledPrefix(node.callee.object)) {
20+
const id = getIdFrom(path.parentPath)
21+
if (!id) return
22+
node.callee.object = insertBefore(node.callee.object, id)
23+
break
24+
}
25+
node = node.callee.object
26+
}
27+
} catch (e) {
28+
console.log(e)
29+
return
30+
}
31+
32+
function insertBefore(node, id) {
33+
return t.callExpression(t.memberExpression(node, t.identifier('attrs')), [
34+
t.arrowFunctionExpression(
35+
[],
36+
t.objectExpression([
37+
t.objectProperty(t.StringLiteral(options.attribute), t.StringLiteral(id))
38+
])
39+
)
40+
])
41+
}
42+
function isStyledPrefix(node) {
43+
// handle two forms: styled.div and styled(Comp)
44+
return (
45+
(t.isMemberExpression(node) && isStyledComponentsBinding(node.object)) ||
46+
(t.isCallExpression(node) && isStyledComponentsBinding(node.callee))
47+
)
48+
function isStyledComponentsBinding(node) {
49+
if (!t.isIdentifier(node)) return false
50+
const binding = scope.getBinding(node.name)
51+
if (!binding || binding.kind !== 'module') return false
52+
return binding.path.parent.source.value == 'styled-components'
53+
}
54+
}
55+
function getIdFrom(parentPath) {
56+
while (parentPath && !parentPath.node.id && !parentPath.node.left) {
57+
parentPath = parentPath.parentPath
58+
}
59+
const id =
60+
parentPath &&
61+
parentPath.node &&
62+
((parentPath.node.id && parentPath.node.id.name) ||
63+
(parentPath.node.left && parentPath.node.left.name))
64+
return id
65+
}
66+
}

0 commit comments

Comments
 (0)