generated from JS-DevTools/template-node-typescript
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathfind-main-node.ts
44 lines (38 loc) · 1.21 KB
/
find-main-node.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
import { Node } from "unist";
import { isHtmlElementNode } from "./type-guards";
import { HtmlElementNode } from "./types";
/**
* Returns the `<main>` node, or the `<body>` node if there is no `<main>`.
* The second node returned is the parent of the first node.
*/
export function findMainNode(root: Node): [HtmlElementNode, HtmlElementNode] {
let [body, bodyParent] = findTagName(root, "body");
let [main, mainParent] = findTagName(body || root, "main");
if (main) {
return [main, mainParent || body || root as HtmlElementNode];
}
else {
return [
body || root as HtmlElementNode,
bodyParent || root as HtmlElementNode
];
}
}
/**
* Recursively crawls the HAST tree and finds the first element with the specified tag name.
*/
function findTagName(node: Node, tagName: string): [HtmlElementNode | undefined, HtmlElementNode | undefined] {
if (isHtmlElementNode(node) && node.tagName === tagName) {
return [node, undefined];
}
if (node.children) {
let parent = node as HtmlElementNode;
for (let child of parent.children!) {
let [found] = findTagName(child, tagName);
if (found) {
return [found, parent];
}
}
}
return [undefined, undefined];
}