first commit

This commit is contained in:
2024-11-10 21:08:49 +01:00
commit 0d932ce5ee
14455 changed files with 2567501 additions and 0 deletions

View File

@@ -0,0 +1,141 @@
/**
* External dependencies
*/
import {
useCollection,
useQueryStateByKey,
} from '@woocommerce/base-context/hooks';
import { decodeEntities } from '@wordpress/html-entities';
import { __ } from '@wordpress/i18n';
import { getSettingWithCoercion } from '@woocommerce/settings';
import {
AttributeObject,
isAttributeQueryCollection,
isAttributeTermCollection,
isBoolean,
} from '@woocommerce/types';
/**
* Internal dependencies
*/
import { renderRemovableListItem, removeArgsFromFilterUrl } from './utils';
import { removeAttributeFilterBySlug } from '../../utils/attributes-query';
interface ActiveAttributeFiltersProps {
displayStyle: string;
operator: 'and' | 'in';
slugs: string[];
attributeObject: AttributeObject;
}
/**
* Component that renders active attribute (terms) filters.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.attributeObject The attribute object.
* @param {Array} props.slugs The slugs for attributes.
* @param {string} props.operator The operator for the filter.
* @param {string} props.displayStyle The style used for displaying the filters.
*/
const ActiveAttributeFilters = ( {
attributeObject,
slugs = [],
operator = 'in',
displayStyle,
}: ActiveAttributeFiltersProps ) => {
const { results, isLoading } = useCollection( {
namespace: '/wc/store/v1',
resourceName: 'products/attributes/terms',
resourceValues: [ attributeObject.id ],
} );
const [ productAttributes, setProductAttributes ] = useQueryStateByKey(
'attributes',
[]
);
if (
isLoading ||
! Array.isArray( results ) ||
! isAttributeTermCollection( results ) ||
! isAttributeQueryCollection( productAttributes )
) {
return null;
}
const attributeLabel = attributeObject.label;
const filteringForPhpTemplate = getSettingWithCoercion(
'is_rendering_php_template',
false,
isBoolean
);
return (
<li>
<span className="wc-block-active-filters__list-item-type">
{ attributeLabel }:
</span>
<ul>
{ slugs.map( ( slug, index ) => {
const termObject = results.find( ( term ) => {
return term.slug === slug;
} );
if ( ! termObject ) {
return null;
}
let prefix: string | JSX.Element = '';
if ( index > 0 && operator === 'and' ) {
prefix = (
<span className="wc-block-active-filters__list-item-operator">
{ __( 'and', 'woo-gutenberg-products-block' ) }
</span>
);
}
return renderRemovableListItem( {
type: attributeLabel,
name: decodeEntities( termObject.name || slug ),
prefix,
removeCallback: () => {
if ( filteringForPhpTemplate ) {
const currentAttribute = productAttributes.find(
( { attribute } ) =>
attribute ===
`pa_${ attributeObject.name }`
);
// If only one attribute was selected, we remove both filter and query type from the URL.
if ( currentAttribute?.slug.length === 1 ) {
return removeArgsFromFilterUrl(
`query_type_${ attributeObject.name }`,
`filter_${ attributeObject.name }`
);
}
// Remove only the slug from the URL.
return removeArgsFromFilterUrl( {
[ `filter_${ attributeObject.name }` ]:
slug,
} );
}
removeAttributeFilterBySlug(
productAttributes,
setProductAttributes,
attributeObject,
slug
);
},
showLabel: false,
displayStyle,
} );
} ) }
</ul>
</li>
);
};
export default ActiveAttributeFilters;

View File

@@ -0,0 +1,11 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
export const blockAttributes = {
heading: {
type: 'string',
default: __( 'Active filters', 'woo-gutenberg-products-block' ),
},
};

View File

@@ -0,0 +1,29 @@
{
"name": "woocommerce/active-filters",
"version": "1.0.0",
"title": "Active Product Filters",
"description": "Show the currently active product filters. Works in combination with the All Products and filters blocks.",
"category": "woocommerce",
"keywords": [ "WooCommerce" ],
"supports": {
"html": false,
"multiple": false,
"color": {
"text": true,
"background": false
}
},
"attributes": {
"displayStyle": {
"type": "string",
"default": "list"
},
"headingLevel": {
"type": "number",
"default": 3
}
},
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2,
"$schema": "https://schemas.wp.org/trunk/block.json"
}

View File

@@ -0,0 +1,328 @@
/**
* External dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { useQueryStateByKey } from '@woocommerce/base-context/hooks';
import { getSetting, getSettingWithCoercion } from '@woocommerce/settings';
import { useMemo, useEffect } from '@wordpress/element';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import Label from '@woocommerce/base-components/label';
import {
isAttributeQueryCollection,
isBoolean,
isRatingQueryCollection,
isStockStatusQueryCollection,
isStockStatusOptions,
} from '@woocommerce/types';
import { getUrlParameter } from '@woocommerce/utils';
/**
* Internal dependencies
*/
import './style.scss';
import { getAttributeFromTaxonomy } from '../../utils/attributes';
import {
formatPriceRange,
renderRemovableListItem,
removeArgsFromFilterUrl,
cleanFilterUrl,
} from './utils';
import ActiveAttributeFilters from './active-attribute-filters';
import { Attributes } from './types';
/**
* Component displaying active filters.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.attributes Incoming attributes for the block.
* @param {boolean} props.isEditor Whether or not in the editor context.
*/
const ActiveFiltersBlock = ( {
attributes: blockAttributes,
isEditor = false,
}: {
attributes: Attributes;
isEditor?: boolean;
} ) => {
const filteringForPhpTemplate = getSettingWithCoercion(
'is_rendering_php_template',
false,
isBoolean
);
const [ productAttributes, setProductAttributes ] = useQueryStateByKey(
'attributes',
[]
);
const [ productStockStatus, setProductStockStatus ] = useQueryStateByKey(
'stock_status',
[]
);
const [ minPrice, setMinPrice ] = useQueryStateByKey( 'min_price' );
const [ maxPrice, setMaxPrice ] = useQueryStateByKey( 'max_price' );
const STOCK_STATUS_OPTIONS = getSetting( 'stockStatusOptions', [] );
const activeStockStatusFilters = useMemo( () => {
if (
productStockStatus.length === 0 ||
! isStockStatusQueryCollection( productStockStatus ) ||
! isStockStatusOptions( STOCK_STATUS_OPTIONS )
) {
return null;
}
return productStockStatus.map( ( slug ) => {
return renderRemovableListItem( {
type: __( 'Stock Status', 'woo-gutenberg-products-block' ),
name: STOCK_STATUS_OPTIONS[ slug ],
removeCallback: () => {
if ( filteringForPhpTemplate ) {
return removeArgsFromFilterUrl( {
filter_stock_status: slug,
} );
}
const newStatuses = productStockStatus.filter(
( status ) => {
return status !== slug;
}
);
setProductStockStatus( newStatuses );
},
displayStyle: blockAttributes.displayStyle,
} );
} );
}, [
STOCK_STATUS_OPTIONS,
productStockStatus,
setProductStockStatus,
blockAttributes.displayStyle,
filteringForPhpTemplate,
] );
const activePriceFilters = useMemo( () => {
if ( ! Number.isFinite( minPrice ) && ! Number.isFinite( maxPrice ) ) {
return null;
}
return renderRemovableListItem( {
type: __( 'Price', 'woo-gutenberg-products-block' ),
name: formatPriceRange( minPrice, maxPrice ),
removeCallback: () => {
if ( filteringForPhpTemplate ) {
return removeArgsFromFilterUrl( 'max_price', 'min_price' );
}
setMinPrice( undefined );
setMaxPrice( undefined );
},
displayStyle: blockAttributes.displayStyle,
} );
}, [
minPrice,
maxPrice,
blockAttributes.displayStyle,
setMinPrice,
setMaxPrice,
filteringForPhpTemplate,
] );
const activeAttributeFilters = useMemo( () => {
if ( ! isAttributeQueryCollection( productAttributes ) ) {
return null;
}
return productAttributes.map( ( attribute ) => {
const attributeObject = getAttributeFromTaxonomy(
attribute.attribute
);
if ( ! attributeObject ) {
return null;
}
return (
<ActiveAttributeFilters
attributeObject={ attributeObject }
displayStyle={ blockAttributes.displayStyle }
slugs={ attribute.slug }
key={ attribute.attribute }
operator={ attribute.operator }
/>
);
} );
}, [ productAttributes, blockAttributes.displayStyle ] );
const [ productRatings, setProductRatings ] =
useQueryStateByKey( 'ratings' );
/**
* Parse the filter URL to set the active rating fitlers.
* This code should be moved to Rating Filter block once it's implemented.
*/
useEffect( () => {
if ( ! filteringForPhpTemplate ) {
return;
}
if ( productRatings.length && productRatings.length > 0 ) {
return;
}
const currentRatings = getUrlParameter( 'rating_filter' )?.toString();
if ( ! currentRatings ) {
return;
}
setProductRatings( currentRatings.split( ',' ) );
}, [ filteringForPhpTemplate, productRatings, setProductRatings ] );
const activeRatingFilters = useMemo( () => {
if (
productRatings.length === 0 ||
! isRatingQueryCollection( productRatings )
) {
return null;
}
return productRatings.map( ( slug ) => {
return renderRemovableListItem( {
type: __( 'Rating', 'woo-gutenberg-products-block' ),
name: sprintf(
/* translators: %s is referring to the average rating value */
__( 'Rated %s out of 5', 'woo-gutenberg-products-block' ),
slug
),
removeCallback: () => {
if ( filteringForPhpTemplate ) {
return removeArgsFromFilterUrl( {
rating_filter: slug,
} );
}
const newRatings = productRatings.filter( ( rating ) => {
return rating !== slug;
} );
setProductRatings( newRatings );
},
displayStyle: blockAttributes.displayStyle,
} );
} );
}, [
productRatings,
setProductRatings,
blockAttributes.displayStyle,
filteringForPhpTemplate,
] );
const hasFilters = () => {
return (
productAttributes.length > 0 ||
productStockStatus.length > 0 ||
productRatings.length > 0 ||
Number.isFinite( minPrice ) ||
Number.isFinite( maxPrice )
);
};
if ( ! hasFilters() && ! isEditor ) {
return null;
}
const TagName =
`h${ blockAttributes.headingLevel }` as keyof JSX.IntrinsicElements;
const hasFilterableProducts = getSettingWithCoercion(
'has_filterable_products',
false,
isBoolean
);
if ( ! hasFilterableProducts ) {
return null;
}
const listClasses = classnames( 'wc-block-active-filters__list', {
'wc-block-active-filters__list--chips':
blockAttributes.displayStyle === 'chips',
} );
return (
<>
{ ! isEditor && blockAttributes.heading && (
<TagName className="wc-block-active-filters__title">
{ blockAttributes.heading }
</TagName>
) }
<div className="wc-block-active-filters">
<ul className={ listClasses }>
{ isEditor ? (
<>
{ renderRemovableListItem( {
type: __(
'Size',
'woo-gutenberg-products-block'
),
name: __(
'Small',
'woo-gutenberg-products-block'
),
displayStyle: blockAttributes.displayStyle,
} ) }
{ renderRemovableListItem( {
type: __(
'Color',
'woo-gutenberg-products-block'
),
name: __(
'Blue',
'woo-gutenberg-products-block'
),
displayStyle: blockAttributes.displayStyle,
} ) }
</>
) : (
<>
{ activePriceFilters }
{ activeStockStatusFilters }
{ activeAttributeFilters }
{ activeRatingFilters }
</>
) }
</ul>
<button
className="wc-block-active-filters__clear-all"
onClick={ () => {
if ( filteringForPhpTemplate ) {
return cleanFilterUrl();
}
setMinPrice( undefined );
setMaxPrice( undefined );
setProductAttributes( [] );
setProductStockStatus( [] );
} }
>
<Label
label={ __(
'Clear All',
'woo-gutenberg-products-block'
) }
screenReaderLabel={ __(
'Clear All Filters',
'woo-gutenberg-products-block'
) }
/>
</button>
</div>
</>
);
};
ActiveFiltersBlock.propTypes = {
/**
* The attributes for this block.
*/
attributes: PropTypes.object.isRequired,
/**
* Whether it's in the editor or frontend display.
*/
isEditor: PropTypes.bool,
};
export default ActiveFiltersBlock;

View File

