Skip to content

Commit

Permalink
Tabs: delay activeId updates until focus can be properly detected (#…
Browse files Browse the repository at this point in the history
…58625)

* add requestAnimationFrame

* changelog

Co-authored-by: chad1008 <[email protected]>
Co-authored-by: ciampo <[email protected]>
  • Loading branch information
3 people authored Feb 2, 2024
1 parent 5f740d2 commit b550b13
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
- `Guide`, `Modal`: Restore accent color themability ([#58098](https://github.com/WordPress/gutenberg/pull/58098)).
- `DropdownMenuV2`: Restore accent color themability ([#58130](https://github.com/WordPress/gutenberg/pull/58130)).
- `Tabs`: improve controlled mode focus handling and keyboard navigation ([#57696](https://github.com/WordPress/gutenberg/pull/57696)).
- `Tabs`: prevent internal focus from updating too early ([#58625](https://github.com/WordPress/gutenberg/pull/58625)).
- Expand theming support in the `COLORS` variable object ([#58097](https://github.com/WordPress/gutenberg/pull/58097)).

### Enhancements
Expand Down
34 changes: 18 additions & 16 deletions packages/components/src/tabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,23 +164,25 @@ function Tabs( {
return;
}

const focusedElement =
items?.[ 0 ]?.element?.ownerDocument.activeElement;

if (
! focusedElement ||
! items.some( ( item ) => focusedElement === item.element )
) {
return; // Return early if no tabs are focused.
}
requestAnimationFrame( () => {
const focusedElement =
items?.[ 0 ]?.element?.ownerDocument.activeElement;

if (
! focusedElement ||
! items.some( ( item ) => focusedElement === item.element )
) {
return; // Return early if no tabs are focused.
}

// If, after ariakit re-computes the active tab, that tab doesn't match
// the currently focused tab, then we force an update to ariakit to avoid
// any mismatches, especially when navigating to previous/next tab with
// arrow keys.
if ( activeId !== focusedElement.id ) {
setActiveId( focusedElement.id );
}
// If, after ariakit re-computes the active tab, that tab doesn't match
// the currently focused tab, then we force an update to ariakit to avoid
// any mismatches, especially when navigating to previous/next tab with
// arrow keys.
if ( activeId !== focusedElement.id ) {
setActiveId( focusedElement.id );
}
} );
}, [ activeId, isControlled, items, setActiveId ] );

const contextValue = useMemo(
Expand Down

0 comments on commit b550b13

Please sign in to comment.