Skip to content

Commit

Permalink
feat: dynamic giscus theme switching
Browse files Browse the repository at this point in the history
  • Loading branch information
atsuyaw committed Nov 19, 2023
1 parent 8513726 commit d027fb6
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions v4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -749,6 +749,7 @@ Then, in the `config.toml` file, set the `giscus` parameter to `true` and the pr
giscusCategory = "General"
giscusCategoryId = "DIC_kwDOGX153M4B_2Vz" # generated by Giscus website
giscusTheme = "light"
giscusDarkTheme = "dark"
giscusReactions = "1"
giscusEmitMetadata = "0"
giscusLanguage = "en"
Expand Down
43 changes: 43 additions & 0 deletions v4/layouts/partials/giscus.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,48 @@
crossorigin="{{ .Site.Params.giscusCrossOrigin }}"
async>
</script>
{{ if .Site.Params.enableLightDarkMode | default false }}
<script class="giscusThemeSwitcher">
const lightDarkToggle = document.getElementById("light-dark-toggle");

function handleGiscusMessage(event) {
if (event.origin !== 'https://giscus.app') {
return;
}
if (!(typeof event.data === 'object' && event.data.giscus)) {
return;
}
if (lightDarkToggle.className === "fa fa-moon") {
setGiscusTheme("{{ .Site.Params.giscusDarkTheme | default "dark" }}");
}
window.removeEventListener("message", handleGiscusMessage);
};

function setGiscusTheme(mode){
function sendGiscusMsg(message) {
const iframe = document.querySelector("iframe.giscus-frame");
if (!iframe) return;
iframe.contentWindow.postMessage(
{ giscus: message }, "{{ .Site.Params.giscusJsUrl | strings.TrimSuffix "/client.js" }}"
);
}
sendGiscusMsg({
setConfig: {
theme: mode,
},
});
};

window.addEventListener("message", handleGiscusMessage);

lightDarkToggle.addEventListener("click", () => {
if (lightDarkToggle.className === "fa fa-moon") {
setGiscusTheme("{{ .Site.Params.giscusTheme }}");
} else {
setGiscusTheme("{{ .Site.Params.giscusDarkTheme | default "dark" }}");
}
});
</script>
{{ end }}
<div id="giscus"></div>
{{ end }}

0 comments on commit d027fb6

Please sign in to comment.