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

Commit

Permalink
Fix broken post/page editor screens in WordPress versions earlier tha…
Browse files Browse the repository at this point in the history
…n 6.2 (#9090)

* Fix infinite loop (range error) on subscribe callback.

* Replace getEditedPostContext with getEditedPostId to retrieve the templateId from the Site Editor for 6.1.1 compatibility

---------

Co-authored-by: tjcafferkey <[email protected]>
  • Loading branch information
2 people authored and Aljullu committed Apr 19, 2023
1 parent 732ffbb commit 316ae40
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions assets/js/atomic/utils/register-block-single-product-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ import {
} from '@wordpress/blocks';
import { subscribe, select } from '@wordpress/data';

// Creating a local cache to prevent multiple registration tries.
const blocksRegistered = new Set();

function parseTemplateId( templateId: string | undefined ) {
return templateId?.split( '//' )[ 1 ];
}

export const registerBlockSingleProductTemplate = ( {
blockName,
blockMetadata,
Expand All @@ -31,9 +38,7 @@ export const registerBlockSingleProductTemplate = ( {
subscribe( () => {
const previousTemplateId = currentTemplateId;
const store = select( 'core/edit-site' );
currentTemplateId = store?.getEditedPostContext< {
templateSlug?: string;
} >()?.templateSlug;
currentTemplateId = parseTemplateId( store?.getEditedPostId() );
const hasChangedTemplate = previousTemplateId !== currentTemplateId;
const hasTemplateId = Boolean( currentTemplateId );

Expand Down Expand Up @@ -86,16 +91,21 @@ export const registerBlockSingleProductTemplate = ( {
}, 'core/edit-site' );

subscribe( () => {
const isBlockRegistered = Boolean( getBlockType( blockName ) );
const editPostStoreExists = Boolean( select( 'core/edit-post' ) );

if ( ! isBlockRegistered && editPostStoreExists ) {
const isBlockRegistered = Boolean( variationName )
? blocksRegistered.has( variationName )
: blocksRegistered.has( blockName );
// This subscribe callback could be invoked with the core/blocks store
// which would cause infinite registration loops because of the `registerBlockType` call.
// This local cache helps prevent that.
if ( ! isBlockRegistered ) {
if ( isVariationBlock ) {
blocksRegistered.add( variationName );
registerBlockVariation(
blockName,
blockSettings as BlockVariation< BlockAttributes >
);
} else {
blocksRegistered.add( blockName );
// @ts-expect-error: `registerBlockType` is typed in WordPress core
registerBlockType( blockMetadata, blockSettings );
}
Expand Down

0 comments on commit 316ae40

Please sign in to comment.