From e75c4e7b7b6585f4a084bfa029bfd6a794631cd0 Mon Sep 17 00:00:00 2001 From: Kai Hao Date: Fri, 19 May 2023 11:28:59 +0800 Subject: [PATCH] Defer focusing on then next frame --- .../src/components/list-view/block.js | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/packages/block-editor/src/components/list-view/block.js b/packages/block-editor/src/components/list-view/block.js index d31f6bf4ca70af..b44ee6e59e3f9b 100644 --- a/packages/block-editor/src/components/list-view/block.js +++ b/packages/block-editor/src/components/list-view/block.js @@ -192,21 +192,17 @@ function ListViewBlock( { return focus.focusable.find( row )[ 0 ]; }; - let focusElement = getFocusElement(); - if ( focusElement ) { - focusElement.focus(); - } else { - // The element hasn't been painted yet. Defer focusing on the next frame. - // This could happen when all blocks have been deleted and the default block - // hasn't been added to the editor yet. - window.requestAnimationFrame( () => { - focusElement = getFocusElement(); - // Ignore if the element still doesn't exist. - if ( focusElement ) { - focusElement.focus(); - } - } ); - } + // Defer focusing on the next frame so that React can update the description + // of the focused element before some Screen Readers read it. + // It also solves problem when all blocks have been deleted and the default + // block hasn't been rendered yet. + window.requestAnimationFrame( () => { + const focusElement = getFocusElement(); + // Ignore if the element doesn't exist. + if ( focusElement ) { + focusElement.focus(); + } + } ); }, [ selectBlock, treeGridElementRef ] );