2022-04-20 08:38:24 +00:00
|
|
|
'use strict';
|
2019-08-15 16:29:55 +00:00
|
|
|
var toggle_theme = document.getElementById('toggle_theme');
|
2022-05-06 01:46:59 +00:00
|
|
|
toggle_theme.href = 'javascript:void(0)';
|
2019-05-05 12:34:27 +00:00
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
const STORAGE_KEY_THEME = 'dark_mode';
|
|
|
|
const THEME_DARK = 'dark';
|
|
|
|
const THEME_LIGHT = 'light';
|
|
|
|
const THEME_SYSTEM = '';
|
2019-06-15 15:08:06 +00:00
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
// TODO: theme state controlled by system
|
|
|
|
toggle_theme.addEventListener('click', function () {
|
|
|
|
const isDarkTheme = helpers.storage.get(STORAGE_KEY_THEME) === THEME_DARK;
|
|
|
|
setTheme(isDarkTheme ? THEME_LIGHT : THEME_DARK);
|
2022-05-06 01:46:59 +00:00
|
|
|
helpers.xhr('GET', '/toggle_theme?redirect=false', {}, {});
|
2019-05-05 12:34:27 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
// Ask system about dark theme
|
|
|
|
var systemDarkTheme = matchMedia('(prefers-color-scheme: dark)');
|
|
|
|
systemDarkTheme.addListener(function () {
|
|
|
|
// Ignore system events if theme set manually
|
|
|
|
if (!helpers.storage.get(STORAGE_KEY_THEME))
|
|
|
|
setTheme(THEME_SYSTEM);
|
2019-08-15 16:29:55 +00:00
|
|
|
});
|
|
|
|
|
2020-03-02 15:33:47 +00:00
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
/** @param {THEME_DARK|THEME_LIGHT|THEME_SYSTEM} theme */
|
|
|
|
function setTheme(theme) {
|
|
|
|
if (theme !== THEME_SYSTEM)
|
|
|
|
helpers.storage.set(STORAGE_KEY_THEME, theme);
|
2020-03-02 15:33:47 +00:00
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
if (theme === THEME_DARK || (theme === THEME_SYSTEM && systemDarkTheme.matches)) {
|
2019-05-05 12:34:27 +00:00
|
|
|
toggle_theme.children[0].setAttribute('class', 'icon ion-ios-sunny');
|
2020-11-16 03:19:41 +00:00
|
|
|
document.body.classList.remove('no-theme');
|
|
|
|
document.body.classList.remove('light-theme');
|
|
|
|
document.body.classList.add('dark-theme');
|
2019-05-05 12:34:27 +00:00
|
|
|
} else {
|
|
|
|
toggle_theme.children[0].setAttribute('class', 'icon ion-ios-moon');
|
2020-11-16 03:19:41 +00:00
|
|
|
document.body.classList.remove('no-theme');
|
|
|
|
document.body.classList.remove('dark-theme');
|
|
|
|
document.body.classList.add('light-theme');
|
2019-05-05 12:34:27 +00:00
|
|
|
}
|
|
|
|
}
|
2019-08-15 16:29:55 +00:00
|
|
|
|
2022-05-15 05:38:46 +00:00
|
|
|
// Handles theme change event caused by other tab
|
|
|
|
addEventListener('storage', function (e) {
|
|
|
|
if (e.key === STORAGE_KEY_THEME) setTheme(e.newValue);
|
|
|
|
});
|
|
|
|
|
|
|
|
// Set theme from preferences on page load
|
|
|
|
addEventListener('DOMContentLoaded', function () {
|
|
|
|
const prefTheme = document.getElementById('dark_mode_pref').textContent;
|
|
|
|
setTheme(prefTheme);
|
|
|
|
});
|