Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 40 additions & 3 deletions projects/packages/forms/src/form-editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand All @@ -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;
Expand Down