Skip to content

Commit

Permalink
Block categories - ensure that categories are unique by slug. (#62954)
Browse files Browse the repository at this point in the history
* 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 <chrico@git.wordpress.org>
Co-authored-by: talldan <talldanwp@git.wordpress.org>
  • Loading branch information
3 people authored Aug 2, 2024
1 parent 6581dfb commit c6d7b2f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/blocks/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ||
Expand Down
16 changes: 16 additions & 0 deletions packages/blocks/src/store/test/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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( [
{
Expand Down

1 comment on commit c6d7b2f

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in c6d7b2f.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/10209605288
📝 Reported issues:

Please sign in to comment.