@@ -0,0 +1,109 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import HeadingToolbar from '@woocommerce/editor-components/heading-toolbar';
import BlockTitle from '@woocommerce/editor-components/block-title';
import type { BlockEditProps } from '@wordpress/blocks';
import {
Disabled,
PanelBody,
withSpokenMessages,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControl as ToggleGroupControl,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from '@wordpress/components';
/**
* Internal dependencies
*/
import Block from './block';
import type { Attributes } from './types';
const Edit = ( {
attributes,
setAttributes,
}: BlockEditProps< Attributes > ) => {
const { className, displayStyle, heading, headingLevel } = attributes;
const blockProps = useBlockProps( {
className,
} );
const getInspectorControls = () => {
return (
<InspectorControls key="inspector">
<PanelBody
title={ __(
'Block Settings',
'woo-gutenberg-products-block'
) }
>
<ToggleGroupControl
label={ __(
'Display Style',
'woo-gutenberg-products-block'
) }
value={ displayStyle }
onChange={ ( value: Attributes[ 'displayStyle' ] ) =>
setAttributes( {
displayStyle: value,
} )
}
>
<ToggleGroupControlOption
value="list"
label={ __(
'List',
'woo-gutenberg-products-block'
) }
/>
<ToggleGroupControlOption
value="chips"
label={ __(
'Chips',
'woo-gutenberg-products-block'
) }
/>
</ToggleGroupControl>
<p>
{ __(
'Heading Level',
'woo-gutenberg-products-block'
) }
</p>
<HeadingToolbar
isCollapsed={ false }
minLevel={ 2 }
maxLevel={ 7 }
selectedLevel={ headingLevel }
onChange={ ( newLevel: Attributes[ 'headingLevel' ] ) =>
setAttributes( { headingLevel: newLevel } )
}
/>
</PanelBody>
</InspectorControls>
);
};
return (
<div { ...blockProps }>
{ getInspectorControls() }
<BlockTitle
className="wc-block-active-filters__title"
headingLevel={ headingLevel }
heading={ heading }
onChange={ ( value: Attributes[ 'heading' ] ) =>
setAttributes( { heading: value } )
}
/>
<Disabled>
<Block attributes={ attributes } isEditor={ true } />
</Disabled>
</div>
);
};
export default withSpokenMessages( Edit );

View File

@@ -0,0 +1,32 @@
/**
* External dependencies
*/
import { renderFrontend } from '@woocommerce/base-utils';
/**
* Internal dependencies
*/
import Block from './block';
import metadata from './block.json';
import { blockAttributes } from './attributes';
const getProps = ( el: HTMLElement ) => {
return {
attributes: {
displayStyle:
el.dataset.displayStyle ||
metadata.attributes.displayStyle.default,
heading: el.dataset.heading || blockAttributes.heading.default,
headingLevel: el.dataset.headingLevel
? parseInt( el.dataset.headingLevel, 10 )
: metadata.attributes.headingLevel.default,
},
isEditor: false,
};
};
renderFrontend( {
selector: '.wp-block-woocommerce-active-filters',
Block,
getProps,
} );

View File

@@ -0,0 +1,84 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { createBlock, registerBlockType } from '@wordpress/blocks';
import { toggle } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import classNames from 'classnames';
import { useBlockProps } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import edit from './edit';
import metadata from './block.json';
import { blockAttributes } from './attributes';
import { Attributes } from './types';
registerBlockType( metadata, {
title: __( 'Active Product Filters', 'woo-gutenberg-products-block' ),
description: __(
'Show the currently active product filters. Works in combination with the All Products and filters blocks.',
'woo-gutenberg-products-block'
),
icon: {
src: (
<Icon
icon={ toggle }
className="wc-block-editor-components-block-icon"
/>
),
},
attributes: {
...metadata.attributes,
...blockAttributes,
},
transforms: {
from: [
{
type: 'block',
blocks: [ 'core/legacy-widget' ],
// We can't transform if raw instance isn't shown in the REST API.
isMatch: ( { idBase, instance } ) =>
idBase === 'woocommerce_layered_nav_filters' &&
!! instance?.raw,
transform: ( { instance } ) =>
createBlock( 'woocommerce/active-filters', {
displayStyle: 'list',
heading:
instance?.raw?.title ||
__(
'Active filters',
'woo-gutenberg-products-block'
),
headingLevel: 3,
} ),
},
],
},
edit,
// Save the props to post content.
save( { attributes }: { attributes: Attributes } ) {
const { className, displayStyle, heading, headingLevel } = attributes;
const data = {
'data-display-style': displayStyle,
'data-heading': heading,
'data-heading-level': headingLevel,
};
return (
<div
{ ...useBlockProps.save( {
className: classNames( 'is-loading', className ),
} ) }
{ ...data }
>
<span
aria-hidden
className="wc-block-active-product-filters__placeholder"
/>
</div>
);
},
} );

View File

@@ -0,0 +1,98 @@
.wc-block-active-filters {
margin-bottom: $gap-large;
overflow: hidden;
.wc-block-active-filters__clear-all {
@include font-size(regular);
float: right;
border: none;
padding: 0;
text-decoration: underline;
cursor: pointer;
&,
&:hover,
&:focus,
&:active {
background: transparent;
color: inherit;
}
}
.wc-block-active-filters__list {
margin: 0 0 $gap-smallest;
padding: 0;
list-style: none outside;
clear: both;
li {
margin: 0;
padding: 0;
list-style: none outside;
clear: both;
ul {
margin: 0;
padding: 0;
list-style: none outside;
}
&:first-child {
.wc-block-active-filters__list-item-type {
margin: 0;
}
}
}
}
.wc-block-active-filters__list-item-type {
@include font-size(smaller);
text-transform: uppercase;
letter-spacing: 0.1em;
margin: $gap 0 0;
display: block;
}
.wc-block-active-filters__list-item-operator {
font-weight: normal;
font-style: italic;
}
.wc-block-active-filters__list-item-name {
font-weight: bold;
display: block;
position: relative;
padding: 0 16px 0 0;
}
.wc-block-active-filters__list-item-remove {
background: transparent;
border: 0;
appearance: none;
height: 16px;
width: 16px;
padding: 0;
position: absolute;
right: 0;
top: 50%;
margin: -8px 0 0 0;
color: currentColor;
}
.wc-block-active-filters__list--chips {
ul,
li {
display: inline;
}
.wc-block-active-filters__list-item-type {
display: none;
}
.wc-block-components-chip {
@include font-size(small);
margin-top: em($gap-small * 0.25);
margin-bottom: em($gap-small * 0.25);
}
}
}

View File

@@ -0,0 +1,6 @@
export interface Attributes {
heading: string;
headingLevel: number;
displayStyle: string;
className?: string;
}

View File

@@ -0,0 +1,213 @@
/**
* External dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { formatPrice } from '@woocommerce/price-format';
import { RemovableChip } from '@woocommerce/base-components/chip';
import Label from '@woocommerce/base-components/label';
import { getQueryArgs, addQueryArgs, removeQueryArgs } from '@wordpress/url';
/**
* Format a min/max price range to display.
*
* @param {number} minPrice The min price, if set.
* @param {number} maxPrice The max price, if set.
*/
export const formatPriceRange = ( minPrice: number, maxPrice: number ) => {
if ( Number.isFinite( minPrice ) && Number.isFinite( maxPrice ) ) {
return sprintf(
/* translators: %1$s min price, %2$s max price */
__( 'Between %1$s and %2$s', 'woo-gutenberg-products-block' ),
formatPrice( minPrice ),
formatPrice( maxPrice )
);
}
if ( Number.isFinite( minPrice ) ) {
return sprintf(
/* translators: %s min price */
__( 'From %s', 'woo-gutenberg-products-block' ),
formatPrice( minPrice )
);
}
return sprintf(
/* translators: %s max price */
__( 'Up to %s', 'woo-gutenberg-products-block' ),
formatPrice( maxPrice )
);
};
interface RemovableListItemProps {
type: string;
name: string;
prefix?: string | JSX.Element;
showLabel?: boolean;
displayStyle: string;
removeCallback?: () => void;
}
/**
* Render a removable item in the active filters block list.
*
* @param {Object} listItem The removable item to render.
* @param {string} listItem.type Type string.
* @param {string} listItem.name Name string.
* @param {string} [listItem.prefix=''] Prefix shown before item name.
* @param {Function} listItem.removeCallback Callback to remove item.
* @param {string} listItem.displayStyle Whether it's a list or chips.
* @param {boolean} [listItem.showLabel=true] Should the label be shown for
* this item?
*/
export const renderRemovableListItem = ( {
type,
name,
prefix = '',
removeCallback = () => null,
showLabel = true,
displayStyle,
}: RemovableListItemProps ) => {
const prefixedName = prefix ? (
<>
{ prefix }
&nbsp;
{ name }
</>
) : (
name
);
const removeText = sprintf(
/* translators: %s attribute value used in the filter. For example: yellow, green, small, large. */
__( 'Remove %s filter', 'woo-gutenberg-products-block' ),
name
);
return (
<li
className="wc-block-active-filters__list-item"
key={ type + ':' + name }
>
{ showLabel && (
<span className="wc-block-active-filters__list-item-type">
{ type + ': ' }
</span>
) }
{ displayStyle === 'chips' ? (
<RemovableChip
element="span"
text={ prefixedName }
onRemove={ removeCallback }
radius="large"
ariaLabel={ removeText }
/>
) : (
<span className="wc-block-active-filters__list-item-name">
{ prefixedName }
<button
className="wc-block-active-filters__list-item-remove"
onClick={ removeCallback }
>
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<ellipse
cx="8"
cy="8"
rx="8"
ry="8"
transform="rotate(-180 8 8)"
fill="currentColor"
fillOpacity="0.7"
/>
<rect
x="10.636"
y="3.94983"
width="2"
height="9.9466"
transform="rotate(45 10.636 3.94983)"
fill="white"
/>
<rect
x="12.0503"
y="11.0209"
width="2"
height="9.9466"
transform="rotate(135 12.0503 11.0209)"
fill="white"
/>
</svg>
<Label screenReaderLabel={ removeText } />
</button>
</span>
) }
</li>
);
};
/**
* Update the current URL to update or remove provided query arguments.
*
*
* @param {Array<string|Record<string, string>>} args Args to remove
*/
export const removeArgsFromFilterUrl = (
...args: ( string | Record< string, string > )[]
) => {
const url = window.location.href;
const currentQuery = getQueryArgs( url );
const cleanUrl = removeQueryArgs( url, ...Object.keys( currentQuery ) );
args.forEach( ( item ) => {
if ( typeof item === 'string' ) {
return delete currentQuery[ item ];
}
if ( typeof item === 'object' ) {
const key = Object.keys( item )[ 0 ];
const currentQueryValue = currentQuery[ key ]
.toString()
.split( ',' );
currentQuery[ key ] = currentQueryValue
.filter( ( value ) => value !== item[ key ] )
.join( ',' );
}
} );
const filteredQuery = Object.fromEntries(
Object.entries( currentQuery ).filter( ( [ , value ] ) => value )
);
window.location.href = addQueryArgs( cleanUrl, filteredQuery );
};
/**
* Clean the filter URL.
*/
export const cleanFilterUrl = () => {
const url = window.location.href;
const args = getQueryArgs( url );
const cleanUrl = removeQueryArgs( url, ...Object.keys( args ) );
const remainingArgs = Object.fromEntries(
Object.keys( args )
.filter( ( arg ) => {
if (
arg.includes( 'min_price' ) ||
arg.includes( 'max_price' ) ||
arg.includes( 'rating_filter' ) ||
arg.includes( 'filter_' ) ||
arg.includes( 'query_type_' )
) {
return false;
}
return true;
} )
.map( ( key ) => [ key, args[ key ] ] )
);
window.location.href = addQueryArgs( cleanUrl, remainingArgs );
};

View File

@@ -0,0 +1,11 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
export const blockAttributes = {
heading: {
type: 'string',
default: __( 'Filter by attribute', 'woo-gutenberg-products-block' ),
},
};

View File

@@ -0,0 +1,57 @@
{
"name": "woocommerce/attribute-filter",
"version": "1.0.0",
"title": "Filter Products by Attribute",
"description": "Allow customers to filter the grid by product attribute, such as color. Works in combination with the All Products block.",
"category": "woocommerce",
"keywords": [ "WooCommerce" ],
"supports": {
"html": false,
"color": {
"text": true,
"background": false
}
},
"example": {
"attributes": {
"isPreview": true
}
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"attributeId": {
"type": "number",
"default": 0
},
"showCounts": {
"type": "boolean",
"default": true
},
"queryType": {
"type": "string",
"default": "or"
},
"headingLevel": {
"type": "number",
"default": 3
},
"displayStyle": {
"type": "string",
"default": "list"
},
"showFilterButton": {
"type": "boolean",
"default": false
},
"isPreview": {
"type": "boolean",
"default": false
}
},
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2,
"$schema": "https://schemas.wp.org/trunk/block.json"
}

View File

@@ -0,0 +1,621 @@
/**
* External dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import { usePrevious, useShallowEqual } from '@woocommerce/base-hooks';
import {
useCollection,
useQueryStateByKey,
useQueryStateByContext,
useCollectionData,
} from '@woocommerce/base-context/hooks';
import { useCallback, useEffect, useState, useMemo } from '@wordpress/element';
import CheckboxList from '@woocommerce/base-components/checkbox-list';
import DropdownSelector from '@woocommerce/base-components/dropdown-selector';
import Label from '@woocommerce/base-components/filter-element-label';
import FilterSubmitButton from '@woocommerce/base-components/filter-submit-button';
import isShallowEqual from '@wordpress/is-shallow-equal';
import { decodeEntities } from '@wordpress/html-entities';
import { Notice } from 'wordpress-components';
import classNames from 'classnames';
import { getSettingWithCoercion } from '@woocommerce/settings';
import { getQueryArgs, removeQueryArgs } from '@wordpress/url';
import {
AttributeQuery,
isAttributeQueryCollection,
isBoolean,
isString,
objectHasProp,
} from '@woocommerce/types';
import {
PREFIX_QUERY_ARG_FILTER_TYPE,
PREFIX_QUERY_ARG_QUERY_TYPE,
} from '@woocommerce/utils';
/**
* Internal dependencies
*/
import { getAttributeFromID } from '../../utils/attributes';
import { updateAttributeFilter } from '../../utils/attributes-query';
import { previewAttributeObject, previewOptions } from './preview';
import { useBorderProps } from '../../hooks/style-attributes';
import './style.scss';
import {
formatParams,
getActiveFilters,
areAllFiltersRemoved,
isQueryArgsEqual,
parseTaxonomyToGenerateURL,
} from './utils';
import { BlockAttributes, DisplayOption } from './types';
/**
* Formats filter values into a string for the URL parameters needed for filtering PHP templates.
*
* @param {string} url Current page URL.
* @param {Array} params Parameters and their constraints.
*
* @return {string} New URL with query parameters in it.
*/
/**
* Component displaying an attribute filter.
*
* @param {Object} props Incoming props for the component.
* @param {Object} props.attributes Incoming block attributes.
* @param {boolean} props.isEditor
*/
const AttributeFilterBlock = ( {
attributes: blockAttributes,
isEditor = false,
}: {
attributes: BlockAttributes;
isEditor?: boolean;
} ) => {
const hasFilterableProducts = getSettingWithCoercion(
'has_filterable_products',
false,
isBoolean
);
const filteringForPhpTemplate = getSettingWithCoercion(
'is_rendering_php_template',
false,
isBoolean
);
const pageUrl = getSettingWithCoercion(
'page_url',
window.location.href,
isString
);
const [ hasSetPhpFilterDefaults, setHasSetPhpFilterDefaults ] =
useState( false );
const attributeObject =
blockAttributes.isPreview && ! blockAttributes.attributeId
? previewAttributeObject
: getAttributeFromID( blockAttributes.attributeId );
const [ checked, setChecked ] = useState(
getActiveFilters( filteringForPhpTemplate, attributeObject )
);
const [ displayedOptions, setDisplayedOptions ] = useState<
DisplayOption[]
>(
blockAttributes.isPreview && ! blockAttributes.attributeId
? previewOptions
: []
);
const borderProps = useBorderProps( blockAttributes );
const [ queryState ] = useQueryStateByContext();
const [ productAttributesQuery, setProductAttributesQuery ] =
useQueryStateByKey( 'attributes', [] );
const { results: attributeTerms, isLoading: attributeTermsLoading } =
useCollection( {
namespace: '/wc/store/v1',
resourceName: 'products/attributes/terms',
resourceValues: [ attributeObject?.id || 0 ],
shouldSelect: blockAttributes.attributeId > 0,
} );
const filterAvailableTerms =
blockAttributes.displayStyle !== 'dropdown' &&
blockAttributes.queryType === 'and';
const { results: filteredCounts, isLoading: filteredCountsLoading } =
useCollectionData( {
queryAttribute: {
taxonomy: attributeObject?.taxonomy || '',
queryType: blockAttributes.queryType,
},
queryState: {
...queryState,
attributes: filterAvailableTerms ? queryState.attributes : null,
},
} );
/**
* Get count data about a given term by ID.
*/
const getFilteredTerm = useCallback(
( id ) => {
if (
! objectHasProp( filteredCounts, 'attribute_counts' ) ||
! Array.isArray( filteredCounts.attribute_counts )
) {
return null;
}
return filteredCounts.attribute_counts.find(
( { term } ) => term === id
);
},
[ filteredCounts ]
);
/**
* Compare intersection of all terms and filtered counts to get a list of options to display.
*/
useEffect( () => {
/**
* Checks if a term slug is in the query state.
*
* @param {string} termSlug The term of the slug to check.
*/
const isTermInQueryState = ( termSlug: string ) => {
if ( ! queryState?.attributes ) {
return false;
}
return queryState.attributes.some(
( { attribute, slug = [] }: AttributeQuery ) =>
attribute === attributeObject?.taxonomy &&
slug.includes( termSlug )
);
};
if ( attributeTermsLoading || filteredCountsLoading ) {
return;
}
if ( ! Array.isArray( attributeTerms ) ) {
return;
}
const newOptions = attributeTerms
.map( ( term ) => {
const filteredTerm = getFilteredTerm( term.id );
// If there is no match this term doesn't match the current product collection - only render if checked.
if (
! filteredTerm &&
! checked.includes( term.slug ) &&
! isTermInQueryState( term.slug )
) {
return null;
}
const count = filteredTerm ? filteredTerm.count : 0;
return {
value: term.slug,
name: decodeEntities( term.name ),
label: (
<Label
name={ decodeEntities( term.name ) }
count={ blockAttributes.showCounts ? count : null }
/>
),
};
} )
.filter( ( option ): option is DisplayOption => !! option );
setDisplayedOptions( newOptions );
}, [
attributeObject?.taxonomy,
attributeTerms,
attributeTermsLoading,
blockAttributes.showCounts,
filteredCountsLoading,
getFilteredTerm,
checked,
queryState.attributes,
] );
/**
* Returns an array of term objects that have been chosen via the checkboxes.
*/
const getSelectedTerms = useCallback(
( newChecked ) => {
if ( ! Array.isArray( attributeTerms ) ) {
return [];
}
return attributeTerms.reduce( ( acc, term ) => {
if ( newChecked.includes( term.slug ) ) {
acc.push( term );
}
return acc;
}, [] );
},
[ attributeTerms ]
);
/**
* Appends query params to the current pages URL and redirects them to the new URL for PHP rendered templates.
*
* @param {Object} query The object containing the active filter query.
* @param {boolean} allFiltersRemoved If there are active filters or not.
*/
const redirectPageForPhpTemplate = useCallback(
( query, allFiltersRemoved = false ) => {
if ( allFiltersRemoved ) {
if ( ! attributeObject?.taxonomy ) {
return;
}
const currentQueryArgKeys = Object.keys(
getQueryArgs( window.location.href )
);
const parsedTaxonomy = parseTaxonomyToGenerateURL(
attributeObject.taxonomy
);
const url = currentQueryArgKeys.reduce(
( currentUrl, queryArg ) =>
queryArg.includes(
PREFIX_QUERY_ARG_QUERY_TYPE + parsedTaxonomy
) ||
queryArg.includes(
PREFIX_QUERY_ARG_FILTER_TYPE + parsedTaxonomy
)
? removeQueryArgs( currentUrl, queryArg )
: currentUrl,
window.location.href
);
const newUrl = formatParams( url, query );
window.location.href = newUrl;
} else {
const newUrl = formatParams( pageUrl, query );
const currentQueryArgs = getQueryArgs( window.location.href );
const newUrlQueryArgs = getQueryArgs( newUrl );
if ( ! isQueryArgsEqual( currentQueryArgs, newUrlQueryArgs ) ) {
window.location.href = newUrl;
}
}
},
[ pageUrl, attributeObject?.taxonomy ]
);
const onSubmit = ( checkedFilters: string[] ) => {
const query = updateAttributeFilter(
productAttributesQuery,
setProductAttributesQuery,
attributeObject,
getSelectedTerms( checkedFilters ),
blockAttributes.queryType === 'or' ? 'in' : 'and'
);
// This is for PHP rendered template filtering only.
if ( filteringForPhpTemplate ) {
redirectPageForPhpTemplate( query, checkedFilters.length === 0 );
}
};
const updateCheckedFilters = useCallback(
( checkedFilters: string[] ) => {
if ( isEditor ) {
return;
}
setChecked( checkedFilters );
if ( ! blockAttributes.showFilterButton ) {
updateAttributeFilter(
productAttributesQuery,
setProductAttributesQuery,
attributeObject,
getSelectedTerms( checkedFilters ),
blockAttributes.queryType === 'or' ? 'in' : 'and'
);
}
},
[
isEditor,
setChecked,
productAttributesQuery,
setProductAttributesQuery,
attributeObject,
getSelectedTerms,
blockAttributes.queryType,
blockAttributes.showFilterButton,
]
);
const checkedQuery = useMemo( () => {
if ( ! isAttributeQueryCollection( productAttributesQuery ) ) {
return [];
}
return productAttributesQuery
.filter(
( { attribute } ) => attribute === attributeObject?.taxonomy
)
.flatMap( ( { slug } ) => slug );
}, [ productAttributesQuery, attributeObject?.taxonomy ] );
const currentCheckedQuery = useShallowEqual( checkedQuery );
const previousCheckedQuery = usePrevious( currentCheckedQuery );
// Track ATTRIBUTES QUERY changes so the block reflects current filters.
useEffect( () => {
if (
previousCheckedQuery &&
! isShallowEqual( previousCheckedQuery, currentCheckedQuery ) && // checked query changed
! isShallowEqual( checked, currentCheckedQuery ) // checked query doesn't match the UI
) {
updateCheckedFilters( currentCheckedQuery );
}
}, [
checked,
currentCheckedQuery,
previousCheckedQuery,
updateCheckedFilters,
] );
const multiple =
blockAttributes.displayStyle !== 'dropdown' ||
blockAttributes.queryType === 'or';
/**
* When a checkbox in the list changes, update state.
*/
const onChange = useCallback(
( checkedValue ) => {
const getFilterNameFromValue = ( filterValue: string ) => {
const result = displayedOptions.find(
( option ) => option.value === filterValue
);
if ( result ) {
return result.name;
}
};
const announceFilterChange = ( {
filterAdded,
filterRemoved,
}: {
filterAdded?: string | null;
filterRemoved?: string | null;
} ) => {
const filterAddedName = filterAdded
? getFilterNameFromValue( filterAdded )
: null;
const filterRemovedName = filterRemoved
? getFilterNameFromValue( filterRemoved )
: null;
if ( filterAddedName && filterRemovedName ) {
speak(
sprintf(
/* translators: %1$s and %2$s are attribute terms (for example: 'red', 'blue', 'large'...). */
__(
'%1$s filter replaced with %2$s.',
'woo-gutenberg-products-block'
),
filterAddedName,
filterRemovedName
)
);
} else if ( filterAddedName ) {
speak(
sprintf(
/* translators: %s attribute term (for example: 'red', 'blue', 'large'...) */
__(
'%s filter added.',
'woo-gutenberg-products-block'
),
filterAddedName
)
);
} else if ( filterRemovedName ) {
speak(
sprintf(
/* translators: %s attribute term (for example: 'red', 'blue', 'large'...) */
__(
'%s filter removed.',
'woo-gutenberg-products-block'
),
filterRemovedName
)
);
}
};
const previouslyChecked = checked.includes( checkedValue );
let newChecked;
if ( ! multiple ) {
newChecked = previouslyChecked ? [] : [ checkedValue ];
const filterAdded = previouslyChecked ? null : checkedValue;
const filterRemoved =
checked.length === 1 ? checked[ 0 ] : null;
announceFilterChange( { filterAdded, filterRemoved } );
} else {
newChecked = checked.filter(
( value ) => value !== checkedValue
);
if ( ! previouslyChecked ) {
newChecked.push( checkedValue );
newChecked.sort();
announceFilterChange( { filterAdded: checkedValue } );
} else {
announceFilterChange( { filterRemoved: checkedValue } );
}
}
updateCheckedFilters( newChecked );
},
[ checked, displayedOptions, multiple, updateCheckedFilters ]
);
/**
* Important: For PHP rendered block templates only.
*
* When we render the PHP block template (e.g. Classic Block) we need to set the default checked values,
* and also update the URL when the filters are clicked/updated.
*/
useEffect( () => {
if ( filteringForPhpTemplate && attributeObject ) {
if (
areAllFiltersRemoved( {
currentCheckedFilters: checked,
hasSetPhpFilterDefaults,
} )
) {
if ( ! blockAttributes.showFilterButton ) {
setChecked( [] );
redirectPageForPhpTemplate( productAttributesQuery, true );
}
}
if ( ! blockAttributes.showFilterButton ) {
setChecked( checked );
redirectPageForPhpTemplate( productAttributesQuery, false );
}
}
}, [
hasSetPhpFilterDefaults,
redirectPageForPhpTemplate,
filteringForPhpTemplate,
productAttributesQuery,
attributeObject,
checked,
blockAttributes.showFilterButton,
] );
/**
* Important: For PHP rendered block templates only.
*
* When we set the default parameter values which we get from the URL in the above useEffect(),
* we need to run updateCheckedFilters which will set these values in state for the Active Filters block.
*/
useEffect( () => {
if ( filteringForPhpTemplate ) {
const activeFilters = getActiveFilters(
filteringForPhpTemplate,
attributeObject
);
if (
activeFilters.length > 0 &&
! hasSetPhpFilterDefaults &&
! attributeTermsLoading
) {
setHasSetPhpFilterDefaults( true );
updateCheckedFilters( activeFilters );
}
}
}, [
attributeObject,
filteringForPhpTemplate,
hasSetPhpFilterDefaults,
attributeTermsLoading,
updateCheckedFilters,
] );
if ( ! hasFilterableProducts ) {
return null;
}
// Short-circuit if no attribute is selected.
if ( ! attributeObject ) {
if ( isEditor ) {
return (
<Notice status="warning" isDismissible={ false }>
<p>
{ __(
'Please select an attribute to use this filter!',
'woo-gutenberg-products-block'
) }
</p>
</Notice>
);
}
return null;
}
if ( displayedOptions.length === 0 && ! attributeTermsLoading ) {
if ( isEditor ) {
return (
<Notice status="warning" isDismissible={ false }>
<p>
{ __(
'The selected attribute does not have any term assigned to products.',
'woo-gutenberg-products-block'
) }
</p>
</Notice>
);
}
return null;
}
const TagName =
`h${ blockAttributes.headingLevel }` as keyof JSX.IntrinsicElements;
const isLoading = ! blockAttributes.isPreview && attributeTermsLoading;
const isDisabled = ! blockAttributes.isPreview && filteredCountsLoading;
return (
<>
{ ! isEditor &&
blockAttributes.heading &&
displayedOptions.length > 0 && (
<TagName className="wc-block-attribute-filter__title">
{ blockAttributes.heading }
</TagName>
) }
<div
className={ `wc-block-attribute-filter style-${ blockAttributes.displayStyle }` }
>
{ blockAttributes.displayStyle === 'dropdown' ? (
<DropdownSelector
attributeLabel={ attributeObject.label }
checked={ checked }
className={ classNames(
'wc-block-attribute-filter-dropdown',
borderProps.className
) }
style={ { ...borderProps.style, borderStyle: 'none' } }
inputLabel={ blockAttributes.heading }
isLoading={ isLoading }
multiple={ multiple }
onChange={ onChange }
options={ displayedOptions }
/>
) : (
<CheckboxList
className={ 'wc-block-attribute-filter-list' }
options={ displayedOptions }
checked={ checked }
onChange={ onChange }
isLoading={ isLoading }
isDisabled={ isDisabled }
/>
) }
{ blockAttributes.showFilterButton && (
<FilterSubmitButton
className="wc-block-attribute-filter__button"
disabled={ isLoading || isDisabled }
onClick={ () => onSubmit( checked ) }
/>
) }
</div>
</>
);
};
export default AttributeFilterBlock;

View File

@@ -0,0 +1,420 @@
/**
* External dependencies
*/
import { __, sprintf, _n } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import {
InspectorControls,
BlockControls,
useBlockProps,
} from '@wordpress/block-editor';
import { Icon, category, external } from '@wordpress/icons';
import { SearchListControl } from '@woocommerce/editor-components/search-list-control';
import { sortBy } from 'lodash';
import { getAdminLink, getSetting } from '@woocommerce/settings';
import HeadingToolbar from '@woocommerce/editor-components/heading-toolbar';
import BlockTitle from '@woocommerce/editor-components/block-title';
import classnames from 'classnames';
import { SearchListItemsType } from '@woocommerce/editor-components/search-list-control/types';
import { AttributeSetting } from '@woocommerce/types';
import {
Placeholder,
Disabled,
PanelBody,
ToggleControl,
Button,
ToolbarGroup,
withSpokenMessages,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControl as ToggleGroupControl,
// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
__experimentalToggleGroupControlOption as ToggleGroupControlOption,
} from '@wordpress/components';
/**
* Internal dependencies
*/
import Block from './block';
import './editor.scss';
import type { EditProps } from './types';
const ATTRIBUTES = getSetting< AttributeSetting[] >( 'attributes', [] );
const Edit = ( { attributes, setAttributes, debouncedSpeak }: EditProps ) => {
const {
attributeId,
className,
displayStyle,
heading,
headingLevel,
isPreview,
queryType,
showCounts,
showFilterButton,
} = attributes;
const [ isEditing, setIsEditing ] = useState(
! attributeId && ! isPreview
);
const blockProps = useBlockProps();
const getBlockControls = () => {
return (
<BlockControls>
<ToolbarGroup
controls={ [
{
icon: 'edit',
title: __( 'Edit', 'woo-gutenberg-products-block' ),
onClick: () => setIsEditing( ! isEditing ),
isActive: isEditing,
},
] }
/>
</BlockControls>
);
};
const onChange = ( selected: SearchListItemsType ) => {
if ( ! selected || ! selected.length ) {
return;
}
const selectedId = selected[ 0 ].id;
const productAttribute = ATTRIBUTES.find(
( attribute ) => attribute.attribute_id === selectedId.toString()
);
if ( ! productAttribute || attributeId === selectedId ) {
return;
}
const attributeName = productAttribute.attribute_label;
setAttributes( {
attributeId: selectedId as number,
heading: sprintf(
/* translators: %s attribute name. */
__( 'Filter by %s', 'woo-gutenberg-products-block' ),
attributeName
),
} );
};
const renderAttributeControl = ( {
isCompact,
}: {
isCompact: boolean;
} ) => {
const messages = {
clear: __(
'Clear selected attribute',
'woo-gutenberg-products-block'
),
list: __( 'Product Attributes', 'woo-gutenberg-products-block' ),
noItems: __(
"Your store doesn't have any product attributes.",
'woo-gutenberg-products-block'
),
search: __(
'Search for a product attribute:',
'woo-gutenberg-products-block'
),
selected: ( n: number ) =>
sprintf(
/* translators: %d is the number of attributes selected. */
_n(
'%d attribute selected',
'%d attributes selected',
n,
'woo-gutenberg-products-block'
),
n
),
updated: __(
'Product attribute search results updated.',
'woo-gutenberg-products-block'
),
};
const list = sortBy(
ATTRIBUTES.map( ( item ) => {
return {
id: parseInt( item.attribute_id, 10 ),
name: item.attribute_label,
};
} ),
'name'
);
return (
<SearchListControl
className="woocommerce-product-attributes"
list={ list }
selected={ list.filter( ( { id } ) => id === attributeId ) }
onChange={ onChange }
messages={ messages }
isSingle
isCompact={ isCompact }
/>
);
};
const getInspectorControls = () => {
return (
<InspectorControls key="inspector">
<PanelBody
title={ __( 'Content', 'woo-gutenberg-products-block' ) }
>
<ToggleControl
label={ __(
'Product count',
'woo-gutenberg-products-block'
) }
help={
showCounts
? __(
'Product count is visible.',
'woo-gutenberg-products-block'
)
: __(
'Product count is hidden.',
'woo-gutenberg-products-block'
)
}
checked={ showCounts }
onChange={ () =>
setAttributes( {
showCounts: ! showCounts,
} )
}
/>
<p>
{ __(
'Heading Level',
'woo-gutenberg-products-block'
) }
</p>
<HeadingToolbar
isCollapsed={ false }
minLevel={ 2 }
maxLevel={ 7 }
selectedLevel={ headingLevel }
onChange={ ( newLevel: number ) =>
setAttributes( { headingLevel: newLevel } )
}
/>
</PanelBody>
<PanelBody
title={ __(
'Block Settings',
'woo-gutenberg-products-block'
) }
>
<ToggleGroupControl
label={ __(
'Query Type',
'woo-gutenberg-products-block'
) }
help={
queryType === 'and'
? __(
'Products that have all of the selected attributes will be shown.',
'woo-gutenberg-products-block'
)
: __(
'Products that have any of the selected attributes will be shown.',
'woo-gutenberg-products-block'
)
}
value={ queryType }
onChange={ ( value: string ) =>
setAttributes( {
queryType: value,
} )
}
>
<ToggleGroupControlOption
value="and"
label={ __(
'And',
'woo-gutenberg-products-block'
) }
/>
<ToggleGroupControlOption
value="or"
label={ __( 'Or', 'woo-gutenberg-products-block' ) }
/>
</ToggleGroupControl>
<ToggleGroupControl
label={ __(
'Display Style',
'woo-gutenberg-products-block'
) }
value={ displayStyle }
onChange={ ( value: string ) =>
setAttributes( {
displayStyle: value,
} )
}
>
<ToggleGroupControlOption
value="list"
label={ __(
'List',
'woo-gutenberg-products-block'
) }
/>
<ToggleGroupControlOption
value="dropdown"
label={ __(
'Dropdown',
'woo-gutenberg-products-block'
) }
/>
</ToggleGroupControl>
<ToggleControl
label={ __(
'Filter button',
'woo-gutenberg-products-block'
) }
help={
showFilterButton
? __(
'Products will only update when the button is pressed.',
'woo-gutenberg-products-block'
)
: __(
'Products will update as options are selected.',
'woo-gutenberg-products-block'
)
}
checked={ showFilterButton }
onChange={ ( value ) =>
setAttributes( {
showFilterButton: value,
} )
}
/>
</PanelBody>
<PanelBody
title={ __(
'Filter Products by Attribute',
'woo-gutenberg-products-block'
) }
initialOpen={ false }
>
{ renderAttributeControl( { isCompact: true } ) }
</PanelBody>
</InspectorControls>
);
};
const noAttributesPlaceholder = () => (
<Placeholder
className="wc-block-attribute-filter"
icon={ <Icon icon={ category } /> }
label={ __(
'Filter Products by Attribute',
'woo-gutenberg-products-block'
) }
instructions={ __(
'Display a list of filters based on a chosen attribute.',
'woo-gutenberg-products-block'
) }
>
<p>
{ __(
"Attributes are needed for filtering your products. You haven't created any attributes yet.",
'woo-gutenberg-products-block'
) }
</p>
<Button
className="wc-block-attribute-filter__add-attribute-button"
isSecondary
href={ getAdminLink(
'edit.php?post_type=product&page=product_attributes'
) }
>
{ __( 'Add new attribute', 'woo-gutenberg-products-block' ) +
' ' }
<Icon icon={ external } />
</Button>
<Button
className="wc-block-attribute-filter__read_more_button"
isTertiary
href="https://docs.woocommerce.com/document/managing-product-taxonomies/"
>
{ __( 'Learn more', 'woo-gutenberg-products-block' ) }
</Button>
</Placeholder>
);
const onDone = () => {
setIsEditing( false );
debouncedSpeak(
__(
'Showing Filter Products by Attribute block preview.',
'woo-gutenberg-products-block'
)
);
};
const renderEditMode = () => {
return (
<Placeholder
className="wc-block-attribute-filter"
icon={ <Icon icon={ category } /> }
label={ __(
'Filter Products by Attribute',
'woo-gutenberg-products-block'
) }
instructions={ __(
'Display a list of filters based on a chosen attribute.',
'woo-gutenberg-products-block'
) }
>
<div className="wc-block-attribute-filter__selection">
{ renderAttributeControl( { isCompact: false } ) }
<Button isPrimary onClick={ onDone }>
{ __( 'Done', 'woo-gutenberg-products-block' ) }
</Button>
</div>
</Placeholder>
);
};
return Object.keys( ATTRIBUTES ).length === 0 ? (
noAttributesPlaceholder()
) : (
<div { ...blockProps }>
{ getBlockControls() }
{ getInspectorControls() }
{ isEditing ? (
renderEditMode()
) : (
<div
className={ classnames(
className,
'wc-block-attribute-filter'
) }
>
<BlockTitle
className="wc-block-attribute-filter__title"
headingLevel={ headingLevel }
heading={ heading }
onChange={ ( value: string ) =>
setAttributes( { heading: value } )
}
/>
<Disabled>
<Block attributes={ attributes } isEditor />
</Disabled>
</div>
) }
</div>
);
};
export default withSpokenMessages( Edit );

View File

@@ -0,0 +1,49 @@
.editor-styles-wrapper .wp-block-woocommerce-attribute-filter {
// We need to override it because by default the global styles applied the border-style: solid;
// Our goal is not to have a border on main wrapper DOM element
border-style: none !important;
}
.wc-block-attribute-filter {
.components-placeholder__instructions {
border-bottom: 1px solid #e0e2e6;
width: 100%;
padding-bottom: 1em;
margin-bottom: 2em;
}
.components-placeholder__label svg {
fill: currentColor;
margin-right: 1ch;
}
.components-placeholder__fieldset {
display: block; /* Disable flex box */
}
.woocommerce-search-list__search {
border-top: 0;
margin-top: 0;
padding-top: 0;
}
.wc-block-attribute-filter__add-attribute-button {
margin: 0 0 1em;
vertical-align: middle;
height: auto;
padding: 0.5em 1em;
svg {
fill: currentColor;
margin-left: 0.5ch;
vertical-align: middle;
}
}
.wc-block-attribute-filter__read_more_button {
display: block;
margin-bottom: 1em;
}
.components-disabled {
border-radius: inherit;
border-color: inherit;
}
}

View File

@@ -0,0 +1,39 @@
/**
* External dependencies
*/
import { renderFrontend } from '@woocommerce/base-utils';
/**
* Internal dependencies
*/
import Block from './block';
import { blockAttributes } from './attributes';
import metadata from './block.json';
const getProps = ( el: HTMLElement ) => {
return {
isEditor: false,
attributes: {
attributeId: parseInt( el.dataset.attributeId || '0', 10 ),
showCounts: el.dataset.showCounts === 'true',
queryType:
el.dataset.queryType || metadata.attributes.queryType.default,
heading: el.dataset.heading || blockAttributes.heading.default,
headingLevel: el.dataset.headingLevel
? parseInt( el.dataset.headingLevel, 10 )
: metadata.attributes.headingLevel.default,
displayStyle:
el.dataset.displayStyle ||
metadata.attributes.displayStyle.default,
showFilterButton: el.dataset.showFilterButton === 'true',
isPreview: false,
className: el.dataset.className || '',
},
};
};
renderFrontend( {
selector: '.wp-block-woocommerce-attribute-filter',
Block,
getProps,
} );

View File

@@ -0,0 +1,114 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { createBlock, registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from '@wordpress/block-editor';
import { isFeaturePluginBuild } from '@woocommerce/block-settings';
import { Icon, category } from '@wordpress/icons';
import classNames from 'classnames';
/**
* Internal dependencies
*/
import edit from './edit';
import type { BlockAttributes } from './types';
import { blockAttributes } from './attributes';
import metadata from './block.json';
registerBlockType( metadata, {
title: __( 'Filter Products by Attribute', 'woo-gutenberg-products-block' ),
description: __(
'Allow customers to filter the grid by product attribute, such as color. Works in combination with the All Products block.',
'woo-gutenberg-products-block'
),
icon: {
src: (
<Icon
icon={ category }
className="wc-block-editor-components-block-icon"
/>
),
},
supports: {
...metadata.supports,
...( isFeaturePluginBuild() && {
__experimentalBorder: {
radius: true,
color: true,
width: false,
},
} ),
},
attributes: {
...metadata.attributes,
...blockAttributes,
},
transforms: {
from: [
{
type: 'block',
blocks: [ 'core/legacy-widget' ],
// We can't transform if raw instance isn't shown in the REST API.
isMatch: ( { idBase, instance } ) =>
idBase === 'woocommerce_layered_nav' && !! instance?.raw,
transform: ( { instance } ) =>
createBlock( 'woocommerce/attribute-filter', {
attributeId: 0,
showCounts: true,
queryType: instance?.raw?.query_type || 'or',
heading:
instance?.raw?.title ||
__(
'Filter by attribute',
'woo-gutenberg-products-block'
),
headingLevel: 3,
displayStyle: instance?.raw?.display_type || 'list',
showFilterButton: false,
isPreview: false,
} ),
},
],
},
edit,
// Save the props to post content.
save( { attributes }: { attributes: BlockAttributes } ) {
const {
className,
showCounts,
queryType,
attributeId,
heading,
headingLevel,
displayStyle,
showFilterButton,
} = attributes;
const data: Record< string, unknown > = {
'data-attribute-id': attributeId,
'data-show-counts': showCounts,
'data-query-type': queryType,
'data-heading': heading,
'data-heading-level': headingLevel,
};
if ( displayStyle !== 'list' ) {
data[ 'data-display-style' ] = displayStyle;
}
if ( showFilterButton ) {
data[ 'data-show-filter-button' ] = showFilterButton;
}
return (
<div
{ ...useBlockProps.save( {
className: classNames( 'is-loading', className ),
} ) }
{ ...data }
>
<span
aria-hidden
className="wc-block-product-attribute-filter__placeholder"
/>
</div>
);
},
} );

View File

@@ -0,0 +1,29 @@
/**
* External dependencies
*/
import Label from '@woocommerce/base-components/filter-element-label';
export const previewOptions = [
{
value: 'preview-1',
name: 'Blue',
label: <Label name="Blue" count={ 3 } />,
},
{
value: 'preview-2',
name: 'Green',
label: <Label name="Green" count={ 3 } />,
},
{
value: 'preview-3',
name: 'Red',
label: <Label name="Red" count={ 2 } />,
},
];
export const previewAttributeObject = {
id: 0,
name: 'preview',
taxonomy: 'preview',
label: 'Preview',
};

View File

@@ -0,0 +1,53 @@
.wp-block-woocommerce-attribute-filter {
// We need to override it because by default the global styles applied the border-style: solid;
// Our goal is not to have a border on main wrapper DOM element
border-style: none !important;
}
.wc-block-attribute-filter {
margin-bottom: $gap-large;
border-radius: inherit;
border-color: inherit;
&.style-dropdown {
display: flex;
gap: $gap;
border-radius: inherit;
border-color: inherit;
}
.wc-block-attribute-filter-list {
margin: 0;
width: 100%;
li {
label {
cursor: pointer;
}
input {
cursor: pointer;
display: inline-block;
}
}
}
.wc-block-attribute-filter-dropdown {
flex-grow: 1;
max-width: unset;
width: 0;
border-radius: inherit;
border-color: inherit;
}
.is-single .wc-block-attribute-filter-list-count,
.wc-block-dropdown-selector .wc-block-dropdown-selector__list .wc-block-attribute-filter-list-count {
opacity: 0.6;
}
.wc-block-components-dropdown-selector__input-wrapper {
height: 100%;
border-radius: inherit;
border-color: inherit;
}
}

View File

@@ -0,0 +1,26 @@
/**
* External dependencies
*/
import type { BlockEditProps } from '@wordpress/blocks';
export interface BlockAttributes {
className: string;
attributeId: number;
showCounts: boolean;
queryType: string;
heading: string;
headingLevel: number;
displayStyle: string;
showFilterButton: boolean;
isPreview: boolean;
}
export interface EditProps extends BlockEditProps< BlockAttributes > {
debouncedSpeak: ( label: string ) => void;
}
export interface DisplayOption {
value: string;
name: string;
label: JSX.Element;
}

View File

@@ -0,0 +1,95 @@
/**
* External dependencies
*/
import { addQueryArgs, removeQueryArgs } from '@wordpress/url';
import { QueryArgs } from '@wordpress/url/build-types/get-query-args';
import {
getUrlParameter,
PREFIX_QUERY_ARG_FILTER_TYPE,
PREFIX_QUERY_ARG_QUERY_TYPE,
} from '@woocommerce/utils';
import { AttributeObject } from '@woocommerce/types';
interface Param {
attribute: string;
operator: string;
slug: Array< string >;
}
export const parseTaxonomyToGenerateURL = ( taxonomy: string ) =>
taxonomy.replace( 'pa_', '' );
export const formatParams = ( url: string, params: Array< Param > = [] ) => {
const paramObject: Record< string, string > = {};
params.forEach( ( param ) => {
const { attribute, slug, operator } = param;
// Custom filters are prefix with `pa_` so we need to remove this.
const name = parseTaxonomyToGenerateURL( attribute );
const values = slug.join( ',' );
const queryType = `${ PREFIX_QUERY_ARG_QUERY_TYPE }${ name }`;
const type = operator === 'in' ? 'or' : 'and';
// The URL parameter requires the prefix filter_ with the attribute name.
paramObject[ `${ PREFIX_QUERY_ARG_FILTER_TYPE }${ name }` ] = values;
paramObject[ queryType ] = type;
} );
// Clean the URL before we add our new query parameters to it.
const cleanUrl = removeQueryArgs( url, ...Object.keys( paramObject ) );
return addQueryArgs( cleanUrl, paramObject );
};
export const areAllFiltersRemoved = ( {
currentCheckedFilters,
hasSetPhpFilterDefaults,
}: {
currentCheckedFilters: Array< string >;
hasSetPhpFilterDefaults: boolean;
} ) => hasSetPhpFilterDefaults && currentCheckedFilters.length === 0;
export const getActiveFilters = (
isFilteringForPhpTemplateEnabled: boolean,
attributeObject: AttributeObject | undefined
) => {
if ( isFilteringForPhpTemplateEnabled && attributeObject ) {
const defaultAttributeParam = getUrlParameter(
`filter_${ attributeObject.name }`
);
const defaultCheckedValue =
typeof defaultAttributeParam === 'string'
? defaultAttributeParam.split( ',' )
: [];
return defaultCheckedValue;
}
return [];
};
export const isQueryArgsEqual = (
currentQueryArgs: QueryArgs,
newQueryArgs: QueryArgs
) => {
// The user can add same two filter blocks for the same attribute.
// We removed the query type from the check to avoid refresh loop.
const filteredNewQueryArgs = Object.entries( newQueryArgs ).reduce(
( acc, [ key, value ] ) => {
return key.includes( 'query_type' )
? acc
: {
...acc,
[ key ]: value,
};
},
{}
);
return Object.entries( filteredNewQueryArgs ).reduce(
( isEqual, [ key, value ] ) =>
currentQueryArgs[ key ] === value ? isEqual : false,
true
);
};

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { getBlockTypes } from '@wordpress/blocks';
// List of core block types to allow in inner block areas.
const coreBlockTypes = [ 'core/paragraph', 'core/image', 'core/separator' ];
/**
* Gets a list of allowed blocks types under a specific parent block type.
*/
export const getAllowedBlocks = ( block: string ): string[] => [
...getBlockTypes()
.filter( ( blockType ) =>
( blockType?.parent || [] ).includes( block )
)
.map( ( { name } ) => name ),
...coreBlockTypes,
];

View File

@@ -0,0 +1,176 @@
/**
* HACKS
*
* This file contains functionality to "lock" blocks i.e. to prevent blocks being moved or deleted. This needs to be
* kept in place until native support for locking is available in WordPress (estimated WordPress 5.9).
*/
/**
* @todo Remove custom block locking (requires native WordPress support)
*/
/**
* External dependencies
*/
import {
useBlockProps,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { isTextField } from '@wordpress/dom';
import { subscribe, select as _select } from '@wordpress/data';
import { useEffect, useRef } from '@wordpress/element';
import { MutableRefObject } from 'react';
import { BACKSPACE, DELETE } from '@wordpress/keycodes';
import { hasFilter } from '@wordpress/hooks';
import { getBlockType } from '@wordpress/blocks';
/**
* Toggle class on body.
*
* @param {string} className CSS Class name.
* @param {boolean} add True to add, false to remove.
*/
const toggleBodyClass = ( className: string, add = true ) => {
if ( add ) {
window.document.body.classList.add( className );
} else {
window.document.body.classList.remove( className );
}
};
/**
* addClassToBody
*
* This components watches the current selected block and adds a class name to the body if that block is locked. If the
* current block is not locked, it removes the class name. The appended body class is used to hide UI elements to prevent
* the block from being deleted.
*
* We use a component so we can react to changes in the store.
*/
export const addClassToBody = (): void => {
if ( ! hasFilter( 'blocks.registerBlockType', 'core/lock/addAttribute' ) ) {
subscribe( () => {
const blockEditorSelect = _select( blockEditorStore );
if ( ! blockEditorSelect ) {
return;
}
const selectedBlock = blockEditorSelect.getSelectedBlock();
if ( ! selectedBlock ) {
return;
}
toggleBodyClass(
'wc-lock-selected-block--remove',
!! selectedBlock?.attributes?.lock?.remove
);
toggleBodyClass(
'wc-lock-selected-block--move',
!! selectedBlock?.attributes?.lock?.move
);
} );
}
};
const isBlockLocked = ( clientId: string ): boolean => {
if ( ! clientId ) {
return false;
}
const { getBlock } = _select( blockEditorStore );
const block = getBlock( clientId );
// If lock.remove is defined at the block instance (not using the default value)
// Then we use it.
if ( typeof block?.attributes?.lock?.remove === 'boolean' ) {
return block.attributes.lock.remove;
}
// If we don't have lock on the block instance, we check the type
const blockType = getBlockType( block.name );
if ( typeof blockType?.attributes?.lock?.default?.remove === 'boolean' ) {
return blockType?.attributes?.lock?.default?.remove;
}
// If nothing is defined, return false
return false;
};
/**
* This is a hook we use in conjunction with useBlockProps. Its goal is to check if of the block's children is locked and being deleted.
* It will stop the keydown event from propagating to stop it from being deleted via the keyboard.
*
*/
const useLockedChildren = ( {
ref,
}: {
ref: MutableRefObject< HTMLElement | undefined >;
} ): void => {
const lockInCore = hasFilter(
'blocks.registerBlockType',
'core/lock/addAttribute'
);
const node = ref.current;
return useEffect( () => {
if ( ! node || lockInCore ) {
return;
}
function onKeyDown( event: KeyboardEvent ) {
const { keyCode, target } = event;
if ( ! ( target instanceof HTMLElement ) ) {
return;
}
// We're not trying to delete something here.
if ( keyCode !== BACKSPACE && keyCode !== DELETE ) {
return;
}
// We're in a field, so we should let text be deleted.
if ( isTextField( target ) ) {
return;
}
// Typecast to fix issue with isTextField.
const targetNode = target as HTMLElement;
// Our target isn't a block.
if ( targetNode.dataset.block === undefined ) {
return;
}
const clientId = targetNode.dataset.block;
const isLocked = isBlockLocked( clientId );
// Prevent the keyboard event from propogating if it supports locking.
if ( isLocked ) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
}
node.addEventListener( 'keydown', onKeyDown, {
capture: true,
passive: false,
} );
return () => {
node.removeEventListener( 'keydown', onKeyDown, {
capture: true,
} );
};
}, [ node, lockInCore ] );
};
/**
* This hook is a light wrapper to useBlockProps, it wraps that hook plus useLockBlock to pass data between them.
*/
export const useBlockPropsWithLocking = (
props: Record< string, unknown > = {}
): Record< string, unknown > => {
const ref = useRef< HTMLElement >();
const blockProps = useBlockProps( { ref, ...props } );
useLockedChildren( {
ref,
} );
return blockProps;
};

View File

@@ -0,0 +1,4 @@
export * from './hacks';
export * from './use-forced-layout';
export * from './editor-utils';
export * from './use-view-switcher';

View File

@@ -0,0 +1,158 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
useExpressPaymentMethods,
usePaymentMethodInterface,
} from '@woocommerce/base-context/hooks';
import {
cloneElement,
isValidElement,
useCallback,
useRef,
} from '@wordpress/element';
import {
useEditorContext,
usePaymentMethodDataContext,
} from '@woocommerce/base-context';
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import PaymentMethodErrorBoundary from './payment-method-error-boundary';
const ExpressPaymentMethods = () => {
const { isEditor } = useEditorContext();
const {
setActivePaymentMethod,
setExpressPaymentError,
activePaymentMethod,
paymentMethodData,
setPaymentStatus,
} = usePaymentMethodDataContext();
const paymentMethodInterface = usePaymentMethodInterface();
const { paymentMethods } = useExpressPaymentMethods();
const previousActivePaymentMethod = useRef( activePaymentMethod );
const previousPaymentMethodData = useRef( paymentMethodData );
/**
* onExpressPaymentClick should be triggered when the express payment button is clicked.
*
* This will store the previous active payment method, set the express method as active, and set the payment status
* to started.
*/
const onExpressPaymentClick = useCallback(
( paymentMethodId ) => () => {
previousActivePaymentMethod.current = activePaymentMethod;
previousPaymentMethodData.current = paymentMethodData;
setPaymentStatus().started();
setActivePaymentMethod( paymentMethodId );
},
[
activePaymentMethod,
paymentMethodData,
setActivePaymentMethod,
setPaymentStatus,
]
);
/**
* onExpressPaymentClose should be triggered when the express payment process is cancelled or closed.
*
* This restores the active method and returns the state to pristine.
*/
const onExpressPaymentClose = useCallback( () => {
setPaymentStatus().pristine();
setActivePaymentMethod(
previousActivePaymentMethod.current,
previousPaymentMethodData.current
);
}, [ setActivePaymentMethod, setPaymentStatus ] );
/**
* onExpressPaymentError should be triggered when the express payment process errors.
*
* This shows an error message then restores the active method and returns the state to pristine.
*/
const onExpressPaymentError = useCallback(
( errorMessage ) => {
setPaymentStatus().error( errorMessage );
setExpressPaymentError( errorMessage );
setActivePaymentMethod(
previousActivePaymentMethod.current,
previousPaymentMethodData.current
);
},
[ setActivePaymentMethod, setPaymentStatus, setExpressPaymentError ]
);
/**
* Calling setExpressPaymentError directly is deprecated.
*/
const deprecatedSetExpressPaymentError = useCallback(
( errorMessage = '' ) => {
deprecated(
'Express Payment Methods should use the provided onError handler instead.',
{
alternative: 'onError',
plugin: 'woocommerce-gutenberg-products-block',
link: 'https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/4228',
}
);
if ( errorMessage ) {
onExpressPaymentError( errorMessage );
} else {
setExpressPaymentError( '' );
}
},
[ setExpressPaymentError, onExpressPaymentError ]
);
/**
* @todo Find a way to Memoize Express Payment Method Content
*
* Payment method content could potentially become a bottleneck if lots of logic is ran in the content component. It
* Currently re-renders excessively but is not easy to useMemo because paymentMethodInterface could become stale.
* paymentMethodInterface itself also updates on most renders.
*/
const entries = Object.entries( paymentMethods );
const content =
entries.length > 0 ? (
entries.map( ( [ id, paymentMethod ] ) => {
const expressPaymentMethod = isEditor
? paymentMethod.edit
: paymentMethod.content;
return isValidElement( expressPaymentMethod ) ? (
<li key={ id } id={ `express-payment-method-${ id }` }>
{ cloneElement( expressPaymentMethod, {
...paymentMethodInterface,
onClick: onExpressPaymentClick( id ),
onClose: onExpressPaymentClose,
onError: onExpressPaymentError,
setExpressPaymentError:
deprecatedSetExpressPaymentError,
} ) }
</li>
) : null;
} )
) : (
<li key="noneRegistered">
{ __(
'No registered Payment Methods',
'woocommerce'
) }
</li>
);
return (
<PaymentMethodErrorBoundary isEditor={ isEditor }>
<ul className="wc-block-components-express-payment__event-buttons">
{ content }
</ul>
</PaymentMethodErrorBoundary>
);
};
export default ExpressPaymentMethods;

View File

@@ -0,0 +1,75 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
useEmitResponse,
useExpressPaymentMethods,
} from '@woocommerce/base-context/hooks';
import {
StoreNoticesContainer,
useCheckoutContext,
usePaymentMethodDataContext,
} from '@woocommerce/base-context';
import LoadingMask from '@woocommerce/base-components/loading-mask';
/**
* Internal dependencies
*/
import ExpressPaymentMethods from '../express-payment-methods';
import './style.scss';
const CartExpressPayment = () => {
const { paymentMethods, isInitialized } = useExpressPaymentMethods();
const { noticeContexts } = useEmitResponse();
const {
isCalculating,
isProcessing,
isAfterProcessing,
isBeforeProcessing,
isComplete,
hasError,
} = useCheckoutContext();
const { currentStatus: paymentStatus } = usePaymentMethodDataContext();
if (
! isInitialized ||
( isInitialized && Object.keys( paymentMethods ).length === 0 )
) {
return null;
}
// Set loading state for express payment methods when payment or checkout is in progress.
const checkoutProcessing =
isProcessing ||
isAfterProcessing ||
isBeforeProcessing ||
( isComplete && ! hasError );
return (
<>
<LoadingMask
isLoading={
isCalculating ||
checkoutProcessing ||
paymentStatus.isDoingExpressPayment
}
>
<div className="wc-block-components-express-payment wc-block-components-express-payment--cart">
<div className="wc-block-components-express-payment__content">
<StoreNoticesContainer
context={ noticeContexts.EXPRESS_PAYMENTS }
/>
<ExpressPaymentMethods />
</div>
</div>
</LoadingMask>
<div className="wc-block-components-express-payment-continue-rule wc-block-components-express-payment-continue-rule--cart">
{ /* translators: Shown in the Cart block between the express payment methods and the Proceed to Checkout button */ }
{ __( 'Or', 'woocommerce' ) }
</div>
</>
);
};
export default CartExpressPayment;

View File

@@ -0,0 +1,104 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
useEmitResponse,
useExpressPaymentMethods,
} from '@woocommerce/base-context/hooks';
import {
StoreNoticesContainer,
useCheckoutContext,
usePaymentMethodDataContext,
useEditorContext,
} from '@woocommerce/base-context';
import Title from '@woocommerce/base-components/title';
import LoadingMask from '@woocommerce/base-components/loading-mask';
import { CURRENT_USER_IS_ADMIN } from '@woocommerce/settings';
/**
* Internal dependencies
*/
import ExpressPaymentMethods from '../express-payment-methods';
import './style.scss';
const CheckoutExpressPayment = () => {
const {
isCalculating,
isProcessing,
isAfterProcessing,
isBeforeProcessing,
isComplete,
hasError,
} = useCheckoutContext();
const { currentStatus: paymentStatus } = usePaymentMethodDataContext();
const { paymentMethods, isInitialized } = useExpressPaymentMethods();
const { isEditor } = useEditorContext();
const { noticeContexts } = useEmitResponse();
if (
! isInitialized ||
( isInitialized && Object.keys( paymentMethods ).length === 0 )
) {
// Make sure errors are shown in the editor and for admins. For example,
// when a payment method fails to register.
if ( isEditor || CURRENT_USER_IS_ADMIN ) {
return (
<StoreNoticesContainer
context={ noticeContexts.EXPRESS_PAYMENTS }
/>
);
}
return null;
}
// Set loading state for express payment methods when payment or checkout is in progress.
const checkoutProcessing =
isProcessing ||
isAfterProcessing ||
isBeforeProcessing ||
( isComplete && ! hasError );
return (
<>
<LoadingMask
isLoading={
isCalculating ||
checkoutProcessing ||
paymentStatus.isDoingExpressPayment
}
>
<div className="wc-block-components-express-payment wc-block-components-express-payment--checkout">
<div className="wc-block-components-express-payment__title-container">
<Title
className="wc-block-components-express-payment__title"
headingLevel="2"
>
{ __(
'Express checkout',
'woocommerce'
) }
</Title>
</div>
<div className="wc-block-components-express-payment__content">
<StoreNoticesContainer
context={ noticeContexts.EXPRESS_PAYMENTS }
/>
<p>
{ __(
'In a hurry? Use one of our express checkout options:',
'woocommerce'
) }
</p>
<ExpressPaymentMethods />
</div>
</div>
</LoadingMask>
<div className="wc-block-components-express-payment-continue-rule wc-block-components-express-payment-continue-rule--checkout">
{ __( 'Or continue below', 'woocommerce' ) }
</div>
</>
);
};
export default CheckoutExpressPayment;

