Skip to content

Commit

Permalink
update useFocus Hook to handle animations and catch `findNodeHandle…
Browse files Browse the repository at this point in the history
…` errors (#220)
  • Loading branch information
JDMathew authored Jul 30, 2024
1 parent 943db65 commit 018549a
Showing 1 changed file with 33 additions and 12 deletions.
45 changes: 33 additions & 12 deletions packages/core/src/hooks/useFocus.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { SHELL_COLORS } from '@react-native-ama/internal';
import * as React from 'react';
import { AccessibilityInfo, findNodeHandle } from 'react-native';
import {
AccessibilityInfo,
InteractionManager,
findNodeHandle,
} from 'react-native';

export const useFocus = (refComponent?: React.RefObject<any>) => {
const setFocus = React.useCallback(
Expand All @@ -11,18 +15,35 @@ export const useFocus = (refComponent?: React.RefObject<any>) => {
| React.Component<any, any>
| React.ComponentClass<any>,
) => {
// @ts-ignore
const elementId = findNodeHandle(component);

if (elementId) {
AccessibilityInfo.setAccessibilityFocus(elementId);
AccessibilityInfo.setAccessibilityFocus(elementId);
} else if (__DEV__) {
console.warn(
// @ts-ignore
`${SHELL_COLORS.BG_RED}AMA.${SHELL_COLORS.RESET} ${SHELL_COLORS.BLUE}useFocus${SHELL_COLORS.RESET}: ${SHELL_COLORS.YELLOW}Ref element not found${SHELL_COLORS.RESET}`,
);
if (!component) {
return;
}

InteractionManager.runAfterInteractions(() => {
try {
const elementId = findNodeHandle(component);

if (elementId) {
AccessibilityInfo.setAccessibilityFocus(elementId);
setTimeout(() => {
AccessibilityInfo.setAccessibilityFocus(elementId); //ISSUE: https://github.com/facebook/react-native/issues/30097
}, 100);
} else if (__DEV__) {
console.warn(
// @ts-ignore
`${SHELL_COLORS.BG_RED}AMA.${SHELL_COLORS.RESET} ${SHELL_COLORS.BLUE}useFocus${SHELL_COLORS.RESET}: ${SHELL_COLORS.YELLOW}Ref element not found${SHELL_COLORS.RESET}`,
);
}
} catch (error) {
if (__DEV__) {
console.warn(
// @ts-ignore
`${SHELL_COLORS.BG_RED}AMA.${SHELL_COLORS.RESET} ${SHELL_COLORS.BLUE}useFocus${SHELL_COLORS.RESET}: ${SHELL_COLORS.YELLOW}Error finding node handle${SHELL_COLORS.RESET} \n`,
error,
);
}
}
});
},
[],
);
Expand Down

0 comments on commit 018549a

Please sign in to comment.