Skip to content

Commit

Permalink
use items to find active element, instead of a ref
Browse files Browse the repository at this point in the history
  • Loading branch information
chad1008 committed Dec 1, 2023
1 parent 19c8cd4 commit ea1e323
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions packages/components/src/tabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,6 @@ function Tabs( {
const { items, selectedId } = store.useState();
const { setSelectedId, move } = store;

const tabsRef = useRef< HTMLDivElement >( null );
const tabsHasFocus =
!! tabsRef.current?.ownerDocument.activeElement &&
items
.map( ( item ) => item.id )
.includes( tabsRef.current?.ownerDocument.activeElement.id );

// Keep track of whether tabs have been populated. This is used to prevent
// certain effects from firing too early while tab data and relevant
// variables are undefined during the initial render.
Expand Down Expand Up @@ -167,14 +160,20 @@ function Tabs( {
if ( ! isControlled || ! selectOnMove ) {
return;
}
const currentItem = items.find( ( item ) => item.id === selectedId );
const activeElement = currentItem?.element?.ownerDocument.activeElement;
const tabsHasFocus = items.some( ( item ) => {
return activeElement && activeElement === item.element;
} );

if (
activeElement &&
tabsHasFocus &&
selectedId !== tabsRef.current?.ownerDocument.activeElement.id
selectedId !== activeElement.id
) {
move( selectedId );
}
}, [ isControlled, move, selectOnMove, selectedId, tabsHasFocus ] );
}, [ isControlled, items, move, selectOnMove, selectedId ] );

const contextValue = useMemo(
() => ( {
Expand All @@ -185,11 +184,9 @@ function Tabs( {
);

return (
<div ref={ tabsRef }>
<TabsContext.Provider value={ contextValue }>
{ children }
</TabsContext.Provider>
</div>
<TabsContext.Provider value={ contextValue }>
{ children }
</TabsContext.Provider>
);
}

Expand Down

0 comments on commit ea1e323

Please sign in to comment.