Skip to content

Commit

Permalink
Implement object property comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
ockham committed Jun 4, 2024
1 parent 8b0dacc commit 39c79ed
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/blocks/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { createSelector } from '@wordpress/data';
/**
* Internal dependencies
*/
import { getValueFromObjectPath } from './utils';
import { getValueFromObjectPath, matchesAttributes } from './utils';

/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
/** @typedef {import('../api/registration').WPBlockVariationScope} WPBlockVariationScope */
Expand Down Expand Up @@ -269,10 +269,21 @@ export function getActiveBlockVariation( state, blockName, attributes, scope ) {
if ( variationAttributeValue === undefined ) {
return false;
}
return (
variationAttributeValue ===
getValueFromObjectPath( attributes, attribute )
const blockAttributeValue = getValueFromObjectPath(
attributes,
attribute
);
// If the attribute value is an object, we need to compare its properties.
if (
variationAttributeValue !== null &&
typeof variationAttributeValue === 'object'
) {
return matchesAttributes(
blockAttributeValue,
variationAttributeValue
);
}
return variationAttributeValue === blockAttributeValue;
} );
if ( isMatch && definedAttributesLength > maxMatchedAttributes ) {
match = variation;
Expand Down
12 changes: 12 additions & 0 deletions packages/blocks/src/store/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,15 @@ export const getValueFromObjectPath = ( object, path, defaultValue ) => {
} );
return value ?? defaultValue;
};

export function matchesAttributes( blockAttributes, variation ) {
return Object.entries( variation ).every( ( [ key, value ] ) => {
if (
typeof value === 'object' &&
typeof blockAttributes[ key ] === 'object'
) {
return matchesAttributes( blockAttributes[ key ], value );
}
return blockAttributes[ key ] === value;
} );
}

0 comments on commit 39c79ed

Please sign in to comment.