Merge branch 'feature/refactor-theme-mode-switch'

This commit is contained in:
Cotes Chung 2021-12-13 03:33:32 +08:00
commit ebb3dc940c
2 changed files with 38 additions and 17 deletions

View file

@ -3,8 +3,34 @@
--> -->
<script src="https://cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js"></script>
<script> <script>
$(function() { $(function() {
function updateMermaid(event) {
if (event.source === window && event.data &&
event.data.direction === ModeToggle.ID) {
const mode = event.data.message;
if (typeof mermaid === "undefined") {
return;
}
let expectedTheme = (mode === ModeToggle.DARK_MODE? "dark" : "default");
let config = { theme: expectedTheme };
/* Re-render the SVG <https://github.com/mermaid-js/mermaid/issues/311#issuecomment-332557344> */
$(".mermaid").each(function() {
let svgCode = $(this).prev().children().html();
$(this).removeAttr("data-processed");
$(this).html(svgCode);
});
mermaid.initialize(config);
mermaid.init(undefined, ".mermaid");
}
}
let initTheme = "default"; let initTheme = "default";
if ($("html[mode=dark]").length > 0 if ($("html[mode=dark]").length > 0
@ -25,5 +51,7 @@
}); });
mermaid.initialize(mermaidConf); mermaid.initialize(mermaidConf);
window.addEventListener("message", updateMermaid);
}); });
</script> </script>

View file

@ -7,6 +7,7 @@
static get MODE_KEY() { return "mode"; } static get MODE_KEY() { return "mode"; }
static get DARK_MODE() { return "dark"; } static get DARK_MODE() { return "dark"; }
static get LIGHT_MODE() { return "light"; } static get LIGHT_MODE() { return "light"; }
static get ID() { return "mode-toggle"; }
constructor() { constructor() {
if (this.hasMode) { if (this.hasMode) {
@ -40,7 +41,8 @@
self.clearMode(); self.clearMode();
} }
self.updateMermaid(); self.notify();
}); });
} /* constructor() */ } /* constructor() */
@ -82,21 +84,12 @@
sessionStorage.removeItem(ModeToggle.MODE_KEY); sessionStorage.removeItem(ModeToggle.MODE_KEY);
} }
updateMermaid() { /* Notify another plugins that the theme mode has changed */
if (typeof mermaid !== "undefined") { notify() {
let expectedTheme = (this.modeStatus === ModeToggle.DARK_MODE? "dark" : "default"); window.postMessage({
let config = { theme: expectedTheme }; direction: ModeToggle.ID,
message: this.modeStatus
/* re-render the SVG <https://github.com/mermaid-js/mermaid/issues/311#issuecomment-332557344> */ }, "*");
$(".mermaid").each(function() {
let svgCode = $(this).prev().children().html();
$(this).removeAttr("data-processed");
$(this).html(svgCode);
});
mermaid.initialize(config);
mermaid.init(undefined, ".mermaid");
}
} }
} /* ModeToggle */ } /* ModeToggle */
@ -128,7 +121,7 @@
} }
} }
toggle.updateMermaid(); toggle.notify();
} /* flipMode() */ } /* flipMode() */