Switching mermaid theme with docsify theme
Thank you for the excellent addon to docsify ecosystem!
One of the problems that we faced is that we use
- Probably the most common/widely used docsify-themeable
- And docsify-darklight-theme as a theme switcher
All out of the box mermaid themes work fine only on dark or light theme, i.e. there is no mermaid theme that works both for light and dark theme at the same time. So we came up with this code to make mermaid theme to match docsify theme.
<!-- Mermaid support -->
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
let theme = "base";
let dlTheme = localStorage.getItem('DARK_LIGHT_THEME');
if (dlTheme) {
if (dlTheme === "dark") {
theme = "dark";
}
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
theme = "dark";
}
mermaid.initialize({
startOnLoad: true,
theme: theme
});
window.mermaid = mermaid;
</script>
<script src="//unpkg.com/[email protected]/dist/docsify-mermaid.js"></script>
If docsify-darklight-theme switcher is not used, and docsify-themeable is defined by prefers-color-scheme like is written in docsify-themeable docs:
<link rel="stylesheet" media="(prefers-color-scheme: dark)" href= dark theme...
<link rel="stylesheet" media="(prefers-color-scheme: light)" href= light theme
Then the code above becomes:
<!-- Mermaid support -->
<script type="module">
import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs";
let theme = "base";
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
theme = "dark";
}
mermaid.initialize({
startOnLoad: true,
theme: theme
});
window.mermaid = mermaid;
</script>
<script src="//unpkg.com/[email protected]/dist/docsify-mermaid.js"></script>
This approach still has a problem that if theme is changed by docsify-darklight-theme switcher dynamically, mermaid theme is not switched until the next page reload. IDK if mermaid-docsify could integrate better theme and switching handling. But at least this issue might be useful for others searching how to deal with docsify themeable and mermaid themes.