-
Notifications
You must be signed in to change notification settings - Fork 2
/
babel-plugin-react-element-classes.js
80 lines (69 loc) · 1.92 KB
/
babel-plugin-react-element-classes.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
/*
* This plugin is a proof of concept for getting `elementClasses` to behave similarly to
* how they work in metal-jsx. This plugin is not intended for production use.
*/
module.exports = function(babel) {
const {types: t} = babel;
const elementClassesExpression = t.memberExpression(
t.memberExpression(t.thisExpression(), t.identifier('props')),
t.identifier('elementClasses')
);
const elementClassesString = t.binaryExpression(
'+',
t.stringLiteral(' '),
elementClassesExpression
);
const elementClassesTernary = t.conditionalExpression(
elementClassesExpression,
elementClassesString,
t.stringLiteral('')
);
const classNameAttribute = t.jSXAttribute(
t.jSXIdentifier('className'),
t.jSXExpressionContainer(elementClassesTernary)
);
const addToClassName = classNameAttr => {
const prevVal = classNameAttr.value;
if (prevVal.type === 'JSXExpressionContainer') {
classNameAttr.value.expression = t.binaryExpression(
'+',
prevVal.expression,
elementClassesTernary
);
} else if (prevVal.type === 'StringLiteral') {
classNameAttr.value = t.jSXExpressionContainer(
t.binaryExpression('+', prevVal, elementClassesTernary)
);
}
};
return {
name: 'element-classes',
visitor: {
ReturnStatement(path) {
const functionParent = path.getFunctionParent();
if (
functionParent.node.id &&
functionParent.node.id.name === 'render'
) {
if (path.node.argument.type === 'JSXElement') {
const firstElementOpening =
path.node.argument.openingElement;
if (firstElementOpening.name === 'svg') {
return;
}
const classNameAttr = firstElementOpening.attributes.find(
attr => attr.name && attr.name.name === 'className'
);
if (classNameAttr) {
addToClassName(classNameAttr);
} else {
firstElementOpening.attributes.push(
classNameAttribute
);
}
}
}
}
}
};
};