forked from ember-cli/eslint-plugin-ember
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-attribute-order.js
More file actions
103 lines (95 loc) · 2.57 KB
/
template-attribute-order.js
File metadata and controls
103 lines (95 loc) · 2.57 KB
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
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'enforce consistent ordering of attributes in template elements',
category: 'Stylistic Issues',
strictGjs: true,
strictGts: true,
url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/template-attribute-order.md',
},
fixable: null,
schema: [
{
type: 'object',
properties: {
order: {
type: 'array',
items: {
type: 'string',
},
},
},
additionalProperties: false,
},
],
messages: {
wrongOrder: 'Attribute "{{currentAttr}}" should come {{position}} "{{expectedAttr}}".',
},
},
create(context) {
const options = context.options[0] || {};
const order = options.order || [
'class',
'id',
'role',
'aria-',
'data-test-',
'type',
'name',
'value',
'placeholder',
'disabled',
];
function getAttributeCategory(attrName) {
for (const category of order) {
if (category.endsWith('-')) {
if (attrName.startsWith(category)) {
return category;
}
} else if (attrName === category) {
return category;
}
}
return null;
}
function getExpectedIndex(attrName) {
const category = getAttributeCategory(attrName);
if (category === null) {
return order.length; // Unknown attributes go last
}
return order.indexOf(category);
}
return {
GlimmerElementNode(node) {
if (!node.attributes || node.attributes.length < 2) {
return;
}
const attributes = node.attributes.filter(
(attr) => attr.type === 'GlimmerAttrNode' && attr.name
);
for (let i = 1; i < attributes.length; i++) {
const current = attributes[i];
const currentIndex = getExpectedIndex(current.name);
for (let j = 0; j < i; j++) {
const previous = attributes[j];
const previousIndex = getExpectedIndex(previous.name);
if (currentIndex < previousIndex) {
context.report({
node: current,
messageId: 'wrongOrder',
data: {
currentAttr: current.name,
position: 'before',
expectedAttr: previous.name,
},
});
break;
}
}
}
},
};
},
};