remcohaszing / rehype-mermaid

A rehype plugin to render mermaid diagrams
MIT License
68 stars 8 forks source link

ColorScheme and dark doesn't work in the browser #13

Closed shashank1010 closed 5 months ago

shashank1010 commented 5 months ago

First off, Thank you for creating this useful library.

I have a very simple setup.

     const file = await unified()
                    .use(remarkParse)
                    .use(remarkGfm)
                    .use(remarkRehype)
                    .use(rehypeMermaid, {
                        colorScheme,
                        dark: colorScheme === 'dark' || undefined,
                    })
                    .use(rehypeReact, rehypeReactOptions)
                    .process(markdown);

When I pass colorScheme as dark and dark: true, it doesn't matter. The output is always exactly the same.

Upon investigating, I found that the options are not passed down to mermaid.render and thus, the result always is in light mode.

image

I was surprised that no one ever faced this issue. I suppose my only next option is to create a dark mode css theme of my own.

remcohaszing commented 5 months ago

I’m glad you like it. :)

The problem is that mermaid.render() doesn’t accept a theme, mermaid.initialize() does, but this configures it in global state. I don’t want this library to touch global state.

I think your best options is to have something like this in your code base:

import mermaid from 'mermaid'

const themeMatcher = window.matchMedia('(prefers-color-scheme: dark)')
themeMatcher.onchange = configureMermaid

function configureMermaid() {
  mermaid.initialize({
    startOnLoad: true,
    theme: themeMatcher.matches ? 'dark' : 'default'
  })
}

Then use the pre-mermaid strategy.

I would absolutely love to support this though. It would be great if you could realize support for passing a theme to mermaid.render(), so I can support it here. For now I’m closing this issue, as it’s not actionable for me.

shashank1010 commented 5 months ago

That's helpful!

I figured this out on my own hours after looking at the mermaid codebase, however, I'm still not sure if calling initialise would update the theme or not as my app supports updating the theme with the click of a button.

I have a suggestion though. Looking through the code base, I realised you parse the AST. That said, if there a possibility that you can add a configuration to the chart, then you can add dark mode by modifying the chart config. I'm sure you know that for each chart mermaid allows you to have a configuration and theme is acceptable in all of them.

For now, I have a solution which works for me.