themes.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0 */
  2. 'use strict';
  3. var toggle_theme = document.getElementById('toggle_theme');
  4. toggle_theme.href = 'javascript:void(0)';
  5. const STORAGE_KEY_THEME = 'dark_mode';
  6. const THEME_DARK = 'dark';
  7. const THEME_LIGHT = 'light';
  8. // TODO: theme state controlled by system
  9. toggle_theme.addEventListener('click', function () {
  10. const isDarkTheme = helpers.storage.get(STORAGE_KEY_THEME) === THEME_DARK;
  11. const newTheme = isDarkTheme ? THEME_LIGHT : THEME_DARK;
  12. setTheme(newTheme);
  13. helpers.storage.set(STORAGE_KEY_THEME, newTheme);
  14. helpers.xhr('GET', '/toggle_theme?redirect=false', {}, {});
  15. });
  16. /** @param {THEME_DARK|THEME_LIGHT} theme */
  17. function setTheme(theme) {
  18. // By default body element has .no-theme class that uses OS theme via CSS @media rules
  19. // It rewrites using hard className below
  20. if (theme === THEME_DARK) {
  21. toggle_theme.children[0].className = 'icon ion-ios-sunny';
  22. document.body.className = 'dark-theme';
  23. } else {
  24. toggle_theme.children[0].className = 'icon ion-ios-moon';
  25. document.body.className = 'light-theme';
  26. }
  27. }
  28. // Handles theme change event caused by other tab
  29. addEventListener('storage', function (e) {
  30. if (e.key === STORAGE_KEY_THEME)
  31. setTheme(helpers.storage.get(STORAGE_KEY_THEME));
  32. });
  33. // Set theme from preferences on page load
  34. addEventListener('DOMContentLoaded', function () {
  35. const prefTheme = document.getElementById('dark_mode_pref').textContent;
  36. if (prefTheme) {
  37. setTheme(prefTheme);
  38. helpers.storage.set(STORAGE_KEY_THEME, prefTheme);
  39. }
  40. });
  41. /* @license-end */