forked from OtterMind/Chat2DB
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseTheme.ts
More file actions
75 lines (64 loc) · 2.58 KB
/
Copy pathuseTheme.ts
File metadata and controls
75 lines (64 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { useEffect, useState } from 'react';
import { getOsTheme } from '@/utils';
import { ITheme } from '@/typings';
import { ThemeType, PrimaryColorType } from '@/constants';
import { getPrimaryColor, getTheme, setPrimaryColor, setTheme } from '@/utils/localStorage';
import { v4 as uuidv4 } from 'uuid';
const colorSchemeListeners: {
[key: string]: (theme: { backgroundColor: ThemeType; primaryColor: PrimaryColorType }) => void;
} = {};
const addColorSchemeListener = (
callback: (theme: { backgroundColor: ThemeType; primaryColor: PrimaryColorType }) => void,
) => {
const uuid = uuidv4();
colorSchemeListeners[uuid] = callback;
return uuid;
};
const initialTheme = () => {
const localStorageTheme = getTheme();
const localStoragePrimaryColor = getPrimaryColor();
// 判断localStorage的theme在不在ThemeType中, 如果存在就用localStorageTheme
let backgroundColor = ThemeType.Light;
if (Object.values(ThemeType).includes(localStorageTheme)) {
backgroundColor = localStorageTheme;
}
let primaryColor = PrimaryColorType.Golden_Purple;
if (Object.values(PrimaryColorType).includes(localStoragePrimaryColor)) {
primaryColor = localStoragePrimaryColor;
}
if (backgroundColor === ThemeType.FollowOs) {
backgroundColor = getOsTheme();
}
document.documentElement.setAttribute('theme', backgroundColor);
document.documentElement.setAttribute('primary-color', primaryColor);
return {
backgroundColor,
primaryColor,
};
};
export function useTheme<T = ITheme>(): [T, React.Dispatch<React.SetStateAction<ITheme>>] {
const [appTheme, setAppTheme] = useState<ITheme>(initialTheme());
// const isDark = useMemo(() => appTheme.backgroundColor === ThemeType.Dark, [appTheme]);
useEffect(() => {
const uuid = addColorSchemeListener(setAppTheme as any);
return () => {
delete colorSchemeListeners[uuid];
};
}, []);
function handleAppThemeChange(theme: { backgroundColor: ThemeType; primaryColor: PrimaryColorType }) {
if (theme.backgroundColor === ThemeType.FollowOs) {
theme.backgroundColor =
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
? ThemeType.DarkDimmed
: ThemeType.Light;
}
Object.keys(colorSchemeListeners)?.forEach((t) => {
colorSchemeListeners[t]?.(theme);
});
document.documentElement.setAttribute('theme', theme.backgroundColor);
setTheme(theme.backgroundColor);
document.documentElement.setAttribute('primary-color', theme.primaryColor);
setPrimaryColor(theme.primaryColor);
}
return [appTheme, handleAppThemeChange] as any;
}