@@ -2,35 +2,43 @@ import { useState, useEffect } from 'react';
22
33export type Appearance = 'light' | 'dark' | 'system' ;
44
5- export function useAppearance ( ) {
6- const [ appearance , setAppearance ] = useState < Appearance > ( 'system' ) ;
7-
8- const prefersDark = ( ) =>
5+ const prefersDark = ( ) =>
96 window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches ;
107
11- const applyTheme = ( mode : Appearance ) => {
12- const isDark = mode === 'dark' || ( mode === 'system' && prefersDark ( ) ) ;
8+ const applyTheme = ( appearance : Appearance ) => {
9+ const isDark =
10+ appearance === 'dark' ||
11+ ( appearance === 'system' && prefersDark ( ) ) ;
12+
1313 document . documentElement . classList . toggle ( 'dark' , isDark ) ;
14- } ;
14+ }
1515
16- const updateAppearance = ( mode : Appearance ) => {
17- setAppearance ( mode ) ;
18- localStorage . setItem ( 'appearance' , mode ) ;
19- applyTheme ( mode ) ;
20- } ;
16+ export function initializeTheme ( ) {
17+ const savedAppearance = localStorage . getItem ( 'appearance' ) as Appearance || 'system' ;
18+ applyTheme ( savedAppearance ) ;
19+ }
2120
22- useEffect ( ( ) => {
23- const savedAppearance = localStorage . getItem ( 'appearance' ) as Appearance ;
24- updateAppearance ( savedAppearance || 'system' ) ;
21+ export function useAppearance ( ) {
22+ const [ appearance , setAppearance ] = useState < Appearance > ( 'system' ) ;
2523
26- const mediaQuery = window . matchMedia ( '(prefers-color-scheme: dark)' ) ;
27- const handleChange = ( ) => {
28- if ( appearance === 'system' ) applyTheme ( 'system' ) ;
24+ const updateAppearance = ( mode : Appearance ) => {
25+ setAppearance ( mode ) ;
26+ localStorage . setItem ( 'appearance' , mode ) ;
27+ applyTheme ( mode ) ;
2928 } ;
3029
31- mediaQuery . addEventListener ( 'change' , handleChange ) ;
32- return ( ) => mediaQuery . removeEventListener ( 'change' , handleChange ) ;
33- } , [ ] ) ;
30+ useEffect ( ( ) => {
31+ const savedAppearance = localStorage . getItem ( 'appearance' ) as Appearance ;
32+ updateAppearance ( savedAppearance || 'system' ) ;
33+
34+ const mediaQuery = window . matchMedia ( '(prefers-color-scheme: dark)' ) ;
35+ const handleChange = ( ) => {
36+ if ( appearance === 'system' ) applyTheme ( 'system' ) ;
37+ } ;
38+
39+ mediaQuery . addEventListener ( 'change' , handleChange ) ;
40+ return ( ) => mediaQuery . removeEventListener ( 'change' , handleChange ) ;
41+ } , [ ] ) ;
3442
35- return { appearance, updateAppearance } ;
43+ return { appearance, updateAppearance } ;
3644}
0 commit comments