-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathuseAutoDetectAppearance.tsx
44 lines (37 loc) · 1.38 KB
/
useAutoDetectAppearance.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
import * as React from 'react';
import { noop } from '@vkontakte/vkjs';
import type { AppearanceType } from '../lib/appearance';
import { useDOM } from '../lib/dom';
import { matchMediaListAddListener, matchMediaListRemoveListener } from '../lib/matchMedia';
import { useIsomorphicLayoutEffect } from '../lib/useIsomorphicLayoutEffect';
/**
* @private
*/
export const useAutoDetectAppearance = (appearanceProp?: AppearanceType): AppearanceType => {
const { window } = useDOM();
const [appearance, setAppearance] = React.useState<AppearanceType>(() => {
if (appearanceProp) {
return appearanceProp;
}
// eslint-disable-next-line no-restricted-properties
return window!.matchMedia('(prefers-color-scheme: dark)')?.matches ? 'dark' : 'light';
});
useIsomorphicLayoutEffect(() => {
if (appearanceProp) {
setAppearance(appearanceProp);
return noop;
}
const mediaQuery = window!.matchMedia('(prefers-color-scheme: dark)');
if (!mediaQuery) {
return noop;
}
const check = (event: MediaQueryList | MediaQueryListEvent) => {
// eslint-disable-next-line no-restricted-properties
setAppearance(event.matches ? 'dark' : 'light');
};
check(mediaQuery);
matchMediaListAddListener(mediaQuery, check);
return () => matchMediaListRemoveListener(mediaQuery, check);
}, [window, appearanceProp]);
return appearance;
};