-
Notifications
You must be signed in to change notification settings - Fork 0
/
normalize.ts
80 lines (62 loc) · 2.03 KB
/
normalize.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Heading, Nodes, Root } from "npm:@types/mdast";
import { SKIP, visitParents } from "npm:unist-util-visit-parents";
type AddValueToHeading<T extends Nodes> = T extends Heading
? Heading & { value: string }
: T;
const copyNodeWithoutChildren = <T extends Nodes>(
node: T,
): AddValueToHeading<T> => {
const result = { ...node };
if ("children" in result) {
result["children"] = [];
if (node.type === "heading" && node.children[0]?.type === "text") {
// @ts-ignore tyepscript doesn't understand that result is of type heading here
result.value = node.children[0].value;
}
}
if ("position" in result) {
delete result["position"];
}
// @ts-ignore it can't infer type of result properly
return result;
};
const copyRecursive = <T extends Nodes>(node: T): AddValueToHeading<T> => {
const result = copyNodeWithoutChildren(node);
if (node.type !== "heading" && "children" in node) {
for (const child of node["children"]) {
// @ts-ignore typescript doesn't understand result has children because node has
result.children.push(copyRecursive(child));
}
}
return result;
};
export const normalize = (root: Root): Root => {
const result = copyNodeWithoutChildren(root);
const stack: Heading[] = [];
visitParents(root, (node) => {
if (node.type === "root") return true;
const copy = copyRecursive(node);
if (node.type === "heading") {
while (stack.length > 0 && stack.at(-1)!.depth >= node.depth) {
stack.pop();
}
if (stack.length === 0) {
result.children.push(copy);
} else {
// @ts-ignore It doesn't infer type of copy correctly
stack.at(-1)!.children.push(copy);
}
// @ts-ignore It doesn't infer type of copy correctly
stack.push(copy);
return SKIP;
}
if (stack.length === 0) {
result.children.push(copy);
return SKIP;
}
// @ts-ignore It doesn't infer type of copy correctly
stack.at(-1)!.children.push(copy);
return SKIP;
});
return result;
};