Skip to content

Commit

Permalink
Merge pull request #2805 from WordPress/fix/get-block-error
Browse files Browse the repository at this point in the history
Selectors: Fix getBlock error for block not in state
  • Loading branch information
aduth committed Sep 27, 2017
2 parents 345ca17 + bf70177 commit feccae8
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
10 changes: 6 additions & 4 deletions editor/selectors.js
Expand Up @@ -380,9 +380,12 @@ export function getEditedPostPreviewLink( state ) {
export const getBlock = createSelector(
( state, uid ) => {
const block = state.editor.blocksByUid[ uid ];
const type = getBlockType( block.name );
if ( ! block ) {
return null;
}

if ( ! block || ! type || ! type.attributes ) {
const type = getBlockType( block.name );
if ( ! type || ! type.attributes ) {
return block;
}

Expand All @@ -394,8 +397,7 @@ export const getBlock = createSelector(
return result;
}, {} );

// Avoid injecting an empty `attributes: {}`
if ( ! block.attributes && ! metaAttributes.length ) {
if ( ! Object.keys( metaAttributes ).length ) {
return block;
}

Expand Down
52 changes: 52 additions & 0 deletions editor/test/selectors.js
Expand Up @@ -39,6 +39,7 @@ import {
getBlocks,
getBlockCount,
getSelectedBlock,
getEditedPostContent,
getMultiSelectedBlockUids,
getMultiSelectedBlocksStartUid,
getMultiSelectedBlocksEndUid,
Expand Down Expand Up @@ -84,6 +85,9 @@ describe( 'selectors', () => {

beforeEach( () => {
isEditedPostDirty.clear();
getBlock.clear();
getBlocks.clear();
getEditedPostContent.clear();
} );

afterAll( () => {
Expand Down Expand Up @@ -1071,6 +1075,54 @@ describe( 'selectors', () => {

expect( getBlock( state, 123 ) ).toEqual( { uid: 123, name: 'core/paragraph' } );
} );

it( 'should return null if the block is not present in state', () => {
const state = {
currentPost: {},
editor: {
blocksByUid: {},
edits: {},
},
};

expect( getBlock( state, 123 ) ).toBe( null );
} );

it( 'should merge meta attributes for the block', () => {
registerBlockType( 'core/meta-block', {
save: ( props ) => props.attributes.text,
category: 'common',
title: 'test block',
attributes: {
foo: {
type: 'string',
meta: 'foo',
},
},
} );

const state = {
currentPost: {
meta: {
foo: 'bar',
},
},
editor: {
blocksByUid: {
123: { uid: 123, name: 'core/meta-block' },
},
edits: {},
},
};

expect( getBlock( state, 123 ) ).toEqual( {
uid: 123,
name: 'core/meta-block',
attributes: {
foo: 'bar',
},
} );
} );
} );

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

0 comments on commit feccae8

Please sign in to comment.