Skip to content

Commit

Permalink
Try: simplify focus return (#27705)
Browse files Browse the repository at this point in the history
* Try: simplify focus return

* Reformat code
  • Loading branch information
ellatrix authored Dec 14, 2020
1 parent fcc4b8c commit ecfa1ab
Showing 1 changed file with 22 additions and 31 deletions.
53 changes: 22 additions & 31 deletions packages/compose/src/hooks/use-focus-return/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,53 +33,44 @@ import useCallbackRef from '../use-callback-ref';
* ```
*/
function useFocusReturn( onFocusReturn ) {
const ref = useRef();
const focusedBeforeMount = useRef();
const isFocused = useRef( false );
const onFocusReturnRef = useRef( onFocusReturn );
useEffect( () => {
onFocusReturnRef.current = onFocusReturn;
}, [] );
}, [ onFocusReturn ] );

const ref = useCallbackRef( ( newNode ) => {
const updateLastFocusedRef = ( { target } ) => {
isFocused.current = newNode && newNode.contains( target );
};
return useCallbackRef( ( node ) => {
if ( node ) {
// Set ref to be used when unmounting.
ref.current = node;

// Unmounting the reference
if ( ! newNode && focusedBeforeMount.current ) {
if ( newNode?.ownerDocument ) {
newNode.ownerDocument.removeEventListener(
'focusin',
updateLastFocusedRef
);
// Only set when the node mounts.
if ( focusedBeforeMount.current ) {
return;
}

if ( ! isFocused.current ) {
focusedBeforeMount.current = node.ownerDocument.activeElement;
} else if ( focusedBeforeMount.current ) {
const isFocused = ref.current.contains(
ref.current.ownerDocument.activeElement
);

if ( ! isFocused ) {
return;
}

// Defer to the component's own explicit focus return behavior,
// if specified. This allows for support that the `onFocusReturn` decides to allow the
// default behavior to occur under some conditions.
// Defer to the component's own explicit focus return behavior, if
// specified. This allows for support that the `onFocusReturn`
// decides to allow the default behavior to occur under some
// conditions.
if ( onFocusReturnRef.current ) {
onFocusReturnRef.current();
return;
} else {
focusedBeforeMount.current.focus();
}

focusedBeforeMount.current.focus();
}

// Mounting the new reference
focusedBeforeMount.current = newNode?.ownerDocument.activeElement;
if ( newNode?.ownerDocument ) {
newNode.ownerDocument.addEventListener(
'focusin',
updateLastFocusedRef
);
}
}, [] );

return ref;
}

export default useFocusReturn;

0 comments on commit ecfa1ab

Please sign in to comment.