-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathjsx-no-constructed-context-values.js
227 lines (202 loc) · 7.37 KB
/
jsx-no-constructed-context-values.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/**
* @fileoverview Prevents jsx context provider values from taking values that
* will cause needless rerenders.
* @author Dylan Oshima
*/
'use strict';
const Components = require('../util/Components');
const docsUrl = require('../util/docsUrl');
const getScope = require('../util/eslint').getScope;
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
// Recursively checks if an element is a construction.
// A construction is a variable that changes identity every render.
function isConstruction(node, callScope) {
switch (node.type) {
case 'Literal':
if (node.regex != null) {
return { type: 'regular expression', node };
}
return null;
case 'Identifier': {
const variableScoping = callScope.set.get(node.name);
if (variableScoping == null || variableScoping.defs == null) {
// If it's not in scope, we don't care.
return null; // Handled
}
// Gets the last variable identity
const variableDefs = variableScoping.defs;
const def = variableDefs[variableDefs.length - 1];
if (def != null
&& def.type !== 'Variable'
&& def.type !== 'FunctionName'
) {
// Parameter or an unusual pattern. Bail out.
return null; // Unhandled
}
if (def.node.type === 'FunctionDeclaration') {
return { type: 'function declaration', node: def.node, usage: node };
}
const init = def.node.init;
if (init == null) {
return null;
}
const initConstruction = isConstruction(init, callScope);
if (initConstruction == null) {
return null;
}
return {
type: initConstruction.type,
node: initConstruction.node,
usage: node,
};
}
case 'ObjectExpression':
// Any object initialized inline will create a new identity
return { type: 'object', node };
case 'ArrayExpression':
return { type: 'array', node };
case 'ArrowFunctionExpression':
case 'FunctionExpression':
// Functions that are initialized inline will have a new identity
return { type: 'function expression', node };
case 'ClassExpression':
return { type: 'class expression', node };
case 'NewExpression':
// `const a = new SomeClass();` is a construction
return { type: 'new expression', node };
case 'ConditionalExpression':
return (isConstruction(node.consequent, callScope)
|| isConstruction(node.alternate, callScope)
);
case 'LogicalExpression':
return (isConstruction(node.left, callScope)
|| isConstruction(node.right, callScope)
);
case 'MemberExpression': {
const objConstruction = isConstruction(node.object, callScope);
if (objConstruction == null) {
return null;
}
return {
type: objConstruction.type,
node: objConstruction.node,
usage: node.object,
};
}
case 'JSXFragment':
return { type: 'JSX fragment', node };
case 'JSXElement':
return { type: 'JSX element', node };
case 'AssignmentExpression': {
const construct = isConstruction(node.right, callScope);
if (construct != null) {
return {
type: 'assignment expression',
node: construct.node,
usage: node,
};
}
return null;
}
case 'TypeCastExpression':
case 'TSAsExpression':
return isConstruction(node.expression, callScope);
default:
return null;
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
withIdentifierMsg: "The '{{variableName}}' {{type}} (at line {{nodeLine}}) passed as the value prop to the Context provider (at line {{usageLine}}) changes every render. To fix this consider wrapping it in a useMemo hook.",
withIdentifierMsgFunc: "The '{{variableName}}' {{type}} (at line {{nodeLine}}) passed as the value prop to the Context provider (at line {{usageLine}}) changes every render. To fix this consider wrapping it in a useCallback hook.",
defaultMsg: 'The {{type}} passed as the value prop to the Context provider (at line {{nodeLine}}) changes every render. To fix this consider wrapping it in a useMemo hook.',
defaultMsgFunc: 'The {{type}} passed as the value prop to the Context provider (at line {{nodeLine}}) changes every render. To fix this consider wrapping it in a useCallback hook.',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallows JSX context provider values from taking values that will cause needless rerenders',
category: 'Best Practices',
recommended: false,
url: docsUrl('jsx-no-constructed-context-values'),
},
messages,
schema: [],
},
// eslint-disable-next-line arrow-body-style
create: Components.detect((context, components, utils) => {
return {
JSXOpeningElement(node) {
const openingElementName = node.name;
if (openingElementName.type !== 'JSXMemberExpression') {
// Has no member
return;
}
const isJsxContext = openingElementName.property.name === 'Provider';
if (!isJsxContext) {
// Member is not Provider
return;
}
// Contexts can take in more than just a value prop
// so we need to iterate through all of them
const jsxValueAttribute = node.attributes.find(
(attribute) => attribute.type === 'JSXAttribute' && attribute.name.name === 'value'
);
if (jsxValueAttribute == null) {
// No value prop was passed
return;
}
const valueNode = jsxValueAttribute.value;
if (!valueNode) {
// attribute is a boolean shorthand
return;
}
if (valueNode.type !== 'JSXExpressionContainer') {
// value could be a literal
return;
}
const valueExpression = valueNode.expression;
const invocationScope = getScope(context, node);
// Check if the value prop is a construction
const constructInfo = isConstruction(valueExpression, invocationScope);
if (constructInfo == null) {
return;
}
if (!utils.getParentComponent(node)) {
return;
}
// Report found error
const constructType = constructInfo.type;
const constructNode = constructInfo.node;
const constructUsage = constructInfo.usage;
const data = {
type: constructType, nodeLine: constructNode.loc.start.line,
};
let messageId = 'defaultMsg';
// Variable passed to value prop
if (constructUsage != null) {
messageId = 'withIdentifierMsg';
data.usageLine = constructUsage.loc.start.line;
data.variableName = constructUsage.name;
}
// Type of expression
if (
constructType === 'function expression'
|| constructType === 'function declaration'
) {
messageId += 'Func';
}
report(context, messages[messageId], messageId, {
node: constructNode,
data,
});
},
};
}),
};