Skip to content
This repository has been archived by the owner on Jul 16, 2023. It is now read-only.

Commit

Permalink
fix(toc): 🐛 fix issue with sections creation when headers not start f…
Browse files Browse the repository at this point in the history
…rom h1
  • Loading branch information
filipowm committed Jul 3, 2020
1 parent 642680e commit b0c0ba4
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions plugins/gatsby-remark-sectionize-toc/sectionize-toc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,27 @@ const MAX_HEADING_DEPTH = 6;

module.exports = () => transform;

const transform = (tree, maxDepth) => {
const transform = (tree, maxDepth, title) => {
const maxTocDepth = maxDepth ? maxDepth : MAX_HEADING_DEPTH;
const visitFunction = sectionize(maxTocDepth);
const visitFunction = sectionize(maxTocDepth, title);
for (let depth = MAX_HEADING_DEPTH; depth > 0; depth--) {
visit(tree, (node) => node.type === 'heading' && node.depth === depth, visitFunction);
}
};
const sectionize = (maxTocDepth) => {
const sectionize = (maxTocDepth, title) => {
let minDepth = MAX_HEADING_DEPTH;
return (node, ancestors) => {
const start = node;
const depth = start.depth;
const parent = ancestors[ancestors.length - 1];

minDepth = depth < minDepth ? depth : minDepth;
const isEnd = (node) =>
(node.type === 'heading' && node.depth <= depth) ||
(node.type === 'section' && node.depth > depth && node.depth <= maxTocDepth) ||
// node.depth - (minDepth - 1) was added to fix case, when headers
// do not start from h1 or h2 (etc..)
(node.type === 'section' && node.depth > depth && (node.depth - (minDepth - 1) ) <= maxTocDepth) ||
node.type === 'export';
const end = findAfter(parent, start, isEnd);

const startIndex = parent.children.indexOf(start);
const endIndex = parent.children.indexOf(end);

Expand Down

0 comments on commit b0c0ba4

Please sign in to comment.