Skip to content

Commit

Permalink
🐛 fix: properly initialise currentTheme
Browse files Browse the repository at this point in the history
The `currentTheme` variable is now properly initialized when setting
the initial theme, which fixes the "extra click" issue observed when system preference
is `dark` and there's no saved theme in localStorage.

Also minifies the themeSwitcher.

Fixes #94
  • Loading branch information
welpo committed Jul 24, 2023
1 parent b6f7f80 commit e1dfd2e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 48 deletions.
26 changes: 15 additions & 11 deletions static/js/themeSwitcher.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
// Get the theme switcher button element.
const themeSwitcher = document.querySelector(".theme-switcher");

// Retrieve theme from localStorage.
let currentTheme = localStorage.getItem("theme");
// Retrieve theme from either the localStorage or the data-theme attribute on the document element.
let currentTheme = localStorage.getItem("theme") || document.documentElement.getAttribute('data-theme');

// Function to switch between dark and light themes.
function setTheme(theme) {
// Function to set theme
function setTheme(theme, saveToLocalStorage = false) {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
currentTheme = theme;

if (saveToLocalStorage) {
localStorage.setItem("theme", theme);
}

// Dispatch a custom event for comment systems.
// Dispatch a custom event for utterances and giscus.
const event = new CustomEvent("themeChanged", {
detail: { theme: theme }
});
window.dispatchEvent(event);
}

// Function to switch between dark and light themes.
function switchTheme() {
// Set the new theme based on the current theme.
const newTheme = currentTheme === "dark" ? "light" : "dark";
setTheme(newTheme);
setTheme(newTheme, true); // Save the theme to localStorage when the user changes it.
}

// Initialize the theme switcher button.
themeSwitcher.addEventListener("click", switchTheme, false);

// Update the theme based on system preference if the user hasn't manually changed the theme.
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", e => {
if (!localStorage.getItem("theme")) {
const newTheme = e.matches ? "dark" : "light";
setTheme(newTheme);
}
const newTheme = e.matches ? "dark" : "light";
setTheme(newTheme);
});
38 changes: 1 addition & 37 deletions static/js/themeSwitcher.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e1dfd2e

Please sign in to comment.