View File

@@ -0,0 +1,2 @@
export { default as CartExpressPayment } from './cart-express-payment.js';
export { default as CheckoutExpressPayment } from './checkout-express-payment.js';

View File

@@ -0,0 +1,162 @@
$border-width: 1px;
$border-radius: 5px;
.wc-block-components-express-payment {
margin: auto;
position: relative;
.wc-block-components-express-payment__event-buttons {
list-style: none;
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
padding: 0;
margin: 0;
overflow: hidden;
text-align: center;
> li {
margin: 0;
> img {
width: 100%;
height: 48px;
}
}
}
}
.wc-block-components-express-payment--checkout {
margin-top: $border-radius;
.wc-block-components-express-payment__title-container {
display: flex;
flex-direction: row;
left: 0;
position: absolute;
right: 0;
top: -$border-radius;
vertical-align: middle;
// Pseudo-elements used to show the border before and after the title.
&::before {
border-left: $border-width solid currentColor;
border-top: $border-width solid currentColor;
border-radius: $border-radius 0 0 0;
content: "";
display: block;
height: $border-radius - $border-width;
margin-right: $gap-small;
opacity: 0.3;
pointer-events: none;
width: #{$gap-large - $gap-small - $border-width * 2};
}
&::after {
border-right: $border-width solid currentColor;
border-top: $border-width solid currentColor;
border-radius: 0 $border-radius 0 0;
content: "";
display: block;
height: $border-radius - $border-width;
margin-left: $gap-small;
opacity: 0.3;
pointer-events: none;
flex-grow: 1;
}
}
.wc-block-components-express-payment__title {
flex-grow: 0;
transform: translateY(-50%);
}
.wc-block-components-express-payment__content {
@include with-translucent-border(0 $border-width $border-width);
padding: em($gap-large) #{$gap-large - $border-width};
&::after {
border-radius: 0 0 $border-radius $border-radius;
}
> p {
margin-bottom: em($gap);
}
}
.wc-block-components-express-payment__event-buttons {
> li {
display: inline-block;
width: 50%;
}
> li:only-child {
display: block;
width: 100%;
}
> li:nth-child(even) {
padding-left: $gap-smaller;
}
> li:nth-child(odd) {
padding-right: $gap-smaller;
}
}
}
.wc-block-components-express-payment--cart {
.wc-block-components-express-payment__event-buttons {
> li {
padding-bottom: $gap;
text-align: center;
width: 100%;
&:last-child {
padding-bottom: 0;
}
}
}
}
.wc-block-components-express-payment-continue-rule {
display: flex;
align-items: center;
text-align: center;
padding: 0 $gap-large;
margin: $gap-large 0;
&::before {
margin-right: 10px;
}
&::after {
margin-left: 10px;
}
&::before,
&::after {
content: " ";
flex: 1;
border-bottom: 1px solid;
opacity: 0.3;
}
}
.wc-block-components-express-payment-continue-rule--cart {
margin: $gap 0;
text-transform: uppercase;
}
.theme-twentynineteen {
.wc-block-components-express-payment__title::before {
display: none;
}
}
// For Twenty Twenty we need to increase specificity of the title.
.theme-twentytwenty {
.wc-block-components-express-payment .wc-block-components-express-payment__title {
padding-left: $gap-small;
padding-right: $gap-small;
}
}

