Last active
August 22, 2023 17:28
-
-
Save dbernheisel/7fbf6f08a8b4146c0f859bf0e8086322 to your computer and use it in GitHub Desktop.
How to handle switching themes in Mermaid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# keep the src around for mermaid for re-renders. | |
def maybe_rewrite_mermaid( | |
{"pre", _attrs, [{"code", [{"class", "mermaid"}], inner, meta}], pre_meta} | |
) do | |
{"div", | |
[ | |
{"phx-update", "ignore"} | |
], | |
[ | |
{"pre", | |
[ | |
{"class", "mermaid flex place-content-center"}, | |
{"data-src", inner} | |
], [], meta} | |
], pre_meta} | |
end | |
def maybe_rewrite_mermaid(code_ast), do: code_ast |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For initializing mermaid with the ability to change themes. | |
import mermaid from 'mermaid' | |
window.mermId = 0 | |
window.getMermId = () => `mermaid-id-${window.mermId++}` | |
window.merm = mermaid.mermaidAPI | |
window.mermOpts = { | |
startOnLoad: false, | |
// know somehow what theme you're currently on; I'm storing in window.theme which is initialized earlier. | |
theme: window.theme === 'dark' ? 'dark' : 'default', | |
darkMode: window.theme === 'dark', | |
fontFamily: 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"' | |
} | |
window.merm.initialize(Object.assign({}, window.mermOpts)) | |
window.mermTheme = function(theme) { | |
window.mermOpts = { ...window.mermOpts, theme: theme, darkMode: theme === 'dark' } | |
window.merm.initialize(Object.assign({}, window.mermOpts)) | |
window.renderMermaids(document) | |
} | |
window.renderMermaids = function (el) { | |
el.querySelectorAll('pre.mermaid').forEach((mermEl) => { | |
if (mermEl.dataset.processed === 'true' && mermEl.dataset.theme === window.theme) { | |
return | |
} | |
if (mermEl.dataset.theme !== window.theme) { | |
window.merm.render(window.getMermId(), mermEl.dataset.src, (svg) => { | |
mermEl.innerHTML = svg | |
mermEl.dataset.theme = window.theme | |
}) | |
} | |
}) | |
} | |
// in your hooks for changing the theme | |
if (window.mermTheme) window.mermTheme('dark') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment