@@ -3,23 +3,26 @@ import {
3
3
createSignal ,
4
4
event$ ,
5
5
isBrowser ,
6
+ isServer ,
6
7
useStyles$ ,
7
8
type Signal ,
8
9
} from '@qwik.dev/core' ;
9
10
import { themeStorageKey } from '../router-head/theme-script' ;
10
11
import { SunAndMoon } from './sun-and-moon' ;
11
12
import themeToggle from './theme-toggle.css?inline' ;
12
13
13
- type ThemeName = 'dark' | 'light' | undefined ;
14
+ type ThemeName = 'dark' | 'light' | 'auto' ;
14
15
15
16
export const getTheme = ( ) : ThemeName => {
17
+ if ( isServer ) {
18
+ return 'auto' ;
19
+ }
16
20
let theme ;
17
- const matchMedia = window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches ? 'dark' : 'light' ;
18
21
try {
19
22
theme = localStorage . getItem ( themeStorageKey ) ;
20
- return ( theme as ThemeName ) || matchMedia ;
23
+ return ( theme as ThemeName ) || 'auto' ;
21
24
} catch {
22
- return matchMedia ;
25
+ return 'auto' ;
23
26
}
24
27
} ;
25
28
@@ -38,13 +41,12 @@ export const getThemeSignal = () => {
38
41
} ;
39
42
40
43
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' ) ;
44
46
} else {
45
- localStorage . setItem ( themeStorageKey , theme ) ;
47
+ document . firstElementChild ?. setAttribute ( 'data-theme' , theme ! ) ;
46
48
}
47
- document . firstElementChild ?. setAttribute ( 'data-theme' , theme ! ) ;
49
+ localStorage . setItem ( themeStorageKey , theme ) ;
48
50
if ( currentThemeSignal ) {
49
51
currentThemeSignal . value = theme ;
50
52
}
0 commit comments