✨ feat(theme-switcher): add theme reset button (#198)
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
// Get the theme switcher button element.
|
||||
// Get the theme switcher button elements.
|
||||
const themeSwitcher = document.querySelector(".theme-switcher");
|
||||
const themeResetter = document.querySelector(".theme-resetter");
|
||||
|
||||
// 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 set theme
|
||||
// Function to set theme.
|
||||
function setTheme(theme, saveToLocalStorage = false) {
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
currentTheme = theme;
|
||||
@@ -13,6 +14,12 @@ function setTheme(theme, saveToLocalStorage = false) {
|
||||
|
||||
if (saveToLocalStorage) {
|
||||
localStorage.setItem("theme", theme);
|
||||
themeResetter.classList.add("has-custom-theme");
|
||||
themeResetter.setAttribute("aria-hidden", "false");
|
||||
} else {
|
||||
localStorage.removeItem("theme");
|
||||
themeResetter.classList.remove("has-custom-theme");
|
||||
themeResetter.setAttribute("aria-hidden", "true");
|
||||
}
|
||||
|
||||
// Dispatch a custom event for comment systems.
|
||||
@@ -22,6 +29,12 @@ function setTheme(theme, saveToLocalStorage = false) {
|
||||
window.dispatchEvent(event);
|
||||
}
|
||||
|
||||
function resetTheme() {
|
||||
const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
const defaultTheme = isSystemDark ? "dark" : "light";
|
||||
setTheme(defaultTheme);
|
||||
}
|
||||
|
||||
// Function to switch between dark and light themes.
|
||||
function switchTheme() {
|
||||
// Set the new theme based on the current theme.
|
||||
@@ -31,6 +44,8 @@ function switchTheme() {
|
||||
|
||||
// Initialize the theme switcher button.
|
||||
themeSwitcher.addEventListener("click", switchTheme, false);
|
||||
themeResetter.addEventListener("click", resetTheme, false);
|
||||
|
||||
themeSwitcher.setAttribute("role", "button");
|
||||
let togglePressed = currentTheme === "dark" ? "true" : "false";
|
||||
themeSwitcher.setAttribute("aria-pressed", togglePressed);
|
||||
@@ -40,3 +55,9 @@ window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", e =
|
||||
const newTheme = e.matches ? "dark" : "light";
|
||||
setTheme(newTheme);
|
||||
});
|
||||
|
||||
if (localStorage.getItem("theme")) {
|
||||
themeResetter.classList.add("has-custom-theme");
|
||||
} else {
|
||||
themeResetter.classList.remove("has-custom-theme");
|
||||
}
|
||||
|
Reference in New Issue
Block a user