Skip to content

Commit

Permalink
Fix scenario where blocks have been inserted but focus has not left t…
Browse files Browse the repository at this point in the history
…he canvas (#61472)

Now that the inserter stays open when focus leaves it, an edge case can occur where blocks are inserted before the canvas has ever been focused. When that happens, focus is trying to get sent to the previously focused block, but no block has been focused.

This focuses the currently selected block when entering the canvas.

Co-authored-by: jeryj <[email protected]>
Co-authored-by: mikachan <[email protected]>
Co-authored-by: priethor <[email protected]>
  • Loading branch information
4 people authored May 9, 2024
1 parent e492737 commit 802519e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { useCallback } from '@wordpress/element';
* Internal dependencies
*/
import { store as blockEditorStore } from '../../../store';
import { unlock } from '../../../lock-unlock';

/**
* @typedef WPInserterConfig
Expand Down Expand Up @@ -86,10 +87,23 @@ function useInsertionPoint( {
insertBlocks,
showInsertionPoint,
hideInsertionPoint,
} = useDispatch( blockEditorStore );
setLastFocus,
} = unlock( useDispatch( blockEditorStore ) );

const onInsertBlocks = useCallback(
( blocks, meta, shouldForceFocusBlock = false ) => {
// When we are trying to move focus or select a new block on insert, we also
// need to clear the last focus to avoid the focus being set to the wrong block
// when tabbing back into the canvas if the block was added from outside the
// editor canvas.
if (
shouldForceFocusBlock ||
shouldFocusBlock ||
selectBlockOnInsert
) {
setLastFocus( null );
}

const selectedBlock = getSelectedBlock();

if (
Expand Down
11 changes: 10 additions & 1 deletion packages/block-editor/src/components/writing-flow/use-tab-nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,16 @@ export default function useTabNav() {
} else if ( hasMultiSelection() ) {
container.current.focus();
} else if ( getSelectedBlockClientId() ) {
getLastFocus()?.current.focus();
if ( getLastFocus()?.current ) {
getLastFocus().current.focus();
} else {
// Handles when the last focus has not been set yet, or has been cleared by new blocks being added via the inserter.
container.current
.querySelector(
`[data-block="${ getSelectedBlockClientId() }"]`
)
.focus();
}
} else {
setNavigationMode( true );

Expand Down

0 comments on commit 802519e

Please sign in to comment.