-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
useAutoFocusInput.ts
57 lines (48 loc) · 1.95 KB
/
useAutoFocusInput.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
import {useFocusEffect} from '@react-navigation/native';
import {useCallback, useContext, useEffect, useRef, useState} from 'react';
import type {TextInput} from 'react-native';
import {InteractionManager} from 'react-native';
import CONST from '@src/CONST';
import * as Expensify from '@src/Expensify';
type UseAutoFocusInput = {
inputCallbackRef: (ref: TextInput | null) => void;
};
export default function useAutoFocusInput(): UseAutoFocusInput {
const [isInputInitialized, setIsInputInitialized] = useState(false);
const [isScreenTransitionEnded, setIsScreenTransitionEnded] = useState(false);
// @ts-expect-error TODO: Remove this when Expensify.js is migrated.
const {isSplashHidden} = useContext(Expensify.SplashScreenHiddenContext);
const inputRef = useRef<TextInput | null>(null);
const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (!isScreenTransitionEnded || !isInputInitialized || !inputRef.current || !isSplashHidden) {
return;
}
const focusTaskHandle = InteractionManager.runAfterInteractions(() => {
inputRef.current?.focus();
setIsScreenTransitionEnded(false);
});
return () => {
focusTaskHandle.cancel();
};
}, [isScreenTransitionEnded, isInputInitialized, isSplashHidden]);
useFocusEffect(
useCallback(() => {
focusTimeoutRef.current = setTimeout(() => {
setIsScreenTransitionEnded(true);
}, CONST.ANIMATED_TRANSITION);
return () => {
setIsScreenTransitionEnded(false);
if (!focusTimeoutRef.current) {
return;
}
clearTimeout(focusTimeoutRef.current);
};
}, []),
);
const inputCallbackRef = (ref: TextInput | null) => {
inputRef.current = ref;
setIsInputInitialized(true);
};
return {inputCallbackRef};
}