load-theme.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. (function () {
  2. function getThemeMode() {
  3. return parseInt(localStorage.getItem('dark_mode') || 2);
  4. }
  5. function canChangeTheme() {
  6. // If var is set, then user is allowed to change the theme variation.
  7. return Boolean(window.wcDarkLightEnabled);
  8. }
  9. function initThemeVariation() {
  10. if (!canChangeTheme()) {
  11. return;
  12. }
  13. let currentThemeMode = getThemeMode();
  14. let isDarkTheme;
  15. switch (currentThemeMode) {
  16. case 0:
  17. isDarkTheme = false;
  18. break;
  19. case 1:
  20. isDarkTheme = true;
  21. break;
  22. default:
  23. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  24. // The visitor prefers dark themes and switching to the dark variation is allowed by admin.
  25. isDarkTheme = true;
  26. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  27. // The visitor prefers light themes and switching to the dark variation is allowed by admin.
  28. isDarkTheme = false;
  29. } else {
  30. // Use the site's default theme variation based on `light` in the theme file.
  31. isDarkTheme = isSiteThemeDark;
  32. }
  33. break;
  34. }
  35. if (isDarkTheme) {
  36. document.body.classList.add("dark");
  37. } else {
  38. document.body.classList.remove("dark");
  39. }
  40. }
  41. // Initialize theme variation.
  42. initThemeVariation();
  43. })();