diff --git a/packages/block-editor/src/hooks/style.js b/packages/block-editor/src/hooks/style.js index 85b8247743b385..702da2ae7983f0 100644 --- a/packages/block-editor/src/hooks/style.js +++ b/packages/block-editor/src/hooks/style.js @@ -1,13 +1,14 @@ /** * External dependencies */ -import { capitalize, has, get, startsWith } from 'lodash'; +import { capitalize, get, has, omitBy, startsWith } from 'lodash'; /** * WordPress dependencies */ import { addFilter } from '@wordpress/hooks'; import { + getBlockSupport, hasBlockSupport, __EXPERIMENTAL_STYLE_PROPERTY as STYLE_PROPERTY, } from '@wordpress/blocks'; @@ -96,6 +97,22 @@ function addAttribute( settings ) { return settings; } +/** + * Filters a style object returning only the keys + * that are serializable for a given block. + * + * @param {Object} style Input style object to filter. + * @param {Object} blockSupports Info about block supports. + * @return {Object} Filtered style. + */ +export function omitKeysNotToSerialize( style, blockSupports ) { + return omitBy( + style, + ( value, key ) => + !! blockSupports[ key ]?.__experimentalSkipSerialization + ); +} + /** * Override props assigned to save component to inject the CSS variables definition. * @@ -110,8 +127,11 @@ export function addSaveProps( props, blockType, attributes ) { } const { style } = attributes; + const filteredStyle = omitKeysNotToSerialize( style, { + [ COLOR_SUPPORT_KEY ]: getBlockSupport( blockType, COLOR_SUPPORT_KEY ), + } ); props.style = { - ...getInlineStyles( style ), + ...getInlineStyles( filteredStyle ), ...props.style, }; diff --git a/packages/block-editor/src/hooks/test/style.js b/packages/block-editor/src/hooks/test/style.js index 62c5a97b6e211e..afa1d45856b2a4 100644 --- a/packages/block-editor/src/hooks/test/style.js +++ b/packages/block-editor/src/hooks/test/style.js @@ -1,7 +1,7 @@ /** * Internal dependencies */ -import { getInlineStyles } from '../style'; +import { getInlineStyles, omitKeysNotToSerialize } from '../style'; describe( 'getInlineStyles', () => { it( 'should return an empty object when called with undefined', () => { @@ -28,3 +28,31 @@ describe( 'getInlineStyles', () => { } ); } ); } ); + +describe( 'omitKeysNotToSerialize', () => { + it( 'should return the same style if no keys are skipped from serialization', () => { + const style = { + color: { text: 'red' }, + lineHeight: 2, + }; + expect( omitKeysNotToSerialize( style, {} ) ).toEqual( { + color: { text: 'red' }, + lineHeight: 2, + } ); + } ); + + it( 'should omit the color key if it is skipped for serialization', () => { + const style = { + color: { text: 'red' }, + lineHeight: 2, + }; + const blockSupports = { + color: { + __experimentalSkipSerialization: true, + }, + }; + expect( omitKeysNotToSerialize( style, blockSupports ) ).toEqual( { + lineHeight: 2, + } ); + } ); +} );