source: imaps-frontend/node_modules/eslint-plugin-react/lib/rules/no-array-index-key.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 7.3 KB
Line 
1/**
2 * @fileoverview Prevent usage of Array index in keys
3 * @author Joe Lencioni
4 */
5
6'use strict';
7
8const has = require('hasown');
9const astUtil = require('../util/ast');
10const docsUrl = require('../util/docsUrl');
11const pragma = require('../util/pragma');
12const report = require('../util/report');
13const variableUtil = require('../util/variable');
14
15// ------------------------------------------------------------------------------
16// Rule Definition
17// ------------------------------------------------------------------------------
18
19function isCreateCloneElement(node, context) {
20 if (!node) {
21 return false;
22 }
23
24 if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
25 return node.object
26 && node.object.name === pragma.getFromContext(context)
27 && ['createElement', 'cloneElement'].indexOf(node.property.name) !== -1;
28 }
29
30 if (node.type === 'Identifier') {
31 const variable = variableUtil.findVariableByName(context, node, node.name);
32 if (variable && variable.type === 'ImportSpecifier') {
33 return variable.parent.source.value === 'react';
34 }
35 }
36
37 return false;
38}
39
40const messages = {
41 noArrayIndex: 'Do not use Array index in keys',
42};
43
44/** @type {import('eslint').Rule.RuleModule} */
45module.exports = {
46 meta: {
47 docs: {
48 description: 'Disallow usage of Array index in keys',
49 category: 'Best Practices',
50 recommended: false,
51 url: docsUrl('no-array-index-key'),
52 },
53
54 messages,
55
56 schema: [],
57 },
58
59 create(context) {
60 // --------------------------------------------------------------------------
61 // Public
62 // --------------------------------------------------------------------------
63 const indexParamNames = [];
64 const iteratorFunctionsToIndexParamPosition = {
65 every: 1,
66 filter: 1,
67 find: 1,
68 findIndex: 1,
69 flatMap: 1,
70 forEach: 1,
71 map: 1,
72 reduce: 2,
73 reduceRight: 2,
74 some: 1,
75 };
76
77 function isArrayIndex(node) {
78 return node.type === 'Identifier'
79 && indexParamNames.indexOf(node.name) !== -1;
80 }
81
82 function isUsingReactChildren(node) {
83 const callee = node.callee;
84 if (
85 !callee
86 || !callee.property
87 || !callee.object
88 ) {
89 return null;
90 }
91
92 const isReactChildMethod = ['map', 'forEach'].indexOf(callee.property.name) > -1;
93 if (!isReactChildMethod) {
94 return null;
95 }
96
97 const obj = callee.object;
98 if (obj && obj.name === 'Children') {
99 return true;
100 }
101 if (obj && obj.object && obj.object.name === pragma.getFromContext(context)) {
102 return true;
103 }
104
105 return false;
106 }
107
108 function getMapIndexParamName(node) {
109 const callee = node.callee;
110 if (callee.type !== 'MemberExpression' && callee.type !== 'OptionalMemberExpression') {
111 return null;
112 }
113 if (callee.property.type !== 'Identifier') {
114 return null;
115 }
116 if (!has(iteratorFunctionsToIndexParamPosition, callee.property.name)) {
117 return null;
118 }
119
120 const name = /** @type {keyof iteratorFunctionsToIndexParamPosition} */ (callee.property.name);
121
122 const callbackArg = isUsingReactChildren(node)
123 ? node.arguments[1]
124 : node.arguments[0];
125
126 if (!callbackArg) {
127 return null;
128 }
129
130 if (!astUtil.isFunctionLikeExpression(callbackArg)) {
131 return null;
132 }
133
134 const params = callbackArg.params;
135
136 const indexParamPosition = iteratorFunctionsToIndexParamPosition[name];
137 if (params.length < indexParamPosition + 1) {
138 return null;
139 }
140
141 return params[indexParamPosition].name;
142 }
143
144 function getIdentifiersFromBinaryExpression(side) {
145 if (side.type === 'Identifier') {
146 return side;
147 }
148
149 if (side.type === 'BinaryExpression') {
150 // recurse
151 const left = getIdentifiersFromBinaryExpression(side.left);
152 const right = getIdentifiersFromBinaryExpression(side.right);
153 return [].concat(left, right).filter(Boolean);
154 }
155
156 return null;
157 }
158
159 function checkPropValue(node) {
160 if (isArrayIndex(node)) {
161 // key={bar}
162 report(context, messages.noArrayIndex, 'noArrayIndex', {
163 node,
164 });
165 return;
166 }
167
168 if (node.type === 'TemplateLiteral') {
169 // key={`foo-${bar}`}
170 node.expressions.filter(isArrayIndex).forEach(() => {
171 report(context, messages.noArrayIndex, 'noArrayIndex', {
172 node,
173 });
174 });
175
176 return;
177 }
178
179 if (node.type === 'BinaryExpression') {
180 // key={'foo' + bar}
181 const identifiers = getIdentifiersFromBinaryExpression(node);
182
183 identifiers.filter(isArrayIndex).forEach(() => {
184 report(context, messages.noArrayIndex, 'noArrayIndex', {
185 node,
186 });
187 });
188
189 return;
190 }
191
192 if (node.type === 'CallExpression'
193 && node.callee
194 && node.callee.type === 'MemberExpression'
195 && node.callee.object
196 && isArrayIndex(node.callee.object)
197 && node.callee.property
198 && node.callee.property.type === 'Identifier'
199 && node.callee.property.name === 'toString'
200 ) {
201 // key={bar.toString()}
202 report(context, messages.noArrayIndex, 'noArrayIndex', {
203 node,
204 });
205 return;
206 }
207
208 if (node.type === 'CallExpression'
209 && node.callee
210 && node.callee.type === 'Identifier'
211 && node.callee.name === 'String'
212 && Array.isArray(node.arguments)
213 && node.arguments.length > 0
214 && isArrayIndex(node.arguments[0])
215 ) {
216 // key={String(bar)}
217 report(context, messages.noArrayIndex, 'noArrayIndex', {
218 node: node.arguments[0],
219 });
220 }
221 }
222
223 function popIndex(node) {
224 const mapIndexParamName = getMapIndexParamName(node);
225 if (!mapIndexParamName) {
226 return;
227 }
228
229 indexParamNames.pop();
230 }
231
232 return {
233 'CallExpression, OptionalCallExpression'(node) {
234 if (isCreateCloneElement(node.callee, context) && node.arguments.length > 1) {
235 // React.createElement
236 if (!indexParamNames.length) {
237 return;
238 }
239
240 const props = node.arguments[1];
241
242 if (props.type !== 'ObjectExpression') {
243 return;
244 }
245
246 props.properties.forEach((prop) => {
247 if (!prop.key || prop.key.name !== 'key') {
248 // { ...foo }
249 // { foo: bar }
250 return;
251 }
252
253 checkPropValue(prop.value);
254 });
255
256 return;
257 }
258
259 const mapIndexParamName = getMapIndexParamName(node);
260 if (!mapIndexParamName) {
261 return;
262 }
263
264 indexParamNames.push(mapIndexParamName);
265 },
266
267 JSXAttribute(node) {
268 if (node.name.name !== 'key') {
269 // foo={bar}
270 return;
271 }
272
273 if (!indexParamNames.length) {
274 // Not inside a call expression that we think has an index param.
275 return;
276 }
277
278 const value = node.value;
279 if (!value || value.type !== 'JSXExpressionContainer') {
280 // key='foo' or just simply 'key'
281 return;
282 }
283
284 checkPropValue(value.expression);
285 },
286
287 'CallExpression:exit': popIndex,
288 'OptionalCallExpression:exit': popIndex,
289 };
290 },
291};
Note: See TracBrowser for help on using the repository browser.