Skip to content

Commit

Permalink
feat: re-render mermaid when theme changed
Browse files Browse the repository at this point in the history
  • Loading branch information
st1020 committed Mar 18, 2024
1 parent 44acba4 commit be0ec89
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 6 deletions.
5 changes: 2 additions & 3 deletions static/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -1459,9 +1459,8 @@ body {
background-color: rgb(0 0 0 / var(--tw-bg-opacity));
}

.bg-white {
--tw-bg-opacity: 1;
background-color: rgb(255 255 255 / var(--tw-bg-opacity));
.bg-inherit {
background-color: inherit;
}

.bg-white\/50 {
Expand Down
8 changes: 7 additions & 1 deletion templates/partials/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@

// dark theme
const setDark = (isDark) => {
htmlClass[isDark ? "add" : "remove"]("dark");
if (isDark) {
document.body.dispatchEvent(new CustomEvent("set-theme", { detail: "dark" }));
htmlClass.add("dark");
} else {
document.body.dispatchEvent(new CustomEvent("set-theme", { detail: "light" }));
htmlClass.remove("dark");
}
localStorage.setItem("dark", isDark);
};

Expand Down
30 changes: 29 additions & 1 deletion templates/partials/mermaid.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,32 @@
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
mermaid.initialize({ startOnLoad: true });

const initMermaid = (isDark) => {
mermaid.initialize({
theme: isDark ? "dark" : "default",
startOnLoad: false,
});
mermaid.run();
};

// Add data-mermaid-code attribute on all mermaid block.
document.querySelectorAll(".mermaid").forEach((element) => {
element.setAttribute("data-mermaid-code", element.innerHTML);
});

// Re-render mermaid when theme changed.
document.body.addEventListener("set-theme", (e) => {
document.querySelectorAll(".mermaid").forEach((element) => {
const mermaidCode = element.getAttribute("data-mermaid-code");
if (mermaidCode != null) {
element.removeAttribute("data-processed");
element.innerHTML = mermaidCode;
}
});
initMermaid(e.detail == "dark");
});

// The es module script will load defer, so the localStorage should already be set by script in header.
// If this script is loaded first, the script in header will dispatch an event to re-render mermaid, it's works too.
initMermaid(localStorage.getItem("dark") === "true");
</script>
2 changes: 1 addition & 1 deletion templates/shortcodes/mermaid.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<pre class="mermaid bg-white">
<pre class="mermaid bg-inherit">
{{ body | trim_start_matches(pat="```mermaid") | trim_start_matches(pat="```") | trim_end_matches(pat="```") }}
</pre>

0 comments on commit be0ec89

Please sign in to comment.