rehype-custom-toc 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 roboin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # rehype-custom-toc
2
+
3
+ rehype plugin to generate a customizable table of contents.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install rehype-custom-toc
9
+ ```
10
+
11
+ ## Example
12
+
13
+ ```javascript
14
+ import remarkComment from "remark-comment";
15
+ import remarkParse from "remark-parse";
16
+ import remarkRehype from "remark-rehype";
17
+ import rehypeCustomToc from "./index";
18
+ import rehypeStringify from "rehype-stringify";
19
+ import { unified } from "unified";
20
+
21
+ /**
22
+ * A comment node generated by the `remark-comment` plugin.
23
+ */
24
+ interface Comment extends Node {
25
+ type: "comment";
26
+ value: "";
27
+ commentValue: string;
28
+ }
29
+
30
+ const processor = unified()
31
+ .use(remarkParse)
32
+ .use(remarkComment, {
33
+ ast: true
34
+ })
35
+ .use(remarkRehype, {
36
+ handlers: {
37
+ /**
38
+ * Convert a mdast comment node to a hast comment node.
39
+ * @param _ State
40
+ * @param node mdast comment node
41
+ * @returns hast comment node
42
+ */
43
+ comment: (_, node: Comment) => ({
44
+ type: "comment",
45
+ value: node.commentValue
46
+ })
47
+ }
48
+ })
49
+ .use(rehypeCustomToc)
50
+ .use(rehypeStringify);
51
+
52
+ const markdown = `
53
+ # Title
54
+
55
+ This is a sample markdown paragraph.
56
+
57
+ <!-- toc -->
58
+
59
+ ## Section 1
60
+
61
+ ### Subsection 1.1
62
+ `;
63
+
64
+ processor.process(markdown).then((result) => {
65
+ console.log(result.toString());
66
+ });
67
+ ```
68
+
69
+ The above code will output the following (formatted for readability):
70
+
71
+ ```html
72
+ <h1 id="title">Title</h1>
73
+ <p>This is a sample markdown paragraph.</p>
74
+ <aside class="toc">
75
+ <h2>Contents</h2>
76
+ <nav>
77
+ <ul>
78
+ <li><a href="#title">Title</a></li>
79
+ <ul>
80
+ <li><a href="#section-1">Section 1</a></li>
81
+ <ul>
82
+ <li><a href="#subsection-11">Subsection 1.1</a></li>
83
+ </ul>
84
+ </ul>
85
+ </ul>
86
+ </nav>
87
+ </aside>
88
+ <h2 id="section-1">Section 1</h2>
89
+ <h3 id="subsection-11">Subsection 1.1</h3>
90
+ ```
91
+
92
+ ## Options
93
+
94
+ ### `template`
95
+
96
+ A function that takes the generated HTML and returns the final HTML. This can be used to wrap the generated HTML in a custom template.
97
+
98
+ Default:
99
+
100
+ ```javascript
101
+ const defaultTemplate = (html) => {
102
+ return `
103
+ <aside class="toc">
104
+ <h2>Contents</h2>
105
+ <nav>
106
+ ${html}
107
+ </nav>
108
+ </aside>`.trim();
109
+ };
110
+ ```
111
+
112
+ ### `maxDepth`
113
+
114
+ The maximum depth of headings to include in the table of contents.
115
+
116
+ Default: `3`
117
+
118
+ ### `ordered`
119
+
120
+ Whether to use an ordered list (`<ol>`) or an unordered list (`<ul>`).
121
+
122
+ Default: `false`
@@ -0,0 +1,48 @@
1
+ import type { Root } from "hast";
2
+ import type { Plugin } from "unified";
3
+ /**
4
+ * Custom TOC template function.
5
+ * @param html HTML content of the TOC list
6
+ * @returns Wrapped HTML content
7
+ */
8
+ type RehypeCustomTocTemplate = (html: string) => string;
9
+ /**
10
+ * Options for the rehypeCustomToc plugin.
11
+ */
12
+ interface RehypeCustomTocOptions {
13
+ /**
14
+ * A function that takes the generated HTML and returns the final HTML.
15
+ * This can be used to wrap the generated HTML in a custom template.
16
+ * @default
17
+ * ```javascript
18
+ * const defaultTemplate = (html) => {
19
+ * return `
20
+ * <aside class="toc">
21
+ * <h2>Contents</h2>
22
+ * <nav>
23
+ * ${html}
24
+ * </nav>
25
+ * </aside>`.trim();
26
+ * };
27
+ * ```
28
+ */
29
+ template?: RehypeCustomTocTemplate;
30
+ /**
31
+ * The maximum depth of headings to include in the table of contents.
32
+ * @default 3
33
+ */
34
+ maxDepth?: number;
35
+ /**
36
+ * Whether to use an ordered list (`<ol>`) or an unordered list (`<ul>`).
37
+ * @default false
38
+ */
39
+ ordered?: boolean;
40
+ }
41
+ /**
42
+ * Rehype plugin to generate a table of contents.
43
+ * @param userOptions Options for the plugin
44
+ * @returns The plugin
45
+ */
46
+ declare const rehypeCustomToc: Plugin<[RehypeCustomTocOptions], Root>;
47
+ export default rehypeCustomToc;
48
+ export type { RehypeCustomTocOptions, RehypeCustomTocTemplate };
package/dist/index.js ADDED
@@ -0,0 +1,141 @@
1
+ import GitHubSlugger from "github-slugger";
2
+ import { fromHtml } from "hast-util-from-html";
3
+ import { h } from "hastscript";
4
+ import { isNonEmptyArray } from "@robot-inventor/ts-utils";
5
+ import { toHtml } from "hast-util-to-html";
6
+ import { toText } from "hast-util-to-text";
7
+ import { visit } from "unist-util-visit";
8
+ import { visitParents } from "unist-util-visit-parents";
9
+ /**
10
+ * Default TOC template function for {@link RehypeCustomTocTemplate}.
11
+ * @param html HTML content of the TOC list
12
+ * @returns Wrapped HTML content
13
+ */
14
+ const defaultTemplate = (html) => `
15
+ <aside class="toc">
16
+ <h2>Contents</h2>
17
+ <nav>
18
+ ${html}
19
+ </nav>
20
+ </aside>`.trim();
21
+ /**
22
+ * Default options for the rehypeCustomToc plugin.
23
+ */
24
+ const DEFAULT_OPTIONS = {
25
+ maxDepth: 3,
26
+ ordered: false,
27
+ template: defaultTemplate
28
+ };
29
+ /**
30
+ * Generate the table of contents from the headings data.
31
+ * @param tree The HAST tree
32
+ * @param options Options for the plugin
33
+ * @returns The generated table of contents
34
+ */
35
+ // eslint-disable-next-line max-statements, max-lines-per-function
36
+ const generateToc = (tree, options) => {
37
+ const toc = {
38
+ children: [],
39
+ properties: {},
40
+ tagName: options.ordered ? "ol" : "ul",
41
+ type: "element"
42
+ };
43
+ const headings = [];
44
+ const slugger = new GitHubSlugger();
45
+ visit(tree, "element", (node) => {
46
+ if (!["h1", "h2", "h3", "h4", "h5", "h6"].includes(node.tagName))
47
+ return;
48
+ const text = toText(node).trim();
49
+ const slug = node.properties["id"] || slugger.slug(text);
50
+ node.properties["id"] = slug;
51
+ // eslint-disable-next-line no-magic-numbers
52
+ const depth = parseInt(node.tagName.slice(1), 10);
53
+ headings.push({
54
+ depth,
55
+ slug,
56
+ text
57
+ });
58
+ });
59
+ if (!isNonEmptyArray(headings))
60
+ return [];
61
+ let currentDepth = headings[0].depth;
62
+ let currentParent = toc;
63
+ const parents = [toc];
64
+ for (const heading of headings) {
65
+ // eslint-disable-next-line no-continue
66
+ if (heading.depth > options.maxDepth)
67
+ continue;
68
+ const li = h("li", h("a", { href: `#${heading.slug}` }, heading.text));
69
+ if (heading.depth === currentDepth) {
70
+ // The current heading is at the same level as the previous one.
71
+ currentParent.children.push(li);
72
+ currentDepth = heading.depth;
73
+ }
74
+ else if (heading.depth > currentDepth) {
75
+ // The current heading is at a deeper level than the previous one.
76
+ const ul = h(options.ordered ? "ol" : "ul", li);
77
+ currentParent.children.push(ul);
78
+ currentParent = ul;
79
+ parents.push(currentParent);
80
+ currentDepth = heading.depth;
81
+ }
82
+ else {
83
+ // The current heading is at a shallower level than the previous one.
84
+ // eslint-disable-next-line id-length
85
+ for (let i = 0; i < currentDepth - heading.depth; i++) {
86
+ parents.pop();
87
+ // eslint-disable-next-line no-magic-numbers
88
+ const parentNode = parents[parents.length - 1];
89
+ if (!parentNode) {
90
+ throw new Error("Parent node not found. Make sure the headings are sorted by depth.");
91
+ }
92
+ currentParent = parentNode;
93
+ }
94
+ currentParent.children.push(li);
95
+ currentDepth = heading.depth;
96
+ }
97
+ }
98
+ return fromHtml(options.template(toHtml(toc)), { fragment: true }).children;
99
+ };
100
+ /**
101
+ * Rehype plugin to generate a table of contents.
102
+ * @param userOptions Options for the plugin
103
+ * @returns The plugin
104
+ */
105
+ const rehypeCustomToc = (userOptions) => {
106
+ const options = { ...DEFAULT_OPTIONS, ...userOptions };
107
+ /**
108
+ * The transformer function for the plugin.
109
+ * @param tree The HAST tree
110
+ */
111
+ const transformer = (tree) => {
112
+ const tocNodes = generateToc(tree, options);
113
+ let tocInserted = false;
114
+ visitParents(tree, "comment", (node, ancestors) => {
115
+ if (node.value.trim().toLowerCase() !== "toc")
116
+ return;
117
+ // eslint-disable-next-line no-magic-numbers, @typescript-eslint/no-non-null-assertion
118
+ const parent = ancestors.at(-1);
119
+ const index = parent.children.indexOf(node);
120
+ // eslint-disable-next-line no-magic-numbers
121
+ if (parent.type === "element" && parent.tagName === "p" && parent.children.length === 1) {
122
+ // eslint-disable-next-line no-magic-numbers, @typescript-eslint/no-non-null-assertion
123
+ const grand = ancestors.at(-2);
124
+ const parentIdx = grand.children.indexOf(parent);
125
+ // eslint-disable-next-line no-magic-numbers
126
+ grand.children.splice(parentIdx, 1, ...tocNodes);
127
+ }
128
+ else {
129
+ // eslint-disable-next-line no-magic-numbers
130
+ parent.children.splice(index, 1, ...tocNodes);
131
+ }
132
+ tocInserted = true;
133
+ });
134
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
135
+ if (!tocInserted) {
136
+ tree.children.unshift(...tocNodes);
137
+ }
138
+ };
139
+ return transformer;
140
+ };
141
+ export default rehypeCustomToc;
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "rehype-custom-toc",
3
+ "version": "0.0.0",
4
+ "description": "rehype plugin to generate a customizable table of contents",
5
+ "keywords": [
6
+ "rehype",
7
+ "toc",
8
+ "unified",
9
+ "hast",
10
+ "html",
11
+ "markdown"
12
+ ],
13
+ "homepage": "https://github.com/Robot-Inventor/rehype-custom-toc#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/Robot-Inventor/rehype-custom-toc/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/Robot-Inventor/rehype-custom-toc.git"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Robot-Inventor",
23
+ "type": "module",
24
+ "main": "dist/index.js",
25
+ "types": "dist/index.d.ts",
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "scripts": {
30
+ "test": "cross-env NODE_ENV=\"production\" vitest",
31
+ "lint": "eslint --flag unstable_native_nodejs_ts_config \"./src/**/*.ts\"",
32
+ "build": "tsc",
33
+ "format": "prettier --write \"./src/**/*.ts\"",
34
+ "format:check": "prettier --check \"./src/**/*.ts\"",
35
+ "ci:version": "changeset version",
36
+ "ci:publish": "npm run build && changeset publish"
37
+ },
38
+ "dependencies": {
39
+ "@robot-inventor/ts-utils": "^0.8.3",
40
+ "github-slugger": "^2.0.0",
41
+ "hast-util-from-html": "^2.0.3",
42
+ "hast-util-to-html": "^9.0.5",
43
+ "hast-util-to-text": "^4.0.2",
44
+ "hastscript": "^9.0.1",
45
+ "unified": "^11.0.5",
46
+ "unist-util-visit": "^5.0.0",
47
+ "unist-util-visit-parents": "^6.0.2"
48
+ },
49
+ "devDependencies": {
50
+ "@changesets/changelog-github": "^0.5.2",
51
+ "@changesets/cli": "^2.29.8",
52
+ "@robot-inventor/eslint-config": "^11.1.1",
53
+ "@robot-inventor/tsconfig-base": "^7.0.0",
54
+ "@types/hast": "^3.0.4",
55
+ "cross-env": "^10.1.0",
56
+ "eslint": "^9.39.2",
57
+ "prettier": "^3.7.4",
58
+ "rehype-stringify": "^10.0.1",
59
+ "remark-comment": "^1.0.0",
60
+ "remark-parse": "^11.0.0",
61
+ "remark-rehype": "^11.1.2",
62
+ "typescript": "^5.9.3",
63
+ "vitest": "^4.0.16"
64
+ },
65
+ "overrides": {
66
+ "zod-validation-error": "^5.0.0"
67
+ }
68
+ }