From da03081e5e5fec8345620070b356c0c8f4c0d682 Mon Sep 17 00:00:00 2001 From: Ella <4710635+ellatrix@users.noreply.github.com> Date: Thu, 15 Dec 2022 16:28:43 +0200 Subject: [PATCH] DOM: fix findNext/Previous tabbable if target is not in findFocusable list (#46580) --- packages/dom/src/tabbable.js | 37 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/packages/dom/src/tabbable.js b/packages/dom/src/tabbable.js index 66ae1ee7d4fd46..25bc81f2154582 100644 --- a/packages/dom/src/tabbable.js +++ b/packages/dom/src/tabbable.js @@ -159,18 +159,15 @@ export function find( context ) { * @return {Element|undefined} Preceding tabbable element. */ export function findPrevious( element ) { - const focusables = findFocusable( element.ownerDocument.body ); - const index = focusables.indexOf( element ); - - if ( index === -1 ) { - return undefined; - } - - // Remove all focusables after and including `element`. - focusables.length = index; - - const tabbable = filterTabbable( focusables ); - return tabbable[ tabbable.length - 1 ]; + return filterTabbable( findFocusable( element.ownerDocument.body ) ) + .reverse() + .find( ( focusable ) => { + return ( + // eslint-disable-next-line no-bitwise + element.compareDocumentPosition( focusable ) & + element.DOCUMENT_POSITION_PRECEDING + ); + } ); } /** @@ -182,11 +179,13 @@ export function findPrevious( element ) { * @return {Element|undefined} Next tabbable element. */ export function findNext( element ) { - const focusables = findFocusable( element.ownerDocument.body ); - const index = focusables.indexOf( element ); - - // Remove all focusables before and including `element`. - const remaining = focusables.slice( index + 1 ); - - return filterTabbable( remaining )[ 0 ]; + return filterTabbable( findFocusable( element.ownerDocument.body ) ).find( + ( focusable ) => { + return ( + // eslint-disable-next-line no-bitwise + element.compareDocumentPosition( focusable ) & + element.DOCUMENT_POSITION_FOLLOWING + ); + } + ); }