-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathtoc.ts
75 lines (58 loc) · 1.55 KB
/
toc.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { toc } from "mdast-util-toc";
import { remark } from "remark";
import { visit } from "unist-util-visit";
const textTypes = ["text", "emphasis", "strong", "inlineCode"];
function flattenNode(node: any) {
const p: any[] = [];
visit(node, (node) => {
if (!textTypes.includes(node.type)) return;
p.push(node.value);
});
return p.join("");
}
interface Item {
title: string;
url: string;
items?: Item[];
}
interface Items {
items?: Item[];
}
function getItems(node: any, current: any): Items {
if (!node) {
return {};
}
if (node.type === "paragraph") {
visit(node, (item) => {
if (item.type === "link") {
current.url = item.url;
current.title = flattenNode(node);
}
if (item.type === "text") {
current.title = flattenNode(node);
}
});
return current;
}
if (node.type === "list") {
current.items = node.children.map((i: any) => getItems(i, {}));
return current;
} else if (node.type === "listItem") {
const heading = getItems(node.children[0], {});
if (node.children.length > 1) {
getItems(node.children[1], heading);
}
return heading;
}
return {};
}
const getToc = () => (node: any, file: any) => {
const table = toc(node);
file.data = getItems(table.map, {});
};
export type TableOfContents = Items;
export async function getTableOfContents(content: string): Promise<TableOfContents> {
const result = await remark().use(getToc).process(content);
return result.data;
}