|
| 1 | +/** |
| 2 | + * The type of the `useIsFocused` hook from `@react-navigation/native`. |
| 3 | + */ |
| 4 | +type UseIsFocusedHook = () => boolean; |
| 5 | + |
| 6 | +let _useIsFocused: UseIsFocusedHook | undefined; |
| 7 | + |
| 8 | +/** |
| 9 | + * Attempts to load `useIsFocused` from `@react-navigation/native`. |
| 10 | + * |
| 11 | + * This is done once at module load time. If the package is not installed, |
| 12 | + * the import will fail and `_useIsFocused` will remain `undefined`. |
| 13 | + */ |
| 14 | +try { |
| 15 | + // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports |
| 16 | + _useIsFocused = require('@react-navigation/native').useIsFocused; |
| 17 | +} catch { |
| 18 | + // @react-navigation/native is not installed; this is fine. |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * A fallback hook that always returns `true`. |
| 23 | + * |
| 24 | + * Used when `@react-navigation/native` is not installed. Since there is no |
| 25 | + * navigation container managing focus, the component is always considered |
| 26 | + * focused. |
| 27 | + * |
| 28 | + * @returns `true` |
| 29 | + */ |
| 30 | +function useAlwaysFocused(): boolean { |
| 31 | + return true; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * A hook that returns whether the screen is currently focused. |
| 36 | + * |
| 37 | + * If `@react-navigation/native` is installed, this delegates to its |
| 38 | + * `useIsFocused` hook. Otherwise, it falls back to always returning `true`, |
| 39 | + * which is appropriate when no navigation container is in use (the component |
| 40 | + * is always "focused" if there is no navigation stack managing focus). |
| 41 | + * |
| 42 | + * @returns `true` if the screen is focused (or if React Navigation is not |
| 43 | + * installed), `false` otherwise. |
| 44 | + */ |
| 45 | +export const useIsFocused: UseIsFocusedHook = _useIsFocused ?? useAlwaysFocused; |
0 commit comments