forked from TelegramOrg/Telegram-web-z
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseAppLayout.ts
75 lines (61 loc) · 2.55 KB
/
useAppLayout.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
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 {
MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,
MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,
MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,
MOBILE_SCREEN_MAX_WIDTH,
} from '../config';
import { useEffect } from '../lib/teact/teact';
import { IS_IOS } from '../util/windowEnvironment';
import { createCallbackManager } from '../util/callbacks';
import { updateSizes } from '../util/windowSize';
import useForceUpdate from './useForceUpdate';
type MediaQueryCacheKey = 'mobile' | 'tablet' | 'landscape';
const mediaQueryCache = new Map<MediaQueryCacheKey, MediaQueryList>();
const callbacks = createCallbackManager();
let isMobile: boolean | undefined;
let isTablet: boolean | undefined;
let isLandscape: boolean | undefined;
export function getIsMobile() {
return isMobile;
}
export function getIsTablet() {
return isTablet;
}
function handleMediaQueryChange() {
isMobile = mediaQueryCache.get('mobile')?.matches || false;
isTablet = !isMobile && (mediaQueryCache.get('tablet')?.matches || false);
isLandscape = mediaQueryCache.get('landscape')?.matches || false;
updateSizes();
callbacks.runCallbacks();
}
function initMediaQueryCache() {
const mobileQuery = window.matchMedia(`(max-width: ${MOBILE_SCREEN_MAX_WIDTH}px), \
(max-width: ${MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH}px and max-height: ${MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT}px)`);
mediaQueryCache.set('mobile', mobileQuery);
mobileQuery.addEventListener('change', handleMediaQueryChange);
const tabletQuery = window.matchMedia(`(max-width: ${MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN}px)`);
mediaQueryCache.set('tablet', tabletQuery);
tabletQuery.addEventListener('change', handleMediaQueryChange);
const landscapeQuery = window.matchMedia(
IS_IOS
? '(orientation: landscape)'
// Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/
// Feature is marked as deprecated now, but it is still supported
// https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility
: 'screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)',
);
mediaQueryCache.set('landscape', landscapeQuery);
landscapeQuery.addEventListener('change', handleMediaQueryChange);
}
initMediaQueryCache();
handleMediaQueryChange();
export default function useAppLayout() {
const forceUpdate = useForceUpdate();
useEffect(() => callbacks.addCallback(forceUpdate), [forceUpdate]);
return {
isMobile,
isTablet,
isLandscape,
isDesktop: !isMobile && !isTablet,
};
}