@@ -8,6 +8,11 @@ const CLASSLIST_UPDATE_TIMEOUT = 10;
88
99type ThemeName = 'light' | 'dark' ;
1010
11+ const getCurrentTheme = ( ) : ThemeName => {
12+ const { matches } = window . matchMedia ( '(prefers-color-scheme: dark)' ) ;
13+ return matches ? 'dark' : 'light' ;
14+ } ;
15+
1116type ThemeContextProps = {
1217 name : ThemeName ;
1318 update : ( newTheme : ThemeName ) => void ;
@@ -20,7 +25,7 @@ const ThemeContext = createContext<ThemeContextProps>({
2025
2126export const ThemeProvider = ( { children } : { children : ReactNode } ) => {
2227 const [ cookieValue , setCookieValue ] = useCookie ( 'theme' ) ;
23- const [ name , setName ] = useState < ThemeName > ( cookieValue === 'dark' ? 'dark' : 'light' ) ;
28+ const [ name , setName ] = useState < ThemeName > ( ( cookieValue as ThemeName ) || getCurrentTheme ( ) ) ;
2429
2530 const updateClassList = useCallback ( async ( newTheme : ThemeName ) => {
2631 const htmlElm = document . querySelector ( 'html' ) ;
@@ -30,9 +35,11 @@ export const ThemeProvider = ({ children }: { children: ReactNode }) => {
3035 await wait ( CLASSLIST_UPDATE_TIMEOUT ) ;
3136
3237 if ( newTheme === 'dark' ) {
33- htmlElm ?. classList . replace ( 'light-theme' , 'dark-theme' ) ;
38+ htmlElm ?. classList . remove ( 'light-theme' ) ;
39+ htmlElm ?. classList . add ( 'dark-theme' ) ;
3440 } else {
35- htmlElm ?. classList . replace ( 'dark-theme' , 'light-theme' ) ;
41+ htmlElm ?. classList . remove ( 'dark-theme' ) ;
42+ htmlElm ?. classList . add ( 'light-theme' ) ;
3643 }
3744
3845 await wait ( CLASSLIST_UPDATE_TIMEOUT ) ;
0 commit comments