forked from jsx-eslint/eslint-plugin-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsx-handler-names.js
74 lines (62 loc) · 2.21 KB
/
jsx-handler-names.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
/**
* @fileoverview Enforce event handler naming conventions in JSX
* @author Jake Marsh
*/
'use strict';
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Enforce event handler naming conventions in JSX',
category: 'Stylistic Issues',
recommended: false
},
schema: [{
type: 'object',
properties: {
eventHandlerPrefix: {
type: 'string'
},
eventHandlerPropPrefix: {
type: 'string'
}
},
additionalProperties: false
}]
},
create: function(context) {
var sourceCode = context.getSourceCode();
var configuration = context.options[0] || {};
var eventHandlerPrefix = configuration.eventHandlerPrefix || 'handle';
var eventHandlerPropPrefix = configuration.eventHandlerPropPrefix || 'on';
var EVENT_HANDLER_REGEX = new RegExp(`^((props\\.${eventHandlerPropPrefix})|((.*\\.)?${eventHandlerPrefix}))[A-Z].*$`);
var PROP_EVENT_HANDLER_REGEX = new RegExp(`^(${eventHandlerPropPrefix}[A-Z].*|ref)$`);
return {
JSXAttribute: function(node) {
if (!node.value || !node.value.expression || !node.value.expression.object) {
return;
}
var propKey = typeof node.name === 'object' ? node.name.name : node.name;
var propValue = sourceCode.getText(node.value.expression).replace(/^this\.|.*::/, '');
if (propKey === 'ref') {
return;
}
var propIsEventHandler = PROP_EVENT_HANDLER_REGEX.test(propKey);
var propFnIsNamedCorrectly = EVENT_HANDLER_REGEX.test(propValue);
if (propIsEventHandler && !propFnIsNamedCorrectly) {
context.report({
node: node,
message: `Handler function for ${propKey} prop key must begin with '${eventHandlerPrefix}'`
});
} else if (propFnIsNamedCorrectly && !propIsEventHandler) {
context.report({
node: node,
message: `Prop key for ${propValue} must begin with '${eventHandlerPropPrefix}'`
});
}
}
};
}
};