forked from sindresorhus/eslint-plugin-unicorn
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-event-key.js
234 lines (211 loc) · 5.15 KB
/
prefer-event-key.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
228
229
230
231
232
233
234
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');
const MESSAGE_ID = 'prefer-event-key';
const messages = {
[MESSAGE_ID]: 'Use `.key` instead of `.{{name}}`.'
};
const keys = new Set([
'keyCode',
'charCode',
'which'
]);
// https://github.com/facebook/react/blob/b87aabd/packages/react-dom/src/events/getEventKey.js#L36
// Only meta characters which can't be deciphered from `String.fromCharCode()`
const translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1',
113: 'F2',
114: 'F3',
115: 'F4',
116: 'F5',
117: 'F6',
118: 'F7',
119: 'F8',
120: 'F9',
121: 'F10',
122: 'F11',
123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
219: '[',
220: '\\',
221: ']',
222: '\'',
224: 'Meta'
};
const isPropertyNamedAddEventListener = node =>
node &&
node.type === 'CallExpression' &&
node.callee &&
node.callee.type === 'MemberExpression' &&
node.callee.property &&
node.callee.property.name === 'addEventListener';
const getEventNodeAndReferences = (context, node) => {
const eventListener = getMatchingAncestorOfType(node, 'CallExpression', isPropertyNamedAddEventListener);
const callback = eventListener && eventListener.arguments && eventListener.arguments[1];
switch (callback && callback.type) {
case 'ArrowFunctionExpression':
case 'FunctionExpression': {
const eventVariable = context.getDeclaredVariables(callback)[0];
const references = eventVariable && eventVariable.references;
return {
event: callback.params && callback.params[0],
references
};
}
default:
return {};
}
};
const isPropertyOf = (node, eventNode) => {
return (
node &&
node.parent &&
node.parent.type === 'MemberExpression' &&
node.parent.object &&
node.parent.object === eventNode
);
};
// The third argument is a condition function, as one passed to `Array#filter()`
// Helpful if nearest node of type also needs to have some other property
const getMatchingAncestorOfType = (node, type, fn = () => true) => {
let current = node;
while (current) {
if (current.type === type && fn(current)) {
return current;
}
current = current.parent;
}
};
const getParentByLevel = (node, level) => {
let current = node;
while (current && level) {
level--;
current = current.parent;
}
/* istanbul ignore else */
if (level === 0) {
return current;
}
};
const fix = node => fixer => {
// Since we're only fixing direct property access usages, like `event.keyCode`
const nearestIf = getParentByLevel(node, 3);
if (!nearestIf || nearestIf.type !== 'IfStatement') {
return;
}
const {right = {}, operator} = nearestIf.test;
const isTestingEquality = operator === '==' || operator === '===';
const isRightValid = isTestingEquality && right.type === 'Literal' && typeof right.value === 'number';
// Either a meta key or a printable character
const keyCode = translateToKey[right.value] || String.fromCharCode(right.value);
// And if we recognize the `.keyCode`
if (!isRightValid || !keyCode) {
return;
}
// Apply fixes
return [
fixer.replaceText(node, 'key'),
fixer.replaceText(right, quoteString(keyCode))
];
};
const create = context => {
const report = node => {
context.report({
messageId: MESSAGE_ID,
data: {name: node.name},
node,
fix: fix(node)
});
};
return {
'Identifier:matches([name="keyCode"], [name="charCode"], [name="which"])'(node) {
// Normal case when usage is direct -> `event.keyCode`
const {event, references} = getEventNodeAndReferences(context, node);
if (!event) {
return;
}
if (
references &&
references.some(reference => isPropertyOf(node, reference.identifier))
) {
report(node);
}
},
Property(node) {
// Destructured case
const propertyName = node.value && node.value.name;
if (!keys.has(propertyName)) {
return;
}
const {event, references} = getEventNodeAndReferences(context, node);
if (!event) {
return;
}
const nearestVariableDeclarator = getMatchingAncestorOfType(
node,
'VariableDeclarator'
);
const initObject =
nearestVariableDeclarator &&
nearestVariableDeclarator.init &&
nearestVariableDeclarator.init;
// Make sure initObject is a reference of eventVariable
if (
references &&
references.some(reference => reference.identifier === initObject)
) {
report(node.value);
return;
}
// When the event parameter itself is destructured directly
const isEventParameterDestructured = event.type === 'ObjectPattern';
if (isEventParameterDestructured) {
// Check for properties
for (const property of event.properties) {
if (property === node) {
report(node.value);
}
}
}
}
};
};
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code',
messages
}
};