mirror of
https://github.com/ChenQihan666/MyBlog-Next.git
synced 2026-08-14 11:29:33 +08:00
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:
@@ -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 />
|
||||
|
||||
Reference in New Issue
Block a user