Skip to content

Commit

Permalink
[Docs Site] Re-render Mermaid diagrams when theme changes (#17312)
Browse files Browse the repository at this point in the history
* [Docs Site] Re-render Mermaid diagrams when theme changes

* Remove leftover FOUC fix

* Small refactor to init
  • Loading branch information
KianNH authored Oct 4, 2024
1 parent 8fe8308 commit 88ec628
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 7 deletions.
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"littlefoot": "^4.1.1",
"lz-string": "^1.5.0",
"marked": "^14.1.1",
"mermaid": "^11.2.1",
"mermaid": "^11.3.0",
"node-html-parser": "^6.1.13",
"patch-package": "^8.0.0",
"prettier": "^3.3.3",
Expand Down
35 changes: 34 additions & 1 deletion src/components/overrides/Head.astro
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,40 @@ if (Astro.props.entry.data.external_link) {
<script>
import mermaid from "mermaid";

mermaid.initialize({ startOnLoad: true, theme: "neutral" });
const diagrams = document.querySelectorAll<HTMLPreElement>("pre.mermaid");

let init = false;

async function render() {
const theme =
document.documentElement.getAttribute("data-theme") === "light"
? "neutral"
: "dark";

for (const diagram of diagrams) {
if (!init) {
diagram.setAttribute("data-diagram", diagram.textContent as string);
}

const def = diagram.getAttribute("data-diagram") as string;

mermaid.initialize({ startOnLoad: false, theme });
await mermaid
.render(`mermaid-${crypto.randomUUID()}`, def)
.then(({ svg }) => (diagram.innerHTML = svg));

diagram.setAttribute("data-processed", "true");
}

init = true;
}

const obs = new MutationObserver(() => render());

obs.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});
</script>
<script src="src/scripts/analytics.ts"></script>
<Default {...Astro.props}><slot /></Default>

0 comments on commit 88ec628

Please sign in to comment.