generated from JS-DevTools/template-node-typescript
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathinsert-toc.ts
36 lines (30 loc) · 1.11 KB
/
insert-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
import { Node } from "unist";
import { NormalizedOptions } from "./options";
import { HtmlElementNode } from "./types";
/**
* Inserts the table of contents at the specified position, relative to the given nodes.
*
* @param toc - The table of contents node to insert
* @param target - The node to insert `toc` in/before/after
* @param parent - The parent node of `target`. This is used for inserting `toc` before/after `target`
* @param options - The `position` option determines where `toc` is inserted
*/
export function insertTOC(toc: Node, target: HtmlElementNode, parent: HtmlElementNode, { position }: NormalizedOptions): void {
let childIndex = parent.children!.indexOf(target);
switch (position) {
case "beforebegin":
parent.children!.splice(childIndex, 0, toc);
break;
case "afterbegin":
target.children!.unshift(toc);
break;
case "beforeend":
target.children!.push(toc);
break;
case "afterend":
parent.children!.splice(childIndex + 1, 0, toc);
break;
default:
throw new Error(`Invalid table-of-contents position: ${position}`);
}
}