TemplateSelector.jsx
68 lines
| 1 | import './editor.scss'; |
| 2 | import { Button, Placeholder } from '@wordpress/components'; |
| 3 | import { createBlocksFromInnerBlocksTemplate } from '@wordpress/blocks'; |
| 4 | import { useDispatch } from '@wordpress/data'; |
| 5 | import { __ } from '@wordpress/i18n'; |
| 6 | import { store as blockEditorStore } from '@wordpress/block-editor'; |
| 7 | |
| 8 | export function TemplateSelector( { |
| 9 | clientId, |
| 10 | setAttributes, |
| 11 | label, |
| 12 | instructions, |
| 13 | templates, |
| 14 | } ) { |
| 15 | const { replaceInnerBlocks, removeBlock, selectBlock } = useDispatch( blockEditorStore ); |
| 16 | |
| 17 | return ( |
| 18 | <div className="wp-block"> |
| 19 | <Placeholder |
| 20 | label={ label } |
| 21 | instructions={ instructions } |
| 22 | className="gb-select-variation" |
| 23 | > |
| 24 | <div className="gb-variation-selector"> |
| 25 | { templates && templates.map( ( template ) => ( |
| 26 | <Button |
| 27 | key={ `template-${ template.id }` } |
| 28 | className="gb-variation-selector__button" |
| 29 | onClick={ () => { |
| 30 | replaceInnerBlocks( |
| 31 | clientId, |
| 32 | createBlocksFromInnerBlocksTemplate( template.innerBlocks ) |
| 33 | ); |
| 34 | |
| 35 | if ( template.attributes ) { |
| 36 | setAttributes( template.attributes ); |
| 37 | } |
| 38 | |
| 39 | if ( 'function' === typeof template.onClick ) { |
| 40 | template.onClick(); |
| 41 | } |
| 42 | |
| 43 | setAttributes( { |
| 44 | showTemplateSelector: false, |
| 45 | } ); |
| 46 | |
| 47 | selectBlock( clientId ); |
| 48 | } } |
| 49 | > |
| 50 | { template.icon }<span>{ template.label }</span> |
| 51 | </Button> |
| 52 | ) ) } |
| 53 | </div> |
| 54 | |
| 55 | <div className="gb-select-variation__actions"> |
| 56 | <Button |
| 57 | className="is-small" |
| 58 | onClick={ () => removeBlock( clientId ) } |
| 59 | variant="secondary" |
| 60 | > |
| 61 | { __( 'Cancel', 'generateblocks' ) } |
| 62 | </Button> |
| 63 | </div> |
| 64 | </Placeholder> |
| 65 | </div> |
| 66 | ); |
| 67 | } |
| 68 |