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( { /> ); const select = () => registry.select( blockEditorStore ); - const selectBlock = ( clientId ) => + const selectBlock = ( clientId: string ) => registry.dispatch( blockEditorStore ).selectBlock( clientId ); return { registry, selectionRef, update, select, selectBlock }; } @@ -877,7 +901,7 @@ describe( 'useBlockSync hook', () => { const { registry, update, select, selectBlock, selectionRef } = renderCanvas( [ 'copy-a', 'copy-b' ] ); let entity = [ paragraph( 'p', 1 ) ]; - const onChangeA = ( blocks ) => ( entity = blocks ); + const onChangeA = ( blocks: TestBlock[] ) => ( entity = blocks ); const onChangeB = vi.fn(); const controllers = () => [ { 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 f6d097ee978ed2..dee1683cf85597 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -317,7 +317,7 @@ export default function useBlockSync( { // already in the store: the same external IDs in the same order, all // 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 ) => + const hasSameStructure = ( blocks: Block[], clones: Block[] ): boolean => blocks.length === clones.length && blocks.every( ( block, index ) => { const clone = clones[ index ]; @@ -333,10 +333,14 @@ export default function useBlockSync( { // 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 = {} ) => { + const collectAttributeChanges = ( + blocks: Block[], + clones: Block[], + changes: Record< string, Record< string, unknown > > = {} + ) => { blocks.forEach( ( block, index ) => { const clone = clones[ index ]; - const changed = {}; + const changed: Record< string, unknown > = {}; let hasChanged = false; for ( const key of new Set( [ ...Object.keys( block.attributes ), From 1c7cd8b3bdca943ae845710f07b69df9ca23627f Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 08:32:28 -0600 Subject: [PATCH 13/33] Tests: Write the duplicate Navigation selection spec in TypeScript Trunk now requires new end-to-end spec files to be TypeScript. Co-Authored-By: Claude Opus 5.5 --- ...c.js => navigation-selection-sync.spec.ts} | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) rename test/e2e/specs/site-editor/{navigation-selection-sync.spec.js => navigation-selection-sync.spec.ts} (83%) diff --git a/test/e2e/specs/site-editor/navigation-selection-sync.spec.js b/test/e2e/specs/site-editor/navigation-selection-sync.spec.ts similarity index 83% rename from test/e2e/specs/site-editor/navigation-selection-sync.spec.js rename to test/e2e/specs/site-editor/navigation-selection-sync.spec.ts index 7eeb4936e8a81a..74049b4f9dfade 100644 --- a/test/e2e/specs/site-editor/navigation-selection-sync.spec.js +++ b/test/e2e/specs/site-editor/navigation-selection-sync.spec.ts @@ -1,4 +1,8 @@ -const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); +import type { Page } from '@playwright/test'; +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; + +// Records every selection that enters the duplicate Navigation block. +type TrackedWindow = typeof window & { __selectionsInDuplicate: string[] }; const MENU_CONTENT = ''; @@ -10,12 +14,11 @@ const MENU_CONTENT = * 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. + * @param page Playwright page. + * @return Index of the containing Navigation block in document order, or null + * when the selection is outside every Navigation block. */ -function getSelectedNavigationIndex( page ) { +function getSelectedNavigationIndex( page: Page ): Promise< number | null > { return page.evaluate( () => { const { getSelectedBlockClientId, getBlocksByName, getBlockParents } = window.wp.data.select( 'core/block-editor' ); @@ -26,7 +29,7 @@ function getSelectedNavigationIndex( page ) { const navigationBlocks = getBlocksByName( 'core/navigation' ); const parents = getBlockParents( selected ); const index = navigationBlocks.findIndex( - ( clientId ) => + ( clientId: string ) => clientId === selected || parents.includes( clientId ) ); return index === -1 ? null : index; @@ -108,16 +111,17 @@ test.describe( 'Duplicate Navigation blocks using the same menu', () => { getBlockParents, } = window.wp.data.select( 'core/block-editor' ); const duplicate = getBlocksByName( 'core/navigation' ).at( -1 ); - window.__selectionsInDuplicate = []; + const tracked = window as TrackedWindow; + tracked.__selectionsInDuplicate = []; window.wp.data.subscribe( () => { const selected = getSelectedBlockClientId(); if ( selected && ( selected === duplicate || getBlockParents( selected ).includes( duplicate ) ) && - window.__selectionsInDuplicate.at( -1 ) !== selected + tracked.__selectionsInDuplicate.at( -1 ) !== selected ) { - window.__selectionsInDuplicate.push( selected ); + tracked.__selectionsInDuplicate.push( selected ); } } ); } ); @@ -131,7 +135,9 @@ test.describe( 'Duplicate Navigation blocks using the same menu', () => { await expect( labels.first() ).toHaveText( 'IteXm' ); await expect( labels.last() ).toHaveText( 'IteXm' ); expect( - await page.evaluate( () => window.__selectionsInDuplicate ) + await page.evaluate( + () => ( window as TrackedWindow ).__selectionsInDuplicate + ) ).toEqual( [] ); expect( await getSelectedNavigationIndex( page ) ).toBe( 0 ); } ); From 4c3269680f0ff2c666497273682d4a3710f9de50 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 08:56:15 -0600 Subject: [PATCH 14/33] Block Editor: Restore undo selection like the re-clone path does Two regressions against trunk in how a controller restores the selection after an incoming change. The in-place update left the record of the last restored selection in place, so an undo handing back that same selection object skipped the restore. That happens on undo, type, undo: typing without moving the caret first records the selection the first undo restored. Clear it after an in-place update, as re-cloning does. The guard took any controller above the selected block for another copy of this entity. A Template Part holding Post Title and Post Content then stopped an undo in Post Content from moving the caret back while it sat on Post Title. Another copy is always a block of the same type, so only count controllers of this controller's block type. Also trims the changelog entry to what changes for users of the package, and names duplicate Post Content blocks in it. Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/CHANGELOG.md | 2 +- .../test/use-block-sync.jsdom.test.tsx | 105 ++++++++++++++++++ .../src/components/provider/use-block-sync.ts | 17 ++- 3 files changed, 119 insertions(+), 5 deletions(-) diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index b7ad2db2a4d0f0..16a3cca5cbbf05 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -43,7 +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)). +- Inner block controllers rendering the same entity, such as two Navigation blocks on the same menu, two Post Content blocks, or two Template Parts on the same slug, no longer move the selection into each other, lose keystrokes, or split typing in one of them into an undo level per character ([#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 7df52c1d69207a..ef8b8f01d5b912 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 @@ -996,5 +996,110 @@ describe( 'useBlockSync hook', () => { ); } ); + + // Post Content inside a Template Part, with the caret on Post Title + // next to it in the same Template Part. Only another block of the + // same type renders the same entity. + it( 'restores the selection when the caret is in a controller of another type', () => { + const { update, select, selectBlock, selectionRef } = renderCanvas( + [ 'part' ] + ); + const contentHost = { + ...paragraph( 'content-host', 0 ), + name: 'test/other-block', + }; + const part = { + clientId: 'part', + value: [ paragraph( 'title', 0 ), contentHost ], + }; + update( [ part ] ); + const [ titleClone, contentHostClone ] = + select().getBlocks( 'part' ); + const content = { + clientId: contentHostClone.clientId, + value: [ paragraph( 'content-block', 1 ) ], + }; + update( [ part, content ] ); + selectBlock( titleClone.clientId ); + + // The undo reverts the content block and records the selection + // in it. + selectionRef.current = { + selectionStart: { clientId: 'content-block' }, + selectionEnd: { clientId: 'content-block' }, + }; + update( [ + part, + { ...content, value: [ paragraph( 'content-block', 0 ) ] }, + ] ); + + const [ contentBlockClone ] = select().getBlocks( + contentHostClone.clientId + ); + expect( contentBlockClone.attributes.foo ).toBe( 0 ); + expect( select().getSelectionStart().clientId ).toBe( + contentBlockClone.clientId + ); + } ); + + // Typing between two undos without moving the caret records the + // selection the first undo restored, so the second undo hands back + // that same selection object. + it( 'restores a selection again when an undo returns to it', () => { + const { registry, update, select, selectionRef } = renderCanvas( [ + 'outer', + ] ); + let entity = [ paragraph( 'p', 1 ) ]; + const onChange = ( blocks: TestBlock[] ) => ( entity = blocks ); + const controllers = () => [ + { + clientId: 'outer', + value: entity, + onChange, + onInput: onChange, + }, + ]; + update( controllers() ); + const clone = () => select().getBlocks( 'outer' )[ 0 ]; + const caret = ( clientId: string, offset: number ) => ( { + clientId, + attributeKey: 'foo', + offset, + } ); + + // The first undo. + const restored = { + selectionStart: caret( 'p', 5 ), + selectionEnd: caret( 'p', 5 ), + }; + selectionRef.current = restored; + entity = [ paragraph( 'p', 2 ) ]; + update( controllers() ); + expect( select().getSelectionStart() ).toEqual( + caret( clone().clientId, 5 ) + ); + + // Typing moves the caret on. + registry + .dispatch( blockEditorStore ) + .selectionChange( clone().clientId, 'foo', 8, 8 ); + registry + .dispatch( blockEditorStore ) + .updateBlockAttributes( clone().clientId, { foo: 3 } ); + selectionRef.current = { + selectionStart: caret( 'p', 8 ), + selectionEnd: caret( 'p', 8 ), + }; + update( controllers() ); + + // The second undo. + selectionRef.current = restored; + entity = [ paragraph( 'p', 2 ) ]; + update( controllers() ); + expect( clone().attributes.foo ).toBe( 2 ); + expect( select().getSelectionStart() ).toEqual( + caret( clone().clientId, 5 ) + ); + } ); } ); } ); 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 dee1683cf85597..f07c56e3000e98 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -303,13 +303,19 @@ export default function useBlockSync( { // 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. + // inside Post Content. Outside it, another copy is a controller of + // the same block type, such as a second Navigation block. One of + // another type, such as a Template Part around Post Title, renders + // another entity, and neither does the root block list. const parents = getBlockParents( currentStartClientId ); + const blockName = getBlockName( clientId ); return ( ! parents.includes( clientId ) && - parents.some( ( parentId ) => areInnerBlocksControlled( parentId ) ) + parents.some( + ( parentId ) => + areInnerBlocksControlled( parentId ) && + getBlockName( parentId ) === blockName + ) ); }; @@ -399,6 +405,9 @@ export default function useBlockSync( { updateBlockAttributes( changedClientIds, changes, { uniqueByBlock: true, } ); + // As after re-cloning, let an undo restore its recorded + // selection even if it is the one restored last time. + appliedSelectionRef.current = null; } return; } From 1cc86f30001c1e764bcdf13f3ccb433c583febc2 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 09:39:15 -0600 Subject: [PATCH 15/33] Tests: Cover undo restoring the caret into Post Content Two end-to-end tests for the selection restore fixed in the previous commits, both with the page's template shown: - With Post Title and Post Content in one Template Part, an undo in Post Content brings the caret back from Post Title. - On undo, type, undo, the second undo brings the caret back to where the typing started. Both fail without those fixes. Each first types a second after the editor loads: the first typing after loading does not always get an undo level of its own, on trunk too, which made the tests flaky. Co-Authored-By: Claude Opus 5.5 --- .../various/post-content-focus-mode.spec.js | 157 ++++++++++++++++++ 1 file changed, 157 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 e121f91ef4fc50..9bbdc6bce8753a 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 @@ -22,6 +22,7 @@ test.describe( 'Post Content focus mode', () => { test.afterAll( async ( { requestUtils } ) => { await requestUtils.activateTheme( 'twentytwentyone' ); await requestUtils.resetPreferences(); + await requestUtils.deleteAllPosts(); } ); test( 'inserts blocks into Post Content from different selection states', async ( { @@ -191,6 +192,59 @@ test.describe( 'Post Content focus mode', () => { expect( selected ).toBe( 'First' ); } ); + // The undo level that typing opens starts from the selection the last + // undo restored, so the next undo hands back that same selection, and + // has to restore it again. + // See https://github.com/WordPress/gutenberg/pull/82706. + test( 'undo moves the caret back on undo, type, undo', async ( { + admin, + editor, + page, + pageUtils, + postContentFocusMode, + requestUtils, + } ) => { + // A saved paragraph, so no undo level can remove it. + const { id } = await requestUtils.createPost( { + content: + '

Hello world

', + } ); + await admin.editPost( id ); + await postContentFocusMode.enableShowTemplate(); + + // Type after "Hello", then undo. + await editor.canvas.getByText( 'Hello world' ).click(); + await page.keyboard.press( 'End' ); + for ( let i = 0; i < ' world'.length; i++ ) { + await page.keyboard.press( 'ArrowLeft' ); + } + // The first typing after the editor loads does not always get an + // undo level of its own: an undo can turn out empty, or take back + // more than the typing. Typing a second after the last change starts + // a new level, and nothing on the page shows when that second is up, + // so wait it out. + // eslint-disable-next-line no-restricted-syntax, playwright/no-wait-for-timeout + await page.waitForTimeout( 1100 ); + await page.keyboard.type( '-a' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello-a world' ] ); + await postContentFocusMode.undoUntil( pageUtils, [ 'Hello world' ] ); + + // Type again at the caret the undo restored, then undo again. + await page.keyboard.type( '-b' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello-b world' ] ); + await postContentFocusMode.undoUntil( pageUtils, [ 'Hello world' ] ); + + // The caret is back after "Hello", not after the undone text. + await page.keyboard.type( '-c' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello-c world' ] ); + } ); + // Check for regressions of https://github.com/WordPress/gutenberg/issues/76101. test.describe( 'post content inside a template part', () => { test.beforeAll( async ( { requestUtils } ) => { @@ -298,6 +352,54 @@ test.describe( 'Post Content focus mode', () => { } ); } ); + // The template part is an inner block controller too, but it renders + // another entity, so a caret in it must not stop an undo in Post + // Content from moving the caret back. + // See https://github.com/WordPress/gutenberg/pull/82706. + test( 'undo moves the caret back into Post Content from Post Title', async ( { + admin, + editor, + page, + pageUtils, + postContentFocusMode, + requestUtils, + } ) => { + // A saved paragraph, so no undo level can remove it. + const { id } = await requestUtils.createPost( { + content: + '

Initial content

', + } ); + await admin.editPost( id ); + await postContentFocusMode.enableShowTemplate(); + + await editor.canvas.getByText( 'Initial content' ).click(); + await page.keyboard.press( 'End' ); + // See the settle wait in "undo moves the caret back on undo, + // type, undo". + // eslint-disable-next-line no-restricted-syntax, playwright/no-wait-for-timeout + await page.waitForTimeout( 1100 ); + await page.keyboard.type( '-a' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Initial content-a' ] ); + + // Move the caret to Post Title, in the same template part. + await editor.selectBlocks( + editor.canvas.getByRole( 'document', { name: 'Block: Title' } ) + ); + await expect + .poll( () => postContentFocusMode.getSelectedBlockName() ) + .toBe( 'core/post-title' ); + + await postContentFocusMode.undoUntil( pageUtils, [ + 'Initial content', + ] ); + + expect( await postContentFocusMode.getSelectedBlockName() ).toBe( + 'core/paragraph' + ); + } ); + test( 'template part blocks outside post content are not editable', async ( { admin, editor, @@ -618,6 +720,61 @@ class PostContentFocusMode { } ); } + /** + * Returns the content of Post Content's inner blocks. + * + * @return {string[]} The content of each block inside Post Content. + */ + async getPostContentText() { + return await this.page.evaluate( () => { + const { getBlocksByName, getBlockOrder, getBlockAttributes } = + window.wp.data.select( 'core/block-editor' ); + const [ postContentId ] = getBlocksByName( 'core/post-content' ); + return getBlockOrder( postContentId ).map( ( id ) => + getBlockAttributes( id )?.content?.toString?.() + ); + } ); + } + + /** + * Returns the name of the selected block. + * + * @return {string|null} The selected block's name, or null. + */ + async getSelectedBlockName() { + return await this.page.evaluate( () => { + const { getSelectedBlockClientId, getBlockName } = + window.wp.data.select( 'core/block-editor' ); + const clientId = getSelectedBlockClientId(); + return clientId ? getBlockName( clientId ) : null; + } ); + } + + /** + * Undoes until Post Content's blocks have the given content. Typing + * coalesces into undo levels on a timer, so the number of levels an edit + * produces is not fixed. + * + * @param {Object} pageUtils Page utils fixture. + * @param {string[]} expected The content of each block to undo back to. + */ + async undoUntil( pageUtils, expected ) { + for ( let i = 0; i < 8; i++ ) { + await pageUtils.pressKeys( 'primary+z' ); + try { + await expect + .poll( () => this.getPostContentText(), { timeout: 1000 } ) + .toEqual( expected ); + return; + } catch { + // Not there yet; undo again. + } + } + await expect + .poll( () => this.getPostContentText() ) + .toEqual( expected ); + } + /** * Returns the block names of the direct children of the template part * that contains Post Content. From eb3548d40d045c17bfb908fe6605035e77da7402 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 09:39:21 -0600 Subject: [PATCH 16/33] Block Editor: Say which controllers the selection guard counts as copies The guard counts any controller of the same block type as a copy, so two Template Parts on different slugs count as copies of each other too. Say so next to the guard, and in the undo test pinned as fixme, which the guard would also block once its other cause is fixed. Co-Authored-By: Claude Opus 5.5 --- .../components/provider/test/use-block-sync.jsdom.test.tsx | 6 +++--- .../block-editor/src/components/provider/use-block-sync.ts | 7 +++++-- test/e2e/specs/site-editor/undo.spec.js | 4 +++- 3 files changed, 11 insertions(+), 6 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 ef8b8f01d5b912..10729ebba61454 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 @@ -1042,9 +1042,9 @@ describe( 'useBlockSync hook', () => { ); } ); - // Typing between two undos without moving the caret records the - // selection the first undo restored, so the second undo hands back - // that same selection object. + // The undo level that typing opens starts from the selection the + // last undo restored, so undoing it hands back that same selection + // object. it( 'restores a selection again when an undo returns to it', () => { const { registry, update, select, selectionRef } = renderCanvas( [ 'outer', 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 f07c56e3000e98..f81e1a0ef68167 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -271,7 +271,7 @@ export default function useBlockSync( { }; // Whether the block-editor's current selection sits inside a *different* - // inner block controller. + // inner block controller of the same block type. // // Several controllers can render one entity — two Navigation blocks using // the same menu, two Post Content blocks showing the same post. Each keeps @@ -306,7 +306,10 @@ export default function useBlockSync( { // inside Post Content. Outside it, another copy is a controller of // the same block type, such as a second Navigation block. One of // another type, such as a Template Part around Post Title, renders - // another entity, and neither does the root block list. + // another entity, and the root block list belongs to no controller. + // Two controllers of one type that render different entities, such + // as Template Parts on different slugs, count as copies too: telling + // them apart would need each controller to record its entity. const parents = getBlockParents( currentStartClientId ); const blockName = getBlockName( clientId ); return ( diff --git a/test/e2e/specs/site-editor/undo.spec.js b/test/e2e/specs/site-editor/undo.spec.js index 0bc14968dc5030..b4488d9254fbc3 100644 --- a/test/e2e/specs/site-editor/undo.spec.js +++ b/test/e2e/specs/site-editor/undo.spec.js @@ -155,7 +155,9 @@ test.describe( 'undo in a container duplicated from one entity', () => { // 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. +// of scope. Once that is fixed, the guard that pull request adds would still +// stop the restore: it counts two Template Parts as copies of each other +// whatever their slugs, so it would also need to tell them apart. test.describe( 'undo across containers of different entities', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.activateTheme( 'emptytheme' ); From 05af5ff596d775daab5e41e45a1133598b373062 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 11:15:03 -0600 Subject: [PATCH 17/33] Tests: Wait for Post Content to be visible, not for a second Until the canvas reports Post Content as visible, a moment after it renders, the block reads the post asynchronously. Typing then undone quickly is missed altogether, leaving its blocks with the typing while the post no longer has it. Wait for that state instead of a timeout, and undo once per typing now that no undo can go missing. Co-Authored-By: Claude Opus 5.5 --- .../various/post-content-focus-mode.spec.js | 65 +++++++++---------- 1 file changed, 29 insertions(+), 36 deletions(-) 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 9bbdc6bce8753a..f8a18794b73da3 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 @@ -218,25 +218,25 @@ test.describe( 'Post Content focus mode', () => { for ( let i = 0; i < ' world'.length; i++ ) { await page.keyboard.press( 'ArrowLeft' ); } - // The first typing after the editor loads does not always get an - // undo level of its own: an undo can turn out empty, or take back - // more than the typing. Typing a second after the last change starts - // a new level, and nothing on the page shows when that second is up, - // so wait it out. - // eslint-disable-next-line no-restricted-syntax, playwright/no-wait-for-timeout - await page.waitForTimeout( 1100 ); + await postContentFocusMode.waitForPostContentVisible(); await page.keyboard.type( '-a' ); await expect .poll( () => postContentFocusMode.getPostContentText() ) .toEqual( [ 'Hello-a world' ] ); - await postContentFocusMode.undoUntil( pageUtils, [ 'Hello world' ] ); + await pageUtils.pressKeys( 'primary+z' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello world' ] ); // Type again at the caret the undo restored, then undo again. await page.keyboard.type( '-b' ); await expect .poll( () => postContentFocusMode.getPostContentText() ) .toEqual( [ 'Hello-b world' ] ); - await postContentFocusMode.undoUntil( pageUtils, [ 'Hello world' ] ); + await pageUtils.pressKeys( 'primary+z' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello world' ] ); // The caret is back after "Hello", not after the undone text. await page.keyboard.type( '-c' ); @@ -374,10 +374,7 @@ test.describe( 'Post Content focus mode', () => { await editor.canvas.getByText( 'Initial content' ).click(); await page.keyboard.press( 'End' ); - // See the settle wait in "undo moves the caret back on undo, - // type, undo". - // eslint-disable-next-line no-restricted-syntax, playwright/no-wait-for-timeout - await page.waitForTimeout( 1100 ); + await postContentFocusMode.waitForPostContentVisible(); await page.keyboard.type( '-a' ); await expect .poll( () => postContentFocusMode.getPostContentText() ) @@ -391,9 +388,10 @@ test.describe( 'Post Content focus mode', () => { .poll( () => postContentFocusMode.getSelectedBlockName() ) .toBe( 'core/post-title' ); - await postContentFocusMode.undoUntil( pageUtils, [ - 'Initial content', - ] ); + await pageUtils.pressKeys( 'primary+z' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Initial content' ] ); expect( await postContentFocusMode.getSelectedBlockName() ).toBe( 'core/paragraph' @@ -751,28 +749,23 @@ class PostContentFocusMode { } /** - * Undoes until Post Content's blocks have the given content. Typing - * coalesces into undo levels on a timer, so the number of levels an edit - * produces is not fixed. - * - * @param {Object} pageUtils Page utils fixture. - * @param {string[]} expected The content of each block to undo back to. + * Waits until the canvas counts Post Content as visible, which it reports + * a moment after rendering. Until then, Post Content is neither selected + * nor visible, so it reads the post asynchronously. When typing is + * quickly undone, it then misses both edits: its blocks keep the typing + * while the post no longer has it. */ - async undoUntil( pageUtils, expected ) { - for ( let i = 0; i < 8; i++ ) { - await pageUtils.pressKeys( 'primary+z' ); - try { - await expect - .poll( () => this.getPostContentText(), { timeout: 1000 } ) - .toEqual( expected ); - return; - } catch { - // Not there yet; undo again. - } - } + async waitForPostContentVisible() { await expect - .poll( () => this.getPostContentText() ) - .toEqual( expected ); + .poll( () => + this.page.evaluate( () => { + const { getBlocksByName, __unstableGetVisibleBlocks } = + window.wp.data.select( 'core/block-editor' ); + const [ clientId ] = getBlocksByName( 'core/post-content' ); + return __unstableGetVisibleBlocks().has( clientId ); + } ) + ) + .toBe( true ); } /** From 4537125e4d8c2f01e3e99759555770fa9e84089a Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 11:44:12 -0600 Subject: [PATCH 18/33] Tests: Undo once per edit between blocks of the same Post Content Like the other two undo tests, this one typed before Post Content was reported visible, so the first undo could be missed. An undo-until loop absorbed that, but it would equally have accepted the two edits being merged into one undo level. Wait for visibility instead, and check that each undo reverts exactly one edit. Co-Authored-By: Claude Opus 5.5 --- .../various/post-content-focus-mode.spec.js | 22 +++++-------------- 1 file changed, 6 insertions(+), 16 deletions(-) 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 f8a18794b73da3..d815ce3165b6a3 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 @@ -150,6 +150,7 @@ test.describe( 'Post Content focus mode', () => { // Edit the first block, then the second, leaving the caret in the // second. + await postContentFocusMode.waitForPostContentVisible(); await editor.selectBlocks( editor.canvas.getByText( 'First' ) ); await page.keyboard.press( 'End' ); await page.keyboard.type( '-a' ); @@ -162,22 +163,11 @@ test.describe( 'Post Content focus mode', () => { .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 ); + // Each edit is an undo level of its own. + await pageUtils.pressKeys( 'primary+z' ); + await expect.poll( postContentText ).toEqual( [ 'First-a', 'Second' ] ); + await pageUtils.pressKeys( 'primary+z' ); + await expect.poll( postContentText ).toEqual( [ 'First', 'Second' ] ); // The caret was in the second block and has to follow the undo to // the first one. From af48aa9651a84c8a3a5df63cd19b773e749da894 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 12:35:27 -0600 Subject: [PATCH 19/33] Block Editor: Test the in-place update's reorder and undo cases Two checks had no test that fails without them: - a reorder of the same blocks must re-clone, or each clone stays mapped to the block that used to be in its place, and an edit to one is reported as an edit to another; - an undo that updates the edited block in place must start a new undo level for the next typing, or the next undo also takes back the edit before it. Also correct comments that still describe a duplicate re-cloning between keystrokes, drop a claim that the selection guard has to run after the blocks are set (either order restores the selection), and name the nested-controller re-clone case for what it covers. Co-Authored-By: Claude Opus 5.5 --- .../test/use-block-sync.jsdom.test.tsx | 48 +++++++++++++++-- .../src/components/provider/use-block-sync.ts | 2 - packages/block-editor/src/store/reducer.ts | 9 ++-- .../block-editor/src/store/test/reducer.ts | 52 +++++++++++++++++-- 4 files changed, 98 insertions(+), 13 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 10729ebba61454..3652655ed15735 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 @@ -815,7 +815,7 @@ describe( 'useBlockSync hook', () => { } ); } ); - describe( 'selection after an incoming change', () => { + describe( 'controllers on one canvas', () => { const paragraph = ( clientId: string, content: number @@ -943,12 +943,52 @@ describe( 'useBlockSync hook', () => { expect( onChangeB ).not.toHaveBeenCalled(); } ); + // Moving a block in one copy hands the other copy the same blocks + // in another order. Updating its clones in place would leave each + // mapped to the block that used to be there, so that an edit to one + // would be reported as an edit to another. + it( 're-clones when the blocks are reordered', () => { + const { registry, update, select } = renderCanvas( [ 'copy' ] ); + const onChange = vi.fn(); + const first = paragraph( 'first', 1 ); + const second = paragraph( 'second', 1 ); + update( [ + { clientId: 'copy', value: [ first, second ], onChange }, + ] ); + + update( [ + { clientId: 'copy', value: [ second, first ], onChange }, + ] ); + const [ clone ] = select().getBlocks( 'copy' ); + registry + .dispatch( blockEditorStore ) + .updateBlockAttributes( clone.clientId, { foo: 2 } ); + + expect( onChange ).toHaveBeenCalledWith( + [ + expect.objectContaining( { + clientId: 'second', + attributes: { foo: 2 }, + } ), + expect.objectContaining( { + clientId: 'first', + attributes: { foo: 1 }, + } ), + ], + expect.anything() + ); + } ); + // An undo in the outer controller, while the caret sits in a // controller nested inside it, such as a synced pattern inside Post - // Content. + // Content. Re-cloning replaces the nested host, and the block the + // caret was in with it, so the selection has to be repaired. it.each( [ - [ 'updates the clones in place', [] ], - [ 're-clones', [ paragraph( 'added', 0 ) ] ], + [ 'updates its clones in place', [] ], + [ + 're-clones, replacing the nested block', + [ paragraph( 'added', 0 ) ], + ], ] )( 'restores the selection when the caret is in a nested controller and the outer one %s', ( _, addedBlocks ) => { 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 f81e1a0ef68167..21625165f6502a 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -524,8 +524,6 @@ export default function useBlockSync( { // 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. diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index fe83bbe0f739f5..61940674a67beb 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -520,10 +520,11 @@ function withPersistentBlockChange( reducer: Reducer< BlocksState > ) { // // 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. + // must not split a typing run into separate undo levels either. + // Another copy of the same entity updating its own clones while the + // entity is typed into elsewhere is such a change. One that does + // change those blocks, like an undo resetting them or updating them + // in place, still starts a new level. if ( pendingHistoryMode !== 'ignore' || ! leavesBlocksUntouched( state, nextState, lastAction ) diff --git a/packages/block-editor/src/store/test/reducer.ts b/packages/block-editor/src/store/test/reducer.ts index 99852fd5f90a0e..296cbc3d0a07eb 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -2713,9 +2713,10 @@ describe( 'state', () => { 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. + // two keystrokes, as a copy of the same entity does when + // it cannot update its clones in place. 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', @@ -2835,6 +2836,51 @@ describe( 'state', () => { expect( state.isPersistentChange ).toBe( true ); } ); + it( 'starts a persistent change after an ignored change updates the edited block', () => { + let state = deepFreeze( + blocks( undefined, { + type: 'RESET_BLOCKS', + blocks: [ + partial< Block >( { + clientId: 'kumquat', + attributes: {}, + innerBlocks: [], + } ), + ], + } ) + ); + + state = blocks( state, { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'kumquat' ], + attributes: { content: 'a' }, + } ); + expect( state.isPersistentChange ).toBe( true ); + + // An undo in a container updates its clones in place. + // The block is the same one, but its attributes now come + // from the entity, 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: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'kumquat' ], + attributes: { kumquat: { content: '' } }, + options: { uniqueByBlock: true }, + } ); + 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 0a6b72dc37ccf12475611f001bcd06f1cac5a698 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 12:52:34 -0600 Subject: [PATCH 20/33] Tests: Give the in-place update test's clones a real host block The hook ignores changes to the clones of a controller that has no block in the store, so the check that an in-place update is not reported back passed whatever the hook did. With a host block, it fails when the hook stops marking the update as incoming. Co-Authored-By: Claude Opus 5.5 --- .../provider/test/use-block-sync.jsdom.test.tsx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) 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 3652655ed15735..8a7b0fc44f4f57 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 @@ -717,7 +717,20 @@ describe( 'useBlockSync hook', () => { { - registry = reg; + if ( ! registry ) { + registry = reg; + // The hook ignores changes to the clones of a + // controller with no block in the store. + const host: TestBlock = { + name: 'test/test-block', + clientId: 'controller', + innerBlocks: [], + attributes: {}, + }; + reg.dispatch( blockEditorStore ).resetBlocks( [ + host, + ] as Block[] ); + } } } value={ [ block( { foo: 1 } ) ] } onChange={ onChange } From 3cddd7dc0ec3c6e47a985dffc277a95f3aea4b3c Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 24 Nov 2026 13:26:49 -0600 Subject: [PATCH 21/33] Tests: Pin the history and in-place checks of the duplicate fixes Three conditions had no test that fails without them: - a copy's in-place mirror of another copy's keystroke must be ignored by history, or each keystroke starts an undo level of its own; - the reducer rule must apply only to changes history ignores, or typing in a second block splits into one level per keystroke; - the nested-controller selection test must take the in-place path when it says it does. Also correct a reducer test comment that credited the block entry for what its attributes catch, and reuse the Post Content text helper. Co-Authored-By: Claude Opus 5.5 --- .../test/use-block-sync.jsdom.test.tsx | 55 ++++++++++++++++++- .../block-editor/src/store/test/reducer.ts | 48 +++++++++++++++- .../various/post-content-focus-mode.spec.js | 10 +--- 3 files changed, 99 insertions(+), 14 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 8a7b0fc44f4f57..275c6a563c613b 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 @@ -956,6 +956,52 @@ describe( 'useBlockSync hook', () => { expect( onChangeB ).not.toHaveBeenCalled(); } ); + // Copy B mirrors each keystroke in copy A. History ignores that, + // or every keystroke would start an undo level of its own. + it( 'keeps typing in one copy in a single undo level while another copy mirrors it', () => { + const { registry, update, select } = renderCanvas( [ + 'copy-a', + 'copy-b', + ] ); + let entity = [ paragraph( 'p', 0 ) ]; + const reports: string[] = []; + const controllers = () => [ + { + clientId: 'copy-a', + value: entity, + onChange: ( blocks: TestBlock[] ) => { + reports.push( 'change' ); + entity = blocks; + }, + onInput: ( blocks: TestBlock[] ) => { + reports.push( 'input' ); + entity = blocks; + }, + }, + { + clientId: 'copy-b', + value: entity, + onChange: vi.fn(), + onInput: vi.fn(), + }, + ]; + update( controllers() ); + const [ cloneA ] = select().getBlocks( 'copy-a' ); + + for ( const foo of [ 1, 2, 3 ] ) { + registry + .dispatch( blockEditorStore ) + .updateBlockAttributes( cloneA.clientId, { foo } ); + update( controllers() ); + } + + // The first keystroke opens an undo level and the rest join it. + expect( reports ).toEqual( [ 'change', 'input', 'input' ] ); + expect( select().getBlocks( 'copy-b' )[ 0 ].attributes.foo ).toBe( + 3 + ); + } ); + // Moving a block in one copy hands the other copy the same blocks // in another order. Updating its clones in place would leave each // mapped to the block that used to be there, so that an edit to one @@ -997,14 +1043,15 @@ describe( 'useBlockSync hook', () => { // Content. Re-cloning replaces the nested host, and the block the // caret was in with it, so the selection has to be repaired. it.each( [ - [ 'updates its clones in place', [] ], + [ 'updates its clones in place', [], true ], [ 're-clones, replacing the nested block', [ paragraph( 'added', 0 ) ], + false, ], ] )( 'restores the selection when the caret is in a nested controller and the outer one %s', - ( _, addedBlocks ) => { + ( _, addedBlocks, keepsClones ) => { const { update, select, selectBlock, selectionRef } = renderCanvas( [ 'outer' ] ); const outerBlock = paragraph( 'outer-block', 1 ); @@ -1020,6 +1067,7 @@ describe( 'useBlockSync hook', () => { value: [ paragraph( 'nested-block', 1 ) ], }; update( [ outer, nested ] ); + const [ outerBlockCloneBefore ] = select().getBlocks( 'outer' ); selectBlock( select().getBlocks( nestedHostClone.clientId )[ 0 ].clientId ); @@ -1044,6 +1092,9 @@ describe( 'useBlockSync hook', () => { const [ outerBlockClone ] = select().getBlocks( 'outer' ); expect( outerBlockClone.attributes.foo ).toBe( 0 ); + expect( + outerBlockClone.clientId === outerBlockCloneBefore.clientId + ).toBe( keepsClones ); expect( select().getSelectionStart().clientId ).toBe( outerBlockClone.clientId ); diff --git a/packages/block-editor/src/store/test/reducer.ts b/packages/block-editor/src/store/test/reducer.ts index 296cbc3d0a07eb..5ae56cb7338a09 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -2815,9 +2815,9 @@ describe( 'state', () => { } ); 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. + // An undo resets the blocks from the entity, bringing + // back the attributes from before the typing, so typing + // into the block again starts a new undo level. state = blocks( state, { type: 'MARK_NEXT_CHANGE_AS_NOT_PERSISTENT', history: 'ignore', @@ -2881,6 +2881,48 @@ describe( 'state', () => { expect( state.isPersistentChange ).toBe( true ); } ); + it( 'keeps typing in one block a single undo level after typing in another', () => { + let state = deepFreeze( + blocks( undefined, { + type: 'RESET_BLOCKS', + blocks: [ + partial< Block >( { + clientId: 'kumquat', + attributes: {}, + innerBlocks: [], + } ), + partial< Block >( { + clientId: 'loquat', + attributes: {}, + innerBlocks: [], + } ), + ], + } ) + ); + + state = blocks( state, { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'kumquat' ], + attributes: { content: 'a' }, + } ); + state = blocks( state, { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'loquat' ], + attributes: { content: 'b' }, + } ); + expect( state.isPersistentChange ).toBe( true ); + + // Typing on in the second block, which history does not + // ignore, joins the undo level its first keystroke + // opened. + state = blocks( state, { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'loquat' ], + attributes: { content: 'bc' }, + } ); + expect( state.isPersistentChange ).toBe( false ); + } ); + it( 'should retain reference for same state, same persistence', () => { const original = deepFreeze( blocks( undefined, { 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 d815ce3165b6a3..d68a1154c591f9 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 @@ -138,15 +138,7 @@ test.describe( 'Post Content focus mode', () => { } ); 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?.() - ); - } ); + const postContentText = () => postContentFocusMode.getPostContentText(); // Edit the first block, then the second, leaving the caret in the // second. From 907e332cc4dd01c6373bcb3d32f9a9e7eba02495 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 08:35:30 -0600 Subject: [PATCH 22/33] Block Editor: Spell recognizes the American way in useBlockSync Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/src/components/provider/use-block-sync.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 21625165f6502a..ba96da67043ad5 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -276,7 +276,7 @@ export default function useBlockSync( { // 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 + // external IDs, so each of them recognizes 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. From 9df1068bce60a36f307cf5ed493ed0a12907b6bb Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 13:37:03 -0600 Subject: [PATCH 23/33] Block Editor: Name the duplicate fix helpers for what they compare Rename hasSameFields to areBlockFieldsEqual and leavesBlocksUntouched to areLastUpdatedBlocksUnchanged, so that each name says what it compares, as suggested in review. Co-Authored-By: Claude Opus 5.5 --- .../src/components/provider/use-block-sync.ts | 6 +++--- packages/block-editor/src/store/reducer.ts | 11 ++++++----- 2 files changed, 9 insertions(+), 8 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 ba96da67043ad5..b46c717c2a58d1 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -110,9 +110,9 @@ function restoreSelectionIds( * * @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. + * @return Whether the blocks have equal fields. */ -function hasSameFields( block: Block, clone: Block ): boolean { +function areBlockFieldsEqual( block: Block, clone: Block ): boolean { for ( const key of new Set( [ ...Object.keys( block ), ...Object.keys( clone ), @@ -334,7 +334,7 @@ export default function useBlockSync( { idMappingRef.current.internalToExternal.get( clone.clientId ) === block.clientId && - hasSameFields( block, clone ) && + areBlockFieldsEqual( block, clone ) && ( areInnerBlocksControlled( clone.clientId ) || hasSameStructure( block.innerBlocks, clone.innerBlocks ) ) ); diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index 61940674a67beb..f0fb0a03991a56 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -221,16 +221,17 @@ function getAttributeUpdates( } /** - * Returns true if the blocks that the given action updated are the same in - * both states, or false otherwise. Only attribute updates are considered. + * Returns true if the blocks that the last action updated are unchanged + * between the two 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. + * @return Whether the blocks the last action updated are unchanged. */ -function leavesBlocksUntouched( +function areLastUpdatedBlocksUnchanged( state: BlocksState | undefined, nextState: BlocksState, lastAction: Action | undefined @@ -527,7 +528,7 @@ function withPersistentBlockChange( reducer: Reducer< BlocksState > ) { // in place, still starts a new level. if ( pendingHistoryMode !== 'ignore' || - ! leavesBlocksUntouched( state, nextState, lastAction ) + ! areLastUpdatedBlocksUnchanged( state, nextState, lastAction ) ) { lastAction = action; } From c41745e1e7cc7e9cfcab175838fb3b6188d8ad90 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 13:45:06 -0600 Subject: [PATCH 24/33] Block Editor: Count a selected duplicate controller as holding the selection The selection guard checked only the parents of the selected block, so a selection on another copy's own block did not count. Adding a link to a Navigation block can leave that Navigation block selected, and review caught the duplicate then restoring the previous link onto its own clone, pulling the selection into it. Count the selected block as well as its parents. Also say in the guard why it counts copies by block type rather than by a registered entity. Co-Authored-By: Claude Opus 5.5 --- .../test/use-block-sync.jsdom.test.tsx | 46 +++++++++++++++++++ .../src/components/provider/use-block-sync.ts | 23 ++++++---- 2 files changed, 61 insertions(+), 8 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 275c6a563c613b..0472411d07445f 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 @@ -956,6 +956,52 @@ describe( 'useBlockSync hook', () => { expect( onChangeB ).not.toHaveBeenCalled(); } ); + // Adding a link to a Navigation block can leave the Navigation block + // itself selected. That selection is in copy A too. + it( 'does not take the selection when another controller of the same entity is selected', () => { + const { registry, update, select, selectBlock, selectionRef } = + renderCanvas( [ 'copy-a', 'copy-b' ] ); + let entity = [ paragraph( 'p', 1 ) ]; + const onChangeA = ( blocks: TestBlock[] ) => ( 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() ); + selectBlock( 'copy-a' ); + selectionRef.current = { + selectionStart: { clientId: 'p' }, + selectionEnd: { clientId: 'p' }, + }; + + // Add a block to copy A, and hand the new entity to both copies. + registry + .dispatch( blockEditorStore ) + .replaceInnerBlocks( + 'copy-a', + [ + ...select().getBlocks( 'copy-a' ), + paragraph( 'added', 0 ) as Block, + ], + false + ); + update( controllers() ); + + expect( select().getBlocks( 'copy-b' ) ).toHaveLength( 2 ); + expect( select().getSelectionStart().clientId ).toBe( 'copy-a' ); + } ); + // Copy B mirrors each keystroke in copy A. History ignores that, // or every keystroke would start an undo level of its own. it( 'keeps typing in one copy in a single undo level while another copy mirrors it', () => { 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 b46c717c2a58d1..2989e0b2915778 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -307,17 +307,24 @@ export default function useBlockSync( { // the same block type, such as a second Navigation block. One of // another type, such as a Template Part around Post Title, renders // another entity, and the root block list belongs to no controller. + // The selected block counts as well as its parents: adding a link to + // a Navigation block can leave that Navigation block selected. // Two controllers of one type that render different entities, such - // as Template Parts on different slugs, count as copies too: telling - // them apart would need each controller to record its entity. - const parents = getBlockParents( currentStartClientId ); + // as Template Parts on different slugs, count as copies too. Telling + // them apart would need each controller to record its entity in the + // store. The block type is the simpler check, and where it is wrong + // it only skips a restore, leaving the selection where it is. + const holders = [ + ...getBlockParents( currentStartClientId ), + currentStartClientId, + ]; const blockName = getBlockName( clientId ); return ( - ! parents.includes( clientId ) && - parents.some( - ( parentId ) => - areInnerBlocksControlled( parentId ) && - getBlockName( parentId ) === blockName + ! holders.includes( clientId ) && + holders.some( + ( holderId ) => + areInnerBlocksControlled( holderId ) && + getBlockName( holderId ) === blockName ) ); }; From 2cc273c17abd6558d06afeae7d80c5b1ba2f74fc Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 13:45:12 -0600 Subject: [PATCH 25/33] Tests: Cover redo in a container duplicated from one entity One redo must bring the whole typed run back, in both containers. Co-Authored-By: Claude Opus 5.5 --- test/e2e/specs/site-editor/undo.spec.js | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/test/e2e/specs/site-editor/undo.spec.js b/test/e2e/specs/site-editor/undo.spec.js index b4488d9254fbc3..dc561513c70b76 100644 --- a/test/e2e/specs/site-editor/undo.spec.js +++ b/test/e2e/specs/site-editor/undo.spec.js @@ -144,6 +144,40 @@ test.describe( 'undo in a container duplicated from one entity', () => { // One undo level for one typed run, not one level per character. await expect( edited ).toHaveText( 'Some container content' ); } ); + + test( 'restores the entire typed run in both containers with one redo', 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 } ); + await expect( duplicate ).toHaveText( 'Some container contentHello' ); + + await pageUtils.pressKeys( 'primary+z' ); + await expect( edited ).toHaveText( 'Some container content' ); + await expect( duplicate ).toHaveText( 'Some container content' ); + + await pageUtils.pressKeys( 'primaryShift+z' ); + await expect( edited ).toHaveText( 'Some container contentHello' ); + await expect( duplicate ).toHaveText( 'Some container contentHello' ); + } ); } ); // Two Template Parts backed by different entities are two inner block From 99e86dafd0019cf1f99a8ac2ea2f788c2181ed2f Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 08:41:53 -0600 Subject: [PATCH 26/33] Block Editor: Unlock an unsynced pattern's blocks when undo removes its metadata When a container updates its inner blocks in place, an undo that removes the metadata of an unsynced pattern arrives as `metadata: undefined`. The derived editing modes only treated a truthy `metadata` as a change, so the pattern's blocks stayed content only until the page was reloaded. Count `metadata` as changed whenever the update includes it. Reported by ramonjd in review, with the fix. Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/src/store/reducer.ts | 5 +- .../block-editor/src/store/test/reducer.ts | 39 ++++++++++ .../various/post-content-focus-mode.spec.js | 74 +++++++++++++++++++ 3 files changed, 116 insertions(+), 2 deletions(-) diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index f0fb0a03991a56..ef91c079bb387a 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -3215,8 +3215,9 @@ export function withDerivedBlockEditingModes( reducer: Reducer< State > ) { // a regular block but was an unsynced pattern. // Check that `metadata` is part of the included attributes, as // `updateBlockAttributes` merges attributes, if it isn't present - // the previous `metadata` would be retained. - attributes.metadata && + // the previous `metadata` would be retained. It can be present + // but undefined, which removes it. + Object.hasOwn( attributes, 'metadata' ) && ! attributes.metadata?.patternName && state.blocks.attributes.get( clientId )?.metadata ?.patternName diff --git a/packages/block-editor/src/store/test/reducer.ts b/packages/block-editor/src/store/test/reducer.ts index 5ae56cb7338a09..0a7d75383aec91 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -6349,6 +6349,45 @@ describe( 'state', () => { expect( derivedBlockEditingModes ).toEqual( new Map() ); } ); + // An inner block controller sets a removed attribute to undefined + // when it updates its clones in place, as on undo. + it( 'removes block editing modes when the `metadata` attribute is removed from the unsynced pattern', () => { + const { derivedBlockEditingModes } = dispatchActions( + [ + { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'group-1' ], + attributes: { + 'group-1': { metadata: undefined }, + }, + options: { uniqueByBlock: true }, + }, + ], + testReducer, + initialState + ); + + expect( derivedBlockEditingModes ).toEqual( new Map() ); + } ); + + it( 'keeps block editing modes when an update leaves out the `metadata` attribute', () => { + const { derivedBlockEditingModes } = dispatchActions( + [ + { + type: 'UPDATE_BLOCK_ATTRIBUTES', + clientIds: [ 'group-1' ], + attributes: { className: 'updated' }, + }, + ], + testReducer, + initialState + ); + + expect( derivedBlockEditingModes ).toBe( + initialState.derivedBlockEditingModes + ); + } ); + it( 'allows explicitly set blockEditingModes to override the unsynced pattern editing modes', () => { const { derivedBlockEditingModes } = dispatchActions( [ 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 d68a1154c591f9..a47dacf9a1aa28 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 @@ -23,6 +23,7 @@ test.describe( 'Post Content focus mode', () => { await requestUtils.activateTheme( 'twentytwentyone' ); await requestUtils.resetPreferences(); await requestUtils.deleteAllPosts(); + await requestUtils.deleteAllBlocks(); } ); test( 'inserts blocks into Post Content from different selection states', async ( { @@ -227,6 +228,79 @@ test.describe( 'Post Content focus mode', () => { .toEqual( [ 'Hello-c world' ] ); } ); + test( 'undo of creating an unsynced pattern makes its blocks editable again', async ( { + admin, + editor, + page, + postContentFocusMode, + requestUtils, + } ) => { + // A Group without metadata, so undo removes the metadata entirely. + const { id } = await requestUtils.createPost( { + content: + '

One

Two

', + } ); + await admin.editPost( id ); + await postContentFocusMode.enableShowTemplate(); + await postContentFocusMode.waitForPostContentVisible(); + + const getGroupState = () => + page.evaluate( () => { + const { getBlocksByName, getBlocks, getBlockEditingMode } = + window.wp.data.select( 'core/block-editor' ); + const [ postContentId ] = + getBlocksByName( 'core/post-content' ); + const [ group ] = getBlocks( postContentId ); + return { + metadata: group.attributes.metadata ?? null, + innerBlockEditingModes: group.innerBlocks.map( ( block ) => + getBlockEditingMode( block.clientId ) + ), + }; + } ); + await expect.poll( getGroupState ).toEqual( { + metadata: null, + innerBlockEditingModes: [ 'default', 'default' ], + } ); + + await editor.selectBlocks( + editor.canvas.getByRole( 'document', { name: 'Block: Group' } ) + ); + await editor.showBlockToolbar(); + await page + .getByRole( 'toolbar', { name: 'Block tools' } ) + .getByRole( 'button', { name: 'Options' } ) + .click(); + await page.getByRole( 'menuitem', { name: 'Create pattern' } ).click(); + const createPatternDialog = page.getByRole( 'dialog', { + name: 'add pattern', + } ); + await createPatternDialog + .getByRole( 'textbox', { name: 'Name' } ) + .fill( 'Unsynced pattern' ); + await createPatternDialog + .getByRole( 'checkbox', { name: 'Synced' } ) + .setChecked( false ); + await createPatternDialog + .getByRole( 'button', { name: 'Add' } ) + .click(); + await expect + .poll( + async () => ( await getGroupState() ).innerBlockEditingModes + ) + .toEqual( [ 'contentOnly', 'contentOnly' ] ); + + await page + .getByRole( 'region', { name: 'Editor top bar' } ) + .getByRole( 'button', { name: 'Undo' } ) + .click(); + + await expect.poll( getGroupState ).toEqual( { + metadata: null, + innerBlockEditingModes: [ 'default', 'default' ], + } ); + } ); + // Check for regressions of https://github.com/WordPress/gutenberg/issues/76101. test.describe( 'post content inside a template part', () => { test.beforeAll( async ( { requestUtils } ) => { From 7b654f3038be379fba212a39cb1537c960b18290 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 15:06:20 -0600 Subject: [PATCH 27/33] Block Editor: Find duplicate controllers by what they render The selection guard counted any inner block controller of the same block type as a copy. That is wrong for two controllers of one type that render different entities, such as Template Parts on different slugs, or a Post Content block inside a block that features another post: an undo in one of them could not move the caret back while it sat in the other. Each controller now records what it renders in the block-editor store, one ID per controller, as suggested in review of #79929. The guard compares those IDs, and falls back to the block type for a controller that records none. The ID reaches useBlockSync through a private context that the controller block provides around its inner blocks. Co-Authored-By: Claude Opus 5.5 --- .../src/components/inner-blocks/index.tsx | 14 +- .../controlled-inner-blocks-source-context.ts | 11 ++ .../test/use-block-sync.jsdom.test.tsx | 126 +++++++++++++++++- .../src/components/provider/types.ts | 6 + .../src/components/provider/use-block-sync.ts | 52 ++++++-- packages/block-editor/src/private-apis.ts | 2 + .../block-editor/src/store/private-actions.ts | 21 +++ .../src/store/private-selectors.ts | 16 +++ packages/block-editor/src/store/reducer.ts | 32 +++++ packages/block-editor/src/store/types.ts | 6 + 10 files changed, 266 insertions(+), 20 deletions(-) create mode 100644 packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts diff --git a/packages/block-editor/src/components/inner-blocks/index.tsx b/packages/block-editor/src/components/inner-blocks/index.tsx index e343f77ac17ab3..cb8d4822980454 100644 --- a/packages/block-editor/src/components/inner-blocks/index.tsx +++ b/packages/block-editor/src/components/inner-blocks/index.tsx @@ -5,7 +5,7 @@ import type { } from 'react'; import clsx from 'clsx'; import { useMergeRefs } from '@wordpress/compose'; -import { forwardRef, useMemo, memo } from '@wordpress/element'; +import { forwardRef, useContext, useMemo, memo } from '@wordpress/element'; import { useSelect } from '@wordpress/data'; import { getBlockSupport, @@ -22,6 +22,7 @@ import { BlockContextProvider } from '../block-context'; import { useBlockEditContext } from '../block-edit/context'; import useAutoGridDrop from '../grid/use-auto-grid-drop'; import useBlockSync from '../provider/use-block-sync'; +import { ControlledInnerBlocksSourceContext } from '../provider/controlled-inner-blocks-source-context'; import { store as blockEditorStore } from '../../store'; import useBlockDropZone from '../use-block-drop-zone'; import { normalizeLegacyLayout } from '../../layouts/utils'; @@ -181,8 +182,15 @@ function UncontrolledInnerBlocks( props: InnerBlocksProps ) { * @param props The component props. */ function ControlledInnerBlocks( props: InnerBlocksProps ) { - useBlockSync( props ); - return ; + const source = useContext( ControlledInnerBlocksSourceContext ); + useBlockSync( { ...props, source } ); + // The source belongs to this controller alone, so a controller nested in + // it that provides none does not take it on. + return ( + + + + ); } // The statics are assigned below. diff --git a/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts b/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts new file mode 100644 index 00000000000000..8056748618b4a3 --- /dev/null +++ b/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts @@ -0,0 +1,11 @@ +import { createContext } from '@wordpress/element'; + +/** + * What the inner block controller below renders, such as the entity it syncs + * its inner blocks with. A block that controls its inner blocks provides it + * around its inner blocks, so that the controllers rendering the same source + * can tell that they are copies of each other. + */ +export const ControlledInnerBlocksSourceContext = createContext< + string | undefined +>( undefined ); 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 0472411d07445f..0a21dea9036d10 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 @@ -16,6 +16,7 @@ import withRegistryProvider from '../with-registry-provider'; import { SelectionContext } from '../selection-context'; import * as blockEditorActions from '../../../store/actions'; import { store as blockEditorStore } from '../../../store'; +import { unlock } from '../../../lock-unlock'; vi.mock( import( '../../../store/actions' ), async ( importOriginal ) => { const actions = await importOriginal(); return { @@ -876,16 +877,20 @@ describe( 'useBlockSync hook', () => { } ) as ComponentType< CanvasProps >; - function renderCanvas( hostClientIds: string[] ) { + function renderCanvas( + hostClientIds: string[], + hostNames: Record< string, 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[] + hostClientIds.map( ( clientId ) => ( { + ...paragraph( clientId, 0 ), + name: hostNames[ clientId ] ?? 'test/test-block', + } ) ) as Block[] ); } }; @@ -1192,6 +1197,119 @@ describe( 'useBlockSync hook', () => { ); } ); + // Template Parts on different slugs are controllers of one type that + // render different entities, so neither is a copy of the other. + it( 'restores the selection when the caret is in a controller of the same type rendering another source', () => { + const { update, select, selectBlock, selectionRef } = renderCanvas( + [ 'part' ] + ); + const part = { + clientId: 'part', + source: 'part-entity', + value: [ + paragraph( 'title', 0 ), + paragraph( 'content-host', 0 ), + ], + }; + update( [ part ] ); + const [ titleClone, contentHostClone ] = + select().getBlocks( 'part' ); + const content = { + clientId: contentHostClone.clientId, + source: 'content-entity', + value: [ paragraph( 'content-block', 1 ) ], + }; + update( [ part, content ] ); + selectBlock( titleClone.clientId ); + + // The undo reverts the content block and records the selection + // in it. + selectionRef.current = { + selectionStart: { clientId: 'content-block' }, + selectionEnd: { clientId: 'content-block' }, + }; + update( [ + part, + { ...content, value: [ paragraph( 'content-block', 0 ) ] }, + ] ); + + const [ contentBlockClone ] = select().getBlocks( + contentHostClone.clientId + ); + expect( contentBlockClone.attributes.foo ).toBe( 0 ); + expect( select().getSelectionStart().clientId ).toBe( + contentBlockClone.clientId + ); + } ); + + // What a controller renders decides whether it is a copy, not the + // type of the block that renders it. + it( 'does not take the selection from a controller of another type rendering the same source', () => { + const { registry, update, select, selectBlock, selectionRef } = + renderCanvas( [ 'copy-a', 'copy-b' ], { + 'copy-b': 'test/other-block', + } ); + let entity = [ paragraph( 'p', 1 ) ]; + const onChangeA = ( blocks: TestBlock[] ) => ( entity = blocks ); + const controllers = () => [ + { + clientId: 'copy-a', + source: 'entity', + value: entity, + onChange: onChangeA, + onInput: onChangeA, + }, + { + clientId: 'copy-b', + source: 'entity', + value: entity, + onChange: vi.fn(), + onInput: vi.fn(), + }, + ]; + update( controllers() ); + const [ cloneA ] = select().getBlocks( 'copy-a' ); + selectBlock( cloneA.clientId ); + selectionRef.current = { + selectionStart: { clientId: 'p' }, + selectionEnd: { clientId: 'p' }, + }; + + registry + .dispatch( blockEditorStore ) + .updateBlockAttributes( cloneA.clientId, { foo: 2 } ); + update( controllers() ); + + expect( select().getBlocks( 'copy-b' )[ 0 ].attributes.foo ).toBe( + 2 + ); + expect( select().getSelectionStart().clientId ).toBe( + cloneA.clientId + ); + } ); + + // A Navigation block that switches menus renders another entity. + it( 'records its source in the store until it unmounts', () => { + const { update, select } = renderCanvas( [ 'controller' ] ); + const source = () => + unlock( select() ).getControlledInnerBlocksSource( + 'controller' + ); + const controller = { + clientId: 'controller', + value: [ paragraph( 'p', 0 ) ], + }; + + update( [ { ...controller, source: 'menu-1' } ] ); + expect( source() ).toBe( 'menu-1' ); + + update( [ { ...controller, source: 'menu-2' } ] ); + expect( source() ).toBe( 'menu-2' ); + + update( [] ); + expect( source() ).toBeUndefined(); + } ); + // The undo level that typing opens starts from the selection the // last undo restored, so undoing it hands back that same selection // object. diff --git a/packages/block-editor/src/components/provider/types.ts b/packages/block-editor/src/components/provider/types.ts index 8c1ee86e25f9b5..b7ddfb34762dca 100644 --- a/packages/block-editor/src/components/provider/types.ts +++ b/packages/block-editor/src/components/provider/types.ts @@ -88,6 +88,12 @@ export interface UseBlockSyncProps { * Called when a non-persistent change has been made. */ onInput?: OnBlockUpdate; + /** + * What the controller renders, such as the entity it syncs its inner + * blocks with. Controllers that render the same source are copies of + * each other. + */ + source?: string; } /** 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 2989e0b2915778..b0415eb428a7ad 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -3,6 +3,7 @@ import { useRegistry } from '@wordpress/data'; import { cloneBlock } from '@wordpress/blocks'; import type { Block } from '@wordpress/blocks'; import { store as blockEditorStore } from '../../store'; +import { unlock } from '../../lock-unlock'; import { SelectionContext } from './selection-context'; import type { BlockSelection } from '../../store/types'; import type { @@ -168,12 +169,17 @@ function areBlockFieldsEqual( block: Block, clone: Block ): boolean { * change has been made in the block-editor blocks * for the given clientId. When this is called, * controlling sources do not become dirty. + * @param props.source What the inner block controller renders, such as + * the entity it syncs its inner blocks with. + * Controllers that render the same source are + * copies of each other. */ export default function useBlockSync( { clientId = null, value: controlledBlocks, onChange = noop, onInput = noop, + source, }: UseBlockSyncProps ) { const registry = useRegistry(); const { getSelection, onChangeSelection } = useContext( SelectionContext ); @@ -194,6 +200,12 @@ export default function useBlockSync( { getBlockParents, areInnerBlocksControlled, } = registry.select( blockEditorStore ); + const { setControlledInnerBlocksSource } = unlock( + registry.dispatch( blockEditorStore ) + ); + const { getControlledInnerBlocksSource } = unlock( + registry.select( blockEditorStore ) + ); const pendingChangesRef = useRef< { incoming: Block[] | null; @@ -303,28 +315,32 @@ export default function useBlockSync( { // 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, another copy is a controller of - // the same block type, such as a second Navigation block. One of - // another type, such as a Template Part around Post Title, renders - // another entity, and the root block list belongs to no controller. - // The selected block counts as well as its parents: adding a link to - // a Navigation block can leave that Navigation block selected. - // Two controllers of one type that render different entities, such - // as Template Parts on different slugs, count as copies too. Telling - // them apart would need each controller to record its entity in the - // store. The block type is the simpler check, and where it is wrong - // it only skips a restore, leaving the selection where it is. + // inside Post Content. Outside it, another copy is a controller that + // renders the same source, such as a second Navigation block on the + // same menu. One that renders another source, such as a Template + // Part on another slug, is not a copy, and the root block list + // belongs to no controller. The selected block counts as well as its + // parents: adding a link to a Navigation block can leave that + // Navigation block selected. + // A controller that does not record its source counts as a copy of + // any controller of the same block type, since a copy of one entity + // is always rendered by the same kind of block. const holders = [ ...getBlockParents( currentStartClientId ), currentStartClientId, ]; const blockName = getBlockName( clientId ); + const isCopy = ( holderId: string ) => { + const holderSource = getControlledInnerBlocksSource( holderId ); + return source && holderSource + ? holderSource === source + : getBlockName( holderId ) === blockName; + }; return ( ! holders.includes( clientId ) && holders.some( ( holderId ) => - areInnerBlocksControlled( holderId ) && - getBlockName( holderId ) === blockName + areInnerBlocksControlled( holderId ) && isCopy( holderId ) ) ); }; @@ -495,6 +511,16 @@ export default function useBlockSync( { onChangeRef.current = onChange; }, [ onInput, onChange ] ); + // Record what this controller renders, so that the other controllers can + // tell whether it is a copy of them. + useEffect( () => { + if ( ! clientId || ! source ) { + return; + } + setControlledInnerBlocksSource( clientId, source ); + return () => setControlledInnerBlocksSource( clientId, undefined ); + }, [ clientId, source, setControlledInnerBlocksSource ] ); + // Determine if blocks need to be reset when they change. // Also restores selection from context after blocks are set. useEffect( () => { diff --git a/packages/block-editor/src/private-apis.ts b/packages/block-editor/src/private-apis.ts index 439748ab92eaa6..25100e058144ea 100644 --- a/packages/block-editor/src/private-apis.ts +++ b/packages/block-editor/src/private-apis.ts @@ -1,6 +1,7 @@ import { privateApis as globalStylesEnginePrivateApis } from '@wordpress/global-styles-engine'; import * as globalStyles from './components/global-styles'; import { ExperimentalBlockEditorProvider } from './components/provider'; +import { ControlledInnerBlocksSourceContext } from './components/provider/controlled-inner-blocks-source-context'; import { lock, unlock } from './lock-unlock'; import { getRichTextValues } from './components/rich-text/get-rich-text-values'; import ResizableBoxPopover from './components/resizable-box-popover'; @@ -91,6 +92,7 @@ const { getDuotoneFilter } = unlock( globalStylesEnginePrivateApis ); export const privateApis = {}; lock( privateApis, { ...globalStyles, + ControlledInnerBlocksSourceContext, PrivateBlockInspectorEditOriginal, ExperimentalBlockCanvas, BlockCanvasCover, diff --git a/packages/block-editor/src/store/private-actions.ts b/packages/block-editor/src/store/private-actions.ts index 4873125a00fd2a..babe61db1b1c42 100644 --- a/packages/block-editor/src/store/private-actions.ts +++ b/packages/block-editor/src/store/private-actions.ts @@ -90,6 +90,27 @@ export function __experimentalUpdateSettings( }; } +/** + * Records what an inner block controller renders, such as the entity it syncs + * its inner blocks with. Controllers that render the same source are copies of + * each other. + * + * @param clientId The client ID of the inner block controller. + * @param source What the controller renders, or undefined to clear it. + * + * @return Action object. + */ +export function setControlledInnerBlocksSource( + clientId: string, + source: string | undefined +) { + return { + type: 'SET_CONTROLLED_INNER_BLOCKS_SOURCE', + clientId, + source, + }; +} + /** * Hides the block interface (eg. toolbar, outline, etc.) * diff --git a/packages/block-editor/src/store/private-selectors.ts b/packages/block-editor/src/store/private-selectors.ts index c0cf569beaaf80..482d2c75d09451 100644 --- a/packages/block-editor/src/store/private-selectors.ts +++ b/packages/block-editor/src/store/private-selectors.ts @@ -98,6 +98,22 @@ export function isBlockInterfaceHidden( state: State ) { return state.isBlockInterfaceHidden; } +/** + * Returns what an inner block controller renders, such as the entity it syncs + * its inner blocks with, if the controller recorded it. + * + * @param state Global application state. + * @param clientId The client ID of the inner block controller. + * + * @return What the controller renders, or undefined. + */ +export function getControlledInnerBlocksSource( + state: State, + clientId: string +) { + return state.controlledInnerBlocksSources.get( clientId ); +} + /** * Gets the client ids of the last inserted blocks. * diff --git a/packages/block-editor/src/store/reducer.ts b/packages/block-editor/src/store/reducer.ts index ef91c079bb387a..bec6e6770ec1e6 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -2655,8 +2655,40 @@ export function isResponsiveEditing( return state; } +/** + * Reducer returning what each inner block controller renders, such as the + * entity it syncs its inner blocks with, keyed by the controller's client ID. + * Controllers that render the same source are copies of each other. + * + * @param state Current state. + * @param action Dispatched action. + * + * @return Updated state. + */ +export function controlledInnerBlocksSources( + state: State[ 'controlledInnerBlocksSources' ] = new Map(), + action: Action +) { + if ( action.type !== 'SET_CONTROLLED_INNER_BLOCKS_SOURCE' ) { + return state; + } + + if ( state.get( action.clientId ) === action.source ) { + return state; + } + + const newState = new Map( state ); + if ( action.source === undefined ) { + newState.delete( action.clientId ); + } else { + newState.set( action.clientId, action.source ); + } + return newState; +} + const combinedReducers = combineReducers( { blocks, + controlledInnerBlocksSources, isDragging, isTyping, isBlockInterfaceHidden, diff --git a/packages/block-editor/src/store/types.ts b/packages/block-editor/src/store/types.ts index 652e54428655c1..befd366a4e6a82 100644 --- a/packages/block-editor/src/store/types.ts +++ b/packages/block-editor/src/store/types.ts @@ -573,6 +573,7 @@ export interface SelectedBlockStyleState { export interface State { blocks: BlocksState; + controlledInnerBlocksSources: Map< string, string >; isDragging: boolean; isTyping: boolean; isBlockInterfaceHidden: boolean; @@ -764,6 +765,11 @@ export type Action = clientId: string; hasControlledInnerBlocks: boolean; } + | { + type: 'SET_CONTROLLED_INNER_BLOCKS_SOURCE'; + clientId: string; + source: string | undefined; + } | { type: 'SET_INSERTION_POINT'; value: InsertionPoint | null } | { type: 'SET_OPEN_LIST_VIEW_PANEL'; clientId: string | null } | { type: 'SET_RESPONSIVE_EDITING'; enabled: boolean } From 04bb8c1115d2faa6e8f6ef673377bb4e92d336f9 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 15:06:28 -0600 Subject: [PATCH 28/33] Block Library: Say what Navigation, Post Content and Template Part render Provide each controller's entity to its inner blocks, so that the selection guard can tell copies of one entity from controllers of the same block type that render another. Synced patterns are left out: each instance parses the pattern with its own overrides and never shares edits with the others, so they fall back to the block type. Co-Authored-By: Claude Opus 5.5 --- .../src/navigation/edit/inner-blocks.jsx | 15 +++++++++-- .../block-library/src/post-content/edit.tsx | 26 +++++++++++++------ .../src/template-part/edit/inner-blocks.tsx | 12 ++++++++- 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/packages/block-library/src/navigation/edit/inner-blocks.jsx b/packages/block-library/src/navigation/edit/inner-blocks.jsx index bf248a8c966e91..f6089148b3c49e 100644 --- a/packages/block-library/src/navigation/edit/inner-blocks.jsx +++ b/packages/block-library/src/navigation/edit/inner-blocks.jsx @@ -1,13 +1,17 @@ -import { useEntityBlockEditor } from '@wordpress/core-data'; +import { useEntityBlockEditor, useEntityId } from '@wordpress/core-data'; import { useInnerBlocksProps, InnerBlocks, store as blockEditorStore, + privateApis as blockEditorPrivateApis, } from '@wordpress/block-editor'; import { useSelect } from '@wordpress/data'; import { useMemo } from '@wordpress/element'; import PlaceholderPreview from './placeholder/placeholder-preview'; import { DEFAULT_BLOCK, PRIORITIZED_INSERTER_BLOCKS } from '../constants'; +import { unlock } from '../../lock-unlock'; + +const { ControlledInnerBlocksSourceContext } = unlock( blockEditorPrivateApis ); export default function NavigationInnerBlocks( { clientId, @@ -49,6 +53,7 @@ export default function NavigationInnerBlocks( { 'postType', 'wp_navigation' ); + const menuId = useEntityId( 'postType', 'wp_navigation' ); // When the block is selected itself or has a top level item selected that // doesn't itself have children, show the standard appender. Else show no @@ -100,5 +105,11 @@ export default function NavigationInnerBlocks( { } ); - return
; + return ( + +
+ + ); } diff --git a/packages/block-library/src/post-content/edit.tsx b/packages/block-library/src/post-content/edit.tsx index f64f56a41da3a5..d7a0e121184347 100644 --- a/packages/block-library/src/post-content/edit.tsx +++ b/packages/block-library/src/post-content/edit.tsx @@ -22,7 +22,9 @@ import { useCanEditEntity } from '../utils/hooks'; import { unlock } from '../lock-unlock'; import type { PostContentAttributes, PostContentBlockContext } from './types'; -const { HTMLElementControl } = unlock( blockEditorPrivateApis ); +const { HTMLElementControl, ControlledInnerBlocksSourceContext } = unlock( + blockEditorPrivateApis +); type TagNameType = 'div' | 'main' | 'section' | 'article'; @@ -140,13 +142,21 @@ function EditableContent( { } return ( - + + + ); } diff --git a/packages/block-library/src/template-part/edit/inner-blocks.tsx b/packages/block-library/src/template-part/edit/inner-blocks.tsx index 085156285c0aa7..1e345e61391ea2 100644 --- a/packages/block-library/src/template-part/edit/inner-blocks.tsx +++ b/packages/block-library/src/template-part/edit/inner-blocks.tsx @@ -7,12 +7,16 @@ import { useSettings, store as blockEditorStore, useBlockEditingMode, + privateApis as blockEditorPrivateApis, } from '@wordpress/block-editor'; import { useSelect } from '@wordpress/data'; import { useMemo } from '@wordpress/element'; import { parse } from '@wordpress/blocks'; import type { Block } from '@wordpress/blocks'; import type { TemplatePartAttributes } from '../types'; +import { unlock } from '../../lock-unlock'; + +const { ControlledInnerBlocksSourceContext } = unlock( blockEditorPrivateApis ); type EditorLayout = NonNullable< Parameters< typeof useInnerBlocksProps >[ 1 ] @@ -154,7 +158,13 @@ function EditableTemplatePartInnerBlocks( { } : {}; - return ; + return ( + + + + ); } export default function TemplatePartInnerBlocks( { From 472ca652d8b22e9fdbb421cb732e910b85f3df94 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 15:06:33 -0600 Subject: [PATCH 29/33] Tests: Cover undo from the Post Content of another post A block that features another post renders that post's Post Content, a controller of the same type as the current post's but of another entity. A caret in it must not stop an undo in the current post's Post Content from moving the caret back. The test plugin gains a block that provides the post context, standing in for such a block. Co-Authored-By: Claude Opus 5.5 --- packages/e2e-tests/plugins/block-context.php | 20 ++++ .../e2e-tests/plugins/block-context/index.js | 32 +++++++ .../various/post-content-focus-mode.spec.js | 92 +++++++++++++++++++ 3 files changed, 144 insertions(+) diff --git a/packages/e2e-tests/plugins/block-context.php b/packages/e2e-tests/plugins/block-context.php index a251e9763e5253..14619813682e43 100644 --- a/packages/e2e-tests/plugins/block-context.php +++ b/packages/e2e-tests/plugins/block-context.php @@ -39,6 +39,26 @@ function gutenberg_test_register_context_blocks() { ) ); + register_block_type( + 'gutenberg/test-post-context-provider', + array( + 'attributes' => array( + 'postId' => array( + 'type' => 'number', + ), + 'postType' => array( + 'type' => 'string', + 'default' => 'post', + ), + ), + 'provides_context' => array( + 'postId' => 'postId', + 'postType' => 'postType', + ), + 'editor_script_handles' => array( 'gutenberg-test-block-context' ), + ) + ); + register_block_type( 'gutenberg/test-context-consumer', array( diff --git a/packages/e2e-tests/plugins/block-context/index.js b/packages/e2e-tests/plugins/block-context/index.js index bd452f49bd81c3..2dc704f2cf3953 100644 --- a/packages/e2e-tests/plugins/block-context/index.js +++ b/packages/e2e-tests/plugins/block-context/index.js @@ -46,6 +46,38 @@ }, } ); + // Provides the post context of another post to its inner blocks, as a + // block that features a post would. + registerBlockType( 'gutenberg/test-post-context-provider', { + apiVersion: 3, + title: 'Test Post Context Provider', + + icon: 'list-view', + + attributes: { + postId: { type: 'number' }, + postType: { type: 'string', default: 'post' }, + }, + + // TODO: While redundant with server-side registration, it's required + // to assign this value since it is not picked in the implementation of + // `get_block_editor_server_block_settings`. + providesContext: { + postId: 'postId', + postType: 'postType', + }, + + category: 'text', + + edit: function Edit() { + return el( 'div', useInnerBlocksProps( useBlockProps() ) ); + }, + + save() { + return el( InnerBlocks.Content ); + }, + } ); + registerBlockType( 'gutenberg/test-context-consumer', { apiVersion: 3, title: 'Test Context Consumer', 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 a47dacf9a1aa28..a25cc7c541c4d7 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 @@ -715,6 +715,82 @@ test.describe( 'Post Content focus mode', () => { ).toEqual( [] ); } ); } ); + + // A block that features another post renders that post's Post Content, + // which is an inner block controller of the same type as the current + // post's, but of another entity. A caret in it must not stop an undo in + // the current post's Post Content from moving the caret back. + test.describe( 'post content of another post', () => { + let otherPostId; + + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'emptytheme' ); + await requestUtils.activatePlugin( 'gutenberg-test-block-context' ); + ( { id: otherPostId } = await requestUtils.createPost( { + title: 'Other post', + status: 'publish', + content: + '

Other post content

', + } ) ); + 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' ); + await requestUtils.deleteAllPosts(); + await requestUtils.deactivatePlugin( + 'gutenberg-test-block-context' + ); + } ); + + test( 'undo moves the caret back into Post Content from the Post Content of another post', async ( { + admin, + editor, + page, + pageUtils, + postContentFocusMode, + requestUtils, + } ) => { + // A saved paragraph, so no undo level can remove it. + const { id } = await requestUtils.createPost( { + content: + '

Initial content

', + } ); + await admin.editPost( id ); + await postContentFocusMode.enableShowTemplate(); + + const edited = editor.canvas.getByText( 'Initial content' ); + await edited.click(); + await page.keyboard.press( 'End' ); + await postContentFocusMode.waitForPostContentVisible(); + await page.keyboard.type( '-a' ); + await expect( edited ).toHaveText( 'Initial content-a' ); + + // Move the caret into the other post's content. + await editor.canvas.getByText( 'Other post content' ).click(); + await expect + .poll( () => postContentFocusMode.getSelectedBlockContent() ) + .toBe( 'Other post content' ); + + await pageUtils.pressKeys( 'primary+z' ); + await expect( edited ).toHaveText( 'Initial content' ); + + expect( await postContentFocusMode.getSelectedBlockContent() ).toBe( + 'Initial content' + ); + } ); + } ); } ); class PostContentFocusMode { @@ -804,6 +880,22 @@ class PostContentFocusMode { } ); } + /** + * Returns the text content of the selected block. + * + * @return {Promise} The selected block's content, or null. + */ + async getSelectedBlockContent() { + return await this.page.evaluate( () => { + const { getSelectedBlockClientId, getBlockAttributes } = + window.wp.data.select( 'core/block-editor' ); + const clientId = getSelectedBlockClientId(); + return clientId + ? ( getBlockAttributes( clientId ).content?.toString() ?? null ) + : null; + } ); + } + /** * Waits until the canvas counts Post Content as visible, which it reports * a moment after rendering. Until then, Post Content is neither selected From d397db49571649c095b7633cb0366e190be25f4d Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 15:07:57 -0600 Subject: [PATCH 30/33] Block Editor: Point the duplicate controllers changelog entry at #87777 Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index 16a3cca5cbbf05..e1241c60ad190f 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -43,7 +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 the same entity, such as two Navigation blocks on the same menu, two Post Content blocks, or two Template Parts on the same slug, no longer move the selection into each other, lose keystrokes, or split typing in one of them into an undo level per character ([#82706](https://github.com/WordPress/gutenberg/pull/82706)). +- Inner block controllers rendering the same entity, such as two Navigation blocks on the same menu, two Post Content blocks, or two Template Parts on the same slug, no longer move the selection into each other, lose keystrokes, or split typing in one of them into an undo level per character ([#87777](https://github.com/WordPress/gutenberg/pull/87777)). ### Internal From 8c23ddcb00c94c05a6c77be7c5695492b779596b Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 16:13:49 -0600 Subject: [PATCH 31/33] Block Editor: Say the selection guard looks for copies The comment above the guard still said it looked for controllers of the same block type. Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/src/components/provider/use-block-sync.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b0415eb428a7ad..b97a9f44d171ab 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -283,7 +283,7 @@ export default function useBlockSync( { }; // Whether the block-editor's current selection sits inside a *different* - // inner block controller of the same block type. + // inner block controller that is a copy of this one. // // Several controllers can render one entity — two Navigation blocks using // the same menu, two Post Content blocks showing the same post. Each keeps From 7b470144ecebcc8773997487efa7a76105c9a0d8 Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Tue, 1 Dec 2026 16:13:55 -0600 Subject: [PATCH 32/33] Tests: Pin the entity each inner block controller records Nothing on the canvas shows a Navigation block's or a Template Part's source yet, so a missing one would only make the guard fall back to the block type, and every other test would still pass. Read the sources from the store instead: copies record the same one, different entities differ, and a synced pattern inside a template part records none rather than taking on the template part's. Co-Authored-By: Claude Opus 5.5 --- .../site-editor/controller-sources.spec.ts | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 test/e2e/specs/site-editor/controller-sources.spec.ts diff --git a/test/e2e/specs/site-editor/controller-sources.spec.ts b/test/e2e/specs/site-editor/controller-sources.spec.ts new file mode 100644 index 00000000000000..4a91b6198a4aa1 --- /dev/null +++ b/test/e2e/specs/site-editor/controller-sources.spec.ts @@ -0,0 +1,137 @@ +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; + +const PRIVATE_APIS_CONSENT = + 'I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.'; + +const MENU_CONTENT = + ''; + +// Inner block controllers that render the same entity are copies of each +// other, so each records the entity it renders. Nothing on the canvas shows +// these yet, since only an undo into a nested entity would, so they're read +// from the store. +test.describe( 'Inner block controller sources', () => { + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'emptytheme' ); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await requestUtils.deleteAllTemplates( 'wp_template' ); + await requestUtils.deleteAllTemplates( 'wp_template_part' ); + await requestUtils.deleteAllMenus(); + await requestUtils.deleteAllBlocks(); + await requestUtils.activateTheme( 'twentytwentyone' ); + } ); + + test( 'records the entity each controller renders', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + const menuA = await requestUtils.createNavigationMenu( { + title: 'Menu A', + content: MENU_CONTENT, + } ); + const menuB = await requestUtils.createNavigationMenu( { + title: 'Menu B', + content: MENU_CONTENT, + } ); + const pattern = await requestUtils.createBlock( { + title: 'Synced pattern', + status: 'publish', + content: + '

Synced pattern content

', + } ); + // A synced pattern controls its inner blocks but records no entity, + // so it must not take on the source of the template part around it. + await requestUtils.createTemplate( 'wp_template_part', { + slug: 'part-a', + title: 'Part A', + content: ``, + } ); + await requestUtils.createTemplate( 'wp_template_part', { + slug: 'part-b', + title: 'Part B', + content: + '

Part B content

', + } ); + + await admin.visitSiteEditor( { + postId: 'emptytheme//index', + postType: 'wp_template', + canvas: 'edit', + } ); + for ( const ref of [ menuA.id, menuA.id, menuB.id ] ) { + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref }, + } ); + } + for ( const slug of [ 'part-a', 'part-b' ] ) { + await editor.insertBlock( { + name: 'core/template-part', + attributes: { slug, theme: 'emptytheme' }, + } ); + } + await expect( + editor.canvas.getByText( 'Synced pattern content' ) + ).toBeVisible(); + await expect( + editor.canvas.getByText( 'Part B content' ) + ).toBeVisible(); + + await expect + .poll( () => + page.evaluate( ( consent ) => { + const { unlock } = ( + window as any + ).wp.privateApis.__dangerousOptInToUnstableAPIsOnlyForCoreModules( + consent, + '@wordpress/core-data' + ); + const select = window.wp.data.select( 'core/block-editor' ); + const { getControlledInnerBlocksSource } = unlock( select ); + const sources = ( name: string ) => + select + .getBlocksByName( name ) + .map( + ( clientId: string ) => + getControlledInnerBlocksSource( + clientId + ) ?? 'none' + ) + .sort(); + // The theme's own header is a template part too. + const partSources = Object.fromEntries( + select + .getBlocksByName( 'core/template-part' ) + .map( ( clientId: string ) => [ + select.getBlockAttributes( clientId ).slug, + getControlledInnerBlocksSource( clientId ), + ] ) + .filter( ( [ slug ]: [ string ] ) => + slug.startsWith( 'part-' ) + ) + ); + return { + navigation: sources( 'core/navigation' ), + templatePart: partSources, + syncedPattern: sources( 'core/block' ), + }; + }, PRIVATE_APIS_CONSENT ) + ) + .toEqual( { + navigation: [ + `postType/wp_navigation/${ menuA.id }`, + `postType/wp_navigation/${ menuA.id }`, + `postType/wp_navigation/${ menuB.id }`, + ].sort(), + templatePart: { + 'part-a': 'postType/wp_template_part/emptytheme//part-a', + 'part-b': 'postType/wp_template_part/emptytheme//part-b', + }, + syncedPattern: [ 'none' ], + } ); + } ); +} ); From 5e3fa643a9fd8760f8c0cede52e9b2842312ca2f Mon Sep 17 00:00:00 2001 From: Jerry Jones Date: Wed, 2 Dec 2026 08:47:59 -0600 Subject: [PATCH 33/33] Block Editor: Take a controller's sync source as an inner blocks option A block passes what its controlled inner blocks render as `syncSource`, next to `value`, `onInput` and `onChange`, in place of a private context around its inner blocks. Nothing is inherited, so a nested controller no longer needs the context reset, and third-party controllers can pass one too. Synced patterns now pass theirs as well: like a Template Part, each renders one entity, and two different patterns are not copies. Suggested by talldan in review. Co-Authored-By: Claude Opus 5.5 --- packages/block-editor/CHANGELOG.md | 1 + .../src/components/inner-blocks/README.md | 18 ++++++ .../src/components/inner-blocks/index.tsx | 14 +---- .../src/components/inner-blocks/types.ts | 2 +- .../controlled-inner-blocks-source-context.ts | 11 ---- .../test/use-block-sync.jsdom.test.tsx | 12 ++-- .../src/components/provider/types.ts | 2 +- .../src/components/provider/use-block-sync.ts | 56 +++++++++---------- packages/block-editor/src/private-apis.ts | 2 - packages/block-library/src/block/edit.tsx | 1 + .../src/navigation/edit/inner-blocks.jsx | 15 ++--- .../block-library/src/post-content/edit.tsx | 26 ++++----- .../src/template-part/edit/inner-blocks.tsx | 13 +---- .../site-editor/controller-sources.spec.ts | 6 +- 14 files changed, 80 insertions(+), 99 deletions(-) delete mode 100644 packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index e1241c60ad190f..00d5bc0cb4130e 100644 --- a/packages/block-editor/CHANGELOG.md +++ b/packages/block-editor/CHANGELOG.md @@ -8,6 +8,7 @@ - Add `getTransformClassesAndStyles()`, for blocks that apply transform styles to an inner element ([#86240](https://github.com/WordPress/gutenberg/pull/86240)). - Add an Offset control with X and Y axes to the Transform panel, for the `transform.translate` block support ([#86282](https://github.com/WordPress/gutenberg/pull/86282)). - Add a Scale control to the Transform panel, for the `transform.scale` block support ([#86727](https://github.com/WordPress/gutenberg/pull/86727)). +- `useInnerBlocksProps`, `InnerBlocks`: Add a `syncSource` option that names what controlled inner blocks render, such as the entity they sync with. Blocks that render the same source are treated as copies of each other ([#87777](https://github.com/WordPress/gutenberg/pull/87777)). ### Enhancements diff --git a/packages/block-editor/src/components/inner-blocks/README.md b/packages/block-editor/src/components/inner-blocks/README.md index 8a0525b2807317..47848993697a28 100644 --- a/packages/block-editor/src/components/inner-blocks/README.md +++ b/packages/block-editor/src/components/inner-blocks/README.md @@ -212,3 +212,21 @@ const DEFAULT_BLOCK = { name: 'core/paragraph', attributes: { content: 'Lorem ip When `true`, the appender inserts `defaultBlock` directly and skips the inserter dropdown, **including any registered inserter variations** of that block type. Use this to opt out of the variation picker; otherwise leave unset. Note: redundant when `allowedBlocks` resolves to a single block type with no variations, the appender already inserts directly. + +### `syncSource` + +- **Type:** `String` +- **Default:** `undefined`. + +For inner blocks controlled with `value` and `onChange`: a name for what they render, such as the entity they sync with. Blocks that render one source in several places, such as two Navigation blocks on the same menu, pass the same `syncSource`, so that editing one copy doesn't move the selection into another. + +```jsx +const innerBlocksProps = useInnerBlocksProps( blockProps, { + value: blocks, + onInput, + onChange, + syncSource: `postType/wp_navigation/${ menuId }`, +} ); +``` + +Controlled inner blocks without a `syncSource` count as copies of any controlled inner blocks of the same block type. diff --git a/packages/block-editor/src/components/inner-blocks/index.tsx b/packages/block-editor/src/components/inner-blocks/index.tsx index cb8d4822980454..e343f77ac17ab3 100644 --- a/packages/block-editor/src/components/inner-blocks/index.tsx +++ b/packages/block-editor/src/components/inner-blocks/index.tsx @@ -5,7 +5,7 @@ import type { } from 'react'; import clsx from 'clsx'; import { useMergeRefs } from '@wordpress/compose'; -import { forwardRef, useContext, useMemo, memo } from '@wordpress/element'; +import { forwardRef, useMemo, memo } from '@wordpress/element'; import { useSelect } from '@wordpress/data'; import { getBlockSupport, @@ -22,7 +22,6 @@ import { BlockContextProvider } from '../block-context'; import { useBlockEditContext } from '../block-edit/context'; import useAutoGridDrop from '../grid/use-auto-grid-drop'; import useBlockSync from '../provider/use-block-sync'; -import { ControlledInnerBlocksSourceContext } from '../provider/controlled-inner-blocks-source-context'; import { store as blockEditorStore } from '../../store'; import useBlockDropZone from '../use-block-drop-zone'; import { normalizeLegacyLayout } from '../../layouts/utils'; @@ -182,15 +181,8 @@ function UncontrolledInnerBlocks( props: InnerBlocksProps ) { * @param props The component props. */ function ControlledInnerBlocks( props: InnerBlocksProps ) { - const source = useContext( ControlledInnerBlocksSourceContext ); - useBlockSync( { ...props, source } ); - // The source belongs to this controller alone, so a controller nested in - // it that provides none does not take it on. - return ( - - - - ); + useBlockSync( props ); + return ; } // The statics are assigned below. diff --git a/packages/block-editor/src/components/inner-blocks/types.ts b/packages/block-editor/src/components/inner-blocks/types.ts index 570b3b45235e71..ca8df3e3154dcf 100644 --- a/packages/block-editor/src/components/inner-blocks/types.ts +++ b/packages/block-editor/src/components/inner-blocks/types.ts @@ -30,7 +30,7 @@ export type DirectInsert = boolean | ( ( ...args: never[] ) => unknown ); */ export interface InnerBlocksOptions extends Pick< UseBlockSyncProps, - 'value' | 'onChange' | 'onInput' + 'value' | 'onChange' | 'onInput' | 'syncSource' > { /** Block names which are permitted in inner blocks. */ allowedBlocks?: boolean | string[]; diff --git a/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts b/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts deleted file mode 100644 index 8056748618b4a3..00000000000000 --- a/packages/block-editor/src/components/provider/controlled-inner-blocks-source-context.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createContext } from '@wordpress/element'; - -/** - * What the inner block controller below renders, such as the entity it syncs - * its inner blocks with. A block that controls its inner blocks provides it - * around its inner blocks, so that the controllers rendering the same source - * can tell that they are copies of each other. - */ -export const ControlledInnerBlocksSourceContext = createContext< - string | undefined ->( undefined ); 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 0a21dea9036d10..aee85ffc083a88 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 @@ -1205,7 +1205,7 @@ describe( 'useBlockSync hook', () => { ); const part = { clientId: 'part', - source: 'part-entity', + syncSource: 'part-entity', value: [ paragraph( 'title', 0 ), paragraph( 'content-host', 0 ), @@ -1216,7 +1216,7 @@ describe( 'useBlockSync hook', () => { select().getBlocks( 'part' ); const content = { clientId: contentHostClone.clientId, - source: 'content-entity', + syncSource: 'content-entity', value: [ paragraph( 'content-block', 1 ) ], }; update( [ part, content ] ); @@ -1254,14 +1254,14 @@ describe( 'useBlockSync hook', () => { const controllers = () => [ { clientId: 'copy-a', - source: 'entity', + syncSource: 'entity', value: entity, onChange: onChangeA, onInput: onChangeA, }, { clientId: 'copy-b', - source: 'entity', + syncSource: 'entity', value: entity, onChange: vi.fn(), onInput: vi.fn(), @@ -1300,10 +1300,10 @@ describe( 'useBlockSync hook', () => { value: [ paragraph( 'p', 0 ) ], }; - update( [ { ...controller, source: 'menu-1' } ] ); + update( [ { ...controller, syncSource: 'menu-1' } ] ); expect( source() ).toBe( 'menu-1' ); - update( [ { ...controller, source: 'menu-2' } ] ); + update( [ { ...controller, syncSource: 'menu-2' } ] ); expect( source() ).toBe( 'menu-2' ); update( [] ); diff --git a/packages/block-editor/src/components/provider/types.ts b/packages/block-editor/src/components/provider/types.ts index b7ddfb34762dca..8ccbabbef805ac 100644 --- a/packages/block-editor/src/components/provider/types.ts +++ b/packages/block-editor/src/components/provider/types.ts @@ -93,7 +93,7 @@ export interface UseBlockSyncProps { * blocks with. Controllers that render the same source are copies of * each other. */ - source?: string; + syncSource?: string; } /** 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 b97a9f44d171ab..2d8b6cb7070959 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.ts +++ b/packages/block-editor/src/components/provider/use-block-sync.ts @@ -151,35 +151,35 @@ function areBlockFieldsEqual( block: Block, clone: Block ): boolean { * controllers. * - Passes selection state from the block-editor store to the controlling entity. * - * @param props Props for the block sync hook - * @param props.clientId The client ID of the inner block controller. - * If none is passed, then it is assumed to be a - * root controller rather than an inner block - * controller. - * @param props.value The control value for the blocks. This value - * is used to initialize the block-editor store - * and for resetting the blocks to incoming - * changes like undo. - * @param props.onChange Function to call when a persistent - * change has been made in the block-editor blocks - * for the given clientId. For example, after - * this function is called, an entity is marked - * dirty because it has changes to save. - * @param props.onInput Function to call when a non-persistent - * change has been made in the block-editor blocks - * for the given clientId. When this is called, - * controlling sources do not become dirty. - * @param props.source What the inner block controller renders, such as - * the entity it syncs its inner blocks with. - * Controllers that render the same source are - * copies of each other. + * @param props Props for the block sync hook + * @param props.clientId The client ID of the inner block controller. + * If none is passed, then it is assumed to be a + * root controller rather than an inner block + * controller. + * @param props.value The control value for the blocks. This value + * is used to initialize the block-editor store + * and for resetting the blocks to incoming + * changes like undo. + * @param props.onChange Function to call when a persistent + * change has been made in the block-editor blocks + * for the given clientId. For example, after + * this function is called, an entity is marked + * dirty because it has changes to save. + * @param props.onInput Function to call when a non-persistent + * change has been made in the block-editor blocks + * for the given clientId. When this is called, + * controlling sources do not become dirty. + * @param props.syncSource What the inner block controller renders, such as + * the entity it syncs its inner blocks with. + * Controllers that render the same source are + * copies of each other. */ export default function useBlockSync( { clientId = null, value: controlledBlocks, onChange = noop, onInput = noop, - source, + syncSource, }: UseBlockSyncProps ) { const registry = useRegistry(); const { getSelection, onChangeSelection } = useContext( SelectionContext ); @@ -332,8 +332,8 @@ export default function useBlockSync( { const blockName = getBlockName( clientId ); const isCopy = ( holderId: string ) => { const holderSource = getControlledInnerBlocksSource( holderId ); - return source && holderSource - ? holderSource === source + return syncSource && holderSource + ? holderSource === syncSource : getBlockName( holderId ) === blockName; }; return ( @@ -514,12 +514,12 @@ export default function useBlockSync( { // Record what this controller renders, so that the other controllers can // tell whether it is a copy of them. useEffect( () => { - if ( ! clientId || ! source ) { + if ( ! clientId || ! syncSource ) { return; } - setControlledInnerBlocksSource( clientId, source ); + setControlledInnerBlocksSource( clientId, syncSource ); return () => setControlledInnerBlocksSource( clientId, undefined ); - }, [ clientId, source, setControlledInnerBlocksSource ] ); + }, [ clientId, syncSource, setControlledInnerBlocksSource ] ); // Determine if blocks need to be reset when they change. // Also restores selection from context after blocks are set. diff --git a/packages/block-editor/src/private-apis.ts b/packages/block-editor/src/private-apis.ts index 25100e058144ea..439748ab92eaa6 100644 --- a/packages/block-editor/src/private-apis.ts +++ b/packages/block-editor/src/private-apis.ts @@ -1,7 +1,6 @@ import { privateApis as globalStylesEnginePrivateApis } from '@wordpress/global-styles-engine'; import * as globalStyles from './components/global-styles'; import { ExperimentalBlockEditorProvider } from './components/provider'; -import { ControlledInnerBlocksSourceContext } from './components/provider/controlled-inner-blocks-source-context'; import { lock, unlock } from './lock-unlock'; import { getRichTextValues } from './components/rich-text/get-rich-text-values'; import ResizableBoxPopover from './components/resizable-box-popover'; @@ -92,7 +91,6 @@ const { getDuotoneFilter } = unlock( globalStylesEnginePrivateApis ); export const privateApis = {}; lock( privateApis, { ...globalStyles, - ControlledInnerBlocksSourceContext, PrivateBlockInspectorEditOriginal, ExperimentalBlockCanvas, BlockCanvasCover, diff --git a/packages/block-library/src/block/edit.tsx b/packages/block-library/src/block/edit.tsx index c9f5cf612c3753..cb07ef17e424c3 100644 --- a/packages/block-library/src/block/edit.tsx +++ b/packages/block-library/src/block/edit.tsx @@ -276,6 +276,7 @@ function ReusableBlockEdit( { value: blocks, onInput: NOOP, onChange: NOOP, + syncSource: ref ? `postType/wp_block/${ ref }` : undefined, renderAppender: blocks?.length ? undefined : InnerBlocks.ButtonBlockAppender, diff --git a/packages/block-library/src/navigation/edit/inner-blocks.jsx b/packages/block-library/src/navigation/edit/inner-blocks.jsx index f6089148b3c49e..22fc9857efdfff 100644 --- a/packages/block-library/src/navigation/edit/inner-blocks.jsx +++ b/packages/block-library/src/navigation/edit/inner-blocks.jsx @@ -3,15 +3,11 @@ import { useInnerBlocksProps, InnerBlocks, store as blockEditorStore, - privateApis as blockEditorPrivateApis, } from '@wordpress/block-editor'; import { useSelect } from '@wordpress/data'; import { useMemo } from '@wordpress/element'; import PlaceholderPreview from './placeholder/placeholder-preview'; import { DEFAULT_BLOCK, PRIORITIZED_INSERTER_BLOCKS } from '../constants'; -import { unlock } from '../../lock-unlock'; - -const { ControlledInnerBlocksSourceContext } = unlock( blockEditorPrivateApis ); export default function NavigationInnerBlocks( { clientId, @@ -93,6 +89,9 @@ export default function NavigationInnerBlocks( { value: blocks, onInput, onChange, + syncSource: menuId + ? `postType/wp_navigation/${ menuId }` + : undefined, prioritizedInserterBlocks: PRIORITIZED_INSERTER_BLOCKS, defaultBlock: DEFAULT_BLOCK, directInsert: true, @@ -105,11 +104,5 @@ export default function NavigationInnerBlocks( { } ); - return ( - -
- - ); + return
; } diff --git a/packages/block-library/src/post-content/edit.tsx b/packages/block-library/src/post-content/edit.tsx index d7a0e121184347..bb18ae8925524b 100644 --- a/packages/block-library/src/post-content/edit.tsx +++ b/packages/block-library/src/post-content/edit.tsx @@ -22,9 +22,7 @@ import { useCanEditEntity } from '../utils/hooks'; import { unlock } from '../lock-unlock'; import type { PostContentAttributes, PostContentBlockContext } from './types'; -const { HTMLElementControl, ControlledInnerBlocksSourceContext } = unlock( - blockEditorPrivateApis -); +const { HTMLElementControl } = unlock( blockEditorPrivateApis ); type TagNameType = 'div' | 'main' | 'section' | 'article'; @@ -86,18 +84,21 @@ function EditableContentLoaded( { blocks, onInput, onChange, + syncSource, tagName: TagName = 'div', }: { blockProps: Record< string, unknown >; blocks: Block[] | undefined; onInput: ReturnType< typeof useEntityBlockEditor >[ 1 ]; onChange: ReturnType< typeof useEntityBlockEditor >[ 2 ]; + syncSource: string | undefined; tagName?: TagNameType; } ) { const props = useInnerBlocksProps( blockProps, { value: blocks, onInput, onChange, + syncSource, } ); return ; } @@ -142,21 +143,18 @@ function EditableContent( { } return ( - - - + tagName={ TagName } + /> ); } diff --git a/packages/block-library/src/template-part/edit/inner-blocks.tsx b/packages/block-library/src/template-part/edit/inner-blocks.tsx index 1e345e61391ea2..7a7ab865e8d269 100644 --- a/packages/block-library/src/template-part/edit/inner-blocks.tsx +++ b/packages/block-library/src/template-part/edit/inner-blocks.tsx @@ -7,16 +7,12 @@ import { useSettings, store as blockEditorStore, useBlockEditingMode, - privateApis as blockEditorPrivateApis, } from '@wordpress/block-editor'; import { useSelect } from '@wordpress/data'; import { useMemo } from '@wordpress/element'; import { parse } from '@wordpress/blocks'; import type { Block } from '@wordpress/blocks'; import type { TemplatePartAttributes } from '../types'; -import { unlock } from '../../lock-unlock'; - -const { ControlledInnerBlocksSourceContext } = unlock( blockEditorPrivateApis ); type EditorLayout = NonNullable< Parameters< typeof useInnerBlocksProps >[ 1 ] @@ -141,6 +137,7 @@ function EditableTemplatePartInnerBlocks( { value: blocks, onInput, onChange, + syncSource: id ? `postType/wp_template_part/${ id }` : undefined, renderAppender: useRenderAppender( hasInnerBlocks ), layout: useLayout( layout ), } ); @@ -158,13 +155,7 @@ function EditableTemplatePartInnerBlocks( { } : {}; - return ( - - - - ); + return ; } export default function TemplatePartInnerBlocks( { diff --git a/test/e2e/specs/site-editor/controller-sources.spec.ts b/test/e2e/specs/site-editor/controller-sources.spec.ts index 4a91b6198a4aa1..a05eab20ac145f 100644 --- a/test/e2e/specs/site-editor/controller-sources.spec.ts +++ b/test/e2e/specs/site-editor/controller-sources.spec.ts @@ -43,8 +43,8 @@ test.describe( 'Inner block controller sources', () => { content: '

Synced pattern content

', } ); - // A synced pattern controls its inner blocks but records no entity, - // so it must not take on the source of the template part around it. + // A synced pattern inside a template part records its own entity, + // not the template part's. await requestUtils.createTemplate( 'wp_template_part', { slug: 'part-a', title: 'Part A', @@ -131,7 +131,7 @@ test.describe( 'Inner block controller sources', () => { 'part-a': 'postType/wp_template_part/emptytheme//part-a', 'part-b': 'postType/wp_template_part/emptytheme//part-b', }, - syncedPattern: [ 'none' ], + syncedPattern: [ `postType/wp_block/${ pattern.id }` ], } ); } ); } );