Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow tab to be active but not selected #60573

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading