-
-
Notifications
You must be signed in to change notification settings - Fork 668
/
Copy pathorder-in-components.js
355 lines (320 loc) · 10 KB
/
order-in-components.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
/**
* @fileoverview Keep order of properties in components
* @author Michał Sajnóg
*/
'use strict'
const utils = require('../utils')
const traverseNodes = require('vue-eslint-parser').AST.traverseNodes
/**
* @typedef {import('eslint-visitor-keys').VisitorKeys} VisitorKeys
*/
const defaultOrder = [
// Side Effects (triggers effects outside the component)
'el',
// Global Awareness (requires knowledge beyond the component)
'name',
'key', // for Nuxt
'parent',
// Component Type (changes the type of the component)
'functional',
// Template Modifiers (changes the way templates are compiled)
['delimiters', 'comments'],
// Template Dependencies (assets used in the template)
['components', 'directives', 'filters'],
// Composition (merges properties into the options)
'extends',
'mixins',
['provide', 'inject'], // for Vue.js 2.2.0+
// Page Options (component rendered as a router page)
'ROUTER_GUARDS', // for Vue Router
'layout', // for Nuxt
'middleware', // for Nuxt
'validate', // for Nuxt
'scrollToTop', // for Nuxt
'transition', // for Nuxt
'loading', // for Nuxt
// Interface (the interface to the component)
'inheritAttrs',
'model',
['props', 'propsData'],
'emits', // for Vue.js 3.x
// Note:
// The `setup` option is included in the "Composition" category,
// but the behavior of the `setup` option requires the definition of "Interface",
// so we prefer to put the `setup` option after the "Interface".
'setup', // for Vue 3.x
// Local State (local reactive properties)
'asyncData', // for Nuxt
'data',
'fetch', // for Nuxt
'head', // for Nuxt
'computed',
// Events (callbacks triggered by reactive events)
'watch',
'watchQuery', // for Nuxt
'LIFECYCLE_HOOKS',
// Non-Reactive Properties (instance properties independent of the reactivity system)
'methods',
// Rendering (the declarative description of the component output)
['template', 'render'],
'renderError'
]
/** @type { { [key: string]: string[] } } */
const groups = {
LIFECYCLE_HOOKS: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'activated',
'deactivated',
'beforeUnmount', // for Vue.js 3.x
'unmounted', // for Vue.js 3.x
'beforeDestroy',
'destroyed',
'renderTracked', // for Vue.js 3.x
'renderTriggered', // for Vue.js 3.x
'errorCaptured' // for Vue.js 2.5.0+
],
ROUTER_GUARDS: ['beforeRouteEnter', 'beforeRouteUpdate', 'beforeRouteLeave']
}
/**
* @param {(string | string[])[]} order
*/
function getOrderMap(order) {
/** @type {Map<string, number>} */
const orderMap = new Map()
for (const [i, property] of order.entries()) {
if (Array.isArray(property)) {
for (const p of property) {
orderMap.set(p, i)
}
} else {
orderMap.set(property, i)
}
}
return orderMap
}
/**
* @param {Token} node
*/
function isComma(node) {
return node.type === 'Punctuator' && node.value === ','
}
const ARITHMETIC_OPERATORS = ['+', '-', '*', '/', '%', '**' /* es2016 */]
const BITWISE_OPERATORS = ['&', '|', '^', '~', '<<', '>>', '>>>']
const COMPARISON_OPERATORS = ['==', '!=', '===', '!==', '>', '>=', '<', '<=']
const RELATIONAL_OPERATORS = ['in', 'instanceof']
const ALL_BINARY_OPERATORS = new Set([
...ARITHMETIC_OPERATORS,
...BITWISE_OPERATORS,
...COMPARISON_OPERATORS,
...RELATIONAL_OPERATORS
])
const LOGICAL_OPERATORS = new Set(['&&', '||', '??' /* es2020 */])
/**
* Result `true` if the node is sure that there are no side effects
*
* Currently known side effects types
*
* node.type === 'CallExpression'
* node.type === 'NewExpression'
* node.type === 'UpdateExpression'
* node.type === 'AssignmentExpression'
* node.type === 'TaggedTemplateExpression'
* node.type === 'UnaryExpression' && node.operator === 'delete'
*
* @param {ASTNode} node target node
* @param {VisitorKeys} visitorKeys sourceCode.visitorKey
* @returns {boolean} no side effects
*/
function isNotSideEffectsNode(node, visitorKeys) {
let result = true
/** @type {ASTNode | null} */
let skipNode = null
traverseNodes(node, {
visitorKeys,
/** @param {ASTNode} node */
enterNode(node) {
if (!result || skipNode) {
return
}
if (
// no side effects node
node.type === 'FunctionExpression' ||
node.type === 'Identifier' ||
node.type === 'Literal' ||
// es2015
node.type === 'ArrowFunctionExpression' ||
node.type === 'TemplateElement' ||
// typescript
node.type === 'TSAsExpression'
) {
skipNode = node
} else if (
node.type !== 'Property' &&
node.type !== 'ObjectExpression' &&
node.type !== 'ArrayExpression' &&
(node.type !== 'UnaryExpression' ||
!['!', '~', '+', '-', 'typeof'].includes(node.operator)) &&
(node.type !== 'BinaryExpression' ||
!ALL_BINARY_OPERATORS.has(node.operator)) &&
(node.type !== 'LogicalExpression' ||
!LOGICAL_OPERATORS.has(node.operator)) &&
node.type !== 'MemberExpression' &&
node.type !== 'ConditionalExpression' &&
// es2015
node.type !== 'SpreadElement' &&
node.type !== 'TemplateLiteral' &&
// es2020
node.type !== 'ChainExpression'
) {
// Can not be sure that a node has no side effects
result = false
}
},
/** @param {ASTNode} node */
leaveNode(node) {
if (skipNode === node) {
skipNode = null
}
}
})
return result
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce order of properties in components',
categories: ['vue3-recommended', 'recommended'],
url: 'https://eslint.vuejs.org/rules/order-in-components.html'
},
fixable: 'code', // null or "code" or "whitespace"
schema: [
{
type: 'object',
properties: {
order: {
type: 'array'
}
},
additionalProperties: false
}
],
messages: {
order:
'The "{{name}}" property should be above the "{{firstUnorderedPropertyName}}" property on line {{line}}.'
}
},
/** @param {RuleContext} context */
create(context) {
const options = context.options[0] || {}
/** @type {(string|string[])[]} */
const order = options.order || defaultOrder
/** @type {(string|string[])[]} */
const extendedOrder = order.map(
(property) =>
(typeof property === 'string' && groups[property]) || property
)
const orderMap = getOrderMap(extendedOrder)
const sourceCode = context.getSourceCode()
/**
* @param {string} name
*/
function getOrderPosition(name) {
const num = orderMap.get(name)
return num == null ? -1 : num
}
/**
* @param {(Property | SpreadElement)[]} propertiesNodes
*/
function checkOrder(propertiesNodes) {
const properties = propertiesNodes
.filter(utils.isProperty)
.map((property) => ({
node: property,
name:
utils.getStaticPropertyName(property) ||
(property.key.type === 'Identifier' && property.key.name) ||
''
}))
for (const [i, property] of properties.entries()) {
const orderPos = getOrderPosition(property.name)
if (orderPos < 0) {
continue
}
const propertiesAbove = properties.slice(0, i)
const unorderedProperties = propertiesAbove
.filter(
(p) => getOrderPosition(p.name) > getOrderPosition(property.name)
)
.sort((p1, p2) =>
getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
)
const firstUnorderedProperty = unorderedProperties[0]
if (firstUnorderedProperty) {
const line = firstUnorderedProperty.node.loc.start.line
context.report({
node: property.node,
messageId: 'order',
data: {
name: property.name,
firstUnorderedPropertyName: firstUnorderedProperty.name,
line
},
*fix(fixer) {
const propertyNode = property.node
const firstUnorderedPropertyNode = firstUnorderedProperty.node
const hasSideEffectsPossibility = propertiesNodes
.slice(
propertiesNodes.indexOf(firstUnorderedPropertyNode),
propertiesNodes.indexOf(propertyNode) + 1
)
.some(
(property) =>
!isNotSideEffectsNode(property, sourceCode.visitorKeys)
)
if (hasSideEffectsPossibility) {
return
}
const afterComma = sourceCode.getTokenAfter(propertyNode)
const hasAfterComma = isComma(afterComma)
const beforeComma = sourceCode.getTokenBefore(propertyNode)
const codeStart = beforeComma.range[1] // to include comments
const codeEnd = hasAfterComma
? afterComma.range[1]
: propertyNode.range[1]
const removeStart = hasAfterComma
? codeStart
: beforeComma.range[0]
yield fixer.removeRange([removeStart, codeEnd])
const propertyCode =
sourceCode.text.slice(codeStart, codeEnd) +
(hasAfterComma ? '' : ',')
const insertTarget = sourceCode.getTokenBefore(
firstUnorderedPropertyNode
)
yield fixer.insertTextAfter(insertTarget, propertyCode)
}
})
}
}
}
return utils.compositingVisitors(
utils.executeOnVue(context, (obj) => {
checkOrder(obj.properties)
}),
utils.defineScriptSetupVisitor(context, {
onDefineOptionsEnter(node) {
if (node.arguments.length === 0) return
const define = node.arguments[0]
if (define.type !== 'ObjectExpression') return
checkOrder(define.properties)
}
})
)
}
}