Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return focus more from focus return hook #52710

Merged
merged 1 commit into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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