View File

@@ -0,0 +1,4 @@
export { default as PaymentMethods } from './payment-methods';
export { default as ExpressPaymentMethods } from './express-payment-methods';
export { CartExpressPayment, CheckoutExpressPayment } from './express-payment';
export { default as SavedPaymentMethodOptions } from './saved-payment-method-options';

View File

@@ -0,0 +1,81 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { Placeholder, Button, Notice } from 'wordpress-components';
import { Icon, payment } from '@wordpress/icons';
import { ADMIN_URL } from '@woocommerce/settings';
import { useEditorContext } from '@woocommerce/base-context';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import './style.scss';
/**
* Render content when no payment methods are found depending on context.
*/
const NoPaymentMethods = () => {
const { isEditor } = useEditorContext();
return isEditor ? (
<NoPaymentMethodsPlaceholder />
) : (
<NoPaymentMethodsNotice />
);
};
/**
* Renders a placeholder in the editor.
*/
const NoPaymentMethodsPlaceholder = () => {
return (
<Placeholder
icon={ <Icon icon={ payment } /> }
label={ __( 'Payment methods', 'woocommerce' ) }
className="wc-block-checkout__no-payment-methods-placeholder"
>
<span className="wc-block-checkout__no-payment-methods-placeholder-description">
{ __(
'Your store does not have any payment methods configured that support the checkout block. Once you have configured a compatible payment method it will be shown here.',
'woocommerce'
) }
</span>
<Button
isSecondary
href={ `${ ADMIN_URL }admin.php?page=wc-settings&tab=checkout` }
target="_blank"
rel="noopener noreferrer"
>
{ __(
'Configure Payment Methods',
'woocommerce'
) }
</Button>
</Placeholder>
);
};
/**
* Renders a notice on the frontend.
*/
const NoPaymentMethodsNotice = () => {
return (
<Notice
isDismissible={ false }
className={ classnames(
'wc-block-checkout__no-payment-methods-notice',
'woocommerce-message',
'woocommerce-error'
) }
>
{ __(
'There are no payment methods available. This may be an error on our side. Please contact us if you need any help placing your order.',
'woocommerce'
) }
</Notice>
);
};
export default NoPaymentMethods;

