-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathhtml-no-duplicate-attributes.ts
More file actions
60 lines (47 loc) · 1.96 KB
/
html-no-duplicate-attributes.ts
File metadata and controls
60 lines (47 loc) · 1.96 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
import { BaseRuleVisitor, forEachAttribute } from "./utils/rule-utils.js"
import { ParserRule } from "../types.js"
import type { LintOffense, LintContext } from "../types.js"
import type { HTMLOpenTagNode, HTMLSelfCloseTagNode, HTMLAttributeNameNode, Node } from "@herb-tools/core"
class NoDuplicateAttributesVisitor extends BaseRuleVisitor {
visitHTMLOpenTagNode(node: HTMLOpenTagNode): void {
this.checkDuplicateAttributes(node)
super.visitHTMLOpenTagNode(node)
}
visitHTMLSelfCloseTagNode(node: HTMLSelfCloseTagNode): void {
this.checkDuplicateAttributes(node)
super.visitHTMLSelfCloseTagNode(node)
}
private checkDuplicateAttributes(node: HTMLOpenTagNode | HTMLSelfCloseTagNode): void {
const attributeNames = new Map<string, HTMLAttributeNameNode[]>()
forEachAttribute(node, (attributeNode) => {
if (attributeNode.name?.type !== "AST_HTML_ATTRIBUTE_NAME_NODE") return
const nameNode = attributeNode.name as HTMLAttributeNameNode
if (!nameNode.name) return
const attributeName = nameNode.name.value.toLowerCase() // HTML attributes are case-insensitive
if (!attributeNames.has(attributeName)) {
attributeNames.set(attributeName, [])
}
attributeNames.get(attributeName)!.push(nameNode)
})
for (const [attributeName, nameNodes] of attributeNames) {
if (nameNodes.length > 1) {
for (let i = 1; i < nameNodes.length; i++) {
const nameNode = nameNodes[i]
this.addOffense(
`Duplicate attribute \`${attributeName}\` found on tag. Remove the duplicate occurrence.`,
nameNode.location,
"error"
)
}
}
}
}
}
export class HTMLNoDuplicateAttributesRule extends ParserRule {
name = "html-no-duplicate-attributes"
check(node: Node, context?: Partial<LintContext>): LintOffense[] {
const visitor = new NoDuplicateAttributesVisitor(this.name, context)
visitor.visit(node)
return visitor.offenses
}
}