From c79bbcb082e21ef60ce867e8d5c05a49c433c766 Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Mon, 27 Nov 2017 14:59:09 +0100 Subject: [PATCH] Block versioning: Introduce a migration function --- blocks/api/parser.js | 14 ++++++++++---- blocks/api/test/parser.js | 3 ++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/blocks/api/parser.js b/blocks/api/parser.js index 82add30a463e8f..ca78755a4b391f 100644 --- a/blocks/api/parser.js +++ b/blocks/api/parser.js @@ -147,10 +147,16 @@ export function getAttributesFromDeprecatedVersion( blockType, innerHTML, attrib ...omit( blockType, [ 'attributes', 'save', 'supports' ] ), // Parsing/Serialization properties ...blockType.deprecated[ i ], }; - const deprecatedBlockAttributes = getBlockAttributes( deprecatedBlockType, innerHTML, attributes ); - const isValid = isValidBlock( innerHTML, deprecatedBlockType, deprecatedBlockAttributes ); - if ( isValid ) { - return deprecatedBlockAttributes; + + try { + const deprecatedBlockAttributes = getBlockAttributes( deprecatedBlockType, innerHTML, attributes ); + const migratedBlockAttributes = deprecatedBlockType.migrate ? deprecatedBlockType.migrate( deprecatedBlockAttributes ) : deprecatedBlockAttributes; + const isValid = isValidBlock( innerHTML, deprecatedBlockType, deprecatedBlockAttributes ); + if ( isValid ) { + return migratedBlockAttributes; + } + } catch ( error ) { + // ignore error, it means this deprecated version is invalid } } } diff --git a/blocks/api/test/parser.js b/blocks/api/test/parser.js index fc850a08730a86..7a8fd86ed929e6 100644 --- a/blocks/api/test/parser.js +++ b/blocks/api/test/parser.js @@ -304,6 +304,7 @@ describe( 'block parser', () => { }, }, save: ( { attributes } ) => { attributes.fruit }, + migrate: ( attributes ) => ( { fruit: 'Big ' + attributes.fruit } ), }, ], } ); @@ -314,7 +315,7 @@ describe( 'block parser', () => { { fruit: 'Bananas' } ); expect( block.name ).toEqual( 'core/test-block' ); - expect( block.attributes ).toEqual( { fruit: 'Bananas' } ); + expect( block.attributes ).toEqual( { fruit: 'Big Bananas' } ); expect( block.isValid ).toBe( true ); expectFailingBlockValidation(); } );