Skip to content
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
4 changes: 2 additions & 2 deletions packages/compose/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,11 @@ const WithFocusReturn = () => {

_Parameters_

- _onFocusReturn_ `Function?`: Overrides the default return behavior.
- _onFocusReturn_ `[() => void]`: Overrides the default return behavior.

_Returns_

- `Function`: Element Ref.
- `import('react').RefCallback<HTMLElement>`: Element Ref.

<a name="useInstanceId" href="#useInstanceId">#</a> **useInstanceId**

Expand Down
18 changes: 10 additions & 8 deletions packages/compose/src/hooks/use-focus-return/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { useRef, useEffect, useCallback } from '@wordpress/element';
* previously focused element when closed.
* The current hook implements the returning behavior.
*
* @param {Function?} onFocusReturn Overrides the default return behavior.
* @return {Function} Element Ref.
* @param {() => void} [onFocusReturn] Overrides the default return behavior.
* @return {import('react').RefCallback<HTMLElement>} Element Ref.
*
* @example
* ```js
Expand All @@ -28,8 +28,10 @@ import { useRef, useEffect, useCallback } from '@wordpress/element';
* ```
*/
function useFocusReturn( onFocusReturn ) {
const ref = useRef();
const focusedBeforeMount = useRef();
/** @type {import('react').MutableRefObject<null | HTMLElement>} */
const ref = useRef( null );
/** @type {import('react').MutableRefObject<null | Element>} */
const focusedBeforeMount = useRef( null );
const onFocusReturnRef = useRef( onFocusReturn );
useEffect( () => {
onFocusReturnRef.current = onFocusReturn;
Expand All @@ -47,11 +49,11 @@ function useFocusReturn( onFocusReturn ) {

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

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

Expand All @@ -62,7 +64,7 @@ function useFocusReturn( onFocusReturn ) {
if ( onFocusReturnRef.current ) {
onFocusReturnRef.current();
} else {
focusedBeforeMount.current.focus();
/** @type {null | HTMLElement} */ ( focusedBeforeMount.current )?.focus();
}
}
}, [] );
Expand Down
1 change: 1 addition & 0 deletions packages/compose/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"src/hooks/use-async-list/**/*",
"src/hooks/use-constrained-tabbing/**/*",
"src/hooks/use-instance-id/**/*",
"src/hooks/use-focus-return/**/*",
"src/utils/**/*"
]
}