Skip to content

Commit

Permalink
Fix dark mode toggle and persist setting
Browse files Browse the repository at this point in the history
Signed-off-by: Zack Cerza <[email protected]>
  • Loading branch information
zmc committed Dec 12, 2023
1 parent bfae9ae commit b307b05
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
11 changes: 6 additions & 5 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Pulpito" />
<link rel="apple-touch-icon" href="/favicon.ico" />
<link rel="manifest" href="/manifest.json" />
Expand All @@ -27,10 +26,12 @@
<div id="root"></div>
<script>
try {
let colorScheme = "light";
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
colorScheme = "dark";
};
let colorScheme = localStorage.getItem("theme");
const systemDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (!colorScheme) {
colorScheme = systemDarkMode ? "dark" : "light";
}
if (!!colorScheme) localStorage.setItem("theme", colorScheme);
document.getElementsByTagName("body")[0].setAttribute("color-scheme", colorScheme);
} catch (e) {
console.error(e);
Expand Down
8 changes: 3 additions & 5 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,12 @@ function useDarkMode(): [boolean, Function] {
const systemDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
const [state, setState] = React.useState({
system: systemDarkMode,
user: localStorage.getItem("theme") === "dark",
} as DarkModeState);

function setDarkMode(value: boolean) {
const newState = { ...state, user: value };
if (value !== state.user) {
setState(newState);
}
setState(newState);
localStorage.setItem("theme", value? "dark" : "light");
setState({ ...state, user: value });
}
const darkMode = state.user === undefined ? systemDarkMode : state.user;
return [darkMode, setDarkMode];
Expand Down

0 comments on commit b307b05

Please sign in to comment.