diff --git a/packages/block-editor/src/components/provider/test/use-block-sync.js b/packages/block-editor/src/components/provider/test/use-block-sync.js index 00260264a286d3..aafeedee91e726 100644 --- a/packages/block-editor/src/components/provider/test/use-block-sync.js +++ b/packages/block-editor/src/components/provider/test/use-block-sync.js @@ -14,6 +14,7 @@ import { render } from '@testing-library/react'; import useBlockSync from '../use-block-sync'; import withRegistryProvider from '../with-registry-provider'; import * as blockEditorActions from '../../../store/actions'; +import { SelectionContext } from '../selection-context'; import { store as blockEditorStore } from '../../../store'; jest.mock( '../../../store/actions', () => { @@ -36,6 +37,32 @@ const TestWrapper = withRegistryProvider( ( props ) => { return null; } ); +// Renders one useBlockSync controller. Several of these can be nested +// under a single SelectionTestWrapper to simulate multiple controlled +// blocks (e.g. two Navigation blocks) sharing one block-editor store. +function Controller( props ) { + useBlockSync( props ); + return null; +} + +// Provides a single registry and a SelectionContext (normally provided +// by BlockEditorProvider) so tests can control the entity-level +// selection that restoreSelection() reads. +const SelectionTestWrapper = withRegistryProvider( + ( { registry, setRegistry, getSelection, children } ) => { + if ( setRegistry ) { + setRegistry( registry ); + } + return ( + {} } } + > + { children } + + ); + } +); + describe( 'useBlockSync hook', () => { beforeAll( () => { registerBlockType( 'test/test-block', { @@ -673,4 +700,257 @@ describe( 'useBlockSync hook', () => { // The internal IDs should be different from the external IDs (due to cloning) expect( replacedBlocks[ 0 ].clientId ).not.toBe( originalClientId ); } ); + + describe( 'selection restoration', () => { + // The entity blocks shared by the duplicate controllers below, + // like a wp_navigation menu used by two Navigation blocks. + const sharedEntityBlocks = [ + { + name: 'test/test-block', + clientId: 'link-1', + innerBlocks: [], + attributes: { foo: 1 }, + }, + ]; + + it( 'restores the entity selection onto its own clones when an inner block controller syncs', () => { + let registry; + const setRegistry = ( reg ) => { + registry = reg; + }; + const selection = { + selectionStart: { clientId: 'link-1' }, + selectionEnd: { clientId: 'link-1' }, + }; + + render( + selection } + > + + + ); + + // The selection uses the external ID ('link-1'), and must be + // restored onto the controller's internal clone of it. + const clone = registry + .select( blockEditorStore ) + .getBlocks( 'nav-a' )[ 0 ]; + expect( + registry.select( blockEditorStore ).getSelectionStart().clientId + ).toBe( clone.clientId ); + } ); + + it( 'does not let a duplicate controller steal the selection when a shared entity updates', () => { + let registry; + const setRegistry = ( reg ) => { + registry = reg; + }; + // Holds the entity-level selection, unset until the user selects. + const contextSelection = { current: undefined }; + const getSelection = () => contextSelection.current; + const renderControllers = ( value ) => ( + + + + + ); + + const { rerender } = render( + renderControllers( sharedEntityBlocks ) + ); + + // The user selects the block inside the first controller. + const cloneA = registry + .select( blockEditorStore ) + .getBlocks( 'nav-a' )[ 0 ]; + registry + .dispatch( blockEditorStore ) + .selectBlock( cloneA.clientId ); + + // The selection is recorded on the entity with external IDs, + // which both controllers can map — neither map identifies the + // owner, so this is where the ownership ambiguity comes from. + contextSelection.current = { + selectionStart: { clientId: 'link-1' }, + selectionEnd: { clientId: 'link-1' }, + }; + + // The shared entity updates, so both controllers re-clone + // their blocks and try to restore the selection. + rerender( + renderControllers( [ + { ...sharedEntityBlocks[ 0 ], attributes: { foo: 2 } }, + ] ) + ); + + const { getSelectionStart, getBlockParents } = + registry.select( blockEditorStore ); + const selectedClientId = getSelectionStart().clientId; + expect( selectedClientId ).toBeTruthy(); + // The selection must stay within the controller that owned it, + // not move to the duplicate that synced last. + expect( getBlockParents( selectedClientId ) ).toContain( 'nav-a' ); + expect( getBlockParents( selectedClientId ) ).not.toContain( + 'nav-b' + ); + } ); + + it( 'restores the entity selection into a controller even while another block is selected (undo jump-in)', () => { + let registry; + const setRegistry = ( reg ) => { + registry = reg; + }; + // Holds the entity-level selection, unset until the user selects. + const contextSelection = { current: undefined }; + const getSelection = () => contextSelection.current; + const otherEntityBlocks = [ + { + name: 'test/test-block', + clientId: 'other-1', + innerBlocks: [], + attributes: { foo: 1 }, + }, + ]; + const renderControllers = ( value ) => ( + + + + + ); + + const { rerender } = render( + renderControllers( otherEntityBlocks ) + ); + + // The user is working inside the first controller… + const cloneA = registry + .select( blockEditorStore ) + .getBlocks( 'nav-a' )[ 0 ]; + registry + .dispatch( blockEditorStore ) + .selectBlock( cloneA.clientId ); + + // …when the other controller's entity comes back with a + // selection targeting its own content (e.g. undoing an edit + // made inside it). The selection targets a different external + // block than the one currently selected, so it must be applied. + contextSelection.current = { + selectionStart: { clientId: 'other-1' }, + selectionEnd: { clientId: 'other-1' }, + }; + rerender( + renderControllers( [ + { ...otherEntityBlocks[ 0 ], attributes: { foo: 2 } }, + ] ) + ); + + const { getSelectionStart, getBlockParents } = + registry.select( blockEditorStore ); + const selectedClientId = getSelectionStart().clientId; + expect( getBlockParents( selectedClientId ) ).toContain( 'other' ); + } ); + + it( 'restores the entity selection when the root controller resets blocks (undo/redo)', () => { + let registry; + const setRegistry = ( reg ) => { + registry = reg; + }; + // Holds the entity-level selection, unset until the user selects. + const contextSelection = { current: undefined }; + const getSelection = () => contextSelection.current; + const renderRoot = ( value ) => ( + + + + ); + + const { rerender } = render( + renderRoot( [ + { + name: 'test/test-block', + clientId: 'a', + innerBlocks: [], + attributes: { foo: 1 }, + }, + ] ) + ); + + // The user places the caret in the block ("typing"). + registry + .dispatch( blockEditorStore ) + .selectionChange( 'a', 'foo', 5, 5 ); + + // Undo: the entity restores an earlier value AND an earlier + // selection (different offset). Because block 'a' still exists + // after the reset, the store keeps the stale caret — the + // entity selection must still win, or undo would leave the + // caret where it was after typing. + contextSelection.current = { + selectionStart: { + clientId: 'a', + attributeKey: 'foo', + offset: 2, + }, + selectionEnd: { + clientId: 'a', + attributeKey: 'foo', + offset: 2, + }, + }; + rerender( + renderRoot( [ + { + name: 'test/test-block', + clientId: 'a', + innerBlocks: [], + attributes: { foo: 0 }, + }, + ] ) + ); + + expect( + registry.select( blockEditorStore ).getSelectionStart() + ).toEqual( { clientId: 'a', attributeKey: 'foo', offset: 2 } ); + } ); + } ); } ); diff --git a/packages/block-editor/src/components/provider/use-block-sync.js b/packages/block-editor/src/components/provider/use-block-sync.js index e3cd69cac81df5..442c2f41e76d2b 100644 --- a/packages/block-editor/src/components/provider/use-block-sync.js +++ b/packages/block-editor/src/components/provider/use-block-sync.js @@ -10,6 +10,7 @@ import { cloneBlock } from '@wordpress/blocks'; */ import { store as blockEditorStore } from '../../store'; import { SelectionContext } from './selection-context'; +import { unlock } from '../../lock-unlock'; const noop = () => {}; @@ -158,8 +159,14 @@ export default function useBlockSync( { setHasControlledInnerBlocks, __unstableMarkNextChangeAsNotPersistent, } = registry.dispatch( blockEditorStore ); + const { setControllerExternalClientIds } = unlock( + registry.dispatch( blockEditorStore ) + ); const { getBlockName, getBlocks, getSelectionStart, getSelectionEnd } = registry.select( blockEditorStore ); + const { getExternalClientId } = unlock( + registry.select( blockEditorStore ) + ); const pendingChangesRef = useRef( { incoming: null, outgoing: [] } ); const subscribedRef = useRef( false ); @@ -202,6 +209,27 @@ export default function useBlockSync( { : !! getBlockName( startClientId ); if ( isOurs ) { + // The check above cannot tell duplicate controllers apart: two + // controllers synced from the same entity (e.g. two Navigation + // blocks using the same menu) map the same external IDs, so both + // consider the selection theirs and the last one to sync would + // steal it. To break the tie, check whether the selection is + // already in place: every controller registers in the store + // which external block each of its clones was made from, so if + // the currently selected block is a copy of the same external + // block this selection targets — whichever controller made the + // copy — there is nothing left to restore. The root controller + // never skips: it doesn't clone, so its blocks have no + // registered external IDs to compare. + if ( clientId ) { + const currentClientId = getSelectionStart()?.clientId; + if ( + currentClientId && + getExternalClientId( currentClientId ) === startClientId + ) { + return; + } + } appliedSelectionRef.current = selection; // Inner block controllers need to convert external→internal // IDs via the clone mapping; the root controller uses @@ -261,6 +289,15 @@ export default function useBlockSync( { __unstableMarkNextChangeAsNotPersistent(); replaceInnerBlocks( clientId, storeBlocks ); + // Publish a snapshot of the clone mapping so that other + // controllers can recognise this controller's clones when + // deciding whether to restore a selection (see + // restoreSelection). + setControllerExternalClientIds( + clientId, + new Map( idMappingRef.current.internalToExternal ) + ); + // Invalidate the applied-selection ref so that // restoreSelection() at the end of the // controlledBlocks effect re-applies with the @@ -284,6 +321,7 @@ export default function useBlockSync( { setHasControlledInnerBlocks( clientId, false ); __unstableMarkNextChangeAsNotPersistent(); replaceInnerBlocks( clientId, [] ); + setControllerExternalClientIds( clientId, null ); } else { __unstableMarkNextChangeAsNotPersistent(); resetBlocks( [] ); diff --git a/packages/block-editor/src/store/private-actions.js b/packages/block-editor/src/store/private-actions.js index 018ba16e95360f..75b70faac31545 100644 --- a/packages/block-editor/src/store/private-actions.js +++ b/packages/block-editor/src/store/private-actions.js @@ -589,3 +589,23 @@ export function setResponsiveEditing( enabled ) { enabled, }; } + +/** + * Registers which external (original) client ID each of an inner block + * controller's internal (cloned) blocks was made from, so that other + * controllers can recognise copies of the same external block. Pass null + * to remove the controller's registration (e.g. on unmount). + * + * @param {string} clientId The controller block's client ID. + * @param {Map|null} internalToExternal Map of internal → external client IDs, + * or null to unregister. + * + * @return {Object} Action object. + */ +export function setControllerExternalClientIds( clientId, internalToExternal ) { + return { + type: 'SET_CONTROLLER_EXTERNAL_CLIENT_IDS', + clientId, + internalToExternal, + }; +} diff --git a/packages/block-editor/src/store/private-selectors.js b/packages/block-editor/src/store/private-selectors.js index dc463ef1d84ab6..83f48ac5c0632c 100644 --- a/packages/block-editor/src/store/private-selectors.js +++ b/packages/block-editor/src/store/private-selectors.js @@ -1373,3 +1373,23 @@ export function isSelectedBlockStyleStateShownOnCanvas( state, clientId ) { return state.selectedBlockStyleState.showStateOnCanvas ?? true; } + +/** + * Returns the external (original) client ID that the given internal (cloned) + * block was made from, if any inner block controller has registered it. + * Returns undefined for blocks that are not controller-made copies (e.g. + * root-level blocks). + * + * @param {Object} state Global application state. + * @param {string} clientId The internal block client ID. + * + * @return {string|undefined} The external client ID, if known. + */ +export function getExternalClientId( state, clientId ) { + for ( const internalToExternal of state.externalClientIds.values() ) { + const externalClientId = internalToExternal.get( clientId ); + if ( externalClientId !== undefined ) { + return externalClientId; + } + } +} diff --git a/packages/block-editor/src/store/reducer.js b/packages/block-editor/src/store/reducer.js index 1119a805d333a6..a1ff5360d9ad95 100644 --- a/packages/block-editor/src/store/reducer.js +++ b/packages/block-editor/src/store/reducer.js @@ -2423,6 +2423,40 @@ export function isResponsiveEditing( state = false, action ) { return state; } +/** + * Reducer tracking, per inner block controller, which external (original) + * client ID each of its internal (cloned) blocks was made from. Controllers + * synced from the same entity (e.g. two Navigation blocks using the same + * menu) share external IDs but keep private clone mappings; publishing the + * mapping here lets one controller recognise that the current selection + * already points at a copy of a given external block, whichever controller + * made the copy. + * + * The state is a Map of controller client ID → Map of internal → external + * client IDs. + * + * @param {Map} state Current state. + * @param {Object} action Dispatched action. + * + * @return {Map} Updated state. + */ +export function externalClientIds( state = new Map(), action ) { + if ( action.type === 'SET_CONTROLLER_EXTERNAL_CLIENT_IDS' ) { + if ( ! action.internalToExternal && ! state.has( action.clientId ) ) { + return state; + } + const nextState = new Map( state ); + if ( action.internalToExternal ) { + nextState.set( action.clientId, action.internalToExternal ); + } else { + nextState.delete( action.clientId ); + } + return nextState; + } + + return state; +} + const combinedReducers = combineReducers( { blocks, isDragging, @@ -2461,6 +2495,7 @@ const combinedReducers = combineReducers( { selectedBlockStyleState, styleStateViewport, isResponsiveEditing, + externalClientIds, } ); /** diff --git a/test/e2e/specs/editor/various/undo.spec.js b/test/e2e/specs/editor/various/undo.spec.js index 0c29e68c3ee653..6fd746d3e9b869 100644 --- a/test/e2e/specs/editor/various/undo.spec.js +++ b/test/e2e/specs/editor/various/undo.spec.js @@ -86,6 +86,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=button[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. + // After the undo, the block that was typed in still exists, so the + // store keeps this selection across the block reset — the selection + // stored with the undo level must still 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/duplicate-navigation-blocks.spec.js b/test/e2e/specs/site-editor/duplicate-navigation-blocks.spec.js new file mode 100644 index 00000000000000..bfa5cafbbbc90b --- /dev/null +++ b/test/e2e/specs/site-editor/duplicate-navigation-blocks.spec.js @@ -0,0 +1,116 @@ +/** + * WordPress dependencies + */ +const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); + +// Two Navigation blocks referencing the same menu are synced from the same +// wp_navigation entity, so editing one makes the other re-sync. The re-sync +// must not move the selection (and scroll) to the other block. +// 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.afterAll( async ( { requestUtils } ) => { + await requestUtils.activateTheme( 'twentytwentyone' ); + await requestUtils.deleteAllMenus(); + } ); + + test( 'editing a menu item in one block does not move the selection to its duplicate', async ( { + admin, + editor, + page, + pageUtils, + requestUtils, + } ) => { + const { id: menuId } = await requestUtils.createNavigationMenu( { + title: 'Shared menu', + content: + '', + } ); + + await admin.visitSiteEditor( { + postId: 'emptytheme//index', + postType: 'wp_template', + canvas: 'edit', + } ); + + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menuId }, + } ); + await editor.insertBlock( { + name: 'core/paragraph', + attributes: { content: 'Content between the two menus' }, + } ); + await editor.insertBlock( { + name: 'core/navigation', + attributes: { ref: menuId }, + } ); + + // Wait for both Navigation blocks to load the menu. + const linkLabels = editor.canvas.locator( + 'role=textbox[name="Navigation link text"i]' + ); + await expect( linkLabels ).toHaveCount( 2 ); + + // Place the caret in the first Navigation block's link label. (A + // content overlay covers unselected Navigation blocks, hence the + // click on the block before the click on the label.) + await editor.canvas + .getByRole( 'document', { name: 'Block: Navigation' } ) + .first() + .click(); + await linkLabels.first().click(); + + // Record every time the selection enters the second Navigation + // block. Stealing the selection is momentary (the editor scrolls as + // soon as it happens, even if the selection later recovers), so + // asserting on the final selection alone could miss it. This is + // installed after the caret is placed above, because inserting the + // blocks left the second Navigation block selected. + await page.evaluate( () => { + const { + getSelectedBlockClientId, + getBlockParents, + getBlockOrder, + getBlockName, + } = window.wp.data.select( 'core/block-editor' ); + const secondNavigationClientId = getBlockOrder() + .filter( ( id ) => getBlockName( id ) === 'core/navigation' ) + .at( -1 ); + window.__selectionsInSecondNavigation = []; + window.wp.data.subscribe( () => { + const selected = getSelectedBlockClientId(); + if ( + selected && + ( selected === secondNavigationClientId || + getBlockParents( selected ).includes( + secondNavigationClientId + ) ) && + window.__selectionsInSecondNavigation.at( -1 ) !== selected + ) { + window.__selectionsInSecondNavigation.push( selected ); + } + } ); + } ); + + // Rewrite the link label. Every keystroke updates the shared entity + // and re-syncs the second Navigation block, which is when it used + // to steal the selection and scroll into view. With the selection + // stolen, the caret snapped back to a stale position after every + // keystroke, so the text came out reversed ("lebal weN"). + await pageUtils.pressKeys( 'primary+a' ); + await page.keyboard.type( 'New label' ); + + // The edit syncs into both Navigation blocks… + await expect( linkLabels.first() ).toHaveText( 'New label' ); + await expect( linkLabels.last() ).toHaveText( 'New label' ); + + // …and the selection never enters the second one. + expect( + await page.evaluate( () => window.__selectionsInSecondNavigation ) + ).toEqual( [] ); + } ); +} );