Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 280 additions & 0 deletions packages/block-editor/src/components/provider/test/use-block-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand All @@ -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 (
<SelectionContext.Provider
value={ { getSelection, onChangeSelection: () => {} } }
>
{ children }
</SelectionContext.Provider>
);
}
);

describe( 'useBlockSync hook', () => {
beforeAll( () => {
registerBlockType( 'test/test-block', {
Expand Down Expand Up @@ -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(
<SelectionTestWrapper
setRegistry={ setRegistry }
getSelection={ () => selection }
>
<Controller
clientId="nav-a"
value={ sharedEntityBlocks }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
</SelectionTestWrapper>
);

// 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 ) => (
<SelectionTestWrapper
setRegistry={ setRegistry }
getSelection={ getSelection }
>
<Controller
clientId="nav-a"
value={ value }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
<Controller
clientId="nav-b"
value={ value }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
</SelectionTestWrapper>
);

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 ) => (
<SelectionTestWrapper
setRegistry={ setRegistry }
getSelection={ getSelection }
>
<Controller
clientId="nav-a"
value={ sharedEntityBlocks }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
<Controller
clientId="other"
value={ value }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
</SelectionTestWrapper>
);

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 ) => (
<SelectionTestWrapper
setRegistry={ setRegistry }
getSelection={ getSelection }
>
<Controller
value={ value }
onChange={ jest.fn() }
onInput={ jest.fn() }
/>
</SelectionTestWrapper>
);

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 } );
} );
} );
} );
38 changes: 38 additions & 0 deletions packages/block-editor/src/components/provider/use-block-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = () => {};

Expand Down Expand Up @@ -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 );
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -284,6 +321,7 @@ export default function useBlockSync( {
setHasControlledInnerBlocks( clientId, false );
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks( clientId, [] );
setControllerExternalClientIds( clientId, null );
} else {
__unstableMarkNextChangeAsNotPersistent();
resetBlocks( [] );
Expand Down
20 changes: 20 additions & 0 deletions packages/block-editor/src/store/private-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}
Loading
Loading