UNPKG

@react-navigation/core

Version:

Core utilities for building navigators

70 lines (66 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFocusEvents = useFocusEvents; var React = _interopRequireWildcard(require("react")); var _NavigationContext = require("./NavigationContext.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * Hook to take care of emitting `focus` and `blur` events. */ function useFocusEvents({ state, emitter }) { const navigation = React.useContext(_NavigationContext.NavigationContext); const lastFocusedKeyRef = React.useRef(); const currentFocusedKey = state.routes[state.index].key; // When the parent screen changes its focus state, we also need to change child's focus // Coz the child screen can't be focused if the parent screen is out of focus React.useEffect(() => navigation?.addListener('focus', () => { lastFocusedKeyRef.current = currentFocusedKey; emitter.emit({ type: 'focus', target: currentFocusedKey }); }), [currentFocusedKey, emitter, navigation]); React.useEffect(() => navigation?.addListener('blur', () => { lastFocusedKeyRef.current = undefined; emitter.emit({ type: 'blur', target: currentFocusedKey }); }), [currentFocusedKey, emitter, navigation]); React.useEffect(() => { const lastFocusedKey = lastFocusedKeyRef.current; lastFocusedKeyRef.current = currentFocusedKey; // We wouldn't have `lastFocusedKey` on initial mount // Fire focus event for the current route on mount if there's no parent navigator if (lastFocusedKey === undefined && !navigation) { emitter.emit({ type: 'focus', target: currentFocusedKey }); } // We should only emit events when the focused key changed and navigator is focused // When navigator is not focused, screens inside shouldn't receive focused status either if (lastFocusedKey === currentFocusedKey || !(navigation ? navigation.isFocused() : true)) { return; } if (lastFocusedKey === undefined) { // Only fire events after initial mount return; } emitter.emit({ type: 'blur', target: lastFocusedKey }); emitter.emit({ type: 'focus', target: currentFocusedKey }); }, [currentFocusedKey, emitter, navigation]); } //# sourceMappingURL=useFocusEvents.js.map