Introduce withCategory HOC for featured category block (https://github.com/woocommerce/woocommerce-blocks/pull/846)

* Introduce withCategory hoc

* Refactor featured category to use new hoc

* Update docblocks
This commit is contained in:
Mike Jolley 2019-08-15 10:36:24 +01:00 committed by GitHub
parent 6ad05724c8
commit 1ed14cdc01
6 changed files with 297 additions and 211 deletions

View File

@ -2,7 +2,6 @@
* External dependencies * External dependencies
*/ */
import { __ } from '@wordpress/i18n'; import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { import {
AlignmentToolbar, AlignmentToolbar,
BlockControls, BlockControls,
@ -27,130 +26,81 @@ import {
withSpokenMessages, withSpokenMessages,
} from '@wordpress/components'; } from '@wordpress/components';
import classnames from 'classnames'; import classnames from 'classnames';
import { Component, Fragment } from '@wordpress/element'; import { Fragment } from '@wordpress/element';
import { compose } from '@wordpress/compose'; import { compose } from '@wordpress/compose';
import { debounce, isObject } from 'lodash';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { IconFolderStar } from '../../components/icons'; import { IconFolderStar } from '../../components/icons';
/** /**
* Internal dependencies * Internal dependencies
*/ */
import { ENDPOINTS } from '../../constants';
import ProductCategoryControl from '../../components/product-category-control'; import ProductCategoryControl from '../../components/product-category-control';
import ApiErrorPlaceholder from '../../components/api-error-placeholder';
import {
dimRatioToClass,
getBackgroundImageStyles,
getCategoryImageId,
getCategoryImageSrc,
} from './utils';
import { withCategory } from '../../hocs';
/** /**
* The min-height for the block content. * The min-height for the block content.
*/ */
const MIN_HEIGHT = wc_product_block_data.min_height; const MIN_HEIGHT = wc_product_block_data.min_height;
/**
* Get the src from a category object, unless null (no image).
*
* @param {object|null} category A product category object from the API.
* @return {string} The src of the category image.
*/
function getCategoryImageSrc( category ) {
if ( isObject( category.image ) ) {
return category.image.src;
}
return '';
}
/**
* Get the attachment ID from a category object, unless null (no image).
*
* @param {object|null} category A product category object from the API.
* @return {number} The id of the category image.
*/
function getCategoryImageID( category ) {
if ( isObject( category.image ) ) {
return category.image.id;
}
return 0;
}
/**
* Generate a style object given either a product category image from the API or URL to an image.
*
* @param {string} url An image URL.
* @return {Object} A style object with a backgroundImage set (if a valid image is provided).
*/
function backgroundImageStyles( url ) {
if ( url ) {
return { backgroundImage: `url(${ url })` };
}
return {};
}
/**
* Convert the selected ratio to the correct background class.
*
* @param {number} ratio Selected opacity from 0 to 100.
* @return {string} The class name, if applicable (not used for ratio 0 or 50).
*/
function dimRatioToClass( ratio ) {
return ratio === 0 || ratio === 50 ?
null :
`has-background-dim-${ 10 * Math.round( ratio / 10 ) }`;
}
/** /**
* Component to handle edit mode of "Featured Category". * Component to handle edit mode of "Featured Category".
*/ */
class FeaturedCategory extends Component { const FeaturedCategory = ( { attributes, isSelected, setAttributes, error, getCategory, isLoading, category, overlayColor, setOverlayColor, debouncedSpeak } ) => {
constructor() { const renderApiError = () => (
super( ...arguments ); <ApiErrorPlaceholder
this.state = { className="wc-block-featured-category-error"
category: false, error={ error }
loaded: false, isLoading={ isLoading }
onRetry={ getCategory }
/>
);
const getBlockControls = () => {
const { contentAlign } = attributes;
const mediaId = attributes.mediaId || getCategoryImageId( category );
return (
<BlockControls>
<AlignmentToolbar
value={ contentAlign }
onChange={ ( nextAlign ) => {
setAttributes( { contentAlign: nextAlign } );
} }
/>
<MediaUploadCheck>
<Toolbar>
<MediaUpload
onSelect={ ( media ) => {
setAttributes( { mediaId: media.id, mediaSrc: media.url } );
} }
allowedTypes={ [ 'image' ] }
value={ mediaId }
render={ ( { open } ) => (
<IconButton
className="components-toolbar__control"
label={ __( 'Edit media' ) }
icon="format-image"
onClick={ open }
disabled={ ! category }
/>
) }
/>
</Toolbar>
</MediaUploadCheck>
</BlockControls>
);
}; };
this.debouncedGetCategory = debounce( this.getCategory.bind( this ), 200 ); const getInspectorControls = () => {
}
componentDidMount() {
this.getCategory();
}
componentWillUnmount() {
this.debouncedGetCategory.cancel();
}
componentDidUpdate( prevProps ) {
if ( prevProps.attributes.categoryId !== this.props.attributes.categoryId ) {
this.debouncedGetCategory();
}
}
getCategory() {
const { categoryId } = this.props.attributes;
if ( ! categoryId ) {
// We've removed the selected product, or no product is selected yet.
this.setState( { category: false, loaded: true } );
return;
}
apiFetch( {
path: `${ ENDPOINTS.products }/categories/${ categoryId }`,
} )
.then( ( category ) => {
this.setState( { category, loaded: true } );
} )
.catch( () => {
this.setState( { category: false, loaded: true } );
} );
}
getInspectorControls() {
const {
attributes,
setAttributes,
overlayColor,
setOverlayColor,
} = this.props;
const url = const url =
attributes.mediaSrc || getCategoryImageSrc( this.state.category ); attributes.mediaSrc || getCategoryImageSrc( category );
const { focalPoint = { x: 0.5, y: 0.5 } } = attributes; const { focalPoint = { x: 0.5, y: 0.5 } } = attributes;
// FocalPointPicker was introduced in Gutenberg 5.0 (WordPress 5.2), // FocalPointPicker was introduced in Gutenberg 5.0 (WordPress 5.2),
// so we need to check if it exists before using it. // so we need to check if it exists before using it.
@ -198,10 +148,9 @@ class FeaturedCategory extends Component {
</PanelColorSettings> </PanelColorSettings>
</InspectorControls> </InspectorControls>
); );
} };
renderEditMode() { const renderEditMode = () => {
const { attributes, debouncedSpeak, setAttributes } = this.props;
const onDone = () => { const onDone = () => {
setAttributes( { editMode: false } ); setAttributes( { editMode: false } );
debouncedSpeak( debouncedSpeak(
@ -237,36 +186,32 @@ class FeaturedCategory extends Component {
</div> </div>
</Placeholder> </Placeholder>
); );
} };
render() { const renderCategory = () => {
const { attributes, isSelected, overlayColor, setAttributes } = this.props;
const { const {
className, className,
contentAlign, contentAlign,
dimRatio, dimRatio,
editMode,
focalPoint, focalPoint,
height, height,
showDesc, showDesc,
} = attributes; } = attributes;
const { loaded, category } = this.state;
const classes = classnames( const classes = classnames(
'wc-block-featured-category', 'wc-block-featured-category',
{ {
'is-selected': isSelected, 'is-selected': isSelected,
'is-loading': ! category && ! loaded, 'is-loading': ! category && isLoading,
'is-not-found': ! category && loaded, 'is-not-found': ! category && ! isLoading,
'has-background-dim': dimRatio !== 0, 'has-background-dim': dimRatio !== 0,
}, },
dimRatioToClass( dimRatio ), dimRatioToClass( dimRatio ),
contentAlign !== 'center' && `has-${ contentAlign }-content`, contentAlign !== 'center' && `has-${ contentAlign }-content`,
className, className,
); );
const mediaId = attributes.mediaId || getCategoryImageID( category ); const mediaSrc = attributes.mediaSrc || getCategoryImageSrc( category );
const mediaSrc = attributes.mediaSrc || getCategoryImageSrc( this.state.category );
const style = !! category ? const style = !! category ?
backgroundImageStyles( mediaSrc ) : getBackgroundImageStyles( mediaSrc ) :
{}; {};
if ( overlayColor.color ) { if ( overlayColor.color ) {
style.backgroundColor = overlayColor.color; style.backgroundColor = overlayColor.color;
@ -281,41 +226,6 @@ class FeaturedCategory extends Component {
}; };
return ( return (
<Fragment>
<BlockControls>
<AlignmentToolbar
value={ contentAlign }
onChange={ ( nextAlign ) => {
setAttributes( { contentAlign: nextAlign } );
} }
/>
<MediaUploadCheck>
<Toolbar>
<MediaUpload
onSelect={ ( media ) => {
setAttributes( { mediaId: media.id, mediaSrc: media.url } );
} }
allowedTypes={ [ 'image' ] }
value={ mediaId }
render={ ( { open } ) => (
<IconButton
className="components-toolbar__control"
label={ __( 'Edit media' ) }
icon="format-image"
onClick={ open }
disabled={ ! this.state.category }
/>
) }
/>
</Toolbar>
</MediaUploadCheck>
</BlockControls>
{ ! attributes.editMode && this.getInspectorControls() }
{ editMode ? (
this.renderEditMode()
) : (
<Fragment>
{ !! category ? (
<ResizableBox <ResizableBox
className={ classes } className={ classes }
size={ { height } } size={ { height } }
@ -359,25 +269,45 @@ class FeaturedCategory extends Component {
</div> </div>
</div> </div>
</ResizableBox> </ResizableBox>
) : ( );
};
const renderNoCategory = () => (
<Placeholder <Placeholder
className="wc-block-featured-category" className="wc-block-featured-category"
icon={ <IconFolderStar /> } icon={ <IconFolderStar /> }
label={ __( 'Featured Category', 'woo-gutenberg-products-block' ) } label={ __( 'Featured Category', 'woo-gutenberg-products-block' ) }
> >
{ ! loaded ? ( { isLoading ? (
<Spinner /> <Spinner />
) : ( ) : (
__( 'No product category is selected.', 'woo-gutenberg-products-block' ) __( 'No product category is selected.', 'woo-gutenberg-products-block' )
) } ) }
</Placeholder> </Placeholder>
) } );
</Fragment>
const { editMode } = attributes;
if ( error ) {
return renderApiError();
}
if ( editMode ) {
return renderEditMode();
}
return (
<Fragment>
{ getBlockControls() }
{ getInspectorControls() }
{ category ? (
renderCategory()
) : (
renderNoCategory()
) } ) }
</Fragment> </Fragment>
); );
} };
}
FeaturedCategory.propTypes = { FeaturedCategory.propTypes = {
/** /**
@ -396,6 +326,15 @@ FeaturedCategory.propTypes = {
* A callback to update attributes. * A callback to update attributes.
*/ */
setAttributes: PropTypes.func.isRequired, setAttributes: PropTypes.func.isRequired,
// from withCategory
error: PropTypes.object,
getCategory: PropTypes.func,
isLoading: PropTypes.bool,
category: PropTypes.shape( {
name: PropTypes.node,
description: PropTypes.node,
permalink: PropTypes.string,
} ),
// from withColors // from withColors
overlayColor: PropTypes.object, overlayColor: PropTypes.object,
setOverlayColor: PropTypes.func.isRequired, setOverlayColor: PropTypes.func.isRequired,
@ -404,6 +343,7 @@ FeaturedCategory.propTypes = {
}; };
export default compose( [ export default compose( [
withCategory,
withColors( { overlayColor: 'background-color' } ), withColors( { overlayColor: 'background-color' } ),
withSpokenMessages, withSpokenMessages,
] )( FeaturedCategory ); ] )( FeaturedCategory );

View File

@ -0,0 +1,57 @@
/**
* External dependencies
*/
import { isObject } from 'lodash';
/**
* Get the src from a category object, unless null (no image).
*
* @param {object|null} category A product category object from the API.
* @return {string} The src of the category image.
*/
function getCategoryImageSrc( category ) {
if ( category && isObject( category.image ) ) {
return category.image.src;
}
return '';
}
/**
* Get the attachment ID from a category object, unless null (no image).
*
* @param {object|null} category A product category object from the API.
* @return {number} The id of the category image.
*/
function getCategoryImageId( category ) {
if ( category && isObject( category.image ) ) {
return category.image.id;
}
return 0;
}
/**
* Generate a style object given either a product category image from the API or URL to an image.
*
* @param {string} url An image URL.
* @return {Object} A style object with a backgroundImage set (if a valid image is provided).
*/
function getBackgroundImageStyles( url ) {
if ( url ) {
return { backgroundImage: `url(${ url })` };
}
return {};
}
/**
* Convert the selected ratio to the correct background class.
*
* @param {number} ratio Selected opacity from 0 to 100.
* @return {string} The class name, if applicable (not used for ratio 0 or 50).
*/
function dimRatioToClass( ratio ) {
return ratio === 0 || ratio === 50 ?
null :
`has-background-dim-${ 10 * Math.round( ratio / 10 ) }`;
}
export { getCategoryImageSrc, getCategoryImageId, getBackgroundImageStyles, dimRatioToClass };

View File

@ -54,7 +54,7 @@ export const getProducts = ( { selected = [], search } ) => {
/** /**
* Get a promise that resolves to a product object from the API. * Get a promise that resolves to a product object from the API.
* *
* @param {Object} productId Id of the product to retrieve. * @param {number} productId Id of the product to retrieve.
*/ */
export const getProduct = ( productId ) => { export const getProduct = ( productId ) => {
return apiFetch( { return apiFetch( {
@ -96,3 +96,14 @@ export const getProductTags = ( { selected = [], search } ) => {
return uniqBy( flatten( data ), 'id' ); return uniqBy( flatten( data ), 'id' );
} ); } );
}; };
/**
* Get a promise that resolves to a category object from the API.
*
* @param {number} categoryId Id of the product to retrieve.
*/
export const getCategory = ( categoryId ) => {
return apiFetch( {
path: `${ ENDPOINTS.categories }/${ categoryId }`,
} );
};

View File

@ -2,4 +2,5 @@ const NAMESPACE = '/wc/blocks';
export const ENDPOINTS = { export const ENDPOINTS = {
root: NAMESPACE, root: NAMESPACE,
products: `${ NAMESPACE }/products`, products: `${ NAMESPACE }/products`,
categories: `${ NAMESPACE }/products/categories`,
}; };

View File

@ -1,3 +1,4 @@
export { default as withComponentId } from './with-component-id'; export { default as withComponentId } from './with-component-id';
export { default as withProduct } from './with-product'; export { default as withProduct } from './with-product';
export { default as withCategory } from './with-category';
export { default as withSearchedProducts } from './with-searched-products'; export { default as withSearchedProducts } from './with-searched-products';

View File

@ -0,0 +1,76 @@
/**
* External dependencies
*/
import { Component } from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { getCategory } from '../components/utils';
const withCategory = createHigherOrderComponent(
( OriginalComponent ) => {
return class WrappedComponent extends Component {
constructor() {
super( ...arguments );
this.state = {
error: null,
loading: false,
category: null,
};
this.loadCategory = this.loadCategory.bind( this );
}
componentDidMount() {
this.loadCategory();
}
componentDidUpdate( prevProps ) {
if ( prevProps.attributes.categoryId !== this.props.attributes.categoryId ) {
this.loadCategory();
}
}
loadCategory() {
const { categoryId } = this.props.attributes;
if ( ! categoryId ) {
this.setState( { category: null, loading: false, error: null } );
return;
}
this.setState( { loading: true } );
getCategory( categoryId ).then( ( category ) => {
this.setState( { category, loading: false, error: null } );
} ).catch( ( apiError ) => {
const error = typeof apiError === 'object' && apiError.hasOwnProperty( 'message' ) ? {
apiMessage: apiError.message,
} : {
// If we can't get any message from the API, set it to null and
// let <ApiErrorPlaceholder /> handle the message to display.
apiMessage: null,
};
this.setState( { category: null, loading: false, error } );
} );
}
render() {
const { error, loading, category } = this.state;
return <OriginalComponent
{ ...this.props }
error={ error }
getCategory={ this.loadCategory }
isLoading={ loading }
category={ category }
/>;
}
};
},
'withCategory'
);
export default withCategory;