index.js
60 lines
| 1 | import './editor.scss'; |
| 2 | import { Button, Placeholder } from '@wordpress/components'; |
| 3 | import { useContext } from '@wordpress/element'; |
| 4 | import TemplateContext from './templateContext'; |
| 5 | import { createBlocksFromInnerBlocksTemplate } from '@wordpress/blocks'; |
| 6 | import { useDispatch } from '@wordpress/data'; |
| 7 | import { __ } from '@wordpress/i18n'; |
| 8 | |
| 9 | export default function TemplateSelector( { clientId, setAttributes } ) { |
| 10 | const { label, instructions, templates } = useContext( TemplateContext ); |
| 11 | const { replaceInnerBlocks, removeBlock, selectBlock } = useDispatch( 'core/block-editor' ); |
| 12 | |
| 13 | return ( |
| 14 | <div className="wp-block"> |
| 15 | <Placeholder |
| 16 | label={ label } |
| 17 | instructions={ instructions } |
| 18 | className="gb-select-layout" |
| 19 | > |
| 20 | <div className="gb-templates-wrapper"> |
| 21 | { templates && templates.map( ( template ) => ( |
| 22 | <Button |
| 23 | key={ `template-${ template.id }` } |
| 24 | className="gb-template-selector-button" |
| 25 | onClick={ () => { |
| 26 | replaceInnerBlocks( |
| 27 | clientId, |
| 28 | createBlocksFromInnerBlocksTemplate( template.innerBlocks ) |
| 29 | ); |
| 30 | |
| 31 | if ( template.attributes ) { |
| 32 | setAttributes( template.attributes ); |
| 33 | } |
| 34 | |
| 35 | if ( 'function' === typeof template.onClick ) { |
| 36 | template.onClick(); |
| 37 | } |
| 38 | |
| 39 | selectBlock( clientId ); |
| 40 | } } |
| 41 | > |
| 42 | { template.icon }<span>{ template.label }</span> |
| 43 | </Button> |
| 44 | ) ) } |
| 45 | </div> |
| 46 | |
| 47 | <div className="gb-select-layout__actions"> |
| 48 | <Button |
| 49 | className="gblocks-cancel-placeholder is-small" |
| 50 | onClick={ () => removeBlock( clientId ) } |
| 51 | variant="secondary" |
| 52 | > |
| 53 | { __( 'Cancel', 'generateblocks' ) } |
| 54 | </Button> |
| 55 | </div> |
| 56 | </Placeholder> |
| 57 | </div> |
| 58 | ); |
| 59 | } |
| 60 |