Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,19 @@ const BLOCK_CONTEXT_CACHE = new WeakMap();
*/
export default function getBlockContext( attributes, blockType ) {
if ( ! BLOCK_CONTEXT_CACHE.has( blockType ) ) {
BLOCK_CONTEXT_CACHE.set( blockType, new WeakMap() );
BLOCK_CONTEXT_CACHE.set( blockType, new Map() );
}

const blockTypeCache = BLOCK_CONTEXT_CACHE.get( blockType );
if ( ! blockTypeCache.has( attributes ) ) {
const context = mapValues(
blockType.providesContext,
( attributeName ) => attributes[ attributeName ]
);
const context = mapValues(
blockType.providesContext,
( attributeName ) => attributes[ attributeName ]
);

blockTypeCache.set( attributes, context );
const cacheKey = JSON.stringify( context );
if ( ! blockTypeCache.has( cacheKey ) ) {
blockTypeCache.set( cacheKey, context );
}

return blockTypeCache.get( attributes );
return blockTypeCache.get( cacheKey );
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* WordPress dependencies
*/
import {
getBlockType,
getBlockTypes,
registerBlockType,
unregisterBlockType,
} from '@wordpress/blocks';

/**
* Internal dependencies
*/
import getBlockContext from '../get-block-context';

describe( 'getBlockContext', () => {
beforeAll( () => {
registerBlockType( 'core/fruit-basket', {
category: 'text',
title: 'Fruit Basket',
attributes: {
id: {
type: 'number',
},
name: {
type: 'string',
},
},
providesContext: { basketId: 'id' },
} );
} );
afterAll( () => {
getBlockTypes().forEach( ( block ) => {
unregisterBlockType( block.name );
} );
} );

it( 'should return cached value when attributes are the same', () => {
const attributes = { id: 1, name: '' };
const blockType = getBlockType( 'core/fruit-basket' );

const prevContext = getBlockContext( attributes, blockType );
const nextContext = getBlockContext( attributes, blockType );

expect( prevContext ).toBe( nextContext );
} );

it( 'should return cached value if attributes used in context are the same', () => {
Copy link
Member

Choose a reason for hiding this comment

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

Should we also add a test for the case when there's no providesContext?

Copy link
Member Author

Choose a reason for hiding this comment

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

The blockType object is a required argument, so I'm not sure how helpful that test would be.

const blockType = getBlockType( 'core/fruit-basket' );

const prevContext = getBlockContext( { id: 1, name: '' }, blockType );
const nextContext = getBlockContext(
{ id: 1, name: 'Apples' },
blockType
);

expect( prevContext ).toBe( nextContext );
} );
} );