-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathuseKeyboard.ts
More file actions
85 lines (77 loc) · 2.63 KB
/
useKeyboard.ts
File metadata and controls
85 lines (77 loc) · 2.63 KB
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
76
77
78
79
80
81
82
83
84
85
import {useEffect, useState} from 'react'
import {Keyboard, KeyboardEventListener, ScreenRect} from 'react-native'
export type KeyboardAnimationType = 'show' | 'hide'
interface KeyboardAnimationEvent {
active: boolean
duration: number
type: KeyboardAnimationType
}
const emptyCoordinates = Object.freeze({
screenX: 0,
screenY: 0,
width: 0,
height: 0,
})
const initialCoordinates = {
start: emptyCoordinates,
end: emptyCoordinates,
}
const initialAnimation: KeyboardAnimationEvent = {
active: false,
duration: 0,
type: 'show',
}
export function useKeyboard() {
const [shown, setShown] = useState(false)
const [animation, setAnimation] = useState<KeyboardAnimationEvent>(
initialAnimation,
)
const [coordinates, setCoordinates] = useState<{
start: ScreenRect
end: ScreenRect
}>(initialCoordinates)
const [keyboardHeight, setKeyboardHeight] = useState<number>(0)
const handleKeyboardWillShow: KeyboardEventListener = (e) => {
setAnimation({active: true, duration: e.duration, type: 'show'})
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
}
const handleKeyboardDidShow: KeyboardEventListener = (e) => {
setShown(true)
setAnimation({active: false, duration: e.duration, type: 'show'})
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
setKeyboardHeight(e.endCoordinates.height)
}
const handleKeyboardWillHide: KeyboardEventListener = (e) => {
setAnimation({active: true, duration: e.duration, type: 'hide'})
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
}
const handleKeyboardDidHide: KeyboardEventListener = (e) => {
setShown(false)
if (e) {
setAnimation({active: false, duration: e.duration, type: 'hide'})
setCoordinates({start: e.startCoordinates, end: e.endCoordinates})
} else {
setAnimation(initialAnimation)
setCoordinates(initialCoordinates)
setKeyboardHeight(0)
}
}
useEffect(() => {
Keyboard.addListener('keyboardWillShow', handleKeyboardWillShow)
Keyboard.addListener('keyboardDidShow', handleKeyboardDidShow)
Keyboard.addListener('keyboardWillHide', handleKeyboardWillHide)
Keyboard.addListener('keyboardDidHide', handleKeyboardDidHide)
return () => {
Keyboard.removeListener('keyboardWillShow', handleKeyboardWillShow)
Keyboard.removeListener('keyboardDidShow', handleKeyboardDidShow)
Keyboard.removeListener('keyboardWillHide', handleKeyboardWillHide)
Keyboard.removeListener('keyboardDidHide', handleKeyboardDidHide)
}
}, [])
return {
keyboardShown: shown,
coordinates,
animation,
keyboardHeight,
}
}