Skip to content

Commit

Permalink
Use setTimeout only when the focus on mount target is the first tabba…
Browse files Browse the repository at this point in the history
…ble element.
  • Loading branch information
afercia committed Jul 7, 2022
1 parent 61d5124 commit 9d311c7
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions packages/compose/src/hooks/use-focus-on-mount/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,23 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
return;
}

const focusTimeout = setTimeout( () => {
let target = node;

if ( focusOnMountRef.current === 'firstElement' ) {
const firstTabbable = focus.tabbable.find( node )[ 0 ];

if ( firstTabbable ) {
target = /** @type {HTMLElement} */ ( firstTabbable );
}
}

target.focus( {
if ( focusOnMountRef.current !== 'firstElement' ) {
node.focus( {
// When focusing newly mounted dialogs,
// the position of the popover is often not right on the first render
// This prevents the layout shifts when focusing the dialogs.
preventScroll: true,
} );

return;
}

const focusTimeout = setTimeout( () => {
const firstTabbable = focus.tabbable.find( node )[ 0 ];

if ( firstTabbable ) {
/** @type {HTMLElement} */ ( firstTabbable ).focus();
}
}, 0 );

return () => clearTimeout( focusTimeout );
Expand Down

0 comments on commit 9d311c7

Please sign in to comment.