UNPKG

2.24 kBJavaScriptView Raw
1import * as React from 'react';
2import NavigationContext from './NavigationContext';
3
4/**
5 * Hook to take care of emitting `focus` and `blur` events.
6 */
7export default function useFocusEvents(_ref) {
8 let {
9 state,
10 emitter
11 } = _ref;
12 const navigation = React.useContext(NavigationContext);
13 const lastFocusedKeyRef = React.useRef();
14 const currentFocusedKey = state.routes[state.index].key; // When the parent screen changes its focus state, we also need to change child's focus
15 // Coz the child screen can't be focused if the parent screen is out of focus
16
17 React.useEffect(() => navigation === null || navigation === void 0 ? void 0 : navigation.addListener('focus', () => {
18 lastFocusedKeyRef.current = currentFocusedKey;
19 emitter.emit({
20 type: 'focus',
21 target: currentFocusedKey
22 });
23 }), [currentFocusedKey, emitter, navigation]);
24 React.useEffect(() => navigation === null || navigation === void 0 ? void 0 : navigation.addListener('blur', () => {
25 lastFocusedKeyRef.current = undefined;
26 emitter.emit({
27 type: 'blur',
28 target: currentFocusedKey
29 });
30 }), [currentFocusedKey, emitter, navigation]);
31 React.useEffect(() => {
32 const lastFocusedKey = lastFocusedKeyRef.current;
33 lastFocusedKeyRef.current = currentFocusedKey; // We wouldn't have `lastFocusedKey` on initial mount
34 // Fire focus event for the current route on mount if there's no parent navigator
35
36 if (lastFocusedKey === undefined && !navigation) {
37 emitter.emit({
38 type: 'focus',
39 target: currentFocusedKey
40 });
41 } // We should only emit events when the focused key changed and navigator is focused
42 // When navigator is not focused, screens inside shouldn't receive focused status either
43
44
45 if (lastFocusedKey === currentFocusedKey || !(navigation ? navigation.isFocused() : true)) {
46 return;
47 }
48
49 if (lastFocusedKey === undefined) {
50 // Only fire events after initial mount
51 return;
52 }
53
54 emitter.emit({
55 type: 'blur',
56 target: lastFocusedKey
57 });
58 emitter.emit({
59 type: 'focus',
60 target: currentFocusedKey
61 });
62 }, [currentFocusedKey, emitter, navigation]);
63}
64//# sourceMappingURL=useFocusEvents.js.map
\No newline at end of file