-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathv-on-handler-style.js
644 lines (620 loc) · 20.3 KB
/
v-on-handler-style.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/**
* @author Yosuke Ota <https://github.com/ota-meshi>
* See LICENSE file in root directory for full license.
*/
'use strict'
const utils = require('../utils')
/**
* @typedef {import('eslint').ReportDescriptorFix} ReportDescriptorFix
* @typedef {'method' | 'inline' | 'inline-function'} HandlerKind
* @typedef {object} ObjectOption
* @property {boolean} [ignoreIncludesComment]
* @property {boolean} [allowInlineFuncSingleArg]
*/
/**
* @param {RuleContext} context
*/
function parseOptions(context) {
/** @type {[HandlerKind | HandlerKind[] | undefined, ObjectOption | undefined]} */
const options = /** @type {any} */ (context.options)
/** @type {HandlerKind[]} */
const allows = []
if (options[0]) {
if (Array.isArray(options[0])) {
allows.push(...options[0])
} else {
allows.push(options[0])
}
} else {
allows.push('method', 'inline-function')
}
const option = options[1] || {}
const ignoreIncludesComment = !!option.ignoreIncludesComment
const allowInlineFuncSingleArg = option.allowInlineFuncSingleArg === true
return { allows, ignoreIncludesComment, allowInlineFuncSingleArg }
}
/**
* Check whether the given token is a quote.
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is a quote.
*/
function isQuote(token) {
return (
token != null &&
token.type === 'Punctuator' &&
(token.value === '"' || token.value === "'")
)
}
/**
* Check whether the given node is an identifier call expression. e.g. `foo()`
* @param {Expression} node The node to check.
* @returns {node is CallExpression & {callee: Identifier}}
*/
function isIdentifierCallExpression(node) {
if (node.type !== 'CallExpression') {
return false
}
if (node.optional) {
// optional chaining
return false
}
const callee = node.callee
return callee.type === 'Identifier'
}
/**
* Returns a call expression node if the given VOnExpression or BlockStatement consists
* of only a single identifier call expression.
* e.g.
* @click="foo()"
* @click="{ foo() }"
* @click="foo();;"
* @param {VOnExpression | BlockStatement} node
* @returns {CallExpression & {callee: Identifier} | null}
*/
function getIdentifierCallExpression(node) {
/** @type {ExpressionStatement} */
let exprStatement
let body = node.body
while (true) {
const statements = body.filter((st) => st.type !== 'EmptyStatement')
if (statements.length !== 1) {
return null
}
const statement = statements[0]
if (statement.type === 'ExpressionStatement') {
exprStatement = statement
break
}
if (statement.type === 'BlockStatement') {
body = statement.body
continue
}
return null
}
const expression = exprStatement.expression
if (!isIdentifierCallExpression(expression)) {
return null
}
return expression
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce writing style for handlers in `v-on` directives',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/v-on-handler-style.html'
},
fixable: 'code',
schema: {
anyOf: [
// `inline`, `inline-function` or `['method', 'inline']`
{
type: 'array',
items: [
{
anyOf: [
{ enum: ['inline', 'inline-function'] },
{
type: 'array',
items: [{ const: 'method' }, { const: 'inline' }],
uniqueItems: true,
additionalItems: false,
minItems: 2,
maxItems: 2
}
]
},
{
type: 'object',
properties: {
ignoreIncludesComment: {
type: 'boolean'
}
},
additionalProperties: false
}
],
additionalItems: false,
minItems: 1,
maxItems: 2
},
// `['method', 'inline-function']` or `['inline', 'inline-function']`
{
type: 'array',
items: [
{
type: 'array',
items: [
{ enum: ['method', 'inline'] },
{ const: 'inline-function' }
],
uniqueItems: true,
additionalItems: false,
minItems: 2,
maxItems: 2
},
{
type: 'object',
properties: {
ignoreIncludesComment: {
type: 'boolean'
},
allowInlineFuncSingleArg: {
type: 'boolean'
}
},
additionalProperties: false
}
],
additionalItems: false,
minItems: 0,
maxItems: 2
}
]
},
messages: {
preferMethodOverInline:
'Prefer method handler over inline handler in v-on.',
preferMethodOverInlineWithoutIdCall:
'Prefer method handler over inline handler in v-on. Note that you may need to create a new method.',
preferMethodOverInlineFunction:
'Prefer method handler over inline function in v-on.',
preferMethodOverInlineFunctionWithoutIdCall:
'Prefer method handler over inline function in v-on. Note that you may need to create a new method.',
preferInlineOverMethod:
'Prefer inline handler over method handler in v-on.',
preferInlineOverInlineFunction:
'Prefer inline handler over inline function in v-on.',
preferInlineOverInlineFunctionWithMultipleParams:
'Prefer inline handler over inline function in v-on. Note that the custom event must be changed to a single payload.',
preferInlineFunctionOverMethod:
'Prefer inline function over method handler in v-on.',
preferInlineFunctionOverInline:
'Prefer inline function over inline handler in v-on.'
}
},
/** @param {RuleContext} context */
create(context) {
const { allows, ignoreIncludesComment, allowInlineFuncSingleArg } =
parseOptions(context)
/** @type {Set<VElement>} */
const upperElements = new Set()
/** @type {Map<string, number>} */
const methodParamCountMap = new Map()
/** @type {Identifier[]} */
const $eventIdentifiers = []
/**
* Verify for inline handler.
* @param {VOnExpression} node
* @param {HandlerKind} kind
* @returns {boolean} Returns `true` if reported.
*/
function verifyForInlineHandler(node, kind) {
switch (kind) {
case 'method': {
return verifyCanUseMethodHandlerForInlineHandler(node)
}
case 'inline-function': {
reportCanUseInlineFunctionForInlineHandler(node)
return true
}
}
return false
}
/**
* Report for method handler.
* @param {Identifier} node
* @param {HandlerKind} kind
* @returns {boolean} Returns `true` if reported.
*/
function reportForMethodHandler(node, kind) {
switch (kind) {
case 'inline':
case 'inline-function': {
context.report({
node,
messageId:
kind === 'inline'
? 'preferInlineOverMethod'
: 'preferInlineFunctionOverMethod'
})
return true
}
}
// This path is currently not taken.
return false
}
/**
* Verify for inline function handler.
* @param {ArrowFunctionExpression | FunctionExpression} node
* @param {HandlerKind} kind
* @returns {boolean} Returns `true` if reported.
*/
function verifyForInlineFunction(node, kind) {
switch (kind) {
case 'method': {
return verifyCanUseMethodHandlerForInlineFunction(node)
}
case 'inline': {
reportCanUseInlineHandlerForInlineFunction(node)
return true
}
}
return false
}
/**
* Get token information for the given VExpressionContainer node.
* @param {VExpressionContainer} node
*/
function getVExpressionContainerTokenInfo(node) {
const sourceCode = context.getSourceCode()
const tokenStore = sourceCode.parserServices.getTemplateBodyTokenStore()
const tokens = tokenStore.getTokens(node, {
includeComments: true
})
const firstToken = tokens[0]
const lastToken = tokens[tokens.length - 1]
const hasQuote = isQuote(firstToken)
/** @type {Range} */
const rangeWithoutQuotes = hasQuote
? [firstToken.range[1], lastToken.range[0]]
: [firstToken.range[0], lastToken.range[1]]
return {
rangeWithoutQuotes,
get hasComment() {
return tokens.some(
(token) => token.type === 'Block' || token.type === 'Line'
)
},
hasQuote
}
}
/**
* Checks whether the given node refers to a variable of the element.
* @param {Expression | VOnExpression} node
*/
function hasReferenceUpperElementVariable(node) {
for (const element of upperElements) {
for (const vv of element.variables) {
for (const reference of vv.references) {
const { range } = reference.id
if (node.range[0] <= range[0] && range[1] <= node.range[1]) {
return true
}
}
}
}
return false
}
/**
* Check if `v-on:click="foo()"` can be converted to `v-on:click="foo"` and report if it can.
* @param {VOnExpression} node
* @returns {boolean} Returns `true` if reported.
*/
function verifyCanUseMethodHandlerForInlineHandler(node) {
const { rangeWithoutQuotes, hasComment } =
getVExpressionContainerTokenInfo(node.parent)
if (ignoreIncludesComment && hasComment) {
return false
}
const idCallExpr = getIdentifierCallExpression(node)
if (
(!idCallExpr || idCallExpr.arguments.length > 0) &&
hasReferenceUpperElementVariable(node)
) {
// It cannot be converted to method because it refers to the variable of the element.
// e.g. <template v-for="e in list"><button @click="foo(e)" /></template>
return false
}
context.report({
node,
messageId: idCallExpr
? 'preferMethodOverInline'
: 'preferMethodOverInlineWithoutIdCall',
fix: (fixer) => {
if (
hasComment /* The statement contains comment and cannot be fixed. */ ||
!idCallExpr /* The statement is not a simple identifier call and cannot be fixed. */ ||
idCallExpr.arguments.length > 0
) {
return null
}
const paramCount = methodParamCountMap.get(idCallExpr.callee.name)
if (paramCount != null && paramCount > 0) {
// The behavior of target method can change given the arguments.
return null
}
return fixer.replaceTextRange(
rangeWithoutQuotes,
context.getSourceCode().getText(idCallExpr.callee)
)
}
})
return true
}
/**
* Check if `v-on:click="() => foo()"` can be converted to `v-on:click="foo"` and report if it can.
* @param {ArrowFunctionExpression | FunctionExpression} node
* @returns {boolean} Returns `true` if reported.
*/
function verifyCanUseMethodHandlerForInlineFunction(node) {
const { rangeWithoutQuotes, hasComment } =
getVExpressionContainerTokenInfo(
/** @type {VExpressionContainer} */ (node.parent)
)
if (ignoreIncludesComment && hasComment) {
return false
}
/** @type {CallExpression & {callee: Identifier} | null} */
let idCallExpr = null
if (node.body.type === 'BlockStatement') {
idCallExpr = getIdentifierCallExpression(node.body)
} else if (isIdentifierCallExpression(node.body)) {
idCallExpr = node.body
}
if (
(!idCallExpr || !isSameParamsAndArgs(idCallExpr)) &&
hasReferenceUpperElementVariable(node)
) {
// It cannot be converted to method because it refers to the variable of the element.
// e.g. <template v-for="e in list"><button @click="() => foo(e)" /></template>
return false
}
context.report({
node,
messageId: idCallExpr
? 'preferMethodOverInlineFunction'
: 'preferMethodOverInlineFunctionWithoutIdCall',
fix: (fixer) => {
if (
hasComment /* The function contains comment and cannot be fixed. */ ||
!idCallExpr /* The function is not a simple identifier call and cannot be fixed. */
) {
return null
}
if (!isSameParamsAndArgs(idCallExpr)) {
// It is not a call with the arguments given as is.
return null
}
const paramCount = methodParamCountMap.get(idCallExpr.callee.name)
if (
paramCount != null &&
paramCount !== idCallExpr.arguments.length
) {
// The behavior of target method can change given the arguments.
return null
}
return fixer.replaceTextRange(
rangeWithoutQuotes,
context.getSourceCode().getText(idCallExpr.callee)
)
}
})
return true
/**
* Checks whether parameters are passed as arguments as-is.
* @param {CallExpression} expression
*/
function isSameParamsAndArgs(expression) {
return (
node.params.length === expression.arguments.length &&
node.params.every((param, index) => {
if (param.type !== 'Identifier') {
return false
}
const arg = expression.arguments[index]
if (!arg || arg.type !== 'Identifier') {
return false
}
return param.name === arg.name
})
)
}
}
/**
* Report `v-on:click="foo()"` can be converted to `v-on:click="()=>foo()"`.
* @param {VOnExpression} node
* @returns {void}
*/
function reportCanUseInlineFunctionForInlineHandler(node) {
context.report({
node,
messageId: 'preferInlineFunctionOverInline',
*fix(fixer) {
const has$Event = $eventIdentifiers.some(
({ range }) =>
node.range[0] <= range[0] && range[1] <= node.range[1]
)
if (has$Event) {
/* The statements contains $event and cannot be fixed. */
return
}
const { rangeWithoutQuotes, hasQuote } =
getVExpressionContainerTokenInfo(node.parent)
if (!hasQuote) {
/* The statements is not enclosed in quotes and cannot be fixed. */
return
}
yield fixer.insertTextBeforeRange(rangeWithoutQuotes, '() => ')
const sourceCode = context.getSourceCode()
const tokenStore =
sourceCode.parserServices.getTemplateBodyTokenStore()
const firstToken = tokenStore.getFirstToken(node)
const lastToken = tokenStore.getLastToken(node)
if (firstToken.value === '{' && lastToken.value === '}') return
if (
lastToken.value !== ';' &&
node.body.length === 1 &&
node.body[0].type === 'ExpressionStatement'
) {
// it is a single expression
return
}
yield fixer.insertTextBefore(firstToken, '{')
yield fixer.insertTextAfter(lastToken, '}')
}
})
}
/**
* Report `v-on:click="() => foo()"` can be converted to `v-on:click="foo()"`.
* @param {ArrowFunctionExpression | FunctionExpression} node
* @returns {void}
*/
function reportCanUseInlineHandlerForInlineFunction(node) {
// If a function has one parameter, you can turn it into an inline handler using $event.
// If a function has two or more parameters, it cannot be easily converted to an inline handler.
// However, users can use inline handlers by changing the payload of the component's custom event.
// So we report it regardless of the number of parameters.
context.report({
node,
messageId:
node.params.length > 1
? 'preferInlineOverInlineFunctionWithMultipleParams'
: 'preferInlineOverInlineFunction',
fix:
node.params.length > 0
? null /* The function has parameters and cannot be fixed. */
: (fixer) => {
let text = context.getSourceCode().getText(node.body)
if (node.body.type === 'BlockStatement') {
text = text.slice(1, -1) // strip braces
}
return fixer.replaceText(node, text)
}
})
}
return utils.defineTemplateBodyVisitor(
context,
{
VElement(node) {
upperElements.add(node)
},
'VElement:exit'(node) {
upperElements.delete(node)
},
/** @param {VExpressionContainer} node */
"VAttribute[directive=true][key.name.name='on'][key.argument!=null] > VExpressionContainer.value:exit"(
node
) {
const expression = node.expression
if (!expression) {
return
}
switch (expression.type) {
case 'VOnExpression': {
// e.g. v-on:click="foo()"
if (allows[0] === 'inline') {
return
}
for (const allow of allows) {
if (verifyForInlineHandler(expression, allow)) {
return
}
}
break
}
case 'Identifier': {
// e.g. v-on:click="foo"
if (allows[0] === 'method') {
return
}
for (const allow of allows) {
if (reportForMethodHandler(expression, allow)) {
return
}
}
break
}
case 'ArrowFunctionExpression':
case 'FunctionExpression': {
// e.g. v-on:click="()=>foo()"
if (allows[0] === 'inline-function') {
return
}
if (allows[1] === 'inline-function') {
if (expression.params.length > 1) {
return
}
if (
expression.params.length === 1 &&
allowInlineFuncSingleArg
) {
return
}
}
for (const allow of allows) {
if (verifyForInlineFunction(expression, allow)) {
return
}
}
break
}
default: {
return
}
}
},
...(allows.includes('inline-function')
? // Collect $event identifiers to check for side effects
// when converting from `v-on:click="foo($event)"` to `v-on:click="()=>foo($event)"` .
{
'Identifier[name="$event"]'(node) {
$eventIdentifiers.push(node)
}
}
: {})
},
allows.includes('method')
? // Collect method definition with params information to check for side effects.
// when converting from `v-on:click="foo()"` to `v-on:click="foo"`, or
// converting from `v-on:click="() => foo()"` to `v-on:click="foo"`.
utils.defineVueVisitor(context, {
onVueObjectEnter(node) {
for (const method of utils.iterateProperties(
node,
new Set(['methods'])
)) {
if (method.type !== 'object') {
// This branch is usually not passed.
continue
}
const value = method.property.value
if (
value.type === 'FunctionExpression' ||
value.type === 'ArrowFunctionExpression'
) {
methodParamCountMap.set(
method.name,
value.params.some((p) => p.type === 'RestElement')
? Number.POSITIVE_INFINITY
: value.params.length
)
}
}
}
})
: {}
)
}
}