1 | import * as React from 'react';
|
2 | import { Keyboard, TextInput } from 'react-native';
|
3 | export default function useKeyboardManager(isEnabled) {
|
4 |
|
5 |
|
6 | const previouslyFocusedTextInputRef = React.useRef(undefined);
|
7 | const startTimestampRef = React.useRef(0);
|
8 | const keyboardTimeoutRef = React.useRef();
|
9 | const clearKeyboardTimeout = React.useCallback(() => {
|
10 | if (keyboardTimeoutRef.current !== undefined) {
|
11 | clearTimeout(keyboardTimeoutRef.current);
|
12 | keyboardTimeoutRef.current = undefined;
|
13 | }
|
14 | }, []);
|
15 | const onPageChangeStart = React.useCallback(() => {
|
16 | if (!isEnabled()) {
|
17 | return;
|
18 | }
|
19 |
|
20 | clearKeyboardTimeout();
|
21 | const input = TextInput.State.currentlyFocusedInput();
|
22 |
|
23 | input === null || input === void 0 ? void 0 : input.blur();
|
24 |
|
25 | previouslyFocusedTextInputRef.current = input;
|
26 |
|
27 | startTimestampRef.current = Date.now();
|
28 | }, [clearKeyboardTimeout, isEnabled]);
|
29 | const onPageChangeConfirm = React.useCallback(force => {
|
30 | if (!isEnabled()) {
|
31 | return;
|
32 | }
|
33 |
|
34 | clearKeyboardTimeout();
|
35 |
|
36 | if (force) {
|
37 |
|
38 |
|
39 |
|
40 | Keyboard.dismiss();
|
41 | } else {
|
42 | const input = previouslyFocusedTextInputRef.current;
|
43 |
|
44 |
|
45 | input === null || input === void 0 ? void 0 : input.blur();
|
46 | }
|
47 |
|
48 |
|
49 | previouslyFocusedTextInputRef.current = undefined;
|
50 | }, [clearKeyboardTimeout, isEnabled]);
|
51 | const onPageChangeCancel = React.useCallback(() => {
|
52 | if (!isEnabled()) {
|
53 | return;
|
54 | }
|
55 |
|
56 | clearKeyboardTimeout();
|
57 |
|
58 | const input = previouslyFocusedTextInputRef.current;
|
59 |
|
60 | if (input) {
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | if (Date.now() - startTimestampRef.current < 100) {
|
68 | keyboardTimeoutRef.current = setTimeout(() => {
|
69 | input === null || input === void 0 ? void 0 : input.focus();
|
70 | previouslyFocusedTextInputRef.current = undefined;
|
71 | }, 100);
|
72 | } else {
|
73 | input === null || input === void 0 ? void 0 : input.focus();
|
74 | previouslyFocusedTextInputRef.current = undefined;
|
75 | }
|
76 | }
|
77 | }, [clearKeyboardTimeout, isEnabled]);
|
78 | React.useEffect(() => {
|
79 | return () => clearKeyboardTimeout();
|
80 | }, [clearKeyboardTimeout]);
|
81 | return {
|
82 | onPageChangeStart,
|
83 | onPageChangeConfirm,
|
84 | onPageChangeCancel
|
85 | };
|
86 | }
|
87 |
|
\ | No newline at end of file |