-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.ts
67 lines (57 loc) · 2.07 KB
/
index.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
// eslint-disable-next-line no-restricted-imports
import {useEffect, useState} from 'react';
import {Dimensions} from 'react-native';
import type {ScaledSize} from 'react-native';
type InitialWindowDimensions = {
initialWidth: number;
initialHeight: number;
};
type NewDimensions = {
window: ScaledSize;
screen: ScaledSize;
};
/**
* A convenience hook that provides initial size (width and height).
* An initial height allows to know the real height of window,
* while the standard useWindowDimensions hook return the height minus Virtual keyboard height
* @returns with information about initial width and height
*/
export default function (): InitialWindowDimensions {
const [dimensions, setDimensions] = useState(() => {
const window = Dimensions.get('window');
const screen = Dimensions.get('screen');
return {
screenHeight: screen.height,
screenWidth: screen.width,
initialHeight: window.height,
initialWidth: window.width,
};
});
useEffect(() => {
const onDimensionChange = (newDimensions: NewDimensions) => {
const {window, screen} = newDimensions;
setDimensions((oldState) => {
if (screen.width !== oldState.screenWidth || screen.height !== oldState.screenHeight || window.height > oldState.initialHeight) {
return {
initialHeight: window.height,
initialWidth: window.width,
screenHeight: screen.height,
screenWidth: screen.width,
};
}
return oldState;
});
};
const dimensionsEventListener = Dimensions.addEventListener('change', onDimensionChange);
return () => {
if (!dimensionsEventListener) {
return;
}
dimensionsEventListener.remove();
};
}, []);
return {
initialWidth: dimensions.initialWidth,
initialHeight: dimensions.initialHeight,
};
}