-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: replace current dark mode detector logic by new component
- Loading branch information
1 parent
7b6b577
commit 09ddb81
Showing
2 changed files
with
58 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
--- | ||
--- | ||
|
||
<!-- Block until theme class is set --> | ||
<script is:inline> | ||
/** | ||
* Check if dark theme is preferred or set by user | ||
*/ | ||
const isDarkTheme = () => { | ||
if (typeof localStorage !== "undefined" && localStorage.getItem("darkMode")) { | ||
return localStorage.getItem("darkMode"); | ||
} | ||
if (window.matchMedia("(prefers-color-scheme: dark)").matches) { | ||
return "true"; | ||
} | ||
return "false"; | ||
}; | ||
|
||
/** | ||
* Set dark theme class | ||
*/ | ||
const setDarkClass = () => { | ||
const htmlClasses = document.documentElement.classList; | ||
|
||
if (isDarkTheme() === "false") { | ||
htmlClasses.remove("dark"); | ||
} else { | ||
htmlClasses.add("dark"); | ||
} | ||
}; | ||
|
||
/** | ||
* Update meta theme color. | ||
* | ||
* @return {void} | ||
*/ | ||
const setThemeColor = () => { | ||
const metaThemeColor = document.querySelector("meta[name=theme-color]"); | ||
const themeColor = isDarkTheme() === "true" ? "#2b333b" : "#fad0b0"; | ||
metaThemeColor.setAttribute("content", themeColor); | ||
}; | ||
|
||
/** | ||
* Needs to be set on load because theme-color meta tag comes later in the loading sequence | ||
*/ | ||
window.onload = function () { | ||
setThemeColor(); | ||
}; | ||
|
||
setDarkClass(); | ||
|
||
localStorage.setItem("darkMode", isDarkTheme()); | ||
|
||
document.addEventListener("astro:after-swap", setDarkClass); | ||
</script> |