60 lines
1.8 KiB
JavaScript
60 lines
1.8 KiB
JavaScript
const themeRoot = document.documentElement;
|
|
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)');
|
|
let selectedTheme = 'system';
|
|
let themeButton;
|
|
|
|
try {
|
|
const savedTheme = localStorage.getItem('havox-theme');
|
|
if (savedTheme === 'light' || savedTheme === 'dark') {
|
|
selectedTheme = savedTheme;
|
|
}
|
|
} catch (error) {
|
|
if (error.name !== 'SecurityError') throw error;
|
|
console.warn('Theme preference storage is unavailable.', error);
|
|
}
|
|
|
|
function applyTheme() {
|
|
if (selectedTheme === 'system') {
|
|
delete themeRoot.dataset.theme;
|
|
} else {
|
|
themeRoot.dataset.theme = selectedTheme;
|
|
}
|
|
const dark =
|
|
selectedTheme === 'dark' ||
|
|
(selectedTheme === 'system' && systemTheme.matches);
|
|
document.querySelectorAll('meta[name="theme-color"]').forEach((meta) => {
|
|
meta.content = dark ? '#1e1e2e' : '#eff1f5';
|
|
});
|
|
if (themeButton) {
|
|
const action = `Switch to ${dark ? 'light' : 'dark'} theme`;
|
|
themeButton.dataset.theme = dark ? 'dark' : 'light';
|
|
themeButton.setAttribute('aria-label', action);
|
|
themeButton.title = `${dark ? 'Dark' : 'Light'} theme. ${action}`;
|
|
}
|
|
}
|
|
|
|
// Restore the preference before the stylesheet paints the page.
|
|
applyTheme();
|
|
systemTheme.addEventListener('change', applyTheme);
|
|
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
themeButton = document.querySelector('.theme-toggle');
|
|
applyTheme();
|
|
themeButton.hidden = false;
|
|
themeButton.addEventListener('click', () => {
|
|
selectedTheme = themeButton.dataset.theme === 'dark' ? 'light' : 'dark';
|
|
applyTheme();
|
|
try {
|
|
localStorage.setItem('havox-theme', selectedTheme);
|
|
} catch (error) {
|
|
if (
|
|
error.name !== 'SecurityError' &&
|
|
error.name !== 'QuotaExceededError'
|
|
) {
|
|
throw error;
|
|
}
|
|
console.warn('Theme preference could not be saved.', error);
|
|
}
|
|
});
|
|
});
|