about summary refs log tree commit diff
path: root/src/lib/hooks/useIsKeyboardVisible.ts
blob: 5b2a86eb0c9953480ded49c311348dddaae7f3ec (plain) (blame)
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
import {useState, useEffect} from 'react'
import {Keyboard} from 'react-native'
import {isIOS} from 'platform/detection'

export function useIsKeyboardVisible({
  iosUseWillEvents,
}: {
  iosUseWillEvents?: boolean
} = {}) {
  const [isKeyboardVisible, setKeyboardVisible] = useState(false)

  // NOTE
  // only iOS suppose the "will" events
  // -prf
  const showEvent =
    isIOS && iosUseWillEvents ? 'keyboardWillShow' : 'keyboardDidShow'
  const hideEvent =
    isIOS && iosUseWillEvents ? 'keyboardWillHide' : 'keyboardDidHide'

  useEffect(() => {
    const keyboardShowListener = Keyboard.addListener(showEvent, () =>
      setKeyboardVisible(true),
    )
    const keyboardHideListener = Keyboard.addListener(hideEvent, () =>
      setKeyboardVisible(false),
    )

    return () => {
      keyboardHideListener.remove()
      keyboardShowListener.remove()
    }
  }, [showEvent, hideEvent])

  return [isKeyboardVisible]
}