Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ module.exports = {
selector: 'ImportDeclaration[source.value=/^plugins$/]',
message: 'Use @wordpress/plugins as import path instead.',
},
{
"selector": "ImportDeclaration[source.value=/^core-data$/]",
"message": "Use @wordpress/core-data as import path instead."
},
{
selector: 'CallExpression[callee.name="deprecated"] Property[key.name="version"][value.value=/' + majorMinorRegExp + '/]',
message: 'Deprecated functions must be removed before releasing this version.',
Expand Down
2 changes: 1 addition & 1 deletion bin/build-plugin-zip.sh
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ zip -r gutenberg.zip \
blocks/library/*/*.php \
post-content.js \
$vendor_scripts \
{blocks,components,date,editor,element,hooks,i18n,data,utils,edit-post,viewport,plugins}/build/*.{js,map} \
{blocks,components,date,editor,element,hooks,i18n,data,utils,edit-post,viewport,plugins,core-data}/build/*.{js,map} \
{blocks,components,editor,edit-post}/build/*.css \
languages/gutenberg.pot \
languages/gutenberg-translations.php \
Expand Down
17 changes: 10 additions & 7 deletions blocks/library/categories/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* WordPress dependencies

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I love how this file has been refactored 👍

*/
import { Component } from '@wordpress/element';
import { Placeholder, Spinner, ToggleControl, withAPIData } from '@wordpress/components';
import { Placeholder, Spinner, ToggleControl } from '@wordpress/components';
import { withSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { times, unescape } from 'lodash';

Expand Down Expand Up @@ -46,7 +47,7 @@ class CategoriesBlock extends Component {
}

getCategories( parentId = null ) {
const categories = this.props.categories.data;
const categories = this.props.categories;
if ( ! categories || ! categories.length ) {
return [];
}
Expand Down Expand Up @@ -142,9 +143,8 @@ class CategoriesBlock extends Component {
}

render() {
const { attributes, focus, setAttributes } = this.props;
const { attributes, focus, setAttributes, isRequesting } = this.props;
const { align, displayAsDropdown, showHierarchy, showPostCounts } = attributes;
const categories = this.getCategories();

const inspectorControls = focus && (
<InspectorControls key="inspector">
Expand All @@ -167,7 +167,7 @@ class CategoriesBlock extends Component {
</InspectorControls>
);

if ( ! categories.length ) {
if ( isRequesting ) {
return [
inspectorControls,
<Placeholder
Expand Down Expand Up @@ -204,8 +204,11 @@ class CategoriesBlock extends Component {
}
}

export default withAPIData( () => {
export default withSelect( ( select ) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

❤️

const { getCategories, isRequestingCategories } = select( 'core' );

return {
categories: '/wp/v2/categories',
categories: getCategories(),
isRequesting: isRequestingCategories(),
};
} )( CategoriesBlock );
49 changes: 49 additions & 0 deletions core-data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Core Data
=========

Core Data is a [data module](../data) intended to simplify access to and manipulation of core WordPress entities. It registers its own store and provides a number of selectors which resolve data from the WordPress REST API automatically, along with dispatching action creators to manipulate data.

Used in combination with features of the data module such as [`subscribe`](https://github.com/WordPress/gutenberg/tree/master/data#subscribe-function) or [higher-order components](https://github.com/WordPress/gutenberg/tree/master/data#higher-order-components), it enables a developer to easily add data into the logic and display of their plugin.

## Example

Below is an example of a component which simply renders a list of categories:

```jsx
const { withSelect } = wp.data;

function MyCategoriesList( { categories, isRequesting } ) {
if ( isRequesting ) {
return 'Loading…';
}

return (
<ul>
{ categories.map( ( category ) => (
<li key={ category.id }>{ category.name }</li>
) ) }
</ul>
);
}

MyCategoriesList = withSelect( ( select ) => {
const { getCategories, isRequestingCategories } = select( 'core' );

return {
categories: getCategories(),
isRequesting: isRequestingCategories(),
};
} );
```

## Actions

The following set of dispatching action creators are available on the object returned by `wp.data.dispatch( 'core' )`:

_Refer to `actions.js` for the full set of dispatching action creators. In the future, this documentation will be automatically generated to detail all available dispatching action creators._

## Selectors

The following selectors are available on the object returned by `wp.data.select( 'core' )`:

_Refer to `selectors.js` for the full set of selectors. In the future, this documentation will be automatically generated to detail all available selectors._
33 changes: 33 additions & 0 deletions core-data/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Returns an action object used in signalling that the request for a given
* data type has been made.
*
* @param {string} dataType Data type requested.
* @param {?string} subType Optional data sub-type.
*
* @return {Object} Action object.
*/
export function setRequested( dataType, subType ) {
return {
type: 'SET_REQUESTED',
dataType,
subType,
};
}

/**
* Returns an action object used in signalling that terms have been received
* for a given taxonomy.
*
* @param {string} taxonomy Taxonomy name.
* @param {Object[]} terms Terms received.
*
* @return {Object} Action object.
*/
export function receiveTerms( taxonomy, terms ) {
return {
type: 'RECEIVE_TERMS',
taxonomy,
terms,
};
}
21 changes: 21 additions & 0 deletions core-data/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

core-data still misses README file.

* WordPress Dependencies
*/
import { registerStore } from '@wordpress/data';

/**
* Internal dependencies
*/
import reducer from './reducer';
import * as selectors from './selectors';
import * as actions from './actions';
import * as resolvers from './resolvers';

const store = registerStore( 'core', {
reducer,
actions,
selectors,
resolvers,
} );

export default store;
42 changes: 42 additions & 0 deletions core-data/reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* External dependencies
*/
import { combineReducers } from 'redux';

/**
* Reducer managing terms state. Keyed by taxonomy slug, the value is either
* undefined (if no request has been made for given taxonomy), null (if a
* request is in-flight for given taxonomy), or the array of terms for the
* taxonomy.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string} Updated state.
*/
export function terms( state = {}, action ) {
switch ( action.type ) {
case 'RECEIVE_TERMS':
return {
...state,
[ action.taxonomy ]: action.terms,
};

case 'SET_REQUESTED':
const { dataType, subType: taxonomy } = action;
if ( dataType !== 'terms' || state.hasOwnProperty( taxonomy ) ) {
return state;
}

return {
...state,
[ taxonomy ]: null,
};
}

return state;
}

export default combineReducers( {
terms,
} );
19 changes: 19 additions & 0 deletions core-data/resolvers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* WordPress dependencies
*/
import apiRequest from '@wordpress/api-request';

/**
* Internal dependencies
*/
import { setRequested, receiveTerms } from './actions';

/**
* Requests categories from the REST API, yielding action objects on request
* progress.
*/
export async function* getCategories() {
yield setRequested( 'terms', 'categories' );
const categories = await apiRequest( { path: '/wp/v2/categories' } );
yield receiveTerms( 'categories', categories );
}
47 changes: 47 additions & 0 deletions core-data/selectors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Returns all the available terms for the given taxonomy.
*
* @param {Object} state Data state.
* @param {string} taxonomy Taxonomy name.
*
* @return {Array} Categories list.
*/
export function getTerms( state, taxonomy ) {
return state.terms[ taxonomy ];
}

/**
* Returns all the available categories.
*
* @param {Object} state Data state.
*
* @return {Array} Categories list.
*/
export function getCategories( state ) {
return getTerms( state, 'categories' );
}

/**
* Returns true if a request is in progress for terms data of a given taxonomy,
* or false otherwise.
*
* @param {Object} state Data state.
* @param {string} taxonomy Taxonomy name.
*
* @return {boolean} Whether a request is in progress for taxonomy's terms.
*/
export function isRequestingTerms( state, taxonomy ) {
return state.terms[ taxonomy ] === null;
}

/**
* Returns true if a request is in progress for categories data, or false
* otherwise.
*
* @param {Object} state Data state.
*
* @return {boolean} Whether a request is in progress for categories.
*/
export function isRequestingCategories( state ) {
return isRequestingTerms( state, 'categories' );
}
1 change: 1 addition & 0 deletions core-data/test/__mocks__/@wordpress/api-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = jest.fn();
69 changes: 69 additions & 0 deletions core-data/test/reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* External dependencies
*/
import deepFreeze from 'deep-freeze';

/**
* Internal dependencies
*/
import { terms } from '../reducer';

describe( 'terms()', () => {
it( 'returns an empty object by default', () => {
const state = terms( undefined, {} );

expect( state ).toEqual( {} );
} );

it( 'returns with received terms', () => {
const originalState = deepFreeze( {} );
const state = terms( originalState, {
type: 'RECEIVE_TERMS',
taxonomy: 'categories',
terms: [ { id: 1 } ],
} );

expect( state ).toEqual( {
categories: [ { id: 1 } ],
} );
} );

it( 'assigns requested taxonomy to null', () => {
const originalState = deepFreeze( {} );
const state = terms( originalState, {
type: 'SET_REQUESTED',
dataType: 'terms',
subType: 'categories',
} );

expect( state ).toEqual( {
categories: null,
} );
} );

it( 'does not assign requested taxonomy to null if received', () => {
const originalState = deepFreeze( {
categories: [ { id: 1 } ],
} );
const state = terms( originalState, {
type: 'SET_REQUESTED',
dataType: 'terms',
subType: 'categories',
} );

expect( state ).toEqual( {
categories: [ { id: 1 } ],
} );
} );

it( 'does not assign requested taxonomy if not terms data type', () => {
const originalState = deepFreeze( {} );
const state = terms( originalState, {
type: 'SET_REQUESTED',
dataType: 'foo',
subType: 'categories',
} );

expect( state ).toEqual( {} );
} );
} );
32 changes: 32 additions & 0 deletions core-data/test/resolvers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* WordPress dependencies
*/
import apiRequest from '@wordpress/api-request';

/**
* Internal dependencies
*/
import { getCategories } from '../resolvers';
import { setRequested, receiveTerms } from '../actions';

jest.mock( '@wordpress/api-request' );

describe( 'getCategories', () => {
const CATEGORIES = [ { id: 1 } ];

beforeAll( () => {
apiRequest.mockImplementation( ( options ) => {
if ( options.path === '/wp/v2/categories' ) {
return Promise.resolve( CATEGORIES );
}
} );
} );

it( 'yields with requested terms', async () => {
const fulfillment = getCategories();
const requested = ( await fulfillment.next() ).value;
expect( requested.type ).toBe( setRequested().type );
const received = ( await fulfillment.next() ).value;
expect( received ).toEqual( receiveTerms( 'categories', CATEGORIES ) );
} );
} );
Loading