parttio / vaadin-js-loader

Dynamic JavaScript loader for Vaadin
2 stars 0 forks source link

How to run mermaid.js with vaadin-js-loader #1

Open martin-schaefer opened 6 months ago

martin-schaefer commented 6 months ago

I had a hard time making mermaid.js run with Vaadin. Neither @NpmPackage nor @JsModule worked but with vaadin-js-loader it works and that's why I just wantet to drop the solution here.

The code below will load and kick in mermaid so it will render all diagrams on <pre>/<div> elements with class: "mermaid".

Thanks for this little gem!

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Pre;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.parttio.vaadinjsloader.JSLoader;

@Route("mermaid")
@PageTitle("MermaidViewer")
public class MermaidView extends Div {

    private String flowchart = "flowchart TB\n" +
                       "  ui([Angular App])-->|REST|bff(Spring Boot App)\n" +
                       "  subgraph Cluster\n" +
                       "    direction LR\n" +
                       "    bff-->|JDBC|db[(PostgreSQL)]\n" +
                       "  end";

    public MermaidView() {
        Pre pre = new Pre();
        pre.setClassName("mermaid");
        pre.setText(flowchart);
        add(pre);
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        JSLoader.loadCdnjs(attachEvent.getUI(),"mermaid", "10.9.1");
        attachEvent.getUI().getPage().executeJs("mermaid.run();");
    }

}
samie commented 5 months ago

Thank you! Great that you shared this, Mermaid is really good library. Also, using the attach event is good approach to lazy load when needed.

If you haven't already, you can also share tips at vaadin.com/forum/tag/i-made-this