diff --git a/packages/block-library/src/columns/test/utils.js b/packages/block-library/src/columns/test/utils.js index d99a7b3d4a6205..72d29c6d77f7df 100644 --- a/packages/block-library/src/columns/test/utils.js +++ b/packages/block-library/src/columns/test/utils.js @@ -1,3 +1,8 @@ +/** + * External dependencies + */ +import deepFreeze from 'deep-freeze'; + /** * Internal dependencies */ @@ -280,4 +285,53 @@ describe( 'getMappedColumnWidths', () => { { clientId: 'b', attributes: { width: '35%' } }, ] ); } ); + + it( 'always returns new objects and does not mutate input blocks', () => { + const blocks = [ + deepFreeze( { clientId: 'a', attributes: { width: 30 } } ), + deepFreeze( { clientId: 'b', attributes: { width: 40 } } ), + ]; + const widths = { + a: 25, + b: 35, + }; + + const result = getMappedColumnWidths( blocks, widths ); + + expect( blocks[ 0 ] ).not.toBe( result[ 0 ] ); + expect( blocks[ 1 ] ).not.toBe( result[ 1 ] ); + } ); + + it( 'merges to block attributes if original blocks do not have any attributes', () => { + const blocks = [ { clientId: 'a' }, { clientId: 'b' } ]; + const widths = { + a: 25, + b: 35, + }; + + const result = getMappedColumnWidths( blocks, widths ); + + expect( result ).toEqual( [ + { clientId: 'a', attributes: { width: '25%' } }, + { clientId: 'b', attributes: { width: '35%' } }, + ] ); + } ); + + it( 'merges to block attributes if original blocks do not have a width attribute', () => { + const blocks = [ + { clientId: 'a', attributes: { align: 'left' } }, + { clientId: 'b', attributes: { align: 'right' } }, + ]; + const widths = { + a: 25, + b: 35, + }; + + const result = getMappedColumnWidths( blocks, widths ); + + expect( result ).toEqual( [ + { clientId: 'a', attributes: { align: 'left', width: '25%' } }, + { clientId: 'b', attributes: { align: 'right', width: '35%' } }, + ] ); + } ); } ); diff --git a/packages/block-library/src/columns/utils.js b/packages/block-library/src/columns/utils.js index b75a7ad77bba18..12cb45a9874d74 100644 --- a/packages/block-library/src/columns/utils.js +++ b/packages/block-library/src/columns/utils.js @@ -1,7 +1,7 @@ /** * External dependencies */ -import { merge, mapValues } from 'lodash'; +import { mapValues } from 'lodash'; /** * Returns a column width attribute value rounded to standard precision. @@ -121,13 +121,13 @@ export function hasExplicitPercentColumnWidths( blocks ) { * @return {WPBlock[]} blocks Mapped block objects. */ export function getMappedColumnWidths( blocks, widths ) { - return blocks.map( ( block ) => - merge( {}, block, { - attributes: { - width: `${ widths[ block.clientId ] }%`, - }, - } ) - ); + return blocks.map( ( block ) => ( { + ...block, + attributes: { + ...block.attributes, + width: `${ widths[ block.clientId ] }%`, + }, + } ) ); } /**