From f29ee5622b9e1a2eb24095a32a91d1a414a93fe4 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Wed, 9 Sep 2026 13:09:06 -0500
Subject: [PATCH 01/33] Tests: cover selection ownership when controllers share
an entity
Adds failing coverage for #79096 and regression guards for the behaviour
a fix must not break.
Two blocks rendering the same entity (two Navigation blocks on one menu,
two Post Content instances) each clone that entity's blocks privately but
build identical external-to-internal ID maps. In useBlockSync's
restoreSelection, ownership is decided by whether the external ID appears
in that map, which every such controller answers true to, so an edit in
one instance is followed by the other claiming the selection.
Failing (the defects):
- editing a menu item leaves the caret and selection in the edited block
- undoing a menu edit returns the caret to the block that made it
- undo moves the caret back into the Navigation block when the caret has
moved outside it
- typing in one Post Content instance leaves the caret and selection in
that instance
The last two are a second, separate gap: a nested controller records its
selection against its own entity, but the only consumer of a recorded
selection reads the root record, so cross-controller undo never restores
the caret.
Passing (guards for existing behaviour):
- undo restores the caret to the undone block when another block is
selected
- selection is restored after returning from a template part
The duplicate tests record every selection entering the other instance
rather than asserting on the final selection: the steal is often
momentary, and the canvas scrolls as soon as it happens even when the
selection recovers. A final-state assertion passed 4 runs in 5.
The Navigation spec is adapted from
https://github.com/WordPress/gutenberg/pull/79929.
Also makes Template Part Focus mode activate its theme per test; the
theme was restored after each test but only activated in beforeAll, so
any second test in the file ran against the wrong theme.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
---
.../various/post-content-focus-mode.spec.js | 117 +++++++++
test/e2e/specs/editor/various/undo.spec.js | 37 +++
.../navigation-selection-sync.spec.js | 240 ++++++++++++++++++
.../template-part-focus-mode.spec.js | 40 ++-
4 files changed, 433 insertions(+), 1 deletion(-)
create mode 100644 test/e2e/specs/site-editor/navigation-selection-sync.spec.js
diff --git a/test/e2e/specs/editor/various/post-content-focus-mode.spec.js b/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
index ffd1f3ff33e00f..c937da27040293 100644
--- a/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
+++ b/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
@@ -367,6 +367,123 @@ test.describe( 'Post Content focus mode', () => {
} );
} );
} );
+
+ // The same post is rendered by two Post Content blocks, which are inner
+ // block controllers sharing one entity.
+ // See https://github.com/WordPress/gutenberg/issues/79096.
+ test.describe( 'duplicate Post Content instances', () => {
+ test.beforeAll( async ( { requestUtils } ) => {
+ await requestUtils.createTemplate( 'wp_template_part', {
+ slug: 'content-area',
+ title: 'Content Area',
+ content:
+ '',
+ } );
+
+ // One Post Content at the template root, another nested inside a
+ // template part, both rendering the same post.
+ await requestUtils.createTemplate( 'wp_template', {
+ slug: 'singular',
+ title: 'Singular',
+ content: [
+ '',
+ '',
+ '',
+ ].join( '\n' ),
+ } );
+ } );
+
+ test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.deleteAllTemplates( 'wp_template' );
+ await requestUtils.deleteAllTemplates( 'wp_template_part' );
+ } );
+
+ test( 'typing in one instance leaves the caret and selection in that instance', async ( {
+ admin,
+ editor,
+ page,
+ postContentFocusMode,
+ } ) => {
+ await admin.createNewPost();
+ await editor.insertBlock( {
+ name: 'core/paragraph',
+ attributes: { content: 'Shared' },
+ } );
+ await postContentFocusMode.enableShowTemplate();
+
+ // Identify the Post Content at the template root, as opposed to
+ // the one nested inside the template part.
+ const { rootParagraph, nestedPostContent } = await page.evaluate(
+ () => {
+ const {
+ getBlocksByName,
+ getBlockOrder,
+ getBlockParents,
+ getBlockName,
+ } = window.wp.data.select( 'core/block-editor' );
+ const isNested = ( clientId ) =>
+ getBlockParents( clientId ).some(
+ ( parent ) =>
+ getBlockName( parent ) === 'core/template-part'
+ );
+ const all = getBlocksByName( 'core/post-content' );
+ const root = all.find(
+ ( clientId ) => ! isNested( clientId )
+ );
+ return {
+ rootParagraph: getBlockOrder( root )[ 0 ],
+ nestedPostContent: all.find( isNested ),
+ };
+ }
+ );
+
+ // Clear the selection so no block toolbar overlaps the paragraph.
+ await page.evaluate( () => {
+ window.wp.data
+ .dispatch( 'core/block-editor' )
+ .clearSelectedBlock();
+ } );
+ await editor.canvas
+ .locator( `[data-block="${ rootParagraph }"]` )
+ .click();
+
+ // Record every time the selection enters the nested instance.
+ // A steal is momentary — the canvas scrolls as soon as it
+ // happens, even if the selection later recovers — so asserting
+ // on the final selection alone misses it.
+ await page.evaluate( ( nestedClientId ) => {
+ const { getSelectedBlockClientId, getBlockParents } =
+ window.wp.data.select( 'core/block-editor' );
+ window.__selectionsInNestedInstance = [];
+ window.wp.data.subscribe( () => {
+ const selected = getSelectedBlockClientId();
+ if (
+ selected &&
+ getBlockParents( selected ).includes(
+ nestedClientId
+ ) &&
+ window.__selectionsInNestedInstance.at( -1 ) !==
+ selected
+ ) {
+ window.__selectionsInNestedInstance.push( selected );
+ }
+ } );
+ }, nestedPostContent );
+
+ await page.keyboard.press( 'End' );
+ await page.keyboard.type( ' edited' );
+
+ // The edit reaches both instances, since they render one post.
+ await expect(
+ editor.canvas.getByText( 'Shared edited' )
+ ).toHaveCount( 2 );
+
+ // …and the selection never enters the nested instance.
+ expect(
+ await page.evaluate( () => window.__selectionsInNestedInstance )
+ ).toEqual( [] );
+ } );
+ } );
} );
class PostContentFocusMode {
diff --git a/test/e2e/specs/editor/various/undo.spec.js b/test/e2e/specs/editor/various/undo.spec.js
index 2a32af0f99f4b2..0278322171a87e 100644
--- a/test/e2e/specs/editor/various/undo.spec.js
+++ b/test/e2e/specs/editor/various/undo.spec.js
@@ -83,6 +83,43 @@ test.describe( 'undo', () => {
} );
} );
+ test( 'should restore the caret to the undone block when another block is selected', async ( {
+ editor,
+ page,
+ pageUtils,
+ undoUtils,
+ } ) => {
+ await editor.canvas
+ .locator( 'role=document[name="Add default block"i]' )
+ .click();
+ await page.keyboard.type( 'first' );
+ await page.keyboard.press( 'Enter' );
+ await page.keyboard.type( 'second' );
+
+ await expect.poll( editor.getBlocks ).toMatchObject( [
+ { name: 'core/paragraph', attributes: { content: 'first' } },
+ { name: 'core/paragraph', attributes: { content: 'second' } },
+ ] );
+
+ // Move the selection away from the block that is about to be undone.
+ // The undone block still exists afterwards, so the store would happily
+ // keep this selection across the block reset — the selection recorded
+ // with the undo level has to win over it.
+ await editor.canvas.locator( 'text=first' ).click();
+
+ await pageUtils.pressKeys( 'primary+z' );
+
+ await expect.poll( editor.getBlocks ).toMatchObject( [
+ { name: 'core/paragraph', attributes: { content: 'first' } },
+ { name: 'core/paragraph', attributes: { content: '' } },
+ ] );
+ await expect.poll( undoUtils.getSelection ).toEqual( {
+ blockIndex: 1,
+ startOffset: 0,
+ endOffset: 0,
+ } );
+ } );
+
test( 'should undo typing after non input change', async ( {
editor,
page,
diff --git a/test/e2e/specs/site-editor/navigation-selection-sync.spec.js b/test/e2e/specs/site-editor/navigation-selection-sync.spec.js
new file mode 100644
index 00000000000000..1e2b3ca5a7291b
--- /dev/null
+++ b/test/e2e/specs/site-editor/navigation-selection-sync.spec.js
@@ -0,0 +1,240 @@
+const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' );
+
+const MENU_CONTENT =
+ '';
+
+/**
+ * Reports which Navigation block, if any, contains the current selection.
+ *
+ * Navigation blocks are inner block controllers: each keeps its own private
+ * clones of the menu's blocks, so the selected client ID only identifies an
+ * instance once it is resolved back to the Navigation block containing it.
+ *
+ * @param {Object} page Playwright page.
+ * @return {Promise} Index of the containing Navigation block in
+ * document order, or null when the selection is
+ * outside every Navigation block.
+ */
+function getSelectedNavigationIndex( page ) {
+ return page.evaluate( () => {
+ const { getSelectedBlockClientId, getBlocksByName, getBlockParents } =
+ window.wp.data.select( 'core/block-editor' );
+ const selected = getSelectedBlockClientId();
+ if ( ! selected ) {
+ return null;
+ }
+ const navigationBlocks = getBlocksByName( 'core/navigation' );
+ const parents = getBlockParents( selected );
+ const index = navigationBlocks.findIndex(
+ ( clientId ) =>
+ clientId === selected || parents.includes( clientId )
+ );
+ return index === -1 ? null : index;
+ } );
+}
+
+// Two Navigation blocks referencing the same menu are synced from the same
+// wp_navigation entity, so editing one makes the other re-sync. Adapted from
+// https://github.com/WordPress/gutenberg/pull/79929.
+// See https://github.com/WordPress/gutenberg/issues/79096.
+test.describe( 'Duplicate Navigation blocks using the same menu', () => {
+ test.beforeAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'emptytheme' );
+ } );
+
+ test.beforeEach( async ( { admin, editor, requestUtils } ) => {
+ const { id } = await requestUtils.createNavigationMenu( {
+ title: 'Shared menu',
+ content: MENU_CONTENT,
+ } );
+
+ await admin.visitSiteEditor( {
+ postId: 'emptytheme//index',
+ postType: 'wp_template',
+ canvas: 'edit',
+ } );
+
+ await editor.insertBlock( {
+ name: 'core/navigation',
+ attributes: { ref: id },
+ } );
+ // Enough space between the two that a selection jump scrolls the canvas.
+ await editor.insertBlock( {
+ name: 'core/spacer',
+ attributes: { height: '2000px' },
+ } );
+ await editor.insertBlock( {
+ name: 'core/navigation',
+ attributes: { ref: id },
+ } );
+
+ await expect(
+ editor.canvas.locator(
+ 'role=textbox[name="Navigation link text"i]'
+ )
+ ).toHaveCount( 2 );
+ } );
+
+ test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'twentytwentyone' );
+ await requestUtils.deleteAllMenus();
+ } );
+
+ test( 'editing a menu item leaves the caret and selection in the edited block', async ( {
+ editor,
+ page,
+ } ) => {
+ const labels = editor.canvas.locator(
+ 'role=textbox[name="Navigation link text"i]'
+ );
+
+ // A content overlay covers an unselected Navigation block, so the
+ // block is clicked before its link label.
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Navigation' } )
+ .first()
+ .click();
+ await labels.first().click();
+ await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 0 );
+
+ // Record every time the selection enters the duplicate. A steal is
+ // momentary — the canvas scrolls as soon as it happens, even if the
+ // selection later recovers — so asserting on the final selection
+ // alone can miss it.
+ await page.evaluate( () => {
+ const {
+ getSelectedBlockClientId,
+ getBlocksByName,
+ getBlockParents,
+ } = window.wp.data.select( 'core/block-editor' );
+ const duplicate = getBlocksByName( 'core/navigation' ).at( -1 );
+ window.__selectionsInDuplicate = [];
+ window.wp.data.subscribe( () => {
+ const selected = getSelectedBlockClientId();
+ if (
+ selected &&
+ ( selected === duplicate ||
+ getBlockParents( selected ).includes( duplicate ) ) &&
+ window.__selectionsInDuplicate.at( -1 ) !== selected
+ ) {
+ window.__selectionsInDuplicate.push( selected );
+ }
+ } );
+ } );
+
+ // Type a character in the middle of the label. The edit syncs into
+ // both blocks; the selection must not follow it into the duplicate.
+ await page.keyboard.press( 'End' );
+ await page.keyboard.press( 'ArrowLeft' );
+ await page.keyboard.type( 'X' );
+
+ await expect( labels.first() ).toHaveText( 'IteXm' );
+ await expect( labels.last() ).toHaveText( 'IteXm' );
+ expect(
+ await page.evaluate( () => window.__selectionsInDuplicate )
+ ).toEqual( [] );
+ expect( await getSelectedNavigationIndex( page ) ).toBe( 0 );
+ } );
+
+ test( 'undoing a menu edit returns the caret to the block that made it', async ( {
+ editor,
+ page,
+ pageUtils,
+ } ) => {
+ const labels = editor.canvas.locator(
+ 'role=textbox[name="Navigation link text"i]'
+ );
+
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Navigation' } )
+ .first()
+ .click();
+ await labels.first().click();
+ await page.keyboard.press( 'End' );
+ await page.keyboard.type( 'ZZ' );
+ await expect( labels.first() ).toHaveText( 'ItemZZ' );
+
+ // Move the caret into the duplicate before undoing.
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Navigation' } )
+ .last()
+ .click();
+ await labels.last().click();
+ await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 1 );
+
+ await pageUtils.pressKeys( 'primary+z' );
+
+ await expect( labels.first() ).toHaveText( 'Item' );
+ // The edit was made in the first block, so that is where the undone
+ // content — and the caret — belongs.
+ await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 0 );
+ } );
+} );
+
+// A Navigation block is an inner block controller, so an edit inside it is
+// recorded against the wp_navigation entity rather than the template.
+test.describe( 'Undo of an edit made inside a Navigation block', () => {
+ test.beforeAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'emptytheme' );
+ } );
+
+ test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'twentytwentyone' );
+ await requestUtils.deleteAllMenus();
+ } );
+
+ test( 'moves the caret back into the Navigation block when the caret has moved outside it', async ( {
+ admin,
+ editor,
+ page,
+ pageUtils,
+ requestUtils,
+ } ) => {
+ const { id } = await requestUtils.createNavigationMenu( {
+ title: 'Menu',
+ content: MENU_CONTENT,
+ } );
+
+ await admin.visitSiteEditor( {
+ postId: 'emptytheme//index',
+ postType: 'wp_template',
+ canvas: 'edit',
+ } );
+
+ await editor.insertBlock( {
+ name: 'core/navigation',
+ attributes: { ref: id },
+ } );
+ await editor.insertBlock( {
+ name: 'core/paragraph',
+ attributes: { content: 'Outside paragraph' },
+ } );
+
+ const label = editor.canvas
+ .locator( 'role=textbox[name="Navigation link text"i]' )
+ .first();
+ await expect( label ).toBeVisible();
+
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Navigation' } )
+ .first()
+ .click();
+ await label.click();
+ await page.keyboard.press( 'End' );
+ await page.keyboard.type( 'ZZ' );
+ await expect( label ).toHaveText( 'ItemZZ' );
+
+ // Park the caret outside the Navigation block.
+ await editor.canvas.getByText( 'Outside paragraph' ).click();
+ await expect
+ .poll( () => getSelectedNavigationIndex( page ) )
+ .toBeNull();
+
+ await pageUtils.pressKeys( 'primary+z' );
+
+ await expect( label ).toHaveText( 'Item' );
+ // The undone edit is inside the Navigation block, which may be off
+ // screen, so the caret follows it there.
+ await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 0 );
+ } );
+} );
diff --git a/test/e2e/specs/site-editor/template-part-focus-mode.spec.js b/test/e2e/specs/site-editor/template-part-focus-mode.spec.js
index 174989d5edd661..03c994a784cecf 100644
--- a/test/e2e/specs/site-editor/template-part-focus-mode.spec.js
+++ b/test/e2e/specs/site-editor/template-part-focus-mode.spec.js
@@ -1,7 +1,9 @@
const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' );
test.describe( 'Template Part Focus mode', () => {
- test.beforeAll( async ( { requestUtils } ) => {
+ // The theme is restored after every test, so each test activates the one
+ // it needs rather than relying on a single beforeAll.
+ test.beforeEach( async ( { requestUtils } ) => {
await requestUtils.activateTheme( 'twentytwentyfour' );
} );
@@ -44,4 +46,40 @@ test.describe( 'Template Part Focus mode', () => {
await expect( page.locator( 'h1' ) ).toContainText( 'Blog Home' );
await expect( page.locator( 'h1' ) ).toContainText( 'Template' );
} );
+
+ test( 'Should restore the selected block after returning from the template part.', async ( {
+ admin,
+ page,
+ editor,
+ } ) => {
+ await admin.visitAdminPage( 'site-editor.php?canvas=edit' );
+ await editor.setPreferences( 'core/edit-site', {
+ welcomeGuide: false,
+ } );
+
+ const templatePart = editor.canvas.getByRole( 'document', {
+ name: 'Header',
+ } );
+ await templatePart.click();
+
+ const getSelectedBlockName = () =>
+ page.evaluate( () => {
+ const { getSelectedBlockClientId, getBlockName } =
+ window.wp.data.select( 'core/block-editor' );
+ const clientId = getSelectedBlockClientId();
+ return clientId ? getBlockName( clientId ) : null;
+ } );
+
+ await expect.poll( getSelectedBlockName ).toBe( 'core/template-part' );
+
+ await editor.clickBlockToolbarButton( 'Edit original' );
+ await expect( page.locator( 'h1' ) ).toContainText( 'Header' );
+
+ await page.getByRole( 'button', { name: 'Back' } ).click();
+ await expect( page.locator( 'h1' ) ).toContainText( 'Blog Home' );
+
+ // The template part that was being edited is selected again, rather
+ // than the selection being dropped or landing on another block.
+ await expect.poll( getSelectedBlockName ).toBe( 'core/template-part' );
+ } );
} );
From 6a82ba8f1bcffcb9c14ed873b9770dc453c65087 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Wed, 9 Sep 2026 14:38:07 -0500
Subject: [PATCH 02/33] Block Editor: Stop duplicate controllers from taking
the selection
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Fixes #79096.
Two blocks can render the same entity — two Navigation blocks using one
menu, a Post Content block at a template root and another inside a
template part. Each is an inner block controller holding private clones,
but both clone the same blocks, so both build the same
external-to-internal ID mapping and both recognise the entity's
selection as their own.
An edit in one instance therefore reaches the other as an incoming
entity change. That controller re-clones and calls restoreSelection,
which converts the external ID to its own copy and dispatches
resetSelection. The canvas scrolled to the duplicate and the caret left
the block being typed in, reliably enough to reorder characters.
Guard the restoreSelection call instead: when the selection already sits
inside a different inner block controller, this sync is a consequence of
an edit made there, so leave it alone. The controller that made the edit
takes the outgoing branch and never reaches this code, so a selection
held by another controller is always one that has been dealt with. A
selection held by the root block list belongs to no controller and still
restores as before, which is what keeps entity navigation and undo
working.
The guard sits at the call site rather than inside restoreSelection: the
question is about the sync that just happened, not about the selection
object, and restoreSelection keeps its existing contract.
This reuses getBlockParents and areInnerBlocksControlled, already
selected in this hook, so there is no new store state, no new action or
selector, and nothing persisted into entity data or collaborative state.
Revives the approach in #79422 by @ramonjd, which asked the same question
with the same selectors and was closed by its author in favour of #79097.
Two differences: the check moved to the call site, and the WeakMap
remembering the last controller to hold the selection is left out.
Also removes two tests added with the failing coverage. They asserted
that undo returns the caret to the block whose edit was undone. Trunk
does not do that for any nested entity, with or without duplicates: a
controller records its selection against its own entity, but the only
consumer of a recorded selection reads the root record. That is a
separate, pre-existing gap and out of scope here.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
---
.../src/components/provider/use-block-sync.ts | 52 ++++++++-
.../navigation-selection-sync.spec.js | 102 ------------------
2 files changed, 47 insertions(+), 107 deletions(-)
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index a06e0b008ef1b1..f0f53c9575345e 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -158,8 +158,14 @@ export default function useBlockSync( {
setHasControlledInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
} = registry.dispatch( blockEditorStore );
- const { getBlockName, getBlocks, getSelectionStart, getSelectionEnd } =
- registry.select( blockEditorStore );
+ const {
+ getBlockName,
+ getBlocks,
+ getSelectionStart,
+ getSelectionEnd,
+ getBlockParents,
+ areInnerBlocksControlled,
+ } = registry.select( blockEditorStore );
const pendingChangesRef = useRef< {
incoming: Block[] | null;
@@ -236,6 +242,36 @@ export default function useBlockSync( {
}
};
+ // Whether the block-editor's current selection sits inside a *different*
+ // inner block controller.
+ //
+ // Several controllers can render one entity — two Navigation blocks using
+ // the same menu, two Post Content blocks showing the same post. Each keeps
+ // private clones of that entity's blocks, but they all map the same
+ // external IDs, so each of them recognises the entity's selection as its
+ // own. A controller that finds the selection already sitting in another
+ // controller is therefore looking at a selection that belongs to a copy
+ // other than itself.
+ //
+ // The root controller is never one of several instances, and a selection
+ // held by the root block list belongs to no controller at all.
+ const isSelectionHeldByAnotherController = () => {
+ if ( clientId === null ) {
+ return false;
+ }
+ const currentStartClientId = getSelectionStart()?.clientId;
+ if ( ! currentStartClientId ) {
+ return false;
+ }
+ const owningController = getBlockParents(
+ currentStartClientId,
+ true
+ ).find( ( parentClientId ) =>
+ areInnerBlocksControlled( parentClientId )
+ );
+ return !! owningController && owningController !== clientId;
+ };
+
const setControlledBlocks = () => {
if ( ! controlledBlocks ) {
return;
@@ -356,7 +392,15 @@ export default function useBlockSync( {
// because dispatching resetSelection between keystrokes breaks
// the isUpdatingSameBlockAttribute chain and creates per-
// character undo levels.
- restoreSelection();
+ //
+ // An edit made in another block rendering this same entity also
+ // arrives here as an external change, and that one must not move
+ // the selection: the caret is in the block being edited, and
+ // restoring would drag it — and the canvas — into this copy.
+ // See https://github.com/WordPress/gutenberg/issues/79096.
+ if ( ! isSelectionHeldByAnotherController() ) {
+ restoreSelection();
+ }
}
}, [ controlledBlocks, clientId ] );
@@ -366,8 +410,6 @@ export default function useBlockSync( {
isLastBlockChangePersistent,
__unstableGetLastBlockChangeHistoryMode,
__unstableIsLastBlockChangeIgnored,
- areInnerBlocksControlled,
- getBlockParents,
} = registry.select( blockEditorStore );
let blocks = getBlocks( clientId );
diff --git a/test/e2e/specs/site-editor/navigation-selection-sync.spec.js b/test/e2e/specs/site-editor/navigation-selection-sync.spec.js
index 1e2b3ca5a7291b..7eeb4936e8a81a 100644
--- a/test/e2e/specs/site-editor/navigation-selection-sync.spec.js
+++ b/test/e2e/specs/site-editor/navigation-selection-sync.spec.js
@@ -135,106 +135,4 @@ test.describe( 'Duplicate Navigation blocks using the same menu', () => {
).toEqual( [] );
expect( await getSelectedNavigationIndex( page ) ).toBe( 0 );
} );
-
- test( 'undoing a menu edit returns the caret to the block that made it', async ( {
- editor,
- page,
- pageUtils,
- } ) => {
- const labels = editor.canvas.locator(
- 'role=textbox[name="Navigation link text"i]'
- );
-
- await editor.canvas
- .getByRole( 'document', { name: 'Block: Navigation' } )
- .first()
- .click();
- await labels.first().click();
- await page.keyboard.press( 'End' );
- await page.keyboard.type( 'ZZ' );
- await expect( labels.first() ).toHaveText( 'ItemZZ' );
-
- // Move the caret into the duplicate before undoing.
- await editor.canvas
- .getByRole( 'document', { name: 'Block: Navigation' } )
- .last()
- .click();
- await labels.last().click();
- await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 1 );
-
- await pageUtils.pressKeys( 'primary+z' );
-
- await expect( labels.first() ).toHaveText( 'Item' );
- // The edit was made in the first block, so that is where the undone
- // content — and the caret — belongs.
- await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 0 );
- } );
-} );
-
-// A Navigation block is an inner block controller, so an edit inside it is
-// recorded against the wp_navigation entity rather than the template.
-test.describe( 'Undo of an edit made inside a Navigation block', () => {
- test.beforeAll( async ( { requestUtils } ) => {
- await requestUtils.activateTheme( 'emptytheme' );
- } );
-
- test.afterAll( async ( { requestUtils } ) => {
- await requestUtils.activateTheme( 'twentytwentyone' );
- await requestUtils.deleteAllMenus();
- } );
-
- test( 'moves the caret back into the Navigation block when the caret has moved outside it', async ( {
- admin,
- editor,
- page,
- pageUtils,
- requestUtils,
- } ) => {
- const { id } = await requestUtils.createNavigationMenu( {
- title: 'Menu',
- content: MENU_CONTENT,
- } );
-
- await admin.visitSiteEditor( {
- postId: 'emptytheme//index',
- postType: 'wp_template',
- canvas: 'edit',
- } );
-
- await editor.insertBlock( {
- name: 'core/navigation',
- attributes: { ref: id },
- } );
- await editor.insertBlock( {
- name: 'core/paragraph',
- attributes: { content: 'Outside paragraph' },
- } );
-
- const label = editor.canvas
- .locator( 'role=textbox[name="Navigation link text"i]' )
- .first();
- await expect( label ).toBeVisible();
-
- await editor.canvas
- .getByRole( 'document', { name: 'Block: Navigation' } )
- .first()
- .click();
- await label.click();
- await page.keyboard.press( 'End' );
- await page.keyboard.type( 'ZZ' );
- await expect( label ).toHaveText( 'ItemZZ' );
-
- // Park the caret outside the Navigation block.
- await editor.canvas.getByText( 'Outside paragraph' ).click();
- await expect
- .poll( () => getSelectedNavigationIndex( page ) )
- .toBeNull();
-
- await pageUtils.pressKeys( 'primary+z' );
-
- await expect( label ).toHaveText( 'Item' );
- // The undone edit is inside the Navigation block, which may be off
- // screen, so the caret follows it there.
- await expect.poll( () => getSelectedNavigationIndex( page ) ).toBe( 0 );
- } );
} );
From 9eef576e57b9d3502321391fa84dbc72c7bf34a6 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Wed, 9 Sep 2026 15:46:35 -0500
Subject: [PATCH 03/33] Block Editor: Find the selection's controller without
walking to the root
getBlockParents collects every ancestor up to the document root and is
memoized on state.blocks.parents, which changes on each re-clone, so the
memo never hits on this path. The answer is almost always the immediate
parent, since a menu item sits directly inside its Navigation block.
Walk up with getBlockRootClientId instead, stopping at the first
controller, and short-circuit on the controller's own mapping when the
selected block is one of its clones.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
---
.../src/components/provider/use-block-sync.ts | 33 +++++++++++++++----
1 file changed, 26 insertions(+), 7 deletions(-)
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index f0f53c9575345e..a06afe7ff42a83 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -164,6 +164,7 @@ export default function useBlockSync( {
getSelectionStart,
getSelectionEnd,
getBlockParents,
+ getBlockRootClientId,
areInnerBlocksControlled,
} = registry.select( blockEditorStore );
@@ -259,17 +260,35 @@ export default function useBlockSync( {
if ( clientId === null ) {
return false;
}
+
const currentStartClientId = getSelectionStart()?.clientId;
if ( ! currentStartClientId ) {
return false;
}
- const owningController = getBlockParents(
- currentStartClientId,
- true
- ).find( ( parentClientId ) =>
- areInnerBlocksControlled( parentClientId )
- );
- return !! owningController && owningController !== clientId;
+
+ // One of our own clones, so the selection is already where it
+ // belongs and there is no need to walk the tree for it.
+ if (
+ idMappingRef.current.internalToExternal.has( currentStartClientId )
+ ) {
+ return false;
+ }
+
+ // Otherwise find the controller the selected block belongs to. Only
+ // the nearest one matters, and it is usually the immediate parent — a
+ // menu item sits directly inside its Navigation block — so walk up and
+ // stop at the first controller rather than collecting every ancestor.
+ let parentClientId = getBlockRootClientId( currentStartClientId );
+ while ( parentClientId ) {
+ if ( areInnerBlocksControlled( parentClientId ) ) {
+ return parentClientId !== clientId;
+ }
+ parentClientId = getBlockRootClientId( parentClientId );
+ }
+
+ // The selection is in the root block list, which belongs to no
+ // controller.
+ return false;
};
const setControlledBlocks = () => {
From e8c5b61e6275f18c7d34fa8788e56e1e7c440350 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Wed, 9 Sep 2026 16:18:59 -0500
Subject: [PATCH 04/33] Block Editor: Put each comment with the code it
explains
The existing comment describes restoreSelection, so it belongs inside the
guard rather than above it. Also records why the guard is checked after
the blocks are set.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
---
.../src/components/provider/use-block-sync.ts | 23 ++++++++++---------
1 file changed, 12 insertions(+), 11 deletions(-)
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index a06afe7ff42a83..505fe42a9ea32a 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -405,19 +405,20 @@ export default function useBlockSync( {
pendingChangesRef.current.outgoing = [];
setControlledBlocks();
- // Restore selection from context if it targets our scope.
- // Only done when blocks were reset from an external source
- // (undo/redo, entity navigation) — NOT for outgoing changes,
- // because dispatching resetSelection between keystrokes breaks
- // the isUpdatingSameBlockAttribute chain and creates per-
- // character undo levels.
- //
- // An edit made in another block rendering this same entity also
- // arrives here as an external change, and that one must not move
- // the selection: the caret is in the block being edited, and
- // restoring would drag it — and the canvas — into this copy.
+ // An edit made in another block rendering this same entity
+ // arrives here as an external change too, but that one must not
+ // move the selection: the caret is in the block being edited,
+ // and restoring would drag it — and the canvas — into this copy.
+ // Checked after the blocks are set, so that a selection this
+ // controller just destroyed by re-cloning still gets repaired.
// See https://github.com/WordPress/gutenberg/issues/79096.
if ( ! isSelectionHeldByAnotherController() ) {
+ // Restore selection from context if it targets our scope.
+ // Only done when blocks were reset from an external source
+ // (undo/redo, entity navigation) — NOT for outgoing changes,
+ // because dispatching resetSelection between keystrokes
+ // breaks the isUpdatingSameBlockAttribute chain and creates
+ // per-character undo levels.
restoreSelection();
}
}
From 84bbbb4b73f6be2d4ba1701aeab76f4818b84e27 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Wed, 9 Sep 2026 16:31:45 -0500
Subject: [PATCH 05/33] Tests: cover undo moving the caret within one
controlled container
Per review on #82706: check that an undo can still move the selection
from one block of a controlled container to another. Post Content is an
inner block controller, so two of its blocks exercise that path.
Passes identically with the guard enabled and disabled, five runs each.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_017RtcwXT84eF6zLdQXK9e1W
---
.../various/post-content-focus-mode.spec.js | 75 +++++++++++++++++++
1 file changed, 75 insertions(+)
diff --git a/test/e2e/specs/editor/various/post-content-focus-mode.spec.js b/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
index c937da27040293..e121f91ef4fc50 100644
--- a/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
+++ b/test/e2e/specs/editor/various/post-content-focus-mode.spec.js
@@ -116,6 +116,81 @@ test.describe( 'Post Content focus mode', () => {
} );
} );
+ // Post Content is an inner block controller, so an undo that moves the
+ // caret between two of its blocks crosses the same controlled container.
+ // See https://github.com/WordPress/gutenberg/pull/82706.
+ test( 'undo moves the caret between blocks of the same Post Content', async ( {
+ admin,
+ editor,
+ page,
+ pageUtils,
+ postContentFocusMode,
+ } ) => {
+ await admin.createNewPost();
+ await editor.insertBlock( {
+ name: 'core/paragraph',
+ attributes: { content: 'First' },
+ } );
+ await editor.insertBlock( {
+ name: 'core/paragraph',
+ attributes: { content: 'Second' },
+ } );
+ await postContentFocusMode.enableShowTemplate();
+
+ const postContentText = () =>
+ page.evaluate( () => {
+ const { getBlocksByName, getBlockOrder, getBlockAttributes } =
+ window.wp.data.select( 'core/block-editor' );
+ const [ postContent ] = getBlocksByName( 'core/post-content' );
+ return getBlockOrder( postContent ).map( ( clientId ) =>
+ getBlockAttributes( clientId )?.content?.toString?.()
+ );
+ } );
+
+ // Edit the first block, then the second, leaving the caret in the
+ // second.
+ await editor.selectBlocks( editor.canvas.getByText( 'First' ) );
+ await page.keyboard.press( 'End' );
+ await page.keyboard.type( '-a' );
+ await expect.poll( postContentText ).toEqual( [ 'First-a', 'Second' ] );
+
+ await editor.selectBlocks( editor.canvas.getByText( 'Second' ) );
+ await page.keyboard.press( 'End' );
+ await page.keyboard.type( '-b' );
+ await expect
+ .poll( postContentText )
+ .toEqual( [ 'First-a', 'Second-b' ] );
+
+ // Typing coalesces into undo levels on a timer, so the number of
+ // levels the two edits produce is not fixed. Undo until the first
+ // block's edit is gone rather than assuming a count.
+ let reverted = false;
+ for ( let i = 0; i < 8 && ! reverted; i++ ) {
+ await pageUtils.pressKeys( 'primary+z' );
+ try {
+ await expect
+ .poll( postContentText, { timeout: 1000 } )
+ .toEqual( [ 'First', 'Second' ] );
+ reverted = true;
+ } catch {
+ // Not there yet; undo again.
+ }
+ }
+ expect( reverted ).toBe( true );
+
+ // The caret was in the second block and has to follow the undo to
+ // the first one.
+ const selected = await page.evaluate( () => {
+ const { getSelectedBlockClientId, getBlockAttributes } =
+ window.wp.data.select( 'core/block-editor' );
+ const clientId = getSelectedBlockClientId();
+ return clientId
+ ? getBlockAttributes( clientId )?.content?.toString?.()
+ : null;
+ } );
+ expect( selected ).toBe( 'First' );
+ } );
+
// Check for regressions of https://github.com/WordPress/gutenberg/issues/76101.
test.describe( 'post content inside a template part', () => {
test.beforeAll( async ( { requestUtils } ) => {
From 6dd564d8ada50bd4a16912ceebed88217e614a4d Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Thu, 10 Sep 2026 14:05:15 -0500
Subject: [PATCH 06/33] Tests: cover typing and undo in a container duplicated
from one entity
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Two Template Parts pointing at the same entity are both inner block
controllers synced from one record. These pin the two behaviours that
matter when typing into one of them.
The first passes: every typed character survives, in both copies. That is
the behaviour the preceding commits on this branch fixed, and it
regresses silently, so it is worth holding down.
The second fails. One undo removes a single character rather than the
whole typed run, because each keystroke makes the *duplicate* run
setControlledBlocks() and dispatch replaceInnerBlocks. That action lands
between keystrokes and breaks the isUpdatingSameBlockAttribute merge
chain, so every character becomes its own undo level. Marking the change
not-persistent does not help: any intervening action on another block
breaks the chain regardless. restoreSelection is not involved — the
existing guard keeps it from firing during typing.
Both tests type at a human cadence on purpose. An instant
keyboard.type() outruns the re-sync and passes, so the delay is
load-bearing rather than incidental.
Co-Authored-By: Claude Opus 5 (1M context)
Claude-Session: https://claude.ai/code/session_01UTowaGipHSMef7nUQAnnJJ
---
test/e2e/specs/site-editor/undo.spec.js | 103 ++++++++++++++++++++++++
1 file changed, 103 insertions(+)
diff --git a/test/e2e/specs/site-editor/undo.spec.js b/test/e2e/specs/site-editor/undo.spec.js
index 37d4539d0ef453..b4ef2b9b905f6d 100644
--- a/test/e2e/specs/site-editor/undo.spec.js
+++ b/test/e2e/specs/site-editor/undo.spec.js
@@ -41,3 +41,106 @@ test.describe( 'undo', () => {
).not.toHaveCount( 0 );
} );
} );
+
+const CONTAINER_CONTENT =
+ 'Some container content
' +
+ 'More container content
';
+
+// Two Template Parts pointing at one entity are both inner block controllers
+// synced from the same record, so an edit in one re-syncs the other. That
+// re-sync is what these tests pin down: it must not split a typed run into
+// separate undo levels, nor strand the caret where the container was entered.
+test.describe( 'undo in a container duplicated from one entity', () => {
+ test.beforeAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'emptytheme' );
+ } );
+
+ test.beforeEach( async ( { admin, editor, requestUtils } ) => {
+ await requestUtils.createTemplate( 'wp_template_part', {
+ slug: 'content-test',
+ title: 'Content Test',
+ content: CONTAINER_CONTENT,
+ } );
+
+ await admin.visitSiteEditor( {
+ postId: 'emptytheme//index',
+ postType: 'wp_template',
+ canvas: 'edit',
+ } );
+
+ for ( let i = 0; i < 2; i++ ) {
+ await editor.insertBlock( {
+ name: 'core/template-part',
+ attributes: { slug: 'content-test', theme: 'emptytheme' },
+ } );
+ }
+
+ await expect(
+ editor.canvas.getByText( 'Some container content' )
+ ).toHaveCount( 2 );
+ } );
+
+ test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.deleteAllTemplates( 'wp_template_part' );
+ await requestUtils.activateTheme( 'twentytwentyone' );
+ } );
+
+ test( 'keeps every typed character in a duplicated container', async ( {
+ editor,
+ page,
+ pageUtils,
+ } ) => {
+ const edited = editor.canvas
+ .getByText( 'Some container content' )
+ .first();
+ const duplicate = editor.canvas
+ .getByText( 'Some container content' )
+ .last();
+
+ // A block overlay covers an unselected Template Part, so the container
+ // is clicked before the paragraph inside it.
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Content Test' } )
+ .first()
+ .click();
+ await edited.click();
+ await pageUtils.pressKeys( 'End' );
+ // Typed at a human cadence on purpose: an instant `type()` outruns the
+ // re-sync between the two containers and hides the defect.
+ await page.keyboard.type( 'Hello', { delay: 150 } );
+
+ // Each keystroke re-syncs the other container. That must not discard
+ // the keystrokes that follow it.
+ await expect( edited ).toHaveText( 'Some container contentHello' );
+ await expect( duplicate ).toHaveText( 'Some container contentHello' );
+ } );
+
+ test( 'removes the entire typed run when undoing inside a duplicated container', async ( {
+ editor,
+ page,
+ pageUtils,
+ } ) => {
+ const edited = editor.canvas
+ .getByText( 'Some container content' )
+ .first();
+
+ // A block overlay covers an unselected Template Part, so the container
+ // is clicked before the paragraph inside it.
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Content Test' } )
+ .first()
+ .click();
+ await edited.click();
+ await pageUtils.pressKeys( 'End' );
+ // Typed at a human cadence on purpose: an instant `type()` outruns the
+ // re-sync between the two containers and hides the defect.
+ await page.keyboard.type( 'Hello', { delay: 150 } );
+
+ await expect( edited ).toHaveText( 'Some container contentHello' );
+
+ await pageUtils.pressKeys( 'primary+z' );
+
+ // One undo level for one typed run, not one level per character.
+ await expect( edited ).toHaveText( 'Some container content' );
+ } );
+} );
From d2496395567db098e52c99d9f3679f6e3b0c7b06 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Mon, 14 Sep 2026 09:57:16 -0500
Subject: [PATCH 07/33] Block Editor: Keep a typing run across ignored changes
to other blocks
Two containers rendering one entity, such as two Template Parts on the
same slug, are both inner block controllers. Typing in one edits the
entity, and the other mirrors the edit onto its own clones as a change
ignored by history. The persistence reducer still recorded that change
as the last action, so the next keystroke no longer looked like a
continuation of the run and was filed as a new undo level. Undo then
removed one character at a time.
A history-ignored change that leaves the last-updated block's entry and
attributes untouched now keeps the previous last action, so the run
continues across it. A change that does replace that block, such as the
reset after an undo, still starts a new level.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
---
packages/block-editor/src/store/reducer.ts | 41 ++++-
.../block-editor/src/store/test/reducer.ts | 155 ++++++++++++++++++
2 files changed, 195 insertions(+), 1 deletion(-)
diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts
index d4b24339321a70..fe83bbe0f739f5 100644
--- a/packages/block-editor/src/store/reducer.ts
+++ b/packages/block-editor/src/store/reducer.ts
@@ -220,6 +220,33 @@ function getAttributeUpdates(
return updates;
}
+/**
+ * Returns true if the blocks that the given action updated are the same in
+ * both states, or false otherwise. Only attribute updates are considered.
+ *
+ * @param state Previous state.
+ * @param nextState Next state.
+ * @param lastAction Previously dispatched action.
+ *
+ * @return Whether the updated blocks are untouched.
+ */
+function leavesBlocksUntouched(
+ state: BlocksState | undefined,
+ nextState: BlocksState,
+ lastAction: Action | undefined
+) {
+ return (
+ lastAction?.type === 'UPDATE_BLOCK_ATTRIBUTES' &&
+ lastAction.clientIds.every(
+ ( clientId ) =>
+ nextState.byClientId.get( clientId ) ===
+ state?.byClientId.get( clientId ) &&
+ nextState.attributes.get( clientId ) ===
+ state?.attributes.get( clientId )
+ )
+ );
+}
+
function updateBlockTreeForBlocks( state: BlocksState, blocks: Block[] ) {
const treeToUpdate = state.tree;
const stack = [ ...blocks ];
@@ -490,7 +517,19 @@ function withPersistentBlockChange( reducer: Reducer< BlocksState > ) {
// In comparing against the previous action, consider only those which
// would have qualified as one which would have been ignored or not
// have resulted in a changed state.
- lastAction = action;
+ //
+ // A change that history ignores and that leaves the blocks of the
+ // previous action untouched is invisible to the undo stack, so it
+ // must not split a typing run into separate undo levels either. A
+ // container re-cloning its blocks while the same entity is typed
+ // into elsewhere is such a change. One that does replace those
+ // blocks, like a reset after an undo, still starts a new level.
+ if (
+ pendingHistoryMode !== 'ignore' ||
+ ! leavesBlocksUntouched( state, nextState, lastAction )
+ ) {
+ lastAction = action;
+ }
if ( pendingHistoryMode === 'ignore' ) {
return {
diff --git a/packages/block-editor/src/store/test/reducer.ts b/packages/block-editor/src/store/test/reducer.ts
index 5a77d0a2798f46..99852fd5f90a0e 100644
--- a/packages/block-editor/src/store/test/reducer.ts
+++ b/packages/block-editor/src/store/test/reducer.ts
@@ -2680,6 +2680,161 @@ describe( 'state', () => {
).toBeUndefined();
} );
+ it( 'keeps a typing run non-persistent across an ignored change to other blocks', () => {
+ let state = deepFreeze(
+ blocks( undefined, {
+ type: 'RESET_BLOCKS',
+ blocks: [
+ partial< Block >( {
+ clientId: 'kumquat',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ partial< Block >( {
+ clientId: 'container',
+ attributes: {},
+ innerBlocks: [
+ partial< Block >( {
+ clientId: 'clone-1',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ ],
+ } ),
+ ],
+ } )
+ );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'a' },
+ } );
+ expect( state.isPersistentChange ).toBe( true );
+
+ // Another controller re-clones its own blocks between
+ // two keystrokes, as a container duplicated from the
+ // same entity does. That change is ignored by history,
+ // so it must not split the typing run either.
+ state = blocks( state, {
+ type: 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT',
+ history: 'ignore',
+ } );
+ state = blocks( state, {
+ type: 'REPLACE_INNER_BLOCKS',
+ rootClientId: 'container',
+ blocks: [
+ partial< Block >( {
+ clientId: 'clone-2',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ ],
+ } );
+ expect( state.isPersistentChange ).toBe( false );
+ expect( state.lastBlockChangeHistoryMode ).toBe( 'ignore' );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'ab' },
+ } );
+ expect( state.isPersistentChange ).toBe( false );
+ expect( state.lastBlockChangeHistoryMode ).toBeUndefined();
+ } );
+
+ it( 'keeps a typing run non-persistent across an ignored attribute update to another block', () => {
+ let state = deepFreeze(
+ blocks( undefined, {
+ type: 'RESET_BLOCKS',
+ blocks: [
+ partial< Block >( {
+ clientId: 'kumquat',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ partial< Block >( {
+ clientId: 'clone',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ ],
+ } )
+ );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'a' },
+ } );
+ expect( state.isPersistentChange ).toBe( true );
+
+ // A container duplicated from the same entity mirrors the
+ // keystroke onto its own clone, as a change ignored by
+ // history.
+ state = blocks( state, {
+ type: 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT',
+ history: 'ignore',
+ } );
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'clone' ],
+ attributes: { clone: { content: 'a' } },
+ options: { uniqueByBlock: true },
+ } );
+ expect( state.isPersistentChange ).toBe( false );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'ab' },
+ } );
+ expect( state.isPersistentChange ).toBe( false );
+ } );
+
+ it( 'starts a persistent change after an ignored change replaces the edited block', () => {
+ const initialBlocks = [
+ partial< Block >( {
+ clientId: 'kumquat',
+ attributes: {},
+ innerBlocks: [],
+ } ),
+ ];
+ let state = deepFreeze(
+ blocks( undefined, {
+ type: 'RESET_BLOCKS',
+ blocks: initialBlocks,
+ } )
+ );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'a' },
+ } );
+ expect( state.isPersistentChange ).toBe( true );
+
+ // An undo resets the blocks from the entity. The block
+ // keeps its client ID, but it is a different block now,
+ // so typing into it again starts a new undo level.
+ state = blocks( state, {
+ type: 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT',
+ history: 'ignore',
+ } );
+ state = blocks( state, {
+ type: 'RESET_BLOCKS',
+ blocks: initialBlocks,
+ } );
+ expect( state.isPersistentChange ).toBe( false );
+
+ state = blocks( state, {
+ type: 'UPDATE_BLOCK_ATTRIBUTES',
+ clientIds: [ 'kumquat' ],
+ attributes: { content: 'a' },
+ } );
+ expect( state.isPersistentChange ).toBe( true );
+ } );
+
it( 'should retain reference for same state, same persistence', () => {
const original = deepFreeze(
blocks( undefined, {
From 2c908b3f517addaf8a546a4d12ddfacc9adc2ea5 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Mon, 14 Sep 2026 09:57:25 -0500
Subject: [PATCH 08/33] Block Editor: Update a controller's clones in place
when only attributes change
An inner block controller rebuilt its whole subtree whenever its entity
changed: it cleared the ID mapping, cloned every block under a fresh
client ID and replaced the inner blocks. With two containers rendering
one entity, that happened on every keystroke made in the other one. Each
keystroke tore down and remounted every block and rich text in the
duplicate, briefly left it without a selection, and dispatched a block
replacement into the store between two keystrokes.
When the incoming value has the same structure as the current clones,
the same external IDs in the same order, the controller now applies the
changed attributes to the existing clones as one history-ignored update.
The mapping, the mounted components and the selection stay valid. A
structural change still takes the rebuild path.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
---
packages/block-editor/CHANGELOG.md | 1 +
.../test/use-block-sync.jsdom.test.tsx | 93 +++++++++++++++++++
.../src/components/provider/use-block-sync.ts | 78 ++++++++++++++++
3 files changed, 172 insertions(+)
diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md
index 85f0eb75913545..b7ad2db2a4d0f0 100644
--- a/packages/block-editor/CHANGELOG.md
+++ b/packages/block-editor/CHANGELOG.md
@@ -43,6 +43,7 @@
- Inspector: Show the Styles tab for blocks whose only style controls are in the `background`, `filter` or `elements` groups ([#87403](https://github.com/WordPress/gutenberg/pull/87403)).
- RichText: Hide the slash inserter in a block that cannot be removed, instead of throwing when an item is picked ([#87152](https://github.com/WordPress/gutenberg/pull/87152)).
- Block toolbar: Return focus to the block with Tab or Escape after a toolbar action replaces the block's element, such as changing a heading's level ([#87360](https://github.com/WordPress/gutenberg/pull/87360)).
+- Inner block controllers rendering one entity, such as two Template Parts on the same slug or two Navigation blocks on the same menu, no longer split typing in one of them into an undo level per character, lose keystrokes, or move the selection into the other one. A controller now updates its existing clones in place when only attributes changed, and a history-ignored change to other blocks no longer ends a typing run ([#82706](https://github.com/WordPress/gutenberg/pull/82706)).
### Internal
diff --git a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
index 7f288862a11969..4f31ac7d07de20 100644
--- a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
+++ b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
@@ -684,4 +684,97 @@ describe( 'useBlockSync hook', () => {
// The internal IDs should be different from the external IDs (due to cloning)
expect( replacedBlocks[ 0 ].clientId ).not.toBe( originalClientId );
} );
+
+ describe( 'controlled value with the same structure', () => {
+ const block = ( attributes ) => ( {
+ name: 'test/test-block',
+ clientId: 'external',
+ innerBlocks: [
+ {
+ name: 'test/test-block',
+ clientId: 'external-inner',
+ innerBlocks: [],
+ attributes: { foo: 10 },
+ },
+ ],
+ attributes,
+ } );
+
+ function renderController() {
+ let registry;
+ const onChange = vi.fn();
+ const onInput = vi.fn();
+ const view = render(
+ {
+ registry = reg;
+ } }
+ value={ [ block( { foo: 1 } ) ] }
+ onChange={ onChange }
+ onInput={ onInput }
+ />
+ );
+ const getClones = () =>
+ registry.select( blockEditorStore ).getBlocks( 'controller' );
+ return { view, getClones, onChange, onInput };
+ }
+
+ it( 'updates the existing clones in place instead of re-cloning', () => {
+ const replaceInnerBlocks = vi.spyOn(
+ blockEditorActions,
+ 'replaceInnerBlocks'
+ );
+ const { view, getClones, onChange, onInput } = renderController();
+ const [ clone ] = getClones();
+ replaceInnerBlocks.mockClear();
+
+ view.rerender(
+
+ );
+
+ expect( replaceInnerBlocks ).not.toHaveBeenCalled();
+ const [ updated ] = getClones();
+ // Same clone, so nothing holding its client ID is invalidated.
+ expect( updated.clientId ).toBe( clone.clientId );
+ expect( updated.attributes ).toEqual( { foo: 2 } );
+ expect( updated.innerBlocks[ 0 ].clientId ).toBe(
+ clone.innerBlocks[ 0 ].clientId
+ );
+ // The change came from the entity, so it is not reported back.
+ expect( onChange ).not.toHaveBeenCalled();
+ expect( onInput ).not.toHaveBeenCalled();
+ } );
+
+ it( 'still re-clones when the structure changes', () => {
+ const replaceInnerBlocks = vi.spyOn(
+ blockEditorActions,
+ 'replaceInnerBlocks'
+ );
+ const { view, onChange, onInput } = renderController();
+ replaceInnerBlocks.mockClear();
+
+ const added = {
+ name: 'test/test-block',
+ clientId: 'external-added',
+ innerBlocks: [],
+ attributes: {},
+ };
+ view.rerender(
+
+ );
+
+ expect( replaceInnerBlocks ).toHaveBeenCalledTimes( 1 );
+ } );
+ } );
} );
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index 505fe42a9ea32a..3bdc2a0bb615a9 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -156,6 +156,7 @@ export default function useBlockSync( {
resetSelection,
replaceInnerBlocks,
setHasControlledInnerBlocks,
+ updateBlockAttributes,
__unstableMarkNextChangeAsNotPersistent,
} = registry.dispatch( blockEditorStore );
const {
@@ -291,6 +292,54 @@ export default function useBlockSync( {
return false;
};
+ // Whether the controlled value has the same structure as the clones
+ // already in the store: the same external IDs in the same order, all
+ // the way down. A nested controller owns its own inner blocks, so those
+ // are left to it.
+ const hasSameStructure = ( blocks, clones ) =>
+ blocks.length === clones.length &&
+ blocks.every( ( block, index ) => {
+ const clone = clones[ index ];
+ return (
+ idMappingRef.current.internalToExternal.get(
+ clone.clientId
+ ) === block.clientId &&
+ block.name === clone.name &&
+ ( areInnerBlocksControlled( clone.clientId ) ||
+ hasSameStructure( block.innerBlocks, clone.innerBlocks ) )
+ );
+ } );
+
+ // Collects, per clone, the attributes whose values differ from the
+ // controlled value. Only called once the structures are known to match.
+ const collectAttributeChanges = ( blocks, clones, changes = {} ) => {
+ blocks.forEach( ( block, index ) => {
+ const clone = clones[ index ];
+ const changed = {};
+ let hasChanged = false;
+ for ( const key of new Set( [
+ ...Object.keys( block.attributes ),
+ ...Object.keys( clone.attributes ),
+ ] ) ) {
+ if ( block.attributes[ key ] !== clone.attributes[ key ] ) {
+ changed[ key ] = block.attributes[ key ];
+ hasChanged = true;
+ }
+ }
+ if ( hasChanged ) {
+ changes[ clone.clientId ] = changed;
+ }
+ if ( ! areInnerBlocksControlled( clone.clientId ) ) {
+ collectAttributeChanges(
+ block.innerBlocks,
+ clone.innerBlocks,
+ changes
+ );
+ }
+ } );
+ return changes;
+ };
+
const setControlledBlocks = () => {
if ( ! controlledBlocks ) {
return;
@@ -300,6 +349,35 @@ export default function useBlockSync( {
// controlled inner blocks when the change was caused by an entity,
// and so it would already be persisted.
if ( clientId ) {
+ // A value with the same structure as the current clones differs
+ // in attributes at most, as when the same entity is typed into
+ // through another container. Update the clones in place: the
+ // mapping, the mounted components and the selection all stay
+ // valid, and nothing is torn down between two keystrokes.
+ const clones = getBlocks( clientId );
+ if (
+ areInnerBlocksControlled( clientId ) &&
+ hasSameStructure( controlledBlocks, clones )
+ ) {
+ const changes = collectAttributeChanges(
+ controlledBlocks,
+ clones
+ );
+ const changedClientIds = Object.keys( changes );
+ if ( changedClientIds.length ) {
+ if ( subscribedRef.current ) {
+ pendingChangesRef.current.incoming = clones;
+ }
+ __unstableMarkNextChangeAsNotPersistent( {
+ history: 'ignore',
+ } );
+ updateBlockAttributes( changedClientIds, changes, {
+ uniqueByBlock: true,
+ } );
+ }
+ return;
+ }
+
// Batch so that the controlled flag and block replacement
// are applied atomically — subscribers see a consistent state.
registry.batch( () => {
From d770b73b5ff478a14dd5f8052074a0bb82fedfe0 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Mon, 14 Sep 2026 09:57:30 -0500
Subject: [PATCH 09/33] Tests: Pin undo across containers of different entities
An undo that reverts an edit in one Template Part while the caret sits in
another should bring the caret back to the reverted block, as it does at
the root of the document. It does not yet: a nested controller only
restores the selection recorded on the root record, which an undo of its
own entity never changes. The test is marked fixme to document the gap.
The duplicated-container tests now also delete saved templates when they
finish, since a leftover saved index template made their setup fail.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_01A6LxkvDuGJg68a7c8KJKry
---
test/e2e/specs/site-editor/undo.spec.js | 125 ++++++++++++++++++++++++
1 file changed, 125 insertions(+)
diff --git a/test/e2e/specs/site-editor/undo.spec.js b/test/e2e/specs/site-editor/undo.spec.js
index b4ef2b9b905f6d..0bc14968dc5030 100644
--- a/test/e2e/specs/site-editor/undo.spec.js
+++ b/test/e2e/specs/site-editor/undo.spec.js
@@ -81,6 +81,7 @@ test.describe( 'undo in a container duplicated from one entity', () => {
} );
test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.deleteAllTemplates( 'wp_template' );
await requestUtils.deleteAllTemplates( 'wp_template_part' );
await requestUtils.activateTheme( 'twentytwentyone' );
} );
@@ -144,3 +145,127 @@ test.describe( 'undo in a container duplicated from one entity', () => {
await expect( edited ).toHaveText( 'Some container content' );
} );
} );
+
+// Two Template Parts backed by different entities are two inner block
+// controllers. An undo that reverts an edit in one of them while the caret sits
+// in the other should bring the caret back to the reverted block, the way it
+// does for blocks at the root of the document.
+//
+// It does not yet: a nested controller only restores the selection recorded
+// on the root record, which an undo of its own entity never changes. This is
+// unrelated to duplicated containers and predates
+// https://github.com/WordPress/gutenberg/pull/82706, which documents it as out
+// of scope.
+test.describe( 'undo across containers of different entities', () => {
+ test.beforeAll( async ( { requestUtils } ) => {
+ await requestUtils.activateTheme( 'emptytheme' );
+ } );
+
+ test.beforeEach( async ( { admin, editor, requestUtils } ) => {
+ for ( const part of [ 'A', 'B' ] ) {
+ await requestUtils.createTemplate( 'wp_template_part', {
+ slug: `part-${ part.toLowerCase() }`,
+ title: `Part ${ part }`,
+ content: `Part ${ part } text
`,
+ } );
+ }
+
+ await admin.visitSiteEditor( {
+ postId: 'emptytheme//index',
+ postType: 'wp_template',
+ canvas: 'edit',
+ } );
+
+ for ( const slug of [ 'part-a', 'part-b' ] ) {
+ await editor.insertBlock( {
+ name: 'core/template-part',
+ attributes: { slug, theme: 'emptytheme' },
+ } );
+ }
+
+ await expect( editor.canvas.getByText( 'Part B text' ) ).toBeVisible();
+ } );
+
+ test.afterAll( async ( { requestUtils } ) => {
+ await requestUtils.deleteAllTemplates( 'wp_template_part' );
+ await requestUtils.activateTheme( 'twentytwentyone' );
+ } );
+
+ test.fixme( 'returns the caret to the reverted container', async ( {
+ editor,
+ page,
+ pageUtils,
+ } ) => {
+ const partA = editor.canvas.getByText( 'Part A text' );
+ const partB = editor.canvas.getByText( 'Part B text' );
+
+ const containerTexts = () =>
+ page.evaluate( () => {
+ const { getBlocksByName, getBlockOrder, getBlockAttributes } =
+ window.wp.data.select( 'core/block-editor' );
+ // The template also carries the theme's header part.
+ return getBlocksByName( 'core/template-part' )
+ .filter( ( clientId ) =>
+ getBlockAttributes( clientId ).slug.startsWith(
+ 'part-'
+ )
+ )
+ .map( ( clientId ) =>
+ getBlockAttributes(
+ getBlockOrder( clientId )[ 0 ]
+ )?.content?.toString?.()
+ );
+ } );
+
+ // A block overlay covers an unselected Template Part, so each
+ // container is clicked before the paragraph inside it.
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Part A' } )
+ .click();
+ await partA.click();
+ await pageUtils.pressKeys( 'End' );
+ await page.keyboard.type( '-a' );
+ await expect
+ .poll( containerTexts )
+ .toEqual( [ 'Part A text-a', 'Part B text' ] );
+
+ await editor.canvas
+ .getByRole( 'document', { name: 'Block: Part B' } )
+ .click();
+ await partB.click();
+ await pageUtils.pressKeys( 'End' );
+ await page.keyboard.type( '-b' );
+ await expect
+ .poll( containerTexts )
+ .toEqual( [ 'Part A text-a', 'Part B text-b' ] );
+
+ // Typing coalesces into undo levels on a timer, so the number of
+ // levels the two edits produce is not fixed. Undo until the first
+ // container's edit is gone rather than assuming a count.
+ let reverted = false;
+ for ( let i = 0; i < 8 && ! reverted; i++ ) {
+ await pageUtils.pressKeys( 'primary+z' );
+ try {
+ await expect
+ .poll( containerTexts, { timeout: 1000 } )
+ .toEqual( [ 'Part A text', 'Part B text' ] );
+ reverted = true;
+ } catch {
+ // Not there yet; undo again.
+ }
+ }
+ expect( reverted ).toBe( true );
+
+ // The caret was in the second container and has to follow the undo
+ // into the first one.
+ const selected = await page.evaluate( () => {
+ const { getSelectedBlockClientId, getBlockAttributes } =
+ window.wp.data.select( 'core/block-editor' );
+ const clientId = getSelectedBlockClientId();
+ return clientId
+ ? getBlockAttributes( clientId )?.content?.toString?.()
+ : null;
+ } );
+ expect( selected ).toBe( 'Part A text' );
+ } );
+} );
From 5702de1551412fbd8b60d08fc488a20e2064d47e Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Thu, 15 Oct 2026 13:13:14 -0500
Subject: [PATCH 10/33] Block Editor: Find the selection's holder with
getBlockParents
The nearest controlled ancestor of the selected block is its holder. The store already has an ascending parent list, so use that instead of walking the tree by hand.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_01UpQLN4sQKUDBA45FqsyUQY
---
.../src/components/provider/use-block-sync.ts | 23 ++++++-------------
1 file changed, 7 insertions(+), 16 deletions(-)
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index 3bdc2a0bb615a9..ed1ad539d71c10 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -165,7 +165,6 @@ export default function useBlockSync( {
getSelectionStart,
getSelectionEnd,
getBlockParents,
- getBlockRootClientId,
areInnerBlocksControlled,
} = registry.select( blockEditorStore );
@@ -275,21 +274,13 @@ export default function useBlockSync( {
return false;
}
- // Otherwise find the controller the selected block belongs to. Only
- // the nearest one matters, and it is usually the immediate parent — a
- // menu item sits directly inside its Navigation block — so walk up and
- // stop at the first controller rather than collecting every ancestor.
- let parentClientId = getBlockRootClientId( currentStartClientId );
- while ( parentClientId ) {
- if ( areInnerBlocksControlled( parentClientId ) ) {
- return parentClientId !== clientId;
- }
- parentClientId = getBlockRootClientId( parentClientId );
- }
-
- // The selection is in the root block list, which belongs to no
- // controller.
- return false;
+ // Otherwise the nearest controller above the selected block holds
+ // it. No controller means the selection is in the root block list,
+ // which belongs to no controller.
+ const holder = getBlockParents( currentStartClientId, true ).find(
+ areInnerBlocksControlled
+ );
+ return holder !== undefined && holder !== clientId;
};
// Whether the controlled value has the same structure as the clones
From b06e29423ffdd0f233fc44c0091accb0e0ed09b1 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Tue, 24 Nov 2026 08:12:03 -0600
Subject: [PATCH 11/33] Block Editor: Keep undo selection restore inside nested
controllers
Two fixes to the duplicate controller guard and in-place update.
The guard skipped restoring the selection whenever the nearest
controlled ancestor of the selected block was not this controller. A
controller nested inside this one, such as a synced pattern inside Post
Content, is still part of this copy, so an undo in Post Content no
longer moved the caret back while it sat in the pattern. A selection
anywhere inside this controller now counts as its own.
The in-place update compared only attributes, so a change to any other
block field never reached the clones. The Custom HTML block keeps its
markup in innerContent and edits it with updateBlock: undoing that edit
in a container left the new markup on screen, and the next edit there
wrote it back into the entity. A value whose blocks differ in any field
other than attributes and inner blocks now re-clones, as before.
Co-Authored-By: Claude Opus 5.5
---
.../test/use-block-sync.jsdom.test.tsx | 196 ++++++++++++++++++
.../src/components/provider/use-block-sync.ts | 48 ++++-
2 files changed, 235 insertions(+), 9 deletions(-)
diff --git a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
index 4f31ac7d07de20..c2d36536cb90e5 100644
--- a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
+++ b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
@@ -1,12 +1,14 @@
import { registerBlockType } from '@wordpress/blocks';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { render } from '@testing-library/react';
+import { useState } from '@wordpress/element';
import type { ComponentType } from 'react';
import type { Block } from '@wordpress/blocks';
import type { DataRegistry } from '@wordpress/data';
import type { BlockEditorProviderProps, RegistryProvidedProps } from '../types';
import useBlockSync from '../use-block-sync';
import withRegistryProvider from '../with-registry-provider';
+import { SelectionContext } from '../selection-context';
import * as blockEditorActions from '../../../store/actions';
import { store as blockEditorStore } from '../../../store';
vi.mock( import( '../../../store/actions' ), async ( importOriginal ) => {
@@ -776,5 +778,199 @@ describe( 'useBlockSync hook', () => {
expect( replaceInnerBlocks ).toHaveBeenCalledTimes( 1 );
} );
+
+ // Some blocks change more than their attributes. The Custom HTML
+ // block keeps its markup in `innerContent`, edited with `updateBlock`.
+ it( 'still re-clones when a block field other than attributes changes', () => {
+ const replaceInnerBlocks = vi.spyOn(
+ blockEditorActions,
+ 'replaceInnerBlocks'
+ );
+ const { view, getClones, onChange, onInput } = renderController();
+ replaceInnerBlocks.mockClear();
+
+ view.rerender(
+ new
' ],
+ },
+ ] }
+ onChange={ onChange }
+ onInput={ onInput }
+ />
+ );
+
+ expect( replaceInnerBlocks ).toHaveBeenCalledTimes( 1 );
+ expect( getClones()[ 0 ].innerContent ).toEqual( [ 'new
' ] );
+ } );
+ } );
+
+ describe( 'selection after an incoming change', () => {
+ const paragraph = ( clientId, content ) => ( {
+ name: 'test/test-block',
+ clientId,
+ innerBlocks: [],
+ attributes: { foo: content },
+ } );
+
+ // Several controllers in one block-editor store, as on a canvas, all
+ // reading the recorded selection from the same context.
+ function Controller( props ) {
+ useBlockSync( props );
+ return null;
+ }
+ const Canvas = withRegistryProvider(
+ ( { registry, setRegistry, selectionRef, controllers } ) => {
+ setRegistry( registry );
+ const [ context ] = useState( () => ( {
+ getSelection: () => selectionRef.current,
+ onChangeSelection: () => {},
+ } ) );
+ return (
+
+ { controllers.map( ( props ) => (
+
+ ) ) }
+
+ );
+ }
+ );
+
+ function renderCanvas( hostClientIds ) {
+ let registry;
+ const selectionRef = { current: undefined };
+ const setRegistry = ( reg ) => {
+ if ( ! registry ) {
+ registry = reg;
+ reg.dispatch( blockEditorStore ).resetBlocks(
+ hostClientIds.map( ( clientId ) =>
+ paragraph( clientId, 0 )
+ )
+ );
+ }
+ };
+ const view = render(
+
+ );
+ const update = ( controllers ) =>
+ view.rerender(
+
+ );
+ const select = () => registry.select( blockEditorStore );
+ const selectBlock = ( clientId ) =>
+ registry.dispatch( blockEditorStore ).selectBlock( clientId );
+ return { registry, selectionRef, update, select, selectBlock };
+ }
+
+ it( 'does not take the selection from another controller of the same entity', () => {
+ const { registry, update, select, selectBlock, selectionRef } =
+ renderCanvas( [ 'copy-a', 'copy-b' ] );
+ let entity = [ paragraph( 'p', 1 ) ];
+ const onChangeA = ( blocks ) => ( entity = blocks );
+ const onChangeB = vi.fn();
+ const controllers = () => [
+ {
+ clientId: 'copy-a',
+ value: entity,
+ onChange: onChangeA,
+ onInput: onChangeA,
+ },
+ {
+ clientId: 'copy-b',
+ value: entity,
+ onChange: onChangeB,
+ onInput: onChangeB,
+ },
+ ];
+ update( controllers() );
+ const [ cloneA ] = select().getBlocks( 'copy-a' );
+ const [ cloneB ] = select().getBlocks( 'copy-b' );
+ selectBlock( cloneA.clientId );
+ selectionRef.current = {
+ selectionStart: { clientId: 'p' },
+ selectionEnd: { clientId: 'p' },
+ };
+
+ // Edit copy A, and hand the edited entity to both copies.
+ registry
+ .dispatch( blockEditorStore )
+ .updateBlockAttributes( cloneA.clientId, { foo: 2 } );
+ update( controllers() );
+
+ // Copy B mirrors the edit onto the clone it already has.
+ const [ mirrored ] = select().getBlocks( 'copy-b' );
+ expect( mirrored.clientId ).toBe( cloneB.clientId );
+ expect( mirrored.attributes.foo ).toBe( 2 );
+ expect( select().getSelectionStart().clientId ).toBe(
+ cloneA.clientId
+ );
+ // Copy B only mirrored the edit, so it reports nothing back.
+ expect( onChangeB ).not.toHaveBeenCalled();
+ } );
+
+ // An undo in the outer controller, while the caret sits in a
+ // controller nested inside it, such as a synced pattern inside Post
+ // Content.
+ it.each( [
+ [ 'updates the clones in place', [] ],
+ [ 're-clones', [ paragraph( 'added', 0 ) ] ],
+ ] )(
+ 'restores the selection when the caret is in a nested controller and the outer one %s',
+ ( _, addedBlocks ) => {
+ const { update, select, selectBlock, selectionRef } =
+ renderCanvas( [ 'outer' ] );
+ const outerBlock = paragraph( 'outer-block', 1 );
+ const nestedHost = paragraph( 'nested-host', 0 );
+ const outer = {
+ clientId: 'outer',
+ value: [ outerBlock, nestedHost ],
+ };
+ update( [ outer ] );
+ const [ , nestedHostClone ] = select().getBlocks( 'outer' );
+ const nested = {
+ clientId: nestedHostClone.clientId,
+ value: [ paragraph( 'nested-block', 1 ) ],
+ };
+ update( [ outer, nested ] );
+ selectBlock(
+ select().getBlocks( nestedHostClone.clientId )[ 0 ].clientId
+ );
+
+ // The undo reverts the outer block and records the
+ // selection in it.
+ selectionRef.current = {
+ selectionStart: { clientId: 'outer-block' },
+ selectionEnd: { clientId: 'outer-block' },
+ };
+ update( [
+ {
+ ...outer,
+ value: [
+ paragraph( 'outer-block', 0 ),
+ nestedHost,
+ ...addedBlocks,
+ ],
+ },
+ nested,
+ ] );
+
+ const [ outerBlockClone ] = select().getBlocks( 'outer' );
+ expect( outerBlockClone.attributes.foo ).toBe( 0 );
+ expect( select().getSelectionStart().clientId ).toBe(
+ outerBlockClone.clientId
+ );
+ }
+ );
} );
} );
diff --git a/packages/block-editor/src/components/provider/use-block-sync.ts b/packages/block-editor/src/components/provider/use-block-sync.ts
index ed1ad539d71c10..f6d097ee978ed2 100644
--- a/packages/block-editor/src/components/provider/use-block-sync.ts
+++ b/packages/block-editor/src/components/provider/use-block-sync.ts
@@ -102,6 +102,33 @@ function restoreSelectionIds(
};
}
+/**
+ * Returns whether two blocks are equal in every field other than their client
+ * ID, attributes and inner blocks. Only attributes are updated in place, so a
+ * change to any other field, such as the `innerContent` that the Custom HTML
+ * block edits, needs the blocks to be cloned again.
+ *
+ * @param block The block from the controlled value.
+ * @param clone Its clone in the block-editor store.
+ * @return Whether the blocks have the same fields.
+ */
+function hasSameFields( block: Block, clone: Block ): boolean {
+ for ( const key of new Set( [
+ ...Object.keys( block ),
+ ...Object.keys( clone ),
+ ] ) as Set< keyof Block > ) {
+ if (
+ key !== 'clientId' &&
+ key !== 'attributes' &&
+ key !== 'innerBlocks' &&
+ block[ key ] !== clone[ key ]
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
/**
* useBlockSync is a side effect which handles bidirectional sync between the
* block-editor store and a controlling data source which provides blocks. This
@@ -274,19 +301,22 @@ export default function useBlockSync( {
return false;
}
- // Otherwise the nearest controller above the selected block holds
- // it. No controller means the selection is in the root block list,
- // which belongs to no controller.
- const holder = getBlockParents( currentStartClientId, true ).find(
- areInnerBlocksControlled
+ // A selection anywhere inside this controller is in this copy, even
+ // one inside a controller nested in it, such as a synced pattern
+ // inside Post Content. Outside it, any controller above the selected
+ // block is another one. No controller means the selection is in the
+ // root block list, which belongs to no controller.
+ const parents = getBlockParents( currentStartClientId );
+ return (
+ ! parents.includes( clientId ) &&
+ parents.some( ( parentId ) => areInnerBlocksControlled( parentId ) )
);
- return holder !== undefined && holder !== clientId;
};
// Whether the controlled value has the same structure as the clones
// already in the store: the same external IDs in the same order, all
- // the way down. A nested controller owns its own inner blocks, so those
- // are left to it.
+ // the way down, with nothing but attributes changed. A nested
+ // controller owns its own inner blocks, so those are left to it.
const hasSameStructure = ( blocks, clones ) =>
blocks.length === clones.length &&
blocks.every( ( block, index ) => {
@@ -295,7 +325,7 @@ export default function useBlockSync( {
idMappingRef.current.internalToExternal.get(
clone.clientId
) === block.clientId &&
- block.name === clone.name &&
+ hasSameFields( block, clone ) &&
( areInnerBlocksControlled( clone.clientId ) ||
hasSameStructure( block.innerBlocks, clone.innerBlocks ) )
);
From 2990c415ad0754781d76df952c1d0f6d18457582 Mon Sep 17 00:00:00 2001
From: Jerry Jones
Date: Tue, 24 Nov 2026 08:29:32 -0600
Subject: [PATCH 12/33] Block Editor: Type the in-place update in useBlockSync
The in-place update and its tests were written in JavaScript before
useBlockSync moved to TypeScript on trunk. Give the helpers and the test
harness their types so the dev project type checks.
Co-Authored-By: Claude Opus 5.5
---
.../test/use-block-sync.jsdom.test.tsx | 62 +++++++++++++------
.../src/components/provider/use-block-sync.ts | 10 ++-
2 files changed, 50 insertions(+), 22 deletions(-)
diff --git a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
index c2d36536cb90e5..7df52c1d69207a 100644
--- a/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
+++ b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx
@@ -5,7 +5,12 @@ import { useState } from '@wordpress/element';
import type { ComponentType } from 'react';
import type { Block } from '@wordpress/blocks';
import type { DataRegistry } from '@wordpress/data';
-import type { BlockEditorProviderProps, RegistryProvidedProps } from '../types';
+import type {
+ BlockEditorProviderProps,
+ BlockSelectionState,
+ RegistryProvidedProps,
+ UseBlockSyncProps,
+} from '../types';
import useBlockSync from '../use-block-sync';
import withRegistryProvider from '../with-registry-provider';
import { SelectionContext } from '../selection-context';
@@ -688,7 +693,9 @@ describe( 'useBlockSync hook', () => {
} );
describe( 'controlled value with the same structure', () => {
- const block = ( attributes ) => ( {
+ const block = (
+ attributes: Record< string, unknown >
+ ): TestBlock => ( {
name: 'test/test-block',
clientId: 'external',
innerBlocks: [
@@ -703,13 +710,13 @@ describe( 'useBlockSync hook', () => {
} );
function renderController() {
- let registry;
+ let registry!: DataRegistry;
const onChange = vi.fn();
const onInput = vi.fn();
const view = render(
{
+ setRegistry={ ( reg: DataRegistry ) => {
registry = reg;
} }
value={ [ block( { foo: 1 } ) ] }
@@ -809,7 +816,10 @@ describe( 'useBlockSync hook', () => {
} );
describe( 'selection after an incoming change', () => {
- const paragraph = ( clientId, content ) => ( {
+ const paragraph = (
+ clientId: string,
+ content: number
+ ): TestBlock => ( {
name: 'test/test-block',
clientId,
innerBlocks: [],
@@ -818,12 +828,23 @@ describe( 'useBlockSync hook', () => {
// Several controllers in one block-editor store, as on a canvas, all
// reading the recorded selection from the same context.
- function Controller( props ) {
- useBlockSync( props );
+ type ControllerProps = Omit< UseBlockSyncProps, 'value' > & {
+ clientId: string;
+ value: TestBlock[];
+ };
+ type CanvasProps = {
+ setRegistry: ( registry: DataRegistry ) => void;
+ selectionRef: { current?: BlockSelectionState };
+ controllers: ControllerProps[];
+ };
+ function Controller( props: ControllerProps ) {
+ useBlockSync( props as UseBlockSyncProps );
return null;
}
const Canvas = withRegistryProvider(
- ( { registry, setRegistry, selectionRef, controllers } ) => {
+ ( props: RegistryProvidedProps ) => {
+ const { registry, setRegistry, selectionRef, controllers } =
+ props as RegistryProvidedProps & CanvasProps;
setRegistry( registry );
const [ context ] = useState( () => ( {
getSelection: () => selectionRef.current,
@@ -831,24 +852,27 @@ describe( 'useBlockSync hook', () => {
} ) );
return (
- { controllers.map( ( props ) => (
-
+ { controllers.map( ( controller ) => (
+
) ) }
);
}
- );
+ ) as ComponentType< CanvasProps >;
- function renderCanvas( hostClientIds ) {
- let registry;
- const selectionRef = { current: undefined };
- const setRegistry = ( reg ) => {
+ function renderCanvas( hostClientIds: string[] ) {
+ let registry!: DataRegistry;
+ const selectionRef: CanvasProps[ 'selectionRef' ] = {};
+ const setRegistry = ( reg: DataRegistry ) => {
if ( ! registry ) {
registry = reg;
reg.dispatch( blockEditorStore ).resetBlocks(
hostClientIds.map( ( clientId ) =>
paragraph( clientId, 0 )
- )
+ ) as Block[]
);
}
};
@@ -859,7 +883,7 @@ describe( 'useBlockSync hook', () => {
controllers={ [] }
/>
);
- const update = ( controllers ) =>
+ const update = ( controllers: ControllerProps[] ) =>
view.rerender(