HuggingPolls / static /theme.js
Banaxi-Tech's picture Hoglet-33's picture
Revamp (#1)
c8876d8
Raw History Blame Contribute Delete
1.61 kB
// Run before the stylesheet so a saved theme is applied before the first paint.
(() => {
const key = 'huggingpolls-theme';
const system = window.matchMedia('(prefers-color-scheme: dark)');
const valid = value => ['system', 'light', 'dark'].includes(value);
let preference = 'system';
try {
const saved = localStorage.getItem(key);
if (valid(saved)) preference = saved;
} catch { /* The system theme still works when browser storage is blocked. */ }
function apply() {
const theme = preference === 'system' ? (system.matches ? 'dark' : 'light') : preference;
document.documentElement.dataset.theme = theme;
document.querySelector('meta[name="theme-color"]').content = theme === 'dark' ? '#11151d' : '#ffffff';
const select = document.querySelector('#theme-select');
if (select) select.value = preference;
const status = document.querySelector('#theme-status');
if (status) status.textContent = `Using ${theme} appearance${preference === 'system' ? ' to match your system' : ''}.`;
}
apply();
system.addEventListener('change', apply);
window.addEventListener('storage', event => {
if (event.key === key || event.key === null) {
preference = valid(event.newValue) ? event.newValue : 'system';
apply();
}
});
document.addEventListener('DOMContentLoaded', () => {
apply();
document.querySelector('#theme-select').addEventListener('change', event => {
preference = event.target.value;
try { localStorage.setItem(key, preference); } catch {}
apply();
});
});
})();