leafac / rehype-shiki

Rehype plugin to highlight code blocks with Shiki
MIT License
31 stars 3 forks source link

Fix duplicate roots for separate transforms #6

Closed TomerAberbach closed 2 years ago

TomerAberbach commented 2 years ago

It seems that performing two separate unified passes currently causes duplicate root nodes (e.g. { type: 'root' } as a child of the top-level root) when an AST from a prior transform is used with this plugin.

I was able to fix it by adding the parsed output's children individually rather than adding the root parsed output node. I've also confirmed that the newly added test fails before the change and passes with the change.

leafac commented 2 years ago

@TomerAberbach Thank you very much for the contribution. I merged it and published it as part of v2.1.2.

I’m curious: What’s the use case for two unified passes?

TomerAberbach commented 2 years ago

No problem!

My use case is:

  1. First unified pass: doing some processing on the server (e.g. parsing Markdown, applying transforms)
  2. Sending down the HTML AST to the client
  3. Second unified pass: using rehype-react to render the AST to React elements

This issue didn't happen if instead of sending the AST I serialized to HTML and then parsed it back on the client, but that would require me to include a library to parse the HTML (e.g. rehype-dom) which I didn't want to do if I could avoid it (for a smaller bundle size)

leafac commented 2 years ago

Thanks for sharing. That makes sense 👍