Skip to content

Commit 75d61fc

Browse files
committed
Implement object property comparison
1 parent 8806d80 commit 75d61fc

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

packages/blocks/src/store/selectors.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { RichTextData } from '@wordpress/rich-text';
1212
/**
1313
* Internal dependencies
1414
*/
15-
import { getValueFromObjectPath } from './utils';
15+
import { getValueFromObjectPath, matchesAttributes } from './utils';
1616

1717
/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
1818
/** @typedef {import('../api/registration').WPBlockVariationScope} WPBlockVariationScope */
@@ -277,6 +277,17 @@ export function getActiveBlockVariation( state, blockName, attributes, scope ) {
277277
if ( blockAttributeValue instanceof RichTextData ) {
278278
blockAttributeValue = blockAttributeValue.toHTMLString();
279279
}
280+
// If the attribute value is an object, we need to compare its properties.
281+
if (
282+
variationAttributeValue !== null &&
283+
typeof variationAttributeValue === 'object' &&
284+
variationAttributeValue.constructor === Object
285+
) {
286+
return matchesAttributes(
287+
blockAttributeValue,
288+
variationAttributeValue
289+
);
290+
}
280291
return variationAttributeValue === blockAttributeValue;
281292
} );
282293
if ( isMatch && definedAttributesLength > maxMatchedAttributes ) {

packages/blocks/src/store/utils.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,27 @@ export const getValueFromObjectPath = ( object, path, defaultValue ) => {
1818
} );
1919
return value ?? defaultValue;
2020
};
21+
22+
/**
23+
* Determine whether a set of object properties matches a given object.
24+
*
25+
* Given an object of block attributes and an object of variation attributes,
26+
* this function checks recursively whether all the variation attributes are
27+
* present in the block attributes object.
28+
*
29+
* @param {Object} blockAttributes The object to inspect.
30+
* @param {Object} variationAttributes The object of property values to match.
31+
* @return {boolean} Whether the block attributes match the variation attributes.
32+
*/
33+
export function matchesAttributes( blockAttributes, variationAttributes ) {
34+
return Object.entries( variationAttributes ).every( ( [ key, value ] ) => {
35+
if (
36+
typeof value === 'object' &&
37+
value !== null &&
38+
typeof blockAttributes[ key ] === 'object'
39+
) {
40+
return matchesAttributes( blockAttributes[ key ], value );
41+
}
42+
return blockAttributes[ key ] === value;
43+
} );
44+
}

0 commit comments

Comments
 (0)