-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
106 lines (86 loc) · 2.85 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
const getAttributeIdentifiers = options => {
if(!options || typeof(options.attributes) === 'undefined') return ['data-test-id', 'data-testid'];
if(Array.isArray(options.attributes)) {
if(options.attributes.length === 0) {
throw new Error('option attributes must be an array with at least one element');
}
if (options.attributes.length !== options.attributes.filter(attr => attr && typeof(attr) === 'string').length) {
throw new Error('all items in the option attributes must be non empty strings');
}
return options.attributes;
}
if(!options.attributes || typeof(options.attributes) !== 'string') {
throw new Error('option attributes must be a non empty string or an array with non empty strings');
}
return [options.attributes];
};
const RemoveDataTestIds = ({ types: t }) => {
const visitor = {
JSXOpeningElement: (path, state) => {
if (path.node.hasStripped) {
return;
}
const attributeIdentifiers = getAttributeIdentifiers(state.opts);
const validTestIdAttributes = attr => {
const isIdent = attributeIdentifiers.find(
attribute => {
return t.isJSXIdentifier(attr.name, { name: attribute });
}
);
return t.isJSXAttribute(attr) && isIdent;
};
const replaceClassNameValues = attr => {
const matchingAttrs = currentAttr => {
if (attr !== currentAttr) {
return currentAttr;
}
};
const isDefined = value => typeof value !== 'undefined';
const attrs = (
path.node.attributes
.map(matchingAttrs)
.filter(isDefined)
);
const node = t.jSXOpeningElement(
path.node.name,
attrs,
path.node.selfClosing
);
node.hasStripped = true;
path.replaceWith(node);
};
path.node.attributes
.filter(validTestIdAttributes)
.forEach(replaceClassNameValues);
const isObjectDefined = value => Object.keys(value).length !== 0;
const matchAndReplaceValues = currentAttr => {
const {
value: { expression: { properties = [] } = {} } = {}
} = currentAttr;
const filteredProperties = properties.filter(property => attributeIdentifiers.includes(property.key.value))
if (filteredProperties.length === 0) {
return {
...currentAttr,
properties: filteredProperties,
}
}
return {}
};
const attrs =
path.node.attributes
.map(matchAndReplaceValues)
.filter(isObjectDefined);
const node = t.jSXOpeningElement(
path.node.name,
attrs,
path.node.selfClosing
);
node.hasStripped = true;
path.replaceWith(node);
}
};
return {
visitor
};
};
export default RemoveDataTestIds;