TLS-Lens/popup/theme.js

61 lines
1.6 KiB
JavaScript

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/* Theme selection for the popup.
*
* The stored value lives in localStorage, not in browser.storage.local: it
* has to be readable *synchronously* from <head>, before the first paint.
* An async read would let the light layout flash up for anyone whose manual
* choice differs from the system setting.
*
* "auto" writes no attribute at all — the CSS then follows
* prefers-color-scheme on its own.
*/
"use strict";
var THEME = (function() {
const SUPPORTED = ["auto", "light", "dark"];
const STORAGE_KEY = "tlslens.theme";
function normalize(value) {
return SUPPORTED.indexOf(value) !== -1 ? value : "auto";
}
function read() {
try {
return normalize(window.localStorage.getItem(STORAGE_KEY));
} catch (e) {
/* storage unavailable — fall back to following the system */
return "auto";
}
}
function apply(value) {
if (value === "auto") {
document.documentElement.removeAttribute("data-theme");
} else {
document.documentElement.setAttribute("data-theme", value);
}
}
function set(value) {
const normalized = normalize(value);
try {
window.localStorage.setItem(STORAGE_KEY, normalized);
} catch (e) {
console.warn("TLS Lens: Could not persist theme setting:", e);
}
apply(normalized);
return normalized;
}
var setting = read();
apply(setting);
return {
set: set,
get setting() { return setting = read(); }
};
})();