Skip to content

Commit

Permalink
Return focus more from focus return hook (#52710)
Browse files Browse the repository at this point in the history
  • Loading branch information
stokesman authored and tellthemachines committed Jul 25, 2023
1 parent 453af8b commit 3ccb2ef
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
2 changes: 1 addition & 1 deletion packages/compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ _Returns_

### useFocusReturn

When opening modals/sidebars/dialogs, the focus must move to the opened area and return to the previously focused element when closed. The current hook implements the returning behavior.
Adds the unmount behavior of returning focus to the element which had it previously as is expected for roles like menus or dialogs.

_Usage_

Expand Down
17 changes: 11 additions & 6 deletions packages/compose/src/hooks/use-focus-return/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
*/
import { useRef, useEffect, useCallback } from '@wordpress/element';

/** @type {Element|null} */
let origin = null;

/**
* When opening modals/sidebars/dialogs, the focus
* must move to the opened area and return to the
* previously focused element when closed.
* The current hook implements the returning behavior.
* Adds the unmount behavior of returning focus to the element which had it
* previously as is expected for roles like menus or dialogs.
*
* @param {() => void} [onFocusReturn] Overrides the default return behavior.
* @return {import('react').RefCallback<HTMLElement>} Element Ref.
Expand Down Expand Up @@ -54,6 +55,7 @@ function useFocusReturn( onFocusReturn ) {
);

if ( ref.current?.isConnected && ! isFocused ) {
origin ??= focusedBeforeMount.current;
return;
}

Expand All @@ -64,10 +66,13 @@ function useFocusReturn( onFocusReturn ) {
if ( onFocusReturnRef.current ) {
onFocusReturnRef.current();
} else {
/** @type {null | HTMLElement} */ (
focusedBeforeMount.current
/** @type {null|HTMLElement} */ (
! focusedBeforeMount.current.isConnected
? origin
: focusedBeforeMount.current
)?.focus();
}
origin = null;
}
}, [] );
}
Expand Down

0 comments on commit 3ccb2ef

Please sign in to comment.