Files
Keyboard-Vagabond-Web/public/site-scripts/theme-toggle.js

64 lines
1.9 KiB
JavaScript
Raw Normal View History

2025-08-13 19:10:31 -05:00
(function() {
const themeToggle = document.getElementById('theme-toggle');
const themeIcon = document.getElementById('theme-icon');
function getStoredTheme() {
2025-08-16 09:43:25 -05:00
return localStorage.getItem('picoPreferredColorScheme') || document.documentElement.getAttribute('data-theme') || 'auto';
2025-08-13 19:10:31 -05:00
}
function storeTheme(theme) {
localStorage.setItem('picoPreferredColorScheme', theme);
}
function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
2025-08-16 09:43:25 -05:00
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
2025-08-13 19:10:31 -05:00
2025-08-16 09:43:25 -05:00
if (theme === 'dark') {
2025-08-13 19:10:31 -05:00
themeIcon.textContent = '☀️';
themeToggle.setAttribute('aria-pressed', 'true');
} else {
themeIcon.textContent = '🌙';
themeToggle.setAttribute('aria-pressed', 'false');
}
}
function toggleTheme() {
2025-08-16 09:43:25 -05:00
let currentStored = getStoredTheme();
2025-08-13 19:10:31 -05:00
if (currentStored === 'auto') {
2025-08-16 09:43:25 -05:00
currentStored = getSystemTheme();
}
if (currentStored === 'auto') {
currentStored = 'light';
2025-08-13 19:10:31 -05:00
}
2025-08-16 09:43:25 -05:00
let nextTheme;
nextTheme = currentStored === 'light' ? 'dark' : 'light';
2025-08-13 19:10:31 -05:00
storeTheme(nextTheme);
2025-08-16 09:43:25 -05:00
applyTheme(nextTheme);
2025-08-13 19:10:31 -05:00
}
function init() {
if (themeToggle) {
applyTheme();
themeToggle.addEventListener('click', toggleTheme);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (getStoredTheme() === 'auto') {
applyTheme();
}
});
}
}
if (document.readyState !== 'loading') {
init();
} else {
document.addEventListener('DOMContentLoaded', init);
}
})();