Skip to content

Commit

Permalink
feat: re-render when switching themes
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Nov 29, 2023
1 parent b142b94 commit 44a201f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
34 changes: 34 additions & 0 deletions assets/hb/modules/mermaid/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
(() => {
const elements = Array.from(document.querySelectorAll<HTMLElement>('pre.mermaid'))
if (!elements) {
return
}
elements.forEach((ele) => {
ele.setAttribute('data-src', ele.innerHTML);
})

const resetElements = (): Promise<void> => {
return new Promise((resolve) => {
elements.forEach((ele) => {
ele.innerHTML = ele.getAttribute('data-src')??'';
ele.removeAttribute('data-processed')
})
resolve()
})
}
const init = (theme: string): void => {
window.mermaid.initialize({ theme })
window.mermaid.init({ theme }, elements)
}

const theme = localStorage.getItem('hb-theme')
if (theme === 'dark') {
init('dark')
}

document.addEventListener('hb:theme', (e) => {
resetElements()
.then(init(e.detail.theme === 'dark' ? 'dark' : 'default'))
.catch(console.error)
})
})()
6 changes: 6 additions & 0 deletions layouts/partials/mermaid/assets/init-js.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{{- $opts := dict "targetPath" "js/mermaid-init.js" "minify" hugo.IsProduction }}
{{- $js := resources.Get "hb/modules/mermaid/init.ts" | js.Build $opts }}
{{- if hugo.IsProduction }}
{{- $js = $js | fingerprint }}
{{- end }}
<script src="{{ $js.RelPermalink }}" defer></script>
7 changes: 7 additions & 0 deletions layouts/partials/mermaid/assets/js.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{{- if or (.HasShortcode "mermaid") (.Store.Get "hasMermaid") }}
<script type="module">
import mermaid from "{{ .Site.Params.mermaid.js_url }}";
window.mermaid = mermaid
</script>
{{ partialCached "mermaid/assets/init-js" . }}
{{- end -}}

0 comments on commit 44a201f

Please sign in to comment.