first commit
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockComponent } from '@woocommerce/blocks-registry';
|
||||
import { lazy } from '@wordpress/element';
|
||||
import { WC_BLOCKS_BUILD_URL } from '@woocommerce/block-settings';
|
||||
|
||||
// Modify webpack publicPath at runtime based on location of WordPress Plugin.
|
||||
// eslint-disable-next-line no-undef,camelcase
|
||||
__webpack_public_path__ = WC_BLOCKS_BUILD_URL;
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-price',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-price" */ './product-elements/price/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-image',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-image" */ './product-elements/image/frontend'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-title',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-title" */ './product-elements/title/frontend'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-rating',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-rating" */ './product-elements/rating/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-button',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-button" */ './product-elements/button/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-summary',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-summary" */ './product-elements/summary/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-sale-badge',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-sale-badge" */ './product-elements/sale-badge/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-sku',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-sku" */ './product-elements/sku/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-stock-indicator',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-stock-indicator" */ './product-elements/stock-indicator/block'
|
||||
)
|
||||
),
|
||||
} );
|
||||
|
||||
registerBlockComponent( {
|
||||
blockName: 'woocommerce/product-add-to-cart',
|
||||
component: lazy( () =>
|
||||
import(
|
||||
/* webpackChunkName: "product-add-to-cart" */ './product-elements/add-to-cart/frontend'
|
||||
)
|
||||
),
|
||||
} );
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './product-elements/title';
|
||||
import './product-elements/price';
|
||||
import './product-elements/image';
|
||||
import './product-elements/rating';
|
||||
import './product-elements/button';
|
||||
import './product-elements/summary';
|
||||
import './product-elements/sale-badge';
|
||||
import './product-elements/sku';
|
||||
import './product-elements/stock-indicator';
|
||||
import './product-elements/add-to-cart';
|
||||
import './product-elements/add-to-cart-form';
|
||||
import './product-elements/product-image-gallery';
|
||||
import './product-elements/product-details';
|
||||
import './product-elements/product-reviews';
|
||||
import './product-elements/related-products';
|
||||
import './product-elements/product-meta';
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "woocommerce/add-to-cart-form",
|
||||
"version": "1.0.0",
|
||||
"title": "Add to Cart form",
|
||||
"description": "Display a button so the customer can add a product to their cart. Options will also be displayed depending on product type. e.g. quantity, variation.",
|
||||
"category": "woocommerce",
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"usesContext": ["postId"],
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { Button, Disabled, Tooltip } from '@wordpress/components';
|
||||
import { Skeleton } from '@woocommerce/base-components/skeleton';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './editor.scss';
|
||||
export interface Attributes {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const Edit = () => {
|
||||
const blockProps = useBlockProps( {
|
||||
className: 'wc-block-add-to-cart-form',
|
||||
} );
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<Tooltip
|
||||
text="Customer will see product add-to-cart options in this space, dependend on the product type. "
|
||||
position="bottom right"
|
||||
>
|
||||
<div className="wc-block-editor-container">
|
||||
<Skeleton numberOfLines={ 3 } />
|
||||
<Disabled>
|
||||
<input
|
||||
type={ 'number' }
|
||||
value={ '1' }
|
||||
className={
|
||||
'wc-block-editor-add-to-cart-form__quantity'
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant={ 'primary' }
|
||||
className={
|
||||
'wc-block-editor-add-to-cart-form__button'
|
||||
}
|
||||
>
|
||||
{ __(
|
||||
'Add to cart',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</Button>
|
||||
</Disabled>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,32 @@
|
||||
.wc-block-editor-add-to-cart-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
row-gap: $default-block-margin;
|
||||
}
|
||||
|
||||
input.wc-block-editor-add-to-cart-form__quantity[type="number"] {
|
||||
max-width: 50px;
|
||||
min-height: 23px;
|
||||
float: left;
|
||||
padding: 6px 6px 6px 12px;
|
||||
margin-right: 10px;
|
||||
font-size: 13px;
|
||||
height: inherit;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
button.components-button.wc-block-add-to-cart-form__button {
|
||||
float: left;
|
||||
padding: 20px 30px;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.wc-block-editor-container {
|
||||
cursor: help;
|
||||
gap: 10px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
import { Icon, button } from '@wordpress/icons';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import metadata from './block.json';
|
||||
import edit from './edit';
|
||||
|
||||
const blockSettings = {
|
||||
edit,
|
||||
icon: {
|
||||
src: (
|
||||
<Icon
|
||||
icon={ button }
|
||||
className="wc-block-editor-components-block-icon"
|
||||
/>
|
||||
),
|
||||
},
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
save() {
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
blockMetadata: metadata,
|
||||
blockSettings,
|
||||
} );
|
||||
@@ -0,0 +1,7 @@
|
||||
.wp-block-add-to-cart-form {
|
||||
.woocommerce-Price-amount.amount,
|
||||
.woocommerce-grouped-product-list-item__price del {
|
||||
font-size: var(--wp--preset--font-size--large);
|
||||
}
|
||||
width: unset;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export const blockAttributes = {
|
||||
showFormElements: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import PropTypes from 'prop-types';
|
||||
import classnames from 'classnames';
|
||||
import {
|
||||
AddToCartFormContextProvider,
|
||||
useAddToCartFormContext,
|
||||
} from '@woocommerce/base-context';
|
||||
import { useProductDataContext } from '@woocommerce/shared-context';
|
||||
import { isEmpty } from 'lodash';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import { AddToCartButton } from './shared';
|
||||
import {
|
||||
SimpleProductForm,
|
||||
VariableProductForm,
|
||||
ExternalProductForm,
|
||||
GroupedProductForm,
|
||||
} from './product-types';
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
* CSS Class name for the component.
|
||||
*/
|
||||
className?: string;
|
||||
/**
|
||||
* Whether or not to show form elements.
|
||||
*/
|
||||
showFormElements?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the add to cart form using useAddToCartFormContext.
|
||||
*/
|
||||
const AddToCartForm = () => {
|
||||
const { showFormElements, productType } = useAddToCartFormContext();
|
||||
|
||||
if ( showFormElements ) {
|
||||
if ( productType === 'variable' ) {
|
||||
return <VariableProductForm />;
|
||||
}
|
||||
if ( productType === 'grouped' ) {
|
||||
return <GroupedProductForm />;
|
||||
}
|
||||
if ( productType === 'external' ) {
|
||||
return <ExternalProductForm />;
|
||||
}
|
||||
if ( productType === 'simple' || productType === 'variation' ) {
|
||||
return <SimpleProductForm />;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return <AddToCartButton />;
|
||||
};
|
||||
|
||||
/**
|
||||
* Product Add to Form Block Component.
|
||||
*/
|
||||
const Block = ( { className, showFormElements }: Props ) => {
|
||||
const { product } = useProductDataContext();
|
||||
const componentClass = classnames(
|
||||
className,
|
||||
'wc-block-components-product-add-to-cart',
|
||||
{
|
||||
'wc-block-components-product-add-to-cart--placeholder':
|
||||
isEmpty( product ),
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<AddToCartFormContextProvider
|
||||
product={ product }
|
||||
showFormElements={ showFormElements }
|
||||
>
|
||||
<div className={ componentClass }>
|
||||
<AddToCartForm />
|
||||
</div>
|
||||
</AddToCartFormContextProvider>
|
||||
);
|
||||
};
|
||||
|
||||
Block.propTypes = {
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default withProductDataContext( Block );
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { cart } from '@woocommerce/icons';
|
||||
import { Icon } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE = __( 'Add to Cart', 'woo-gutenberg-products-block' );
|
||||
export const BLOCK_ICON = (
|
||||
<Icon icon={ cart } className="wc-block-editor-components-block-icon" />
|
||||
);
|
||||
export const BLOCK_DESCRIPTION = __(
|
||||
'Displays an add to cart button. Optionally displays other add to cart form elements.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import EditProductLink from '@woocommerce/editor-components/edit-product-link';
|
||||
import { useProductDataContext } from '@woocommerce/shared-context';
|
||||
import classnames from 'classnames';
|
||||
import {
|
||||
Disabled,
|
||||
PanelBody,
|
||||
ToggleControl,
|
||||
Notice,
|
||||
} from '@wordpress/components';
|
||||
import { InspectorControls } from '@wordpress/block-editor';
|
||||
import { productSupportsAddToCartForm } from '@woocommerce/base-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import Block from './block';
|
||||
import withProductSelector from '../shared/with-product-selector';
|
||||
import { BLOCK_TITLE, BLOCK_ICON } from './constants';
|
||||
|
||||
interface EditProps {
|
||||
attributes: {
|
||||
className: string;
|
||||
showFormElements: boolean;
|
||||
};
|
||||
setAttributes: ( attributes: { showFormElements: boolean } ) => void;
|
||||
}
|
||||
|
||||
const Edit = ( { attributes, setAttributes }: EditProps ) => {
|
||||
const { product } = useProductDataContext();
|
||||
const { className, showFormElements } = attributes;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
className,
|
||||
'wc-block-components-product-add-to-cart'
|
||||
) }
|
||||
>
|
||||
<EditProductLink productId={ product.id } />
|
||||
<InspectorControls>
|
||||
<PanelBody
|
||||
title={ __( 'Layout', 'woo-gutenberg-products-block' ) }
|
||||
>
|
||||
{ productSupportsAddToCartForm( product ) ? (
|
||||
<ToggleControl
|
||||
label={ __(
|
||||
'Display form elements',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
help={ __(
|
||||
'Depending on product type, allow customers to select a quantity, variations etc.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
checked={ showFormElements }
|
||||
onChange={ () =>
|
||||
setAttributes( {
|
||||
showFormElements: ! showFormElements,
|
||||
} )
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Notice
|
||||
className="wc-block-components-product-add-to-cart-notice"
|
||||
isDismissible={ false }
|
||||
status="info"
|
||||
>
|
||||
{ __(
|
||||
'This product does not support the block based add to cart form. A link to the product page will be shown instead.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</Notice>
|
||||
) }
|
||||
</PanelBody>
|
||||
</InspectorControls>
|
||||
<Disabled>
|
||||
<Block { ...attributes } />
|
||||
</Disabled>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductSelector( {
|
||||
icon: BLOCK_ICON,
|
||||
label: BLOCK_TITLE,
|
||||
description: __(
|
||||
'Choose a product to display its add to cart form.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
} )( Edit );
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { withFilteredAttributes } from '@woocommerce/shared-hocs';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import attributes from './attributes';
|
||||
|
||||
export default withFilteredAttributes( attributes )( Block );
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerExperimentalBlockType } from '@woocommerce/block-settings';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import sharedConfig from '../shared/config';
|
||||
import edit from './edit';
|
||||
import attributes from './attributes';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
|
||||
const blockConfig = {
|
||||
title,
|
||||
description,
|
||||
icon: { src: icon },
|
||||
edit,
|
||||
attributes,
|
||||
};
|
||||
|
||||
registerExperimentalBlockType( 'woocommerce/product-add-to-cart', {
|
||||
...sharedConfig,
|
||||
...blockConfig,
|
||||
} );
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import AddToCartButton from '../shared/add-to-cart-button';
|
||||
|
||||
/**
|
||||
* External Product Add To Cart Form
|
||||
*/
|
||||
const External = () => {
|
||||
return <AddToCartButton />;
|
||||
};
|
||||
|
||||
export default External;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Grouped Product Add To Cart Form
|
||||
*/
|
||||
const Grouped = () => (
|
||||
<p>This is a placeholder for the grouped products form element.</p>
|
||||
);
|
||||
|
||||
export default Grouped;
|
||||
@@ -0,0 +1,4 @@
|
||||
export { default as SimpleProductForm } from './simple';
|
||||
export { default as VariableProductForm } from './variable/index';
|
||||
export { default as ExternalProductForm } from './external';
|
||||
export { default as GroupedProductForm } from './grouped';
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { useAddToCartFormContext } from '@woocommerce/base-context';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { AddToCartButton, QuantityInput, ProductUnavailable } from '../shared';
|
||||
|
||||
/**
|
||||
* Simple Product Add To Cart Form
|
||||
*/
|
||||
const Simple = () => {
|
||||
// @todo Add types for `useAddToCartFormContext`
|
||||
const {
|
||||
product,
|
||||
quantity,
|
||||
minQuantity,
|
||||
maxQuantity,
|
||||
multipleOf,
|
||||
dispatchActions,
|
||||
isDisabled,
|
||||
} = useAddToCartFormContext();
|
||||
|
||||
if ( product.id && ! product.is_purchasable ) {
|
||||
return <ProductUnavailable />;
|
||||
}
|
||||
|
||||
if ( product.id && ! product.is_in_stock ) {
|
||||
return (
|
||||
<ProductUnavailable
|
||||
reason={ __(
|
||||
'This product is currently out of stock and cannot be purchased.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<QuantityInput
|
||||
value={ quantity }
|
||||
min={ minQuantity }
|
||||
max={ maxQuantity }
|
||||
step={ multipleOf }
|
||||
disabled={ isDisabled }
|
||||
onChange={ dispatchActions.setQuantity }
|
||||
/>
|
||||
<AddToCartButton />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Simple;
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { useAddToCartFormContext } from '@woocommerce/base-context';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import {
|
||||
AddToCartButton,
|
||||
QuantityInput,
|
||||
ProductUnavailable,
|
||||
} from '../../shared';
|
||||
import VariationAttributes from './variation-attributes';
|
||||
|
||||
/**
|
||||
* Variable Product Add To Cart Form
|
||||
*/
|
||||
const Variable = () => {
|
||||
// @todo Add types for `useAddToCartFormContext`
|
||||
const {
|
||||
product,
|
||||
quantity,
|
||||
minQuantity,
|
||||
maxQuantity,
|
||||
multipleOf,
|
||||
dispatchActions,
|
||||
isDisabled,
|
||||
} = useAddToCartFormContext();
|
||||
|
||||
if ( product.id && ! product.is_purchasable ) {
|
||||
return <ProductUnavailable />;
|
||||
}
|
||||
|
||||
if ( product.id && ! product.is_in_stock ) {
|
||||
return (
|
||||
<ProductUnavailable
|
||||
reason={ __(
|
||||
'This product is currently out of stock and cannot be purchased.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<VariationAttributes
|
||||
product={ product }
|
||||
dispatchers={ dispatchActions }
|
||||
/>
|
||||
<QuantityInput
|
||||
value={ quantity }
|
||||
min={ minQuantity }
|
||||
max={ maxQuantity }
|
||||
step={ multipleOf }
|
||||
disabled={ isDisabled }
|
||||
onChange={ dispatchActions.setQuantity }
|
||||
/>
|
||||
<AddToCartButton />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Variable;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { Dictionary } from '@woocommerce/types';
|
||||
|
||||
export type AttributesMap = Record<
|
||||
string,
|
||||
{ id: number; attributes: Dictionary }
|
||||
>;
|
||||
|
||||
export interface VariationParam {
|
||||
id: number;
|
||||
variation: {
|
||||
attribute: string;
|
||||
value: string;
|
||||
}[];
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useState, useEffect, useMemo } from '@wordpress/element';
|
||||
import { useShallowEqual } from '@woocommerce/base-hooks';
|
||||
import type { SelectControl } from '@wordpress/components';
|
||||
import { Dictionary, ProductResponseAttributeItem } from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import AttributeSelectControl from './attribute-select-control';
|
||||
import {
|
||||
getVariationMatchingSelectedAttributes,
|
||||
getActiveSelectControlOptions,
|
||||
getDefaultAttributes,
|
||||
} from './utils';
|
||||
import { AttributesMap, VariationParam } from '../types';
|
||||
|
||||
interface Props {
|
||||
attributes: Record< string, ProductResponseAttributeItem >;
|
||||
setRequestParams: ( param: VariationParam ) => void;
|
||||
variationAttributes: AttributesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* AttributePicker component.
|
||||
*/
|
||||
const AttributePicker = ( {
|
||||
attributes,
|
||||
variationAttributes,
|
||||
setRequestParams,
|
||||
}: Props ) => {
|
||||
const currentAttributes = useShallowEqual( attributes );
|
||||
const currentVariationAttributes = useShallowEqual( variationAttributes );
|
||||
const [ variationId, setVariationId ] = useState( 0 );
|
||||
const [ selectedAttributes, setSelectedAttributes ] =
|
||||
useState< Dictionary >( {} );
|
||||
const [ hasSetDefaults, setHasSetDefaults ] = useState( false );
|
||||
|
||||
// Get options for each attribute picker.
|
||||
const filteredAttributeOptions = useMemo( () => {
|
||||
return getActiveSelectControlOptions(
|
||||
currentAttributes,
|
||||
currentVariationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
}, [ selectedAttributes, currentAttributes, currentVariationAttributes ] );
|
||||
|
||||
// Set default attributes as selected.
|
||||
useEffect( () => {
|
||||
if ( ! hasSetDefaults ) {
|
||||
const defaultAttributes = getDefaultAttributes( attributes );
|
||||
if ( defaultAttributes ) {
|
||||
setSelectedAttributes( {
|
||||
...defaultAttributes,
|
||||
} );
|
||||
}
|
||||
setHasSetDefaults( true );
|
||||
}
|
||||
}, [ selectedAttributes, attributes, hasSetDefaults ] );
|
||||
|
||||
// Select variations when selections are change.
|
||||
useEffect( () => {
|
||||
const hasSelectedAllAttributes =
|
||||
Object.values( selectedAttributes ).filter(
|
||||
( selected ) => selected !== ''
|
||||
).length === Object.keys( currentAttributes ).length;
|
||||
|
||||
if ( hasSelectedAllAttributes ) {
|
||||
setVariationId(
|
||||
getVariationMatchingSelectedAttributes(
|
||||
currentAttributes,
|
||||
currentVariationAttributes,
|
||||
selectedAttributes
|
||||
)
|
||||
);
|
||||
} else if ( variationId > 0 ) {
|
||||
// Unset variation when form is incomplete.
|
||||
setVariationId( 0 );
|
||||
}
|
||||
}, [
|
||||
selectedAttributes,
|
||||
variationId,
|
||||
currentAttributes,
|
||||
currentVariationAttributes,
|
||||
] );
|
||||
|
||||
// Set requests params as variation ID and data changes.
|
||||
useEffect( () => {
|
||||
setRequestParams( {
|
||||
id: variationId,
|
||||
variation: Object.keys( selectedAttributes ).map(
|
||||
( attributeName ) => {
|
||||
return {
|
||||
attribute: attributeName,
|
||||
value: selectedAttributes[ attributeName ],
|
||||
};
|
||||
}
|
||||
),
|
||||
} );
|
||||
}, [ setRequestParams, variationId, selectedAttributes ] );
|
||||
|
||||
return (
|
||||
<div className="wc-block-components-product-add-to-cart-attribute-picker">
|
||||
{ Object.keys( currentAttributes ).map( ( attributeName ) => (
|
||||
<AttributeSelectControl
|
||||
key={ attributeName }
|
||||
attributeName={ attributeName }
|
||||
options={
|
||||
filteredAttributeOptions[ attributeName ].filter(
|
||||
Boolean
|
||||
) as SelectControl.Option[]
|
||||
}
|
||||
value={ selectedAttributes[ attributeName ] }
|
||||
onChange={ ( selected ) => {
|
||||
setSelectedAttributes( {
|
||||
...selectedAttributes,
|
||||
[ attributeName ]: selected,
|
||||
} );
|
||||
} }
|
||||
/>
|
||||
) ) }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AttributePicker;
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { decodeEntities } from '@wordpress/html-entities';
|
||||
import { SelectControl } from 'wordpress-components';
|
||||
import type { SelectControl as SelectControlType } from '@wordpress/components';
|
||||
import { useEffect } from '@wordpress/element';
|
||||
import classnames from 'classnames';
|
||||
import { ValidationInputError } from '@woocommerce/blocks-checkout';
|
||||
import { VALIDATION_STORE_KEY } from '@woocommerce/block-data';
|
||||
import { useDispatch, useSelect } from '@wordpress/data';
|
||||
|
||||
interface Props extends SelectControlType.Props< string > {
|
||||
attributeName: string;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
// Default option for select boxes.
|
||||
const selectAnOption = {
|
||||
value: '',
|
||||
label: __( 'Select an option', 'woo-gutenberg-products-block' ),
|
||||
};
|
||||
|
||||
/**
|
||||
* VariationAttributeSelect component.
|
||||
*/
|
||||
const AttributeSelectControl = ( {
|
||||
attributeName,
|
||||
options = [],
|
||||
value = '',
|
||||
onChange = () => void 0,
|
||||
errorMessage = __(
|
||||
'Please select a value.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
}: Props ) => {
|
||||
const errorId = attributeName;
|
||||
|
||||
const { setValidationErrors, clearValidationError } =
|
||||
useDispatch( VALIDATION_STORE_KEY );
|
||||
|
||||
const { error } = useSelect( ( select ) => {
|
||||
const store = select( VALIDATION_STORE_KEY );
|
||||
return {
|
||||
error: store.getValidationError( errorId ) || {},
|
||||
};
|
||||
} );
|
||||
|
||||
useEffect( () => {
|
||||
if ( value ) {
|
||||
clearValidationError( errorId );
|
||||
} else {
|
||||
setValidationErrors( {
|
||||
[ errorId ]: {
|
||||
message: errorMessage,
|
||||
hidden: true,
|
||||
},
|
||||
} );
|
||||
}
|
||||
}, [
|
||||
value,
|
||||
errorId,
|
||||
errorMessage,
|
||||
clearValidationError,
|
||||
setValidationErrors,
|
||||
] );
|
||||
|
||||
// Remove validation errors when unmounted.
|
||||
useEffect(
|
||||
() => () => void clearValidationError( errorId ),
|
||||
[ errorId, clearValidationError ]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="wc-block-components-product-add-to-cart-attribute-picker__container">
|
||||
<SelectControl
|
||||
label={ decodeEntities( attributeName ) }
|
||||
value={ value || '' }
|
||||
options={ [ selectAnOption, ...options ] }
|
||||
onChange={ onChange }
|
||||
required={ true }
|
||||
className={ classnames(
|
||||
'wc-block-components-product-add-to-cart-attribute-picker__select',
|
||||
{
|
||||
'has-error': error?.message && ! error?.hidden,
|
||||
}
|
||||
) }
|
||||
/>
|
||||
<ValidationInputError
|
||||
propertyName={ errorId }
|
||||
elementId={ errorId }
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AttributeSelectControl;
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { ProductResponseItem } from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import AttributePicker from './attribute-picker';
|
||||
import { getAttributes, getVariationAttributes } from './utils';
|
||||
|
||||
interface Props {
|
||||
dispatchers: { setRequestParams: () => void };
|
||||
product: ProductResponseItem;
|
||||
}
|
||||
|
||||
/**
|
||||
* VariationAttributes component.
|
||||
*/
|
||||
const VariationAttributes = ( { dispatchers, product }: Props ) => {
|
||||
const attributes = getAttributes( product.attributes );
|
||||
const variationAttributes = getVariationAttributes( product.variations );
|
||||
if (
|
||||
Object.keys( attributes ).length === 0 ||
|
||||
Object.keys( variationAttributes ).length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<AttributePicker
|
||||
attributes={ attributes }
|
||||
variationAttributes={ variationAttributes }
|
||||
setRequestParams={ dispatchers.setRequestParams }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default VariationAttributes;
|
||||
@@ -0,0 +1,33 @@
|
||||
.wc-block-components-product-add-to-cart-attribute-picker {
|
||||
margin: 0;
|
||||
flex-basis: 100%;
|
||||
|
||||
label {
|
||||
display: block;
|
||||
@include font-size(regular);
|
||||
}
|
||||
|
||||
.wc-block-components-product-add-to-cart-attribute-picker__container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.wc-block-components-product-add-to-cart-attribute-picker__select {
|
||||
margin: 0 0 em($gap-small) 0;
|
||||
|
||||
select {
|
||||
min-width: 60%;
|
||||
min-height: 1.75em;
|
||||
}
|
||||
|
||||
&.has-error {
|
||||
margin-bottom: $gap-large;
|
||||
|
||||
select {
|
||||
border-color: $alert-red;
|
||||
&:focus {
|
||||
outline-color: $alert-red;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { ProductResponseAttributeItem } from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import {
|
||||
getAttributes,
|
||||
getVariationAttributes,
|
||||
getVariationsMatchingSelectedAttributes,
|
||||
getVariationMatchingSelectedAttributes,
|
||||
getActiveSelectControlOptions,
|
||||
getDefaultAttributes,
|
||||
} from '../utils';
|
||||
|
||||
const rawAttributeData: ProductResponseAttributeItem[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Color',
|
||||
taxonomy: 'pa_color',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 22,
|
||||
name: 'Blue',
|
||||
slug: 'blue',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 23,
|
||||
name: 'Green',
|
||||
slug: 'green',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
id: 24,
|
||||
name: 'Red',
|
||||
slug: 'red',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 0,
|
||||
name: 'Logo',
|
||||
taxonomy: 'pa_logo',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 0,
|
||||
name: 'Yes',
|
||||
slug: 'Yes',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 0,
|
||||
name: 'No',
|
||||
slug: 'No',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 0,
|
||||
name: 'Non-variable attribute',
|
||||
taxonomy: 'pa_non-variable-attribute',
|
||||
has_variations: false,
|
||||
terms: [
|
||||
{
|
||||
id: 0,
|
||||
name: 'Test',
|
||||
slug: 'Test',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
id: 0,
|
||||
name: 'Test 2',
|
||||
slug: 'Test 2',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const rawVariations = [
|
||||
{
|
||||
id: 35,
|
||||
attributes: [
|
||||
{
|
||||
name: 'Color',
|
||||
value: 'blue',
|
||||
},
|
||||
{
|
||||
name: 'Logo',
|
||||
value: 'Yes',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 28,
|
||||
attributes: [
|
||||
{
|
||||
name: 'Color',
|
||||
value: 'red',
|
||||
},
|
||||
{
|
||||
name: 'Logo',
|
||||
value: 'No',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 29,
|
||||
attributes: [
|
||||
{
|
||||
name: 'Color',
|
||||
value: 'green',
|
||||
},
|
||||
{
|
||||
name: 'Logo',
|
||||
value: 'No',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 30,
|
||||
attributes: [
|
||||
{
|
||||
name: 'Color',
|
||||
value: 'blue',
|
||||
},
|
||||
{
|
||||
name: 'Logo',
|
||||
value: 'No',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const formattedAttributes = {
|
||||
Color: {
|
||||
id: 1,
|
||||
name: 'Color',
|
||||
taxonomy: 'pa_color',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 22,
|
||||
name: 'Blue',
|
||||
slug: 'blue',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 23,
|
||||
name: 'Green',
|
||||
slug: 'green',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
id: 24,
|
||||
name: 'Red',
|
||||
slug: 'red',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
Size: {
|
||||
id: 2,
|
||||
name: 'Size',
|
||||
taxonomy: 'pa_size',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 25,
|
||||
name: 'Large',
|
||||
slug: 'large',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
id: 26,
|
||||
name: 'Medium',
|
||||
slug: 'medium',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 27,
|
||||
name: 'Small',
|
||||
slug: 'small',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
describe( 'Testing utils', () => {
|
||||
describe( 'Testing getAttributes()', () => {
|
||||
it( 'returns empty object if there are no attributes', () => {
|
||||
const attributes = getAttributes( null );
|
||||
expect( attributes ).toStrictEqual( {} );
|
||||
} );
|
||||
it( 'returns list of attributes when given valid data', () => {
|
||||
const attributes = getAttributes( rawAttributeData );
|
||||
expect( attributes ).toStrictEqual( {
|
||||
Color: {
|
||||
id: 1,
|
||||
name: 'Color',
|
||||
taxonomy: 'pa_color',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 22,
|
||||
name: 'Blue',
|
||||
slug: 'blue',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 23,
|
||||
name: 'Green',
|
||||
slug: 'green',
|
||||
default: false,
|
||||
},
|
||||
{
|
||||
id: 24,
|
||||
name: 'Red',
|
||||
slug: 'red',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
Logo: {
|
||||
id: 0,
|
||||
name: 'Logo',
|
||||
taxonomy: 'pa_logo',
|
||||
has_variations: true,
|
||||
terms: [
|
||||
{
|
||||
id: 0,
|
||||
name: 'Yes',
|
||||
slug: 'Yes',
|
||||
default: true,
|
||||
},
|
||||
{
|
||||
id: 0,
|
||||
name: 'No',
|
||||
slug: 'No',
|
||||
default: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
describe( 'Testing getVariationAttributes()', () => {
|
||||
it( 'returns empty object if there are no variations', () => {
|
||||
const variationAttributes = getVariationAttributes( null );
|
||||
expect( variationAttributes ).toStrictEqual( {} );
|
||||
} );
|
||||
it( 'returns list of attribute names and value pairs when given valid data', () => {
|
||||
const variationAttributes = getVariationAttributes( rawVariations );
|
||||
expect( variationAttributes ).toStrictEqual( {
|
||||
'id:35': {
|
||||
id: 35,
|
||||
attributes: {
|
||||
Color: 'blue',
|
||||
Logo: 'Yes',
|
||||
},
|
||||
},
|
||||
'id:28': {
|
||||
id: 28,
|
||||
attributes: {
|
||||
Color: 'red',
|
||||
Logo: 'No',
|
||||
},
|
||||
},
|
||||
'id:29': {
|
||||
id: 29,
|
||||
attributes: {
|
||||
Color: 'green',
|
||||
Logo: 'No',
|
||||
},
|
||||
},
|
||||
'id:30': {
|
||||
id: 30,
|
||||
attributes: {
|
||||
Color: 'blue',
|
||||
Logo: 'No',
|
||||
},
|
||||
},
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
describe( 'Testing getVariationsMatchingSelectedAttributes()', () => {
|
||||
const attributes = getAttributes( rawAttributeData );
|
||||
const variationAttributes = getVariationAttributes( rawVariations );
|
||||
|
||||
it( 'returns all variations, in the correct order, if no selections have been made yet', () => {
|
||||
const selectedAttributes = {};
|
||||
const matches = getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( [ 35, 28, 29, 30 ] );
|
||||
} );
|
||||
|
||||
it( 'returns correct subset of variations after a selection', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'blue',
|
||||
};
|
||||
const matches = getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( [ 35, 30 ] );
|
||||
} );
|
||||
|
||||
it( 'returns correct subset of variations after all selections', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'blue',
|
||||
Logo: 'No',
|
||||
};
|
||||
const matches = getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( [ 30 ] );
|
||||
} );
|
||||
|
||||
it( 'returns no results if selection does not match or is invalid', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'brown',
|
||||
};
|
||||
const matches = getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( [] );
|
||||
} );
|
||||
} );
|
||||
describe( 'Testing getVariationMatchingSelectedAttributes()', () => {
|
||||
const attributes = getAttributes( rawAttributeData );
|
||||
const variationAttributes = getVariationAttributes( rawVariations );
|
||||
|
||||
it( 'returns first match if no selections have been made yet', () => {
|
||||
const selectedAttributes = {};
|
||||
const matches = getVariationMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( 35 );
|
||||
} );
|
||||
|
||||
it( 'returns first match after single selection', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'blue',
|
||||
};
|
||||
const matches = getVariationMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( 35 );
|
||||
} );
|
||||
|
||||
it( 'returns correct match after all selections', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'blue',
|
||||
Logo: 'No',
|
||||
};
|
||||
const matches = getVariationMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( 30 );
|
||||
} );
|
||||
|
||||
it( 'returns no match if invalid', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'brown',
|
||||
};
|
||||
const matches = getVariationMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( matches ).toStrictEqual( 0 );
|
||||
} );
|
||||
} );
|
||||
describe( 'Testing getActiveSelectControlOptions()', () => {
|
||||
const attributes = getAttributes( rawAttributeData );
|
||||
const variationAttributes = getVariationAttributes( rawVariations );
|
||||
|
||||
it( 'returns all possible options if no selections have been made yet', () => {
|
||||
const selectedAttributes = {};
|
||||
const controlOptions = getActiveSelectControlOptions(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( controlOptions ).toStrictEqual( {
|
||||
Color: [
|
||||
{
|
||||
value: 'blue',
|
||||
label: 'Blue',
|
||||
},
|
||||
{
|
||||
value: 'green',
|
||||
label: 'Green',
|
||||
},
|
||||
{
|
||||
value: 'red',
|
||||
label: 'Red',
|
||||
},
|
||||
],
|
||||
Logo: [
|
||||
{
|
||||
value: 'Yes',
|
||||
label: 'Yes',
|
||||
},
|
||||
{
|
||||
value: 'No',
|
||||
label: 'No',
|
||||
},
|
||||
],
|
||||
} );
|
||||
} );
|
||||
|
||||
it( 'returns only valid options if color is selected', () => {
|
||||
const selectedAttributes = {
|
||||
Color: 'green',
|
||||
};
|
||||
const controlOptions = getActiveSelectControlOptions(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
expect( controlOptions ).toStrictEqual( {
|
||||
Color: [
|
||||
{
|
||||
value: 'blue',
|
||||
label: 'Blue',
|
||||
},
|
||||
{
|
||||
value: 'green',
|
||||
label: 'Green',
|
||||
},
|
||||
{
|
||||
value: 'red',
|
||||
label: 'Red',
|
||||
},
|
||||
],
|
||||
Logo: [
|
||||
{
|
||||
value: 'No',
|
||||
label: 'No',
|
||||
},
|
||||
],
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
describe( 'Testing getDefaultAttributes()', () => {
|
||||
const defaultAttributes = getDefaultAttributes( formattedAttributes );
|
||||
|
||||
it( 'should return default attributes in the format that is ready for setting state', () => {
|
||||
expect( defaultAttributes ).toStrictEqual( {
|
||||
Color: 'blue',
|
||||
Size: 'medium',
|
||||
} );
|
||||
} );
|
||||
|
||||
it( 'should return an empty object if given unexpected values', () => {
|
||||
// @ts-expect-error Expected TS Error as we are checking how the function does with *unexpected values*.
|
||||
expect( getDefaultAttributes( [] ) ).toStrictEqual( {} );
|
||||
// @ts-expect-error Ditto above.
|
||||
expect( getDefaultAttributes( null ) ).toStrictEqual( {} );
|
||||
// @ts-expect-error Ditto above.
|
||||
expect( getDefaultAttributes( undefined ) ).toStrictEqual( {} );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
@@ -0,0 +1,295 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { keyBy } from 'lodash';
|
||||
import { decodeEntities } from '@wordpress/html-entities';
|
||||
import {
|
||||
Dictionary,
|
||||
isObject,
|
||||
ProductResponseAttributeItem,
|
||||
ProductResponseTermItem,
|
||||
ProductResponseVariationsItem,
|
||||
} from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { AttributesMap } from '../types';
|
||||
|
||||
/**
|
||||
* Key an array of attributes by name,
|
||||
*/
|
||||
export const getAttributes = (
|
||||
attributes?: ProductResponseAttributeItem[] | null
|
||||
) => {
|
||||
return attributes
|
||||
? keyBy(
|
||||
Object.values( attributes ).filter(
|
||||
( { has_variations: hasVariations } ) => hasVariations
|
||||
),
|
||||
'name'
|
||||
)
|
||||
: {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Format variations from the API into a map of just the attribute names and values.
|
||||
*
|
||||
* Note, each item is keyed by the variation ID with an id: prefix. This is to prevent the object
|
||||
* being reordered when iterated.
|
||||
*/
|
||||
export const getVariationAttributes = (
|
||||
/**
|
||||
* List of Variation objects and attributes keyed by variation ID.
|
||||
*/
|
||||
variations?: ProductResponseVariationsItem[] | null
|
||||
) => {
|
||||
if ( ! variations ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const attributesMap: AttributesMap = {};
|
||||
|
||||
variations.forEach( ( { id, attributes } ) => {
|
||||
attributesMap[ `id:${ id }` ] = {
|
||||
id,
|
||||
attributes: attributes.reduce( ( acc, { name, value } ) => {
|
||||
acc[ name ] = value;
|
||||
return acc;
|
||||
}, {} as Dictionary ),
|
||||
};
|
||||
} );
|
||||
|
||||
return attributesMap;
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a list of variations and a list of attribute values, return variations which match.
|
||||
*
|
||||
* Allows an attribute to be excluded by name. This is used to filter displayed options for
|
||||
* individual attribute selects.
|
||||
*
|
||||
* @return List of matching variation IDs.
|
||||
*/
|
||||
export const getVariationsMatchingSelectedAttributes = (
|
||||
/**
|
||||
* List of attribute names and terms.
|
||||
*
|
||||
* As returned from {@link getAttributes()}.
|
||||
*/
|
||||
attributes: Record< string, ProductResponseAttributeItem >,
|
||||
/**
|
||||
* Attributes for each variation keyed by variation ID.
|
||||
*
|
||||
* As returned from {@link getVariationAttributes()}.
|
||||
*/
|
||||
variationAttributes: AttributesMap,
|
||||
/**
|
||||
* Attribute Name Value pairs of current selections by the user.
|
||||
*/
|
||||
selectedAttributes: Record< string, string | null >
|
||||
) => {
|
||||
const variationIds = Object.values( variationAttributes ).map(
|
||||
( { id } ) => id
|
||||
);
|
||||
|
||||
// If nothing is selected yet, just return all variations.
|
||||
if (
|
||||
Object.values( selectedAttributes ).every( ( value ) => value === '' )
|
||||
) {
|
||||
return variationIds;
|
||||
}
|
||||
|
||||
const attributeNames = Object.keys( attributes );
|
||||
|
||||
return variationIds.filter( ( variationId ) =>
|
||||
attributeNames.every( ( attributeName ) => {
|
||||
const selectedAttribute = selectedAttributes[ attributeName ] || '';
|
||||
const variationAttribute =
|
||||
variationAttributes[ 'id:' + variationId ].attributes[
|
||||
attributeName
|
||||
];
|
||||
|
||||
// If there is no selected attribute, consider this a match.
|
||||
if ( selectedAttribute === '' ) {
|
||||
return true;
|
||||
}
|
||||
// If the variation attributes for this attribute are set to null, it matches all values.
|
||||
if ( variationAttribute === null ) {
|
||||
return true;
|
||||
}
|
||||
// Otherwise, only match if the selected values are the same.
|
||||
return variationAttribute === selectedAttribute;
|
||||
} )
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a list of variations and a list of attribute values, returns the first matched variation ID.
|
||||
*
|
||||
* @return Variation ID.
|
||||
*/
|
||||
export const getVariationMatchingSelectedAttributes = (
|
||||
/**
|
||||
* List of attribute names and terms.
|
||||
*
|
||||
* As returned from {@link getAttributes()}.
|
||||
*/
|
||||
attributes: Record< string, ProductResponseAttributeItem >,
|
||||
/**
|
||||
* Attributes for each variation keyed by variation ID.
|
||||
*
|
||||
* As returned from {@link getVariationAttributes()}.
|
||||
*/
|
||||
variationAttributes: AttributesMap,
|
||||
/**
|
||||
* Attribute Name Value pairs of current selections by the user.
|
||||
*/
|
||||
selectedAttributes: Dictionary
|
||||
) => {
|
||||
const matchingVariationIds = getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributes
|
||||
);
|
||||
return matchingVariationIds[ 0 ] || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a list of terms, filter them and return valid options for the select boxes.
|
||||
*
|
||||
* @see getActiveSelectControlOptions
|
||||
*
|
||||
* @return Value/Label pairs of select box options.
|
||||
*/
|
||||
const getValidSelectControlOptions = (
|
||||
/**
|
||||
* List of attribute term objects.
|
||||
*/
|
||||
attributeTerms: ProductResponseTermItem[],
|
||||
/**
|
||||
* Valid values if selections have been made already.
|
||||
*/
|
||||
validAttributeTerms: Array< string | null > | null = null
|
||||
) => {
|
||||
return Object.values( attributeTerms )
|
||||
.map( ( { name, slug } ) => {
|
||||
if (
|
||||
validAttributeTerms === null ||
|
||||
validAttributeTerms.includes( null ) ||
|
||||
validAttributeTerms.includes( slug )
|
||||
) {
|
||||
return {
|
||||
value: slug,
|
||||
label: decodeEntities( name ),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
} )
|
||||
.filter( Boolean );
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a list of terms, filter them and return active options for the select boxes. This factors in
|
||||
* which options should be hidden due to current selections.
|
||||
*
|
||||
* @return Select box options.
|
||||
*/
|
||||
export const getActiveSelectControlOptions = (
|
||||
/**
|
||||
* List of attribute names and terms.
|
||||
*
|
||||
* As returned from {@link getAttributes()}.
|
||||
*/
|
||||
attributes: Record< string, ProductResponseAttributeItem >,
|
||||
/**
|
||||
* Attributes for each variation keyed by variation ID.
|
||||
*
|
||||
* As returned from {@link getVariationAttributes()}.
|
||||
*/
|
||||
variationAttributes: AttributesMap,
|
||||
/**
|
||||
* Attribute Name Value pairs of current selections by the user.
|
||||
*/
|
||||
selectedAttributes: Dictionary
|
||||
) => {
|
||||
const options: Record<
|
||||
string,
|
||||
Array< { label: string; value: string } | null >
|
||||
> = {};
|
||||
const attributeNames = Object.keys( attributes );
|
||||
const hasSelectedAttributes =
|
||||
Object.values( selectedAttributes ).filter( Boolean ).length > 0;
|
||||
|
||||
attributeNames.forEach( ( attributeName ) => {
|
||||
const currentAttribute = attributes[ attributeName ];
|
||||
const selectedAttributesExcludingCurrentAttribute = {
|
||||
...selectedAttributes,
|
||||
[ attributeName ]: null,
|
||||
};
|
||||
// This finds matching variations for selected attributes apart from this one. This will be
|
||||
// used to get valid attribute terms of the current attribute narrowed down by those matching
|
||||
// variation IDs. For example, if I had Large Blue Shirts and Medium Red Shirts, I want to only
|
||||
// show Red shirts if Medium is selected.
|
||||
const matchingVariationIds = hasSelectedAttributes
|
||||
? getVariationsMatchingSelectedAttributes(
|
||||
attributes,
|
||||
variationAttributes,
|
||||
selectedAttributesExcludingCurrentAttribute
|
||||
)
|
||||
: null;
|
||||
// Uses the above matching variation IDs to get the attributes from just those variations.
|
||||
const validAttributeTerms =
|
||||
matchingVariationIds !== null
|
||||
? matchingVariationIds.map(
|
||||
( varId ) =>
|
||||
variationAttributes[ 'id:' + varId ].attributes[
|
||||
attributeName
|
||||
]
|
||||
)
|
||||
: null;
|
||||
// Intersects attributes with valid attributes.
|
||||
options[ attributeName ] = getValidSelectControlOptions(
|
||||
currentAttribute.terms,
|
||||
validAttributeTerms
|
||||
);
|
||||
} );
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the default values of the given attributes in a format ready to be set in state.
|
||||
*
|
||||
* @return Default attributes.
|
||||
*/
|
||||
export const getDefaultAttributes = (
|
||||
/**
|
||||
* List of attribute names and terms.
|
||||
*
|
||||
* As returned from {@link getAttributes()}.
|
||||
*/
|
||||
attributes: Record< string, ProductResponseAttributeItem >
|
||||
) => {
|
||||
if ( ! isObject( attributes ) ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const attributeNames = Object.keys( attributes );
|
||||
|
||||
if ( attributeNames.length === 0 ) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const attributesEntries = Object.values( attributes );
|
||||
|
||||
return attributesEntries.reduce( ( acc, curr ) => {
|
||||
const defaultValues = curr.terms.filter( ( term ) => term.default );
|
||||
|
||||
if ( defaultValues.length > 0 ) {
|
||||
acc[ curr.name ] = defaultValues[ 0 ]?.slug;
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, {} as Dictionary );
|
||||
};
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __, _n, sprintf } from '@wordpress/i18n';
|
||||
import Button, { ButtonProps } from '@woocommerce/base-components/button';
|
||||
import { Icon, check } from '@wordpress/icons';
|
||||
import { useState, useEffect } from '@wordpress/element';
|
||||
import { useAddToCartFormContext } from '@woocommerce/base-context';
|
||||
import {
|
||||
useStoreEvents,
|
||||
useStoreAddToCart,
|
||||
} from '@woocommerce/base-context/hooks';
|
||||
import { useInnerBlockLayoutContext } from '@woocommerce/shared-context';
|
||||
|
||||
type LinkProps = Pick< ButtonProps, 'className' | 'href' | 'onClick' | 'text' >;
|
||||
|
||||
interface ButtonComponentProps
|
||||
extends Pick< ButtonProps, 'className' | 'onClick' > {
|
||||
/**
|
||||
* Whether the button is disabled or not.
|
||||
*/
|
||||
isDisabled: boolean;
|
||||
/**
|
||||
* Whether processing is done.
|
||||
*/
|
||||
isDone: boolean;
|
||||
/**
|
||||
* Whether processing action is occurring.
|
||||
*/
|
||||
isProcessing: ButtonProps[ 'showSpinner' ];
|
||||
/**
|
||||
* Quantity of said item currently in the cart.
|
||||
*/
|
||||
quantityInCart: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Button component for non-purchasable products.
|
||||
*/
|
||||
const LinkComponent = ( { className, href, text, onClick }: LinkProps ) => {
|
||||
return (
|
||||
<Button
|
||||
className={ className }
|
||||
href={ href }
|
||||
onClick={ onClick }
|
||||
rel="nofollow"
|
||||
>
|
||||
{ text }
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Button for purchasable products.
|
||||
*/
|
||||
const ButtonComponent = ( {
|
||||
className,
|
||||
quantityInCart,
|
||||
isProcessing,
|
||||
isDisabled,
|
||||
isDone,
|
||||
onClick,
|
||||
}: ButtonComponentProps ) => {
|
||||
return (
|
||||
<Button
|
||||
className={ className }
|
||||
disabled={ isDisabled }
|
||||
showSpinner={ isProcessing }
|
||||
onClick={ onClick }
|
||||
>
|
||||
{ isDone && quantityInCart > 0
|
||||
? sprintf(
|
||||
/* translators: %s number of products in cart. */
|
||||
_n(
|
||||
'%d in cart',
|
||||
'%d in cart',
|
||||
quantityInCart,
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
quantityInCart
|
||||
)
|
||||
: __( 'Add to cart', 'woo-gutenberg-products-block' ) }
|
||||
{ !! isDone && <Icon icon={ check } /> }
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add to Cart Form Button Component.
|
||||
*/
|
||||
const AddToCartButton = () => {
|
||||
// @todo Add types for `useAddToCartFormContext`
|
||||
const {
|
||||
showFormElements,
|
||||
productIsPurchasable,
|
||||
productHasOptions,
|
||||
product,
|
||||
productType,
|
||||
isDisabled,
|
||||
isProcessing,
|
||||
eventRegistration,
|
||||
hasError,
|
||||
dispatchActions,
|
||||
} = useAddToCartFormContext();
|
||||
const { parentName } = useInnerBlockLayoutContext();
|
||||
const { dispatchStoreEvent } = useStoreEvents();
|
||||
const { cartQuantity } = useStoreAddToCart( product.id || 0 );
|
||||
const [ addedToCart, setAddedToCart ] = useState( false );
|
||||
const addToCartButtonData = product.add_to_cart || {
|
||||
url: '',
|
||||
text: '',
|
||||
};
|
||||
|
||||
// Subscribe to emitter for after processing.
|
||||
useEffect( () => {
|
||||
const onSuccess = () => {
|
||||
if ( ! hasError ) {
|
||||
setAddedToCart( true );
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const unsubscribeProcessing =
|
||||
eventRegistration.onAddToCartAfterProcessingWithSuccess(
|
||||
onSuccess,
|
||||
0
|
||||
);
|
||||
return () => {
|
||||
unsubscribeProcessing();
|
||||
};
|
||||
}, [ eventRegistration, hasError ] );
|
||||
|
||||
/**
|
||||
* We can show a real button if we are:
|
||||
*
|
||||
* a) Showing a full add to cart form.
|
||||
* b) The product doesn't have options and can therefore be added directly to the cart.
|
||||
* c) The product is purchasable.
|
||||
*
|
||||
* Otherwise we show a link instead.
|
||||
*/
|
||||
const showButton =
|
||||
( showFormElements ||
|
||||
( ! productHasOptions && productType === 'simple' ) ) &&
|
||||
productIsPurchasable;
|
||||
|
||||
return showButton ? (
|
||||
<ButtonComponent
|
||||
className="wc-block-components-product-add-to-cart-button"
|
||||
quantityInCart={ cartQuantity }
|
||||
isDisabled={ isDisabled }
|
||||
isProcessing={ isProcessing }
|
||||
isDone={ addedToCart }
|
||||
onClick={ () => {
|
||||
dispatchActions.submitForm(
|
||||
`woocommerce/single-product/${ product?.id || 0 }`
|
||||
);
|
||||
dispatchStoreEvent( 'cart-add-item', {
|
||||
product,
|
||||
listName: parentName,
|
||||
} );
|
||||
} }
|
||||
/>
|
||||
) : (
|
||||
<LinkComponent
|
||||
className="wc-block-components-product-add-to-cart-button"
|
||||
href={ addToCartButtonData.url }
|
||||
text={
|
||||
addToCartButtonData.text ||
|
||||
__( 'View Product', 'woo-gutenberg-products-block' )
|
||||
}
|
||||
onClick={ () => {
|
||||
dispatchStoreEvent( 'product-view-link', {
|
||||
product,
|
||||
listName: parentName,
|
||||
} );
|
||||
} }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddToCartButton;
|
||||
@@ -0,0 +1,3 @@
|
||||
export { default as AddToCartButton } from './add-to-cart-button';
|
||||
export { default as QuantityInput } from './quantity-input';
|
||||
export { default as ProductUnavailable } from './product-unavailable';
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
const ProductUnavailable = ( {
|
||||
reason = __(
|
||||
'Sorry, this product cannot be purchased.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
} ) => {
|
||||
return (
|
||||
<div className="wc-block-components-product-add-to-cart-unavailable">
|
||||
{ reason }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductUnavailable;
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useDebouncedCallback } from 'use-debounce';
|
||||
|
||||
type JSXInputProps = JSX.IntrinsicElements[ 'input' ];
|
||||
|
||||
interface QuantityInputProps extends Omit< JSXInputProps, 'onChange' > {
|
||||
max: number;
|
||||
min: number;
|
||||
onChange: ( val: number | string ) => void;
|
||||
step: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quantity Input Component.
|
||||
*/
|
||||
const QuantityInput = ( {
|
||||
disabled,
|
||||
min,
|
||||
max,
|
||||
step = 1,
|
||||
value,
|
||||
onChange,
|
||||
}: QuantityInputProps ) => {
|
||||
const hasMaximum = typeof max !== 'undefined';
|
||||
|
||||
/**
|
||||
* The goal of this function is to normalize what was inserted,
|
||||
* but after the customer has stopped typing.
|
||||
*
|
||||
* It's important to wait before normalizing or we end up with
|
||||
* a frustrating experience, for example, if the minimum is 2 and
|
||||
* the customer is trying to type "10", premature normalizing would
|
||||
* always kick in at "1" and turn that into 2.
|
||||
*
|
||||
* Copied from <QuantitySelector>
|
||||
*/
|
||||
const normalizeQuantity = useDebouncedCallback< ( val: number ) => void >(
|
||||
( initialValue ) => {
|
||||
// We copy the starting value.
|
||||
let newValue = initialValue;
|
||||
|
||||
// We check if we have a maximum value, and select the lowest between what was inserted and the maximum.
|
||||
if ( hasMaximum ) {
|
||||
newValue = Math.min(
|
||||
newValue,
|
||||
// the maximum possible value in step increments.
|
||||
Math.floor( max / step ) * step
|
||||
);
|
||||
}
|
||||
|
||||
// Select the biggest between what's inserted, the the minimum value in steps.
|
||||
newValue = Math.max( newValue, Math.ceil( min / step ) * step );
|
||||
|
||||
// We round off the value to our steps.
|
||||
newValue = Math.floor( newValue / step ) * step;
|
||||
|
||||
// Only commit if the value has changed
|
||||
if ( newValue !== initialValue ) {
|
||||
onChange?.( newValue );
|
||||
}
|
||||
},
|
||||
300
|
||||
);
|
||||
|
||||
return (
|
||||
<input
|
||||
className="wc-block-components-product-add-to-cart-quantity"
|
||||
type="number"
|
||||
value={ value }
|
||||
min={ min }
|
||||
max={ max }
|
||||
step={ step }
|
||||
hidden={ max === 1 }
|
||||
disabled={ disabled }
|
||||
onChange={ ( e ) => {
|
||||
onChange?.( e.target.value );
|
||||
normalizeQuantity( Number( e.target.value ) );
|
||||
} }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default QuantityInput;
|
||||
@@ -0,0 +1,49 @@
|
||||
.wc-block-components-product-add-to-cart {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
.wc-block-components-product-add-to-cart-button {
|
||||
margin: 0 0 em($gap-small) 0;
|
||||
|
||||
.wc-block-components-button__text {
|
||||
display: block;
|
||||
|
||||
> svg {
|
||||
fill: currentColor;
|
||||
vertical-align: top;
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
margin: -0.25em 0 -0.25em 0.5em;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.wc-block-components-product-add-to-cart-quantity {
|
||||
margin: 0 1em em($gap-small) 0;
|
||||
flex-basis: 5em;
|
||||
padding: 0.618em;
|
||||
background: $white;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 2px;
|
||||
color: #43454b;
|
||||
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.125);
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.is-loading .wc-block-components-product-add-to-cart,
|
||||
.wc-block-components-product-add-to-cart--placeholder {
|
||||
.wc-block-components-product-add-to-cart-quantity,
|
||||
.wc-block-components-product-add-to-cart-button {
|
||||
@include placeholder();
|
||||
}
|
||||
}
|
||||
|
||||
.wc-block-grid .wc-block-components-product-add-to-cart {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.wc-block-components-product-add-to-cart-notice {
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import type { BlockAttributes } from '@wordpress/blocks';
|
||||
|
||||
export const blockAttributes: BlockAttributes = {
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
isDescendentOfQueryLoop: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
textAlign: {
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
width: {
|
||||
type: 'number',
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import classnames from 'classnames';
|
||||
import { __, _n, sprintf } from '@wordpress/i18n';
|
||||
import {
|
||||
useStoreEvents,
|
||||
useStoreAddToCart,
|
||||
} from '@woocommerce/base-context/hooks';
|
||||
import {
|
||||
useBorderProps,
|
||||
useColorProps,
|
||||
useTypographyProps,
|
||||
useSpacingProps,
|
||||
} from '@woocommerce/base-hooks';
|
||||
import { decodeEntities } from '@wordpress/html-entities';
|
||||
import { CART_URL } from '@woocommerce/block-settings';
|
||||
import { getSetting } from '@woocommerce/settings';
|
||||
import {
|
||||
useInnerBlockLayoutContext,
|
||||
useProductDataContext,
|
||||
} from '@woocommerce/shared-context';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import type {
|
||||
BlockAttributes,
|
||||
AddToCartButtonAttributes,
|
||||
AddToCartButtonPlaceholderAttributes,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Product Button Block Component.
|
||||
*
|
||||
* @param {Object} props Incoming props.
|
||||
* @param {Object} [props.product] Product.
|
||||
* @param {Object} [props.colorStyles] Object contains CSS class and CSS style for color.
|
||||
* @param {Object} [props.borderStyles] Object contains CSS class and CSS style for border.
|
||||
* @param {Object} [props.typographyStyles] Object contains CSS class and CSS style for typography.
|
||||
* @param {Object} [props.spacingStyles] Object contains CSS style for spacing.
|
||||
* @param {Object} [props.textAlign] Text alignment.
|
||||
*
|
||||
* @return {*} The component.
|
||||
*/
|
||||
const AddToCartButton = ( {
|
||||
product,
|
||||
colorStyles,
|
||||
borderStyles,
|
||||
typographyStyles,
|
||||
spacingStyles,
|
||||
textAlign,
|
||||
}: AddToCartButtonAttributes ): JSX.Element => {
|
||||
const {
|
||||
id,
|
||||
permalink,
|
||||
add_to_cart: productCartDetails,
|
||||
has_options: hasOptions,
|
||||
is_purchasable: isPurchasable,
|
||||
is_in_stock: isInStock,
|
||||
} = product;
|
||||
const { dispatchStoreEvent } = useStoreEvents();
|
||||
const { cartQuantity, addingToCart, addToCart } = useStoreAddToCart( id );
|
||||
|
||||
const addedToCart = Number.isFinite( cartQuantity ) && cartQuantity > 0;
|
||||
const allowAddToCart = ! hasOptions && isPurchasable && isInStock;
|
||||
const buttonAriaLabel = decodeEntities(
|
||||
productCartDetails?.description || ''
|
||||
);
|
||||
const buttonText = addedToCart
|
||||
? sprintf(
|
||||
/* translators: %s number of products in cart. */
|
||||
_n(
|
||||
'%d in cart',
|
||||
'%d in cart',
|
||||
cartQuantity,
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
cartQuantity
|
||||
)
|
||||
: decodeEntities(
|
||||
productCartDetails?.text ||
|
||||
__( 'Add to cart', 'woo-gutenberg-products-block' )
|
||||
);
|
||||
|
||||
const ButtonTag = allowAddToCart ? 'button' : 'a';
|
||||
const buttonProps = {} as HTMLAnchorElement & { onClick: () => void };
|
||||
|
||||
if ( ! allowAddToCart ) {
|
||||
buttonProps.href = permalink;
|
||||
buttonProps.rel = 'nofollow';
|
||||
buttonProps.onClick = () => {
|
||||
dispatchStoreEvent( 'product-view-link', {
|
||||
product,
|
||||
} );
|
||||
};
|
||||
} else {
|
||||
buttonProps.onClick = async () => {
|
||||
await addToCart();
|
||||
dispatchStoreEvent( 'cart-add-item', {
|
||||
product,
|
||||
} );
|
||||
// redirect to cart if the setting to redirect to the cart page
|
||||
// on cart add item is enabled
|
||||
const { cartRedirectAfterAdd }: { cartRedirectAfterAdd: boolean } =
|
||||
getSetting( 'productsSettings' );
|
||||
if ( cartRedirectAfterAdd ) {
|
||||
window.location.href = CART_URL;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<ButtonTag
|
||||
aria-label={ buttonAriaLabel }
|
||||
className={ classnames(
|
||||
'wp-block-button__link',
|
||||
'wp-element-button',
|
||||
'add_to_cart_button',
|
||||
'wc-block-components-product-button__button',
|
||||
colorStyles.className,
|
||||
borderStyles.className,
|
||||
{
|
||||
loading: addingToCart,
|
||||
added: addedToCart,
|
||||
},
|
||||
{
|
||||
[ `has-text-align-${ textAlign }` ]: textAlign,
|
||||
}
|
||||
) }
|
||||
style={ {
|
||||
...colorStyles.style,
|
||||
...borderStyles.style,
|
||||
...typographyStyles.style,
|
||||
...spacingStyles.style,
|
||||
} }
|
||||
disabled={ addingToCart }
|
||||
{ ...buttonProps }
|
||||
>
|
||||
{ buttonText }
|
||||
</ButtonTag>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Product Button Block Component.
|
||||
*
|
||||
* @param {Object} props Incoming props.
|
||||
* @param {Object} [props.colorStyles] Object contains CSS class and CSS style for color.
|
||||
* @param {Object} [props.borderStyles] Object contains CSS class and CSS style for border.
|
||||
* @param {Object} [props.typographyStyles] Object contains CSS class and CSS style for typography.
|
||||
* @param {Object} [props.spacingStyles] Object contains CSS style for spacing.
|
||||
*
|
||||
* @return {*} The component.
|
||||
*/
|
||||
const AddToCartButtonPlaceholder = ( {
|
||||
colorStyles,
|
||||
borderStyles,
|
||||
typographyStyles,
|
||||
spacingStyles,
|
||||
}: AddToCartButtonPlaceholderAttributes ): JSX.Element => {
|
||||
return (
|
||||
<button
|
||||
className={ classnames(
|
||||
'wp-block-button__link',
|
||||
'wp-element-button',
|
||||
'add_to_cart_button',
|
||||
'wc-block-components-product-button__button',
|
||||
'wc-block-components-product-button__button--placeholder',
|
||||
colorStyles.className,
|
||||
borderStyles.className
|
||||
) }
|
||||
style={ {
|
||||
...colorStyles.style,
|
||||
...borderStyles.style,
|
||||
...typographyStyles.style,
|
||||
...spacingStyles.style,
|
||||
} }
|
||||
disabled={ true }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Product Button Block Component.
|
||||
*
|
||||
* @param {Object} props Incoming props.
|
||||
* @param {string} [props.className] CSS Class name for the component.
|
||||
* @param {string} [props.textAlign] Text alignment.
|
||||
* @return {*} The component.
|
||||
*/
|
||||
export const Block = ( props: BlockAttributes ): JSX.Element => {
|
||||
const { className, textAlign } = props;
|
||||
const { parentClassName } = useInnerBlockLayoutContext();
|
||||
const { product } = useProductDataContext();
|
||||
const colorProps = useColorProps( props );
|
||||
const borderProps = useBorderProps( props );
|
||||
const typographyProps = useTypographyProps( props );
|
||||
const spacingProps = useSpacingProps( props );
|
||||
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
className,
|
||||
'wp-block-button',
|
||||
'wc-block-components-product-button',
|
||||
{
|
||||
[ `${ parentClassName }__product-add-to-cart` ]:
|
||||
parentClassName,
|
||||
},
|
||||
{
|
||||
[ `has-text-align-${ textAlign }` ]: textAlign,
|
||||
}
|
||||
) }
|
||||
>
|
||||
{ product.id ? (
|
||||
<AddToCartButton
|
||||
product={ product }
|
||||
colorStyles={ colorProps }
|
||||
borderStyles={ borderProps }
|
||||
typographyStyles={ typographyProps }
|
||||
spacingStyles={ spacingProps }
|
||||
/>
|
||||
) : (
|
||||
<AddToCartButtonPlaceholder
|
||||
colorStyles={ colorProps }
|
||||
borderStyles={ borderProps }
|
||||
typographyStyles={ typographyProps }
|
||||
spacingStyles={ spacingProps }
|
||||
/>
|
||||
) }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductDataContext( Block );
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { Icon, button } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE: string = __(
|
||||
'Add to Cart Button',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
export const BLOCK_ICON: JSX.Element = (
|
||||
<Icon icon={ button } className="wc-block-editor-components-block-icon" />
|
||||
);
|
||||
export const BLOCK_DESCRIPTION: string = __(
|
||||
'Display a call to action button which either adds the product to the cart, or links to the product page.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
|
||||
export const BLOCK_NAME = 'woocommerce/product-button';
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import classnames from 'classnames';
|
||||
import {
|
||||
Disabled,
|
||||
Button,
|
||||
ButtonGroup,
|
||||
PanelBody,
|
||||
} from '@wordpress/components';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import {
|
||||
AlignmentToolbar,
|
||||
BlockControls,
|
||||
useBlockProps,
|
||||
InspectorControls,
|
||||
} from '@wordpress/block-editor';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
import { useEffect } from '@wordpress/element';
|
||||
import { ProductQueryContext as Context } from '@woocommerce/blocks/product-query/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import { BlockAttributes } from './types';
|
||||
|
||||
function WidthPanel( {
|
||||
selectedWidth,
|
||||
setAttributes,
|
||||
}: {
|
||||
selectedWidth: number | undefined;
|
||||
setAttributes: ( attributes: BlockAttributes ) => void;
|
||||
} ) {
|
||||
function handleChange( newWidth: number ) {
|
||||
// Check if we are toggling the width off
|
||||
const width = selectedWidth === newWidth ? undefined : newWidth;
|
||||
|
||||
// Update attributes.
|
||||
setAttributes( { width } );
|
||||
}
|
||||
|
||||
return (
|
||||
<PanelBody
|
||||
title={ __( 'Width settings', 'woo-gutenberg-products-block' ) }
|
||||
>
|
||||
<ButtonGroup
|
||||
aria-label={ __(
|
||||
'Button width',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
>
|
||||
{ [ 25, 50, 75, 100 ].map( ( widthValue ) => {
|
||||
return (
|
||||
<Button
|
||||
key={ widthValue }
|
||||
isSmall
|
||||
variant={
|
||||
widthValue === selectedWidth
|
||||
? 'primary'
|
||||
: undefined
|
||||
}
|
||||
onClick={ () => handleChange( widthValue ) }
|
||||
>
|
||||
{ widthValue }%
|
||||
</Button>
|
||||
);
|
||||
} ) }
|
||||
</ButtonGroup>
|
||||
</PanelBody>
|
||||
);
|
||||
}
|
||||
|
||||
const Edit = ( {
|
||||
attributes,
|
||||
setAttributes,
|
||||
context,
|
||||
}: BlockEditProps< BlockAttributes > & {
|
||||
context?: Context | undefined;
|
||||
} ): JSX.Element => {
|
||||
const blockProps = useBlockProps();
|
||||
const isDescendentOfQueryLoop = Number.isFinite( context?.queryId );
|
||||
const { width } = attributes;
|
||||
|
||||
useEffect(
|
||||
() => setAttributes( { isDescendentOfQueryLoop } ),
|
||||
[ setAttributes, isDescendentOfQueryLoop ]
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<BlockControls>
|
||||
{ isDescendentOfQueryLoop && (
|
||||
<AlignmentToolbar
|
||||
value={ attributes.textAlign }
|
||||
onChange={ ( newAlign ) => {
|
||||
setAttributes( { textAlign: newAlign || '' } );
|
||||
} }
|
||||
/>
|
||||
) }
|
||||
</BlockControls>
|
||||
<InspectorControls>
|
||||
<WidthPanel
|
||||
selectedWidth={ width }
|
||||
setAttributes={ setAttributes }
|
||||
/>
|
||||
</InspectorControls>
|
||||
<div { ...blockProps }>
|
||||
<Disabled>
|
||||
<Block
|
||||
{ ...{ ...attributes, ...context } }
|
||||
className={ classnames( attributes.className, {
|
||||
[ `has-custom-width wp-block-button__width-${ width }` ]:
|
||||
width,
|
||||
} ) }
|
||||
/>
|
||||
</Disabled>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockType } from '@wordpress/blocks';
|
||||
import type { BlockConfiguration } from '@wordpress/blocks';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { supports } from './supports';
|
||||
import attributes from './attributes';
|
||||
import sharedConfig from '../shared/config';
|
||||
import edit from './edit';
|
||||
import save from './save';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
BLOCK_NAME,
|
||||
} from './constants';
|
||||
|
||||
const blockConfig: BlockConfiguration = {
|
||||
...sharedConfig,
|
||||
apiVersion: 2,
|
||||
title,
|
||||
description,
|
||||
ancestor: [
|
||||
'woocommerce/all-products',
|
||||
'woocommerce/single-product',
|
||||
'core/post-template',
|
||||
],
|
||||
usesContext: [ 'query', 'queryId', 'postId' ],
|
||||
icon: { src: icon },
|
||||
attributes,
|
||||
supports,
|
||||
edit,
|
||||
save,
|
||||
styles: [
|
||||
{
|
||||
name: 'fill',
|
||||
label: __( 'Fill', 'woo-gutenberg-products-block' ),
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
name: 'outline',
|
||||
label: __( 'Outline', 'woo-gutenberg-products-block' ),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
registerBlockType( BLOCK_NAME, { ...blockConfig } );
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import classnames from 'classnames';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { BlockAttributes } from './types';
|
||||
|
||||
type Props = {
|
||||
attributes: BlockAttributes;
|
||||
};
|
||||
|
||||
const Save = ( { attributes }: Props ): JSX.Element | null => {
|
||||
if ( attributes.isDescendentOfQueryLoop ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
{ ...useBlockProps.save( {
|
||||
className: classnames( 'is-loading', attributes.className, {
|
||||
[ `has-custom-width wp-block-button__width-${ attributes.width }` ]:
|
||||
attributes.width,
|
||||
} ),
|
||||
} ) }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default Save;
|
||||
@@ -0,0 +1,74 @@
|
||||
.wp-block-button.wc-block-components-product-button {
|
||||
word-break: break-word;
|
||||
white-space: normal;
|
||||
|
||||
.wc-block-components-product-button__button {
|
||||
border-style: none;
|
||||
display: inline-flex;
|
||||
font-family: inherit;
|
||||
font-weight: inherit;
|
||||
justify-content: center;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.wc-block-components-product-button__button--placeholder {
|
||||
@include placeholder();
|
||||
min-width: 8em;
|
||||
min-height: 3em;
|
||||
}
|
||||
|
||||
.wc-block-all-products & {
|
||||
margin-bottom: $gap-small;
|
||||
}
|
||||
}
|
||||
|
||||
.is-loading .wc-block-components-product-button > .wc-block-components-product-button__button {
|
||||
@include placeholder();
|
||||
min-width: 8em;
|
||||
min-height: 3em;
|
||||
}
|
||||
|
||||
.theme-twentytwentyone {
|
||||
// Prevent buttons appearing disabled in the editor.
|
||||
.editor-styles-wrapper .wc-block-components-product-button .wp-block-button__link {
|
||||
background-color: var(--button--color-background);
|
||||
color: var(--button--color-text);
|
||||
border-color: var(--button--color-background);
|
||||
}
|
||||
}
|
||||
|
||||
// Style: Fill & Outline
|
||||
.wp-block-button.is-style-outline {
|
||||
.wp-block-button__link {
|
||||
border: 2px solid currentColor;
|
||||
|
||||
&:not(.has-text-color) {
|
||||
color: currentColor;
|
||||
}
|
||||
|
||||
&:not(.has-background) {
|
||||
background-color: transparent;
|
||||
background-image: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Width setting
|
||||
.wp-block-button {
|
||||
&.has-custom-width {
|
||||
.wp-block-button__link {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
@for $i from 1 through 4 {
|
||||
&.wp-block-button__width-#{$i * 25} {
|
||||
.wp-block-button__link {
|
||||
width: $i * 25%; // 25%, 50%, 75%, 100%
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/* eslint-disable @wordpress/no-unsafe-wp-apis */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
|
||||
import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor';
|
||||
|
||||
export const supports = {
|
||||
...( isFeaturePluginBuild() && {
|
||||
color: {
|
||||
text: true,
|
||||
background: true,
|
||||
link: false,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
__experimentalBorder: {
|
||||
radius: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
padding: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
} ),
|
||||
typography: {
|
||||
fontSize: true,
|
||||
lineHeight: true,
|
||||
__experimentalFontWeight: true,
|
||||
__experimentalFontFamily: true,
|
||||
__experimentalFontStyle: true,
|
||||
__experimentalTextTransform: true,
|
||||
__experimentalTextDecoration: true,
|
||||
__experimentalLetterSpacing: true,
|
||||
__experimentalDefaultControls: {
|
||||
fontSize: true,
|
||||
},
|
||||
},
|
||||
__experimentalSelector:
|
||||
'.wp-block-button.wc-block-components-product-button .wc-block-components-product-button__button',
|
||||
} ),
|
||||
...( typeof __experimentalGetSpacingClassesAndStyles === 'function' &&
|
||||
! isFeaturePluginBuild() && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
},
|
||||
} ),
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
interface WithClass {
|
||||
className: string;
|
||||
}
|
||||
|
||||
interface WithStyle {
|
||||
style: Record< string, unknown >;
|
||||
}
|
||||
|
||||
export interface BlockAttributes {
|
||||
className?: string | undefined;
|
||||
textAlign?: string | undefined;
|
||||
isDescendentOfQueryLoop?: boolean | undefined;
|
||||
width?: number | undefined;
|
||||
}
|
||||
|
||||
export interface AddToCartButtonPlaceholderAttributes {
|
||||
borderStyles: WithClass & WithStyle;
|
||||
colorStyles: WithClass & WithStyle;
|
||||
spacingStyles: WithStyle;
|
||||
typographyStyles: WithStyle;
|
||||
}
|
||||
|
||||
export interface AddToCartButtonAttributes
|
||||
extends AddToCartButtonPlaceholderAttributes {
|
||||
product: {
|
||||
id: number;
|
||||
permalink: string;
|
||||
add_to_cart: {
|
||||
url: string;
|
||||
description: string;
|
||||
text: string;
|
||||
};
|
||||
has_options: boolean;
|
||||
is_purchasable: boolean;
|
||||
is_in_stock: boolean;
|
||||
};
|
||||
textAlign?: ( WithClass & WithStyle ) | undefined;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import type { BlockAttributes } from '@wordpress/blocks';
|
||||
|
||||
export const blockAttributes: BlockAttributes = {
|
||||
showProductLink: {
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
},
|
||||
showSaleBadge: {
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
},
|
||||
saleBadgeAlign: {
|
||||
type: 'string',
|
||||
default: 'right',
|
||||
},
|
||||
imageSizing: {
|
||||
type: 'string',
|
||||
default: 'full-size',
|
||||
},
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
isDescendentOfQueryLoop: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
isDescendentOfSingleProductBlock: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { Fragment } from '@wordpress/element';
|
||||
import { __, sprintf } from '@wordpress/i18n';
|
||||
import classnames from 'classnames';
|
||||
import { PLACEHOLDER_IMG_SRC } from '@woocommerce/settings';
|
||||
import {
|
||||
useInnerBlockLayoutContext,
|
||||
useProductDataContext,
|
||||
} from '@woocommerce/shared-context';
|
||||
import {
|
||||
useBorderProps,
|
||||
useSpacingProps,
|
||||
useTypographyProps,
|
||||
} from '@woocommerce/base-hooks';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
import { useStoreEvents } from '@woocommerce/base-context/hooks';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import ProductSaleBadge from '../sale-badge/block';
|
||||
import './style.scss';
|
||||
import type { BlockAttributes } from './types';
|
||||
|
||||
const ImagePlaceholder = (): JSX.Element => {
|
||||
return (
|
||||
<img
|
||||
src={ PLACEHOLDER_IMG_SRC }
|
||||
alt=""
|
||||
width={ undefined }
|
||||
height={ undefined }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
interface ImageProps {
|
||||
image?: null | {
|
||||
alt?: string | undefined;
|
||||
id: number;
|
||||
name: string;
|
||||
sizes?: string | undefined;
|
||||
src?: string | undefined;
|
||||
srcset?: string | undefined;
|
||||
thumbnail?: string | undefined;
|
||||
};
|
||||
loaded: boolean;
|
||||
showFullSize: boolean;
|
||||
fallbackAlt: string;
|
||||
}
|
||||
|
||||
const Image = ( {
|
||||
image,
|
||||
loaded,
|
||||
showFullSize,
|
||||
fallbackAlt,
|
||||
}: ImageProps ): JSX.Element => {
|
||||
const { thumbnail, src, srcset, sizes, alt } = image || {};
|
||||
const imageProps = {
|
||||
alt: alt || fallbackAlt,
|
||||
hidden: ! loaded,
|
||||
src: thumbnail,
|
||||
...( showFullSize && { src, srcSet: srcset, sizes } ),
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{ imageProps.src && (
|
||||
/* eslint-disable-next-line jsx-a11y/alt-text */
|
||||
<img data-testid="product-image" { ...imageProps } />
|
||||
) }
|
||||
{ ! image && <ImagePlaceholder /> }
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
type Props = BlockAttributes & HTMLAttributes< HTMLDivElement >;
|
||||
|
||||
export const Block = ( props: Props ): JSX.Element | null => {
|
||||
const {
|
||||
className,
|
||||
imageSizing = 'full-size',
|
||||
showProductLink = true,
|
||||
showSaleBadge,
|
||||
saleBadgeAlign = 'right',
|
||||
} = props;
|
||||
const { parentClassName } = useInnerBlockLayoutContext();
|
||||
const { product, isLoading } = useProductDataContext();
|
||||
const { dispatchStoreEvent } = useStoreEvents();
|
||||
const typographyProps = useTypographyProps( props );
|
||||
const borderProps = useBorderProps( props );
|
||||
const spacingProps = useSpacingProps( props );
|
||||
|
||||
if ( ! product.id ) {
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
className,
|
||||
'wc-block-components-product-image',
|
||||
{
|
||||
[ `${ parentClassName }__product-image` ]:
|
||||
parentClassName,
|
||||
},
|
||||
borderProps.className
|
||||
) }
|
||||
style={ {
|
||||
...typographyProps.style,
|
||||
...borderProps.style,
|
||||
...spacingProps.style,
|
||||
} }
|
||||
>
|
||||
<ImagePlaceholder />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const hasProductImages = !! product.images.length;
|
||||
const image = hasProductImages ? product.images[ 0 ] : null;
|
||||
const ParentComponent = showProductLink ? 'a' : Fragment;
|
||||
const anchorLabel = sprintf(
|
||||
/* translators: %s is referring to the product name */
|
||||
__( 'Link to %s', 'woo-gutenberg-products-block' ),
|
||||
product.name
|
||||
);
|
||||
const anchorProps = {
|
||||
href: product.permalink,
|
||||
...( ! hasProductImages && { 'aria-label': anchorLabel } ),
|
||||
onClick: () => {
|
||||
dispatchStoreEvent( 'product-view-link', {
|
||||
product,
|
||||
} );
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
className,
|
||||
'wc-block-components-product-image',
|
||||
{
|
||||
[ `${ parentClassName }__product-image` ]: parentClassName,
|
||||
},
|
||||
borderProps.className
|
||||
) }
|
||||
style={ {
|
||||
...typographyProps.style,
|
||||
...borderProps.style,
|
||||
...spacingProps.style,
|
||||
} }
|
||||
>
|
||||
<ParentComponent { ...( showProductLink && anchorProps ) }>
|
||||
{ !! showSaleBadge && (
|
||||
<ProductSaleBadge
|
||||
align={ saleBadgeAlign }
|
||||
product={ product }
|
||||
/>
|
||||
) }
|
||||
<Image
|
||||
fallbackAlt={ product.name }
|
||||
image={ image }
|
||||
loaded={ ! isLoading }
|
||||
showFullSize={ imageSizing !== 'cropped' }
|
||||
/>
|
||||
</ParentComponent>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductDataContext( Block );
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { image, Icon } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE: string = __(
|
||||
'Product Image',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
export const BLOCK_ICON: JSX.Element = (
|
||||
<Icon icon={ image } className="wc-block-editor-components-block-icon" />
|
||||
);
|
||||
export const BLOCK_DESCRIPTION: string = __(
|
||||
'Display the main product image.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
|
||||
import { createInterpolateElement, useEffect } from '@wordpress/element';
|
||||
import { getAdminLink, getSettingWithCoercion } from '@woocommerce/settings';
|
||||
import { isBoolean } from '@woocommerce/types';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
import { ProductQueryContext as Context } from '@woocommerce/blocks/product-query/types';
|
||||
import {
|
||||
Disabled,
|
||||
PanelBody,
|
||||
ToggleControl,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore - Ignoring because `__experimentalToggleGroupControl` is not yet in the type definitions.
|
||||
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
|
||||
__experimentalToggleGroupControl as ToggleGroupControl,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore - Ignoring because `__experimentalToggleGroupControl` is not yet in the type definitions.
|
||||
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
|
||||
__experimentalToggleGroupControlOption as ToggleGroupControlOption,
|
||||
} from '@wordpress/components';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import withProductSelector from '../shared/with-product-selector';
|
||||
import {
|
||||
BLOCK_TITLE as label,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
import type { BlockAttributes } from './types';
|
||||
|
||||
type SaleBadgeAlignProps = 'left' | 'center' | 'right';
|
||||
type ImageSizingProps = 'full-size' | 'cropped';
|
||||
|
||||
const Edit = ( {
|
||||
attributes,
|
||||
setAttributes,
|
||||
context,
|
||||
}: BlockEditProps< BlockAttributes > & { context: Context } ): JSX.Element => {
|
||||
const { showProductLink, imageSizing, showSaleBadge, saleBadgeAlign } =
|
||||
attributes;
|
||||
const blockProps = useBlockProps();
|
||||
const isDescendentOfQueryLoop = Number.isFinite( context.queryId );
|
||||
const isBlockThemeEnabled = getSettingWithCoercion(
|
||||
'is_block_theme_enabled',
|
||||
false,
|
||||
isBoolean
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => setAttributes( { isDescendentOfQueryLoop } ),
|
||||
[ setAttributes, isDescendentOfQueryLoop ]
|
||||
);
|
||||
|
||||
useEffect( () => {
|
||||
if ( isBlockThemeEnabled && attributes.imageSizing !== 'full-size' ) {
|
||||
setAttributes( { imageSizing: 'full-size' } );
|
||||
}
|
||||
}, [ attributes.imageSizing, isBlockThemeEnabled, setAttributes ] );
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<InspectorControls>
|
||||
<PanelBody
|
||||
title={ __( 'Content', 'woo-gutenberg-products-block' ) }
|
||||
>
|
||||
<ToggleControl
|
||||
label={ __(
|
||||
'Link to Product Page',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
help={ __(
|
||||
'Links the image to the single product listing.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
checked={ showProductLink }
|
||||
onChange={ () =>
|
||||
setAttributes( {
|
||||
showProductLink: ! showProductLink,
|
||||
} )
|
||||
}
|
||||
/>
|
||||
<ToggleControl
|
||||
label={ __(
|
||||
'Show On-Sale Badge',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
help={ __(
|
||||
'Display a “sale” badge if the product is on-sale.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
checked={ showSaleBadge }
|
||||
onChange={ () =>
|
||||
setAttributes( {
|
||||
showSaleBadge: ! showSaleBadge,
|
||||
} )
|
||||
}
|
||||
/>
|
||||
{ showSaleBadge && (
|
||||
<ToggleGroupControl
|
||||
label={ __(
|
||||
'Sale Badge Alignment',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
value={ saleBadgeAlign }
|
||||
onChange={ ( value: SaleBadgeAlignProps ) =>
|
||||
setAttributes( { saleBadgeAlign: value } )
|
||||
}
|
||||
>
|
||||
<ToggleGroupControlOption
|
||||
value="left"
|
||||
label={ __(
|
||||
'Left',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
<ToggleGroupControlOption
|
||||
value="center"
|
||||
label={ __(
|
||||
'Center',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
<ToggleGroupControlOption
|
||||
value="right"
|
||||
label={ __(
|
||||
'Right',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
</ToggleGroupControl>
|
||||
) }
|
||||
{ ! isBlockThemeEnabled && (
|
||||
<ToggleGroupControl
|
||||
label={ __(
|
||||
'Image Sizing',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
help={ createInterpolateElement(
|
||||
__(
|
||||
'Product image cropping can be modified in the <a>Customizer</a>.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
{
|
||||
a: (
|
||||
// eslint-disable-next-line jsx-a11y/anchor-has-content
|
||||
<a
|
||||
href={ `${ getAdminLink(
|
||||
'customize.php'
|
||||
) }?autofocus[panel]=woocommerce&autofocus[section]=woocommerce_product_images` }
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
/>
|
||||
),
|
||||
}
|
||||
) }
|
||||
value={ imageSizing }
|
||||
onChange={ ( value: ImageSizingProps ) =>
|
||||
setAttributes( { imageSizing: value } )
|
||||
}
|
||||
>
|
||||
<ToggleGroupControlOption
|
||||
value="full-size"
|
||||
label={ __(
|
||||
'Full Size',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
<ToggleGroupControlOption
|
||||
value="cropped"
|
||||
label={ __(
|
||||
'Cropped',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
</ToggleGroupControl>
|
||||
) }
|
||||
</PanelBody>
|
||||
</InspectorControls>
|
||||
<Disabled>
|
||||
<Block { ...{ ...attributes, ...context } } />
|
||||
</Disabled>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductSelector( { icon, label, description } )( Edit );
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { withFilteredAttributes } from '@woocommerce/shared-hocs';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import attributes from './attributes';
|
||||
|
||||
export default withFilteredAttributes( attributes )( Block );
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockType } from '@wordpress/blocks';
|
||||
import type { BlockConfiguration } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import edit from './edit';
|
||||
|
||||
import { supports } from './supports';
|
||||
import attributes from './attributes';
|
||||
import sharedConfig from '../shared/config';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
|
||||
const blockConfig: BlockConfiguration = {
|
||||
...sharedConfig,
|
||||
apiVersion: 2,
|
||||
name: 'woocommerce/product-image',
|
||||
title,
|
||||
icon: { src: icon },
|
||||
keywords: [ 'WooCommerce' ],
|
||||
description,
|
||||
usesContext: [ 'query', 'queryId', 'postId' ],
|
||||
ancestor: [
|
||||
'woocommerce/all-products',
|
||||
'woocommerce/single-product',
|
||||
'core/post-template',
|
||||
],
|
||||
textdomain: 'woo-gutenberg-products-block',
|
||||
attributes,
|
||||
supports,
|
||||
edit,
|
||||
};
|
||||
|
||||
registerBlockType( 'woocommerce/product-image', { ...blockConfig } );
|
||||
@@ -0,0 +1,62 @@
|
||||
.editor-styles-wrapper .wc-block-grid__products .wc-block-grid__product .wc-block-components-product-image,
|
||||
.wc-block-components-product-image {
|
||||
text-decoration: none;
|
||||
display: block;
|
||||
position: relative;
|
||||
|
||||
a {
|
||||
border-radius: inherit;
|
||||
text-decoration: none;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
img {
|
||||
border-radius: inherit;
|
||||
vertical-align: middle;
|
||||
width: 100%;
|
||||
|
||||
&[hidden] {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
img[alt=""] {
|
||||
border: 1px solid $image-placeholder-border-color;
|
||||
}
|
||||
|
||||
.wc-block-components-product-sale-badge {
|
||||
&--align-left {
|
||||
position: absolute;
|
||||
left: $gap-smaller * 0.5;
|
||||
top: $gap-smaller * 0.5;
|
||||
right: auto;
|
||||
margin: 0;
|
||||
}
|
||||
&--align-center {
|
||||
position: absolute;
|
||||
top: $gap-smaller * 0.5;
|
||||
left: 50%;
|
||||
right: auto;
|
||||
transform: translateX(-50%);
|
||||
margin: 0;
|
||||
}
|
||||
&--align-right {
|
||||
position: absolute;
|
||||
right: $gap-smaller * 0.5;
|
||||
top: $gap-smaller * 0.5;
|
||||
left: auto;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.is-loading .wc-block-components-product-image {
|
||||
@include placeholder($include-border-radius: false);
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.wc-block-components-product-image {
|
||||
margin: 0 0 $gap-small;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/* eslint-disable @wordpress/no-unsafe-wp-apis */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
|
||||
import { __experimentalGetSpacingClassesAndStyles as getSpacingClassesAndStyles } from '@wordpress/block-editor';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
|
||||
export const supports = {
|
||||
html: false,
|
||||
...( isFeaturePluginBuild() && {
|
||||
__experimentalBorder: {
|
||||
radius: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
typography: {
|
||||
fontSize: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
...( typeof getSpacingClassesAndStyles === 'function' && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
padding: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
} ),
|
||||
__experimentalSelector: '.wc-block-components-product-image',
|
||||
} ),
|
||||
};
|
||||
@@ -0,0 +1,294 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { render, fireEvent } from '@testing-library/react';
|
||||
import { ProductDataContextProvider } from '@woocommerce/shared-context';
|
||||
import { ProductResponseItem } from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import { Block } from '../block';
|
||||
|
||||
jest.mock( '@woocommerce/base-hooks', () => ( {
|
||||
__esModule: true,
|
||||
useBorderProps: jest.fn( () => ( {
|
||||
className: '',
|
||||
style: {},
|
||||
} ) ),
|
||||
useTypographyProps: jest.fn( () => ( {
|
||||
style: {},
|
||||
} ) ),
|
||||
useSpacingProps: jest.fn( () => ( {
|
||||
style: {},
|
||||
} ) ),
|
||||
} ) );
|
||||
|
||||
const productWithoutImages: ProductResponseItem = {
|
||||
name: 'Test product',
|
||||
id: 1,
|
||||
permalink: 'http://test.com/product/test-product/',
|
||||
images: [],
|
||||
parent: 0,
|
||||
type: '',
|
||||
variation: '',
|
||||
sku: '',
|
||||
short_description: '',
|
||||
description: '',
|
||||
on_sale: false,
|
||||
prices: {
|
||||
currency_code: 'USD',
|
||||
currency_symbol: '',
|
||||
currency_minor_unit: 0,
|
||||
currency_decimal_separator: '',
|
||||
currency_thousand_separator: '',
|
||||
currency_prefix: '',
|
||||
currency_suffix: '',
|
||||
price: '',
|
||||
regular_price: '',
|
||||
sale_price: '',
|
||||
price_range: null,
|
||||
},
|
||||
price_html: '',
|
||||
average_rating: '',
|
||||
review_count: 0,
|
||||
categories: [],
|
||||
tags: [],
|
||||
attributes: [],
|
||||
variations: [],
|
||||
has_options: false,
|
||||
is_purchasable: false,
|
||||
is_in_stock: false,
|
||||
is_on_backorder: false,
|
||||
low_stock_remaining: null,
|
||||
sold_individually: false,
|
||||
add_to_cart: {
|
||||
text: '',
|
||||
description: '',
|
||||
url: '',
|
||||
minimum: 0,
|
||||
maximum: 0,
|
||||
multiple_of: 0,
|
||||
},
|
||||
};
|
||||
|
||||
const productWithImages: ProductResponseItem = {
|
||||
name: 'Test product',
|
||||
id: 1,
|
||||
permalink: 'http://test.com/product/test-product/',
|
||||
images: [
|
||||
{
|
||||
id: 56,
|
||||
src: 'logo-1.jpg',
|
||||
thumbnail: 'logo-1-324x324.jpg',
|
||||
srcset: 'logo-1.jpg 800w, logo-1-300x300.jpg 300w, logo-1-150x150.jpg 150w, logo-1-768x767.jpg 768w, logo-1-324x324.jpg 324w, logo-1-416x415.jpg 416w, logo-1-100x100.jpg 100w',
|
||||
sizes: '(max-width: 800px) 100vw, 800px',
|
||||
name: 'logo-1.jpg',
|
||||
alt: '',
|
||||
},
|
||||
{
|
||||
id: 55,
|
||||
src: 'beanie-with-logo-1.jpg',
|
||||
thumbnail: 'beanie-with-logo-1-324x324.jpg',
|
||||
srcset: 'beanie-with-logo-1.jpg 800w, beanie-with-logo-1-300x300.jpg 300w, beanie-with-logo-1-150x150.jpg 150w, beanie-with-logo-1-768x768.jpg 768w, beanie-with-logo-1-324x324.jpg 324w, beanie-with-logo-1-416x416.jpg 416w, beanie-with-logo-1-100x100.jpg 100w',
|
||||
sizes: '(max-width: 800px) 100vw, 800px',
|
||||
name: 'beanie-with-logo-1.jpg',
|
||||
alt: '',
|
||||
},
|
||||
],
|
||||
parent: 0,
|
||||
type: '',
|
||||
variation: '',
|
||||
sku: '',
|
||||
short_description: '',
|
||||
description: '',
|
||||
on_sale: false,
|
||||
prices: {
|
||||
currency_code: 'USD',
|
||||
currency_symbol: '',
|
||||
currency_minor_unit: 0,
|
||||
currency_decimal_separator: '',
|
||||
currency_thousand_separator: '',
|
||||
currency_prefix: '',
|
||||
currency_suffix: '',
|
||||
price: '',
|
||||
regular_price: '',
|
||||
sale_price: '',
|
||||
price_range: null,
|
||||
},
|
||||
price_html: '',
|
||||
average_rating: '',
|
||||
review_count: 0,
|
||||
categories: [],
|
||||
tags: [],
|
||||
attributes: [],
|
||||
variations: [],
|
||||
has_options: false,
|
||||
is_purchasable: false,
|
||||
is_in_stock: false,
|
||||
is_on_backorder: false,
|
||||
low_stock_remaining: null,
|
||||
sold_individually: false,
|
||||
add_to_cart: {
|
||||
text: '',
|
||||
description: '',
|
||||
url: '',
|
||||
minimum: 0,
|
||||
maximum: 0,
|
||||
multiple_of: 0,
|
||||
},
|
||||
};
|
||||
|
||||
describe( 'Product Image Block', () => {
|
||||
describe( 'with product link', () => {
|
||||
test( 'should render an anchor with the product image', () => {
|
||||
const component = render(
|
||||
<ProductDataContextProvider
|
||||
product={ productWithImages }
|
||||
isLoading={ false }
|
||||
>
|
||||
<Block
|
||||
showProductLink={ true }
|
||||
productId={ productWithImages.id }
|
||||
showSaleBadge={ false }
|
||||
saleBadgeAlign={ 'left' }
|
||||
imageSizing={ 'full-size' }
|
||||
isDescendentOfQueryLoop={ false }
|
||||
/>
|
||||
</ProductDataContextProvider>
|
||||
);
|
||||
|
||||
// use testId as alt is added after image is loaded
|
||||
const image = component.getByTestId( 'product-image' );
|
||||
fireEvent.load( image );
|
||||
|
||||
const productImage = component.getByAltText(
|
||||
productWithImages.name
|
||||
);
|
||||
expect( productImage.getAttribute( 'src' ) ).toBe(
|
||||
productWithImages.images[ 0 ].src
|
||||
);
|
||||
|
||||
const anchor = productImage.closest( 'a' );
|
||||
expect( anchor?.getAttribute( 'href' ) ).toBe(
|
||||
productWithImages.permalink
|
||||
);
|
||||
} );
|
||||
|
||||
test( 'should render an anchor with the placeholder image', () => {
|
||||
const component = render(
|
||||
<ProductDataContextProvider
|
||||
product={ productWithoutImages }
|
||||
isLoading={ false }
|
||||
>
|
||||
<Block
|
||||
showProductLink={ true }
|
||||
productId={ productWithoutImages.id }
|
||||
showSaleBadge={ false }
|
||||
saleBadgeAlign={ 'left' }
|
||||
imageSizing={ 'full-size' }
|
||||
isDescendentOfQueryLoop={ false }
|
||||
/>
|
||||
</ProductDataContextProvider>
|
||||
);
|
||||
|
||||
const placeholderImage = component.getByAltText( '' );
|
||||
expect( placeholderImage.getAttribute( 'src' ) ).toBe(
|
||||
'placeholder.jpg'
|
||||
);
|
||||
|
||||
const anchor = placeholderImage.closest( 'a' );
|
||||
expect( anchor?.getAttribute( 'href' ) ).toBe(
|
||||
productWithoutImages.permalink
|
||||
);
|
||||
expect( anchor?.getAttribute( 'aria-label' ) ).toBe(
|
||||
`Link to ${ productWithoutImages.name }`
|
||||
);
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'without product link', () => {
|
||||
test( 'should render the product image without an anchor wrapper', () => {
|
||||
const component = render(
|
||||
<ProductDataContextProvider
|
||||
product={ productWithImages }
|
||||
isLoading={ false }
|
||||
>
|
||||
<Block
|
||||
showProductLink={ false }
|
||||
productId={ productWithImages.id }
|
||||
showSaleBadge={ false }
|
||||
saleBadgeAlign={ 'left' }
|
||||
imageSizing={ 'full-size' }
|
||||
isDescendentOfQueryLoop={ false }
|
||||
/>
|
||||
</ProductDataContextProvider>
|
||||
);
|
||||
const image = component.getByTestId( 'product-image' );
|
||||
fireEvent.load( image );
|
||||
|
||||
const productImage = component.getByAltText(
|
||||
productWithImages.name
|
||||
);
|
||||
expect( productImage.getAttribute( 'src' ) ).toBe(
|
||||
productWithImages.images[ 0 ].src
|
||||
);
|
||||
|
||||
const anchor = productImage.closest( 'a' );
|
||||
expect( anchor ).toBe( null );
|
||||
} );
|
||||
|
||||
test( 'should render the placeholder image without an anchor wrapper', () => {
|
||||
const component = render(
|
||||
<ProductDataContextProvider
|
||||
product={ productWithoutImages }
|
||||
isLoading={ false }
|
||||
>
|
||||
<Block
|
||||
showProductLink={ false }
|
||||
productId={ productWithoutImages.id }
|
||||
showSaleBadge={ false }
|
||||
saleBadgeAlign={ 'left' }
|
||||
imageSizing={ 'full-size' }
|
||||
isDescendentOfQueryLoop={ false }
|
||||
/>
|
||||
</ProductDataContextProvider>
|
||||
);
|
||||
|
||||
const placeholderImage = component.getByAltText( '' );
|
||||
expect( placeholderImage.getAttribute( 'src' ) ).toBe(
|
||||
'placeholder.jpg'
|
||||
);
|
||||
|
||||
const anchor = placeholderImage.closest( 'a' );
|
||||
expect( anchor ).toBe( null );
|
||||
} );
|
||||
} );
|
||||
|
||||
describe( 'without image', () => {
|
||||
test( 'should render the placeholder with no inline width or height attributes', () => {
|
||||
const component = render(
|
||||
<ProductDataContextProvider
|
||||
product={ productWithoutImages }
|
||||
isLoading={ false }
|
||||
>
|
||||
<Block
|
||||
showProductLink={ true }
|
||||
productId={ productWithoutImages.id }
|
||||
showSaleBadge={ false }
|
||||
saleBadgeAlign={ 'left' }
|
||||
imageSizing={ 'full-size' }
|
||||
isDescendentOfQueryLoop={ false }
|
||||
/>
|
||||
</ProductDataContextProvider>
|
||||
);
|
||||
|
||||
const placeholderImage = component.getByAltText( '' );
|
||||
expect( placeholderImage.getAttribute( 'src' ) ).toBe(
|
||||
'placeholder.jpg'
|
||||
);
|
||||
expect( placeholderImage.getAttribute( 'width' ) ).toBe( null );
|
||||
expect( placeholderImage.getAttribute( 'height' ) ).toBe( null );
|
||||
} );
|
||||
} );
|
||||
} );
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface BlockAttributes {
|
||||
// The product ID.
|
||||
productId: number;
|
||||
// CSS Class name for the component.
|
||||
className?: string | undefined;
|
||||
// Whether or not to display a link to the product page.
|
||||
showProductLink: boolean;
|
||||
// Whether or not to display the on sale badge.
|
||||
showSaleBadge: boolean;
|
||||
// How should the sale badge be aligned if displayed.
|
||||
saleBadgeAlign: 'left' | 'center' | 'right';
|
||||
// Size of image to use.
|
||||
imageSizing: 'full-size' | 'cropped';
|
||||
// Whether or not be a children of Query Loop Block.
|
||||
isDescendentOfQueryLoop: boolean;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { BlockAttributes } from '@wordpress/blocks';
|
||||
|
||||
export const blockAttributes: BlockAttributes = {
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
isDescendentOfQueryLoop: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
textAlign: {
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
isDescendentOfSingleProductTemplate: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
isDescendentOfSingleProductBlock: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import classnames from 'classnames';
|
||||
import ProductPrice from '@woocommerce/base-components/product-price';
|
||||
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
|
||||
import {
|
||||
useInnerBlockLayoutContext,
|
||||
useProductDataContext,
|
||||
} from '@woocommerce/shared-context';
|
||||
import {
|
||||
useColorProps,
|
||||
useSpacingProps,
|
||||
useTypographyProps,
|
||||
} from '@woocommerce/base-hooks';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
import { CurrencyCode } from '@woocommerce/type-defs/currency';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import type { BlockAttributes } from './types';
|
||||
import './style.scss';
|
||||
|
||||
type Props = BlockAttributes & HTMLAttributes< HTMLDivElement >;
|
||||
|
||||
interface PriceProps {
|
||||
currency_code: CurrencyCode;
|
||||
currency_symbol: string;
|
||||
currency_minor_unit: number;
|
||||
currency_decimal_separator: string;
|
||||
currency_thousand_separator: string;
|
||||
currency_prefix: string;
|
||||
currency_suffix: string;
|
||||
price: string;
|
||||
regular_price: string;
|
||||
sale_price: string;
|
||||
price_range: null | { min_amount: string; max_amount: string };
|
||||
}
|
||||
|
||||
export const Block = ( props: Props ): JSX.Element | null => {
|
||||
const { className, textAlign, isDescendentOfSingleProductTemplate } = props;
|
||||
const { parentClassName } = useInnerBlockLayoutContext();
|
||||
const { product } = useProductDataContext();
|
||||
|
||||
const colorProps = useColorProps( props );
|
||||
const spacingProps = useSpacingProps( props );
|
||||
const typographyProps = useTypographyProps( props );
|
||||
|
||||
const wrapperClassName = classnames(
|
||||
'wc-block-components-product-price',
|
||||
className,
|
||||
colorProps.className,
|
||||
{
|
||||
[ `${ parentClassName }__product-price` ]: parentClassName,
|
||||
},
|
||||
typographyProps.className
|
||||
);
|
||||
|
||||
if ( ! product.id && ! isDescendentOfSingleProductTemplate ) {
|
||||
return (
|
||||
<ProductPrice align={ textAlign } className={ wrapperClassName } />
|
||||
);
|
||||
}
|
||||
|
||||
const style = {
|
||||
...colorProps.style,
|
||||
...typographyProps.style,
|
||||
};
|
||||
const spacingStyle = {
|
||||
...spacingProps.style,
|
||||
};
|
||||
const prices: PriceProps = product.prices;
|
||||
const currency = isDescendentOfSingleProductTemplate
|
||||
? getCurrencyFromPriceResponse()
|
||||
: getCurrencyFromPriceResponse( prices );
|
||||
|
||||
const pricePreview = '5000';
|
||||
const isOnSale = prices.price !== prices.regular_price;
|
||||
const priceClassName = classnames( {
|
||||
[ `${ parentClassName }__product-price__value` ]: parentClassName,
|
||||
[ `${ parentClassName }__product-price__value--on-sale` ]: isOnSale,
|
||||
} );
|
||||
|
||||
return (
|
||||
<ProductPrice
|
||||
align={ textAlign }
|
||||
className={ wrapperClassName }
|
||||
regularPriceStyle={ style }
|
||||
priceStyle={ style }
|
||||
priceClassName={ priceClassName }
|
||||
currency={ currency }
|
||||
price={
|
||||
isDescendentOfSingleProductTemplate
|
||||
? pricePreview
|
||||
: prices.price
|
||||
}
|
||||
// Range price props
|
||||
minPrice={ prices?.price_range?.min_amount }
|
||||
maxPrice={ prices?.price_range?.max_amount }
|
||||
// This is the regular or original price when the `price` value is a sale price.
|
||||
regularPrice={
|
||||
isDescendentOfSingleProductTemplate
|
||||
? pricePreview
|
||||
: prices.regular_price
|
||||
}
|
||||
regularPriceClassName={ classnames( {
|
||||
[ `${ parentClassName }__product-price__regular` ]:
|
||||
parentClassName,
|
||||
} ) }
|
||||
spacingStyle={ spacingStyle }
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default ( props: Props ) => {
|
||||
// It is necessary because this block has to support serveral contexts:
|
||||
// - Inside `All Products Block` -> `withProductDataContext` HOC
|
||||
// - Inside `Products Block` -> Gutenberg Context
|
||||
// - Inside `Single Product Template` -> Gutenberg Context
|
||||
// - Without any parent -> `WithSelector` and `withProductDataContext` HOCs
|
||||
// For more details, check https://github.com/woocommerce/woocommerce-blocks/pull/8609
|
||||
if ( props.isDescendentOfSingleProductTemplate ) {
|
||||
return <Block { ...props } />;
|
||||
}
|
||||
return withProductDataContext( Block )( props );
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { currencyDollar, Icon } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE: string = __(
|
||||
'Product Price',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
export const BLOCK_ICON: JSX.Element = (
|
||||
<Icon
|
||||
icon={ currencyDollar }
|
||||
className="wc-block-editor-components-block-icon"
|
||||
/>
|
||||
);
|
||||
export const BLOCK_DESCRIPTION: string = __(
|
||||
'Display the price of a product.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import {
|
||||
AlignmentToolbar,
|
||||
BlockControls,
|
||||
useBlockProps,
|
||||
} from '@wordpress/block-editor';
|
||||
import { useEffect } from '@wordpress/element';
|
||||
import type { BlockAlignment } from '@wordpress/blocks';
|
||||
import { useSelect } from '@wordpress/data';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
|
||||
type UnsupportedAligments = 'wide' | 'full';
|
||||
type AllowedAlignments = Exclude< BlockAlignment, UnsupportedAligments >;
|
||||
|
||||
interface BlockAttributes {
|
||||
textAlign?: AllowedAlignments;
|
||||
}
|
||||
|
||||
interface Attributes {
|
||||
textAlign: 'left' | 'center' | 'right';
|
||||
isDescendentOfSingleProduct: boolean;
|
||||
isDescendentOfSingleProductBlock: boolean;
|
||||
productId: number;
|
||||
}
|
||||
|
||||
interface Context {
|
||||
queryId: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
attributes: Attributes;
|
||||
setAttributes: (
|
||||
attributes: Partial< BlockAttributes > & Record< string, unknown >
|
||||
) => void;
|
||||
context: Context;
|
||||
}
|
||||
|
||||
const PriceEdit = ( {
|
||||
attributes,
|
||||
setAttributes,
|
||||
context,
|
||||
}: Props ): JSX.Element => {
|
||||
const blockProps = useBlockProps();
|
||||
const blockAttrs = {
|
||||
...attributes,
|
||||
...context,
|
||||
};
|
||||
const isDescendentOfQueryLoop = Number.isFinite( context.queryId );
|
||||
|
||||
const isDescendentOfSingleProductTemplate = useSelect(
|
||||
( select ) => {
|
||||
const store = select( 'core/edit-site' );
|
||||
const postId = store?.getEditedPostId< string | undefined >();
|
||||
|
||||
return (
|
||||
postId?.includes( '//single-product' ) &&
|
||||
! isDescendentOfQueryLoop
|
||||
);
|
||||
},
|
||||
[ isDescendentOfQueryLoop ]
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
setAttributes( {
|
||||
isDescendentOfQueryLoop,
|
||||
isDescendentOfSingleProductTemplate,
|
||||
} ),
|
||||
[
|
||||
isDescendentOfQueryLoop,
|
||||
isDescendentOfSingleProductTemplate,
|
||||
setAttributes,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<BlockControls>
|
||||
<AlignmentToolbar
|
||||
value={ attributes.textAlign }
|
||||
onChange={ ( textAlign: AllowedAlignments ) => {
|
||||
setAttributes( { textAlign } );
|
||||
} }
|
||||
/>
|
||||
</BlockControls>
|
||||
<div { ...blockProps }>
|
||||
<Block { ...blockAttrs } />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PriceEdit;
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockType } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import sharedConfig from '../shared/config';
|
||||
import edit from './edit';
|
||||
import attributes from './attributes';
|
||||
import { supports } from './supports';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
|
||||
const { ancestor, ...configuration } = sharedConfig;
|
||||
|
||||
const blockConfig = {
|
||||
...configuration,
|
||||
apiVersion: 2,
|
||||
title,
|
||||
description,
|
||||
usesContext: [ 'query', 'queryId', 'postId' ],
|
||||
icon: { src: icon },
|
||||
attributes,
|
||||
supports,
|
||||
edit,
|
||||
};
|
||||
|
||||
registerBlockType( 'woocommerce/product-price', blockConfig );
|
||||
@@ -0,0 +1,7 @@
|
||||
.wc-block-components-product-price {
|
||||
display: block;
|
||||
|
||||
.wc-block-all-products & {
|
||||
margin-bottom: $gap-small;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
|
||||
import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import sharedConfig from '../shared/config';
|
||||
|
||||
export const supports = {
|
||||
...sharedConfig.supports,
|
||||
...( isFeaturePluginBuild() && {
|
||||
color: {
|
||||
text: true,
|
||||
background: true,
|
||||
link: false,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
typography: {
|
||||
fontSize: true,
|
||||
lineHeight: true,
|
||||
__experimentalFontFamily: true,
|
||||
__experimentalFontWeight: true,
|
||||
__experimentalFontStyle: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
__experimentalLetterSpacing: true,
|
||||
},
|
||||
__experimentalSelector: '.wc-block-components-product-price',
|
||||
} ),
|
||||
...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
padding: true,
|
||||
},
|
||||
} ),
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface BlockAttributes {
|
||||
productId?: number;
|
||||
className?: string;
|
||||
textAlign?: 'left' | 'center' | 'right';
|
||||
isDescendentOfQueryLoop?: boolean;
|
||||
isDescendentOfSingleProductTemplate?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "woocommerce/product-details",
|
||||
"version": "1.0.0",
|
||||
"icon": "info",
|
||||
"title": "Product Details",
|
||||
"description": "A block that allows your customers to see details and reviews about the product.",
|
||||
"category": "woocommerce",
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"supports": {
|
||||
"align": true
|
||||
},
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import classnames from 'classnames';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
|
||||
interface SingleProductTab {
|
||||
id: string;
|
||||
title: string;
|
||||
active: boolean;
|
||||
content: string | undefined;
|
||||
}
|
||||
|
||||
const ProductTabTitle = ( {
|
||||
id,
|
||||
title,
|
||||
active,
|
||||
}: Pick< SingleProductTab, 'id' | 'title' | 'active' > ) => {
|
||||
return (
|
||||
<li
|
||||
className={ classnames( `${ id }_tab`, {
|
||||
active,
|
||||
} ) }
|
||||
id={ `tab-title-${ id }` }
|
||||
role="tab"
|
||||
aria-controls={ `tab-${ id }` }
|
||||
>
|
||||
<a href={ `#tab-${ id }` }>{ title }</a>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const ProductTabContent = ( {
|
||||
id,
|
||||
content,
|
||||
}: Pick< SingleProductTab, 'id' | 'content' > ) => {
|
||||
return (
|
||||
<div
|
||||
className={ `${ id }_tab` }
|
||||
id={ `tab-title-${ id }` }
|
||||
role="tab"
|
||||
aria-controls={ `tab-${ id }` }
|
||||
>
|
||||
{ content }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const SingleProductDetails = () => {
|
||||
const blockProps = useBlockProps();
|
||||
const productTabs = [
|
||||
{
|
||||
id: 'description',
|
||||
title: 'Description',
|
||||
active: true,
|
||||
content: __(
|
||||
'This block lists description, attributes and reviews for a single product.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'additional_information',
|
||||
title: 'Additional Information',
|
||||
active: false,
|
||||
},
|
||||
{ id: 'reviews', title: 'Reviews', active: false },
|
||||
];
|
||||
const tabsTitle = productTabs.map( ( { id, title, active } ) => (
|
||||
<ProductTabTitle
|
||||
key={ id }
|
||||
id={ id }
|
||||
title={ title }
|
||||
active={ active }
|
||||
/>
|
||||
) );
|
||||
const tabsContent = productTabs.map( ( { id, content } ) => (
|
||||
<ProductTabContent key={ id } id={ id } content={ content } />
|
||||
) );
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<ul className="wc-tabs tabs" role="tablist">
|
||||
{ tabsTitle }
|
||||
</ul>
|
||||
{ tabsContent }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SingleProductDetails;
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import { Disabled } from '@wordpress/components';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import { Attributes } from './types';
|
||||
|
||||
const Edit = ( { attributes }: BlockEditProps< Attributes > ) => {
|
||||
const { className } = attributes;
|
||||
const blockProps = useBlockProps( {
|
||||
className,
|
||||
} );
|
||||
|
||||
return (
|
||||
<>
|
||||
<div { ...blockProps }>
|
||||
<Disabled>
|
||||
<Block />
|
||||
</Disabled>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import metadata from './block.json';
|
||||
import edit from './edit';
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core
|
||||
blockMetadata: metadata,
|
||||
blockSettings: {
|
||||
edit,
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
},
|
||||
} );
|
||||
@@ -0,0 +1,38 @@
|
||||
.wp-block-woocommerce-product-details {
|
||||
ul.wc-tabs {
|
||||
list-style: none;
|
||||
padding: 0 0 0 1em;
|
||||
margin: 0 0 1.618em;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
border-bottom: 1px solid $gray-200;
|
||||
|
||||
li {
|
||||
border: 1px solid $gray-200;
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
border-radius: 4px 4px 0 0;
|
||||
margin: 0;
|
||||
padding: 0.5em 1em;
|
||||
|
||||
a {
|
||||
display: inline-block;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
&.active {
|
||||
z-index: 2;
|
||||
|
||||
a {
|
||||
text-shadow: inherit;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface Attributes {
|
||||
className?: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "woocommerce/product-image-gallery",
|
||||
"version": "1.0.0",
|
||||
"title": "Product Image Gallery",
|
||||
"icon": "gallery",
|
||||
"description": "Display a product's images.",
|
||||
"category": "woocommerce",
|
||||
"supports": {
|
||||
"align": true,
|
||||
"multiple": false
|
||||
},
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"usesContext": [ "postId", "postType", "queryId" ],
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { WC_BLOCKS_IMAGE_URL } from '@woocommerce/block-settings';
|
||||
import { isEmptyObject } from '@woocommerce/types';
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import { BlockAttributes } from '@wordpress/blocks';
|
||||
import { Disabled } from '@wordpress/components';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './editor.scss';
|
||||
|
||||
const Placeholder = () => {
|
||||
return (
|
||||
<div className="wc-block-editor-product-gallery">
|
||||
<img
|
||||
src={ `${ WC_BLOCKS_IMAGE_URL }block-placeholders/product-image-gallery.svg` }
|
||||
alt="Placeholder"
|
||||
/>
|
||||
<div className="wc-block-editor-product-gallery__other-images">
|
||||
{ [ ...Array( 4 ).keys() ].map( ( index ) => {
|
||||
return (
|
||||
<img
|
||||
key={ index }
|
||||
src={ `${ WC_BLOCKS_IMAGE_URL }block-placeholders/product-image-gallery.svg` }
|
||||
alt="Placeholder"
|
||||
/>
|
||||
);
|
||||
} ) }
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type Context = {
|
||||
postId: string;
|
||||
postType: string;
|
||||
queryId: string;
|
||||
};
|
||||
|
||||
interface Props extends BlockEditProps< BlockAttributes > {
|
||||
context: Context;
|
||||
}
|
||||
|
||||
const Edit = ( { context }: Props ) => {
|
||||
const blockProps = useBlockProps();
|
||||
|
||||
if ( isEmptyObject( context ) ) {
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<Disabled>
|
||||
<Placeholder />
|
||||
</Disabled>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// We have work on this case when we will work on the Single Product block.
|
||||
return <></>;
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,14 @@
|
||||
.wc-block-editor-product-gallery {
|
||||
img {
|
||||
max-width: 500px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
.wc-block-editor-product-gallery__other-images {
|
||||
img {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
margin: 5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { gallery as icon } from '@wordpress/icons';
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import edit from './edit';
|
||||
import metadata from './block.json';
|
||||
import './style.scss';
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core
|
||||
blockMetadata: metadata,
|
||||
blockSettings: {
|
||||
icon,
|
||||
// @ts-expect-error `edit` can be extended to include other attributes
|
||||
edit,
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
},
|
||||
} );
|
||||
@@ -0,0 +1,13 @@
|
||||
.woocommerce .wp-block-woocommerce-product-image-gallery {
|
||||
position: relative;
|
||||
|
||||
span.onsale {
|
||||
right: unset;
|
||||
z-index: 1;
|
||||
left: -1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.woocommerce .wp-block-woocommerce-product-image-gallery .woocommerce-product-gallery.images {
|
||||
width: initial;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "woocommerce/product-meta",
|
||||
"version": "1.0.0",
|
||||
"title": "Product Meta",
|
||||
"icon": "product",
|
||||
"description": "Display Product Meta",
|
||||
"category": "woocommerce",
|
||||
"supports": {
|
||||
"align": true,
|
||||
"reusable": false
|
||||
},
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"usesContext": [ "postId", "postType", "queryId" ],
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';
|
||||
import { InnerBlockTemplate } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './editor.scss';
|
||||
|
||||
const Edit = () => {
|
||||
const TEMPLATE: InnerBlockTemplate[] = [
|
||||
[
|
||||
'core/group',
|
||||
{ layout: { type: 'flex', flexWrap: 'nowrap' } },
|
||||
[
|
||||
[
|
||||
'woocommerce/product-sku',
|
||||
{
|
||||
isDescendentOfSingleProductTemplate: true,
|
||||
},
|
||||
],
|
||||
[
|
||||
'core/post-terms',
|
||||
{
|
||||
prefix: 'Category: ',
|
||||
term: 'product_cat',
|
||||
},
|
||||
],
|
||||
[
|
||||
'core/post-terms',
|
||||
{
|
||||
prefix: 'Tags: ',
|
||||
term: 'product_tag',
|
||||
},
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
const blockProps = useBlockProps();
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<InnerBlocks template={ TEMPLATE } />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,4 @@
|
||||
.wc-block-editor-related-products__notice {
|
||||
margin: 10px auto;
|
||||
max-width: max-content;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { box as icon } from '@wordpress/icons';
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import edit from './edit';
|
||||
import metadata from './block.json';
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core
|
||||
blockMetadata: metadata,
|
||||
blockSettings: {
|
||||
edit,
|
||||
icon,
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
},
|
||||
} );
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';
|
||||
|
||||
const Save = () => {
|
||||
const blockProps = useBlockProps.save();
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
{ /* @ts-expect-error: `InnerBlocks.Content` is a component that is typed in WordPress core*/ }
|
||||
<InnerBlocks.Content />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Save;
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "woocommerce/product-reviews",
|
||||
"version": "1.0.0",
|
||||
"icon": "admin-comments",
|
||||
"title": "Product Reviews",
|
||||
"description": "A block that shows the reviews for a product.",
|
||||
"category": "woocommerce",
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"supports": {},
|
||||
"attributes": {},
|
||||
"usesContext": [ "postId" ],
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// We are using anchors as mere placeholders to replicate the front-end look.
|
||||
/* eslint-disable jsx-a11y/anchor-is-valid */
|
||||
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { WC_BLOCKS_IMAGE_URL } from '@woocommerce/block-settings';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import { Notice } from '@wordpress/components';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
|
||||
export const ProductReviews = () => {
|
||||
const blockProps = useBlockProps();
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<Notice
|
||||
className={ 'wc-block-editor-related-products__notice' }
|
||||
status={ 'info' }
|
||||
isDismissible={ false }
|
||||
>
|
||||
<p>
|
||||
{ __(
|
||||
'The products reviews and the form to add a new review will be displayed here according to your theme. The look you see here is not representative of what is going to look like, this is just a placeholder.',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</p>
|
||||
</Notice>
|
||||
<h2>
|
||||
{ __(
|
||||
'3 reviews for this product',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</h2>
|
||||
<img
|
||||
src={ `${ WC_BLOCKS_IMAGE_URL }block-placeholders/product-reviews.svg` }
|
||||
alt="Placeholder"
|
||||
/>
|
||||
<h3>{ __( 'Add a review', 'woo-gutenberg-products-block' ) }</h3>
|
||||
<div className="wp-block-woocommerce-product-reviews__editor__form-container">
|
||||
<div className="wp-block-woocommerce-product-reviews__editor__row">
|
||||
<span>
|
||||
{ __(
|
||||
'Your rating *',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</span>
|
||||
<p className="wp-block-woocommerce-product-reviews__editor__stars"></p>
|
||||
</div>
|
||||
<div className="wp-block-woocommerce-product-reviews__editor__row">
|
||||
<span>
|
||||
{ __(
|
||||
'Your review *',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</span>
|
||||
<textarea />
|
||||
</div>
|
||||
<input
|
||||
type="submit"
|
||||
className="submit wp-block-button__link wp-element-button"
|
||||
value={ __( 'Submit', 'woo-gutenberg-products-block' ) }
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductReviews;
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import { Disabled } from '@wordpress/components';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import { Attributes } from './types';
|
||||
|
||||
const Edit = ( { attributes }: BlockEditProps< Attributes > ) => {
|
||||
const { className } = attributes;
|
||||
const blockProps = useBlockProps( {
|
||||
className,
|
||||
} );
|
||||
|
||||
return (
|
||||
<>
|
||||
<div { ...blockProps }>
|
||||
<Disabled>
|
||||
<Block />
|
||||
</Disabled>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import metadata from './block.json';
|
||||
import edit from './edit';
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core
|
||||
blockMetadata: metadata,
|
||||
blockSettings: {
|
||||
edit,
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
},
|
||||
} );
|
||||
@@ -0,0 +1,53 @@
|
||||
.wp-block-woocommerce-product-reviews {
|
||||
img {
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.submit {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.wp-block-woocommerce-product-reviews__editor__row {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
|
||||
> span {
|
||||
flex-basis: 20%;
|
||||
}
|
||||
|
||||
textarea,
|
||||
.wp-block-woocommerce-product-reviews__editor__stars {
|
||||
flex-grow: 1;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
textarea {
|
||||
flex-grow: 1;
|
||||
height: 8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.wp-block-woocommerce-product-reviews__editor__stars {
|
||||
display: inline-block;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
width: 5.3em;
|
||||
height: 1.618em;
|
||||
line-height: 1.618;
|
||||
font-size: 1em;
|
||||
/* stylelint-disable-next-line font-family-no-missing-generic-family-keyword */
|
||||
font-family: star;
|
||||
font-weight: 400;
|
||||
|
||||
&::before {
|
||||
color: inherit;
|
||||
content: "SSSSS";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface Attributes {
|
||||
className?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import type { BlockAttributes } from '@wordpress/blocks';
|
||||
|
||||
export const blockAttributes: BlockAttributes = {
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
isDescendentOfQueryLoop: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
textAlign: {
|
||||
type: 'string',
|
||||
default: '',
|
||||
},
|
||||
isDescendentOfSingleProductBlock: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __, _n, sprintf } from '@wordpress/i18n';
|
||||
import classnames from 'classnames';
|
||||
import {
|
||||
useInnerBlockLayoutContext,
|
||||
useProductDataContext,
|
||||
} from '@woocommerce/shared-context';
|
||||
import {
|
||||
useColorProps,
|
||||
useSpacingProps,
|
||||
useTypographyProps,
|
||||
} from '@woocommerce/base-hooks';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
import { isNumber, ProductResponseItem } from '@woocommerce/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
|
||||
type Props = {
|
||||
textAlign?: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
type RatingProps = {
|
||||
reviews: number;
|
||||
rating: number;
|
||||
parentClassName?: string;
|
||||
};
|
||||
|
||||
type AddReviewProps = {
|
||||
href?: string;
|
||||
};
|
||||
|
||||
const getAverageRating = (
|
||||
product: Omit< ProductResponseItem, 'average_rating' > & {
|
||||
average_rating: string;
|
||||
}
|
||||
) => {
|
||||
const rating = parseFloat( product.average_rating );
|
||||
|
||||
return Number.isFinite( rating ) && rating > 0 ? rating : 0;
|
||||
};
|
||||
|
||||
const getReviewsHref = ( product: ProductResponseItem ) => {
|
||||
const { permalink } = product;
|
||||
return `${ permalink }#reviews`;
|
||||
};
|
||||
|
||||
const getRatingCount = ( product: ProductResponseItem ) => {
|
||||
const count = isNumber( product.review_count )
|
||||
? product.review_count
|
||||
: parseInt( product.review_count, 10 );
|
||||
|
||||
return Number.isFinite( count ) && count > 0 ? count : 0;
|
||||
};
|
||||
|
||||
const Rating = ( props: RatingProps ): JSX.Element => {
|
||||
const { rating, reviews, parentClassName } = props;
|
||||
|
||||
const starStyle = {
|
||||
width: ( rating / 5 ) * 100 + '%',
|
||||
};
|
||||
|
||||
const ratingText = sprintf(
|
||||
/* translators: %f is referring to the average rating value */
|
||||
__( 'Rated %f out of 5', 'woo-gutenberg-products-block' ),
|
||||
rating
|
||||
);
|
||||
|
||||
const ratingHTML = {
|
||||
__html: sprintf(
|
||||
/* translators: %1$s is referring to the average rating value, %2$s is referring to the number of ratings */
|
||||
_n(
|
||||
'Rated %1$s out of 5 based on %2$s customer rating',
|
||||
'Rated %1$s out of 5 based on %2$s customer ratings',
|
||||
reviews,
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
sprintf( '<strong class="rating">%f</strong>', rating ),
|
||||
sprintf( '<span class="rating">%d</span>', reviews )
|
||||
),
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
'wc-block-components-product-rating__stars',
|
||||
`${ parentClassName }__product-rating__stars`
|
||||
) }
|
||||
role="img"
|
||||
aria-label={ ratingText }
|
||||
>
|
||||
<span style={ starStyle } dangerouslySetInnerHTML={ ratingHTML } />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const AddReview = ( props: AddReviewProps ): JSX.Element | null => {
|
||||
const { href } = props;
|
||||
const label = __( 'Add review', 'woo-gutenberg-products-block' );
|
||||
|
||||
return href ? (
|
||||
<a className="wc-block-components-product-rating__link" href={ href }>
|
||||
{ label }
|
||||
</a>
|
||||
) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Product Rating Block Component.
|
||||
*
|
||||
* @param {Object} props Incoming props.
|
||||
* @param {string} [props.className] CSS Class name for the component.
|
||||
* @param {string} [props.textAlign] Text alignment.
|
||||
*
|
||||
* @return {*} The component.
|
||||
*/
|
||||
export const Block = ( props: Props ): JSX.Element | null => {
|
||||
const { textAlign } = props;
|
||||
const { parentClassName } = useInnerBlockLayoutContext();
|
||||
const { product } = useProductDataContext();
|
||||
const rating = getAverageRating( product );
|
||||
const colorProps = useColorProps( props );
|
||||
const typographyProps = useTypographyProps( props );
|
||||
const spacingProps = useSpacingProps( props );
|
||||
const reviews = getRatingCount( product );
|
||||
const href = getReviewsHref( product );
|
||||
|
||||
const className = classnames(
|
||||
colorProps.className,
|
||||
'wc-block-components-product-rating',
|
||||
{
|
||||
[ `${ parentClassName }__product-rating` ]: parentClassName,
|
||||
[ `has-text-align-${ textAlign }` ]: textAlign,
|
||||
}
|
||||
);
|
||||
|
||||
const content = reviews ? (
|
||||
<Rating
|
||||
rating={ rating }
|
||||
reviews={ reviews }
|
||||
parentClassName={ parentClassName }
|
||||
/>
|
||||
) : (
|
||||
<AddReview href={ href } />
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={ className }
|
||||
style={ {
|
||||
...colorProps.style,
|
||||
...typographyProps.style,
|
||||
...spacingProps.style,
|
||||
} }
|
||||
>
|
||||
{ content }
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductDataContext( Block );
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { starEmpty, Icon } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE: string = __(
|
||||
'Product Rating',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
export const BLOCK_ICON: JSX.Element = (
|
||||
<Icon
|
||||
icon={ starEmpty }
|
||||
className="wc-block-editor-components-block-icon"
|
||||
/>
|
||||
);
|
||||
export const BLOCK_DESCRIPTION: string = __(
|
||||
'Display the average rating of a product.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import {
|
||||
AlignmentToolbar,
|
||||
BlockControls,
|
||||
useBlockProps,
|
||||
} from '@wordpress/block-editor';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
import { useEffect } from '@wordpress/element';
|
||||
import { ProductQueryContext as Context } from '@woocommerce/blocks/product-query/types';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import withProductSelector from '../shared/with-product-selector';
|
||||
import { BLOCK_TITLE, BLOCK_ICON } from './constants';
|
||||
import { BlockAttributes } from './types';
|
||||
import './editor.scss';
|
||||
|
||||
const Edit = ( {
|
||||
attributes,
|
||||
setAttributes,
|
||||
context,
|
||||
}: BlockEditProps< BlockAttributes > & { context: Context } ): JSX.Element => {
|
||||
const blockProps = useBlockProps( {
|
||||
className: 'wp-block-woocommerce-product-rating',
|
||||
} );
|
||||
const blockAttrs = {
|
||||
...attributes,
|
||||
...context,
|
||||
};
|
||||
const isDescendentOfQueryLoop = Number.isFinite( context.queryId );
|
||||
|
||||
useEffect(
|
||||
() => setAttributes( { isDescendentOfQueryLoop } ),
|
||||
[ setAttributes, isDescendentOfQueryLoop ]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<BlockControls>
|
||||
<AlignmentToolbar
|
||||
value={ attributes.textAlign }
|
||||
onChange={ ( newAlign ) => {
|
||||
setAttributes( { textAlign: newAlign || '' } );
|
||||
} }
|
||||
/>
|
||||
</BlockControls>
|
||||
<div { ...blockProps }>
|
||||
<Block { ...blockAttrs } />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
export default withProductSelector( {
|
||||
icon: BLOCK_ICON,
|
||||
label: BLOCK_TITLE,
|
||||
description: __(
|
||||
'Choose a product to display its rating.',
|
||||
'woo-gutenberg-products-block'
|
||||
),
|
||||
} )( Edit );
|
||||
@@ -0,0 +1,3 @@
|
||||
.wc-block-components-product-rating__link {
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockType } from '@wordpress/blocks';
|
||||
import type { BlockConfiguration } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import sharedConfig from '../shared/config';
|
||||
import attributes from './attributes';
|
||||
import edit from './edit';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
import { supports } from './support';
|
||||
|
||||
const blockConfig: BlockConfiguration = {
|
||||
...sharedConfig,
|
||||
apiVersion: 2,
|
||||
title,
|
||||
description,
|
||||
usesContext: [ 'query', 'queryId', 'postId' ],
|
||||
ancestor: [
|
||||
'woocommerce/all-products',
|
||||
'woocommerce/single-product',
|
||||
'core/post-template',
|
||||
],
|
||||
icon: { src: icon },
|
||||
attributes,
|
||||
supports,
|
||||
edit,
|
||||
};
|
||||
|
||||
registerBlockType( 'woocommerce/product-rating', { ...blockConfig } );
|
||||
@@ -0,0 +1,75 @@
|
||||
.wc-block-components-product-rating {
|
||||
display: block;
|
||||
line-height: 1;
|
||||
|
||||
&__stars {
|
||||
display: inline-block;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
width: 5.3em;
|
||||
height: 1.618em;
|
||||
line-height: 1.618;
|
||||
font-size: 1em;
|
||||
/* stylelint-disable-next-line font-family-no-missing-generic-family-keyword */
|
||||
font-family: star;
|
||||
font-weight: 400;
|
||||
|
||||
&::before {
|
||||
content: "\53\53\53\53\53";
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
position: absolute;
|
||||
opacity: 0.5;
|
||||
color: inherit;
|
||||
white-space: nowrap;
|
||||
}
|
||||
span {
|
||||
overflow: hidden;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
position: absolute;
|
||||
color: inherit;
|
||||
padding-top: 1.5em;
|
||||
}
|
||||
span::before {
|
||||
content: "\53\53\53\53\53";
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
position: absolute;
|
||||
color: inherit;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
&__link {
|
||||
display: inline-block;
|
||||
height: 1.618em;
|
||||
width: 100%;
|
||||
text-align: inherit;
|
||||
@include font-size(small);
|
||||
}
|
||||
|
||||
.wc-block-all-products & {
|
||||
margin-top: 0;
|
||||
margin-bottom: $gap-small;
|
||||
}
|
||||
}
|
||||
|
||||
.wc-block-single-product {
|
||||
.wc-block-components-product-rating__stars {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.wc-block-all-products,
|
||||
.wp-block-query {
|
||||
.is-loading {
|
||||
.wc-block-components-product-rating {
|
||||
@include placeholder();
|
||||
width: 7em;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/* eslint-disable @wordpress/no-unsafe-wp-apis */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
|
||||
import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor';
|
||||
|
||||
export const supports = {
|
||||
...( isFeaturePluginBuild() && {
|
||||
color: {
|
||||
text: true,
|
||||
background: false,
|
||||
link: false,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
spacing: {
|
||||
margin: true,
|
||||
padding: true,
|
||||
},
|
||||
typography: {
|
||||
fontSize: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
__experimentalSelector: '.wc-block-components-product-rating',
|
||||
} ),
|
||||
...( ! isFeaturePluginBuild() &&
|
||||
typeof __experimentalGetSpacingClassesAndStyles === 'function' && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
},
|
||||
} ),
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface BlockAttributes {
|
||||
productId: number;
|
||||
isDescendentOfQueryLoop: boolean;
|
||||
textAlign: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "woocommerce/related-products",
|
||||
"version": "1.0.0",
|
||||
"title": "Related Products",
|
||||
"icon": "product",
|
||||
"description": "Display related products.",
|
||||
"category": "woocommerce",
|
||||
"supports": {
|
||||
"align": true,
|
||||
"reusable": false
|
||||
},
|
||||
"keywords": [ "WooCommerce" ],
|
||||
"usesContext": [ "postId", "postType", "queryId" ],
|
||||
"textdomain": "woocommerce",
|
||||
"apiVersion": 2,
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import {
|
||||
BLOCK_ATTRIBUTES,
|
||||
INNER_BLOCKS_TEMPLATE,
|
||||
} from '@woocommerce/blocks/product-query/variations';
|
||||
import {
|
||||
InnerBlocks,
|
||||
InspectorControls,
|
||||
useBlockProps,
|
||||
} from '@wordpress/block-editor';
|
||||
import { InnerBlockTemplate } from '@wordpress/blocks';
|
||||
import { Notice } from '@wordpress/components';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './editor.scss';
|
||||
|
||||
const Edit = () => {
|
||||
const TEMPLATE: InnerBlockTemplate[] = [
|
||||
[ 'core/query', BLOCK_ATTRIBUTES, INNER_BLOCKS_TEMPLATE ],
|
||||
];
|
||||
const blockProps = useBlockProps();
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<InspectorControls>
|
||||
<Notice
|
||||
className={ 'wc-block-editor-related-products__notice' }
|
||||
status={ 'warning' }
|
||||
isDismissible={ false }
|
||||
>
|
||||
<p>
|
||||
{ __(
|
||||
'These products will vary depending on the main product in the page',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
</p>
|
||||
</Notice>
|
||||
</InspectorControls>
|
||||
<InnerBlocks template={ TEMPLATE } />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Edit;
|
||||
@@ -0,0 +1,4 @@
|
||||
.wc-block-editor-related-products__notice {
|
||||
margin: auto $gap $gap;
|
||||
max-width: max-content;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { box as icon } from '@wordpress/icons';
|
||||
import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import edit from './edit';
|
||||
import save from './save';
|
||||
import metadata from './block.json';
|
||||
|
||||
registerBlockSingleProductTemplate( {
|
||||
blockName: metadata.name,
|
||||
// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core
|
||||
blockMetadata: metadata,
|
||||
blockSettings: {
|
||||
icon,
|
||||
edit,
|
||||
save,
|
||||
ancestor: [ 'woocommerce/single-product' ],
|
||||
},
|
||||
} );
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';
|
||||
|
||||
const Save = () => {
|
||||
const blockProps = useBlockProps.save();
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
{ /* @ts-expect-error: `InnerBlocks.Content` is a component that is typed in WordPress core*/ }
|
||||
<InnerBlocks.Content />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Save;
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import type { BlockAttributes } from '@wordpress/blocks';
|
||||
|
||||
export const blockAttributes: BlockAttributes = {
|
||||
productId: {
|
||||
type: 'number',
|
||||
default: 0,
|
||||
},
|
||||
isDescendentOfQueryLoop: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
},
|
||||
};
|
||||
|
||||
export default blockAttributes;
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import classnames from 'classnames';
|
||||
import Label from '@woocommerce/base-components/label';
|
||||
import {
|
||||
useInnerBlockLayoutContext,
|
||||
useProductDataContext,
|
||||
} from '@woocommerce/shared-context';
|
||||
import {
|
||||
useBorderProps,
|
||||
useColorProps,
|
||||
useSpacingProps,
|
||||
useTypographyProps,
|
||||
} from '@woocommerce/base-hooks';
|
||||
import { withProductDataContext } from '@woocommerce/shared-hocs';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import './style.scss';
|
||||
import type { BlockAttributes } from './types';
|
||||
|
||||
type Props = BlockAttributes & HTMLAttributes< HTMLDivElement >;
|
||||
|
||||
export const Block = ( props: Props ): JSX.Element | null => {
|
||||
const { className, align } = props;
|
||||
const { parentClassName } = useInnerBlockLayoutContext();
|
||||
const { product } = useProductDataContext();
|
||||
const borderProps = useBorderProps( props );
|
||||
const colorProps = useColorProps( props );
|
||||
const typographyProps = useTypographyProps( props );
|
||||
const spacingProps = useSpacingProps( props );
|
||||
|
||||
if ( ! product.id || ! product.on_sale ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const alignClass =
|
||||
typeof align === 'string'
|
||||
? `wc-block-components-product-sale-badge--align-${ align }`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={ classnames(
|
||||
'wc-block-components-product-sale-badge',
|
||||
className,
|
||||
alignClass,
|
||||
{
|
||||
[ `${ parentClassName }__product-onsale` ]: parentClassName,
|
||||
},
|
||||
colorProps.className,
|
||||
borderProps.className,
|
||||
typographyProps.className
|
||||
) }
|
||||
style={ {
|
||||
...colorProps.style,
|
||||
...borderProps.style,
|
||||
...typographyProps.style,
|
||||
...spacingProps.style,
|
||||
} }
|
||||
>
|
||||
<Label
|
||||
label={ __( 'Sale', 'woo-gutenberg-products-block' ) }
|
||||
screenReaderLabel={ __(
|
||||
'Product on sale',
|
||||
'woo-gutenberg-products-block'
|
||||
) }
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductDataContext( Block );
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { percent, Icon } from '@wordpress/icons';
|
||||
|
||||
export const BLOCK_TITLE: string = __(
|
||||
'On-Sale Badge',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
export const BLOCK_ICON: JSX.Element = (
|
||||
<Icon icon={ percent } className="wc-block-editor-components-block-icon" />
|
||||
);
|
||||
export const BLOCK_DESCRIPTION: string = __(
|
||||
'Displays an on-sale badge if the product is on-sale.',
|
||||
'woo-gutenberg-products-block'
|
||||
);
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { useBlockProps } from '@wordpress/block-editor';
|
||||
import type { BlockEditProps } from '@wordpress/blocks';
|
||||
import { ProductQueryContext as Context } from '@woocommerce/blocks/product-query/types';
|
||||
import { useEffect } from '@wordpress/element';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import Block from './block';
|
||||
import withProductSelector from '../shared/with-product-selector';
|
||||
import {
|
||||
BLOCK_TITLE as label,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
import type { BlockAttributes } from './types';
|
||||
|
||||
const Edit = ( {
|
||||
attributes,
|
||||
setAttributes,
|
||||
context,
|
||||
}: BlockEditProps< BlockAttributes > & { context: Context } ): JSX.Element => {
|
||||
const blockProps = useBlockProps();
|
||||
|
||||
const blockAttrs = {
|
||||
...attributes,
|
||||
...context,
|
||||
};
|
||||
const isDescendentOfQueryLoop = Number.isFinite( context.queryId );
|
||||
|
||||
useEffect(
|
||||
() => setAttributes( { isDescendentOfQueryLoop } ),
|
||||
[ setAttributes, isDescendentOfQueryLoop ]
|
||||
);
|
||||
|
||||
return (
|
||||
<div { ...blockProps }>
|
||||
<Block { ...blockAttrs } />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default withProductSelector( { icon, label, description } )( Edit );
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { registerBlockType } from '@wordpress/blocks';
|
||||
import type { BlockConfiguration } from '@wordpress/blocks';
|
||||
|
||||
/**
|
||||
* Internal dependencies
|
||||
*/
|
||||
import sharedConfig from '../shared/config';
|
||||
import attributes from './attributes';
|
||||
import edit from './edit';
|
||||
import {
|
||||
BLOCK_TITLE as title,
|
||||
BLOCK_ICON as icon,
|
||||
BLOCK_DESCRIPTION as description,
|
||||
} from './constants';
|
||||
import { supports } from './support';
|
||||
|
||||
const blockConfig: BlockConfiguration = {
|
||||
...sharedConfig,
|
||||
title,
|
||||
description,
|
||||
icon: { src: icon },
|
||||
apiVersion: 2,
|
||||
supports,
|
||||
attributes,
|
||||
edit,
|
||||
usesContext: [ 'query', 'queryId', 'postId' ],
|
||||
ancestor: [
|
||||
'woocommerce/all-products',
|
||||
'woocommerce/single-product',
|
||||
'core/post-template',
|
||||
],
|
||||
};
|
||||
|
||||
registerBlockType( 'woocommerce/product-sale-badge', { ...blockConfig } );
|
||||
@@ -0,0 +1,23 @@
|
||||
.wc-block-components-product-sale-badge {
|
||||
margin: 0 auto $gap-small;
|
||||
@include font-size(small);
|
||||
padding: em($gap-smallest) em($gap-small);
|
||||
display: inline-block;
|
||||
width: auto;
|
||||
border: 1px solid #43454b;
|
||||
border-radius: 3px;
|
||||
box-sizing: border-box;
|
||||
color: #43454b;
|
||||
background: #fff;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
z-index: 9;
|
||||
position: static;
|
||||
|
||||
span {
|
||||
color: inherit;
|
||||
background-color: inherit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/* eslint-disable @wordpress/no-unsafe-wp-apis */
|
||||
/**
|
||||
* External dependencies
|
||||
*/
|
||||
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
|
||||
import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor';
|
||||
|
||||
export const supports = {
|
||||
html: false,
|
||||
...( isFeaturePluginBuild() && {
|
||||
color: {
|
||||
gradients: true,
|
||||
background: true,
|
||||
link: false,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
typography: {
|
||||
fontSize: true,
|
||||
lineHeight: true,
|
||||
__experimentalFontFamily: true,
|
||||
__experimentalFontWeight: true,
|
||||
__experimentalFontStyle: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
__experimentalLetterSpacing: true,
|
||||
__experimentalTextTransform: true,
|
||||
__experimentalTextDecoration: true,
|
||||
},
|
||||
__experimentalBorder: {
|
||||
color: true,
|
||||
radius: true,
|
||||
width: true,
|
||||
__experimentalSkipSerialization: true,
|
||||
},
|
||||
...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
padding: true,
|
||||
},
|
||||
} ),
|
||||
__experimentalSelector: '.wc-block-components-product-sale-badge',
|
||||
} ),
|
||||
...( typeof __experimentalGetSpacingClassesAndStyles === 'function' &&
|
||||
! isFeaturePluginBuild() && {
|
||||
spacing: {
|
||||
margin: true,
|
||||
},
|
||||
} ),
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user