Skip to content

Commit

Permalink
fix: rerender mermaid diagrams on theme change (#509)
Browse files Browse the repository at this point in the history
Make mermaid render diagrams on manual toggle between themes, after initial page load
  • Loading branch information
torbjornbp authored Dec 8, 2024
1 parent 0dcf7e7 commit bd34a5b
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion layouts/partials/scripts.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,32 @@
{{- $mermaidJS := resources.Get "lib/mermaid/mermaid.min.js" | fingerprint -}}
<script defer src="{{ $mermaidJS.RelPermalink }}" integrity="{{ $mermaidJS.Data.Integrity }}"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("DOMContentLoaded", () => {
// Store original mermaid code for each diagram
document.querySelectorAll(".mermaid").forEach(el => {
el.dataset.original = el.innerHTML;
});

const theme = document.documentElement.classList.contains("dark") ? "dark" : "default";
mermaid.initialize({ startOnLoad: true, theme: theme });

let timeout;
new MutationObserver(() => {
clearTimeout(timeout);
timeout = setTimeout(() => {
const theme = document.documentElement.classList.contains("dark") ? "dark" : "default";
document.querySelectorAll(".mermaid").forEach(el => {
// Reset to original content, preserving HTML
el.innerHTML = el.dataset.original;
el.removeAttribute("data-processed");
});
mermaid.initialize({ startOnLoad: true, theme: theme });
mermaid.init();
}, 150);
}).observe(document.documentElement, {
attributes: true,
attributeFilter: ["class"]
});
});
</script>
{{- end -}}
Expand Down

0 comments on commit bd34a5b

Please sign in to comment.