Skip to content

Commit 9b2bf13

Browse files
committed
docs: improve theme toggle 🍓
1 parent 575d379 commit 9b2bf13

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

packages/docs/src/components/theme-toggle/theme-toggle.tsx

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,26 @@ import {
33
createSignal,
44
event$,
55
isBrowser,
6+
isServer,
67
useStyles$,
78
type Signal,
89
} from '@qwik.dev/core';
910
import { themeStorageKey } from '../router-head/theme-script';
1011
import { SunAndMoon } from './sun-and-moon';
1112
import themeToggle from './theme-toggle.css?inline';
1213

13-
type ThemeName = 'dark' | 'light' | undefined;
14+
type ThemeName = 'dark' | 'light' | 'auto';
1415

1516
export const getTheme = (): ThemeName => {
17+
if (isServer) {
18+
return 'auto';
19+
}
1620
let theme;
17-
const matchMedia = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
1821
try {
1922
theme = localStorage.getItem(themeStorageKey);
20-
return (theme as ThemeName) || matchMedia;
23+
return (theme as ThemeName) || 'auto';
2124
} catch {
22-
return matchMedia;
25+
return 'auto';
2326
}
2427
};
2528

@@ -38,13 +41,12 @@ export const getThemeSignal = () => {
3841
};
3942

4043
export const setTheme = (theme: ThemeName) => {
41-
if (!theme) {
42-
localStorage.removeItem(themeStorageKey);
43-
theme = getTheme();
44+
if (theme === 'auto') {
45+
document.firstElementChild?.removeAttribute('data-theme');
4446
} else {
45-
localStorage.setItem(themeStorageKey, theme);
47+
document.firstElementChild?.setAttribute('data-theme', theme!);
4648
}
47-
document.firstElementChild?.setAttribute('data-theme', theme!);
49+
localStorage.setItem(themeStorageKey, theme);
4850
if (currentThemeSignal) {
4951
currentThemeSignal.value = theme;
5052
}

0 commit comments

Comments
 (0)