/* Toggle Dark/Light Mode */ function initThemeToggle() { const rootHtml = document.documentElement; const toggleThemeBtn = document.getElementById("theme-toggle"); // The dataset of toggleThemeBtn comes with translated label & title texts for site's language function getThemeTexts(theme) { const isDarkMode = theme === "dark"; return { label: isDarkMode ? toggleThemeBtn.dataset.labelLight : toggleThemeBtn.dataset.labelDark, title: isDarkMode ? toggleThemeBtn.dataset.titleLight : toggleThemeBtn.dataset.titleDark, }; } // Apply correct aria-label and title to the theme toggle button function setLabelAndTitle(labelText, titleText) { toggleThemeBtn.setAttribute("aria-label", labelText); toggleThemeBtn.setAttribute("title", titleText); } // Apply different theme description to button & root, the display is handled by CSS function setTheme(theme) { const { label: newLabel, title: newTitle } = getThemeTexts(theme); setLabelAndTitle(newLabel, newTitle); rootHtml.setAttribute("data-theme", theme); } // Initial data-theme attribute is set by inline script in on first page load const initialTheme = rootHtml.getAttribute("data-theme") ?? "light"; const { label: initialLabel, title: initialTitle } = getThemeTexts(initialTheme); setLabelAndTitle(initialLabel, initialTitle); // Change theme on click and save user's choice toggleThemeBtn.addEventListener("click", () => { const newTheme = rootHtml.getAttribute("data-theme") === "dark" ? "light" : "dark"; setTheme(newTheme); localStorage.setItem("theme", newTheme); }); } export default initThemeToggle;