From c6d7b2f73f0af71284d8a6a745062f2afdc88a62 Mon Sep 17 00:00:00 2001 From: Christian Leucht Date: Fri, 2 Aug 2024 05:38:32 +0200 Subject: [PATCH] Block categories - ensure that categories are unique by slug. (#62954) * blocks/store/reducer // ensure that categories are unique by slug. Block categories can be registered through backend by hooking into the "block_categories_all"-filter or through frontend by calling wp.blocks.setCategories(). Both require an array of WPBlockCategory elements. This change aims for making the categories: WPBlockCategory[] with unique entries by slug to avoid rendering in Block Inserter all Blocks duplicated. See also: #50061 * eslint * blocks/store/reducer.js // add test case for unique catgories by slug. ---- Co-authored-by: Chrico Co-authored-by: talldan --- packages/blocks/src/store/reducer.js | 7 ++++++- packages/blocks/src/store/test/reducer.js | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/blocks/src/store/reducer.js b/packages/blocks/src/store/reducer.js index 0851fc2bede4c..f1cfdcd04e303 100644 --- a/packages/blocks/src/store/reducer.js +++ b/packages/blocks/src/store/reducer.js @@ -328,7 +328,12 @@ export const groupingBlockName = createBlockNameSetterReducer( export function categories( state = DEFAULT_CATEGORIES, action ) { switch ( action.type ) { case 'SET_CATEGORIES': - return action.categories || []; + // Ensure, that categories are unique by slug. + const uniqueCategories = new Map(); + ( action.categories || [] ).forEach( ( category ) => { + uniqueCategories.set( category.slug, category ); + } ); + return [ ...uniqueCategories.values() ]; case 'UPDATE_CATEGORY': { if ( ! action.category || diff --git a/packages/blocks/src/store/test/reducer.js b/packages/blocks/src/store/test/reducer.js index babaaad4e0e0d..1a295f1efc30d 100644 --- a/packages/blocks/src/store/test/reducer.js +++ b/packages/blocks/src/store/test/reducer.js @@ -420,6 +420,22 @@ describe( 'categories', () => { expect( state ).toEqual( [ { slug: 'wings', title: 'Wings' } ] ); } ); + it( 'should ensure, that categories are unique by slug', () => { + const original = deepFreeze( [ + { slug: 'chicken', title: 'Chicken' }, + ] ); + + const state = categories( original, { + type: 'SET_CATEGORIES', + categories: [ { slug: 'chicken', title: 'Another chicken' } ], + } ); + + expect( state ).toEqual( [ + { slug: 'chicken', title: 'Another chicken' }, + ] ); + expect( state.length ).toBe( 1 ); + } ); + it( 'should add the category icon', () => { const original = deepFreeze( [ {