nagaozen / markdown-it-toc-done-right

A table of contents (TOC) plugin for Markdown-it with focus on semantic and security. Made to work gracefully with markdown-it-anchor.
MIT License
133 stars 26 forks source link

access the state object in the callback #47

Open rdeltour opened 3 years ago

rdeltour commented 3 years ago

Would it be possible to add the state object, or the runtime env, as an argument of the callback function?

I'm using markdown-it-doc-done-right in a context (building an Eleventy site)) where I don't control the call to the markdown-it renderer, but where I'd like to augment the passed environment with the toc AST.

I'd like to use this as a callback:

(html, ast, state) => {
  if (state.env && !state.env.toc) {
    state.env.toc = ast;
  }
}

I can submit a PR if you’re interested!

nagaozen commented 3 years ago

What an interesting scenario! Let me check if I got it right: (i) You don't control the call to markdownIt.render, but knows a priori that there's an env being passed as argument to it. (ii) Although without access to (i), you are able to specify additional options to markdown-it-toc-done-right, like a callback function. So, what's about:

// env exists
var env = {};

// it's possible to construct the markdown parser and provide options
var md = window.markdownit({
    html: false,
    xhtmlOut: true,
    typographer: true
}).use( window.markdownItAnchor, { permalink: true, permalinkBefore: true, permalinkSymbol: '§' } )
  .use( window.markdownItTocDoneRight, { callback: function (html, ast) { env.toc = ast } } );

// but you don't have access to this
var result = md.render("# markdown-it rulezz!\n\n${toc}\n## with markdown-it-toc-done-right rulezz even more!", env);
rdeltour commented 3 years ago

Thanks for answering! You got it (almost) right 😊

The issue in my case is that at the time I configure markdown-it-toc-done-right I do not know the env. In fact render is called several times (the context is a static site generation, let's say to simplify that it's called once per page), and each time with a different env. So I cannot use an external a priori known env in the callback function… the only way I could access it (as far as I understand) is if it was available dynamically from the callback arguments. Does it make any sense?