nasg/templates/themeswitcher.js

59 lines
1.4 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
2018-11-15 14:06:35 +00:00
function setTheme(e) {
var mode = e.target.value;
if (mode == 'auto') {
localStorage.removeItem(STORAGE_KEY);
2018-11-15 13:35:47 +00:00
}
else {
2018-11-15 14:06:35 +00:00
localStorage.setItem(STORAGE_KEY, mode);
2018-11-15 13:35:47 +00:00
}
2018-11-15 14:06:35 +00:00
applyTheme(mode);
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');
}
for(var i = colorscheme.length; i--; ) {
if(colorscheme[i].value == mode) {
colorscheme[i].checked = true;
}
}
2018-11-15 13:35:47 +00:00
}
function mqlTheme(e) {
2018-11-15 14:06:35 +00:00
if (localStorage.getItem(STORAGE_KEY) != null) {
return false;
}
2018-11-15 13:35:47 +00:00
if (e.matches) {
2018-11-15 14:06:35 +00:00
applyTheme(ALT_THEME);
2018-11-15 13:35:47 +00:00
}
else {
2018-11-15 14:06:35 +00:00
applyTheme(DEFAULT_THEME);
2018-11-15 13:35:47 +00:00
}
}
2018-11-15 14:06:35 +00:00
var current = localStorage.getItem(STORAGE_KEY);
if (current == null) { current = 'auto'; }
applyTheme(current);
var mql = window.matchMedia('(prefers-color-scheme: ' + ALT_THEME + ')');
mql.addListener(mqlTheme);
for(var i = colorscheme.length; i--; ) {
colorscheme[i].onclick = setTheme;
2018-11-15 13:35:47 +00:00
}
2018-11-15 14:06:35 +00:00
var themeforms = document.getElementsByClassName(STORAGE_KEY);
for(var i = themeforms.length; i--; ) {
themeforms[i].style.display = 'inline-block';
2018-11-15 13:35:47 +00:00
}