Skip to content

Commit

Permalink
Inner Blocks: Keep inner blocks in sync with template
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Jun 20, 2018
1 parent ac9839b commit fc0bdf7
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions editor/components/inner-blocks/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { isEqual, pick } from 'lodash';
import { isEqual, pick, map } from 'lodash';
import classnames from 'classnames';

/**
Expand Down Expand Up @@ -31,15 +31,37 @@ class InnerBlocks extends Component {
this.updateNestedSettings( {
supportedBlocks: this.props.allowedBlocks,
} );
this.insertTemplateBlocks( this.props.template );

this.synchronizeBlocksWithTemplate();
}

componentDidUpdate( prevProps ) {
const { template, block } = this.props;

const hasTemplateChanged = ! isEqual( template, prevProps.template );
const isTemplateInnerBlockMismatch = (
template &&
block.innerBlocks.length !== template.length
);

if ( hasTemplateChanged || isTemplateInnerBlockMismatch ) {
this.synchronizeBlocksWithTemplate();
}
}

insertTemplateBlocks( template ) {
const { block, insertBlocks } = this.props;
if ( template && ! block.innerBlocks.length ) {
// synchronizeBlocksWithTemplate( [], template ) parses the template structure,
// and returns/creates the necessary blocks to represent it.
insertBlocks( synchronizeBlocksWithTemplate( [], template ) );
/**
* Called on mount or when a mismatch exists between the templates and
* inner blocks, synchronizes inner blocks with the template, replacing
* current blocks.
*/
synchronizeBlocksWithTemplate() {
const { template, block, replaceInnerBlocks } = this.props;
const { innerBlocks } = block;

// Synchronize with templates. If the next set differs, replace.
const nextBlocks = synchronizeBlocksWithTemplate( innerBlocks, template );
if ( ! isEqual( nextBlocks, innerBlocks ) ) {
replaceInnerBlocks( nextBlocks );
}
}

Expand Down Expand Up @@ -94,12 +116,16 @@ InnerBlocks = compose( [
};
} ),
withDispatch( ( dispatch, ownProps ) => {
const { insertBlocks, updateBlockListSettings } = dispatch( 'core/editor' );
const { uid } = ownProps;
const {
replaceBlocks,
updateBlockListSettings,
} = dispatch( 'core/editor' );
const { block, uid } = ownProps;

return {
insertBlocks( blocks ) {
dispatch( insertBlocks( blocks, undefined, uid ) );
replaceInnerBlocks( blocks ) {
const uids = map( block.innerBlocks, 'uid' );
replaceBlocks( uids, blocks );
},
updateNestedSettings( settings ) {
dispatch( updateBlockListSettings( uid, settings ) );
Expand Down

0 comments on commit fc0bdf7

Please sign in to comment.