-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
theme.provider.tsx
60 lines (53 loc) · 1.88 KB
/
theme.provider.tsx
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
import { useMemo, useSyncExternalStore } from 'react';
export type Theme = 'light' | 'dark' | 'system';
export function useTheme(): [Theme, (theme: Theme) => void] {
const [subscribe, getSnapshot, getServerSnapshot] = useMemo(() => {
return [
(notify: () => void) => {
const handleStorageEvent = (evt: StorageEvent) => {
if (evt.key === 'theme') {
changeDocumentClassName();
notify();
}
};
const changeDocumentClassName = () => {
if (
localStorage['theme'] === 'dark' ||
((!localStorage['theme'] || localStorage['theme'] === 'system') &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
document.documentElement.classList.add('dark', 'changing-theme');
} else {
document.documentElement.classList.remove('dark', 'changing-theme');
}
window.setTimeout(() => {
document.documentElement.classList.remove('changing-theme');
});
};
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', changeDocumentClassName);
window.addEventListener('storage', handleStorageEvent);
changeDocumentClassName();
return () => {
mediaQuery.removeEventListener('change', changeDocumentClassName);
window.removeEventListener('storage', handleStorageEvent);
};
},
() => window.localStorage['theme'] ?? 'system',
() => 'system',
];
}, []);
return [
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot),
(theme: Theme) => {
localStorage['theme'] = theme;
// For current window
window.dispatchEvent(
new StorageEvent('storage', {
key: 'theme',
newValue: theme,
})
);
},
];
}