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
*/
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
AlignmentToolbar,
BlockControls,
@ -27,130 +26,81 @@ import {
withSpokenMessages,
} from '@wordpress/components';
import classnames from 'classnames';
import { Component, Fragment } from '@wordpress/element';
import { Fragment } from '@wordpress/element';
import { compose } from '@wordpress/compose';
import { debounce, isObject } from 'lodash';
import PropTypes from 'prop-types';
import { IconFolderStar } from '../../components/icons';
/**
* Internal dependencies
*/
import { ENDPOINTS } from '../../constants';
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.
*/
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".
*/
class FeaturedCategory extends Component {
constructor() {
super( ...arguments );
this.state = {
category: false,
loaded: false,
};
const FeaturedCategory = ( { attributes, isSelected, setAttributes, error, getCategory, isLoading, category, overlayColor, setOverlayColor, debouncedSpeak } ) => {
const renderApiError = () => (
<ApiErrorPlaceholder
className="wc-block-featured-category-error"
error={ error }
isLoading={ isLoading }
onRetry={ getCategory }
/>
);
this.debouncedGetCategory = debounce( this.getCategory.bind( this ), 200 );
}
const getBlockControls = () => {
const { contentAlign } = attributes;
const mediaId = attributes.mediaId || getCategoryImageId( category );
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;
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>
);
};
const getInspectorControls = () => {
const url =
attributes.mediaSrc || getCategoryImageSrc( this.state.category );
attributes.mediaSrc || getCategoryImageSrc( category );
const { focalPoint = { x: 0.5, y: 0.5 } } = attributes;
// FocalPointPicker was introduced in Gutenberg 5.0 (WordPress 5.2),
// so we need to check if it exists before using it.
@ -198,10 +148,9 @@ class FeaturedCategory extends Component {
</PanelColorSettings>
</InspectorControls>
);
}
};
renderEditMode() {
const { attributes, debouncedSpeak, setAttributes } = this.props;
const renderEditMode = () => {
const onDone = () => {
setAttributes( { editMode: false } );
debouncedSpeak(
@ -237,36 +186,32 @@ class FeaturedCategory extends Component {
</div>
</Placeholder>
);
}
};
render() {
const { attributes, isSelected, overlayColor, setAttributes } = this.props;
const renderCategory = () => {
const {
className,
contentAlign,
dimRatio,
editMode,
focalPoint,
height,
showDesc,
} = attributes;
const { loaded, category } = this.state;
const classes = classnames(
'wc-block-featured-category',
{
'is-selected': isSelected,
'is-loading': ! category && ! loaded,
'is-not-found': ! category && loaded,
'is-loading': ! category && isLoading,
'is-not-found': ! category && ! isLoading,
'has-background-dim': dimRatio !== 0,
},
dimRatioToClass( dimRatio ),
contentAlign !== 'center' && `has-${ contentAlign }-content`,
className,
);
const mediaId = attributes.mediaId || getCategoryImageID( category );
const mediaSrc = attributes.mediaSrc || getCategoryImageSrc( this.state.category );
const mediaSrc = attributes.mediaSrc || getCategoryImageSrc( category );
const style = !! category ?
backgroundImageStyles( mediaSrc ) :
getBackgroundImageStyles( mediaSrc ) :
{};
if ( overlayColor.color ) {
style.backgroundColor = overlayColor.color;
@ -281,103 +226,88 @@ class FeaturedCategory extends Component {
};
return (
<Fragment>
<BlockControls>
<AlignmentToolbar
value={ contentAlign }
onChange={ ( nextAlign ) => {
setAttributes( { contentAlign: nextAlign } );
<ResizableBox
className={ classes }
size={ { height } }
minHeight={ MIN_HEIGHT }
enable={ { bottom: true } }
onResizeStop={ onResizeStop }
style={ style }
>
<div className="wc-block-featured-category__wrapper">
<h2
className="wc-block-featured-category__title"
dangerouslySetInnerHTML={ {
__html: category.name,
} }
/>
<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
className={ classes }
size={ { height } }
minHeight={ MIN_HEIGHT }
enable={ { bottom: true } }
onResizeStop={ onResizeStop }
style={ style }
>
<div className="wc-block-featured-category__wrapper">
<h2
className="wc-block-featured-category__title"
dangerouslySetInnerHTML={ {
__html: category.name,
} }
/>
{ showDesc && (
<div
className="wc-block-featured-category__description"
dangerouslySetInnerHTML={ {
__html: category.description,
} }
/>
) }
<div className="wc-block-featured-category__link">
<InnerBlocks
template={ [
[
'core/button',
{
text: __(
'Shop now',
'woo-gutenberg-products-block'
),
url: category.permalink,
align: 'center',
},
],
] }
templateLock="all"
/>
</div>
</div>
</ResizableBox>
) : (
<Placeholder
className="wc-block-featured-category"
icon={ <IconFolderStar /> }
label={ __( 'Featured Category', 'woo-gutenberg-products-block' ) }
>
{ ! loaded ? (
<Spinner />
) : (
__( 'No product category is selected.', 'woo-gutenberg-products-block' )
) }
</Placeholder>
) }
</Fragment>
) }
</Fragment>
{ showDesc && (
<div
className="wc-block-featured-category__description"
dangerouslySetInnerHTML={ {
__html: category.description,
} }
/>
) }
<div className="wc-block-featured-category__link">
<InnerBlocks
template={ [
[
'core/button',
{
text: __(
'Shop now',
'woo-gutenberg-products-block'
),
url: category.permalink,
align: 'center',
},
],
] }
templateLock="all"
/>
</div>
</div>
</ResizableBox>
);
};
const renderNoCategory = () => (
<Placeholder
className="wc-block-featured-category"
icon={ <IconFolderStar /> }
label={ __( 'Featured Category', 'woo-gutenberg-products-block' ) }
>
{ isLoading ? (
<Spinner />
) : (
__( 'No product category is selected.', 'woo-gutenberg-products-block' )
) }
</Placeholder>
);
const { editMode } = attributes;
if ( error ) {
return renderApiError();
}
}
if ( editMode ) {
return renderEditMode();
}
return (
<Fragment>
{ getBlockControls() }
{ getInspectorControls() }
{ category ? (
renderCategory()
) : (
renderNoCategory()
) }
</Fragment>
);
};
FeaturedCategory.propTypes = {
/**
@ -396,6 +326,15 @@ FeaturedCategory.propTypes = {
* A callback to update attributes.
*/
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
overlayColor: PropTypes.object,
setOverlayColor: PropTypes.func.isRequired,
@ -404,6 +343,7 @@ FeaturedCategory.propTypes = {
};
export default compose( [
withCategory,
withColors( { overlayColor: 'background-color' } ),
withSpokenMessages,
] )( 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.
*
* @param {Object} productId Id of the product to retrieve.
* @param {number} productId Id of the product to retrieve.
*/
export const getProduct = ( productId ) => {
return apiFetch( {
@ -96,3 +96,14 @@ export const getProductTags = ( { selected = [], search } ) => {
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 = {
root: NAMESPACE,
products: `${ NAMESPACE }/products`,
categories: `${ NAMESPACE }/products/categories`,
};

View File

@ -1,3 +1,4 @@
export { default as withComponentId } from './with-component-id';
export { default as withProduct } from './with-product';
export { default as withCategory } from './with-category';
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;