Skip to content

Commit

Permalink
Set initially selected tab on render
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuatf committed Mar 10, 2023
1 parent 988177b commit 20fc28a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function TabButton( {
const { onClick } = fillProps;
return (
<Button
key={ id }
className={ classes }
onClick={ () => onClick( id ) }
>
Expand Down
48 changes: 44 additions & 4 deletions packages/js/product-editor/src/components/tabs/tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,60 @@
/**
* External dependencies
*/
import {
createElement,
Fragment,
useEffect,
useState,
} from '@wordpress/element';
import { ReactElement } from 'react';
import { Slot } from '@wordpress/components';
import { createElement } from '@wordpress/element';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore No types for this exist yet.
// eslint-disable-next-line @woocommerce/dependency-group
import { navigateTo, getNewPath } from '@woocommerce/navigation';

/**
* Internal dependencies
*/
import { TABS_SLOT_NAME } from './constants';

type TabsProps = {
onChange: ( tabId: string ) => void;
onChange: ( tabId: string | null ) => void;
};

export type TabsFillProps = {
onClick: ( tabId: string ) => void;
};

export function Tabs( { onChange = () => {} }: TabsProps ) {
const [ selected, setSelected ] = useState< string | null >( null );
function onClick( tabId: string ) {
onChange( tabId );
window.document.documentElement.scrollTop = 0;
navigateTo( {
url: getNewPath( { tab: tabId } ),
} );
setSelected( tabId );
}

useEffect( () => {
onChange( selected );
}, [ selected ] );

function maybeSetSelected( fills: readonly ( readonly ReactElement[] )[] ) {
if ( selected ) {
return;
}

for ( let i = 0; i < fills.length; i++ ) {
if ( fills[ i ][ 0 ].props.disabled ) {
continue;
}
// Remove the `.$` prefix on keys. E.g., .$key => key
const tabId = fills[ i ][ 0 ].key?.toString().slice( 2 ) || null;
setSelected( tabId );
return;
}
}

return (
Expand All @@ -31,7 +66,12 @@ export function Tabs( { onChange = () => {} }: TabsProps ) {
} as TabsFillProps
}
name={ TABS_SLOT_NAME }
/>
>
{ ( fills ) => {
maybeSetSelected( fills );
return <>{ fills }</>;
} }
</Slot>
</div>
);
}

0 comments on commit 20fc28a

Please sign in to comment.