Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix theme switching failure caused because missing values #11

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

scopewu
Copy link

@scopewu scopewu commented Sep 14, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant