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

Block API: Allow "array of attributes to be compared" for isActive property in block variations #30913

Merged
merged 19 commits into from
Apr 22, 2021
Merged
Show file tree
Hide file tree
Changes from 12 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: 1 addition & 1 deletion docs/reference-guides/block-api/block-variations.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ An object describing a variation defined for the block type can contain the foll
- `block` - Used by blocks to filter specific block variations. Mostly used in Placeholder patterns like `Columns` block.
- `transform` - Block Variation will be shown in the component for Block Variations transformations.
- `keywords` (optional, type `string[]`) - An array of terms (which can be translated) that help users discover the variation while searching.
- `isActive` (optional, type `Function`) - A function that accepts a block's attributes and the variation's attributes and determines if a variation is active. This function doesn't try to find a match dynamically based on all block's attributes, as in many cases some attributes are irrelevant. An example would be for `embed` block where we only care about `providerNameSlug` attribute's value.
- `isActive` (optional, type `Function|string[]`) - A function that accepts a block's attributes and the variation's attributes and determines if a variation is active. This function doesn't try to find a match dynamically based on all block's attributes, as in many cases some attributes are irrelevant. An example would be for `embed` block where we only care about `providerNameSlug` attribute's value. We can also use a `string[]` to tell which attributes should be compared as a shorthand. Each attributes will be matched and the variation will be active if all of them are matching.
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved

The main difference between style variations and block variations is that a style variation just applies a `css class` to the block, so it can be styled in an alternative way. If we want to apply initial attributes or inner blocks, we fall in block variation territory.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,19 @@ export default function useBlockDisplayInformation( clientId ) {
const { getBlockName, getBlockAttributes } = select(
blockEditorStore
);
const { getBlockType, getBlockVariations } = select( blocksStore );
const { getBlockType, getActiveBlockVariation } = select(
blocksStore
);
const blockName = getBlockName( clientId );
const blockType = getBlockType( blockName );
if ( ! blockType ) return null;
const variations = getBlockVariations( blockName );
const blockTypeInfo = {
title: blockType.title,
icon: blockType.icon,
description: blockType.description,
};
if ( ! variations?.length ) return blockTypeInfo;
const attributes = getBlockAttributes( clientId );
const match = variations.find( ( variation ) =>
variation.isActive?.( attributes, variation.attributes )
);
const match = getActiveBlockVariation( blockName, attributes );
if ( ! match ) return blockTypeInfo;
return {
title: match.title || blockType.title,
Expand Down
10 changes: 5 additions & 5 deletions packages/block-editor/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import {
/**
* WordPress dependencies
*/
import { combineReducers } from '@wordpress/data';
import { getBlockVariations } from '@wordpress/blocks';
import { combineReducers, select } from '@wordpress/data';
import { store as blocksStore } from '@wordpress/blocks';
/**
* Internal dependencies
*/
Expand Down Expand Up @@ -1510,9 +1510,9 @@ export function preferences( state = PREFERENCES_DEFAULTS, action ) {
case 'REPLACE_BLOCKS':
return action.blocks.reduce( ( prevState, block ) => {
const { attributes, name: blockName } = block;
const variations = getBlockVariations( blockName );
const match = variations?.find( ( variation ) =>
variation.isActive?.( attributes, variation.attributes )
const match = select( blocksStore ).getActiveBlockVariation(
blockName,
attributes
);
// If a block variation match is found change the name to be the same with the
// one that is used for block variations in the Inserter (`getItemFromVariation`).
Expand Down
32 changes: 32 additions & 0 deletions packages/blocks/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,38 @@ export function getBlockVariations( state, blockName, scope ) {
} );
}

/**
* Returns the active block variation for a given block based on its attributes.
ntsekouras marked this conversation as resolved.
Show resolved Hide resolved
*
* @param {Object} state Data state.
* @param {string} blockName Name of block (example: “core/columns”).
* @param {Object} attributes Block attributes used to determine active variation.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @return {(WPBlockVariation|void)} Active block variation.
david-szabo97 marked this conversation as resolved.
Show resolved Hide resolved
*/
export function getActiveBlockVariation( state, blockName, attributes, scope ) {
const variations = getBlockVariations( state, blockName, scope );

const match = variations?.find( ( variation ) => {
if ( Array.isArray( variation.isActive ) ) {
david-szabo97 marked this conversation as resolved.
Show resolved Hide resolved
const blockType = getBlockType( state, blockName );
const attributeKeys = Object.keys( blockType.attributes || {} );
return variation.isActive
.filter( ( attribute ) => attributeKeys.includes( attribute ) )
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: Would it be worth validating this earlier during block registration? It might be nice for folks to know that something isn't quite right when developing blocks.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually that's what I had in mind too in my first comment. This way we will avoid calling this check so many times.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! First iteration is here: 637b62b

.every(
david-szabo97 marked this conversation as resolved.
Show resolved Hide resolved
( attribute ) =>
attributes[ attribute ] ===
variation.attributes[ attribute ]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we'll still want to return false if either of these values is undefined. Blocks and variations may have optional attributes.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't come up with a case for this 🤔 It seems to be working as expected:

  1. If both of them are undefined, then that's correct and should match.
  2. If variation.attributes[ attribute ] = undefined and attributes[ attribute ] != undefined then it won't match
  3. If variation.attributes[ attribute ] != undefined and attributes[ attribute ] = undefined then it won't match

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gwwar can you expand on the use case you have in mind with an example?

Copy link
Contributor

@gwwar gwwar Apr 20, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I missed 👀 that we were already iterating over variations instead of all possible block attributes, so only the left side may be undefined, eg attributes[ attribute ]. Code here is fine 👍

btw I personally find that code reuse in tests isn't that useful. What's nicer for me is being able to read a single test case without needing to skip to different definitions. (Fixtures/snapshots can also help when things go crazy). Curious if folks had thoughts on that.

Here's a free test case, where I verified this:

it( 'should handle optional attributes', () => {
				const testLinkName = 'test/link-block';
				const state = {
					blockTypes: {
						[ testLinkName ]: {
							name: testLinkName,
							attributes: {
								url: { type: 'string' },
								type: { type: 'string' },
								id: { type: 'number' },
							},
						},
					},
					blockVariations: {
						[ testLinkName ]: [
							{
								attributes: { url: 'https://wordpress.org' },
								isActive: [ 'url' ],
							},
							{
								attributes: { type: 'foo' },
								isActive: [ 'type' ],
							},
							{
								attributes: {
									type: 'bar',
									url: 'https://example.com',
								},
								isActive: [ 'type', 'url' ],
							},
						],
					},
				};

				expect(
					getActiveBlockVariation( state, testLinkName, {
						type: 'foo',
					} )
				).toEqual( {
					attributes: { type: 'foo' },
					isActive: [ 'type' ],
				} );

				expect(
					getActiveBlockVariation( state, testLinkName, {
						url: 'https://wordpress.org',
					} )
				).toEqual( {
					attributes: { url: 'https://wordpress.org' },
					isActive: [ 'url' ],
				} );

				expect(
					getActiveBlockVariation( state, testLinkName, {
						type: 'bar',
						url: 'https://example.com',
					} )
				).toEqual( {
					attributes: {
						type: 'bar',
						url: 'https://example.com',
					},
					isActive: [ 'type', 'url' ],
				} );

				expect(
					getActiveBlockVariation( state, testLinkName, {
						id: 1234,
					} )
				).toEqual( undefined );
			} );

Copy link
Member Author

@david-szabo97 david-szabo97 Apr 20, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I had that in mind too. 😄 That's why the last tests are totally separate. Definitely needs some cleaning. A little bit of reuse doesn't hurt though 😄

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A little bit of reuse doesn't hurt though

Certainly, I wanted to leave a note since I was having a bit of trouble reading what the state shape was without inspecting tests.

);
}

return variation.isActive?.( attributes, variation.attributes );
} );

return match;
}

/**
* Returns the default block variation for the given block type.
* When there are multiple variations annotated as the default one,
Expand Down
250 changes: 250 additions & 0 deletions packages/blocks/src/store/test/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
getGroupingBlockName,
isMatchingSearchTerm,
getCategories,
getActiveBlockVariation,
} from '../selectors';

describe( 'selectors', () => {
Expand Down Expand Up @@ -277,6 +278,255 @@ describe( 'selectors', () => {
);
} );
} );
describe( 'getActiveBlockVariation', () => {
const blockTypeWithTestAttributes = {
name: 'block/name',
attributes: {
testAttribute: {},
firstTestAttribute: {},
secondTestAttribute: {},
},
};
const FIRST_VARIATION_TEST_ATTRIBUTE_VALUE = 1;
const SECOND_VARIATION_TEST_ATTRIBUTE_VALUE = 2;
const UNUSED_TEST_ATTRIBUTE_VALUE = 5555;
const firstActiveBlockVariationFunction = {
...firstBlockVariation,
attributes: {
testAttribute: FIRST_VARIATION_TEST_ATTRIBUTE_VALUE,
},
isActive: ( blockAttributes, variationAttributes ) => {
return (
blockAttributes.testAttribute ===
variationAttributes.testAttribute
);
},
};
const secondActiveBlockVariationFunction = {
...secondBlockVariation,
attributes: {
testAttribute: SECOND_VARIATION_TEST_ATTRIBUTE_VALUE,
},
isActive: ( blockAttributes, variationAttributes ) => {
return (
blockAttributes.testAttribute ===
variationAttributes.testAttribute
);
},
};
const firstActiveBlockVariationArray = {
...firstBlockVariation,
attributes: {
testAttribute: FIRST_VARIATION_TEST_ATTRIBUTE_VALUE,
},
isActive: [ 'testAttribute' ],
};
const secondActiveBlockVariationArray = {
...secondBlockVariation,
attributes: {
testAttribute: SECOND_VARIATION_TEST_ATTRIBUTE_VALUE,
},
isActive: [ 'testAttribute' ],
};
const createBlockVariationsStateWithTestBlockType = (
variations
) =>
deepFreeze( {
...createBlockVariationsState( variations ),
blockTypes: {
[ blockTypeWithTestAttributes.name ]: blockTypeWithTestAttributes,
},
} );
const stateFunction = createBlockVariationsStateWithTestBlockType( [
firstActiveBlockVariationFunction,
secondActiveBlockVariationFunction,
thirdBlockVariation,
] );
const stateArray = createBlockVariationsStateWithTestBlockType( [
firstActiveBlockVariationArray,
secondActiveBlockVariationArray,
thirdBlockVariation,
] );
test.each( [
[
firstActiveBlockVariationFunction.name,
firstActiveBlockVariationFunction,
],
[
secondActiveBlockVariationFunction.name,
secondActiveBlockVariationFunction,
],
] )(
'should return the active variation based on the given isActive function (%s)',
( _variationName, variation ) => {
const blockAttributes = {
testAttribute: variation.attributes.testAttribute,
};

const result = getActiveBlockVariation(
stateFunction,
blockName,
blockAttributes
);

expect( result ).toEqual( variation );
}
);
it( 'should return undefined if no active variation is found', () => {
const blockAttributes = {
testAttribute: UNUSED_TEST_ATTRIBUTE_VALUE,
};

const result = getActiveBlockVariation(
stateFunction,
blockName,
blockAttributes
);

expect( result ).toBeUndefined();
} );
it( 'should return the active variation based on the given isActive array', () => {
david-szabo97 marked this conversation as resolved.
Show resolved Hide resolved
[
firstActiveBlockVariationArray,
secondActiveBlockVariationArray,
].forEach( ( variation ) => {
const blockAttributes = {
testAttribute: variation.attributes.testAttribute,
};

const result = getActiveBlockVariation(
stateArray,
blockName,
blockAttributes
);

expect( result ).toEqual( variation );
} );
} );
it( 'should return the active variation based on the given isActive array (multiple values)', () => {
const variations = [
{
name: 'variation-1',
attributes: {
firstTestAttribute: 1,
secondTestAttribute: 10,
},
isActive: [
'firstTestAttribute',
'secondTestAttribute',
],
},
{
name: 'variation-2',
attributes: {
firstTestAttribute: 2,
secondTestAttribute: 20,
},
isActive: [
'firstTestAttribute',
'secondTestAttribute',
],
},
{
name: 'variation-3',
attributes: {
firstTestAttribute: 1,
secondTestAttribute: 20,
},
isActive: [
'firstTestAttribute',
'secondTestAttribute',
],
},
];

const state = createBlockVariationsStateWithTestBlockType(
variations
);

expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 1,
secondTestAttribute: 10,
} )
).toEqual( variations[ 0 ] );
expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 2,
secondTestAttribute: 20,
} )
).toEqual( variations[ 1 ] );
expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 1,
secondTestAttribute: 20,
} )
).toEqual( variations[ 2 ] );
} );
it( 'should ignore attributes that are not defined in the block type', () => {
const variations = [
{
name: 'variation-1',
attributes: {
firstTestAttribute: 1,
secondTestAttribute: 10,
undefinedTestAttribute: 100,
},
isActive: [
'firstTestAttribute',
'secondTestAttribute',
'undefinedTestAttribute',
],
},
{
name: 'variation-2',
attributes: {
firstTestAttribute: 2,
secondTestAttribute: 20,
undefinedTestAttribute: 200,
},
isActive: [
'firstTestAttribute',
'secondTestAttribute',
'undefinedTestAttribute',
],
},
];

const state = createBlockVariationsStateWithTestBlockType(
variations
);

expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 1,
secondTestAttribute: 10,
undefinedTestAttribute: 100,
} )
).toEqual( variations[ 0 ] );
expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 1,
secondTestAttribute: 10,
undefinedTestAttribute: 1234,
} )
).toEqual( variations[ 0 ] );
expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 2,
secondTestAttribute: 20,
undefinedTestAttribute: 200,
} )
).toEqual( variations[ 1 ] );
expect(
getActiveBlockVariation( state, blockName, {
firstTestAttribute: 2,
secondTestAttribute: 20,
undefinedTestAttribute: 2345,
} )
).toEqual( variations[ 1 ] );
} );
} );
describe( 'getDefaultBlockVariation', () => {
it( 'should return the default variation when set', () => {
const defaultBlockVariation = {
Expand Down