diff --git a/public/site-scripts/theme-toggle.js b/public/site-scripts/theme-toggle.js index 202b7b2..aef1acc 100644 --- a/public/site-scripts/theme-toggle.js +++ b/public/site-scripts/theme-toggle.js @@ -3,7 +3,7 @@ const themeIcon = document.getElementById('theme-icon'); function getStoredTheme() { - return localStorage.getItem('picoPreferredColorScheme') || 'auto'; + return localStorage.getItem('picoPreferredColorScheme') || document.documentElement.getAttribute('data-theme') || 'auto'; } function storeTheme(theme) { @@ -14,19 +14,10 @@ return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } - function applyTheme() { - const storedTheme = getStoredTheme(); - let actualTheme; + function applyTheme(theme) { + document.documentElement.setAttribute('data-theme', theme); - if (storedTheme === 'auto') { - actualTheme = getSystemTheme(); - } else { - actualTheme = storedTheme; - } - - document.documentElement.setAttribute('data-theme', actualTheme); - - if (actualTheme === 'dark') { + if (theme === 'dark') { themeIcon.textContent = '☀️'; themeToggle.setAttribute('aria-pressed', 'true'); } else { @@ -36,19 +27,19 @@ } function toggleTheme() { - const currentStored = getStoredTheme(); + let currentStored = getStoredTheme(); + if (currentStored === 'auto') { + currentStored = getSystemTheme(); + } + if (currentStored === 'auto') { + currentStored = 'light'; + } let nextTheme; - if (currentStored === 'auto') { - nextTheme = 'light'; - } else if (currentStored === 'light') { - nextTheme = 'dark'; - } else { - nextTheme = 'auto'; - } + nextTheme = currentStored === 'light' ? 'dark' : 'light'; storeTheme(nextTheme); - applyTheme(); + applyTheme(nextTheme); } function init() {