View File

@@ -0,0 +1,25 @@
.components-placeholder.wc-block-checkout__no-payment-methods-placeholder {
margin-bottom: $gap;
* {
pointer-events: all; // Overrides parent disabled component in editor context
}
.components-placeholder__fieldset {
display: block;
.components-button {
background-color: $gray-900;
color: $white;
}
.wc-block-checkout__no-payment-methods-placeholder-description {
display: block;
margin: 0.25em 0 1em 0;
}
}
}
.components-notice.wc-block-checkout__no-payment-methods-notice {
margin-bottom: $gap;
}

View File

@@ -0,0 +1,59 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
useCheckoutContext,
useEditorContext,
usePaymentMethodDataContext,
} from '@woocommerce/base-context';
import { CheckboxControl } from '@woocommerce/blocks-checkout';
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import PaymentMethodErrorBoundary from './payment-method-error-boundary';
/**
* Component used to render the contents of a payment method card.
*
* @param {Object} props Incoming props for the component.
* @param {boolean} props.showSaveOption Whether that payment method allows saving
* the data for future purchases.
* @param {Object} props.children Content of the payment method card.
*
* @return {*} The rendered component.
*/
const PaymentMethodCard = ( { children, showSaveOption } ) => {
const { isEditor } = useEditorContext();
const { shouldSavePayment, setShouldSavePayment } =
usePaymentMethodDataContext();
const { customerId } = useCheckoutContext();
return (
<PaymentMethodErrorBoundary isEditor={ isEditor }>
{ children }
{ customerId > 0 && showSaveOption && (
<CheckboxControl
className="wc-block-components-payment-methods__save-card-info"
label={ __(
'Save payment information to my account for future purchases.',
'woocommerce'
) }
checked={ shouldSavePayment }
onChange={ () =>
setShouldSavePayment( ! shouldSavePayment )
}
/>
) }
</PaymentMethodErrorBoundary>
);
};
PaymentMethodCard.propTypes = {
showSaveOption: PropTypes.bool,
children: PropTypes.node,
};
export default PaymentMethodCard;

View File

@@ -0,0 +1,68 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { Component } from 'react';
import PropTypes from 'prop-types';
import { CURRENT_USER_IS_ADMIN } from '@woocommerce/settings';
import { StoreNoticesContainer } from '@woocommerce/base-context';
import { noticeContexts } from '@woocommerce/base-context/hooks';
class PaymentMethodErrorBoundary extends Component {
state = { errorMessage: '', hasError: false };
static getDerivedStateFromError( error ) {
return {
errorMessage: error.message,
hasError: true,
};
}
render() {
const { hasError, errorMessage } = this.state;
const { isEditor } = this.props;
if ( hasError ) {
let errorText = __(
'This site is experiencing difficulties with this payment method. Please contact the owner of the site for assistance.',
'woocommerce'
);
if ( isEditor || CURRENT_USER_IS_ADMIN ) {
if ( errorMessage ) {
errorText = errorMessage;
} else {
errorText = __(
"There was an error with this payment method. Please verify it's configured correctly.",
'woocommerce'
);
}
}
const notices = [
{
id: '0',
content: errorText,
isDismissible: false,
status: 'error',
},
];
return (
<StoreNoticesContainer
additionalNotices={ notices }
context={ noticeContexts.PAYMENTS }
/>
);
}
return this.props.children;
}
}
PaymentMethodErrorBoundary.propTypes = {
isEditor: PropTypes.bool,
};
PaymentMethodErrorBoundary.defaultProps = {
isEditor: false,
};
export default PaymentMethodErrorBoundary;

View File

@@ -0,0 +1,102 @@
/**
* External dependencies
*/
import {
usePaymentMethods,
usePaymentMethodInterface,
useEmitResponse,
useStoreEvents,
} from '@woocommerce/base-context/hooks';
import { cloneElement, useCallback } from '@wordpress/element';
import {
useEditorContext,
usePaymentMethodDataContext,
} from '@woocommerce/base-context';
import classNames from 'classnames';
import RadioControlAccordion from '@woocommerce/base-components/radio-control-accordion';
import { useDispatch } from '@wordpress/data';
/**
* Internal dependencies
*/
import PaymentMethodCard from './payment-method-card';
/**
* Component used to render all non-saved payment method options.
*
* @return {*} The rendered component.
*/
const PaymentMethodOptions = () => {
const {
setActivePaymentMethod,
activeSavedToken,
isExpressPaymentMethodActive,
customerPaymentMethods,
} = usePaymentMethodDataContext();
const { paymentMethods } = usePaymentMethods();
const { activePaymentMethod, ...paymentMethodInterface } =
usePaymentMethodInterface();
const { noticeContexts } = useEmitResponse();
const { removeNotice } = useDispatch( 'core/notices' );
const { dispatchCheckoutEvent } = useStoreEvents();
const { isEditor } = useEditorContext();
const options = Object.keys( paymentMethods ).map( ( name ) => {
const { edit, content, label, supports } = paymentMethods[ name ];
const component = isEditor ? edit : content;
return {
value: name,
label:
typeof label === 'string'
? label
: cloneElement( label, {
components: paymentMethodInterface.components,
} ),
name: `wc-saved-payment-method-token-${ name }`,
content: (
<PaymentMethodCard showSaveOption={ supports.showSaveOption }>
{ cloneElement( component, {
activePaymentMethod,
...paymentMethodInterface,
} ) }
</PaymentMethodCard>
),
};
} );
const onChange = useCallback(
( value ) => {
setActivePaymentMethod( value );
removeNotice( 'wc-payment-error', noticeContexts.PAYMENTS );
dispatchCheckoutEvent( 'set-active-payment-method', {
value,
} );
},
[
dispatchCheckoutEvent,
noticeContexts.PAYMENTS,
removeNotice,
setActivePaymentMethod,
]
);
const isSinglePaymentMethod =
Object.keys( customerPaymentMethods ).length === 0 &&
Object.keys( paymentMethods ).length === 1;
const singleOptionClass = classNames( {
'disable-radio-control': isSinglePaymentMethod,
} );
return isExpressPaymentMethodActive ? null : (
<RadioControlAccordion
id={ 'wc-payment-method-options' }
className={ singleOptionClass }
selected={ activeSavedToken ? null : activePaymentMethod }
onChange={ onChange }
options={ options }
/>
);
};
export default PaymentMethodOptions;

View File

@@ -0,0 +1,55 @@
/**
* External dependencies
*/
import { usePaymentMethods } from '@woocommerce/base-context/hooks';
import { __ } from '@wordpress/i18n';
import Label from '@woocommerce/base-components/label';
import { usePaymentMethodDataContext } from '@woocommerce/base-context';
/**
* Internal dependencies
*/
import NoPaymentMethods from './no-payment-methods';
import PaymentMethodOptions from './payment-method-options';
import SavedPaymentMethodOptions from './saved-payment-method-options';
/**
* PaymentMethods component.
*
* @return {*} The rendered component.
*/
const PaymentMethods = () => {
const { isInitialized, paymentMethods } = usePaymentMethods();
const { customerPaymentMethods } = usePaymentMethodDataContext();
if ( isInitialized && Object.keys( paymentMethods ).length === 0 ) {
return <NoPaymentMethods />;
}
return (
<>
<SavedPaymentMethodOptions />
{ Object.keys( customerPaymentMethods ).length > 0 && (
<Label
label={ __(
'Use another payment method.',
'woocommerce'
) }
screenReaderLabel={ __(
'Other available payment methods',
'woocommerce'
) }
wrapperElement="p"
wrapperProps={ {
className: [
'wc-block-components-checkout-step__description wc-block-components-checkout-step__description-payments-aligned',
],
} }
/>
) }
<PaymentMethodOptions />
</>
);
};
export default PaymentMethods;

View File

@@ -0,0 +1,145 @@
/**
* External dependencies
*/
import { useMemo, cloneElement } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { usePaymentMethodDataContext } from '@woocommerce/base-context';
import RadioControl from '@woocommerce/base-components/radio-control';
import {
usePaymentMethodInterface,
usePaymentMethods,
useStoreEvents,
useEmitResponse,
} from '@woocommerce/base-context/hooks';
import { useDispatch } from '@wordpress/data';
/**
* @typedef {import('@woocommerce/type-defs/contexts').CustomerPaymentMethod} CustomerPaymentMethod
* @typedef {import('@woocommerce/type-defs/contexts').PaymentStatusDispatch} PaymentStatusDispatch
*/
/**
* Returns the option object for a cc or echeck saved payment method token.
*
* @param {CustomerPaymentMethod} savedPaymentMethod
* @return {string} label
*/
const getCcOrEcheckLabel = ( { method, expires } ) => {
return sprintf(
/* translators: %1$s is referring to the payment method brand, %2$s is referring to the last 4 digits of the payment card, %3$s is referring to the expiry date. */
__(
'%1$s ending in %2$s (expires %3$s)',
'woocommerce'
),
method.brand,
method.last4,
expires
);
};
/**
* Returns the option object for any non specific saved payment method.
*
* @param {CustomerPaymentMethod} savedPaymentMethod
* @return {string} label
*/
const getDefaultLabel = ( { method } ) => {
/* For saved payment methods with brand & last 4 */
if ( method.brand && method.last4 ) {
return sprintf(
/* translators: %1$s is referring to the payment method brand, %2$s is referring to the last 4 digits of the payment card. */
__( '%1$s ending in %2$s', 'woocommerce' ),
method.brand,
method.last4
);
}
/* For saved payment methods without brand & last 4 */
return sprintf(
/* translators: %s is the name of the payment method gateway. */
__( 'Saved token for %s', 'woocommerce' ),
method.gateway
);
};
const SavedPaymentMethodOptions = () => {
const {
customerPaymentMethods,
activePaymentMethod,
setActivePaymentMethod,
activeSavedToken,
} = usePaymentMethodDataContext();
const { paymentMethods } = usePaymentMethods();
const paymentMethodInterface = usePaymentMethodInterface();
const { noticeContexts } = useEmitResponse();
const { removeNotice } = useDispatch( 'core/notices' );
const { dispatchCheckoutEvent } = useStoreEvents();
const options = useMemo( () => {
const types = Object.keys( customerPaymentMethods );
return types
.flatMap( ( type ) => {
const typeMethods = customerPaymentMethods[ type ];
return typeMethods.map( ( paymentMethod ) => {
const isCC = type === 'cc' || type === 'echeck';
const paymentMethodSlug = paymentMethod.method.gateway;
return {
name: `wc-saved-payment-method-token-${ paymentMethodSlug }`,
label: isCC
? getCcOrEcheckLabel( paymentMethod )
: getDefaultLabel( paymentMethod ),
value: paymentMethod.tokenId.toString(),
onChange: ( token ) => {
const savedTokenKey = `wc-${ paymentMethodSlug }-payment-token`;
setActivePaymentMethod( paymentMethodSlug, {
token,
payment_method: paymentMethodSlug,
[ savedTokenKey ]: token.toString(),
isSavedToken: true,
} );
removeNotice(
'wc-payment-error',
noticeContexts.PAYMENTS
);
dispatchCheckoutEvent(
'set-active-payment-method',
{
paymentMethodSlug,
}
);
},
};
} );
} )
.filter( Boolean );
}, [
customerPaymentMethods,
setActivePaymentMethod,
removeNotice,
noticeContexts.PAYMENTS,
dispatchCheckoutEvent,
] );
const savedPaymentMethodHandler =
!! activeSavedToken &&
paymentMethods[ activePaymentMethod ] &&
paymentMethods[ activePaymentMethod ]?.savedTokenComponent
? cloneElement(
paymentMethods[ activePaymentMethod ]?.savedTokenComponent,
{ token: activeSavedToken, ...paymentMethodInterface }
)
: null;
return options.length > 0 ? (
<>
<RadioControl
id={ 'wc-payment-method-saved-tokens' }
selected={ activeSavedToken }
options={ options }
/>
{ savedPaymentMethodHandler }
</>
) : null;
};
export default SavedPaymentMethodOptions;

View File

