53 lines
1.7 KiB
JavaScript
53 lines
1.7 KiB
JavaScript
(function () {
|
|
const KEY = 'whatidoTheme';
|
|
const MODES = ['auto', 'day', 'night'];
|
|
const LABELS = { auto: 'Авто', day: 'День', night: 'Ночь' };
|
|
const ICONS = { auto: 'monitor', day: 'sun', night: 'moon' };
|
|
const media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
|
|
let link = document.getElementById('themeCss');
|
|
|
|
function get() {
|
|
let value = null;
|
|
try { value = localStorage.getItem(KEY); } catch {}
|
|
return MODES.includes(value) ? value : 'auto';
|
|
}
|
|
|
|
function isDark(mode) {
|
|
return mode === 'night' || (mode === 'auto' && !!(media && media.matches));
|
|
}
|
|
|
|
function apply() {
|
|
const mode = get();
|
|
const dark = isDark(mode);
|
|
document.documentElement.classList.toggle('midnight-neon', dark);
|
|
if (!link) {
|
|
link = document.createElement('link');
|
|
link.id = 'themeCss';
|
|
link.rel = 'stylesheet';
|
|
link.href = '/admin-dark.css';
|
|
document.head.appendChild(link);
|
|
}
|
|
link.disabled = !dark;
|
|
document.dispatchEvent(new CustomEvent('whatido:themechange', { detail: { mode: mode, dark: dark } }));
|
|
return mode;
|
|
}
|
|
|
|
function set(mode) {
|
|
if (!MODES.includes(mode)) return get();
|
|
try { localStorage.setItem(KEY, mode); } catch {}
|
|
return apply();
|
|
}
|
|
|
|
function next() {
|
|
return set(MODES[(MODES.indexOf(get()) + 1) % MODES.length]);
|
|
}
|
|
|
|
window.WhatIDoTheme = { get: get, set: set, next: next, apply: apply, modes: MODES, labels: LABELS, icons: ICONS };
|
|
apply();
|
|
if (media) {
|
|
const onChange = () => { if (get() === 'auto') apply(); };
|
|
if (media.addEventListener) media.addEventListener('change', onChange);
|
|
else if (media.addListener) media.addListener(onChange);
|
|
}
|
|
})();
|