index.js
43 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 | |
| 8 | export default function TemplateSelector( { clientId, setAttributes } ) { |
| 9 | const { label, instructions, templates } = useContext( TemplateContext ); |
| 10 | const { replaceInnerBlocks } = useDispatch( 'core/block-editor' ); |
| 11 | |
| 12 | return ( |
| 13 | <div className="wp-block"> |
| 14 | <Placeholder |
| 15 | label={ label } |
| 16 | instructions={ instructions } |
| 17 | className="gb-select-layout" |
| 18 | > |
| 19 | <div className="gb-templates-wrapper"> |
| 20 | { templates && templates.map( ( template ) => ( |
| 21 | <Button |
| 22 | key={ `template-${ template.id }` } |
| 23 | className="gb-template-selector-button" |
| 24 | onClick={ () => { |
| 25 | replaceInnerBlocks( |
| 26 | clientId, |
| 27 | createBlocksFromInnerBlocksTemplate( template.innerBlocks ) |
| 28 | ); |
| 29 | |
| 30 | if ( template.attributes ) { |
| 31 | setAttributes( template.attributes ); |
| 32 | } |
| 33 | } } |
| 34 | > |
| 35 | { template.icon }<span>{ template.label }</span> |
| 36 | </Button> |
| 37 | ) ) } |
| 38 | </div> |
| 39 | </Placeholder> |
| 40 | </div> |
| 41 | ); |
| 42 | } |
| 43 |