astro-nano icon indicating copy to clipboard operation
astro-nano copied to clipboard

Fix theme switching failure caused because missing values

Open scopewu opened this issue 5 months ago • 0 comments

The current code is able to switch themes according to the system state. The problem is that when the site is loaded and the system state changes, the theme switching failure caused because missing values. There are two fixes: A. Determine the missing values when the state changes:

window.matchMedia("(prefers-color-scheme: dark)")
  .addEventListener("change", event => {
    if (localStorage.theme === "system" || !localStorage.theme) {
      toggleTheme(event.matches);
    }
  }
);

B. Set missing values when loading:

function preloadTheme() {
  const userTheme = localStorage.theme;

  if (!userTheme) {
    localStorage.setItem("theme", "system");
  }

  if (userTheme === "light" || userTheme === "dark") {
    toggleTheme(userTheme === "dark");
  } else {
    toggleTheme(window.matchMedia("(prefers-color-scheme: dark)").matches);
  }
}

Here I have chosen the first way(A).

Thanks for your work.

scopewu avatar Sep 14 '24 12:09 scopewu