2024-10-28 16:58:50 +01:00
|
|
|
import { memo, useCallback, useEffect, useState } from '@wordpress/element';
|
2024-10-24 13:54:50 +02:00
|
|
|
import { TabPanel } from '@wordpress/components';
|
2024-10-28 15:58:40 +01:00
|
|
|
import { getQuery, updateQueryString } from '@woocommerce/navigation';
|
2024-10-24 13:54:50 +02:00
|
|
|
|
2024-10-28 15:47:53 +01:00
|
|
|
const TabNavigation = ( { tabs } ) => {
|
2024-10-28 16:58:50 +01:00
|
|
|
const { panel } = getQuery();
|
2024-10-28 15:47:53 +01:00
|
|
|
|
2024-10-28 16:58:50 +01:00
|
|
|
const isValidTab = ( tabsList, checkTab ) => {
|
|
|
|
return tabsList.some( ( tab ) => tab.name === checkTab );
|
2024-10-28 15:47:53 +01:00
|
|
|
};
|
2024-10-24 13:54:50 +02:00
|
|
|
|
2024-10-28 16:58:50 +01:00
|
|
|
const getValidInitialPanel = () => {
|
|
|
|
if ( ! panel || ! isValidTab( tabs, panel ) ) {
|
|
|
|
return tabs[ 0 ].name;
|
|
|
|
}
|
|
|
|
return panel;
|
|
|
|
};
|
|
|
|
|
|
|
|
const [ activePanel, setActivePanel ] = useState( getValidInitialPanel );
|
|
|
|
|
|
|
|
const updatePanelUri = useCallback(
|
|
|
|
( tabName ) => {
|
|
|
|
if ( isValidTab( tabs, tabName ) ) {
|
|
|
|
setActivePanel( tabName );
|
|
|
|
} else {
|
|
|
|
console.warn( `Invalid tab name: ${ tabName }` );
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[ tabs ]
|
|
|
|
);
|
|
|
|
|
2024-10-28 15:58:40 +01:00
|
|
|
useEffect( () => {
|
|
|
|
updateQueryString( { panel: activePanel }, '/', getQuery() );
|
|
|
|
}, [ activePanel ] );
|
|
|
|
|
2024-10-24 13:54:50 +02:00
|
|
|
return (
|
|
|
|
<TabPanel
|
2024-10-28 15:56:11 +01:00
|
|
|
className={ `ppcp-r-tabs ${ activePanel }` }
|
|
|
|
initialTabName={ activePanel }
|
2024-10-28 15:47:53 +01:00
|
|
|
onSelect={ updatePanelUri }
|
|
|
|
tabs={ tabs }
|
2024-10-24 13:54:50 +02:00
|
|
|
>
|
2024-10-28 15:47:53 +01:00
|
|
|
{ ( tab ) => {
|
|
|
|
return tab.component || <>{ tab.title ?? tab.name }</>;
|
|
|
|
} }
|
2024-10-24 13:54:50 +02:00
|
|
|
</TabPanel>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default TabNavigation;
|