-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjsx.ts
72 lines (59 loc) · 1.82 KB
/
jsx.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
import {
JSCodeshift,
JSXAttribute,
JSXElement,
JSXIdentifier,
} from "jscodeshift";
import { TransformerConfig } from "./shared";
import { componentsSelector } from "./v0-components";
const baseSelector = componentsSelector;
interface FindJSXElementOptions {
config: TransformerConfig;
moduleName: string;
selector?: string;
}
export function findByModuleName(options: FindJSXElementOptions) {
const { config, moduleName, selector = baseSelector } = options;
const regex = new RegExp(`^(${selector})$`);
const { root, j } = config;
const localNames = new Set();
root
.find(j.ImportDeclaration, {
source: { value: moduleName },
})
.find(j.ImportSpecifier, (node) => regex.test(node.imported.name))
.forEach((path) => {
localNames.add(path.value.local.name);
});
const check = (name: string) => {
return localNames.has(name);
};
return check;
}
export function findJSXElementsByModuleName(options: FindJSXElementOptions) {
options.selector ??= baseSelector;
const {
config: { root },
} = options;
const hasName = findByModuleName(options);
return root.findJSXElements().filter((node) => {
const identifier = node.value.openingElement.name as JSXIdentifier;
return hasName(identifier.name);
});
}
export function renameJSXElement(node: JSXElement, name: string) {
(node.openingElement.name as JSXIdentifier).name = name;
(node.closingElement.name as JSXIdentifier).name = name;
}
export function createJSXElement(
j: JSCodeshift,
localName: string,
attrs: JSXAttribute[] = [],
) {
const openingElement = j.jsxOpeningElement(j.jsxIdentifier(localName), attrs);
openingElement.selfClosing = true;
return j.jsxElement(openingElement);
}
export function getJSXElementName(node: JSXElement) {
return (node.openingElement.name as JSXIdentifier).name;
}