-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
useAutoFocusInput.ts
61 lines (52 loc) · 2.07 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
58
59
60
61
import {useFocusEffect} from '@react-navigation/native';
import {useCallback, useEffect, useRef, useState} from 'react';
import type {RefObject} from 'react';
import type {TextInput} from 'react-native';
import {InteractionManager} from 'react-native';
import CONST from '@src/CONST';
import {useSplashScreenStateContext} from '@src/SplashScreenStateContext';
type UseAutoFocusInput = {
inputCallbackRef: (ref: TextInput | null) => void;
inputRef: RefObject<TextInput | null>;
};
export default function useAutoFocusInput(): UseAutoFocusInput {
const [isInputInitialized, setIsInputInitialized] = useState(false);
const [isScreenTransitionEnded, setIsScreenTransitionEnded] = useState(false);
const {splashScreenState} = useSplashScreenStateContext();
const inputRef = useRef<TextInput | null>(null);
const focusTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (!isScreenTransitionEnded || !isInputInitialized || !inputRef.current || splashScreenState !== CONST.BOOT_SPLASH_STATE.HIDDEN) {
return;
}
const focusTaskHandle = InteractionManager.runAfterInteractions(() => {
inputRef.current?.focus();
setIsScreenTransitionEnded(false);
});
return () => {
focusTaskHandle.cancel();
};
}, [isScreenTransitionEnded, isInputInitialized, splashScreenState]);
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;
if (isInputInitialized) {
return;
}
setIsInputInitialized(true);
};
return {inputCallbackRef, inputRef};
}