diff --git a/projects/packages/forms/src/form-editor/index.tsx b/projects/packages/forms/src/form-editor/index.tsx index 22fa601cd66bf..d444af74e6884 100644 --- a/projects/packages/forms/src/form-editor/index.tsx +++ b/projects/packages/forms/src/form-editor/index.tsx @@ -178,6 +178,11 @@ const enforceBlockNesting = () => { let isJetpackFormEditor: boolean | null = null; let categoriesFiltered = false; +// State tracking for performance optimization +let lastRootBlockIds = ''; +let lastSelectedBlockId: string | null | undefined = null; +let isFormBlockLocked = false; + let unsubscribe: ( () => void ) | null = null; // Subscribe to editor changes to lock the form block when ready. @@ -192,9 +197,37 @@ const setupFormEditorSubscription = () => { if ( ! formBlockClientId ) { locateFormBlock(); // Locate the form block if we haven't } - enforceBlockNesting(); - enforceBlockSelection(); - lockFormBlock(); + + // Check if root blocks changed by comparing their IDs + // This detects when blocks are added, removed, or reordered at the root level + const { getBlocks } = select( 'core/block-editor' ); + const rootBlocks = getBlocks(); + const currentRootBlockIds = JSON.stringify( rootBlocks.map( b => b.clientId ) ); + + if ( currentRootBlockIds !== lastRootBlockIds ) { + lastRootBlockIds = currentRootBlockIds; + enforceBlockNesting(); + } + + // Only check selection when it changes + const { getSelectedBlockClientId } = select( 'core/block-editor' ); + const currentSelectedBlockId = getSelectedBlockClientId(); + if ( currentSelectedBlockId !== lastSelectedBlockId ) { + lastSelectedBlockId = currentSelectedBlockId; + enforceBlockSelection(); + } + + // Only try to lock the form block once + if ( ! isFormBlockLocked && formBlockClientId ) { + lockFormBlock(); + // Verify the block is now locked by checking the attributes + const { getBlock } = select( 'core/block-editor' ); + const formBlock = getBlock( formBlockClientId ); + const lock = formBlock?.attributes?.lock as { remove?: boolean; move?: boolean } | undefined; + if ( formBlock && lock?.remove && lock?.move ) { + isFormBlockLocked = true; + } + } if ( ! categoriesFiltered ) { categoriesFiltered = true; @@ -216,6 +249,10 @@ const setupFormEditorSubscription = () => { document.body.classList.remove( 'post-type-jetpack_form' ); formBlockClientId = null; // Reset the form block client ID if we are not in the Form editor anymore. categoriesFiltered = false; // Reset the flag + // Reset performance tracking state + lastRootBlockIds = ''; + lastSelectedBlockId = null; + isFormBlockLocked = false; } // Update the flag. isJetpackFormEditor = isCurrentPostTypeJetpackForm;