2022-04-20 01:38:24 -07:00
|
|
|
'use strict';
|
2019-08-15 09:29:55 -07:00
|
|
|
var toggle_theme = document.getElementById('toggle_theme');
|
2022-05-05 18:46:59 -07:00
|
|
|
toggle_theme.href = 'javascript:void(0)';
|
2019-05-05 05:34:27 -07:00
|
|
|
|
2022-05-14 22:38:46 -07:00
|
|
|
const STORAGE_KEY_THEME = 'dark_mode';
|
|
|
|
const THEME_DARK = 'dark';
|
|
|
|
const THEME_LIGHT = 'light';
|
|
|
|
const THEME_SYSTEM = '';
|
2019-06-15 08:08:06 -07:00
|
|
|
|
2022-05-14 22:38:46 -07: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-05 18:46:59 -07:00
|
|
|
helpers.xhr('GET', '/toggle_theme?redirect=false', {}, {});
|
2019-05-05 05:34:27 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
|
2022-05-14 22:38:46 -07: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 09:29:55 -07:00
|
|
|
});
|
|
|
|
|
2020-03-02 07:33:47 -08:00
|
|
|
|
2022-05-14 22:38:46 -07: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 07:33:47 -08:00
|
|
|
|
2022-05-14 22:38:46 -07:00
|
|
|
if (theme === THEME_DARK || (theme === THEME_SYSTEM && systemDarkTheme.matches)) {
|
2019-05-05 05:34:27 -07:00
|
|
|
toggle_theme.children[0].setAttribute('class', 'icon ion-ios-sunny');
|
2020-11-15 19:19:41 -08:00
|
|
|
document.body.classList.remove('no-theme');
|
|
|
|
document.body.classList.remove('light-theme');
|
|
|
|
document.body.classList.add('dark-theme');
|
2019-05-05 05:34:27 -07:00
|
|
|
} else {
|
|
|
|
toggle_theme.children[0].setAttribute('class', 'icon ion-ios-moon');
|
2020-11-15 19:19:41 -08:00
|
|
|
document.body.classList.remove('no-theme');
|
|
|
|
document.body.classList.remove('dark-theme');
|
|
|
|
document.body.classList.add('light-theme');
|
2019-05-05 05:34:27 -07:00
|
|
|
}
|
|
|
|
}
|
2019-08-15 09:29:55 -07:00
|
|
|
|
2022-05-14 22:38:46 -07: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);
|
|
|
|
});
|