Skip to content

Commit

Permalink
Implement skip serialization for color key in style att (#29253)
Browse files Browse the repository at this point in the history
  • Loading branch information
nosolosw authored Feb 26, 2021
1 parent 645224d commit c857bdb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
24 changes: 22 additions & 2 deletions packages/block-editor/src/hooks/style.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
*
Expand All @@ -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,
};

Expand Down
30 changes: 29 additions & 1 deletion packages/block-editor/src/hooks/test/style.js
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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,
} );
} );
} );

0 comments on commit c857bdb

Please sign in to comment.