40 lines
1.7 KiB
JavaScript
40 lines
1.7 KiB
JavaScript
/* Blocking, same-origin bootstrap: keep this before body paint. */
|
|
(function () {
|
|
'use strict';
|
|
var key = 'videoreg-theme';
|
|
var root = document.documentElement;
|
|
var media = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-color-scheme: dark)') : null;
|
|
function valid(value) { return value === 'light' || value === 'dark' || value === 'system'; }
|
|
function read() { try { var value = localStorage.getItem(key); return valid(value) ? value : 'system'; } catch (_) { return 'system'; } }
|
|
var choice = read();
|
|
function apply() {
|
|
var resolved = choice === 'system' ? (media && media.matches ? 'dark' : 'light') : choice;
|
|
root.dataset.theme = resolved;
|
|
root.dataset.themeChoice = choice;
|
|
root.style.colorScheme = resolved;
|
|
window.dispatchEvent(new CustomEvent('videoreg:theme-change'));
|
|
}
|
|
window.videoregTheme = {
|
|
get: function () { return choice; },
|
|
set: function (value) {
|
|
if (!valid(value)) return;
|
|
choice = value;
|
|
try { localStorage.setItem(key, choice); } catch (_) { /* Session choice still works. */ }
|
|
apply();
|
|
}
|
|
};
|
|
function osChanged() { if (choice === 'system') apply(); }
|
|
if (media) {
|
|
if (media.addEventListener) media.addEventListener('change', osChanged);
|
|
else if (media.addListener) media.addListener(osChanged);
|
|
}
|
|
window.addEventListener('storage', function (event) {
|
|
if (event.key !== key && event.key !== null) return;
|
|
// Ignore sessionStorage events; inaccessible storage must not break rendering.
|
|
try { if (event.storageArea && event.storageArea !== localStorage) return; } catch (_) { return; }
|
|
choice = read();
|
|
apply();
|
|
});
|
|
apply();
|
|
}());
|