-
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
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
// SPDX-FileCopyrightText: 2024 Shota FUJI <pockawoooh@gmail.com>
//
// SPDX-License-Identifier: Apache-2.0
import type * as Hast from "../../../deps/esm.sh/hast/types.ts";
import { SKIP, visit } from "../../../deps/esm.sh/unist-util-visit/mod.ts";
import { fastUslug } from "../../../deps/esm.sh/@shelf/fast-uslug/mod.ts";
import { isElement } from "../../../deps/esm.sh/hast-util-is-element/mod.ts";
import { toString } from "../../../deps/esm.sh/hast-util-to-string/mod.ts";
export interface TocItem<Node = Hast.ElementContent[]> {
id: string;
text: Node;
level: number;
children: TocItem<Node>[];
}
export function mapTocItem<A, B>(item: TocItem<A>, f: (a: A) => B): TocItem<B> {
return {
id: item.id,
level: item.level,
text: f(item.text),
children: item.children.map((child) => mapTocItem(child, f)),
};
}
/**
* Mutates given Hast by adding ID to headings and Returns table of contents.
*/
export function tocMut<Node extends Hast.Node>(
hast: Node,
): readonly TocItem<Hast.ElementContent[]>[] {
const items: TocItem[] = [];
const stack: TocItem[] = [];
const pop = () => {
const popped = stack.pop();
if (!popped) {
return;
}
const parent = stack[stack.length - 1];
if (!parent) {
items.push(popped);
return;
}
parent.children.push(popped);
};
visit(hast, (node) => {
if (!isElement(node)) {
return false;
}
switch (node.tagName) {
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return true;
default:
return false;
}
}, (node) => {
if (!isElement(node)) {
return SKIP;
}
const levelMatch = node.tagName.match(/^h(\d)$/);
if (!levelMatch) {
return SKIP;
}
const level = parseInt(levelMatch[1]);
if (!Number.isFinite(level)) {
return SKIP;
}
let id = node.properties.id;
if (typeof id !== "string") {
id = fastUslug(toString(node), {
lower: false,
});
node.properties.id = id;
}
const item: TocItem = {
id,
level,
text: node.children,
children: [],
};
if (!stack.length) {
stack.push(item);
return;
}
for (let i = stack.length; i >= 0; i--) {
if (!stack[i]) {
continue;
}
if (level < stack[i].level) {
pop();
continue;
}
if (level === stack[i].level) {
pop();
stack.push(item);
break;
}
stack[i].children.push(item);
break;
}
});
while (stack.length > 0) {
pop();
}
return items;
}