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-09-22 15:00:19 +00:00
|
|
|
import { Toolbar, ToolbarDropdownMenu } from '@wordpress/components';
|
|
|
|
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;
|
|
|
|
component: () => JSX.Element;
|
|
|
|
} => {
|
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
|
|
|
|
|
|
|
const ViewSwitcherComponent = () => (
|
2021-09-24 15:13:39 +00:00
|
|
|
<Toolbar>
|
|
|
|
<ToolbarDropdownMenu
|
|
|
|
label={ __( 'Switch view', 'woo-gutenberg-products-block' ) }
|
|
|
|
text={ currentView.label }
|
|
|
|
icon={
|
|
|
|
<Icon srcElement={ eye } style={ { marginRight: '8px' } } />
|
|
|
|
}
|
|
|
|
controls={ views.map( ( view ) => ( {
|
|
|
|
...view,
|
|
|
|
title: view.label,
|
|
|
|
onClick: () => {
|
|
|
|
setCurrentView( view );
|
|
|
|
selectBlock(
|
|
|
|
getBlock( clientId ).innerBlocks.find(
|
|
|
|
( block: { name: string } ) =>
|
|
|
|
block.name === view.view
|
|
|
|
)?.clientId || clientId
|
|
|
|
);
|
|
|
|
},
|
|
|
|
} ) ) }
|
|
|
|
/>
|
|
|
|
</Toolbar>
|
2021-09-22 15:00:19 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
currentView: currentView.view,
|
|
|
|
component: ViewSwitcherComponent,
|
|
|
|
};
|
|
|
|
};
|