fumadocs-core
Version:
The React.js library for building a documentation website
45 lines (43 loc) • 1.33 kB
JavaScript
import { t as flattenNode } from "../mdast-utils-mc9-X-PK.js";
import Slugger from "github-slugger";
import { visit } from "unist-util-visit";
//#region src/mdx-plugins/remark-heading.ts
const slugger = new Slugger();
const regex = /\s*\[#(?<slug>[^]+?)]\s*$/;
/**
* Add heading ids and extract TOC
*/
function remarkHeading({ slug: defaultSlug, customId = true, generateToc = true } = {}) {
return (root, file) => {
const toc = [];
slugger.reset();
visit(root, "heading", (heading) => {
heading.data ||= {};
heading.data.hProperties ||= {};
const props = heading.data.hProperties;
const lastNode = heading.children.at(-1);
if (lastNode?.type === "text" && customId) {
const match = regex.exec(lastNode.value);
if (match?.[1]) {
props.id = match[1];
lastNode.value = lastNode.value.slice(0, match.index);
}
}
let flattened = null;
if (!props.id) {
flattened ??= flattenNode(heading);
props.id = defaultSlug ? defaultSlug(root, heading, flattened) : slugger.slug(flattened);
}
if (generateToc) toc.push({
title: flattened ?? flattenNode(heading),
url: `#${props.id}`,
depth: heading.depth
});
return "skip";
});
if (generateToc) file.data.toc = toc;
};
}
//#endregion
export { remarkHeading };
//# sourceMappingURL=remark-heading.js.map