Skip to content

Commit

Permalink
Avoid keeping the same client ID when transforming blocks (#32453)
Browse files Browse the repository at this point in the history
* Avoid keeping the same client ID when transforming blocks

* Fix unit tests
  • Loading branch information
youknowriad committed Jun 7, 2021
1 parent 3282bbb commit 8fe2295
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
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

0 comments on commit 8fe2295

Please sign in to comment.