59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
(function() {
|
|
const themeToggle = document.getElementById('theme-toggle');
|
|
const themeIcon = document.getElementById('theme-icon');
|
|
|
|
|
|
function storeTheme(theme) {
|
|
localStorage.setItem('picoPreferredColorScheme', theme);
|
|
}
|
|
|
|
function getStoredTheme() {
|
|
return localStorage.getItem('picoPreferredColorScheme');
|
|
}
|
|
|
|
function getCurrentTheme() {
|
|
return document.documentElement.getAttribute('data-theme') ||
|
|
(window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
|
}
|
|
|
|
function applyTheme(currentTheme) {
|
|
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
|
document.documentElement.setAttribute('data-theme', newTheme);
|
|
if (newTheme === 'dark') {
|
|
themeIcon.textContent = '☀️';
|
|
themeToggle.setAttribute('aria-pressed', 'true');
|
|
} else {
|
|
themeIcon.textContent = '🌙';
|
|
themeToggle.setAttribute('aria-pressed', 'false');
|
|
}
|
|
}
|
|
|
|
themeToggle.addEventListener('click', () => {
|
|
const currentTheme = getCurrentTheme();
|
|
|
|
applyTheme(currentTheme);
|
|
storeTheme(currentTheme);
|
|
});
|
|
|
|
function init() {
|
|
let storedTheme = getStoredTheme() || getCurrentTheme();
|
|
|
|
applyTheme(storedTheme);
|
|
|
|
themeToggle.addEventListener('click', toggleTheme);
|
|
|
|
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
|
// Only apply theme if user hasn't made an explicit choice
|
|
const storedTheme = getStoredTheme();
|
|
if (storedTheme === 'auto') {
|
|
applyTheme();
|
|
}
|
|
})
|
|
}
|
|
|
|
if (document.readyState !== 'loading') {
|
|
init();
|
|
} else {
|
|
document.addEventListener('DOMContentLoaded', init);
|
|
}
|
|
})(); |