@@ -0,0 +1,254 @@
.wc-block-card-elements {
display: flex;
width: 100%;
.wc-block-components-validation-error {
position: static;
}
}
.wc-block-gateway-container {
position: relative;
margin-bottom: em($gap-large);
white-space: nowrap;
&.wc-card-number-element {
flex-basis: 15em;
flex-grow: 1;
// Currently, min() CSS function calls need to be wrapped with unquote.
min-width: string.unquote("min(15em, 60%)");
}
&.wc-card-expiry-element {
flex-basis: 7em;
margin-left: $gap-small;
min-width: string.unquote("min(7em, calc(24% - #{$gap-small}))");
}
&.wc-card-cvc-element {
flex-basis: 7em;
margin-left: $gap-small;
// Notice the min width ems value is smaller than flex-basis. That's because
// by default we want it to have the same width as `expiry-element`, but
// if available space is scarce, `cvc-element` should get smaller faster.
min-width: string.unquote("min(5em, calc(16% - #{$gap-small}))");
}
.wc-block-gateway-input {
@include font-size(regular);
line-height: 1.375; // =22px when font-size is 16px.
background-color: #fff;
padding: em($gap-small) 0 em($gap-small) $gap;
border-radius: 4px;
border: 1px solid $input-border-gray;
width: 100%;
font-family: inherit;
margin: 0;
box-sizing: border-box;
height: 3em;
color: $input-text-active;
cursor: text;
&:focus {
background-color: #fff;
}
}
&:focus {
background-color: #fff;
}
label {
@include reset-typography();
@include font-size(regular);
line-height: 1.375; // =22px when font-size is 16px.
position: absolute;
transform: translateY(0.75em);
left: 0;
top: 0;
transform-origin: top left;
color: $gray-700;
transition: transform 200ms ease;
margin: 0 0 0 #{$gap + 1px};
overflow: hidden;
text-overflow: ellipsis;
max-width: calc(100% - #{$gap + $gap-smaller});
cursor: text;
@media screen and (prefers-reduced-motion: reduce) {
transition: none;
}
}
&.wc-inline-card-element {
label {
// $gap is the padding of the input box, 1.5em the width of the card
// icon and $gap-smaller the space between the card
// icon and the label.
margin-left: calc(#{$gap + $gap-smaller} + 1.5em);
}
.wc-block-gateway-input.focused.empty,
.wc-block-gateway-input:not(.empty) {
+ label {
margin-left: $gap;
transform: translateY(#{$gap-smallest}) scale(0.75);
}
}
+ .wc-block-components-validation-error {
position: static;
margin-top: -$gap-large;
}
}
.wc-block-gateway-input.focused.empty,
.wc-block-gateway-input:not(.empty) {
padding: em($gap-large) 0 em($gap-smallest) $gap;
+ label {
transform: translateY(#{$gap-smallest}) scale(0.75);
}
}
.wc-block-gateway-input.has-error {
border-color: $alert-red;
&:focus {
outline-color: $alert-red;
}
}
.wc-block-gateway-input.has-error + label {
color: $alert-red;
}
}
// These elements have available space below, so we can display errors with a
// larger line height.
.is-medium,
.is-large {
.wc-card-expiry-element,
.wc-card-cvc-element {
.wc-block-components-validation-error > p {
line-height: 16px;
padding-top: 4px;
}
}
}
.is-mobile,
.is-small {
.wc-card-expiry-element,
.wc-card-cvc-element {
.wc-block-components-validation-error > p {
min-height: 28px;
}
}
}
.wc-block-components-checkout-payment-methods * {
pointer-events: all; // Overrides parent disabled component in editor context
}
.is-mobile,
.is-small {
.wc-block-card-elements {
flex-wrap: wrap;
}
.wc-block-gateway-container.wc-card-number-element {
flex-basis: 100%;
}
.wc-block-gateway-container.wc-card-expiry-element {
flex-basis: calc(50% - #{$gap-smaller});
margin-left: 0;
margin-right: $gap-smaller;
}
.wc-block-gateway-container.wc-card-cvc-element {
flex-basis: calc(50% - #{$gap-smaller});
margin-left: $gap-smaller;
}
}
.wc-block-checkout__payment-method {
.wc-block-components-radio-control__option {
padding-left: 56px;
&::after {
content: none;
}
.wc-block-components-radio-control__input {
left: 16px;
}
}
// We need to add the first-child and last-child pseudoclasses for specificity.
.wc-block-components-radio-control__option,
.wc-block-components-radio-control__option:first-child,
.wc-block-components-radio-control__option:last-child {
margin: 0;
padding-bottom: em($gap);
padding-top: em($gap);
}
.wc-block-components-radio-control__option-checked {
font-weight: bold;
}
.wc-block-components-radio-control-accordion-option,
.wc-block-components-radio-control__option {
@include with-translucent-border(1px 1px 0 1px);
}
.wc-block-components-radio-control__option:last-child::after,
.wc-block-components-radio-control-accordion-option:last-child::after {
border-width: 1px;
}
.wc-block-components-radio-control-accordion-option {
.wc-block-components-radio-control__option::after {
border-width: 0;
}
.wc-block-components-radio-control__label {
display: flex;
align-items: center;
justify-content: flex-start;
}
.wc-block-components-radio-control__label img {
height: 24px;
max-height: 24px;
object-fit: contain;
object-position: left;
}
}
.wc-block-components-radio-control.disable-radio-control {
.wc-block-components-radio-control__option {
padding-left: 16px;
}
.wc-block-components-radio-control__input {
display: none;
}
}
.wc-block-components-checkout-step__description-payments-aligned {
padding-top: 14px;
height: 28px;
}
}
.wc-block-components-radio-control-accordion-content {
padding: 0 $gap em($gap) $gap;
&:empty {
display: none;
}
}
.wc-block-checkout__order-notes {
.wc-block-components-checkout-step__content {
padding-bottom: 0;
}
}

View File

@@ -0,0 +1,160 @@
/**
* External dependencies
*/
import { render, screen, waitFor } from '@testing-library/react';
import { previewCart } from '@woocommerce/resource-previews';
import { dispatch } from '@wordpress/data';
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { default as fetchMock } from 'jest-fetch-mock';
import {
registerPaymentMethod,
__experimentalDeRegisterPaymentMethod,
} from '@woocommerce/blocks-registry';
import {
PaymentMethodDataProvider,
usePaymentMethodDataContext,
} from '@woocommerce/base-context';
import userEvent from '@testing-library/user-event';
/**
* Internal dependencies
*/
import PaymentMethods from '../payment-methods';
import { defaultCartState } from '../../../../data/default-states';
jest.mock( '../saved-payment-method-options', () => ( { onChange } ) => {
return (
<>
<span>Saved payment method options</span>
<button onClick={ () => onChange( '0' ) }>Select saved</button>
</>
);
} );
jest.mock(
'@woocommerce/base-components/radio-control-accordion',
() =>
( { onChange } ) =>
(
<>
<span>Payment method options</span>
<button onClick={ () => onChange( 'credit-card' ) }>
Select new payment
</button>
</>
)
);
const registerMockPaymentMethods = () => {
[ 'credit-card' ].forEach( ( name ) => {
registerPaymentMethod( {
name,
label: name,
content: <div>A payment method</div>,
edit: <div>A payment method</div>,
icons: null,
canMakePayment: () => true,
supports: {
showSavedCards: true,
showSaveOption: true,
features: [ 'products' ],
},
ariaLabel: name,
} );
} );
};
const resetMockPaymentMethods = () => {
[ 'credit-card' ].forEach( ( name ) => {
__experimentalDeRegisterPaymentMethod( name );
} );
};
describe( 'PaymentMethods', () => {
beforeEach( () => {
fetchMock.mockResponse( ( req ) => {
if ( req.url.match( /wc\/store\/v1\/cart/ ) ) {
return Promise.resolve( JSON.stringify( previewCart ) );
}
return Promise.resolve( '' );
} );
// need to clear the store resolution state between tests.
dispatch( storeKey ).invalidateResolutionForStore();
dispatch( storeKey ).receiveCart( defaultCartState.cartData );
} );
afterEach( () => {
fetchMock.resetMocks();
} );
test( 'should show no payment methods component when there are no payment methods', async () => {
render(
<PaymentMethodDataProvider>
<PaymentMethods />
</PaymentMethodDataProvider>
);
await waitFor( () => {
const noPaymentMethods = screen.queryAllByText(
/no payment methods available/
);
// We might get more than one match because the `speak()` function
// creates an extra `div` with the notice contents used for a11y.
expect( noPaymentMethods.length ).toBeGreaterThanOrEqual( 1 );
} );
} );
test( 'selecting new payment method', async () => {
const ShowActivePaymentMethod = () => {
const { activePaymentMethod, activeSavedToken } =
usePaymentMethodDataContext();
return (
<>
<div>
{ 'Active Payment Method: ' + activePaymentMethod }
</div>
<div>{ 'Active Saved Token: ' + activeSavedToken }</div>
</>
);
};
registerMockPaymentMethods();
render(
<PaymentMethodDataProvider>
<PaymentMethods />
<ShowActivePaymentMethod />
</PaymentMethodDataProvider>
);
await waitFor( () => {
const savedPaymentMethodOptions = screen.queryByText(
/Saved payment method options/
);
expect( savedPaymentMethodOptions ).not.toBeNull();
} );
await waitFor( () => {
const paymentMethodOptions = screen.queryByText(
/Payment method options/
);
expect( paymentMethodOptions ).not.toBeNull();
} );
await waitFor( () => {
const savedToken = screen.queryByText(
/Active Payment Method: credit-card/
);
expect( savedToken ).toBeNull();
} );
userEvent.click( screen.getByText( 'Select new payment' ) );
await waitFor( () => {
const activePaymentMethod = screen.queryByText(
/Active Payment Method: credit-card/
);
expect( activePaymentMethod ).not.toBeNull();
} );
resetMockPaymentMethods();
} );
} );

View File

@@ -0,0 +1,150 @@
/**
* External dependencies
*/
import {
useLayoutEffect,
useRef,
useCallback,
useMemo,
} from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import {
createBlock,
getBlockType,
createBlocksFromInnerBlocksTemplate,
} from '@wordpress/blocks';
import type { Block, AttributeSource, TemplateArray } from '@wordpress/blocks';
import { isEqual } from 'lodash';
const isBlockLocked = ( {
attributes,
}: {
attributes: Record< string, AttributeSource.Attribute >;
} ) => Boolean( attributes.lock?.remove || attributes.lock?.default?.remove );
/**
* useForcedLayout hook
*
* Responsible for ensuring FORCED blocks exist in the inner block layout. Forced blocks cannot be removed.
*/
export const useForcedLayout = ( {
clientId,
registeredBlocks,
defaultTemplate = [],
}: {
// Client ID of the parent block.
clientId: string;
// An array of registered blocks that may be forced in this particular layout.
registeredBlocks: Array< string >;
// The default template for the inner blocks in this layout.
defaultTemplate: TemplateArray;
} ): void => {
const currentRegisteredBlocks = useRef( registeredBlocks );
const currentDefaultTemplate = useRef( defaultTemplate );
const { insertBlock, replaceInnerBlocks } =
useDispatch( 'core/block-editor' );
const { innerBlocks, registeredBlockTypes } = useSelect(
( select ) => {
return {
innerBlocks:
select( 'core/block-editor' ).getBlocks( clientId ),
registeredBlockTypes: currentRegisteredBlocks.current.map(
( blockName ) => getBlockType( blockName )
),
};
},
[ clientId, currentRegisteredBlocks.current ]
);
const appendBlock = useCallback(
( block, position ) => {
const newBlock = createBlock( block.name );
insertBlock( newBlock, position, clientId, false );
},
[ clientId, insertBlock ]
);
const lockedBlockTypes = useMemo(
() =>
registeredBlockTypes.filter(
( block: Block | undefined ) => block && isBlockLocked( block )
),
[ registeredBlockTypes ]
) as Block[];
/**
* If the current inner blocks differ from the registered blocks, push the differences.
*/
useLayoutEffect( () => {
if ( ! clientId ) {
return;
}
// If there are NO inner blocks, sync with the given template.
if (
innerBlocks.length === 0 &&
currentDefaultTemplate.current.length > 0
) {
const nextBlocks = createBlocksFromInnerBlocksTemplate(
currentDefaultTemplate.current
);
if ( ! isEqual( nextBlocks, innerBlocks ) ) {
replaceInnerBlocks( clientId, nextBlocks );
return;
}
}
// Find registered locked blocks missing from Inner Blocks and append them.
lockedBlockTypes.forEach( ( block ) => {
// If the locked block type is already in the layout, we can skip this one.
if (
innerBlocks.find(
( { name }: { name: string } ) => name === block.name
)
) {
return;
}
// Is the forced block part of the default template, find it's original position.
const defaultTemplatePosition =
currentDefaultTemplate.current.findIndex(
( [ blockName ] ) => blockName === block.name
);
switch ( defaultTemplatePosition ) {
case -1:
// The block is not part of the default template so we append it to the current layout.
appendBlock( block, innerBlocks.length );
break;
case 0:
// The block was the first block in the default layout, so prepend it to the current layout.
appendBlock( block, 0 );
break;
default:
// The new layout may have extra blocks compared to the default template, so rather than insert
// at the default position, we should append it after another default block.
const adjacentBlock =
currentDefaultTemplate.current[
defaultTemplatePosition - 1
];
const position = innerBlocks.findIndex(
( { name: blockName } ) =>
blockName === adjacentBlock[ 0 ]
);
appendBlock(
block,
position === -1 ? defaultTemplatePosition : position + 1
);
break;
}
} );
}, [
clientId,
innerBlocks,
lockedBlockTypes,
replaceInnerBlocks,
appendBlock,
] );
};

View File

@@ -0,0 +1,111 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import { useDispatch, select } from '@wordpress/data';
import { ToolbarGroup, ToolbarDropdownMenu } from '@wordpress/components';
import { eye } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { store as blockEditorStore } from '@wordpress/block-editor';
interface View {
view: string;
label: string;
icon: string | JSX.Element;
}
function getView( viewName: string, views: View[] ) {
return views.find( ( view ) => view.view === viewName );
}
export const useViewSwitcher = (
clientId: string,
views: View[]
): {
currentView: string;
component: JSX.Element;
} => {
const initialView = views[ 0 ];
const [ currentView, setCurrentView ] = useState( initialView );
const { selectBlock } = useDispatch( 'core/block-editor' );
const { getBlock, getSelectedBlockClientId, getBlockParentsByBlockName } =
select( blockEditorStore );
const selectedBlockClientId = getSelectedBlockClientId();
useEffect( () => {
const selectedBlock = getBlock( selectedBlockClientId );
if ( ! selectedBlock ) {
return;
}
if ( currentView.view === selectedBlock.name ) {
return;
}
const viewNames = views.map( ( { view } ) => view );
if ( viewNames.includes( selectedBlock.name ) ) {
const newView = getView( selectedBlock.name, views );
if ( newView ) {
return setCurrentView( newView );
}
}
const parentBlockIds = getBlockParentsByBlockName(
selectedBlockClientId,
viewNames
);
if ( parentBlockIds.length !== 1 ) {
return;
}
const parentBlock = getBlock( parentBlockIds[ 0 ] );
if ( currentView.view === parentBlock.name ) {
return;
}
const newView = getView( parentBlock.name, views );
if ( newView ) {
setCurrentView( newView );
}
}, [
getBlockParentsByBlockName,
selectedBlockClientId,
getBlock,
currentView.view,
views,
] );
const ViewSwitcherComponent = (
<ToolbarGroup>
<ToolbarDropdownMenu
label={ __( 'Switch view', 'woo-gutenberg-products-block' ) }
text={ currentView.label }
icon={ <Icon icon={ eye } style={ { marginRight: '8px' } } /> }
controls={ views.map( ( view ) => ( {
...view,
title: <span>{ view.label }</span>,
isActive: view.view === currentView.view,
onClick: () => {
setCurrentView( view );
selectBlock(
getBlock( clientId ).innerBlocks.find(
( block: { name: string } ) =>
block.name === view.view
)?.clientId || clientId
);
},
} ) ) }
/>
</ToolbarGroup>
);
return {
currentView: currentView.view,
component: ViewSwitcherComponent,
};
};

View File

@@ -0,0 +1,33 @@
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
export const blockName = 'woocommerce/cart';
export const blockAttributes = {
isPreview: {
type: 'boolean',
default: false,
save: false,
},
hasDarkControls: {
type: 'boolean',
default: getSetting( 'hasDarkEditorStyleSupport', false ),
},
// Deprecated - here for v1 migration support
isShippingCalculatorEnabled: {
type: 'boolean',
default: getSetting( 'isShippingCalculatorEnabled', true ),
},
checkoutPageId: {
type: 'number',
default: 0,
},
showRateAfterTaxName: {
type: 'boolean',
default: true,
},
align: {
type: 'string',
},
};

View File

@@ -0,0 +1,101 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { useStoreCart } from '@woocommerce/base-context/hooks';
import { useEffect } from '@wordpress/element';
import LoadingMask from '@woocommerce/base-components/loading-mask';
import {
ValidationContextProvider,
StoreNoticesContainer,
SnackbarNoticesContainer,
} from '@woocommerce/base-context';
import { CURRENT_USER_IS_ADMIN } from '@woocommerce/settings';
import BlockErrorBoundary from '@woocommerce/base-components/block-error-boundary';
import { translateJQueryEventToNative } from '@woocommerce/base-utils';
import withScrollToTop from '@woocommerce/base-hocs/with-scroll-to-top';
import {
StoreNoticesProvider,
CartProvider,
} from '@woocommerce/base-context/providers';
import { SlotFillProvider } from '@woocommerce/blocks-checkout';
/**
* Internal dependencies
*/
import { CartBlockContext } from './context';
import './style.scss';
const reloadPage = () => void window.location.reload( true );
const Cart = ( { children, attributes = {} } ) => {
const { cartIsLoading } = useStoreCart();
const { hasDarkControls } = attributes;
return (
<LoadingMask showSpinner={ true } isLoading={ cartIsLoading }>
<CartBlockContext.Provider
value={ {
hasDarkControls,
} }
>
<ValidationContextProvider>
{ children }
</ValidationContextProvider>
</CartBlockContext.Provider>
</LoadingMask>
);
};
const ScrollOnError = ( { scrollToTop } ) => {
useEffect( () => {
// Make it so we can read jQuery events triggered by WC Core elements.
const removeJQueryAddedToCartEvent = translateJQueryEventToNative(
'added_to_cart',
'wc-blocks_added_to_cart'
);
document.body.addEventListener(
'wc-blocks_added_to_cart',
scrollToTop
);
return () => {
removeJQueryAddedToCartEvent();
document.body.removeEventListener(
'wc-blocks_added_to_cart',
scrollToTop
);
};
}, [ scrollToTop ] );
return null;
};
const Block = ( { attributes, children, scrollToTop } ) => (
<BlockErrorBoundary
header={ __( 'Something went wrong…', 'woocommerce' ) }
text={ __(
'The cart has encountered an unexpected error. If the error persists, please get in touch with us for help.',
'woocommerce'
) }
button={
<button className="wc-block-button" onClick={ reloadPage }>
{ __( 'Reload the page', 'woocommerce' ) }
</button>
}
showErrorMessage={ CURRENT_USER_IS_ADMIN }
>
<SnackbarNoticesContainer context="wc/cart" />
<StoreNoticesProvider>
<StoreNoticesContainer context="wc/cart" />
<SlotFillProvider>
<CartProvider>
<Cart attributes={ attributes }>{ children }</Cart>
<ScrollOnError scrollToTop={ scrollToTop } />
</CartProvider>
</SlotFillProvider>
</StoreNoticesProvider>
</BlockErrorBoundary>
);
export default withScrollToTop( Block );

View File

@@ -0,0 +1,359 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import QuantitySelector from '@woocommerce/base-components/quantity-selector';
import ProductPrice from '@woocommerce/base-components/product-price';
import ProductName from '@woocommerce/base-components/product-name';
import {
useStoreCartItemQuantity,
useStoreEvents,
useStoreCart,
} from '@woocommerce/base-context/hooks';
import {
ProductBackorderBadge,
ProductImage,
ProductLowStockBadge,
ProductMetadata,
ProductSaleBadge,
} from '@woocommerce/base-components/cart-checkout';
import {
getCurrencyFromPriceResponse,
Currency,
} from '@woocommerce/price-format';
import {
__experimentalApplyCheckoutFilter,
mustContain,
} from '@woocommerce/blocks-checkout';
import Dinero from 'dinero.js';
import { forwardRef, useMemo } from '@wordpress/element';
import type { CartItem } from '@woocommerce/type-defs/cart';
import { objectHasProp } from '@woocommerce/types';
import { getSetting } from '@woocommerce/settings';
/**
* Convert a Dinero object with precision to store currency minor unit.
*
* @param {Dinero} priceObject Price object to convert.
* @param {Object} currency Currency data.
* @return {number} Amount with new minor unit precision.
*/
const getAmountFromRawPrice = (
priceObject: Dinero.Dinero,
currency: Currency
) => {
return priceObject.convertPrecision( currency.minorUnit ).getAmount();
};
const productPriceValidation = ( value ) => mustContain( value, '<price/>' );
interface CartLineItemRowProps {
lineItem: CartItem | Record< string, never >;
onRemove?: () => void;
tabIndex?: number;
}
/**
* Cart line item table row component.
*/
const CartLineItemRow = forwardRef< HTMLTableRowElement, CartLineItemRowProps >(
(
{ lineItem, onRemove = () => void null, tabIndex = null },
ref
): JSX.Element => {
const {
name: initialName = '',
catalog_visibility: catalogVisibility = 'visible',
short_description: shortDescription = '',
description: fullDescription = '',
low_stock_remaining: lowStockRemaining = null,
show_backorder_badge: showBackorderBadge = false,
quantity_limits: quantityLimits = {
minimum: 1,
maximum: 99,
multiple_of: 1,
editable: true,
},
sold_individually: soldIndividually = false,
permalink = '',
images = [],
variation = [],
item_data: itemData = [],
prices = {
currency_code: 'USD',
currency_minor_unit: 2,
currency_symbol: '$',
currency_prefix: '$',
currency_suffix: '',
currency_decimal_separator: '.',
currency_thousand_separator: ',',
price: '0',
regular_price: '0',
sale_price: '0',
price_range: null,
raw_prices: {
precision: 6,
price: '0',
regular_price: '0',
sale_price: '0',
},
},
totals = {
currency_code: 'USD',
currency_minor_unit: 2,
currency_symbol: '$',
currency_prefix: '$',
currency_suffix: '',
currency_decimal_separator: '.',
currency_thousand_separator: ',',
line_subtotal: '0',
line_subtotal_tax: '0',
},
extensions,
} = lineItem;
const { quantity, setItemQuantity, removeItem, isPendingDelete } =
useStoreCartItemQuantity( lineItem );
const { dispatchStoreEvent } = useStoreEvents();
// Prepare props to pass to the __experimentalApplyCheckoutFilter filter.
// We need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { receiveCart, ...cart } = useStoreCart();
const arg = useMemo(
() => ( {
context: 'cart',
cartItem: lineItem,
cart,
} ),
[ lineItem, cart ]
);
const priceCurrency = getCurrencyFromPriceResponse( prices );
const name = __experimentalApplyCheckoutFilter( {
filterName: 'itemName',
defaultValue: initialName,
extensions,
arg,
} );
const regularAmountSingle = Dinero( {
amount: parseInt( prices.raw_prices.regular_price, 10 ),
precision: prices.raw_prices.precision,
} );
const purchaseAmountSingle = Dinero( {
amount: parseInt( prices.raw_prices.price, 10 ),
precision: prices.raw_prices.precision,
} );
const saleAmountSingle =
regularAmountSingle.subtract( purchaseAmountSingle );
const saleAmount = saleAmountSingle.multiply( quantity );
const totalsCurrency = getCurrencyFromPriceResponse( totals );
let lineSubtotal = parseInt( totals.line_subtotal, 10 );
if ( getSetting( 'displayCartPricesIncludingTax', false ) ) {
lineSubtotal += parseInt( totals.line_subtotal_tax, 10 );
}
const subtotalPrice = Dinero( {
amount: lineSubtotal,
precision: totalsCurrency.minorUnit,
} );
const firstImage = images.length ? images[ 0 ] : {};
const isProductHiddenFromCatalog =
catalogVisibility === 'hidden' || catalogVisibility === 'search';
const cartItemClassNameFilter = __experimentalApplyCheckoutFilter( {
filterName: 'cartItemClass',
defaultValue: '',
extensions,
arg,
} );
// Allow extensions to filter how the price is displayed. Ie: prepending or appending some values.
const productPriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'cartItemPrice',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
const subtotalPriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'subtotalPriceFormat',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
const saleBadgePriceFormat = __experimentalApplyCheckoutFilter( {
filterName: 'saleBadgePriceFormat',
defaultValue: '<price/>',
extensions,
arg,
validation: productPriceValidation,
} );
return (
<tr
className={ classnames(
'wc-block-cart-items__row',
cartItemClassNameFilter,
{
'is-disabled': isPendingDelete,
}
) }
ref={ ref }
tabIndex={ tabIndex }
>
{ /* If the image has no alt text, this link is unnecessary and can be hidden. */ }
<td
className="wc-block-cart-item__image"
aria-hidden={
! objectHasProp( firstImage, 'alt' ) || ! firstImage.alt
}
>
{ /* We don't need to make it focusable, because product name has the same link. */ }
{ isProductHiddenFromCatalog ? (
<ProductImage
image={ firstImage }
fallbackAlt={ name }
/>
) : (
<a href={ permalink } tabIndex={ -1 }>
<ProductImage
image={ firstImage }
fallbackAlt={ name }
/>
</a>
) }
</td>
<td className="wc-block-cart-item__product">
<div className="wc-block-cart-item__wrap">
<ProductName
disabled={
isPendingDelete || isProductHiddenFromCatalog
}
name={ name }
permalink={ permalink }
/>
{ showBackorderBadge ? (
<ProductBackorderBadge />
) : (
!! lowStockRemaining && (
<ProductLowStockBadge
lowStockRemaining={ lowStockRemaining }
/>
)
) }
<div className="wc-block-cart-item__prices">
<ProductPrice
currency={ priceCurrency }
regularPrice={ getAmountFromRawPrice(
regularAmountSingle,
priceCurrency
) }
price={ getAmountFromRawPrice(
purchaseAmountSingle,
priceCurrency
) }
format={ subtotalPriceFormat }
/>
</div>
<ProductSaleBadge
currency={ priceCurrency }
saleAmount={ getAmountFromRawPrice(
saleAmountSingle,
priceCurrency
) }
format={ saleBadgePriceFormat }
/>
<ProductMetadata
shortDescription={ shortDescription }
fullDescription={ fullDescription }
itemData={ itemData }
variation={ variation }
/>
<div className="wc-block-cart-item__quantity">
{ ! soldIndividually &&
!! quantityLimits.editable && (
<QuantitySelector
disabled={ isPendingDelete }
quantity={ quantity }
minimum={ quantityLimits.minimum }
maximum={ quantityLimits.maximum }
step={ quantityLimits.multiple_of }
onChange={ ( newQuantity ) => {
setItemQuantity( newQuantity );
dispatchStoreEvent(
'cart-set-item-quantity',
{
product: lineItem,
quantity: newQuantity,
}
);
} }
itemName={ name }
/>
) }
<button
className="wc-block-cart-item__remove-link"
onClick={ () => {
onRemove();
removeItem();
dispatchStoreEvent( 'cart-remove-item', {
product: lineItem,
quantity,
} );
speak(
sprintf(
/* translators: %s refers to the item name in the cart. */
__(
'%s has been removed from your cart.',
'woo-gutenberg-products-block'
),
name
)
);
} }
disabled={ isPendingDelete }
>
{ __(
'Remove item',
'woo-gutenberg-products-block'
) }
</button>
</div>
</div>
</td>
<td className="wc-block-cart-item__total">
<div className="wc-block-cart-item__total-price-and-sale-badge-wrapper">
<ProductPrice
currency={ totalsCurrency }
format={ productPriceFormat }
price={ subtotalPrice.getAmount() }
/>
{ quantity > 1 && (
<ProductSaleBadge
currency={ priceCurrency }
saleAmount={ getAmountFromRawPrice(
saleAmount,
priceCurrency
) }
format={ saleBadgePriceFormat }
/>
) }
</div>
</td>
</tr>
);
}
);
export default CartLineItemRow;

View File

@@ -0,0 +1,102 @@
/**
* External dependencies
*/
import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { CartResponseItem } from '@woocommerce/type-defs/cart-response';
import { createRef, useEffect, useRef } from '@wordpress/element';
import type { RefObject } from 'react';
/**
* Internal dependencies
*/
import CartLineItemRow from './cart-line-item-row';
const placeholderRows = [ ...Array( 3 ) ].map( ( _x, i ) => (
<CartLineItemRow lineItem={ {} } key={ i } />
) );
interface CartLineItemsTableProps {
lineItems: CartResponseItem[];
isLoading: boolean;
className?: string;
}
const setRefs = ( lineItems: CartResponseItem[] ) => {
const refs = {} as Record< string, RefObject< HTMLTableRowElement > >;
lineItems.forEach( ( { key } ) => {
refs[ key ] = createRef();
} );
return refs;
};
const CartLineItemsTable = ( {
lineItems = [],
isLoading = false,
className,
}: CartLineItemsTableProps ): JSX.Element => {
const tableRef = useRef< HTMLTableElement | null >( null );
const rowRefs = useRef( setRefs( lineItems ) );
useEffect( () => {
rowRefs.current = setRefs( lineItems );
}, [ lineItems ] );
const onRemoveRow = ( nextItemKey: string | null ) => () => {
if (
rowRefs?.current &&
nextItemKey &&
rowRefs.current[ nextItemKey ].current instanceof HTMLElement
) {
( rowRefs.current[ nextItemKey ].current as HTMLElement ).focus();
} else if ( tableRef.current instanceof HTMLElement ) {
tableRef.current.focus();
}
};
const products = isLoading
? placeholderRows
: lineItems.map( ( lineItem, i ) => {
const nextItemKey =
lineItems.length > i + 1 ? lineItems[ i + 1 ].key : null;
return (
<CartLineItemRow
key={ lineItem.key }
lineItem={ lineItem }
onRemove={ onRemoveRow( nextItemKey ) }
ref={ rowRefs.current[ lineItem.key ] }
tabIndex={ -1 }
/>
);
} );
return (
<table
className={ classnames( 'wc-block-cart-items', className ) }
ref={ tableRef }
tabIndex={ -1 }
>
<thead>
<tr className="wc-block-cart-items__header">
<th className="wc-block-cart-items__header-image">
<span>
{ __( 'Product', 'woo-gutenberg-products-block' ) }
</span>
</th>
<th className="wc-block-cart-items__header-product">
<span>
{ __( 'Details', 'woo-gutenberg-products-block' ) }
</span>
</th>
<th className="wc-block-cart-items__header-total">
<span>
{ __( 'Total', 'woo-gutenberg-products-block' ) }
</span>
</th>
</tr>
</thead>
<tbody>{ products }</tbody>
</table>
);
};
export default CartLineItemsTable;

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { createContext, useContext } from '@wordpress/element';
/**
* Context consumed by inner blocks.
*/
export type CartBlockContextProps = {
hasDarkControls: boolean;
};
export const CartBlockContext = createContext< CartBlockContextProps >( {
hasDarkControls: false,
} );
export const useCartBlockContext = (): CartBlockContextProps => {
return useContext( CartBlockContext );
};

View File

@@ -0,0 +1,196 @@
/* tslint:disable */
/**
* External dependencies
*/
import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { CartCheckoutFeedbackPrompt } from '@woocommerce/editor-components/feedback-prompt';
import {
useBlockProps,
InnerBlocks,
InspectorControls,
BlockControls,
} from '@wordpress/block-editor';
import { PanelBody, ToggleControl, Notice } from '@wordpress/components';
import { CartCheckoutCompatibilityNotice } from '@woocommerce/editor-components/compatibility-notices';
import { CART_PAGE_ID } from '@woocommerce/block-settings';
import BlockErrorBoundary from '@woocommerce/base-components/block-error-boundary';
import {
EditorProvider,
useEditorContext,
CartProvider,
} from '@woocommerce/base-context';
import { createInterpolateElement } from '@wordpress/element';
import { getAdminLink } from '@woocommerce/settings';
import { previewCart } from '@woocommerce/resource-previews';
import { filledCart, removeCart } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
/**
* Internal dependencies
*/
import './inner-blocks';
import './editor.scss';
import {
addClassToBody,
useViewSwitcher,
useBlockPropsWithLocking,
useForcedLayout,
} from '../cart-checkout-shared';
import { CartBlockContext } from './context';
// This is adds a class to body to signal if the selected block is locked
addClassToBody();
// Array of allowed block names.
const ALLOWED_BLOCKS = [
'woocommerce/filled-cart-block',
'woocommerce/empty-cart-block',
];
const views = [
{
view: 'woocommerce/filled-cart-block',
label: __( 'Filled Cart', 'woocommerce' ),
icon: <Icon icon={ filledCart } />,
},
{
view: 'woocommerce/empty-cart-block',
label: __( 'Empty Cart', 'woocommerce' ),
icon: <Icon icon={ removeCart } />,
},
];
const BlockSettings = ( { attributes, setAttributes } ) => {
const { hasDarkControls } = attributes;
const { currentPostId } = useEditorContext();
return (
<InspectorControls>
{ currentPostId !== CART_PAGE_ID && (
<Notice
className="wc-block-cart__page-notice"
isDismissible={ false }
status="warning"
>
{ createInterpolateElement(
__(
'If you would like to use this block as your default cart you must update your <a>page settings in WooCommerce</a>.',
'woocommerce'
),
{
a: (
// eslint-disable-next-line jsx-a11y/anchor-has-content
<a
href={ getAdminLink(
'admin.php?page=wc-settings&tab=advanced'
) }
target="_blank"
rel="noopener noreferrer"
/>
),
}
) }
</Notice>
) }
<PanelBody title={ __( 'Style', 'woocommerce' ) }>
<ToggleControl
label={ __(
'Dark mode inputs',
'woocommerce'
) }
help={ __(
'Inputs styled specifically for use on dark background colors.',
'woocommerce'
) }
checked={ hasDarkControls }
onChange={ () =>
setAttributes( {
hasDarkControls: ! hasDarkControls,
} )
}
/>
</PanelBody>
<CartCheckoutFeedbackPrompt />
</InspectorControls>
);
};
export const Edit = ( { className, attributes, setAttributes, clientId } ) => {
const { hasDarkControls } = attributes;
const { currentView, component: ViewSwitcherComponent } = useViewSwitcher(
clientId,
views
);
const defaultTemplate = [
[ 'woocommerce/filled-cart-block', {}, [] ],
[ 'woocommerce/empty-cart-block', {}, [] ],
];
const blockProps = useBlockPropsWithLocking( {
className: classnames( className, 'wp-block-woocommerce-cart', {
'is-editor-preview': attributes.isPreview,
} ),
} );
useForcedLayout( {
clientId,
registeredBlocks: ALLOWED_BLOCKS,
defaultTemplate,
} );
return (
<div { ...blockProps }>
<BlockErrorBoundary
header={ __(
'Cart Block Error',
'woocommerce'
) }
text={ __(
'There was an error whilst rendering the cart block. If this problem continues, try re-creating the block.',
'woocommerce'
) }
showErrorMessage={ true }
errorMessagePrefix={ __(
'Error message:',
'woocommerce'
) }
>
<EditorProvider
currentView={ currentView }
previewData={ { previewCart } }
>
<BlockSettings
attributes={ attributes }
setAttributes={ setAttributes }
/>
<BlockControls __experimentalShareWithChildBlocks>
{ ViewSwitcherComponent }
</BlockControls>
<CartBlockContext.Provider
value={ {
hasDarkControls,
} }
>
<CartProvider>
<InnerBlocks
allowedBlocks={ ALLOWED_BLOCKS }
template={ defaultTemplate }
templateLock={ false }
/>
</CartProvider>
</CartBlockContext.Provider>
</EditorProvider>
</BlockErrorBoundary>
<CartCheckoutCompatibilityNotice blockName="cart" />
</div>
);
};
export const Save = () => {
return (
<div
{ ...useBlockProps.save( {
className: 'is-loading',
} ) }
>
<InnerBlocks.Content />
</div>
);
};

View File

@@ -0,0 +1,41 @@
.wc-block-cart__page-notice {
margin: 0;
}
body.wc-lock-selected-block--move {
.block-editor-block-mover__move-button-container,
.block-editor-block-mover {
display: none;
}
}
body.wc-lock-selected-block--remove {
.block-editor-block-settings-menu__popover {
.components-menu-group:last-child {
display: none;
}
.components-menu-group:nth-last-child(2) {
margin-bottom: -12px;
}
}
}
.wp-block-woocommerce-cart-items-block,
.wp-block-woocommerce-cart-totals-block,
.wp-block-woocommerce-empty-cart-block {
// Temporary fix after the appender button was positioned absolute
// See https://github.com/woocommerce/woocommerce-gutenberg-products-block/issues/5742#issuecomment-1032804168
.block-list-appender {
position: relative;
}
}
.wp-block-woocommerce-cart-order-summary-block {
.block-editor-block-list__layout > div {
margin: 0 !important;
}
.wc-block-components-totals-wrapper {
box-sizing: border-box;
}
}

View File

@@ -0,0 +1,50 @@
/**
* External dependencies
*/
import { getValidBlockAttributes } from '@woocommerce/base-utils';
import { Children, cloneElement, isValidElement } from '@wordpress/element';
import { useStoreCart } from '@woocommerce/base-context';
import { getRegisteredBlockComponents } from '@woocommerce/blocks-registry';
import { renderParentBlock } from '@woocommerce/atomic-utils';
/**
* Internal dependencies
*/
import './inner-blocks/register-components';
import Block from './block';
import { blockName, blockAttributes } from './attributes';
const getProps = ( el ) => {
return {
attributes: getValidBlockAttributes(
blockAttributes,
!! el ? el.dataset : {}
),
};
};
const Wrapper = ( { children } ) => {
// we need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { extensions, receiveCart, ...cart } = useStoreCart();
return Children.map( children, ( child ) => {
if ( isValidElement( child ) ) {
const componentProps = {
extensions,
cart,
};
return cloneElement( child, componentProps );
}
return child;
} );
};
renderParentBlock( {
Block,
blockName,
selector: '.wp-block-woocommerce-cart',
getProps,
blockMap: getRegisteredBlockComponents( blockName ),
blockWrapper: Wrapper,
} );

View File

@@ -0,0 +1,114 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import classnames from 'classnames';
import { InnerBlocks } from '@wordpress/block-editor';
import { cart } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
import { createBlock } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import './style.scss';
import { blockName, blockAttributes } from './attributes';
import './inner-blocks';
/**
* Register and run the Cart block.
*/
const settings = {
title: __( 'Cart', 'woocommerce' ),
icon: {
src: (
<Icon
icon={ cart }
className="wc-block-editor-components-block-icon"
/>
),
},
category: 'woocommerce',
keywords: [ __( 'WooCommerce', 'woocommerce' ) ],
description: __( 'Shopping cart.', 'woocommerce' ),
supports: {
align: [ 'wide' ],
html: false,
multiple: false,
__experimentalExposeControlsToChildren: true,
},
example: {
attributes: {
isPreview: true,
},
},
attributes: blockAttributes,
edit: Edit,
save: Save,
// Migrates v1 to v2 checkout.
deprecated: [
{
attributes: blockAttributes,
save: ( { attributes } ) => {
return (
<div
className={ classnames(
'is-loading',
attributes.className
) }
>
<InnerBlocks.Content />
</div>
);
},
migrate: ( attributes, innerBlocks ) => {
const { checkoutPageId, align } = attributes;
return [
attributes,
[
createBlock(
'woocommerce/filled-cart-block',
{ align },
[
createBlock( 'woocommerce/cart-items-block' ),
createBlock(
'woocommerce/cart-totals-block',
{},
[
createBlock(
'woocommerce/cart-order-summary-block',
{}
),
createBlock(
'woocommerce/cart-express-payment-block'
),
createBlock(
'woocommerce/proceed-to-checkout-block',
{ checkoutPageId }
),
createBlock(
'woocommerce/cart-accepted-payment-methods-block'
),
]
),
]
),
createBlock(
'woocommerce/empty-cart-block',
{ align },
innerBlocks
),
],
];
},
isEligible: ( _, innerBlocks ) => {
return ! innerBlocks.find(
( block ) => block.name === 'woocommerce/filled-cart-block'
);
},
},
],
};
registerFeaturePluginBlockType( blockName, settings );

View File

@@ -0,0 +1,17 @@
{
"name": "woocommerce/cart-accepted-payment-methods-block",
"version": "1.0.0",
"title": "Accepted Payment Methods",
"description": "Display accepted payment methods.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": true
},
"parent": [ "woocommerce/cart-totals-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { PaymentMethodIcons } from '@woocommerce/base-components/cart-checkout';
import { usePaymentMethods } from '@woocommerce/base-context/hooks';
import { getIconsFromPaymentMethods } from '@woocommerce/base-utils';
const Block = ( { className }: { className: string } ): JSX.Element => {
const { paymentMethods } = usePaymentMethods();
return (
<PaymentMethodIcons
className={ className }
icons={ getIconsFromPaymentMethods( paymentMethods ) }
/>
);
};
export default Block;

View File

@@ -0,0 +1,27 @@
/**
* External dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
}: {
attributes: { className: string };
} ): JSX.Element => {
const { className } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Block className={ className } />
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
import { Icon, payment } from '@wordpress/icons';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ payment }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/cart-express-payment-block",
"version": "1.0.0",
"title": "Express Checkout",
"description": "Provide an express payment option for your customers.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": false,
"lock": false
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/cart-totals-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,31 @@
/**
* External dependencies
*/
import { useStoreCart } from '@woocommerce/base-context/hooks';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import { CartExpressPayment } from '../../../cart-checkout-shared/payment-methods';
const Block = ( { className }: { className: string } ): JSX.Element | null => {
const { cartNeedsPayment } = useStoreCart();
if ( ! cartNeedsPayment ) {
return null;
}
return (
<div
className={ classnames(
'wc-block-cart__payment-options',
className
) }
>
<CartExpressPayment />
</div>
);
};
export default Block;

View File

@@ -0,0 +1,82 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
import { Placeholder, Button } from 'wordpress-components';
import { useExpressPaymentMethods } from '@woocommerce/base-context/hooks';
import { Icon, payment } from '@wordpress/icons';
import { ADMIN_URL } from '@woocommerce/settings';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import Block from './block';
import './editor.scss';
/**
* Renders a placeholder in the editor.
*/
const NoExpressPaymentMethodsPlaceholder = () => {
return (
<Placeholder
icon={ <Icon icon={ payment } /> }
label={ __( 'Express Checkout', 'woo-gutenberg-products-block' ) }
className="wp-block-woocommerce-checkout-express-payment-block-placeholder"
>
<span className="wp-block-woocommerce-checkout-express-payment-block-placeholder__description">
{ __(
"Your store doesn't have any Payment Methods that support the Express Checkout Block. If they are added, they will be shown here.",
'woo-gutenberg-products-block'
) }
</span>
<Button
isPrimary
href={ `${ ADMIN_URL }admin.php?page=wc-settings&tab=checkout` }
target="_blank"
rel="noopener noreferrer"
className="wp-block-woocommerce-checkout-express-payment-block-placeholder__button"
>
{ __(
'Configure Payment Methods',
'woo-gutenberg-products-block'
) }
</Button>
</Placeholder>
);
};
export const Edit = ( {
attributes,
}: {
attributes: { className: string };
} ): JSX.Element | null => {
const { paymentMethods, isInitialized } = useExpressPaymentMethods();
const hasExpressPaymentMethods = Object.keys( paymentMethods ).length > 0;
const blockProps = useBlockProps( {
className: classnames( {
'wp-block-woocommerce-cart-express-payment-block--has-express-payment-methods':
hasExpressPaymentMethods,
} ),
} );
const { className } = attributes;
if ( ! isInitialized ) {
return null;
}
return (
<div { ...blockProps }>
{ hasExpressPaymentMethods ? (
<Block className={ className } />
) : (
<NoExpressPaymentMethodsPlaceholder />
) }
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,29 @@
// Adjust padding and margins in the editor to improve selected block outlines.
.wp-block-woocommerce-cart-express-payment-block {
.components-placeholder__label svg {
font-size: 1em;
}
.wc-block-cart__payment-options {
padding: 0;
.wc-block-components-express-payment-continue-rule {
margin-bottom: -12px;
}
}
}
.wp-block-woocommerce-checkout-express-payment-block-placeholder {
* {
pointer-events: all; // Overrides parent disabled component in editor context
}
.wp-block-woocommerce-cart-express-payment-block &,
.wp-block-woocommerce-checkout-express-payment-block-placeholder__description {
margin: 0 0 1em;
}
.wp-block-woocommerce-checkout-express-payment-block-placeholder__description {
display: block;
}
}

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Icon, payment } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ payment }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/cart-items-block",
"version": "1.0.0",
"title": "Cart Items block",
"description": "Column containing cart items.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": false,
"lock": false
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/filled-cart-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,46 @@
/**
* External dependencies
*/
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { Main } from '@woocommerce/base-components/sidebar-layout';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
import type { TemplateArray } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import {
useForcedLayout,
getAllowedBlocks,
} from '../../../cart-checkout-shared';
export const Edit = ( { clientId }: { clientId: string } ): JSX.Element => {
const blockProps = useBlockProps( { className: 'wc-block-cart__main' } );
const allowedBlocks = getAllowedBlocks( innerBlockAreas.CART_ITEMS );
const defaultTemplate = [
[ 'woocommerce/cart-line-items-block', {}, [] ],
] as TemplateArray;
useForcedLayout( {
clientId,
registeredBlocks: allowedBlocks,
defaultTemplate,
} );
return (
<Main { ...blockProps }>
<InnerBlocks
allowedBlocks={ allowedBlocks }
template={ defaultTemplate }
templateLock={ false }
renderAppender={ InnerBlocks.ButtonBlockAppender }
/>
</Main>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<InnerBlocks.Content />
</div>
);
};

View File

@@ -0,0 +1,21 @@
/**
* External dependencies
*/
import { Main } from '@woocommerce/base-components/sidebar-layout';
import classnames from 'classnames';
const FrontendBlock = ( {
children,
className,
}: {
children: JSX.Element;
className: string;
} ): JSX.Element => {
return (
<Main className={ classnames( 'wc-block-cart__main', className ) }>
{ children }
</Main>
);
};
export default FrontendBlock;

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Icon, column } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ column }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/cart-line-items-block",
"version": "1.0.0",
"title": "Cart Line Items",
"description": "Block containing current line items in Cart.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": false,
"lock": false
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/cart-items-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,21 @@
/**
* External dependencies
*/
import { useStoreCart } from '@woocommerce/base-context/hooks';
/**
* Internal dependencies
*/
import CartLineItemsTable from '../../cart-line-items-table';
const Block = ( { className }: { className: string } ): JSX.Element => {
const { cartItems, cartIsLoading } = useStoreCart();
return (
<CartLineItemsTable
className={ className }
lineItems={ cartItems }
isLoading={ cartIsLoading }
/>
);
};
export default Block;

View File

@@ -0,0 +1,31 @@
/**
* External dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';
import Noninteractive from '@woocommerce/base-components/noninteractive';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
}: {
attributes: { className: string };
} ): JSX.Element => {
const { className } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Noninteractive>
<Block className={ className } />
</Noninteractive>
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Icon, column } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ column }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,27 @@
{
"name": "woocommerce/cart-order-summary-block",
"version": "1.0.0",
"title": "Order Summary",
"description": "Show customers a summary of their order.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"inserter": false,
"lock": false
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true,
"move": true
}
}
},
"parent": [ "woocommerce/cart-totals-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,74 @@
/**
* External dependencies
*/
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import type { TemplateArray } from '@wordpress/blocks';
import { innerBlockAreas } from '@woocommerce/blocks-checkout';
import { __ } from '@wordpress/i18n';
import { TotalsFooterItem } from '@woocommerce/base-components/cart-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import { useStoreCart } from '@woocommerce/base-context/hooks';
/**
* Internal dependencies
*/
import {
useForcedLayout,
getAllowedBlocks,
} from '../../../cart-checkout-shared';
import { OrderMetaSlotFill } from './slotfills';
export const Edit = ( { clientId }: { clientId: string } ): JSX.Element => {
const blockProps = useBlockProps();
const { cartTotals } = useStoreCart();
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
const allowedBlocks = getAllowedBlocks(
innerBlockAreas.CART_ORDER_SUMMARY
);
const defaultTemplate = [
[
'woocommerce/cart-order-summary-heading-block',
{
content: __( 'Cart totals', 'woo-gutenberg-products-block' ),
},
[],
],
[ 'woocommerce/cart-order-summary-subtotal-block', {}, [] ],
[ 'woocommerce/cart-order-summary-fee-block', {}, [] ],
[ 'woocommerce/cart-order-summary-discount-block', {}, [] ],
[ 'woocommerce/cart-order-summary-coupon-form-block', {}, [] ],
[ 'woocommerce/cart-order-summary-shipping-block', {}, [] ],
[ 'woocommerce/cart-order-summary-taxes-block', {}, [] ],
] as TemplateArray;
useForcedLayout( {
clientId,
registeredBlocks: allowedBlocks,
defaultTemplate,
} );
return (
<div { ...blockProps }>
<InnerBlocks
allowedBlocks={ allowedBlocks }
template={ defaultTemplate }
/>
<div className="wc-block-components-totals-wrapper">
<TotalsFooterItem
currency={ totalsCurrency }
values={ cartTotals }
/>
</div>
{ /* do I put an totals wrapper here? */ }
<OrderMetaSlotFill />
</div>
);
};
export const Save = (): JSX.Element => {
return (
<div { ...useBlockProps.save() }>
<InnerBlocks.Content />
</div>
);
};

View File

@@ -0,0 +1,37 @@
/**
* External dependencies
*/
import { TotalsFooterItem } from '@woocommerce/base-components/cart-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import { useStoreCart } from '@woocommerce/base-context/hooks';
/**
* Internal dependencies
*/
import { OrderMetaSlotFill } from './slotfills';
const FrontendBlock = ( {
children,
className = '',
}: {
children?: JSX.Element | JSX.Element[];
className?: string;
} ): JSX.Element | null => {
const { cartTotals } = useStoreCart();
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<div className={ className }>
{ children }
<div className="wc-block-components-totals-wrapper">
<TotalsFooterItem
currency={ totalsCurrency }
values={ cartTotals }
/>
</div>
<OrderMetaSlotFill />
</div>
);
};
export default FrontendBlock;

View File

@@ -0,0 +1,25 @@
/**
* External dependencies
*/
import { totals } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,18 @@
/**
* External dependencies
*/
import { ExperimentalOrderMeta } from '@woocommerce/blocks-checkout';
import { useStoreCart } from '@woocommerce/base-context/hooks';
export const OrderMetaSlotFill = (): JSX.Element => {
// Prepare props to pass to the ExperimentalOrderMeta slot fill. We need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { extensions, receiveCart, ...cart } = useStoreCart();
const slotFillProps = {
extensions,
cart,
context: 'woocommerce/cart',
};
return <ExperimentalOrderMeta.Slot { ...slotFillProps } />;
};

View File

@@ -0,0 +1,29 @@
{
"name": "woocommerce/cart-order-summary-coupon-form-block",
"version": "1.0.0",
"title": "Coupon Form",
"description": "Shows the apply coupon form.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": false,
"move": false
}
}
},
"parent": [ "woocommerce/cart-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,28 @@
/**
* External dependencies
*/
import { TotalsCoupon } from '@woocommerce/base-components/cart-checkout';
import { useStoreCartCoupons } from '@woocommerce/base-context/hooks';
import { getSetting } from '@woocommerce/settings';
import { TotalsWrapper } from '@woocommerce/blocks-checkout';
const Block = ( { className }: { className: string } ): JSX.Element | null => {
const couponsEnabled = getSetting( 'couponsEnabled', true );
const { applyCoupon, isApplyingCoupon } = useStoreCartCoupons( 'wc/cart' );
if ( ! couponsEnabled ) {
return null;
}
return (
<TotalsWrapper className={ className }>
<TotalsCoupon
onSubmit={ applyCoupon }
isLoading={ isApplyingCoupon }
/>
</TotalsWrapper>
);
};
export default Block;

View File

@@ -0,0 +1,33 @@
/**
* External dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';
import Noninteractive from '@woocommerce/base-components/noninteractive';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
}: {
attributes: {
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { className } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Noninteractive>
<Block className={ className } />
</Noninteractive>
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import { Icon, tag } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ tag }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,30 @@
{
"name": "woocommerce/cart-order-summary-discount-block",
"version": "1.0.0",
"title": "Discount",
"description": "Shows the cart discount row.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"lock": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": true,
"move": false
}
}
},
"parent": [ "woocommerce/cart-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,49 @@
/**
* External dependencies
*/
import { TotalsDiscount } from '@woocommerce/base-components/cart-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import {
useStoreCartCoupons,
useStoreCart,
} from '@woocommerce/base-context/hooks';
import {
ExperimentalDiscountsMeta,
TotalsWrapper,
} from '@woocommerce/blocks-checkout';
const DiscountSlotFill = (): JSX.Element => {
// Prepare props to pass to the ExperimentalOrderMeta slot fill. We need to pluck out receiveCart.
// eslint-disable-next-line no-unused-vars
const { extensions, receiveCart, ...cart } = useStoreCart();
const discountsSlotFillProps = {
extensions,
cart,
context: 'woocommerce/cart',
};
return <ExperimentalDiscountsMeta.Slot { ...discountsSlotFillProps } />;
};
const Block = ( { className }: { className: string } ): JSX.Element => {
const { cartTotals, cartCoupons } = useStoreCart();
const { removeCoupon, isRemovingCoupon } = useStoreCartCoupons( 'wc/cart' );
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<>
<TotalsWrapper className={ className }>
<TotalsDiscount
cartCoupons={ cartCoupons }
currency={ totalsCurrency }
isRemovingCoupon={ isRemovingCoupon }
removeCoupon={ removeCoupon }
values={ cartTotals }
/>
</TotalsWrapper>
<DiscountSlotFill />
</>
);
};
export default Block;

View File

@@ -0,0 +1,30 @@
/**
* External dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
}: {
attributes: {
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { className } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Block className={ className } />
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,25 @@
/**
* External dependencies
*/
import { totals } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,30 @@
{
"name": "woocommerce/cart-order-summary-fee-block",
"version": "1.0.0",
"title": "Fees",
"description": "Shows the cart fee row.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"lock": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"lock": {
"type": "object",
"default": {
"remove": true,
"move": false
}
}
},
"parent": [ "woocommerce/cart-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,19 @@
/**
* External dependencies
*/
import { TotalsFees, TotalsWrapper } from '@woocommerce/blocks-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import { useStoreCart } from '@woocommerce/base-context/hooks';
const Block = ( { className }: { className: string } ): JSX.Element => {
const { cartFees, cartTotals } = useStoreCart();
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<TotalsWrapper className={ className }>
<TotalsFees currency={ totalsCurrency } cartFees={ cartFees } />
</TotalsWrapper>
);
};
export default Block;

