Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid keeping the same client ID when transforming blocks #32453

Merged
merged 2 commits into from
Jun 7, 2021
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
22 changes: 7 additions & 15 deletions packages/blocks/src/api/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { v4 as uuid } from 'uuid';
import {
every,
castArray,
findIndex,
some,
isObjectLike,
filter,
first,
Expand Down Expand Up @@ -538,28 +538,18 @@ export function switchToBlockType( blocks, name ) {
return null;
}

const firstSwitchedBlock = findIndex(
const hasSwitchedBlock = some(
transformationResults,
( result ) => result.name === name
);

// Ensure that at least one block object returned by the transformation has
// the expected "destination" block type.
if ( firstSwitchedBlock < 0 ) {
if ( ! hasSwitchedBlock ) {
return null;
}

return transformationResults.map( ( result, index ) => {
const transformedBlock = {
...result,
// The first transformed block whose type matches the "destination"
// type gets to keep the existing client ID of the first block.
clientId:
index === firstSwitchedBlock
? firstBlock.clientId
: result.clientId,
};

const ret = transformationResults.map( ( result ) => {
/**
* Filters an individual transform result from block transformation.
* All of the original blocks are passed, since transformations are
Expand All @@ -570,10 +560,12 @@ export function switchToBlockType( blocks, name ) {
*/
return applyFilters(
'blocks.switchToBlockType.transformedBlock',
transformedBlock,
result,
blocks
);
} );

return ret;
}

/**
Expand Down
4 changes: 0 additions & 4 deletions packages/blocks/src/api/test/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -1537,15 +1537,11 @@ describe( 'block factory', () => {
// to keep the existing block's client ID.
expect( transformedBlocks ).toHaveLength( 2 );
expect( transformedBlocks[ 0 ] ).toHaveProperty( 'clientId' );
expect( transformedBlocks[ 0 ].clientId ).not.toBe(
block.clientId
);
expect( transformedBlocks[ 0 ].name ).toBe( 'core/text-block' );
expect( transformedBlocks[ 0 ].isValid ).toBe( true );
expect( transformedBlocks[ 0 ].attributes ).toEqual( {
value: 'chicken ribs',
} );
expect( transformedBlocks[ 1 ].clientId ).toBe( block.clientId );
expect( transformedBlocks[ 1 ] ).toHaveProperty( 'clientId' );
expect( transformedBlocks[ 1 ].name ).toBe(
'core/updated-text-block'
Expand Down