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,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,
};
};