View File

@@ -0,0 +1,30 @@
/**
* External dependencies
*/
import { useBlockProps } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import Block from './block';
export const Edit = ( {
attributes,
}: {
attributes: {
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { className } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Block className={ className } />
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,6 @@
/**
* Internal dependencies
*/
import Block from './block';
export default Block;

View File

@@ -0,0 +1,25 @@
/**
* External dependencies
*/
import { totals } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,18 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
export default {
content: {
type: 'string',
default: __( 'Cart totals', 'woo-gutenberg-products-block' ),
},
lock: {
type: 'object',
default: {
remove: false,
move: false,
},
},
};

View File

@@ -0,0 +1,33 @@
{
"name": "woocommerce/cart-order-summary-heading-block",
"version": "1.0.0",
"title": "Heading",
"description": "Shows the heading row.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"content": {
"type": "string",
"default": "Cart totals"
},
"lock": {
"type": "object",
"default": {
"remove": false,
"move": false
}
}
},
"parent": [ "woocommerce/cart-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,24 @@
/**
* External dependencies
*/
import Title from '@woocommerce/base-components/title';
import classnames from 'classnames';
const Block = ( {
className,
content = '',
}: {
className: string;
content: string;
} ): JSX.Element => {
return (
<Title
headingLevel="2"
className={ classnames( className, 'wc-block-cart__totals-title' ) }
>
{ content }
</Title>
);
};
export default Block;

View File

@@ -0,0 +1,48 @@
/**
* External dependencies
*/
import { PlainText, useBlockProps } from '@wordpress/block-editor';
import Title from '@woocommerce/base-components/title';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import './editor.scss';
export const Edit = ( {
attributes,
setAttributes,
}: {
attributes: {
content: string;
className: string;
};
setAttributes: ( attributes: Record< string, unknown > ) => void;
} ): JSX.Element => {
const { content = '', className = '' } = attributes;
const blockProps = useBlockProps();
return (
<div { ...blockProps }>
<Title
headingLevel="2"
className={ classnames(
className,
'wc-block-cart__totals-title'
) }
>
<PlainText
className={ '' }
value={ content }
onChange={ ( value ) =>
setAttributes( { content: value } )
}
/>
</Title>
</div>
);
};
export const Save = (): JSX.Element => {
return <div { ...useBlockProps.save() } />;
};

View File

@@ -0,0 +1,8 @@
.wp-block-woocommerce-cart-order-summary-heading-block {
textarea {
text-align: right;
text-transform: uppercase;
line-height: 1;
height: auto;
}
}

View File

@@ -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 );

View File

@@ -0,0 +1,25 @@
/**
* External dependencies
*/
import { totals } from '@woocommerce/icons';
import { Icon } from '@wordpress/icons';
import { registerFeaturePluginBlockType } from '@woocommerce/block-settings';
/**
* Internal dependencies
*/
import { Edit, Save } from './edit';
import metadata from './block.json';
registerFeaturePluginBlockType( metadata, {
icon: {
src: (
<Icon
icon={ totals }
className="wc-block-editor-components-block-icon"
/>
),
},
edit: Edit,
save: Save,
} );

View File

@@ -0,0 +1,18 @@
/**
* External dependencies
*/
import { getSetting } from '@woocommerce/settings';
export default {
isShippingCalculatorEnabled: {
type: 'boolean',
default: getSetting( 'isShippingCalculatorEnabled', true ),
},
lock: {
type: 'object',
default: {
move: false,
remove: true,
},
},
};

View File

@@ -0,0 +1,26 @@
{
"name": "woocommerce/cart-order-summary-shipping-block",
"version": "1.0.0",
"title": "Shipping",
"description": "Shows the cart shipping row.",
"category": "woocommerce",
"supports": {
"align": false,
"html": false,
"multiple": false,
"reusable": false,
"lock": false
},
"attributes": {
"lock": {
"type": "object",
"default": {
"remove": true,
"move": false
}
}
},
"parent": [ "woocommerce/cart-order-summary-block" ],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2
}

View File

@@ -0,0 +1,36 @@
/**
* External dependencies
*/
import { TotalsShipping } from '@woocommerce/base-components/cart-checkout';
import { getCurrencyFromPriceResponse } from '@woocommerce/price-format';
import { useStoreCart } from '@woocommerce/base-context/hooks';
import { TotalsWrapper } from '@woocommerce/blocks-checkout';
const Block = ( {
className,
isShippingCalculatorEnabled,
}: {
className: string;
isShippingCalculatorEnabled: boolean;
} ): JSX.Element | null => {
const { cartTotals, cartNeedsShipping } = useStoreCart();
if ( ! cartNeedsShipping ) {
return null;
}
const totalsCurrency = getCurrencyFromPriceResponse( cartTotals );
return (
<TotalsWrapper className={ className }>
<TotalsShipping
showCalculator={ isShippingCalculatorEnabled }
showRateSelector={ true }
values={ cartTotals }
currency={ totalsCurrency }
/>
</TotalsWrapper>
);
};
export default Block;

Some files were not shown because too many files have changed in this diff Show More