Skip to content

Commit

Permalink
Clean empty objects
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad committed Mar 24, 2020
1 parent 583f1b2 commit dfca58c
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
16 changes: 15 additions & 1 deletion packages/block-editor/src/hooks/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* External dependencies
*/
import classnames from 'classnames';
import { pickBy, isEqual, isObject, identity, mapValues } from 'lodash';

/**
* WordPress dependencies
Expand All @@ -28,6 +29,19 @@ import { getBlockDOMNode } from '../utils/dom';

export const COLOR_SUPPORT_KEY = '__experimentalColor';

export const cleanEmptyObject = ( object ) => {
if ( ! isObject( object ) ) {
return object;
}
const cleanedNestedObjects = pickBy(
mapValues( object, cleanEmptyObject ),
identity
);
return isEqual( cleanedNestedObjects, {} )
? undefined
: cleanedNestedObjects;
};

/**
* Filters registered block settings, extending attributes to include
* `backgroundColor` and `textColor` attribute.
Expand Down Expand Up @@ -186,7 +200,7 @@ export const withBlockControls = createHigherOrderComponent(
? colorObject.slug
: undefined;
props.setAttributes( {
style: newStyle,
style: cleanEmptyObject( newStyle ),
[ attributeName ]: newNamedColor,
} );
};
Expand Down
12 changes: 12 additions & 0 deletions packages/block-editor/src/hooks/test/color.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Internal dependencies
*/
import { cleanEmptyObject } from '../color';

describe( 'cleanEmptyObject', () => {
it( 'should remove nested keys', () => {
expect( cleanEmptyObject( { color: { text: undefined } } ) ).toEqual(
undefined
);
} );
} );
4 changes: 4 additions & 0 deletions packages/block-editor/src/hooks/test/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ describe( 'getCSSVariables', () => {
} );
} );

it( 'should omit CSS variables when the provided value is falsy', () => {
expect( getCSSVariables( { color: undefined } ) ).toEqual( {} );
} );

it( 'should flatten nested style config', () => {
expect(
getCSSVariables( {
Expand Down
6 changes: 4 additions & 2 deletions packages/block-library/src/group/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ export const settings = {
example: {
attributes: {
style: {
textColor: '#000000',
backgroundColor: '#ffffff',
color: {
text: '#000000',
background: '#ffffff',
},
},
},
innerBlocks: [
Expand Down

0 comments on commit dfca58c

Please sign in to comment.