valeriangalliat / markdown-it-anchor

A markdown-it plugin that adds an `id` attribute to headings and optionally permalinks.
The Unlicense
292 stars 72 forks source link

Return an array from the callback #72

Closed theredfish closed 4 years ago

theredfish commented 4 years ago

Hello,

I'm trying to use your callback function, but I'm facing issues. I would like to get an array of (token, info) instead of an item for each token. The current behaviour leads to the following issues (at least, in my case) :

For example markdown-it-toc-and-anchor allows to use the callback function to get the tocArray. However the plugin is out of date and does too much for me.

What do you think about this idea?

nagaozen commented 4 years ago

Hi! tl;dr answer: Not a good idea.

Conceptually, the scope of this project is about setting ids on the headers and, optionally, adding a permalink, not generating a TOC. For a TOC component made to be used with this plugin use markdown-it-toc-done-right.

That said, it's important to note that this project is currently powering many relevant projects out-there (over 400k weekly downloads) and breaking the API will probably cause issues in systems that are "working fine" fine today. If you just want to get an array of the header tokens, you might want to filter the markdown-it tokens on their rules. Or use the callback provided by this project as a pusher to an array somewhere else in your app.

theredfish commented 4 years ago

Hi, ok thank you for your time !

theredfish commented 4 years ago

If someone is looking for a way to get the anchors, I did something like that based on @nagaozen explanations :

// in a class / function / whatever
parser.use(markdownItAnchor, {
  level: [1],
  callback: (_token, info) => {
    this.toc.push({ title: info.title, anchor: info.slug });
  },
});

// table of contents will be generated once render has been called
// through the callback.
this.outHtml = parser.render(source);

return { toc: this.toc, outHtml: this.outHtml };

That's all :) this plugin already do all the stuff I need. If you use VueJS (or Angular, React, ... I guess?) Do not use the callback function in your component to update your data because it will call the render function of your component (and you will end up with an infinite loop). In my case I first parse the markdown, then I set the toc / outHtml properties in my component.

I do not use markdown-it-toc-done-right because I need to manage my own toc component. Also I do not want to change my markdown source with a "toc placeholder" or add a lot of dependencies to my app.