2022-04-20 04:38:24 -04:00
|
|
|
'use strict';
|
2019-08-15 12:29:55 -04:00
|
|
|
var toggle_theme = document.getElementById('toggle_theme');
|
2022-05-05 21:46:59 -04:00
|
|
|
toggle_theme.href = 'javascript:void(0)';
|
2019-05-05 08:34:27 -04:00
|
|
|
|
2022-05-15 01:38:46 -04:00
|
|
|
const STORAGE_KEY_THEME = 'dark_mode';
|
|
|
|
const THEME_DARK = 'dark';
|
|
|
|
const THEME_LIGHT = 'light';
|
2019-06-15 11:08:06 -04:00
|
|
|
|
2022-05-15 01:38:46 -04:00
|
|
|
// TODO: theme state controlled by system
|
|
|
|
toggle_theme.addEventListener('click', function () {
|
|
|
|
const isDarkTheme = helpers.storage.get(STORAGE_KEY_THEME) === THEME_DARK;
|
2022-05-16 06:13:00 -04:00
|
|
|
const newTheme = isDarkTheme ? THEME_LIGHT : THEME_DARK;
|
|
|
|
setTheme(newTheme);
|
|
|
|
helpers.storage.set(STORAGE_KEY_THEME, newTheme);
|
2022-05-05 21:46:59 -04:00
|
|
|
helpers.xhr('GET', '/toggle_theme?redirect=false', {}, {});
|
2019-05-05 08:34:27 -04:00
|
|
|
});
|
|
|
|
|
2022-05-16 06:51:28 -04:00
|
|
|
/** @param {THEME_DARK|THEME_LIGHT} theme */
|
2022-05-15 01:38:46 -04:00
|
|
|
function setTheme(theme) {
|
2022-05-16 06:51:28 -04:00
|
|
|
// By default body element has .no-theme class that uses OS theme via CSS @media rules
|
|
|
|
// It rewrites using hard className below
|
|
|
|
if (theme === THEME_DARK) {
|
|
|
|
toggle_theme.children[0].className = 'icon ion-ios-sunny';
|
|
|
|
document.body.className = 'dark-theme';
|
2022-12-29 14:41:17 -05:00
|
|
|
} else if (theme === THEME_LIGHT) {
|
2022-05-16 06:51:28 -04:00
|
|
|
toggle_theme.children[0].className = 'icon ion-ios-moon';
|
|
|
|
document.body.className = 'light-theme';
|
2022-12-29 14:41:17 -05:00
|
|
|
} else {
|
|
|
|
document.body.className = 'no-theme';
|
2019-05-05 08:34:27 -04:00
|
|
|
}
|
|
|
|
}
|
2019-08-15 12:29:55 -04:00
|
|
|
|
2022-05-15 01:38:46 -04:00
|
|
|
// Handles theme change event caused by other tab
|
|
|
|
addEventListener('storage', function (e) {
|
2022-05-16 06:13:00 -04:00
|
|
|
if (e.key === STORAGE_KEY_THEME)
|
|
|
|
setTheme(helpers.storage.get(STORAGE_KEY_THEME));
|
2022-05-15 01:38:46 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
// Set theme from preferences on page load
|
|
|
|
addEventListener('DOMContentLoaded', function () {
|
|
|
|
const prefTheme = document.getElementById('dark_mode_pref').textContent;
|
2022-05-16 06:51:28 -04:00
|
|
|
if (prefTheme) {
|
|
|
|
setTheme(prefTheme);
|
|
|
|
helpers.storage.set(STORAGE_KEY_THEME, prefTheme);
|
|
|
|
}
|
2022-05-15 01:38:46 -04:00
|
|
|
});
|