diff --git a/packages/block-editor/CHANGELOG.md b/packages/block-editor/CHANGELOG.md index 85f0eb75913545..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 @@ -43,6 +44,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 ([#87777](https://github.com/WordPress/gutenberg/pull/87777)). ### Internal 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/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/test/use-block-sync.jsdom.test.tsx b/packages/block-editor/src/components/provider/test/use-block-sync.jsdom.test.tsx index 7f288862a11969..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 @@ -1,14 +1,22 @@ 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 type { + BlockEditorProviderProps, + BlockSelectionState, + RegistryProvidedProps, + UseBlockSyncProps, +} 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'; +import { unlock } from '../../../lock-unlock'; vi.mock( import( '../../../store/actions' ), async ( importOriginal ) => { const actions = await importOriginal(); return { @@ -684,4 +692,682 @@ 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: Record< string, unknown > + ): TestBlock => ( { + name: 'test/test-block', + clientId: 'external', + innerBlocks: [ + { + name: 'test/test-block', + clientId: 'external-inner', + innerBlocks: [], + attributes: { foo: 10 }, + }, + ], + attributes, + } ); + + function renderController() { + let registry!: DataRegistry; + const onChange = vi.fn(); + const onInput = vi.fn(); + const view = render( + { + 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 } + 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 ); + } ); + + // 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( 'controllers on one canvas', () => { + const paragraph = ( + clientId: string, + content: number + ): TestBlock => ( { + 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. + 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( + ( props: RegistryProvidedProps ) => { + const { registry, setRegistry, selectionRef, controllers } = + props as RegistryProvidedProps & CanvasProps; + setRegistry( registry ); + const [ context ] = useState( () => ( { + getSelection: () => selectionRef.current, + onChangeSelection: () => {}, + } ) ); + return ( + + { controllers.map( ( controller ) => ( + + ) ) } + + ); + } + ) as ComponentType< CanvasProps >; + + 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 ), + name: hostNames[ clientId ] ?? 'test/test-block', + } ) ) as Block[] + ); + } + }; + const view = render( + + ); + const update = ( controllers: ControllerProps[] ) => + view.rerender( + + ); + const select = () => registry.select( blockEditorStore ); + const selectBlock = ( clientId: string ) => + 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: 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() ); + 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(); + } ); + + // 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', () => { + 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 + // 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. 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', [], 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, keepsClones ) => { + 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 ] ); + const [ outerBlockCloneBefore ] = select().getBlocks( 'outer' ); + 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( + outerBlockClone.clientId === outerBlockCloneBefore.clientId + ).toBe( keepsClones ); + expect( select().getSelectionStart().clientId ).toBe( + outerBlockClone.clientId + ); + } + ); + + // 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 + ); + } ); + + // 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', + syncSource: 'part-entity', + value: [ + paragraph( 'title', 0 ), + paragraph( 'content-host', 0 ), + ], + }; + update( [ part ] ); + const [ titleClone, contentHostClone ] = + select().getBlocks( 'part' ); + const content = { + clientId: contentHostClone.clientId, + syncSource: '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', + syncSource: 'entity', + value: entity, + onChange: onChangeA, + onInput: onChangeA, + }, + { + clientId: 'copy-b', + syncSource: '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, syncSource: 'menu-1' } ] ); + expect( source() ).toBe( 'menu-1' ); + + update( [ { ...controller, syncSource: '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. + 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/types.ts b/packages/block-editor/src/components/provider/types.ts index 8c1ee86e25f9b5..8ccbabbef805ac 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. + */ + 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 a06e0b008ef1b1..2d8b6cb7070959 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 { @@ -102,6 +103,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 equal fields. + */ +function areBlockFieldsEqual( 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 @@ -123,30 +151,35 @@ function restoreSelectionIds( * 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 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, + syncSource, }: UseBlockSyncProps ) { const registry = useRegistry(); const { getSelection, onChangeSelection } = useContext( SelectionContext ); @@ -156,10 +189,23 @@ export default function useBlockSync( { resetSelection, replaceInnerBlocks, setHasControlledInnerBlocks, + updateBlockAttributes, __unstableMarkNextChangeAsNotPersistent, } = registry.dispatch( blockEditorStore ); - const { getBlockName, getBlocks, getSelectionStart, getSelectionEnd } = - registry.select( blockEditorStore ); + const { + getBlockName, + getBlocks, + getSelectionStart, + getSelectionEnd, + getBlockParents, + areInnerBlocksControlled, + } = registry.select( blockEditorStore ); + const { setControlledInnerBlocksSource } = unlock( + registry.dispatch( blockEditorStore ) + ); + const { getControlledInnerBlocksSource } = unlock( + registry.select( blockEditorStore ) + ); const pendingChangesRef = useRef< { incoming: Block[] | null; @@ -236,6 +282,121 @@ export default function useBlockSync( { } }; + // Whether the block-editor's current selection sits inside a *different* + // 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 + // private clones of that entity's blocks, but they all map the same + // 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. + // + // 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; + } + + // 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; + } + + // 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 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 syncSource && holderSource + ? holderSource === syncSource + : getBlockName( holderId ) === blockName; + }; + return ( + ! holders.includes( clientId ) && + holders.some( + ( holderId ) => + areInnerBlocksControlled( holderId ) && isCopy( holderId ) + ) + ); + }; + + // 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, with nothing but attributes changed. A nested + // controller owns its own inner blocks, so those are left to it. + const hasSameStructure = ( blocks: Block[], clones: Block[] ): boolean => + blocks.length === clones.length && + blocks.every( ( block, index ) => { + const clone = clones[ index ]; + return ( + idMappingRef.current.internalToExternal.get( + clone.clientId + ) === block.clientId && + areBlockFieldsEqual( block, clone ) && + ( 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: Block[], + clones: Block[], + changes: Record< string, Record< string, unknown > > = {} + ) => { + blocks.forEach( ( block, index ) => { + const clone = clones[ index ]; + const changed: Record< string, unknown > = {}; + 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; @@ -245,6 +406,38 @@ 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, + } ); + // As after re-cloning, let an undo restore its recorded + // selection even if it is the one restored last time. + appliedSelectionRef.current = null; + } + return; + } + // Batch so that the controlled flag and block replacement // are applied atomically — subscribers see a consistent state. registry.batch( () => { @@ -318,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 || ! syncSource ) { + return; + } + setControlledInnerBlocksSource( clientId, syncSource ); + return () => setControlledInnerBlocksSource( clientId, undefined ); + }, [ clientId, syncSource, setControlledInnerBlocksSource ] ); + // Determine if blocks need to be reset when they change. // Also restores selection from context after blocks are set. useEffect( () => { @@ -350,13 +553,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. - restoreSelection(); + // 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. + // 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(); + } } }, [ controlledBlocks, clientId ] ); @@ -366,8 +576,6 @@ export default function useBlockSync( { isLastBlockChangePersistent, __unstableGetLastBlockChangeHistoryMode, __unstableIsLastBlockChangeIgnored, - areInnerBlocksControlled, - getBlockParents, } = registry.select( blockEditorStore ); let blocks = getBlocks( clientId ); 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 d4b24339321a70..bec6e6770ec1e6 100644 --- a/packages/block-editor/src/store/reducer.ts +++ b/packages/block-editor/src/store/reducer.ts @@ -220,6 +220,34 @@ function getAttributeUpdates( return updates; } +/** + * 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 blocks the last action updated are unchanged. + */ +function areLastUpdatedBlocksUnchanged( + 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 +518,20 @@ 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. + // 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' || + ! areLastUpdatedBlocksUnchanged( state, nextState, lastAction ) + ) { + lastAction = action; + } if ( pendingHistoryMode === 'ignore' ) { return { @@ -2614,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, @@ -3174,8 +3247,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 5a77d0a2798f46..0a7d75383aec91 100644 --- a/packages/block-editor/src/store/test/reducer.ts +++ b/packages/block-editor/src/store/test/reducer.ts @@ -2680,6 +2680,249 @@ 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 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', + } ); + 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, 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', + } ); + 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( '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( '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, { @@ -6106,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/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 } 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 bf248a8c966e91..22fc9857efdfff 100644 --- a/packages/block-library/src/navigation/edit/inner-blocks.jsx +++ b/packages/block-library/src/navigation/edit/inner-blocks.jsx @@ -1,4 +1,4 @@ -import { useEntityBlockEditor } from '@wordpress/core-data'; +import { useEntityBlockEditor, useEntityId } from '@wordpress/core-data'; import { useInnerBlocksProps, InnerBlocks, @@ -49,6 +49,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 @@ -88,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, diff --git a/packages/block-library/src/post-content/edit.tsx b/packages/block-library/src/post-content/edit.tsx index f64f56a41da3a5..bb18ae8925524b 100644 --- a/packages/block-library/src/post-content/edit.tsx +++ b/packages/block-library/src/post-content/edit.tsx @@ -84,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 ; } @@ -145,6 +148,11 @@ function EditableContent( { blocks={ blocks } onInput={ onInput } onChange={ onChange } + syncSource={ + postType && postId + ? `postType/${ postType }/${ postId }` + : undefined + } 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 085156285c0aa7..7a7ab865e8d269 100644 --- a/packages/block-library/src/template-part/edit/inner-blocks.tsx +++ b/packages/block-library/src/template-part/edit/inner-blocks.tsx @@ -137,6 +137,7 @@ function EditableTemplatePartInnerBlocks( { value: blocks, onInput, onChange, + syncSource: id ? `postType/wp_template_part/${ id }` : undefined, renderAppender: useRenderAppender( hasInnerBlocks ), layout: useLayout( layout ), } ); 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 ffd1f3ff33e00f..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 @@ -22,6 +22,8 @@ test.describe( 'Post Content focus mode', () => { test.afterAll( async ( { requestUtils } ) => { await requestUtils.activateTheme( 'twentytwentyone' ); await requestUtils.resetPreferences(); + await requestUtils.deleteAllPosts(); + await requestUtils.deleteAllBlocks(); } ); test( 'inserts blocks into Post Content from different selection states', async ( { @@ -116,6 +118,189 @@ 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 = () => postContentFocusMode.getPostContentText(); + + // 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' ); + 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' ] ); + + // 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. + 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' ); + } ); + + // 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' ); + } + await postContentFocusMode.waitForPostContentVisible(); + await page.keyboard.type( '-a' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Hello-a 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 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' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .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 } ) => { @@ -223,6 +408,52 @@ 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' ); + await postContentFocusMode.waitForPostContentVisible(); + 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 pageUtils.pressKeys( 'primary+z' ); + await expect + .poll( () => postContentFocusMode.getPostContentText() ) + .toEqual( [ 'Initial content' ] ); + + expect( await postContentFocusMode.getSelectedBlockName() ).toBe( + 'core/paragraph' + ); + } ); + test( 'template part blocks outside post content are not editable', async ( { admin, editor, @@ -367,6 +598,199 @@ 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( [] ); + } ); + } ); + + // 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 { @@ -426,6 +850,72 @@ 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; + } ); + } + + /** + * 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 + * 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 waitForPostContentVisible() { + await expect + .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 ); + } + /** * Returns the block names of the direct children of the template part * that contains Post Content. 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/controller-sources.spec.ts b/test/e2e/specs/site-editor/controller-sources.spec.ts new file mode 100644 index 00000000000000..a05eab20ac145f --- /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 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', + 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: [ `postType/wp_block/${ pattern.id }` ], + } ); + } ); +} ); diff --git a/test/e2e/specs/site-editor/navigation-selection-sync.spec.ts b/test/e2e/specs/site-editor/navigation-selection-sync.spec.ts new file mode 100644 index 00000000000000..74049b4f9dfade --- /dev/null +++ b/test/e2e/specs/site-editor/navigation-selection-sync.spec.ts @@ -0,0 +1,144 @@ +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 = + ''; + +/** + * 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 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: Page ): Promise< number | null > { + 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: string ) => + 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 ); + const tracked = window as TrackedWindow; + tracked.__selectionsInDuplicate = []; + window.wp.data.subscribe( () => { + const selected = getSelectedBlockClientId(); + if ( + selected && + ( selected === duplicate || + getBlockParents( selected ).includes( duplicate ) ) && + tracked.__selectionsInDuplicate.at( -1 ) !== selected + ) { + tracked.__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 as TrackedWindow ).__selectionsInDuplicate + ) + ).toEqual( [] ); + expect( await 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' ); + } ); } ); diff --git a/test/e2e/specs/site-editor/undo.spec.js b/test/e2e/specs/site-editor/undo.spec.js index 37d4539d0ef453..dc561513c70b76 100644 --- a/test/e2e/specs/site-editor/undo.spec.js +++ b/test/e2e/specs/site-editor/undo.spec.js @@ -41,3 +41,267 @@ 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' ); + 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' ); + } ); + + 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 +// 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. 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' ); + } ); + + 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' ); + } ); +} );