darkmode-darkreader.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const DARK = "dark";
  2. const LIGHT = "light";
  3. const SYSTEM = "system";
  4. const COLOR_THEME = "color-theme";
  5. const DARK_OPTIONS = {
  6. brightness: 100,
  7. contrast: 100,
  8. sepia: 0
  9. };
  10. const SVG_INVERT = {invert: ['img[src$=".svg"]']};
  11. const NAVBAR_ICON_ID = "navbar-theme-icon-svg";
  12. const DARK_ICON = "/icons/moon-svgrepo-com.svg";
  13. const LIGHT_ICON = "/icons/sun-svgrepo-com.svg";
  14. const SYSTEM_ICON = "/icons/computer-svgrepo-com.svg";
  15. function enableDarkTheme() {
  16. localStorage.setItem(COLOR_THEME, DARK);
  17. DarkReader.enable(DARK_OPTIONS, SVG_INVERT);
  18. document.getElementById(NAVBAR_ICON_ID).src = DARK_ICON;
  19. }
  20. function enableLightTheme() {
  21. localStorage.setItem(COLOR_THEME, LIGHT);
  22. DarkReader.disable();
  23. document.getElementById(NAVBAR_ICON_ID).src = LIGHT_ICON;
  24. }
  25. function useSystemTheme() {
  26. localStorage.setItem(COLOR_THEME, SYSTEM);
  27. DarkReader.auto(DARK_OPTIONS, SVG_INVERT);
  28. document.getElementById(NAVBAR_ICON_ID).src = SYSTEM_ICON;
  29. }
  30. function initializeColorTheme() {
  31. // We're using the themeInitialization attributes as a 'hack' for setting up
  32. // the default color scheme because we don't want to complicate this further
  33. // by creating custom javascript output in Hugo.
  34. let themeInitialization = document.getElementById("theme-initialization");
  35. let defaultColorScheme = themeInitialization.getAttribute('default-theme');
  36. // If the user has already selected a preferred theme then use that instead
  37. // of the default theme. Also, the default theme gets loaded to localStorage
  38. // on the first visit.
  39. let colorTheme = localStorage.getItem(COLOR_THEME);
  40. if (colorTheme == null || colorTheme.length == 0) {
  41. colorTheme = defaultColorScheme;
  42. }
  43. // Enable the color theme
  44. if (colorTheme == DARK) {
  45. enableDarkTheme();
  46. } else if (colorTheme == SYSTEM) {
  47. useSystemTheme();
  48. } else {
  49. // We use light theme for the two conditions below.
  50. // 1. the selected theme is light
  51. // 2. no default theme is found - fall back to original behavior
  52. enableLightTheme();
  53. }
  54. }
  55. initializeColorTheme()