Skip to content

Commit

Permalink
Make dark/light mode change with website theme.
Browse files Browse the repository at this point in the history
  • Loading branch information
ramsayleung committed Dec 4, 2024
1 parent 96c9702 commit a8038d0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 8 deletions.
57 changes: 51 additions & 6 deletions layouts/partials/comments.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,52 @@
<script src="https://utteranc.es/client.js"
repo="ramsayleung/comment"
issue-term="title"
theme="github-light"
crossorigin="anonymous"
async>
<section>
<h2>Comments</h2>
<div id="comments-utteranc"></div>
</section>

<script type="text/javascript">

function getCurrentTheme() {
return document.documentElement.getAttribute('data-theme') || document.body.classList.contains('dark') ? 'dark' : 'light';
}

function loadUtterances(darkMode=false) {
const giscusContainer = document.getElementById("comments-utteranc");
if (giscusContainer !== null) {
giscusContainer.innerHTML = ''
const giscusScript = document.createElement("script");
giscusScript.setAttribute("id", "utteranc");
giscusScript.setAttribute("src", "https://utteranc.es/client.js");
giscusScript.setAttribute("data-repo", "ramsayleung/comment");
giscusScript.setAttribute("data-category", "Announcements");
giscusScript.setAttribute("data-mapping", "pathname");
giscusScript.setAttribute("data-reactions-enabled", "1");
giscusScript.setAttribute("data-emit-metadata", "0");
giscusScript.setAttribute("data-theme", darkMode ? "github-dark" : "github-light");
giscusScript.setAttribute("data-issue-term", "title");
giscusScript.setAttribute("crossorigin", "anonymous");
giscusScript.setAttribute("async", "true");
giscusContainer.appendChild(giscusScript);
}
}

const isDarkMode = getCurrentTheme() === 'dark';
loadUtterances(isDarkMode);

// Watch for theme changes
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const isDarkMode = getCurrentTheme() === 'dark';
loadUtterances(isDarkMode);
console.log(`changing theme`);
}
});
});

// Start observing the body element for class changes
observer.observe(document.body, {
attributes: true,
attributeFilter: ['class']
});

</script>
3 changes: 1 addition & 2 deletions layouts/shortcodes/heatmap.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@
<script type="text/javascript">
var myChart;

// Function to get current theme
function getCurrentTheme() {
return document.body.classList.contains('dark') ? 'dark' : 'light';
return document.documentElement.getAttribute('data-theme') || document.body.classList.contains('dark') ? 'dark' : 'light';
}

function getThemeColors() {
Expand Down

0 comments on commit a8038d0

Please sign in to comment.