UNPKG

2.04 kBPlain TextView Raw
1'use strict';
2import { useEffect, useRef } from 'react';
3import {
4 makeMutable,
5 subscribeForKeyboardEvents,
6 unsubscribeFromKeyboardEvents,
7} from '../core';
8import type {
9 AnimatedKeyboardInfo,
10 AnimatedKeyboardOptions,
11} from '../commonTypes';
12import { KeyboardState } from '../commonTypes';
13
14/**
15 * Lets you synchronously get the position and state of the keyboard.
16 *
17 * @param options - An additional keyboard configuration options.
18 * @returns An object with the current keyboard `height` and `state` as [shared values](https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/glossary#shared-value).
19 * @see https://docs.swmansion.com/react-native-reanimated/docs/device/useAnimatedKeyboard
20 */
21export function useAnimatedKeyboard(
22 options: AnimatedKeyboardOptions = { isStatusBarTranslucentAndroid: false }
23): AnimatedKeyboardInfo {
24 const ref = useRef<AnimatedKeyboardInfo | null>(null);
25 const listenerId = useRef<number>(-1);
26 const isSubscribed = useRef<boolean>(false);
27
28 if (ref.current === null) {
29 const keyboardEventData: AnimatedKeyboardInfo = {
30 state: makeMutable<KeyboardState>(KeyboardState.UNKNOWN),
31 height: makeMutable(0),
32 };
33 listenerId.current = subscribeForKeyboardEvents((state, height) => {
34 'worklet';
35 keyboardEventData.state.value = state;
36 keyboardEventData.height.value = height;
37 }, options);
38 ref.current = keyboardEventData;
39 isSubscribed.current = true;
40 }
41 useEffect(() => {
42 if (isSubscribed.current === false && ref.current !== null) {
43 const keyboardEventData = ref.current;
44 // subscribe again after Fast Refresh
45 listenerId.current = subscribeForKeyboardEvents((state, height) => {
46 'worklet';
47 keyboardEventData.state.value = state;
48 keyboardEventData.height.value = height;
49 }, options);
50 isSubscribed.current = true;
51 }
52 return () => {
53 unsubscribeFromKeyboardEvents(listenerId.current);
54 isSubscribed.current = false;
55 };
56 }, []);
57 return ref.current;
58}