1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const t = require("babel-types");
|
4 | const utils_1 = require("./utils");
|
5 | function buildMethodName(n) {
|
6 | return `render${n.charAt(0).toUpperCase() + n.slice(1)}`;
|
7 | }
|
8 | exports.buildVistor = () => {
|
9 | const renameMap = new Map();
|
10 | const classMethodRenamer = () => {
|
11 | return {
|
12 | visitor: {
|
13 | JSXElement(path) {
|
14 | let methodName = '';
|
15 | const classMethod = path.findParent(p => p.isClassMethod());
|
16 | if (classMethod && classMethod.isClassMethod() && t.isIdentifier(classMethod.node.key)) {
|
17 | methodName = classMethod.node.key.name;
|
18 | if (methodName.startsWith('render') || methodName === 'constructor') {
|
19 | return;
|
20 | }
|
21 | classMethod.node.key = t.identifier(buildMethodName(methodName));
|
22 | }
|
23 | const classProp = path.findParent(p => p.isClassProperty());
|
24 | if (classProp && classProp.isClassProperty()) {
|
25 | methodName = classProp.node.key.name;
|
26 | if (methodName.startsWith('render')) {
|
27 | return;
|
28 | }
|
29 | if (!t.isArrowFunctionExpression(classProp.node.value)) {
|
30 | return;
|
31 | }
|
32 | classProp.replaceWith(t.classMethod('method', t.identifier(buildMethodName(methodName)), classProp.node.value.params, t.isBlockStatement(classProp.node.value.body) ? classProp.node.value.body : t.blockStatement([
|
33 | t.returnStatement(classProp.node.value.body)
|
34 | ])));
|
35 | return;
|
36 | }
|
37 | if (methodName.length > 0 && !methodName.startsWith('render')) {
|
38 | renameMap.set(methodName, buildMethodName(methodName));
|
39 | }
|
40 | },
|
41 | Identifier(path) {
|
42 | const name = path.node.name;
|
43 | if (renameMap.has(name)) {
|
44 | const memberExpr = path.parentPath;
|
45 | if (memberExpr.isMemberExpression() && memberExpr.parentPath.isCallExpression()) {
|
46 | const object = memberExpr.get('object');
|
47 | if (object.isThisExpression()) {
|
48 | path.replaceWith(t.identifier(buildMethodName(name)));
|
49 | }
|
50 | else if (object.isIdentifier() && utils_1.isDerivedFromThis(path.scope, object.node.name)) {
|
51 | memberExpr.replaceWith(t.memberExpression(t.thisExpression(), t.identifier(buildMethodName(name))));
|
52 | }
|
53 | }
|
54 | else if (memberExpr.isCallExpression() && utils_1.isDerivedFromThis(path.scope, name)) {
|
55 | path.scope.rename(name, buildMethodName(name));
|
56 | }
|
57 | }
|
58 | }
|
59 | }
|
60 | };
|
61 | };
|
62 | return classMethodRenamer;
|
63 | };
|
64 |
|
\ | No newline at end of file |