forked from react-native-community/hooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseKeyboard.ts
66 lines (60 loc) · 1.88 KB
/
useKeyboard.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
import {useEffect, useState} from 'react'
import {Keyboard, KeyboardEventListener, KeyboardMetrics} from 'react-native'
const emptyCoordinates: KeyboardMetrics = Object.freeze({
screenX: 0,
screenY: 0,
width: 0,
height: 0,
})
const initialValue = {
start: emptyCoordinates as KeyboardMetrics | undefined,
end: emptyCoordinates,
}
const defaultState = {
keyboardShown: false,
coordinates: initialValue,
keyboardHeight: 0,
}
export function useKeyboard() {
const [state, setState] = useState(defaultState)
const handleKeyboardWillShow: KeyboardEventListener = (e) => {
setState((prevState) => ({
...prevState,
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
}))
}
const handleKeyboardDidShow: KeyboardEventListener = (e) => {
setState(() => ({
keyboardShown: true,
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
keyboardHeight: e.endCoordinates.height,
}))
}
const handleKeyboardWillHide: KeyboardEventListener = (e) => {
setState((prevState) => ({
...prevState,
coordinates: {start: e.startCoordinates, end: e.endCoordinates},
}))
}
const handleKeyboardDidHide: KeyboardEventListener = (e) => {
setState((prevState) => ({
keyboardShown: false,
coordinates: e
? {start: e.startCoordinates, end: e.endCoordinates}
: initialValue,
keyboardHeight: e ? prevState.keyboardHeight : 0,
}))
}
useEffect(() => {
const subscriptions = [
Keyboard.addListener('keyboardWillShow', handleKeyboardWillShow),
Keyboard.addListener('keyboardDidShow', handleKeyboardDidShow),
Keyboard.addListener('keyboardWillHide', handleKeyboardWillHide),
Keyboard.addListener('keyboardDidHide', handleKeyboardDidHide),
]
return () => {
subscriptions.forEach((subscription) => subscription.remove())
}
}, [])
return state
}