1+ import { setCookie } from '@/dashboard/lib/cookie' ;
12import { onMounted , ref } from 'vue' ;
23
34type Appearance = 'light' | 'dark' | 'system' ;
45
5- const getCurrentTheme = ( ) : Appearance => {
6- return document . documentElement . classList . contains ( 'dark' ) ? 'dark' : 'light' ;
7- } ;
8-
96export function updateTheme ( value : Appearance ) {
10- if ( typeof window === 'undefined' ) {
11- return ;
12- }
13-
14- const systemTheme = mediaQuery ( ) ?. matches ? 'dark' : 'light' ;
7+ const systemTheme = mediaQuery ( ) . matches ? 'dark' : 'light' ;
158 const desiredTheme = value === 'system' ? systemTheme : value ;
169 const currentTheme = getCurrentTheme ( ) ;
1710
@@ -30,19 +23,15 @@ export function updateTheme(value: Appearance) {
3023 }
3124}
3225
33- const mediaQuery = ( ) => {
34- if ( typeof window === 'undefined' ) {
35- return null ;
36- }
26+ const getCurrentTheme = ( ) : Appearance => {
27+ return document . documentElement . classList . contains ( 'dark' ) ? 'dark' : 'light' ;
28+ } ;
3729
30+ const mediaQuery = ( ) => {
3831 return window . matchMedia ( '(prefers-color-scheme: dark)' ) ;
3932} ;
4033
4134const getStoredAppearance = ( ) => {
42- if ( typeof window === 'undefined' ) {
43- return null ;
44- }
45-
4635 return localStorage . getItem ( 'appearance' ) as Appearance | null ;
4736} ;
4837
@@ -53,22 +42,16 @@ const handleSystemThemeChange = () => {
5342} ;
5443
5544export const initializeTheme = ( ) => {
56- if ( typeof window === 'undefined' ) {
57- return ;
58- }
59-
6045 const savedAppearance = getStoredAppearance ( ) ;
6146 updateTheme ( savedAppearance || 'system' ) ;
6247
63- mediaQuery ( ) ? .addEventListener ( 'change' , handleSystemThemeChange ) ;
48+ mediaQuery ( ) . addEventListener ( 'change' , handleSystemThemeChange ) ;
6449} ;
6550
6651export function useAppearance ( ) {
6752 const appearance = ref < Appearance > ( 'system' ) ;
6853
6954 onMounted ( ( ) => {
70- initializeTheme ( ) ;
71-
7255 const savedAppearance = localStorage . getItem ( 'appearance' ) as Appearance | null ;
7356
7457 if ( savedAppearance ) {
@@ -81,6 +64,8 @@ export function useAppearance() {
8164
8265 localStorage . setItem ( 'appearance' , value ) ;
8366
67+ setCookie ( 'appearance' , value ) ;
68+
8469 updateTheme ( value ) ;
8570 } ;
8671
0 commit comments