Skip to content

Commit

Permalink
Block Example: Avoid a crash when block is not registered (#55686)
Browse files Browse the repository at this point in the history
* Block Example: Avoid a crash when block is not registered

* Use a try-catch statement
  • Loading branch information
t-hamano authored Oct 30, 2023
1 parent c7c5549 commit 7e3b80c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
22 changes: 15 additions & 7 deletions packages/blocks/src/api/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,11 +580,19 @@ export function switchToBlockType( blocks, name ) {
* @return {Object} block.
*/
export const getBlockFromExample = ( name, example ) => {
return createBlock(
name,
example.attributes,
( example.innerBlocks ?? [] ).map( ( innerBlock ) =>
getBlockFromExample( innerBlock.name, innerBlock )
)
);
try {
return createBlock(
name,
example.attributes,
( example.innerBlocks ?? [] ).map( ( innerBlock ) =>
getBlockFromExample( innerBlock.name, innerBlock )
)
);
} catch {
return createBlock( 'core/missing', {
originalName: name,
originalContent: '',
originalUndelimitedContent: '',
} );
}
};
30 changes: 30 additions & 0 deletions packages/blocks/src/api/test/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
findTransform,
isWildcardBlockTransform,
isContainerGroupBlock,
getBlockFromExample,
} from '../factory';
import {
getBlockType,
Expand Down Expand Up @@ -2276,4 +2277,33 @@ describe( 'block factory', () => {
expect( isContainerGroupBlock( 'core/group' ) ).toBe( false );
} );
} );

describe( 'getBlockFromExample', () => {
it( 'should replace unregistered block with core/missing block', () => {
registerBlockType( 'core/missing', {
title: 'Unsupported',
} );
registerBlockType( 'core/paragraph', {
title: 'Paragraph',
} );
registerBlockType( 'core/group', {
title: 'A block that groups other blocks.',
} );
const example = {
innerBlocks: [
{ name: 'core/paragraph' },
{ name: 'core/image' },
],
};
expect(
getBlockFromExample( 'core/group', example )
).toMatchObject( {
name: 'core/group',
innerBlocks: [
{ name: 'core/paragraph' },
{ name: 'core/missing' },
],
} );
} );
} );
} );

0 comments on commit 7e3b80c

Please sign in to comment.