Fix `useForcedLayout` to prevent breaking style book (https://github.com/woocommerce/woocommerce-blocks/pull/8243)

* Subscribe only to changes on core/block-editor

* Improve performance of useForcedLayou

This is because by the time we reach this line, innerBlocks will be an empty array (or we wouldn't make it this far) and if nextBlocks contains ANY items it will, by definition be unequal, so a length check is simpler and more performant. Also we can remove the dependence on yet another lodash function by doing it this way.

* Check if templates synced before doing it again in useForcedLayout

Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com>
This commit is contained in:
Thomas Roberts 2023-01-27 10:45:49 +00:00 committed by GitHub
parent 5fc57e9fea
commit 282bb81046
1 changed files with 6 additions and 4 deletions

View File

@ -10,7 +10,6 @@ import {
BlockInstance,
} from '@wordpress/blocks';
import type { Block, TemplateArray } from '@wordpress/blocks';
import { isEqual } from 'lodash';
import { MutableRefObject } from 'react';
interface LockableBlock extends Block {
@ -116,6 +115,7 @@ export const useForcedLayout = ( {
const registry = useRegistry();
useEffect( () => {
let templateSynced = false;
const { replaceInnerBlocks } = dispatch( 'core/block-editor' );
return registry.subscribe( () => {
const innerBlocks = registry
@ -125,12 +125,14 @@ export const useForcedLayout = ( {
// If there are NO inner blocks, sync with the given template.
if (
innerBlocks.length === 0 &&
currentDefaultTemplate.current.length > 0
currentDefaultTemplate.current.length > 0 &&
! templateSynced
) {
const nextBlocks = createBlocksFromInnerBlocksTemplate(
currentDefaultTemplate.current
);
if ( ! isEqual( nextBlocks, innerBlocks ) ) {
if ( nextBlocks.length !== 0 ) {
templateSynced = true;
replaceInnerBlocks( clientId, nextBlocks );
return;
}
@ -178,6 +180,6 @@ export const useForcedLayout = ( {
.dispatch( 'core/block-editor' )
.insertBlocks( blockConfig, insertAtPosition, clientId );
} );
} );
}, 'core/block-editor' );
}, [ clientId, registry ] );
};