Skip to content

Commit

Permalink
Block versioning: Introduce a migration function (#3673)
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad authored Jan 19, 2018
1 parent aa5e157 commit f43140e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
17 changes: 13 additions & 4 deletions blocks/api/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,19 @@ 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 {
// Parse using the deprecated block version .
// Try to validate the parsed block using this same deprecated version.
// Ignore this version if the the validation fails.
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
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion blocks/api/test/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ describe( 'block parser', () => {
},
},
save: ( { attributes } ) => <span>{ attributes.fruit }</span>,
migrate: ( attributes ) => ( { fruit: 'Big ' + attributes.fruit } ),
},
],
} );
Expand All @@ -306,7 +307,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 );
expect( console ).toHaveErrored();
expect( console ).toHaveWarned();
Expand Down

0 comments on commit f43140e

Please sign in to comment.