-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNormalizedEventHandler.js
111 lines (89 loc) · 3.14 KB
/
NormalizedEventHandler.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
const BaseRule = require('src/rules/Base');
class NormalizedEventHandlerRule extends BaseRule {
/**
* allows to define expected Vue event handler declaration
*
* {@link https://vuejs.org/guide/essentials/event-handling.html#key-modifiers}
*
* @param {PatchronContext} patchronContext
* @param {NormalizedEventHandlerConfig} config
* @param {Patch} file
*/
constructor(patchronContext, config, file) {
super(patchronContext, file);
const { prefix, noUnnecessaryBraces } = config;
this.prefix = prefix;
this.noUnnecessaryBraces = noUnnecessaryBraces;
this.SHORTHAND_EVENT_EXPRESSION = /@click="(.*)"/;
this.LONGHAND_EVENT_EXPRESSION = /v-on:click="(.*)"/;
}
invoke() {
if (!this.prefix && !this.noUnnecessaryBraces) {
this.log.warning(__filename, 'Rule has no effect.', this.file);
return [];
}
const { splitPatch } = this.file;
const data = this.setupData(splitPatch);
const reviewComments = this._reviewData(data);
return reviewComments;
}
_reviewData(data) {
const reviewComments = [];
const dataLength = data.length;
for (let index = 0; index < dataLength; index++) {
const row = data[index];
const { trimmedContent } = row;
if (
this.CUSTOM_LINES.includes(trimmedContent) ||
trimmedContent.startsWith(this.HUNK_HEADER_INDICATOR)
) {
continue;
}
const matchResult =
trimmedContent.match(this.SHORTHAND_EVENT_EXPRESSION) ||
trimmedContent.match(this.LONGHAND_EVENT_EXPRESSION);
if (!matchResult) {
continue;
}
const eventHandler = matchResult[1];
if (eventHandler.includes('=') || eventHandler.startsWith('$')) {
continue;
}
const result = {
isWithPrefix: this.prefix
? eventHandler.startsWith(this.prefix)
: true,
hasNoUnnecessaryBraces: this.noUnnecessaryBraces
? trimmedContent.includes('()') ||
trimmedContent.includes('($event)')
: false
};
if (!result.isWithPrefix || result.hasNoUnnecessaryBraces) {
reviewComments.push(
this.getSingleLineComment({
body: this._getCommentBody(result),
index
})
);
}
}
return reviewComments;
}
/**
* @returns {string}
*/
_getCommentBody(result) {
return `Please
${
this.prefix && !result.isWithPrefix
? `, start event handler name with \`${this.prefix}\` prefix `
: ''
}
${
this.hasNoUnnecessaryBraces && !result.hasNoUnnecessaryBraces
? ', remove unnecessary braces.'
: ''
}`;
}
}
module.exports = NormalizedEventHandlerRule;