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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 29 additions & 36 deletions packages/block-editor/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -601,26 +601,23 @@ const withBlockReset = ( reducer ) => ( state, action ) => {
if ( action.type === 'RESET_BLOCKS' ) {
/**
* Preserve controlled inner block flags across RESET_BLOCKS.
* Previously this was cleared to `{}`, which caused nested
* controllers (e.g. post-content, patterns) to lose their
* controlled status and unnecessarily re-clone blocks. Stale
* flags are cleaned up naturally by unsetControlledBlocks()
* when useBlockSync unmounts.
* If there are old and new blocks that:
* - have the same `clientId`
* - have the `controlledInnerBlocks` flag
* - don't have any own, uncontrolled children
* then we preserve the `controlledInnerBlocks` flag and the controlled sub-trees.
* Nested controllers (e.g., `post-content`, patterns) don't lose their
* controlled status and don't unnecessarily re-clone blocks.
*/
const newState = reducer( undefined, {
type: 'INSERT_BLOCKS',
rootClientId: '',
blocks: action.blocks,
} );

const preservedControlledInnerBlocks =
state?.controlledInnerBlocks ?? {};

const newState = {
...state,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we still keep this just in case? It's totally fine to rebuild the state from scratch, but I just want to be sure we're not missing something

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To ensure we're not forgetting some piece of state, not even in the future, I switched to another approach. Let the inner reducer create the new state, by initializing an empty state with INSERT_BLOCKS:

reducer( undefined, { type: 'INSERT_BLOCKS', rootClientId: '', blocks } )

That's exactly what the previous code was doing. Everything is much simpler now.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really like how this simplified the logic. Great refactoring, @jsnajdr!

byClientId: new Map(
getFlattenedBlocksWithoutAttributes( action.blocks )
),
attributes: new Map( getFlattenedBlockAttributes( action.blocks ) ),
order: mapBlockOrder( action.blocks ),
parents: new Map( mapBlockParents( action.blocks ) ),
controlledInnerBlocks: preservedControlledInnerBlocks,
};

// Preserve controlled inner blocks data from the old state.
// The maps above are rebuilt solely from action.blocks, but
// controlled inner blocks live under cloned IDs that aren't
Expand All @@ -637,23 +634,24 @@ const withBlockReset = ( reducer ) => ( state, action ) => {
if ( ! newState.byClientId.has( clientId ) ) {
continue;
}
newState.controlledInnerBlocks[ clientId ] = true;
const oldOrder = state.order.get( clientId );
if ( ! oldOrder?.length ) {
continue;
}
newState.order.set( clientId, oldOrder );
const preserveBlock = ( blockId, parentId ) => {
const blockData = state.byClientId?.get( blockId );
const blockData = state.byClientId.get( blockId );
if ( ! blockData ) {
return;
}
newState.byClientId.set( blockId, blockData );
newState.attributes.set(
blockId,
state.attributes?.get( blockId )
state.attributes.get( blockId )
);
newState.parents.set( blockId, parentId );
const childOrder = state.order?.get( blockId ) || [];
const childOrder = state.order.get( blockId ) || [];
newState.order.set( blockId, childOrder );
childOrder.forEach( ( childId ) =>
preserveBlock( childId, blockId )
Expand All @@ -663,43 +661,38 @@ const withBlockReset = ( reducer ) => ( state, action ) => {
}
}

newState.tree = new Map( state?.tree );
updateBlockTreeForBlocks( newState, action.blocks );

// Fix tree entries for controlled blocks. updateBlockTreeForBlocks
// built tree entries using action.blocks' inner block structure
// (entity-level IDs), but we need them to reference the preserved
// cloned inner blocks instead. Mutating the existing object
// preserves references held by ancestor tree entries.
for ( const clientId of Object.keys(
preservedControlledInnerBlocks
newState.controlledInnerBlocks
) ) {
if ( ! preservedControlledInnerBlocks[ clientId ] ) {
continue;
}
if ( ! newState.byClientId.has( clientId ) ) {
continue;
}
const controlledOrder = newState.order.get( clientId );
if ( ! controlledOrder?.length ) {
continue;
}
const innerBlocks = controlledOrder.map( ( id ) =>
newState.tree.get( id )
state.tree.get( id )
);
const existingEntry = newState.tree.get( clientId );
if ( existingEntry ) {
existingEntry.innerBlocks = innerBlocks;
}
newState.tree.set( 'controlled||' + clientId, { innerBlocks } );
const preserveTreeEntry = ( blockId ) => {
const treeEntry = state.tree.get( blockId );
if ( ! treeEntry ) {
return;
}
newState.tree.set( blockId, treeEntry );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are references to these treeEntry old state objects fine? Should we create copies just in case?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we're copying entries in the controlled subtrees that are guaranteed to be not touched. We can copy them. All the byClientId, attributes, parents and tree records.

Other reducers also do this. Typically they copy all old entries to a new map with newState.foo = new Map( oldState.foo ) and then modify the map.

const childOrder = newState.order.get( blockId ) || [];
childOrder.forEach( preserveTreeEntry );
};
controlledOrder.forEach( preserveTreeEntry );
}

newState.tree.set( '', {
innerBlocks: action.blocks.map( ( subBlock ) =>
newState.tree.get( subBlock.clientId )
),
} );

return newState;
}

Expand Down
199 changes: 198 additions & 1 deletion packages/block-editor/src/store/test/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import {
withDerivedBlockEditingModes,
viewportModalClientIds,
} from '../reducer';

import { getBlockOrder, getBlocks } from '../selectors';
import { unlock } from '../../lock-unlock';
import { sectionRootClientIdKey, isIsolatedEditorKey } from '.././private-keys';

Expand Down Expand Up @@ -2478,6 +2478,203 @@ describe( 'state', () => {
expect( state.controlledInnerBlocks.chicken ).toBe( true );
} );

it( 'should preserve controlledInnerBlocks blocks across RESET_BLOCKS', () => {
const original = blocks( undefined, {
type: 'RESET_BLOCKS',
blocks: [
{
clientId: 'chicken',
name: 'core/test-block',
attributes: {},
innerBlocks: [],
},
],
} );
const withControlled = blocks( original, {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
clientId: 'chicken',
hasControlledInnerBlocks: true,
} );

const withControlledContent = blocks( withControlled, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: 'chicken',
blocks: [
{
clientId: 'content',
innerBlocks: [
{
clientId: 'content-inner',
innerBlocks: [],
},
],
},
],
} );

expect(
getBlocks(
{ blocks: withControlledContent },
'chicken'
).map( ( b ) => b.clientId )
).toEqual( [ 'content' ] );
expect(
getBlocks(
{ blocks: withControlledContent },
'content'
).map( ( b ) => b.clientId )
).toEqual( [ 'content-inner' ] );

const state = blocks( withControlledContent, {
type: 'RESET_BLOCKS',
blocks: [
{
clientId: 'chicken',
name: 'core/test-block',
attributes: {},
innerBlocks: [],
},
],
} );

expect( state.controlledInnerBlocks.chicken ).toBe( true );
expect(
getBlocks( { blocks: state }, 'chicken' ).map(
( b ) => b.clientId
)
).toEqual( [ 'content' ] );
expect(
getBlocks( { blocks: state }, 'content' ).map(
( b ) => b.clientId
)
).toEqual( [ 'content-inner' ] );
} );

it( 'should forget controlledInnerBlocks during full RESET_BLOCKS', () => {
const templateBlock = {
clientId: 'template',
name: 'core/post-content',
attributes: {},
innerBlocks: [],
};
const contentBlock = {
clientId: 'content',
name: 'core/paragraph',
attributes: {},
innerBlocks: [],
};

let state = blocks( undefined, {
type: 'RESET_BLOCKS',
blocks: [ templateBlock ],
} );

state = blocks( state, {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
clientId: 'template',
hasControlledInnerBlocks: true,
} );

state = blocks( state, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: 'template',
blocks: [ contentBlock ],
} );

// Reset blocks completely, we expect that the controlled blocks are forgotten.
state = blocks( state, {
type: 'RESET_BLOCKS',
blocks: [],
} );

// Reset back to the template.
state = blocks( state, {
type: 'RESET_BLOCKS',
blocks: [ templateBlock ],
} );

// Expect that the `template`/`content` blocks are reconstructed.
const fullState = { blocks: state };
expect( getBlocks( fullState, 'template' ) ).toEqual( [] );
expect( getBlockOrder( fullState, 'template' ) ).toEqual(
[]
);
} );

it( 'should not leave stale controlled tree entries after root replacement and reset', () => {
const templateBlock = {
clientId: 'template',
name: 'core/post-content',
attributes: {},
innerBlocks: [],
};
const contentBlock = {
clientId: 'content',
name: 'core/paragraph',
attributes: {},
innerBlocks: [],
};

// Initialize template, simulates root `useBlockSync` initialization.
let state = blocks( undefined, {
type: 'RESET_BLOCKS',
blocks: [ templateBlock ],
} );

// Add a controlled child to the template using two actions, simulates inner `useBlockSync` initialization.
state = blocks( state, {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
clientId: 'template',
hasControlledInnerBlocks: true,
} );

state = blocks( state, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: 'template',
blocks: [ contentBlock ],
} );

// Reset blocks completely, simulates root `useBlockSync` cleanup.
state = blocks( state, {
type: 'RESET_BLOCKS',
blocks: [],
} );

// Unset controlled inner blocks, simulates inner `useBlockSync` cleanup.
state = blocks( state, {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
clientId: 'template',
hasControlledInnerBlocks: false,
} );

// Initialize template again, simulates `useBlockSync` after navigation.
state = blocks( state, {
type: 'RESET_BLOCKS',
blocks: [ templateBlock ],
} );

// Set controlled inner blocks again, this time to empty.
state = blocks( state, {
type: 'SET_HAS_CONTROLLED_INNER_BLOCKS',
clientId: 'template',
hasControlledInnerBlocks: true,
} );

state = blocks( state, {
type: 'REPLACE_INNER_BLOCKS',
rootClientId: 'template',
blocks: [],
} );

// At this point the template has empty content, and `useInnerBlockTemplateSync` should apply
// its template content. It will check if `getBlocks` is empty before applying the template.
const fullState = { blocks: state };
expect( getBlockOrder( fullState, 'template' ) ).toEqual(
[]
);
expect( getBlocks( fullState, 'template' ) ).toEqual( [] );
} );

it( 'should not create new state references when setting controlled inner blocks on a block with no inner blocks', () => {
const original = blocks( undefined, {
type: 'RESET_BLOCKS',
Expand Down
Loading