1+ import { setCookie } from '@/dashboard/lib/cookie' ;
12import { onMounted , ref } from 'vue' ;
23
34type Appearance = 'light' | 'dark' | 'system' ;
45
56export function updateTheme ( value : Appearance ) {
6- if ( typeof window === 'undefined' ) {
7+ const systemTheme = mediaQuery ( ) . matches ? 'dark' : 'light' ;
8+ const desiredTheme = value === 'system' ? systemTheme : value ;
9+ const currentTheme = getCurrentTheme ( ) ;
10+
11+ if ( currentTheme === desiredTheme ) {
712 return ;
813 }
914
@@ -24,19 +29,15 @@ export function updateTheme(value: Appearance) {
2429 }
2530}
2631
27- const mediaQuery = ( ) => {
28- if ( typeof window === 'undefined' ) {
29- return null ;
30- }
32+ const getCurrentTheme = ( ) : Appearance => {
33+ return document . documentElement . classList . contains ( 'dark' ) ? 'dark' : 'light' ;
34+ } ;
3135
36+ const mediaQuery = ( ) => {
3237 return window . matchMedia ( '(prefers-color-scheme: dark)' ) ;
3338} ;
3439
3540const getStoredAppearance = ( ) => {
36- if ( typeof window === 'undefined' ) {
37- return null ;
38- }
39-
4041 return localStorage . getItem ( 'appearance' ) as Appearance | null ;
4142} ;
4243
@@ -46,23 +47,17 @@ const handleSystemThemeChange = () => {
4647 updateTheme ( currentAppearance || 'system' ) ;
4748} ;
4849
49- export function initializeTheme ( ) {
50- if ( typeof window === 'undefined' ) {
51- return ;
52- }
53-
50+ export const initializeTheme = ( ) => {
5451 const savedAppearance = getStoredAppearance ( ) ;
5552 updateTheme ( savedAppearance || 'system' ) ;
5653
57- mediaQuery ( ) ? .addEventListener ( 'change' , handleSystemThemeChange ) ;
58- }
54+ mediaQuery ( ) . addEventListener ( 'change' , handleSystemThemeChange ) ;
55+ } ;
5956
6057export function useAppearance ( ) {
6158 const appearance = ref < Appearance > ( 'system' ) ;
6259
6360 onMounted ( ( ) => {
64- initializeTheme ( ) ;
65-
6661 const savedAppearance = localStorage . getItem ( 'appearance' ) as Appearance | null ;
6762
6863 if ( savedAppearance ) {
@@ -75,6 +70,8 @@ export function useAppearance() {
7570
7671 localStorage . setItem ( 'appearance' , value ) ;
7772
73+ setCookie ( 'appearance' , value ) ;
74+
7875 updateTheme ( value ) ;
7976 }
8077
0 commit comments