quranic-universal-aligner / src /ui /static /theme-toggle.js
hetchyy's picture
deploy
35d8fb6 verified
Raw History Blame Contribute Delete
2.41 kB
// Light/dark switch for the header button.
//
// Gradio picks the theme once at mount — from `?__theme=` or the OS preference
// — and puts `dark` on <body>, then re-applies it whenever the OS preference
// changes. This keeps the visitor's own choice on top of that: stored across
// reloads, and re-asserted whenever Gradio moves the class underneath it.
(function () {
var KEY = 'qa-theme';
var BUTTON_ID = 'theme-toggle';
function stored() {
try { return localStorage.getItem(KEY); } catch (e) { return null; }
}
function remember(theme) {
try { localStorage.setItem(KEY, theme); } catch (e) { /* private mode */ }
}
function isDark() { return document.body.classList.contains('dark'); }
function paintButton() {
var btn = document.getElementById(BUTTON_ID);
if (!btn) return;
var label = isDark() ? 'Switch to light theme' : 'Switch to dark theme';
btn.textContent = isDark() ? '☀️' : '🌙';
btn.title = label;
btn.setAttribute('aria-label', label);
}
function apply(theme) {
document.body.classList.toggle('dark', theme === 'dark');
paintButton();
}
// Only writes when the class has drifted from the stored choice, so the
// MutationObserver below cannot loop on its own change.
function enforce() {
var want = stored();
if (want && (want === 'dark') !== isDark()) apply(want);
else paintButton();
}
document.addEventListener('click', function (ev) {
if (!ev.target.closest || !ev.target.closest('#' + BUTTON_ID)) return;
var theme = isDark() ? 'light' : 'dark';
remember(theme);
apply(theme);
});
function start() {
enforce();
new MutationObserver(enforce).observe(document.body, {
attributes: true,
attributeFilter: ['class'],
});
// Gradio mounts the header after this script parses, so the icon has
// no button to paint yet. Watch for it, then stop.
var waiting = setInterval(function () {
if (!document.getElementById(BUTTON_ID)) return;
clearInterval(waiting);
enforce();
}, 100);
}
if (document.body) start();
else document.addEventListener('DOMContentLoaded', start);
})();