-
-
Notifications
You must be signed in to change notification settings - Fork 400
/
Copy pathattr-sorted.ts
60 lines (54 loc) · 1.42 KB
/
attr-sorted.ts
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
import { Rule } from '../types'
export default {
id: 'attr-sorted',
description: 'Attribute tags must be in proper order.',
init(parser, reporter) {
const orderMap: { [key: string]: number } = {}
const sortOrder = [
'class',
'id',
'name',
'src',
'for',
'type',
'href',
'value',
'title',
'alt',
'role',
]
for (let i = 0; i < sortOrder.length; i++) {
orderMap[sortOrder[i]] = i
}
parser.addListener('tagstart', (event) => {
const attrs = event.attrs
const listOfAttributes = []
for (let i = 0; i < attrs.length; i++) {
listOfAttributes.push(attrs[i].name)
}
const originalAttrs = JSON.stringify(listOfAttributes)
listOfAttributes.sort((a, b) => {
if (orderMap[a] == undefined && orderMap[b] == undefined) {
return a.localeCompare(b)
}
if (orderMap[a] == undefined) {
return 1
} else if (orderMap[b] == undefined) {
return -1
}
return orderMap[a] - orderMap[b] || a.localeCompare(b)
})
if (originalAttrs !== JSON.stringify(listOfAttributes)) {
reporter.error(
`Inaccurate order ${originalAttrs} should be in hierarchy ${JSON.stringify(
listOfAttributes
)} `,
event.line,
event.col,
this,
event.raw
)
}
})
},
} as Rule