2020-01-16 14:50:48 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { __ } from '@wordpress/i18n';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import classnames from 'classnames';
|
|
|
|
import { ButtonGroup, Button } from '@wordpress/components';
|
|
|
|
import { useState, Fragment } from '@wordpress/element';
|
2020-03-26 12:39:54 +00:00
|
|
|
import { withInstanceId } from '@wordpress/compose';
|
2020-01-16 14:50:48 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import './editor.scss';
|
|
|
|
|
|
|
|
const ViewSwitcher = ( {
|
|
|
|
className,
|
|
|
|
label = __( 'View', 'woo-gutenberg-products-block' ),
|
|
|
|
views,
|
|
|
|
defaultView,
|
2020-03-10 14:40:30 +00:00
|
|
|
instanceId,
|
2020-01-16 14:50:48 +00:00
|
|
|
render,
|
|
|
|
} ) => {
|
|
|
|
const [ currentView, setCurrentView ] = useState( defaultView );
|
|
|
|
const classes = classnames( className, 'wc-block-view-switch-control' );
|
2020-03-10 14:40:30 +00:00
|
|
|
const htmlId = 'wc-block-view-switch-control-' + instanceId;
|
2020-01-16 14:50:48 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<Fragment>
|
|
|
|
<div className={ classes }>
|
|
|
|
<label
|
|
|
|
htmlFor={ htmlId }
|
|
|
|
className="wc-block-view-switch-control__label"
|
|
|
|
>
|
|
|
|
{ label + ': ' }
|
|
|
|
</label>
|
|
|
|
<ButtonGroup id={ htmlId }>
|
|
|
|
{ views.map( ( view ) => (
|
|
|
|
<Button
|
|
|
|
key={ view.value }
|
|
|
|
isPrimary={ currentView === view.value }
|
|
|
|
isLarge
|
|
|
|
aria-pressed={ currentView === view.value }
|
2020-04-06 15:36:03 +00:00
|
|
|
onMouseDown={ () => {
|
|
|
|
if ( currentView !== view.value ) {
|
|
|
|
setCurrentView( view.value );
|
|
|
|
}
|
|
|
|
} }
|
2020-01-16 14:50:48 +00:00
|
|
|
onClick={ () => {
|
2020-04-06 15:36:03 +00:00
|
|
|
if ( currentView !== view.value ) {
|
|
|
|
setCurrentView( view.value );
|
|
|
|
}
|
2020-01-16 14:50:48 +00:00
|
|
|
} }
|
|
|
|
>
|
|
|
|
{ view.name }
|
|
|
|
</Button>
|
|
|
|
) ) }
|
|
|
|
</ButtonGroup>
|
|
|
|
</div>
|
|
|
|
{ render( currentView ) }
|
|
|
|
</Fragment>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
ViewSwitcher.propTypes = {
|
|
|
|
/**
|
|
|
|
* Custom class name to add to component.
|
|
|
|
*/
|
|
|
|
className: PropTypes.string,
|
|
|
|
/**
|
|
|
|
* List of views.
|
|
|
|
*/
|
|
|
|
views: PropTypes.arrayOf(
|
|
|
|
PropTypes.shape( {
|
|
|
|
name: PropTypes.string.isRequired,
|
|
|
|
value: PropTypes.string.isRequired,
|
|
|
|
} )
|
|
|
|
).isRequired,
|
|
|
|
/**
|
|
|
|
* The default selected view.
|
|
|
|
*/
|
|
|
|
defaultView: PropTypes.string.isRequired,
|
|
|
|
/**
|
|
|
|
* Render prop for selected views.
|
|
|
|
*/
|
|
|
|
render: PropTypes.func.isRequired,
|
2020-03-10 14:40:30 +00:00
|
|
|
// from withInstanceId
|
|
|
|
instanceId: PropTypes.number.isRequired,
|
2020-01-16 14:50:48 +00:00
|
|
|
};
|
|
|
|
|
2020-03-10 14:40:30 +00:00
|
|
|
export default withInstanceId( ViewSwitcher );
|