-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathhtml-img-require-alt.ts
More file actions
43 lines (35 loc) · 1.27 KB
/
html-img-require-alt.ts
File metadata and controls
43 lines (35 loc) · 1.27 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
import { BaseRuleVisitor, getTagName, hasAttribute } from "./utils/rule-utils.js"
import { ParserRule } from "../types.js"
import type { LintOffense, LintContext } from "../types.js"
import type { HTMLOpenTagNode, HTMLSelfCloseTagNode, Node } from "@herb-tools/core"
class ImgRequireAltVisitor extends BaseRuleVisitor {
visitHTMLOpenTagNode(node: HTMLOpenTagNode): void {
this.checkImgTag(node)
super.visitHTMLOpenTagNode(node)
}
visitHTMLSelfCloseTagNode(node: HTMLSelfCloseTagNode): void {
this.checkImgTag(node)
super.visitHTMLSelfCloseTagNode(node)
}
private checkImgTag(node: HTMLOpenTagNode | HTMLSelfCloseTagNode): void {
const tagName = getTagName(node)
if (tagName !== "img") {
return
}
if (!hasAttribute(node, "alt")) {
this.addOffense(
'Missing required `alt` attribute on `<img>` tag. Add `alt=""` for decorative images or `alt="description"` for informative images.',
node.tag_name!.location,
"error"
)
}
}
}
export class HTMLImgRequireAltRule extends ParserRule {
name = "html-img-require-alt"
check(node: Node, context?: Partial<LintContext>): LintOffense[] {
const visitor = new ImgRequireAltVisitor(this.name, context)
visitor.visit(node)
return visitor.offenses
}
}