initial commit

This commit is contained in:
2021-12-10 12:03:04 +00:00
commit c46c7ddbf0
3643 changed files with 582794 additions and 0 deletions

View File

@ -0,0 +1,480 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
AlignmentToolbar,
BlockControls,
InnerBlocks,
InspectorControls,
MediaReplaceFlow,
PanelColorSettings,
withColors,
RichText,
} from '@wordpress/block-editor';
import {
Button,
FocalPointPicker,
PanelBody,
Placeholder,
RangeControl,
ResizableBox,
Spinner,
ToggleControl,
ToolbarGroup,
withSpokenMessages,
} from '@wordpress/components';
import classnames from 'classnames';
import { Component } from '@wordpress/element';
import { withSelect } from '@wordpress/data';
import { compose, createHigherOrderComponent } from '@wordpress/compose';
import PropTypes from 'prop-types';
import { getSetting } from '@woocommerce/settings';
import { Icon, folderStarred } from '@woocommerce/icons';
import ProductCategoryControl from '@woocommerce/editor-components/product-category-control';
import ErrorPlaceholder from '@woocommerce/editor-components/error-placeholder';
/**
* Internal dependencies
*/
import {
dimRatioToClass,
getBackgroundImageStyles,
getCategoryImageId,
getCategoryImageSrc,
} from './utils';
import { withCategory } from '../../hocs';
/**
* Component to handle edit mode of "Featured Category".
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.attributes Incoming block attributes.
* @param {boolean} props.isSelected Whether block is selected or not.
* @param {function(any):any} props.setAttributes Function for setting new attributes.
* @param {string} props.error Error message
* @param {function(any):any} props.getCategory Function for getting category details.
* @param {boolean} props.isLoading Whether loading or not.
* @param {Object} props.category The product category object.
* @param {Object} props.overlayColor Overlay color object for content.
* @param {function(any):any} props.setOverlayColor Setter for overlay color.
* @param {function(any):any} props.debouncedSpeak Function for delayed speak.
* @param {function():void} props.triggerUrlUpdate Function to update Shop now button Url.
*/
const FeaturedCategory = ( {
attributes,
isSelected,
setAttributes,
error,
getCategory,
isLoading,
category,
overlayColor,
setOverlayColor,
debouncedSpeak,
triggerUrlUpdate = () => void null,
} ) => {
const renderApiError = () => (
<ErrorPlaceholder
className="wc-block-featured-category-error"
error={ error }
isLoading={ isLoading }
onRetry={ getCategory }
/>
);
const getBlockControls = () => {
const { contentAlign, mediaSrc } = attributes;
const mediaId = attributes.mediaId || getCategoryImageId( category );
return (
<BlockControls>
<AlignmentToolbar
value={ contentAlign }
onChange={ ( nextAlign ) => {
setAttributes( { contentAlign: nextAlign } );
} }
/>
<MediaReplaceFlow
mediaId={ mediaId }
mediaURL={ mediaSrc }
accept="image/*"
onSelect={ ( media ) => {
setAttributes( {
mediaId: media.id,
mediaSrc: media.url,
} );
} }
allowedTypes={ [ 'image' ] }
/>
<ToolbarGroup
controls={ [
{
icon: 'edit',
title: __( 'Edit' ),
onClick: () =>
setAttributes( { editMode: ! editMode } ),
isActive: editMode,
},
] }
/>
</BlockControls>
);
};
const getInspectorControls = () => {
const url = 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.
const focalPointPickerExists = typeof FocalPointPicker === 'function';
return (
<InspectorControls key="inspector">
<PanelBody
title={ __( 'Content', 'woocommerce' ) }
>
<ToggleControl
label={ __(
'Show description',
'woocommerce'
) }
checked={ attributes.showDesc }
onChange={ () =>
setAttributes( { showDesc: ! attributes.showDesc } )
}
/>
</PanelBody>
<PanelColorSettings
title={ __( 'Overlay', 'woocommerce' ) }
colorSettings={ [
{
value: overlayColor.color,
onChange: setOverlayColor,
label: __(
'Overlay Color',
'woocommerce'
),
},
] }
>
{ !! url && (
<>
<RangeControl
label={ __(
'Background Opacity',
'woocommerce'
) }
value={ attributes.dimRatio }
onChange={ ( ratio ) =>
setAttributes( { dimRatio: ratio } )
}
min={ 0 }
max={ 100 }
step={ 10 }
/>
{ focalPointPickerExists && (
<FocalPointPicker
label={ __( 'Focal Point Picker' ) }
url={ url }
value={ focalPoint }
onChange={ ( value ) =>
setAttributes( { focalPoint: value } )
}
/>
) }
</>
) }
</PanelColorSettings>
</InspectorControls>
);
};
const renderEditMode = () => {
const onDone = () => {
setAttributes( { editMode: false } );
debouncedSpeak(
__(
'Showing Featured Product block preview.',
'woocommerce'
)
);
};
return (
<Placeholder
icon={ <Icon srcElement={ folderStarred } /> }
label={ __(
'Featured Category',
'woocommerce'
) }
className="wc-block-featured-category"
>
{ __(
'Visually highlight a product category and encourage prompt action.',
'woocommerce'
) }
<div className="wc-block-featured-category__selection">
<ProductCategoryControl
selected={ [ attributes.categoryId ] }
onChange={ ( value = [] ) => {
const id = value[ 0 ] ? value[ 0 ].id : 0;
setAttributes( {
categoryId: id,
mediaId: 0,
mediaSrc: '',
} );
triggerUrlUpdate();
} }
isSingle
/>
<Button isPrimary onClick={ onDone }>
{ __( 'Done', 'woocommerce' ) }
</Button>
</div>
</Placeholder>
);
};
const renderButton = () => {
const buttonClasses = classnames(
'wp-block-button__link',
'is-style-fill'
);
const buttonStyle = {
backgroundColor: 'vivid-green-cyan',
borderRadius: '5px',
};
const wrapperStyle = {
width: '100%',
};
return attributes.categoryId === 'preview' ? (
<div className="wp-block-button aligncenter" style={ wrapperStyle }>
<RichText.Content
tagName="a"
className={ buttonClasses }
href={ category.permalink }
title={ attributes.linkText }
style={ buttonStyle }
value={ attributes.linkText }
target={ category.permalink }
/>
</div>
) : (
<InnerBlocks
template={ [
[
'core/button',
{
text: __(
'Shop now',
'woocommerce'
),
url: category.permalink,
align: 'center',
},
],
] }
templateLock="all"
/>
);
};
const renderCategory = () => {
const {
className,
contentAlign,
dimRatio,
focalPoint,
height,
showDesc,
} = attributes;
const classes = classnames(
'wc-block-featured-category',
{
'is-selected': isSelected && attributes.productId !== 'preview',
'is-loading': ! category && isLoading,
'is-not-found': ! category && ! isLoading,
'has-background-dim': dimRatio !== 0,
},
dimRatioToClass( dimRatio ),
contentAlign !== 'center' && `has-${ contentAlign }-content`,
className
);
const mediaSrc = attributes.mediaSrc || getCategoryImageSrc( category );
const style = !! category ? getBackgroundImageStyles( mediaSrc ) : {};
if ( overlayColor.color ) {
style.backgroundColor = overlayColor.color;
}
if ( focalPoint ) {
const bgPosX = focalPoint.x * 100;
const bgPosY = focalPoint.y * 100;
style.backgroundPosition = `${ bgPosX }% ${ bgPosY }%`;
}
const onResizeStop = ( event, direction, elt ) => {
setAttributes( { height: parseInt( elt.style.height, 10 ) } );
};
return (
<ResizableBox
className={ classes }
size={ { height } }
minHeight={ getSetting( 'min_height', 500 ) }
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">
{ renderButton() }
</div>
</div>
</ResizableBox>
);
};
const renderNoCategory = () => (
<Placeholder
className="wc-block-featured-category"
icon={ <Icon srcElement={ folderStarred } /> }
label={ __( 'Featured Category', 'woocommerce' ) }
>
{ isLoading ? (
<Spinner />
) : (
__(
'No product category is selected.',
'woocommerce'
)
) }
</Placeholder>
);
const { editMode } = attributes;
if ( error ) {
return renderApiError();
}
if ( editMode ) {
return renderEditMode();
}
return (
<>
{ getBlockControls() }
{ getInspectorControls() }
{ category ? renderCategory() : renderNoCategory() }
</>
);
};
FeaturedCategory.propTypes = {
/**
* The attributes for this block.
*/
attributes: PropTypes.object.isRequired,
/**
* Whether this block is currently active.
*/
isSelected: PropTypes.bool.isRequired,
/**
* The register block name.
*/
name: PropTypes.string.isRequired,
/**
* 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,
// from withSpokenMessages
debouncedSpeak: PropTypes.func.isRequired,
triggerUrlUpdate: PropTypes.func,
};
export default compose( [
withCategory,
withColors( { overlayColor: 'background-color' } ),
withSpokenMessages,
withSelect( ( select, { clientId }, { dispatch } ) => {
const Block = select( 'core/block-editor' ).getBlock( clientId );
const buttonBlockId = Block?.innerBlocks[ 0 ]?.clientId || '';
const currentButtonAttributes =
Block?.innerBlocks[ 0 ]?.attributes || {};
const updateBlockAttributes = ( attributes ) => {
if ( buttonBlockId ) {
dispatch( 'core/block-editor' ).updateBlockAttributes(
buttonBlockId,
attributes
);
}
};
return { updateBlockAttributes, currentButtonAttributes };
} ),
createHigherOrderComponent( ( ProductComponent ) => {
class WrappedComponent extends Component {
state = {
doUrlUpdate: false,
};
componentDidUpdate() {
const {
attributes,
updateBlockAttributes,
currentButtonAttributes,
category,
} = this.props;
if (
this.state.doUrlUpdate &&
! attributes.editMode &&
category?.permalink &&
currentButtonAttributes?.url &&
category.permalink !== currentButtonAttributes.url
) {
updateBlockAttributes( {
...currentButtonAttributes,
url: category.permalink,
} );
this.setState( { doUrlUpdate: false } );
}
}
triggerUrlUpdate = () => {
this.setState( { doUrlUpdate: true } );
};
render() {
return (
<ProductComponent
triggerUrlUpdate={ this.triggerUrlUpdate }
{ ...this.props }
/>
);
}
}
return WrappedComponent;
}, 'withUpdateButtonAttributes' ),
] )( FeaturedCategory );

View File

@ -0,0 +1,13 @@
.wc-block-featured-category {
.components-resizable-box__handle {
z-index: 10;
}
.components-placeholder__label svg {
fill: currentColor;
margin-right: 1ch;
}
}
.wc-block-featured-category__selection {
width: 100%;
}

View File

@ -0,0 +1,18 @@
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
import { previewCategories } from '@woocommerce/resource-previews';
export const example = {
attributes: {
contentAlign: 'center',
dimRatio: 50,
editMode: false,
height: getSetting( 'default_height', 500 ),
mediaSrc: '',
showDesc: true,
categoryId: 'preview',
previewCategory: previewCategories[ 0 ],
},
};

View File

@ -0,0 +1,155 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { InnerBlocks } from '@wordpress/block-editor';
import { registerBlockType } from '@wordpress/blocks';
import { getSetting } from '@woocommerce/settings';
import { Icon, folderStarred } from '@woocommerce/icons';
/**
* Internal dependencies
*/
import './style.scss';
import './editor.scss';
import Block from './block';
import { example } from './example';
/**
* Register and run the "Featured Category" block.
*/
registerBlockType( 'woocommerce/featured-category', {
title: __( 'Featured Category', 'woocommerce' ),
icon: {
src: <Icon srcElement={ folderStarred } />,
foreground: '#96588a',
},
category: 'woocommerce',
keywords: [ __( 'WooCommerce', 'woocommerce' ) ],
description: __(
'Visually highlight a product category and encourage prompt action.',
'woocommerce'
),
supports: {
align: [ 'wide', 'full' ],
html: false,
},
example,
attributes: {
/**
* Alignment of content inside block.
*/
contentAlign: {
type: 'string',
default: 'center',
},
/**
* Percentage opacity of overlay.
*/
dimRatio: {
type: 'number',
default: 50,
},
/**
* Toggle for edit mode in the block preview.
*/
editMode: {
type: 'boolean',
default: true,
},
/**
* Focus point for the background image
*/
focalPoint: {
type: 'object',
},
/**
* A fixed height for the block.
*/
height: {
type: 'number',
default: getSetting( 'default_height', 500 ),
},
/**
* ID for a custom image, overriding the product's featured image.
*/
mediaId: {
type: 'number',
default: 0,
},
/**
* URL for a custom image, overriding the product's featured image.
*/
mediaSrc: {
type: 'string',
default: '',
},
/**
* The overlay color, from the color list.
*/
overlayColor: {
type: 'string',
},
/**
* The overlay color, if a custom color value.
*/
customOverlayColor: {
type: 'string',
},
/**
* Text for the category link.
*/
linkText: {
type: 'string',
default: __( 'Shop now', 'woocommerce' ),
},
/**
* The category ID to display.
*/
categoryId: {
type: 'number',
},
/**
* Show the category description.
*/
showDesc: {
type: 'boolean',
default: true,
},
/**
* Category preview.
*/
previewCategory: {
type: 'object',
default: null,
},
},
/**
* Renders and manages the block.
*
* @param {Object} props Props to pass to block.
*/
edit( props ) {
return <Block { ...props } />;
},
/**
* Block content is rendered in PHP, not via save function.
*/
save() {
return <InnerBlocks.Content />;
},
} );

View File

@ -0,0 +1,134 @@
.wc-block-featured-category {
position: relative;
background-color: $gray-900;
background-size: cover;
background-position: center center;
width: 100%;
margin: 0 0 1.5em 0;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
align-content: center;
.wc-block-featured-category__wrapper {
overflow: hidden;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
align-content: center;
}
&.has-left-content {
justify-content: flex-start;
.wc-block-featured-category__title,
.wc-block-featured-category__description,
.wc-block-featured-category__price {
margin-left: 0;
text-align: left;
}
}
&.has-right-content {
justify-content: flex-end;
.wc-block-featured-category__title,
.wc-block-featured-category__description,
.wc-block-featured-category__price {
margin-right: 0;
text-align: right;
}
}
.wc-block-featured-category__title,
.wc-block-featured-category__description,
.wc-block-featured-category__price {
color: $white;
line-height: 1.25;
margin-bottom: 0;
text-align: center;
a,
a:hover,
a:focus,
a:active {
color: $white;
}
}
.wc-block-featured-category__title,
.wc-block-featured-category__description,
.wc-block-featured-category__price,
.wc-block-featured-category__link {
width: 100%;
padding: 0 48px 16px 48px;
z-index: 1;
}
.wc-block-featured-category__title {
margin-top: 0;
&::before {
display: none;
}
}
.wc-block-featured-category__description {
p {
margin: 0;
}
}
.wp-block-button.aligncenter {
text-align: center;
}
&.has-background-dim::before {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: inherit;
opacity: 0.5;
z-index: 1;
}
@for $i from 1 through 10 {
&.has-background-dim.has-background-dim-#{ $i * 10 }::before {
opacity: $i * 0.1;
}
}
// Apply max-width to floated items that have no intrinsic width
&.alignleft,
&.alignright {
max-width: $content-width * 0.5;
width: 100%;
}
// Using flexbox without an assigned height property breaks vertical center alignment in IE11.
// Appending an empty ::after element tricks IE11 into giving the cover image an implicit height, which sidesteps this issue.
&::after {
display: block;
content: "";
font-size: 0;
min-height: inherit;
// IE doesn't support flex so omit that.
@supports (position: sticky) {
content: none;
}
}
// Aligned cover blocks should not use our global alignment rules
&.aligncenter,
&.alignleft,
&.alignright {
display: flex;
}
}

View File

@ -0,0 +1,62 @@
/**
* 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,
};