11import { useEffect , useState } from 'react' ;
2- // import { addColorSchemeListener, colorSchemeListeners } from '@/layouts';
2+ import { addColorSchemeListener , colorSchemeListeners } from '@/layouts/GlobalLayout ' ;
33import { getOsTheme } from '@/utils' ;
44import { ITheme } from '@/typings' ;
55import { ThemeType , PrimaryColorType } from '@/constants' ;
66import { getPrimaryColor , getTheme , setPrimaryColor , setTheme } from '@/utils/localStorage' ;
7+ import { v4 as uuidv4 } from 'uuid' ;
8+
9+ const colorSchemeListeners : {
10+ [ key : string ] : ( theme : { backgroundColor : ThemeType ; primaryColor : PrimaryColorType } ) => void ;
11+ } = { } ;
12+
13+ const addColorSchemeListener = (
14+ callback : ( theme : { backgroundColor : ThemeType ; primaryColor : PrimaryColorType } ) => void ,
15+ ) => {
16+ const uuid = uuidv4 ( ) ;
17+ colorSchemeListeners [ uuid ] = callback ;
18+ return uuid ;
19+ } ;
720
821const initialTheme = ( ) => {
922 const localStorageTheme = getTheme ( ) ;
1023 const localStoragePrimaryColor = getPrimaryColor ( ) ;
1124
1225 // 判断localStorage的theme在不在ThemeType中, 如果存在就用localStorageTheme
13- let backgroundColor = ThemeType . Light
26+ let backgroundColor = ThemeType . Light ;
1427 if ( Object . values ( ThemeType ) . includes ( localStorageTheme ) ) {
1528 backgroundColor = localStorageTheme ;
1629 }
1730
18- let primaryColor = PrimaryColorType . Golden_Purple
31+ let primaryColor = PrimaryColorType . Golden_Purple ;
1932 if ( Object . values ( PrimaryColorType ) . includes ( localStoragePrimaryColor ) ) {
2033 primaryColor = localStoragePrimaryColor ;
2134 }
@@ -37,10 +50,10 @@ export function useTheme<T = ITheme>(): [T, React.Dispatch<React.SetStateAction<
3750 // const isDark = useMemo(() => appTheme.backgroundColor === ThemeType.Dark, [appTheme]);
3851
3952 useEffect ( ( ) => {
40- // const uuid = addColorSchemeListener(setAppTheme as any);
41- // return () => {
42- // delete colorSchemeListeners[uuid];
43- // };
53+ const uuid = addColorSchemeListener ( setAppTheme as any ) ;
54+ return ( ) => {
55+ delete colorSchemeListeners [ uuid ] ;
56+ } ;
4457 } , [ ] ) ;
4558
4659 function handleAppThemeChange ( theme : { backgroundColor : ThemeType ; primaryColor : PrimaryColorType } ) {
@@ -50,9 +63,9 @@ export function useTheme<T = ITheme>(): [T, React.Dispatch<React.SetStateAction<
5063 ? ThemeType . DarkDimmed
5164 : ThemeType . Light ;
5265 }
53- // Object.keys(colorSchemeListeners)?.forEach((t) => {
54- // colorSchemeListeners[t]?.(theme);
55- // });
66+ Object . keys ( colorSchemeListeners ) ?. forEach ( ( t ) => {
67+ colorSchemeListeners [ t ] ?.( theme ) ;
68+ } ) ;
5669 document . documentElement . setAttribute ( 'theme' , theme . backgroundColor ) ;
5770 setTheme ( theme . backgroundColor ) ;
5871 document . documentElement . setAttribute ( 'primary-color' , theme . primaryColor ) ;
0 commit comments