themes.js 1.6 KB

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