Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new function to register a new block category #1732

Closed
wants to merge 17 commits into from
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
55 changes: 55 additions & 0 deletions blocks/api/categories.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint no-console: [ 'error', { allow: [ 'error' ] } ] */

/**
* WordPress dependencies
*/
Expand All @@ -20,6 +22,14 @@ const categories = [
{ slug: 'reusable-blocks', title: __( 'Saved Blocks' ) },
];

/**
* @type {RegExp}
* @const
*
* Category names must be a combination of lower-case letters, numbers, and hypens
*/
const categoryNamePattern = /^[a-z0-9-]+$/;

/**
* Returns all the block categories.
*
Expand All @@ -28,3 +38,48 @@ const categories = [
export function getCategories() {
return categories;
}

Copy link
Member

@gziolo gziolo Feb 5, 2018

Choose a reason for hiding this comment

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

It's also possible to achieve a very similar result using this code:

import { applyFilters } from '@wordpress/hooks';

let cachedCategories;
export function getCategories() {
    if ( ! cachedCategories ) {
        const extraCategories = ...applyFilters( 'blocks.getExtraCategories',  [] );
        // we can perform optonal validation here and filter out all items that don't have slug and name 
        cachedCategories = [ ...extraCategories, ...categories ];
    }        
    return cachedCategories;
}

Usage:

function addCategory( extraCategories ) {
    return [ ...extraCategories, { slug: 'my-category', title: __( 'My category' ) } ];
} 

wp.hooks.addFilter( 'blocks.getExtraCategories', 'my-plugin/extra-categories', addCategory );

Copy link
Member

Choose a reason for hiding this comment

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

also, since JavaScript functions are much cheaper than PHP functions we can wrap via composition and keep different logic separate 😄

import { once } from 'lodash'

const getCategories = once( () => [
	...applyFilters( 'blocks.getExtraCategories', [] ),
	...categories,
] )

and without lodash it's easy to recreate once

const once = f => {
	let isPrimed = false
	let value

	return ( ...args ) => ! isPrimed
		? ( isPrimed = true, value = f( ...args ) )
		: value
}

Copy link
Member

Choose a reason for hiding this comment

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

@dmsnell thanks for making it even simpler :)

/**
* Register a new block Category.
*
* @param {Array} category e.g {slug: 'custom', title: __('Custom Blocks')}
*
* @return {Array} categories
*/
export function registerCategory( category ) {
if ( ! category ) {
console.error(
'The block Category must be defined'
);
return;
}
if ( ! category.slug ) {
console.error(
'The block Category slug must be defined'
);
return;
}
if ( ! categoryNamePattern.test( category.slug ) ) {
console.error(
'The block Category slug must not contain characters which are invalid for urls'
);
return;
}

if ( categories.some( x => x.slug === category.slug ) ) {
console.error(
'The block Category "' + category.slug + '" is already registered'
);
return;
}
if ( ! category.title ) {
console.error(
'The block Category title must be defined'
);
return;
}

categories.push( category );
return categories;
}
Copy link
Member

Choose a reason for hiding this comment

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

oh typing…we either get it in a robust and helpful way or we manually force it in unreliable and costly ways…

(this is not a comment on the code submission, but just me noting a place where having static typing could save us so much effort and provide us so much help)


5 changes: 4 additions & 1 deletion blocks/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ export {
getSaveElement,
} from './serializer';
export { isValidBlock } from './validation';
export { getCategories } from './categories';
export {
getCategories,
registerCategory,
} from './categories';
export {
registerBlockType,
unregisterBlockType,
Expand Down
69 changes: 69 additions & 0 deletions blocks/api/test/categories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/* eslint-disable no-console */

/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
*/
import {
registerCategory,
} from '../categories';

describe( 'categories', () => {
const error = console.error;

// Reset block state before each test.
beforeEach( () => {
console.error = jest.fn();
} );

afterEach( () => {
console.error = error;
} );

describe( 'registerCategory()', () => {
it( 'should reject empty categories', () => {
const categories = registerCategory();
expect( console.error ).toHaveBeenCalledWith( 'The block Category must be defined' );
expect( categories ).toBeUndefined();
} );

it( 'should reject categories with empty slug', () => {
const categories = registerCategory( { slug: '', title: __( 'Custom Blocks' ) } );
expect( console.error ).toHaveBeenCalledWith( 'The block Category slug must be defined' );
expect( categories ).toBeUndefined();
} );

it( 'should reject categories with slug not defined', () => {
const categories = registerCategory( { title: __( 'Custom Blocks' ) } );
expect( console.error ).toHaveBeenCalledWith( 'The block Category slug must be defined' );
expect( categories ).toBeUndefined();
} );

it( 'should reject categories with invalid slug', () => {
const categories = registerCategory( { slug: 'custom blocks', title: __( 'Custom Blocks' ) } );
expect( console.error ).toHaveBeenCalledWith( 'The block Category slug must not contain characters which are invalid for urls' );
expect( categories ).toBeUndefined();
} );

it( 'should reject categories with empty title', () => {
const categories = registerCategory( { slug: 'custom-blocks', title: '' } );
expect( console.error ).toHaveBeenCalledWith( 'The block Category title must be defined' );
expect( categories ).toBeUndefined();
} );

it( 'should store the new category', () => {
const categories = registerCategory( { slug: 'custom-blocks', title: 'Custom Blocks' } );
expect( categories ).toEqual( jasmine.arrayContaining( [ { slug: 'custom-blocks', title: 'Custom Blocks' } ] ) );
} );

it( 'should reject categories already registered', () => {
const categories = registerCategory( { slug: 'custom-blocks', title: 'Custom Blocks' } );
expect( console.error ).toHaveBeenCalledWith( 'The block Category "custom-blocks" is already registered' );
expect( categories ).toBeUndefined();
} );
} );
} );