From 316ae4013531dbb7d482f4fa52ffa3dcccf51c8c Mon Sep 17 00:00:00 2001 From: Darren Ethier Date: Wed, 19 Apr 2023 03:08:40 -0400 Subject: [PATCH] Fix broken post/page editor screens in WordPress versions earlier than 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 --- .../register-block-single-product-template.ts | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/assets/js/atomic/utils/register-block-single-product-template.ts b/assets/js/atomic/utils/register-block-single-product-template.ts index 8b7e492f751..9d4df9ba2e4 100644 --- a/assets/js/atomic/utils/register-block-single-product-template.ts +++ b/assets/js/atomic/utils/register-block-single-product-template.ts @@ -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, @@ -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 ); @@ -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 ); }