-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
82 lines (75 loc) · 2.34 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
const types = require("@babel/types");
const PLUGIN_NAME = "babel-plugin-format-testID";
/**
*
* A babel plugin to format testID when building the app
*
* INPUT:
* <Button testID={variable} />
* <Button testID={"asdf"+2} />
* <Button testID="asdf" />
*
* OUTPUT:
* <Button testID={"prefix" + variable} />
* <Button testID={"prefix" + ("asdf" + 2)} />
* <Button testID={"prefix" + "asdf"} />
*
*/
/**
* @param {*} opts: {prefix: string, skip?: boolean,}
*/
module.exports = function prefixTestID(_, opts) {
if (!opts || !opts.prefix) {
console.warn(`${PLUGIN_NAME} is missing a prefix value in configuration`);
}
const PREFIX = opts.prefix;
const updatePrefix = (path, testIDValue) => {
const str = types.stringLiteral(PREFIX);
const call = types.jsxExpressionContainer(
types.binaryExpression("+", str, testIDValue),
);
path.node.value = call;
};
return {
name: PLUGIN_NAME,
visitor: {
JSXAttribute(path) {
if (path.node.name.name !== "testID" || opts?.skip || !PREFIX) return;
let testIDValue;
if (
types.isExpression(path.node.value) &&
path.node.value.type === "StringLiteral"
) {
if (!path.node.value.value.startsWith(PREFIX)) {
testIDValue = path.node.value;
updatePrefix(path, testIDValue);
}
} else if (path.node.value.type === "JSXExpressionContainer") {
testIDValue = path.node.value.expression;
if (path.node.value.expression.type === "BinaryExpression") {
if (
types.isLiteral(path.node.value.expression.left) ||
types.isStringLiteral(path.node.value.expression.left)
) {
// eslint-disable-next-line max-depth
if (!path.node.value.expression.left.value.startsWith(PREFIX)) {
updatePrefix(path, testIDValue);
}
}
} else if (
["LogicalExpression", "TemplateLiteral"].includes(
path.node.value.expression.type,
)
) {
updatePrefix(path, testIDValue);
} else if (
path.node.value.expression.type === "Identifier" &&
path.node.value.expression.name === "variable"
) {
updatePrefix(path, testIDValue);
}
}
},
},
};
};