Skip to content

Commit

Permalink
Allow tab to be active but not selected
Browse files Browse the repository at this point in the history
If defaultSelectedId is undefined, it will automatically set the first tab as selected.
  • Loading branch information
jeryj committed Apr 8, 2024
1 parent 7c25dc4 commit ff034d0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
22 changes: 18 additions & 4 deletions packages/components/src/tabs/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,18 @@ function Tabs( {
orientation = 'horizontal',
onSelect,
children,
selectedOnMount = true,
selectedTabId,
}: TabsProps ) {
const instanceId = useInstanceId( Tabs, 'tabs' );

const store = Ariakit.useTabStore( {
selectOnMove,
orientation,
defaultSelectedId: defaultTabId && `${ instanceId }-${ defaultTabId }`,
defaultSelectedId:
defaultTabId && selectedOnMount
? `${ instanceId }-${ defaultTabId }`
: null,
setSelectedId: ( selectedId ) => {
const strippedDownId =
typeof selectedId === 'string'
Expand All @@ -48,7 +53,6 @@ function Tabs( {
} );

const isControlled = selectedTabId !== undefined;

const { items, selectedId, activeId } = store.useState();
const { setSelectedId, setActiveId } = store;

Expand Down Expand Up @@ -83,17 +87,25 @@ function Tabs( {
return;
}

const setInitialTab = ( tabId: string | undefined ) => {
if ( selectedOnMount ) {
setSelectedId( tabId );
} else {
setActiveId( tabId );
}
};

// If the currently selected tab is missing (i.e. removed from the DOM),
// fall back to the initial tab or the first enabled tab if there is
// one. Otherwise, no tab should be selected.
if ( ! items.find( ( item ) => item.id === selectedId ) ) {
if ( initialTab && ! initialTab.dimmed ) {
setSelectedId( initialTab?.id );
setInitialTab( initialTab?.id );
return;
}

if ( firstEnabledTab ) {
setSelectedId( firstEnabledTab.id );
setInitialTab( firstEnabledTab.id );
} else if ( tabsHavePopulated.current ) {
setSelectedId( null );
}
Expand All @@ -105,6 +117,8 @@ function Tabs( {
isControlled,
items,
selectedId,
selectedOnMount,
setActiveId,
setSelectedId,
] );

Expand Down
7 changes: 7 additions & 0 deletions packages/components/src/tabs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ export type TabsProps = {
* provided. (Controlled Mode)
*/
defaultTabId?: string;
/**
* If the initial tab should show the tab pane (be selected) or only
* show the active tab.
*
* @default true
*/
selectedOnMount?: boolean;
/**
* The function called when a tab has been selected.
* It is passed the id of the newly selected tab as an argument.
Expand Down

0 comments on commit ff034d0

Please sign in to comment.