jsx-key.js
9.05 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/**
* @fileoverview Report missing `key` props in iterators/collection literals.
* @author Ben Mosher
*/
'use strict';
const hasProp = require('jsx-ast-utils/hasProp');
const propName = require('jsx-ast-utils/propName');
const values = require('object.values');
const docsUrl = require('../util/docsUrl');
const pragmaUtil = require('../util/pragma');
const report = require('../util/report');
const astUtil = require('../util/ast');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const defaultOptions = {
checkFragmentShorthand: false,
checkKeyMustBeforeSpread: false,
warnOnDuplicates: false,
};
const messages = {
missingIterKey: 'Missing "key" prop for element in iterator',
missingIterKeyUsePrag: 'Missing "key" prop for element in iterator. Shorthand fragment syntax does not support providing keys. Use {{reactPrag}}.{{fragPrag}} instead',
missingArrayKey: 'Missing "key" prop for element in array',
missingArrayKeyUsePrag: 'Missing "key" prop for element in array. Shorthand fragment syntax does not support providing keys. Use {{reactPrag}}.{{fragPrag}} instead',
keyBeforeSpread: '`key` prop must be placed before any `{...spread}, to avoid conflicting with React’s new JSX transform: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html`',
nonUniqueKeys: '`key` prop must be unique',
};
module.exports = {
meta: {
docs: {
description: 'Disallow missing `key` props in iterators/collection literals',
category: 'Possible Errors',
recommended: true,
url: docsUrl('jsx-key'),
},
messages,
schema: [{
type: 'object',
properties: {
checkFragmentShorthand: {
type: 'boolean',
default: defaultOptions.checkFragmentShorthand,
},
checkKeyMustBeforeSpread: {
type: 'boolean',
default: defaultOptions.checkKeyMustBeforeSpread,
},
warnOnDuplicates: {
type: 'boolean',
default: defaultOptions.warnOnDuplicates,
},
},
additionalProperties: false,
}],
},
create(context) {
const options = Object.assign({}, defaultOptions, context.options[0]);
const checkFragmentShorthand = options.checkFragmentShorthand;
const checkKeyMustBeforeSpread = options.checkKeyMustBeforeSpread;
const warnOnDuplicates = options.warnOnDuplicates;
const reactPragma = pragmaUtil.getFromContext(context);
const fragmentPragma = pragmaUtil.getFragmentFromContext(context);
function checkIteratorElement(node) {
if (node.type === 'JSXElement' && !hasProp(node.openingElement.attributes, 'key')) {
report(context, messages.missingIterKey, 'missingIterKey', {
node,
});
} else if (checkFragmentShorthand && node.type === 'JSXFragment') {
report(context, messages.missingIterKeyUsePrag, 'missingIterKeyUsePrag', {
node,
data: {
reactPrag: reactPragma,
fragPrag: fragmentPragma,
},
});
}
}
function getReturnStatements(node) {
const returnStatements = arguments[1] || [];
if (node.type === 'IfStatement') {
if (node.consequent) {
getReturnStatements(node.consequent, returnStatements);
}
if (node.alternate) {
getReturnStatements(node.alternate, returnStatements);
}
} else if (Array.isArray(node.body)) {
node.body.forEach((item) => {
if (item.type === 'IfStatement') {
getReturnStatements(item, returnStatements);
}
if (item.type === 'ReturnStatement') {
returnStatements.push(item);
}
});
}
return returnStatements;
}
function isKeyAfterSpread(attributes) {
let hasFoundSpread = false;
return attributes.some((attribute) => {
if (attribute.type === 'JSXSpreadAttribute') {
hasFoundSpread = true;
return false;
}
if (attribute.type !== 'JSXAttribute') {
return false;
}
return hasFoundSpread && propName(attribute) === 'key';
});
}
/**
* Checks if the given node is a function expression or arrow function,
* and checks if there is a missing key prop in return statement's arguments
* @param {ASTNode} node
*/
function checkFunctionsBlockStatement(node) {
if (astUtil.isFunctionLikeExpression(node)) {
if (node.body.type === 'BlockStatement') {
getReturnStatements(node.body)
.filter((returnStatement) => returnStatement && returnStatement.argument)
.forEach((returnStatement) => {
checkIteratorElement(returnStatement.argument);
});
}
}
}
/**
* Checks if the given node is an arrow function that has an JSX Element or JSX Fragment in its body,
* and the JSX is missing a key prop
* @param {ASTNode} node
*/
function checkArrowFunctionWithJSX(node) {
const isArrFn = node && node.type === 'ArrowFunctionExpression';
if (isArrFn && (node.body.type === 'JSXElement' || node.body.type === 'JSXFragment')) {
checkIteratorElement(node.body);
}
}
const childrenToArraySelector = `:matches(
CallExpression
[callee.object.object.name=${reactPragma}]
[callee.object.property.name=Children]
[callee.property.name=toArray],
CallExpression
[callee.object.name=Children]
[callee.property.name=toArray]
)`.replace(/\s/g, '');
let isWithinChildrenToArray = false;
const seen = new WeakSet();
return {
[childrenToArraySelector]() {
isWithinChildrenToArray = true;
},
[`${childrenToArraySelector}:exit`]() {
isWithinChildrenToArray = false;
},
'ArrayExpression, JSXElement > JSXElement'(node) {
if (isWithinChildrenToArray) {
return;
}
const jsx = (node.type === 'ArrayExpression' ? node.elements : node.parent.children).filter((x) => x && x.type === 'JSXElement');
if (jsx.length === 0) {
return;
}
const map = {};
jsx.forEach((element) => {
const attrs = element.openingElement.attributes;
const keys = attrs.filter((x) => x.name && x.name.name === 'key');
if (keys.length === 0) {
if (node.type === 'ArrayExpression') {
report(context, messages.missingArrayKey, 'missingArrayKey', {
node: element,
});
}
} else {
keys.forEach((attr) => {
const value = context.getSourceCode().getText(attr.value);
if (!map[value]) { map[value] = []; }
map[value].push(attr);
if (checkKeyMustBeforeSpread && isKeyAfterSpread(attrs)) {
report(context, messages.keyBeforeSpread, 'keyBeforeSpread', {
node: node.type === 'ArrayExpression' ? node : node.parent,
});
}
});
}
});
if (warnOnDuplicates) {
values(map).filter((v) => v.length > 1).forEach((v) => {
v.forEach((n) => {
if (!seen.has(n)) {
seen.add(n);
report(context, messages.nonUniqueKeys, 'nonUniqueKeys', {
node: n,
});
}
});
});
}
},
JSXFragment(node) {
if (!checkFragmentShorthand || isWithinChildrenToArray) {
return;
}
if (node.parent.type === 'ArrayExpression') {
report(context, messages.missingArrayKeyUsePrag, 'missingArrayKeyUsePrag', {
node,
data: {
reactPrag: reactPragma,
fragPrag: fragmentPragma,
},
});
}
},
// Array.prototype.map
// eslint-disable-next-line no-multi-str
'CallExpression[callee.type="MemberExpression"][callee.property.name="map"],\
CallExpression[callee.type="OptionalMemberExpression"][callee.property.name="map"],\
OptionalCallExpression[callee.type="MemberExpression"][callee.property.name="map"],\
OptionalCallExpression[callee.type="OptionalMemberExpression"][callee.property.name="map"]'(node) {
if (isWithinChildrenToArray) {
return;
}
const fn = node.arguments.length > 0 && node.arguments[0];
if (!fn || !astUtil.isFunctionLikeExpression(fn)) {
return;
}
checkArrowFunctionWithJSX(fn);
checkFunctionsBlockStatement(fn);
},
// Array.from
'CallExpression[callee.type="MemberExpression"][callee.property.name="from"]'(node) {
if (isWithinChildrenToArray) {
return;
}
const fn = node.arguments.length > 1 && node.arguments[1];
if (!astUtil.isFunctionLikeExpression(fn)) {
return;
}
checkArrowFunctionWithJSX(fn);
checkFunctionsBlockStatement(fn);
},
};
},
};