-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathrender-result-naming-convention.ts
110 lines (91 loc) · 2.85 KB
/
render-result-naming-convention.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { ASTUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
import {
getDeepestIdentifierNode,
getFunctionName,
getInnermostReturningFunction,
isObjectPattern,
} from '../node-utils';
export const RULE_NAME = 'render-result-naming-convention';
export type MessageIds = 'renderResultNamingConvention';
type Options = [];
const ALLOWED_VAR_NAMES = ['view', 'utils'];
const ALLOWED_VAR_NAMES_TEXT = ALLOWED_VAR_NAMES.map(
(name) => `\`${name}\``
).join(', ');
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: 'Enforce a valid naming for return value from `render`',
recommendedConfig: {
dom: false,
angular: 'error',
react: 'error',
vue: 'error',
},
},
messages: {
renderResultNamingConvention: `\`{{ renderResultName }}\` is not a recommended name for \`render\` returned value. Instead, you should destructure it, or name it using one of: ${ALLOWED_VAR_NAMES_TEXT}`,
},
schema: [],
},
defaultOptions: [],
create(context, _, helpers) {
const renderWrapperNames: string[] = [];
function detectRenderWrapper(node: TSESTree.Identifier): void {
const innerFunction = getInnermostReturningFunction(context, node);
if (innerFunction) {
renderWrapperNames.push(getFunctionName(innerFunction));
}
}
return {
CallExpression(node) {
const callExpressionIdentifier = getDeepestIdentifierNode(node);
if (!callExpressionIdentifier) {
return;
}
if (helpers.isRenderUtil(callExpressionIdentifier)) {
detectRenderWrapper(callExpressionIdentifier);
}
},
VariableDeclarator(node) {
if (!node.init) {
return;
}
const initIdentifierNode = getDeepestIdentifierNode(node.init);
if (!initIdentifierNode) {
return;
}
if (
!helpers.isRenderVariableDeclarator(node) &&
!renderWrapperNames.includes(initIdentifierNode.name)
) {
return;
}
// check if destructuring return value from render
if (isObjectPattern(node.id)) {
return;
}
const renderResultName = ASTUtils.isIdentifier(node.id) && node.id.name;
if (!renderResultName) {
return;
}
const isAllowedRenderResultName =
ALLOWED_VAR_NAMES.includes(renderResultName);
// check if return value var name is allowed
if (isAllowedRenderResultName) {
return;
}
context.report({
node,
messageId: 'renderResultNamingConvention',
data: {
renderResultName,
},
});
},
};
},
});