Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provide a way to extract the table of content #412

Closed
JeanMeche opened this issue Sep 21, 2023 · 3 comments · Fixed by #413
Closed

provide a way to extract the table of content #412

JeanMeche opened this issue Sep 21, 2023 · 3 comments · Fixed by #413
Labels

Comments

@JeanMeche
Copy link
Contributor

Right now, this package allows to generate headings with ids for markdown content and this works great !

Often for long document, you like to generate a table of content, with anchor links to those ids.

The issue is that I have found that hard to generate a TOC data set when using this plugin.

I was thinking about opening a PR to provide such function with the lexer output as argument :

const convertRaw = (raw) =>
  raw
    .toLowerCase()
    .trim()
    .replace(/<[!\/a-z].*?>/gi, '');

export function extractHeadings(lexer, { prefix = '' } = {}) {
  const slugger = new GithubSlugger();
  const headings = lexer.filter((x) => x.type === 'heading');

  return headings.map((heading) => {
    const raw = heading.raw); // doesn't work
    const raw = heading.text); // doesn't work
    const raw = heading.tokens.reduce((acc, token) => `${acc}${token.raw}`, ''); // doesn't work

    const slugged = slugger.slug(convertRaw(raw));
    console.log(raw, slugged, heading);
    return {
      raw: heading.raw,
      level: heading.depth,
      text: heading.text,
      id: `${prefix}${slugged}`,
    };
  });
}

It'd be great to have a way to acess the same raw as the one provided with the renderer. Wdyt ?

@UziTech
Copy link
Member

UziTech commented Sep 22, 2023

To avoid having to create each slug twice, since that id isn't sent to the renderer, we could keep the ids in an array and export a function that provides them.

So a user could write:

import { marked } from "marked";
import { gfmHeadingId, getHeadingList } from "marked-gfm-heading-id";

marked.use(gfmHeadingId());
marked.use({
  hooks: {
    postprocess(html) {
      const headings = getHeadingList();
      ...
    }
  }
});

@JeanMeche
Copy link
Contributor Author

This is a good alternative @UziTech ! I've opened a PR !

@github-actions
Copy link
Contributor

🎉 This issue has been resolved in version 3.1.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants