2

I create the syntax for a mermaid mindmap diagram from my data (from an array) using Javascript. The diagram renders beautifully in https://mermaid.live/edit. I use the mermaid API with "await mermaid.renderAsync". (code attached). The problem now is that the first time I call it, the error "Syntax error in graph" appears and in the console the error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'h')
    at cF.run (cytoscape.umd.js

If I now change my theme (e.g. base or neutral or dark), the mindmap is displayed correctly on the second call. Where is the error here?

code to render the graph:

async function makeGraph(id) {
    let data = localStorage.getItem("mermaidMindMapInput");
    
    var svg = await mermaid.renderAsync("svg_" + id, data);
    var elem = document.getElementById(id);
    elem.innerHTML = svg;
}

html:

<div id="g2"></div>

code to change theme:

   function changeTheme() {
        // Get a reference to the select element
        var themeSelect = document.querySelector("#theme-select");

        // Add an event listener to the select element to change the theme
        console.log(document.querySelector("#theme-select"));
        document
            .querySelector("#theme-select")
            .addEventListener("change", function () {
                // Get the selected theme
                var selectedTheme = event.target.value;

                // Check if the selected theme is different from the current theme
                if (selectedTheme !== currentTheme) {
                    // Update the current theme
                    currentTheme = selectedTheme;

                    // Reinitialize Mermaid with the new theme
                    mermaid.initialize({ startOnLoad: true, theme: currentTheme });

                    var diagrams = document.querySelectorAll(".g2");
                    diagrams.forEach((diagram) => {
                        var svg = diagram.querySelector("svg");
                        if (svg) {
                            diagram.removeChild(svg);
                        }
                    });

                    makeGraph("g2");
                }
            });
    }

This is the result of the MindMap: enter image description here

Ralf Bordé
  • 333
  • 4
  • 18
  • 1
    Since `changeTheme` contains an `.addEventListener`, I assume that the function `changeTheme()` is called only _once_. Am I right? – Heiko Theißen Apr 23 '23 at 06:30
  • @HeikoTheißen: changeTheme() is not triggered during the initial call. I can then select via a select box and the change event is then triggered. – Ralf Bordé Apr 23 '23 at 07:41
  • But `changeTheme` does not _trigger_ the event, it _registers_ the event handler. And that should happen only once. – Heiko Theißen Apr 23 '23 at 11:40

1 Answers1

0

I solved my problem. First i call the changeTheme("neutral") with a fixed theme. Then i call the make_graph() function. And It works.!

Ralf Bordé
  • 333
  • 4
  • 18