Files
MangaBom/dist/theme.js
2026-11-02 04:08:02 +03:00

39 lines
2.1 KiB
JavaScript

(() => {
const key = 'mangabom.theme';
let saved;
try { saved = JSON.parse(localStorage.getItem(key)); } catch {}
const system = matchMedia('(prefers-color-scheme: dark)');
let theme = ['light', 'dark'].includes(saved) ? saved : (system.matches ? 'dark' : 'light');
function apply() {
document.documentElement.dataset.theme = theme;
document.querySelectorAll('[data-theme-toggle]').forEach(button => {
button.textContent = theme === 'dark' ? '☀ Светлая' : '☾ Тёмная';
button.setAttribute('aria-label', theme === 'dark' ? 'Включить светлую тему' : 'Включить тёмную тему');
button.setAttribute('aria-pressed', String(theme === 'dark'));
button.dataset.themeIcon = theme === 'dark' ? '☀' : '☾';
button.title = theme === 'dark' ? 'Включить светлую тему' : 'Включить тёмную тему';
});
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', theme === 'dark' ? '#16181e' : '#fcf5ed');
}
apply();
document.addEventListener('DOMContentLoaded', () => {
if (!document.querySelector('[data-theme-toggle]')) {
const button = document.createElement('button');
button.type = 'button'; button.className = 'site-theme-toggle'; button.dataset.themeToggle = '';
document.querySelector('.footer-bottom, .reader-footer')?.append(button);
}
apply();
});
document.addEventListener('click', event => {
if (!event.target.closest('[data-theme-toggle]')) return;
theme = theme === 'dark' ? 'light' : 'dark'; saved = theme;
try { localStorage.setItem(key, JSON.stringify(theme)); } catch {}
apply();
});
system.addEventListener('change', () => { if (!saved) { theme = system.matches ? 'dark' : 'light'; apply(); } });
window.addEventListener('storage', event => {
if (event.key !== key && event.key !== null) return;
try { saved = JSON.parse(localStorage.getItem(key)); } catch { saved = null; }
theme = ['light', 'dark'].includes(saved) ? saved : (system.matches ? 'dark' : 'light'); apply();
});
})();