-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathprefer-true-attribute-shorthand.js
110 lines (100 loc) · 3.05 KB
/
prefer-true-attribute-shorthand.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
/**
* @author Pig Fang
* See LICENSE file in root directory for full license.
*/
'use strict'
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const utils = require('../utils')
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'require shorthand form attribute when `v-bind` value is `true`',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/prefer-true-attribute-shorthand.html'
},
fixable: null,
hasSuggestions: true,
schema: [{ enum: ['always', 'never'] }],
messages: {
expectShort:
"Boolean prop with 'true' value should be written in shorthand form.",
expectLong:
"Boolean prop with 'true' value should be written in long form.",
rewriteIntoShort: 'Rewrite this prop into shorthand form.',
rewriteIntoLongVueProp:
'Rewrite this prop into long-form Vue component prop.',
rewriteIntoLongHtmlAttr:
'Rewrite this prop into long-form HTML attribute.'
}
},
/** @param {RuleContext} context */
create(context) {
/** @type {'always' | 'never'} */
const option = context.options[0] || 'always'
return utils.defineTemplateBodyVisitor(context, {
VAttribute(node) {
if (!utils.isCustomComponent(node.parent.parent)) {
return
}
if (option === 'never' && !node.directive && !node.value) {
context.report({
node,
messageId: 'expectLong',
suggest: [
{
messageId: 'rewriteIntoLongVueProp',
fix: (fixer) =>
fixer.replaceText(node, `:${node.key.rawName}="true"`)
},
{
messageId: 'rewriteIntoLongHtmlAttr',
fix: (fixer) =>
fixer.replaceText(
node,
`${node.key.rawName}="${node.key.rawName}"`
)
}
]
})
return
}
if (option !== 'always') {
return
}
if (
!node.directive ||
!node.value ||
!node.value.expression ||
node.value.expression.type !== 'Literal' ||
node.value.expression.value !== true
) {
return
}
const { argument } = node.key
if (!argument) {
return
}
context.report({
node,
messageId: 'expectShort',
suggest: [
{
messageId: 'rewriteIntoShort',
fix: (fixer) => {
const sourceCode = context.getSourceCode()
return fixer.replaceText(node, sourceCode.getText(argument))
}
}
]
})
}
})
}
}