From 7168ff418ef50340946f34e837bfdc6b952fc043 Mon Sep 17 00:00:00 2001 From: Thomas Roberts <5656702+opr@users.noreply.github.com> Date: Fri, 27 Jan 2023 10:45:49 +0000 Subject: [PATCH] Fix `useForcedLayout` to prevent breaking style book (#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> --- .../blocks/cart-checkout-shared/use-forced-layout.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/assets/js/blocks/cart-checkout-shared/use-forced-layout.ts b/assets/js/blocks/cart-checkout-shared/use-forced-layout.ts index 72183567f0c..72068736f5f 100644 --- a/assets/js/blocks/cart-checkout-shared/use-forced-layout.ts +++ b/assets/js/blocks/cart-checkout-shared/use-forced-layout.ts @@ -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 ] ); };