-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathclassname-prefix.ts
94 lines (83 loc) · 2.49 KB
/
classname-prefix.ts
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
import type { API, FileInfo, TemplateElement } from 'jscodeshift';
type Expression = {
type: string;
arguments?: Node[];
};
type Node = {
type: string;
value?: string;
quasis?: TemplateElement[];
expression?: Expression;
consequent?: Node;
alternate?: Node;
right?: Node;
left?: Node;
test?: Node;
};
const replaceInLiteral = (node: string) => {
if (node.startsWith('fds-')) {
return node.replace('fds-', 'ds-');
}
return node;
};
const replaceInTemplateLiteral = (node: TemplateElement[]) => {
for (const element of node) {
const value = element.value.raw;
if (typeof value !== 'string') continue;
element.value.raw = replaceInLiteral(value);
}
};
const processNode = (node: Node) => {
if (!node) return;
if (node.type === 'Literal') {
const value = node.value;
if (typeof value !== 'string') return;
node.value = replaceInLiteral(value);
} else if (node.type === 'StringLiteral') {
const value = node.value;
if (typeof value !== 'string') return;
node.value = replaceInLiteral(value);
} else if (node.type === 'TemplateLiteral') {
node.quasis && replaceInTemplateLiteral(node.quasis);
} else if (node.type === 'JSXExpressionContainer') {
const expression = node.expression;
if (!expression) return;
if (expression.type === 'CallExpression') {
expression.arguments?.forEach(processNode);
} else {
processNode(expression);
}
} else if (node.type === 'ConditionalExpression') {
node.test && processNode(node.test);
node.consequent && processNode(node.consequent);
node.alternate && processNode(node.alternate);
} else if (node.type === 'BinaryExpression') {
node.right && processNode(node.right);
node.left && processNode(node.left);
} else if (node.type === 'LogicalExpression') {
node.right && processNode(node.right);
node.left && processNode(node.left);
}
};
/**
* Replace all class prefixes from 'fds-' to 'ds-'
* @param file
* @param api
* @returns
*/
function replaceClassNamePrefix(file: FileInfo, api: API): string | undefined {
const j = api.jscodeshift;
const root = j(file.source);
for (const path of root.find(j.JSXElement).paths()) {
const nodes = j(path).find(j.JSXAttribute, { name: { name: 'className' } });
for (const nodePath of nodes.paths()) {
processNode(nodePath.value.value as Node);
}
}
return root.toSource({
quote: 'single',
reuseWhitespace: true,
wrapColumn: 100,
});
}
export default replaceClassNamePrefix;