From 7e3b80c3066c608ff5a00b1337818431f5a3667c Mon Sep 17 00:00:00 2001 From: Aki Hamano <54422211+t-hamano@users.noreply.github.com> Date: Mon, 30 Oct 2023 23:04:54 +0900 Subject: [PATCH] Block Example: Avoid a crash when block is not registered (#55686) * Block Example: Avoid a crash when block is not registered * Use a try-catch statement --- packages/blocks/src/api/factory.js | 22 ++++++++++++------ packages/blocks/src/api/test/factory.js | 30 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/packages/blocks/src/api/factory.js b/packages/blocks/src/api/factory.js index 7112ae25ccdde2..53333ef688085f 100644 --- a/packages/blocks/src/api/factory.js +++ b/packages/blocks/src/api/factory.js @@ -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: '', + } ); + } }; diff --git a/packages/blocks/src/api/test/factory.js b/packages/blocks/src/api/test/factory.js index 84d7161659928a..22d069205113bf 100644 --- a/packages/blocks/src/api/test/factory.js +++ b/packages/blocks/src/api/test/factory.js @@ -17,6 +17,7 @@ import { findTransform, isWildcardBlockTransform, isContainerGroupBlock, + getBlockFromExample, } from '../factory'; import { getBlockType, @@ -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' }, + ], + } ); + } ); + } ); } );