2021-09-22 15:00:19 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { __ } from '@wordpress/i18n';
|
|
|
|
import { useState } from '@wordpress/element';
|
2021-09-24 15:13:39 +00:00
|
|
|
import { useDispatch, select } from '@wordpress/data';
|
2021-10-27 15:41:57 +00:00
|
|
|
import { ToolbarGroup, ToolbarDropdownMenu } from '@wordpress/components';
|
2021-09-22 15:00:19 +00:00
|
|
|
import { Icon, eye } from '@woocommerce/icons';
|
2021-09-24 15:13:39 +00:00
|
|
|
import { store as blockEditorStore } from '@wordpress/block-editor';
|
2021-09-22 15:00:19 +00:00
|
|
|
|
|
|
|
interface View {
|
|
|
|
view: string;
|
|
|
|
label: string;
|
|
|
|
icon: string | JSX.Element;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useViewSwitcher = (
|
2021-09-24 15:13:39 +00:00
|
|
|
clientId: string,
|
2021-09-22 15:00:19 +00:00
|
|
|
views: View[]
|
|
|
|
): {
|
|
|
|
currentView: string;
|
2021-10-27 15:41:57 +00:00
|
|
|
component: JSX.Element;
|
2021-09-22 15:00:19 +00:00
|
|
|
} => {
|
2021-09-24 15:13:39 +00:00
|
|
|
const initialView = views[ 0 ];
|
2021-09-22 15:00:19 +00:00
|
|
|
const [ currentView, setCurrentView ] = useState( initialView );
|
2021-09-24 15:13:39 +00:00
|
|
|
const { selectBlock } = useDispatch( 'core/block-editor' );
|
|
|
|
const { getBlock } = select( blockEditorStore );
|
2021-09-22 15:00:19 +00:00
|
|
|
|
2021-10-27 15:41:57 +00:00
|
|
|
const ViewSwitcherComponent = (
|
|
|
|
<ToolbarGroup>
|
2021-09-24 15:13:39 +00:00
|
|
|
<ToolbarDropdownMenu
|
|
|
|
label={ __( 'Switch view', 'woo-gutenberg-products-block' ) }
|
|
|
|
text={ currentView.label }
|
|
|
|
icon={
|
|
|
|
<Icon srcElement={ eye } style={ { marginRight: '8px' } } />
|
|
|
|
}
|
|
|
|
controls={ views.map( ( view ) => ( {
|
|
|
|
...view,
|
2021-11-09 13:18:55 +00:00
|
|
|
title: <span>{ view.label }</span>,
|
2021-10-27 15:41:57 +00:00
|
|
|
isActive: view.view === currentView.view,
|
2021-09-24 15:13:39 +00:00
|
|
|
onClick: () => {
|
|
|
|
setCurrentView( view );
|
|
|
|
selectBlock(
|
|
|
|
getBlock( clientId ).innerBlocks.find(
|
|
|
|
( block: { name: string } ) =>
|
|
|
|
block.name === view.view
|
|
|
|
)?.clientId || clientId
|
|
|
|
);
|
|
|
|
},
|
|
|
|
} ) ) }
|
|
|
|
/>
|
2021-10-27 15:41:57 +00:00
|
|
|
</ToolbarGroup>
|
2021-09-22 15:00:19 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
currentView: currentView.view,
|
|
|
|
component: ViewSwitcherComponent,
|
|
|
|
};
|
|
|
|
};
|