-
Notifications
You must be signed in to change notification settings - Fork 9
/
useAppearance.ts
40 lines (30 loc) · 1.32 KB
/
useAppearance.ts
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
'use client';
import { useCallback, useContext, useEffect, useState } from 'react';
import { getTelegramData } from 'helpers/telegram';
import { AppRootContext, AppRootContextInterface } from '../AppRootContext';
import { getBrowserAppearanceSubscriber } from './helpers/getBrowserAppearanceSubscriber';
import { getInitialAppearance } from './helpers/getInitialAppearance';
export const useAppearance = (appearanceProp?: AppRootContextInterface['appearance']): NonNullable<AppRootContextInterface['appearance']> => {
const { appearance: contextAppearance } = useContext(AppRootContext);
const [appearance, setAppearance] = useState(appearanceProp || contextAppearance || getInitialAppearance());
const handleThemeChange = useCallback(() => {
const telegramData = getTelegramData();
if (!telegramData) {
return;
}
setAppearance(telegramData.colorScheme);
}, []);
useEffect(() => {
if (appearanceProp !== undefined) {
setAppearance(appearanceProp);
return () => {};
}
const telegramData = getTelegramData();
if (telegramData) {
telegramData.onEvent('themeChanged', handleThemeChange);
return () => telegramData.offEvent('themeChanged', handleThemeChange);
}
return getBrowserAppearanceSubscriber(setAppearance);
}, [appearanceProp]);
return appearance;
};