-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathhtml-no-nested-links.ts
More file actions
66 lines (51 loc) · 1.76 KB
/
html-no-nested-links.ts
File metadata and controls
66 lines (51 loc) · 1.76 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
import { BaseRuleVisitor, getTagName } from "./utils/rule-utils.js"
import { ParserRule } from "../types.js"
import type { LintOffense, LintContext } from "../types.js"
import type { HTMLOpenTagNode, HTMLElementNode, Node } from "@herb-tools/core"
class NestedLinkVisitor extends BaseRuleVisitor {
private linkStack: HTMLOpenTagNode[] = []
private checkNestedLink(openTag: HTMLOpenTagNode): boolean {
if (this.linkStack.length > 0) {
this.addOffense(
"Nested `<a>` elements are not allowed. Links cannot contain other links.",
openTag.tag_name!.location,
"error"
)
return true
}
return false
}
visitHTMLElementNode(node: HTMLElementNode): void {
if (!node.open_tag || node.open_tag.type !== "AST_HTML_OPEN_TAG_NODE") {
super.visitHTMLElementNode(node)
return
}
const openTag = node.open_tag as HTMLOpenTagNode
const tagName = getTagName(openTag)
if (tagName !== "a") {
super.visitHTMLElementNode(node)
return
}
// If we're already inside a link, this is a nested link
this.checkNestedLink(openTag)
this.linkStack.push(openTag)
super.visitHTMLElementNode(node)
this.linkStack.pop()
}
// Handle self-closing <a> tags (though they're not valid HTML, they might exist)
visitHTMLOpenTagNode(node: HTMLOpenTagNode): void {
const tagName = getTagName(node)
if (tagName === "a" && node.is_void) {
this.checkNestedLink(node)
}
super.visitHTMLOpenTagNode(node)
}
}
export class HTMLNoNestedLinksRule extends ParserRule {
name = "html-no-nested-links"
check(node: Node, context?: Partial<LintContext>): LintOffense[] {
const visitor = new NestedLinkVisitor(this.name, context)
visitor.visit(node)
return visitor.offenses
}
}