Skip to content

Commit

Permalink
limit the number of inner block to 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dinhtungdu committed Sep 2, 2022
1 parent 3ba7237 commit 3d02766
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
55 changes: 41 additions & 14 deletions assets/js/blocks/filter-wrapper/edit.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,51 @@
/**
* External dependencies
*/
import { useInnerBlocksProps, useBlockProps } from '@wordpress/block-editor';
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import type { BlockEditProps } from '@wordpress/blocks';

const Edit = ( { attributes } ) => {
/**
* Internal dependencies
*/
import { Attributes } from './types';

const Edit = ( { attributes, clientId }: BlockEditProps< Attributes > ) => {
const blockProps = useBlockProps();
const innerBlocksProps = useInnerBlocksProps( blockProps, {
allowedBlocks: [ 'core/heading' ],
template: [
[ 'core/heading', { level: 3, content: attributes.heading || '' } ],
[
`woocommerce/${ attributes.filterType }`,
{
heading: '',
},
],
],

const innerBlockCount = useSelect( ( select ) => {
const currentBlock = select( 'core/block-editor' ).getBlock( clientId );
if ( ! currentBlock ) {
return 0;
}
return currentBlock.innerBlocks.length;
} );

return <div { ...innerBlocksProps } />;
return (
<div { ...blockProps }>
<InnerBlocks
allowedBlocks={ [ 'core/heading' ] }
template={ [
[
'core/heading',
{ level: 3, content: attributes.heading || '' },
],
[
`woocommerce/${ attributes.filterType }`,
{
heading: '',
},
],
] }
renderAppender={ () => {
if ( innerBlockCount < 2 ) {
return <InnerBlocks.ButtonBlockAppender />;
}
return null;
} }
/>
</div>
);
};

export default Edit;
4 changes: 4 additions & 0 deletions assets/js/blocks/filter-wrapper/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Attributes {
heading: string;
filterType: string;
}

0 comments on commit 3d02766

Please sign in to comment.