syntax-tree/mdast-util-toc

feature request: minDepth option

Closed this issue · 6 comments

Initial checklist

Problem

I am trying to create a table of contents for h2s and h3s only. There is a maxDepth option which enables me to ignore h4-h6 headings, but not a minDepth option to ignore h1s.

In my document, the single h1 is the main title of the document, with subheadings in the h2-h6 range.

It makes sense to me that the table of contents not contain the h1.

Solution

Add a minDepth option.

Alternatives

I could remove the h1 from the mdast tree before passing it to toc(mdast).

wooorm commented

Can you make this idea practical with a realistic input/actual/expected example?

Sure, given the following example:

import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkStringify from 'remark-stringify';
import { toc } from 'mdast-util-toc';

const markdown = `
# My awesome course

## Heading 2.1

Paragraph

### Heading 3.1

Paragraph

#### Heading 4.1

Paragraph

### Heading 3.2

Paragraph

## Heading 2.2

Paragraph

### Heading 3.3

Paragraph

## Heading 2.3

Paragraph

### Heading 3.4

Paragraph

#### Heading 4.2

Paragraph
`

const processor = unified().use(remarkParse).use(remarkStringify)

const mdast = processor.parse(markdown);

const tocMdast = toc(mdast as Nodes, { maxDepth: 3 }).map

const tableOfContents = processor.stringify({ type: 'root', children: [tocMdast] })

console.log(tableOfContents)

The output is:

* [My amazing course](#my-amazing-course)

  * [Heading 2.1](#heading-21)

    * [Heading 3.1](#heading-31)
    * [Heading 3.2](#heading-32)

  * [Heading 2.2](#heading-22)

    * [Heading 3.3](#heading-33)

  * [Heading 2.3](#heading-23)

    * [Heading 3.4](#heading-34)

What I'm hoping to achieve is:

### Table of contents

* [Heading 2.1](#heading-21)

  * [Heading 3.1](#heading-31)
  * [Heading 3.2](#heading-32)

* [Heading 2.2](#heading-22)

  * [Heading 3.3](#heading-33)

* [Heading 2.3](#heading-23)

  * [Heading 3.4](#heading-34)

Thanks.

wooorm commented

Right, right. Yeah, I think this makes sense. Want to work on a PR?

Hi! This was marked as ready to be worked on! Note that while this is ready to be worked on, nothing is said about priority: it may take a while for this to be solved.

Is this something you can and want to work on?

Team: please use the area/* (to describe the scope of the change), platform/* (if this is related to a specific one), and semver/* and type/* labels to annotate this. If this is first-timers friendly, add good first issue and if this could use help, add help wanted.

Hi! This was closed. Team: If this was fixed, please add phase/solved. Otherwise, please add one of the no/* labels.

wooorm commented

Done in 7.1.0. Thank you!