Skip to content

Commit feb4a41

Browse files
authored
fix: correct default dark-mode preference (#1069)
Thanks for shipping Dark mode for JSR! (#1055) 🎉 Though I noticed that the media `prefers-color-scheme` detection is not working correctly. During loading the correct theme will be applied (via `_app.tsx` script), but when Preact renders it will override with incorrect theme. This is because the `isDarkStored ?? isDarkPreference` expression basically always returning `isDarkStored` (`isDarkStored` is `boolean`, not `boolean | undefined | null`). This PR attempts to fix the issue by ensuring the [logic is the same as for `_app.tsx`](https://github.com/jsr-io/jsr/blob/main/frontend/routes/_app.tsx#L74-L81) for when Dark mode should be applied, which avoids dark -> light flashing for when dark mode is preferred without any stored value. ## Current behavior This is how it looks for me (3G throttled) when I have no `darkMode` localeStorage item. https://github.com/user-attachments/assets/56ff105f-5a39-46ff-bf6c-40f518366ed2
1 parent 2c71e6b commit feb4a41

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

frontend/islands/DarkModeToggle.tsx

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@ export default function DarkModeToggle() {
66
const [isDark, setIsDark] = useState(false);
77

88
useEffect(() => {
9-
const isDarkStored = localStorage.getItem("darkMode") === "true";
9+
const isDarkStored = localStorage.getItem("darkMode");
1010
const isDarkPreference =
1111
globalThis.matchMedia("(prefers-color-scheme: dark)").matches;
12-
const initialDarkMode = isDarkStored ?? isDarkPreference;
12+
const initialDarkMode = isDarkStored === "true" ||
13+
isDarkStored === null && isDarkPreference;
1314

1415
setIsDark(initialDarkMode);
1516
updateTheme(initialDarkMode);

0 commit comments

Comments
 (0)