Skip to content

Commit

Permalink
Refactor getBlockTransforms to use block type normalization
Browse files Browse the repository at this point in the history
  • Loading branch information
gziolo committed Nov 7, 2018
1 parent 2f5ef04 commit 896e4b9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
10 changes: 6 additions & 4 deletions packages/blocks/src/api/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { createHooks, applyFilters } from '@wordpress/hooks';
* Internal dependencies
*/
import { getBlockType, getBlockTypes } from './registration';
import { normalizeBlockType } from './utils';

/**
* Returns a block object given its type and attributes.
Expand Down Expand Up @@ -279,21 +280,22 @@ export function findTransform( transforms, predicate ) {
* transform object includes `blockName` as a property.
*
* @param {string} direction Transform direction ("to", "from").
* @param {?string} blockName Optional block name.
* @param {string|Object} blockTypeOrName Block type or name.
*
* @return {Array} Block transforms for direction.
*/
export function getBlockTransforms( direction, blockName ) {
export function getBlockTransforms( direction, blockTypeOrName ) {
// When retrieving transforms for all block types, recurse into self.
if ( blockName === undefined ) {
if ( blockTypeOrName === undefined ) {
return flatMap(
getBlockTypes(),
( { name } ) => getBlockTransforms( direction, name )
);
}

// Validate that block type exists and has array of direction.
const { transforms } = getBlockType( blockName ) || {};
const blockType = normalizeBlockType( blockTypeOrName );
const { name: blockName, transforms } = blockType || {};
if ( ! transforms || ! Array.isArray( transforms[ direction ] ) ) {
return [];
}
Expand Down
21 changes: 20 additions & 1 deletion packages/blocks/src/api/test/factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ import {
getBlockTransforms,
findTransform,
} from '../factory';
import { getBlockTypes, unregisterBlockType, registerBlockType } from '../registration';
import {
getBlockType,
getBlockTypes,
registerBlockType,
unregisterBlockType,
} from '../registration';

describe( 'block factory', () => {
const defaultBlockSettings = {
Expand Down Expand Up @@ -1181,6 +1186,20 @@ describe( 'block factory', () => {
},
] );
} );

it( 'should return single block type transforms when passed as an object', () => {
const transforms = getBlockTransforms(
'from',
getBlockType( 'core/transform-from-text-block-1' )
);

expect( transforms ).toEqual( [
{
blocks: [ 'core/text-block' ],
blockName: 'core/transform-from-text-block-1',
},
] );
} );
} );

describe( 'findTransform', () => {
Expand Down

0 comments on commit 896e4b9

Please sign in to comment.