mermaid

How to dynamically style a mermaid graph?


I have a simple mermaid graph in an html page:

<html>
  <body>
    <pre class="mermaid">
        stateDiagram

        OFF --> ON
        ON --> OFF

        classDef selected fill:yellow,font-weight:bold,stroke-width:2px

        class OFF selected
    </pre>

    <script type="module">
        import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
        mermaid.initialize({ startOnLoad: false });
        await mermaid.run();
    </script>

  </body>
</html>

It looks like this: enter image description here

I have a style called selected that highlights the currently selected node in yellow, in this case OFF.

I would like to be able to dynamically change the currently selected node in the image from OFF to ON and vice versa.

Is there a way in the mermaid API to dynamically apply styles or otherwise change the styling of the objects in a graph, dynamically at runtime using JS?


Solution

  • One way I was able to do it was to dynamically add the selected class to the proper node:

    <html>
      <body>
        <pre class="mermaid">
            stateDiagram
    
            OFF --> ON
            ON --> OFF
    
            classDef selected fill:yellow,font-weight:bold,stroke-width:2px
        </pre>
    
        <script type="module">
            import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
            mermaid.initialize({ startOnLoad: false });
            await mermaid.run();
    
            document.querySelectorAll('g').forEach((g) => {
                g.classList.remove('selected');
            });
            document.querySelector('g[data-id=ON]').classList.add('selected');
            await mermaid.run();
    
    </script>
    
      </body>
    </html>