Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Fix useForcedLayout to prevent breaking style book (#8243)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
opr and wavvves authored Jan 27, 2023
1 parent c5597cb commit 7168ff4
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions assets/js/blocks/cart-checkout-shared/use-forced-layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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;
}
Expand Down Expand Up @@ -178,6 +180,6 @@ export const useForcedLayout = ( {
.dispatch( 'core/block-editor' )
.insertBlocks( blockConfig, insertAtPosition, clientId );
} );
} );
}, 'core/block-editor' );
}, [ clientId, registry ] );
};

0 comments on commit 7168ff4

Please sign in to comment.