-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
48 lines (39 loc) · 1.12 KB
/
index.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
import { Heading as AstHeading } from "mdast";
import { Node, visit } from "unist-util-visit";
import { toString } from "mdast-util-to-string";
import { VFileWithOutput } from "unified";
export interface Heading {
depth: number;
value: string;
data?: any;
}
export const hasHeadingsData = (
data: unknown
): data is { headings: Heading[] } =>
data instanceof Object &&
data.hasOwnProperty("headings") &&
// @ts-expect-error
data.headings instanceof Array;
export const headings = (root: Node) => {
const headingList: Heading[] = [];
visit(root, "heading", (node: AstHeading) => {
const heading: Heading = {
depth: node.depth,
value: toString(node, { includeImageAlt: false }),
};
// Other remark plugins can store arbitrary data
// inside a node's `data` property, such as a
// custom heading id.
const data = node?.data;
if (data) {
heading.data = data;
}
headingList.push(heading);
});
return headingList;
};
export default function remarkHeadings() {
return (node: Node, file: VFileWithOutput<any>) => {
file.data.headings = headings(node);
};
}