nasg/templates/themeswitcher.js

74 lines
2 KiB
JavaScript
Raw Normal View History

2018-11-15 13:35:47 +00:00
var DEFAULT_THEME = 'dark';
var ALT_THEME = 'light';
2018-11-15 14:06:35 +00:00
var STORAGE_KEY = 'theme';
var colorscheme = document.getElementsByName('colorscheme');
2018-11-15 13:35:47 +00:00
function indicateTheme(mode) {
for(var i = colorscheme.length; i--; ) {
if(colorscheme[i].value == mode) {
colorscheme[i].checked = true;
}
2018-11-15 13:35:47 +00:00
}
}
2018-11-15 14:06:35 +00:00
function applyTheme(mode) {
var st = document.getElementById('css_alt');
if (mode == ALT_THEME) {
st.setAttribute('media', 'all');
}
else {
st.setAttribute('media', 'speech');
}
2018-11-15 13:35:47 +00:00
}
function setTheme(e) {
var mode = e.target.value;
var mql = window.matchMedia('(prefers-color-scheme: ' + ALT_THEME + ')');
/* user wants == mql match => remove storage */
if ((mode == DEFAULT_THEME && !mql.matches) || (mode == ALT_THEME && mql.matches)) {
localStorage.removeItem(STORAGE_KEY);
2018-11-15 13:35:47 +00:00
}
else {
2019-01-15 21:28:58 +00:00
if(confirm("I\'ll need to store your theme of choice in your browser, in a place called localStorage.\n\nAre you OK with this?")) {
localStorage.setItem(STORAGE_KEY, mode);
}
2018-11-15 13:35:47 +00:00
}
autoTheme(mql);
2018-11-15 13:35:47 +00:00
}
function autoTheme(e) {
var mode = DEFAULT_THEME;
2019-01-15 21:28:58 +00:00
try {
var current = localStorage.getItem(STORAGE_KEY);
} catch(e) {
var current = DEFAULT_THEME;
}
if ( current != null) {
mode = current;
}
else if (e.matches) {
mode = ALT_THEME;
}
applyTheme(mode);
indicateTheme(mode);
}
2018-11-15 14:06:35 +00:00
var mql = window.matchMedia('(prefers-color-scheme: ' + ALT_THEME + ')');
autoTheme(mql);
mql.addListener(autoTheme);
2019-01-15 21:28:58 +00:00
var test = 'ping';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
for(var i = colorscheme.length; i--; ) {
colorscheme[i].onclick = setTheme;
}
2019-01-15 21:28:58 +00:00
var themeforms = document.getElementsByClassName(STORAGE_KEY);
for(var i = themeforms.length; i--; ) {
themeforms[i].style.display = 'inline-block';
}
} catch(e) {
console.log('localStorage is not available, manual theme switching is disabled');
}