refactor: update toggle theme function for better structure and a11y

Move theme switch js codes in Layout.astro file to external js file (toggle-theme.js). Update
.prettierignore to exclude the new toggle-theme.js file.  Update base.css for new data-theme
attribute.
This commit is contained in:
satnaing
2022-11-26 23:43:27 +06:30
parent 5a67afc6b2
commit 0eeed8e870
4 changed files with 61 additions and 44 deletions
+1 -39
View File
@@ -61,45 +61,7 @@ const socialImageURL = new URL(
onload="this.onload=null;this.rel='stylesheet'"
/>
<script is:inline>
const primaryColorScheme = "none"; // "light" | "dark" | "none"
const darkModeMediaQuery = window.matchMedia(
"(prefers-color-scheme: dark)"
).matches;
// Get theme data from local storage
const currentTheme = localStorage.getItem("theme");
let theme;
// Set theme to 'theme-dark' if currentTheme is 'dark'
if (currentTheme) {
theme = currentTheme === "dark" ? "theme-dark" : "";
} else {
// If primary color scheme is dark
// or primary color scheme is not set and prefers-color-scheme is dark
// choose dark mode
if (
primaryColorScheme === "dark" ||
(primaryColorScheme === "none" && darkModeMediaQuery)
) {
theme = "theme-dark";
}
// If primary color scheme is light
// choose light mode
else if (primaryColorScheme === "light") {
theme = "";
}
// fallback to prefers-color-scheme
else {
theme = darkModeMediaQuery ? "theme-dark" : "";
}
}
// Put dark class on html tag to enable dark mode
document.querySelector("html").className = theme;
</script>
<script is:inline src="/toggle-theme.js"></script>
</head>
<body>
<slot />