-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.ts
More file actions
44 lines (34 loc) · 1.31 KB
/
visitor.ts
File metadata and controls
44 lines (34 loc) · 1.31 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
/* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */
import { HTMLElement, Node, TextNode } from 'node-html-parser'
import { NoHtmlBodyError, UnsupportedHtmlError } from './errors.ts'
import { snakeToPascalCase } from '../../common/support/strings.ts'
export abstract class HtmlVisitor<T> {
visit(node: Node): T {
switch (node.nodeType) {
case 1: { // Element node
const element = node as HTMLElement
const pascalCase = snakeToPascalCase(element.tagName)
const methodName = `visit${pascalCase}`
if (methodName in this) {
const method = (this as unknown as Record<string, (element: HTMLElement) => T>)[methodName]
return method.call(this, element)
}
return this.visitHtmlElement(element)
}
case 3: // Text node
return this.visitText(node as TextNode)
default:
throw new UnsupportedHtmlError(`Unexpected node type ${node.nodeType}`)
}
}
visitRoot(element: HTMLElement): T {
const body = element.querySelector('body')
if (body === null) {
throw new NoHtmlBodyError('Could not find an HTML body element')
}
return this.visitBody(body)
}
abstract visitText(node: TextNode): T
abstract visitBody(element: HTMLElement): T
abstract visitHtmlElement(element: HTMLElement): T
}