Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lodash: Refactor away from _.set() in PushChangesToGlobalStylesControl #52404

Merged
merged 1 commit into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/core-data/src/utils/set-nested-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*
* @see https://lodash.com/docs/4.17.15#set
*
* @todo Needs to be deduplicated with its copy in `@wordpress/edit-site`.
*
* @param {Object} object Object to modify
* @param {Array} path Path of the property to set.
* @param {*} value Value to set.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { get, set } from 'lodash';
import { get } from 'lodash';

/**
* WordPress dependencies
Expand Down Expand Up @@ -119,6 +119,46 @@ function useChangesToPush( name, attributes ) {
);
}

/**
* Sets the value at path of object.
* If a portion of path doesn’t exist, it’s created.
* Arrays are created for missing index properties while objects are created
* for all other missing properties.
*
* This function intentionally mutates the input object.
*
* Inspired by _.set().
*
* @see https://lodash.com/docs/4.17.15#set
*
* @todo Needs to be deduplicated with its copy in `@wordpress/core-data`.
*
* @param {Object} object Object to modify
* @param {Array} path Path of the property to set.
* @param {*} value Value to set.
*/
function setNestedValue( object, path, value ) {
if ( ! object || typeof object !== 'object' ) {
return object;
}

path.reduce( ( acc, key, idx ) => {
if ( acc[ key ] === undefined ) {
if ( Number.isInteger( path[ idx + 1 ] ) ) {
acc[ key ] = [];
} else {
acc[ key ] = {};
}
}
if ( idx === path.length - 1 ) {
acc[ key ] = value;
}
return acc[ key ];
}, object );

return object;
}

function cloneDeep( object ) {
return ! object ? {} : JSON.parse( JSON.stringify( object ) );
}
Expand Down Expand Up @@ -148,8 +188,12 @@ function PushChangesToGlobalStylesControl( {
const newUserConfig = cloneDeep( userConfig );

for ( const { path, value } of changes ) {
set( newBlockStyles, path, undefined );
set( newUserConfig, [ 'styles', 'blocks', name, ...path ], value );
setNestedValue( newBlockStyles, path, undefined );
setNestedValue(
newUserConfig,
[ 'styles', 'blocks', name, ...path ],
value
);
}

// @wordpress/core-data doesn't support editing multiple entity types in
Expand Down