mermaidjs is a useful tool where one can turn text into diagrams easily. I have used it on many projects, but have long wanted a way to click on an element and bring up additional information. Using htmx and the bootstrap5 modal api , I have figured out a way to do it.
By default, Mermaid supports various interactions that you can use to attach actions to your nodes.
click A callback "Tooltip for a callback"
click B "https://www.github.com" "This is a tooltip for a link"
click C call callback() "Tooltip for a callback"
click D href "https://www.github.com" "This is a tooltip for a link"
In the past, I have used the href callback, but this time I wanted to implement a modal popup. For our implementation, we want the mermaidjs side to look like this.
click C call mermaidShowModal("/path/to/modal")
We start by adding our bootstrap modal container to our page.
<!-- We only need to implement basic shell, since the inside will be filled in by htmx -->
<div
id="modals-here"
class="modal modal-blur fade"
style="display: none"
aria-hidden="false"
tabindex="-1"
>
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content"></div>
</div>
</div>
If we read the documentation for the htmx ajax methods, we see how we can query and replace a selector.
function mermaidShowModal(href) {
htmx.ajax("GET", href, "#modals-here");
}
This gives us enough to call our method, and load a specific url, but we have not quite handled the modal part yet.
If we view the bootstrap documentation for the modal javascript we see how to access that.
// Set a constant reference to our modal object
const modal = new bootstrap.Modal("#modals-here");
function mermaidShowModal(href) {
// We can get the element associated with our modal object via
// modal._element
htmx.ajax("GET", href, modal._element);
}
Lastly, we need to actually show our modal value;
const modal = new bootstrap.Modal("#modals-here");
function mermaidShowModal(href) {
htmx.ajax("GET", href, modal._element).then(() => {
modal.show();
});
}
By default, mermaid disables some of our events, so we want to initalize it with a custom configuration.
const config = {
startOnLoad: true,
securityLevel: "loose",
};
mermaid.initialize(config);
With only a few lines of Javascript, we can now connect mermaidjs, htmx, and bootstrap into having easy to use modal information popups.
Moving forward, I expect to use mermaidjs to create various diagrams of servers and other systems, and have modal popups to show details and status for that node.